text
stringlengths
2
1.05M
var DateTime = artifacts.require("./DateTime.sol"); var ProofOfExistence = artifacts.require("./ProofOfExistence.sol"); module.exports = function(deployer) { deployer.deploy(DateTime); deployer.link(DateTime, ProofOfExistence); deployer.deploy(ProofOfExistence); };
import axios from 'axios'; export const FETCH_POSTS = "fetch_posts"; export const CREATE_POST = "create_post"; const ROOT_URL='http://reduxblog.herokuapp.com/api'; const API_KEY='?key=agparadiso'; export function fetchPosts() { const request = axios.get(`${ROOT_URL}/posts${API_KEY}`); return { type: FETCH_POSTS, payload: request }; } export function createPost(values, callback) { const request = axios.post(`${ROOT_URL}/posts${API_KEY}`, values) .then(() => callback()); return { type: CREATE_POST, payload: request }; }
define(["exports"],(function(e){"use strict";let t,l;const s=e=>{let t=e.target.parentElement.querySelector(".hoo-mdldialog-outer");t.classList.remove("is-hidden"),t.classList.add("is-visible")},o=e=>{let t=e.target.closest(".hoo-mdldialog-outer");t.classList.remove("is-visible"),t.classList.add("is-hidden")};e.registerDialog=()=>{t=document.querySelectorAll(".show-dialog"),l=document.querySelectorAll(".hoo-dlgheader-closer"),t&&t.forEach((e=>{e.addEventListener("click",s)})),l&&l.forEach((e=>{e.addEventListener("click",o)}))},Object.defineProperty(e,"__esModule",{value:!0})}));
const path = require('path'); const merge = require('webpack-merge').merge; const scssTask = require('./webpack.scss'); const es5Task = require('./webpack.es5'); let BundleAnalyzerPlugin; if (process.env.APOS_BUNDLE_ANALYZER) { BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; } module.exports = ({ importFile, modulesDir, outputPath, outputFilename, es5 }, apos) => { const taskFns = [ scssTask ]; if (es5) { taskFns.push(es5Task); } const tasks = taskFns.map(task => task( { importFile, modulesDir, outputFilename }, apos ) ); let config = { entry: importFile, target: es5 ? 'es5' : 'web', mode: process.env.NODE_ENV || 'development', optimization: { minimize: process.env.NODE_ENV === 'production' }, devtool: 'eval-source-map', output: { path: outputPath, filename: outputFilename }, resolveLoader: { extensions: [ '*', '.js' ], modules: [ 'node_modules' ] }, resolve: { extensions: [ '*', '.js' ], alias: { // resolve apostrophe modules Modules: path.resolve(modulesDir) }, modules: [ `${apos.npmRootDir}/node_modules`, // Make sure core-js and regenerator-runtime can always be found, even // if npm didn't hoist them `${apos.npmRootDir}/node_modules/apostrophe/node_modules` ] }, stats: 'verbose', plugins: process.env.APOS_BUNDLE_ANALYZER ? [ new BundleAnalyzerPlugin() ] : [] }; config = merge(config, ...tasks); return config; };
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello Express JS'); }); app.post('/home', (req, res) => { res.send('Hello Home'); }); app.put('/about', (req, res) => { res.send('Hello About'); }); app.delete('/contact', (req, res) => { res.send('Hello Contact'); }); // simple string response // res.send() === response body // res.end() === response ending point app.get('/stringOne', (req, res) => { res.send('String One Response'); }); app.post('/stringTwo', (req, res) => { res.send('String Two Response'); }); // response status code app.get('/statusOne', (req, res) => { res.status(401); res.send('Unauthorized Access'); }); // JSON response app.get('/jsonResponse', (req, res) => { const jsonResponse = [ { name: 'Mohammad Noman', age: 25, occupation: 'Unemployed', city: 'Dhaka', }, { name: 'Mohammad Faruque', age: 21, occupation: 'Student', city: 'Jashore', }, { name: 'Mohammad Baki', age: 22, occupation: 'Developer', city: 'Rajshai', }, ]; res.json(jsonResponse); }); // response download app.get('/download', (req, res) => { res.download('./index.js'); }); // response redirecet app.get('/bangladesh', (req, res) => { res.redirect(`http://localhost:4000/pakistan`); }); app.get('/pakistan', (req, res) => { res.send('This is Pakistan'); }); // response header app.get('/header', (req, res) => { res.append('name', 'Mohammad Noman'); res.append('age', '25'); res.append('city', 'dhaka'); res.status(201); res.send('This is Header'); res.end(); }); // response set cookies app.get('/cookies', (req, res) => { res.cookie('name', 'Mohammad Faruque'); res.cookie('age', '30'); res.cookie('city', 'Jashore'); res.cookie('profession', 'student'); res.send('This is Cookies'); }); // response clear cookies app.get('/cookiesClear', (req, res) => { res.clearCookie('name'); res.clearCookie('profession'); res.clearCookie('city'); res.send('This is Cookies clear'); }); app.listen(4000, () => { console.log('Server run successfully on port 4000'); });
"use strict"; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ Object.defineProperty(exports, "__esModule", { value: true }); const command_1 = require("../models/command"); const open = require('open'); class DocCommand extends command_1.Command { async run(options) { if (!options.keyword) { this.logger.error('You should specify a keyword, for instance, `ng doc ActivatedRoute`.'); return 0; } let searchUrl = `https://angular.io/api?query=${options.keyword}`; if (options.search) { searchUrl = `https://www.google.com/search?q=site%3Aangular.io+${options.keyword}`; } // We should wrap `open` in a new Promise because `open` is already resolved await new Promise(() => { open(searchUrl, { wait: false, }); }); } } exports.DocCommand = DocCommand;
export { AlpacaClient } from './client.js'; export { AlpacaStream } from './stream.js'; import { AlpacaClient } from './client.js'; import { AlpacaStream } from './stream.js'; export default { AlpacaClient: AlpacaClient, AlpacaStream: AlpacaStream, };
import React, { useState, useLayoutEffect } from "react"; // Components import Layout from "../components/layout"; import SEO from "../components/seo"; // Images import Astronaut from '../images/404/Astronaut-big.png' import BalloonLost from '../images/404/Balloon Lost-big.png' import BrokenClock from '../images/404/Broken Clock-big.png' import Ostrich from '../images/404/Ostrich-big.png' import CautionTape from '../images/404/Caution Tape-big.png' import BrokenMug from '../images/404/Broken Mug-big.png' import BurntToast from '../images/404/Burnt Toast-big.png' import DogAte from '../images/404/Dog Ate-big.png' import SpilledMilk from '../images/404/Spilled Milk-big.png' import ShoesTied from '../images/404/Shoes Tied-big.png' import KidsToy from '../images/404/Kid_s Toy-big.png' import LostTourist from '../images/404/Lost Tourist-big.png' import BoatLeak from '../images/404/Boat Leak-big.png' import Ghost from '../images/404/Ghost-big.png' import PizzaBox from '../images/404/Pizza Box-big.png' import LostKeys from '../images/404/Lost Keys-big.png' import Trash from '../images/404/Trash-big.png' import LochNess from '../images/404/Loch Ness-big.png' import IceCreamSpill from '../images/404/Ice Cream Spill-big.png' const fourOhFourHeadingText = [ "This Page is Lost in Space", "This Page is Lost in the Wind", "This Page is Burried in the Sand", "This Page is Broken", "Caution! This Page is Cordoned Off", "This Page is Broken", "This Page is Burnt to a Crisp", "A Dog Ate this Page", "Don't Cry Over Spilled Page", "Oh No! We Tripped Up!", "This Page is Wrong", "This Page is Not on the Map", "There's a Leak in the Website", "This Page is a Ghost", "This Page Contains Nothing but Scraps", "This Page is Lost", "This Page is in the Garbage", "This Page is Not Real", "This Page is Melted in the Sun" ] const fourOhFourParagraphText = [ "You thought this mission to the moon would be a quick six month thing. Your neighbor offered to look after your dog. Your high school math teacher was impressed. He once said you wouldn't amount to anything. You sure showed him. But now here you are, fifty feet from your spaceship with no way to get back. Your dog will be so sad. Your math teacher will be so smug. Pretty devastating.", "The child had looked so excited when the clown had presented a large red balloon. You had seen this, but in the throes of your morning commute you didn't register it until it was too late. Who asked the government to support a fair in the middle of Main Street during a week day anyway? Your bike barrelled right between the child and the clown and sent the balloon on its merry way. You didn't turn back to see the damage you had done. Later you saw the balloon floating outside your office window.", "You have never seen an ostrich head. Whenever you're around it seems ostriches are avoiding your gaze. You came on this trip specifically to see an ostrich head, but here is this ostrich right in front of you, head invisible. You may never see an ostrich head.", "A broken clock is right twice a day. But if you just have one clock, it's impossible to tell exactly when the clock is right. So it could be right at any moment. And that brings you to the crux of the conceptualization. What is time? Nothing but an abyss. Clocks are just false attempts to harness its power. It's a cruel reality.", "The earthquake was not good to the bike lane on your way to work. A large gap in the pavement (too big to be called a pothole) had swallowed three oblivious bikers whole. So the city had put up two pylons and yellow caution tape. Pretty frustrating for you given your propensity to do 360 jumps over the gap.", "This mug was a family heirloom. Of your neighbor. Your neighbor always loved the color, shape, and quantity of coffee held by this mug. But your neighbor moved out and left it on their porch, no explanation, no repair materials, no nothing. So now you have this broken mug.", "Toast takes so long to make. You stare at the toaster tapping your feet. Your laundry is in the dryer and it just dingerd. Maybe you'll take it out. After all, you have time. You take out your laundry. You fold your underwear. You think about folding your socks. You remember your toast! It's too late. It's burnt to a crisp. The process repeats itself. You should probably figure out your toasting settings.", "Your dog is cute but honestly a menace. Where are my shoes? Where is my graduation certificate? Where is the chocolate cake I baked for my Aunt's birthday? And why did you take your dog to the vet on that same Thursday?!", "Gulp. You hold back tears as the white liquid spreads across the floor from your sad looking carton. You should have bought the chocolate milk. It was clearly the better choice. And then maybe you wouldn't have so carelessly smacked it across the room when you emphatically pointed at a bird outside. Too late now. You wipe the single tear from your eye and go fetch the mop.", "You had been told you should always check your shoes before getting up from the bleachers. Freshman were known to walk under them and tie peoples’ shoes together.", "You have been trying for ten minutes. It’s pretty late at night and pretty dark in your room. You reach over and flick on a lamp. You feel oh so stupid. The gap in the toy is a triangle and you only have the cylinder and cube pieces. In dismay you toss the toy aside. Curse your five year old’s inability to keep track of the triangle!", "You told your friends you weren’t bringing your phone, to try and experience what travel was like back in the day. You bought a map and a bottle of water and carried your camera for the money shot. But the map was from 2005 and the landscape had changed. So here you are, in the middle of a large field, that the map continues to claim is a local grocer.", "The boat had looked good to the naked eye. But you wear a very strong prescription and should have been wearing glasses. As you cling on to the bouey the coast guard had thrown at you, you watch the water rush into you beloved dingy. The leak sprays water higher and higher. Then the boat was swallowed and sunk into the abyss.", "Once alive and now dead, this ghost appears to have some unfinished business. Could it be with you? Or the treasure hidden under the floorboards of the old mansion in the hills that may never reach its rightful owner, a compassionate school teacher in Brooklyn.", "A perfectly enticing pizza box sitting on a table. You open it filled with anticipation. And find… nothing but scraps. Perhaps a half eaten crust. And a lot of grease. The anticipation turns to deep disappointment and despair. There’s nothing left!", "You bought a little bracelet for the express purpose of not losing your keys. You put a hook on your door specifically meant for keeping your keys. You briefly attempted to attach your keys to your phone. But here they are. In the dirt. In the park across the street from that bar you used to like but decided the last time you went that you probably wouldn’t go again. You’ll never find them.", "When the king of racoons approached you during the fall of 2005, you were taken aback by the generosity of the offer he made and also his ability to talk. You’ve been living in harmony ever since. They pay 50% of your rent and you “forget” to take out the garbage every other week.", "The imposing figure with the trenchcoat shows you the two polaroids. One appears to show the Loch Ness monster herself in the middle of a stretch of dark water. The other shows a sasquatch picking it’s way through a dark forest. You look closer. The animal shapes are drawn on with ink. “This isn’t real!” You scream and throw the polaroids to the floor, sobbing.", "People questioned your desire to get strawberry. “That’s the worst flavor,” they said. But you are strong and independent so you got it anyway. And honestly, it wasn’t great. Luckily, two licks in a bike whizzed past you and knocked the cone out of your hand. “Oh no!” you yelled as the creamy pink became a mess in the dirt. But really you were happy." ] const fourOhFourImgSrc = [ Astronaut, BalloonLost, Ostrich, BrokenClock, CautionTape, BrokenMug, BurntToast, DogAte, SpilledMilk, ShoesTied, KidsToy, LostTourist, BoatLeak, Ghost, PizzaBox, LostKeys, Trash, LochNess, IceCreamSpill ] export default () => { const [ pick, updatePick ] = useState(0) useLayoutEffect(() => { const newPick = Math.floor(Math.random()*fourOhFourHeadingText.length) updatePick(newPick) }) return ( <Layout> <SEO title="404: Not found" /> <div> <img src={fourOhFourImgSrc[pick]} className="block mx-auto w-1/2" alt="Ghost getting abducted by aliens" /> <h2 className="bg-yellow-400 text-2xl font-bold inline-block my-8 p-3"> {fourOhFourHeadingText[pick]} </h2> <p className="font-sans text-lg subpixel-antialiased font-thin"> {fourOhFourParagraphText[pick]} </p> </div> </Layout> ); }
/* * Copyright © 2020 VMware, Inc. All Rights Reserved. * SPDX-License-Identifier: BSD-2-Clause */ 'use strict' const connectorExplang = require('connector-explang') const btoa = require('btoa') const service = require('../services/zendesk-tasks-service') const mfCommons = require('@vmw/mobile-flows-connector-commons') const commonUtils = require('../utils/common-utils') const reqUtils = require('../utils/req-utils') const jsonUtils = require('../utils/json-utils') /** * REST endpoint for generating card objects for Assigned Tasks. * @param {*} req request Payload * @param {*} res Recieved Hub Payload * @return ResponseEntity */ const cardsController = async (req, res) => { try { const userInfo = await service.getUserInfo(res.locals) let cardsArray = [] if (userInfo) { const userTickets = await service.getUserTickets(res.locals, userInfo.id) const getUniqueIds = (ids) => { return ids.reduce((unique, item) => { return unique.includes(item) ? unique : [...unique, item] }, []) } const assignee = userInfo.email let requesterIds = userTickets.map(ticket => ticket.requester_id) requesterIds = getUniqueIds(requesterIds) let submitterIds = userTickets.map(ticket => ticket.submitter_id) submitterIds = getUniqueIds(submitterIds) const userIds = requesterIds.concat(submitterIds) const users = await service.getUsers(res.locals, userIds.join()) const groups = await service.getGroups(res.locals) const ticketComments = await Promise.all(userTickets.map(async ticket => await service.getTicketComments(res.locals, ticket.id))) if (ticketComments) { userTickets.forEach(ticket => { ticket.comments = ticketComments.find(el => el.length !== 0 && el[0].ticket_id === ticket.id) }) } if (userTickets && userTickets.length > 0) { cardsArray = JSON.parse(generateCards(res.locals, userTickets, users, groups, assignee)) return res.status(200).json(cardsArray) } } return res.status(200).json({ objects: cardsArray }) } catch (err) { return reqUtils.prepareErrorResponse(res, err, 'cardsController') } } /** * Fetches The Card Objects From The Given Cases PayLoad * @param {*} locals payLoad Recieved From Hub * @param {*} tasks Tasks PayLoad * @param {*} users Users MetaData * @param {*} groups Groups MetaData * @param {*} assignee Task Assignee * @return {Array} the Card Objects */ const generateCards = (locals, tasks, users, groups, assignee) => { const cardsConfig = require('../config.json') delete require.cache[require.resolve('../config.json')] const linearizedTickets = linearizeData(locals, tasks, users, groups, assignee) const requestMap = { routing_prefix: `${locals.mfRoutingPrefix}actions` // used for building action url } const result = connectorExplang(linearizedTickets, cardsConfig, requestMap) mfCommons.log(`linearizeData for ${assignee} => ${JSON.stringify(linearizeData)}. Generated card from engine => ${result}`) return result } /** * Creates The Linearized Data Required By Engine * @param {*} locals payLoad Recieved From Hub * @param {*} tasks Tasks PayLoad * @param {*} users Users MetaData * @param {*} groups Groups MetaData * @param {*} assignee Task Assignee * @return {Array} the Linearize Data */ const linearizeData = (locals, tasks, users, groups, assignee) => { /** * Linearizes The Input For Comments * @param {*} comment comment PayLoad * @return {Map} linearized Data */ const constructComment = (comment) => { return { ':subject': comment.plain_body } } return tasks.map(r => { const backendId = btoa(`${locals.mfJwt.email}-${r.id}-${r.created_at}`) const groupName = groups && groups.length > 0 ? groups.filter(el => el.id === r.group_id)[0].name : '' const requester = users && users.length > 0 ? users.filter(el => el.id === r.requester_id)[0].email : '' const submitter = users && users.length > 0 ? users.filter(el => el.id === r.submitter_id)[0].email : '' const attachments = r.comments && r.comments && r.comments.flatMap(comment => getAttachmentInfo(comment)) const dueDate = r.due_at ? r.due_at : '' const tags = r.tags && r.tags.length > 0 ? r.tags.join(', ') : '' const filteredCommentsArray = r.comments if (filteredCommentsArray && filteredCommentsArray.length > 0) filteredCommentsArray.shift() const comments = filteredCommentsArray && filteredCommentsArray.map(comment => constructComment(comment)) let respJson = { ':backend_id': backendId, ':ticket_type': r.type, ':ticket_description': r.description, ':ticket_subject': r.subject, ':ticket_priority': r.priority, ':ticket_status': r.status, ':ticket_raw_subject': r.raw_subject, ':channel': r.via.channel, ':ticket_id': r.id, ':ticket_requester': requester, ':ticket_submitter': submitter, ':ticket_assignee': assignee, ':ticket_group': groupName, ':ticket_due_date': dueDate, ':ticket_tags': tags, ':comments-section': comments, ':attachments-section': attachments } respJson = commonUtils.removeEmptyKeys(respJson) const stringifiedJson = jsonUtils.stringifyJsonValues(respJson) return stringifiedJson }) } /** * Linearizes The Input For Attachments * @param {*} comment comment PayLoad * @return {Map} linearized Data */ const getAttachmentInfo = (comment) => { const constructAttachment = (attachment) => { return { ':att_name': attachment.file_name, ':att-link': attachment.content_url } } const items = comment && comment.attachments && comment.attachments.map(el => constructAttachment(el)) return items } module.exports = { cardsController }
var app = angular.module('mybuilder', []); app.controller('mybuildercontroller', function ($scope, $http) { $http.get("/files/user_data.json").then(function (dados) { $scope.list = dados.data; }, function (err) { console.log("ERRO GET: " + err); }); });
// (C) Copyright 2016 Hewlett Packard Enterprise Development LP import AnnotatedMeter from './components/AnnotatedMeter'; import FilterControl from './components/FilterControl'; import ListPlaceholder from './components/ListPlaceholder'; import Query from './utils/Query'; import SideSplit from './components/SideSplit'; export default { AnnotatedMeter, FilterControl, ListPlaceholder, Query, SideSplit };
import React from "react"; const Container = (props) => { return ( <div className={props.hideXOverflow ? "overflow-x-hidden" : ""} {...(props.dataCy ? {'data-cy': props.dataCy} : {})}> <div className="mx-auto px-4 md:px-6 lg:px-8 max-w-[90rem]"> {props.children} </div> </div> ); }; export default Container;
/** * * create by ligx * * @flow */ import { unZip, unZipCopyData, zip, zipCopyData } from '../src'; import LayoutFile from './LayoutFile'; import LayoutFileZip from './LayoutFileZip'; import CopyDataZip from './copydata_zip'; import CopyData from './copydata'; import LugiaDFile from './lugiaDFile'; import LugiaDFileZip from './lugiaDFileZip'; import CopyChildrenData from './CopyChildrenData'; describe('zip.test', () => { it('zip', () => { const orginal = JSON.parse(JSON.stringify(LayoutFile)); const file: Object = LayoutFile; const zipJSONString = JSON.stringify(zip(file)); expect(zipJSONString).toEqual(JSON.stringify(LayoutFileZip)); expect(unZip(zipJSONString)).toEqual({ ...orginal, zip: true }); }); it('zip lugiaDFile', () => { const meta = JSON.parse(JSON.stringify(LugiaDFile)); expect(JSON.stringify(LugiaDFileZip)).toEqual( JSON.stringify(zip(LugiaDFile)) ); expect( unZip(JSON.stringify(JSON.parse(JSON.stringify(LugiaDFileZip)))) ).toEqual(meta); }); function deepClone(target: Object): Object { return JSON.parse(JSON.stringify(target)); } it('copydata', () => { expect(unZipCopyData(deepClone(CopyDataZip))).toEqual(deepClone(CopyData)); expect(zipCopyData(deepClone(CopyData))).toEqual(deepClone(CopyDataZip)); expect(unZipCopyData(deepClone(zipCopyData(deepClone(CopyData))))).toEqual( deepClone(CopyData) ); }); it('CopyChildrenData', () => { expect(zipCopyData(deepClone(unZipCopyData(deepClone(CopyChildrenData))))).toEqual( deepClone(CopyChildrenData) ); }); });
const express = require('express') const router = express.Router() const { signup } = require('../../../controllers/signup') // Tutte le routes definite in questo file saranno di tipo /api/v1/signup/* router.post('/', signup) // POST /api/v1/signup/ module.exports = router
const express = require("express"); const app = express(); let PORT = 3000; let alunos = [ { id: 0, nome: "Jose", }, { id: 1, nome: "Paulo", }, { id: 2, nome: "Maria", }, { id: 3, nome: "Pedro", }, ]; // urlencoded são dados vindos por form // Pega as informações do form e cria um body dentro da requisição app.use(express.urlencoded({ extended: true })); app.get("/", (req, res) => { res.send("Hello World"); }); // O /aluno é uma rota/path. Que a partir dessa rota que vamos decidir o que o node vai fazer app.get("/alunos", (req, res) => { // se for essa rota responde com o array inteiro dos alunos res.json(JSON.stringify(alunos)); }); app.get("/aluno", (req, res) => { console.log(req.body); // pega o id trago pela requisição pelo body let aluno = alunos[req.body.id]; res.json(aluno); // query é quando no url é chamado com ? /aluno?id=1, fazendo com que depois do ? você possa colocar os elementos como o id + seu valor = 1; console.log(req.query); let aluno2 = alunos[req.query.id]; res.json(aluno2); }); // basicamente quando é colocado : depoius da / + um nome faz com que o que vier depois da / vire um parametro com o nome colocado no caso id // porém depende muito do tipo de informação sendo passada ali pq não seria bom passar informações delicadas pelo link do navegador como senha e usuário // ficar atento para casos de tentar utilizar a requisição do exemplo acima porém se colocar algo depois da / e o node perceber que existe um aluno com o id do elemento ele vai automaticamente usar o get do exemplo abaixo em vez do de cima pois ele se encaixa mais na requisição app.get("/aluno/:id", (req, res) => { // chama o parametro colocado depois da / console.log(req.params.id); // assim faz com que chame o aluno pelo número/elemento colocado depois da / let aluno = alunos[req.params.id]; res.json(aluno); }); app.listen(PORT, () => { console.log("Server rodando...."); });
var __extends=this.__extends||function(e,t){function r(){this.constructor=e}for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);r.prototype=t.prototype,e.prototype=new r},wijmo;(function(e){(function(t){"use strict";var n=jQuery,r="wijexpander",i="ui-expander-content",s=function(t){function r(){t.apply(this,arguments)}return __extends(r,t),r.prototype._setOption=function(e,t){var r=this.element.find("> ."+i);switch(e){case"contentUrl":t?r.wijContent(t):r.html(this.storeContentHTML);break;case"expandDirection":this._onDirectionChange(t,!0,this.options.expandDirection);break;case"expanded":t?this.expand():this.collapse();return;default:}n.wijmo.widget.prototype._setOption.apply(this,arguments)},r.prototype._innerDisable=function(){t.prototype._innerDisable.call(this),this._toggleDisableExpander(!0)},r.prototype._innerEnable=function(){t.prototype._innerEnable.call(this),this._toggleDisableExpander(!1)},r.prototype._toggleDisableExpander=function(e){var t=this.element.find("> ."+i);this.element.toggleClass(this.options.wijCSS.stateDisabled,e).find("> .ui-expander-header").toggleClass(this.options.wijCSS.stateDisabled,e),t.toggleClass(this.options.wijCSS.stateDisabled,e)},r.prototype._create=function(){var r=this.options,s=this.element.children(),o,u,a=r.wijCSS;window.wijmoApplyWijTouchUtilEvents&&(n=window.wijmoApplyWijTouchUtilEvents(n)),this.element.addClass("wijmo-wijexpander ui-expander "+r.wijCSS.widget+" ui-expander-icons"),this.header=o=n(s[0]),this.content=u=n(s[1]);if(r.expandDirection==="left"||r.expandDirection==="top")o.remove(),o.insertAfter(u);o.addClass("ui-expander-header"),o.attr("role","tab"),u.attr("role","tabpanel"),o.find("> a").length===0&&(o.wrapInner('<a href="javascript:void(null)"></a>'),this.headerLink=o.children()),o.find("> ."+e.getCSSSelector(a.icon)).length===0&&(this.headerIcon=n("<span></span>").addClass(a.icon).insertBefore(n("> a",o)[0])),u.addClass(i+" "+a.content),this.storeContentHTML=u.html(),t.prototype._create.call(this)},r.prototype._init=function(){var t=this.options,n=this.element.find("> ."+i);this._onDirectionChange(t.expandDirection,!1),t.contentUrl&&n.wijContent(this.options.contentUrl),t.expanded?(this.element.find("> .ui-expander-header").addClass(t.wijCSS.stateDefault+" "+t.wijCSS.stateActive).attr({"aria-expanded":"true",tabIndex:0}).addClass(this._headerCornerOpened).find("> ."+e.getCSSSelector(t.wijCSS.icon)).addClass(this._triangleIconOpened),n.addClass("ui-expander-content-active").addClass(this._contentCornerOpened).wijTriggerVisibility()):(n.hide(),this.element.find("> .ui-expander-header").addClass(t.wijCSS.stateDefault+" "+t.wijCSS.cornerAll).attr({"aria-expanded":"false",tabIndex:-1}).find("> ."+e.getCSSSelector(t.wijCSS.icon)).addClass(this._triangleIconClosed)),this._isDisabled()&&(this.element.addClass(t.wijCSS.stateDisabled).find("> .ui-expander-header").addClass(t.wijCSS.stateDisabled),n.addClass(t.wijCSS.stateDisabled)),this._bindLiveEvents()},r.prototype.destroy=function(){var e=this.options,t="wijmo-wijexpander ui-expander "+e.wijCSS.widget+" "+"ui-helper-reset ui-expander-icons "+"ui-expander-"+e.expandDirection+" "+e.wijCSS.stateFocus+" "+e.wijCSS.stateHover+" "+e.wijCSS.stateDisabled,r="ui-expander-header "+e.wijCSS.stateDefault+" "+e.wijCSS.cornerAll+" "+e.wijCSS.stateActive+" "+this._headerCornerOpened,s=i+" "+e.wijCSS.content+" "+"ui-expander-content-active "+e.wijCSS.stateDisabled+" "+this._contentCornerOpened;this._unbindLiveEvents(),this.element.removeClass(t),this.headerIcon&&(this.headerIcon.remove(),this.headerIcon=null),this.headerLink&&(this.header.html(this.headerLink.html()),this.headerLink.remove(),this.headerLink=null),this.header.removeClass(r),this.header.removeAttr("role").removeAttr("aria-expanded").removeAttr("tabIndex"),this.content.removeClass(s),this.content.removeAttr("role"),e.contentUrl&&this.content.html(this.storeContentHTML),this.header.insertBefore(this.content),n.wijmo.widget.prototype.destroy.apply(this,arguments)},r.prototype._bindLiveEvents=function(){var e=this.options,t="";this.element.off(".wijexpander"),n.support.isTouchEnabled&&n.support.isTouchEnabled()&&(t="wij"),this.element.on(t+"click.wijexpander",">.ui-expander-header",jQuery.proxy(this._onHeaderClick,this)),this.element.on(t+"mouseenter.wijexpander",".ui-expander-header",function(){n(this).addClass(e.wijCSS.stateHover)}),this.element.on(t+"mouseleave.wijexpander",".ui-expander-header",function(){n(this).removeClass(e.wijCSS.stateHover)}),this.element.on(t+"focus.wijexpander",".ui-expander-header",function(){n(this).addClass(e.wijCSS.stateFocus)}),this.element.on(t+"blur.wijexpander",".ui-expander-header",function(){n(this).removeClass(e.wijCSS.stateFocus)})},r.prototype._unbindLiveEvents=function(){this.element.off(".wijexpander",".ui-expander-header")},r.prototype._onDirectionChange=function(e,t,r){typeof r=="undefined"&&(r=null);var s,o,u,a,f,l,c,h,p=this.options;r&&r!==e&&this.element.removeClass("ui-expander-"+r),t&&(o=this.element.find(".ui-expander-header."+this._headerCornerOpened),o.removeClass(this._headerCornerOpened),u=this.element.find("."+i+"."+this._contentCornerOpened),u.removeClass(this._contentCornerOpened),a=this.element.find("."+this._triangleIconOpened),f=this.element.find("."+this._triangleIconClosed),a.removeClass(this._triangleIconOpened),f.removeClass(this._triangleIconClosed));switch(e){case"top":this._headerCornerOpened="ui-corner-bottom",this._contentCornerOpened="ui-corner-top",this._triangleIconOpened=p.wijCSS.iconArrowUp,this._triangleIconClosed=p.wijCSS.iconArrowRight,s=!0,this.element.removeClass("ui-helper-horizontal"),this.element.addClass("ui-expander-top");break;case"right":this._headerCornerOpened="ui-corner-left",this._contentCornerOpened="ui-corner-right",this._triangleIconOpened=p.wijCSS.iconArrowRight,this._triangleIconClosed=p.wijCSS.iconArrowDown,s=!1,this.element.addClass("ui-helper-horizontal"),this.element.addClass("ui-expander-right");break;case"left":this._headerCornerOpened="ui-corner-right",this._contentCornerOpened="ui-corner-left",this._triangleIconOpened=p.wijCSS.iconArrowLeft,this._triangleIconClosed=p.wijCSS.iconArrowDown,s=!0,this.element.addClass("ui-helper-horizontal"),this.element.addClass("ui-expander-left");break;default:this._headerCornerOpened="ui-corner-top",this._contentCornerOpened="ui-corner-bottom",this._triangleIconOpened=p.wijCSS.iconArrowDown,this._triangleIconClosed=p.wijCSS.iconArrowRight,s=!1,this.element.removeClass("ui-helper-horizontal"),this.element.addClass("ui-expander-bottom")}l=this.element.data("rightToLeft"),this.element.data("rightToLeft",s),t&&(a.addClass(this._triangleIconOpened),f.addClass(this._triangleIconClosed),o.addClass(this._headerCornerOpened),u.addClass(this._contentCornerOpened)),t&&s!==l&&this.element.children(".ui-expander-header").each(function(e,t){h=n(this),s?(c=h.next("."+i),h.remove(),h.insertAfter(c)):(c=h.prev("."+i),h.remove(),h.insertBefore(c))})},r.prototype.collapse=function(){var t=this.options,r,s,o,u,a=this.element.find("> ."+i);if(!t.allowExpand)return;return this.element.hasAllClasses(t.wijCSS.stateDisabled)?!1:this._trigger("beforeCollapse")?(t.animated?(r={expand:!1,content:a,complete:jQuery.proxy(function(){a.removeClass("ui-expander-content-active"),this._trigger("afterCollapse"),a.css("display","")},this),horizontal:this.element.hasClass("ui-helper-horizontal")},s=n.wijmo.wijexpander.animations,o=t.duration,u=t.animated,u&&!s[u]&&!n.easing[u]&&(u="slide"),s[u]||(s[u]=function(e){this.slide(e,{easing:u,duration:o||700})}),s[u](r)):(a.hide(),this._trigger("afterCollapse")),this.element.find("> .ui-expander-header").removeClass(t.wijCSS.stateActive).removeClass(this._headerCornerOpened).attr({"aria-expanded":"false",tabIndex:-1}).addClass(t.wijCSS.stateDefault+" "+t.wijCSS.cornerAll).find("> ."+e.getCSSSelector(t.wijCSS.icon)).removeClass(this._triangleIconOpened).addClass(this._triangleIconClosed),this.options.expanded=!1,!0):!1},r.prototype.expand=function(){var t=this.options,r,s,o,u,a=this.element.find("> ."+i);if(!t.allowExpand)return;return this.element.hasAllClasses(t.wijCSS.stateDisabled)?!1:this._trigger("beforeExpand")?(t.animated?(r={expand:!0,content:a,complete:jQuery.proxy(function(){a.addClass("ui-expander-content-active").addClass(this._contentCornerOpened).wijTriggerVisibility(),this._trigger("afterExpand"),a.css("display","")},this),horizontal:this.element.hasClass("ui-helper-horizontal")},s=n.wijmo.wijexpander.animations,o=t.duration,u=t.animated,u&&!s[u]&&!n.easing[u]&&(u="slide"),s[u]||(s[u]=function(e){this.slide(e,{easing:u,duration:o||700})}),s[u](r)):(a.show(),this._trigger("afterExpand")),this.element.find("> .ui-expander-header").removeClass(t.wijCSS.cornerAll).addClass(t.wijCSS.stateActive).addClass(this._headerCornerOpened).attr({"aria-expanded":"true",tabIndex:0}).find("> ."+e.getCSSSelector(t.wijCSS.icon)).removeClass(this._triangleIconClosed).addClass(this._triangleIconOpened),this.options.expanded=!0,!0):!1},r.prototype._onHeaderClick=function(e){this.option("expanded",!this.options.expanded)},r}(e.wijmoWidget);t.wijexpander=s;var o=function(){function e(){this.wijMobileCSS={header:"ui-header ui-bar-a",content:"ui-content ui-body ui-body-b"},this.initSelector=":jqmData(role='wijexpander')",this.allowExpand=!0,this.animated="slide",this.contentUrl="",this.expanded=!0,this.expandDirection="bottom",this.beforeCollapse=null,this.beforeExpand=null,this.afterCollapse=null,this.afterExpand=null}return e}();s.prototype.options=n.extend(!0,{},e.wijmoWidget.prototype.options,new o),n.wijmo.registerWidget(r,s.prototype),n.extend(n.wijmo.wijexpander,{animations:{slide:function(e,t){var r;e=n.extend({easing:"swing",duration:300},e,t),e.expand?(e.horizontal?r={width:"show",opacity:"show"}:r={height:"show",opacity:"show"},e.content.stop(!0,!0).animate(r,e)):(e.horizontal?r={width:"hide",opacity:"hide"}:r={height:"hide",opacity:"hide"},e.content.stop(!0,!0).animate(r,e))}}})})(e.expander||(e.expander={}));var t=e.expander})(wijmo||(wijmo={}));
var c = document.getElementById("c"); // set up size to fill the page c.height = 0.96*window.innerHeight; c.width = 0.96*window.innerWidth; var newx = c.width/2, newy = c.height/2; var ctx = c.getContext("2d"); var snowflake = { x:Math.random()*c.width, y:Math.random()*c.height, radius:30 }; // a function to update the scene function draw(){ // select color ctx.fillStyle = "rgba(64,83,203,1)"; // draw rectngle as a background ctx.fillRect(0, 0, c.width, c.height); //caption text // snowflakes ctx.beginPath(); // ctx.fillStyle = "rgba(255,255,255,0.9)"; ctx.textAlign = 'center' ctx.font = 'italic 20pt Calibri'; ctx.fillText('добро пожаловать на курс',0.5*c.width, 0.1*c.height); ctx.fillText('"Пишем Мобильные Приложения!"',0.5*c.width, 0.1*c.height+30); // draw snowflakes snowflake.y += ((newy- snowflake.y) >0) ? 0.8 : -0.8; snowflake.x += ((newx- snowflake.x) >0) ? 0.8 : -0.8; ctx.moveTo(snowflake.x,snowflake.y); ctx.arc(snowflake.x, snowflake.y ,30,0,Math.PI*2,true); ctx.fill(); } var i = 0; console.log("Happy new year to you too, my dear console dwellers! :)") setInterval(draw,33); function onMouseMove(evt) { if (evt.pageX > 0 && evt.pageX < c.width) { newx = evt.pageX; newy = evt.pageY; } } $(document).mousemove(onMouseMove);
/*! * remark (http://getbootstrapadmin.com/remark) * Copyright 2017 amazingsurge * Licensed under the Themeforest Standard Licenses */ !function(document,window,$){"use strict";var Site=window.Site;$(document).ready(function($){Site.run()}),function(){var cssAnimationData={labels:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],series:[[1,2,2.7,0,3,5,3,4,8,10,12,7],[0,1.2,2,7,2.5,9,5,8,9,11,14,4],[10,9,8,6.5,6.8,6,5.4,5.3,4.5,4.4,3,2.8]]},cssAnimationResponsiveOptions=[[{axisX:{labelInterpolationFnc:function(value,index){return index%2==0&&value}}}]];new Chartist.Line("#exampleLineAnimation",cssAnimationData,null,cssAnimationResponsiveOptions)}(),new Chartist.Line("#exampleSimpleLine",{labels:["Monday","Tuesday","Wednesday","Thursday","Friday"],series:[[12,9,7,8,5],[2,1,3.5,7,3],[1,3,4,5,6]]},{fullWidth:!0,chartPadding:{right:40}}),function(){var ctScatterTimes=function(n){return Array.apply(null,new Array(n))},ctScatterData=ctScatterTimes(52).map(Math.random).reduce(function(data,rnd,index){return data.labels.push(index+1),data.series.forEach(function(series){series.push(100*Math.random())}),data},{labels:[],series:ctScatterTimes(4).map(function(){return[]})}),ctScatterOptions={showLine:!1,axisX:{labelInterpolationFnc:function(value,index){return index%13==0?"W"+value:null}}},ctScatterResponsiveOptions=[["screen and (min-width: 640px)",{axisX:{labelInterpolationFnc:function(value,index){return index%4==0?"W"+value:null}}}]];new Chartist.Line("#exampleLineScatter",ctScatterData,ctScatterOptions,ctScatterResponsiveOptions)}(),function(){new Chartist.Line("#exampleTooltipsLine",{labels:["1","2","3","4","5","6"],series:[{name:"Fibonacci sequence",data:[1,2,3,5,8,13]},{name:"Golden section",data:[1,1.618,2.618,4.236,6.854,11.09]}]},{plugins:[Chartist.plugins.tooltip()]});$("#exampleTooltipsLine")}(),new Chartist.Line("#exampleAreaLine",{labels:[1,2,3,4,5,6,7,8],series:[[5,9,7,8,5,3,5,4]]},{low:0,showArea:!0}),new Chartist.Line("#exampleOnlyArea",{labels:[1,2,3,4,5,6,7,8],series:[[1,2,3,1,-2,0,1,0],[-2,-1,-2,-1,-2.5,-1,-2,-1],[0,0,0,1,2,2.5,2,1],[2.5,2,1,.5,1,.5,-1,-2.5]]},{high:3,low:-3,showArea:!0,showLine:!1,showPoint:!1,fullWidth:!0,axisX:{showLabel:!1,showGrid:!1}}),function(){var animationsChart=new Chartist.Line("#exampleLineAnimations",{labels:["1","2","3","4","5","6","7","8","9","10","11","12"],series:[[12,9,7,8,5,4,6,2,3,3,4,6],[4,5,3,7,3,5,5,3,4,4,5,5],[5,3,4,5,6,3,3,4,5,6,3,4],[3,4,5,6,7,6,4,5,6,7,6,3]]},{low:0}),seq=0;animationsChart.on("created",function(){seq=0}),animationsChart.on("draw",function(data){if(seq++,"line"===data.type)data.element.animate({opacity:{begin:80*seq+1e3,dur:500,from:0,to:1}});else if("label"===data.type&&"x"===data.axis)data.element.animate({y:{begin:80*seq,dur:500,from:data.y+100,to:data.y,easing:"easeOutQuart"}});else if("label"===data.type&&"y"===data.axis)data.element.animate({x:{begin:80*seq,dur:500,from:data.x-100,to:data.x,easing:"easeOutQuart"}});else if("point"===data.type)data.element.animate({x1:{begin:80*seq,dur:500,from:data.x-10,to:data.x,easing:"easeOutQuart"},x2:{begin:80*seq,dur:500,from:data.x-10,to:data.x,easing:"easeOutQuart"},opacity:{begin:80*seq,dur:500,from:0,to:1,easing:"easeOutQuart"}});else if("grid"===data.type){var pos1Animation={begin:80*seq,dur:500,from:data[data.axis.units.pos+"1"]-30,to:data[data.axis.units.pos+"1"],easing:"easeOutQuart"},pos2Animation={begin:80*seq,dur:500,from:data[data.axis.units.pos+"2"]-100,to:data[data.axis.units.pos+"2"],easing:"easeOutQuart"},ctAnimations={};ctAnimations[data.axis.units.pos+"1"]=pos1Animation,ctAnimations[data.axis.units.pos+"2"]=pos2Animation,ctAnimations.opacity={begin:80*seq,dur:500,from:0,to:1,easing:"easeOutQuart"},data.element.animate(ctAnimations)}}),animationsChart.on("created",function(){window.__exampleAnimateTimeout&&(clearTimeout(window.__exampleAnimateTimeout),window.__exampleAnimateTimeout=null),window.__exampleAnimateTimeout=setTimeout(animationsChart.update.bind(animationsChart),12e3)})}(),new Chartist.Line("#examplePathAnimation",{labels:["Mon","Tue","Wed","Thu","Fri","Sat"],series:[[1,5,2,5,4,3],[2,3,4,8,1,2],[5,4,3,2,1,.5]]},{low:0,showArea:!0,showPoint:!1,fullWidth:!0}).on("draw",function(data){"line"!==data.type&&"area"!==data.type||data.element.animate({d:{begin:2e3*data.index,dur:2e3,from:data.path.clone().scale(1,0).translate(0,data.chartRect.height()).stringify(),to:data.path.clone().stringify(),easing:Chartist.Svg.Easing.easeOutQuint}})}),new Chartist.Line("#exampleSmoothingLine",{labels:[1,2,3,4,5],series:[[1,5,10,0,1],[10,15,0,1,2]]},{lineSmooth:Chartist.Interpolation.simple({divisor:2}),fullWidth:!0,chartPadding:{right:20},low:0}),function(){var biPolarData={labels:["W1","W2","W3","W4","W5","W6","W7","W8","W9","W10"],series:[[1,2,4,8,6,-2,-1,-4,-6,-2]]},biPolarOptions={high:10,low:-10,axisX:{labelInterpolationFnc:function(value,index){return index%2==0?value:null}}};new Chartist.Bar("#exampleBiPolarBar",biPolarData,biPolarOptions)}(),function(){var overlappingData={labels:["Jan","Feb","Mar","Apr","Mai","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],series:[[5,4,3,7,5,10,3,4,8,10,6,8],[3,2,9,5,4,6,4,6,7,8,7,4]]},overlappingOptions={seriesBarDistance:10},overlappingResponsiveOptions=[["screen and (max-width: 640px)",{seriesBarDistance:5,axisX:{labelInterpolationFnc:function(value){return value[0]}}}]];new Chartist.Bar("#exampleOverlappingBar",overlappingData,overlappingOptions,overlappingResponsiveOptions)}(),new Chartist.Bar("#examplePeakCirclesBar",{labels:["W1","W2","W3","W4","W5","W6","W7","W8","W9","W10"],series:[[1,2,4,8,6,-2,-1,-4,-6,-2]]},{high:10,low:-10,axisX:{labelInterpolationFnc:function(value,index){return index%2==0?value:null}}}).on("draw",function(data){"bar"===data.type&&data.group.append(new Chartist.Svg("circle",{cx:data.x2,cy:data.y2,r:2*Math.abs(Chartist.getMultiValue(data.value))+5},"ct-slice-pie"))}),new Chartist.Bar("#exampleMultiLabelsBar",{labels:["First quarter of the year","Second quarter of the year","Third quarter of the year","Fourth quarter of the year"],series:[[6e4,4e4,8e4,7e4],[4e4,3e4,7e4,65e3],[8e3,3e3,1e4,6e3]]},{seriesBarDistance:10,axisX:{offset:60},axisY:{offset:80,labelInterpolationFnc:function(value){return value+" CHF"},scaleMinSpace:15}}),new Chartist.Bar("#exampleStackedBar",{labels:["Q1","Q2","Q3","Q4"],series:[[8e5,12e5,14e5,13e5],[2e5,4e5,5e5,3e5],[1e5,2e5,4e5,6e5]]},{stackBars:!0,axisY:{labelInterpolationFnc:function(value){return value/1e3+"k"}}}).on("draw",function(data){"bar"===data.type&&data.element.attr({style:"stroke-width: 30px"})}),new Chartist.Bar("#exampleHorizontalBar",{labels:["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],series:[[5,4,3,7,5,10,3],[3,2,9,5,4,6,4]]},{seriesBarDistance:10,reverseData:!0,horizontalBars:!0,axisY:{offset:70}}),new Chartist.Bar("#exampleResponsiveBar",{labels:["Quarter 1","Quarter 2","Quarter 3","Quarter 4"],series:[[5,4,3,7],[3,2,9,5],[1,5,8,4],[2,3,4,6],[4,1,2,1]]},{stackBars:!0,axisX:{labelInterpolationFnc:function(value){return value.split(/\s+/).map(function(word){return word[0]}).join("")}},axisY:{offset:20}},[["screen and (min-width: 480px)",{reverseData:!0,horizontalBars:!0,axisX:{labelInterpolationFnc:Chartist.noop},axisY:{offset:60}}],["screen and (min-width: 992px)",{stackBars:!1,seriesBarDistance:10}],["screen and (min-width: 1200px)",{reverseData:!1,horizontalBars:!1,seriesBarDistance:15}]]),function(){var simplePiedata={series:[5,3,4]},simplePieSum=function(a,b){return a+b};new Chartist.Pie("#exampleSimplePie",simplePiedata,{labelInterpolationFnc:function(value){return Math.round(value/simplePiedata.series.reduce(simplePieSum)*100)+"%"}})}(),function(){var labelsPieData={labels:["Bananas","Apples","Grapes"],series:[20,15,40]},labelsPieOptions={labelInterpolationFnc:function(value){return value[0]}},labelsPieResponsiveOptions=[["screen and (min-width: 640px)",{chartPadding:30,labelOffset:100,labelDirection:"explode",labelInterpolationFnc:function(value){return value}}],["screen and (min-width: 1024px)",{labelOffset:80,chartPadding:20}]];new Chartist.Pie("#exampleLabelsPie",labelsPieData,labelsPieOptions,labelsPieResponsiveOptions)}(),new Chartist.Pie("#exampleGaugePie",{series:[20,10,30,40]},{donut:!0,donutWidth:60,startAngle:270,total:200,showLabel:!1})}(document,window,jQuery);
Clazz.declarePackage ("J.g3d"); Clazz.load (["J.api.JmolRendererInterface", "JU.GData", "JU.P3i", "$.V3"], "J.g3d.Graphics3D", ["java.lang.NullPointerException", "java.util.Arrays", "javajs.awt.Font", "JU.AU", "J.api.Interface", "J.c.STER", "J.g3d.CylinderRenderer", "$.LineRenderer", "$.Pixelator", "$.PixelatorScreened", "$.PixelatorShaded", "$.PixelatorT", "$.Platform3D", "$.SphereRenderer", "$.TextRenderer", "$.TextString", "JU.C", "$.Normix"], function () { c$ = Clazz.decorateAsClass (function () { this.platform = null; this.line3d = null; this.sphere3d = null; this.cylinder3d = null; this.triangle3d = null; this.circle3d = null; this.hermite3d = null; this.isFullSceneAntialiasingEnabled = false; this.antialias2 = false; this.strings = null; this.stringCount = 0; this.anaglyphChannelBytes = null; this.twoPass = false; this.$haveTranslucentObjects = false; this.pbuf = null; this.pbufT = null; this.zbuf = null; this.zbufT = null; this.translucencyMask = 0; this.renderLow = false; this.shadesCurrent = null; this.anaglyphLength = 0; this.pixel = null; this.pixel0 = null; this.pixelT0 = null; this.pixelScreened = null; this.pixelShaded = null; this.zMargin = 0; this.aobuf = null; this.currentShadeIndex = 0; this.lastRawColor = 0; this.translucencyLog = 0; this.wasScreened = false; this.saveAmbient = 0; this.saveDiffuse = 0; this.sA = null; this.sB = null; this.sC = null; this.vectorAB = null; this.vectorAC = null; this.vectorNormal = null; this.shadeIndexes = null; this.shadeIndexes2Sided = null; this.pass2Flag01 = 0; Clazz.instantialize (this, arguments); }, J.g3d, "Graphics3D", JU.GData, J.api.JmolRendererInterface); Clazz.prepareFields (c$, function () { this.sA = new JU.P3i (); this.sB = new JU.P3i (); this.sC = new JU.P3i (); this.vectorAB = new JU.V3 (); this.vectorAC = new JU.V3 (); this.vectorNormal = new JU.V3 (); this.shadeIndexes = Clazz.newByteArray (JU.GData.normixCount, 0); this.shadeIndexes2Sided = Clazz.newByteArray (JU.GData.normixCount, 0); }); Clazz.overrideMethod (c$, "isWebGL", function () { return false; }); Clazz.overrideMethod (c$, "clear", function () { this.stringCount = 0; this.strings = null; J.g3d.TextRenderer.clearFontCache (); }); Clazz.overrideMethod (c$, "destroy", function () { this.releaseBuffers (); this.platform = null; this.pixel = this.pixel0 = this.pixelShaded = null; this.pixelT0 = null; this.pixelScreened = null; this.graphicsForMetrics = null; }); Clazz.defineMethod (c$, "setZMargin", function (dz) { this.zMargin = dz; }, "~N"); Clazz.makeConstructor (c$, function () { Clazz.superConstructor (this, J.g3d.Graphics3D, []); for (var i = JU.GData.normixCount; --i >= 0; ) this.transformedVectors[i] = new JU.V3 (); }); Clazz.overrideMethod (c$, "initialize", function (vwr, apiPlatform) { this.vwr = vwr; this.apiPlatform = apiPlatform; this.platform = new J.g3d.Platform3D (apiPlatform); this.pixel = this.pixel0 = new J.g3d.Pixelator (this); this.graphicsForMetrics = this.platform.getGraphicsForMetrics (); this.line3d = new J.g3d.LineRenderer (this); this.sphere3d = new J.g3d.SphereRenderer (this); this.cylinder3d = new J.g3d.CylinderRenderer (this); }, "JV.Viewer,javajs.api.GenericPlatform"); Clazz.overrideMethod (c$, "addRenderer", function (tok) { switch (tok) { case 1073741880: if (this.circle3d == null) this.circle3d = this.getRenderer ("Circle"); break; case 553648147: if (this.hermite3d == null) this.hermite3d = this.getRenderer ("Hermite"); case 1073742182: if (this.triangle3d == null) { this.triangle3d = this.getRenderer ("Triangle"); (this.triangle3d).isOrthographic = !this.vwr.tm.perspectiveDepth; }break; } }, "~N"); Clazz.defineMethod (c$, "getRenderer", function (type) { var r = (J.api.Interface.getOption ("g3d." + type + "Renderer", this.vwr, "render")); if (r == null) throw new NullPointerException ("Interface"); r.set (this, this); return r; }, "~S"); Clazz.overrideMethod (c$, "setWindowParameters", function (width, height, antialias) { this.setWinParams (width, height, antialias); if (this.currentlyRendering) this.endRendering (); }, "~N,~N,~B"); Clazz.overrideMethod (c$, "checkTranslucent", function (isAlphaTranslucent) { if (isAlphaTranslucent) this.$haveTranslucentObjects = true; return (!this.twoPass || this.twoPass && (this.isPass2 == isAlphaTranslucent)); }, "~B"); Clazz.overrideMethod (c$, "beginRendering", function (rotationMatrix, translucentMode, isImageWrite, renderLow) { if (this.currentlyRendering) this.endRendering (); this.renderLow = renderLow; if (this.windowWidth != this.newWindowWidth || this.windowHeight != this.newWindowHeight || this.newAntialiasing != this.isFullSceneAntialiasingEnabled) { this.windowWidth = this.newWindowWidth; this.windowHeight = this.newWindowHeight; this.isFullSceneAntialiasingEnabled = this.newAntialiasing; this.releaseBuffers (); }this.setRotationMatrix (rotationMatrix); (this.line3d).isOrthographic = !this.vwr.tm.perspectiveDepth; if (this.triangle3d != null) (this.triangle3d).isOrthographic = !this.vwr.tm.perspectiveDepth; this.antialiasEnabled = this.antialiasThisFrame = this.newAntialiasing; this.currentlyRendering = true; if (this.strings != null) for (var i = Math.min (this.strings.length, this.stringCount); --i >= 0; ) this.strings[i] = null; this.stringCount = 0; this.twoPass = true; this.isPass2 = false; this.pass2Flag01 = 0; this.colixCurrent = 0; this.$haveTranslucentObjects = this.wasScreened = false; this.pixel = this.pixel0; this.pixel.bgcolor = this.bgcolor; this.translucentCoverOnly = !translucentMode; if (this.pbuf == null) { this.platform.allocateBuffers (this.windowWidth, this.windowHeight, this.antialiasThisFrame, isImageWrite); this.pbuf = this.platform.pBuffer; this.zbuf = this.platform.zBuffer; this.aobuf = null; this.pixel0.setBuf (); if (this.pixelT0 != null) this.pixelT0.setBuf (); if (this.pixelShaded != null) this.pixelShaded.setBuf (); }this.setWidthHeight (this.antialiasThisFrame); if (this.pixelScreened != null) this.pixelScreened.width = this.width; this.platform.clearBuffer (); if (this.backgroundImage != null) this.plotImage (-2147483648, 0, -2147483648, this.backgroundImage, null, 0, 0, 0); this.textY = 0; }, "JU.M3,~B,~B,~B"); Clazz.overrideMethod (c$, "setBackgroundTransparent", function (TF) { if (this.platform != null) this.platform.setBackgroundTransparent (TF); }, "~B"); Clazz.defineMethod (c$, "releaseBuffers", function () { this.pbuf = null; this.zbuf = null; this.pbufT = null; this.zbufT = null; this.aobuf = null; this.platform.releaseBuffers (); this.line3d.clearLineCache (); }); Clazz.overrideMethod (c$, "setPass2", function (antialiasTranslucent) { if (!this.$haveTranslucentObjects || !this.currentlyRendering) return false; this.isPass2 = true; this.pass2Flag01 = 1; this.colixCurrent = 0; if (this.pbufT == null || this.antialias2 != antialiasTranslucent) { this.platform.allocateTBuffers (antialiasTranslucent); this.pbufT = this.platform.pBufferT; this.zbufT = this.platform.zBufferT; }this.antialias2 = antialiasTranslucent; if (this.antialiasThisFrame && !this.antialias2) this.downsampleFullSceneAntialiasing (true); this.platform.clearTBuffer (); if (this.pixelT0 == null) this.pixelT0 = new J.g3d.PixelatorT (this); if (this.pixel.p0 == null) this.pixel = this.pixelT0; else this.pixel.p0 = this.pixelT0; return true; }, "~B"); Clazz.overrideMethod (c$, "endRendering", function () { if (!this.currentlyRendering) return; if (this.pbuf != null) { if (this.isPass2 && this.pbufT != null) for (var offset = this.pbufT.length; --offset >= 0; ) this.pbuf[offset] = J.g3d.Graphics3D.mergeBufferPixel (this.pbuf[offset], this.pbufT[offset], this.bgcolor); if (this.pixel === this.pixelShaded && this.pixelShaded.zShadePower == 0) this.pixelShaded.showZBuffer (); if (this.antialiasThisFrame) this.downsampleFullSceneAntialiasing (false); }this.platform.setBackgroundColor (this.bgcolor); this.platform.notifyEndOfRendering (); this.currentlyRendering = this.isPass2 = false; }); c$.mergeBufferPixel = Clazz.defineMethod (c$, "mergeBufferPixel", function (argbA, argbB, bgcolor) { if (argbB == 0 || argbA == argbB) return argbA; if (argbA == 0) argbA = bgcolor; var rbA = (argbA & 0x00FF00FF); var gA = (argbA & 0x0000FF00); var rbB = (argbB & 0x00FF00FF); var gB = (argbB & 0x0000FF00); var logAlpha = (argbB >> 24) & 0xF; switch (logAlpha) { case 0: rbA = rbB; gA = gB; break; case 1: rbA = (((rbB << 2) + (rbB << 1) + rbB + rbA) >> 3) & 0x00FF00FF; gA = (((gB << 2) + +(gB << 1) + gB + gA) >> 3) & 0x0000FF00; break; case 2: rbA = (((rbB << 1) + rbB + rbA) >> 2) & 0x00FF00FF; gA = (((gB << 1) + gB + gA) >> 2) & 0x0000FF00; break; case 3: rbA = (((rbB << 2) + rbB + (rbA << 1) + rbA) >> 3) & 0x00FF00FF; gA = (((gB << 2) + gB + (gA << 1) + gA) >> 3) & 0x0000FF00; break; case 4: rbA = ((rbA + rbB) >> 1) & 0x00FF00FF; gA = ((gA + gB) >> 1) & 0x0000FF00; break; case 5: rbA = (((rbB << 1) + rbB + (rbA << 2) + rbA) >> 3) & 0x00FF00FF; gA = (((gB << 1) + gB + (gA << 2) + gA) >> 3) & 0x0000FF00; break; case 6: rbA = (((rbA << 1) + rbA + rbB) >> 2) & 0x00FF00FF; gA = (((gA << 1) + gA + gB) >> 2) & 0x0000FF00; break; case 7: rbA = (((rbA << 2) + (rbA << 1) + rbA + rbB) >> 3) & 0x00FF00FF; gA = (((gA << 2) + (gA << 1) + gA + gB) >> 3) & 0x0000FF00; break; } return 0xFF000000 | rbA | gA; }, "~N,~N,~N"); Clazz.overrideMethod (c$, "getScreenImage", function (isImageWrite) { { var obj = this.platform.bufferedImage; if (isImageWrite) { this.releaseBuffers(); } return obj; }}, "~B"); Clazz.overrideMethod (c$, "applyAnaglygh", function (stereoMode, stereoColors) { switch (stereoMode) { case J.c.STER.REDCYAN: for (var i = this.anaglyphLength; --i >= 0; ) { var blue = this.anaglyphChannelBytes[i] & 0x000000FF; var cyan = (blue << 8) | blue; this.pbuf[i] = this.pbuf[i] & 0xFFFF0000 | cyan; } break; case J.c.STER.CUSTOM: var color1 = stereoColors[0]; var color2 = stereoColors[1] & 0x00FFFFFF; for (var i = this.anaglyphLength; --i >= 0; ) { var a = this.anaglyphChannelBytes[i] & 0x000000FF; a = (a | ((a | (a << 8)) << 8)) & color2; this.pbuf[i] = (this.pbuf[i] & color1) | a; } break; case J.c.STER.REDBLUE: for (var i = this.anaglyphLength; --i >= 0; ) { var blue = this.anaglyphChannelBytes[i] & 0x000000FF; this.pbuf[i] = (this.pbuf[i] & 0xFFFF0000) | blue; } break; case J.c.STER.REDGREEN: for (var i = this.anaglyphLength; --i >= 0; ) { var green = (this.anaglyphChannelBytes[i] & 0x000000FF) << 8; this.pbuf[i] = (this.pbuf[i] & 0xFFFF0000) | green; } break; case J.c.STER.DTI: case J.c.STER.DOUBLE: case J.c.STER.NONE: break; } }, "J.c.STER,~A"); Clazz.overrideMethod (c$, "snapshotAnaglyphChannelBytes", function () { if (this.currentlyRendering) throw new NullPointerException (); this.anaglyphLength = this.windowWidth * this.windowHeight; if (this.anaglyphChannelBytes == null || this.anaglyphChannelBytes.length != this.anaglyphLength) this.anaglyphChannelBytes = Clazz.newByteArray (this.anaglyphLength, 0); for (var i = this.anaglyphLength; --i >= 0; ) this.anaglyphChannelBytes[i] = this.pbuf[i]; }); Clazz.overrideMethod (c$, "releaseScreenImage", function () { this.platform.clearScreenBufferThreaded (); }); Clazz.overrideMethod (c$, "haveTranslucentObjects", function () { return this.$haveTranslucentObjects; }); Clazz.overrideMethod (c$, "setSlabAndZShade", function (slabValue, depthValue, zSlab, zDepth, zShadePower) { this.setSlab (slabValue); this.setDepth (depthValue); if (zSlab < zDepth) { if (this.pixelShaded == null) this.pixelShaded = new J.g3d.PixelatorShaded (this); this.pixel = this.pixelShaded.set (zSlab, zDepth, zShadePower); } else { this.pixel = this.pixel0; }}, "~N,~N,~N,~N,~N"); Clazz.defineMethod (c$, "downsampleFullSceneAntialiasing", function (downsampleZBuffer) { var bgcheck = this.bgcolor; if (downsampleZBuffer) bgcheck += ((bgcheck & 0xFF) == 0xFF ? -1 : 1); J.g3d.Graphics3D.downsample2d (this.pbuf, this.windowWidth, this.windowHeight, bgcheck); if (downsampleZBuffer) { J.g3d.Graphics3D.downsample2dZ (this.pbuf, this.zbuf, this.windowWidth, this.windowHeight, bgcheck); this.antialiasThisFrame = false; this.setWidthHeight (false); }}, "~B"); c$.downsample2d = Clazz.defineMethod (c$, "downsample2d", function (pbuf, width, height, bgcheck) { var width4 = width << 1; if (bgcheck != 0) { bgcheck &= 0xFFFFFF; for (var i = pbuf.length; --i >= 0; ) if (pbuf[i] == 0) pbuf[i] = bgcheck; }var bg0 = ((bgcheck >> 2) & 0x3F3F3F3F) << 2; bg0 += (bg0 & 0xC0C0C0C0) >> 6; var offset1 = 0; var offset4 = 0; for (var i = height; --i >= 0; offset4 += width4) for (var j = width; --j >= 0; ++offset1) { var argb = ((pbuf[offset4] >> 2) & 0x3F3F3F3F) + ((pbuf[offset4++ + width4] >> 2) & 0x3F3F3F3F) + ((pbuf[offset4] >> 2) & 0x3F3F3F3F) + ((pbuf[offset4++ + width4] >> 2) & 0x3F3F3F3F); argb += (argb & 0xC0C0C0C0) >> 6; if (argb == bg0) argb = bgcheck; { pbuf[offset1] = argb & 0x00FFFFFF | 0xFF000000; }} }, "~A,~N,~N,~N"); c$.downsample2dZ = Clazz.defineMethod (c$, "downsample2dZ", function (pbuf, zbuf, width, height, bgcheck) { var width4 = width << 1; var offset1 = 0; var offset4 = 0; for (var i = height; --i >= 0; offset4 += width4) for (var j = width; --j >= 0; ++offset1, ++offset4) { var z = Math.min (zbuf[offset4], zbuf[offset4 + width4]); z = Math.min (z, zbuf[++offset4]); z = Math.min (z, zbuf[offset4 + width4]); if (z != 2147483647) z >>= 1; zbuf[offset1] = (pbuf[offset1] == bgcheck ? 2147483647 : z); } }, "~A,~A,~N,~N,~N"); Clazz.defineMethod (c$, "hasContent", function () { return this.platform.hasContent (); }); Clazz.overrideMethod (c$, "setC", function (colix) { var isLast = JU.C.isColixLastAvailable (colix); if (!isLast && colix == this.colixCurrent && this.currentShadeIndex == -1) return true; var mask = colix & 30720; if (mask == 16384) return false; if (this.renderLow) mask = 0; var isTranslucent = (mask != 0); var isScreened = (isTranslucent && mask == 30720); this.setScreened (isScreened); if (!this.checkTranslucent (isTranslucent && !isScreened)) return false; if (this.isPass2) { this.translucencyMask = (mask << 13) | 0xFFFFFF; this.translucencyLog = mask >> 11; } else { this.translucencyLog = 0; }this.colixCurrent = colix; if (isLast) { if (this.argbCurrent != this.lastRawColor) { if (this.argbCurrent == 0) this.argbCurrent = 0xFFFFFFFF; this.lastRawColor = this.argbCurrent; this.shader.setLastColix (this.argbCurrent, this.inGreyscaleMode); }}this.shadesCurrent = this.getShades (colix); this.currentShadeIndex = -1; this.setColor (this.getColorArgbOrGray (colix)); return true; }, "~N"); Clazz.defineMethod (c$, "setScreened", function (isScreened) { if (this.wasScreened != isScreened) { this.wasScreened = isScreened; if (isScreened) { if (this.pixelScreened == null) this.pixelScreened = new J.g3d.PixelatorScreened (this, this.pixel0); if (this.pixel.p0 == null) this.pixel = this.pixelScreened; else this.pixel.p0 = this.pixelScreened; } else if (this.pixel.p0 == null || this.pixel === this.pixelScreened) { this.pixel = (this.isPass2 ? this.pixelT0 : this.pixel0); } else { this.pixel.p0 = (this.isPass2 ? this.pixelT0 : this.pixel0); }}return this.pixel; }, "~B"); Clazz.overrideMethod (c$, "drawFilledCircle", function (colixRing, colixFill, diameter, x, y, z) { if (this.isClippedZ (z)) return; var r = Clazz.doubleToInt ((diameter + 1) / 2); var isClipped = x < r || x + r >= this.width || y < r || y + r >= this.height; if (isClipped && this.isClippedXY (diameter, x, y)) return; if (colixRing != 0 && this.setC (colixRing)) { if (isClipped) { if (!this.isClippedXY (diameter, x, y)) (this.circle3d).plotCircleCenteredClipped (x, y, z, diameter); } else { (this.circle3d).plotCircleCenteredUnclipped (x, y, z, diameter); }}if (colixFill != 0 && this.setC (colixFill)) { if (isClipped) (this.circle3d).plotFilledCircleCenteredClipped (x, y, z, diameter); else (this.circle3d).plotFilledCircleCenteredUnclipped (x, y, z, diameter); }}, "~N,~N,~N,~N,~N,~N"); Clazz.overrideMethod (c$, "volumeRender4", function (diameter, x, y, z) { if (diameter == 1) { this.plotPixelClippedArgb (this.argbCurrent, x, y, z, this.width, this.zbuf, this.pixel); return; }if (this.isClippedZ (z)) return; var r = Clazz.doubleToInt ((diameter + 1) / 2); var isClipped = x < r || x + r >= this.width || y < r || y + r >= this.height; if (isClipped && this.isClippedXY (diameter, x, y)) return; if (isClipped) (this.circle3d).plotFilledCircleCenteredClipped (x, y, z, diameter); else (this.circle3d).plotFilledCircleCenteredUnclipped (x, y, z, diameter); }, "~N,~N,~N,~N"); Clazz.overrideMethod (c$, "fillSphereXYZ", function (diameter, x, y, z) { switch (diameter) { case 1: this.plotPixelClippedArgb (this.argbCurrent, x, y, z, this.width, this.zbuf, this.pixel); return; case 0: return; } if (diameter <= (this.antialiasThisFrame ? 2000 : 1000)) this.sphere3d.render (this.shadesCurrent, diameter, x, y, z, null, null, null, -1, null); }, "~N,~N,~N,~N"); Clazz.overrideMethod (c$, "volumeRender", function (TF) { if (TF) { this.saveAmbient = this.getAmbientPercent (); this.saveDiffuse = this.getDiffusePercent (); this.setAmbientPercent (100); this.setDiffusePercent (0); this.addRenderer (1073741880); } else { this.setAmbientPercent (this.saveAmbient); this.setDiffusePercent (this.saveDiffuse); }}, "~B"); Clazz.overrideMethod (c$, "fillSphereI", function (diameter, center) { this.fillSphereXYZ (diameter, center.x, center.y, center.z); }, "~N,JU.P3i"); Clazz.overrideMethod (c$, "fillSphereBits", function (diameter, center) { this.fillSphereXYZ (diameter, Math.round (center.x), Math.round (center.y), Math.round (center.z)); }, "~N,JU.P3"); Clazz.overrideMethod (c$, "fillEllipsoid", function (center, points, x, y, z, diameter, mToEllipsoidal, coef, mDeriv, selectedOctant, octantPoints) { switch (diameter) { case 1: this.plotPixelClippedArgb (this.argbCurrent, x, y, z, this.width, this.zbuf, this.pixel); return; case 0: return; } if (diameter <= (this.antialiasThisFrame ? 2000 : 1000)) this.sphere3d.render (this.shadesCurrent, diameter, x, y, z, mToEllipsoidal, coef, mDeriv, selectedOctant, octantPoints); }, "JU.P3,~A,~N,~N,~N,~N,JU.M3,~A,JU.M4,~N,~A"); Clazz.overrideMethod (c$, "drawRect", function (x, y, z, zSlab, rWidth, rHeight) { if (zSlab != 0 && this.isClippedZ (zSlab)) return; var w = rWidth - 1; var h = rHeight - 1; var xRight = x + w; var yBottom = y + h; if (y >= 0 && y < this.height) this.drawHLine (x, y, z, w); if (yBottom >= 0 && yBottom < this.height) this.drawHLine (x, yBottom, z, w); if (x >= 0 && x < this.width) this.drawVLine (x, y, z, h); if (xRight >= 0 && xRight < this.width) this.drawVLine (xRight, y, z, h); }, "~N,~N,~N,~N,~N,~N"); Clazz.defineMethod (c$, "drawHLine", function (x, y, z, w) { if (w < 0) { x += w; w = -w; }if (x < 0) { w += x; x = 0; }if (x + w >= this.width) w = this.width - 1 - x; var p = this.pixel; var c = this.argbCurrent; var offset = x + this.width * y; for (var i = 0; i <= w; i++) { if (z < this.zbuf[offset]) p.addPixel (offset, z, c); offset++; } }, "~N,~N,~N,~N"); Clazz.defineMethod (c$, "drawVLine", function (x, y, z, h) { if (h < 0) { y += h; h = -h; }if (y < 0) { h += y; y = 0; }if (y + h >= this.height) { h = this.height - 1 - y; }var offset = x + this.width * y; var p = this.pixel; var c = this.argbCurrent; for (var i = 0; i <= h; i++) { if (z < this.zbuf[offset]) p.addPixel (offset, z, c); offset += this.width; } }, "~N,~N,~N,~N"); Clazz.overrideMethod (c$, "fillTextRect", function (x, y, z, zSlab, widthFill, heightFill) { if (this.isClippedZ (zSlab)) return; var w = this.width; if (x < 0) { widthFill += x; if (widthFill <= 0) return; x = 0; }if (x + widthFill > w) { widthFill = w - x; if (widthFill <= 0) return; }if (y < 0) { heightFill += y; if (heightFill <= 0) return; y = 0; }if (y + heightFill > this.height) heightFill = this.height - y; var c = this.argbCurrent; var zb = this.zbuf; var p = this.pixel; while (--heightFill >= 0) this.plotPixelsUnclippedCount (c, widthFill, x, y++, z, w, zb, p); }, "~N,~N,~N,~N,~N,~N"); Clazz.overrideMethod (c$, "drawString", function (str, font3d, xBaseline, yBaseline, z, zSlab, bgColix) { this.currentShadeIndex = 0; if (str == null) return; if (this.isClippedZ (zSlab)) return; this.drawStringNoSlab (str, font3d, xBaseline, yBaseline, z, bgColix); }, "~S,javajs.awt.Font,~N,~N,~N,~N,~N"); Clazz.overrideMethod (c$, "drawStringNoSlab", function (str, font3d, xBaseline, yBaseline, z, bgColix) { if (str == null) return; if (this.strings == null) this.strings = new Array (10); if (this.stringCount == this.strings.length) this.strings = JU.AU.doubleLength (this.strings); var t = new J.g3d.TextString (); t.setText (str, font3d == null ? this.currentFont : (this.currentFont = font3d), this.argbCurrent, JU.C.isColixTranslucent (bgColix) ? (this.getColorArgbOrGray (bgColix) & 0xFFFFFF) | ((bgColix & 30720) << 13) : 0, xBaseline, yBaseline, z); this.strings[this.stringCount++] = t; }, "~S,javajs.awt.Font,~N,~N,~N,~N"); Clazz.overrideMethod (c$, "renderAllStrings", function (jmolRenderer) { if (this.strings == null) return; if (this.stringCount >= 2) { if (J.g3d.Graphics3D.sort == null) J.g3d.Graphics3D.sort = new J.g3d.TextString (); java.util.Arrays.sort (this.strings, J.g3d.Graphics3D.sort); }for (var i = 0; i < this.stringCount; i++) { var ts = this.strings[i]; this.plotText (ts.x, ts.y, ts.z, ts.argb, ts.bgargb, ts.text, ts.font, jmolRenderer); } this.strings = null; this.stringCount = 0; }, "~O"); Clazz.overrideMethod (c$, "plotText", function (x, y, z, argb, bgargb, text, font3d, jmolRenderer) { J.g3d.TextRenderer.plot (x, y, z, argb, bgargb, text, font3d, this, jmolRenderer, this.antialiasThisFrame); }, "~N,~N,~N,~N,~N,~S,javajs.awt.Font,J.api.JmolRendererInterface"); Clazz.overrideMethod (c$, "drawImage", function (objImage, x, y, z, zSlab, bgcolix, width, height) { if (objImage != null && width > 0 && height > 0 && !this.isClippedZ (zSlab)) this.plotImage (x, y, z, objImage, null, bgcolix, width, height); }, "~O,~N,~N,~N,~N,~N,~N,~N"); Clazz.overrideMethod (c$, "plotImage", function (x, y, z, image, jmolRenderer, bgcolix, imageWidth, imageHeight) { this.setC (bgcolix); if (!this.isPass2) this.translucencyMask = -1; if (bgcolix == 0) this.argbCurrent = 0; var isBackground = (x == -2147483648); var bg = (isBackground ? this.bgcolor : this.argbCurrent); if (isBackground) { x = 0; z = 2147483646; imageWidth = this.width; imageHeight = this.height; }if (x + imageWidth <= 0 || x >= this.width || y + imageHeight <= 0 || y >= this.height) return; var g; { g = null; }var buffer = this.apiPlatform.drawImageToBuffer (g, this.platform.offscreenImage, image, imageWidth, imageHeight, isBackground ? bg : 0); if (buffer == null) return; var zb = this.zbuf; var w = this.width; var p = this.pixel; var h = this.height; var t = this.translucencyLog; if (jmolRenderer == null && (x >= 0 && x + imageWidth <= w && y >= 0 && y + imageHeight <= h)) { for (var i = 0, offset = 0, pbufOffset = y * w + x; i < imageHeight; i++, pbufOffset += (w - imageWidth)) { for (var j = 0; j < imageWidth; j++, offset++, pbufOffset++) { if (z < zb[pbufOffset]) { var b = buffer[offset]; if ((b & 0xFF000000) == (-16777216)) p.addPixel (pbufOffset, z, b); }} } } else { if (jmolRenderer == null) jmolRenderer = this; for (var i = 0, offset = 0; i < imageHeight; i++) for (var j = 0; j < imageWidth; j++) { var b = buffer[offset++]; if ((b & 0xFF000000) == (-16777216)) jmolRenderer.plotImagePixel (b, x + j, y + i, z, 8, bg, w, h, zb, p, t); } }}, "~N,~N,~N,~O,J.api.JmolRendererInterface,~N,~N,~N"); Clazz.overrideMethod (c$, "setFontFid", function (fid) { this.currentFont = javajs.awt.Font.getFont3D (fid); }, "~N"); Clazz.overrideMethod (c$, "setFont", function (font3d) { this.currentFont = font3d; }, "javajs.awt.Font"); Clazz.overrideMethod (c$, "drawPixel", function (x, y, z) { this.plotPixelClippedArgb (this.argbCurrent, x, y, z, this.width, this.zbuf, this.pixel); }, "~N,~N,~N"); Clazz.overrideMethod (c$, "drawPoints", function (count, coordinates, scale) { if (scale > 1) { var s2 = scale * scale * 0.8; for (var i = -scale; i < scale; i++) { for (var j = -scale; j < scale; j++) { if (i * i + j * j > s2) continue; this.plotPoints (count, coordinates, i, j); this.plotPoints (count, coordinates, i, j); } } } else { this.plotPoints (count, coordinates, 0, 0); }}, "~N,~A,~N"); Clazz.overrideMethod (c$, "drawDashedLineBits", function (run, rise, pointA, pointB) { this.setScreeni (pointA, this.sA); this.setScreeni (pointB, this.sB); this.line3d.plotLineBits (this.argbCurrent, this.argbCurrent, this.sA, this.sB, run, rise, true); }, "~N,~N,JU.P3,JU.P3"); Clazz.defineMethod (c$, "setScreeni", function (pt, p) { p.x = Math.round (pt.x); p.y = Math.round (pt.y); p.z = Math.round (pt.z); }, "JU.P3,JU.P3i"); Clazz.overrideMethod (c$, "drawLineXYZ", function (x1, y1, z1, x2, y2, z2) { this.line3d.plotLineOld (this.argbCurrent, this.argbCurrent, x1, y1, z1, x2, y2, z2); }, "~N,~N,~N,~N,~N,~N"); Clazz.overrideMethod (c$, "drawLine", function (colixA, colixB, x1, y1, z1, x2, y2, z2) { if (!this.setC (colixA)) colixA = 0; var argbA = this.argbCurrent; if (!this.setC (colixB)) colixB = 0; if (colixA != 0 || colixB != 0) this.line3d.plotLineOld (argbA, this.argbCurrent, x1, y1, z1, x2, y2, z2); }, "~N,~N,~N,~N,~N,~N,~N,~N"); Clazz.overrideMethod (c$, "drawLineBits", function (colixA, colixB, pointA, pointB) { if (!this.setC (colixA)) colixA = 0; var argbA = this.argbCurrent; if (!this.setC (colixB)) colixB = 0; if (colixA != 0 || colixB != 0) { this.setScreeni (pointA, this.sA); this.setScreeni (pointB, this.sB); this.line3d.plotLineBits (argbA, this.argbCurrent, this.sA, this.sB, 0, 0, false); }}, "~N,~N,JU.P3,JU.P3"); Clazz.overrideMethod (c$, "drawLineAB", function (pointA, pointB) { this.setScreeni (pointA, this.sA); this.setScreeni (pointB, this.sB); this.line3d.plotLineBits (this.argbCurrent, this.argbCurrent, this.sA, this.sB, 0, 0, false); }, "JU.P3,JU.P3"); Clazz.overrideMethod (c$, "fillCylinderXYZ", function (colixA, colixB, endcaps, diameter, xA, yA, zA, xB, yB, zB) { if (diameter > this.ht3) return; var screen = 0; this.currentShadeIndex = 0; if (!this.setC (colixB)) colixB = 0; if (this.wasScreened) screen = 2; if (!this.setC (colixA)) colixA = 0; if (this.wasScreened) screen += 1; if (colixA == 0 && colixB == 0) return; this.cylinder3d.renderOld (colixA, colixB, screen, endcaps, diameter, xA, yA, zA, xB, yB, zB); }, "~N,~N,~N,~N,~N,~N,~N,~N,~N,~N"); Clazz.overrideMethod (c$, "fillCylinderScreen3I", function (endcaps, diameter, screenA, screenB, pt0f, pt1f, radius) { if (diameter <= this.ht3) this.cylinder3d.renderOld (this.colixCurrent, this.colixCurrent, 0, endcaps, diameter, Clazz.floatToInt (screenA.x), Clazz.floatToInt (screenA.y), Clazz.floatToInt (screenA.z), Clazz.floatToInt (screenB.x), Clazz.floatToInt (screenB.y), Clazz.floatToInt (screenB.z)); }, "~N,~N,JU.P3,JU.P3,JU.P3,JU.P3,~N"); Clazz.overrideMethod (c$, "fillCylinder", function (endcaps, diameter, screenA, screenB) { if (diameter <= this.ht3) this.cylinder3d.renderOld (this.colixCurrent, this.colixCurrent, 0, endcaps, diameter, screenA.x, screenA.y, screenA.z, screenB.x, screenB.y, screenB.z); }, "~N,~N,JU.P3i,JU.P3i"); Clazz.overrideMethod (c$, "fillCylinderBits", function (endcaps, diameter, screenA, screenB) { if (diameter <= this.ht3 && screenA.z != 1 && screenB.z != 1) { this.setScreeni (screenA, this.sA); this.setScreeni (screenB, this.sB); this.cylinder3d.renderBits (this.colixCurrent, this.colixCurrent, 0, endcaps, diameter, this.sA, this.sB); }}, "~N,~N,JU.P3,JU.P3"); Clazz.overrideMethod (c$, "fillCylinderBits2", function (colixA, colixB, endcaps, diameter, screenA, screenB) { if (diameter > this.ht3) return; var screen = 0; this.currentShadeIndex = 0; if (!this.setC (colixB)) colixB = 0; if (this.wasScreened) screen = 2; if (!this.setC (colixA)) colixA = 0; if (this.wasScreened) screen += 1; if (colixA == 0 && colixB == 0) return; this.setScreeni (screenA, this.sA); this.setScreeni (screenB, this.sB); this.cylinder3d.renderBits (colixA, colixB, screen, endcaps, diameter, this.sA, this.sB); }, "~N,~N,~N,~N,JU.P3,JU.P3"); Clazz.overrideMethod (c$, "fillConeScreen3f", function (endcap, screenDiameter, screenBase, screenTip, isBarb) { if (screenDiameter <= this.ht3) this.cylinder3d.renderConeOld (this.colixCurrent, endcap, screenDiameter, screenBase.x, screenBase.y, screenBase.z, screenTip.x, screenTip.y, screenTip.z, true, isBarb); }, "~N,~N,JU.P3,JU.P3,~B"); Clazz.overrideMethod (c$, "drawHermite4", function (tension, s0, s1, s2, s3) { (this.hermite3d).renderHermiteRope (false, tension, 0, 0, 0, s0, s1, s2, s3); }, "~N,JU.P3,JU.P3,JU.P3,JU.P3"); Clazz.overrideMethod (c$, "drawHermite7", function (fill, border, tension, s0, s1, s2, s3, s4, s5, s6, s7, aspectRatio, colixBack) { if (colixBack == 0) { (this.hermite3d).renderHermiteRibbon (fill, border, tension, s0, s1, s2, s3, s4, s5, s6, s7, aspectRatio, 0); return; }(this.hermite3d).renderHermiteRibbon (fill, border, tension, s0, s1, s2, s3, s4, s5, s6, s7, aspectRatio, 1); var colix = this.colixCurrent; this.setC (colixBack); (this.hermite3d).renderHermiteRibbon (fill, border, tension, s0, s1, s2, s3, s4, s5, s6, s7, aspectRatio, -1); this.setC (colix); }, "~B,~B,~N,JU.P3,JU.P3,JU.P3,JU.P3,JU.P3,JU.P3,JU.P3,JU.P3,~N,~N"); Clazz.overrideMethod (c$, "fillHermite", function (tension, diameterBeg, diameterMid, diameterEnd, s0, s1, s2, s3) { (this.hermite3d).renderHermiteRope (true, tension, diameterBeg, diameterMid, diameterEnd, s0, s1, s2, s3); }, "~N,~N,~N,~N,JU.P3,JU.P3,JU.P3,JU.P3"); Clazz.overrideMethod (c$, "drawTriangle3C", function (screenA, colixA, screenB, colixB, screenC, colixC, check) { if ((check & 1) == 1) this.drawLine (colixA, colixB, screenA.x, screenA.y, screenA.z, screenB.x, screenB.y, screenB.z); if ((check & 2) == 2) this.drawLine (colixB, colixC, screenB.x, screenB.y, screenB.z, screenC.x, screenC.y, screenC.z); if ((check & 4) == 4) this.drawLine (colixA, colixC, screenA.x, screenA.y, screenA.z, screenC.x, screenC.y, screenC.z); }, "JU.P3i,~N,JU.P3i,~N,JU.P3i,~N,~N"); Clazz.overrideMethod (c$, "fillTriangleTwoSided", function (normix, screenA, screenB, screenC) { this.setColorNoisy (this.getShadeIndex (normix)); this.fillTriangleP3f (screenA, screenB, screenC, false); }, "~N,JU.P3,JU.P3,JU.P3"); Clazz.defineMethod (c$, "fillTriangleP3f", function (screenA, screenB, screenC, useGouraud) { this.setScreeni (screenA, this.sA); this.setScreeni (screenB, this.sB); this.setScreeni (screenC, this.sC); (this.triangle3d).fillTriangle (this.sA, this.sB, this.sC, useGouraud); }, "JU.P3,JU.P3,JU.P3,~B"); Clazz.overrideMethod (c$, "fillTriangle3f", function (screenA, screenB, screenC, isSolid) { var i = this.getShadeIndexP3 (screenA, screenB, screenC, isSolid); if (i < 0) return; if (isSolid) this.setColorNoisy (i); else this.setColor (this.shadesCurrent[i]); this.fillTriangleP3f (screenA, screenB, screenC, false); }, "JU.P3,JU.P3,JU.P3,~B"); Clazz.overrideMethod (c$, "fillTriangle3i", function (screenA, screenB, screenC, ptA, ptB, ptC, doShade) { if (doShade) { var v = this.vectorAB; v.set (screenB.x - screenA.x, screenB.y - screenA.y, screenB.z - screenA.z); var shadeIndex; if (screenC == null) { shadeIndex = this.shader.getShadeIndex (-v.x, -v.y, v.z); } else { this.vectorAC.set (screenC.x - screenA.x, screenC.y - screenA.y, screenC.z - screenA.z); v.cross (v, this.vectorAC); shadeIndex = v.z >= 0 ? this.shader.getShadeIndex (-v.x, -v.y, v.z) : this.shader.getShadeIndex (v.x, v.y, -v.z); }if (shadeIndex > 56) shadeIndex = 56; this.setColorNoisy (shadeIndex); }this.fillTriangleP3f (screenA, screenB, screenC, false); }, "JU.P3,JU.P3,JU.P3,JU.T3,JU.T3,JU.T3,~B"); Clazz.overrideMethod (c$, "fillTriangle3CN", function (screenA, colixA, normixA, screenB, colixB, normixB, screenC, colixC, normixC) { (this.triangle3d).fillTriangle (screenA, screenB, screenC, this.checkGouraud (colixA, colixB, colixC, normixA, normixB, normixC)); }, "JU.P3i,~N,~N,JU.P3i,~N,~N,JU.P3i,~N,~N"); Clazz.overrideMethod (c$, "fillTriangle3CNBits", function (screenA, colixA, normixA, screenB, colixB, normixB, screenC, colixC, normixC, twoSided) { this.fillTriangleP3f (screenA, screenB, screenC, this.checkGouraud (colixA, colixB, colixC, normixA, normixB, normixC)); }, "JU.P3,~N,~N,JU.P3,~N,~N,JU.P3,~N,~N,~B"); Clazz.defineMethod (c$, "checkGouraud", function (colixA, colixB, colixC, normixA, normixB, normixC) { if (!this.isPass2 && normixA == normixB && normixA == normixC && colixA == colixB && colixA == colixC) { var shadeIndex = this.getShadeIndex (normixA); if (colixA != this.colixCurrent || this.currentShadeIndex != shadeIndex) { this.currentShadeIndex = -1; this.setC (colixA); this.setColorNoisy (shadeIndex); }return false; }this.setTriangleTranslucency (colixA, colixB, colixC); (this.triangle3d).setGouraud (this.getShades (colixA)[this.getShadeIndex (normixA)], this.getShades (colixB)[this.getShadeIndex (normixB)], this.getShades (colixC)[this.getShadeIndex (normixC)]); return true; }, "~N,~N,~N,~N,~N,~N"); Clazz.defineMethod (c$, "getShadeIndex", function (normix) { return (normix == -10000 || normix == 9999 ? J.g3d.Graphics3D.nullShadeIndex : normix < 0 ? this.shadeIndexes2Sided[~normix] : this.shadeIndexes[normix]); }, "~N"); Clazz.defineMethod (c$, "setTriangleTranslucency", function (colixA, colixB, colixC) { if (this.isPass2) { var maskA = colixA & 30720; var maskB = colixB & 30720; var maskC = colixC & 30720; maskA &= -16385; maskB &= -16385; maskC &= -16385; var mask = JU.GData.roundInt (Clazz.doubleToInt ((maskA + maskB + maskC) / 3)) & 30720; this.translucencyMask = (mask << 13) | 0xFFFFFF; }}, "~N,~N,~N"); Clazz.overrideMethod (c$, "fillQuadrilateral", function (screenA, screenB, screenC, screenD, isSolid) { var i = this.getShadeIndexP3 (screenA, screenB, screenC, isSolid); if (i < 0) return; this.setColorNoisy (i); this.fillTriangleP3f (screenA, screenB, screenC, false); this.fillTriangleP3f (screenA, screenC, screenD, false); }, "JU.P3,JU.P3,JU.P3,JU.P3,~B"); Clazz.overrideMethod (c$, "drawSurface", function (meshSurface, colix) { }, "JU.MeshSurface,~N"); Clazz.overrideMethod (c$, "plotPixelClippedP3i", function (screen) { this.plotPixelClippedArgb (this.argbCurrent, screen.x, screen.y, screen.z, this.width, this.zbuf, this.pixel); }, "JU.P3i"); Clazz.defineMethod (c$, "plotPixelClippedArgb", function (argb, x, y, z, width, zbuf, p) { if (this.isClipped3 (x, y, z)) return; var offset = y * width + x; if (z < zbuf[offset]) p.addPixel (offset, z, argb); }, "~N,~N,~N,~N,~N,~A,J.g3d.Pixelator"); Clazz.defineMethod (c$, "plotPixelUnclipped", function (argb, x, y, z, width, zbuf, p) { var offset = y * width + x; if (z < zbuf[offset]) p.addPixel (offset, z, argb); }, "~N,~N,~N,~N,~N,~A,J.g3d.Pixelator"); Clazz.defineMethod (c$, "plotImagePixel", function (argb, x, y, z, shade, bgargb, width, height, zbuf, p, transpLog) { if (x < 0 || x >= width || y < 0 || y >= height) return; (p).addImagePixel (shade, transpLog, y * width + x, z, argb, bgargb); }, "~N,~N,~N,~N,~N,~N,~N,~N,~A,~O,~N"); Clazz.defineMethod (c$, "plotPixelsClippedRaster", function (count, x, y, zAtLeft, zPastRight, rgb16Left, rgb16Right) { var depth; var slab; if (count <= 0 || y < 0 || y >= this.height || x >= this.width || (zAtLeft < (slab = this.slab) && zPastRight < slab) || (zAtLeft > (depth = this.depth) && zPastRight > depth)) return; var zb = this.zbuf; var seed = (x << 16) + (y << 1) ^ 0x33333333; var zScaled = (zAtLeft << 10) + (512); var dz = zPastRight - zAtLeft; var roundFactor = Clazz.doubleToInt (count / 2); var zIncrementScaled = JU.GData.roundInt (Clazz.doubleToInt (((dz << 10) + (dz >= 0 ? roundFactor : -roundFactor)) / count)); if (x < 0) { x = -x; zScaled += zIncrementScaled * x; count -= x; if (count <= 0) return; x = 0; }if (count + x > this.width) count = this.width - x; var offsetPbuf = y * this.width + x; var p = this.pixel; if (rgb16Left == null) { var adn = this.argbNoisyDn; var aup = this.argbNoisyUp; var ac = this.argbCurrent; while (--count >= 0) { var z = zScaled >> 10; if (z >= slab && z <= depth && z < zb[offsetPbuf]) { seed = ((seed << 16) + (seed << 1) + seed) & 0x7FFFFFFF; var bits = (seed >> 16) & 0x07; p.addPixel (offsetPbuf, z, bits == 0 ? adn : (bits == 1 ? aup : ac)); }++offsetPbuf; zScaled += zIncrementScaled; } } else { var rScaled = rgb16Left.r << 8; var rIncrement = Clazz.doubleToInt (((rgb16Right.r - rgb16Left.r) << 8) / count); var gScaled = rgb16Left.g; var gIncrement = Clazz.doubleToInt ((rgb16Right.g - gScaled) / count); var bScaled = rgb16Left.b; var bIncrement = Clazz.doubleToInt ((rgb16Right.b - bScaled) / count); while (--count >= 0) { var z = zScaled >> 10; if (z >= slab && z <= depth && z < zb[offsetPbuf]) p.addPixel (offsetPbuf, z, 0xFF000000 | (rScaled & 0xFF0000) | (gScaled & 0xFF00) | ((bScaled >> 8) & 0xFF)); ++offsetPbuf; zScaled += zIncrementScaled; rScaled += rIncrement; gScaled += gIncrement; bScaled += bIncrement; } }}, "~N,~N,~N,~N,~N,JU.Rgb16,JU.Rgb16"); Clazz.defineMethod (c$, "plotPixelsUnclippedRaster", function (count, x, y, zAtLeft, zPastRight, rgb16Left, rgb16Right) { if (count <= 0) return; var seed = ((x << 16) + (y << 1) ^ 0x33333333) & 0x7FFFFFFF; var zScaled = (zAtLeft << 10) + (512); var dz = zPastRight - zAtLeft; var roundFactor = Clazz.doubleToInt (count / 2); var zIncrementScaled = JU.GData.roundInt (Clazz.doubleToInt (((dz << 10) + (dz >= 0 ? roundFactor : -roundFactor)) / count)); var offsetPbuf = y * this.width + x; var zb = this.zbuf; var p = this.pixel; if (rgb16Left == null) { var adn = this.argbNoisyDn; var aup = this.argbNoisyUp; var ac = this.argbCurrent; while (--count >= 0) { var z = zScaled >> 10; if (z < zb[offsetPbuf]) { seed = ((seed << 16) + (seed << 1) + seed) & 0x7FFFFFFF; var bits = (seed >> 16) & 0x07; p.addPixel (offsetPbuf, z, bits == 0 ? adn : (bits == 1 ? aup : ac)); }++offsetPbuf; zScaled += zIncrementScaled; } } else { var rScaled = rgb16Left.r << 8; var rIncrement = JU.GData.roundInt (Clazz.doubleToInt (((rgb16Right.r - rgb16Left.r) << 8) / count)); var gScaled = rgb16Left.g; var gIncrement = JU.GData.roundInt (Clazz.doubleToInt ((rgb16Right.g - gScaled) / count)); var bScaled = rgb16Left.b; var bIncrement = JU.GData.roundInt (Clazz.doubleToInt ((rgb16Right.b - bScaled) / count)); while (--count >= 0) { var z = zScaled >> 10; if (z < zb[offsetPbuf]) p.addPixel (offsetPbuf, z, 0xFF000000 | (rScaled & 0xFF0000) | (gScaled & 0xFF00) | ((bScaled >> 8) & 0xFF)); ++offsetPbuf; zScaled += zIncrementScaled; rScaled += rIncrement; gScaled += gIncrement; bScaled += bIncrement; } }}, "~N,~N,~N,~N,~N,JU.Rgb16,JU.Rgb16"); Clazz.defineMethod (c$, "plotPixelsClippedRasterBits", function (count, x, y, zAtLeft, zPastRight, rgb16Left, rgb16Right, a, b) { var depth; var slab; if (count <= 0 || y < 0 || y >= this.height || x >= this.width || (zAtLeft < (slab = this.slab) && zPastRight < slab) || (zAtLeft > (depth = this.depth) && zPastRight > depth)) return; var zb = this.zbuf; var seed = (x << 16) + (y << 1) ^ 0x33333333; if (x < 0) { x = -x; count -= x; if (count <= 0) return; x = 0; }if (count + x > this.width) count = this.width - x; var offsetPbuf = y * this.width + x; var p = this.pixel; if (rgb16Left == null) { var adn = this.argbNoisyDn; var aup = this.argbNoisyUp; var ac = this.argbCurrent; while (--count >= 0) { var zCurrent = this.line3d.getZCurrent (a, b, x++); if (zCurrent >= slab && zCurrent <= depth && zCurrent < zb[offsetPbuf]) { seed = ((seed << 16) + (seed << 1) + seed) & 0x7FFFFFFF; var bits = (seed >> 16) & 0x07; p.addPixel (offsetPbuf, zCurrent, bits < 2 ? adn : bits < 6 ? aup : ac); }++offsetPbuf; } } else { var rScaled = rgb16Left.r << 8; var rIncrement = Clazz.doubleToInt (((rgb16Right.r - rgb16Left.r) << 8) / count); var gScaled = rgb16Left.g; var gIncrement = Clazz.doubleToInt ((rgb16Right.g - gScaled) / count); var bScaled = rgb16Left.b; var bIncrement = Clazz.doubleToInt ((rgb16Right.b - bScaled) / count); while (--count >= 0) { var zCurrent = this.line3d.getZCurrent (a, b, x++); if (zCurrent >= slab && zCurrent <= depth && zCurrent < zb[offsetPbuf]) p.addPixel (offsetPbuf, zCurrent, 0xFF000000 | (rScaled & 0xFF0000) | (gScaled & 0xFF00) | ((bScaled >> 8) & 0xFF)); ++offsetPbuf; rScaled += rIncrement; gScaled += gIncrement; bScaled += bIncrement; } }}, "~N,~N,~N,~N,~N,JU.Rgb16,JU.Rgb16,~N,~N"); Clazz.defineMethod (c$, "plotPixelsUnclippedRasterBits", function (count, x, y, rgb16Left, rgb16Right, a, b) { if (count <= 0) return; var seed = ((x << 16) + (y << 1) ^ 0x33333333) & 0x7FFFFFFF; var offsetPbuf = y * this.width + x; var zb = this.zbuf; var p = this.pixel; if (rgb16Left == null) { var adn = this.argbNoisyDn; var aup = this.argbNoisyUp; var ac = this.argbCurrent; while (--count >= 0) { var zCurrent = this.line3d.getZCurrent (a, b, x++); if (zCurrent < zb[offsetPbuf]) { seed = ((seed << 16) + (seed << 1) + seed) & 0x7FFFFFFF; var bits = (seed >> 16) & 0x07; var c = (bits == 0 ? adn : bits == 1 ? aup : ac); p.addPixel (offsetPbuf, zCurrent, c); }++offsetPbuf; } } else { var rScaled = rgb16Left.r << 8; var rIncrement = JU.GData.roundInt (Clazz.doubleToInt (((rgb16Right.r - rgb16Left.r) << 8) / count)); var gScaled = rgb16Left.g; var gIncrement = JU.GData.roundInt (Clazz.doubleToInt ((rgb16Right.g - gScaled) / count)); var bScaled = rgb16Left.b; var bIncrement = JU.GData.roundInt (Clazz.doubleToInt ((rgb16Right.b - bScaled) / count)); while (--count >= 0) { var zCurrent = this.line3d.getZCurrent (a, b, x++); if (zCurrent < zb[offsetPbuf]) p.addPixel (offsetPbuf, zCurrent, 0xFF000000 | (rScaled & 0xFF0000) | (gScaled & 0xFF00) | ((bScaled >> 8) & 0xFF)); ++offsetPbuf; rScaled += rIncrement; gScaled += gIncrement; bScaled += bIncrement; } }}, "~N,~N,~N,JU.Rgb16,JU.Rgb16,~N,~N"); Clazz.defineMethod (c$, "plotPixelsUnclippedCount", function (c, count, x, y, z, width, zbuf, p) { var offsetPbuf = y * width + x; while (--count >= 0) { if (z < zbuf[offsetPbuf]) p.addPixel (offsetPbuf, z, c); ++offsetPbuf; } }, "~N,~N,~N,~N,~N,~N,~A,J.g3d.Pixelator"); Clazz.defineMethod (c$, "plotPoints", function (count, coordinates, xOffset, yOffset) { var p = this.pixel; var c = this.argbCurrent; var zb = this.zbuf; var w = this.width; var antialias = this.antialiasThisFrame; for (var i = count * 3; i > 0; ) { var z = coordinates[--i]; var y = coordinates[--i] + yOffset; var x = coordinates[--i] + xOffset; if (this.isClipped3 (x, y, z)) continue; var offset = y * w + x++; if (z < zb[offset]) p.addPixel (offset, z, c); if (antialias) { offset = y * w + x; if (!this.isClipped3 (x, y, z) && z < zb[offset]) p.addPixel (offset, z, c); offset = (++y) * w + x; if (!this.isClipped3 (x, y, z) && z < zb[offset]) p.addPixel (offset, z, c); offset = y * w + (--x); if (!this.isClipped3 (x, y, z) && z < zb[offset]) p.addPixel (offset, z, c); }} }, "~N,~A,~N,~N"); Clazz.defineMethod (c$, "setColorNoisy", function (shadeIndex) { this.currentShadeIndex = shadeIndex; this.argbCurrent = this.shadesCurrent[shadeIndex]; this.argbNoisyUp = this.shadesCurrent[shadeIndex < 63 ? shadeIndex + 1 : 63]; this.argbNoisyDn = this.shadesCurrent[shadeIndex > 0 ? shadeIndex - 1 : 0]; }, "~N"); Clazz.defineMethod (c$, "getShadeIndexP3", function (screenA, screenB, screenC, isSolid) { this.vectorAB.sub2 (screenB, screenA); this.vectorAC.sub2 (screenC, screenA); var v = this.vectorNormal; v.cross (this.vectorAB, this.vectorAC); var i = (v.z < 0 ? this.shader.getShadeIndex (v.x, v.y, -v.z) : isSolid ? -1 : this.shader.getShadeIndex (-v.x, -v.y, v.z)); return i; }, "JU.P3,JU.P3,JU.P3,~B"); Clazz.overrideMethod (c$, "renderBackground", function (jmolRenderer) { if (this.backgroundImage != null) this.plotImage (-2147483648, 0, -2147483648, this.backgroundImage, jmolRenderer, 0, 0, 0); }, "J.api.JmolRendererInterface"); Clazz.overrideMethod (c$, "drawAtom", function (atom, radius) { this.fillSphereXYZ (atom.sD, atom.sX, atom.sY, atom.sZ); }, "JM.Atom,~N"); Clazz.overrideMethod (c$, "getExportType", function () { return 0; }); Clazz.overrideMethod (c$, "getExportName", function () { return null; }); Clazz.defineMethod (c$, "canDoTriangles", function () { return true; }); Clazz.defineMethod (c$, "isCartesianExport", function () { return false; }); Clazz.overrideMethod (c$, "initializeExporter", function (vwr, privateKey, g3d, params) { return null; }, "JV.Viewer,~N,JU.GData,java.util.Map"); Clazz.overrideMethod (c$, "finalizeOutput", function () { return null; }); Clazz.overrideMethod (c$, "drawBond", function (atomA, atomB, colixA, colixB, endcaps, mad, bondOrder) { }, "JU.P3,JU.P3,~N,~N,~N,~N,~N"); Clazz.overrideMethod (c$, "drawEllipse", function (ptAtom, ptX, ptY, fillArc, wireframeOnly) { return false; }, "JU.P3,JU.P3,JU.P3,~B,~B"); Clazz.defineMethod (c$, "getPrivateKey", function () { return 0; }); Clazz.overrideMethod (c$, "clearFontCache", function () { J.g3d.TextRenderer.clearFontCache (); }); Clazz.defineMethod (c$, "setRotationMatrix", function (rotationMatrix) { var vertexVectors = JU.Normix.getVertexVectors (); for (var i = JU.GData.normixCount; --i >= 0; ) { var tv = this.transformedVectors[i]; rotationMatrix.rotate2 (vertexVectors[i], tv); this.shadeIndexes[i] = this.shader.getShadeB (tv.x, -tv.y, tv.z); this.shadeIndexes2Sided[i] = (tv.z >= 0 ? this.shadeIndexes[i] : this.shader.getShadeB (-tv.x, tv.y, -tv.z)); } }, "JU.M3"); Clazz.overrideMethod (c$, "renderCrossHairs", function (minMax, screenWidth, screenHeight, navOffset, navDepth) { var antialiased = this.isAntialiased (); this.setC (navDepth < 0 ? 10 : navDepth > 100 ? 11 : 23); var x = Math.max (Math.min (this.width, Math.round (navOffset.x)), 0); var y = Math.max (Math.min (this.height, Math.round (navOffset.y)), 0); var z = Math.round (navOffset.z) + 1; var off = (antialiased ? 8 : 4); var h = (antialiased ? 20 : 10); var w = (antialiased ? 2 : 1); this.drawRect (x - off, y, z, 0, h, w); this.drawRect (x, y - off, z, 0, w, h); this.drawRect (x - off, y - off, z, 0, h, h); off = h; h = h >> 1; this.setC (minMax[1] < navOffset.x ? 21 : 11); this.drawRect (x - off, y, z, 0, h, w); this.setC (minMax[0] > navOffset.x ? 21 : 11); this.drawRect (x + h, y, z, 0, h, w); this.setC (minMax[3] < navOffset.y ? 21 : 11); this.drawRect (x, y - off, z, 0, w, h); this.setC (minMax[2] > navOffset.y ? 21 : 11); this.drawRect (x, y + h, z, 0, w, h); }, "~A,~N,~N,JU.P3,~N"); Clazz.overrideMethod (c$, "initializeOutput", function (vwr, privateKey, params) { return false; }, "JV.Viewer,~N,java.util.Map"); Clazz.defineStatics (c$, "sort", null, "nullShadeIndex", 50); });
/** * Index Component Spec Test */ 'use strict'; var React = require('react'); var IndexComponent = React.createFactory(require('../../../client/scripts/components/index<% if (useJsx) { %>.jsx<% } %>')); describe('Index Component', function() { var ReactTestUtils; var reactRender; beforeEach(function() { ReactTestUtils = require('react/addons').addons.TestUtils; reactRender = ReactTestUtils.renderIntoDocument; this.indexComponent = new IndexComponent(); }); it('provides the "Index Component" instance', function() { // Expect it to exist expect(this.indexComponent)<% if (testFramework === 'jasmine') { %>.toBeDefined()<% } else if (testFramework === 'mocha') { %>.to.be.ok<% } %>; }); });
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-example-query-scan.html. Purpose: ddb_scan.js demonstrates how to return items and attributes from an Amazon DynamoDB table. Running the code: node ddb_scan.js */ // snippet-start:[dynamodb.JavaScript.table.scanV3] // Import required AWS SDK clients and commands for Node.js import { ScanCommand } from "@aws-sdk/client-dynamodb"; import { ddbClient } from "./libs/ddbClient.js"; // Set the parameters. export const params = { // Specify which items in the results are returned. FilterExpression: "Subtitle = :topic AND Season = :s AND Episode = :e", // Define the expression attribute value, which are substitutes for the values you want to compare. ExpressionAttributeValues: { ":topic": { S: "SubTitle2" }, ":s": { N: "1" }, ":e": { N: "2" }, }, // Set the projection expression, which the the attributes that you want. ProjectionExpression: "Season, Episode, Title, Subtitle", TableName: "EPISODES_TABLE", }; export const run = async () => { try { const data = await ddbClient.send(new ScanCommand(params)); return data; data.Items.forEach(function (element, index, array) { console.log(element.Title.S + " (" + element.Subtitle.S + ")"); }); } catch (err) { console.log("Error", err); } } run(); // snippet-end:[dynamodb.JavaScript.table.scanV3] // For unit tests only. // module.exports ={run, params};
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ 'use strict'; const path = require('path'); const rimraf = require('rimraf'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ReactServerWebpackPlugin = require('react-server-dom-webpack/plugin'); const isProduction = process.env.NODE_ENV === 'production'; rimraf.sync(path.resolve(__dirname, '../build')); webpack( { mode: isProduction ? 'production' : 'development', devtool: isProduction ? 'source-map' : 'cheap-module-source-map', entry: [path.resolve(__dirname, '../src/index.client.js')], output: { path: path.resolve(__dirname, '../build'), filename: 'main.js', }, module: { rules: [ { test: /\.js$/, use: 'babel-loader', exclude: /node_modules/, }, ], }, plugins: [ new HtmlWebpackPlugin({ inject: true, template: path.resolve(__dirname, '../public/index.html'), }), new ReactServerWebpackPlugin({isServer: false}), ], }, (err, stats) => { if (err) { console.error(err.stack || err); if (err.details) { console.error(err.details); } process.exit(1); return; } const info = stats.toJson(); if (stats.hasErrors()) { console.log('Finished running webpack with errors.'); info.errors.forEach((e) => console.error(e)); process.exit(1); } else { console.log('Finished running webpack.'); } } );
'use strict'; // MODULES // var betaincinv = require( 'compute-betaincinv/lib/ibeta_inv_imp.js' ); // QUANTILE // /** * FUNCTION: quantile( p, alpha, beta ) * Evaluates the quantile function for a Beta distribution with first shape parameter `alpha` and second shape parameter `beta` at a probability `p`. * * @param {Number} p - input value * @param {Number} alpha - first shape parameter * @param {Number} beta - second shape parameter * @returns {Number} evaluated quantile function */ function quantile( p, alpha, beta ) { if ( p !== p || p < 0 || p > 1 ) { return NaN; } return betaincinv( alpha, beta, p, 1 - p )[ 0 ]; } // end FUNCTION quantile() // EXPORTS // module.exports = quantile;
var crypto = require("crypto"); var transParams = (data) => { let params = new URLSearchParams(); for (let item in data) { params.append(item, data["" + item + ""]); } return params; }; //data 是准备加密的字符串,key是你的密钥 function encryption(data, key) { var iv = ""; var cipherEncoding = "base64"; var cipher = crypto.createCipheriv("aes-128-ecb", key, iv); cipher.setAutoPadding(true); return Buffer.concat([cipher.update(data), cipher.final()]).toString( cipherEncoding ); } //data 是你的准备解密的字符串,key是你的密钥 function decryption(data, key) { var iv = ""; var clearEncoding = "utf8"; var cipherEncoding = "base64"; var decipher = crypto.createDecipheriv("aes-128-ecb", key, iv); decipher.setAutoPadding(true); return Buffer.concat([ decipher.update(data, cipherEncoding), decipher.final(), ]).toString(clearEncoding); } function a(str) { str = str + str; return str.substr(8, 16); } var taskcallback = { // 查询活动状态 query: async (axios, options) => { let { params } = options; const useragent = `ChinaUnicom4.x/1.0 CFNetwork/1209 Darwin/20.2.0`; let { data, config } = await axios.request({ baseURL: "https://m.client.10010.com/", headers: { "user-agent": useragent, referer: `https://m.client.10010.com`, origin: "https://m.client.10010.com", }, url: `/taskcallback/taskfilter/query`, method: "POST", data: transParams(params), }); if (data.code === "0000") { console.log( data.timeflag === "1" ? `今日参加活动已达上限(${data.achieve}/${data.allocation}次)` : `活动可参加(${data.achieve}/${data.allocation}次)` ); return { num: parseInt(data.allocation) - parseInt(data.achieve), jar: config.jar, }; } else { console.log("查询出错", data.desc); return false; } }, reward: async (axios, options) => { let { params, jar } = options; let cookiesJson = jar.toJSON(); let ecs_token = cookiesJson.cookies.find((i) => i.key == "ecs_token"); if (!ecs_token) { throw new Error("ecs_token缺失"); } ecs_token = ecs_token.value; let orderId = params.orderId || crypto .createHash("md5") .update(new Date().getTime() + "") .digest("hex"); let codeId = parseInt(params.codeId || 945535616); let app_id = "5049584"; let media_extra = [ ecs_token, options.user, "android", params.arguments1, params.arguments2, orderId, // orderId codeId, //codeId params.remark, "Wifi", ]; var data = { oversea_version_type: 0, reward_name: `android-${params.remark1 || params.remark}-激励视频`, reward_amount: 1, network: 4, // "latitude": 26.611770629882812, // "longitude": 106.63581085205078, sdk_version: "3.3.0.3", user_agent: "Mozilla/5.0 (Linux; Android 9; VKY-AL00 Build/HUAWEIVKY-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/86.0.4240.198 Mobile Safari/537.36", extra: { // "ad_slot_type": 7, // "oaid": "ebdde3b9-def7-6cc3-fdfe-9bfff7ce4126", // "language": "golang", // "ug_creative_id": "", // "ad_id": 1687489184287789, // "creative_id": 1687493310795863, // "convert_id": 1682419505842179, // "uid": 95981094553, // "ad_type": 1, // "pricing": 9, // "ut": 12, // "version_code": "8.1", // "device_id": 50137151117, // "width": 360, // "height": 640, // "mac": "10:44:00:73:74:BF", // "uuid": "867442035025655", // "uuid_md5": "8a4dac2481580bd94f8c4b17787b74cd", // "os": "android", // "client_ip": "111.121.67.62", // "open_udid": "", // "os_type": null, // "app_name": "手机营业厅", // "device_type": "VKY-AL00", // "os_version": "9", // "app_id": "5049584", // "template_id": 0, // "template_rate": 0, // "promotion_type": 0, // "img_gen_type": 0, // "img_md5": "", // "source_type": 1, // "pack_time": "{pack_time}", // "cid": 1687493310795863, // "interaction_type": 4, // "src_type": "app", // "package_name": "com.sinovatech.unicom.ui", // "pos": 5, // "landing_type": 3, // "is_sdk": true, // "is_dsp_ad": false, // "imei": "867442035025655", // "req_id": "e9da96b1-2d0c-49d0-b5b0-3fd6540d22d4u2997", rit: codeId, }, media_extra: encodeURI(media_extra.join("|")), video_duration: 28.143, play_start_ts: new Date().getTime() - 32 * 1000, play_end_ts: 0, duration: 28143, user_id: app_id, trans_id: crypto .createHash("md5") .update(new Date().getTime() + "") .digest("hex"), }; let key = crypto .createHash("md5") .update(new Date().getTime() + "") .digest("hex") .substr(8, 16); let t = JSON.stringify(data).replace(/\//g, "\\/"); //.replace('"{pack_time}"', '1.609770734935479E9') let m = encryption(t, a(key)).replace(/(.{76})/g, "$1\n"); m = "2" + key + m; var message = { message: m, cypher: 2, }; // let s = a(message.message.substr(1, 16)) // console.log(decryption(message.message.replace(/\n/g, '').substr(17), s)) // process.exit(0) const useragent = `VADNetAgent/0`; let res = await axios.request({ headers: { "user-agent": useragent, "Content-Type": "application/json; charset=utf-8", }, url: `https://api-access.pangolin-sdk-toutiao.com/api/ad/union/sdk/reward_video/reward/`, method: "POST", data: message, }); data = res.data; // console.log(data); // s = a(data.message.substr(1, 16)); // console.log(decryption(data.message.replace(/\n/g, "").substr(17), s)); if ("code" in data) { console.log(data); throw new Error("获取激励信息出错"); } return { orderId, }; }, // 提交任务 doTask: async (axios, options) => { let result = await taskcallback.reward(axios, options); let params = options.params; params["orderId"] = result["orderId"]; delete params.codeId; const useragent = `okhttp/4.4.0`; // const useragent = ` ChinaUnicom4.x/1.0 CFNetwork/1209 Darwin/20.2.0`; let { data } = await axios.request({ baseURL: "https://m.client.10010.com/", headers: { "user-agent": useragent, referer: `https://m.client.10010.com/`, origin: "https://m.client.10010.com", }, url: `/taskcallback/taskfilter/dotasks`, method: "POST", data: transParams(params), }); if (data.code === "0000") { console.log("提交任务成功", data.prizeName + "+" + data.prizeCount); } else { console.log("提交任务出错", data.desc); } }, }; module.exports = taskcallback;
// Required: Initialize bugsplat with database name, app name, and version const BugSplat = require("bugsplat-node"); const bugsplat = new BugSplat("fred", "my-node-crasher", "1.0.0.0"); bugsplat.setDefaultAppKey("AppKey"); bugsplat.setDefaultUser("Fred"); bugsplat.setDefaultEmail("fred@bedrock.com"); bugsplat.setDefaultDescription("description"); // Create a native report from an error const error = new Error("BugSplat rocks!"); process.report.writeReport("report.json", error); // Send the error to BugSplat and attach the native report bugsplat.post(error, { additionalFilePaths: ["./report.json"]}) .then(result => console.log(result));
const User = require('./user') const Products = require('./products') const Type = require('./type') const Bussines = require('./bussines') /** * If we had any associations to make, this would be a great place to put them! * ex. if we had another model called BlogPost, we might say: * * BlogPost.belongsTo(User) */ /** * We'll export all of our models here, so that any time a module needs a model, * we can just require it from 'db/models' * for example, we can say: const {User} = require('../db/models') * instead of: const User = require('../db/models/user') */ Products.belongsTo(Type) Type.hasMany(Products) Type.belongsTo(Bussines) Bussines.hasMany(Type) module.exports = { User, Products, Type, Bussines }
import express from 'express'; import agentRoutes from './agent/agent.route'; import authRoutes from './auth/auth.route'; import pusherRoutes from './pusher/pusher.route'; import organizationRoutes from './organization/organization.route'; import taskRoutes from './task/task.route'; import teamRoutes from './team/team.route'; import userRoutes from './user/user.route'; const router = express.Router(); // eslint-disable-line new-cap /** GET /health-check - Check service health */ router.get('/health-check', (req, res) => res.send('OK') ); // mount agents routes at /agents router.use('/agents', agentRoutes); // mount auth routes at /auth router.use('/auth', authRoutes); // mount organizations routes at /organizations router.use('/organizations', organizationRoutes); // mount pusher routes at /pusher router.use('/pusher', pusherRoutes); // mount tasks routes at /tasks router.use('/tasks', taskRoutes); // mount teams routes at /teams router.use('/teams', teamRoutes); // mount user routes at /users router.use('/users', userRoutes); export default router;
module.exports = { len: function (obj) { return obj.length; }, when: function (operand_1, operator, operand_2, options) { switch (operator) { case 'eq': case '=': case '==': case '===': return operand_1 == operand_2; case 'neq': case 'noteq': case '!=': case '!==': return operand_1 != operand_2; case 'gt': case '>': return operand_1 > operand_2; case 'gtoreq': case '>=': return operand_1 >= operand_2; case 'lt': case '<': return operand_1 < operand_2; case 'ltoreq': case '<=': return operand_1 <= operand_2; case 'or': case '||': return operand_1 || operand_2; case 'and': case '&&': return operand_1 && operand_2; case 'mod': case '%': return operand_1 % operand_2 === 0; default: return options.inverse(this); } }, yaml: function (obj) { var YAML = require('yaml'); return YAML.stringify(obj); }, json: function (obj) { return JSON.stringify(obj, null, 2); }, xml: function (obj) { var Parser = require('fast-xml-parser').j2xParser; var parser = new Parser(); return parser.parse(obj); }, };
const given = require('../../steps/given') const when = require('../../steps/when') const then = require('../../steps/then') describe('When a user signs up', () => { it("The user's profile should be saved in DynamoDB", async () => { const { password, name, email } = given.a_random_user() const user = await when.a_user_signs_up(password, name, email) const ddbUser = await then.user_exists_in_UsersTable(user.username) expect(ddbUser).toMatchObject({ id: user.username, name, createdAt: expect.stringMatching( /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?Z?/g, ), followersCount: 0, followingCount: 0, tweetsCount: 0, likesCount: 0, }) const [firstName, lastName] = name.split(' ') expect(ddbUser.screenName).toContain(firstName) expect(ddbUser.screenName).toContain(lastName) }) })
webpackJsonp([69,73],{202:function(t,s,i){var n=i(1)(null,i(320),null,null);t.exports=n.exports},320:function(t,s){t.exports={render:function(){var t=this,s=t.$createElement,i=t._self._c||s;return i("div",{staticClass:"container"},[i("topComponent",{attrs:{title:"如何注册账号"}}),t._v(" "),i("div",{staticClass:"reportRegStep"},[t._m(0),t._v(" "),i("i",{staticClass:"icon01"},[t._v("注册步骤示例图1")]),t._v(" "),i("p",[t._v('第二步:点击"新用户注册"')]),t._v(" "),i("i",{staticClass:"icon02"},[t._v("注册步骤示例图2")]),t._v(" "),i("p",[t._v('第三步:填写身份信息、验证码,阅读服务协议,点击"下一步"')]),t._v(" "),i("i",{staticClass:"icon03"},[t._v("注册步骤示例图3")]),t._v(" "),i("p",[t._v('第四步:填写用户基本信息,然后点击"提交"')]),t._v(" "),i("i",{staticClass:"icon04"},[t._v("注册步骤示例图4")]),t._v(" "),i("p",[t._v("第五步:注册完成,页面提示用户注册成功")]),t._v(" "),i("i",{staticClass:"icon05"},[t._v("注册步骤示例图5")]),t._v(" "),i("p",[t._v("注册完成之后,即可使用登录名及密码在"+t._s(t.appName)+"APP内登录")])])],1)},staticRenderFns:[function(){var t=this,s=t.$createElement,i=t._self._c||s;return i("p",[t._v("第一步:用电脑打开网址:"),i("br"),i("span",{staticClass:"blue"},[t._v("https://ipcrs.pbccrc.org.cn/")]),t._v('点击“马上开始"')])}]}}});
// @flow import * as React from 'react'; import { withRouter } from 'react-router'; import styles from './style.scss'; const BackTabbar = props => ( <div className={styles.tabbar}> <button onClick={() => { props.history.goBack(); }} className={`${styles.navLink}`} > Back </button> </div> ); // Export with Router, so we can access the history export default withRouter(BackTabbar);
/*! * jQuery JavaScript Library v1.4.2 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Sat Feb 13 22:33:48 2010 -0500 */ (function( window, undefined ) { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/, // Is it a simple selector isSimple = /^.[^:#\[\.,]*$/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // Has the ready events already been bound? readyBound = false, // The functions to execute on DOM ready readyList = [], // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, indexOf = Array.prototype.indexOf; jQuery.fn = jQuery.prototype = { init: function( selector, context ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context ) { this.context = document; this[0] = document.body; this.selector = "body"; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? match = quickExpr.exec( selector ); // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); if ( elem ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $("TAG") } else if ( !context && /^\w+$/.test( selector ) ) { this.selector = selector; this.context = document; selector = document.getElementsByTagName( selector ); return jQuery.merge( this, selector ); // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return (context || rootjQuery).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return jQuery( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.4.2", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + (this.selector ? " " : "") + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // If the DOM is already ready if ( jQuery.isReady ) { // Execute the function immediately fn.call( document, jQuery ); // Otherwise, remember the function for later } else if ( readyList ) { // Add the function to the wait list readyList.push( fn ); } return this; }, eq: function( i ) { return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || jQuery(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { // copy reference to target object var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging object literal values or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) { var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src : jQuery.isArray(copy) ? [] : {}; // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { window.$ = _$; if ( deep ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // Handle when the DOM is ready ready: function() { // Make sure that the DOM is not already loaded if ( !jQuery.isReady ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 13 ); } // Remember that the DOM is ready jQuery.isReady = true; // If there are functions bound, to execute if ( readyList ) { // Execute all of them var fn, i = 0; while ( (fn = readyList[ i++ ]) ) { fn.call( document, jQuery ); } // Reset the list of functions readyList = null; } // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); } } }, bindReady: function() { if ( readyBound ) { return; } readyBound = true; // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { return jQuery.ready(); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent("onreadystatechange", DOMContentLoaded); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return toString.call(obj) === "[object Function]"; }, isArray: function( obj ) { return toString.call(obj) === "[object Array]"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwnProperty.call(obj, "constructor") && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwnProperty.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@") .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]") .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); } }, noop: function() {}, // Evalulates a script in a global context globalEval: function( data ) { if ( data && rnotwhite.test(data) ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; if ( jQuery.support.scriptEval ) { script.appendChild( document.createTextNode( data ) ); } else { script.text = data; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction(object); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} } } return object; }, trim: function( text ) { return (text || "").replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = []; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { if ( !inv !== !callback( elems[ i ], i ) ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var ret = [], value; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, length = elems.length; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, proxy: function( fn, proxy, thisObject ) { if ( arguments.length === 2 ) { if ( typeof proxy === "string" ) { thisObject = fn; fn = thisObject[ proxy ]; proxy = undefined; } else if ( proxy && !jQuery.isFunction( proxy ) ) { thisObject = proxy; proxy = undefined; } } if ( !proxy && fn ) { proxy = function() { return fn.apply( thisObject || this, arguments ); }; } // Set the guid of unique handler to the same of original handler, so it can be removed if ( fn ) { proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; } // So proxy can be declared as an argument return proxy; }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, browser: {} }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } if ( indexOf ) { jQuery.inArray = function( elem, array ) { return indexOf.call( array, elem ); }; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch( error ) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its a function function access( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; } function now() { return (new Date).getTime(); } (function() { jQuery.support = {}; var root = document.documentElement, script = document.createElement("script"), div = document.createElement("div"), id = "script" + now(); div.style.display = "none"; div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var all = div.getElementsByTagName("*"), a = div.getElementsByTagName("a")[0]; // Can't get basic test support if ( !all || !all.length || !a ) { return; } jQuery.support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText insted) style: /red/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55$/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: div.getElementsByTagName("input")[0].value === "on", // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: document.createElement("select").appendChild( document.createElement("option") ).selected, parentNode: div.removeChild( div.appendChild( document.createElement("div") ) ).parentNode === null, // Will be defined later deleteExpando: true, checkClone: false, scriptEval: false, noCloneEvent: true, boxModel: null }; script.type = "text/javascript"; try { script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); } catch(e) {} root.insertBefore( script, root.firstChild ); // Make sure that the execution of code works by injecting a script // tag with appendChild/createTextNode // (IE doesn't support this, fails, and uses .text instead) if ( window[ id ] ) { jQuery.support.scriptEval = true; delete window[ id ]; } // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete script.test; } catch(e) { jQuery.support.deleteExpando = false; } root.removeChild( script ); if ( div.attachEvent && div.fireEvent ) { div.attachEvent("onclick", function click() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) jQuery.support.noCloneEvent = false; div.detachEvent("onclick", click); }); div.cloneNode(true).fireEvent("onclick"); } div = document.createElement("div"); div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; var fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // Figure out if the W3C box model works as expected // document.body must exist before we can do this jQuery(function() { var div = document.createElement("div"); div.style.width = div.style.paddingLeft = "1px"; document.body.appendChild( div ); jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; document.body.removeChild( div ).style.display = 'none'; div = null; }); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ var eventSupported = function( eventName ) { var el = document.createElement("div"); eventName = "on" + eventName; var isSupported = (eventName in el); if ( !isSupported ) { el.setAttribute(eventName, "return;"); isSupported = typeof el[eventName] === "function"; } el = null; return isSupported; }; jQuery.support.submitBubbles = eventSupported("submit"); jQuery.support.changeBubbles = eventSupported("change"); // release memory in IE root = script = div = all = a = null; })(); jQuery.props = { "for": "htmlFor", "class": "className", readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", colspan: "colSpan", tabindex: "tabIndex", usemap: "useMap", frameborder: "frameBorder" }; var expando = "jQuery" + now(), uuid = 0, windowData = {}; jQuery.extend({ cache: {}, expando:expando, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, "object": true, "applet": true }, data: function( elem, name, data ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { return; } elem = elem == window ? windowData : elem; var id = elem[ expando ], cache = jQuery.cache, thisCache; if ( !id && typeof name === "string" && data === undefined ) { return null; } // Compute a unique ID for the element if ( !id ) { id = ++uuid; } // Avoid generating a new cache unless none exists and we // want to manipulate it. if ( typeof name === "object" ) { elem[ expando ] = id; thisCache = cache[ id ] = jQuery.extend(true, {}, name); } else if ( !cache[ id ] ) { elem[ expando ] = id; cache[ id ] = {}; } thisCache = cache[ id ]; // Prevent overriding the named cache with undefined values if ( data !== undefined ) { thisCache[ name ] = data; } return typeof name === "string" ? thisCache[ name ] : thisCache; }, removeData: function( elem, name ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { return; } elem = elem == window ? windowData : elem; var id = elem[ expando ], cache = jQuery.cache, thisCache = cache[ id ]; // If we want to remove a specific section of the element's data if ( name ) { if ( thisCache ) { // Remove the section of cache data delete thisCache[ name ]; // If we've removed all the data, remove the element's cache if ( jQuery.isEmptyObject(thisCache) ) { jQuery.removeData( elem ); } } // Otherwise, we want to remove all of the element's data } else { if ( jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } // Completely remove the data cache delete cache[ id ]; } } }); jQuery.fn.extend({ data: function( key, value ) { if ( typeof key === "undefined" && this.length ) { return jQuery.data( this[0] ); } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function() { jQuery.data( this, key, value ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { if ( !elem ) { return; } type = (type || "fx") + "queue"; var q = jQuery.data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( !data ) { return q || []; } if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } return q; }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(); // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function( i, elem ) { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue( type, function() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); } }); var rclass = /[\n\t]/g, rspace = /\s+/, rreturn = /\r/g, rspecialurl = /href|src|style/, rtype = /(button|input)/i, rfocusable = /(button|input|object|select|textarea)/i, rclickable = /^(a|area)$/i, rradiocheck = /radio|checkbox/; jQuery.fn.extend({ attr: function( name, value ) { return access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name, fn ) { return this.each(function(){ jQuery.attr( this, name, "" ); if ( this.nodeType === 1 ) { this.removeAttribute( name ); } }); }, addClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class")) ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspace ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " ", setClass = elem.className; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { setClass += " " + classNames[c]; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split(rspace); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[c] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery(this), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery.data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { if ( value === undefined ) { var elem = this[0]; if ( elem ) { if ( jQuery.nodeName( elem, "option" ) ) { return (elem.attributes.value || {}).specified ? elem.value : elem.text; } // We need to handle select boxes special if ( jQuery.nodeName( elem, "select" ) ) { var index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; if ( option.selected ) { // Get the specifc value for the option value = jQuery(option).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; } // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { return elem.getAttribute("value") === null ? "on" : elem.value; } // Everything else, we just grab the value return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction(value); return this.each(function(i) { var self = jQuery(this), val = value; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call(this, i, self.val()); } // Typecast each time if the value is a Function and the appended // value is therefore different each time. if ( typeof val === "number" ) { val += ""; } if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { this.checked = jQuery.inArray( self.val(), val ) >= 0; } else if ( jQuery.nodeName( this, "select" ) ) { var values = jQuery.makeArray(val); jQuery( "option", this ).each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { this.selectedIndex = -1; } } else { this.value = val; } }); } }); jQuery.extend({ attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { // don't set attributes on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery(elem)[name](value); } var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), // Whether we are setting (or getting) set = value !== undefined; // Try to normalize/fix the name name = notxml && jQuery.props[ name ] || name; // Only do all the following if this is a node (faster for style) if ( elem.nodeType === 1 ) { // These attributes require special treatment var special = rspecialurl.test( name ); // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( name === "selected" && !jQuery.support.optSelected ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } // If applicable, access the attribute via the DOM 0 way if ( name in elem && notxml && !special ) { if ( set ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } elem[ name ] = value; } // browsers index elements by id/name on forms, give priority to attributes. if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { return elem.getAttributeNode( name ).nodeValue; } // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ if ( name === "tabIndex" ) { var attributeNode = elem.getAttributeNode( "tabIndex" ); return attributeNode && attributeNode.specified ? attributeNode.value : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } return elem[ name ]; } if ( !jQuery.support.style && notxml && name === "style" ) { if ( set ) { elem.style.cssText = "" + value; } return elem.style.cssText; } if ( set ) { // convert the value to a string (all browsers do this but IE) see #1070 elem.setAttribute( name, "" + value ); } var attr = !jQuery.support.hrefNormalized && notxml && special ? // Some attributes require a special call on IE elem.getAttribute( name, 2 ) : elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return attr === null ? undefined : attr; } // elem is actually elem.style ... set the style // Using attr for specific style information is now deprecated. Use style instead. return jQuery.style( elem, name, value ); } }); var rnamespaces = /\.(.*)$/, fcleanup = function( nm ) { return nm.replace(/[^\w\s\.\|`]/g, function( ch ) { return "\\" + ch; }); }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( elem.setInterval && ( elem !== window && !elem.frameElement ) ) { elem = window; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery.data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } var events = elemData.events = elemData.events || {}, eventHandle = elemData.handle, eventHandle; if ( !eventHandle ) { elemData.handle = eventHandle = function() { // Handle the second event of a trigger and when // an event is called after a page has unloaded return typeof jQuery !== "undefined" && !jQuery.event.triggered ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; handleObj.guid = handler.guid; // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // Only use addEventListener/attachEvent if the special // events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have been used, for global triggering jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } var ret, type, fn, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, elemData = jQuery.data( elem ), events = elemData && elemData.events; if ( !elemData || !events ) { return; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)") } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( var j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( var j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem ); } } }, // bubbling is internal trigger: function( event, data, elem /*, bubbling */ ) { // Event object or event type var type = event.type || event, bubbling = arguments[3]; if ( !bubbling ) { event = typeof event === "object" ? // jQuery.Event object event[expando] ? event : // Object literal jQuery.extend( jQuery.Event(type), event ) : // Just the event type (string) jQuery.Event(type); if ( type.indexOf("!") >= 0 ) { event.type = type = type.slice(0, -1); event.exclusive = true; } // Handle a global trigger if ( !elem ) { // Don't bubble custom events when global (to avoid too much overhead) event.stopPropagation(); // Only trigger if we've ever bound an event for it if ( jQuery.event.global[ type ] ) { jQuery.each( jQuery.cache, function() { if ( this.events && this.events[type] ) { jQuery.event.trigger( event, data, this.handle.elem ); } }); } } // Handle triggering a single element // don't do events on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // Clean up in case it is reused event.result = undefined; event.target = elem; // Clone the incoming data, if any data = jQuery.makeArray( data ); data.unshift( event ); } event.currentTarget = elem; // Trigger the event, it is assumed that "handle" is a function var handle = jQuery.data( elem, "handle" ); if ( handle ) { handle.apply( elem, data ); } var parent = elem.parentNode || elem.ownerDocument; // Trigger an inline bound script try { if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { event.result = false; } } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (e) {} if ( !event.isPropagationStopped() && parent ) { jQuery.event.trigger( event, data, parent, true ); } else if ( !event.isDefaultPrevented() ) { var target = event.target, old, isClick = jQuery.nodeName(target, "a") && type === "click", special = jQuery.event.special[ type ] || {}; if ( (!special._default || special._default.call( elem, event ) === false) && !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { try { if ( target[ type ] ) { // Make sure that we don't accidentally re-trigger the onFOO events old = target[ "on" + type ]; if ( old ) { target[ "on" + type ] = null; } jQuery.event.triggered = true; target[ type ](); } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (e) {} if ( old ) { target[ "on" + type ] = old; } jQuery.event.triggered = false; } } }, handle: function( event ) { var all, handlers, namespaces, namespace, events; event = arguments[0] = jQuery.event.fix( event || window.event ); event.currentTarget = this; // Namespaced event handlers all = event.type.indexOf(".") < 0 && !event.exclusive; if ( !all ) { namespaces = event.type.split("."); event.type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)"); } var events = jQuery.data(this, "events"), handlers = events[ event.type ]; if ( events && handlers ) { // Clone the handlers to prevent manipulation handlers = handlers.slice(0); for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Filter the functions by class if ( all || namespace.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, arguments ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } } return event.result; }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function( event ) { if ( event[ expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add which for key events if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) { event.which = event.charCode || event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, handleObj.origType, jQuery.extend({}, handleObj, {handler: liveHandler}) ); }, remove: function( handleObj ) { var remove = true, type = handleObj.origType.replace(rnamespaces, ""); jQuery.each( jQuery.data(this, "events").live || [], function() { if ( type === this.origType.replace(rnamespaces, "") ) { remove = false; return false; } }); if ( remove ) { jQuery.event.remove( this, handleObj.origType, liveHandler ); } } }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( this.setInterval ) { this.onbeforeunload = eventHandle; } return false; }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } } }; var removeEvent = document.removeEventListener ? function( elem, type, handle ) { elem.removeEventListener( type, handle, false ); } : function( elem, type, handle ) { elem.detachEvent( "on" + type, handle ); }; jQuery.Event = function( src ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Event type } else { this.type = src; } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = now(); // Mark it as fixed this[ expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); } // otherwise set the returnValue property of the original event to false (IE) e.returnValue = false; }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { // Traverse up the tree while ( parent && parent !== this ) { parent = parent.parentNode; } if ( parent !== this ) { // set the correct event type event.type = event.data; // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } // assuming we've left the element since we most likely mousedover a xul element } catch(e) { } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( this.nodeName.toLowerCase() !== "form" ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { return trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { return trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var formElems = /textarea|input|select/i, changeFilters, getVal = function( elem ) { var type = elem.type, val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( elem.nodeName.toLowerCase() === "select" ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !formElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery.data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery.data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; return jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, click: function( e ) { var elem = e.target, type = elem.type; if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { return testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = elem.type; if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { return testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information/focus[in] is not needed anymore beforeactivate: function( e ) { var elem = e.target; jQuery.data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return formElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return formElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; } function trigger( type, elem, args ) { args[0].type = type; return jQuery.event.handle.apply( elem, args ); } // Create "bubbling" focus and blur events if ( document.addEventListener ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { jQuery.event.special[ fix ] = { setup: function() { this.addEventListener( orig, handler, true ); }, teardown: function() { this.removeEventListener( orig, handler, true ); } }; function handler( e ) { e = jQuery.event.fix( e ); e.type = fix; return jQuery.event.handle.call( this, e ); } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } var handler = name === "one" ? jQuery.proxy( fn, function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }) : fn; if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { var event = jQuery.Event( type ); event.preventDefault(); event.stopPropagation(); jQuery.event.trigger( event, data, this[0] ); return event.result; } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, i = 1; // link all the functions, so any of them can unbind this click handler while ( i < args.length ) { jQuery.proxy( fn, args[ i++ ] ); } return this.click( jQuery.proxy( fn, function( event ) { // Figure out which function to execute var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; })); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( type === "focus" || type === "blur" ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler context.each(function(){ jQuery.event.add( this, liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); }); } else { // unbind live handler context.unbind( liveConvert( type, selector ), fn ); } } return this; } }); function liveHandler( event ) { var stop, elems = [], selectors = [], args = arguments, related, match, handleObj, elem, j, i, l, data, events = jQuery.data( this, "events" ); // Make sure we avoid non-left-click bubbling in Firefox (#3861) if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) { return; } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( match[i].selector === handleObj.selector ) { elem = match[i].elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; if ( match.handleObj.origHandler.apply( match.elem, args ) === false ) { stop = false; break; } } return stop; } function liveConvert( type, selector ) { return "live." + (type && type !== "*" ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&"); } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( fn ) { return fn ? this.bind( name, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); // Prevent memory leaks in IE // Window isn't included so as not to unbind existing unload events // More info: // - http://isaacschlueter.com/2006/10/msie-memory-leaks/ if ( window.attachEvent && !window.addEventListener ) { window.attachEvent("onunload", function() { for ( var id in jQuery.cache ) { if ( jQuery.cache[ id ].handle ) { // Try/Catch is to handle iframes being unloaded, see #4280 try { jQuery.event.remove( jQuery.cache[ id ].handle.elem ); } catch(e) {} } } }); } /*! * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function(){ baseHasDuplicate = false; return 0; }); var Sizzle = function(selector, context, results, seed) { results = results || []; var origContext = context = context || document; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, extra, prune = true, contextXML = isXML(context), soFar = selector; // Reset the position of the chunker regexp (start from head) while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { var ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { var ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray(set); } else { prune = false; } while ( parts.length ) { var cur = parts.pop(), pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function(results){ if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort(sortOrder); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[i-1] ) { results.splice(i--, 1); } } } } return results; }; Sizzle.matches = function(expr, set){ return Sizzle(expr, null, null, set); }; Sizzle.find = function(expr, context, isXML){ var set, match; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice(1,1); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; Sizzle.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound, isXMLFilter = set && set[0] && isXML(set[0]); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var filter = Expr.filter[ type ], found, item, left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function(elem){ return elem.getAttribute("href"); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.test(part), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function(checkSet, part){ var isPartStr = typeof part === "string"; if ( isPartStr && !/\W/.test(part) ) { part = part.toLowerCase(); for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = part.toLowerCase(); checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); }, "~": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = part.toLowerCase(); checkFn = dirNodeCheck; } checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); } }, find: { ID: function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? [m] : []; } }, NAME: function(match, context){ if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName(match[1]); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function(match, context){ return context.getElementsByTagName(match[1]); } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not, isXML){ match = " " + match[1].replace(/\\/g, "") + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ return match[1].toLowerCase(); }, CHILD: function(match){ if ( match[1] === "nth" ) { // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function(match, curLoop, inplace, result, not, isXML){ var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function(match, curLoop, inplace, result, not){ if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function(match){ match.unshift( true ); return match; } }, filters: { enabled: function(elem){ return elem.disabled === false && elem.type !== "hidden"; }, disabled: function(elem){ return elem.disabled === true; }, checked: function(elem){ return elem.checked === true; }, selected: function(elem){ // Accessing this property makes selected-by-default // options in Safari work properly elem.parentNode.selectedIndex; return elem.selected === true; }, parent: function(elem){ return !!elem.firstChild; }, empty: function(elem){ return !elem.firstChild; }, has: function(elem, i, match){ return !!Sizzle( match[3], elem ).length; }, header: function(elem){ return /h\d/i.test( elem.nodeName ); }, text: function(elem){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function(elem){ return /input|select|textarea|button/i.test(elem.nodeName); } }, setFilters: { first: function(elem, i){ return i === 0; }, last: function(elem, i, match, array){ return i === array.length - 1; }, even: function(elem, i){ return i % 2 === 0; }, odd: function(elem, i){ return i % 2 === 1; }, lt: function(elem, i, match){ return i < match[3] - 0; }, gt: function(elem, i, match){ return i > match[3] - 0; }, nth: function(elem, i, match){ return match[3] - 0 === i; }, eq: function(elem, i, match){ return match[3] - 0 === i; } }, filter: { PSEUDO: function(elem, match, i, array){ var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var i = 0, l = not.length; i < l; i++ ) { if ( not[i] === elem ) { return false; } } return true; } else { Sizzle.error( "Syntax error, unrecognized expression: " + name ); } }, CHILD: function(elem, match){ var type = match[1], node = elem; switch (type) { case 'only': case 'first': while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case 'last': while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case 'nth': var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function(elem, match){ return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function(elem, match){ return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function(elem, match){ return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function(elem, match){ var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function(elem, match, i, array){ var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, function(all, num){ return "\\" + (num - 0 + 1); })); } var makeArray = function(array, results) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch(e){ makeArray = function(array, results) { var ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var i = 0, l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( var i = 0; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { if ( a == b ) { hasDuplicate = true; } return a.compareDocumentPosition ? -1 : 1; } var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( "sourceIndex" in document.documentElement ) { sortOrder = function( a, b ) { if ( !a.sourceIndex || !b.sourceIndex ) { if ( a == b ) { hasDuplicate = true; } return a.sourceIndex ? -1 : 1; } var ret = a.sourceIndex - b.sourceIndex; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( document.createRange ) { sortOrder = function( a, b ) { if ( !a.ownerDocument || !b.ownerDocument ) { if ( a == b ) { hasDuplicate = true; } return a.ownerDocument ? -1 : 1; } var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); aRange.setStart(a, 0); aRange.setEnd(a, 0); bRange.setStart(b, 0); bRange.setEnd(b, 0); var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } // Utility function for retreiving the text value of an array of DOM nodes function getText( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += getText( elem.childNodes ); } } return ret; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date).getTime(); form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly var root = document.documentElement; root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function(elem, match){ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); root = form = null; // release memory in IE })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function(match, context){ var results = context.getElementsByTagName(match[1]); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function(elem){ return elem.getAttribute("href", 2); }; } div = null; // release memory in IE })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"); div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function(query, context, extra, seed){ context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && context.nodeType === 9 && !isXML(context) ) { try { return makeArray( context.querySelectorAll(query), extra ); } catch(e){} } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } div = null; // release memory in IE })(); } (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function(match, context, isXML) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; div = null; // release memory in IE })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } var contains = document.compareDocumentPosition ? function(a, b){ return !!(a.compareDocumentPosition(b) & 16); } : function(a, b){ return a !== b && (a.contains ? a.contains(b) : true); }; var isXML = function(elem){ // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function(selector, context){ var tmpSet = [], later = "", match, root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = getText; jQuery.isXMLDoc = isXML; jQuery.contains = contains; return; window.Sizzle = Sizzle; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, slice = Array.prototype.slice; // Implement the identical functionality for filter and not var winnow = function( elements, qualifier, keep ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return (elem === qualifier) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return (jQuery.inArray( elem, qualifier ) >= 0) === keep; }); }; jQuery.fn.extend({ find: function( selector ) { var ret = this.pushStack( "", "find", selector ), length = 0; for ( var i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( var n = length; n < ret.length; n++ ) { for ( var r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && jQuery.filter( selector, this ).length > 0; }, closest: function( selectors, context ) { if ( jQuery.isArray( selectors ) ) { var ret = [], cur = this[0], match, matches = {}, selector; if ( cur && selectors.length ) { for ( var i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[selector] ) { matches[selector] = jQuery.expr.match.POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[selector]; if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { ret.push({ selector: selector, elem: cur }); delete matches[selector]; } } cur = cur.parentNode; } } return ret; } var pos = jQuery.expr.match.POS.test( selectors ) ? jQuery( selectors, context || this.context ) : null; return this.map(function( i, cur ) { while ( cur && cur.ownerDocument && cur !== context ) { if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) { return cur; } cur = cur.parentNode; } return null; }); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context || this.context ) : jQuery.makeArray( selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call(arguments).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[dir]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g, rselfClosing = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<script|<object|<embed|<option|<style/i, rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, // checked="checked" or checked (html5) fcloseTag = function( all, front, tag ) { return rselfClosing.test( tag ) ? all : front + "></" + tag + ">"; }, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery(this); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append(this); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { return this.each(function() { jQuery( this ).wrapAll( html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( events ) { // Do the clone var ret = this.map(function() { if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { // IE copies events bound via attachEvent when // using cloneNode. Calling detachEvent on the // clone will also remove the events from the orignal // In order to get around this, we use innerHTML. // Unfortunately, this means some modifications to // attributes in IE that are actually only stored // as properties will not be copied (such as the // the name attribute on an input). var html = this.outerHTML, ownerDocument = this.ownerDocument; if ( !html ) { var div = ownerDocument.createElement("div"); div.appendChild( this.cloneNode(true) ); html = div.innerHTML; } return jQuery.clean([html.replace(rinlinejQuery, "") // Handle the case in IE 8 where action=/test/> self-closes a tag .replace(/=([^="'>\s]+\/)>/g, '="$1">') .replace(rleadingWhitespace, "")], ownerDocument)[0]; } else { return this.cloneNode(true); } }); // Copy the events from the original to the clone if ( events === true ) { cloneCopyEvent( this, ret ); cloneCopyEvent( this.find("*"), ret.find("*") ); } // Return the cloned set return ret; }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, fcloseTag); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery(this), old = self.html(); self.empty().append(function(){ return value.call( this, i, old ); }); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery(value).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery(this).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ); } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, value = args[0], scripts = [], fragment, parent; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], i > 0 || results.cacheable || this.length > 1 ? fragment.cloneNode(true) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } } }); function cloneCopyEvent(orig, ret) { var i = 0; ret.each(function() { if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) { return; } var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var handler in events[ type ] ) { jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); } } } }); } function buildFragment( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); // Only cache "small" (1/2 KB) strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults ) { if ( cacheresults !== 1 ) { fragment = cacheresults; } } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; } jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ original ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); jQuery.extend({ clean: function( elems, context, fragment, scripts ) { context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = []; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" && !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else if ( typeof elem === "string" ) { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, fcloseTag); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( var j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { for ( var i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ]; if ( data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); } else { removeEvent( elem, type, data.handle ); } } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); // exclude the following css properties to add px var rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, ralpha = /alpha\([^)]*\)/, ropacity = /opacity=([^)]*)/, rfloat = /float/i, rdashAlpha = /-([a-z])/ig, rupper = /([A-Z])/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, cssShow = { position: "absolute", visibility: "hidden", display:"block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], // cache check for defaultView.getComputedStyle getComputedStyle = document.defaultView && document.defaultView.getComputedStyle, // normalize float css property styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat", fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn.css = function( name, value ) { return access( this, name, value, true, function( elem, name, value ) { if ( value === undefined ) { return jQuery.curCSS( elem, name ); } if ( typeof value === "number" && !rexclude.test(name) ) { value += "px"; } jQuery.style( elem, name, value ); }); }; jQuery.extend({ style: function( elem, name, value ) { // don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // ignore negative width and height values #1599 if ( (name === "width" || name === "height") && parseFloat(value) < 0 ) { value = undefined; } var style = elem.style || elem, set = value !== undefined; // IE uses filters for opacity if ( !jQuery.support.opacity && name === "opacity" ) { if ( set ) { // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = parseInt( value, 10 ) + "" === "NaN" ? "" : "alpha(opacity=" + value * 100 + ")"; var filter = style.filter || jQuery.curCSS( elem, "filter" ) || ""; style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : opacity; } return style.filter && style.filter.indexOf("opacity=") >= 0 ? (parseFloat( ropacity.exec(style.filter)[1] ) / 100) + "": ""; } // Make sure we're using the right name for getting the float value if ( rfloat.test( name ) ) { name = styleFloat; } name = name.replace(rdashAlpha, fcamelCase); if ( set ) { style[ name ] = value; } return style[ name ]; }, css: function( elem, name, force, extra ) { if ( name === "width" || name === "height" ) { var val, props = cssShow, which = name === "width" ? cssWidth : cssHeight; function getWH() { val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0; } else { val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; } }); } if ( elem.offsetWidth !== 0 ) { getWH(); } else { jQuery.swap( elem, props, getWH ); } return Math.max(0, Math.round(val)); } return jQuery.curCSS( elem, name, force ); }, curCSS: function( elem, name, force ) { var ret, style = elem.style, filter; // IE uses filters for opacity if ( !jQuery.support.opacity && name === "opacity" && elem.currentStyle ) { ret = ropacity.test(elem.currentStyle.filter || "") ? (parseFloat(RegExp.$1) / 100) + "" : ""; return ret === "" ? "1" : ret; } // Make sure we're using the right name for getting the float value if ( rfloat.test( name ) ) { name = styleFloat; } if ( !force && style && style[ name ] ) { ret = style[ name ]; } else if ( getComputedStyle ) { // Only "float" is needed here if ( rfloat.test( name ) ) { name = "float"; } name = name.replace( rupper, "-$1" ).toLowerCase(); var defaultView = elem.ownerDocument.defaultView; if ( !defaultView ) { return null; } var computedStyle = defaultView.getComputedStyle( elem, null ); if ( computedStyle ) { ret = computedStyle.getPropertyValue( name ); } // We should always get a number back from opacity if ( name === "opacity" && ret === "" ) { ret = "1"; } } else if ( elem.currentStyle ) { var camelCase = name.replace(rdashAlpha, fcamelCase); ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values var left = style.left, rsLeft = elem.runtimeStyle.left; // Put in the new values to get a computed value out elem.runtimeStyle.left = elem.currentStyle.left; style.left = camelCase === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; elem.runtimeStyle.left = rsLeft; } } return ret; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( var name in options ) { elem.style[ name ] = old[ name ]; } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight, skip = elem.nodeName.toLowerCase() === "tr"; return width === 0 && height === 0 && !skip ? true : width > 0 && height > 0 && !skip ? false : jQuery.curCSS(elem, "display") === "none"; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var jsc = now(), rscript = /<script(.|\s)*?\/script>/gi, rselectTextarea = /select|textarea/i, rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i, jsre = /=\?(&|$)/, rquery = /\?/, rts = /(\?|&)_=.*?(&|$)/, rurl = /^(\w+:)?\/\/([^\/?#]+)/, r20 = /%20/g, // Keep a copy of the old load method _load = jQuery.fn.load; jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" ) { return _load.call( this, url ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf(" "); if ( off >= 0 ) { var selector = url.slice(off, url.length); url = url.slice(0, off); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = null; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, complete: function( res, status ) { // If successful, inject the HTML into all the matched elements if ( status === "success" || status === "notmodified" ) { // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div />") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(res.responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result res.responseText ); } if ( callback ) { self.each( callback, [res.responseText, status, res] ); } } }); return this; }, serialize: function() { return jQuery.param(this.serializeArray()); }, serializeArray: function() { return this.map(function() { return this.elements ? jQuery.makeArray(this.elements) : this; }) .filter(function() { return this.name && !this.disabled && (this.checked || rselectTextarea.test(this.nodeName) || rinput.test(this.type)); }) .map(function( i, elem ) { var val = jQuery(this).val(); return val == null ? null : jQuery.isArray(val) ? jQuery.map( val, function( val, i ) { return { name: elem.name, value: val }; }) : { name: elem.name, value: val }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) { jQuery.fn[o] = function( f ) { return this.bind(o, f); }; }); jQuery.extend({ get: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type }); }, getScript: function( url, callback ) { return jQuery.get(url, null, callback, "script"); }, getJSON: function( url, data, callback ) { return jQuery.get(url, data, callback, "json"); }, post: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = {}; } return jQuery.ajax({ type: "POST", url: url, data: data, success: callback, dataType: type }); }, ajaxSetup: function( settings ) { jQuery.extend( jQuery.ajaxSettings, settings ); }, ajaxSettings: { url: location.href, global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, username: null, password: null, traditional: false, */ // Create the request object; Microsoft failed to properly // implement the XMLHttpRequest in IE7 (can't request local files), // so we use the ActiveXObject when it is available // This function can be overriden by calling jQuery.ajaxSetup xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ? function() { return new window.XMLHttpRequest(); } : function() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} }, accepts: { xml: "application/xml, text/xml", html: "text/html", script: "text/javascript, application/javascript", json: "application/json, text/javascript", text: "text/plain", _default: "*/*" } }, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajax: function( origSettings ) { var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings); var jsonp, status, data, callbackContext = origSettings && origSettings.context || s, type = s.type.toUpperCase(); // convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Handle JSONP Parameter Callbacks if ( s.dataType === "jsonp" ) { if ( type === "GET" ) { if ( !jsre.test( s.url ) ) { s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?"; } } else if ( !s.data || !jsre.test(s.data) ) { s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; } s.dataType = "json"; } // Build temporary JSONP function if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { jsonp = s.jsonpCallback || ("jsonp" + jsc++); // Replace the =? sequence both in the query string and the data if ( s.data ) { s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); } s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure // that a JSONP style response is executed properly s.dataType = "script"; // Handle JSONP-style loading window[ jsonp ] = window[ jsonp ] || function( tmp ) { data = tmp; success(); complete(); // Garbage collect window[ jsonp ] = undefined; try { delete window[ jsonp ]; } catch(e) {} if ( head ) { head.removeChild( script ); } }; } if ( s.dataType === "script" && s.cache === null ) { s.cache = false; } if ( s.cache === false && type === "GET" ) { var ts = now(); // try replacing _= if it is there var ret = s.url.replace(rts, "$1_=" + ts + "$2"); // if nothing was replaced, add timestamp to the end s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : ""); } // If data is available, append data to url for get requests if ( s.data && type === "GET" ) { s.url += (rquery.test(s.url) ? "&" : "?") + s.data; } // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } // Matches an absolute URL, and saves the domain var parts = rurl.exec( s.url ), remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host); // If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType === "script" && type === "GET" && remote ) { var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); script.src = s.url; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; success(); complete(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } } }; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); // We handle everything using the script element injection return undefined; } var requestDone = false; // Create the request object var xhr = s.xhr(); if ( !xhr ) { return; } // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open(type, s.url, s.async, s.username, s.password); } else { xhr.open(type, s.url, s.async); } // Need an extra try/catch for cross domain requests in Firefox 3 try { // Set the correct header, if data is being sent if ( s.data || origSettings && origSettings.contentType ) { xhr.setRequestHeader("Content-Type", s.contentType); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[s.url] ) { xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]); } if ( jQuery.etag[s.url] ) { xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]); } } // Set header so the called script knows that it's an XMLHttpRequest // Only send the header if it's not a remote XHR if ( !remote ) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); } // Set the Accepts header for the server, depending on the dataType xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? s.accepts[ s.dataType ] + ", */*" : s.accepts._default ); } catch(e) {} // Allow custom headers/mimetypes and early abort if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) { // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } // close opended socket xhr.abort(); return false; } if ( s.global ) { trigger("ajaxSend", [xhr, s]); } // Wait for a response to come back var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) { // The request was aborted if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) { // Opera doesn't call onreadystatechange before this point // so we simulate the call if ( !requestDone ) { complete(); } requestDone = true; if ( xhr ) { xhr.onreadystatechange = jQuery.noop; } // The transfer is complete and the data is available, or the request timed out } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) { requestDone = true; xhr.onreadystatechange = jQuery.noop; status = isTimeout === "timeout" ? "timeout" : !jQuery.httpSuccess( xhr ) ? "error" : s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" : "success"; var errMsg; if ( status === "success" ) { // Watch for, and catch, XML document parse errors try { // process the data (runs the xml through httpData regardless of callback) data = jQuery.httpData( xhr, s.dataType, s ); } catch(err) { status = "parsererror"; errMsg = err; } } // Make sure that the request was successful or notmodified if ( status === "success" || status === "notmodified" ) { // JSONP handles its own success callback if ( !jsonp ) { success(); } } else { jQuery.handleError(s, xhr, status, errMsg); } // Fire the complete handlers complete(); if ( isTimeout === "timeout" ) { xhr.abort(); } // Stop memory leaks if ( s.async ) { xhr = null; } } }; // Override the abort handler, if we can (IE doesn't allow it, but that's OK) // Opera doesn't fire onreadystatechange at all on abort try { var oldAbort = xhr.abort; xhr.abort = function() { if ( xhr ) { oldAbort.call( xhr ); } onreadystatechange( "abort" ); }; } catch(e) { } // Timeout checker if ( s.async && s.timeout > 0 ) { setTimeout(function() { // Check to see if the request is still happening if ( xhr && !requestDone ) { onreadystatechange( "timeout" ); } }, s.timeout); } // Send the data try { xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null ); } catch(e) { jQuery.handleError(s, xhr, null, e); // Fire the complete handlers complete(); } // firefox 1.5 doesn't fire statechange for sync requests if ( !s.async ) { onreadystatechange(); } function success() { // If a local callback was specified, fire it and pass it the data if ( s.success ) { s.success.call( callbackContext, data, status, xhr ); } // Fire the global callback if ( s.global ) { trigger( "ajaxSuccess", [xhr, s] ); } } function complete() { // Process result if ( s.complete ) { s.complete.call( callbackContext, xhr, status); } // The request was completed if ( s.global ) { trigger( "ajaxComplete", [xhr, s] ); } // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } } function trigger(type, args) { (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args); } // return XMLHttpRequest to allow aborting the request etc. return xhr; }, handleError: function( s, xhr, status, e ) { // If a local callback was specified, fire it if ( s.error ) { s.error.call( s.context || s, xhr, status, e ); } // Fire the global callback if ( s.global ) { (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] ); } }, // Counter for holding the number of active queries active: 0, // Determines if an XMLHttpRequest was successful or not httpSuccess: function( xhr ) { try { // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 return !xhr.status && location.protocol === "file:" || // Opera returns 0 when status is 304 ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 304 || xhr.status === 1223 || xhr.status === 0; } catch(e) {} return false; }, // Determines if an XMLHttpRequest returns NotModified httpNotModified: function( xhr, url ) { var lastModified = xhr.getResponseHeader("Last-Modified"), etag = xhr.getResponseHeader("Etag"); if ( lastModified ) { jQuery.lastModified[url] = lastModified; } if ( etag ) { jQuery.etag[url] = etag; } // Opera returns 0 when status is 304 return xhr.status === 304 || xhr.status === 0; }, httpData: function( xhr, type, s ) { var ct = xhr.getResponseHeader("content-type") || "", xml = type === "xml" || !type && ct.indexOf("xml") >= 0, data = xml ? xhr.responseXML : xhr.responseText; if ( xml && data.documentElement.nodeName === "parsererror" ) { jQuery.error( "parsererror" ); } // Allow a pre-filtering function to sanitize the response // s is checked to keep backwards compatibility if ( s && s.dataFilter ) { data = s.dataFilter( data, type ); } // The filter can actually parse the response if ( typeof data === "string" ) { // Get the JavaScript object, if JSON is used. if ( type === "json" || !type && ct.indexOf("json") >= 0 ) { data = jQuery.parseJSON( data ); // If the type is "script", eval it in global context } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) { jQuery.globalEval( data ); } } return data; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = []; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray(a) || a.jquery ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[prefix] ); } } // Return the resulting serialization return s.join("&").replace(r20, "+"); function buildParams( prefix, obj ) { if ( jQuery.isArray(obj) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || /\[\]$/.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. jQuery.each( obj, function( k, v ) { buildParams( prefix + "[" + k + "]", v ); }); } else { // Serialize scalar item. add( prefix, obj ); } } function add( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction(value) ? value() : value; s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value); } } }); var elemdisplay = {}, rfxtypes = /toggle|show|hide/, rfxnum = /^([+-]=)?([\d+-.]+)(.*)$/, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ]; jQuery.fn.extend({ show: function( speed, callback ) { if ( speed || speed === 0) { return this.animate( genFx("show", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ) { var old = jQuery.data(this[i], "olddisplay"); this[i].style.display = old || ""; if ( jQuery.css(this[i], "display") === "none" ) { var nodeName = this[i].nodeName, display; if ( elemdisplay[ nodeName ] ) { display = elemdisplay[ nodeName ]; } else { var elem = jQuery("<" + nodeName + " />").appendTo("body"); display = elem.css("display"); if ( display === "none" ) { display = "block"; } elem.remove(); elemdisplay[ nodeName ] = display; } jQuery.data(this[i], "olddisplay", display); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var j = 0, k = this.length; j < k; j++ ) { this[j].style.display = jQuery.data(this[j], "olddisplay") || ""; } return this; } }, hide: function( speed, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ) { var old = jQuery.data(this[i], "olddisplay"); if ( !old && old !== "none" ) { jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display")); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var j = 0, k = this.length; j < k; j++ ) { this[j].style.display = "none"; } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2 ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2); } return this; }, fadeTo: function( speed, to, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete ); } return this[ optall.queue === false ? "each" : "queue" ](function() { var opt = jQuery.extend({}, optall), p, hidden = this.nodeType === 1 && jQuery(this).is(":hidden"), self = this; for ( p in prop ) { var name = p.replace(rdashAlpha, fcamelCase); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; p = name; } if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { return opt.complete.call(this); } if ( ( p === "height" || p === "width" ) && this.style ) { // Store display property opt.display = jQuery.css(this, "display"); // Make sure that nothing sneaks out opt.overflow = this.style.overflow; } if ( jQuery.isArray( prop[p] ) ) { // Create (if needed) and add to specialEasing (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; prop[p] = prop[p][0]; } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } opt.curAnim = jQuery.extend({}, prop); jQuery.each( prop, function( name, val ) { var e = new jQuery.fx( self, opt, name ); if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); } else { var parts = rfxnum.exec(val), start = e.cur(true) || 0; if ( parts ) { var end = parseFloat( parts[2] ), unit = parts[3] || "px"; // We need to compute starting value if ( unit !== "px" ) { self.style[ name ] = (end || 1) + unit; start = ((end || 1) / e.cur(true)) * start; self.style[ name ] = start + unit; } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ((parts[1] === "-=" ? -1 : 1) * end) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } }); // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { var timers = jQuery.timers; if ( clearQueue ) { this.queue([]); } this.each(function() { // go in reverse order so anything added to the queue during the loop is ignored for ( var i = timers.length - 1; i >= 0; i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, callback ) { return this.animate( props, speed, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? speed : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction(easing) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function() { if ( opt.queue !== false ) { jQuery(this).dequeue(); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; if ( !options.orig ) { options.orig = {}; } } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); // Set display property to block for height/width animations if ( ( this.prop === "height" || this.prop === "width" ) && this.elem.style ) { this.elem.style.display = "block"; } }, // Get the current size cur: function( force ) { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var r = parseFloat(jQuery.css(this.elem, this.prop, force)); return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0; }, // Start an animation from one number to another custom: function( from, to, unit ) { this.startTime = now(); this.start = from; this.end = to; this.unit = unit || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; var self = this; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval(jQuery.fx.tick, 13); } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { var t = now(), done = true; if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; for ( var i in this.options.curAnim ) { if ( this.options.curAnim[i] !== true ) { done = false; } } if ( done ) { if ( this.options.display != null ) { // Reset the overflow this.elem.style.overflow = this.options.overflow; // Reset the display var old = jQuery.data(this.elem, "olddisplay"); this.elem.style.display = old ? old : this.options.display; if ( jQuery.css(this.elem, "display") === "none" ) { this.elem.style.display = "block"; } } // Hide the element if the "hide" operation was done if ( this.options.hide ) { jQuery(this.elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( this.options.hide || this.options.show ) { for ( var p in this.options.curAnim ) { jQuery.style(this.elem, p, this.options.orig[p]); } } // Execute the complete function this.options.complete.call( this.elem ); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; // Perform the easing function, defaults to swing var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timers = jQuery.timers; for ( var i = 0; i < timers.length; i++ ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style(fx.elem, "opacity", fx.now); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, top = box.top + (self.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop, left = box.left + (self.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent, offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0, html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed", checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden", innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); body = container = innerDiv = checkDiv = table = td = null; jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0; left += parseFloat( jQuery.curCSS(body, "marginLeft", true) ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { // set position first, in-case top/left are set even on static elem if ( /static/.test( jQuery.curCSS( elem, "position" ) ) ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curTop = parseInt( jQuery.curCSS( elem, "top", true ), 10 ) || 0, curLeft = parseInt( jQuery.curCSS( elem, "left", true ), 10 ) || 0; if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } var props = { top: (options.top - curOffset.top) + curTop, left: (options.left - curOffset.left) + curLeft }; if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = /^body|html$/i.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.curCSS(elem, "marginTop", true) ) || 0; offset.left -= parseFloat( jQuery.curCSS(elem, "marginLeft", true) ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.curCSS(offsetParent[0], "borderTopWidth", true) ) || 0; parentOffset.left += parseFloat( jQuery.curCSS(offsetParent[0], "borderLeftWidth", true) ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!/^body|html$/i.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function(val) { var elem = this[0], win; if ( !elem ) { return null; } if ( val !== undefined ) { // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery(win).scrollLeft(), i ? val : jQuery(win).scrollTop() ); } else { this[ method ] = val; } }); } else { win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } }; }); function getWindow( elem ) { return ("scrollTo" in elem && elem.document) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function() { return this[0] ? jQuery.css( this[0], type, false, "padding" ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { return this[0] ? jQuery.css( this[0], type, false, margin ? "margin" : "border" ) : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } return ("scrollTo" in elem && elem.document) ? // does it walk and quack like a window? // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] || elem.document.body[ "client" + name ] : // Get document width or height (elem.nodeType === 9) ? // is it a document // Either scroll[Width/Height] or offset[Width/Height], whichever is greater Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ) : // Get or set width or height on the element size === undefined ? // Get width or height on the element jQuery.css( elem, type ) : // Set the width or height on the element (default to pixels if value is unitless) this.css( type, typeof size === "string" ? size : size + "px" ); }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; })(window); /** * The MIT License * * Copyright (c) 2010 Adam Abrons and Misko Hevery http://getangular.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ (function(window, document, previousOnLoad){ var _jQuery = window.jQuery.noConflict(true); //////////////////////////////////// if (typeof document.getAttribute == $undefined) document.getAttribute = function() {}; /** * @workInProgress * @ngdoc function * @name angular.lowercase * @function * * @description Converts string to lowercase * @param {string} string String to be lowercased. * @returns {string} Lowercased string. */ var lowercase = function (string){ return isString(string) ? string.toLowerCase() : string; }; /** * @workInProgress * @ngdoc function * @name angular.uppercase * @function * * @description Converts string to uppercase. * @param {string} string String to be uppercased. * @returns {string} Uppercased string. */ var uppercase = function (string){ return isString(string) ? string.toUpperCase() : string; }; var manualLowercase = function (s) { return isString(s) ? s.replace(/[A-Z]/g, function (ch) {return fromCharCode(ch.charCodeAt(0) | 32); }) : s; }; var manualUppercase = function (s) { return isString(s) ? s.replace(/[a-z]/g, function (ch) {return fromCharCode(ch.charCodeAt(0) & ~32); }) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods with // correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } function fromCharCode(code) { return String.fromCharCode(code); } var _undefined = undefined, _null = null, $$element = '$element', $$update = '$update', $$scope = '$scope', $$validate = '$validate', $angular = 'angular', $array = 'array', $boolean = 'boolean', $console = 'console', $date = 'date', $display = 'display', $element = 'element', $function = 'function', $length = 'length', $name = 'name', $none = 'none', $noop = 'noop', $null = 'null', $number = 'number', $object = 'object', $string = 'string', $value = 'value', $selected = 'selected', $undefined = 'undefined', NG_EXCEPTION = 'ng-exception', NG_VALIDATION_ERROR = 'ng-validation-error', NOOP = 'noop', PRIORITY_FIRST = -99999, PRIORITY_WATCH = -1000, PRIORITY_LAST = 99999, PRIORITY = {'FIRST': PRIORITY_FIRST, 'LAST': PRIORITY_LAST, 'WATCH':PRIORITY_WATCH}, Error = window.Error, jQuery = window['jQuery'] || window['$'], // weirdness to make IE happy _ = window['_'], /** holds major version number for IE or NaN for real browsers */ msie = parseInt((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1], 10), jqLite = jQuery || jqLiteWrap, slice = Array.prototype.slice, push = Array.prototype.push, error = window[$console] ? bind(window[$console], window[$console]['error'] || noop) : noop, angular = window[$angular] || (window[$angular] = {}), angularTextMarkup = extensionMap(angular, 'markup'), angularAttrMarkup = extensionMap(angular, 'attrMarkup'), /** @name angular.directive */ angularDirective = extensionMap(angular, 'directive'), /** @name angular.widget */ angularWidget = extensionMap(angular, 'widget', lowercase), /** @name angular.validator */ angularValidator = extensionMap(angular, 'validator'), /** @name angular.fileter */ angularFilter = extensionMap(angular, 'filter'), /** @name angular.formatter */ angularFormatter = extensionMap(angular, 'formatter'), /** @name angular.service */ angularService = extensionMap(angular, 'service'), angularCallbacks = extensionMap(angular, 'callbacks'), nodeName, rngScript = /^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/; /** * @workInProgress * @ngdoc function * @name angular.foreach * @function * * @description * Invokes the `iterator` function once for each item in `obj` collection. The collection can either * be an object or an array. The `iterator` function is invoked with `iterator(value, key)`, where * `value` is the value of an object property or an array element and `key` is the object property * key or array element index. Optionally, `context` can be specified for the iterator function. * <pre> var values = {name: 'misko', gender: 'male'}; var log = []; angular.foreach(values, function(value, key){ this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender:male']); </pre> * * @param {Object|Array} obj Object to iterate over. * @param {function()} iterator Iterator function. * @param {Object} context Object to become context (`this`) for the iterator function. * @returns {Objet|Array} Reference to `obj`. */ function foreach(obj, iterator, context) { var key; if (obj) { if (isFunction(obj)){ for (key in obj) { if (key != 'prototype' && key != $length && key != $name && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } else if (obj.forEach) { obj.forEach(iterator, context); } else if (isObject(obj) && isNumber(obj.length)) { for (key = 0; key < obj.length; key++) iterator.call(context, obj[key], key); } else { for (key in obj) iterator.call(context, obj[key], key); } } return obj; } function foreachSorted(obj, iterator, context) { var keys = []; for (var key in obj) keys.push(key); keys.sort(); for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } /** * @workInProgress * @ngdoc function * @name angular.extend * @function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` objects to * `dst`. You can specify multiple `src` objects. * * @param {Object} dst The destination object. * @param {...Object} src The source object(s). */ function extend(dst) { foreach(arguments, function(obj){ if (obj !== dst) { foreach(obj, function(value, key){ dst[key] = value; }); } }); return dst; } function inherit(parent, extra) { return extend(new (extend(function(){}, {prototype:parent}))(), extra); } /** * @workInProgress * @ngdoc function * @name angular.noop * @function * * @description * Empty function that performs no operation whatsoever. This function is useful when writing code * in the functional style. <pre> function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } </pre> */ function noop() {} /** * @workInProgress * @ngdoc function * @name angular.identity * @function * * @description * A function that does nothing except for returning its first argument. This function is useful * when writing code in the functional style. * <pre> function transformer(transformationFn, value) { return (transformationFn || identity)(value); }; </pre> */ function identity($) {return $;} function valueFn(value) {return function(){ return value; };} function extensionMap(angular, name, transform) { var extPoint; return angular[name] || (extPoint = angular[name] = function (name, fn, prop){ name = (transform || identity)(name); if (isDefined(fn)) { if (isDefined(extPoint[name])) { foreach(extPoint[name], function(property, key) { if (key.charAt(0) == '$' && isUndefined(fn[key])) fn[key] = property; }); } extPoint[name] = extend(fn, prop || {}); } return extPoint[name]; }); } function jqLiteWrap(element) { // for some reasons the parentNode of an orphan looks like _null but its typeof is object. if (element) { if (isString(element)) { var div = document.createElement('div'); div.innerHTML = element; element = new JQLite(div.childNodes); } else if (!(element instanceof JQLite) && isElement(element)) { element = new JQLite(element); } } return element; } /** * @workInProgress * @ngdoc function * @name angular.isUndefined * @function * * @description * Checks if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value){ return typeof value == $undefined; } /** * @workInProgress * @ngdoc function * @name angular.isDefined * @function * * @description * Checks if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value){ return typeof value != $undefined; } /** * @workInProgress * @ngdoc function * @name angular.isObject * @function * * @description * Checks if a reference is an `Object`. Unlike in JavaScript `null`s are not considered to be * objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value){ return value!=_null && typeof value == $object;} /** * @workInProgress * @ngdoc function * @name angular.isString * @function * * @description * Checks if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value){ return typeof value == $string;} /** * @workInProgress * @ngdoc function * @name angular.isNumber * @function * * @description * Checks if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value){ return typeof value == $number;} /** * @workInProgress * @ngdoc function * @name angular.isDate * @function * * @description * Checks if value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value){ return value instanceof Date; } /** * @workInProgress * @ngdoc function * @name angular.isArray * @function * * @description * Checks if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ function isArray(value) { return value instanceof Array; } /** * @workInProgress * @ngdoc function * @name angular.isFunction * @function * * @description * Checks if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value){ return typeof value == $function;} function isBoolean(value) { return typeof value == $boolean;} function isTextNode(node) { return nodeName(node) == '#text'; } function trim(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; } function isElement(node) { return node && (node.nodeName || node instanceof JQLite || (jQuery && node instanceof jQuery)); } /** * HTML class which is the only class which can be used in ng:bind to inline HTML for security reasons. * @constructor * @param html raw (unsafe) html * @param {string=} option if set to 'usafe' then get method will return raw (unsafe/unsanitized) html */ function HTML(html, option) { this.html = html; this.get = lowercase(option) == 'unsafe' ? valueFn(html) : function htmlSanitize() { var buf = []; htmlParser(html, htmlSanitizeWriter(buf)); return buf.join(''); }; } if (msie) { nodeName = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML' ) ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function quickClone(element) { return jqLite(element[0].cloneNode(true)); } function isVisible(element) { var rect = element[0].getBoundingClientRect(), width = (rect.width || (rect.right||0 - rect.left||0)), height = (rect.height || (rect.bottom||0 - rect.top||0)); return width>0 && height>0; } function map(obj, iterator, context) { var results = []; foreach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } /** * @workInProgress * @ngdoc function * @name angular.Object.size * @function * * @description * Determines the number of elements in an array or number of properties of an object. * * Note: this function is used to augment the Object type in angular expressions. See * {@link angular.Object} for more info. * * @param {Object|Array} obj Object or array to inspect. * @returns {number} The size of `obj` or `0` if `obj` is not an object or array. * * @example * Number of items in array: {{ [1,2].$size() }}<br/> * Number of items in object: {{ {a:1, b:2, c:3}.$size() }}<br/> */ function size(obj) { var size = 0; if (obj) { if (isNumber(obj.length)) { return obj.length; } else if (isObject(obj)){ for (key in obj) size++; } } return size; } function includes(array, obj) { for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return true; } return false; } function indexOf(array, obj) { for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * @workInProgress * @ngdoc function * @name angular.Object.copy * @function * * @description * Creates a deep copy of `source`. * * If `destination` is not provided and `source` is an object or an array, a copy is created & * returned, otherwise the `source` is returned. * * If `destination` is provided, all of its properties will be deleted. * * If `source` is an object or an array, all of its members will be copied into the `destination` * object. * * Note: this function is used to augment the Object type in angular expressions. See * {@link angular.Object} for more info. * * @param {*} source The source to be used to make a copy. * Can be any type including primitives, `null` and `undefined`. * @param {(Object|Array)=} destination Optional destination into which the source is copied. * @returns {*} The copy or updated `destination` if `destination` was specified. * * @example Salutation: <input type="text" name="master.salutation" value="Hello" /><br/> Name: <input type="text" name="master.name" value="world"/><br/> <button ng:click="form = master.$copy()">copy</button> <hr/> Master is <span ng:hide="master.$equals(form)">NOT</span> same as form. <pre>master={{master}}</pre> <pre>form={{form}}</pre> */ function copy(source, destination){ if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isObject(source)) { destination = copy(source, {}); } } } else { if (isArray(source)) { while(destination.length) { destination.pop(); } for ( var i = 0; i < source.length; i++) { destination.push(copy(source[i])); } } else { foreach(destination, function(value, key){ delete destination[key]; }); for ( var key in source) { destination[key] = copy(source[key]); } } } return destination; } /** * @workInProgress * @ngdoc function * @name angular.Object.equals * @function * * @description * Determines if two objects or value are equivalent. * * To be equivalent, they must pass `==` comparison or be of the same type and have all their * properties pass `==` comparison. * * Supports values types, arrays and objects. * * For objects `function` properties and properties that start with `$` are not considered during * comparisons. * * Note: this function is used to augment the Object type in angular expressions. See * {@link angular.Object} for more info. * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. * * @example Salutation: <input type="text" name="master.salutation" value="Hello" /><br/> Name: <input type="text" name="master.name" value="world"/><br/> <button ng:click="form = master.$copy()">copy</button> <hr/> Master is <span ng:hide="master.$equals(form)">NOT</span> same as form. <pre>master={{master}}</pre> <pre>form={{form}}</pre> */ function equals(o1, o2) { if (o1 == o2) return true; var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2 && t1 == 'object') { if (o1 instanceof Array) { if ((length = o1.length) == o2.length) { for(key=0; key<length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else { keySet = {}; for(key in o1) { if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) return false; keySet[key] = true; } for(key in o2) { if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false; } return true; } } return false; } function setHtml(node, html) { if (isLeafNode(node)) { if (msie) { node.innerText = html; } else { node.textContent = html; } } else { node.innerHTML = html; } } function isRenderableElement(element) { var name = element && element[0] && element[0].nodeName; return name && name.charAt(0) != '#' && !includes(['TR', 'COL', 'COLGROUP', 'TBODY', 'THEAD', 'TFOOT'], name); } function elementError(element, type, error) { while (!isRenderableElement(element)) { element = element.parent() || jqLite(document.body); } if (element[0]['$NG_ERROR'] !== error) { element[0]['$NG_ERROR'] = error; if (error) { element.addClass(type); element.attr(type, error); } else { element.removeClass(type); element.removeAttr(type); } } } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index, array2.length)); } /** * @workInProgress * @ngdoc function * @name angular.bind * @function * * @description * Returns function which calls function `fn` bound to `self` (`self` becomes the `this` for `fn`). * Optional `args` can be supplied which are prebound to the function, also known as * [function currying](http://en.wikipedia.org/wiki/Currying). * * @param {Object} self Context in which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {(...*)=} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? slice.call(arguments, 2, arguments.length) : []; if (typeof fn == $function) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0, arguments.length))) : fn.apply(self, curryArgs); }: function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions and so they can not be bound (but they don't need to be) return fn; } } function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } function merge(src, dst) { for ( var key in src) { var value = dst[key]; var type = typeof value; if (type == $undefined) { dst[key] = fromJson(toJson(src[key])); } else if (type == 'object' && value.constructor != array && key.substring(0, 1) != "$") { merge(src[key], value); } } } /** * @workInProgress * @ngdoc function * @name angular.compile * @function * * @description * Compiles a piece of HTML or DOM into a {@link angular.scope scope} object. <pre> var scope1 = angular.compile(window.document); scope1.$init(); var scope2 = angular.compile('<div ng:click="clicked = true">click me</div>'); scope2.$init(); </pre> * * @param {string|DOMElement} element Element to compile. * @param {Object=} parentScope Scope to become the parent scope of the newly compiled scope. * @returns {Object} Compiled scope object. */ function compile(element, parentScope) { var compiler = new Compiler(angularTextMarkup, angularAttrMarkup, angularDirective, angularWidget), $element = jqLite(element); return compiler.compile($element)($element, parentScope); } ///////////////////////////////////////////////// /** * Parses an escaped url query string into key-value pairs. * @returns Object.<(string|boolean)> */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; foreach((keyValue || "").split('&'), function(keyValue){ if (keyValue) { key_value = keyValue.split('='); key = unescape(key_value[0]); obj[key] = isDefined(key_value[1]) ? unescape(key_value[1]) : true; } }); return obj; } function toKeyValue(obj) { var parts = []; foreach(obj, function(value, key) { parts.push(escape(key) + (value === true ? '' : '=' + escape(value))); }); return parts.length ? parts.join('&') : ''; } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:autobind * @element script * * @TODO ng:autobind is not a directive!! it should be documented as bootstrap parameter in a * separate bootstrap section. * @TODO rename to ng:autobind to ng:autoboot * * @description * This section explains how to bootstrap your application with angular using either the angular * javascript file. * * * ## The angular distribution * Note that there are two versions of the angular javascript file that you can use: * * * `angular.js` - the development version - this file is unobfuscated, uncompressed, and thus * human-readable and useful when developing your angular applications. * * `angular.min.js` - the production version - this is a minified and obfuscated version of * `angular.js`. You want to use this version when you want to load a smaller but functionally * equivalent version of the code in your application. We use the Closure compiler to create this * file. * * * ## Auto-bootstrap with `ng:autobind` * The simplest way to get an <angular/> application up and running is by inserting a script tag in * your HTML file that bootstraps the `http://code.angularjs.org/angular-x.x.x.min.js` code and uses * the special `ng:autobind` attribute, like in this snippet of HTML: * * <pre> &lt;!doctype html&gt; &lt;html xmlns:ng="http://angularjs.org"&gt; &lt;head&gt; &lt;script type="text/javascript" src="http://code.angularjs.org/angular-0.9.3.min.js" ng:autobind&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; Hello {{'world'}}! &lt;/body&gt; &lt;/html&gt; * </pre> * * The `ng:autobind` attribute tells <angular/> to compile and manage the whole HTML document. The * compilation occurs in the page's `onLoad` handler. Note that you don't need to explicitly add an * `onLoad` event; auto bind mode takes care of all the magic for you. * * * ## Auto-bootstrap with `#autobind` * In rare cases when you can't define the `ng` namespace before the script tag (e.g. in some CMS * systems, etc), it is possible to auto-bootstrap angular by appending `#autobind` to the script * src URL, like in this snippet: * * <pre> &lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="http://code.angularjs.org/angular-0.9.3.min.js#autobind"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div xmlns:ng="http://angularjs.org"&gt; Hello {{'world'}}! &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; * </pre> * * In this case it's the `#autobind` URL fragment that tells angular to auto-bootstrap. * * * ## Filename Restrictions for Auto-bootstrap * In order for us to find the auto-bootstrap script attribute or URL fragment, the value of the * `script` `src` attribute that loads angular script must match one of these naming * conventions: * * - `angular.js` * - `angular-min.js` * - `angular-x.x.x.js` * - `angular-x.x.x.min.js` * - `angular-x.x.x-xxxxxxxx.js` (dev snapshot) * - `angular-x.x.x-xxxxxxxx.min.js` (dev snapshot) * - `angular-bootstrap.js` (used for development of angular) * * Optionally, any of the filename format above can be prepended with relative or absolute URL that * ends with `/`. * * * ## Manual Bootstrap * Using auto-bootstrap is a handy way to start using <angular/>, but advanced users who want more * control over the initialization process might prefer to use manual bootstrap instead. * * The best way to get started with manual bootstraping is to look at the magic behind `ng:autobind` * by writing out each step of the autobind process explicitly. Note that the following code is * equivalent to the code in the previous section. * * <pre> &lt;!doctype html&gt; &lt;html xmlns:ng="http://angularjs.org"&gt; &lt;head&gt; &lt;script type="text/javascript" src="http://code.angularjs.org/angular-0.9.3.min.js" ng:autobind&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; (function(window, previousOnLoad){ window.onload = function(){ try { (previousOnLoad||angular.noop)(); } catch(e) {} angular.compile(window.document).$init(); }; })(window, window.onload); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; Hello {{'World'}}! &lt;/body&gt; &lt;/html&gt; * </pre> * * This is the sequence that your code should follow if you're bootstrapping angular on your own: * * * After the page is loaded, find the root of the HTML template, which is typically the root of * the document. * * Run the HTML compiler, which converts the templates into an executable, bi-directionally bound * application. * * * ##XML Namespace * *IMPORTANT:* When using <angular/> you must declare the ng namespace using the xmlns tag. If you * don't declare the namespace, Internet Explorer does not render widgets properly. * * <pre> * &lt;html xmlns:ng="http://angularjs.org"&gt; * </pre> * * * ## Create your own namespace * If you want to define your own widgets, you must create your own namespace and use that namespace * to form the fully qualified widget name. For example, you could map the alias `my` to your domain * and create a widget called my:widget. To create your own namespace, simply add another xmlsn tag * to your page, create an alias, and set it to your unique domain: * * <pre> * &lt;html xmlns:ng="http://angularjs.org" xmlns:my="http://mydomain.com"&gt; * </pre> * * * ## Global Object * The <angular/> script creates a single global variable `angular` in the global namespace. All * APIs are bound to fields of this global object. * */ function angularInit(config){ if (config.autobind) { // TODO default to the source of angular.js var scope = compile(window.document, _null, {'$config':config}), $browser = scope.$inject('$browser'); if (config.css) $browser.addCss(config.base_url + config.css); else if(msie<8) $browser.addJs(config.base_url + config.ie_compat, config.ie_compat_id); scope.$init(); } } function angularJsConfig(document, config) { var scripts = document.getElementsByTagName("script"), match; config = extend({ ie_compat_id: 'ng-ie-compat' }, config); for(var j = 0; j < scripts.length; j++) { match = (scripts[j].src || "").match(rngScript); if (match) { config.base_url = match[1]; config.ie_compat = match[1] + 'angular-ie-compat' + (match[2] || '') + '.js'; extend(config, parseKeyValue(match[6])); eachAttribute(jqLite(scripts[j]), function(value, name){ if (/^ng:/.exec(name)) { name = name.substring(3).replace(/-/g, '_'); if (name == 'autobind') value = true; config[name] = value; } }); } } return config; } var array = [].constructor; /** * @workInProgress * @ngdoc function * @name angular.toJson * @function * * @description * Serializes the input into a JSON formated string. * * @param {Object|Array|Date|string|number} obj Input to jsonify. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string} Jsonified string representing `obj`. */ function toJson(obj, pretty) { var buf = []; toJsonArray(buf, obj, pretty ? "\n " : _null, []); return buf.join(''); } /** * @workInProgress * @ngdoc function * @name angular.fromJson * @function * * @description * Deserializes a string in the JSON format. * * @param {string} json JSON string to deserialize. * @returns {Object|Array|Date|string|number} Deserialized thingy. */ function fromJson(json) { if (!json) return json; try { var p = parser(json, true); var expression = p.primary(); p.assertAllConsumed(); return expression(); } catch (e) { error("fromJson error: ", json, e); throw e; } } angular['toJson'] = toJson; angular['fromJson'] = fromJson; function toJsonArray(buf, obj, pretty, stack) { if (isObject(obj)) { if (obj === window) { buf.push('WINDOW'); return; } if (obj === document) { buf.push('DOCUMENT'); return; } if (includes(stack, obj)) { buf.push('RECURSION'); return; } stack.push(obj); } if (obj === _null) { buf.push($null); } else if (obj instanceof RegExp) { buf.push(angular['String']['quoteUnicode'](obj.toString())); } else if (isFunction(obj)) { return; } else if (isBoolean(obj)) { buf.push('' + obj); } else if (isNumber(obj)) { if (isNaN(obj)) { buf.push($null); } else { buf.push('' + obj); } } else if (isString(obj)) { return buf.push(angular['String']['quoteUnicode'](obj)); } else if (isObject(obj)) { if (isArray(obj)) { buf.push("["); var len = obj.length; var sep = false; for(var i=0; i<len; i++) { var item = obj[i]; if (sep) buf.push(","); if (!(item instanceof RegExp) && (isFunction(item) || isUndefined(item))) { buf.push($null); } else { toJsonArray(buf, item, pretty, stack); } sep = true; } buf.push("]"); } else if (isDate(obj)) { buf.push(angular['String']['quoteUnicode'](angular['Date']['toString'](obj))); } else { buf.push("{"); if (pretty) buf.push(pretty); var comma = false; var childPretty = pretty ? pretty + " " : false; var keys = []; for(var k in obj) { if (obj[k] === _undefined) continue; keys.push(k); } keys.sort(); for ( var keyIndex = 0; keyIndex < keys.length; keyIndex++) { var key = keys[keyIndex]; var value = obj[key]; if (typeof value != $function) { if (comma) { buf.push(","); if (pretty) buf.push(pretty); } buf.push(angular['String']['quote'](key)); buf.push(":"); toJsonArray(buf, value, childPretty, stack); comma = true; } } buf.push("}"); } } if (isObject(obj)) { stack.pop(); } } /** * Template provides directions an how to bind to a given element. * It contains a list of init functions which need to be called to * bind to a new instance of elements. It also provides a list * of child paths which contain child templates */ function Template(priority) { this.paths = []; this.children = []; this.inits = []; this.priority = priority; this.newScope = false; } Template.prototype = { init: function(element, scope) { var inits = {}; this.collectInits(element, inits, scope); foreachSorted(inits, function(queue){ foreach(queue, function(fn) {fn();}); }); }, collectInits: function(element, inits, scope) { var queue = inits[this.priority], childScope = scope; if (!queue) { inits[this.priority] = queue = []; } element = jqLite(element); if (this.newScope) { childScope = createScope(scope); scope.$onEval(childScope.$eval); element.data($$scope, childScope); } foreach(this.inits, function(fn) { queue.push(function() { childScope.$tryEval(function(){ return childScope.$inject(fn, childScope, element); }, element); }); }); var i, childNodes = element[0].childNodes, children = this.children, paths = this.paths, length = paths.length; for (i = 0; i < length; i++) { children[i].collectInits(childNodes[paths[i]], inits, childScope); } }, addInit:function(init) { if (init) { this.inits.push(init); } }, addChild: function(index, template) { if (template) { this.paths.push(index); this.children.push(template); } }, empty: function() { return this.inits.length === 0 && this.paths.length === 0; } }; /* * Function walks up the element chain looking for the scope associated with the give element. */ function retrieveScope(element) { var scope; while (element && !(scope = element.data($$scope))) { element = element.parent(); } return scope; } /////////////////////////////////// //Compiler ////////////////////////////////// function Compiler(markup, attrMarkup, directives, widgets){ this.markup = markup; this.attrMarkup = attrMarkup; this.directives = directives; this.widgets = widgets; } Compiler.prototype = { compile: function(rawElement) { rawElement = jqLite(rawElement); var index = 0, template, parent = rawElement.parent(); if (parent && parent[0]) { parent = parent[0]; for(var i = 0; i < parent.childNodes.length; i++) { if (parent.childNodes[i] == rawElement[0]) { index = i; } } } template = this.templatize(rawElement, index, 0) || new Template(); return function(element, parentScope){ element = jqLite(element); var scope = parentScope && parentScope.$eval ? parentScope : createScope(parentScope); element.data($$scope, scope); return extend(scope, { $element:element, $init: function() { template.init(element, scope); scope.$eval(); delete scope.$init; return scope; } }); }; }, /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:eval-order * * @description * Normally the view is updated from top to bottom. This usually is * not a problem, but under some circumstances the values for data * is not available until after the full view is computed. If such * values are needed before they are computed the order of * evaluation can be change using ng:eval-order * * @element ANY * @param {integer|string=} [priority=0] priority integer, or FIRST, LAST constant * * @exampleDescription * try changing the invoice and see that the Total will lag in evaluation * @example <div>TOTAL: without ng:eval-order {{ items.$sum('total') | currency }}</div> <div ng:eval-order='LAST'>TOTAL: with ng:eval-order {{ items.$sum('total') | currency }}</div> <table ng:init="items=[{qty:1, cost:9.99, desc:'gadget'}]"> <tr> <td>QTY</td> <td>Description</td> <td>Cost</td> <td>Total</td> <td></td> </tr> <tr ng:repeat="item in items"> <td><input name="item.qty"/></td> <td><input name="item.desc"/></td> <td><input name="item.cost"/></td> <td>{{item.total = item.qty * item.cost | currency}}</td> <td><a href="" ng:click="items.$remove(item)">X</a></td> </tr> <tr> <td colspan="3"><a href="" ng:click="items.$add()">add</a></td> <td>{{ items.$sum('total') | currency }}</td> </tr> </table> * * @scenario it('should check ng:format', function(){ expect(using('.doc-example-live div:first').binding("items.$sum('total')")).toBe('$9.99'); expect(using('.doc-example-live div:last').binding("items.$sum('total')")).toBe('$9.99'); input('item.qty').enter('2'); expect(using('.doc-example-live div:first').binding("items.$sum('total')")).toBe('$9.99'); expect(using('.doc-example-live div:last').binding("items.$sum('total')")).toBe('$19.98'); }); */ templatize: function(element, elementIndex, priority){ var self = this, widget, fn, directiveFns = self.directives, descend = true, directives = true, elementName = nodeName(element), template, selfApi = { compile: bind(self, self.compile), comment:function(text) {return jqLite(document.createComment(text));}, element:function(type) {return jqLite(document.createElement(type));}, text:function(text) {return jqLite(document.createTextNode(text));}, descend: function(value){ if(isDefined(value)) descend = value; return descend;}, directives: function(value){ if(isDefined(value)) directives = value; return directives;}, scope: function(value){ if(isDefined(value)) template.newScope = template.newScope || value; return template.newScope;} }; try { priority = element.attr('ng:eval-order') || priority || 0; } catch (e) { // for some reason IE throws error under some weird circumstances. so just assume nothing priority = priority || 0; } if (isString(priority)) { priority = PRIORITY[uppercase(priority)] || parseInt(priority, 10); } template = new Template(priority); eachAttribute(element, function(value, name){ if (!widget) { if (widget = self.widgets('@' + name)) { element.addClass('ng-attr-widget'); widget = bind(selfApi, widget, value, element); } } }); if (!widget) { if (widget = self.widgets(elementName)) { if (elementName.indexOf(':') > 0) element.addClass('ng-widget'); widget = bind(selfApi, widget, element); } } if (widget) { descend = false; directives = false; var parent = element.parent(); template.addInit(widget.call(selfApi, element)); if (parent && parent[0]) { element = jqLite(parent[0].childNodes[elementIndex]); } } if (descend){ // process markup for text nodes only for(var i=0, child=element[0].childNodes; i<child.length; i++) { if (isTextNode(child[i])) { foreach(self.markup, function(markup){ if (i<child.length) { var textNode = jqLite(child[i]); markup.call(selfApi, textNode.text(), textNode, element); } }); } } } if (directives) { // Process attributes/directives eachAttribute(element, function(value, name){ foreach(self.attrMarkup, function(markup){ markup.call(selfApi, value, name, element); }); }); eachAttribute(element, function(value, name){ fn = directiveFns[name]; if (fn) { element.addClass('ng-directive'); template.addInit((directiveFns[name]).call(selfApi, value, element)); } }); } // Process non text child nodes if (descend) { eachNode(element, function(child, i){ template.addChild(i, self.templatize(child, i, priority)); }); } return template.empty() ? _null : template; } }; function eachNode(element, fn){ var i, chldNodes = element[0].childNodes || [], chld; for (i = 0; i < chldNodes.length; i++) { if(!isTextNode(chld = chldNodes[i])) { fn(jqLite(chld), i); } } } function eachAttribute(element, fn){ var i, attrs = element[0].attributes || [], chld, attr, name, value, attrValue = {}; for (i = 0; i < attrs.length; i++) { attr = attrs[i]; name = attr.name; value = attr.value; if (msie && name == 'href') { value = decodeURIComponent(element[0].getAttribute(name, 2)); } attrValue[name] = value; } foreachSorted(attrValue, fn); } function getter(instance, path, unboundFn) { if (!path) return instance; var element = path.split('.'); var key; var lastInstance = instance; var len = element.length; for ( var i = 0; i < len; i++) { key = element[i]; if (!key.match(/^[\$\w][\$\w\d]*$/)) throw "Expression '" + path + "' is not a valid expression for accesing variables."; if (instance) { lastInstance = instance; instance = instance[key]; } if (isUndefined(instance) && key.charAt(0) == '$') { var type = angular['Global']['typeOf'](lastInstance); type = angular[type.charAt(0).toUpperCase()+type.substring(1)]; var fn = type ? type[[key.substring(1)]] : _undefined; if (fn) { instance = bind(lastInstance, fn, lastInstance); return instance; } } } if (!unboundFn && isFunction(instance)) { return bind(lastInstance, instance); } return instance; } function setter(instance, path, value){ var element = path.split('.'); for ( var i = 0; element.length > 1; i++) { var key = element.shift(); var newInstance = instance[key]; if (!newInstance) { newInstance = {}; instance[key] = newInstance; } instance = newInstance; } instance[element.shift()] = value; return value; } /////////////////////////////////// var scopeId = 0, getterFnCache = {}, compileCache = {}, JS_KEYWORDS = {}; foreach( ("abstract,boolean,break,byte,case,catch,char,class,const,continue,debugger,default," + "delete,do,double,else,enum,export,extends,false,final,finally,float,for,function,goto," + "if,implements,import,ininstanceof,intinterface,long,native,new,null,package,private," + "protected,public,return,short,static,super,switch,synchronized,this,throw,throws," + "transient,true,try,typeof,var,volatile,void,undefined,while,with").split(/,/), function(key){ JS_KEYWORDS[key] = true;} ); function getterFn(path){ var fn = getterFnCache[path]; if (fn) return fn; var code = 'var l, fn, t;\n'; foreach(path.split('.'), function(key) { key = (JS_KEYWORDS[key]) ? '["' + key + '"]' : '.' + key; code += 'if(!s) return s;\n' + 'l=s;\n' + 's=s' + key + ';\n' + 'if(typeof s=="function") s = function(){ return l'+key+'.apply(l, arguments); };\n'; if (key.charAt(1) == '$') { // special code for super-imposed functions var name = key.substr(2); code += 'if(!s) {\n' + ' t = angular.Global.typeOf(l);\n' + ' fn = (angular[t.charAt(0).toUpperCase() + t.substring(1)]||{})["' + name + '"];\n' + ' if (fn) s = function(){ return fn.apply(l, [l].concat(Array.prototype.slice.call(arguments, 0, arguments.length))); };\n' + '}\n'; } }); code += 'return s;'; fn = Function('s', code); fn["toString"] = function(){ return code; }; return getterFnCache[path] = fn; } /////////////////////////////////// function expressionCompile(exp){ if (typeof exp === $function) return exp; var fn = compileCache[exp]; if (!fn) { var p = parser(exp); var fnSelf = p.statements(); p.assertAllConsumed(); fn = compileCache[exp] = extend( function(){ return fnSelf(this);}, {fnSelf: fnSelf}); } return fn; } function errorHandlerFor(element, error) { elementError(element, NG_EXCEPTION, isDefined(error) ? formatError(error) : error); } /** * @workInProgress * @ngdoc overview * @name angular.scope * * @description * Scope is a JavaScript object and the execution context for expressions. You can think about * scopes as JavaScript objects that have extra APIs for registering watchers. A scope is the model * in the model-view-controller design pattern. * * A few other characteristics of scopes: * * - Scopes can be nested. A scope (prototypically) inherits properties from its parent scope. * - Scopes can be attached (bound) to the HTML DOM tree (the view). * - A scope {@link angular.scope.$become becomes} `this` for a controller. * - Scope's {@link angular.scope.$eval $eval} is used to update its view. * - Scopes can {@link angular.scope.$watch watch} properties and fire events. * * # Basic Operations * Scopes can be created by calling {@link angular.scope() angular.scope()} or by compiling HTML. * * {@link angular.widget Widgets} and data bindings register listeners on the current scope to get * notified of changes to the scope state. When notified, these listeners push the updated state * through to the DOM. * * Here is a simple scope snippet to show how you can interact with the scope. * <pre> var scope = angular.scope(); scope.salutation = 'Hello'; scope.name = 'World'; expect(scope.greeting).toEqual(undefined); scope.$watch('name', function(){ this.greeting = this.salutation + ' ' + this.name + '!'; }); expect(scope.greeting).toEqual('Hello World!'); scope.name = 'Misko'; // scope.$eval() will propagate the change to listeners expect(scope.greeting).toEqual('Hello World!'); scope.$eval(); expect(scope.greeting).toEqual('Hello Misko!'); * </pre> * * # Inheritance * A scope can inherit from a parent scope, as in this example: * <pre> var parent = angular.scope(); var child = angular.scope(parent); parent.salutation = "Hello"; child.name = "World"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * </pre> * * # Dependency Injection * Scope also acts as a simple dependency injection framework. * * **TODO**: more info needed * * # When scopes are evaluated * Anyone can update a scope by calling its {@link angular.scope.$eval $eval()} method. By default * angular widgets listen to user change events (e.g. the user enters text into text field), copy * the data from the widget to the scope (the MVC model), and then call the `$eval()` method on the * root scope to update dependents. This creates a spreadsheet-like behavior: the bound views update * immediately as the user types into the text field. * * Similarly, when a request to fetch data from a server is made and the response comes back, the * data is written into the model and then $eval() is called to push updates through to the view and * any other dependents. * * Because a change in the model that's triggered either by user input or by server response calls * `$eval()`, it is unnecessary to call `$eval()` from within your controller. The only time when * calling `$eval()` is needed, is when implementing a custom widget or service. * * Because scopes are inherited, the child scope `$eval()` overrides the parent `$eval()` method. * So to update the whole page you need to call `$eval()` on the root scope as `$root.$eval()`. * * Note: A widget that creates scopes (i.e. {@link angular.widget.@ng:repeat ng:repeat}) is * responsible for forwarding `$eval()` calls from the parent to those child scopes. That way, * calling $eval() on the root scope will update the whole page. * * * @TODO THESE PARAMS AND RETURNS ARE NOT RENDERED IN THE TEMPLATE!! FIX THAT! * @param {Object} parent The scope that should become the parent for the newly created scope. * @param {Object.<string, function()>=} providers Map of service factory which need to be provided * for the current scope. Usually {@link angular.service}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. * @returns {Object} Newly created scope. * * * @exampleDescription * This example demonstrates scope inheritance and property overriding. * * In this example, the root scope encompasses the whole HTML DOM tree. This scope has `salutation`, * `name`, and `names` properties. The {@link angular.widget@ng:repeat ng:repeat} creates a child * scope, one for each element in the names array. The repeater also assigns $index and name into * the child scope. * * Notice that: * * - While the name is set in the child scope it does not change the name defined in the root scope. * - The child scope inherits the salutation property from the root scope. * - The $index property does not leak from the child scope to the root scope. * * @example <ul ng:init="salutation='Hello'; name='Misko'; names=['World', 'Earth']"> <li ng:repeat="name in names"> {{$index}}: {{salutation}} {{name}}! </li> </ul> <pre> $index={{$index}} salutation={{salutation}} name={{name}}</pre> @scenario it('should inherit the salutation property and override the name property', function() { expect(using('.doc-example-live').repeater('li').row(0)). toEqual(['0', 'Hello', 'World']); expect(using('.doc-example-live').repeater('li').row(1)). toEqual(['1', 'Hello', 'Earth']); expect(using('.doc-example-live').element('pre').text()). toBe('$index=\nsalutation=Hello\nname=Misko'); }); */ function createScope(parent, providers, instanceCache) { function Parent(){} parent = Parent.prototype = (parent || {}); var instance = new Parent(); var evalLists = {sorted:[]}; extend(instance, { 'this': instance, $id: (scopeId++), $parent: parent, /** * @workInProgress * @ngdoc function * @name angular.scope.$bind * @function * * @description * Binds a function `fn` to the current scope. See: {@link angular.bind}. <pre> var scope = angular.scope(); var fn = scope.$bind(function(){ return this; }); expect(fn()).toEqual(scope); </pre> * * @param {function()} fn Function to be bound. */ $bind: bind(instance, bind, instance), /** * @workInProgress * @ngdoc function * @name angular.scope.$get * @function * * @description * Returns the value for `property_chain` on the current scope. Unlike in JavaScript, if there * are any `undefined` intermediary properties, `undefined` is returned instead of throwing an * exception. * <pre> var scope = angular.scope(); expect(scope.$get('person.name')).toEqual(undefined); scope.person = {}; expect(scope.$get('person.name')).toEqual(undefined); scope.person.name = 'misko'; expect(scope.$get('person.name')).toEqual('misko'); </pre> * * @param {string} property_chain String representing name of a scope property. Optionally * properties can be chained with `.` (dot), e.g. `'person.name.first'` * @returns {*} Value for the (nested) property. */ $get: bind(instance, getter, instance), /** * @workInProgress * @ngdoc function * @name angular.scope.$set * @function * * @description * Assigns a value to a property of the current scope specified via `property_chain`. Unlike in * JavaScript, if there are any `undefined` intermediary properties, empty objects are created * and assigned in to them instead of throwing an exception. * <pre> var scope = angular.scope(); expect(scope.person).toEqual(undefined); scope.$set('person.name', 'misko'); expect(scope.person).toEqual({name:'misko'}); expect(scope.person.name).toEqual('misko'); </pre> * * @param {string} property_chain String representing name of a scope property. Optionally * properties can be chained with `.` (dot), e.g. `'person.name.first'` * @param {*} value Value to assign to the scope property. */ $set: bind(instance, setter, instance), /** * @workInProgress * @ngdoc function * @name angular.scope.$eval * @function * * @description * Without the `exp` parameter triggers an eval cycle, for this scope and it's child scopes. * * With the `exp` parameter, compiles the expression to a function and calls it with `this` set * to the current scope and returns the result. * * # Example <pre> var scope = angular.scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(){ return this.a + this.b; })).toEqual(3); scope.$onEval('sum = a+b'); expect(scope.sum).toEqual(undefined); scope.$eval(); expect(scope.sum).toEqual(3); </pre> * * @param {(string|function())=} exp An angular expression to be compiled to a function or a js * function. * * @returns {*} The result of calling compiled `exp` with `this` set to the current scope. */ $eval: function(exp) { var type = typeof exp; var i, iSize; var j, jSize; var queue; var fn; if (type == $undefined) { for ( i = 0, iSize = evalLists.sorted.length; i < iSize; i++) { for ( queue = evalLists.sorted[i], jSize = queue.length, j= 0; j < jSize; j++) { instance.$tryEval(queue[j].fn, queue[j].handler); } } } else if (type === $function) { return exp.call(instance); } else if (type === 'string') { return expressionCompile(exp).call(instance); } }, /** * @workInProgress * @ngdoc function * @name angular.scope.$tryEval * @function * * @description * Evaluates the expression in the context of the current scope just like * {@link angular.scope.$eval()} with expression parameter, but also wraps it in a try/catch * block. * * If exception is thrown then `exceptionHandler` is used to handle the exception. * * # Example <pre> var scope = angular.scope(); scope.error = function(){ throw 'myerror'; }; scope.$exceptionHandler = function(e) {this.lastException = e; }; expect(scope.$eval('error()')); expect(scope.lastException).toEqual('myerror'); this.lastException = null; expect(scope.$eval('error()'), function(e) {this.lastException = e; }); expect(scope.lastException).toEqual('myerror'); var body = angular.element(window.document.body); expect(scope.$eval('error()'), body); expect(body.attr('ng-exception')).toEqual('"myerror"'); expect(body.hasClass('ng-exception')).toEqual(true); </pre> * * @param {string|function()} expression Angular expression to evaluate. * @param {function()|DOMElement} exceptionHandler Function to be called or DOMElement to be * decorated. * @returns {*} The result of `expression` evaluation. */ $tryEval: function (expression, exceptionHandler) { var type = typeof expression; try { if (type == $function) { return expression.call(instance); } else if (type == 'string'){ return expressionCompile(expression).call(instance); } } catch (e) { (instance.$log || {error:error}).error(e); if (isFunction(exceptionHandler)) { exceptionHandler(e); } else if (exceptionHandler) { errorHandlerFor(exceptionHandler, e); } else if (isFunction(instance.$exceptionHandler)) { instance.$exceptionHandler(e); } } }, /** * @workInProgress * @ngdoc function * @name angular.scope.$watch * @function * * @description * Registers `listener` as a callback to be executed every time the `watchExp` changes. Be aware * that callback gets, by default, called upon registration, this can be prevented via the * `initRun` parameter. * * # Example <pre> var scope = angular.scope(); scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', 'counter = counter + 1'); expect(scope.counter).toEqual(1); scope.$eval(); expect(scope.counter).toEqual(1); scope.name = 'adam'; scope.$eval(); expect(scope.counter).toEqual(2); </pre> * * @param {function()|string} watchExp Expression that should be evaluated and checked for * change during each eval cycle. Can be an angular string expression or a function. * @param {function()|string} listener Function (or angular string expression) that gets called * every time the value of the `watchExp` changes. The function will be called with two * parameters, `newValue` and `oldValue`. * @param {(function()|DOMElement)=} [exceptionHanlder=angular.service.$exceptionHandler] Handler * that gets called when `watchExp` or `listener` throws an exception. If a DOMElement is * specified as handler, the element gets decorated by angular with the information about the * exception. * @param {boolean=} [initRun=true] Flag that prevents the first execution of the listener upon * registration. * */ $watch: function(watchExp, listener, exceptionHandler, initRun) { var watch = expressionCompile(watchExp), last = watch.call(instance); listener = expressionCompile(listener); function watcher(firstRun){ var value = watch.call(instance), // we have to save the value because listener can call ourselves => inf loop lastValue = last; if (firstRun || lastValue !== value) { last = value; instance.$tryEval(function(){ return listener.call(instance, value, lastValue); }, exceptionHandler); } } instance.$onEval(PRIORITY_WATCH, watcher); if (isUndefined(initRun)) initRun = true; if (initRun) watcher(true); }, /** * @workInProgress * @ngdoc function * @name angular.scope.$onEval * @function * * @description * Evaluates the `expr` expression in the context of the current scope during each * {@link angular.scope.$eval eval cycle}. * * # Example <pre> var scope = angular.scope(); scope.counter = 0; scope.$onEval('counter = counter + 1'); expect(scope.counter).toEqual(0); scope.$eval(); expect(scope.counter).toEqual(1); </pre> * * @param {number} [priority=0] Execution priority. Lower priority numbers get executed first. * @param {string|function()} expr Angular expression or function to be executed. * @param {(function()|DOMElement)=} [exceptionHandler=angular.service.$exceptionHandler] Handler * function to call or DOM element to decorate when an exception occurs. * */ $onEval: function(priority, expr, exceptionHandler){ if (!isNumber(priority)) { exceptionHandler = expr; expr = priority; priority = 0; } var evalList = evalLists[priority]; if (!evalList) { evalList = evalLists[priority] = []; evalList.priority = priority; evalLists.sorted.push(evalList); evalLists.sorted.sort(function(a,b){return a.priority-b.priority;}); } evalList.push({ fn: expressionCompile(expr), handler: exceptionHandler }); }, /** * @workInProgress * @ngdoc function * @name angular.scope.$become * @function * @deprecated This method will be removed before 1.0 * * @description * Modifies the scope to act like an instance of the given class by: * * - copying the class's prototype methods * - applying the class's initialization function to the scope instance (without using the new * operator) * * That makes the scope be a `this` for the given class's methods — effectively an instance of * the given class with additional (scope) stuff. A scope can later `$become` another class. * * `$become` gets used to make the current scope act like an instance of a controller class. * This allows for use of a controller class in two ways. * * - as an ordinary JavaScript class for standalone testing, instantiated using the new * operator, with no attached view. * - as a controller for an angular model stored in a scope, "instantiated" by * `scope.$become(ControllerClass)`. * * Either way, the controller's methods refer to the model variables like `this.name`. When * stored in a scope, the model supports data binding. When bound to a view, {{name}} in the * HTML template refers to the same variable. */ $become: function(Class) { if (isFunction(Class)) { instance.constructor = Class; foreach(Class.prototype, function(fn, name){ instance[name] = bind(instance, fn); }); instance.$inject.apply(instance, concat([Class, instance], arguments, 1)); //TODO: backwards compatibility hack, remove when we don't depend on init methods if (isFunction(Class.prototype.init)) { instance.init(); } } }, /** * @workInProgress * @ngdoc function * @name angular.scope.$new * @function * * @description * Creates a new {@link angular.scope scope}, that: * * - is a child of the current scope * - will {@link angular.scope.$become $become} of type specified via `constructor` * * @param {function()} constructor Constructor function of the type the new scope should assume. * @returns {Object} The newly created child scope. * */ $new: function(constructor) { var child = createScope(instance); child.$become.apply(instance, concat([constructor], arguments, 1)); instance.$onEval(child.$eval); return child; } }); if (!parent.$root) { instance.$root = instance; instance.$parent = instance; (instance.$inject = createInjector(instance, providers, instanceCache))(); } return instance; } /** * @ngdoc function * @name angular.injector * @function * * @description * Creates an inject function that can be used for dependency injection. * * @param {Object=} [providerScope={}] provider's `this` * @param {Object.<string, function()>=} [providers=angular.service] Map of provider (factory) * function. * @param {Object.<string, function()>=} [cache={}] Place where instances are saved for reuse. Can * also be used to override services speciafied by `providers` (useful in tests). * @returns {function()} Injector function. * * @TODO These docs need a lot of work. Specifically the returned function should be described in * great detail + we need to provide some examples. */ function createInjector(providerScope, providers, cache) { providers = providers || angularService; cache = cache || {}; providerScope = providerScope || {}; /** * injection function * @param value: string, array, object or function. * @param scope: optional function "this" * @param args: optional arguments to pass to function after injection * parameters * @returns depends on value: * string: return an instance for the injection key. * array of keys: returns an array of instances. * function: look at $inject property of function to determine instances * and then call the function with instances and `scope`. Any * additional arguments (`args`) are appended to the function * arguments. * object: initialize eager providers and publish them the ones with publish here. * none: same as object but use providerScope as place to publish. */ return function inject(value, scope, args){ var returnValue, provider, creation; if (isString(value)) { if (!cache.hasOwnProperty(value)) { provider = providers[value]; if (!provider) throw "Unknown provider for '"+value+"'."; cache[value] = inject(provider, providerScope); } returnValue = cache[value]; } else if (isArray(value)) { returnValue = []; foreach(value, function(name) { returnValue.push(inject(name)); }); } else if (isFunction(value)) { returnValue = inject(value.$inject || []); returnValue = value.apply(scope, concat(returnValue, arguments, 2)); } else if (isObject(value)) { foreach(providers, function(provider, name){ creation = provider.$creation; if (creation == 'eager') { inject(name); } if (creation == 'eager-published') { setter(value, name, inject(name)); } }); } else { returnValue = inject(providerScope); } return returnValue; }; }var OPERATORS = { 'null':function(self){return _null;}, 'true':function(self){return true;}, 'false':function(self){return false;}, $undefined:noop, '+':function(self, a,b){return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, '-':function(self, a,b){return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, '*':function(self, a,b){return a*b;}, '/':function(self, a,b){return a/b;}, '%':function(self, a,b){return a%b;}, '^':function(self, a,b){return a^b;}, '=':function(self, a,b){return setter(self, a, b);}, '==':function(self, a,b){return a==b;}, '!=':function(self, a,b){return a!=b;}, '<':function(self, a,b){return a<b;}, '>':function(self, a,b){return a>b;}, '<=':function(self, a,b){return a<=b;}, '>=':function(self, a,b){return a>=b;}, '&&':function(self, a,b){return a&&b;}, '||':function(self, a,b){return a||b;}, '&':function(self, a,b){return a&b;}, // '|':function(self, a,b){return a|b;}, '|':function(self, a,b){return b(self, a);}, '!':function(self, a){return !a;} }; var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; function lex(text, parseStringsForObjects){ var dateParseLength = parseStringsForObjects ? 24 : -1, tokens = [], token, index = 0, json = [], ch, lastCh = ':'; // can start regexp while (index < text.length) { ch = text.charAt(index); if (is('"\'')) { readString(ch); } else if (isNumber(ch) || is('.') && isNumber(peek())) { readNumber(); } else if ( was('({[:,;') && is('/') ) { readRegexp(); } else if (isIdent(ch)) { readIdent(); if (was('{,') && json[0]=='{' && (token=tokens[tokens.length-1])) { token.json = token.text.indexOf('.') == -1; } } else if (is('(){}[].,;:')) { tokens.push({index:index, text:ch, json:is('{}[]:,')}); if (is('{[')) json.unshift(ch); if (is('}]')) json.shift(); index++; } else if (isWhitespace(ch)) { index++; continue; } else { var ch2 = ch + peek(), fn = OPERATORS[ch], fn2 = OPERATORS[ch2]; if (fn2) { tokens.push({index:index, text:ch2, fn:fn2}); index += 2; } else if (fn) { tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); index += 1; } else { throwError("Unexpected next character ", index, index+1); } } lastCh = ch; } return tokens; function is(chars) { return chars.indexOf(ch) != -1; } function was(chars) { return chars.indexOf(lastCh) != -1; } function peek() { return index + 1 < text.length ? text.charAt(index + 1) : false; } function isNumber(ch) { return '0' <= ch && ch <= '9'; } function isWhitespace(ch) { return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 } function isIdent(ch) { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' == ch || ch == '$'; } function isExpOperator(ch) { return ch == '-' || ch == '+' || isNumber(ch); } function throwError(error, start, end) { end = end || index; throw Error("Lexer Error: " + error + " at column" + (isDefined(start) ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]" : " " + end) + " in expression [" + text + "]."); } function readNumber() { var number = ""; var start = index; while (index < text.length) { var ch = lowercase(text.charAt(index)); if (ch == '.' || isNumber(ch)) { number += ch; } else { var peekCh = peek(); if (ch == 'e' && isExpOperator(peekCh)) { number += ch; } else if (isExpOperator(ch) && peekCh && isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (isExpOperator(ch) && (!peekCh || !isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { throwError('Invalid exponent'); } else { break; } } index++; } number = 1 * number; tokens.push({index:start, text:number, json:true, fn:function(){return number;}}); } function readIdent() { var ident = ""; var start = index; while (index < text.length) { var ch = text.charAt(index); if (ch == '.' || isIdent(ch) || isNumber(ch)) { ident += ch; } else { break; } index++; } var fn = OPERATORS[ident]; if (!fn) { fn = getterFn(ident); fn.isAssignable = ident; } tokens.push({index:start, text:ident, fn:fn, json: OPERATORS[ident]}); } function readString(quote) { var start = index; index++; var string = ""; var rawString = quote; var escape = false; while (index < text.length) { var ch = text.charAt(index); rawString += ch; if (escape) { if (ch == 'u') { var hex = text.substring(index + 1, index + 5); if (!hex.match(/[\da-f]{4}/i)) throwError( "Invalid unicode escape [\\u" + hex + "]"); index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch == '\\') { escape = true; } else if (ch == quote) { index++; tokens.push({index:start, text:rawString, string:string, json:true, fn:function(){ return (string.length == dateParseLength) ? angular['String']['toDate'](string) : string; }}); return; } else { string += ch; } index++; } throwError("Unterminated quote", start); } function readRegexp(quote) { var start = index; index++; var regexp = ""; var escape = false; while (index < text.length) { var ch = text.charAt(index); if (escape) { regexp += ch; escape = false; } else if (ch === '\\') { regexp += ch; escape = true; } else if (ch === '/') { index++; var flags = ""; if (isIdent(text.charAt(index))) { readIdent(); flags = tokens.pop().text; } var compiledRegexp = new RegExp(regexp, flags); tokens.push({index:start, text:regexp, flags:flags, fn:function(){return compiledRegexp;}}); return; } else { regexp += ch; } index++; } throwError("Unterminated RegExp", start); } } ///////////////////////////////////////// function parser(text, json){ var ZERO = valueFn(0), tokens = lex(text, json); return { assertAllConsumed: assertAllConsumed, primary: primary, statements: statements, validator: validator, filter: filter, //TODO: delete me, since having watch in UI is logic in UI. (leftover form getangular) watch: watch }; /////////////////////////////////// function throwError(msg, token) { throw Error("Parse Error: Token '" + token.text + "' " + msg + " at column " + (token.index + 1) + " of expression [" + text + "] starting at [" + text.substring(token.index) + "]."); } function peekToken() { if (tokens.length === 0) throw Error("Unexpected end of expression: " + text); return tokens[0]; } function peek(e1, e2, e3, e4) { if (tokens.length > 0) { var token = tokens[0]; var t = token.text; if (t==e1 || t==e2 || t==e3 || t==e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; } function expect(e1, e2, e3, e4){ var token = peek(e1, e2, e3, e4); if (token) { if (json && !token.json) { index = token.index; throwError("is not valid json", token); } tokens.shift(); this.currentToken = token; return token; } return false; } function consume(e1){ if (!expect(e1)) { throwError("is unexpected, expecting [" + e1 + "]", peek()); } } function unaryFn(fn, right) { return function(self) { return fn(self, right(self)); }; } function binaryFn(left, fn, right) { return function(self) { return fn(self, left(self), right(self)); }; } function hasTokens () { return tokens.length > 0; } function assertAllConsumed(){ if (tokens.length !== 0) { throwError("is extra token not part of expression", tokens[0]); } } function statements(){ var statements = []; while(true) { if (tokens.length > 0 && !peek('}', ')', ';', ']')) statements.push(filterChain()); if (!expect(';')) { return function (self){ var value; for ( var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) value = statement(self); } return value; }; } } } function filterChain(){ var left = expression(); var token; while(true) { if ((token = expect('|'))) { left = binaryFn(left, token.fn, filter()); } else { return left; } } } function filter(){ return pipeFunction(angularFilter); } function validator(){ return pipeFunction(angularValidator); } function pipeFunction(fnScope){ var fn = functionIdent(fnScope); var argsFn = []; var token; while(true) { if ((token = expect(':'))) { argsFn.push(expression()); } else { var fnInvoke = function(self, input){ var args = [input]; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self)); } return fn.apply(self, args); }; return function(){ return fnInvoke; }; } } } function expression(){ return assignment(); } function assignment(){ var left = logicalOR(); var token; if (token = expect('=')) { if (!left.isAssignable) { throwError("implies assignment but [" + text.substring(0, token.index) + "] can not be assigned to", token); } var ident = function(){return left.isAssignable;}; return binaryFn(ident, token.fn, logicalOR()); } else { return left; } } function logicalOR(){ var left = logicalAND(); var token; while(true) { if ((token = expect('||'))) { left = binaryFn(left, token.fn, logicalAND()); } else { return left; } } } function logicalAND(){ var left = equality(); var token; if ((token = expect('&&'))) { left = binaryFn(left, token.fn, logicalAND()); } return left; } function equality(){ var left = relational(); var token; if ((token = expect('==','!='))) { left = binaryFn(left, token.fn, equality()); } return left; } function relational(){ var left = additive(); var token; if (token = expect('<', '>', '<=', '>=')) { left = binaryFn(left, token.fn, relational()); } return left; } function additive(){ var left = multiplicative(); var token; while(token = expect('+','-')) { left = binaryFn(left, token.fn, multiplicative()); } return left; } function multiplicative(){ var left = unary(); var token; while(token = expect('*','/','%')) { left = binaryFn(left, token.fn, unary()); } return left; } function unary(){ var token; if (expect('+')) { return primary(); } else if (token = expect('-')) { return binaryFn(ZERO, token.fn, unary()); } else if (token = expect('!')) { return unaryFn(token.fn, unary()); } else { return primary(); } } function functionIdent(fnScope) { var token = expect(); var element = token.text.split('.'); var instance = fnScope; var key; for ( var i = 0; i < element.length; i++) { key = element[i]; if (instance) instance = instance[key]; } if (typeof instance != $function) { throwError("should be a function", token); } return instance; } function primary() { var primary; if (expect('(')) { var expression = filterChain(); consume(')'); primary = expression; } else if (expect('[')) { primary = arrayDeclaration(); } else if (expect('{')) { primary = object(); } else { var token = expect(); primary = token.fn; if (!primary) { throwError("not a primary expression", token); } } var next; while (next = expect('(', '[', '.')) { if (next.text === '(') { primary = functionCall(primary); } else if (next.text === '[') { primary = objectIndex(primary); } else if (next.text === '.') { primary = fieldAccess(primary); } else { throwError("IMPOSSIBLE"); } } return primary; } function fieldAccess(object) { var field = expect().text; var getter = getterFn(field); var fn = function (self){ return getter(object(self)); }; fn.isAssignable = field; return fn; } function objectIndex(obj) { var indexFn = expression(); consume(']'); if (expect('=')) { var rhs = expression(); return function (self){ return obj(self)[indexFn(self)] = rhs(self); }; } else { return function (self){ var o = obj(self); var i = indexFn(self); return (o) ? o[i] : _undefined; }; } } function functionCall(fn) { var argsFn = []; if (peekToken().text != ')') { do { argsFn.push(expression()); } while (expect(',')); } consume(')'); return function (self){ var args = []; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self)); } var fnPtr = fn(self) || noop; // IE stupidity! return fnPtr.apply ? fnPtr.apply(self, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); }; } // This is used with json array declaration function arrayDeclaration () { var elementFns = []; if (peekToken().text != ']') { do { elementFns.push(expression()); } while (expect(',')); } consume(']'); return function (self){ var array = []; for ( var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self)); } return array; }; } function object () { var keyValues = []; if (peekToken().text != '}') { do { var token = expect(), key = token.string || token.text; consume(":"); var value = expression(); keyValues.push({key:key, value:value}); } while (expect(',')); } consume('}'); return function (self){ var object = {}; for ( var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; var value = keyValue.value(self); object[keyValue.key] = value; } return object; }; } //TODO: delete me, since having watch in UI is logic in UI. (leftover form getangular) function watch () { var decl = []; while(hasTokens()) { decl.push(watchDecl()); if (!expect(';')) { assertAllConsumed(); } } assertAllConsumed(); return function (self){ for ( var i = 0; i < decl.length; i++) { var d = decl[i](self); self.addListener(d.name, d.fn); } }; } function watchDecl () { var anchorName = expect().text; consume(":"); var expressionFn; if (peekToken().text == '{') { consume("{"); expressionFn = statements(); consume("}"); } else { expressionFn = expression(); } return function(self) { return {name:anchorName, fn:expressionFn}; }; } } function Route(template, defaults) { this.template = template = template + '#'; this.defaults = defaults || {}; var urlParams = this.urlParams = {}; foreach(template.split(/\W/), function(param){ if (param && template.match(new RegExp(":" + param + "\\W"))) { urlParams[param] = true; } }); } Route.prototype = { url: function(params) { var path = []; var self = this; var url = this.template; params = params || {}; foreach(this.urlParams, function(_, urlParam){ var value = params[urlParam] || self.defaults[urlParam] || ""; url = url.replace(new RegExp(":" + urlParam + "(\\W)"), value + "$1"); }); url = url.replace(/\/?#$/, ''); var query = []; foreachSorted(params, function(value, key){ if (!self.urlParams[key]) { query.push(encodeURI(key) + '=' + encodeURI(value)); } }); url = url.replace(/\/*$/, ''); return url + (query.length ? '?' + query.join('&') : ''); } }; function ResourceFactory(xhr) { this.xhr = xhr; } ResourceFactory.DEFAULT_ACTIONS = { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }; ResourceFactory.prototype = { route: function(url, paramDefaults, actions){ var self = this; var route = new Route(url); actions = extend({}, ResourceFactory.DEFAULT_ACTIONS, actions); function extractParams(data){ var ids = {}; foreach(paramDefaults || {}, function(value, key){ ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; }); return ids; } function Resource(value){ copy(value || {}, this); } foreach(actions, function(action, name){ var isPostOrPut = action.method == 'POST' || action.method == 'PUT'; Resource[name] = function (a1, a2, a3) { var params = {}; var data; var callback = noop; switch(arguments.length) { case 3: callback = a3; case 2: if (isFunction(a2)) { callback = a2; } else { params = a1; data = a2; break; } case 1: if (isFunction(a1)) callback = a1; else if (isPostOrPut) data = a1; else params = a1; break; case 0: break; default: throw "Expected between 0-3 arguments [params, data, callback], got " + arguments.length + " arguments."; } var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); self.xhr( action.method, route.url(extend({}, action.params || {}, extractParams(data), params)), data, function(status, response, clear) { if (status == 200) { if (action.isArray) { value.length = 0; foreach(response, function(item){ value.push(new Resource(item)); }); } else { copy(response, value); } (callback||noop)(value); } else { throw {status: status, response:response, message: status + ": " + response}; } }, action.verifyCache); return value; }; Resource.bind = function(additionalParamDefaults){ return self.route(url, extend({}, paramDefaults, additionalParamDefaults), actions); }; Resource.prototype['$' + name] = function(a1, a2){ var params = extractParams(this); var callback = noop; switch(arguments.length) { case 2: params = a1; callback = a2; case 1: if (typeof a1 == $function) callback = a1; else params = a1; case 0: break; default: throw "Expected between 1-2 arguments [params, callback], got " + arguments.length + " arguments."; } var data = isPostOrPut ? this : _undefined; Resource[name].call(this, params, data, callback); }; }); return Resource; } }; ////////////////////////////// // Browser ////////////////////////////// var XHR = window.XMLHttpRequest || function () { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} throw new Error("This browser does not support XMLHttpRequest."); }; function Browser(location, document, head, XHR, $log, setTimeout) { var self = this; self.isMock = false; ////////////////////////////////////////////////////////////// // XHR API ////////////////////////////////////////////////////////////// var idCounter = 0; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; /** * Executes the `fn` function (supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, slice.call(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @workInProgress * @ngdoc method * @name angular.service.$browser#xhr * @methodOf angular.service.$browser * * @param {string} method Requested method (get|post|put|delete|head|json) * @param {string} url Requested url * @param {string=} post Post data to send * @param {function(number, string)} callback Function that will be called on response * * @description * Send ajax request */ self.xhr = function(method, url, post, callback) { if (isFunction(post)) { callback = post; post = _null; } if (lowercase(method) == 'json') { var callbackId = "angular_" + Math.random() + '_' + (idCounter++); callbackId = callbackId.replace(/\d\./, ''); var script = document[0].createElement('script'); script.type = 'text/javascript'; script.src = url.replace('JSON_CALLBACK', callbackId); window[callbackId] = function(data){ window[callbackId] = _undefined; callback(200, data); }; head.append(script); } else { var xhr = new XHR(); xhr.open(method, url, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.setRequestHeader("Accept", "application/json, text/plain, */*"); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); outstandingRequestCount ++; xhr.onreadystatechange = function() { if (xhr.readyState == 4) { completeOutstandingRequest(callback, xhr.status || 200, xhr.responseText); } }; xhr.send(post || ''); } }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#notifyWhenNoOutstandingRequests * @methodOf angular.service.$browser * * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = []; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#poll * @methodOf angular.service.$browser */ self.poll = function() { foreach(pollFns, function(pollFn){ pollFn(); }); }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#addPollFn * @methodOf angular.service.$browser * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes * * @returns {function()} the added function */ self.addPollFn = function(fn) { pollFns.push(fn); return fn; }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#startPoller * @methodOf angular.service.$browser * * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ self.startPoller = function(interval, setTimeout) { (function check(){ self.poll(); setTimeout(check, interval); })(); }; ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// /** * @workInProgress * @ngdoc method * @name angular.service.$browser#setUrl * @methodOf angular.service.$browser * * @param {string} url New url * * @description * Sets browser's url */ self.setUrl = function(url) { var existingURL = location.href; if (!existingURL.match(/#/)) existingURL += '#'; if (!url.match(/#/)) url += '#'; location.href = url; }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#getUrl * @methodOf angular.service.$browser * * @description * Get current browser's url * * @returns {string} Browser's url */ self.getUrl = function() { return location.href; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var rawDocument = document[0]; var lastCookies = {}; var lastCookieString = ''; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#cookies * @methodOf angular.service.$browser * * @param {string=} name Cookie name * @param {string=} value Cokkie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * <ul> * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li> * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li> * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li> * </ul> * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function (name, value) { var cookieLength, cookieArray, i, keyValue; if (name) { if (value === _undefined) { rawDocument.cookie = escape(name) + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { rawDocument.cookie = escape(name) + '=' + escape(value); cookieLength = name.length + value.length + 1; if (cookieLength > 4096) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } if (lastCookies.length > 20) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " + "were already set (" + lastCookies.length + " > 20 )"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { keyValue = cookieArray[i].split("="); if (keyValue.length === 2) { //ignore nameless cookies lastCookies[unescape(keyValue[0])] = unescape(keyValue[1]); } } } return lastCookies; } }; /** * @workInProgress * @ngdoc * @name angular.service.$browser#defer * @methodOf angular.service.$browser * * @description * Executes a fn asynchroniously via `setTimeout(fn, 0)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programaticaly flushed via * `$browser.defer.flush()`. * * @param {function()} fn A function, who's execution should be defered. */ self.defer = function(fn) { outstandingRequestCount++; setTimeout(function() { completeOutstandingRequest(fn); }, 0); }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// var hoverListener = noop; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#hover * @methodOf angular.service.$browser * * @description * Set hover listener. * * @param {function(Object, boolean)} listener Function that will be called when hover event * occurs. */ self.hover = function(listener) { hoverListener = listener; }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#bind * @methodOf angular.service.$browser * * @description * Register hover function to real browser */ self.bind = function() { document.bind("mouseover", function(event){ hoverListener(jqLite(msie ? event.srcElement : event.target), true); return true; }); document.bind("mouseleave mouseout click dblclick keypress keyup", function(event){ hoverListener(jqLite(event.target), false); return true; }); }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#addCss * @methodOf angular.service.$browser * * @param {string} url Url to css file * @description * Adds a stylesheet tag to the head. */ self.addCss = function(url) { var link = jqLite(rawDocument.createElement('link')); link.attr('rel', 'stylesheet'); link.attr('type', 'text/css'); link.attr('href', url); head.append(link); }; /** * @workInProgress * @ngdoc method * @name angular.service.$browser#addJs * @methodOf angular.service.$browser * * @param {string} url Url to js file * @param {string=} dom_id Optional id for the script tag * * @description * Adds a script tag to the head. */ self.addJs = function(url, dom_id) { var script = jqLite(rawDocument.createElement('script')); script.attr('type', 'text/javascript'); script.attr('src', url); if (dom_id) script.attr('id', dom_id); head.append(script); }; } /* * HTML Parser By Misko Hevery (misko@hevery.com) * based on: HTML Parser By John Resig (ejohn.org) * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js * * // Use like so: * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * */ // Regular Expressions for parsing tags and attributes var START_TAG_REGEXP = /^<\s*([\w:]+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, END_TAG_REGEXP = /^<\s*\/\s*([\w:]+)[^>]*>/, ATTR_REGEXP = /(\w+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^</, BEGING_END_TAGE_REGEXP = /^<\s*\//, COMMENT_REGEXP = /<!--(.*?)-->/g, CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, URI_REGEXP = /^((ftp|https?):\/\/|mailto:|#)/, NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character) // Empty Elements - HTML 4.01 var emptyElements = makeMap("area,br,col,hr,img"); // Block Elements - HTML 4.01 var blockElements = makeMap("address,blockquote,center,dd,del,dir,div,dl,dt,"+ "hr,ins,li,map,menu,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul"); // Inline Elements - HTML 4.01 var inlineElements = makeMap("a,abbr,acronym,b,bdo,big,br,cite,code,del,dfn,em,font,i,img,"+ "ins,kbd,label,map,q,s,samp,small,span,strike,strong,sub,sup,tt,u,var"); // Elements that you can, intentionally, leave open // (and which close themselves) var closeSelfElements = makeMap("colgroup,dd,dt,li,p,td,tfoot,th,thead,tr"); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); var validElements = extend({}, emptyElements, blockElements, inlineElements, closeSelfElements); //see: http://www.w3.org/TR/html4/index/attributes.html //Attributes that have their values filled in disabled="disabled" var fillAttrs = makeMap("compact,ismap,nohref,nowrap"); //Attributes that have href and hence need to be sanitized var uriAttrs = makeMap("background,href,longdesc,src,usemap"); var validAttrs = extend({}, fillAttrs, uriAttrs, makeMap( 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ 'color,cols,colspan,coords,dir,face,headers,height,hreflang,hspace,'+ 'lang,language,rel,rev,rows,rowspan,rules,'+ 'scope,scrolling,shape,span,start,summary,target,title,type,'+ 'valign,value,vspace,width')); /** * @example * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParser( html, handler ) { var index, chars, match, stack = [], last = html; stack.last = function(){ return stack[ stack.length - 1 ]; }; while ( html ) { chars = true; // Make sure we're not in a script or style element if ( !stack.last() || !specialElements[ stack.last() ] ) { // Comment if ( html.indexOf("<!--") === 0 ) { index = html.indexOf("-->"); if ( index >= 0 ) { if ( handler.comment ) handler.comment( html.substring( 4, index ) ); html = html.substring( index + 3 ); chars = false; } // end tag } else if ( BEGING_END_TAGE_REGEXP.test(html) ) { match = html.match( END_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( END_TAG_REGEXP, parseEndTag ); chars = false; } // start tag } else if ( BEGIN_TAG_REGEXP.test(html) ) { match = html.match( START_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( START_TAG_REGEXP, parseStartTag ); chars = false; } } if ( chars ) { index = html.indexOf("<"); var text = index < 0 ? html : html.substring( 0, index ); html = index < 0 ? "" : html.substring( index ); handler.chars( decodeEntities(text) ); } } else { html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){ text = text. replace(COMMENT_REGEXP, "$1"). replace(CDATA_REGEXP, "$1"); handler.chars( decodeEntities(text) ); return ""; }); parseEndTag( "", stack.last() ); } if ( html == last ) { throw "Parse Error: " + html; } last = html; } // Clean up any remaining tags parseEndTag(); function parseStartTag( tag, tagName, rest, unary ) { tagName = lowercase(tagName); if ( blockElements[ tagName ] ) { while ( stack.last() && inlineElements[ stack.last() ] ) { parseEndTag( "", stack.last() ); } } if ( closeSelfElements[ tagName ] && stack.last() == tagName ) { parseEndTag( "", tagName ); } unary = emptyElements[ tagName ] || !!unary; if ( !unary ) stack.push( tagName ); var attrs = {}; rest.replace(ATTR_REGEXP, function(match, name) { var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : ""; attrs[name] = decodeEntities(value); //value.replace(/(^|[^\\])"/g, '$1\\\"') //" }); handler.start( tagName, attrs, unary ); } function parseEndTag( tag, tagName ) { var pos = 0, i; tagName = lowercase(tagName); if ( tagName ) // Find the closest opened tag of the same type for ( pos = stack.length - 1; pos >= 0; pos-- ) if ( stack[ pos ] == tagName ) break; if ( pos >= 0 ) { // Close all the open elements, up the stack for ( i = stack.length - 1; i >= pos; i-- ) handler.end( stack[ i ] ); // Remove the open elements from the stack stack.length = pos; } } } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str){ var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } /** * decodes all entities into regular string * @param value * @returns {string} A string with decoded entities. */ var hiddenPre=document.createElement("pre"); function decodeEntities(value) { hiddenPre.innerHTML=value.replace(/</g,"&lt;"); return hiddenPre.innerText || hiddenPre.textContent; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(NON_ALPHANUMERIC_REGEXP, function(value){ return '&#' + value.charCodeAt(0) + ';'; }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.jain('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriter(buf){ var ignore = false; var out = bind(buf, buf.push); return { start: function(tag, attrs, unary){ tag = lowercase(tag); if (!ignore && specialElements[tag]) { ignore = tag; } if (!ignore && validElements[tag] == true) { out('<'); out(tag); foreach(attrs, function(value, key){ var lkey=lowercase(key); if (validAttrs[lkey]==true && (uriAttrs[lkey]!==true || value.match(URI_REGEXP))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out(unary ? '/>' : '>'); } }, end: function(tag){ tag = lowercase(tag); if (!ignore && validElements[tag] == true) { out('</'); out(tag); out('>'); } if (tag == ignore) { ignore = false; } }, chars: function(chars){ if (!ignore) { out(encodeEntities(chars)); } } }; } ////////////////////////////////// //JQLite ////////////////////////////////// var jqCache = {}, jqName = 'ng-' + new Date().getTime(), jqId = 1, addEventListener = (window.document.attachEvent ? function(element, type, fn) {element.attachEvent('on' + type, fn);} : function(element, type, fn) {element.addEventListener(type, fn, false);}), removeEventListener = (window.document.detachEvent ? function(element, type, fn) {element.detachEvent('on' + type, fn); } : function(element, type, fn) { element.removeEventListener(type, fn, false); }); function jqNextId() { return (jqId++); } function jqClearData(element) { var cacheId = element[jqName], cache = jqCache[cacheId]; if (cache) { foreach(cache.bind || {}, function(fn, type){ removeEventListener(element, type, fn); }); delete jqCache[cacheId]; if (msie) element[jqName] = ''; // ie does not allow deletion of attributes on elements. else delete element[jqName]; } } function getStyle(element) { var current = {}, style = element[0].style, value, name, i; if (typeof style.length == 'number') { for(i = 0; i < style.length; i++) { name = style[i]; current[name] = style[name]; } } else { for (name in style) { value = style[name]; if (1*name != name && name != 'cssText' && value && typeof value == 'string' && value !='false') current[name] = value; } } return current; } function JQLite(element) { if (isElement(element)) { this[0] = element; this.length = 1; } else if (isDefined(element.length) && element.item) { for(var i=0; i < element.length; i++) { this[i] = element[i]; } this.length = element.length; } } JQLite.prototype = { data: function(key, value) { var element = this[0], cacheId = element[jqName], cache = jqCache[cacheId || -1]; if (isDefined(value)) { if (!cache) { element[jqName] = cacheId = jqNextId(); cache = jqCache[cacheId] = {}; } cache[key] = value; } else { return cache ? cache[key] : _null; } }, removeData: function(){ jqClearData(this[0]); }, dealoc: function(){ (function dealoc(element){ jqClearData(element); for ( var i = 0, children = element.childNodes; i < children.length; i++) { dealoc(children[i]); } })(this[0]); }, bind: function(type, fn){ var self = this, element = self[0], bind = self.data('bind'), eventHandler; if (!bind) this.data('bind', bind = {}); foreach(type.split(' '), function(type){ eventHandler = bind[type]; if (!eventHandler) { bind[type] = eventHandler = function(event) { if (!event.preventDefault) { event.preventDefault = function(){ event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } foreach(eventHandler.fns, function(fn){ fn.call(self, event); }); }; eventHandler.fns = []; addEventListener(element, type, eventHandler); } eventHandler.fns.push(fn); }); }, replaceWith: function(replaceNode) { this[0].parentNode.replaceChild(jqLite(replaceNode)[0], this[0]); }, children: function() { return new JQLite(this[0].childNodes); }, append: function(node) { var self = this[0]; node = jqLite(node); foreach(node, function(child){ self.appendChild(child); }); }, remove: function() { this.dealoc(); var parentNode = this[0].parentNode; if (parentNode) parentNode.removeChild(this[0]); }, removeAttr: function(name) { this[0].removeAttribute(name); }, after: function(element) { this[0].parentNode.insertBefore(jqLite(element)[0], this[0].nextSibling); }, hasClass: function(selector) { var className = " " + selector + " "; if ( (" " + this[0].className + " ").replace(/[\n\t]/g, " ").indexOf( className ) > -1 ) { return true; } return false; }, removeClass: function(selector) { this[0].className = trim((" " + this[0].className + " ").replace(/[\n\t]/g, " ").replace(" " + selector + " ", "")); }, toggleClass: function(selector, condition) { var self = this; (condition ? self.addClass : self.removeClass).call(self, selector); }, addClass: function( selector ) { if (!this.hasClass(selector)) { this[0].className = trim(this[0].className + ' ' + selector); } }, css: function(name, value) { var style = this[0].style; if (isString(name)) { if (isDefined(value)) { style[name] = value; } else { return style[name]; } } else { extend(style, name); } }, attr: function(name, value){ var e = this[0]; if (isObject(name)) { foreach(name, function(value, name){ e.setAttribute(name, value); }); } else if (isDefined(value)) { e.setAttribute(name, value); } else { // the extra argument is to get the right thing for a.href in IE, see jQuery code return e.getAttribute(name, 2); } }, text: function(value) { if (isDefined(value)) { this[0].textContent = value; } return this[0].textContent; }, val: function(value) { if (isDefined(value)) { this[0].value = value; } return this[0].value; }, html: function(value) { if (isDefined(value)) { var i = 0, childNodes = this[0].childNodes; for ( ; i < childNodes.length; i++) { jqLite(childNodes[i]).dealoc(); } this[0].innerHTML = value; } return this[0].innerHTML; }, parent: function() { return jqLite(this[0].parentNode); }, clone: function() { return jqLite(this[0].cloneNode(true)); } }; if (msie) { extend(JQLite.prototype, { text: function(value) { var e = this[0]; // NodeType == 3 is text node if (e.nodeType == 3) { if (isDefined(value)) e.nodeValue = value; return e.nodeValue; } else { if (isDefined(value)) e.innerText = value; return e.innerText; } } }); } var angularGlobal = { 'typeOf':function(obj){ if (obj === _null) return $null; var type = typeof obj; if (type == $object) { if (obj instanceof Array) return $array; if (isDate(obj)) return $date; if (obj.nodeType == 1) return $element; } return type; } }; /** * @workInProgress * @ngdoc overview * @name angular.Object * @function * * @description * Utility functions for manipulation with JavaScript objects. * * These functions are exposed in two ways: * * - **in angular expressions**: the functions are bound to all objects and augment the Object * type. The names of these methods are prefixed with `$` character to minimize naming collisions. * To call a method, invoke the function without the first argument, e.g, `myObject.$foo(param2)`. * * - **in JavaScript code**: the functions don't augment the Object type and must be invoked as * functions of `angular.Object` as `angular.Object.foo(myObject, param2)`. * */ var angularCollection = { 'copy': copy, 'size': size, 'equals': equals }; var angularObject = { 'extend': extend }; /** * @workInProgress * @ngdoc overview * @name angular.Array * * @description * Utility functions for manipulation with JavaScript Array objects. * * These functions are exposed in two ways: * * - **in angular expressions**: the functions are bound to the Array objects and augment the Array * type as array methods. The names of these methods are prefixed with `$` character to minimize * naming collisions. To call a method, invoke `myArrayObject.$foo(params)`. * * - **in JavaScript code**: the functions don't augment the Array type and must be invoked as * functions of `angular.Array` as `angular.Array.foo(myArrayObject, params)`. * */ var angularArray = { /** * @workInProgress * @ngdoc function * @name angular.Array.indexOf * @function * * @description * Determines the index of `value` in `array`. * * Note: this function is used to augment the Array type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array Array to search. * @param {*} value Value to search for. * @returns {number} The position of the element in `array`. The position is 0-based. `-1` is returned if the value can't be found. * * @example <div ng:init="books = ['Moby Dick', 'Great Gatsby', 'Romeo and Juliet']"></div> <input name='bookName' value='Romeo and Juliet'> <br> Index of '{{bookName}}' in the list {{books}} is <em>{{books.$indexOf(bookName)}}</em>. @scenario it('should correctly calculate the initial index', function() { expect(binding('books.$indexOf(bookName)')).toBe('2'); }); it('should recalculate', function() { input('bookName').enter('foo'); expect(binding('books.$indexOf(bookName)')).toBe('-1'); input('bookName').enter('Moby Dick'); expect(binding('books.$indexOf(bookName)')).toBe('0'); }); */ 'indexOf': indexOf, /** * @workInProgress * @ngdoc function * @name angular.Array.sum * @function * * @description * This function calculates the sum of all numbers in `array`. If the `expressions` is supplied, * it is evaluated once for each element in `array` and then the sum of these values is returned. * * Note: this function is used to augment the Array type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The source array. * @param {(string|function())=} expression Angular expression or a function to be evaluated for each * element in `array`. The array element becomes the `this` during the evaluation. * @returns {number} Sum of items in the array. * * @example <table ng:init="invoice= {items:[{qty:10, description:'gadget', cost:9.95}]}"> <tr><th>Qty</th><th>Description</th><th>Cost</th><th>Total</th><th></th></tr> <tr ng:repeat="item in invoice.items"> <td><input name="item.qty" value="1" size="4" ng:required ng:validate="integer"></td> <td><input name="item.description"></td> <td><input name="item.cost" value="0.00" ng:required ng:validate="number" size="6"></td> <td>{{item.qty * item.cost | currency}}</td> <td>[<a href ng:click="invoice.items.$remove(item)">X</a>]</td> </tr> <tr> <td><a href ng:click="invoice.items.$add()">add item</a></td> <td></td> <td>Total:</td> <td>{{invoice.items.$sum('qty*cost') | currency}}</td> </tr> </table> @scenario //TODO: these specs are lame because I had to work around issues #164 and #167 it('should initialize and calculate the totals', function() { expect(repeater('.doc-example-live table tr', 'item in invoice.items').count()).toBe(3); expect(repeater('.doc-example-live table tr', 'item in invoice.items').row(1)). toEqual(['$99.50']); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50'); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50'); }); it('should add an entry and recalculate', function() { element('.doc-example a:contains("add item")').click(); using('.doc-example-live tr:nth-child(3)').input('item.qty').enter('20'); using('.doc-example-live tr:nth-child(3)').input('item.cost').enter('100'); expect(repeater('.doc-example-live table tr', 'item in invoice.items').row(2)). toEqual(['$2,000.00']); expect(binding("invoice.items.$sum('qty*cost')")).toBe('$2,099.50'); }); */ 'sum':function(array, expression) { var fn = angular['Function']['compile'](expression); var sum = 0; for (var i = 0; i < array.length; i++) { var value = 1 * fn(array[i]); if (!isNaN(value)){ sum += value; } } return sum; }, /** * @workInProgress * @ngdoc function * @name angular.Array.remove * @function * * @description * Modifies `array` by removing an element from it. The element will be looked up using the * {@link angular.Array.indexOf indexOf} function on the `array` and only the first instance of * the element will be removed. * * Note: this function is used to augment the Array type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array Array from which an element should be removed. * @param {*} value Element to be removed. * @returns {*} The removed element. * * @example <ul ng:init="tasks=['Learn Angular', 'Read Documentation', 'Check out demos', 'Build cool applications']"> <li ng:repeat="task in tasks"> {{task}} [<a href="" ng:click="tasks.$remove(task)">X</a>] </li> </ul> <hr/> tasks = {{tasks}} @scenario it('should initialize the task list with for tasks', function() { expect(repeater('.doc-example ul li', 'task in tasks').count()).toBe(4); expect(repeater('.doc-example ul li', 'task in tasks').column('task')). toEqual(['Learn Angular', 'Read Documentation', 'Check out demos', 'Build cool applications']); }); it('should initialize the task list with for tasks', function() { element('.doc-example ul li a:contains("X"):first').click(); expect(repeater('.doc-example ul li', 'task in tasks').count()).toBe(3); element('.doc-example ul li a:contains("X"):last').click(); expect(repeater('.doc-example ul li', 'task in tasks').count()).toBe(2); expect(repeater('.doc-example ul li', 'task in tasks').column('task')). toEqual(['Read Documentation', 'Check out demos']); }); */ 'remove':function(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; }, /** * @workInProgress * @ngdoc function * @name angular.Array.filter * @function * * @description * Selects a subset of items from `array` and returns it as a new array. * * Note: this function is used to augment the Array type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: Predicate that results in a substring match using the value of `expression` * string. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * * - `function`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * * @example <div ng:init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}]"></div> Search: <input name="searchText"/> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng:repeat="friend in friends.$filter(searchText)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> <hr> Any: <input name="search.$"/> <br> Name only <input name="search.name"/><br> Phone only <input name="search.phone"/><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th><tr> <tr ng:repeat="friend in friends.$filter(search)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <tr> </table> @scenario it('should search across all fields when filtering with a string', function() { input('searchText').enter('m'); expect(repeater('#searchTextResults tr', 'friend in friends').column('name')). toEqual(['Mary', 'Mike', 'Adam']); input('searchText').enter('76'); expect(repeater('#searchTextResults tr', 'friend in friends').column('name')). toEqual(['John', 'Julie']); }); it('should search in specific fields when filtering with a predicate object', function() { input('search.$').enter('i'); expect(repeater('#searchObjResults tr', 'friend in friends').column('name')). toEqual(['Mary', 'Mike', 'Julie']); }); */ 'filter':function(array, expression) { var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; var search = function(obj, text){ if (text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return ('' + obj).toLowerCase().indexOf(text) > -1; case "object": for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function(){ var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(value, text); }); })(); } else { (function(){ var path = key; var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(getter(value, path), text); }); })(); } } break; case $function: predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; }, /** * @workInProgress * @ngdoc function * @name angular.Array.add * @function * * @description * `add` is a function similar to JavaScript's `Array#push` method, in that it appends a new * element to an array, but it differs in that the value being added is optional and defaults to * an emty object. * * Note: this function is used to augment the Array type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The array expand. * @param {*=} [value={}] The value to be added. * @returns {Array} The expanded array. * * @exampleDescription * This example shows how an initially empty array can be filled with objects created from user * input via the `$add` method. * * @example [<a href="" ng:click="people.$add()">add empty</a>] [<a href="" ng:click="people.$add({name:'John', sex:'male'})">add 'John'</a>] [<a href="" ng:click="people.$add({name:'Mary', sex:'female'})">add 'Mary'</a>] <ul ng:init="people=[]"> <li ng:repeat="person in people"> <input name="person.name"> <select name="person.sex"> <option value="">--chose one--</option> <option>male</option> <option>female</option> </select> [<a href="" ng:click="people.$remove(person)">X</a>] </li> </ul> <pre>people = {{people}}</pre> @scenario beforeEach(function() { expect(binding('people')).toBe('people = []'); }); it('should create an empty record when "add empty" is clicked', function() { element('.doc-example a:contains("add empty")').click(); expect(binding('people')).toBe('people = [{\n "name":"",\n "sex":null}]'); }); it('should create a "John" record when "add \'John\'" is clicked', function() { element('.doc-example a:contains("add \'John\'")').click(); expect(binding('people')).toBe('people = [{\n "name":"John",\n "sex":"male"}]'); }); it('should create a "Mary" record when "add \'Mary\'" is clicked', function() { element('.doc-example a:contains("add \'Mary\'")').click(); expect(binding('people')).toBe('people = [{\n "name":"Mary",\n "sex":"female"}]'); }); it('should delete a record when "X" is clicked', function() { element('.doc-example a:contains("add empty")').click(); element('.doc-example li a:contains("X"):first').click(); expect(binding('people')).toBe('people = []'); }); */ 'add':function(array, value) { array.push(isUndefined(value)? {} : value); return array; }, /** * @workInProgress * @ngdoc function * @name angular.Array.count * @function * * @description * Determines the number of elements in an array. Optionally it will count only those elements * for which the `condition` evaluets to `true`. * * Note: this function is used to augment the Array type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The array to count elements in. * @param {(function()|string)=} condition A function to be evaluated or angular expression to be * compiled and evaluated. The element that is currently being iterated over, is exposed to * the `condition` as `this`. * @returns {number} Number of elements in the array (for which the condition evaluates to true). * * @example <pre ng:init="items = [{name:'knife', points:1}, {name:'fork', points:3}, {name:'spoon', points:1}]"></pre> <ul> <li ng:repeat="item in items"> {{item.name}}: points= <input type="text" name="item.points"/> <!-- id="item{{$index}} --> </li> </ul> <p>Number of items which have one point: <em>{{ items.$count('points==1') }}</em></p> <p>Number of items which have more than one point: <em>{{items.$count('points&gt;1')}}</em></p> @scenario it('should calculate counts', function() { expect(binding('items.$count(\'points==1\')')).toEqual(2); expect(binding('items.$count(\'points>1\')')).toEqual(1); }); it('should recalculate when updated', function() { using('.doc-example li:first-child').input('item.points').enter('23'); expect(binding('items.$count(\'points==1\')')).toEqual(1); expect(binding('items.$count(\'points>1\')')).toEqual(2); }); */ 'count':function(array, condition) { if (!condition) return array.length; var fn = angular['Function']['compile'](condition), count = 0; foreach(array, function(value){ if (fn(value)) { count ++; } }); return count; }, /** * @workInProgress * @ngdoc function * @name angular.Array.orderBy * @function * * @description * Orders `array` by the `expression` predicate. * * Note: this function is used to augment the Array type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array The array to sort. * @param {function()|string|Array.<(function()|string)>} expression A predicate to be used by the * comparator to determine the order of elements. * * Can be one of: * * - `function`: JavaScript's Array#sort comparator function * - `string`: angular expression which evaluates to an object to order by, such as 'name' to * sort by a property called 'name'. Optionally prefixed with `+` or `-` to control ascending * or descending sort order (e.g. +name or -name). * - `Array`: array of function or string predicates, such that a first predicate in the array * is used for sorting, but when the items are equivalent next predicate is used. * * @param {boolean=} reverse Reverse the order the array. * @returns {Array} Sorted copy of the source array. * * @example <div ng:init="friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}]"></div> <pre>Sorting predicate = {{predicate}}</pre> <hr/> <table ng:init="predicate='-age'"> <tr> <th><a href="" ng:click="predicate = 'name'">Name</a> (<a href ng:click="predicate = '-name'">^</a>)</th> <th><a href="" ng:click="predicate = 'phone'">Phone</a> (<a href ng:click="predicate = '-phone'">^</a>)</th> <th><a href="" ng:click="predicate = 'age'">Age</a> (<a href ng:click="predicate = '-age'">^</a>)</th> <tr> <tr ng:repeat="friend in friends.$orderBy(predicate)"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> <tr> </table> @scenario it('should be reverse ordered by aged', function() { expect(binding('predicate')).toBe('Sorting predicate = -age'); expect(repeater('.doc-example table', 'friend in friends').column('friend.age')). toEqual(['35', '29', '21', '19', '10']); expect(repeater('.doc-example table', 'friend in friends').column('friend.name')). toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); }); it('should reorder the table when user selects different predicate', function() { element('.doc-example a:contains("Name")').click(); expect(repeater('.doc-example table', 'friend in friends').column('friend.name')). toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); expect(repeater('.doc-example table', 'friend in friends').column('friend.age')). toEqual(['35', '10', '29', '19', '21']); element('.doc-example a:contains("Phone")+a:contains("^")').click(); expect(repeater('.doc-example table', 'friend in friends').column('friend.phone')). toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); expect(repeater('.doc-example table', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); }); */ //TODO: WTH is descend param for and how/when it should be used, how is it affected by +/- in // predicate? the code below is impossible to read and specs are not very good. 'orderBy':function(array, expression, descend) { expression = isArray(expression) ? expression: [expression]; expression = map(expression, function($){ var descending = false, get = $ || identity; if (isString($)) { if (($.charAt(0) == '+' || $.charAt(0) == '-')) { descending = $.charAt(0) == '-'; $ = $.substring(1); } get = expressionCompile($).fnSelf; } return reverse(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverse(comparator, descend)); function comparator(o1, o2){ for ( var i = 0; i < expression.length; i++) { var comp = expression[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverse(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } }, /** * @workInProgress * @ngdoc function * @name angular.Array.limitTo * @function * * @description * Creates a new array containing only the first, or last `limit` number of elements of the * source `array`. * * Note: this function is used to augment the Array type in angular expressions. See * {@link angular.Array} for more info. * * @param {Array} array Source array to be limited. * @param {string|Number} limit The length of the returned array. If the number is positive, the * first `limit` items from the source array will be copied, if the number is negative, the * last `limit` items will be copied. * @returns {Array} New array of length `limit`. * */ limitTo: function(array, limit) { limit = parseInt(limit, 10); var out = [], i, n; if (limit > 0) { i = 0; n = limit; } else { i = array.length + limit; n = array.length; } for (; i<n; i++) { out.push(array[i]); } return out; } }; var R_ISO8061_STR = /^(\d{4})-(\d\d)-(\d\d)(?:T(\d\d)(?:\:(\d\d)(?:\:(\d\d)(?:\.(\d{3}))?)?)?Z)?$/; var angularString = { 'quote':function(string) { return '"' + string.replace(/\\/g, '\\\\'). replace(/"/g, '\\"'). replace(/\n/g, '\\n'). replace(/\f/g, '\\f'). replace(/\r/g, '\\r'). replace(/\t/g, '\\t'). replace(/\v/g, '\\v') + '"'; }, 'quoteUnicode':function(string) { var str = angular['String']['quote'](string); var chars = []; for ( var i = 0; i < str.length; i++) { var ch = str.charCodeAt(i); if (ch < 128) { chars.push(str.charAt(i)); } else { var encode = "000" + ch.toString(16); chars.push("\\u" + encode.substring(encode.length - 4)); } } return chars.join(''); }, /** * Tries to convert input to date and if successful returns the date, otherwise returns the input. * @param {string} string * @return {(Date|string)} */ 'toDate':function(string){ var match; if (isString(string) && (match = string.match(R_ISO8061_STR))){ var date = new Date(0); date.setUTCFullYear(match[1], match[2] - 1, match[3]); date.setUTCHours(match[4]||0, match[5]||0, match[6]||0, match[7]||0); return date; } return string; } }; var angularDate = { 'toString':function(date){ return !date ? date : date.toISOString ? date.toISOString() : padNumber(date.getUTCFullYear(), 4) + '-' + padNumber(date.getUTCMonth() + 1, 2) + '-' + padNumber(date.getUTCDate(), 2) + 'T' + padNumber(date.getUTCHours(), 2) + ':' + padNumber(date.getUTCMinutes(), 2) + ':' + padNumber(date.getUTCSeconds(), 2) + '.' + padNumber(date.getUTCMilliseconds(), 3) + 'Z'; } }; var angularFunction = { 'compile':function(expression) { if (isFunction(expression)){ return expression; } else if (expression){ return expressionCompile(expression).fnSelf; } else { return identity; } } }; function defineApi(dst, chain){ angular[dst] = angular[dst] || {}; foreach(chain, function(parent){ extend(angular[dst], parent); }); } defineApi('Global', [angularGlobal]); defineApi('Collection', [angularGlobal, angularCollection]); defineApi('Array', [angularGlobal, angularCollection, angularArray]); defineApi('Object', [angularGlobal, angularCollection, angularObject]); defineApi('String', [angularGlobal, angularString]); defineApi('Date', [angularGlobal, angularDate]); //IE bug angular['Date']['toString'] = angularDate['toString']; defineApi('Function', [angularGlobal, angularCollection, angularFunction]); /** * @workInProgress * @ngdoc filter * @name angular.filter.currency * @function * * @description * Formats a number as a currency (ie $1,234.56). * * @param {number} amount Input to filter. * @returns {string} Formated number. * * @css ng-format-negative * When the value is negative, this css class is applied to the binding making it by default red. * * @example <input type="text" name="amount" value="1234.56"/> <br/> {{amount | currency}} * * @scenario it('should init with 1234.56', function(){ expect(binding('amount | currency')).toBe('$1,234.56'); }); it('should update', function(){ input('amount').enter('-1234'); expect(binding('amount | currency')).toBe('$-1,234.00'); expect(element('.doc-example-live .ng-binding').attr('className')). toMatch(/ng-format-negative/); }); */ angularFilter.currency = function(amount){ this.$element.toggleClass('ng-format-negative', amount < 0); return '$' + angularFilter['number'].apply(this, [amount, 2]); }; /** * @workInProgress * @ngdoc filter * @name angular.filter.number * @function * * @description * Formats a number as text. * * If the input is not a number empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example Enter number: <input name='val' value='1234.56789' /><br/> Default formatting: {{val | number}}<br/> No fractions: {{val | number:0}}<br/> Negative number: {{-val | number:4}} * @scenario it('should format numbers', function(){ expect(binding('val | number')).toBe('1,234.57'); expect(binding('val | number:0')).toBe('1,235'); expect(binding('-val | number:4')).toBe('-1,234.5679'); }); it('should update', function(){ input('val').enter('3374.333'); expect(binding('val | number')).toBe('3,374.33'); expect(binding('val | number:0')).toBe('3,374'); expect(binding('-val | number:4')).toBe('-3,374.3330'); }); */ angularFilter.number = function(number, fractionSize){ if (isNaN(number) || !isFinite(number)) { return ''; } fractionSize = typeof fractionSize == $undefined ? 2 : fractionSize; var isNegative = number < 0; number = Math.abs(number); var pow = Math.pow(10, fractionSize); var text = "" + Math.round(number * pow); var whole = text.substring(0, text.length - fractionSize); whole = whole || '0'; var frc = text.substring(text.length - fractionSize); text = isNegative ? '-' : ''; for (var i = 0; i < whole.length; i++) { if ((whole.length - i)%3 === 0 && i !== 0) { text += ','; } text += whole.charAt(i); } if (fractionSize > 0) { for (var j = frc.length; j < fractionSize; j++) { frc += '0'; } text += '.' + frc.substring(0, fractionSize); } return text; }; function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), a: function(date){return date.getHours() < 12 ? 'am' : 'pm';}, Z: function(date){ var offset = date.getTimezoneOffset(); return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2); } }; var DATE_FORMATS_SPLIT = /([^yMdHhmsaZ]*)(y+|M+|d+|H+|h+|m+|s+|a|Z)(.*)/; var NUMBER_STRING = /^\d+$/; /** * @workInProgress * @ngdoc filter * @name angular.filter.date * @function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year e.g. 2010 * * `'yy'`: 2 digit representation of year, padded (00-99) * * `'MM'`: Month in year, padded (01‒12) * * `'M'`: Month in year (1‒12) * * `'dd'`: Day in month, padded (01‒31) * * `'d'`: Day in month (1-31) * * `'HH'`: Hour in day, padded (00‒23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01‒12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00‒59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00‒59) * * `'s'`: Second in minute (0‒59) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200‒1200) * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or ISO 8601 extended datetime string (yyyy-MM-ddTHH:mm:ss.SSSZ). * @param {string=} format Formatting rules. If not specified, Date#toLocaleDateString is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <span ng:non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br/> <span ng:non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br/> * * @scenario it('should format date', function(){ expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/); expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(am|pm)/); }); * */ angularFilter.date = function(date, format) { if (isString(date)) { if (NUMBER_STRING.test(date)) { date = parseInt(date, 10); } else { date = angularString.toDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } var text = date.toLocaleDateString(), fn; if (format && isString(format)) { text = ''; var parts = []; while(format) { parts = concat(parts, DATE_FORMATS_SPLIT.exec(format), 1); format = parts.pop(); } foreach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date) : value; }); } return text; }; /** * @workInProgress * @ngdoc filter * @name angular.filter.json * @function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * @css ng-monospace Always applied to the encapsulating element. * * @example: <input type="text" name="objTxt" value="{a:1, b:[]}" ng:eval="obj = $eval(objTxt)"/> <pre>{{ obj | json }}</pre> * * @scenario it('should jsonify filtered objects', function() { expect(binding('obj | json')).toBe('{\n "a":1,\n "b":[]}'); }); it('should update', function() { input('objTxt').enter('[1, 2, 3]'); expect(binding('obj | json')).toBe('[1,2,3]'); }); * */ angularFilter.json = function(object) { this.$element.addClass("ng-monospace"); return toJson(object, true); }; /** * @workInProgress * @ngdoc filter * @name angular.filter.lowercase * @function * * @see angular.lowercase */ angularFilter.lowercase = lowercase; /** * @workInProgress * @ngdoc filter * @name angular.filter.uppercase * @function * * @see angular.uppercase */ angularFilter.uppercase = uppercase; /** * @workInProgress * @ngdoc filter * @name angular.filter.html * @function * * @description * Prevents the input from getting escaped by angular. By default the input is sanitized and * inserted into the DOM as is. * * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string, however since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. * * If you hate your users, you may call the filter with optional 'unsafe' argument, which bypasses * the html sanitizer, but makes your application vulnerable to XSS and other attacks. Using this * option is strongly discouraged and should be used only if you absolutely trust the input being * filtered and you can't get the content through the sanitizer. * * @param {string} html Html input. * @param {string=} option If 'unsafe' then do not sanitize the HTML input. * @returns {string} Sanitized or raw html. * * @example Snippet: <textarea name="snippet" cols="60" rows="3"> &lt;p style="color:blue"&gt;an html &lt;em onmouseover="this.textContent='PWN3D!'"&gt;click here&lt;/em&gt; snippet&lt;/p&gt;</textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="html-filter"> <td>html filter</td> <td> <pre>&lt;div ng:bind="snippet | html"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng:bind="snippet | html"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng:bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet"></div></td> </tr> <tr id="html-unsafe-filter"> <td>unsafe html filter</td> <td><pre>&lt;div ng:bind="snippet | html:'unsafe'"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet | html:'unsafe'"></div></td> </tr> </table> * * @scenario it('should sanitize the html snippet ', function(){ expect(using('#html-filter').binding('snippet | html')). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it ('should escape snippet without any filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it ('should inline raw snippet if filtered as unsafe', function() { expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should update', function(){ input('snippet').enter('new <b>text</b>'); expect(using('#html-filter').binding('snippet | html')).toBe('new <b>text</b>'); expect(using('#escaped-html').binding('snippet')).toBe("new &lt;b&gt;text&lt;/b&gt;"); expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")).toBe('new <b>text</b>'); }); */ angularFilter.html = function(html, option){ return new HTML(html, option); }; /** * @workInProgress * @ngdoc filter * @name angular.filter.linky * @function * * @description * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and * plane email address links. * * @param {string} text Input text. * @returns {string} Html-linkified text. * * @example Snippet: <textarea name="snippet" cols="60" rows="3"> Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, another@somewhere.org, and one more: ftp://127.0.0.1/.</textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng:bind="snippet | linky"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng:bind="snippet | linky"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng:bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet"></div></td> </tr> </table> @scenario it('should linkify the snippet with urls', function(){ expect(using('#linky-filter').binding('snippet | linky')). toBe('Pretty text with some links:\n' + '<a href="http://angularjs.org/">http://angularjs.org/</a>,\n' + '<a href="mailto:us@somewhere.org">us@somewhere.org</a>,\n' + '<a href="mailto:another@somewhere.org">another@somewhere.org</a>,\n' + 'and one more: <a href="ftp://127.0.0.1/">ftp://127.0.0.1/</a>.'); }); it ('should not linkify snippet without the linky filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("Pretty text with some links:\n" + "http://angularjs.org/,\n" + "mailto:us@somewhere.org,\n" + "another@somewhere.org,\n" + "and one more: ftp://127.0.0.1/."); }); it('should update', function(){ input('snippet').enter('new http://link.'); expect(using('#linky-filter').binding('snippet | linky')). toBe('new <a href="http://link">http://link</a>.'); expect(using('#escaped-html').binding('snippet')).toBe('new http://link.'); }); */ //TODO: externalize all regexps angularFilter.linky = function(text){ if (!text) return text; var URL = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/; var match; var raw = text; var html = []; var writer = htmlSanitizeWriter(html); var url; var i; while (match=raw.match(URL)) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/mailto then assume mailto if (match[2]==match[3]) url = 'mailto:' + url; i = match.index; writer.chars(raw.substr(0, i)); writer.start('a', {href:url}); writer.chars(match[0].replace(/^mailto:/, '')); writer.end('a'); raw = raw.substring(i + match[0].length); } writer.chars(raw); return new HTML(html.join('')); }; function formatter(format, parse) {return {'format':format, 'parse':parse || format};} function toString(obj) { return (isDefined(obj) && obj !== _null) ? "" + obj : obj; } var NUMBER = /^\s*[-+]?\d*(\.\d*)?\s*$/; angularFormatter.noop = formatter(identity, identity); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.json * * @description * Formats the user input as JSON text. * * @returns {string} A JSON string representation of the model. * * @example * <div ng:init="data={name:'misko', project:'angular'}"> * <input type="text" size='50' name="data" ng:format="json"/> * <pre>data={{data}}</pre> * </div> * * @scenario * it('should format json', function(){ * expect(binding('data')).toEqual('data={\n \"name\":\"misko\",\n \"project\":\"angular\"}'); * input('data').enter('{}'); * expect(binding('data')).toEqual('data={\n }'); * }); */ angularFormatter.json = formatter(toJson, fromJson); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.boolean * * @description * Use boolean formatter if you wish to store the data as boolean. * * @returns {boolean} Converts to `true` unless user enters (blank), `f`, `false`, `0`, `no`, `[]`. * * @example * Enter truthy text: * <input type="text" name="value" ng:format="boolean" value="no"/> * <input type="checkbox" name="value"/> * <pre>value={{value}}</pre> * * @scenario * it('should format boolean', function(){ * expect(binding('value')).toEqual('value=false'); * input('value').enter('truthy'); * expect(binding('value')).toEqual('value=true'); * }); */ angularFormatter['boolean'] = formatter(toString, toBoolean); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.number * * @description * Use number formatter if you wish to convert the user entered string to a number. * * @returns {number} Number from the parsed string. * * @example * Enter valid number: * <input type="text" name="value" ng:format="number" value="1234"/> * <pre>value={{value}}</pre> * * @scenario * it('should format numbers', function(){ * expect(binding('value')).toEqual('value=1234'); * input('value').enter('5678'); * expect(binding('value')).toEqual('value=5678'); * }); */ angularFormatter.number = formatter(toString, function(obj){ if (obj == _null || NUMBER.exec(obj)) { return obj===_null || obj === '' ? _null : 1*obj; } else { throw "Not a number"; } }); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.list * * @description * Use list formatter if you wish to convert the user entered string to an array. * * @returns {Array} Array parsed from the entered string. * * @example * Enter a list of items: * <input type="text" name="value" ng:format="list" value=" chair ,, table"/> * <input type="text" name="value" ng:format="list"/> * <pre>value={{value}}</pre> * * @scenario * it('should format lists', function(){ * expect(binding('value')).toEqual('value=["chair","table"]'); * this.addFutureAction('change to XYZ', function($window, $document, done){ * $document.elements('.doc-example :input:last').val(',,a,b,').trigger('change'); * done(); * }); * expect(binding('value')).toEqual('value=["a","b"]'); * }); */ angularFormatter.list = formatter( function(obj) { return obj ? obj.join(", ") : obj; }, function(value) { var list = []; foreach((value || '').split(','), function(item){ item = trim(item); if (item) list.push(item); }); return list; } ); /** * @workInProgress * @ngdoc formatter * @name angular.formatter.trim * * @description * Use trim formatter if you wish to trim extra spaces in user text. * * @returns {String} Trim excess leading and trailing space. * * @example * Enter text with leading/trailing spaces: * <input type="text" name="value" ng:format="trim" value=" book "/> * <input type="text" name="value" ng:format="trim"/> * <pre>value={{value|json}}</pre> * * @scenario * it('should format trim', function(){ * expect(binding('value')).toEqual('value="book"'); * this.addFutureAction('change to XYZ', function($window, $document, done){ * $document.elements('.doc-example :input:last').val(' text ').trigger('change'); * done(); * }); * expect(binding('value')).toEqual('value="text"'); * }); */ angularFormatter.trim = formatter( function(obj) { return obj ? trim("" + obj) : ""; } ); extend(angularValidator, { 'noop': function() { return _null; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.regexp * @description * Use regexp validator to restrict the input to any Regular Expression. * * @param {string} value value to validate * @param {regexp} expression regular expression. * @css ng-validation-error * * @example * Enter valid SSN: * <input name="ssn" value="123-45-6789" ng:validate="regexp:/^\d\d\d-\d\d-\d\d\d\d$/" > * * @scenario * it('should invalidate non ssn', function(){ * var textBox = element('.doc-example :input'); * expect(textBox.attr('className')).not().toMatch(/ng-validation-error/); * expect(textBox.val()).toEqual('123-45-6789'); * * input('ssn').enter('123-45-67890'); * expect(textBox.attr('className')).toMatch(/ng-validation-error/); * }); * */ 'regexp': function(value, regexp, msg) { if (!value.match(regexp)) { return msg || "Value does not match expected format " + regexp + "."; } else { return _null; } }, /** * @workInProgress * @ngdoc validator * @name angular.validator.number * @description * Use number validator to restrict the input to numbers with an * optional range. (See integer for whole numbers validator). * * @param {string} value value to validate * @param {int=} [min=MIN_INT] minimum value. * @param {int=} [max=MAX_INT] maximum value. * @css ng-validation-error * * @example * Enter number: <input name="n1" ng:validate="number" > <br> * Enter number greater than 10: <input name="n2" ng:validate="number:10" > <br> * Enter number between 100 and 200: <input name="n3" ng:validate="number:100:200" > <br> * * @scenario * it('should invalidate number', function(){ * var n1 = element('.doc-example :input[name=n1]'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('n1').enter('1.x'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * * var n2 = element('.doc-example :input[name=n2]'); * expect(n2.attr('className')).not().toMatch(/ng-validation-error/); * input('n2').enter('9'); * expect(n2.attr('className')).toMatch(/ng-validation-error/); * * var n3 = element('.doc-example :input[name=n3]'); * expect(n3.attr('className')).not().toMatch(/ng-validation-error/); * input('n3').enter('201'); * expect(n3.attr('className')).toMatch(/ng-validation-error/); * * }); * */ 'number': function(value, min, max) { var num = 1 * value; if (num == value) { if (typeof min != $undefined && num < min) { return "Value can not be less than " + min + "."; } if (typeof min != $undefined && num > max) { return "Value can not be greater than " + max + "."; } return _null; } else { return "Not a number"; } }, /** * @workInProgress * @ngdoc validator * @name angular.validator.integer * @description * Use number validator to restrict the input to integers with an * optional range. (See integer for whole numbers validator). * * @param {string} value value to validate * @param {int=} [min=MIN_INT] minimum value. * @param {int=} [max=MAX_INT] maximum value. * @css ng-validation-error * * @example * Enter integer: <input name="n1" ng:validate="integer" > <br> * Enter integer equal or greater than 10: <input name="n2" ng:validate="integer:10" > <br> * Enter integer between 100 and 200 (inclusive): <input name="n3" ng:validate="integer:100:200" > <br> * * @scenario * it('should invalidate integer', function(){ * var n1 = element('.doc-example :input[name=n1]'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('n1').enter('1.1'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * * var n2 = element('.doc-example :input[name=n2]'); * expect(n2.attr('className')).not().toMatch(/ng-validation-error/); * input('n2').enter('10.1'); * expect(n2.attr('className')).toMatch(/ng-validation-error/); * * var n3 = element('.doc-example :input[name=n3]'); * expect(n3.attr('className')).not().toMatch(/ng-validation-error/); * input('n3').enter('100.1'); * expect(n3.attr('className')).toMatch(/ng-validation-error/); * * }); */ 'integer': function(value, min, max) { var numberError = angularValidator['number'](value, min, max); if (numberError) return numberError; if (!("" + value).match(/^\s*[\d+]*\s*$/) || value != Math.round(value)) { return "Not a whole number"; } return _null; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.date * @description * Use date validator to restrict the user input to a valid date * in format in format MM/DD/YYYY. * * @param {string} value value to validate * @css ng-validation-error * * @example * Enter valid date: * <input name="text" value="1/1/2009" ng:validate="date" > * * @scenario * it('should invalidate date', function(){ * var n1 = element('.doc-example :input'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('text').enter('123/123/123'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * }); * */ 'date': function(value) { var fields = /^(\d\d?)\/(\d\d?)\/(\d\d\d\d)$/.exec(value); var date = fields ? new Date(fields[3], fields[1]-1, fields[2]) : 0; return (date && date.getFullYear() == fields[3] && date.getMonth() == fields[1]-1 && date.getDate() == fields[2]) ? _null : "Value is not a date. (Expecting format: 12/31/2009)."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.email * @description * Use email validator if you wist to restrict the user input to a valid email. * * @param {string} value value to validate * @css ng-validation-error * * @example * Enter valid email: * <input name="text" ng:validate="email" value="me@example.com"> * * @scenario * it('should invalidate email', function(){ * var n1 = element('.doc-example :input'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('text').enter('a@b.c'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * }); * */ 'email': function(value) { if (value.match(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/)) { return _null; } return "Email needs to be in username@host.com format."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.phone * @description * Use phone validator to restrict the input phone numbers. * * @param {string} value value to validate * @css ng-validation-error * * @example * Enter valid phone number: * <input name="text" value="1(234)567-8901" ng:validate="phone" > * * @scenario * it('should invalidate phone', function(){ * var n1 = element('.doc-example :input'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('text').enter('+12345678'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * }); * */ 'phone': function(value) { if (value.match(/^1\(\d\d\d\)\d\d\d-\d\d\d\d$/)) { return _null; } if (value.match(/^\+\d{2,3} (\(\d{1,5}\))?[\d ]+\d$/)) { return _null; } return "Phone number needs to be in 1(987)654-3210 format in North America or +999 (123) 45678 906 internationaly."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.url * @description * Use phone validator to restrict the input URLs. * * @param {string} value value to validate * @css ng-validation-error * * @example * Enter valid phone number: * <input name="text" value="http://example.com/abc.html" size="40" ng:validate="url" > * * @scenario * it('should invalidate url', function(){ * var n1 = element('.doc-example :input'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('text').enter('abc://server/path'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * }); * */ 'url': function(value) { if (value.match(/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/)) { return _null; } return "URL needs to be in http://server[:port]/path format."; }, /** * @workInProgress * @ngdoc validator * @name angular.validator.json * @description * Use json validator if you wish to restrict the user input to a valid JSON. * * @param {string} value value to validate * @css ng-validation-error * * @example * <textarea name="json" cols="60" rows="5" ng:validate="json"> * {name:'abc'} * </textarea> * * @scenario * it('should invalidate json', function(){ * var n1 = element('.doc-example :input'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('json').enter('{name}'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * }); * */ 'json': function(value) { try { fromJson(value); return _null; } catch (e) { return e.toString(); } }, /** * @workInProgress * @ngdoc validator * @name angular.validator.asynchronous * @description * Use asynchronous validator if the validation can not be computed * immediately, but is provided through a callback. The widget * automatically shows a spinning indicator while the validity of * the widget is computed. This validator caches the result. * * @param {string} value value to validate * @param {function(inputToValidate,validationDone)} validate function to call to validate the state * of the input. * @param {function(data)=} [update=noop] function to call when state of the * validator changes * * @paramDescription * The `validate` function (specified by you) is called as * `validate(inputToValidate, validationDone)`: * * * `inputToValidate`: value of the input box. * * `validationDone`: `function(error, data){...}` * * `error`: error text to display if validation fails * * `data`: data object to pass to update function * * The `update` function is optionally specified by you and is * called by <angular/> on input change. Since the * asynchronous validator caches the results, the update * function can be called without a call to `validate` * function. The function is called as `update(data)`: * * * `data`: data object as passed from validate function * * @css ng-input-indicator-wait, ng-validation-error * * @example * <script> * function myValidator(inputToValidate, validationDone) { * setTimeout(function(){ * validationDone(inputToValidate.length % 2); * }, 500); * } * </script> * This input is validated asynchronously: * <input name="text" ng:validate="asynchronous:$window.myValidator"> * * @scenario * it('should change color in delayed way', function(){ * var textBox = element('.doc-example :input'); * expect(textBox.attr('className')).not().toMatch(/ng-input-indicator-wait/); * expect(textBox.attr('className')).not().toMatch(/ng-validation-error/); * * input('text').enter('X'); * expect(textBox.attr('className')).toMatch(/ng-input-indicator-wait/); * * pause(.6); * * expect(textBox.attr('className')).not().toMatch(/ng-input-indicator-wait/); * expect(textBox.attr('className')).toMatch(/ng-validation-error/); * * }); * */ /* * cache is attached to the element * cache: { * inputs : { * 'user input': { * response: server response, * error: validation error * }, * current: 'current input' * } * */ 'asynchronous': function(input, asynchronousFn, updateFn) { if (!input) return; var scope = this; var element = scope.$element; var cache = element.data('$asyncValidator'); if (!cache) { element.data('$asyncValidator', cache = {inputs:{}}); } cache.current = input; var inputState = cache.inputs[input]; if (!inputState) { cache.inputs[input] = inputState = { inFlight: true }; scope.$invalidWidgets.markInvalid(scope.$element); element.addClass('ng-input-indicator-wait'); asynchronousFn(input, function(error, data) { inputState.response = data; inputState.error = error; inputState.inFlight = false; if (cache.current == input) { element.removeClass('ng-input-indicator-wait'); scope.$invalidWidgets.markValid(element); } element.data($$validate)(); scope.$root.$eval(); }); } else if (inputState.inFlight) { // request in flight, mark widget invalid, but don't show it to user scope.$invalidWidgets.markInvalid(scope.$element); } else { (updateFn||noop)(inputState.response); } return inputState.error; } }); var URL_MATCH = /^(file|ftp|http|https):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, HASH_MATCH = /^([^\?]*)?(\?([^\?]*))?$/, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp':21}, EAGER = 'eager', EAGER_PUBLISHED = EAGER + '-published'; function angularServiceInject(name, fn, inject, eager) { angularService(name, fn, {$inject:inject, $creation:eager}); } /** * @workInProgress * @ngdoc service * @name angular.service.$window * * @description * Is reference to the browser's <b>window</b> object. While <b>window</b> * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In <b><angular/></b> we always refer to it through the * $window service, so it may be overriden, removed or mocked for testing. * * All expressions are evaluated with respect to current scope so they don't * suffer from window globality. * * @example <input ng:init="greeting='Hello World!'" type="text" name="greeting" /> <button ng:click="$window.alert(greeting)">ALERT</button> */ angularServiceInject("$window", bind(window, identity, window), [], EAGER_PUBLISHED); /** * @workInProgress * @ngdoc service * @name angular.service.$document * @requires $window * * @description * Reference to the browser window.document, but wrapped into angular.element(). */ angularServiceInject("$document", function(window){ return jqLite(window.document); }, ['$window'], EAGER_PUBLISHED); /** * @workInProgress * @ngdoc service * @name angular.service.$location * @requires $browser * * @property {string} href * @property {string} protocol * @property {string} host * @property {number} port * @property {string} path * @property {Object.<string|boolean>} search * @property {string} hash * @property {string} hashPath * @property {Object.<string|boolean>} hashSearch * * @description * Parses the browser location url and makes it available to your application. * Any changes to the url are reflected into $location service and changes to * $location are reflected to url. * Notice that using browser's forward/back buttons changes the $location. * * @example <a href="#">clear hash</a> | <a href="#myPath?name=misko">test hash</a><br/> <input type='text' name="$location.hash"/> <pre>$location = {{$location}}</pre> */ angularServiceInject("$location", function(browser) { var scope = this, location = {toString:toString, update:update, updateHash: updateHash}, lastBrowserUrl = browser.getUrl(), lastLocationHref, lastLocationHash; browser.addPollFn(function() { if (lastBrowserUrl != browser.getUrl()) { update(lastBrowserUrl = browser.getUrl()); updateLastLocation(); scope.$eval(); } }); this.$onEval(PRIORITY_FIRST, updateBrowser); this.$onEval(PRIORITY_LAST, updateBrowser); update(lastBrowserUrl); updateLastLocation(); return location; // PUBLIC METHODS /** * @workInProgress * @ngdoc method * @name angular.service.$location#update * @methodOf angular.service.$location * * @description * Update location object * Does not immediately update the browser * Browser is updated at the end of $eval() * * @example * scope.$location.update('http://www.angularjs.org/path#hash?search=x'); * scope.$location.update({host: 'www.google.com', protocol: 'https'}); * scope.$location.update({hashPath: '/path', hashSearch: {a: 'b', x: true}}); * * @param {(string|Object)} href Full href as a string or hash object with properties */ function update(href) { if (isString(href)) { extend(location, parseHref(href)); } else { if (isDefined(href.hash)) { extend(href, parseHash(href.hash)); } extend(location, href); if (isDefined(href.hashPath || href.hashSearch)) { location.hash = composeHash(location); } location.href = composeHref(location); } } /** * @workInProgress * @ngdoc method * @name angular.service.$location#updateHash * @methodOf angular.service.$location * * @description * Update location hash part * @see update() * * @example * scope.$location.updateHash('/hp') * ==> update({hashPath: '/hp'}) * * scope.$location.updateHash({a: true, b: 'val'}) * ==> update({hashSearch: {a: true, b: 'val'}}) * * scope.$location.updateHash('/hp', {a: true}) * ==> update({hashPath: '/hp', hashSearch: {a: true}}) * * @param {(string|Object)} path A hashPath or hashSearch object * @param {Object=} search A hashSearch object */ function updateHash(path, search) { var hash = {}; if (isString(path)) { hash.hashPath = path; if (isDefined(search)) hash.hashSearch = search; } else hash.hashSearch = path; update(hash); } /** * @workInProgress * @ngdoc method * @name angular.service.$location#toString * @methodOf angular.service.$location * * @description * Returns string representation - href */ function toString() { updateLocation(); return location.href; } // INNER METHODS /** * Update location object * * User is allowed to change properties, so after property change, * location object is not in consistent state. * * @example * scope.$location.href = 'http://www.angularjs.org/path#a/b' * immediately after this call, other properties are still the old ones... * * This method checks the changes and update location to the consistent state */ function updateLocation() { if (location.href == lastLocationHref) { if (location.hash == lastLocationHash) { location.hash = composeHash(location); } location.href = composeHref(location); } update(location.href); } /** * Update information about last location */ function updateLastLocation() { lastLocationHref = location.href; lastLocationHash = location.hash; } /** * If location has changed, update the browser * This method is called at the end of $eval() phase */ function updateBrowser() { updateLocation(); if (location.href != lastLocationHref) { browser.setUrl(lastBrowserUrl = location.href); updateLastLocation(); } } /** * Compose href string from a location object * * @param {Object} loc The location object with all properties * @return {string} Composed href */ function composeHref(loc) { var url = toKeyValue(loc.search); var port = (loc.port == DEFAULT_PORTS[loc.protocol] ? _null : loc.port); return loc.protocol + '://' + loc.host + (port ? ':' + port : '') + loc.path + (url ? '?' + url : '') + (loc.hash ? '#' + loc.hash : ''); } /** * Compose hash string from location object * * @param {Object} loc Object with hashPath and hashSearch properties * @return {string} Hash string */ function composeHash(loc) { var hashSearch = toKeyValue(loc.hashSearch); //TODO: temporary fix for issue #158 return escape(loc.hashPath).replace(/%21/gi, '!').replace(/%3A/gi, ':').replace(/%24/gi, '$') + (hashSearch ? '?' + hashSearch : ''); } /** * Parse href string into location object * * @param {string} href * @return {Object} The location object */ function parseHref(href) { var loc = {}; var match = URL_MATCH.exec(href); if (match) { loc.href = href.replace(/#$/, ''); loc.protocol = match[1]; loc.host = match[3] || ''; loc.port = match[5] || DEFAULT_PORTS[loc.protocol] || _null; loc.path = match[6] || ''; loc.search = parseKeyValue(match[8]); loc.hash = match[10] || ''; extend(loc, parseHash(loc.hash)); } return loc; } /** * Parse hash string into object * * @param {string} hash */ function parseHash(hash) { var h = {}; var match = HASH_MATCH.exec(hash); if (match) { h.hash = hash; h.hashPath = unescape(match[1] || ''); h.hashSearch = parseKeyValue(match[3]); } return h; } }, ['$browser'], EAGER_PUBLISHED); /** * @workInProgress * @ngdoc service * @name angular.service.$log * @requires $window * * @description * Is simple service for logging. Default implementation writes the message * into the browser's console (if present). * * This is useful for debugging. * * @example <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" name="message" value="Hello World!"/> <button ng:click="$log.log(message)">log</button> <button ng:click="$log.warn(message)">warn</button> <button ng:click="$log.info(message)">info</button> <button ng:click="$log.error(message)">error</button> */ angularServiceInject("$log", function($window){ return { /** * @workInProgress * @ngdoc method * @name angular.service.$log#log * @methodOf angular.service.$log * * @description * Write a log message */ log: consoleLog('log'), /** * @workInProgress * @ngdoc method * @name angular.service.$log#warn * @methodOf angular.service.$log * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @workInProgress * @ngdoc method * @name angular.service.$log#info * @methodOf angular.service.$log * * @description * Write an information message */ info: consoleLog('info'), /** * @workInProgress * @ngdoc method * @name angular.service.$log#error * @methodOf angular.service.$log * * @description * Write an error message */ error: consoleLog('error') }; function consoleLog(type) { var console = $window.console || {}; var logFn = console[type] || console.log || noop; if (logFn.apply) { return function(){ var args = []; foreach(arguments, function(arg){ args.push(formatError(arg)); }); return logFn.apply(console, args); }; } else { // we are IE, in which case there is nothing we can do return logFn; } } }, ['$window'], EAGER_PUBLISHED); /** * @workInProgress * @ngdoc service * @name angular.service.$exceptionHandler * @requires $log * * @description * Any uncaught exception in <angular/> is delegated to this service. * The default implementation simply delegates to $log.error which logs it into * the browser console. * * When unit testing it is useful to have uncaught exceptions propagate * to the test so the test will fail rather than silently log the exception * to the browser console. For this purpose you can override this service with * a simple rethrow. * * @example */ angularServiceInject('$exceptionHandler', function($log){ return function(e) { $log.error(e); }; }, ['$log'], EAGER_PUBLISHED); /** * @workInProgress * @ngdoc service * @name angular.service.$hover * @requires $browser * @requires $document * * @description * * @example */ angularServiceInject("$hover", function(browser, document) { var tooltip, self = this, error, width = 300, arrowWidth = 10, body = jqLite(document[0].body); browser.hover(function(element, show){ if (show && (error = element.attr(NG_EXCEPTION) || element.attr(NG_VALIDATION_ERROR))) { if (!tooltip) { tooltip = { callout: jqLite('<div id="ng-callout"></div>'), arrow: jqLite('<div></div>'), title: jqLite('<div class="ng-title"></div>'), content: jqLite('<div class="ng-content"></div>') }; tooltip.callout.append(tooltip.arrow); tooltip.callout.append(tooltip.title); tooltip.callout.append(tooltip.content); body.append(tooltip.callout); } var docRect = body[0].getBoundingClientRect(), elementRect = element[0].getBoundingClientRect(), leftSpace = docRect.right - elementRect.right - arrowWidth; tooltip.title.text(element.hasClass("ng-exception") ? "EXCEPTION:" : "Validation error..."); tooltip.content.text(error); if (leftSpace < width) { tooltip.arrow.addClass('ng-arrow-right'); tooltip.arrow.css({left: (width + 1)+'px'}); tooltip.callout.css({ position: 'fixed', left: (elementRect.left - arrowWidth - width - 4) + "px", top: (elementRect.top - 3) + "px", width: width + "px" }); } else { tooltip.arrow.addClass('ng-arrow-left'); tooltip.callout.css({ position: 'fixed', left: (elementRect.right + arrowWidth) + "px", top: (elementRect.top - 3) + "px", width: width + "px" }); } } else if (tooltip) { tooltip.callout.remove(); tooltip = _null; } }); }, ['$browser', '$document'], EAGER); /** * @workInProgress * @ngdoc service * @name angular.service.$invalidWidgets * * @description * Keeps references to all invalid widgets found during validation. * Can be queried to find whether there are any invalid widgets currently displayed. * * @example */ angularServiceInject("$invalidWidgets", function(){ var invalidWidgets = []; /** Remove an element from the array of invalid widgets */ invalidWidgets.markValid = function(element){ var index = indexOf(invalidWidgets, element); if (index != -1) invalidWidgets.splice(index, 1); }; /** Add an element to the array of invalid widgets */ invalidWidgets.markInvalid = function(element){ var index = indexOf(invalidWidgets, element); if (index === -1) invalidWidgets.push(element); }; /** Return count of all invalid widgets that are currently visible */ invalidWidgets.visible = function() { var count = 0; foreach(invalidWidgets, function(widget){ count = count + (isVisible(widget) ? 1 : 0); }); return count; }; /* At the end of each eval removes all invalid widgets that are not part of the current DOM. */ this.$onEval(PRIORITY_LAST, function() { for(var i = 0; i < invalidWidgets.length;) { var widget = invalidWidgets[i]; if (isOrphan(widget[0])) { invalidWidgets.splice(i, 1); if (widget.dealoc) widget.dealoc(); } else { i++; } } }); /** * Traverses DOM element's (widget's) parents and considers the element to be an orphant if one of * it's parents isn't the current window.document. */ function isOrphan(widget) { if (widget == window.document) return false; var parent = widget.parentNode; return !parent || isOrphan(parent); } return invalidWidgets; }, [], EAGER_PUBLISHED); function switchRouteMatcher(on, when, dstName) { var regex = '^' + when.replace(/[\.\\\(\)\^\$]/g, "\$1") + '$', params = [], dst = {}; foreach(when.split(/\W/), function(param){ if (param) { var paramRegExp = new RegExp(":" + param + "([\\W])"); if (regex.match(paramRegExp)) { regex = regex.replace(paramRegExp, "([^\/]*)$1"); params.push(param); } } }); var match = on.match(new RegExp(regex)); if (match) { foreach(params, function(name, index){ dst[name] = match[index + 1]; }); if (dstName) this.$set(dstName, dst); } return match ? dst : _null; } /** * @workInProgress * @ngdoc service * @name angular.service.$route * @requires $location * * @property {Object} current Name of the current route * @property {Array.<Object>} routes List of configured routes * * @description * Watches $location.hashPath and tries to map the hash to an existing route * definition. It is used for deep-linking URLs to controllers and views (HTML partials). * * $route is typically used in conjunction with ng:include widget. * * @example <p> This example shows how changing the URL hash causes the <tt>$route</tt> to match a route against the URL, and the <tt>[[ng:include]]</tt> pulls in the partial. Try changing the URL in the input box to see changes. </p> <script> angular.service('myApp', function($route) { $route.when('/Book/:bookId', {template:'rsrc/book.html', controller:BookCntl}); $route.when('/Book/:bookId/ch/:chapterId', {template:'rsrc/chapter.html', controller:ChapterCntl}); $route.onChange(function() { $route.current.scope.params = $route.current.params; }); }, {$inject: ['$route']}); function BookCntl() { this.name = "BookCntl"; } function ChapterCntl() { this.name = "ChapterCntl"; } </script> Chose: <a href="#/Book/Moby">Moby</a> | <a href="#/Book/Moby/ch/1">Moby: Ch1</a> | <a href="#/Book/Gatsby">Gatsby</a> | <a href="#/Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a><br/> <input type="text" name="$location.hashPath" size="80" /> <pre>$location={{$location}}</pre> <pre>$route.current.template={{$route.current.template}}</pre> <pre>$route.current.params={{$route.current.params}}</pre> <pre>$route.current.scope.name={{$route.current.scope.name}}</pre> <hr/> <ng:include src="$route.current.template" scope="$route.current.scope"/> */ angularServiceInject('$route', function(location) { var routes = {}, onChange = [], matcher = switchRouteMatcher, parentScope = this, dirty = 0, $route = { routes: routes, /** * @workInProgress * @ngdoc method * @name angular.service.$route#onChange * @methodOf angular.service.$route * * @param {function()} fn Function that will be called on route change * * @description * Register a handler function that will be called when route changes */ onChange: bind(onChange, onChange.push), /** * @workInProgress * @ngdoc method * @name angular.service.$route#when * @methodOf angular.service.$route * * @param {string} path Route path (matched against $location.hash) * @param {Object} params Mapping information to be assigned to `$route.current` on route * match. * @returns {Object} route object * * @description * Add new route */ when:function (path, params) { if (angular.isUndefined(path)) return routes; var route = routes[path]; if (!route) route = routes[path] = {}; if (params) angular.extend(route, params); dirty++; return route; } }; function updateRoute(){ var childScope; $route.current = _null; angular.foreach(routes, function(routeParams, route) { if (!childScope) { var pathParams = matcher(location.hashPath, route); if (pathParams) { childScope = angular.scope(parentScope); $route.current = angular.extend({}, routeParams, { scope: childScope, params: angular.extend({}, location.hashSearch, pathParams) }); } } }); angular.foreach(onChange, parentScope.$tryEval); if (childScope) { childScope.$become($route.current.controller); } } this.$watch(function(){return dirty + location.hash;}, updateRoute); return $route; }, ['$location'], EAGER_PUBLISHED); /** * @workInProgress * @ngdoc service * @name angular.service.$xhr * @requires $browser * @requires $xhr.error * @requires $log * * @description * * @example */ angularServiceInject('$xhr', function($browser, $error, $log){ var self = this; return function(method, url, post, callback){ if (isFunction(post)) { callback = post; post = _null; } if (post && isObject(post)) { post = toJson(post); } $browser.xhr(method, url, post, function(code, response){ try { if (isString(response) && /^\s*[\[\{]/.exec(response) && /[\}\]]\s*$/.exec(response)) { response = fromJson(response); } if (code == 200) { callback(code, response); } else { $error( {method: method, url:url, data:post, callback:callback}, {status: code, body:response}); } } catch (e) { $log.error(e); } finally { self.$eval(); } }); }; }, ['$browser', '$xhr.error', '$log']); /** * @workInProgress * @ngdoc service * @name angular.service.$xhr.error * @requires $log * * @description * * @example */ angularServiceInject('$xhr.error', function($log){ return function(request, response){ $log.error('ERROR: XHR: ' + request.url, request, response); }; }, ['$log']); /** * @workInProgress * @ngdoc service * @name angular.service.$xhr.bulk * @requires $xhr * @requires $xhr.error * @requires $log * * @description * * @example */ angularServiceInject('$xhr.bulk', function($xhr, $error, $log){ var requests = [], scope = this; function bulkXHR(method, url, post, callback) { if (isFunction(post)) { callback = post; post = _null; } var currentQueue; foreach(bulkXHR.urls, function(queue){ if (isFunction(queue.match) ? queue.match(url) : queue.match.exec(url)) { currentQueue = queue; } }); if (currentQueue) { if (!currentQueue.requests) currentQueue.requests = []; currentQueue.requests.push({method: method, url: url, data:post, callback:callback}); } else { $xhr(method, url, post, callback); } } bulkXHR.urls = {}; bulkXHR.flush = function(callback){ foreach(bulkXHR.urls, function(queue, url){ var currentRequests = queue.requests; if (currentRequests && currentRequests.length) { queue.requests = []; queue.callbacks = []; $xhr('POST', url, {requests:currentRequests}, function(code, response){ foreach(response, function(response, i){ try { if (response.status == 200) { (currentRequests[i].callback || noop)(response.status, response.response); } else { $error(currentRequests[i], response); } } catch(e) { $log.error(e); } }); (callback || noop)(); }); scope.$eval(); } }); }; this.$onEval(PRIORITY_LAST, bulkXHR.flush); return bulkXHR; }, ['$xhr', '$xhr.error', '$log']); /** * @workInProgress * @ngdoc service * @name angular.service.$defer * @requires $browser * @requires $log * * @description * Delegates to {@link angular.service.$browser.defer $browser.defer}, but wraps the `fn` function * into a try/catch block and delegates any exceptions to * {@link angular.services.$exceptionHandler $exceptionHandler} service. * * In tests you can use `$browser.defer.flush()` to flush the queue of deferred functions. * * @param {function()} fn A function, who's execution should be deferred. */ angularServiceInject('$defer', function($browser, $exceptionHandler) { return function(fn) { $browser.defer(function() { try { fn(); } catch(e) { $exceptionHandler(e); } }); }; }, ['$browser', '$exceptionHandler']); /** * @workInProgress * @ngdoc service * @name angular.service.$xhr.cache * @requires $xhr * * @description * * @example */ angularServiceInject('$xhr.cache', function($xhr, $defer){ var inflight = {}, self = this; function cache(method, url, post, callback, verifyCache){ if (isFunction(post)) { callback = post; post = _null; } if (method == 'GET') { var data, dataCached; if (dataCached = cache.data[url]) { $defer(function() { callback(200, copy(dataCached.value)); }); if (!verifyCache) return; } if (data = inflight[url]) { data.callbacks.push(callback); } else { inflight[url] = {callbacks: [callback]}; cache.delegate(method, url, post, function(status, response){ if (status == 200) cache.data[url] = { value: response }; var callbacks = inflight[url].callbacks; delete inflight[url]; foreach(callbacks, function(callback){ try { (callback||noop)(status, copy(response)); } catch(e) { self.$log.error(e); } }); }); } } else { cache.data = {}; cache.delegate(method, url, post, callback); } } cache.data = {}; cache.delegate = $xhr; return cache; }, ['$xhr.bulk', '$defer']); /** * @workInProgress * @ngdoc service * @name angular.service.$resource * @requires $xhr * * @description * Is a factory which creates a resource object which lets you interact with * <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" target="_blank">RESTful</a> * server-side data sources. * Resource object has action methods which provide high-level behaviors without * the need to interact with the low level $xhr or XMLHttpRequest(). * * <pre> // Define CreditCard class var CreditCard = $resource('/user/:userId/card/:cardId', {userId:123, cardId:'@id'}, { charge: {method:'POST', params:{charge:true}} }); // We can retrieve a collection from the server var cards = CreditCard.query(); // GET: /user/123/card // server returns: [ {id:456, number:'1234', name:'Smith'} ]; var card = cards[0]; // each item is an instance of CreditCard expect(card instanceof CreditCard).toEqual(true); card.name = "J. Smith"; // non GET methods are mapped onto the instances card.$save(); // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // our custom method is mapped as well. card.$charge({amount:9.99}); // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // we can create an instance as well var newCard = new CreditCard({number:'0123'}); newCard.name = "Mike Smith"; newCard.$save(); // POST: /user/123/card {number:'0123', name:'Mike Smith'} // server returns: {id:789, number:'01234', name: 'Mike Smith'}; expect(newCard.id).toEqual(789); * </pre> * * * @param {string} url A parameterized URL template with parameters prefixed by `:` as in * `/user/:username`. * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in * `actions` methods. * @param {Object.<Object>=} actions Map of actions available for the resource. * * Each resource comes preconfigured with `get`, `save`, `query`, `remove`, and `delete` to * mimic the RESTful philosophy. * * To create your own actions, pass in a map keyed on action names (e.g. `'charge'`) with * elements consisting of these properties: * * - `{string} method`: Request method type. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`, * and [`JSON`](http://en.wikipedia.org/wiki/JSON#JSONP) (also known as JSONP). * - `{Object=} params`: Set of pre-bound parameters for the action. * - `{boolean=} isArray`: If true then the returned object for this action is an array, see the * pre-binding section. * - `{boolean=} verifyCache`: If true then items returned from cache, are double checked by * running the query again and updating the resource asynchroniously. * * Each service comes preconfigured with the following overridable actions: * <pre> * { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }; * </pre> * * @returns {Object} A resource "class" which has "static" method for each action in the definition. * Calling these methods invoke `$xhr` on the `url` template with the given `method` and * `params`. When the data is returned from the server then the object is an instance of the * resource type and all of the non-GET methods are available with `$` prefix. This allows you * to easily support CRUD operations (create, read, update, delete) on server-side data. <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function(){ user.abc = true; user.$save(); }); </pre> * * * @example <script> function BuzzController($resource) { this.Activity = $resource( 'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments', {alt:'json', callback:'JSON_CALLBACK'}, {get:{method:'JSON', params:{visibility:'@self'}}, replies: {method:'JSON', params:{visibility:'@self', comments:'@comments'}}} ); } BuzzController.prototype = { fetch: function() { this.activities = this.Activity.get({userId:this.userId}); }, expandReplies: function(activity) { activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id}); } }; BuzzController.$inject = ['$resource']; </script> <div ng:controller="BuzzController"> <input name="userId" value="googlebuzz"/> <button ng:click="fetch()">fetch</button> <hr/> <div ng:repeat="item in activities.data.items"> <h1 style="font-size: 15px;"> <img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a> <a href ng:click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a> </h1> {{item.object.content | html}} <div ng:repeat="reply in item.replies.data.items" style="margin-left: 20px;"> <img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}} </div> </div> </div> */ angularServiceInject('$resource', function($xhr){ var resource = new ResourceFactory($xhr); return bind(resource, resource.route); }, ['$xhr.cache']); /** * @workInProgress * @ngdoc service * @name angular.service.$cookies * @requires $browser * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from * this object, new cookies are created/deleted at the end of current $eval. * * @example */ angularServiceInject('$cookies', function($browser) { var rootScope = this, cookies = {}, lastCookies = {}, lastBrowserCookies; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); rootScope.$eval(); } })(); //at the end of each eval, push cookies this.$onEval(PRIORITY_LAST, push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were stored. */ function push(){ var name, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, _undefined); } } //update all cookies updated in $cookies for(name in cookies) { if (cookies[name] !== lastCookies[name]) { $browser.cookies(name, cookies[name]); updated = true; } } //verify what was actually stored if (updated){ updated = !updated; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } if (updated) { rootScope.$eval(); } } } }, ['$browser'], EAGER_PUBLISHED); /** * @workInProgress * @ngdoc service * @name angular.service.$cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * @example */ angularServiceInject('$cookieStore', function($store) { return { /** * @workInProgress * @ngdoc method * @name angular.service.$cookieStore#get * @methodOf angular.service.$cookieStore * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { return fromJson($store[key]); }, /** * @workInProgress * @ngdoc method * @name angular.service.$cookieStore#put * @methodOf angular.service.$cookieStore * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $store[key] = toJson(value); }, /** * @workInProgress * @ngdoc method * @name angular.service.$cookieStore#remove * @methodOf angular.service.$cookieStore * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $store[key]; } }; }, ['$cookies']); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:init * * @description * `ng:init` attribute allows the for initialization tasks to be executed * before the template enters execution mode during bootstrap. * * @element ANY * @param {expression} expression to eval. * * @example <div ng:init="greeting='Hello'; person='World'"> {{greeting}} {{person}}! </div> * * @scenario it('should check greeting', function(){ expect(binding('greeting')).toBe('Hello'); expect(binding('person')).toBe('World'); }); */ angularDirective("ng:init", function(expression){ return function(element){ this.$tryEval(expression, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:controller * * @description * To support the Model-View-Controller design pattern, it is possible * to assign behavior to a scope through `ng:controller`. The scope is * the MVC model. The HTML (with data bindings) is the MVC view. * The `ng:controller` directive specifies the MVC controller class * * @element ANY * @param {expression} expression to eval. * * @example <script type="text/javascript"> function SettingsController() { this.name = "John Smith"; this.contacts = [ {type:'phone', value:'408 555 1212'}, {type:'email', value:'john.smith@example.org'} ]; } SettingsController.prototype = { greet: function(){ alert(this.name); }, addContact: function(){ this.contacts.push({type:'email', value:'yourname@example.org'}); }, removeContact: function(contactToRemove) { angular.Array.remove(this.contacts, contactToRemove); }, clearContact: function(contact) { contact.type = 'phone'; contact.value = ''; } }; </script> <div ng:controller="SettingsController"> Name: <input type="text" name="name"/> [ <a href="" ng:click="greet()">greet</a> ]<br/> Contact: <ul> <li ng:repeat="contact in contacts"> <select name="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" name="contact.value"/> [ <a href="" ng:click="clearContact(contact)">clear</a> | <a href="" ng:click="removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng:click="addContact()">add</a> ]</li> </ul> </div> * * @scenario it('should check controller', function(){ expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li[ng\\:repeat-index="0"] input').val()).toBe('408 555 1212'); expect(element('.doc-example-live li[ng\\:repeat-index="1"] input').val()).toBe('john.smith@example.org'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li[ng\\:repeat-index="2"] input').val()).toBe('yourname@example.org'); }); */ angularDirective("ng:controller", function(expression){ this.scope(true); return function(element){ var controller = getter(window, expression, true) || getter(this, expression, true); if (!controller) throw "Can not find '"+expression+"' controller."; if (!isFunction(controller)) throw "Reference '"+expression+"' is not a class."; this.$become(controller); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:eval * * @description * The `ng:eval` allows you to execute a binding which has side effects * without displaying the result to the user. * * @element ANY * @param {expression} expression to eval. * * @exampleDescription * Notice that `{{` `obj.multiplied = obj.a * obj.b` `}}` has a side effect of assigning * a value to `obj.multiplied` and displaying the result to the user. Sometimes, * however, it is desirable to execute a side effect without showing the value to * the user. In such a case `ng:eval` allows you to execute code without updating * the display. * * @example * <input name="obj.a" value="6" > * * <input name="obj.b" value="2"> * = {{obj.multiplied = obj.a * obj.b}} <br> * <span ng:eval="obj.divide = obj.a / obj.b"></span> * <span ng:eval="obj.updateCount = 1 + (obj.updateCount||0)"></span> * <tt>obj.divide = {{obj.divide}}</tt><br/> * <tt>obj.updateCount = {{obj.updateCount}}</tt> * * @scenario it('should check eval', function(){ expect(binding('obj.divide')).toBe('3'); expect(binding('obj.updateCount')).toBe('2'); input('obj.a').enter('12'); expect(binding('obj.divide')).toBe('6'); expect(binding('obj.updateCount')).toBe('3'); }); */ angularDirective("ng:eval", function(expression){ return function(element){ this.$onEval(expression, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:bind * * @description * The `ng:bind` attribute asks <angular/> to replace the text content of this * HTML element with the value of the given expression and kept it up to * date when the expression's value changes. Usually you just write * {{expression}} and let <angular/> compile it into * `<span ng:bind="expression"></span>` at bootstrap time. * * @element ANY * @param {expression} expression to eval. * * @exampleDescription * Try it here: enter text in text box and watch the greeting change. * @example * Enter name: <input type="text" name="name" value="Whirled">. <br> * Hello <span ng:bind="name" />! * * @scenario it('should check ng:bind', function(){ expect(using('.doc-example-live').binding('name')).toBe('Whirled'); using('.doc-example-live').input('name').enter('world'); expect(using('.doc-example-live').binding('name')).toBe('world'); }); */ angularDirective("ng:bind", function(expression, element){ element.addClass('ng-binding'); return function(element) { var lastValue = noop, lastError = noop; this.$onEval(function() { var error, value, html, isHtml, isDomElement, oldElement = this.hasOwnProperty($$element) ? this.$element : _undefined; this.$element = element; value = this.$tryEval(expression, function(e){ error = formatError(e); }); this.$element = oldElement; // If we are HTML than save the raw HTML data so that we don't // recompute sanitization since it is expensive. // TODO: turn this into a more generic way to compute this if (isHtml = (value instanceof HTML)) value = (html = value).html; if (lastValue === value && lastError == error) return; isDomElement = isElement(value); if (!isHtml && !isDomElement && isObject(value)) { value = toJson(value); } if (value != lastValue || error != lastError) { lastValue = value; lastError = error; elementError(element, NG_EXCEPTION, error); if (error) value = error; if (isHtml) { element.html(html.get()); } else if (isDomElement) { element.html(''); element.append(value); } else { element.text(value === _undefined ? '' : value); } } }, element); }; }); var bindTemplateCache = {}; function compileBindTemplate(template){ var fn = bindTemplateCache[template]; if (!fn) { var bindings = []; foreach(parseBindings(template), function(text){ var exp = binding(text); bindings.push(exp ? function(element){ var error, value = this.$tryEval(exp, function(e){ error = toJson(e); }); elementError(element, NG_EXCEPTION, error); return error ? error : value; } : function() { return text; }); }); bindTemplateCache[template] = fn = function(element){ var parts = [], self = this, oldElement = this.hasOwnProperty($$element) ? self.$element : _undefined; self.$element = element; for ( var i = 0; i < bindings.length; i++) { var value = bindings[i].call(self, element); if (isElement(value)) value = ''; else if (isObject(value)) value = toJson(value, true); parts.push(value); } self.$element = oldElement; return parts.join(''); }; } return fn; } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:bind-template * * @description * The `ng:bind-template` attribute specifies that the element * text should be replaced with the template in ng:bind-template. * Unlike ng:bind the ng:bind-template can contain multiple `{{` `}}` * expressions. (This is required since some HTML elements * can not have SPAN elements such as TITLE, or OPTION to name a few. * * @element ANY * @param {string} template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @exampleDescription * Try it here: enter text in text box and watch the greeting change. * @example Salutation: <input type="text" name="salutation" value="Hello"><br/> Name: <input type="text" name="name" value="World"><br/> <pre ng:bind-template="{{salutation}} {{name}}!"></pre> * * @scenario it('should check ng:bind', function(){ expect(using('.doc-example-live').binding('{{salutation}} {{name}}')). toBe('Hello World!'); using('.doc-example-live').input('salutation').enter('Greetings'); using('.doc-example-live').input('name').enter('user'); expect(using('.doc-example-live').binding('{{salutation}} {{name}}')). toBe('Greetings user!'); }); */ angularDirective("ng:bind-template", function(expression, element){ element.addClass('ng-binding'); var templateFn = compileBindTemplate(expression); return function(element) { var lastValue; this.$onEval(function() { var value = templateFn.call(this, element); if (value != lastValue) { element.text(value); lastValue = value; } }, element); }; }); var REMOVE_ATTRIBUTES = { 'disabled':'disabled', 'readonly':'readOnly', 'checked':'checked', 'selected':'selected' }; /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:bind-attr * * @description * The `ng:bind-attr` attribute specifies that the element attributes * which should be replaced by the expression in it. Unlike `ng:bind` * the `ng:bind-attr` contains a JSON key value pairs representing * which attributes need to be changed. You don’t usually write the * `ng:bind-attr` in the HTML since embedding * <tt ng:non-bindable>{{expression}}</tt> into the * attribute directly is the preferred way. The attributes get * translated into `<span ng:bind-attr="{attr:expression}"/>` at * bootstrap time. * * This HTML snippet is preferred way of working with `ng:bind-attr` * <pre> * <a href="http://www.google.com/search?q={{query}}">Google</a> * </pre> * * The above gets translated to bellow during bootstrap time. * <pre> * <a ng:bind-attr='{"href":"http://www.google.com/search?q={{query}}"}'>Google</a> * </pre> * * @element ANY * @param {string} attribute_json a JSON key-value pairs representing * the attributes to replace. Each key matches the attribute * which needs to be replaced. Each value is a text template of * the attribute with embedded * <tt ng:non-bindable>{{expression}}</tt>s. Any number of * key-value pairs can be specified. * * @exampleDescription * Try it here: enter text in text box and click Google. * @example Google for: <input type="text" name="query" value="AngularJS"/> <a href="http://www.google.com/search?q={{query}}">Google</a> * * @scenario it('should check ng:bind-attr', function(){ expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=AngularJS'); using('.doc-example-live').input('query').enter('google'); expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=google'); }); */ angularDirective("ng:bind-attr", function(expression){ return function(element){ var lastValue = {}; var updateFn = element.data($$update) || noop; this.$onEval(function(){ var values = this.$eval(expression), dirty = noop; for(var key in values) { var value = compileBindTemplate(values[key]).call(this, element), specialName = REMOVE_ATTRIBUTES[lowercase(key)]; if (lastValue[key] !== value) { lastValue[key] = value; if (specialName) { if (toBoolean(value)) { element.attr(specialName, specialName); element.attr('ng-' + specialName, value); } else { element.removeAttr(specialName); element.removeAttr('ng-' + specialName); } (element.data($$validate)||noop)(); } else { element.attr(key, value); } dirty = updateFn; } } dirty(); }, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:click * * @description * The ng:click allows you to specify custom behavior when * element is clicked. * * @element ANY * @param {expression} expression to eval upon click. * * @example <button ng:click="count = count + 1" ng:init="count=0"> Increment </button> count: {{count}} * @scenario it('should check ng:click', function(){ expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. * * TODO: maybe we should consider allowing users to control event propagation in the future. */ angularDirective("ng:click", function(expression, element){ return function(element){ var self = this; element.bind('click', function(event){ self.$tryEval(expression, element); self.$root.$eval(); event.stopPropagation(); }); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:submit * * @description * * @element form * @param {expression} expression to eval. * * @exampleDescription * @example * <form ng:submit="list.push(text);text='';" ng:init="list=[]"> * Enter text and hit enter: * <input type="text" name="text" value="hello"/> * </form> * <pre>list={{list}}</pre> * @scenario it('should check ng:submit', function(){ expect(binding('list')).toBe('list=[]'); element('.doc-example-live form input').click(); this.addFutureAction('submit from', function($window, $document, done) { $window.angular.element( $document.elements('.doc-example-live form')). trigger('submit'); done(); }); expect(binding('list')).toBe('list=["hello"]'); }); */ /** * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page). */ angularDirective("ng:submit", function(expression, element) { return function(element) { var self = this; element.bind('submit', function(event) { self.$tryEval(expression, element); self.$root.$eval(); event.preventDefault(); }); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:watch * * @description * The `ng:watch` allows you watch a variable and then execute * an evaluation on variable change. * * @element ANY * @param {expression} expression to eval. * * @exampleDescription * Notice that the counter is incremented * every time you change the text. * @example <div ng:init="counter=0" ng:watch="name: counter = counter+1"> <input type="text" name="name" value="hello"><br/> Change counter: {{counter}} Name: {{name}} </div> * @scenario it('should check ng:watch', function(){ expect(using('.doc-example-live').binding('counter')).toBe('2'); using('.doc-example-live').input('name').enter('abc'); expect(using('.doc-example-live').binding('counter')).toBe('3'); }); */ //TODO: delete me, since having watch in UI is logic in UI. (leftover form getangular) angularDirective("ng:watch", function(expression, element){ return function(element){ var self = this; parser(expression).watch()({ addListener:function(watch, exp){ self.$watch(watch, function(){ return exp(self); }, element); } }); }; }); function ngClass(selector) { return function(expression, element){ var existing = element[0].className + ' '; return function(element){ this.$onEval(function(){ if (selector(this.$index)) { var value = this.$eval(expression); if (isArray(value)) value = value.join(' '); element[0].className = trim(existing + value); } }, element); }; }; } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:class * * @description * The `ng:class` allows you to set CSS class on HTML element * conditionally. * * @element ANY * @param {expression} expression to eval. * * @exampleDescription * @example <input type="button" value="set" ng:click="myVar='ng-input-indicator-wait'"> <input type="button" value="clear" ng:click="myVar=''"> <br> <span ng:class="myVar">Sample Text &nbsp;&nbsp;&nbsp;&nbsp;</span> * * @scenario it('should check ng:class', function(){ expect(element('.doc-example-live span').attr('className')).not(). toMatch(/ng-input-indicator-wait/); using('.doc-example-live').element(':button:first').click(); expect(element('.doc-example-live span').attr('className')). toMatch(/ng-input-indicator-wait/); using('.doc-example-live').element(':button:last').click(); expect(element('.doc-example-live span').attr('className')).not(). toMatch(/ng-input-indicator-wait/); }); */ angularDirective("ng:class", ngClass(function(){return true;})); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:class-odd * * @description * The `ng:class-odd` and `ng:class-even` works exactly as * `ng:class`, except it works in conjunction with `ng:repeat` * and takes affect only on odd (even) rows. * * @element ANY * @param {expression} expression to eval. Must be inside * `ng:repeat`. * * @exampleDescription * @example <ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng:repeat="name in names"> <span ng:class-odd="'ng-format-negative'" ng:class-even="'ng-input-indicator-wait'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> * * @scenario it('should check ng:class-odd and ng:class-even', function(){ expect(element('.doc-example-live li:first span').attr('className')). toMatch(/ng-format-negative/); expect(element('.doc-example-live li:last span').attr('className')). toMatch(/ng-input-indicator-wait/); }); */ angularDirective("ng:class-odd", ngClass(function(i){return i % 2 === 0;})); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:class-even * * @description * The `ng:class-odd` and `ng:class-even` works exactly as * `ng:class`, except it works in conjunction with `ng:repeat` * and takes affect only on odd (even) rows. * * @element ANY * @param {expression} expression to eval. Must be inside * `ng:repeat`. * * @exampleDescription * @example <ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng:repeat="name in names"> <span ng:class-odd="'ng-format-negative'" ng:class-even="'ng-input-indicator-wait'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> * * @scenario it('should check ng:class-odd and ng:class-even', function(){ expect(element('.doc-example-live li:first span').attr('className')). toMatch(/ng-format-negative/); expect(element('.doc-example-live li:last span').attr('className')). toMatch(/ng-input-indicator-wait/); }); */ angularDirective("ng:class-even", ngClass(function(i){return i % 2 === 1;})); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:show * * @description * The `ng:show` and `ng:hide` allows you to show or hide a portion * of the HTML conditionally. * * @element ANY * @param {expression} expression if truthy then the element is * shown or hidden respectively. * * @exampleDescription * @example Click me: <input type="checkbox" name="checked"><br/> Show: <span ng:show="checked">I show up when you checkbox is checked?</span> <br/> Hide: <span ng:hide="checked">I hide when you checkbox is checked?</span> * * @scenario it('should check ng:show / ng:hide', function(){ expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); */ angularDirective("ng:show", function(expression, element){ return function(element){ this.$onEval(function(){ element.css($display, toBoolean(this.$eval(expression)) ? '' : $none); }, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:hide * * @description * The `ng:show` and `ng:hide` allows you to show or hide a portion * of the HTML conditionally. * * @element ANY * @param {expression} expression if truthy then the element is * shown or hidden respectively. * * @exampleDescription * @example Click me: <input type="checkbox" name="checked"><br/> Show: <span ng:show="checked">I show up when you checkbox is checked?</span> <br/> Hide: <span ng:hide="checked">I hide when you checkbox is checked?</span> * * @scenario it('should check ng:show / ng:hide', function(){ expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); */ angularDirective("ng:hide", function(expression, element){ return function(element){ this.$onEval(function(){ element.css($display, toBoolean(this.$eval(expression)) ? $none : ''); }, element); }; }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:style * * @description * The ng:style allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} expression which evals to an object whes key's are * CSS style names and values are coresponding values for those * CSS keys. * * @exampleDescription * @example <input type="button" value="set" ng:click="myStyle={color:'red'}"> <input type="button" value="clear" ng:click="myStyle={}"> <br/> <span ng:style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> * * @scenario it('should check ng:style', function(){ expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); element('.doc-example-live :button[value=set]').click(); expect(element('.doc-example-live span').css('color')).toBe('red'); element('.doc-example-live :button[value=clear]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); }); */ angularDirective("ng:style", function(expression, element){ return function(element){ var resetStyle = getStyle(element); this.$onEval(function(){ var style = this.$eval(expression) || {}, key, mergedStyle = {}; for(key in style) { if (resetStyle[key] === _undefined) resetStyle[key] = ''; mergedStyle[key] = style[key]; } for(key in resetStyle) { mergedStyle[key] = mergedStyle[key] || resetStyle[key]; } element.css(mergedStyle); }, element); }; }); function parseBindings(string) { var results = []; var lastIndex = 0; var index; while((index = string.indexOf('{{', lastIndex)) > -1) { if (lastIndex < index) results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; index = string.indexOf('}}', index); index = index < 0 ? string.length : index + 2; results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; } if (lastIndex != string.length) results.push(string.substr(lastIndex, string.length - lastIndex)); return results.length === 0 ? [ string ] : results; } function binding(string) { var binding = string.replace(/\n/gm, ' ').match(/^\{\{(.*)\}\}$/); return binding ? binding[1] : _null; } function hasBindings(bindings) { return bindings.length > 1 || binding(bindings[0]) !== _null; } angularTextMarkup('{{}}', function(text, textNode, parentElement) { var bindings = parseBindings(text), self = this; if (hasBindings(bindings)) { if (isLeafNode(parentElement[0])) { parentElement.attr('ng:bind-template', text); } else { var cursor = textNode, newElement; foreach(parseBindings(text), function(text){ var exp = binding(text); if (exp) { newElement = self.element('span'); newElement.attr('ng:bind', exp); } else { newElement = self.text(text); } if (msie && text.charAt(0) == ' ') { newElement = jqLite('<span>&nbsp;</span>'); var nbsp = newElement.html(); newElement.text(text.substr(1)); newElement.html(nbsp + newElement.html()); } cursor.after(newElement); cursor = newElement; }); textNode.remove(); } } }); // TODO: this should be widget not a markup angularTextMarkup('OPTION', function(text, textNode, parentElement){ if (nodeName(parentElement) == "OPTION") { var select = document.createElement('select'); select.insertBefore(parentElement[0].cloneNode(true), _null); if (!select.innerHTML.match(/<option(\s.*\s|\s)value\s*=\s*.*>.*<\/\s*option\s*>/gi)) { parentElement.attr('value', text); } } }); /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:href * * @description * Using <angular/> markup like {{hash}} in an href attribute makes * the page open to a wrong URL, ff the user clicks that link before * angular has a chance to replace the {{hash}} with actual URL, the * link will be broken and will most likely return a 404 error. * The `ng:href` solves this problem by placing the `href` in the * `ng:` namespace. * * The buggy way to write it: * <pre> * <a href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <a ng:href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element ANY * @param {template} template any string which can contain `{{}}` markup. */ /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:src * * @description * Using <angular/> markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until <angular/> replaces the expression inside * `{{hash}}`. The `ng:src` attribute solves this problem by placing * the `src` attribute in the `ng:` namespace. * * The buggy way to write it: * <pre> * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <img ng:src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element ANY * @param {template} template any string which can contain `{{}}` markup. */ var NG_BIND_ATTR = 'ng:bind-attr'; var SPECIAL_ATTRS = {'ng:src': 'src', 'ng:href': 'href'}; angularAttrMarkup('{{}}', function(value, name, element){ // don't process existing attribute markup if (angularDirective(name) || angularDirective("@" + name)) return; if (msie && name == 'src') value = decodeURI(value); var bindings = parseBindings(value), bindAttr; if (hasBindings(bindings)) { element.removeAttr(name); bindAttr = fromJson(element.attr(NG_BIND_ATTR) || "{}"); bindAttr[SPECIAL_ATTRS[name] || name] = value; element.attr(NG_BIND_ATTR, toJson(bindAttr)); } }); /** * @workInProgress * @ngdoc widget * @name angular.widget.HTML * * @description * The most common widgets you will use will be in the from of the * standard HTML set. These widgets are bound using the name attribute * to an expression. In addition they can have `ng:validate`, `ng:required`, * `ng:format`, `ng:change` attribute to further control their behavior. * * @usageContent * see example below for usage * * <input type="text|checkbox|..." ... /> * <textarea ... /> * <select ...> * <option>...</option> * </select> * * @example <table style="font-size:.9em;"> <tr> <th>Name</th> <th>Format</th> <th>HTML</th> <th>UI</th> <th ng:non-bindable>{{input#}}</th> </tr> <tr> <th>text</th> <td>String</td> <td><tt>&lt;input type="text" name="input1"&gt;</tt></td> <td><input type="text" name="input1" size="4"></td> <td><tt>{{input1|json}}</tt></td> </tr> <tr> <th>textarea</th> <td>String</td> <td><tt>&lt;textarea name="input2"&gt;&lt;/textarea&gt;</tt></td> <td><textarea name="input2" cols='6'></textarea></td> <td><tt>{{input2|json}}</tt></td> </tr> <tr> <th>radio</th> <td>String</td> <td><tt> &lt;input type="radio" name="input3" value="A"&gt;<br> &lt;input type="radio" name="input3" value="B"&gt; </tt></td> <td> <input type="radio" name="input3" value="A"> <input type="radio" name="input3" value="B"> </td> <td><tt>{{input3|json}}</tt></td> </tr> <tr> <th>checkbox</th> <td>Boolean</td> <td><tt>&lt;input type="checkbox" name="input4" value="checked"&gt;</tt></td> <td><input type="checkbox" name="input4" value="checked"></td> <td><tt>{{input4|json}}</tt></td> </tr> <tr> <th>pulldown</th> <td>String</td> <td><tt> &lt;select name="input5"&gt;<br> &nbsp;&nbsp;&lt;option value="c"&gt;C&lt;/option&gt;<br> &nbsp;&nbsp;&lt;option value="d"&gt;D&lt;/option&gt;<br> &lt;/select&gt;<br> </tt></td> <td> <select name="input5"> <option value="c">C</option> <option value="d">D</option> </select> </td> <td><tt>{{input5|json}}</tt></td> </tr> <tr> <th>multiselect</th> <td>Array</td> <td><tt> &lt;select name="input6" multiple size="4"&gt;<br> &nbsp;&nbsp;&lt;option value="e"&gt;E&lt;/option&gt;<br> &nbsp;&nbsp;&lt;option value="f"&gt;F&lt;/option&gt;<br> &lt;/select&gt;<br> </tt></td> <td> <select name="input6" multiple size="4"> <option value="e">E</option> <option value="f">F</option> </select> </td> <td><tt>{{input6|json}}</tt></td> </tr> </table> * @scenario * it('should exercise text', function(){ * input('input1').enter('Carlos'); * expect(binding('input1')).toEqual('"Carlos"'); * }); * it('should exercise textarea', function(){ * input('input2').enter('Carlos'); * expect(binding('input2')).toEqual('"Carlos"'); * }); * it('should exercise radio', function(){ * expect(binding('input3')).toEqual('null'); * input('input3').select('A'); * expect(binding('input3')).toEqual('"A"'); * input('input3').select('B'); * expect(binding('input3')).toEqual('"B"'); * }); * it('should exercise checkbox', function(){ * expect(binding('input4')).toEqual('false'); * input('input4').check(); * expect(binding('input4')).toEqual('true'); * }); * it('should exercise pulldown', function(){ * expect(binding('input5')).toEqual('"c"'); * select('input5').option('d'); * expect(binding('input5')).toEqual('"d"'); * }); * it('should exercise multiselect', function(){ * expect(binding('input6')).toEqual('[]'); * select('input6').options('e'); * expect(binding('input6')).toEqual('["e"]'); * select('input6').options('e', 'f'); * expect(binding('input6')).toEqual('["e","f"]'); * }); */ function modelAccessor(scope, element) { var expr = element.attr('name'); if (!expr) throw "Required field 'name' not found."; return { get: function() { return scope.$eval(expr); }, set: function(value) { if (value !== _undefined) { return scope.$tryEval(expr + '=' + toJson(value), element); } } }; } function modelFormattedAccessor(scope, element) { var accessor = modelAccessor(scope, element), formatterName = element.attr('ng:format') || NOOP, formatter = angularFormatter(formatterName); if (!formatter) throw "Formatter named '" + formatterName + "' not found."; return { get: function() { return formatter.format(accessor.get()); }, set: function(value) { return accessor.set(formatter.parse(value)); } }; } function compileValidator(expr) { return parser(expr).validator()(); } /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:validate * * @description * The `ng:validate` attribute widget validates the user input. If the input does not pass * validation, the `ng-validation-error` CSS class and the `ng:error` attribute are set on the input * element. Check out {@link angular.validator validators} to find out more. * * @param {string} validator The name of a built-in or custom {@link angular.validator validator} to * to be used. * * @element INPUT * @css ng-validation-error * * @exampleDescription * This example shows how the input element becomes red when it contains invalid input. Correct * the input to make the error disappear. * * @example I don't validate: <input type="text" name="value" value="NotANumber"><br/> I need an integer or nothing: <input type="text" name="value" ng:validate="integer"><br/> * * @scenario it('should check ng:validate', function(){ expect(element('.doc-example-live :input:last').attr('className')). toMatch(/ng-validation-error/); input('value').enter('123'); expect(element('.doc-example-live :input:last').attr('className')). not().toMatch(/ng-validation-error/); }); */ /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:required * * @description * The `ng:required` attribute widget validates that the user input is present. It is a special case * of the {@link angular.widget.@ng:validate ng:validate} attribute widget. * * @element INPUT * @css ng-validation-error * * @exampleDescription * This example shows how the input element becomes red when it contains invalid input. Correct * the input to make the error disappear. * * @example I cannot be blank: <input type="text" name="value" ng:required><br/> * * @scenario it('should check ng:required', function(){ expect(element('.doc-example-live :input').attr('className')).toMatch(/ng-validation-error/); input('value').enter('123'); expect(element('.doc-example-live :input').attr('className')).not().toMatch(/ng-validation-error/); }); */ /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:format * * @description * The `ng:format` attribute widget formats stored data to user-readable text and parses the text * back to the stored form. You might find this useful for example if you collect user input in a * text field but need to store the data in the model as a list. Check out * {@link angular.formatter formatters} to learn more. * * @param {string} formatter The name of the built-in or custom {@link angular.formatter formatter} * to be used. * * @element INPUT * * @exampleDescription * This example shows how the user input is converted from a string and internally represented as an * array. * * @example Enter a comma separated list of items: <input type="text" name="list" ng:format="list" value="table, chairs, plate"> <pre>list={{list}}</pre> * * @scenario it('should check ng:format', function(){ expect(binding('list')).toBe('list=["table","chairs","plate"]'); input('list').enter(',,, a ,,,'); expect(binding('list')).toBe('list=["a"]'); }); */ function valueAccessor(scope, element) { var validatorName = element.attr('ng:validate') || NOOP, validator = compileValidator(validatorName), requiredExpr = element.attr('ng:required'), formatterName = element.attr('ng:format') || NOOP, formatter = angularFormatter(formatterName), format, parse, lastError, required, invalidWidgets = scope.$invalidWidgets || {markValid:noop, markInvalid:noop}; if (!validator) throw "Validator named '" + validatorName + "' not found."; if (!formatter) throw "Formatter named '" + formatterName + "' not found."; format = formatter.format; parse = formatter.parse; if (requiredExpr) { scope.$watch(requiredExpr, function(newValue) { required = newValue; validate(); }); } else { required = requiredExpr === ''; } element.data($$validate, validate); return { get: function(){ if (lastError) elementError(element, NG_VALIDATION_ERROR, _null); try { var value = parse(element.val()); validate(); return value; } catch (e) { lastError = e; elementError(element, NG_VALIDATION_ERROR, e); } }, set: function(value) { var oldValue = element.val(), newValue = format(value); if (oldValue != newValue) { element.val(newValue || ''); // needed for ie } validate(); } }; function validate() { var value = trim(element.val()); if (element[0].disabled || element[0].readOnly) { elementError(element, NG_VALIDATION_ERROR, _null); invalidWidgets.markValid(element); } else { var error, validateScope = inherit(scope, {$element:element}); error = required && !value ? 'Required' : (value ? validator(validateScope, value) : _null); elementError(element, NG_VALIDATION_ERROR, error); lastError = error; if (error) { invalidWidgets.markInvalid(element); } else { invalidWidgets.markValid(element); } } } } function checkedAccessor(scope, element) { var domElement = element[0], elementValue = domElement.value; return { get: function(){ return !!domElement.checked; }, set: function(value){ domElement.checked = toBoolean(value); } }; } function radioAccessor(scope, element) { var domElement = element[0]; return { get: function(){ return domElement.checked ? domElement.value : _null; }, set: function(value){ domElement.checked = value == domElement.value; } }; } function optionsAccessor(scope, element) { var options = element[0].options; return { get: function(){ var values = []; foreach(options, function(option){ if (option.selected) values.push(option.value); }); return values; }, set: function(values){ var keys = {}; foreach(values, function(value){ keys[value] = true; }); foreach(options, function(option){ option.selected = keys[option.value]; }); } }; } function noopAccessor() { return { get: noop, set: noop }; } var textWidget = inputWidget('keyup change', modelAccessor, valueAccessor, initWidgetValue()), buttonWidget = inputWidget('click', noopAccessor, noopAccessor, noop), INPUT_TYPE = { 'text': textWidget, 'textarea': textWidget, 'hidden': textWidget, 'password': textWidget, 'button': buttonWidget, 'submit': buttonWidget, 'reset': buttonWidget, 'image': buttonWidget, 'checkbox': inputWidget('click', modelFormattedAccessor, checkedAccessor, initWidgetValue(false)), 'radio': inputWidget('click', modelFormattedAccessor, radioAccessor, radioInit), 'select-one': inputWidget('change', modelFormattedAccessor, valueAccessor, initWidgetValue(_null)), 'select-multiple': inputWidget('change', modelFormattedAccessor, optionsAccessor, initWidgetValue([])) // 'file': fileWidget??? }; function initWidgetValue(initValue) { return function (model, view) { var value = view.get(); if (!value && isDefined(initValue)) { value = copy(initValue); } if (isUndefined(model.get()) && isDefined(value)) { model.set(value); } }; } function radioInit(model, view, element) { var modelValue = model.get(), viewValue = view.get(), input = element[0]; input.checked = false; input.name = this.$id + '@' + input.name; if (isUndefined(modelValue)) { model.set(modelValue = _null); } if (modelValue == _null && viewValue !== _null) { model.set(viewValue); } view.set(modelValue); } /** * @workInProgress * @ngdoc directive * @name angular.directive.ng:change * * @description * The directive executes an expression whenever the input widget changes. * * @element INPUT * @param {expression} expression to execute. * * @exampleDescription * @example <div ng:init="checkboxCount=0; textCount=0"></div> <input type="text" name="text" ng:change="textCount = 1 + textCount"> changeCount {{textCount}}<br/> <input type="checkbox" name="checkbox" ng:change="checkboxCount = 1 + checkboxCount"> changeCount {{checkboxCount}}<br/> * * @scenario it('should check ng:change', function(){ expect(binding('textCount')).toBe('0'); expect(binding('checkboxCount')).toBe('0'); using('.doc-example-live').input('text').enter('abc'); expect(binding('textCount')).toBe('1'); expect(binding('checkboxCount')).toBe('0'); using('.doc-example-live').input('checkbox').check(); expect(binding('textCount')).toBe('1'); expect(binding('checkboxCount')).toBe('1'); }); */ function inputWidget(events, modelAccessor, viewAccessor, initFn) { return function(element) { var scope = this, model = modelAccessor(scope, element), view = viewAccessor(scope, element), action = element.attr('ng:change') || '', lastValue; initFn.call(scope, model, view, element); this.$eval(element.attr('ng:init')||''); // Don't register a handler if we are a button (noopAccessor) and there is no action if (action || modelAccessor !== noopAccessor) { element.bind(events, function (){ model.set(view.get()); lastValue = model.get(); scope.$tryEval(action, element); scope.$root.$eval(); }); } scope.$watch(model.get, function(value){ if (lastValue !== value) { view.set(lastValue = value); } }); }; } function inputWidgetSelector(element){ this.directives(true); return INPUT_TYPE[lowercase(element[0].type)] || noop; } angularWidget('input', inputWidgetSelector); angularWidget('textarea', inputWidgetSelector); angularWidget('button', inputWidgetSelector); angularWidget('select', function(element){ this.descend(true); return inputWidgetSelector.call(this, element); }); /* * Consider this: * <select name="selection"> * <option ng:repeat="x in [1,2]">{{x}}</option> * </select> * * The issue is that the select gets evaluated before option is unrolled. * This means that the selection is undefined, but the browser * default behavior is to show the top selection in the list. * To fix that we register a $update function on the select element * and the option creation then calls the $update function when it is * unrolled. The $update function then calls this update function, which * then tries to determine if the model is unassigned, and if so it tries to * chose one of the options from the list. */ angularWidget('option', function(){ this.descend(true); this.directives(true); return function(element) { var select = element.parent(); var scope = retrieveScope(select); var model = modelFormattedAccessor(scope, select); var view = valueAccessor(scope, select); var option = element; var lastValue = option.attr($value); var lastSelected = option.attr('ng-' + $selected); element.data($$update, function(){ var value = option.attr($value); var selected = option.attr('ng-' + $selected); var modelValue = model.get(); if (lastSelected != selected || lastValue != value) { lastSelected = selected; lastValue = value; if (selected || modelValue == _null || modelValue == _undefined) model.set(value); if (value == modelValue) { view.set(lastValue); } } }); }; }); /** * @workInProgress * @ngdoc widget * @name angular.widget.ng:include * * @description * Include external HTML fragment. * * Keep in mind that Same Origin Policy applies to included resources * (e.g. ng:include won't work for file:// access). * * @param {string} src expression evaluating to URL. * @param {Scope=} [scope=new_child_scope] expression evaluating to angular.scope * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @example * <select name="url"> * <option value="angular.filter.date.html">date filter</option> * <option value="angular.filter.html.html">html filter</option> * <option value="">(blank)</option> * </select> * <tt>url = <a href="{{url}}">{{url}}</a></tt> * <hr/> * <ng:include src="url"></ng:include> * * @scenario * it('should load date filter', function(){ * expect(element('.doc-example ng\\:include').text()).toMatch(/angular\.filter\.date/); * }); * it('should change to hmtl filter', function(){ * select('url').option('angular.filter.html.html'); * expect(element('.doc-example ng\\:include').text()).toMatch(/angular\.filter\.html/); * }); * it('should change to blank', function(){ * select('url').option('(blank)'); * expect(element('.doc-example ng\\:include').text()).toEqual(''); * }); */ angularWidget('ng:include', function(element){ var compiler = this, srcExp = element.attr("src"), scopeExp = element.attr("scope") || '', onloadExp = element[0].getAttribute('onload') || ''; //workaround for jquery bug #7537 if (element[0]['ng:compiled']) { this.descend(true); this.directives(true); } else { element[0]['ng:compiled'] = true; return extend(function(xhr, element){ var scope = this, childScope; var changeCounter = 0; var preventRecursion = false; function incrementChange(){ changeCounter++;} this.$watch(srcExp, incrementChange); this.$watch(scopeExp, incrementChange); scope.$onEval(function(){ if (childScope && !preventRecursion) { preventRecursion = true; try { childScope.$eval(); } finally { preventRecursion = false; } } }); this.$watch(function(){return changeCounter;}, function(){ var src = this.$eval(srcExp), useScope = this.$eval(scopeExp); if (src) { xhr('GET', src, function(code, response){ element.html(response); childScope = useScope || createScope(scope); compiler.compile(element)(element, childScope); childScope.$init(); scope.$eval(onloadExp); }); } else { childScope = null; element.html(''); } }); }, {$inject:['$xhr.cache']}); } }); /** * @workInProgress * @ngdoc widget * @name angular.widget.ng:switch * * @description * Conditionally change the DOM structure. * * @usageContent * <any ng:switch-when="matchValue1">...</any> * <any ng:switch-when="matchValue2">...</any> * ... * <any ng:switch-default>...</any> * * @param {*} on expression to match against <tt>ng:switch-when</tt>. * @paramDescription * On child elments add: * * * `ng:switch-when`: the case statement to match against. If match then this * case will be displayed. * * `ng:switch-default`: the default case when no other casses match. * * @example <select name="switch"> <option>settings</option> <option>home</option> <option>other</option> </select> <tt>switch={{switch}}</tt> </hr> <ng:switch on="switch" > <div ng:switch-when="settings">Settings Div</div> <span ng:switch-when="home">Home Span</span> <span ng:switch-default>default</span> </ng:switch> </code> * * @scenario * it('should start in settings', function(){ * expect(element('.doc-example ng\\:switch').text()).toEqual('Settings Div'); * }); * it('should change to home', function(){ * select('switch').option('home'); * expect(element('.doc-example ng\\:switch').text()).toEqual('Home Span'); * }); * it('should select deafault', function(){ * select('switch').option('other'); * expect(element('.doc-example ng\\:switch').text()).toEqual('default'); * }); */ var ngSwitch = angularWidget('ng:switch', function (element){ var compiler = this, watchExpr = element.attr("on"), usingExpr = (element.attr("using") || 'equals'), usingExprParams = usingExpr.split(":"), usingFn = ngSwitch[usingExprParams.shift()], changeExpr = element.attr('change') || '', cases = []; if (!usingFn) throw "Using expression '" + usingExpr + "' unknown."; if (!watchExpr) throw "Missing 'on' attribute."; eachNode(element, function(caseElement){ var when = caseElement.attr('ng:switch-when'); var switchCase = { change: changeExpr, element: caseElement, template: compiler.compile(caseElement) }; if (isString(when)) { switchCase.when = function(scope, value){ var args = [value, when]; foreach(usingExprParams, function(arg){ args.push(arg); }); return usingFn.apply(scope, args); }; cases.unshift(switchCase); } else if (isString(caseElement.attr('ng:switch-default'))) { switchCase.when = valueFn(true); cases.push(switchCase); } }); // this needs to be here for IE foreach(cases, function(_case){ _case.element.remove(); }); element.html(''); return function(element){ var scope = this, childScope; this.$watch(watchExpr, function(value){ var found = false; element.html(''); childScope = createScope(scope); foreach(cases, function(switchCase){ if (!found && switchCase.when(childScope, value)) { found = true; var caseElement = quickClone(switchCase.element); element.append(caseElement); childScope.$tryEval(switchCase.change, element); switchCase.template(caseElement, childScope); childScope.$init(); } }); }); scope.$onEval(function(){ if (childScope) childScope.$eval(); }); }; }, { equals: function(on, when) { return ''+on == when; }, route: switchRouteMatcher }); /* * Modifies the default behavior of html A tag, so that the default action is prevented when href * attribute is empty. * * The reasoning for this change is to allow easy creation of action links with ng:click without * changing the location or causing page reloads, e.g.: * <a href="" ng:click="model.$save()">Save</a> */ angularWidget('a', function() { this.descend(true); this.directives(true); return function(element) { if (element.attr('href') === '') { element.bind('click', function(event){ event.preventDefault(); }); } }; }); /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:repeat * * @description * `ng:repeat` instantiates a template once per item from a collection. The collection is enumerated * with `ng:repeat-index` attribute starting from 0. Each template instance gets its own scope where * the given loop variable is set to the current collection item and `$index` is set to the item * index or key. * * There are special properties exposed on the local scope of each template instance: * * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) * * `$position` – {string} – position of the repeated element in the iterator. One of: `'first'`, * `'middle'` or `'last'`. * * NOTE: `ng:repeat` looks like a directive, but is actually an attribute widget. * * @element ANY * @param {string} repeat_expression The expression indicating how to enumerate a collection. Two * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `track in cd.tracks`. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * @exampleDescription * This example initializes the scope to a list of names and * than uses `ng:repeat` to display every person. * @example <div ng:init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]"> I have {{friends.length}} friends. They are: <ul> <li ng:repeat="friend in friends"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> * @scenario it('should check ng:repeat', function(){ var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(2); expect(r.row(0)).toEqual(["1","John","25"]); expect(r.row(1)).toEqual(["2","Mary","28"]); }); */ angularWidget("@ng:repeat", function(expression, element){ element.removeAttr('ng:repeat'); element.replaceWith(this.comment("ng:repeat: " + expression)); var template = this.compile(element); return function(reference){ var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), lhs, rhs, valueIdent, keyIdent; if (! match) { throw Error("Expected ng:repeat in form of 'item in collection' but got '" + expression + "'."); } lhs = match[1]; rhs = match[2]; match = lhs.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/); if (!match) { throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + keyValue + "'."); } valueIdent = match[3] || match[1]; keyIdent = match[2]; var children = [], currentScope = this; this.$onEval(function(){ var index = 0, childCount = children.length, lastElement = reference, collection = this.$tryEval(rhs, reference), is_array = isArray(collection), collectionLength = 0, childScope, key; if (is_array) { collectionLength = collection.length; } else { for (key in collection) if (collection.hasOwnProperty(key)) collectionLength++; } for (key in collection) { if (!is_array || collection.hasOwnProperty(key)) { if (index < childCount) { // reuse existing child childScope = children[index]; childScope[valueIdent] = collection[key]; if (keyIdent) childScope[keyIdent] = key; } else { // grow children childScope = template(quickClone(element), createScope(currentScope)); childScope[valueIdent] = collection[key]; if (keyIdent) childScope[keyIdent] = key; lastElement.after(childScope.$element); childScope.$index = index; childScope.$position = index == 0 ? 'first' : (index == collectionLength - 1 ? 'last' : 'middle'); childScope.$element.attr('ng:repeat-index', index); childScope.$init(); children.push(childScope); } childScope.$eval(); lastElement = childScope.$element; index ++; } } // shrink children while(children.length > index) { children.pop().$element.remove(); } }, reference); }; }); /** * @workInProgress * @ngdoc widget * @name angular.widget.@ng:non-bindable * * @description * Sometimes it is necessary to write code which looks like bindings but which should be left alone * by angular. Use `ng:non-bindable` to make angular ignore a chunk of HTML. * * NOTE: `ng:non-bindable` looks like a directive, but is actually an attribute widget. * * @element ANY * * @exampleDescription * In this example there are two location where a siple binding (`{{}}`) is present, but the one * wrapped in `ng:non-bindable` is left alone. * * @example <div>Normal: {{1 + 2}}</div> <div ng:non-bindable>Ignored: {{1 + 2}}</div> * * @scenario it('should check ng:non-bindable', function(){ expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); expect(using('.doc-example-live').element('div:last').text()). toMatch(/1 \+ 2/); }); */ angularWidget("@ng:non-bindable", noop); var browserSingleton; /** * @workInProgress * @ngdoc service * @name angular.service.$browser * @requires $log * * @description * Represents the browser. */ angularService('$browser', function($log){ if (!browserSingleton) { browserSingleton = new Browser( window.location, jqLite(window.document), jqLite(window.document.getElementsByTagName('head')[0]), XHR, $log, window.setTimeout); browserSingleton.startPoller(50, function(delay, fn){setTimeout(delay,fn);}); browserSingleton.bind(); } return browserSingleton; }, {inject:['$log']}); extend(angular, { 'element': jqLite, 'compile': compile, 'scope': createScope, 'copy': copy, 'extend': extend, 'equals': equals, 'foreach': foreach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isArray': isArray }); /** * Setup file for the Scenario. * Must be first in the compilation/bootstrap list. */ // Public namespace angular.scenario = angular.scenario || {}; /** * Defines a new output format. * * @param {string} name the name of the new output format * @param {Function} fn function(context, runner) that generates the output */ angular.scenario.output = angular.scenario.output || function(name, fn) { angular.scenario.output[name] = fn; }; /** * Defines a new DSL statement. If your factory function returns a Future * it's returned, otherwise the result is assumed to be a map of functions * for chaining. Chained functions are subject to the same rules. * * Note: All functions on the chain are bound to the chain scope so values * set on "this" in your statement function are available in the chained * functions. * * @param {string} name The name of the statement * @param {Function} fn Factory function(), return a function for * the statement. */ angular.scenario.dsl = angular.scenario.dsl || function(name, fn) { angular.scenario.dsl[name] = function() { function executeStatement(statement, args) { var result = statement.apply(this, args); if (angular.isFunction(result) || result instanceof angular.scenario.Future) return result; var self = this; var chain = angular.extend({}, result); angular.foreach(chain, function(value, name) { if (angular.isFunction(value)) { chain[name] = function() { return executeStatement.call(self, value, arguments); }; } else { chain[name] = value; } }); return chain; } var statement = fn.apply(this, arguments); return function() { return executeStatement.call(this, statement, arguments); }; }; }; /** * Defines a new matcher for use with the expects() statement. The value * this.actual (like in Jasmine) is available in your matcher to compare * against. Your function should return a boolean. The future is automatically * created for you. * * @param {string} name The name of the matcher * @param {Function} fn The matching function(expected). */ angular.scenario.matcher = angular.scenario.matcher || function(name, fn) { angular.scenario.matcher[name] = function(expected) { var prefix = 'expect ' + this.future.name + ' '; if (this.inverse) { prefix += 'not '; } var self = this; this.addFuture(prefix + name + ' ' + angular.toJson(expected), function(done) { var error; self.actual = self.future.value; if ((self.inverse && fn.call(self, expected)) || (!self.inverse && !fn.call(self, expected))) { error = 'expected ' + angular.toJson(expected) + ' but was ' + angular.toJson(self.actual); } done(error); }); }; }; /** * Initialization function for the scenario runner. * * @param {angular.scenario.Runner} $scenario The runner to setup * @param {Object} config Config options */ function angularScenarioInit($scenario, config) { var href = window.location.href; var body = _jQuery(document.body); var output = []; if (config.scenario_output) { output = config.scenario_output.split(','); } angular.foreach(angular.scenario.output, function(fn, name) { if (!output.length || indexOf(output,name) != -1) { var context = body.append('<div></div>').find('div:last'); context.attr('id', name); fn.call({}, context, $scenario); } }); if (!/^http/.test(href) && !/^https/.test(href)) { body.append('<p id="system-error"></p>'); body.find('#system-error').text( 'Scenario runner must be run using http or https. The protocol ' + href.split(':')[0] + ':// is not supported.' ); return; } var appFrame = body.append('<div id="application"></div>').find('#application'); var application = new angular.scenario.Application(appFrame); $scenario.on('RunnerEnd', function() { appFrame.css('display', 'none'); appFrame.find('iframe').attr('src', 'about:blank'); }); $scenario.on('RunnerError', function(error) { if (window.console) { console.log(formatException(error)); } else { // Do something for IE alert(error); } }); $scenario.run(application); } /** * Iterates through list with iterator function that must call the * continueFunction to continute iterating. * * @param {Array} list list to iterate over * @param {Function} iterator Callback function(value, continueFunction) * @param {Function} done Callback function(error, result) called when * iteration finishes or an error occurs. */ function asyncForEach(list, iterator, done) { var i = 0; function loop(error, index) { if (index && index > i) { i = index; } if (error || i >= list.length) { done(error); } else { try { iterator(list[i++], loop); } catch (e) { done(e); } } } loop(); } /** * Formats an exception into a string with the stack trace, but limits * to a specific line length. * * @param {Object} error The exception to format, can be anything throwable * @param {Number} maxStackLines Optional. max lines of the stack trace to include * default is 5. */ function formatException(error, maxStackLines) { maxStackLines = maxStackLines || 5; var message = error.toString(); if (error.stack) { var stack = error.stack.split('\n'); if (stack[0].indexOf(message) === -1) { maxStackLines++; stack.unshift(error.message); } message = stack.slice(0, maxStackLines).join('\n'); } return message; } /** * Returns a function that gets the file name and line number from a * location in the stack if available based on the call site. * * Note: this returns another function because accessing .stack is very * expensive in Chrome. * * @param {Number} offset Number of stack lines to skip */ function callerFile(offset) { var error = new Error(); return function() { var line = (error.stack || '').split('\n')[offset]; // Clean up the stack trace line if (line) { if (line.indexOf('@') !== -1) { // Firefox line = line.substring(line.indexOf('@')+1); } else { // Chrome line = line.substring(line.indexOf('(')+1).replace(')', ''); } } return line || ''; }; } /** * Triggers a browser event. Attempts to choose the right event if one is * not specified. * * @param {Object} Either a wrapped jQuery/jqLite node or a DOMElement * @param {string} Optional event type. */ function browserTrigger(element, type) { if (element && !element.nodeName) element = element[0]; if (!element) return; if (!type) { type = { 'text': 'change', 'textarea': 'change', 'hidden': 'change', 'password': 'change', 'button': 'click', 'submit': 'click', 'reset': 'click', 'image': 'click', 'checkbox': 'click', 'radio': 'click', 'select-one': 'change', 'select-multiple': 'change' }[element.type] || 'click'; } if (lowercase(nodeName(element)) == 'option') { element.parentNode.value = element.value; element = element.parentNode; type = 'change'; } if (msie) { switch(element.type) { case 'radio': case 'checkbox': element.checked = !element.checked; break; } element.fireEvent('on' + type); if (lowercase(element.type) == 'submit') { while(element) { if (lowercase(element.nodeName) == 'form') { element.fireEvent('onsubmit'); break; } element = element.parentNode; } } } else { var evnt = document.createEvent('MouseEvents'); evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element); element.dispatchEvent(evnt); } } /** * Don't use the jQuery trigger method since it works incorrectly. * * jQuery notifies listeners and then changes the state of a checkbox and * does not create a real browser event. A real click changes the state of * the checkbox and then notifies listeners. * * To work around this we instead use our own handler that fires a real event. */ (function(fn){ var parentTrigger = fn.trigger; fn.trigger = function(type) { if (/(click|change|keyup)/.test(type)) { return this.each(function(index, node) { browserTrigger(node, type); }); } return parentTrigger.apply(this, arguments); }; })(_jQuery.fn); /** * Finds all bindings with the substring match of name and returns an * array of their values. * * @param {string} name The name to match * @return {Array.<string>} String of binding values */ _jQuery.fn.bindings = function(name) { function contains(text, value) { return value instanceof RegExp ? value.test(text) : text && text.indexOf(value) >= 0; } var result = []; this.find('.ng-binding:visible').each(function() { var element = new _jQuery(this); if (!angular.isDefined(name) || contains(element.attr('ng:bind'), name) || contains(element.attr('ng:bind-template'), name)) { if (element.is('input, textarea')) { result.push(element.val()); } else { result.push(element.html()); } } }); return result; }; /** * Represents the application currently being tested and abstracts usage * of iframes or separate windows. * * @param {Object} context jQuery wrapper around HTML context. */ angular.scenario.Application = function(context) { this.context = context; context.append( '<h2>Current URL: <a href="about:blank">None</a></h2>' + '<div id="test-frames"></div>' ); }; /** * Gets the jQuery collection of frames. Don't use this directly because * frames may go stale. * * @private * @return {Object} jQuery collection */ angular.scenario.Application.prototype.getFrame_ = function() { return this.context.find('#test-frames iframe:last'); }; /** * Gets the window of the test runner frame. Always favor executeAction() * instead of this method since it prevents you from getting a stale window. * * @private * @return {Object} the window of the frame */ angular.scenario.Application.prototype.getWindow_ = function() { var contentWindow = this.getFrame_().attr('contentWindow'); if (!contentWindow) throw 'Frame window is not accessible.'; return contentWindow; }; /** * Checks that a URL would return a 2xx success status code. Callback is called * with no arguments on success, or with an error on failure. * * Warning: This requires the server to be able to respond to HEAD requests * and not modify the state of your application. * * @param {string} url Url to check * @param {Function} callback function(error) that is called with result. */ angular.scenario.Application.prototype.checkUrlStatus_ = function(url, callback) { var self = this; _jQuery.ajax({ url: url, type: 'HEAD', complete: function(request) { if (request.status < 200 || request.status >= 300) { if (!request.status) { callback.call(self, 'Sandbox Error: Cannot access ' + url); } else { callback.call(self, request.status + ' ' + request.statusText); } } else { callback.call(self); } } }); }; /** * Changes the location of the frame. * * @param {string} url The URL. If it begins with a # then only the * hash of the page is changed. * @param {Function} loadFn function($window, $document) Called when frame loads. * @param {Function} errorFn function(error) Called if any error when loading. */ angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) { var self = this; var frame = this.getFrame_(); //TODO(esprehn): Refactor to use rethrow() errorFn = errorFn || function(e) { throw e; }; if (url === 'about:blank') { errorFn('Sandbox Error: Navigating to about:blank is not allowed.'); } else if (url.charAt(0) === '#') { url = frame.attr('src').split('#')[0] + url; frame.attr('src', url); this.executeAction(loadFn); } else { frame.css('display', 'none').attr('src', 'about:blank'); this.checkUrlStatus_(url, function(error) { if (error) { return errorFn(error); } self.context.find('#test-frames').append('<iframe>'); frame = this.getFrame_(); frame.load(function() { frame.unbind(); try { self.executeAction(loadFn); } catch (e) { errorFn(e); } }).attr('src', url); }); } this.context.find('> h2 a').attr('href', url).text(url); }; /** * Executes a function in the context of the tested application. Will wait * for all pending angular xhr requests before executing. * * @param {Function} action The callback to execute. function($window, $document) * $document is a jQuery wrapped document. */ angular.scenario.Application.prototype.executeAction = function(action) { var self = this; var $window = this.getWindow_(); if (!$window.document) { throw 'Sandbox Error: Application document not accessible.'; } if (!$window.angular) { return action.call(this, $window, _jQuery($window.document)); } var $browser = $window.angular.service.$browser(); $browser.poll(); $browser.notifyWhenNoOutstandingRequests(function() { action.call(self, $window, _jQuery($window.document)); }); }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.foreach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.foreach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; /** * Defines a block to execute before each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {Function} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.foreach(this.children, function(child) { child.getSpecs(specs); }); angular.foreach(this.its, function(it) { specs.push(it); }); var only = []; angular.foreach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * A future action in a spec. * * @param {string} name of the future action * @param {Function} future callback(error, result) * @param {Function} Optional. function that returns the file/line number. */ angular.scenario.Future = function(name, behavior, line) { this.name = name; this.behavior = behavior; this.fulfilled = false; this.value = undefined; this.parser = angular.identity; this.line = line || function() { return ''; }; }; /** * Executes the behavior of the closure. * * @param {Function} doneFn Callback function(error, result) */ angular.scenario.Future.prototype.execute = function(doneFn) { var self = this; this.behavior(function(error, result) { self.fulfilled = true; if (result) { try { result = self.parser(result); } catch(e) { error = e; } } self.value = error || result; doneFn(error, result); }); }; /** * Configures the future to convert it's final with a function fn(value) * * @param {Function} fn function(value) that returns the parsed value */ angular.scenario.Future.prototype.parsedWith = function(fn) { this.parser = fn; return this; }; /** * Configures the future to parse it's final value from JSON * into objects. */ angular.scenario.Future.prototype.fromJson = function() { return this.parsedWith(angular.fromJson); }; /** * Configures the future to convert it's final value from objects * into JSON. */ angular.scenario.Future.prototype.toJson = function() { return this.parsedWith(angular.toJson); }; /** * Maintains an object tree from the runner events. * * @param {Object} runner The scenario Runner instance to connect to. * * TODO(esprehn): Every output type creates one of these, but we probably * want one glonal shared instance. Need to handle events better too * so the HTML output doesn't need to do spec model.getSpec(spec.id) * silliness. */ angular.scenario.ObjectModel = function(runner) { var self = this; this.specMap = {}; this.value = { name: '', children: {} }; runner.on('SpecBegin', function(spec) { var block = self.value; angular.foreach(self.getDefinitionPath(spec), function(def) { if (!block.children[def.name]) { block.children[def.name] = { id: def.id, name: def.name, children: {}, specs: {} }; } block = block.children[def.name]; }); self.specMap[spec.id] = block.specs[spec.name] = new angular.scenario.ObjectModel.Spec(spec.id, spec.name); }); runner.on('SpecError', function(spec, error) { var it = self.getSpec(spec.id); it.status = 'error'; it.error = error; }); runner.on('SpecEnd', function(spec) { var it = self.getSpec(spec.id); complete(it); }); runner.on('StepBegin', function(spec, step) { var it = self.getSpec(spec.id); it.steps.push(new angular.scenario.ObjectModel.Step(step.name)); }); runner.on('StepEnd', function(spec, step) { var it = self.getSpec(spec.id); if (it.getLastStep().name !== step.name) throw 'Events fired in the wrong order. Step names don\' match.'; complete(it.getLastStep()); }); runner.on('StepFailure', function(spec, step, error) { var it = self.getSpec(spec.id); var item = it.getLastStep(); item.error = error; if (!it.status) { it.status = item.status = 'failure'; } }); runner.on('StepError', function(spec, step, error) { var it = self.getSpec(spec.id); var item = it.getLastStep(); it.status = 'error'; item.status = 'error'; item.error = error; }); function complete(item) { item.endTime = new Date().getTime(); item.duration = item.endTime - item.startTime; item.status = item.status || 'success'; } }; /** * Computes the path of definition describe blocks that wrap around * this spec. * * @param spec Spec to compute the path for. * @return {Array<Describe>} The describe block path */ angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) { var path = []; var currentDefinition = spec.definition; while (currentDefinition && currentDefinition.name) { path.unshift(currentDefinition); currentDefinition = currentDefinition.parent; } return path; }; /** * Gets a spec by id. * * @param {string} The id of the spec to get the object for. * @return {Object} the Spec instance */ angular.scenario.ObjectModel.prototype.getSpec = function(id) { return this.specMap[id]; }; /** * A single it block. * * @param {string} id Id of the spec * @param {string} name Name of the spec */ angular.scenario.ObjectModel.Spec = function(id, name) { this.id = id; this.name = name; this.startTime = new Date().getTime(); this.steps = []; }; /** * Adds a new step to the Spec. * * @param {string} step Name of the step (really name of the future) * @return {Object} the added step */ angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) { var step = new angular.scenario.ObjectModel.Step(name); this.steps.push(step); return step; }; /** * Gets the most recent step. * * @return {Object} the step */ angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() { return this.steps[this.steps.length-1]; }; /** * A single step inside a Spec. * * @param {string} step Name of the step */ angular.scenario.ObjectModel.Step = function(name) { this.name = name; this.startTime = new Date().getTime(); }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.foreach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.foreach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; /** * Defines a block to execute before each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {Function} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.foreach(this.children, function(child) { child.getSpecs(specs); }); angular.foreach(this.its, function(it) { specs.push(it); }); var only = []; angular.foreach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * Runner for scenarios. */ angular.scenario.Runner = function($window) { this.listeners = []; this.$window = $window; this.rootDescribe = new angular.scenario.Describe(); this.currentDescribe = this.rootDescribe; this.api = { it: this.it, iit: this.iit, xit: angular.noop, describe: this.describe, ddescribe: this.ddescribe, xdescribe: angular.noop, beforeEach: this.beforeEach, afterEach: this.afterEach }; angular.foreach(this.api, angular.bind(this, function(fn, key) { this.$window[key] = angular.bind(this, fn); })); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.Runner.prototype.emit = function(eventName) { var self = this; var args = Array.prototype.slice.call(arguments, 1); eventName = eventName.toLowerCase(); if (!this.listeners[eventName]) return; angular.foreach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); }; /** * Adds a listener for an event. * * @param {string} eventName The name of the event to add a handler for * @param {string} listener The fn(...) that takes the extra arguments from emit() */ angular.scenario.Runner.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Defines a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.describe = function(name, body) { var self = this; this.currentDescribe.describe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Same as describe, but makes ddescribe the only blocks to run. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.ddescribe = function(name, body) { var self = this; this.currentDescribe.ddescribe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Defines a test in a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.it = function(name, body) { this.currentDescribe.it(name, body); }; /** * Same as it, but makes iit tests the only tests to run. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.iit = function(name, body) { this.currentDescribe.iit(name, body); }; /** * Defines a function to be called before each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {Function} Callback to execute */ angular.scenario.Runner.prototype.beforeEach = function(body) { this.currentDescribe.beforeEach(body); }; /** * Defines a function to be called after each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {Function} Callback to execute */ angular.scenario.Runner.prototype.afterEach = function(body) { this.currentDescribe.afterEach(body); }; /** * Creates a new spec runner. * * @private * @param {Object} scope parent scope */ angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) { return scope.$new(angular.scenario.SpecRunner); }; /** * Runs all the loaded tests with the specified runner class on the * provided application. * * @param {angular.scenario.Application} application App to remote control. */ angular.scenario.Runner.prototype.run = function(application) { var self = this; var $root = angular.scope(this); $root.application = application; this.emit('RunnerBegin'); asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) { var dslCache = {}; var runner = self.createSpecRunner_($root); angular.foreach(angular.scenario.dsl, function(fn, key) { dslCache[key] = fn.call($root); }); angular.foreach(angular.scenario.dsl, function(fn, key) { self.$window[key] = function() { var line = callerFile(3); var scope = angular.scope(runner); // Make the dsl accessible on the current chain scope.dsl = {}; angular.foreach(dslCache, function(fn, key) { scope.dsl[key] = function() { return dslCache[key].apply(scope, arguments); }; }); // Make these methods work on the current chain scope.addFuture = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFuture.apply(scope, arguments); }; scope.addFutureAction = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFutureAction.apply(scope, arguments); }; return scope.dsl[key].apply(scope, arguments); }; }); runner.run(spec, specDone); }, function(error) { if (error) { self.emit('RunnerError', error); } self.emit('RunnerEnd'); }); }; /** * This class is the "this" of the it/beforeEach/afterEach method. * Responsibilities: * - "this" for it/beforeEach/afterEach * - keep state for single it/beforeEach/afterEach execution * - keep track of all of the futures to execute * - run single spec (execute each future) */ angular.scenario.SpecRunner = function() { this.futures = []; this.afterIndex = 0; }; /** * Executes a spec which is an it block with associated before/after functions * based on the describe nesting. * * @param {Object} spec A spec object * @param {Object} specDone An angular.scenario.Application instance * @param {Function} Callback function that is called when the spec finshes. */ angular.scenario.SpecRunner.prototype.run = function(spec, specDone) { var self = this; this.spec = spec; this.emit('SpecBegin', spec); try { spec.before.call(this); spec.body.call(this); this.afterIndex = this.futures.length; spec.after.call(this); } catch (e) { this.emit('SpecError', spec, e); this.emit('SpecEnd', spec); specDone(); return; } var handleError = function(error, done) { if (self.error) { return done(); } self.error = true; done(null, self.afterIndex); }; asyncForEach( this.futures, function(future, futureDone) { self.step = future; self.emit('StepBegin', spec, future); try { future.execute(function(error) { if (error) { self.emit('StepFailure', spec, future, error); self.emit('StepEnd', spec, future); return handleError(error, futureDone); } self.emit('StepEnd', spec, future); self.$window.setTimeout(function() { futureDone(); }, 0); }); } catch (e) { self.emit('StepError', spec, future, e); self.emit('StepEnd', spec, future); handleError(e, futureDone); } }, function(e) { if (e) { self.emit('SpecError', spec, e); } self.emit('SpecEnd', spec); // Call done in a timeout so exceptions don't recursively // call this function self.$window.setTimeout(function() { specDone(); }, 0); } ); }; /** * Adds a new future action. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {Function} behavior Behavior of the future * @param {Function} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) { var future = new angular.scenario.Future(name, angular.bind(this, behavior), line); this.futures.push(future); return future; }; /** * Adds a new future action to be executed on the application window. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {Function} behavior Behavior of the future * @param {Function} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) { var self = this; return this.addFuture(name, function(done) { this.application.executeAction(function($window, $document) { //TODO(esprehn): Refactor this so it doesn't need to be in here. $document.elements = function(selector) { var args = Array.prototype.slice.call(arguments, 1); selector = (self.selector || '') + ' ' + (selector || ''); selector = _jQuery.trim(selector) || '*'; angular.foreach(args, function(value, index) { selector = selector.replace('$' + (index + 1), value); }); var result = $document.find(selector); if (!result.length) { throw { type: 'selector', message: 'Selector ' + selector + ' did not match any elements.' }; } return result; }; try { behavior.call(self, $window, $document, done); } catch(e) { if (e.type && e.type === 'selector') { done(e.message); } else { throw e; } } }); }, line); }; /** * Shared DSL statements that are useful to all scenarios. */ /** * Usage: * wait() waits until you call resume() in the console */ angular.scenario.dsl('wait', function() { return function() { return this.addFuture('waiting for you to resume', function(done) { this.emit('InteractiveWait', this.spec, this.step); this.$window.resume = function() { done(); }; }); }; }); /** * Usage: * pause(seconds) pauses the test for specified number of seconds */ angular.scenario.dsl('pause', function() { return function(time) { return this.addFuture('pause for ' + time + ' seconds', function(done) { this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000); }); }; }); /** * Usage: * browser().navigateTo(url) Loads the url into the frame * browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to * browser().reload() refresh the page (reload the same URL) * browser().location().href() the full URL of the page * browser().location().hash() the full hash in the url * browser().location().path() the full path in the url * browser().location().hashSearch() the hashSearch Object from angular * browser().location().hashPath() the hashPath string from angular */ angular.scenario.dsl('browser', function() { var chain = {}; chain.navigateTo = function(url, delegate) { var application = this.application; return this.addFuture("browser navigate to '" + url + "'", function(done) { if (delegate) { url = delegate.call(this, url); } application.navigateTo(url, function() { done(null, url); }, done); }); }; chain.reload = function() { var application = this.application; return this.addFutureAction('browser reload', function($window, $document, done) { var href = $window.location.href; application.navigateTo(href, function() { done(null, href); }, done); }); }; chain.location = function() { var api = {}; api.href = function() { return this.addFutureAction('browser url', function($window, $document, done) { done(null, $window.location.href); }); }; api.hash = function() { return this.addFutureAction('browser url hash', function($window, $document, done) { done(null, $window.location.hash.replace('#', '')); }); }; api.path = function() { return this.addFutureAction('browser url path', function($window, $document, done) { done(null, $window.location.pathname); }); }; api.search = function() { return this.addFutureAction('browser url search', function($window, $document, done) { done(null, $window.angular.scope().$location.search); }); }; api.hashSearch = function() { return this.addFutureAction('browser url hash search', function($window, $document, done) { done(null, $window.angular.scope().$location.hashSearch); }); }; api.hashPath = function() { return this.addFutureAction('browser url hash path', function($window, $document, done) { done(null, $window.angular.scope().$location.hashPath); }); }; return api; }; return function(time) { return chain; }; }); /** * Usage: * expect(future).{matcher} where matcher is one of the matchers defined * with angular.scenario.matcher * * ex. expect(binding("name")).toEqual("Elliott") */ angular.scenario.dsl('expect', function() { var chain = angular.extend({}, angular.scenario.matcher); chain.not = function() { this.inverse = true; return chain; }; return function(future) { this.future = future; return chain; }; }); /** * Usage: * using(selector, label) scopes the next DSL element selection * * ex. * using('#foo', "'Foo' text field").input('bar') */ angular.scenario.dsl('using', function() { return function(selector, label) { this.selector = _jQuery.trim((this.selector||'') + ' ' + selector); if (angular.isString(label) && label.length) { this.label = label + ' ( ' + this.selector + ' )'; } else { this.label = this.selector; } return this.dsl; }; }); /** * Usage: * binding(name) returns the value of the first matching binding */ angular.scenario.dsl('binding', function() { return function(name) { return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) { var values = $document.elements().bindings(name); if (!values.length) { return done("Binding selector '" + name + "' did not match."); } done(null, values[0]); }); }; }); /** * Usage: * input(name).enter(value) enters value in input with specified name * input(name).check() checks checkbox * input(name).select(value) selects the readio button with specified name/value */ angular.scenario.dsl('input', function() { var chain = {}; chain.enter = function(value) { return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) { var input = $document.elements(':input[name="$1"]', this.name); input.val(value); input.trigger('change'); done(); }); }; chain.check = function() { return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) { var input = $document.elements(':checkbox[name="$1"]', this.name); input.trigger('click'); done(); }); }; chain.select = function(value) { return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) { var input = $document. elements(':radio[name$="@$1"][value="$2"]', this.name, value); input.trigger('click'); done(); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * repeater('#products table', 'Product List').count() number of rows * repeater('#products table', 'Product List').row(1) all bindings in row as an array * repeater('#products table', 'Product List').column('product.name') all values across all rows in an array */ angular.scenario.dsl('repeater', function() { var chain = {}; chain.count = function() { return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.column = function(binding) { return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) { done(null, $document.elements().bindings(binding)); }); }; chain.row = function(index) { return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) { var values = []; var matches = $document.elements().slice(index, index + 1); if (!matches.length) return done('row ' + index + ' out of bounds'); done(null, matches.bindings()); }); }; return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Usage: * select(name).option('value') select one option * select(name).options('value1', 'value2', ...) select options from a multi select */ angular.scenario.dsl('select', function() { var chain = {}; chain.option = function(value) { return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) { var select = $document.elements('select[name="$1"]', this.name); select.val(value); select.trigger('change'); done(); }); }; chain.options = function() { var values = arguments; return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) { var select = $document.elements('select[multiple][name="$1"]', this.name); select.val(values); select.trigger('change'); done(); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * element(selector, label).count() get the number of elements that match selector * element(selector, label).click() clicks an element * element(selector, label).query(fn) executes fn(selectedElements, done) * element(selector, label).{method}() gets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr) * element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr) */ angular.scenario.dsl('element', function() { var KEY_VALUE_METHODS = ['attr', 'css']; var VALUE_METHODS = [ 'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width', 'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset' ]; var chain = {}; chain.count = function() { return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.click = function() { return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) { var elements = $document.elements(); var href = elements.attr('href'); elements.trigger('click'); if (href && elements[0].nodeName.toUpperCase() === 'A') { this.application.navigateTo(href, function() { done(); }, done); } else { done(); } }); }; chain.query = function(fn) { return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) { fn.call(this, $document.elements(), done); }); }; angular.foreach(KEY_VALUE_METHODS, function(methodName) { chain[methodName] = function(name, value) { var futureName = "element '" + this.label + "' get " + methodName + " '" + name + "'"; if (angular.isDefined(value)) { futureName = "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'"; } return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].call(element, name, value)); }); }; }); angular.foreach(VALUE_METHODS, function(methodName) { chain[methodName] = function(value) { var futureName = "element '" + this.label + "' " + methodName; if (angular.isDefined(value)) { futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'"; } return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].call(element, value)); }); }; }); return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Matchers for implementing specs. Follows the Jasmine spec conventions. */ angular.scenario.matcher('toEqual', function(expected) { return angular.equals(this.actual, expected); }); angular.scenario.matcher('toBe', function(expected) { return this.actual === expected; }); angular.scenario.matcher('toBeDefined', function() { return angular.isDefined(this.actual); }); angular.scenario.matcher('toBeTruthy', function() { return this.actual; }); angular.scenario.matcher('toBeFalsy', function() { return !this.actual; }); angular.scenario.matcher('toMatch', function(expected) { return new RegExp(expected).test(this.actual); }); angular.scenario.matcher('toBeNull', function() { return this.actual === null; }); angular.scenario.matcher('toContain', function(expected) { return includes(this.actual, expected); }); angular.scenario.matcher('toBeLessThan', function(expected) { return this.actual < expected; }); angular.scenario.matcher('toBeGreaterThan', function(expected) { return this.actual > expected; }); /** * User Interface for the Scenario Runner. * * TODO(esprehn): This should be refactored now that ObjectModel exists * to use angular bindings for the UI. */ angular.scenario.output('html', function(context, runner) { var model = new angular.scenario.ObjectModel(runner); context.append( '<div id="header">' + ' <h1><span class="angular">&lt;angular/&gt;</span>: Scenario Test Runner</h1>' + ' <ul id="status-legend" class="status-display">' + ' <li class="status-error">0 Errors</li>' + ' <li class="status-failure">0 Failures</li>' + ' <li class="status-success">0 Passed</li>' + ' </ul>' + '</div>' + '<div id="specs">' + ' <div class="test-children"></div>' + '</div>' ); runner.on('InteractiveWait', function(spec, step) { var ui = model.getSpec(spec.id).getLastStep().ui; ui.find('.test-title'). html('waiting for you to <a href="javascript:resume()">resume</a>.'); }); runner.on('SpecBegin', function(spec) { var ui = findContext(spec); ui.find('> .tests').append( '<li class="status-pending test-it"></li>' ); ui = ui.find('> .tests li:last'); ui.append( '<div class="test-info">' + ' <p class="test-title">' + ' <span class="timer-result"></span>' + ' <span class="test-name"></span>' + ' </p>' + '</div>' + '<div class="scrollpane">' + ' <ol class="test-actions"></ol>' + '</div>' ); ui.find('> .test-info .test-name').text(spec.name); ui.find('> .test-info').click(function() { var scrollpane = ui.find('> .scrollpane'); var actions = scrollpane.find('> .test-actions'); var name = context.find('> .test-info .test-name'); if (actions.find(':visible').length) { actions.hide(); name.removeClass('open').addClass('closed'); } else { actions.show(); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); name.removeClass('closed').addClass('open'); } }); model.getSpec(spec.id).ui = ui; }); runner.on('SpecError', function(spec, error) { var ui = model.getSpec(spec.id).ui; ui.append('<pre></pre>'); ui.find('> pre').text(formatException(error)); }); runner.on('SpecEnd', function(spec) { spec = model.getSpec(spec.id); spec.ui.removeClass('status-pending'); spec.ui.addClass('status-' + spec.status); spec.ui.find("> .test-info .timer-result").text(spec.duration + "ms"); if (spec.status === 'success') { spec.ui.find('> .test-info .test-name').addClass('closed'); spec.ui.find('> .scrollpane .test-actions').hide(); } updateTotals(spec.status); }); runner.on('StepBegin', function(spec, step) { spec = model.getSpec(spec.id); step = spec.getLastStep(); spec.ui.find('> .scrollpane .test-actions'). append('<li class="status-pending"></li>'); step.ui = spec.ui.find('> .scrollpane .test-actions li:last'); step.ui.append( '<div class="timer-result"></div>' + '<div class="test-title"></div>' ); step.ui.find('> .test-title').text(step.name); var scrollpane = step.ui.parents('.scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); runner.on('StepFailure', function(spec, step, error) { var ui = model.getSpec(spec.id).getLastStep().ui; addError(ui, step.line, error); }); runner.on('StepError', function(spec, step, error) { var ui = model.getSpec(spec.id).getLastStep().ui; addError(ui, step.line, error); }); runner.on('StepEnd', function(spec, step) { spec = model.getSpec(spec.id); step = spec.getLastStep(); step.ui.find('.timer-result').text(step.duration + 'ms'); step.ui.removeClass('status-pending'); step.ui.addClass('status-' + step.status); var scrollpane = spec.ui.find('> .scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); /** * Finds the context of a spec block defined by the passed definition. * * @param {Object} The definition created by the Describe object. */ function findContext(spec) { var currentContext = context.find('#specs'); angular.foreach(model.getDefinitionPath(spec), function(defn) { var id = 'describe-' + defn.id; if (!context.find('#' + id).length) { currentContext.find('> .test-children').append( '<div class="test-describe" id="' + id + '">' + ' <h2></h2>' + ' <div class="test-children"></div>' + ' <ul class="tests"></ul>' + '</div>' ); context.find('#' + id).find('> h2').text('describe: ' + defn.name); } currentContext = context.find('#' + id); }); return context.find('#describe-' + spec.definition.id); }; /** * Updates the test counter for the status. * * @param {string} the status. */ function updateTotals(status) { var legend = context.find('#status-legend .status-' + status); var parts = legend.text().split(' '); var value = (parts[0] * 1) + 1; legend.text(value + ' ' + parts[1]); } /** * Add an error to a step. * * @param {Object} The JQuery wrapped context * @param {Function} fn() that should return the file/line number of the error * @param {Object} the error. */ function addError(context, line, error) { context.find('.test-title').append('<pre></pre>'); var message = _jQuery.trim(line() + '\n\n' + formatException(error)); context.find('.test-title pre:last').text(message); }; }); /** * Generates JSON output into a context. */ angular.scenario.output('json', function(context, runner) { var model = new angular.scenario.ObjectModel(runner); runner.on('RunnerEnd', function() { context.text(angular.toJson(model.value)); }); }); /** * Generates XML output into a context. */ angular.scenario.output('xml', function(context, runner) { var model = new angular.scenario.ObjectModel(runner); var $ = function(args) {return new context.init(args);}; runner.on('RunnerEnd', function() { var scenario = $('<scenario></scenario>'); context.append(scenario); serializeXml(scenario, model.value); }); /** * Convert the tree into XML. * * @param {Object} context jQuery context to add the XML to. * @param {Object} tree node to serialize */ function serializeXml(context, tree) { angular.foreach(tree.children, function(child) { var describeContext = $('<describe></describe>'); describeContext.attr('id', child.id); describeContext.attr('name', child.name); context.append(describeContext); serializeXml(describeContext, child); }); var its = $('<its></its>'); context.append(its); angular.foreach(tree.specs, function(spec) { var it = $('<it></it>'); it.attr('id', spec.id); it.attr('name', spec.name); it.attr('duration', spec.duration); it.attr('status', spec.status); its.append(it); angular.foreach(spec.steps, function(step) { var stepContext = $('<step></step>'); stepContext.attr('name', step.name); stepContext.attr('duration', step.duration); stepContext.attr('status', step.status); it.append(stepContext); if (step.error) { var error = $('<error></error'); stepContext.append(error); error.text(formatException(stepContext.error)); } }); }); } }); /** * Creates a global value $result with the result of the runner. */ angular.scenario.output('object', function(context, runner) { runner.$window.$result = new angular.scenario.ObjectModel(runner).value; }); var $scenario = new angular.scenario.Runner(window); window.onload = function() { try { if (previousOnLoad) previousOnLoad(); } catch(e) {} angularScenarioInit($scenario, angularJsConfig(document)); }; })(window, document, window.onload); document.write('<style type="text/css">@charset "UTF-8";\n\n.ng-format-negative {\n color: red;\n}\n\n.ng-exception {\n border: 2px solid #FF0000;\n font-family: "Courier New", Courier, monospace;\n font-size: smaller;\n white-space: pre;\n}\n\n.ng-validation-error {\n border: 2px solid #FF0000;\n}\n\n\n/*****************\n * TIP\n *****************/\n#ng-callout {\n margin: 0;\n padding: 0;\n border: 0;\n outline: 0;\n font-size: 13px;\n font-weight: normal;\n font-family: Verdana, Arial, Helvetica, sans-serif;\n vertical-align: baseline;\n background: transparent;\n text-decoration: none;\n}\n\n#ng-callout .ng-arrow-left{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrSLoc/AG8FeUUIN+sGebWAnbKSJodqqlsOxJtqYooU9vvk+vcJIcTkg+QAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n left:-12px;\n height:23px;\n width:10px;\n top:-3px;\n}\n\n#ng-callout .ng-arrow-right{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrCLTcoM29yN6k9socs91e5X3EyJloipYrO4ohTMqA0Fn2XVNswJe+H+SXAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n height:23px;\n width:11px;\n top:-2px;\n}\n\n#ng-callout {\n position: absolute;\n z-index:100;\n border: 2px solid #CCCCCC;\n background-color: #fff;\n}\n\n#ng-callout .ng-content{\n padding:10px 10px 10px 10px;\n color:#333333;\n}\n\n#ng-callout .ng-title{\n background-color: #CCCCCC;\n text-align: left;\n padding-left: 8px;\n padding-bottom: 5px;\n padding-top: 2px;\n font-weight:bold;\n}\n\n\n/*****************\n * indicators\n *****************/\n.ng-input-indicator-wait {\n background-image: url("data:image/png;base64,R0lGODlhEAAQAPQAAP///wAAAPDw8IqKiuDg4EZGRnp6egAAAFhYWCQkJKysrL6+vhQUFJycnAQEBDY2NmhoaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFdyAgAgIJIeWoAkRCCMdBkKtIHIngyMKsErPBYbADpkSCwhDmQCBethRB6Vj4kFCkQPG4IlWDgrNRIwnO4UKBXDufzQvDMaoSDBgFb886MiQadgNABAokfCwzBA8LCg0Egl8jAggGAA1kBIA1BAYzlyILczULC2UhACH5BAkKAAAALAAAAAAQABAAAAV2ICACAmlAZTmOREEIyUEQjLKKxPHADhEvqxlgcGgkGI1DYSVAIAWMx+lwSKkICJ0QsHi9RgKBwnVTiRQQgwF4I4UFDQQEwi6/3YSGWRRmjhEETAJfIgMFCnAKM0KDV4EEEAQLiF18TAYNXDaSe3x6mjidN1s3IQAh+QQJCgAAACwAAAAAEAAQAAAFeCAgAgLZDGU5jgRECEUiCI+yioSDwDJyLKsXoHFQxBSHAoAAFBhqtMJg8DgQBgfrEsJAEAg4YhZIEiwgKtHiMBgtpg3wbUZXGO7kOb1MUKRFMysCChAoggJCIg0GC2aNe4gqQldfL4l/Ag1AXySJgn5LcoE3QXI3IQAh+QQJCgAAACwAAAAAEAAQAAAFdiAgAgLZNGU5joQhCEjxIssqEo8bC9BRjy9Ag7GILQ4QEoE0gBAEBcOpcBA0DoxSK/e8LRIHn+i1cK0IyKdg0VAoljYIg+GgnRrwVS/8IAkICyosBIQpBAMoKy9dImxPhS+GKkFrkX+TigtLlIyKXUF+NjagNiEAIfkECQoAAAAsAAAAABAAEAAABWwgIAICaRhlOY4EIgjH8R7LKhKHGwsMvb4AAy3WODBIBBKCsYA9TjuhDNDKEVSERezQEL0WrhXucRUQGuik7bFlngzqVW9LMl9XWvLdjFaJtDFqZ1cEZUB0dUgvL3dgP4WJZn4jkomWNpSTIyEAIfkECQoAAAAsAAAAABAAEAAABX4gIAICuSxlOY6CIgiD8RrEKgqGOwxwUrMlAoSwIzAGpJpgoSDAGifDY5kopBYDlEpAQBwevxfBtRIUGi8xwWkDNBCIwmC9Vq0aiQQDQuK+VgQPDXV9hCJjBwcFYU5pLwwHXQcMKSmNLQcIAExlbH8JBwttaX0ABAcNbWVbKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICSRBlOY7CIghN8zbEKsKoIjdFzZaEgUBHKChMJtRwcWpAWoWnifm6ESAMhO8lQK0EEAV3rFopIBCEcGwDKAqPh4HUrY4ICHH1dSoTFgcHUiZjBhAJB2AHDykpKAwHAwdzf19KkASIPl9cDgcnDkdtNwiMJCshACH5BAkKAAAALAAAAAAQABAAAAV3ICACAkkQZTmOAiosiyAoxCq+KPxCNVsSMRgBsiClWrLTSWFoIQZHl6pleBh6suxKMIhlvzbAwkBWfFWrBQTxNLq2RG2yhSUkDs2b63AYDAoJXAcFRwADeAkJDX0AQCsEfAQMDAIPBz0rCgcxky0JRWE1AmwpKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICKZzkqJ4nQZxLqZKv4NqNLKK2/Q4Ek4lFXChsg5ypJjs1II3gEDUSRInEGYAw6B6zM4JhrDAtEosVkLUtHA7RHaHAGJQEjsODcEg0FBAFVgkQJQ1pAwcDDw8KcFtSInwJAowCCA6RIwqZAgkPNgVpWndjdyohACH5BAkKAAAALAAAAAAQABAAAAV5ICACAimc5KieLEuUKvm2xAKLqDCfC2GaO9eL0LABWTiBYmA06W6kHgvCqEJiAIJiu3gcvgUsscHUERm+kaCxyxa+zRPk0SgJEgfIvbAdIAQLCAYlCj4DBw0IBQsMCjIqBAcPAooCBg9pKgsJLwUFOhCZKyQDA3YqIQAh+QQJCgAAACwAAAAAEAAQAAAFdSAgAgIpnOSonmxbqiThCrJKEHFbo8JxDDOZYFFb+A41E4H4OhkOipXwBElYITDAckFEOBgMQ3arkMkUBdxIUGZpEb7kaQBRlASPg0FQQHAbEEMGDSVEAA1QBhAED1E0NgwFAooCDWljaQIQCE5qMHcNhCkjIQAh+QQJCgAAACwAAAAAEAAQAAAFeSAgAgIpnOSoLgxxvqgKLEcCC65KEAByKK8cSpA4DAiHQ/DkKhGKh4ZCtCyZGo6F6iYYPAqFgYy02xkSaLEMV34tELyRYNEsCQyHlvWkGCzsPgMCEAY7Cg04Uk48LAsDhRA8MVQPEF0GAgqYYwSRlycNcWskCkApIyEAOwAAAAAAAAAAAA==");\n background-position: right;\n background-repeat: no-repeat;\n}\n</style>'); document.write('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>');
import AppBar from '@material-ui/core/AppBar'; import Button from '@material-ui/core/Button'; import Hidden from '@material-ui/core/Hidden'; import Backdrop from '@material-ui/core/Backdrop'; import CircularProgress from '@material-ui/core/CircularProgress'; import Grid from '@material-ui/core/Grid'; import React, { Suspense, lazy, Component } from 'react'; import '../css/Home.css'; import GridList from '@material-ui/core/GridList'; const Card = lazy(() => import('./Card')); class Player extends Component { constructor(props) { super(props); var player=this.props.match.params.player; this.state = { name:player, infoRecieved:false }; } componentDidMount() { fetch('http://localhost:8081/getPlayerInfo/'+this.state.name) .then(response => response.json()) .then(result => { this.setState({ playerStats:result, infoRecieved:true }); }) .catch(error => { console.error(error); }) } render() { if (!this.state.infoRecieved) { return <Backdrop open={!this.state.infoRecieved}> <CircularProgress color="inherit"/> </Backdrop> } return <div> <h1 className="itemTitle">{this.state.name}</h1> <GridList cols={5} className="cardGridList"> <Card mainInfo={{key:"Runs",value:this.state.playerStats.batting.runs}} backsideInfo={this.state.playerStats.batting.runType} color="#e71d31" turnBack={true} title="Career Runs"/> <Card mainInfo={{key:"Strike Rate",value:this.state.playerStats.batting.strike_rate}} backsideInfo={this.state.playerStats.batting.stats} turnBack={true} color="#e71d31" title="Scoring"/> <Card mainInfo={this.state.playerStats.batting.favoriteStadium} backsideInfo={this.state.playerStats.batting.stadiumRuns} color="#e71d31" turnBack={true} title="Favourite Ground"/> <Card mainInfo={this.state.playerStats.batting.strongestOpponent} backsideInfo={this.state.playerStats.batting.opponentInfo} color="#e71d31" turnBack={true} title="Strongest Opponent"/> <Card mainInfo={this.state.playerStats.batting.frequentDismissalType} backsideInfo={this.state.playerStats.batting.dismissalInfo} color="#e71d31" turnBack={true} title="Dismissal Type"/> <Card mainInfo={{key:"Wickets",value:this.state.playerStats.bowling.wickets}} backsideInfo={this.state.playerStats.bowling.wicketsInfo} color="#1A9A33" turnBack={true} title="Career Wickets"/> <Card mainInfo={{key:"Average",value:this.state.playerStats.bowling.average}} backsideInfo={this.state.playerStats.bowling.stats} color="#1A9A33" title="Abilities" turnBack={true}/> <Card mainInfo={this.state.playerStats.bowling.favoriteStadium} backsideInfo={this.state.playerStats.bowling.stadiumWickets} color="#1A9A33" title="Favorite Stadium" turnBack={true}/> <Card mainInfo={this.state.playerStats.bowling.topFielding} backsideInfo={this.state.playerStats.bowling.fieldingInfo} color="#0E81E7" title="Fielding" turnBack={true}/> </GridList> </div>; } } export default Player;
/* * Copyright (c) 2016 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2025-04-28 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ require("./common.js")(); exports.command = "stop <command>"; exports.desc = "Stop objects"; exports.handler = function () {}; exports.builder = function (yargs) { yargs .command( "service <name>", "Stop a service", function (yargs) { return yargs .epilog( "Stopping a service will prevent all the listeners for that service " + "from accepting new connections. Existing connections will still be " + "handled normally until they are closed." ) .usage("Usage: stop service <name>"); }, function (argv) { maxctrl(argv, function (host) { return doRequest(host, "services/" + argv.name + "/stop", null, { method: "PUT" }); }); } ) .command( "monitor <name>", "Stop a monitor", function (yargs) { return yargs .epilog( "Stopping a monitor will pause the monitoring of the servers. " + "This can be used to manually control server states with the " + "`set server` command." ) .usage("Usage: stop monitor <name>"); }, function (argv) { maxctrl(argv, function (host) { return doRequest(host, "monitors/" + argv.name + "/stop", null, { method: "PUT" }); }); } ) .command( ["services", "maxscale"], "Stop all services", function (yargs) { return yargs .epilog("This command will execute the `stop service` command for " + "all services in MaxScale.") .usage("Usage: stop [services|maxscale]"); }, function (argv) { maxctrl(argv, function (host) { return doRequest(host, "services/", function (res) { var promises = []; res.data.forEach(function (i) { promises.push(doRequest(host, "services/" + i.id + "/stop", null, { method: "PUT" })); }); return Promise.all(promises).then(() => OK()); }); }); } ) .usage("Usage: stop <command>") .help() .wrap(null) .demandCommand(1, helpMsg); };
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _DiffTwoTone = _interopRequireDefault(require("@ant-design/icons-svg/lib/asn/DiffTwoTone")); var _AntdIcon = _interopRequireDefault(require("../components/AntdIcon")); // GENERATE BY ./scripts/generate.ts // DON NOT EDIT IT MANUALLY var DiffTwoTone = function DiffTwoTone(props, ref) { return React.createElement(_AntdIcon.default, Object.assign({}, props, { ref: ref, icon: _DiffTwoTone.default })); }; DiffTwoTone.displayName = 'DiffTwoTone'; var _default = React.forwardRef(DiffTwoTone); exports.default = _default;
import logger from './util/logger' import parseString from './parseString' import denormalise from './denormalise' import toSVG from './toSVG' import toPolylines from './toPolylines' import groupEntitiesByLayer from './groupEntitiesByLayer' export default class Helper { constructor (contents) { if (!(typeof contents === 'string')) { throw Error('Helper constructor expects a DXF string') } this._contents = contents this._parsed = null this._denormalised = null } parse () { this._parsed = parseString(this._contents) logger.info('parsed:', this.parsed) return this._parsed } get parsed () { if (this._parsed === null) { this.parse() } return this._parsed } denormalise () { this._denormalised = denormalise(this.parsed) logger.info('denormalised:', this._denormalised) return this._denormalised } get denormalised () { if (!this._denormalised) { this.denormalise() } return this._denormalised } group () { this._groups = groupEntitiesByLayer(this.denormalised) } get groups () { if (!this._groups) { this.group() } return this._groups } toSVG () { return toSVG(this.parsed) } toPolylines () { return toPolylines(this.parsed) } }
const { Schema, model } = require("mongoose"); const OperationSchema = new Schema( { balance_last: { type: Number, required: true }, balance_now: { type: Number, required: true }, rollback: Date, credit_id: { type: Schema.Types.ObjectId, ref: "Credit", }, debit_id: { type: Schema.Types.ObjectId, ref: "Debit", }, }, { timestamps: true, } ); module.exports = model("Operation", OperationSchema);
"no use strict";(function(e){function t(e,t){var n=e,r="";while(n){var i=t[n];if(typeof i=="string")return i+r;if(i)return i.location.replace(/\/*$/,"/")+(r||i.main||i.name);if(i===!1)return"";var s=n.lastIndexOf("/");if(s===-1)break;r=n.substr(s)+r,n=n.slice(0,s)}return e}if(typeof e.window!="undefined"&&e.document)return;if(e.require&&e.define)return;e.console||(e.console=function(){var e=Array.prototype.slice.call(arguments,0);postMessage({type:"log",data:e})},e.console.error=e.console.warn=e.console.log=e.console.trace=e.console),e.window=e,e.ace=e,e.onerror=function(e,t,n,r,i){postMessage({type:"error",data:{message:e,data:i.data,file:t,line:n,col:r,stack:i.stack}})},e.normalizeModule=function(t,n){if(n.indexOf("!")!==-1){var r=n.split("!");return e.normalizeModule(t,r[0])+"!"+e.normalizeModule(t,r[1])}if(n.charAt(0)=="."){var i=t.split("/").slice(0,-1).join("/");n=(i?i+"/":"")+n;while(n.indexOf(".")!==-1&&s!=n){var s=n;n=n.replace(/^\.\//,"").replace(/\/\.\//,"/").replace(/[^\/]+\/\.\.\//,"")}}return n},e.require=function(r,i){i||(i=r,r=null);if(!i.charAt)throw new Error("worker.js require() accepts only (parentId, id) as arguments");i=e.normalizeModule(r,i);var s=e.require.modules[i];if(s)return s.initialized||(s.initialized=!0,s.exports=s.factory().exports),s.exports;if(!e.require.tlns)return console.log("unable to load "+i);var o=t(i,e.require.tlns);return o.slice(-3)!=".js"&&(o+=".js"),e.require.id=i,e.require.modules[i]={},importScripts(o),e.require(r,i)},e.require.modules={},e.require.tlns={},e.define=function(t,n,r){arguments.length==2?(r=n,typeof t!="string"&&(n=t,t=e.require.id)):arguments.length==1&&(r=t,n=[],t=e.require.id);if(typeof r!="function"){e.require.modules[t]={exports:r,initialized:!0};return}n.length||(n=["require","exports","module"]);var i=function(n){return e.require(t,n)};e.require.modules[t]={exports:{},factory:function(){var e=this,t=r.apply(this,n.map(function(t){switch(t){case"require":return i;case"exports":return e.exports;case"module":return e;default:return i(t)}}));return t&&(e.exports=t),e}}},e.define.amd={},require.tlns={},e.initBaseUrls=function(t){for(var n in t)require.tlns[n]=t[n]},e.initSender=function(){var n=e.require("ace/lib/event_emitter").EventEmitter,r=e.require("ace/lib/oop"),i=function(){};return function(){r.implement(this,n),this.callback=function(e,t){postMessage({type:"call",id:t,data:e})},this.emit=function(e,t){postMessage({type:"event",name:e,data:t})}}.call(i.prototype),new i};var n=e.main=null,r=e.sender=null;e.onmessage=function(t){var i=t.data;if(i.event&&r)r._signal(i.event,i.data);else if(i.command)if(n[i.command])n[i.command].apply(n,i.args);else{if(!e[i.command])throw new Error("Unknown command:"+i.command);e[i.command].apply(e,i.args)}else if(i.init){e.initBaseUrls(i.tlns),require("ace/lib/es5-shim"),r=e.sender=e.initSender();var s=require(i.module)[i.classname];n=e.main=new s(r)}}})(this),define("ace/lib/oop",["require","exports","module"],function(e,t,n){"use strict";t.inherits=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})},t.mixin=function(e,t){for(var n in t)e[n]=t[n];return e},t.implement=function(e,n){t.mixin(e,n)}}),define("ace/lib/lang",["require","exports","module"],function(e,t,n){"use strict";t.last=function(e){return e[e.length-1]},t.stringReverse=function(e){return e.split("").reverse().join("")},t.stringRepeat=function(e,t){var n="";while(t>0){t&1&&(n+=e);if(t>>=1)e+=e}return n};var r=/^\s\s*/,i=/\s\s*$/;t.stringTrimLeft=function(e){return e.replace(r,"")},t.stringTrimRight=function(e){return e.replace(i,"")},t.copyObject=function(e){var t={};for(var n in e)t[n]=e[n];return t},t.copyArray=function(e){var t=[];for(var n=0,r=e.length;n<r;n++)e[n]&&typeof e[n]=="object"?t[n]=this.copyObject(e[n]):t[n]=e[n];return t},t.deepCopy=function s(e){if(typeof e!="object"||!e)return e;var t;if(Array.isArray(e)){t=[];for(var n=0;n<e.length;n++)t[n]=s(e[n]);return t}var r=e.constructor;if(r===RegExp)return e;t=r();for(var n in e)t[n]=s(e[n]);return t},t.arrayToMap=function(e){var t={};for(var n=0;n<e.length;n++)t[e[n]]=1;return t},t.createMap=function(e){var t=Object.create(null);for(var n in e)t[n]=e[n];return t},t.arrayRemove=function(e,t){for(var n=0;n<=e.length;n++)t===e[n]&&e.splice(n,1)},t.escapeRegExp=function(e){return e.replace(/([.*+?^${}()|[\]\/\\])/g,"\\$1")},t.escapeHTML=function(e){return e.replace(/&/g,"&#38;").replace(/"/g,"&#34;").replace(/'/g,"&#39;").replace(/</g,"&#60;")},t.getMatchOffsets=function(e,t){var n=[];return e.replace(t,function(e){n.push({offset:arguments[arguments.length-2],length:e.length})}),n},t.deferredCall=function(e){var t=null,n=function(){t=null,e()},r=function(e){return r.cancel(),t=setTimeout(n,e||0),r};return r.schedule=r,r.call=function(){return this.cancel(),e(),r},r.cancel=function(){return clearTimeout(t),t=null,r},r.isPending=function(){return t},r},t.delayedCall=function(e,t){var n=null,r=function(){n=null,e()},i=function(e){n==null&&(n=setTimeout(r,e||t))};return i.delay=function(e){n&&clearTimeout(n),n=setTimeout(r,e||t)},i.schedule=i,i.call=function(){this.cancel(),e()},i.cancel=function(){n&&clearTimeout(n),n=null},i.isPending=function(){return n},i}}),define("ace/range",["require","exports","module"],function(e,t,n){"use strict";var r=function(e,t){return e.row-t.row||e.column-t.column},i=function(e,t,n,r){this.start={row:e,column:t},this.end={row:n,column:r}};(function(){this.isEqual=function(e){return this.start.row===e.start.row&&this.end.row===e.end.row&&this.start.column===e.start.column&&this.end.column===e.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(e,t){return this.compare(e,t)==0},this.compareRange=function(e){var t,n=e.end,r=e.start;return t=this.compare(n.row,n.column),t==1?(t=this.compare(r.row,r.column),t==1?2:t==0?1:0):t==-1?-2:(t=this.compare(r.row,r.column),t==-1?-1:t==1?42:0)},this.comparePoint=function(e){return this.compare(e.row,e.column)},this.containsRange=function(e){return this.comparePoint(e.start)==0&&this.comparePoint(e.end)==0},this.intersects=function(e){var t=this.compareRange(e);return t==-1||t==0||t==1},this.isEnd=function(e,t){return this.end.row==e&&this.end.column==t},this.isStart=function(e,t){return this.start.row==e&&this.start.column==t},this.setStart=function(e,t){typeof e=="object"?(this.start.column=e.column,this.start.row=e.row):(this.start.row=e,this.start.column=t)},this.setEnd=function(e,t){typeof e=="object"?(this.end.column=e.column,this.end.row=e.row):(this.end.row=e,this.end.column=t)},this.inside=function(e,t){return this.compare(e,t)==0?this.isEnd(e,t)||this.isStart(e,t)?!1:!0:!1},this.insideStart=function(e,t){return this.compare(e,t)==0?this.isEnd(e,t)?!1:!0:!1},this.insideEnd=function(e,t){return this.compare(e,t)==0?this.isStart(e,t)?!1:!0:!1},this.compare=function(e,t){return!this.isMultiLine()&&e===this.start.row?t<this.start.column?-1:t>this.end.column?1:0:e<this.start.row?-1:e>this.end.row?1:this.start.row===e?t>=this.start.column?0:-1:this.end.row===e?t<=this.end.column?0:1:0},this.compareStart=function(e,t){return this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.compareEnd=function(e,t){return this.end.row==e&&this.end.column==t?1:this.compare(e,t)},this.compareInside=function(e,t){return this.end.row==e&&this.end.column==t?1:this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.clipRows=function(e,t){if(this.end.row>t)var n={row:t+1,column:0};else if(this.end.row<e)var n={row:e,column:0};if(this.start.row>t)var r={row:t+1,column:0};else if(this.start.row<e)var r={row:e,column:0};return i.fromPoints(r||this.start,n||this.end)},this.extend=function(e,t){var n=this.compare(e,t);if(n==0)return this;if(n==-1)var r={row:e,column:t};else var s={row:e,column:t};return i.fromPoints(r||this.start,s||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return i.fromPoints(this.start,this.end)},this.collapseRows=function(){return this.end.column==0?new i(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new i(this.start.row,0,this.end.row,0)},this.toScreenRange=function(e){var t=e.documentToScreenPosition(this.start),n=e.documentToScreenPosition(this.end);return new i(t.row,t.column,n.row,n.column)},this.moveBy=function(e,t){this.start.row+=e,this.start.column+=t,this.end.row+=e,this.end.column+=t}}).call(i.prototype),i.fromPoints=function(e,t){return new i(e.row,e.column,t.row,t.column)},i.comparePoints=r,i.comparePoints=function(e,t){return e.row-t.row||e.column-t.column},t.Range=i}),define("ace/apply_delta",["require","exports","module"],function(e,t,n){"use strict";function r(e,t){throw console.log("Invalid Delta:",e),"Invalid Delta: "+t}function i(e,t){return t.row>=0&&t.row<e.length&&t.column>=0&&t.column<=e[t.row].length}function s(e,t){t.action!="insert"&&t.action!="remove"&&r(t,"delta.action must be 'insert' or 'remove'"),t.lines instanceof Array||r(t,"delta.lines must be an Array"),(!t.start||!t.end)&&r(t,"delta.start/end must be an present");var n=t.start;i(e,t.start)||r(t,"delta.start must be contained in document");var s=t.end;t.action=="remove"&&!i(e,s)&&r(t,"delta.end must contained in document for 'remove' actions");var o=s.row-n.row,u=s.column-(o==0?n.column:0);(o!=t.lines.length-1||t.lines[o].length!=u)&&r(t,"delta.range must match delta lines")}t.applyDelta=function(e,t,n){var r=t.start.row,i=t.start.column,s=e[r]||"";switch(t.action){case"insert":var o=t.lines;if(o.length===1)e[r]=s.substring(0,i)+t.lines[0]+s.substring(i);else{var u=[r,1].concat(t.lines);e.splice.apply(e,u),e[r]=s.substring(0,i)+e[r],e[r+t.lines.length-1]+=s.substring(i)}break;case"remove":var a=t.end.column,f=t.end.row;r===f?e[r]=s.substring(0,i)+s.substring(a):e.splice(r,f-r+1,s.substring(0,i)+e[f].substring(a))}}}),define("ace/lib/event_emitter",["require","exports","module"],function(e,t,n){"use strict";var r={},i=function(){this.propagationStopped=!0},s=function(){this.defaultPrevented=!0};r._emit=r._dispatchEvent=function(e,t){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var n=this._eventRegistry[e]||[],r=this._defaultHandlers[e];if(!n.length&&!r)return;if(typeof t!="object"||!t)t={};t.type||(t.type=e),t.stopPropagation||(t.stopPropagation=i),t.preventDefault||(t.preventDefault=s),n=n.slice();for(var o=0;o<n.length;o++){n[o](t,this);if(t.propagationStopped)break}if(r&&!t.defaultPrevented)return r(t,this)},r._signal=function(e,t){var n=(this._eventRegistry||{})[e];if(!n)return;n=n.slice();for(var r=0;r<n.length;r++)n[r](t,this)},r.once=function(e,t){var n=this;t&&this.addEventListener(e,function r(){n.removeEventListener(e,r),t.apply(null,arguments)})},r.setDefaultHandler=function(e,t){var n=this._defaultHandlers;n||(n=this._defaultHandlers={_disabled_:{}});if(n[e]){var r=n[e],i=n._disabled_[e];i||(n._disabled_[e]=i=[]),i.push(r);var s=i.indexOf(t);s!=-1&&i.splice(s,1)}n[e]=t},r.removeDefaultHandler=function(e,t){var n=this._defaultHandlers;if(!n)return;var r=n._disabled_[e];if(n[e]==t){var i=n[e];r&&this.setDefaultHandler(e,r.pop())}else if(r){var s=r.indexOf(t);s!=-1&&r.splice(s,1)}},r.on=r.addEventListener=function(e,t,n){this._eventRegistry=this._eventRegistry||{};var r=this._eventRegistry[e];return r||(r=this._eventRegistry[e]=[]),r.indexOf(t)==-1&&r[n?"unshift":"push"](t),t},r.off=r.removeListener=r.removeEventListener=function(e,t){this._eventRegistry=this._eventRegistry||{};var n=this._eventRegistry[e];if(!n)return;var r=n.indexOf(t);r!==-1&&n.splice(r,1)},r.removeAllListeners=function(e){this._eventRegistry&&(this._eventRegistry[e]=[])},t.EventEmitter=r}),define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(e,t,n){"use strict";var r=e("./lib/oop"),i=e("./lib/event_emitter").EventEmitter,s=t.Anchor=function(e,t,n){this.$onChange=this.onChange.bind(this),this.attach(e),typeof n=="undefined"?this.setPosition(t.row,t.column):this.setPosition(t,n)};(function(){function e(e,t,n){var r=n?e.column<=t.column:e.column<t.column;return e.row<t.row||e.row==t.row&&r}function t(t,n,r){var i=t.action=="insert",s=(i?1:-1)*(t.end.row-t.start.row),o=(i?1:-1)*(t.end.column-t.start.column),u=t.start,a=i?u:t.end;return e(n,u,r)?{row:n.row,column:n.column}:e(a,n,!r)?{row:n.row+s,column:n.column+(n.row==a.row?o:0)}:{row:u.row,column:u.column}}r.implement(this,i),this.getPosition=function(){return this.$clipPositionToDocument(this.row,this.column)},this.getDocument=function(){return this.document},this.$insertRight=!1,this.onChange=function(e){if(e.start.row==e.end.row&&e.start.row!=this.row)return;if(e.start.row>this.row)return;var n=t(e,{row:this.row,column:this.column},this.$insertRight);this.setPosition(n.row,n.column,!0)},this.setPosition=function(e,t,n){var r;n?r={row:e,column:t}:r=this.$clipPositionToDocument(e,t);if(this.row==r.row&&this.column==r.column)return;var i={row:this.row,column:this.column};this.row=r.row,this.column=r.column,this._signal("change",{old:i,value:r})},this.detach=function(){this.document.removeEventListener("change",this.$onChange)},this.attach=function(e){this.document=e||this.document,this.document.on("change",this.$onChange)},this.$clipPositionToDocument=function(e,t){var n={};return e>=this.document.getLength()?(n.row=Math.max(0,this.document.getLength()-1),n.column=this.document.getLine(n.row).length):e<0?(n.row=0,n.column=0):(n.row=e,n.column=Math.min(this.document.getLine(n.row).length,Math.max(0,t))),t<0&&(n.column=0),n}}).call(s.prototype)}),define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"],function(e,t,n){"use strict";var r=e("./lib/oop"),i=e("./apply_delta").applyDelta,s=e("./lib/event_emitter").EventEmitter,o=e("./range").Range,u=e("./anchor").Anchor,a=function(e){this.$lines=[""],e.length===0?this.$lines=[""]:Array.isArray(e)?this.insertMergedLines({row:0,column:0},e):this.insert({row:0,column:0},e)};(function(){r.implement(this,s),this.setValue=function(e){var t=this.getLength()-1;this.remove(new o(0,0,t,this.getLine(t).length)),this.insert({row:0,column:0},e)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(e,t){return new u(this,e,t)},"aaa".split(/a/).length===0?this.$split=function(e){return e.replace(/\r\n|\r/g,"\n").split("\n")}:this.$split=function(e){return e.split(/\r\n|\r|\n/)},this.$detectNewLine=function(e){var t=e.match(/^.*?(\r\n|\r|\n)/m);this.$autoNewLine=t?t[1]:"\n",this._signal("changeNewLineMode")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case"windows":return"\r\n";case"unix":return"\n";default:return this.$autoNewLine||"\n"}},this.$autoNewLine="",this.$newLineMode="auto",this.setNewLineMode=function(e){if(this.$newLineMode===e)return;this.$newLineMode=e,this._signal("changeNewLineMode")},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(e){return e=="\r\n"||e=="\r"||e=="\n"},this.getLine=function(e){return this.$lines[e]||""},this.getLines=function(e,t){return this.$lines.slice(e,t+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(e){return this.getLinesForRange(e).join(this.getNewLineCharacter())},this.getLinesForRange=function(e){var t;if(e.start.row===e.end.row)t=[this.getLine(e.start.row).substring(e.start.column,e.end.column)];else{t=this.getLines(e.start.row,e.end.row),t[0]=(t[0]||"").substring(e.start.column);var n=t.length-1;e.end.row-e.start.row==n&&(t[n]=t[n].substring(0,e.end.column))}return t},this.insertLines=function(e,t){return console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."),this.insertFullLines(e,t)},this.removeLines=function(e,t){return console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."),this.removeFullLines(e,t)},this.insertNewLine=function(e){return console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."),this.insertMergedLines(e,["",""])},this.insert=function(e,t){return this.getLength()<=1&&this.$detectNewLine(t),this.insertMergedLines(e,this.$split(t))},this.insertInLine=function(e,t){var n=this.clippedPos(e.row,e.column),r=this.pos(e.row,e.column+t.length);return this.applyDelta({start:n,end:r,action:"insert",lines:[t]},!0),this.clonePos(r)},this.clippedPos=function(e,t){var n=this.getLength();e===undefined?e=n:e<0?e=0:e>=n&&(e=n-1,t=undefined);var r=this.getLine(e);return t==undefined&&(t=r.length),t=Math.min(Math.max(t,0),r.length),{row:e,column:t}},this.clonePos=function(e){return{row:e.row,column:e.column}},this.pos=function(e,t){return{row:e,column:t}},this.$clipPosition=function(e){var t=this.getLength();return e.row>=t?(e.row=Math.max(0,t-1),e.column=this.getLine(t-1).length):(e.row=Math.max(0,e.row),e.column=Math.min(Math.max(e.column,0),this.getLine(e.row).length)),e},this.insertFullLines=function(e,t){e=Math.min(Math.max(e,0),this.getLength());var n=0;e<this.getLength()?(t=t.concat([""]),n=0):(t=[""].concat(t),e--,n=this.$lines[e].length),this.insertMergedLines({row:e,column:n},t)},this.insertMergedLines=function(e,t){var n=this.clippedPos(e.row,e.column),r={row:n.row+t.length-1,column:(t.length==1?n.column:0)+t[t.length-1].length};return this.applyDelta({start:n,end:r,action:"insert",lines:t}),this.clonePos(r)},this.remove=function(e){var t=this.clippedPos(e.start.row,e.start.column),n=this.clippedPos(e.end.row,e.end.column);return this.applyDelta({start:t,end:n,action:"remove",lines:this.getLinesForRange({start:t,end:n})}),this.clonePos(t)},this.removeInLine=function(e,t,n){var r=this.clippedPos(e,t),i=this.clippedPos(e,n);return this.applyDelta({start:r,end:i,action:"remove",lines:this.getLinesForRange({start:r,end:i})},!0),this.clonePos(r)},this.removeFullLines=function(e,t){e=Math.min(Math.max(0,e),this.getLength()-1),t=Math.min(Math.max(0,t),this.getLength()-1);var n=t==this.getLength()-1&&e>0,r=t<this.getLength()-1,i=n?e-1:e,s=n?this.getLine(i).length:0,u=r?t+1:t,a=r?0:this.getLine(u).length,f=new o(i,s,u,a),l=this.$lines.slice(e,t+1);return this.applyDelta({start:f.start,end:f.end,action:"remove",lines:this.getLinesForRange(f)}),l},this.removeNewLine=function(e){e<this.getLength()-1&&e>=0&&this.applyDelta({start:this.pos(e,this.getLine(e).length),end:this.pos(e+1,0),action:"remove",lines:["",""]})},this.replace=function(e,t){!e instanceof o&&(e=o.fromPoints(e.start,e.end));if(t.length===0&&e.isEmpty())return e.start;if(t==this.getTextRange(e))return e.end;this.remove(e);var n;return t?n=this.insert(e.start,t):n=e.start,n},this.applyDeltas=function(e){for(var t=0;t<e.length;t++)this.applyDelta(e[t])},this.revertDeltas=function(e){for(var t=e.length-1;t>=0;t--)this.revertDelta(e[t])},this.applyDelta=function(e,t){var n=e.action=="insert";if(n?e.lines.length<=1&&!e.lines[0]:!o.comparePoints(e.start,e.end))return;n&&e.lines.length>2e4&&this.$splitAndapplyLargeDelta(e,2e4),i(this.$lines,e,t),this._signal("change",e)},this.$splitAndapplyLargeDelta=function(e,t){var n=e.lines,r=n.length,i=e.start.row,s=e.start.column,o=0,u=0;do{o=u,u+=t-1;var a=n.slice(o,u);if(u>r){e.lines=a,e.start.row=i+o,e.start.column=s;break}a.push(""),this.applyDelta({start:this.pos(i+o,s),end:this.pos(i+u,s=0),action:e.action,lines:a},!0)}while(!0)},this.revertDelta=function(e){this.applyDelta({start:this.clonePos(e.start),end:this.clonePos(e.end),action:e.action=="insert"?"remove":"insert",lines:e.lines.slice()})},this.indexToPosition=function(e,t){var n=this.$lines||this.getAllLines(),r=this.getNewLineCharacter().length;for(var i=t||0,s=n.length;i<s;i++){e-=n[i].length+r;if(e<0)return{row:i,column:e+n[i].length+r}}return{row:s-1,column:n[s-1].length}},this.positionToIndex=function(e,t){var n=this.$lines||this.getAllLines(),r=this.getNewLineCharacter().length,i=0,s=Math.min(e.row,n.length);for(var o=t||0;o<s;++o)i+=n[o].length+r;return i+e.column}}).call(a.prototype),t.Document=a}),define("ace/worker/mirror",["require","exports","module","ace/range","ace/document","ace/lib/lang"],function(e,t,n){"use strict";var r=e("../range").Range,i=e("../document").Document,s=e("../lib/lang"),o=t.Mirror=function(e){this.sender=e;var t=this.doc=new i(""),n=this.deferredUpdate=s.delayedCall(this.onUpdate.bind(this)),r=this;e.on("change",function(e){var i=e.data;if(i[0].start)t.applyDeltas(i);else for(var s=0;s<i.length;s+=2){if(Array.isArray(i[s+1]))var o={action:"insert",start:i[s],lines:i[s+1]};else var o={action:"remove",start:i[s],end:i[s+1]};t.applyDelta(o,!0)}if(r.$timeout)return n.schedule(r.$timeout);r.onUpdate()})};(function(){this.$timeout=500,this.setTimeout=function(e){this.$timeout=e},this.setValue=function(e){this.doc.setValue(e),this.deferredUpdate.schedule(this.$timeout)},this.getValue=function(e){this.sender.callback(this.doc.getValue(),e)},this.onUpdate=function(){},this.isPending=function(){return this.deferredUpdate.isPending()}}).call(o.prototype)}),define("ace/mode/xml/sax",["require","exports","module"],function(e,t,n){function d(){}function v(e,t,n,r,i){function s(e){if(e>65535){e-=65536;var t=55296+(e>>10),n=56320+(e&1023);return String.fromCharCode(t,n)}return String.fromCharCode(e)}function o(e){var t=e.slice(1,-1);return t in n?n[t]:t.charAt(0)==="#"?s(parseInt(t.substr(1).replace("x","0x"))):(i.error("entity not found:"+e),e)}function u(t){var n=e.substring(v,t).replace(/&#?\w+;/g,o);h&&a(v),r.characters(n,0,t-v),v=t}function a(t,n){while(t>=l&&(n=c.exec(e)))f=n.index,l=f+n[0].length,h.lineNumber++;h.columnNumber=t-f+1}var f=0,l=0,c=/.+(?:\r\n?|\n)|.*$/g,h=r.locator,p=[{currentNSMap:t}],d={},v=0;for(;;){var E=e.indexOf("<",v);if(E<0){if(!e.substr(v).match(/^\s*$/)){var N=r.document,C=N.createTextNode(e.substr(v));N.appendChild(C),r.currentElement=C}return}E>v&&u(E);switch(e.charAt(E+1)){case"/":var k=e.indexOf(">",E+3),L=e.substring(E+2,k),A;if(!(p.length>1)){i.fatalError("end tag name not found for: "+L);break}A=p.pop();var O=A.localNSMap;A.tagName!=L&&i.fatalError("end tag name: "+L+" does not match the current start tagName: "+A.tagName),r.endElement(A.uri,A.localName,L);if(O)for(var M in O)r.endPrefixMapping(M);k++;break;case"?":h&&a(E),k=x(e,E,r);break;case"!":h&&a(E),k=S(e,E,r,i);break;default:try{h&&a(E);var _=new T,k=g(e,E,_,o,i),D=_.length;if(D&&h){var P=m(h,{});for(var E=0;E<D;E++){var H=_[E];a(H.offset),H.offset=m(h,{})}m(P,h)}!_.closed&&w(e,k,_.tagName,d)&&(_.closed=!0,n.nbsp||i.warning("unclosed xml attribute")),y(_,r,p),_.uri==="http://www.w3.org/1999/xhtml"&&!_.closed?k=b(e,k,_.tagName,o,r):k++}catch(B){i.error("element parse error: "+B),k=-1}}k<0?u(E+1):v=k}}function m(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function g(e,t,n,r,i){var s,d,v=++t,m=o;for(;;){var g=e.charAt(v);switch(g){case"=":if(m===u)s=e.slice(t,v),m=f;else{if(m!==a)throw new Error("attribute equal must after attrName");m=f}break;case"'":case'"':if(m===f){t=v+1,v=e.indexOf(g,t);if(!(v>0))throw new Error("attribute value no end '"+g+"' match");d=e.slice(t,v).replace(/&#?\w+;/g,r),n.add(s,d,t-1),m=c}else{if(m!=l)throw new Error('attribute value must after "="');d=e.slice(t,v).replace(/&#?\w+;/g,r),n.add(s,d,t),i.warning('attribute "'+s+'" missed start quot('+g+")!!"),t=v+1,m=c}break;case"/":switch(m){case o:n.setTagName(e.slice(t,v));case c:case h:case p:m=p,n.closed=!0;case l:case u:case a:break;default:throw new Error("attribute invalid close char('/')")}break;case"":i.error("unexpected end of input");case">":switch(m){case o:n.setTagName(e.slice(t,v));case c:case h:case p:break;case l:case u:d=e.slice(t,v),d.slice(-1)==="/"&&(n.closed=!0,d=d.slice(0,-1));case a:m===a&&(d=s),m==l?(i.warning('attribute "'+d+'" missed quot(")!!'),n.add(s,d.replace(/&#?\w+;/g,r),t)):(i.warning('attribute "'+d+'" missed value!! "'+d+'" instead!!'),n.add(d,d,t));break;case f:throw new Error("attribute value missed!!")}return v;case"\u0080":g=" ";default:if(g<=" ")switch(m){case o:n.setTagName(e.slice(t,v)),m=h;break;case u:s=e.slice(t,v),m=a;break;case l:var d=e.slice(t,v).replace(/&#?\w+;/g,r);i.warning('attribute "'+d+'" missed quot(")!!'),n.add(s,d,t);case c:m=h}else switch(m){case a:i.warning('attribute "'+s+'" missed value!! "'+s+'" instead!!'),n.add(s,s,t),t=v,m=u;break;case c:i.warning('attribute space is required"'+s+'"!!');case h:m=u,t=v;break;case f:m=l,t=v;break;case p:throw new Error("elements closed character '/' and '>' must be connected to")}}v++}}function y(e,t,n){var r=e.tagName,i=null,s=n[n.length-1].currentNSMap,o=e.length;while(o--){var u=e[o],a=u.qName,f=u.value,l=a.indexOf(":");if(l>0)var c=u.prefix=a.slice(0,l),h=a.slice(l+1),p=c==="xmlns"&&h;else h=a,c=null,p=a==="xmlns"&&"";u.localName=h,p!==!1&&(i==null&&(i={},E(s,s={})),s[p]=i[p]=f,u.uri="http://www.w3.org/2000/xmlns/",t.startPrefixMapping(p,f))}var o=e.length;while(o--){u=e[o];var c=u.prefix;c&&(c==="xml"&&(u.uri="http://www.w3.org/XML/1998/namespace"),c!=="xmlns"&&(u.uri=s[c]))}var l=r.indexOf(":");l>0?(c=e.prefix=r.slice(0,l),h=e.localName=r.slice(l+1)):(c=null,h=e.localName=r);var d=e.uri=s[c||""];t.startElement(d,h,r,e);if(e.closed){t.endElement(d,h,r);if(i)for(c in i)t.endPrefixMapping(c)}else e.currentNSMap=s,e.localNSMap=i,n.push(e)}function b(e,t,n,r,i){if(/^(?:script|textarea)$/i.test(n)){var s=e.indexOf("</"+n+">",t),o=e.substring(t+1,s);if(/[&<]/.test(o))return/^script$/i.test(n)?(i.characters(o,0,o.length),s):(o=o.replace(/&#?\w+;/g,r),i.characters(o,0,o.length),s)}return t+1}function w(e,t,n,r){var i=r[n];return i==null&&(i=r[n]=e.lastIndexOf("</"+n+">")),i<t}function E(e,t){for(var n in e)t[n]=e[n]}function S(e,t,n,r){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var s=e.indexOf("-->",t+4);return s>t?(n.comment(e,t+4,s-t-4),s+3):(r.error("Unclosed comment"),-1)}return-1;default:if(e.substr(t+3,6)=="CDATA["){var s=e.indexOf("]]>",t+9);return n.startCDATA(),n.characters(e,t+9,s-t-9),n.endCDATA(),s+3}var o=C(e,t),u=o.length;if(u>1&&/!doctype/i.test(o[0][0])){var a=o[1][0],f=u>3&&/^public$/i.test(o[2][0])&&o[3][0],l=u>4&&o[4][0],c=o[u-1];return n.startDTD(a,f&&f.replace(/^(['"])(.*?)\1$/,"$2"),l&&l.replace(/^(['"])(.*?)\1$/,"$2")),n.endDTD(),c.index+c[0].length}}return-1}function x(e,t,n){var r=e.indexOf("?>",t);if(r){var i=e.substring(t,r).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);if(i){var s=i[0].length;return n.processingInstruction(i[1],i[2]),r+2}return-1}return-1}function T(e){}function N(e,t){return e.__proto__=t,e}function C(e,t){var n,r=[],i=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;i.lastIndex=t,i.exec(e);while(n=i.exec(e)){r.push(n);if(n[1])return r}}var r=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,i=new RegExp("[\\-\\.0-9"+r.source.slice(1,-1)+"\u00b7\u0300-\u036f\\ux203F-\u2040]"),s=new RegExp("^"+r.source+i.source+"*(?::"+r.source+i.source+"*)?$"),o=0,u=1,a=2,f=3,l=4,c=5,h=6,p=7;return d.prototype={parse:function(e,t,n){var r=this.domBuilder;r.startDocument(),E(t,t={}),v(e,t,n,r,this.errorHandler),r.endDocument()}},T.prototype={setTagName:function(e){if(!s.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},add:function(e,t,n){if(!s.test(e))throw new Error("invalid attribute:"+e);this[this.length++]={qName:e,value:t,offset:n}},length:0,getLocalName:function(e){return this[e].localName},getOffset:function(e){return this[e].offset},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}},N({},N.prototype)instanceof N||(N=function(e,t){function n(){}n.prototype=t,n=new n;for(t in e)n[t]=e[t];return n}),d}),define("ace/mode/xml/dom",["require","exports","module"],function(e,t,n){function r(e,t){for(var n in e)t[n]=e[n]}function i(e,t){var n=e.prototype;if(Object.create){var i=Object.create(t.prototype);n.__proto__=i}if(!(n instanceof t)){function s(){}s.prototype=t.prototype,s=new s,r(n,s),e.prototype=n=s}n.constructor!=e&&(typeof e!="function"&&console.error("unknow Class:"+e),n.constructor=e)}function B(e,t){if(t instanceof Error)var n=t;else n=this,Error.call(this,w[e]),this.message=w[e],Error.captureStackTrace&&Error.captureStackTrace(this,B);return n.code=e,t&&(this.message=this.message+": "+t),n}function j(){}function F(e,t){this._node=e,this._refresh=t,I(this)}function I(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!=t){var n=e._refresh(e._node);gt(e,"length",n.length),r(n,e),e._inc=t}}function q(){}function R(e,t){var n=e.length;while(n--)if(e[n]===t)return n}function U(e,t,n,r){r?t[R(t,r)]=n:t[t.length++]=n;if(e){n.ownerElement=e;var i=e.ownerDocument;i&&(r&&Q(i,e,r),K(i,e,n))}}function z(e,t,n){var r=R(t,n);if(!(r>=0))throw B(L,new Error);var i=t.length-1;while(r<i)t[r]=t[++r];t.length=i;if(e){var s=e.ownerDocument;s&&(Q(s,e,n),n.ownerElement=null)}}function W(e){this._features={};if(e)for(var t in e)this._features=e[t]}function X(){}function V(e){return e=="<"&&"&lt;"||e==">"&&"&gt;"||e=="&"&&"&amp;"||e=='"'&&"&quot;"||"&#"+e.charCodeAt()+";"}function $(e,t){if(t(e))return!0;if(e=e.firstChild)do if($(e,t))return!0;while(e=e.nextSibling)}function J(){}function K(e,t,n){e&&e._inc++;var r=n.namespaceURI;r=="http://www.w3.org/2000/xmlns/"&&(t._nsMap[n.prefix?n.localName:""]=n.value)}function Q(e,t,n,r){e&&e._inc++;var i=n.namespaceURI;i=="http://www.w3.org/2000/xmlns/"&&delete t._nsMap[n.prefix?n.localName:""]}function G(e,t,n){if(e&&e._inc){e._inc++;var r=t.childNodes;if(n)r[r.length++]=n;else{var i=t.firstChild,s=0;while(i)r[s++]=i,i=i.nextSibling;r.length=s}}}function Y(e,t){var n=t.previousSibling,r=t.nextSibling;return n?n.nextSibling=r:e.firstChild=r,r?r.previousSibling=n:e.lastChild=n,G(e.ownerDocument,e),t}function Z(e,t,n){var r=t.parentNode;r&&r.removeChild(t);if(t.nodeType===g){var i=t.firstChild;if(i==null)return t;var s=t.lastChild}else i=s=t;var o=n?n.previousSibling:e.lastChild;i.previousSibling=o,s.nextSibling=n,o?o.nextSibling=i:e.firstChild=i,n==null?e.lastChild=s:n.previousSibling=s;do i.parentNode=e;while(i!==s&&(i=i.nextSibling));return G(e.ownerDocument||e,e),t.nodeType==g&&(t.firstChild=t.lastChild=null),t}function et(e,t){var n=t.parentNode;if(n){var r=e.lastChild;n.removeChild(t);var r=e.lastChild}var r=e.lastChild;return t.parentNode=e,t.previousSibling=r,t.nextSibling=null,r?r.nextSibling=t:e.firstChild=t,e.lastChild=t,G(e.ownerDocument,e,t),t}function tt(){this._nsMap={}}function nt(){}function rt(){}function it(){}function st(){}function ot(){}function ut(){}function at(){}function ft(){}function lt(){}function ct(){}function ht(){}function pt(){}function dt(e,t){switch(e.nodeType){case u:var n=e.attributes,r=n.length,i=e.firstChild,o=e.tagName,h=s===e.namespaceURI;t.push("<",o);for(var y=0;y<r;y++)dt(n.item(y),t,h);if(i||h&&!/^(?:meta|link|img|br|hr|input|button)$/i.test(o)){t.push(">");if(h&&/^script$/i.test(o))i&&t.push(i.data);else while(i)dt(i,t),i=i.nextSibling;t.push("</",o,">")}else t.push("/>");return;case v:case g:var i=e.firstChild;while(i)dt(i,t),i=i.nextSibling;return;case a:return t.push(" ",e.name,'="',e.value.replace(/[<&"]/g,V),'"');case f:return t.push(e.data.replace(/[<&]/g,V));case l:return t.push("<![CDATA[",e.data,"]]>");case d:return t.push("<!--",e.data,"-->");case m:var b=e.publicId,w=e.systemId;t.push("<!DOCTYPE ",e.name);if(b)t.push(' PUBLIC "',b),w&&w!="."&&t.push('" "',w),t.push('">');else if(w&&w!=".")t.push(' SYSTEM "',w,'">');else{var E=e.internalSubset;E&&t.push(" [",E,"]"),t.push(">")}return;case p:return t.push("<?",e.target," ",e.data,"?>");case c:return t.push("&",e.nodeName,";");default:t.push("??",e.nodeName)}}function vt(e,t,n){var r;switch(t.nodeType){case u:r=t.cloneNode(!1),r.ownerDocument=e;case g:break;case a:n=!0}r||(r=t.cloneNode(!1)),r.ownerDocument=e,r.parentNode=null;if(n){var i=t.firstChild;while(i)r.appendChild(vt(e,i,n)),i=i.nextSibling}return r}function mt(e,t,n){var r=new t.constructor;for(var i in t){var s=t[i];typeof s!="object"&&s!=r[i]&&(r[i]=s)}t.childNodes&&(r.childNodes=new j),r.ownerDocument=e;switch(r.nodeType){case u:var o=t.attributes,f=r.attributes=new q,l=o.length;f._ownerElement=r;for(var c=0;c<l;c++)r.setAttributeNode(mt(e,o.item(c),!0));break;case a:n=!0}if(n){var h=t.firstChild;while(h)r.appendChild(mt(e,h,n)),h=h.nextSibling}return r}function gt(e,t,n){e[t]=n}var s="http://www.w3.org/1999/xhtml",o={},u=o.ELEMENT_NODE=1,a=o.ATTRIBUTE_NODE=2,f=o.TEXT_NODE=3,l=o.CDATA_SECTION_NODE=4,c=o.ENTITY_REFERENCE_NODE=5,h=o.ENTITY_NODE=6,p=o.PROCESSING_INSTRUCTION_NODE=7,d=o.COMMENT_NODE=8,v=o.DOCUMENT_NODE=9,m=o.DOCUMENT_TYPE_NODE=10,g=o.DOCUMENT_FRAGMENT_NODE=11,y=o.NOTATION_NODE=12,b={},w={},E=b.INDEX_SIZE_ERR=(w[1]="Index size error",1),S=b.DOMSTRING_SIZE_ERR=(w[2]="DOMString size error",2),x=b.HIERARCHY_REQUEST_ERR=(w[3]="Hierarchy request error",3),T=b.WRONG_DOCUMENT_ERR=(w[4]="Wrong document",4),N=b.INVALID_CHARACTER_ERR=(w[5]="Invalid character",5),C=b.NO_DATA_ALLOWED_ERR=(w[6]="No data allowed",6),k=b.NO_MODIFICATION_ALLOWED_ERR=(w[7]="No modification allowed",7),L=b.NOT_FOUND_ERR=(w[8]="Not found",8),A=b.NOT_SUPPORTED_ERR=(w[9]="Not supported",9),O=b.INUSE_ATTRIBUTE_ERR=(w[10]="Attribute in use",10),M=b.INVALID_STATE_ERR=(w[11]="Invalid state",11),_=b.SYNTAX_ERR=(w[12]="Syntax error",12),D=b.INVALID_MODIFICATION_ERR=(w[13]="Invalid modification",13),P=b.NAMESPACE_ERR=(w[14]="Invalid namespace",14),H=b.INVALID_ACCESS_ERR=(w[15]="Invalid access",15);B.prototype=Error.prototype,r(b,B),j.prototype={length:0,item:function(e){return this[e]||null}},F.prototype.item=function(e){return I(this),this[e]},i(F,j),q.prototype={length:0,item:j.prototype.item,getNamedItem:function(e){var t=this.length;while(t--){var n=this[t];if(n.nodeName==e)return n}},setNamedItem:function(e){var t=e.ownerElement;if(t&&t!=this._ownerElement)throw new B(O);var n=this.getNamedItem(e.nodeName);return U(this._ownerElement,this,e,n),n},setNamedItemNS:function(e){var t=e.ownerElement,n;if(t&&t!=this._ownerElement)throw new B(O);return n=this.getNamedItemNS(e.namespaceURI,e.localName),U(this._ownerElement,this,e,n),n},removeNamedItem:function(e){var t=this.getNamedItem(e);return z(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var n=this.getNamedItemNS(e,t);return z(this._ownerElement,this,n),n},getNamedItemNS:function(e,t){var n=this.length;while(n--){var r=this[n];if(r.localName==t&&r.namespaceURI==e)return r}return null}},W.prototype={hasFeature:function(e,t){var n=this._features[e.toLowerCase()];return n&&(!t||t in n)?!0:!1},createDocument:function(e,t,n){var r=new J;r.implementation=this,r.childNodes=new j,r.doctype=n,n&&r.appendChild(n);if(t){var i=r.createElementNS(e,t);r.appendChild(i)}return r},createDocumentType:function(e,t,n){var r=new ut;return r.name=e,r.nodeName=e,r.publicId=t,r.systemId=n,r}},X.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(e,t){return Z(this,e,t)},replaceChild:function(e,t){this.insertBefore(e,t),t&&this.removeChild(t)},removeChild:function(e){return Y(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return mt(this.ownerDocument||this,this,e)},normalize:function(){var e=this.firstChild;while(e){var t=e.nextSibling;t&&t.nodeType==f&&e.nodeType==f?(this.removeChild(t),e.appendData(t.data)):(e.normalize(),e=t)}},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){var t=this;while(t){var n=t._nsMap;if(n)for(var r in n)if(n[r]==e)return r;t=t.nodeType==2?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){var t=this;while(t){var n=t._nsMap;if(n&&e in n)return n[e];t=t.nodeType==2?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}},r(o,X),r(o,X.prototype),J.prototype={nodeName:"#document",nodeType:v,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==g){var n=e.firstChild;while(n){var r=n.nextSibling;this.insertBefore(n,t),n=r}return e}return this.documentElement==null&&e.nodeType==1&&(this.documentElement=e),Z(this,e,t),e.ownerDocument=this,e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),Y(this,e)},importNode:function(e,t){return vt(this,e,t)},getElementById:function(e){var t=null;return $(this.documentElement,function(n){if(n.nodeType==1&&n.getAttribute("id")==e)return t=n,!0}),t},createElement:function(e){var t=new tt;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.childNodes=new j;var n=t.attributes=new q;return n._ownerElement=t,t},createDocumentFragment:function(){var e=new ct;return e.ownerDocument=this,e.childNodes=new j,e},createTextNode:function(e){var t=new it;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new st;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){var t=new ot;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var n=new ht;return n.ownerDocument=this,n.tagName=n.target=e,n.nodeValue=n.data=t,n},createAttribute:function(e){var t=new nt;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){var t=new lt;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var n=new tt,r=t.split(":"),i=n.attributes=new q;return n.childNodes=new j,n.ownerDocument=this,n.nodeName=t,n.tagName=t,n.namespaceURI=e,r.length==2?(n.prefix=r[0],n.localName=r[1]):n.localName=t,i._ownerElement=n,n},createAttributeNS:function(e,t){var n=new nt,r=t.split(":");return n.ownerDocument=this,n.nodeName=t,n.name=t,n.namespaceURI=e,n.specified=!0,r.length==2?(n.prefix=r[0],n.localName=r[1]):n.localName=t,n}},i(J,X),tt.prototype={nodeType:u,hasAttribute:function(e){return this.getAttributeNode(e)!=null},getAttribute:function(e){var t=this.getAttributeNode(e);return t&&t.value||""},getAttributeNode:function(e){return this.attributes.getNamedItem(e)},setAttribute:function(e,t){var n=this.ownerDocument.createAttribute(e);n.value=n.nodeValue=""+t,this.setAttributeNode(n)},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},appendChild:function(e){return e.nodeType===g?this.insertBefore(e,null):et(this,e)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);n&&this.removeAttributeNode(n)},hasAttributeNS:function(e,t){return this.getAttributeNodeNS(e,t)!=null},getAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);return n&&n.value||""},setAttributeNS:function(e,t,n){var r=this.ownerDocument.createAttributeNS(e,t);r.value=r.nodeValue=""+n,this.setAttributeNode(r)},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByTagName:function(e){return new F(this,function(t){var n=[];return $(t,function(r){r!==t&&r.nodeType==u&&(e==="*"||r.tagName==e)&&n.push(r)}),n})},getElementsByTagNameNS:function(e,t){return new F(this,function(n){var r=[];return $(n,function(i){i!==n&&i.nodeType===u&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&r.push(i)}),r})}},J.prototype.getElementsByTagName=tt.prototype.getElementsByTagName,J.prototype.getElementsByTagNameNS=tt.prototype.getElementsByTagNameNS,i(tt,X),nt.prototype.nodeType=a,i(nt,X),rt.prototype={data:"",substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},appendChild:function(e){throw new Error(w[3])},deleteData:function(e,t){this.replaceData(e,t,"")},replaceData:function(e,t,n){var r=this.data.substring(0,e),i=this.data.substring(e+t);n=r+n+i,this.nodeValue=this.data=n,this.length=n.length}},i(rt,X),it.prototype={nodeName:"#text",nodeType:f,splitText:function(e){var t=this.data,n=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var r=this.ownerDocument.createTextNode(n);return this.parentNode&&this.parentNode.insertBefore(r,this.nextSibling),r}},i(it,rt),st.prototype={nodeName:"#comment",nodeType:d},i(st,rt),ot.prototype={nodeName:"#cdata-section",nodeType:l},i(ot,rt),ut.prototype.nodeType=m,i(ut,X),at.prototype.nodeType=y,i(at,X),ft.prototype.nodeType=h,i(ft,X),lt.prototype.nodeType=c,i(lt,X),ct.prototype.nodeName="#document-fragment",ct.prototype.nodeType=g,i(ct,X),ht.prototype.nodeType=p,i(ht,X),pt.prototype.serializeToString=function(e){var t=[];return dt(e,t),t.join("")},X.prototype.toString=function(){return pt.prototype.serializeToString(this)};try{if(Object.defineProperty){Object.defineProperty(F.prototype,"length",{get:function(){return I(this),this.$$length}}),Object.defineProperty(X.prototype,"textContent",{get:function(){return yt(this)},set:function(e){switch(this.nodeType){case 1:case 11:while(this.firstChild)this.removeChild(this.firstChild);(e||String(e))&&this.appendChild(this.ownerDocument.createTextNode(e));break;default:this.data=e,this.value=value,this.nodeValue=e}}});function yt(e){switch(e.nodeType){case 1:case 11:var t=[];e=e.firstChild;while(e)e.nodeType!==7&&e.nodeType!==8&&t.push(yt(e)),e=e.nextSibling;return t.join("");default:return e.nodeValue}}gt=function(e,t,n){e["$$"+t]=n}}}catch(bt){}return W}),define("ace/mode/xml/dom-parser",["require","exports","module","ace/mode/xml/sax","ace/mode/xml/dom"],function(e,t,n){"use strict";function s(e){this.options=e||{locator:{}}}function o(e,t,n){function s(t){var s=e[t];if(!s)if(i)s=e.length==2?function(n){e(t,n)}:e;else{var o=arguments.length;while(--o)if(s=e[arguments[o]])break}r[t]=s&&function(e){s(e+f(n),e,n)}||function(){}}if(!e){if(t instanceof u)return t;e=t}var r={},i=e instanceof Function;return n=n||{},s("warning","warn"),s("error","warn","warning"),s("fatalError","warn","warning","error"),r}function u(){this.cdata=!1}function a(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}function f(e){if(e)return"\n@"+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function l(e,t,n){return typeof e=="string"?e.substr(t,n):e.length>=t+n||t?new java.lang.String(e,t,n)+"":e}function c(e,t){e.currentElement?e.currentElement.appendChild(t):e.document.appendChild(t)}var r=e("./sax"),i=e("./dom");return s.prototype.parseFromString=function(e,t){var n=this.options,i=new r,s=n.domBuilder||new u,a=n.errorHandler,f=n.locator,l=n.xmlns||{},c={lt:"<",gt:">",amp:"&",quot:'"',apos:"'"};return f&&s.setDocumentLocator(f),i.errorHandler=o(a,s,f),i.domBuilder=n.domBuilder||s,/\/x?html?$/.test(t)&&(c.nbsp="\u00a0",c.copy="\u00a9",l[""]="http://www.w3.org/1999/xhtml"),e?i.parse(e,l,c):i.errorHandler.error("invalid document source"),s.document},u.prototype={startDocument:function(){this.document=(new i).createDocument(null,null,null),this.locator&&(this.document.documentURI=this.locator.systemId)},startElement:function(e,t,n,r){var i=this.document,s=i.createElementNS(e,n||t),o=r.length;c(this,s),this.currentElement=s,this.locator&&a(this.locator,s);for(var u=0;u<o;u++){var e=r.getURI(u),f=r.getValue(u),n=r.getQName(u),l=i.createAttributeNS(e,n);l.getOffset&&a(l.getOffset(1),l),l.value=l.nodeValue=f,s.setAttributeNode(l)}},endElement:function(e,t,n){var r=this.currentElement,i=r.tagName;this.currentElement=r.parentNode},startPrefixMapping:function(e,t){},endPrefixMapping:function(e){},processingInstruction:function(e,t){var n=this.document.createProcessingInstruction(e,t);this.locator&&a(this.locator,n),c(this,n)},ignorableWhitespace:function(e,t,n){},characters:function(e,t,n){e=l.apply(this,arguments);if(this.currentElement&&e){if(this.cdata){var r=this.document.createCDATASection(e);this.currentElement.appendChild(r)}else{var r=this.document.createTextNode(e);this.currentElement.appendChild(r)}this.locator&&a(this.locator,r)}},skippedEntity:function(e){},endDocument:function(){this.document.normalize()},setDocumentLocator:function(e){if(this.locator=e)e.lineNumber=0},comment:function(e,t,n){e=l.apply(this,arguments);var r=this.document.createComment(e);this.locator&&a(this.locator,r),c(this,r)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(e,t,n){var r=this.document.implementation;if(r&&r.createDocumentType){var i=r.createDocumentType(e,t,n);this.locator&&a(this.locator,i),c(this,i)}},warning:function(e){console.warn(e,f(this.locator))},error:function(e){console.error(e,f(this.locator))},fatalError:function(e){throw console.error(e,f(this.locator)),e}},"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(e){u.prototype[e]=function(){return null}}),{DOMParser:s}}),define("ace/mode/xml_worker",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/worker/mirror","ace/mode/xml/dom-parser"],function(e,t,n){"use strict";var r=e("../lib/oop"),i=e("../lib/lang"),s=e("../worker/mirror").Mirror,o=e("./xml/dom-parser").DOMParser,u=t.Worker=function(e){s.call(this,e),this.setTimeout(400),this.context=null};r.inherits(u,s),function(){this.setOptions=function(e){this.context=e.context},this.onUpdate=function(){var e=this.doc.getValue();if(!e)return;var t=new o,n=[];t.options.errorHandler={fatalError:function(e,t,r){n.push({row:r.lineNumber,column:r.columnNumber,text:t,type:"error"})},error:function(e,t,r){n.push({row:r.lineNumber,column:r.columnNumber,text:t,type:"error"})},warning:function(e,t,r){n.push({row:r.lineNumber,column:r.columnNumber,text:t,type:"warning"})}},t.parseFromString(e),this.sender.emit("error",n)}}.call(u.prototype)}),define("ace/lib/es5-shim",["require","exports","module"],function(e,t,n){function r(){}function w(e){try{return Object.defineProperty(e,"sentinel",{}),"sentinel"in e}catch(t){}}function H(e){return e=+e,e!==e?e=0:e!==0&&e!==1/0&&e!==-1/0&&(e=(e>0||-1)*Math.floor(Math.abs(e))),e}function B(e){var t=typeof e;return e===null||t==="undefined"||t==="boolean"||t==="number"||t==="string"}function j(e){var t,n,r;if(B(e))return e;n=e.valueOf;if(typeof n=="function"){t=n.call(e);if(B(t))return t}r=e.toString;if(typeof r=="function"){t=r.call(e);if(B(t))return t}throw new TypeError}Function.prototype.bind||(Function.prototype.bind=function(t){var n=this;if(typeof n!="function")throw new TypeError("Function.prototype.bind called on incompatible "+n);var i=u.call(arguments,1),s=function(){if(this instanceof s){var e=n.apply(this,i.concat(u.call(arguments)));return Object(e)===e?e:this}return n.apply(t,i.concat(u.call(arguments)))};return n.prototype&&(r.prototype=n.prototype,s.prototype=new r,r.prototype=null),s});var i=Function.prototype.call,s=Array.prototype,o=Object.prototype,u=s.slice,a=i.bind(o.toString),f=i.bind(o.hasOwnProperty),l,c,h,p,d;if(d=f(o,"__defineGetter__"))l=i.bind(o.__defineGetter__),c=i.bind(o.__defineSetter__),h=i.bind(o.__lookupGetter__),p=i.bind(o.__lookupSetter__);if([1,2].splice(0).length!=2)if(!function(){function e(e){var t=new Array(e+2);return t[0]=t[1]=0,t}var t=[],n;t.splice.apply(t,e(20)),t.splice.apply(t,e(26)),n=t.length,t.splice(5,0,"XXX"),n+1==t.length;if(n+1==t.length)return!0}())Array.prototype.splice=function(e,t){var n=this.length;e>0?e>n&&(e=n):e==void 0?e=0:e<0&&(e=Math.max(n+e,0)),e+t<n||(t=n-e);var r=this.slice(e,e+t),i=u.call(arguments,2),s=i.length;if(e===n)s&&this.push.apply(this,i);else{var o=Math.min(t,n-e),a=e+o,f=a+s-o,l=n-a,c=n-o;if(f<a)for(var h=0;h<l;++h)this[f+h]=this[a+h];else if(f>a)for(h=l;h--;)this[f+h]=this[a+h];if(s&&e===c)this.length=c,this.push.apply(this,i);else{this.length=c+s;for(h=0;h<s;++h)this[e+h]=i[h]}}return r};else{var v=Array.prototype.splice;Array.prototype.splice=function(e,t){return arguments.length?v.apply(this,[e===void 0?0:e,t===void 0?this.length-e:t].concat(u.call(arguments,2))):[]}}Array.isArray||(Array.isArray=function(t){return a(t)=="[object Array]"});var m=Object("a"),g=m[0]!="a"||!(0 in m);Array.prototype.forEach||(Array.prototype.forEach=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=arguments[1],s=-1,o=r.length>>>0;if(a(t)!="[object Function]")throw new TypeError;while(++s<o)s in r&&t.call(i,r[s],s,n)}),Array.prototype.map||(Array.prototype.map=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0,s=Array(i),o=arguments[1];if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");for(var u=0;u<i;u++)u in r&&(s[u]=t.call(o,r[u],u,n));return s}),Array.prototype.filter||(Array.prototype.filter=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0,s=[],o,u=arguments[1];if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");for(var f=0;f<i;f++)f in r&&(o=r[f],t.call(u,o,f,n)&&s.push(o));return s}),Array.prototype.every||(Array.prototype.every=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0,s=arguments[1];if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");for(var o=0;o<i;o++)if(o in r&&!t.call(s,r[o],o,n))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0,s=arguments[1];if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");for(var o=0;o<i;o++)if(o in r&&t.call(s,r[o],o,n))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0;if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");if(!i&&arguments.length==1)throw new TypeError("reduce of empty array with no initial value");var s=0,o;if(arguments.length>=2)o=arguments[1];else do{if(s in r){o=r[s++];break}if(++s>=i)throw new TypeError("reduce of empty array with no initial value")}while(!0);for(;s<i;s++)s in r&&(o=t.call(void 0,o,r[s],s,n));return o}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0;if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");if(!i&&arguments.length==1)throw new TypeError("reduceRight of empty array with no initial value");var s,o=i-1;if(arguments.length>=2)s=arguments[1];else do{if(o in r){s=r[o--];break}if(--o<0)throw new TypeError("reduceRight of empty array with no initial value")}while(!0);do o in this&&(s=t.call(void 0,s,r[o],o,n));while(o--);return s});if(!Array.prototype.indexOf||[0,1].indexOf(1,2)!=-1)Array.prototype.indexOf=function(t){var n=g&&a(this)=="[object String]"?this.split(""):F(this),r=n.length>>>0;if(!r)return-1;var i=0;arguments.length>1&&(i=H(arguments[1])),i=i>=0?i:Math.max(0,r+i);for(;i<r;i++)if(i in n&&n[i]===t)return i;return-1};if(!Array.prototype.lastIndexOf||[0,1].lastIndexOf(0,-3)!=-1)Array.prototype.lastIndexOf=function(t){var n=g&&a(this)=="[object String]"?this.split(""):F(this),r=n.length>>>0;if(!r)return-1;var i=r-1;arguments.length>1&&(i=Math.min(i,H(arguments[1]))),i=i>=0?i:r-Math.abs(i);for(;i>=0;i--)if(i in n&&t===n[i])return i;return-1};Object.getPrototypeOf||(Object.getPrototypeOf=function(t){return t.__proto__||(t.constructor?t.constructor.prototype:o)});if(!Object.getOwnPropertyDescriptor){var y="Object.getOwnPropertyDescriptor called on a non-object: ";Object.getOwnPropertyDescriptor=function(t,n){if(typeof t!="object"&&typeof t!="function"||t===null)throw new TypeError(y+t);if(!f(t,n))return;var r,i,s;r={enumerable:!0,configurable:!0};if(d){var u=t.__proto__;t.__proto__=o;var i=h(t,n),s=p(t,n);t.__proto__=u;if(i||s)return i&&(r.get=i),s&&(r.set=s),r}return r.value=t[n],r}}Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(t){return Object.keys(t)});if(!Object.create){var b;Object.prototype.__proto__===null?b=function(){return{__proto__:null}}:b=function(){var e={};for(var t in e)e[t]=null;return e.constructor=e.hasOwnProperty=e.propertyIsEnumerable=e.isPrototypeOf=e.toLocaleString=e.toString=e.valueOf=e.__proto__=null,e},Object.create=function(t,n){var r;if(t===null)r=b();else{if(typeof t!="object")throw new TypeError("typeof prototype["+typeof t+"] != 'object'");var i=function(){};i.prototype=t,r=new i,r.__proto__=t}return n!==void 0&&Object.defineProperties(r,n),r}}if(Object.defineProperty){var E=w({}),S=typeof document=="undefined"||w(document.createElement("div"));if(!E||!S)var x=Object.defineProperty}if(!Object.defineProperty||x){var T="Property description must be an object: ",N="Object.defineProperty called on non-object: ",C="getters & setters can not be defined on this javascript engine";Object.defineProperty=function(t,n,r){if(typeof t!="object"&&typeof t!="function"||t===null)throw new TypeError(N+t);if(typeof r!="object"&&typeof r!="function"||r===null)throw new TypeError(T+r);if(x)try{return x.call(Object,t,n,r)}catch(i){}if(f(r,"value"))if(d&&(h(t,n)||p(t,n))){var s=t.__proto__;t.__proto__=o,delete t[n],t[n]=r.value,t.__proto__=s}else t[n]=r.value;else{if(!d)throw new TypeError(C);f(r,"get")&&l(t,n,r.get),f(r,"set")&&c(t,n,r.set)}return t}}Object.defineProperties||(Object.defineProperties=function(t,n){for(var r in n)f(n,r)&&Object.defineProperty(t,r,n[r]);return t}),Object.seal||(Object.seal=function(t){return t}),Object.freeze||(Object.freeze=function(t){return t});try{Object.freeze(function(){})}catch(k){Object.freeze=function(t){return function(n){return typeof n=="function"?n:t(n)}}(Object.freeze)}Object.preventExtensions||(Object.preventExtensions=function(t){return t}),Object.isSealed||(Object.isSealed=function(t){return!1}),Object.isFrozen||(Object.isFrozen=function(t){return!1}),Object.isExtensible||(Object.isExtensible=function(t){if(Object(t)===t)throw new TypeError;var n="";while(f(t,n))n+="?";t[n]=!0;var r=f(t,n);return delete t[n],r});if(!Object.keys){var L=!0,A=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],O=A.length;for(var M in{toString:null})L=!1;Object.keys=function I(e){if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError("Object.keys called on a non-object");var I=[];for(var t in e)f(e,t)&&I.push(t);if(L)for(var n=0,r=O;n<r;n++){var i=A[n];f(e,i)&&I.push(i)}return I}}Date.now||(Date.now=function(){return(new Date).getTime()});var _=" \n \f\r \u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\ufeff";if(!String.prototype.trim||_.trim()){_="["+_+"]";var D=new RegExp("^"+_+_+"*"),P=new RegExp(_+_+"*$");String.prototype.trim=function(){return String(this).replace(D,"").replace(P,"")}}var F=function(e){if(e==null)throw new TypeError("can't convert "+e+" to object");return Object(e)}})
const path = require('path'); const webpack = require('webpack'); module.exports = function override(config, env) { config.resolve.alias = { ...config.resolve.alias, CodeMirror: path.join(__dirname, 'node_modules', 'codemirror'), jQuery: path.join(__dirname, 'node_modules', 'jquery'), $: path.join(__dirname, 'node_modules', 'jquery'), }; config.plugins.push( new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', CodeMirror: 'codemirror', }) ); return config; };
import React, { Component } from 'react'; import '../../semantic/dist/semantic.min.css'; import { Button, Card } from 'semantic-ui-react'; class YupikNounPossessor extends Component { render() { return ( <Card> <Card.Content> <Card.Header> It is owned by someone? </Card.Header> </Card.Content> <Card.Content> <Button as='h4' toggle onClick={this.props.setPossessiveButton.bind(this,1)} active={this.props.possessiveButton===1}>possessive</Button> </Card.Content> </Card> ); } } export default YupikNounPossessor;
import sanityClient from "@sanity/client"; export default sanityClient({ projectId: "dbi6o2or", dataset: "production", apiVersion: "2021-05-18", useCdn: false });
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * JDK-8024512: Regex /[^\[]/ doesn't match * * @test * @run */ print("[M]".match(/(\[[^\[]*\])/)); print("[[]".match(/(\[[^\[]*\])/)); print("[M]".match(/(\[[^\[^]*\])/)); print("[[]".match(/(\[[^\[^]*\])/)); print("[^]".match(/(\[[^\[^]*\])/)); print("[M]".match(/(\[[^\[]\])/)); print("[[]".match(/(\[[^\[]\])/)); print("[M]".match(/(\[[^\[^]\])/)); print("[[]".match(/(\[[^\[^]\])/)); print("[^]".match(/(\[[^\[^]\])/)); print("M".match(/[^\[]/)); print("[".match(/[^\[]/)); print("^".match(/[^\[]/)); // Repeat above without escaping inner square bracket print("[M]".match(/(\[[^[]\])/)); print("[[]".match(/(\[[^[]\])/)); print("[M]".match(/(\[[^[^]\])/)); print("[[]".match(/(\[[^[^]\])/)); print("[^]".match(/(\[[^[^]\])/)); print("M".match(/[^[]/)); print("[".match(/[^[]/)); print("^".match(/[^[]/));
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("devtools","sq",{title:"Të dhënat e elementit",dialogName:"Emri i dritares së dialogut",tabName:"Emri i fletës",elementId:"ID e elementit",elementType:"Lloji i elementit"});
module.exports = Object.freeze({ PATH_TO_LIBS_DIR: './e2e/config/apps/libs/', PATH_TO_KARMA_CONFIG: './e2e/config/karma.conf.js', PATH_TO_TEST_DIR: './e2e/tests/', PATH_TO_TEST_COLLECTION_DIR: './e2e/tests/temp-test-collection/', PATH_TO_APPS_DIR: './e2e/config/apps/', HTTP_SERVER_PORT: 4242, WARN_TIMES_TO_RUN: 100 });
import { auth, initialState } from './auth' import { SAVE_AUTH, DELETE_AUTH } from '../../config/constants'; describe('auth reducer', () => { it('SAVE_AUTH stores auth token', () => { const action = { type: SAVE_AUTH, token: 'ABC123' } const expectedState = { token: 'ABC123' } const newState = auth(initialState, action) expect(newState).toEqual(expectedState); }); it('DELETE_AUTH removes auth token', () => { const action = { type: DELETE_AUTH } const expectedState = { token: null } const newState = auth(initialState, action) expect(newState).toEqual(expectedState); }); });
function submitForm(){var e=$("#contactform"),t=document.getElementById("submsg"),n=document.getElementById("name").value,d=document.getElementById("email").value,a=document.getElementById("msg").value;""!=n||""!=d||""!=a?(e[0].submit(),e[0].reset(),t.textContent="Successfully submitted!",t.style.color="green",$(".fade_span").finish().fadeIn("fast").delay(3e3).fadeOut("slow")):(t.textContent="Please fill out at least one field.",t.style.color="red",$(".fade_span").finish().fadeIn("fast").delay(2e3).fadeOut("slow"))}window.onload=function(){var e=document.createElement("iframe");e.style.display="none",e.name="hidden_iframe",e.id="hidden_iframe",document.body.appendChild(e)};
describe("Core", function () { before(function () { fixture.setBase("test/fixtures"); }); beforeEach(function () { fixture.load('basic_elements.html'); }); afterEach(function () { fixture.cleanup(); }); describe("Jamon", function () { it("should exist", function () { expect(Jamon).to.not.be.undefined; }); it("should be a subclass of Array", function () { expect(Array.isArray(new Jamon())).to.be.true; }); }); describe("Jamon.get", function () { it("should work without arguments", function () { var result = Jamon.get(); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(0); }); it("should work with a selector string", function () { var selector = "div"; var qSResult = document.querySelector(selector); var result = Jamon.get(selector); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(1); expect(result[0]).to.equal(qSResult); }); it("should work with an unmatched selector string", function () { var selector = "unmatchedSelector"; var qSResult = document.querySelector(selector); var result = Jamon.get(selector); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(0); }); it("should work with the document element", function () { var result = Jamon.get(document); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(1); expect(result[0]).to.equal(document); }); it("should work with an element", function () { var el = document.getElementById("id1"); var result = Jamon.get(el); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(1); expect(result[0]).to.equal(el); }); it("should work with a text node", function () { var text = document.createTextNode("text"); var result = Jamon.get(text); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(1); expect(result[0]).to.equal(text); }); it("should work with a Jamón instance", function () { var el1 = document.getElementById("id1"); var el2 = document.getElementById("id2"); var original = Jamon.getAll([el1, el2]); var result = Jamon.get(original); expect(result).to.have.lengthOf(1); expect(result[0]).to.equal(original[0]); }); it("should work with an empty Jamón instance", function () { var original = new Jamon(); var result = Jamon.get(original); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(0); }); it("should work with a NodeList", function () { var nodeList = document.querySelectorAll("div"); var result = Jamon.get(nodeList); expect(nodeList.length).to.be.above(0); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(1); expect(result[0]).to.equal(nodeList[0]); }); it("should work with an empty NodeList", function () { var nodeList = document.querySelectorAll("#nonexistent"); var result = Jamon.get(nodeList); expect(nodeList.length).to.equal(0); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(0); }); it("should work with a HTMLCollection", function () { var htmlCollection = document.getElementsByTagName("div"); var result = Jamon.get(htmlCollection); expect(htmlCollection.length).to.be.above(0); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(1); expect(result[0]).to.equal(htmlCollection[0]); }); it("should work with an empty HTMLCollection", function () { var htmlCollection = document.getElementsByTagName("nonexistent"); var result = Jamon.get(htmlCollection); expect(htmlCollection.length).to.equal(0); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(0); }); it("should work with an Array", function () { var arr = [1,2]; var result = Jamon.get(arr); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(1); expect(result[0]).to.equal(arr[0]); }); it("should work with an empty Array", function () { var arr = []; var result = Jamon.get(arr); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(0); }); it("should work with window", function () { var result = Jamon.get(window); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(1); expect(result[0]).to.equal(window); }); it("should work with a documentFragment", function () { var fragment = document.createDocumentFragment(); var result = Jamon.get(fragment); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(1); expect(result[0]).to.equal(fragment); }); }); describe("Jamon.getAll", function () { it("should work without arguments", function () { var results = Jamon.getAll(); expect(results).to.be.an.instanceof(Jamon); expect(results).to.have.lengthOf(0); }); it("should work with a selector string", function () { var selector = "div"; var qSAResults = document.querySelectorAll(selector); var results = Jamon.getAll(selector); var length = results.length; var i = 0; expect(length).to.equal(qSAResults.length); for (; i < length; i++) { expect(results[i]).to.equal(qSAResults[i]); } }); it("should work with a NodeList", function () { var nodeList = document.querySelectorAll("div"); var results = Jamon.getAll(nodeList); var length = results.length; var i = 0; expect(results).to.be.an.instanceof(Jamon); expect(length).to.equal(nodeList.length); for (; i < length; i++) { expect(results[i]).to.equal(nodeList[i]); } }); it("should work with an empty NodeList", function () { var nodeList = document.querySelectorAll("#nonexistent"); var results = Jamon.getAll(nodeList); expect(nodeList.length).to.equal(0); expect(results).to.be.an.instanceof(Jamon); expect(results).to.have.lengthOf(0); }); it("should work with a HTMLCollection", function () { var htmlCollection = document.getElementsByTagName("div"); var results = Jamon.getAll(htmlCollection); var length = results.length; var i = 0; expect(results).to.be.an.instanceof(Jamon); expect(length).to.equal(htmlCollection.length); for (; i < length; i++) { expect(results[i]).to.equal(htmlCollection[i]); } }); it("should work with an empty HTMLCollection", function () { var htmlCollection = document.getElementsByTagName("nonexistent"); var results = Jamon.get(htmlCollection); expect(htmlCollection.length).to.equal(0); expect(results).to.be.an.instanceof(Jamon); expect(results).to.have.lengthOf(0); }); it("should work with an Array", function () { var arr = [1,2]; var results = Jamon.getAll(arr); var length = results.length; var i = 0; expect(results).to.be.an.instanceof(Jamon); expect(length).to.equal(arr.length); for (; i < length; i++) { expect(results[i]).to.equal(arr[i]); } }); it("should work with an empty Array", function () { var arr = []; var results = Jamon.getAll(arr); expect(results).to.be.an.instanceof(Jamon); expect(results).to.have.lengthOf(0); }); it("should work with a Jamón instance", function () { var original = Jamon.getAll(); var results = Jamon.getAll(original); expect(results).to.be.an.instanceof(Jamon); expect(results).to.equal(original); }); it("should work with an empty Jamón instance", function () { var original = new Jamon(); var results = Jamon.get(original); expect(results).to.be.an.instanceof(Jamon); expect(results).to.have.lengthOf(0); }); it("should work with window", function () { var result = Jamon.getAll(window); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(1); expect(result[0]).to.equal(window); }); it("should work with a documentFragment", function () { var fragment = document.createDocumentFragment(); var result = Jamon.getAll(fragment); expect(result).to.be.an.instanceof(Jamon); expect(result).to.have.lengthOf(1); expect(result[0]).to.equal(fragment); }); }); });
/* */ "format cjs"; (function(factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); } else { factory((typeof global !== 'undefined' ? global : this).moment); } }(function(moment) { return moment.defineLocale('ml', { months: 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split('_'), monthsShort: 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split('_'), weekdays: 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split('_'), weekdaysShort: 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split('_'), weekdaysMin: 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split('_'), longDateFormat: { LT: 'A h:mm -നു', LTS: 'A h:mm:ss -നു', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY, LT', LLLL: 'dddd, D MMMM YYYY, LT' }, calendar: { sameDay: '[ഇന്ന്] LT', nextDay: '[നാളെ] LT', nextWeek: 'dddd, LT', lastDay: '[ഇന്നലെ] LT', lastWeek: '[കഴിഞ്ഞ] dddd, LT', sameElse: 'L' }, relativeTime: { future: '%s കഴിഞ്ഞ്', past: '%s മുൻപ്', s: 'അൽപ നിമിഷങ്ങൾ', m: 'ഒരു മിനിറ്റ്', mm: '%d മിനിറ്റ്', h: 'ഒരു മണിക്കൂർ', hh: '%d മണിക്കൂർ', d: 'ഒരു ദിവസം', dd: '%d ദിവസം', M: 'ഒരു മാസം', MM: '%d മാസം', y: 'ഒരു വർഷം', yy: '%d വർഷം' }, meridiem: function(hour, minute, isLower) { if (hour < 4) { return 'രാത്രി'; } else if (hour < 12) { return 'രാവിലെ'; } else if (hour < 17) { return 'ഉച്ച കഴിഞ്ഞ്'; } else if (hour < 20) { return 'വൈകുന്നേരം'; } else { return 'രാത്രി'; } } }); }));
/** * ueditor完整配置项 * 可以在这里配置整个编辑器的特性 */ /**************************提示******************************** * 所有被注释的配置项均为UEditor默认值。 * 修改默认配置请首先确保已经完全明确该参数的真实用途。 * 主要有两种修改方案,一种是取消此处注释,然后修改成对应参数;另一种是在实例化编辑器时传入对应参数。 * 当升级编辑器时,可直接使用旧版配置文件替换新版配置文件,不用担心旧版配置文件中因缺少新功能所需的参数而导致脚本报错。 **************************提示********************************/ (function () { /** * 编辑器资源文件根路径。它所表示的含义是:以编辑器实例化页面为当前路径,指向编辑器资源文件(即dialog等文件夹)的路径。 * 鉴于很多同学在使用编辑器的时候出现的种种路径问题,此处强烈建议大家使用"相对于网站根目录的相对路径"进行配置。 * "相对于网站根目录的相对路径"也就是以斜杠开头的形如"/myProject/ueditor/"这样的路径。 * 如果站点中有多个不在同一层级的页面需要实例化编辑器,且引用了同一UEditor的时候,此处的URL可能不适用于每个页面的编辑器。 * 因此,UEditor提供了针对不同页面的编辑器可单独配置的根路径,具体来说,在需要实例化编辑器的页面最顶部写上如下代码即可。当然,需要令此处的URL等于对应的配置。 * window.UEDITOR_HOME_URL = "/xxxx/xxxx/"; */ var URL = window.UEDITOR_HOME_URL || getUEBasePath(); /** * 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。 */ window.UEDITOR_CONFIG = { //为编辑器实例添加一个路径,这个不能被注释 UEDITOR_HOME_URL: URL // 服务器统一请求接口路径 , serverUrl: URL + "php/controller.php" //工具栏上的所有的功能按钮和下拉框,可以在new编辑器的实例时选择自己需要的从新定义 , toolbars: [[ 'fullscreen', 'source', '|', 'undo', 'redo', '|', 'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|', 'directionalityltr', 'directionalityrtl', 'indent', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|', 'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|', 'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|', 'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|', 'print', 'preview', 'searchreplace', 'help', 'drafts' ]] //当鼠标放在工具栏上时显示的tooltip提示,留空支持自动多语言配置,否则以配置值为准 //,labelMap:{ // 'anchor':'', 'undo':'' //} //语言配置项,默认是zh-cn。有需要的话也可以使用如下这样的方式来自动多语言切换,当然,前提条件是lang文件夹下存在对应的语言文件: //lang值也可以通过自动获取 (navigator.language||navigator.browserLanguage ||navigator.userLanguage).toLowerCase() //,lang:"zh-cn" //,langPath:URL +"lang/" //主题配置项,默认是default。有需要的话也可以使用如下这样的方式来自动多主题切换,当然,前提条件是themes文件夹下存在对应的主题文件: //现有如下皮肤:default //,theme:'default' //,themePath:URL +"themes/" //,zIndex : 900 //编辑器层级的基数,默认是900 //针对getAllHtml方法,会在对应的head标签中增加该编码设置。 //,charset:"utf-8" //若实例化编辑器的页面手动修改的domain,此处需要设置为true //,customDomain:false //常用配置项目 //,isShow : true //默认显示编辑器 //,textarea:'editorValue' // 提交表单时,服务器获取编辑器提交内容的所用的参数,多实例时可以给容器name属性,会将name给定的值最为每个实例的键值,不用每次实例化的时候都设置这个值 //,initialContent:'欢迎使用ueditor!' //初始化编辑器的内容,也可以通过textarea/script给值,看官网例子 //,autoClearinitialContent:true //是否自动清除编辑器初始内容,注意:如果focus属性设置为true,这个也为真,那么编辑器一上来就会触发导致初始化的内容看不到了 //,focus:false //初始化时,是否让编辑器获得焦点true或false //如果自定义,最好给p标签如下的行高,要不输入中文时,会有跳动感 //,initialStyle:'p{line-height:1em}'//编辑器层级的基数,可以用来改变字体等 //,iframeCssUrl: URL + '/themes/iframe.css' //给编辑器内部引入一个css文件 //indentValue //首行缩进距离,默认是2em ,indentValue:'2em' //,initialFrameWidth:1000 //初始化编辑器宽度,默认1000 //,initialFrameHeight:320 //初始化编辑器高度,默认320 //,readonly : false //编辑器初始化结束后,编辑区域是否是只读的,默认是false //,autoClearEmptyNode : true //getContent时,是否删除空的inlineElement节点(包括嵌套的情况) //启用自动保存 //,enableAutoSave: true //自动保存间隔时间, 单位ms //,saveInterval: 500 //,fullscreen : false //是否开启初始化时即全屏,默认关闭 //,imagePopup:true //图片操作的浮层开关,默认打开 //,autoSyncData:true //自动同步编辑器要提交的数据 //,emotionLocalization:false //是否开启表情本地化,默认关闭。若要开启请确保emotion文件夹下包含官网提供的images表情文件夹 //粘贴只保留标签,去除标签所有属性 //,retainOnlyLabelPasted: false //,pasteplain:false //是否默认为纯文本粘贴。false为不使用纯文本粘贴,true为使用纯文本粘贴 //纯文本粘贴模式下的过滤规则 //'filterTxtRules' : function(){ // function transP(node){ // node.tagName = 'p'; // node.setStyle(); // } // return { // //直接删除及其字节点内容 // '-' : 'script style object iframe embed input select', // 'p': {$:{}}, // 'br':{$:{}}, // 'div':{'$':{}}, // 'li':{'$':{}}, // 'caption':transP, // 'th':transP, // 'tr':transP, // 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP, // 'td':function(node){ // //没有内容的td直接删掉 // var txt = !!node.innerText(); // if(txt){ // node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node); // } // node.parentNode.removeChild(node,node.innerText()) // } // } //}() //,allHtmlEnabled:false //提交到后台的数据是否包含整个html字符串 //insertorderedlist //有序列表的下拉配置,值留空时支持多语言自动识别,若配置值,则以此值为准 //,'insertorderedlist':{ // //自定的样式 // 'num':'1,2,3...', // 'num1':'1),2),3)...', // 'num2':'(1),(2),(3)...', // 'cn':'一,二,三....', // 'cn1':'一),二),三)....', // 'cn2':'(一),(二),(三)....', // //系统自带 // 'decimal' : '' , //'1,2,3...' // 'lower-alpha' : '' , // 'a,b,c...' // 'lower-roman' : '' , //'i,ii,iii...' // 'upper-alpha' : '' , lang //'A,B,C' // 'upper-roman' : '' //'I,II,III...' //} //insertunorderedlist //无序列表的下拉配置,值留空时支持多语言自动识别,若配置值,则以此值为准 //,insertunorderedlist : { //自定的样式 // 'dash' :'— 破折号', //-破折号 // 'dot':' 。 小圆圈', //系统自带 // 'circle' : '', // '○ 小圆圈' // 'disc' : '', // '● 小圆点' // 'square' : '' //'■ 小方块' //} //,listDefaultPaddingLeft : '30'//默认的左边缩进的基数倍 //,listiconpath : 'http://bs.baidu.com/listicon/'//自定义标号的路径 //,maxListLevel : 3 //限制可以tab的级数, 设置-1为不限制 //,autoTransWordToList:false //禁止word中粘贴进来的列表自动变成列表标签 //fontfamily //字体设置 label留空支持多语言自动切换,若配置,则以配置值为准 //,'fontfamily':[ // { label:'',name:'songti',val:'宋体,SimSun'}, // { label:'',name:'kaiti',val:'楷体,楷体_GB2312, SimKai'}, // { label:'',name:'yahei',val:'微软雅黑,Microsoft YaHei'}, // { label:'',name:'heiti',val:'黑体, SimHei'}, // { label:'',name:'lishu',val:'隶书, SimLi'}, // { label:'',name:'andaleMono',val:'andale mono'}, // { label:'',name:'arial',val:'arial, helvetica,sans-serif'}, // { label:'',name:'arialBlack',val:'arial black,avant garde'}, // { label:'',name:'comicSansMs',val:'comic sans ms'}, // { label:'',name:'impact',val:'impact,chicago'}, // { label:'',name:'timesNewRoman',val:'times new roman'} //] //fontsize //字号 //,'fontsize':[10, 11, 12, 14, 16, 18, 20, 24, 36] //paragraph //段落格式 值留空时支持多语言自动识别,若配置,则以配置值为准 //,'paragraph':{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''} //rowspacingtop //段间距 值和显示的名字相同 //,'rowspacingtop':['5', '10', '15', '20', '25'] //rowspacingBottom //段间距 值和显示的名字相同 //,'rowspacingbottom':['5', '10', '15', '20', '25'] //lineheight //行内间距 值和显示的名字相同 //,'lineheight':['1', '1.5','1.75','2', '3', '4', '5'] //customstyle //自定义样式,不支持国际化,此处配置值即可最后显示值 //block的元素是依据设置段落的逻辑设置的,inline的元素依据BIU的逻辑设置 //尽量使用一些常用的标签 //参数说明 //tag 使用的标签名字 //label 显示的名字也是用来标识不同类型的标识符,注意这个值每个要不同, //style 添加的样式 //每一个对象就是一个自定义的样式 //,'customstyle':[ // {tag:'h1', name:'tc', label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;'}, // {tag:'h1', name:'tl',label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;margin:0 0 10px 0;'}, // {tag:'span',name:'im', label:'', style:'font-style:italic;font-weight:bold'}, // {tag:'span',name:'hi', label:'', style:'font-style:italic;font-weight:bold;color:rgb(51, 153, 204)'} //] //打开右键菜单功能 //,enableContextMenu: true //右键菜单的内容,可以参考plugins/contextmenu.js里边的默认菜单的例子,label留空支持国际化,否则以此配置为准 //,contextMenu:[ // { // label:'', //显示的名称 // cmdName:'selectall',//执行的command命令,当点击这个右键菜单时 // //exec可选,有了exec就会在点击时执行这个function,优先级高于cmdName // exec:function () { // //this是当前编辑器的实例 // //this.ui._dialogs['inserttableDialog'].open(); // } // } //] //快捷菜单 //,shortcutMenu:["fontfamily", "fontsize", "bold", "italic", "underline", "forecolor", "backcolor", "insertorderedlist", "insertunorderedlist"] //elementPathEnabled //是否启用元素路径,默认是显示 //,elementPathEnabled : true //wordCount //,wordCount:true //是否开启字数统计 //,maximumWords:10000 //允许的最大字符数 //字数统计提示,{#count}代表当前字数,{#leave}代表还可以输入多少字符数,留空支持多语言自动切换,否则按此配置显示 //,wordCountMsg:'' //当前已输入 {#count} 个字符,您还可以输入{#leave} 个字符 //超出字数限制提示 留空支持多语言自动切换,否则按此配置显示 //,wordOverFlowMsg:'' //<span style="color:red;">你输入的字符个数已经超出最大允许值,服务器可能会拒绝保存!</span> //tab //点击tab键时移动的距离,tabSize倍数,tabNode什么字符做为单位 //,tabSize:4 //,tabNode:'&nbsp;' //removeFormat //清除格式时可以删除的标签和属性 //removeForamtTags标签 //,removeFormatTags:'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' //removeFormatAttributes属性 //,removeFormatAttributes:'class,style,lang,width,height,align,hspace,valign' //undo //可以最多回退的次数,默认20 //,maxUndoCount:20 //当输入的字符数超过该值时,保存一次现场 //,maxInputCount:1 //autoHeightEnabled // 是否自动长高,默认true //,autoHeightEnabled:true //scaleEnabled //是否可以拉伸长高,默认true(当开启时,自动长高失效) //,scaleEnabled:false //,minFrameWidth:800 //编辑器拖动时最小宽度,默认800 //,minFrameHeight:220 //编辑器拖动时最小高度,默认220 //autoFloatEnabled //是否保持toolbar的位置不动,默认true //,autoFloatEnabled:true //浮动时工具栏距离浏览器顶部的高度,用于某些具有固定头部的页面 //,topOffset:30 //编辑器底部距离工具栏高度(如果参数大于等于编辑器高度,则设置无效) //,toolbarTopOffset:400 //pageBreakTag //分页标识符,默认是_ueditor_page_break_tag_ //,pageBreakTag:'_ueditor_page_break_tag_' //autotypeset //自动排版参数 //,autotypeset: { // mergeEmptyline: true, //合并空行 // removeClass: true, //去掉冗余的class // removeEmptyline: false, //去掉空行 // textAlign:"left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版 // imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版 // pasteFilter: false, //根据规则过滤没事粘贴进来的内容 // clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号 // clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体 // removeEmptyNode: false, // 去掉空节点 // //可以去掉的标签 // removeTagNames: {标签名字:1}, // indent: false, // 行首缩进 // indentValue : '2em', //行首缩进的大小 // bdc2sb: false, // tobdc: false //} //tableDragable //表格是否可以拖拽 //,tableDragable: true //,disabledTableInTable:true //禁止表格嵌套 //sourceEditor //源码的查看方式,codemirror 是代码高亮,textarea是文本框,默认是codemirror //注意默认codemirror只能在ie8+和非ie中使用 //,sourceEditor:"codemirror" //如果sourceEditor是codemirror,还用配置一下两个参数 //codeMirrorJsUrl js加载的路径,默认是 URL + "third-party/codemirror/codemirror.js" //,codeMirrorJsUrl:URL + "third-party/codemirror/codemirror.js" //codeMirrorCssUrl css加载的路径,默认是 URL + "third-party/codemirror/codemirror.css" //,codeMirrorCssUrl:URL + "third-party/codemirror/codemirror.css" //编辑器初始化完成后是否进入源码模式,默认为否。 //,sourceEditorFirst:false //iframeUrlMap //dialog内容的路径 ~会被替换成URL,垓属性一旦打开,将覆盖所有的dialog的默认路径 //,iframeUrlMap:{ // 'anchor':'~/dialogs/anchor/anchor.html', //} //webAppKey 百度应用的APIkey,每个站长必须首先去百度官网注册一个key后方能正常使用app功能,注册介绍,http://app.baidu.com/static/cms/getapikey.html //, webAppKey: "" }; function getUEBasePath(docUrl, confUrl) { return getBasePath(docUrl || self.document.URL || self.location.href, confUrl || getConfigFilePath()); } function getConfigFilePath() { var configPath = document.getElementsByTagName('script'); return configPath[ configPath.length - 1 ].src; } function getBasePath(docUrl, confUrl) { var basePath = confUrl; if (/^(\/|\\\\)/.test(confUrl)) { basePath = /^.+?\w(\/|\\\\)/.exec(docUrl)[0] + confUrl.replace(/^(\/|\\\\)/, ''); } else if (!/^[a-z]+:/i.test(confUrl)) { docUrl = docUrl.split("#")[0].split("?")[0].replace(/[^\\\/]+$/, ''); basePath = docUrl + "" + confUrl; } return optimizationPath(basePath); } function optimizationPath(path) { var protocol = /^[a-z]+:\/\//.exec(path)[ 0 ], tmp = null, res = []; path = path.replace(protocol, "").split("?")[0].split("#")[0]; path = path.replace(/\\/g, '/').split(/\//); path[ path.length - 1 ] = ""; while (path.length) { if (( tmp = path.shift() ) === "..") { res.pop(); } else if (tmp !== ".") { res.push(tmp); } } return protocol + res.join("/"); } window.UE = { getUEBasePath: getUEBasePath }; })();
// Copyright 2012 Traceur Authors. // // 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 {ARGUMENTS} from '../syntax/PredefinedName'; import { BindingIdentifier, IdentifierExpression } from '../syntax/trees/ParseTrees'; import {IdentifierToken} from '../syntax/IdentifierToken'; import {IDENTIFIER_EXPRESSION} from '../syntax/trees/ParseTreeType'; import {ParseTreeVisitor} from '../syntax/ParseTreeVisitor'; import {TYPEOF} from '../syntax/TokenType'; /** * Represents the link in the scope chain. */ class Scope { /** * @param {Scope} parent The parent scope, or null if top level scope. */ constructor(parent) { this.parent = parent; this.references = Object.create(null); this.declarations = Object.create(null); } } /** * Gets the name of an identifier expression or token * @param {BindingIdentifier|IdentifierToken|string} name * @returns {string} */ export function getVariableName(name) { if (name instanceof IdentifierExpression) { name = name.identifierToken; } else if (name instanceof BindingIdentifier) { name = name.identifierToken; } if (name instanceof IdentifierToken) { name = name.value; } return name; } /** * Finds the identifiers that are not bound in a program. Run this after all * module imports have been resolved. * * This is run after all transformations to simplify the analysis. In * particular we can ignore: * - module imports * - block scope (let/const) * - classes * as all of these nodes will have been replaced. We assume that synthetic * variables (generated by Traceur) will bind correctly, so we don't worry * about binding them as well as user defined variables. */ export class FreeVariableChecker extends ParseTreeVisitor { /** * @param {ErrorReporter} reporter */ constructor(reporter) { super(); this.reporter_ = reporter; /** Current scope (block, program) */ this.scope_ = null; this.disableChecksLevel_ = 0; } /** * Pushes a scope. * @return {Scope} */ pushScope_() { return this.scope_ = new Scope(this.scope_); } /** * Pops scope, tracks proper matching of push_/pop_ operations. * @param {Scope} scope */ pop_(scope) { if (this.scope_ != scope) { throw new Error('FreeVariableChecker scope mismatch'); } this.validateScope_(); this.scope_ = scope.parent; } visitScript(tree, global) { var scope = this.pushScope_(); // Declare variables from the global scope. // TODO(jmesserly): this should be done through the module loaders, and by // providing the user the option to import URLs like '@dom', but for now // just bind against everything in the global scope. var object = global; while (object) { Object.getOwnPropertyNames(object).forEach(this.declareVariable_, this); object = Object.getPrototypeOf(object); } this.visitList(tree.scriptItemList); this.pop_(scope); } /** * Helper function for visitFunctionDeclaration, visitFunctionExpression and * visitArrowFunctionExpression. * @param {BindingIdentifier} name This is null for the arrow function. * @param {FormalParameterList} parameterList * @param {Block} body * @private */ visitFunction_(name, parameterList, body) { var scope = this.pushScope_(); this.visitAny(name); // Declare the function name, 'arguments' and formal parameters inside the // function this.declareVariable_(ARGUMENTS); this.visitAny(parameterList); this.visitAny(body); this.pop_(scope); } visitFunctionDeclaration(tree) { this.declareVariable_(tree.name); // Function declaration does not bind the name inside the function body. this.visitFunction_(null, tree.parameterList, tree.functionBody); } visitFunctionExpression(tree) { this.visitFunction_(tree.name, tree.parameterList, tree.functionBody); } visitArrowFunctionExpression(tree) { this.visitFunction_(null, tree.parameterList, tree.functionBody); } visitGetAccessor(tree) { var scope = this.pushScope_(); super.visitGetAccessor(tree); this.pop_(scope); } visitSetAccessor(tree) { var scope = this.pushScope_(); super.visitSetAccessor(tree); this.pop_(scope); } visitCatch(tree) { var scope = this.pushScope_(); super.visitCatch(tree); this.pop_(scope); } visitBindingIdentifier(tree) { this.declareVariable_(tree); } visitIdentifierExpression(tree) { if (this.disableChecksLevel_) return; var name = getVariableName(tree); var scope = this.scope_; if (!(name in scope.references)) { scope.references[name] = tree.location; } } visitUnaryExpression(tree) { // Allow typeof x to be a heuristic for allowing reading x later. if (tree.operator.type === TYPEOF && tree.operand.type === IDENTIFIER_EXPRESSION) { this.declareVariable_(tree.operand); } else { super.visitUnaryExpression(tree); } } visitWithStatement(tree) { this.visitAny(tree.expression); // Disable checks inside 'tree.body'. We don't do anything any more than // that because unbound identifiers inside 'with' might be members of // 'tree.expression'. There is no general way to deduce which is which at // compile time. However, we still need to record any declarations within // the block. this.disableChecksLevel_++; this.visitAny(tree.body); this.disableChecksLevel_--; } declareVariable_(tree) { var name = getVariableName(tree); if (name) { var scope = this.scope_; if (!(name in scope.declarations)) { scope.declarations[name] = tree.location; } } } /** * Once we've visited the body of a scope, we check that all variables were * declared. If they haven't been, we promote the references to the parent * scope (because ES can close over variables, as well as reference them * before declaration). * * At the top level scope we issue errors for any remaining free variables. */ validateScope_() { if (this.disableChecksLevel_) return; var scope = this.scope_; // Promote any unresolved references to the parent scope. var errors = []; for (var name in scope.references) { if (!(name in scope.declarations)) { var location = scope.references[name]; if (!scope.parent) { if (!location) { // If location is null, it means we're getting errors from code we // generated. This is an internal error. throw new Error(`generated variable ${name} is not defined`); } // If we're at the top level scope, then issue an error for // remaining free variables. errors.push([location.start, `${name} is not defined`]); } else if (!(name in scope.parent.references)) { scope.parent.references[name] = location; } } } if (errors.length) { // Issue errors in source order. errors.sort((x, y) => x[0].offset - y[0].offset); errors.forEach((args) => { this.reportError_(...args); }); } } reportError_(location, message) { this.reporter_.reportError(location, message); } /** * Checks the program for free variables, and reports an error when it * encounters any. * * @param {ErrorReporter} reporter * @param {Script} tree */ static checkScript(reporter, tree) { new FreeVariableChecker(reporter).visitScript(tree, Reflect.global); } }
import React, { useState } from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import RawQRCode from 'qrcode.react'; import { currency } from 'components/Common/Ticker.js'; import { CopyToClipboard } from 'react-copy-to-clipboard'; import { Event } from 'utils/GoogleAnalytics'; import { convertToEcashPrefix } from 'utils/cashMethods'; export const StyledRawQRCode = styled(RawQRCode)` cursor: pointer; border-radius: 10px; background: ${props => props.theme.qr.background}; margin-bottom: 10px; path:first-child { fill: ${props => props.theme.qr.background}; } :hover { border-color: ${({ xec = 0, ...props }) => xec === 1 ? props.theme.eCashBlue : props.theme.eCashPurple}; } @media (max-width: 768px) { border-radius: 18px; width: 170px; height: 170px; } `; const Copied = styled.div` font-size: 18px; font-weight: bold; width: 100%; text-align: center; background-color: ${({ xec = 0, ...props }) => xec === 1 ? props.theme.eCashBlue : props.theme.eCashPurple}; border: 1px solid; border-color: ${({ xec = 0, ...props }) => xec === 1 ? props.theme.eCashBlue : props.theme.eCashPurple}; color: ${props => props.theme.contrast}; position: absolute; top: 65px; padding: 30px 0; @media (max-width: 768px) { top: 52px; padding: 20px 0; } `; const PrefixLabel = styled.span` text-align: right; font-weight: bold; color: ${({ xec = 0, ...props }) => xec === 1 ? props.theme.eCashBlue : props.theme.eCashPurple}; @media (max-width: 768px) { font-size: 12px; } @media (max-width: 400px) { font-size: 10px; } -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; `; const AddressHighlightTrim = styled.span` font-weight: bold; color: ${props => props.theme.contrast}; @media (max-width: 768px) { font-size: 12px; } @media (max-width: 400px) { font-size: 10px; } -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; `; const CustomInput = styled.div` font-size: 14px; color: ${props => props.theme.lightWhite}; text-align: center; cursor: pointer; margin-bottom: 10px; padding: 6px 0; font-family: 'Roboto Mono', monospace; border-radius: 5px; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; input { border: none; width: 100%; text-align: center; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; cursor: pointer; color: ${props => props.theme.contrast}; padding: 10px 0; background: transparent; margin-bottom: 15px; display: none; } input:focus { outline: none; } input::selection { background: transparent; color: ${props => props.theme.contrast}; } @media (max-width: 768px) { font-size: 10px; input { font-size: 10px; margin-bottom: 10px; } } @media (max-width: 400px) { font-size: 7px; input { font-size: 10px; margin-bottom: 10px; } } `; export const QRCode = ({ address, isCashAddress, size = 210, onClick = () => null, }) => { address = address ? convertToEcashPrefix(address) : ''; const [visible, setVisible] = useState(false); const trimAmount = 8; const address_trim = address ? address.length - trimAmount : ''; const addressSplit = address ? address.split(':') : ['']; const addressPrefix = addressSplit[0]; const prefixLength = addressPrefix.length + 1; const txtRef = React.useRef(null); const handleOnClick = evt => { setVisible(true); setTimeout(() => { setVisible(false); }, 1500); onClick(evt); }; const handleOnCopy = () => { // Event.("Category", "Action", "Label") // xec or etoken? let eventLabel = currency.ticker; if (address && !isCashAddress) { eventLabel = currency.tokenTicker; // Event('Category', 'Action', 'Label') Event('Wallet', 'Copy Address', eventLabel); } setVisible(true); setTimeout(() => { txtRef.current.select(); }, 100); }; return ( <CopyToClipboard style={{ display: 'inline-block', width: '100%', position: 'relative', }} text={address} onCopy={handleOnCopy} > <div style={{ position: 'relative' }} onClick={handleOnClick}> <Copied xec={address && isCashAddress ? 1 : 0} style={{ display: visible ? null : 'none' }} > Copied <br /> <span style={{ fontSize: '12px' }}>{address}</span> </Copied> <StyledRawQRCode id="borderedQRCode" value={address || ''} size={size} xec={address && isCashAddress ? 1 : 0} renderAs={'svg'} includeMargin imageSettings={{ src: address && isCashAddress ? currency.logo : currency.tokenLogo, x: null, y: null, height: 24, width: 24, excavate: true, }} /> {address && ( <CustomInput className="notranslate"> <input ref={txtRef} readOnly value={address} spellCheck="false" type="text" /> <PrefixLabel xec={address && isCashAddress ? 1 : 0}> {address.slice(0, prefixLength)} </PrefixLabel> <AddressHighlightTrim> {address.slice( prefixLength, prefixLength + trimAmount, )} </AddressHighlightTrim> {address.slice(prefixLength + trimAmount, address_trim)} <AddressHighlightTrim> {address.slice(-trimAmount)} </AddressHighlightTrim> </CustomInput> )} </div> </CopyToClipboard> ); }; QRCode.propTypes = { address: PropTypes.string, isCashAddress: PropTypes.bool, size: PropTypes.number, onClick: PropTypes.func, };
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the LICENSE // file in the root directory of this source tree. // // RUN: echo continue | %hdb %s | %FileCheck --match-full-lines %s // REQUIRES: debugger print("continue") // CHECK-LABEL: continue function foo() { var x = 1; debugger; x = 2; return x; } print(foo()) // CHECK-NEXT: Break on 'debugger' statement in foo: {{.*}}:13:3 // CHECK-NEXT: Continuing execution // CHECK-NEXT: 2
import _typeof from "@babel/runtime/helpers/esm/typeof"; import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray"; import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import toArray from "rc-util/es/Children/toArray"; import warning from "rc-util/es/warning"; import { getPosition, isTreeNode } from '../util'; export function getKey(key, pos) { if (key !== null && key !== undefined) { return key; } return pos; } /** * Warning if TreeNode do not provides key */ export function warningWithoutKey() { var treeData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var keys = new Map(); function dig(list) { var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; (list || []).forEach(function (treeNode) { var key = treeNode.key, children = treeNode.children; warning(key !== null && key !== undefined, "Tree node must have a certain key: [".concat(path).concat(key, "]")); var recordKey = String(key); warning(!keys.has(recordKey) || key === null || key === undefined, "Same 'key' exist in the Tree: ".concat(recordKey)); keys.set(recordKey, true); dig(children, "".concat(path).concat(recordKey, " > ")); }); } dig(treeData); } /** * Convert `children` of Tree into `treeData` structure. */ export function convertTreeToData(rootNodes) { function dig(node) { var treeNodes = toArray(node); return treeNodes.map(function (treeNode) { // Filter invalidate node if (!isTreeNode(treeNode)) { warning(!treeNode, 'Tree/TreeNode can only accept TreeNode as children.'); return null; } var key = treeNode.key; var _treeNode$props = treeNode.props, children = _treeNode$props.children, rest = _objectWithoutProperties(_treeNode$props, ["children"]); var dataNode = _objectSpread({ key: key }, rest); var parsedChildren = dig(children); if (parsedChildren.length) { dataNode.children = parsedChildren; } return dataNode; }).filter(function (dataNode) { return dataNode; }); } return dig(rootNodes); } /** * Flat nest tree data into flatten list. This is used for virtual list render. * @param treeNodeList Origin data node list * @param expandedKeys * need expanded keys, provides `true` means all expanded (used in `rc-tree-select`). */ export function flattenTreeData() { var treeNodeList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var expandedKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var expandedKeySet = new Set(expandedKeys === true ? [] : expandedKeys); var flattenList = []; function dig(list) { var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; return list.map(function (treeNode, index) { var pos = getPosition(parent ? parent.pos : '0', index); var mergedKey = getKey(treeNode.key, pos); // Add FlattenDataNode into list var flattenNode = _objectSpread(_objectSpread({}, treeNode), {}, { parent: parent, pos: pos, children: null, data: treeNode, isStart: [].concat(_toConsumableArray(parent ? parent.isStart : []), [index === 0]), isEnd: [].concat(_toConsumableArray(parent ? parent.isEnd : []), [index === list.length - 1]) }); flattenList.push(flattenNode); // Loop treeNode children if (expandedKeys === true || expandedKeySet.has(mergedKey)) { flattenNode.children = dig(treeNode.children || [], flattenNode); } else { flattenNode.children = []; } return flattenNode; }); } dig(treeNodeList); return flattenList; } /** * Traverse all the data by `treeData`. * Please not use it out of the `rc-tree` since we may refactor this code. */ export function traverseDataNodes(dataNodes, callback, // To avoid too many params, let use config instead of origin param config) { // Init config var externalGetKey = null; var childrenPropName; var configType = _typeof(config); if (configType === 'function' || configType === 'string') { // Legacy getKey param externalGetKey = config; } else if (config && configType === 'object') { childrenPropName = config.childrenPropName; externalGetKey = config.externalGetKey; } childrenPropName = childrenPropName || 'children'; // Get keys var syntheticGetKey; if (externalGetKey) { if (typeof externalGetKey === 'string') { syntheticGetKey = function syntheticGetKey(node) { return node[externalGetKey]; }; } else if (typeof externalGetKey === 'function') { syntheticGetKey = function syntheticGetKey(node) { return externalGetKey(node); }; } } else { syntheticGetKey = function syntheticGetKey(node, pos) { return getKey(node.key, pos); }; } // Process function processNode(node, index, parent) { var children = node ? node[childrenPropName] : dataNodes; var pos = node ? getPosition(parent.pos, index) : '0'; // Process node if is not root if (node) { var key = syntheticGetKey(node, pos); var data = { node: node, index: index, pos: pos, key: key, parentPos: parent.node ? parent.pos : null, level: parent.level + 1 }; callback(data); } // Process children node if (children) { children.forEach(function (subNode, subIndex) { processNode(subNode, subIndex, { node: node, pos: pos, level: parent ? parent.level + 1 : -1 }); }); } } processNode(null); } /** * Convert `treeData` into entity records. */ export function convertDataToEntities(dataNodes) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, initWrapper = _ref.initWrapper, processEntity = _ref.processEntity, onProcessFinished = _ref.onProcessFinished, externalGetKey = _ref.externalGetKey, childrenPropName = _ref.childrenPropName; var /** @deprecated Use `config.externalGetKey` instead */ legacyExternalGetKey = arguments.length > 2 ? arguments[2] : undefined; // Init config var mergedExternalGetKey = externalGetKey || legacyExternalGetKey; var posEntities = {}; var keyEntities = {}; var wrapper = { posEntities: posEntities, keyEntities: keyEntities }; if (initWrapper) { wrapper = initWrapper(wrapper) || wrapper; } traverseDataNodes(dataNodes, function (item) { var node = item.node, index = item.index, pos = item.pos, key = item.key, parentPos = item.parentPos, level = item.level; var entity = { node: node, index: index, key: key, pos: pos, level: level }; var mergedKey = getKey(key, pos); posEntities[pos] = entity; keyEntities[mergedKey] = entity; // Fill children entity.parent = posEntities[parentPos]; if (entity.parent) { entity.parent.children = entity.parent.children || []; entity.parent.children.push(entity); } if (processEntity) { processEntity(entity, wrapper); } }, { externalGetKey: mergedExternalGetKey, childrenPropName: childrenPropName }); if (onProcessFinished) { onProcessFinished(wrapper); } return wrapper; } /** * Get TreeNode props with Tree props. */ export function getTreeNodeProps(key, _ref2) { var expandedKeys = _ref2.expandedKeys, selectedKeys = _ref2.selectedKeys, loadedKeys = _ref2.loadedKeys, loadingKeys = _ref2.loadingKeys, checkedKeys = _ref2.checkedKeys, halfCheckedKeys = _ref2.halfCheckedKeys, dragOverNodeKey = _ref2.dragOverNodeKey, dropPosition = _ref2.dropPosition, keyEntities = _ref2.keyEntities; var entity = keyEntities[key]; var treeNodeProps = { eventKey: key, expanded: expandedKeys.indexOf(key) !== -1, selected: selectedKeys.indexOf(key) !== -1, loaded: loadedKeys.indexOf(key) !== -1, loading: loadingKeys.indexOf(key) !== -1, checked: checkedKeys.indexOf(key) !== -1, halfChecked: halfCheckedKeys.indexOf(key) !== -1, pos: String(entity ? entity.pos : ''), // [Legacy] Drag props // Since the interaction of drag is changed, the semantic of the props are // not accuracy, I think it should be finally removed dragOver: dragOverNodeKey === key && dropPosition === 0, dragOverGapTop: dragOverNodeKey === key && dropPosition === -1, dragOverGapBottom: dragOverNodeKey === key && dropPosition === 1 }; return treeNodeProps; } export function convertNodePropsToEventData(props) { var data = props.data, expanded = props.expanded, selected = props.selected, checked = props.checked, loaded = props.loaded, loading = props.loading, halfChecked = props.halfChecked, dragOver = props.dragOver, dragOverGapTop = props.dragOverGapTop, dragOverGapBottom = props.dragOverGapBottom, pos = props.pos, active = props.active; var eventData = _objectSpread(_objectSpread({}, data), {}, { expanded: expanded, selected: selected, checked: checked, loaded: loaded, loading: loading, halfChecked: halfChecked, dragOver: dragOver, dragOverGapTop: dragOverGapTop, dragOverGapBottom: dragOverGapBottom, pos: pos, active: active }); if (!('props' in eventData)) { Object.defineProperty(eventData, 'props', { get: function get() { warning(false, 'Second param return from event is node data instead of TreeNode instance. Please read value directly instead of reading from `props`.'); return props; } }); } return eventData; }
import Message from './message'; import SSHHandle from './sshbus'; import ExecHandle from './execbus'; import Subscription from './subscription'; /** * Drop in replacement for webos-service, but using SSH shell to call luna-send-pub instead. */ export default class Service { /** * * @param {Service|null} service from webos-service module. Used for retreving SSH pubkey passphrase. If null is provided, alternative backend using root execution is used */ constructor(service) { if (service === null) { this.sendingHandle = new ExecHandle(); } else { this.sendingHandle = new SSHHandle(service); } } /* Call a service on the bus * The args parameter is a JSON-compatible object * The callback gets passed a Message object */ call(uri, args, callback) { if (typeof args !== 'object' || args === null) { throw new Error('args must be an object'); } const handle = this.sendingHandle; handle .call(uri, args) .then((body) => { callback(new Message(body, handle)); }) .catch((error) => { if (error.stack) { console.error(error.stack); } callback( new Message( Message.constructBody( JSON.stringify({ returnValue: false, errorCode: -1, errorText: String(error), }), ), handle, ), ); }); } /* Subscribe to a service on the bus * The args parameter is a JSON-compatible object * Returns a Subscription object which raises events when responses come in */ subscribe(uri, args) { if (typeof args !== 'object' || args === null) { throw new Error('args must be an object'); } return new Subscription(this.sendingHandle, uri, args); } }
import React from 'react'; const Textarea = () => { return ( <div className="flex-auto w-full mb-1 text-sm space-y-2"> <label className="font-semibold text-gray-600 py-2">Description</label> <textarea required="" name="message" id="" className="w-full min-h-[100px] max-h-[300px] h-28 appearance-none block w-full bg-grey-lighter text-grey-darker border border-grey-lighter rounded-lg py-4 px-4" placeholder="Enter your comapny info" spellCheck="false" ></textarea> <p className="text-sm text-gray-400 text-left my-3"> You inserted 0 characters </p> </div> ); }; export default Textarea;
/* CELSIUS EM FAHRENHEIT (VICE VERSA) * Crie uma função que receba uma string em celsius ou fahrenheit e faça a transformação de uma unidade para outra C = (F - 32) * 5/8 F = C * 9/5 + 32 */ function transformDegree(degree) { const celsiusExists = degree.toUpperCase().includes('C') const fahrenheitExists = degree.toUpperCase().includes('F') // fluxo de erro if (!celsiusExists && !fahrenheitExists) { throw new Error('Grau não identificado') } // fluxo ideal F -> C let updatedDegree = Number(degree.toUpperCase().replace("F", "")) let formula = fahrenheit => (fahrenheit - 32) * 5 / 9 let degreeSign = 'C' // fluxo alternativo C -> F if (celsiusExists) { updatedDegree = Number(degree.toUpperCase().replace("C", "")) formula = celsius => celsius * 9 / 5 + 32 degreeSign = 'F' } return formula(updatedDegree) + degreeSign } try { console.log(transformDegree('25C')) console.log(transformDegree('50F')) } catch (error) { console.log(error.message) }
layui.use('upload', function(){ var $ = layui.jquery, upload = layui.upload; var duotu = true; upload.render({ elem: '#test2', url: '/admin/upload/imgs', multiple: duotu, data: {'_csrf':'TlhROE5NRVB8HwdpFCIUfXsqKV0FAyoHHQkaaSEBHCAlNzUIOS4EPw=='}, done: function(res){ var imgName = $('.layui-imgs').attr('nametext') $('.layui-upload-lists').append('<span class="item_img" id="' + res.imgid + '"><span class="operate"><img class="cl" src="/statics/themes/admin/images/c.png" alt="" onclick=UPLOAD_IMG_DEL("' + res.imgid + '")></span><img src="/' + res.url + '" class="img" ><input type="hidden" name="'+imgName+'" value="' + res.url + '" /></span>'); } });//多长 upload.render({ elem: '#test1', url: '/admin/upload/imgs', data: {'_csrf':'TlhROE5NRVB8HwdpFCIUfXsqKV0FAyoHHQkaaSEBHCAlNzUIOS4EPw=='}, done: function(res){ var imgName = $('.layui-img').attr('nametext') $('.layui-upload-list').html('<span class="item_img" id="' + res.imgid + '"><span class="operate"><img class="cl" src="/statics/themes/admin/images/c.png" alt="" onclick=UPLOAD_IMG_DEL("' + res.imgid + '")></span><img src="/' + res.url + '" class="img" ><input type="hidden" name="'+imgName+'" value="' + res.url + '" /></span>') } });//单张 }); function UPLOAD_IMG_DEL(divs) { $("#"+divs).remove(); }
/******************************************************************************* * Licensed Materials - Property of IBM * © Copyright IBM Corporation 2017. All Rights Reserved. * * Note to U.S. Government Users Restricted Rights: * Use, duplication or disclosure restricted by GSA ADP Schedule * Contract with IBM Corp. *******************************************************************************/ 'use strict'; const _ = require('lodash'); const moment = require('moment'); const winston = require('winston'); /*eslint-disable */ const emailRegex = /(([^<>()[\]\\.,;:\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,}))/g; /*eslint-disable */ const logger = new winston.Logger({ transports: [ new winston.transports.Console({ timestamp: function() { return `${moment.utc().format('YYYY-MM-DDTHH:mm:ss.SSS')}Z`; }, formatter: function(options) { // Return string will be passed to logger. return `[${options.timestamp()}] [${options.level.toUpperCase()}] ${options.message}`; } }) ], filters: [ function maskEmails(level, msg) { return msg.replace(emailRegex, 'xxxxxxxx'); } ] }); function getMessage(argsObject) { const args = Array.prototype.slice.call(argsObject); args.splice(0, 2); args.forEach((arg, i) => { if (_.isObject(args[i])) { args[i] = JSON.stringify(args[i]); } }); return args.join(' '); } // FORMAT: s"[$time] [$category] [$id] [$name] $message" module.exports = { info: function(tid, name) { logger.info(`[${tid}]`, `[${name}]`, getMessage(arguments)); }, warn: function(tid, name) { logger.warn(`[${tid}]`, `[${name}]`, getMessage(arguments)); }, error: function(tid, name) { logger.error(`[${tid}]`, `[${name}]`, getMessage(arguments)); }, debug: function(tid, name) { logger.debug(`[${tid}]`, `[${name}]`, getMessage(arguments)); } };
var common = require("./editable-text-base-common"); var enums = require("ui/enums"); var EditableTextBase = (function (_super) { __extends(EditableTextBase, _super); function EditableTextBase(options) { _super.call(this, options); } EditableTextBase.prototype.dismissSoftInput = function () { this.ios.resignFirstResponder(); }; EditableTextBase.prototype._onKeyboardTypePropertyChanged = function (data) { var newKeyboardType; switch (data.newValue) { case enums.KeyboardType.datetime: newKeyboardType = UIKeyboardType.UIKeyboardTypeNumbersAndPunctuation; break; case enums.KeyboardType.phone: newKeyboardType = UIKeyboardType.UIKeyboardTypePhonePad; break; case enums.KeyboardType.number: newKeyboardType = UIKeyboardType.UIKeyboardTypeNumbersAndPunctuation; break; case enums.KeyboardType.url: newKeyboardType = UIKeyboardType.UIKeyboardTypeURL; break; case enums.KeyboardType.email: newKeyboardType = UIKeyboardType.UIKeyboardTypeEmailAddress; break; default: newKeyboardType = UIKeyboardType.UIKeyboardTypeDefault; break; } this.ios.keyboardType = newKeyboardType; }; EditableTextBase.prototype._onReturnKeyTypePropertyChanged = function (data) { var newValue; switch (data.newValue) { case enums.ReturnKeyType.done: newValue = UIReturnKeyType.UIReturnKeyDone; break; case enums.ReturnKeyType.go: newValue = UIReturnKeyType.UIReturnKeyGo; break; case enums.ReturnKeyType.next: newValue = UIReturnKeyType.UIReturnKeyNext; break; case enums.ReturnKeyType.search: newValue = UIReturnKeyType.UIReturnKeySearch; break; case enums.ReturnKeyType.send: newValue = UIReturnKeyType.UIReturnKeySend; break; default: newValue = UIReturnKeyType.UIReturnKeyDefault; break; } this.ios.returnKeyType = newValue; }; EditableTextBase.prototype._onAutocapitalizationTypePropertyChanged = function (data) { var newValue; switch (data.newValue) { case enums.AutocapitalizationType.none: newValue = UITextAutocapitalizationType.UITextAutocapitalizationTypeNone; break; case enums.AutocapitalizationType.words: newValue = UITextAutocapitalizationType.UITextAutocapitalizationTypeWords; break; case enums.AutocapitalizationType.sentences: newValue = UITextAutocapitalizationType.UITextAutocapitalizationTypeSentences; break; case enums.AutocapitalizationType.allCharacters: newValue = UITextAutocapitalizationType.UITextAutocapitalizationTypeAllCharacters; break; default: newValue = UITextAutocapitalizationType.UITextAutocapitalizationTypeSentences; break; } this.ios.autocapitalizationType = newValue; }; EditableTextBase.prototype._onAutocorrectPropertyChanged = function (data) { var newValue; switch (data.newValue) { case true: newValue = UITextAutocorrectionType.UITextAutocorrectionTypeYes; break; case false: newValue = UITextAutocorrectionType.UITextAutocorrectionTypeNo; break; default: newValue = UITextAutocorrectionType.UITextAutocorrectionTypeDefault; break; } this.ios.autocorrectionType = newValue; }; return EditableTextBase; }(common.EditableTextBase)); exports.EditableTextBase = EditableTextBase;
var ebml = require('../lib/ebml/index.js'), assert = require('assert'); describe('embl', function() { describe('Pipeline', function() { it('should output input buffer', function(done) { var decoder = new ebml.Decoder(); var encoder = new ebml.Encoder(); var buffer = new Buffer([0x1a, 0x45, 0xdf, 0xa3, 0x84, 0x42, 0x86, 0x81, 0x00]); encoder.on('data', function(chunk) { assert.equal(chunk.toString('hex'), buffer.toString('hex')); done(); }); decoder.pipe(encoder); decoder.write(buffer); }); it('should support end === -1', function (done) { var decoder = new ebml.Decoder(); var encoder = new ebml.Encoder(); encoder.write(['start', {name: 'Cluster', start: 0, end: -1}]); encoder.write(['end', {name: 'Cluster', start: 0, end: -1}]); encoder.pipe(decoder).on('data', function (data) { assert.equal(data[1].name, 'Cluster'); assert.equal(data[1].start, 0); assert.equal(data[1].end, -1); done(); }); }); }); });
// Copyright 2015 Joyent, Inc. module.exports = { read: read, readPkcs1: readPkcs1, write: write, writePkcs1: writePkcs1 }; var assert = require('assert-plus'); var asn1 = require('asn1'); var algs = require('../algs'); var utils = require('../utils'); var Key = require('../key'); var PrivateKey = require('../private-key'); var pem = require('./pem'); var pkcs8 = require('./pkcs8'); var readECDSACurve = pkcs8.readECDSACurve; function read(buf, options) { return (pem.read(buf, options, 'pkcs1')); } function write(key, options) { return (pem.write(key, options, 'pkcs1')); } /* Helper to read in a single mpint */ function readMPInt(der, nm) { assert.strictEqual(der.peek(), asn1.Ber.Integer, nm + ' is not an Integer'); return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); } function readPkcs1(alg, type, der) { switch (alg) { case 'RSA': if (type === 'public') return (readPkcs1RSAPublic(der)); else if (type === 'private') return (readPkcs1RSAPrivate(der)); throw (new Error('Unknown key type: ' + type)); case 'DSA': if (type === 'public') return (readPkcs1DSAPublic(der)); else if (type === 'private') return (readPkcs1DSAPrivate(der)); throw (new Error('Unknown key type: ' + type)); case 'EC': case 'ECDSA': if (type === 'private') return (readPkcs1ECDSAPrivate(der)); else if (type === 'public') return (readPkcs1ECDSAPublic(der)); throw (new Error('Unknown key type: ' + type)); default: throw (new Error('Unknown key algo: ' + alg)); } } function readPkcs1RSAPublic(der) { // modulus and exponent var n = readMPInt(der, 'modulus'); var e = readMPInt(der, 'exponent'); // now, make the key var key = { type: 'rsa', parts: [ { name: 'e', data: e }, { name: 'n', data: n } ] }; return (new Key(key)); } function readPkcs1RSAPrivate(der) { var version = readMPInt(der, 'version'); assert.strictEqual(version[0], 0); // modulus then public exponent var n = readMPInt(der, 'modulus'); var e = readMPInt(der, 'public exponent'); var d = readMPInt(der, 'private exponent'); var p = readMPInt(der, 'prime1'); var q = readMPInt(der, 'prime2'); var dmodp = readMPInt(der, 'exponent1'); var dmodq = readMPInt(der, 'exponent2'); var iqmp = readMPInt(der, 'iqmp'); // now, make the key var key = { type: 'rsa', parts: [ { name: 'n', data: n }, { name: 'e', data: e }, { name: 'd', data: d }, { name: 'iqmp', data: iqmp }, { name: 'p', data: p }, { name: 'q', data: q }, { name: 'dmodp', data: dmodp }, { name: 'dmodq', data: dmodq } ] }; return (new PrivateKey(key)); } function readPkcs1DSAPrivate(der) { var version = readMPInt(der, 'version'); assert.strictEqual(version.readUInt8(0), 0); var p = readMPInt(der, 'p'); var q = readMPInt(der, 'q'); var g = readMPInt(der, 'g'); var y = readMPInt(der, 'y'); var x = readMPInt(der, 'x'); // now, make the key var key = { type: 'dsa', parts: [ { name: 'p', data: p }, { name: 'q', data: q }, { name: 'g', data: g }, { name: 'y', data: y }, { name: 'x', data: x } ] }; return (new PrivateKey(key)); } function readPkcs1DSAPublic(der) { var y = readMPInt(der, 'y'); var p = readMPInt(der, 'p'); var q = readMPInt(der, 'q'); var g = readMPInt(der, 'g'); var key = { type: 'dsa', parts: [ { name: 'y', data: y }, { name: 'p', data: p }, { name: 'q', data: q }, { name: 'g', data: g } ] }; return (new Key(key)); } function readPkcs1ECDSAPublic(der) { der.readSequence(); var oid = der.readOID(); assert.strictEqual(oid, '1.2.840.10045.2.1', 'must be ecPublicKey'); var curveOid = der.readOID(); var curve; var curves = Object.keys(algs.curves); for (var j = 0; j < curves.length; ++j) { var c = curves[j]; var cd = algs.curves[c]; if (cd.pkcs8oid === curveOid) { curve = c; break; } } assert.string(curve, 'a known ECDSA named curve'); var Q = der.readString(asn1.Ber.BitString, true); Q = utils.ecNormalize(Q); var key = { type: 'ecdsa', parts: [ { name: 'curve', data: new Buffer(curve) }, { name: 'Q', data: Q } ] }; return (new Key(key)); } function readPkcs1ECDSAPrivate(der) { var version = readMPInt(der, 'version'); assert.strictEqual(version.readUInt8(0), 1); // private key var d = der.readString(asn1.Ber.OctetString, true); der.readSequence(0xa0); var curve = readECDSACurve(der); assert.string(curve, 'a known elliptic curve'); der.readSequence(0xa1); var Q = der.readString(asn1.Ber.BitString, true); Q = utils.ecNormalize(Q); var key = { type: 'ecdsa', parts: [ { name: 'curve', data: new Buffer(curve) }, { name: 'Q', data: Q }, { name: 'd', data: d } ] }; return (new PrivateKey(key)); } function writePkcs1(der, key) { der.startSequence(); switch (key.type) { case 'rsa': if (PrivateKey.isPrivateKey(key)) writePkcs1RSAPrivate(der, key); else writePkcs1RSAPublic(der, key); break; case 'dsa': if (PrivateKey.isPrivateKey(key)) writePkcs1DSAPrivate(der, key); else writePkcs1DSAPublic(der, key); break; case 'ecdsa': if (PrivateKey.isPrivateKey(key)) writePkcs1ECDSAPrivate(der, key); else writePkcs1ECDSAPublic(der, key); break; default: throw (new Error('Unknown key algo: ' + key.type)); } der.endSequence(); } function writePkcs1RSAPublic(der, key) { der.writeBuffer(key.part.n.data, asn1.Ber.Integer); der.writeBuffer(key.part.e.data, asn1.Ber.Integer); } function writePkcs1RSAPrivate(der, key) { var ver = new Buffer(1); ver[0] = 0; der.writeBuffer(ver, asn1.Ber.Integer); der.writeBuffer(key.part.n.data, asn1.Ber.Integer); der.writeBuffer(key.part.e.data, asn1.Ber.Integer); der.writeBuffer(key.part.d.data, asn1.Ber.Integer); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); if (!key.part.dmodp || !key.part.dmodq) utils.addRSAMissing(key); der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer); der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer); der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer); } function writePkcs1DSAPrivate(der, key) { var ver = new Buffer(1); ver[0] = 0; der.writeBuffer(ver, asn1.Ber.Integer); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); der.writeBuffer(key.part.g.data, asn1.Ber.Integer); der.writeBuffer(key.part.y.data, asn1.Ber.Integer); der.writeBuffer(key.part.x.data, asn1.Ber.Integer); } function writePkcs1DSAPublic(der, key) { der.writeBuffer(key.part.y.data, asn1.Ber.Integer); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); der.writeBuffer(key.part.g.data, asn1.Ber.Integer); } function writePkcs1ECDSAPublic(der, key) { der.startSequence(); der.writeOID('1.2.840.10045.2.1'); /* ecPublicKey */ var curve = key.part.curve.data.toString(); var curveOid = algs.curves[curve].pkcs8oid; assert.string(curveOid, 'a known ECDSA named curve'); der.writeOID(curveOid); der.endSequence(); var Q = utils.ecNormalize(key.part.Q.data, true); der.writeBuffer(Q, asn1.Ber.BitString); } function writePkcs1ECDSAPrivate(der, key) { var ver = new Buffer(1); ver[0] = 1; der.writeBuffer(ver, asn1.Ber.Integer); der.writeBuffer(key.part.d.data, asn1.Ber.OctetString); der.startSequence(0xa0); var curve = key.part.curve.data.toString(); var curveOid = algs.curves[curve].pkcs8oid; assert.string(curveOid, 'a known ECDSA named curve'); der.writeOID(curveOid); der.endSequence(); der.startSequence(0xa1); var Q = utils.ecNormalize(key.part.Q.data, true); der.writeBuffer(Q, asn1.Ber.BitString); der.endSequence(); }
5;
/** * Plugin.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.plugins.code.Plugin', [ 'tinymce.core.PluginManager', 'tinymce.plugins.code.api.Commands', 'tinymce.plugins.code.ui.Buttons' ], function (PluginManager, Commands, Buttons) { PluginManager.add('code', function (editor) { Commands.register(editor); Buttons.register(editor); return {}; }); return function () { }; } );
import React from "react" import PropTypes from "prop-types" import reduxFormField from "./../../../utils/reduxFormField" import { Select } from "antd" const Option = Select.Option const Select1 = props => { return ( <div style={{ marginBottom: "25px" }}> <p className="label">{props.label}</p> <Select showSearch value={props.value} showSearch={props.showSearch} mode={props.type} style={{ width: "100%" }} optionFilterProp="children" onChange={props.onChange} onFocus={props.onFocus} onBlur={props.handleBlur} filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 } > {props.option.map((optionData, index) => { return ( <Option key={index} value={optionData.value}> {optionData.name} </Option> ) })} </Select> </div> ) } Select1.propTypes = { name: PropTypes.string, value: PropTypes.node, label: PropTypes.string, onChange: PropTypes.func, option: PropTypes.array, helperText: PropTypes.string } Select1.defaultProps = { helperText: "" } export default reduxFormField(Select1)
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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. */ import { exec } from '../lib'; export const InstallDependenciesTask = { description: 'Installing node_modules, including production builds of packages', async run(config, log, build) { // We're using --no-bin-links to support systems that don't have symlinks. // This is commonly seen in shared folders on virtual machines const args = ['--production', '--ignore-optional', '--frozen-lockfile', '--no-bin-links', '--prefer-offline']; await exec(log, 'yarn', args, { cwd: build.resolvePath(), }); }, };
export { default as Button } from "./Button"; export { default as Container } from "./Container"; export { default as Icon } from "./Icon"; export { default as WombakLogo } from "./WombakLogo";
console.clear(); function updateInventory(arr1, arr2) { // All inventory must be accounted for or you're fired! /* Reversing done! console.log( reverser( reverser( arr1 ).sort() ) ); */ arr2.map( function(i){ let reminder = 0; arr1.map( function(j){ if( j[1] == i[1] ){ j[0] += i[0]; reminder += 1; } }); if( reminder == 0 ){ arr1.push( i ); } }); //console.log( reverser( reverser( arr1 ).sort() ) ); return reverser( reverser( arr1 ).sort() ); } /* Function that reverse all the elements which are also arrays, in an array*/ function reverser( arr ){ return arr.map( function(i){ return i.reverse(); }); } // Example inventory lists var curInv = [ [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"], [21, "Bowling Ball"] ]; var newInv = [ [2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"] ]; updateInventory( curInv, newInv ); console.time(); console.log('-------Start-------'); updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]).length; //should return an array with a length of 6. console.log('-------end-------'); console.log('-------Start-------'); updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]); //should return [[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]. console.log('-------end-------'); console.log('-------Start-------'); updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], []); //should return [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]; console.log('-------end-------'); console.log('-------Start-------'); updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]); //should return [[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]; console.log('-------end-------'); console.log('-------Start-------'); updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]]); //should return [[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]] console.log('-------end-------'); console.timeEnd();
'use strict' /* global describe, it, beforeEach */ const checkUsage = require('./helpers/utils').checkOutput const expect = require('chai').expect const english = require('../locales/en.json') let yargs = require('../') require('chai').should() describe('validation tests', () => { beforeEach(() => { yargs.reset() }) describe('implies', () => { const implicationsFailedPattern = new RegExp(english['Implications failed:']) it("fails if '_' populated, and implied argument not set", (done) => { yargs(['cat']) .implies({ 1: 'foo' // 1 arg in _ means --foo is required }) .fail((msg) => { msg.should.match(implicationsFailedPattern) return done() }) .parse() }) it("fails if key implies values in '_', but '_' is not populated", (done) => { yargs(['--foo']) .boolean('foo') .implies({ 'foo': 1 // --foo means 1 arg in _ is required }) .fail((msg) => { msg.should.match(implicationsFailedPattern) return done() }) .parse() }) it('fails if either implied argument is not set and displays only failed', (done) => { yargs(['-f', '-b']) .implies('f', ['b', 'c']) .fail((msg1) => { yargs(['-f', '-c']) .implies('f', ['b', 'c']) .fail((msg2) => { msg1.should.match(/f -> c/) msg1.should.not.match(/f -> b/) msg2.should.match(/f -> b/) msg2.should.not.match(/f -> c/) return done() }) .parse() }) .parse() }) it("fails if --no-foo's implied argument is not set", (done) => { yargs([]) .implies({ '--no-bar': 'foo' // when --bar is not given, --foo is required }) .fail((msg) => { msg.should.match(implicationsFailedPattern) return done() }) .parse() }) it('fails if a key is set, along with a key that it implies should not be set', (done) => { yargs(['--bar', '--foo']) .implies({ 'bar': '--no-foo' // --bar means --foo cannot be given }) .fail((msg) => { msg.should.match(implicationsFailedPattern) return done() }) .parse() }) it('fails if implied key (with "no" in the name) is not set', () => { let failCalled = false yargs('--bar') .implies({ 'bar': 'noFoo' // --bar means --noFoo (or --no-foo with boolean-negation disabled) is required // note that this has nothing to do with --foo }) .fail((msg) => { failCalled = true msg.should.match(implicationsFailedPattern) }) .parse() failCalled.should.equal(true) }) it('doesn\'t fail if implied key (with "no" in the name) is set', () => { let failCalled = false const argv = yargs('--bar --noFoo') .implies({ 'bar': 'noFoo' // --bar means --noFoo (or --no-foo with boolean-negation disabled) is required // note that this has nothing to do with --foo }) .fail((msg) => { failCalled = true }) .parse() failCalled.should.equal(false) expect(argv.bar).to.equal(true) expect(argv.noFoo).to.equal(true) expect(argv.foo).to.equal(undefined) }) it('fails if implied key (with "no" in the name) is given when it should not', () => { let failCalled = false yargs('--bar --noFoo') .implies({ 'bar': '--no-noFoo' // --bar means --noFoo (or --no-foo with boolean-negation disabled) cannot be given // note that this has nothing to do with --foo }) .fail((msg) => { failCalled = true msg.should.match(implicationsFailedPattern) }) .parse() failCalled.should.equal(true) }) it('doesn\'t fail if implied key (with "no" in the name) that should not be given is not set', () => { let failCalled = false const argv = yargs('--bar') .implies({ 'bar': '--no-noFoo' // --bar means --noFoo (or --no-foo with boolean-negation disabled) cannot be given // note that this has nothing to do with --foo }) .fail((msg) => { failCalled = true }) .parse() failCalled.should.equal(false) expect(argv.bar).to.equal(true) expect(argv.noFoo).to.equal(undefined) expect(argv.foo).to.equal(undefined) }) it('allows key to be specified with option shorthand', (done) => { yargs('--bar') .option('bar', { implies: 'foo' }) .fail((msg) => { msg.should.match(implicationsFailedPattern) return done() }) .parse() }) }) describe('conflicts', () => { it('fails if both arguments are supplied', (done) => { yargs(['-f', '-b']) .conflicts('f', 'b') .fail((msg) => { msg.should.equal('Arguments f and b are mutually exclusive') return done() }) .parse() }) it('fails if argument is supplied along with either conflicting argument', (done) => { yargs(['-f', '-b']) .conflicts('f', ['b', 'c']) .fail((msg1) => { yargs(['-f', '-c']) .conflicts('f', ['b', 'c']) .fail((msg2) => { msg1.should.equal('Arguments f and b are mutually exclusive') msg2.should.equal('Arguments f and c are mutually exclusive') return done() }) .parse() }) .parse() }) it('should not fail if no conflicting arguments are provided', () => { yargs(['-b', '-c']) .conflicts('f', ['b', 'c']) .fail((msg) => { expect.fail() }) .parse() }) it('should not fail if argument with conflict is provided, but not the argument it conflicts with', () => { yargs(['command', '-f', '-c']) .command('command') .option('f', { describe: 'a foo' }) .option('b', { describe: 'a bar' }) .conflicts('f', 'b') .fail((msg) => { expect.fail() }) .parse() }) it('should not fail if conflicting argument is provided, without argument with conflict', () => { yargs(['command', '-b', '-c']) .command('command') .option('f', { describe: 'a foo' }) .option('b', { describe: 'a bar' }) .conflicts('f', 'b') .fail((msg) => { expect.fail() }) .parse() }) it('allows an object to be provided defining conflicting option pairs', (done) => { yargs(['-t', '-s']) .conflicts({ 'c': 'a', 's': 't' }) .fail((msg) => { msg.should.equal('Arguments s and t are mutually exclusive') return done() }) .parse() }) it('takes into account aliases when applying conflicts logic', (done) => { yargs(['-t', '-c']) .conflicts({ 'c': 'a', 's': 't' }) .alias('c', 's') .fail((msg) => { msg.should.equal('Arguments s and t are mutually exclusive') return done() }) .parse() }) it('allows key to be specified with option shorthand', (done) => { yargs(['-f', '-b']) .option('f', { conflicts: 'b' }) .fail((msg) => { msg.should.equal('Arguments f and b are mutually exclusive') return done() }) .parse() }) it('should fail if alias of conflicting argument is provided', (done) => { yargs(['-f', '--batman=99']) .conflicts('f', 'b') .alias('b', 'batman') .fail((msg) => { msg.should.equal('Arguments f and b are mutually exclusive') return done() }) .parse() }) it('should fail if alias of argument with conflict is provided', (done) => { yargs(['--foo', '-b']) .conflicts('f', 'b') .alias('foo', 'f') .fail((msg) => { msg.should.equal('Arguments f and b are mutually exclusive') return done() }) .parse() }) function loadLocale (locale) { delete require.cache[require.resolve('../')] yargs = require('../') process.env.LC_ALL = locale } it('should use appropriate translation', done => { loadLocale('pirate') try { yargs(['-f', '-b']) .conflicts('f', 'b') .fail(msg => { msg.should.equal('Yon scurvy dogs f and b be as bad as rum and a prudish wench') return done() }) .parse() } finally { loadLocale('en_US.UTF-8') } }) }) describe('demand', () => { it('fails with standard error message if msg is not defined', (done) => { yargs([]) .demand(1) .fail((msg) => { msg.should.equal('Not enough non-option arguments: got 0, need at least 1') return done() }) .parse() }) it('fails in strict mode with invalid command', (done) => { yargs(['koala']) .command('wombat', 'wombat burrows') .command('kangaroo', 'kangaroo handlers') .demand(1) .strict() .fail((msg) => { msg.should.equal('Unknown argument: koala') return done() }) .parse() }) it('does not fail in strict mode when no commands configured', () => { const argv = yargs('koala') .demand(1) .strict() .fail((msg) => { expect.fail() }) .parse() argv._[0].should.equal('koala') }) // addresses: https://github.com/yargs/yargs/issues/791 it('should recognize context variables in strict mode', (done) => { yargs() .command('foo <y>') .strict() .parse('foo 99', { x: 33 }, (err, argv, output) => { expect(err).to.equal(null) expect(output).to.equal('') argv.y.should.equal(99) argv.x.should.equal(33) argv._.should.include('foo') return done() }) }) // addresses: https://github.com/yargs/yargs/issues/791 it('should recognize context variables in strict mode, when running sub-commands', (done) => { yargs() .command('request', 'request command', (yargs) => { yargs .command('get', 'sub-command') .option('y', { describe: 'y inner option' }) }) .strict() .parse('request get --y=22', { x: 33 }, (err, argv, output) => { expect(err).to.equal(null) expect(output).to.equal('') argv.y.should.equal(22) argv.x.should.equal(33) argv._.should.include('request') argv._.should.include('get') return done() }) }) it('fails when a required argument is missing', (done) => { yargs('-w 10 marsupial') .demand(1, ['w', 'b']) .fail((msg) => { msg.should.equal('Missing required argument: b') return done() }) .parse() }) it('fails when required arguments are present, but a command is missing', (done) => { yargs('-w 10 -m wombat') .demand(1, ['w', 'm']) .fail((msg) => { msg.should.equal('Not enough non-option arguments: got 0, need at least 1') return done() }) .parse() }) it('fails without a message if msg is null', (done) => { yargs([]) .demand(1, null) .fail((msg) => { expect(msg).to.equal(null) return done() }) .parse() }) // address regression in: https://github.com/yargs/yargs/pull/740 it('custom failure message should be printed for both min and max constraints', (done) => { yargs(['foo']) .demand(0, 0, 'hey! give me a custom exit message') .fail((msg) => { expect(msg).to.equal('hey! give me a custom exit message') return done() }) .parse() }) it('interprets min relative to command', () => { let failureMsg yargs('lint') .command('lint', 'Lint a file', (yargs) => { yargs.demand(1).fail((msg) => { failureMsg = msg }) }) .parse() expect(failureMsg).to.equal('Not enough non-option arguments: got 0, need at least 1') }) it('interprets max relative to command', () => { let failureMsg yargs('lint one.js two.js') .command('lint', 'Lint a file', (yargs) => { yargs.demand(0, 1).fail((msg) => { failureMsg = msg }) }) .parse() expect(failureMsg).to.equal('Too many non-option arguments: got 2, maximum of 1') }) }) describe('requiresArg', () => { it('fails when a required argument value of type number is missing', (done) => { yargs() .option('w', { type: 'number', requiresArg: true }) .parse('-w', (err, argv, output) => { expect(err).to.not.equal(undefined) expect(err).to.have.property('message', 'Not enough arguments following: w') return done() }) }) it('fails when a required argument value of type string is missing', (done) => { yargs() .option('w', { type: 'string', requiresArg: true }) .parse('-w', (err, argv, output) => { expect(err).to.not.equal(undefined) expect(err).to.have.property('message', 'Not enough arguments following: w') return done() }) }) it('fails when a required argument value of type boolean is missing', (done) => { yargs() .option('w', { type: 'boolean', requiresArg: true }) .parse('-w', (err, argv, output) => { expect(err).to.not.equal(undefined) expect(err).to.have.property('message', 'Not enough arguments following: w') return done() }) }) it('fails when a required argument value of type array is missing', (done) => { yargs() .option('w', { type: 'array', requiresArg: true }) .parse('-w', (err, argv, output) => { expect(err).to.not.equal(undefined) expect(err).to.have.property('message', 'Not enough arguments following: w') return done() }) }) // see: https://github.com/yargs/yargs/issues/1041 it('does not fail if argument with required value is not provided', (done) => { yargs() .option('w', { type: 'number', requiresArg: true }) .command('woo') .parse('', (err, argv, output) => { expect(err).to.equal(null) return done() }) }) it('does not fail if argument with required value is not provided to subcommand', (done) => { yargs() .option('w', { type: 'number', requiresArg: true }) .command('woo') .parse('woo', (err, argv, output) => { expect(err).to.equal(null) return done() }) }) }) describe('choices', () => { it('fails with one invalid value', (done) => { yargs(['--state', 'denial']) .choices('state', ['happy', 'sad', 'hungry']) .fail((msg) => { msg.split('\n').should.deep.equal([ 'Invalid values:', ' Argument: state, Given: "denial", Choices: "happy", "sad", "hungry"' ]) return done() }) .parse() }) it('fails with one valid and one invalid value', (done) => { yargs(['--characters', 'susie', '--characters', 'linus']) .choices('characters', ['calvin', 'hobbes', 'susie', 'moe']) .fail((msg) => { msg.split('\n').should.deep.equal([ 'Invalid values:', ' Argument: characters, Given: "linus", Choices: "calvin", "hobbes", "susie", "moe"' ]) return done() }) .parse() }) it('fails with multiple invalid values for same argument', (done) => { yargs(['--category', 'comedy', '--category', 'drama']) .choices('category', ['animal', 'vegetable', 'mineral']) .fail((msg) => { msg.split('\n').should.deep.equal([ 'Invalid values:', ' Argument: category, Given: "comedy", "drama", Choices: "animal", "vegetable", "mineral"' ]) return done() }) .parse() }) it('fails with case-insensitive value', (done) => { yargs(['--env', 'DEV']) .choices('env', ['dev', 'prd']) .fail((msg) => { msg.split('\n').should.deep.equal([ 'Invalid values:', ' Argument: env, Given: "DEV", Choices: "dev", "prd"' ]) return done() }) .parse() }) it('fails with multiple invalid arguments', (done) => { yargs(['--system', 'osx', '--arch', '64']) .choices('system', ['linux', 'mac', 'windows']) .choices('arch', ['x86', 'x64', 'arm']) .fail((msg) => { msg.split('\n').should.deep.equal([ 'Invalid values:', ' Argument: system, Given: "osx", Choices: "linux", "mac", "windows"', ' Argument: arch, Given: 64, Choices: "x86", "x64", "arm"' ]) return done() }) .parse() }) // addresses: https://github.com/yargs/yargs/issues/849 it('succeeds when demandOption is true and valid choice is provided', (done) => { yargs('one -a 10 marsupial') .command('one', 'level one', (yargs) => { yargs .options({ 'a': { demandOption: true, choices: [10, 20] } }) }, (argv) => { argv._[0].should.equal('one') argv.a.should.equal(10) return done() }) .fail((msg) => { expect.fail() }) .parse() }) // addresses: https://github.com/yargs/yargs/issues/849 it('fails when demandOption is true and choice is not provided', (done) => { yargs('one -a 10 marsupial') .command('one', 'level one', (yargs) => { yargs .options({ 'c': { choices: ['1', '2'] } }) .demandOption('c') }, (argv) => { expect.fail() }) .fail((msg) => { msg.should.equal('Missing required argument: c') return done() }) .parse() }) // addresses: https://github.com/yargs/yargs/issues/849 it('succeeds when demandOption is false and no choice is provided', () => { yargs('one') .command('one', 'level one', (yargs) => { yargs .options({ 'a': { demandOption: false, choices: [10, 20] } }) }, (argv) => { argv._[0].should.equal('one') }) .fail((msg) => { expect.fail() }) .parse() }) // addresses: https://github.com/yargs/yargs/issues/849 it('succeeds when demandOption is not provided and no choice is provided', () => { yargs('one') .command('one', 'level one', (yargs) => { yargs .options({ 'a': { choices: [10, 20] } }) }, (argv) => { argv._[0].should.equal('one') }) .fail((msg) => { expect.fail() }) .parse() }) }) describe('config', () => { it('should raise an appropriate error if JSON file is not found', (done) => { yargs(['--settings', 'fake.json', '--foo', 'bar']) .alias('z', 'zoom') .config('settings') .fail((msg) => { msg.should.eql('Invalid JSON config file: fake.json') return done() }) .parse() }) // see: https://github.com/yargs/yargs/issues/172 it('should not raise an exception if config file is set as default argument value', () => { let fail = false yargs([]) .option('config', { default: 'foo.json' }) .config('config') .fail(() => { fail = true }) .parse() fail.should.equal(false) }) it('should be displayed in the help message', () => { const r = checkUsage(() => yargs(['--help']) .config('settings') .help('help') .version(false) .wrap(null) .parse() ) r.should.have.property('logs').with.length(1) r.logs.join('\n').split(/\n+/).should.deep.equal([ 'Options:', ' --settings Path to JSON config file', ' --help Show help [boolean]' ]) }) it('should be displayed in the help message with its default name', () => { const checkUsage = require('./helpers/utils').checkOutput const r = checkUsage(() => yargs(['--help']) .config() .help('help') .version(false) .wrap(null) .parse() ) r.should.have.property('logs').with.length(1) r.logs.join('\n').split(/\n+/).should.deep.equal([ 'Options:', ' --config Path to JSON config file', ' --help Show help [boolean]' ]) }) it('should allow help message to be overridden', () => { const checkUsage = require('./helpers/utils').checkOutput const r = checkUsage(() => yargs(['--help']) .config('settings', 'pork chop sandwiches') .help('help') .version(false) .wrap(null) .parse() ) r.should.have.property('logs').with.length(1) r.logs.join('\n').split(/\n+/).should.deep.equal([ 'Options:', ' --settings pork chop sandwiches', ' --help Show help [boolean]' ]) }) it('outputs an error returned by the parsing function', () => { const checkUsage = require('./helpers/utils').checkOutput const r = checkUsage(() => yargs(['--settings=./package.json']) .config('settings', 'path to config file', configPath => Error('someone set us up the bomb')) .help('help') .wrap(null) .parse() ) r.errors.join('\n').split(/\n+/).should.deep.equal([ 'Options:', ' --version Show version number [boolean]', ' --settings path to config file', ' --help Show help [boolean]', 'someone set us up the bomb' ]) }) it('outputs an error if thrown by the parsing function', () => { const checkUsage = require('./helpers/utils').checkOutput const r = checkUsage(() => yargs(['--settings=./package.json']) .config('settings', 'path to config file', (configPath) => { throw Error('someone set us up the bomb') }) .wrap(null) .parse() ) r.errors.join('\n').split(/\n+/).should.deep.equal([ 'Options:', ' --help Show help [boolean]', ' --version Show version number [boolean]', ' --settings path to config file', 'someone set us up the bomb' ]) }) }) describe('defaults', () => { // See https://github.com/chevex/yargs/issues/31 it('should not fail when demanded options with defaults are missing', () => { yargs() .fail((msg) => { throw new Error(msg) }) .option('some-option', { describe: 'some option', demand: true, default: 88 }) .strict() .parse([]) }) }) describe('strict mode', () => { it('does not fail when command with subcommands called', () => { yargs('one') .command('one', 'level one', yargs => yargs .command('twoA', 'level two A') .command('twoB', 'level two B') .strict() .fail((msg) => { expect.fail() }), (argv) => { argv._[0].should.equal('one') }) .parse() }) it('does not fail for hidden options', () => { const args = yargs('--foo hey') .strict() .option('foo', { boolean: true, describe: false }) .fail((msg) => { expect.fail() }) .parse() args.foo.should.equal(true) }) it('does not fail if an alias is provided, rather than option itself', () => { const args = yargs('--cat hey') .strict() .option('foo', { boolean: true, describe: false }) .alias('foo', 'bar') .alias('bar', 'cat') .fail((msg) => { expect.fail() }) .parse() args.cat.should.equal(true) args.foo.should.equal(true) args.bar.should.equal(true) }) }) describe('demandOption', () => { it('allows an array of options to be demanded', (done) => { yargs('-a 10 marsupial') .demandOption(['a', 'b']) .fail((msg) => { msg.should.equal('Missing required argument: b') return done() }) .parse() }) it('allows demandOption in option shorthand', (done) => { yargs('-a 10 marsupial') .option('c', { demandOption: true }) .fail((msg) => { msg.should.equal('Missing required argument: c') return done() }) .parse() }) }) describe('demandCommand', () => { it('should return a custom failure message when too many non-hyphenated arguments are found after a demand count', () => { const r = checkUsage(() => yargs(['src', 'dest']) .usage('Usage: $0 [x] [y] [z] {OPTIONS} <src> <dest> [extra_files...]') .demandCommand(0, 1, 'src and dest files are both required', 'too many arguments are provided') .wrap(null) .help(false) .version(false) .parse() ) r.should.have.property('result') r.should.have.property('logs').with.length(0) r.should.have.property('exit').and.to.equal(true) r.result.should.have.property('_').and.deep.equal(['src', 'dest']) r.errors.join('\n').split(/\n+/).should.deep.equal([ 'Usage: usage [x] [y] [z] {OPTIONS} <src> <dest> [extra_files...]', 'too many arguments are provided' ]) }) // see: https://github.com/yargs/yargs/pull/438 it('allows a custom min message to be provided', (done) => { yargs('-a 10 marsupial') .demandCommand(2, 'totes got $0 totes expected $1') .fail((msg) => { msg.should.equal('totes got 1 totes expected 2') return done() }) .parse() }) // see: https://github.com/yargs/yargs/pull/438 it('allows a custom min and max message to be provided', (done) => { yargs('-a 10 marsupial mammal bro') .demandCommand(1, 2, 'totes too few, got $0 totes expected $1', 'totes too many, got $0 totes expected $1') .fail((msg) => { msg.should.equal('totes too many, got 3 totes expected 2') return done() }) .parse() }) it('defaults to demanding 1 command', (done) => { yargs('-a 10') .demandCommand() .fail((msg) => { msg.should.equal('Not enough non-option arguments: got 0, need at least 1') return done() }) .parse() }) }) })
const fs = require('fs'); module.exports = function() { this.addOccurrences = (stringTally, inputString) => { for(let i = 0; i < inputString.length; ++i) { if (stringTally[i] === undefined || stringTally[i] === null) { stringTally[i] = {}; } let positionTally = stringTally[i]; let inputChar = inputString[i]; if (positionTally[inputChar] !== undefined) { positionTally[inputChar]++; } else { positionTally[inputChar] = 1; } } return stringTally; }; this.sumOccurrences = (strings) => { return strings.reduce((count, string) => { return this.addOccurrences(count, string); }, []); }; this.getLeastCommonCharAt = (stringTally, index) => { let positionTally = stringTally[index]; let min = Number.MAX_VALUE; let foundChar = '_'; for(let char in positionTally) { if (positionTally[char] < min) { min = positionTally[char]; foundChar = char; } } return foundChar; }; this.getMostCommonCharAt = (charCount, index) => { let positionTally = charCount[index]; let max = 0; let foundChar = '_'; for(let char in positionTally) { if (positionTally[char] > max) { max = positionTally[char]; foundChar = char; } } return foundChar; }; this.getAverageString = (strings, least) => { let totalTally = this.sumOccurrences(strings); let commonChars = totalTally.map((count, index) => { if (least) { return this.getLeastCommonCharAt(totalTally, index); } else { return this.getMostCommonCharAt(totalTally, index); } }); return commonChars.join(""); }; this.run = () => { let input = fs.readFileSync('advents/input/6.txt', 'utf8'); let result = this.solve(input, false); console.log("6a: Most common: " + result) result = this.solve(input, true); console.log("6b: Least common: " + result) } this.solve = (input, least) => { let strings = input.split('\n'); return this.getAverageString(strings, least); } };
import { rollupTypescript } from "../../scripts/rollup"; export default rollupTypescript("node/index", { external: ["@vuepress/utils", "vuepress-plugin-sass-palette"], });
/*! kjua v0.6.0 - https://larsjung.de/kjua/ */ !function(t,r){"object"==typeof exports&&"object"==typeof module?module.exports=r():"function"==typeof define&&define.amd?define("kjua",[],r):"object"==typeof exports?exports.kjua=r():t.kjua=r()}("undefined"!=typeof self?self:this,function(){return function(e){var n={};function o(t){if(n[t])return n[t].exports;var r=n[t]={i:t,l:!1,exports:{}};return e[t].call(r.exports,r,r.exports,o),r.l=!0,r.exports}return o.m=e,o.c=n,o.d=function(t,r,e){o.o(t,r)||Object.defineProperty(t,r,{enumerable:!0,get:e})},o.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},o.t=function(r,t){if(1&t&&(r=o(r)),8&t)return r;if(4&t&&"object"==typeof r&&r&&r.__esModule)return r;var e=Object.create(null);if(o.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:r}),2&t&&"string"!=typeof r)for(var n in r)o.d(e,n,function(t){return r[t]}.bind(null,n));return e},o.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return o.d(r,"a",r),r},o.o=function(t,r){return Object.prototype.hasOwnProperty.call(t,r)},o.p="",o(o.s=0)}([function(t,r,e){var n=e(1),a=n.create_canvas,u=n.canvas_to_img,f=n.dpr,c=e(3),l=e(4),s=e(6);t.exports=function(t){var r=Object.assign({},c,t),e=l(r.text,r.ecLevel,r.minVersion,r.quiet),n=r.ratio||f,o=a(r.size,n),i=o.getContext("2d");return i.scale(n,n),s(e,i,r),"image"===r.render?u(o):o}},function(u,t,r){(function(t){function n(t){return i.createElement(t)}function e(t,r){return t.getAttribute(r)}function o(t,r,e){return t.setAttribute(r,e)}var r=t.window,i=r.document,a=r.devicePixelRatio||1;u.exports={create_canvas:function(t,r){var e=n("canvas");return o(e,"width",t*r),o(e,"height",t*r),e.style.width="".concat(t,"px"),e.style.height="".concat(t,"px"),e},canvas_to_img:function(t){var r=n("img");return o(r,"crossorigin","anonymous"),o(r,"src",t.toDataURL("image/png")),o(r,"width",e(t,"width")),o(r,"height",e(t,"height")),r.style.width=t.style.width,r.style.height=t.style.height,r},dpr:a}}).call(this,r(2))},function(t,r){var e;e=function(){return this}();try{e=e||new Function("return this")()}catch(t){"object"==typeof window&&(e=window)}t.exports=e},function(t,r){t.exports={render:"image",crisp:!0,minVersion:1,ecLevel:"L",size:200,ratio:null,fill:"#333",back:"#fff",text:"no text",rounded:0,quiet:0,mode:"plain",mSize:30,mPosX:50,mPosY:50,label:"no label",fontname:"sans",fontcolor:"#333",image:null}},function(t,r,e){function a(t){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var u=/code length overflow/i,f=e(5);f.stringToBytes=f.stringToBytesFuncs["UTF-8"];t.exports=function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"",r=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"L",e=2<arguments.length&&void 0!==arguments[2]?arguments[2]:1,n=3<arguments.length&&void 0!==arguments[3]?arguments[3]:0,o=function(t,r){for(var e=2<arguments.length&&void 0!==arguments[2]?arguments[2]:1,o=e=Math.max(1,e);o<=40;o+=1)try{var n=function(){var e=f(o,r);e.addData(t),e.make();var n=e.getModuleCount();return{v:{text:t,level:r,version:o,moduleCount:n,isDark:function(t,r){return 0<=t&&t<n&&0<=r&&r<n&&e.isDark(t,r)}}}}();if("object"===a(n))return n.v}catch(t){if(!(o<40&&u.test(t)))throw new Error(t)}return null}(t,r,e);if(o){var i=o.isDark;o.moduleCount+=2*n,o.isDark=function(t,r){return i(t-n,r-n)}}return o}},function(t,r,e){var n,o,i,a=function(){function i(t,r){function a(t,r){l=function(t){for(var r=new Array(t),e=0;e<t;e+=1){r[e]=new Array(t);for(var n=0;n<t;n+=1)r[e][n]=null}return r}(s=4*u+17),e(0,0),e(s-7,0),e(0,s-7),i(),o(),v(t,r),7<=u&&g(t),null==n&&(n=p(u,f,c)),d(n,r)}var u=t,f=y[r],l=null,s=0,n=null,c=[],h={},e=function(t,r){for(var e=-1;e<=7;e+=1)if(!(t+e<=-1||s<=t+e))for(var n=-1;n<=7;n+=1)r+n<=-1||s<=r+n||(l[t+e][r+n]=0<=e&&e<=6&&(0==n||6==n)||0<=n&&n<=6&&(0==e||6==e)||2<=e&&e<=4&&2<=n&&n<=4)},o=function(){for(var t=8;t<s-8;t+=1)null==l[t][6]&&(l[t][6]=t%2==0);for(var r=8;r<s-8;r+=1)null==l[6][r]&&(l[6][r]=r%2==0)},i=function(){for(var t=w.getPatternPosition(u),r=0;r<t.length;r+=1)for(var e=0;e<t.length;e+=1){var n=t[r],o=t[e];if(null==l[n][o])for(var i=-2;i<=2;i+=1)for(var a=-2;a<=2;a+=1)l[n+i][o+a]=-2==i||2==i||-2==a||2==a||0==i&&0==a}},g=function(t){for(var r=w.getBCHTypeNumber(u),e=0;e<18;e+=1){var n=!t&&1==(r>>e&1);l[Math.floor(e/3)][e%3+s-8-3]=n}for(e=0;e<18;e+=1){n=!t&&1==(r>>e&1);l[e%3+s-8-3][Math.floor(e/3)]=n}},v=function(t,r){for(var e=f<<3|r,n=w.getBCHTypeInfo(e),o=0;o<15;o+=1){var i=!t&&1==(n>>o&1);o<6?l[o][8]=i:o<8?l[o+1][8]=i:l[s-15+o][8]=i}for(o=0;o<15;o+=1){i=!t&&1==(n>>o&1);o<8?l[8][s-o-1]=i:o<9?l[8][15-o-1+1]=i:l[8][15-o-1]=i}l[s-8][8]=!t},d=function(t,r){for(var e=-1,n=s-1,o=7,i=0,a=w.getMaskFunction(r),u=s-1;0<u;u-=2)for(6==u&&(u-=1);;){for(var f=0;f<2;f+=1)if(null==l[n][u-f]){var c=!1;i<t.length&&(c=1==(t[i]>>>o&1)),a(n,u-f)&&(c=!c),l[n][u-f]=c,-1==(o-=1)&&(i+=1,o=7)}if((n+=e)<0||s<=n){n-=e,e=-e;break}}},p=function(t,r,e){for(var n=B.getRSBlocks(t,r),o=C(),i=0;i<e.length;i+=1){var a=e[i];o.put(a.getMode(),4),o.put(a.getLength(),w.getLengthInBits(a.getMode(),t)),a.write(o)}var u=0;for(i=0;i<n.length;i+=1)u+=n[i].dataCount;if(o.getLengthInBits()>8*u)throw"code length overflow. ("+o.getLengthInBits()+">"+8*u+")";for(o.getLengthInBits()+4<=8*u&&o.put(0,4);o.getLengthInBits()%8!=0;)o.putBit(!1);for(;!(o.getLengthInBits()>=8*u||(o.put(236,8),o.getLengthInBits()>=8*u));)o.put(17,8);return function(t,r){for(var e=0,n=0,o=0,i=new Array(r.length),a=new Array(r.length),u=0;u<r.length;u+=1){var f=r[u].dataCount,c=r[u].totalCount-f;n=Math.max(n,f),o=Math.max(o,c),i[u]=new Array(f);for(var l=0;l<i[u].length;l+=1)i[u][l]=255&t.getBuffer()[l+e];e+=f;var s=w.getErrorCorrectPolynomial(c),g=m(i[u],s.getLength()-1).mod(s);for(a[u]=new Array(s.getLength()-1),l=0;l<a[u].length;l+=1){var h=l+g.getLength()-a[u].length;a[u][l]=0<=h?g.getAt(h):0}}var v=0;for(l=0;l<r.length;l+=1)v+=r[l].totalCount;var d=new Array(v),p=0;for(l=0;l<n;l+=1)for(u=0;u<r.length;u+=1)l<i[u].length&&(d[p]=i[u][l],p+=1);for(l=0;l<o;l+=1)for(u=0;u<r.length;u+=1)l<a[u].length&&(d[p]=a[u][l],p+=1);return d}(o,n)};return h.addData=function(t,r){var e=null;switch(r=r||"Byte"){case"Numeric":e=x(t);break;case"Alphanumeric":e=A(t);break;case"Byte":e=M(t);break;case"Kanji":e=S(t);break;default:throw"mode:"+r}c.push(e),n=null},h.isDark=function(t,r){if(t<0||s<=t||r<0||s<=r)throw t+","+r;return l[t][r]},h.getModuleCount=function(){return s},h.make=function(){if(u<1){for(var t=1;t<40;t++){for(var r=B.getRSBlocks(t,f),e=C(),n=0;n<c.length;n++){var o=c[n];e.put(o.getMode(),4),e.put(o.getLength(),w.getLengthInBits(o.getMode(),t)),o.write(e)}var i=0;for(n=0;n<r.length;n++)i+=r[n].dataCount;if(e.getLengthInBits()<=8*i)break}u=t}a(!1,function(){for(var t=0,r=0,e=0;e<8;e+=1){a(!0,e);var n=w.getLostPoint(h);(0==e||n<t)&&(t=n,r=e)}return r}())},h.createTableTag=function(t,r){t=t||2;var e="";e+='<table style="',e+=" border-width: 0px; border-style: none;",e+=" border-collapse: collapse;",e+=" padding: 0px; margin: "+(r=void 0===r?4*t:r)+"px;",e+='">',e+="<tbody>";for(var n=0;n<h.getModuleCount();n+=1){e+="<tr>";for(var o=0;o<h.getModuleCount();o+=1)e+='<td style="',e+=" border-width: 0px; border-style: none;",e+=" border-collapse: collapse;",e+=" padding: 0px; margin: 0px;",e+=" width: "+t+"px;",e+=" height: "+t+"px;",e+=" background-color: ",e+=h.isDark(n,o)?"#000000":"#ffffff",e+=";",e+='"/>';e+="</tr>"}return e+="</tbody>",e+="</table>"},h.createSvgTag=function(t,r){var e={};"object"==typeof t&&(t=(e=t).cellSize,r=e.margin),t=t||2,r=void 0===r?4*t:r;var n,o,i,a,u=h.getModuleCount()*t+2*r,f="";for(a="l"+t+",0 0,"+t+" -"+t+",0 0,-"+t+"z ",f+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',f+=e.scalable?"":' width="'+u+'px" height="'+u+'px"',f+=' viewBox="0 0 '+u+" "+u+'" ',f+=' preserveAspectRatio="xMinYMin meet">',f+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',f+='<path d="',o=0;o<h.getModuleCount();o+=1)for(i=o*t+r,n=0;n<h.getModuleCount();n+=1)h.isDark(o,n)&&(f+="M"+(n*t+r)+","+i+a);return f+='" stroke="transparent" fill="black"/>',f+="</svg>"},h.createDataURL=function(o,t){o=o||2,t=void 0===t?4*o:t;var r=h.getModuleCount()*o+2*t,i=t,a=r-t;return D(r,r,function(t,r){if(i<=t&&t<a&&i<=r&&r<a){var e=Math.floor((t-i)/o),n=Math.floor((r-i)/o);return h.isDark(n,e)?0:1}return 1})},h.createImgTag=function(t,r,e){t=t||2,r=void 0===r?4*t:r;var n=h.getModuleCount()*t+2*r,o="";return o+="<img",o+=' src="',o+=h.createDataURL(t,r),o+='"',o+=' width="',o+=n,o+='"',o+=' height="',o+=n,o+='"',e&&(o+=' alt="',o+=e,o+='"'),o+="/>"},h.createASCII=function(t,r){if((t=t||1)<2)return function(t){t=void 0===t?2:t;var r,e,n,o,i,a=1*h.getModuleCount()+2*t,u=t,f=a-t,c={"██":"█","█ ":"▀"," █":"▄"," ":" "},l={"██":"▀","█ ":"▀"," █":" "," ":" "},s="";for(r=0;r<a;r+=2){for(n=Math.floor((r-u)/1),o=Math.floor((r+1-u)/1),e=0;e<a;e+=1)i="█",u<=e&&e<f&&u<=r&&r<f&&h.isDark(n,Math.floor((e-u)/1))&&(i=" "),u<=e&&e<f&&u<=r+1&&r+1<f&&h.isDark(o,Math.floor((e-u)/1))?i+=" ":i+="█",s+=t<1&&f<=r+1?l[i]:c[i];s+="\n"}return a%2&&0<t?s.substring(0,s.length-a-1)+Array(1+a).join("▀"):s.substring(0,s.length-1)}(r);t-=1,r=void 0===r?2*t:r;var e,n,o,i,a=h.getModuleCount()*t+2*r,u=r,f=a-r,c=Array(t+1).join("██"),l=Array(t+1).join(" "),s="",g="";for(e=0;e<a;e+=1){for(o=Math.floor((e-u)/t),g="",n=0;n<a;n+=1)i=1,u<=n&&n<f&&u<=e&&e<f&&h.isDark(o,Math.floor((n-u)/t))&&(i=0),g+=i?c:l;for(o=0;o<t;o+=1)s+=g+"\n"}return s.substring(0,s.length-1)},h.renderTo2dContext=function(t,r){r=r||2;for(var e=h.getModuleCount(),n=0;n<e;n++)for(var o=0;o<e;o++)t.fillStyle=h.isDark(n,o)?"black":"white",t.fillRect(n*r,o*r,r,r)},h}i.stringToBytes=(i.stringToBytesFuncs={default:function(t){for(var r=[],e=0;e<t.length;e+=1){var n=t.charCodeAt(e);r.push(255&n)}return r}}).default,i.createStringToBytes=function(u,f){var i=function(){function t(){var t=r.read();if(-1==t)throw"eof";return t}for(var r=L(u),e=0,n={};;){var o=r.read();if(-1==o)break;var i=t(),a=t()<<8|t();n[String.fromCharCode(o<<8|i)]=a,e+=1}if(e!=f)throw e+" != "+f;return n}(),a="?".charCodeAt(0);return function(t){for(var r=[],e=0;e<t.length;e+=1){var n=t.charCodeAt(e);if(n<128)r.push(n);else{var o=i[t.charAt(e)];"number"==typeof o?(255&o)==o?r.push(o):(r.push(o>>>8),r.push(255&o)):r.push(a)}}return r}};var a=1,u=2,o=4,f=8,y={L:1,M:0,Q:3,H:2},n=0,c=1,l=2,s=3,g=4,h=5,v=6,d=7,w=function(){function e(t){for(var r=0;0!=t;)r+=1,t>>>=1;return r}var r=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],t={};return t.getBCHTypeInfo=function(t){for(var r=t<<10;0<=e(r)-e(1335);)r^=1335<<e(r)-e(1335);return 21522^(t<<10|r)},t.getBCHTypeNumber=function(t){for(var r=t<<12;0<=e(r)-e(7973);)r^=7973<<e(r)-e(7973);return t<<12|r},t.getPatternPosition=function(t){return r[t-1]},t.getMaskFunction=function(t){switch(t){case n:return function(t,r){return(t+r)%2==0};case c:return function(t,r){return t%2==0};case l:return function(t,r){return r%3==0};case s:return function(t,r){return(t+r)%3==0};case g:return function(t,r){return(Math.floor(t/2)+Math.floor(r/3))%2==0};case h:return function(t,r){return t*r%2+t*r%3==0};case v:return function(t,r){return(t*r%2+t*r%3)%2==0};case d:return function(t,r){return(t*r%3+(t+r)%2)%2==0};default:throw"bad maskPattern:"+t}},t.getErrorCorrectPolynomial=function(t){for(var r=m([1],0),e=0;e<t;e+=1)r=r.multiply(m([1,p.gexp(e)],0));return r},t.getLengthInBits=function(t,r){if(1<=r&&r<10)switch(t){case a:return 10;case u:return 9;case o:case f:return 8;default:throw"mode:"+t}else if(r<27)switch(t){case a:return 12;case u:return 11;case o:return 16;case f:return 10;default:throw"mode:"+t}else{if(!(r<41))throw"type:"+r;switch(t){case a:return 14;case u:return 13;case o:return 16;case f:return 12;default:throw"mode:"+t}}},t.getLostPoint=function(t){for(var r=t.getModuleCount(),e=0,n=0;n<r;n+=1)for(var o=0;o<r;o+=1){for(var i=0,a=t.isDark(n,o),u=-1;u<=1;u+=1)if(!(n+u<0||r<=n+u))for(var f=-1;f<=1;f+=1)o+f<0||r<=o+f||0==u&&0==f||a==t.isDark(n+u,o+f)&&(i+=1);5<i&&(e+=3+i-5)}for(n=0;n<r-1;n+=1)for(o=0;o<r-1;o+=1){var c=0;t.isDark(n,o)&&(c+=1),t.isDark(n+1,o)&&(c+=1),t.isDark(n,o+1)&&(c+=1),t.isDark(n+1,o+1)&&(c+=1),0!=c&&4!=c||(e+=3)}for(n=0;n<r;n+=1)for(o=0;o<r-6;o+=1)t.isDark(n,o)&&!t.isDark(n,o+1)&&t.isDark(n,o+2)&&t.isDark(n,o+3)&&t.isDark(n,o+4)&&!t.isDark(n,o+5)&&t.isDark(n,o+6)&&(e+=40);for(o=0;o<r;o+=1)for(n=0;n<r-6;n+=1)t.isDark(n,o)&&!t.isDark(n+1,o)&&t.isDark(n+2,o)&&t.isDark(n+3,o)&&t.isDark(n+4,o)&&!t.isDark(n+5,o)&&t.isDark(n+6,o)&&(e+=40);var l=0;for(o=0;o<r;o+=1)for(n=0;n<r;n+=1)t.isDark(n,o)&&(l+=1);return e+=10*(Math.abs(100*l/r/r-50)/5)},t}(),p=function(){for(var r=new Array(256),e=new Array(256),t=0;t<8;t+=1)r[t]=1<<t;for(t=8;t<256;t+=1)r[t]=r[t-4]^r[t-5]^r[t-6]^r[t-8];for(t=0;t<255;t+=1)e[r[t]]=t;var n={glog:function(t){if(t<1)throw"glog("+t+")";return e[t]},gexp:function(t){for(;t<0;)t+=255;for(;256<=t;)t-=255;return r[t]}};return n}();function m(n,o){if(void 0===n.length)throw n.length+"/"+o;var r=function(){for(var t=0;t<n.length&&0==n[t];)t+=1;for(var r=new Array(n.length-t+o),e=0;e<n.length-t;e+=1)r[e]=n[e+t];return r}(),i={getAt:function(t){return r[t]},getLength:function(){return r.length},multiply:function(t){for(var r=new Array(i.getLength()+t.getLength()-1),e=0;e<i.getLength();e+=1)for(var n=0;n<t.getLength();n+=1)r[e+n]^=p.gexp(p.glog(i.getAt(e))+p.glog(t.getAt(n)));return m(r,0)},mod:function(t){if(i.getLength()-t.getLength()<0)return i;for(var r=p.glog(i.getAt(0))-p.glog(t.getAt(0)),e=new Array(i.getLength()),n=0;n<i.getLength();n+=1)e[n]=i.getAt(n);for(n=0;n<t.getLength();n+=1)e[n]^=p.gexp(p.glog(t.getAt(n))+r);return m(e,0).mod(t)}};return i}function b(){var e=[],o={writeByte:function(t){e.push(255&t)},writeShort:function(t){o.writeByte(t),o.writeByte(t>>>8)},writeBytes:function(t,r,e){r=r||0,e=e||t.length;for(var n=0;n<e;n+=1)o.writeByte(t[n+r])},writeString:function(t){for(var r=0;r<t.length;r+=1)o.writeByte(t.charCodeAt(r))},toByteArray:function(){return e},toString:function(){var t="";t+="[";for(var r=0;r<e.length;r+=1)0<r&&(t+=","),t+=e[r];return t+="]"}};return o}var k,t,B=(k=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],(t={}).getRSBlocks=function(t,r){var e=function(t,r){switch(r){case y.L:return k[4*(t-1)+0];case y.M:return k[4*(t-1)+1];case y.Q:return k[4*(t-1)+2];case y.H:return k[4*(t-1)+3];default:return}}(t,r);if(void 0===e)throw"bad rs block @ typeNumber:"+t+"/errorCorrectionLevel:"+r;for(var n,o,i=e.length/3,a=[],u=0;u<i;u+=1)for(var f=e[3*u+0],c=e[3*u+1],l=e[3*u+2],s=0;s<f;s+=1)a.push((n=l,o=void 0,(o={}).totalCount=c,o.dataCount=n,o));return a},t),C=function(){var e=[],n=0,o={getBuffer:function(){return e},getAt:function(t){var r=Math.floor(t/8);return 1==(e[r]>>>7-t%8&1)},put:function(t,r){for(var e=0;e<r;e+=1)o.putBit(1==(t>>>r-e-1&1))},getLengthInBits:function(){return n},putBit:function(t){var r=Math.floor(n/8);e.length<=r&&e.push(0),t&&(e[r]|=128>>>n%8),n+=1}};return o},x=function(t){var r=a,n=t,e={getMode:function(){return r},getLength:function(t){return n.length},write:function(t){for(var r=n,e=0;e+2<r.length;)t.put(o(r.substring(e,e+3)),10),e+=3;e<r.length&&(r.length-e==1?t.put(o(r.substring(e,e+1)),4):r.length-e==2&&t.put(o(r.substring(e,e+2)),7))}},o=function(t){for(var r=0,e=0;e<t.length;e+=1)r=10*r+i(t.charAt(e));return r},i=function(t){if("0"<=t&&t<="9")return t.charCodeAt(0)-"0".charCodeAt(0);throw"illegal char :"+t};return e},A=function(t){var r=u,n=t,e={getMode:function(){return r},getLength:function(t){return n.length},write:function(t){for(var r=n,e=0;e+1<r.length;)t.put(45*o(r.charAt(e))+o(r.charAt(e+1)),11),e+=2;e<r.length&&t.put(o(r.charAt(e)),6)}},o=function(t){if("0"<=t&&t<="9")return t.charCodeAt(0)-"0".charCodeAt(0);if("A"<=t&&t<="Z")return t.charCodeAt(0)-"A".charCodeAt(0)+10;switch(t){case" ":return 36;case"$":return 37;case"%":return 38;case"*":return 39;case"+":return 40;case"-":return 41;case".":return 42;case"/":return 43;case":":return 44;default:throw"illegal char :"+t}};return e},M=function(t){var r=o,e=i.stringToBytes(t),n={getMode:function(){return r},getLength:function(t){return e.length},write:function(t){for(var r=0;r<e.length;r+=1)t.put(e[r],8)}};return n},S=function(t){var r=f,n=i.stringToBytesFuncs.SJIS;if(!n)throw"sjis not supported.";!function(t,r){var e=n("友");if(2!=e.length||38726!=(e[0]<<8|e[1]))throw"sjis not supported."}();var o=n(t),e={getMode:function(){return r},getLength:function(t){return~~(o.length/2)},write:function(t){for(var r=o,e=0;e+1<r.length;){var n=(255&r[e])<<8|255&r[e+1];if(33088<=n&&n<=40956)n-=33088;else{if(!(57408<=n&&n<=60351))throw"illegal char at "+(e+1)+"/"+n;n-=49472}n=192*(n>>>8&255)+(255&n),t.put(n,13),e+=2}if(e<r.length)throw"illegal char at "+(e+1)}};return e},L=function(t){var e=t,n=0,o=0,i=0,r={read:function(){for(;i<8;){if(n>=e.length){if(0==i)return-1;throw"unexpected end of file./"+i}var t=e.charAt(n);if(n+=1,"="==t)return i=0,-1;t.match(/^\s$/)||(o=o<<6|a(t.charCodeAt(0)),i+=6)}var r=o>>>i-8&255;return i-=8,r}},a=function(t){if(65<=t&&t<=90)return t-65;if(97<=t&&t<=122)return t-97+26;if(48<=t&&t<=57)return t-48+52;if(43==t)return 62;if(47==t)return 63;throw"c:"+t};return r},D=function(t,r,e){for(var n=function(t,r){var n=t,o=r,s=new Array(t*r),e={setPixel:function(t,r,e){s[r*n+t]=e},write:function(t){t.writeString("GIF87a"),t.writeShort(n),t.writeShort(o),t.writeByte(128),t.writeByte(0),t.writeByte(0),t.writeByte(0),t.writeByte(0),t.writeByte(0),t.writeByte(255),t.writeByte(255),t.writeByte(255),t.writeString(","),t.writeShort(0),t.writeShort(0),t.writeShort(n),t.writeShort(o),t.writeByte(0);var r=i(2);t.writeByte(2);for(var e=0;255<r.length-e;)t.writeByte(255),t.writeBytes(r,e,255),e+=255;t.writeByte(r.length-e),t.writeBytes(r,e,r.length-e),t.writeByte(0),t.writeString(";")}},i=function(t){for(var r=1<<t,e=1+(1<<t),n=t+1,o=g(),i=0;i<r;i+=1)o.add(String.fromCharCode(i));o.add(String.fromCharCode(r)),o.add(String.fromCharCode(e));var a=b(),u=function(t){var e=t,n=0,o=0,r={write:function(t,r){if(t>>>r!=0)throw"length over";for(;8<=n+r;)e.writeByte(255&(t<<n|o)),r-=8-n,t>>>=8-n,n=o=0;o|=t<<n,n+=r},flush:function(){0<n&&e.writeByte(o)}};return r}(a);u.write(r,n);var f=0,c=String.fromCharCode(s[f]);for(f+=1;f<s.length;){var l=String.fromCharCode(s[f]);f+=1,o.contains(c+l)?c+=l:(u.write(o.indexOf(c),n),o.size()<4095&&(o.size()==1<<n&&(n+=1),o.add(c+l)),c=l)}return u.write(o.indexOf(c),n),u.write(e,n),u.flush(),a.toByteArray()},g=function(){var r={},e=0,n={add:function(t){if(n.contains(t))throw"dup key:"+t;r[t]=e,e+=1},size:function(){return e},indexOf:function(t){return r[t]},contains:function(t){return void 0!==r[t]}};return n};return e}(t,r),o=0;o<r;o+=1)for(var i=0;i<t;i+=1)n.setPixel(i,o,e(i,o));var a=b();n.write(a);for(var u=function(){function e(t){a+=String.fromCharCode(r(63&t))}var n=0,o=0,i=0,a="",t={},r=function(t){if(t<0);else{if(t<26)return 65+t;if(t<52)return t-26+97;if(t<62)return t-52+48;if(62==t)return 43;if(63==t)return 47}throw"n:"+t};return t.writeByte=function(t){for(n=n<<8|255&t,o+=8,i+=1;6<=o;)e(n>>>o-6),o-=6},t.flush=function(){if(0<o&&(e(n<<6-o),o=n=0),i%3!=0)for(var t=3-i%3,r=0;r<t;r+=1)a+="="},t.toString=function(){return a},t}(),f=a.toByteArray(),c=0;c<f.length;c+=1)u.writeByte(f[c]);return u.flush(),"data:image/gif;base64,"+u};return i}();a.stringToBytesFuncs["UTF-8"]=function(t){return function(t){for(var r=[],e=0;e<t.length;e++){var n=t.charCodeAt(e);n<128?r.push(n):n<2048?r.push(192|n>>6,128|63&n):n<55296||57344<=n?r.push(224|n>>12,128|n>>6&63,128|63&n):(e++,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),r.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|63&n))}return r}(t)},o=[],void 0===(i="function"==typeof(n=function(){return a})?n.apply(r,o):n)||(t.exports=i)},function(t,r,e){function c(t,r,e,n,o,i){t.isDark(o,i)&&r.rect(i*n,o*n,n,n)}var l=e(7),n=e(8);t.exports=function(t,r,e){!function(t,r){t.fillStyle=r.back,t.fillRect(0,0,r.size,r.size)}(r,e),function(t,r,e){if(t){var n=0<e.rounded&&e.rounded<=100?l:c,o=t.moduleCount,i=e.size/o,a=0;e.crisp&&(i=Math.floor(i),a=Math.floor((e.size-i*o)/2)),r.translate(a,a),r.beginPath();for(var u=0;u<o;u+=1)for(var f=0;f<o;f+=1)n(t,r,e,i,u,f);r.fillStyle=e.fill,r.fill(),r.translate(-a,-a)}}(t,r,e),n(r,e)}},function(t,r){t.exports=function(t,r,e,n,o,i){var a=i*n,u=o*n,f=a+n,c=u+n,l=.005*e.rounded*n,s=t.isDark,g=o-1,h=o+1,v=i-1,d=i+1,p=s(o,i),y=s(g,v),w=s(g,i),m=s(g,d),b=s(o,d),k=s(h,d),B=s(h,i),C=s(h,v),x=s(o,v);r=function(t){return{c:t,m:function(){var t;return(t=this.c).moveTo.apply(t,arguments),this},l:function(){var t;return(t=this.c).lineTo.apply(t,arguments),this},a:function(){var t;return(t=this.c).arcTo.apply(t,arguments),this}}}(r),p?function(t,r,e,n,o,i,a,u,f,c){a?t.m(r+i,e):t.m(r,e),u?t.l(n-i,e).a(n,e,n,o,i):t.l(n,e),f?t.l(n,o-i).a(n,o,r,o,i):t.l(n,o),c?t.l(r+i,o).a(r,o,r,e,i):t.l(r,o),a?t.l(r,e+i).a(r,e,n,e,i):t.l(r,e)}(r,a,u,f,c,l,!w&&!x,!w&&!b,!B&&!b,!B&&!x):function(t,r,e,n,o,i,a,u,f,c){a&&t.m(r+i,e).l(r,e).l(r,e+i).a(r,e,r+i,e,i),u&&t.m(n-i,e).l(n,e).l(n,e+i).a(n,e,n-i,e,i),f&&t.m(n-i,o).l(n,o).l(n,o-i).a(n,o,n-i,o,i),c&&t.m(r+i,o).l(r,o).l(r,o-i).a(r,o,r+i,o,i)}(r,a,u,f,c,l,w&&x&&y,w&&b&&m,B&&b&&k,B&&x&&C)}},function(t,r){t.exports=function(t,r){var e=r.mode;"label"===e?function(t,r){var e=r.size,n="bold "+.01*r.mSize*e+"px "+r.fontname;t.strokeStyle=r.back,t.lineWidth=.01*r.mSize*e*.1,t.fillStyle=r.fontcolor,t.font=n;var o=t.measureText(r.label).width,i=.01*r.mSize,a=(1-o/e)*r.mPosX*.01*e,u=(1-i)*r.mPosY*.01*e+.75*r.mSize*.01*e;t.strokeText(r.label,a,u),t.fillText(r.label,a,u)}(t,r):"image"===e&&function(t,r){var e=r.size,n=r.image.naturalWidth||1,o=r.image.naturalHeight||1,i=.01*r.mSize,a=i*n/o,u=(1-a)*r.mPosX*.01*e,f=(1-i)*r.mPosY*.01*e,c=a*e,l=i*e;t.drawImage(r.image,u,f,c,l)}(t,r)}}])});
/** * @author arman * @since 8/20/18 * */ 'use strict'; import React from 'react'; import isUrl from 'is-url'; import styled from 'react-emotion'; import { Block, Value } from 'slate'; import initialValue from './value.json'; import App from './app.component'; import ListItemContainer from './list-item.container'; import { isKeyHotkey } from 'is-hotkey'; import imageExtensions from 'image-extensions'; import { Button, Icon, Toolbar } from './components'; import { LAST_CHILD_TYPE_INVALID } from 'slate-schema-violations'; import { Editor, getEventRange, getEventTransfer } from 'slate-react'; const DEFAULT_NODE = 'paragraph'; const isBoldHotkey = isKeyHotkey('mod+b'); const isItalicHotkey = isKeyHotkey('mod+i'); const isUnderlinedHotkey = isKeyHotkey('mod+u'); const isCodeHotkey = isKeyHotkey('mod+`'); const Image = styled('img')` display: block; max-width: 100%; max-height: 20em; box-shadow: ${props => (props.selected ? '0 0 0 2px blue;' : 'none')}; `; function isImage(url) { return !!imageExtensions.find(url.endsWith) } const schema = { document: { last: { type: 'paragraph' }, normalize: (change, reason, { node, child }) => { switch (reason) { case LAST_CHILD_TYPE_INVALID: { const paragraph = Block.create('paragraph') return change.insertNodeByKey(node.key, node.nodes.size, paragraph) } } }, }, }; class AppContainer extends React.Component { constructor(props) { super(props); this.state = { value: Value.fromJSON(initialValue) }; } componentDidMount() { this._handleImageUpload(); } onChange = ({ value }) => { this.setState({ value }); }; renderNode = (props) => { const { attributes, children, node, isFocused } = props; switch (node.type) { case 'block-quote': return <blockquote {...attributes}>{children}</blockquote>; case 'bulleted-list': return <ul {...attributes}>{children}</ul>; case 'heading-one': return <h1 {...attributes}>{children}</h1>; case 'heading-two': return <h2 {...attributes}>{children}</h2>; case 'list-item': return <li {...attributes}>{children}</li>; case 'numbered-list': return <ol {...attributes}>{children}</ol>; case 'check-list-item': return <ListItemContainer {...props} />; case 'image': { const src = node.data.get('src'); return <Image src={src} selected={isFocused} {...attributes} /> } } }; onKeyDown = (event, change) => { let mark; const { value } = change; if (isBoldHotkey(event)) { mark = 'bold'; } else if (isItalicHotkey(event)) { mark = 'italic'; } else if (isUnderlinedHotkey(event)) { mark = 'underlined'; } else if (isCodeHotkey(event)) { mark = 'code'; } else if (event.key == 'Enter' && value.startBlock.type == 'check-list-item') { change.splitBlock().setBlocks({ data: { checked: false } }); return true; } else if (event.key == 'Backspace' && value.isCollapsed && value.startBlock.type == 'check-list-item' && value.selection.startOffset === 0) { change.setBlocks('paragraph'); return true; } else { return } event.preventDefault(); change.toggleMark(mark); return true; }; /****************************************** Image Specific Handlers*******************************************/ _handleImageUpload = () => { let insertImage = this.insertImage; let _self = this; document.querySelector('form input[type=file]').addEventListener('change', (event) => { event.preventDefault(); let files = event.target.files; if (typeof files[0] !== 'object') return false; _self.state.value.change().call(insertImage, files[0], undefined, _self); }); }; insertImage(change, file, target, context) { let _self = context; if (target) { change.select(target); } let reader = new FileReader(); // listen for 'load' events on the FileReader reader.addEventListener("load", function () { let src = reader.result; change.insertBlock({ type: 'image', isVoid: true, data: { src }, }); _self.onChange(change); }, false); if (file) { reader.readAsDataURL(file); } }; onClickUpload = (event) => { event.preventDefault(); document.querySelector('form input[type=file]').click(); }; onDropOrPaste = (event, change, editor) => { const target = getEventRange(event, change.value); if (!target && event.type == 'drop') return; const transfer = getEventTransfer(event); const { type, text, files } = transfer; if (type == 'files') { for (const file of files) { const reader = new FileReader(); const [mime] = file.type.split('/'); if (mime != 'image') continue; reader.addEventListener('load', () => { editor.change(c => { c.call(this.insertImage, reader.result, target); }) }); reader.readAsDataURL(file); } } if (type == 'text') { if (!isUrl(text)) return; if (!isImage(text)) return; change.call(insertImage, text, target); } }; /********************************************* Text Specific Handlers *****************************************/ hasMark = (type) => { const { value } = this.state; return value.activeMarks.some(mark => mark.type === type); }; hasBlock = (type) => { const { value } = this.state; return value.blocks.some(node => node.type == type); }; renderMarkButton = (type, icon) => { const isActive = this.hasMark(type); return ( <Button active={isActive} onMouseDown={event => this.onClickMark(event, type)} > <Icon>{icon}</Icon> </Button> ) }; renderBlockButton = (type, icon) => { let isActive = this.hasBlock(type); if (['numbered-list', 'bulleted-list'].includes(type)) { const { value } = this.state; const parent = value.document.getParent(value.blocks.first().key); isActive = this.hasBlock('list-item') && parent && parent.type === type; } return ( <Button active={isActive} onMouseDown={event => this.onClickBlock(event, type)} > <Icon>{icon}</Icon> </Button> ) }; renderMark = props => { const { children, mark, attributes } = props; switch (mark.type) { case 'bold': return <strong {...attributes}>{children}</strong>; case 'code': return <code {...attributes}>{children}</code>; case 'italic': return <em {...attributes}>{children}</em>; case 'underlined': return <u {...attributes}>{children}</u>; } }; onClickMark = (event, type) => { event.preventDefault(); const { value } = this.state; const change = value.change().toggleMark(type); this.onChange(change); }; onClickBlock = (event, type) => { event.preventDefault(); const { value } = this.state; const change = value.change(); const { document } = value; if (type !== 'bulleted-list' && type !== 'numbered-list') { const isActive = this.hasBlock(type); const isList = this.hasBlock('list-item'); if (isList) { change .setBlocks(isActive ? DEFAULT_NODE : type) .unwrapBlock('bulleted-list') .unwrapBlock('numbered-list'); } else { change.setBlocks(isActive ? DEFAULT_NODE : type); } } else { // Handle the extra wrapping required for list buttons. const isList = this.hasBlock('list-item'); const isType = value.blocks.some(block => { return !!document.getClosest(block.key, parent => parent.type == type) }); if (isList && isType) { change .setBlocks(DEFAULT_NODE) .unwrapBlock('bulleted-list') .unwrapBlock('numbered-list'); } else if (isList) { change .unwrapBlock( type == 'bulleted-list' ? 'numbered-list' : 'bulleted-list' ) .wrapBlock(type); } else { change.setBlocks('list-item').wrapBlock(type); } } this.onChange(change); }; render() { let { value } = this.state; return ( <App value={value} schema={schema} onKeyDown={this.onKeyDown} renderMark={this.renderMark} renderMarkButton={this.renderMarkButton} renderBlockButton={this.renderBlockButton} onChange={this.onChange} onDrop={this.onDropOrPaste} onPaste={this.onDropOrPaste} renderNode={this.renderNode} onClickUpload={this.onClickUpload} /> ); } } export default AppContainer;
import React from 'react'; import { ProgressBarDefault } from './index'; export default class ProgressBarKitchenSink extends React.Component { render() { return ( <React.Fragment> <ProgressBarDefault /> </React.Fragment> ); } }
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See http://js.arcgis.com/3.34/esri/copyright.txt for details. //>>built define("esri/dijit/metadata/nls/et/i18nBase",{general:{cancel:"T\u00fchista",close:"Sulge",none:"Puudub",ok:"OK",other:"Muu",stamp:"Tempel",now:"Praegu",choose:"Vali \u00fcks:"},editor:{noMetadata:"Sellel \u00fcksusel puuduvad metaandmed",xmlViewOnly:"Redaktor ei toeta selle \u00fcksusega seotud metaandmete t\u00fc\u00fcpi. Metaandmed peavad olema ArcGIS-i vormingus.",editorDialog:{caption:"Metaandmed",captionPattern:"Metaandmed - {title}"},primaryToolbar:{view:"Vaatamine",viewXml:"Kuva XML",edit:"Muuda", initializing:"Laadimine...",startingEditor:"Redaktori k\u00e4ivitamine...",loadingDocument:"Dokumendi laadimine...",updatingDocument:"Dokumendi uuendamine...",generatingView:"Vaate genereerimine...",errors:{errorGeneratingView:"Vaate genereerimisel tekkis viga.",errorLoadingDocument:"Dokumendi laadimisel tekkis viga."}},changesNotSaved:{prompt:"Teie dokumendis on salvestamata muudatusi.",dialogTitle:"Sulge metaandmete redaktor",closeButton:"Sulge"},download:{caption:"Laadi alla",dialogTitle:"Laadi alla", prompt:"Faili allalaadimiseks kl\u00f5psake siin."},load:{caption:"Avatud",dialogTitle:"Avatud",typeTab:"Uus dokument",fileTab:"Ava fail",templateTab:"Mall",itemTab:"Teie \u00fcksus",filePrompt:"Valige kohalik ArcGIS-i metaandmete XML-fail. Metaandmed peavad olema ArcGIS-i vormingus.",templatePrompt:"Metaandmete loomine",pullItem:"M\u00e4\u00e4rake metaandmed \u00fcksuse detailide kasutades.",importWarning:"Valitud faili ei kuvata ArcGIS-i vormingus. \u00dcles laaditud metaandmed peavad olema ArcGIS-i vormingus.", loading:"Laadimine...",noMetadata:"Selle \u00fcksuse metaandmeid saab luua, valides \u00fche j\u00e4rgmistest valikutest.",unrecognizedMetadata:"Redaktor ei toeta selle \u00fcksusega seotud metaandmete t\u00fc\u00fcpi. Toetatud metaandmeid saab luua, valides \u00fche j\u00e4rgmistest valikutest.",errorLoading:"Laadimisel ilmnes viga.",warnings:{badFile:"Valitud faili ei saanud laadida.",notAnXml:"Valitud fail pole XML-fail.",notSupported:"Seda failit\u00fc\u00fcpi ei toetata."},portalCaption:"Kirjuta \u00fcle"}, save:{caption:"Salvesta",dialogTitle:"Metaandmete salvestamine",working:"Metaandmete salvestamine...",errorSaving:"Ilmnes viga, Teie metaandmeid ei salvestatud.",saveDialog:{pushCaption:"Rakenda muudatused \u00fcksusele"}},saveAndClose:{caption:"Salvesta ja sulge"},saveDraft:{caption:"Allalaadimine",dialogTitle:"Allalaadimine"},validate:{caption:"Valideeri",dialogTitle:"Valideerimine",docIsValid:"Dokument on kehtiv."},viewHtml:{caption:"Vaatamine",dialogTitle:"Kuva metaandmed",savePrompt:"Teie dokumendis on salvestamata muudatusi. Nende n\u00e4gemiseks metaandmete vaatamisel peate k\u00f5ik muudatused salvestama.", saveButton:"Salvesta ja kuva",portalNone:"Standarditel p\u00f5hinevatel metaandmetel puudub autor. Enne metaandmete vaatamist peate salvestama."},del:{caption:"Kustuta",dialogTitle:"Kustuta metaandmed",prompt:"Kas soovite need metaandmed kindlasti kustutada?",working:"Metaandmete kustutamine...",errorDeleting:"Ilmnes viga, Teie metaandmeid ei kustutatud.",portalNone:"Metaandmete dokumenti pole kustutamiseks saadaval. Standarditel p\u00f5hinevatel metaandmetel puudub autor.",portalPrompt:"Sellega kustutatakse metaandmete dokument ja l\u00e4htestatakse selle \u00fcksuse metaandmed teabele (nt pealkiri, sisukirjeldus jt).", portalPrompt2:"See kustutab standardip\u00f5hised metaandmed. Kas soovite need metaandmed kindlasti kustutada?",portalButton:"Kustuta ja sulge"},transform:{caption:"Teisenda",dialogTitle:"Teisenda:",prompt:"",working:"Teisendamine...",errorTransforming:"Dokumendi teisendamisel ilmnes viga."},errorDialog:{dialogTitle:"Ilmnes viga"}},arcgis:{portal:{metadataButton:{caption:"Metaandmed"}}},calendar:{button:"Kalender...",title:"Kalender"},geoExtent:{button:"M\u00e4\u00e4ra geograafiline ulatus",title:"Geograafiline ulatus", navigate:"Navigeeri",draw:"Joonista ristk\u00fclik",drawHint:"Alustamiseks hoia all ja l\u00f5petamiseks vabasta."},hints:{date:"(yyyy v\u00f5i yyyy-mm v\u00f5i yyyy-mm-dd)",dateTime:"(yyyy-mm-ddThh:mm:ss.sss[+-]hh:mm)",dateOrDateTime:"(yyyy v\u00f5i yyyy-mm v\u00f5i yyyy-mm-dd v\u00f5i yyyy-mm-ddThh:mm:ss.sss[+-]hh:mm)",delimitedTextArea:"(eraldamiseks kasuta koma v\u00f5i reapiiri)",fgdcDate:"(yyyy v\u00f5i yyyy-mm v\u00f5i yyyy-mm-dd)",fgdcTime:"(hh:mm:ss.sss[+-]hh:mm)",integer:"(sisesta t\u00e4isarv)", latitude:"(k\u00fcmnendikkraadid)",longitude:"(k\u00fcmnendikkraadid)",number:"(sisesta number)",numberGreaterThanZero:"(sisesta number \x3e 0)"},isoTopicCategoryCode:{caption:"Teemakategooria",boundaries:"Administratiiv- ja poliitilised piirid",farming:"P\u00f5llumajandus ja loomakasvatus",climatologyMeteorologyAtmosphere:"Atmosf\u00e4\u00e4r ja kliima",biota:"Bioloogia ja \u00f6koloogia",economy:"\u00c4ri ja majandus",planningCadastre:"Katastriandmed",society:"Kultuur, \u00fchiskond ja demograafia", elevation:"K\u00f5rgus ja tuletatud tooted",environment:"Keskkond ja loodushoid",structure:"Omadused ja struktuurid",geoscientificInformation:"Geoloogiline ja geof\u00fc\u00fcsiline",health:"Tervishoid ja haigused",imageryBaseMapsEarthCover:"Satelliit- ja aluskaardid",inlandWaters:"Siseveeressursid",location:"Asukohad ja geodeetilised v\u00f5rgud",intelligenceMilitary:"S\u00f5jaline",oceans:"Ookeanid ja suudmed",transportation:"Transpordiv\u00f5rgustikud",utilitiesCommunication:"Tehnoettev\u00f5tted"}, multiplicity:{moveElementDown:"Vii jaotis allapoole",moveElementUp:"Vii jaotis \u00fclespoole",removeElement:"Eemalda jaotis",repeatElement:"Korda jaotist"},optionalNode:{switchTip:"Kaasa see jaotis v\u00f5i j\u00e4ta v\u00e4lja"},serviceTypes:{featureService:"Objektiteenus",mapService:"Kaarditeenus",imageService:"Pilditeenus",wms:"WMS",wfs:"WFS",wcs:"WCS"},validation:{pattern:"{label} - {message}",patternWithHint:"{label} - {message} {hint}",ok:"OK",empty:"V\u00e4\u00e4rtus on n\u00f5utav.",date:"V\u00e4\u00e4rtus peab olema kuup\u00e4ev.", integer:"V\u00e4\u00e4rtus peab olema t\u00e4isarv.",number:"V\u00e4\u00e4rtus peab olema arv.",other:"Vigane v\u00e4\u00e4rtus"},validationPane:{clearMessages:"T\u00fchjenda teated",prompt:"(kl\u00f5psake iga allolevat s\u00f5numit ja sisestage m\u00e4\u00e4ratud v\u00e4ljale vajalik teave)"}});
module.exports = { name: 'landing', preset: '../../jest.preset.js', globals: { 'ts-jest': { tsconfig: '<rootDir>/tsconfig.spec.json' }, }, transform: { '^.+\\.(ts|html)$': 'ts-jest', }, moduleFileExtensions: ['ts', 'js', 'html'], setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'], coverageDirectory: '../../coverage/libs/landing', snapshotSerializers: [ 'jest-preset-angular/build/serializers/no-ng-attributes', 'jest-preset-angular/build/serializers/ng-snapshot', 'jest-preset-angular/build/serializers/html-comment', ], };
/** * Search Console Settings stories. * * Site Kit by Google, 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 * * https://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. */ /** * External dependencies */ import { storiesOf } from '@storybook/react'; /** * Internal dependencies */ import { STORE_NAME } from '../assets/js/modules/search-console/datastore/constants'; import { createTestRegistry, provideUserAuthentication, provideModules, provideModuleRegistrations, } from '../tests/js/utils'; import createLegacySettingsWrapper from './utils/create-legacy-settings-wrapper'; const Settings = createLegacySettingsWrapper( 'search-console' ); const defaultSettings = { propertyID: '', }; storiesOf( 'Search Console Module/Settings', module ) .addDecorator( ( storyFn ) => { const registry = createTestRegistry(); registry.dispatch( STORE_NAME ).receiveGetSettings( {} ); provideUserAuthentication( registry ); provideModules( registry ); provideModuleRegistrations( registry ); return storyFn( registry ); } ) .add( 'View, closed', ( registry ) => { return <Settings isOpen={ false } registry={ registry } />; } ) .add( 'View, open with all settings', ( registry ) => { registry.dispatch( STORE_NAME ).receiveGetSettings( { ...defaultSettings, propertyID: 'http://example.com/', } ); return <Settings isOpen={ true } registry={ registry } />; } ) ;
"use strict"; var NotificationService = require('../services/notification-service'); var token_auth = require('../../JWT_Checker/loginToken'); var express = require('express'); var router = express.Router(); var service = new NotificationService(); router.get('/list', token_auth, function (req, res) { service.getList(req.query.searchValue).then(function (result) { res.send(result); }).catch(function (error) { res.send(error); }); }); router.get('/byuser', token_auth, function (req, res) { var userID = req.query.userID; service.getByUser(userID).then(function (result) { res.send(result); }).catch(function (error) { res.send(error); }); }); router.get('/bytype', token_auth, function (req, res) { var type = req.query.objectType; service.getByType(type).then(function (result) { res.send(result); }).catch(function (error) { res.send(error); }); }); router.get('/bysource', token_auth, function (req, res) { var sourceID = req.query.sourceID; service.getBySource(sourceID).then(function (result) { res.send(result); }).catch(function (error) { res.send(error); }); }); router.get('/single', token_auth, function (req, res) { var notif = req.query.rowid; service.get(notif).then(function (result) { res.send(result); }).catch(function (error) { res.send(error); }); }); router.post('/single', token_auth, function (req, res) { var request = req.body; service.create(request).then(function (result) { res.send(result); }).catch(function (error) { res.send(error); }); }); router.put('/update', token_auth, function (req, res) { var request = req.body; service.update(request).then(function (result) { res.send(result); }).catch(function (error) { res.send(error); }); }); router.delete('/delete', token_auth, function (req, res) { var ID = req.query.ID; service.delete(ID).then(function (result) { res.send(result); }).catch(function (error) { res.send(error); }); }); module.exports = router; //# sourceMappingURL=../../../source-maps/modules/users/controllers/notification-controller.js.map
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import { hbs } from 'ember-cli-htmlbars'; module('Integration | Component | planning-event/panel', function (hooks) { setupRenderingTest(hooks); test('it renders', async function (assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.set('myAction', function(val) { ... }); await render(hbs`<PlanningEvent::Panel />`); assert.equal(this.element.textContent.trim(), ''); // Template block usage: await render(hbs` <PlanningEvent::Panel> template block text </PlanningEvent::Panel> `); assert.equal(this.element.textContent.trim(), 'template block text'); }); });
describe('Hotel collection specs', () => { it('should fetch 2 hotels and show it in screen when visit /hotels urls', () => { // Arrange const params = { apiPath: '/hotels', fixture: 'fixture:hotels', fetchAlias: 'fetchHotels', }; // Act cy.loadData(params); cy.visit('#/hotels'); // Assert cy.wait('@fetchHotels'); cy.get('[data-testid="hotelCollectionContainer"]') .children() .should('have.length', 2); }); it('should fetch hotel collection from backend and show it in screen when visit /hotels urls', () => { // Arrange const params = { apiPath: '/hotels', fetchAlias: 'fetchHotels', }; // Act cy.loadData(params); cy.visit('#/hotels'); // Assert cy.wait('@fetchHotels'); cy.get('[data-testid="hotelCollectionContainer"]') .children() .should('have.length', 10); }); });
/* @license dhtmlxScheduler v.5.3.11 Standard To use dhtmlxScheduler in non-GPL projects (and get Pro version of the product), please obtain Commercial/Enterprise or Ultimate license on our site https://dhtmlx.com/docs/products/dhtmlxScheduler/#licensing or contact us at sales@dhtmlx.com (c) XB Software Ltd. */ Scheduler.plugin(function(e){e.locale={date:{month_full:["Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December"],month_short:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Aug","Sep","Okt","Nov","Dec"],day_full:["Söndag","Måndag","Tisdag","Onsdag","Torsdag","Fredag","Lördag"],day_short:["Sön","Mån","Tis","Ons","Tor","Fre","Lör"]},labels:{dhx_cal_today_button:"Idag",day_tab:"Dag",week_tab:"Vecka",month_tab:"Månad",new_event:"Ny händelse", icon_save:"Spara",icon_cancel:"Ångra",icon_details:"Detaljer",icon_edit:"Ändra",icon_delete:"Ta bort",confirm_closing:"",confirm_deleting:"Är du säker på att du vill ta bort händelsen permanent?",section_description:"Beskrivning",section_time:"Tid",full_day:"Hela dagen",confirm_recurring:"Vill du redigera hela serien med repeterande händelser?",section_recurring:"Upprepa händelse",button_recurring:"Inaktiverat",button_recurring_open:"Aktiverat",button_edit_series:"Redigera serien", button_edit_occurrence:"Redigera en kopia",agenda_tab:"Dagordning",date:"Datum",description:"Beskrivning",year_tab:"År",week_agenda_tab:"Dagordning",grid_tab:"Galler",drag_to_create:"Dra för att skapa ny",drag_to_move:"Dra för att flytta",message_ok:"OK",message_cancel:"Cancel",next:"Next",prev:"Previous",year:"Year",month:"Month",day:"Day",hour:"Hour",minute:"Minute",repeat_radio_day:"Dagligen",repeat_radio_week:"Veckovis",repeat_radio_month:"Månadsvis",repeat_radio_year:"Årligen", repeat_radio_day_type:"Var",repeat_text_day_count:"dag",repeat_radio_day_type2:"Varje arbetsdag",repeat_week:" Upprepa var",repeat_text_week_count:"vecka dessa dagar:",repeat_radio_month_type:"Upprepa",repeat_radio_month_start:"Den",repeat_text_month_day:"dagen var",repeat_text_month_count:"månad",repeat_text_month_count2_before:"var",repeat_text_month_count2_after:"månad",repeat_year_label:"Den",select_year_day2:"i",repeat_text_year_day:"dag i",select_year_month:"månad", repeat_radio_end:"Inget slutdatum",repeat_text_occurences_count:"upprepningar",repeat_radio_end3:"Sluta efter",repeat_radio_end2:"Efter",month_for_recurring:["Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December"],day_for_recurring:["Söndag","Måndag","Tisdag","Onsdag","Torsdag","Fredag","Lördag"]}}}); //# sourceMappingURL=../sources/locale/locale_sv.js.map
function parseJson(s) { var XSSI_PREFIX = ")]}'"; return JSON.parse(s.replace(XSSI_PREFIX, "")); } function onSubmitButtonClick(key, xsrfToken, button) { var formData = $("#" + key).serializeArray(); var request = JSON.stringify({ "xsrf_token": xsrfToken, "key": key, "payload": { "form_data": formData } }); $.ajax({ type: "POST", url: "rest/modules/questionnaire", data: {"request": request}, dataType: "text", success: function(data) { onAjaxPostFormData(data, button); } }); gcbTagEventAudit({key: key, form_data: formData}, "questionnaire"); } function onAjaxPostFormData(data, button) { var data = parseJson(data); if (data.status == 200) { cbShowMsgAutoHide(data.message); $(button).parent().find("div.post-message").removeClass("hidden"); } else { cbShowMsg(data.message); } } function ajaxGetFormData(xsrfToken, key, button, singleSubmission) { $.ajax({ type: "GET", url: "rest/modules/questionnaire", data: {"xsrf_token": xsrfToken, "key": key}, dataType: "text", success: function(data) { onAjaxGetFormData(data, key, button, singleSubmission); } }); } function onAjaxGetFormData(data, key, button, singleSubmission) { var data = parseJson(data); if (data.status == 200) { var payload = JSON.parse(data.payload || "{}"); var form_data = payload.form_data || []; setFormData(form_data, key); if (form_data.length && singleSubmission) { disableForm(button, key); cbShowMsg(button.data('single-submission-message')); } } else { cbShowMsg(data.message); return; } } function setFormData(data, key) { for (var i=0; i < data.length; i++) { var name = data[i].name; var value = data[i].value; var elt = $("#" + key).find("[name='" + name + "']"); var tagName = elt.prop("tagName"); var type = elt.attr("type"); if (tagName == "SELECT" && elt.attr("multiple")) { elt.find("> option").each(function() { if ($(this).val() == value) { this.selected = true; } }); } else if (tagName == "TEXTAREA" || tagName == "SELECT") { elt.val(value); } else { switch(type) { case "checkbox": elt.filter("[value='" + value + "']").prop("checked", true); break; case "radio": elt.filter("[value='" + value + "']").prop("checked", true); break; default: elt.val(value); break; } } } } function disableForm(button, key) { $("#" + key).find("input,select,textarea").prop("disabled", true); $(button).prop("disabled", true); } function init() { $("div.gcb-questionnaire > button.questionnaire-button").each(function(i, button) { button = $(button); var xsrfToken = button.data("xsrf-token"); var key = button.data("form-id"); var disabled = button.data("disabled"); var singleSubmission = button.data("single-submission"); var registered = button.data("registered"); if (! registered) { cbShowMsg(button.data("registered-message")); disableForm(button, key); } else { ajaxGetFormData(xsrfToken, key, button, singleSubmission); if (disabled) { disableForm(button, key); } else { button.click(function() { onSubmitButtonClick(key, xsrfToken, button); return false; }); } } }); } init();
const inquirer = require("inquirer"); const Employee = require("./models/Employee"); const Role = require("./models/Role"); const Department = require("./models/Department"); const cTable = require("console.table"); const { raw } = require("express"); // Sets up the information to be displayed in the table shown in the console const viewEmployees = async () => { let employees = await Employee.findAll(); employeeList = employees.map((d) => d.dataValues); for (i = 0; i < employeeList.length; i++) { // Get the role name to replace the role ID in the table let roleName = await Role.findAll({ where: { id: employeeList[i].role_id, }, raw: true, }); // Get the manager name to replace the role ID in the table let managerName = await Employee.findAll({ where: { id: employeeList[i].manager_id, }, raw: true, }); // Get the department of the specific role let departmentName = await Department.findAll({ where: { id: roleName[0].department_id, }, }); // Check if the manager name exists, else dont try and add the name if (managerName[0]) { employeeList[i].manager_id = managerName[0].first_name; } // Place the variables employeeList[i].role_id = roleName[0].title; employeeList[i].salary = roleName[0].salary; employeeList[i].department = departmentName[0].name; } console.table(employeeList); }; // The main start function const start = async () => { await viewEmployees(); inquirer .prompt([ { type: "list", name: "mainQuestion", message: "What would you like to do?", choices: [ "View All Employees", "View All Departments and Their Employees", "View All Roles", "Add Employee", "Add Role", "Add Department", "Remove Employee", "Remove Department", "Remove Role", "Update Employee Role", "Update Employee Manager", ], }, ]) .then((answer) => { let chosen = answer.mainQuestion; // Runs a switch statement based on the prompt given beforehand switch (chosen) { case "View All Employees": allEmployee(); break; case "View All Departments and Their Employees": allDepartment(); break; case "Add Employee": addEmployee(); break; case "Add Department": addDepartment(); break; case "Add Role": addRole(); break; case "Remove Employee": removeEmployee(); break; case "Remove Department": removeDepartment(); break; case "Remove Role": removeRole(); break; case "Update Employee Role": updateRole(); break; case "Update Employee Manager": updateManager(); break; case "View All Roles": viewRoles(); break; } }); }; // Returns all of the employees in a prompt list const allEmployee = async () => { let employeeList = []; // Simply gets the employees and puts them in an array const employee = await Employee.findAll({ raw: true, }); for (i = 0; i < employee.length; i++) { employeeList.push(employee[i].first_name); } inquirer .prompt([ { type: "list", name: "mainQuestion", message: "Here is a list of all employees, click one to go back.", choices: employeeList, }, ]) .then((answer) => { start(); }); }; // Gives a list of all the departments to view employees under that department const allDepartment = async () => { let departmentList = []; // Gets the departments for the prompt to display const department = await Department.findAll({ raw: true, }); for (i = 0; i < department.length; i++) { departmentList.push(department[i].name); } departmentList.push("Return To Main Menu"); inquirer .prompt([ { type: "list", name: "mainQuestion", message: "Select a department to view all the employees under that department.", choices: departmentList, }, ]) .then(async (answer) => { // Checks if they wish to return to main if (answer.mainQuestion === "Return To Main Menu") { start(); } else { departmentChoice = answer.mainQuestion; let employeeArray = []; // Finds the department chosen const departmentChosen = await Department.findAll({ where: { name: departmentChoice, }, raw: true, }); // Finds all the roles under a department const rolesChosen = await Role.findAll({ where: { department_id: departmentChosen[0].id, }, raw: true, }); // Iterates through the roles array for (i = 0; i < rolesChosen.length; i++) { // Gets all the employees under each role const employeesChosen = await Employee.findAll({ where: { role_id: rolesChosen[i].id, }, raw: true, }); // Goes through the list of employees and pushes their names to an array for (i = 0; i < employeesChosen.length; i++) { employeeArray.push(employeesChosen[i].first_name); } } employeeArray.push("Return"); inquirer .prompt([ { type: "list", name: "employeeArray", message: "Select an employee to return", choices: employeeArray, }, ]) .then((answer) => { allDepartment(); }); } }); }; // Returns all the roles const viewRoles = async () => { let role = []; const roleList = await Role.findAll({ raw: true, }); for (i = 0; i < roleList.length; i++) { role.push(roleList[i].title); } inquirer .prompt([ { type: "list", message: "Here are all the roles, click one to go back", name: "allRoles", choices: role, }, ]) .then((answer) => { start(); }); }; // Add a role to the list of roles const addRole = async () => { let departments = []; const departemntList = await Department.findAll({ raw: true, }); for (i = 0; i < departemntList.length; i++) { departments.push(departemntList[i].name); } inquirer .prompt([ { type: "input", message: "What is the name of the role you want to add?", name: "roleName", }, { type: "input", message: "What is the salary of the role you want to add?", name: "roleSalary", }, { type: "list", message: "What is the department of the role you want to add?", name: "roleDepartment", choices: departments, }, ]) .then(async (answer) => { departmentName = answer.roleDepartment; // Get the role department by name so we can get that id const departments = await Department.findAll({ where: { name: departmentName, }, raw: true, }); // Create the new role await Role.create({ title: answer.roleName, salary: answer.roleSalary, department_id: departments[0].id, }); console.log("Role has been created"); start(); }); }; // Remove a role from the list const removeRole = async () => { let roleList = []; const role = await Role.findAll({ raw: true, }); for (i = 0; i < role.length; i++) { roleList.push(role[i].title); } roleList.push("Go Back To Main Menu"); inquirer .prompt([ { type: "list", message: "What is the name of the role you want to delete?", name: "roleChoice", choices: roleList, }, ]) .then(async (answer) => { // Handle a return option to go back to the main menu if (answer.roleChoice === "Go Back To Main Menu") { start(); } else { let roleName = answer.roleChoice; // Destroys selected role await Role.destroy({ where: { title: roleName, }, }); console.log("Role has been Deleted"); start(); } }); }; // Add a department to the list of departments const addDepartment = async () => { inquirer .prompt([ { type: "input", message: "What is the name of the department you want to add?", name: "newDepartment", }, ]) .then(async (answer) => { let departmentName = answer.newDepartment; await Department.create({ name: departmentName, }); console.log("Department has been created"); start(); }); }; // Delete a department from the list const removeDepartment = async () => { let departmentList = []; const department = await Department.findAll({ raw: true, }); for (i = 0; i < department.length; i++) { departmentList.push(department[i].name); } departmentList.push("Return To Main Menu"); inquirer .prompt([ { type: "list", message: "What is the name of the department you want to delete?", name: "department", choices: departmentList, }, ]) .then(async (answer) => { let departmentName = answer.department; if (departmentName === "Return To Main Menu") { start(); } else { // Check to see if there are any roles under this department const chosenDepartment = await Department.findAll({ where: { name: departmentName, }, raw: true, }); // Return any roles that might exist in this department const rolesInDepartment = await Role.findAll({ where: { department_id: chosenDepartment[0].id, }, raw: true, }); console.log(rolesInDepartment); // Check to see if they align if (rolesInDepartment.length === 0) { await Department.destroy({ where: { name: departmentName, }, }); console.log("Department has been Deleted"); start(); } else { console.log("[YOU MUST DELETE ANY ROLES IN THIS DEPARTMENT FIRST]"); removeDepartment(); } } }); }; // Adds an employee and gives options as to which roles and manager they should have const addEmployee = async () => { let managerList = []; let roleList = []; // Get the managers const manager = await Employee.findAll({ where: { manager_id: null, }, raw: true, }); for (i = 0; i < manager.length; i++) { managerList.push(manager[i].first_name); } managerList.push("They are a manager"); // Get all the roles const role = await Role.findAll({ raw: true, }); for (i = 0; i < role.length; i++) { roleList.push(role[i].title); } inquirer .prompt([ { type: "input", name: "employeeName", message: "What is the employee's first name?", }, { type: "input", name: "employeeLast", message: "What is the employee's last name?", }, { type: "list", name: "employeeRole", message: "What is the employee's role?", choices: roleList, }, { type: "list", name: "employeeManager", message: "Who is the employee's manager?", choices: managerList, }, ]) .then(async (answer) => { firstName = answer.employeeName; lastName = answer.employeeLast; employeRole = answer.employeeRole; managerName = answer.employeeManager; // Determine if the employee is a manager or not if (managerName === "They are a manager") { let roleID = await Role.findAll({ where: { title: role, }, raw: true, }); // Create new manager await Employee.create({ first_name: firstName, last_name: lastName, role_id: roleID[0].id, manager_id: null, }); start(); } else { // If the employee is not a manager get the employee manager let managerID = await Employee.findAll({ where: { first_name: managerName, manager_id: null, }, raw: true, }); // Get the role ID let roleID = await Role.findAll({ where: { title: employeRole, }, raw: true, }); // Create the new employee await Employee.create({ first_name: firstName, last_name: lastName, role_id: roleID[0].id, manager_id: managerID[0].id, }); start(); } }); }; // Code to remove an employee from the list const removeEmployee = async () => { let employeeList = []; const employee = await Employee.findAll({ raw: true, }); for (i = 0; i < employee.length; i++) { employeeList.push(employee[i].first_name); } employeeList.push("Return To Main Menu"); inquirer .prompt([ { type: "list", name: "removeQuestion", message: "What employee do you want to remove?", choices: employeeList, }, ]) .then(async (answer) => { if (answer.removeQuestion === "Return To Main Menu") { start(); } else { // Check to see if the employee you are deleting is managing other employees // Get the employee selected const employeeToDelete = await Employee.findAll({ where: { first_name: answer.removeQuestion, }, raw: true, }); // Check to see if anyone is being managed by them const suboordinates = await Employee.findAll({ where: { manager_id: employeeToDelete[0].id, }, raw: true, }); if (suboordinates.length !== 0) { console.log("[YOU MUST DELETE EMPLOYEES UNDER THIS MANAGER FIRST]"); removeEmployee(); } else { await Employee.destroy({ where: { first_name: answer.removeQuestion, }, }); console.log("Employee has been removed from the list."); start(); } } }); }; const updateRole = async () => { let employeeList = []; let roleList = []; // Get all the employees const employee = await Employee.findAll({ raw: true, }); // Go through and get all the names and push to array for (i = 0; i < employee.length; i++) { employeeList.push(employee[i].first_name); } // Get all the roles const role = await Role.findAll({ raw: true, }); // Go through and get all the titles and push to array for (i = 0; i < role.length; i++) { roleList.push(role[i].title); } inquirer .prompt([ { type: "list", name: "employeeChoice", message: "What employee's role do you want to update?", choices: employeeList, }, { type: "list", name: "roleUpdate", message: "What is the employee's role?", choices: roleList, }, ]) .then(async (answer) => { // Get the employee based on the choice let selected = await Employee.findAll({ where: { first_name: answer.employeeChoice, }, raw: true, }); // Find the role based on the role chosen let theRole = await Role.findAll({ where: { title: answer.roleUpdate, }, raw: true, }); // Update the employee Employee.update( { role_id: theRole[0].id }, { where: { first_name: selected[0].first_name, }, } ); console.log("Employee role has been updated."); start(); }); }; const updateManager = async () => { let employeeList = []; const employee = await Employee.findAll({ raw: true, }); for (i = 0; i < employee.length; i++) { employeeList.push(employee[i].first_name); } let managerList = []; const manager = await Employee.findAll({ where: { manager_id: null, }, raw: true, }); for (i = 0; i < manager.length; i++) { managerList.push(manager[i].first_name); } managerList.push("Return"); inquirer .prompt([ { type: "list", name: "employeeChoice", message: "What employee's manager do you want to update?", choices: employeeList, }, { type: "list", name: "managerUpdate", message: "What is the manager's name?", choices: managerList, }, ]) .then(async (answer) => { if (answer.managerUpdate === "Return") { start(); } let selected = await Employee.findAll({ where: { first_name: answer.employeeChoice, }, raw: true, }); console.log(selected[0]); let theManager = await Employee.findAll({ where: { first_name: answer.managerUpdate, }, raw: true, }); console.log(theManager[0]); Employee.update( { manager_id: theManager[0].id }, { where: { first_name: selected[0].first_name, }, } ); console.log("Employee role has been updated."); start(); }); }; module.exports = { start };
import inquirer from 'inquirer'; import prettyjson from 'prettyjson'; import emoji from 'node-emoji'; import chalk from 'chalk'; import { validateNumber } from '../utils'; export default async sqs => { const DEFAULT_MAX_NUMBER_OF_MESSAGES = 1; const DEFAULT_WAIT_TIME_SECONDS = 10; const DEFAULT_VISIBILITY_TIMEOUT = 2; const questions = [ { type: 'input', name: 'MaxNumberOfMessages', message: "What's the maximum number of messages you want to return? (MaxNumberOfMessages)", default: DEFAULT_MAX_NUMBER_OF_MESSAGES, validate: validateNumber, }, { type: 'input', name: 'VisibilityTimeout', message: 'How long do you want your messages to invisible? (VisibilityTimeout) seconds', default: DEFAULT_VISIBILITY_TIMEOUT, validate: validateNumber, }, { type: 'input', name: 'WaitTimeSeconds', message: 'How long do you want to wait for polling messages? (WaitTimeSeconds) seconds', default: DEFAULT_WAIT_TIME_SECONDS, validate: validateNumber, }, ]; const answer = await inquirer.prompt(questions); const result = await sqs.receiveMessage({ MaxNumberOfMessages: Number(answer.MaxNumberOfMessages), VisibilityTimeout: Number(answer.VisibilityTimeout), WaitTimeSeconds: Number(answer.WaitTimeSeconds), }); const { Messages } = result; if (Messages) { console.log('Poll Messages Success:\n', prettyjson.render(Messages)); console.log( emoji.emojify( `:white_check_mark: ${chalk.green.bold(`Total Messages: ${Messages.length}`)}`, ), ); } else { console.log(emoji.emojify(`:exclamation: ${chalk.bold.red('Sorry. No message available')}`)); } return result; };
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const UserSchema = new Schema({ email: { type: String, trim: true, unique: true, required: "Please enter an email", }, password: { type: String, trim: true, required: "Please enter a password" }, firstName: { type: String, trim: true, default: "" }, lastName: { type: String, trim: true, default: "" }, profileImageUrl: {type: String, default: "https://res.cloudinary.com/djou7v3ho/image/upload/v1614532245/Avatar-removebg-preview_1_g04ftj.png"}, // recording trips on users and trips may be redundant trips: [{ type: Schema.Types.ObjectId, ref: "Trip" }], expenses: [{ type: Schema.Types.ObjectId, ref: "Expense" }], }); const User = mongoose.model("User", UserSchema); module.exports = User;
/** * @ngdoc service * @name refigureShared.services:errorInterceptor * @description * HttpProvider Error interceptor */ (function (angular) { 'use strict'; angular .module('refigureShared') .factory('errorInterceptor', errorInterceptor); errorInterceptor.$inject = [ '$q', '$log', '$injector' ]; function errorInterceptor($q, $log, $injector) { var exports = { response: response, responseError: responseError }; return exports; //////////////////////////// function _error(res, defErr) { var error = utils.get(res, ['data', 'error'], defErr), message = utils.get(res, ['data', 'message'], 'Network error occurred.'); if (error) { utils.set(res, ['data', 'error'], error); utils.set(res, ['data', 'message'], message); } return { error: error, message: message }; } function response(res) { var error = _error(res, 0); if (error.error) { if (intercept(res, error)) { showError(error); } return $q.reject(res); } return res; } function responseError(res) { var error = _error(res, -1); if (intercept(res, error)) { showError(error); } return $q.reject(res); } function intercept(res, error) { var url = utils.get(res, ['config', 'url']), noIntercept = utils.get(res, ['config', 'noIntercept']); if (noIntercept) { return false; } return !validError(error); } function validError(error) { return false; } function showError(error) { var modalDialog = $injector.get('modalDialog'); return modalDialog.error(error.message); } } })(window.angular);
const dropContainer = document.getElementById('drop-zone'); const fileInput = document.getElementById('file-input'); fileInput.onchange = function (e) { onFileChange(e); }; dropContainer.ondragover = dropContainer.ondragenter = function (evt) { evt.preventDefault(); }; function onDrop(evt) { // pretty simple -- but not for IE :( fileInput.files = evt.dataTransfer.files; // If you want to use some of the dropped files const dT = new DataTransfer(); dT.items.add(evt.dataTransfer.files[0]); fileInput.files = dT.files; // Create a new 'change' event const event = new Event('change'); // Dispatch it. fileInput.dispatchEvent(event); evt.preventDefault(); } dropContainer.ondrop = function (evt) { onDrop(evt); }; window.addEventListener( 'dragover', function (e) { e = e || event; e.preventDefault(); document.body.classList.add('dragging'); }, false ); window.addEventListener( 'drop', function (e) { e = e || event; e.preventDefault(); onDrop(e); document.body.classList.remove('dragging'); }, false ); window.addEventListener('mouseout', function (e) { document.body.classList.remove('dragging'); }); function onFileChange(e) { var reader = new FileReader(); reader.onload = function (event) { img = new Image(); img.onload = function () { if (img.width < 2500 && img.height < 2500) { canvasScale = 1; } else { canvasScale = Math.min(2500 / img.width, 2500 / img.height); } canvas.width = tempCanvas.width = holderCanvas.width = rotationCanvas.width = blurredCanvas.width = img.width * canvasScale; canvas.height = tempCanvas.height = holderCanvas.height = rotationCanvas.height = blurredCanvas.height = img.height * canvasScale; ctx.drawImage( img, 0, 0, img.width * canvasScale, img.height * canvasScale ); rotationCtx.drawImage( img, 0, 0, img.width * canvasScale, img.height * canvasScale ); var biggerDimension = Math.max(canvas.width, canvas.height); brushSize = (50 * biggerDimension) / brushAdjustment; brushSizeDiv.value = 50; blurAmount = scale(brushSize, 10, 157, 20, 150); blurAmountDiv.value = blurAmount; setCursor(); }; img.src = event.target.result; }; reader.readAsDataURL(e.target.files[0]); filename = document.getElementById('file-input').value; var exifInformationDiv = document.getElementById('exifInformationHolder'); var imageScrubberInfo = document.getElementById('imageScrubberInfo'); imageScrubberInfo.style.display = 'none'; exifInformationDiv.style.display = 'block'; var file = e.target.files[0]; if (file && file.name) { EXIF.getData(file, function () { var exifData = JSON.stringify(this.exifdata, null, 4); if (exifData) { if (exifData.toString() == '{}') { exifInformationHolder.innerHTML = "<center>No EXIF data found in image '" + file.name + "'.<br><br></center>"; var btn = document.createElement('BUTTON'); btn.id = 'continueButton'; btn.innerHTML = 'Continue to edit image'; btn.onclick = goToBlur; exifInformationHolder.appendChild(btn); } else { var exifScrollDiv = document.createElement('div'); exifScrollDiv.id = 'exifScrollDiv'; exifScrollDiv.innerHTML = file.name + '<pre>' + exifData + '</pre>'; exifInformationHolder.innerHTML = 'Exif Data:<br><br>'; exifInformationHolder.appendChild(exifScrollDiv); var btn = document.createElement('BUTTON'); btn.id = 'continueButtonExif'; btn.innerHTML = 'Scrub Exif Data'; btn.onclick = scrubData; exifInformationHolder.appendChild(btn); } } }); } }
export const getApps = jest.fn().mockReturnValue([]); export const initializeApp = jest.fn();
$(function() { $('.post-item-card').click(function(e) { window.location.href = $(this).attr('post-path'); }); })
(function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports", "../release/go", "./PolylineLinkingTool"], factory); } })(function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /* * Copyright (C) 1998-2017 by Northwoods Software Corporation. All Rights Reserved. */ var go = require("../release/go"); var PolylineLinkingTool_1 = require("./PolylineLinkingTool"); var myDiagram = null; function init() { if (typeof window["goSamples"] === 'function') window["goSamples"](); // init for these samples -- you don't need to call this var $ = go.GraphObject.make; myDiagram = $(go.Diagram, "myDiagramDiv", { initialContentAlignment: go.Spot.Center }); // install custom linking tool, defined in PolylineLinkingTool.js var tool = new PolylineLinkingTool_1.PolylineLinkingTool(); //tool.temporaryLink.routing = go.Link.Orthogonal; // optional, but need to keep link template in sync, below myDiagram.toolManager.linkingTool = tool; myDiagram.nodeTemplate = $(go.Node, "Spot", { locationSpot: go.Spot.Center }, new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify), $(go.Shape, { width: 100, height: 100, fill: "lightgray", portId: "", cursor: "pointer", fromLinkable: true, fromLinkableSelfNode: true, fromLinkableDuplicates: true, toLinkable: true, toLinkableSelfNode: true, toLinkableDuplicates: true // optional }, new go.Binding("fill")), $(go.Shape, { width: 70, height: 70, fill: "transparent", stroke: null }), $(go.TextBlock, new go.Binding("text"))); myDiagram.linkTemplate = $(go.Link, { reshapable: true, resegmentable: true }, //{ routing: go.Link.Orthogonal }, // optional, but need to keep LinkingTool.temporaryLink in sync, above { adjusting: go.Link.Stretch }, // optional new go.Binding("points", "points").makeTwoWay(), $(go.Shape, { strokeWidth: 1.5 }), $(go.Shape, { toArrow: "OpenTriangle" })); load(); // load a simple diagram from the textarea } exports.init = init; // save a model to and load a model from Json text, displayed below the Diagram function save() { var str = myDiagram.model.toJson(); document.getElementById("mySavedModel").value = str; } exports.save = save; function load() { var str = document.getElementById("mySavedModel").value; myDiagram.model = go.Model.fromJson(str); myDiagram.model.undoManager.isEnabled = true; } exports.load = load; });
module.exports = { eslint: { // Warning: This allows production builds to successfully complete even if // your project has ESLint errors. ignoreDuringBuilds: true, }, reactStrictMode: true, trailingSlash: true, productionBrowserSourceMaps: true, webpack: (config, _options) => { config.module.rules.push({ test: /\.cdc/, type: "asset/source", }) return config }, }
Ext.gesture.Drag = Ext.extend(Ext.gesture.Touch, { handles: ['dragstart', 'drag', 'dragend'], dragThreshold: 5, direction: 'both', horizontal: false, vertical: false, constructor: function() { Ext.gesture.Drag.superclass.constructor.apply(this, arguments); if (this.direction == 'both') { this.horizontal = true; this.vertical = true; } else if (this.direction == 'horizontal') { this.horizontal = true; } else { this.vertical = true; } return this; }, onTouchStart: function(e, touch) { this.startX = this.previousX = touch.pageX; this.startY = this.previousY = touch.pageY; this.startTime = this.previousTime = e.timeStamp; this.dragging = false; }, onTouchMove: function(e, touch) { if (this.isLocked('drag')) { return; } var info = this.getInfo(touch); if (!this.dragging) { if (this.isDragging(info) && this.fire('dragstart', e, info)) { this.dragging = true; this.lock('drag', 'dragstart', 'dragend'); this.fire('drag', e, info); } } else { this.fire('drag', e, info); } }, onTouchEnd: function(e) { if (this.dragging) { this.fire('dragend', e, this.lastInfo); } this.dragging = false; }, isDragging: function(info) { return ( (this.horizontal && info.absDeltaX >= this.dragThreshold) || (this.vertical && info.absDeltaY >= this.dragThreshold) ); }, /** * Method to determine whether this Sortable is currently disabled. * @return {Boolean} the disabled state of this Sortable. */ isVertical: function() { return this.vertical; }, /** * Method to determine whether this Sortable is currently sorting. * @return {Boolean} the sorting state of this Sortable. */ isHorizontal: function() { return this.horizontal; } }); Ext.regGesture('drag', Ext.gesture.Drag);
import { v4 as uuidv4 } from 'uuid' const validEvents = { identify: 'identify', group: 'group', session: 'session', pageview: 'pageview', screenview: 'screenview', action: 'action', } export default class Event { /** * * @param {string} event - Event type to create * @param {Object} config - Event config * */ constructor(type, config = {}) { this.eid = uuidv4() this.tid = config.trackingId || store.get(tid) this.sid = '' const storedSID = store.get(sid) if (storedSID) { this.sid = storedSID this.news = false } if (config.sessionId && config.sessionId !== this.sid) { this.sid = config.sessionId this.news = true store.set(sid, this.sid) } if (this.sid === '') { this.sid = uuidv4() this.news = true } this.uid = config.userId || store.get(uid) || '' this.gid = config.groupId || store.get(gid) || '' this.cid = config.deviceId || store.get(cid) || '' this.e = type } setTrackingId(id) { this.tid = id } setSessionId(id) { this.sid = id } setUserId(id) { this.uid = id } setGroupId(id) { this.gid = id } setDeviceId(id) { this.cid = id } }
// 검색어 enter $("#fullTextSearch").keyup(function(e) { if(e.keyCode == 13) { if(fullTextSearchCheck()) { fullTextSearch(); } } }); // 검색 버튼을 눌렀을때 $("#fullTextSearchButton").click(function() { if(fullTextSearchCheck()) { fullTextSearch(); } }); // 닫기 버튼 클릭 $('#districtSearchCloseButton').click(function() { $('#districtSearchResultContent').hide(); }); // 지도 클릭 $('#magoContainer').click(function(e) { if ($("#districtSearchResultContent").is(':visible')) { $("#districtSearchResultContent").hide(); } }); // 입력 체크 function fullTextSearchCheck() { if($("#fullTextSearch").val() === null || $("#fullTextSearch").val().trim() === "") { alert(JS_MESSAGE["search.enter.word"]); $("#fullTextSearch").focus(); return false; } if($("#fullTextSearch").val().trim().length === 1) { alert(JS_MESSAGE["search.required.word"]); $("#fullTextSearch").focus(); return false; } if ($("#districtSelectContent").is(':visible')) { $("#districtSelectContent").hide(); } return true; } var fullTextSearchFlag = true; function fullTextSearch() { if(fullTextSearchFlag) { fullTextSearchFlag = false; //if($('#searchContent').css("display") ==='none') $(".search").click(); districtSearch(null); } else { alert(JS_MESSAGE["searching"]); return; } } // 검색창 클릭시 메뉴 제어 function showSearchMenu() { $("#searchMenu").toggleClass("on"); $('#searchContent').toggle(true); $('#contentsWrap').toggle(true); // $("#newAddressSearchList").height(200); } // 행정구역 검색 function districtSearch(pageNo) { event.stopPropagation(); var info = "fullTextSearch=" + $("#fullTextSearch").val();; info += "&searchKey=newAddress"; if(pageNo !== null) { info = info + "&pageNo=" + pageNo; } $.ajax({ url: "../searchmap/district", type: "GET", data: info, dataType: "json", success: function(msg){ if(msg.statusCode <= 200) { msg.pagination.pageList = []; var start = msg.pagination.startPage; var end = msg.pagination.endPage; for(i = start; i <= end; i++) { msg.pagination.pageList.push(i); } //핸들바 템플릿 컴파일 var template = Handlebars.compile($("#districtSearchResultSource").html()); var pageTemplate = Handlebars.compile($("#districtPaginationSource").html()); $("#districtSearchResultDHTML").html("").append(template(msg)) $("#districtPaginationDHTML").html("").append(pageTemplate(msg)); $('#districtSearchResultContent').show(); fullTextSearchFlag = true; } else { alert(JS_MESSAGE[msg.errorCode]); console.log("---- " + msg.message); } }, error:function(request,status,error) { //console.log(" code : " + request.status + "\n" + ", message : " + request.responseText + "\n" + ", error : " + error); alert(" code : " + request.status + "\n" + ", message : " + request.responseText + "\n" + ", error : " + error); console.log("new address error ..... searchTypeCount = " + searchTypeCount); } }); }
import React, { Fragment } from 'react'; import PropTypes from 'prop-types'; import { includes } from 'lodash'; import { FormattedDate, FormattedMessage } from 'react-intl'; import expenseStatus from '../../lib/constants/expense-status'; import expenseTypes from '../../lib/constants/expenseTypes'; import { PayoutMethodType } from '../../lib/constants/payout-method'; import Avatar from '../Avatar'; import Container from '../Container'; import FormattedMoneyAmount, { DEFAULT_AMOUNT_STYLES } from '../FormattedMoneyAmount'; import { Box, Flex } from '../Grid'; import HTMLContent from '../HTMLContent'; import LinkCollective from '../LinkCollective'; import LoadingPlaceholder from '../LoadingPlaceholder'; import StyledCard from '../StyledCard'; import StyledHr from '../StyledHr'; import { H4, P, Span } from '../Text'; import UploadedFilePreview from '../UploadedFilePreview'; import ExpenseItemsTotalAmount from './ExpenseItemsTotalAmount'; import ExpensePayeeDetails from './ExpensePayeeDetails'; import ExpenseStatusTag from './ExpenseStatusTag'; import ExpenseTags from './ExpenseTags'; import ProcessExpenseButtons, { hasProcessButtons } from './ProcessExpenseButtons'; const CreatedByUserLink = ({ account }) => { return ( <LinkCollective collective={account}> <Span color="black.800" fontWeight={500} textDecoration="none"> {account ? account.name : <FormattedMessage id="profile.incognito" defaultMessage="Incognito" />} </Span> </LinkCollective> ); }; CreatedByUserLink.propTypes = { account: PropTypes.object, }; /** * Last step of the create expense flow, shows the summary of the expense with * the ability to submit it. */ const ExpenseSummary = ({ expense, collective, host, isLoading, isLoadingLoggedInUser, permissions, isEditing, borderless, ...props }) => { const isReceipt = expense?.type === expenseTypes.RECEIPT; const isFundingRequest = expense?.type === expenseTypes.FUNDING_REQUEST; const existsInAPI = expense && (expense.id || expense.legacyId); const showProcessButtons = !isEditing && existsInAPI && collective && hasProcessButtons(permissions); const createdByAccount = expense?.requestedByAccount || expense?.createdByAccount || {}; return ( <StyledCard p={borderless ? 0 : [16, 24, 32]} borderStyle={borderless ? 'none' : 'solid'} {...props}> <Flex flexDirection={['column-reverse', 'row']} alignItems={['flex-start', 'center']} justifyContent="space-between" > <H4 mb={2} mr={2} fontWeight="500"> {isLoading ? <LoadingPlaceholder height={32} minWidth={250} /> : expense.description} </H4> {expense?.status && ( <ExpenseStatusTag display="block" status={expense.status} letterSpacing="0.8px" fontWeight="600" fontSize="10px" showTaxFormTag={includes(expense.requiredLegalDocuments, 'US_TAX_FORM')} showTaxFormMsg={expense.payee.isAdmin} /> )} </Flex> <ExpenseTags expense={expense} isLoading={isLoading} /> <Flex alignItems="center" mt={3}> {isLoading ? ( <LoadingPlaceholder height={24} width={200} /> ) : ( <React.Fragment> <LinkCollective collective={createdByAccount}> <Avatar collective={createdByAccount} size={24} /> </LinkCollective> <P ml={2} fontSize="12px" color="black.600"> {expense.requestedByAccount ? ( <FormattedMessage id="Expense.RequestedByOnDate" defaultMessage="Requested by {name} on {date, date, long}" values={{ name: <CreatedByUserLink account={createdByAccount} />, date: new Date(expense.createdAt), }} /> ) : expense.createdAt ? ( <FormattedMessage id="Expense.SubmittedByOnDate" defaultMessage="Submitted by {name} on {date, date, long}" values={{ name: <CreatedByUserLink account={createdByAccount} />, date: new Date(expense.createdAt) }} /> ) : ( <FormattedMessage id="Expense.SubmittedBy" defaultMessage="Submitted by {name}" values={{ name: <CreatedByUserLink account={createdByAccount} /> }} /> )} </P> </React.Fragment> )} </Flex> {isFundingRequest && expense.longDescription && ( <Fragment> <Flex alignItems="center" mt={4}> <Span fontWeight="bold" fontSize="16px"> <FormattedMessage id="Expense.RequestDescription" defaultMessage="Request Description" /> </Span> <StyledHr flex="1 1" borderColor="black.300" ml={2} /> </Flex> <P mt={4}>{expense.longDescription}</P> </Fragment> )} <Flex my={4} alignItems="center"> {isLoading ? ( <LoadingPlaceholder height={20} maxWidth={150} /> ) : ( <Span fontWeight="bold" fontSize="16px"> {isReceipt ? ( <FormattedMessage id="Expense.AttachedReceipts" defaultMessage="Attached receipts" /> ) : isFundingRequest ? ( <FormattedMessage id="Expense.RequestDetails" defaultMessage="Request Details" /> ) : ( <FormattedMessage id="Expense.InvoiceItems" defaultMessage="Invoice items" /> )} </Span> )} <StyledHr flex="1 1" borderColor="black.300" ml={2} /> </Flex> {isLoading ? ( <LoadingPlaceholder height={68} mb={3} /> ) : ( <div data-cy="expense-summary-items"> {(expense.items.length > 0 ? expense.items : expense.draft?.items || []).map(attachment => ( <React.Fragment key={attachment.id}> <Flex my={24} flexWrap="wrap"> {(isReceipt || attachment.url) && ( <Box mr={3} mb={3} width={['100%', 'auto']}> <UploadedFilePreview url={attachment.url} isLoading={isLoading || isLoadingLoggedInUser} isPrivate={!attachment.url && !isLoading} size={[640, 48]} maxHeight={48} /> </Box> )} <Flex justifyContent="space-between" alignItems="baseline" flex="1"> <Flex flexDirection="column" justifyContent="center" flexGrow="1"> {attachment.description ? ( isFundingRequest ? ( <HTMLContent content={attachment.description} fontSize="12px" data-cy="comment-body" sanitize collapsable color="black.900" fontWeight="500" /> ) : ( <Span as="div" color="black.900" fontWeight="500"> {attachment.description} </Span> ) ) : ( <Span color="black.500" fontStyle="italic"> <FormattedMessage id="NoDescription" defaultMessage="No description provided" /> </Span> )} {!isFundingRequest && ( <Span mt={1} fontSize="12px" color="black.500"> <FormattedMessage id="withColon" defaultMessage="{item}:" values={{ item: <FormattedMessage id="expense.incurredAt" defaultMessage="Date" />, }} />{' '} <FormattedDate value={attachment.incurredAt} /> </Span> )} </Flex> <P fontSize={15} color="black.600" mt={2} textAlign="right" ml={3}> <FormattedMoneyAmount amount={attachment.amount} currency={expense.currency} amountStyles={{ ...DEFAULT_AMOUNT_STYLES, fontWeight: '500' }} precision={2} /> </P> </Flex> </Flex> <StyledHr borderStyle="dotted" /> </React.Fragment> ))} </div> )} <Flex justifyContent="flex-end" mt={4} mb={2}> <Flex alignItems="center"> <Container fontSize="12px" fontWeight="500" mr={3} whiteSpace="nowrap"> <FormattedMessage id="ExpenseFormAttachments.TotalAmount" defaultMessage="Total amount:" /> </Container> {isLoading ? ( <LoadingPlaceholder height={18} width={100} /> ) : ( <ExpenseItemsTotalAmount currency={expense.currency} items={expense.items} /> )} </Flex> </Flex> <ExpensePayeeDetails isLoading={isLoading} host={host} expense={expense} collective={collective} isDraft={!isEditing && expense?.status == expenseStatus.DRAFT} /> {showProcessButtons && ( <Container borderTop="1px solid #DCDEE0" mt={4} pt={12}> <Flex flexWrap="wrap" justifyContent="flex-end"> <ProcessExpenseButtons expense={expense} permissions={permissions} collective={collective} host={host} /> </Flex> </Container> )} </StyledCard> ); }; ExpenseSummary.propTypes = { /** Set this to true if the expense is not loaded yet */ isLoading: PropTypes.bool, /** Set this to true if the logged in user is currenltly loading */ isLoadingLoggedInUser: PropTypes.bool, host: PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, slug: PropTypes.string.isRequired, type: PropTypes.string.isRequired, website: PropTypes.string, location: PropTypes.shape({ address: PropTypes.string, country: PropTypes.string, }), }), /** Must be provided if isLoading is false */ expense: PropTypes.shape({ id: PropTypes.string, legacyId: PropTypes.number, description: PropTypes.string.isRequired, longDescription: PropTypes.string, currency: PropTypes.string.isRequired, invoiceInfo: PropTypes.string, createdAt: PropTypes.string, status: PropTypes.oneOf(Object.values(expenseStatus)), type: PropTypes.oneOf(Object.values(expenseTypes)).isRequired, tags: PropTypes.arrayOf(PropTypes.string), requiredLegalDocuments: PropTypes.arrayOf(PropTypes.string), items: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string, incurredAt: PropTypes.string, description: PropTypes.string, amount: PropTypes.number.isRequired, url: PropTypes.string, }).isRequired, ).isRequired, payee: PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, slug: PropTypes.string.isRequired, type: PropTypes.string.isRequired, isAdmin: PropTypes.bool, }).isRequired, payeeLocation: PropTypes.shape({ address: PropTypes.string, country: PropTypes.string, }), createdByAccount: PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, slug: PropTypes.string.isRequired, type: PropTypes.string.isRequired, }), requestedByAccount: PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, slug: PropTypes.string.isRequired, type: PropTypes.string.isRequired, }), payoutMethod: PropTypes.shape({ id: PropTypes.string, type: PropTypes.oneOf(Object.values(PayoutMethodType)), data: PropTypes.object, }), draft: PropTypes.shape({ items: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string, incurredAt: PropTypes.string, description: PropTypes.string, amount: PropTypes.number.isRequired, url: PropTypes.string, }), ), }), }), /** Wether or not this is being displayed for an edited Expense */ isEditing: PropTypes.bool, /** The account where the expense has been submitted, required to display the process actions */ collective: PropTypes.object, /** To know which process buttons to display (if any) */ permissions: PropTypes.object, /** Disable border and paiding in styled card, usefull for modals */ borderless: PropTypes.bool, }; export default ExpenseSummary;
// LICENSE@@@ // // Copyright (c) 2009-2013 LG Electronics, Inc. // // 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. // // @@@LICENSE /*jslint white: true, onevar: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, nomen: false, maxerr: 500 */ /*global */ var ArrayUtil = { pushAll: function (dst, src) { var i; for (i = 0; i < src.length; i += 1) { dst.push(src[i]); } return dst; }, // Remove the first occurance of toRemove from // the src array. removeValue: function (src, toRemove) { var i, found = false; for (i = 0; i < src.length; i += 1) { if (src[i] === toRemove) { src.splice(i, 1); found = true; return found; } } return found; }, copyOfArray: function (src) { var toReturn = [], i; if (src) { for (i = 0; i < src.length; i += 1) { toReturn[i] = src[i]; } } return toReturn; } };
import React, { Component } from "react" import SEO from "components/seo" import Header from "components/header" import { StickyContainer } from "react-sticky" import UnAuthResultWrapper from "../../../components/trip/unauth-result" import { connect } from "react-redux" import omit from "../../../../node_modules/lodash/omit" import isEmpty from "../../../../node_modules/lodash/isEmpty" import { extractTerminalName } from "../../../lib" import { navigate } from "gatsby" import { setPassengers } from "../../../store/actions/trips" import { CreateUser } from "../../../store/actions/common" import { unAuthBookTripRequest, fetchUnAuthBookingsRequest, } from "../../../store/actions/bookings" import { toast } from "react-toastify" import Grid from "@material-ui/core/Grid" import withStyles from "@material-ui/core/styles/withStyles" import BookSide from "../../../components/trip/book-side" import { UnAuthBookingFooter, UnAuthCompleteBookingContent, } from "components/trip" import UnAuthPassengerDetails from "../../../components/trip/unauth-passenger-details" const style = theme => ({ grid: { position: "relative", top: "8rem", [theme.breakpoints.down("sm")]: { margin: "0", }, }, side: { marginLeft: "1rem", [theme.breakpoints.down("sm")]: { width: "95%", marginLeft: "1rem", marginRight: ".5rem", marginBottom: "1rem", }, }, }) class UnAuthPassenger extends Component { constructor(props) { super(props) this.state = { stage: 0, paymentMethod: "card", breadCrumbs: ["Passengers Details", "Complete Booking"], bookings: [], numberOfTravellers: 0, type: "", trip: {}, email: null, fullName: null, details: {}, open: false, error: "", } } componentDidMount() { const { searchData: { departureTerminalId }, } = this.props this.setState({ stage: 0 }) this._prepStateFromProps() if (!departureTerminalId.length) { navigate("/") return null } } _prepStateFromProps = () => { const { outgoingTrip, returnTrip, searchData: { bookingType, ...searchData }, terminals, serviceCharge, } = this.props const outgoingBooking = omit(outgoingTrip, [ "departureTimestamp", "price", ]) || { seats: [] } let numberOfTravellers = outgoingTrip.seats.length const bookings = [outgoingBooking] const trip = { serviceCharge, ticketsCount: numberOfTravellers, ticketsCost: outgoingTrip.seats.length * Number(outgoingTrip.price), outgoing: { seatsCount: outgoingTrip.seats.length, price: outgoingTrip.seats.length * Number(outgoingTrip.price), departureTimestamp: outgoingTrip.departureTimestamp, departureTerminal: extractTerminalName( terminals, searchData.arrivalTerminalId ), arrivalTerminal: extractTerminalName( terminals, searchData.departureTerminalId ), }, } if (bookingType === "round_trip") { const returnBooking = omit(returnTrip, ["departureTimestamp", "price"]) trip.return = { seatsCount: returnTrip.seats.length, price: returnTrip.seats.length * Number(returnTrip.price), departureTimestamp: returnTrip.departureTimestamp, arrivalTerminal: extractTerminalName( terminals, searchData.arrivalTerminalId ), departureTerminal: extractTerminalName( terminals, searchData.departureTerminalId ), } trip.ticketsCount = numberOfTravellers * 2 trip.ticketsCost = trip.ticketsCost + returnTrip.seats.length * Number(returnTrip.price) bookings.push(returnBooking) } return this.setState({ bookings, numberOfTravellers, trip, type: bookingType, }) } _handleStateChange = (state, value) => { return this.setState({ [state]: value, }) } changeStage = stage => { return this._handleStateChange("stage", stage) } changePaymentMethod = method => { return this._handleStateChange("paymentMethod", method) } _handlePassengerDetails = async passengers => { const name = `${passengers[0].firstName} ${passengers[0].lastName}` let mail = passengers.map(item => item.email).join() let info = { ...passengers } this.setState({ email: mail, fullName: name, details: info, }) const Passengers = { name, email: passengers[0].email, address: passengers[0].address, phoneNumber: passengers[0].phoneNumber, gender: passengers[0].gender, ageBracket: "adult", booking: this.state.bookings, } const profile = { kinFullName: passengers[0].kinFullName, kinPhoneNumber: passengers[0].KinPhoneNumber, address: passengers[0].address, } await this.props.CreateUser(profile) await this.props.fetchUnAuthBookingsRequest(Passengers) } _handleBooking = async paymentResponse => { const { data, unAuthBookTripRequest, bookings: bookingsFromGlobalState, } = this.props const { bookings, numberOfTravellers, paymentMethod, type } = this.state if (bookingsFromGlobalState.loading) { return null } const requestBody = { passengers: [data], bookings, numberOfTravellers, type, paymentType: paymentMethod === "card" ? "online" : "offline", } console.log(requestBody) if (paymentResponse && paymentMethod === "card") { requestBody.paymentRef = paymentResponse.reference } try { const bookingResp = await unAuthBookTripRequest(requestBody) if (bookingResp) return navigate("/trip/book/unAuthcomplete") } catch (error) { toast.error( (error.response && error.response.data.message) || "Sorry, your booking was not successful" ) } } openModal = data => { if (data) { this.setState({ open: true }) } } _renderFooter = () => { const { breadCrumbs, stage, paymentMethod, trip, numberOfTravellers, } = this.state let { passengers, bookings } = this.props const paymentConfig = { publicKey: process.env.GATSBY_PAYSTACK_PUBLIC_KEY, email: this.props.data.email, amount: (trip.ticketsCost + trip.serviceCharge) * 100, channels: ["card"], } return ( <UnAuthBookingFooter paymentMethod={paymentMethod} makeBooking={this._handleBooking} paymentConfig={paymentConfig} payBtn={stage === breadCrumbs.length - 1} completeBookingBtn={numberOfTravellers === passengers.length} onCompleteBookingClick={() => this.changeStage(1)} loading={bookings.loading} details={this.state.details} open={this.state.open} error={this.state.error} /> ) } render() { const { breadCrumbs, stage, paymentMethod, trip, numberOfTravellers, } = this.state const { classes, data } = this.props return ( <StickyContainer> <SEO title={breadCrumbs[stage]} /> <Header /> <Grid container className={classes.grid}> <Grid item xs={12} md={5} className={classes.side}> {!isEmpty(trip) ? <BookSide trip={trip} /> : null} </Grid> <Grid item xs={12} md={5} className={classes.side}> {stage === 0 && ( <UnAuthPassengerDetails numberOfTravellers={numberOfTravellers} onDone={this._handlePassengerDetails} open={this.openModal} /> )} {stage === 1 && ( <UnAuthCompleteBookingContent paymentMethod={paymentMethod} changePaymentMethod={this.changePaymentMethod} passengers={data} /> )} </Grid> </Grid> <UnAuthResultWrapper footer={this._renderFooter()} /> </StickyContainer> ) } } const mapStateToProps = ({ bookings: { data, bookedTrip }, trips: { returnTrip, outgoingTrip, searchData, passengers }, terminals: { data: terminals }, settings: { serviceCharge }, bookings, }) => ({ outgoingTrip, returnTrip, searchData, terminals, passengers, bookings, serviceCharge, data, bookedTrip, }) export default connect(mapStateToProps, { setPassengers, unAuthBookTripRequest, fetchUnAuthBookingsRequest, CreateUser, })(withStyles(style)(UnAuthPassenger))
/** Source Code Line Manager Class This class takes some Source Code Adapter to construct its indexed collection of source code lines. This manager will command the Source Code Lines. Rules: - A Source Code Adapter must be passed in the constructor - Assumes existence of SourceCode class - Uses a Source Code Line Collection to hold source code lines */ function SourceCodeLineManager(adapter, line_factory, empty_collection) { // Uses a SourceCodeLineCollection to hold source code lines this.collection = empty_collection; // Take the passed adapter, and start pulling DOM nodes and indexes (line numbers) var source_nodes = adapter.getSourceNodes(); for (var i = 0; i < source_nodes.length; i++) { // i + 1: source code lines are not 0 indexed this.collection.set(i + 1, line_factory.build(source_nodes[i])); } } // Given a DOM node, see if it's one of the DOM nodes representing the source code, // and if so, return it's line number. If not, return -1. SourceCodeLineManager.prototype.getLineNumber = function (line_node) { return this.collection.getLineNumOfNode(line_node) + 1; }; // Return the Source Code Line at line_num SourceCodeLineManager.prototype.getLine = function (line_num) { return this.collection.get(line_num); };
'use strict' const nodemailer = require('nodemailer') const store = require('../src/componentes/users/store') const { config } = require('../config/config') const { unauthorized } = require('@hapi/boom') const jwt = require('jsonwebtoken') const AdminEmail = config.AdminEmail const emailpass = config.EmailPass async function sendRecovery (email) { const user = await store.findUser(email) if (!user) { console.error(unauthorized) } console.log(user.email) const payload = { sub: user.id, role: user.role } const token = jwt.sign(payload, config.sercret, {expiresIn: '15min'}) const link =`http://myfront.com/recovery?token=${token}` await store.recoveryPassword(user.id, token) const mail = { from: config.AdminEmail, // sender address to: `${user.email} `, // list of receivers subject: 'Email para recuperar la Password ✔', // Subject line text: 'Recupere su Password', // plain text body html: `<b>Cambiar Passwork => ${link} </b>` // html body } const rta = await this.sendMail(email) return rta } async function sendMail (infoMail) { const transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', secure: true, // true for 465, false for other ports port: 465, auth: { user: AdminEmail, pass: emailpass } }) await transporter.sendMail(infoMail) return { message: 'mail send' } } module.exports = { sendMail, sendRecovery }
(function() { 'use strict'; angular.module('todos') .service('TodoResources', TodoResources); TodoResources.$inject = ['TodoConsts']; function TodoResources(TodoConsts) { this.todosPath = TodoConsts.api.path.todos; this.todosParamNoCache = TodoConsts.api.param.noCache; } })();
/* bubbleChart creation function. Returns a function that will * instantiate a new bubble chart given a DOM element to display * it in and a dataset to visualize. * * Organization and style inspired by: * https://bost.ocks.org/mike/chart/ * */ // ================================================================================================================= // Edited BubbleChart() Function variables & changed bubbleChartName for dropdown menue purposes // ================================================================================================================= function bubbleChartMX() { // Constants for sizing var width = 1120; var height = 790; // tooltip for mouseover functionality var tooltip = floatingTooltip('gates_tooltip', 240); // Locations to move bubbles towards, depending // on which view mode is selected. var center = { x: width / 2.3, y: height / 2 }; var yearCenters = { 24: { x: width / 1.7, y: height / 2 }, 25: { x: width / 3.2, y: height / 2 }, 22: { x: 4.3 * width / 5, y: height / 2}, 23: { x: width /2.3, y: height / 2 }, 10: { x: 2.2 * width / 3, y: height / 2 }, 1: { x: width, y: height }, 2: {x: width , y: height }, 15: { x: width, y: height }, 17: {x: width, y: height }, 18: {x: width, y: height }, 19: {x: width, y: height }, 20: {x: width, y: height }, 21: { x: width, y: height }, 26: {x: width, y: height }, 27: { x: width, y: height }, 28: {x: width, y: height }, 29: {x: width, y: height }, 30: {x: width, y: height }, 31: {x: width, y: height }, 32: {x: width, y: height }, 33: {x: width, y: height }, 34: {x: width, y: height }, 35: {x: width, y: height }, 36: {x: width, y: height }, 37: {x: width, y: height }, 38: {x: width, y: height }, 39: {x: width, y: height }, 40: {x: width, y: height }, 41: {x: width, y: height }, 42: {x: width, y: height }, 43: {x: width, y: height }, 44: {x: width, y: height }, 0: {x: width, y: height }, }; // ================================================================================================================= // Edited yearsTitle X variables (key, values) for placement // ================================================================================================================= // X locations of the year titles. var yearsTitleX = { News_Politics: 100, Comedy: 280, Entertainment: 520, Music: 760, People_Blogs: 1000, }; // @v4 strength to apply to the position forces var forceStrength = 0.03; // These will be set in create_nodes and create_vis var svg = null; var bubbles = null; var nodes = []; // Charge function that is called for each node. // As part of the ManyBody force. // This is what creates the repulsion between nodes. // // Charge is proportional to the diameter of the // circle (which is stored in the radius attribute // of the circle's associated data. // // This is done to allow for accurate collision // detection with nodes of different sizes. // // Charge is negative because we want nodes to repel. // @v4 Before the charge was a stand-alone attribute // of the force layout. Now we can use it as a separate force! function charge(d) { return -Math.pow(d.radius, 2.0) * forceStrength; } // Here we create a force layout and // @v4 We create a force simulation now and // add forces to it. var simulation = d3.forceSimulation() .velocityDecay(0.2) .force('x', d3.forceX().strength(forceStrength).x(center.x)) .force('y', d3.forceY().strength(forceStrength).y(center.y)) .force('charge', d3.forceManyBody().strength(charge)) .on('tick', ticked); // @v4 Force starts up automatically, // which we don't want as there aren't any nodes yet. simulation.stop(); // ================================================================================================================= // Edited .domain and .range values // ================================================================================================================= // Nice looking colors - no reason to buck the trend // @v4 scales now have a flattened naming scheme var fillColor = d3.scaleOrdinal() .domain(['Entertainment', 'Music', 'People & Blogs','Comedy','News & Politics','Film & Animation','Autos & Vehicles','Pets & Animals','Sports','Short Movies','Travel & Events','Gaming','Videoblogging','Howto & Style','Education','Science & Technology','Noneprofits','Movies','Anime/Animation','Action/Adventure','Classics','Comedy','Documentary','Drama','Family','Foreign','Horror','Sci-Fi/Fantasy','Thriller','Shorts','Shows','Trailers','0']) .range(['#F08080', '#8A2BE2', '#FFFF00', '#7CFC00','#00FFFF','#7FFFD4','#FF4500','#8B008B','#FFB6C1','#FFF8DC','#BC8F8F','#778899','#808080','#D3D3D3','#D2691E','#FF1493','#000080','#87CEFA','#90EE90','#008000','#FFD700','#E9967A','#808000','#2F4F4F','#8FBC8F','#008080','#C71585','#FAEBD7','#8B4513','#191970','#00FA9A','#FFFFFF','#000000']); /* * This data manipulation function takes the raw data from * the CSV file and converts it into an array of node objects. * Each node will store data and visualization values to visualize * a bubble. * * rawData is expected to be an array of data objects, read in from * one of d3's loading functions like d3.csv. * * This function returns the new node array, with a node in that * array for each element in the rawData input. */ function createNodes(rawData) { // Use the max total_amount in the data as the max in the scale's domain // note we have to ensure the total_amount is a number. var maxAmount = d3.max(rawData, function (d) { return +d.views; }); // Sizes bubbles based on area. // @v4: new flattened scale names. var radiusScale = d3.scalePow() .exponent(0.5) .range([2, 41]) .domain([0, maxAmount]); // Use map() to convert raw data into node data. // Checkout http://learnjsdata.com/ for more on // working with data. // ================================================================================================================= // Edited myNodes return values // ================================================================================================================= var myNodes = rawData.map(function (d) { return { id: d.no_of_vids, radius: radiusScale(+d.views), value: +d.views, name: d.channel_title, org: d.title, group: d.Category_name, year: d.category_id, trending: d.trending_date, x: Math.random() * 900, y: Math.random() * 800 }; }); // sort them to prevent occlusion of smaller nodes. myNodes.sort(function (a, b) { return b.value - a.value; }); return myNodes; } /* * Main entry point to the bubble chart. This function is returned * by the parent closure. It prepares the rawData for visualization * and adds an svg element to the provided selector and starts the * visualization creation process. * * selector is expected to be a DOM element or CSS selector that * points to the parent element of the bubble chart. Inside this * element, the code will add the SVG continer for the visualization. * * rawData is expected to be an array of data objects as provided by * a d3 loading function like d3.csv. */ var chart = function chart(selector, rawData) { // convert raw data into nodes data nodes = createNodes(rawData); // Create a SVG element inside the provided selector // with desired size. svg = d3.select(selector) .append('svg') .attr('width', width) .attr('height', height); // Bind nodes data to what will become DOM elements to represent them. bubbles = svg.selectAll('.bubble') .data(nodes, function (d) { return d.id; }); // Create new circle elements each with class `bubble`. // There will be one circle.bubble for each object in the nodes array. // Initially, their radius (r attribute) will be 0. // @v4 Selections are immutable, so lets capture the // enter selection to apply our transtition to below. var bubblesE = bubbles.enter().append('circle') .classed('bubble', true) .attr('r', 0) .attr('fill', function (d) { return fillColor(d.group); }) .attr('stroke', function (d) { return d3.rgb(fillColor(d.group)).darker(); }) .attr('stroke-width', 2) .on('mouseover', showDetail) .on('mouseout', hideDetail); // @v4 Merge the original empty selection and the enter selection bubbles = bubbles.merge(bubblesE); // Fancy transition to make bubbles appear, ending with the // correct radius bubbles.transition() .duration(2000) .attr('r', function (d) { return d.radius; }); // Set the simulation's nodes to our newly created nodes array. // @v4 Once we set the nodes, the simulation will start running automatically! simulation.nodes(nodes); // Set initial layout to single group. groupBubbles(); }; /* * Callback function that is called after every tick of the * force simulation. * Here we do the acutal repositioning of the SVG circles * based on the current x and y values of their bound node data. * These x and y values are modified by the force simulation. */ function ticked() { bubbles .attr('cx', function (d) { return d.x; }) .attr('cy', function (d) { return d.y; }); } /* * Provides a x value for each node to be used with the split by year * x force. */ function nodeYearPos(d) { return yearCenters[d.year].x; } /* * Sets visualization in "single group mode". * The year labels are hidden and the force layout * tick function is set to move all nodes to the * center of the visualization. */ function groupBubbles() { hideYearTitles(); // @v4 Reset the 'x' force to draw the bubbles to the center. simulation.force('x', d3.forceX().strength(forceStrength).x(center.x)); // @v4 We can reset the alpha value and restart the simulation simulation.alpha(1).restart(); } /* * Sets visualization in "split by year mode". * The year labels are shown and the force layout * tick function is set to move nodes to the * yearCenter of their data's year. */ function splitBubbles() { showYearTitles(); // @v4 Reset the 'x' force to draw the bubbles to their year centers simulation.force('x', d3.forceX().strength(forceStrength).x(nodeYearPos)); // @v4 We can reset the alpha value and restart the simulation simulation.alpha(1).restart(); } /* * Hides Year title displays. */ function hideYearTitles() { svg.selectAll('.year').remove(); } /* * Shows Year title displays. */ function showYearTitles() { // Another way to do this would be to create // the year texts once and then just hide them. var yearsData = d3.keys(yearsTitleX); var years = svg.selectAll('.year') .data(yearsData); years.enter().append('text') .attr('class', 'year') .attr('x', function (d) { return yearsTitleX[d]; }) .attr('y', 40) .attr('text-anchor', 'middle') .text(function (d) { return d; }); } /* * Function called on mouseover to display the * details of a bubble in the tooltip. */ // ================================================================================================================= // Edited var content values ( for mouseover info display) // ================================================================================================================= function showDetail(d) { // change outline to indicate hover state. d3.select(this).attr('stroke', 'black'); var content = '<span class="name">Channel Title: </span><span class="value">' + d.name + '</span><br/>' + '<span class="name">Views: </span><span class="value">' + addCommas(d.value) + '</span><br/>' + '<span class="name">Category Name: </span><span class="value">' + d.group + '</span><br/>'+ '<span class="name">Trending Date(YY/DD/MM): </span><span class="value">' + d.trending + '</span>'; tooltip.showTooltip(content, d3.event); } /* * Hides tooltip */ function hideDetail(d) { // reset outline d3.select(this) .attr('stroke', d3.rgb(fillColor(d.group)).darker()); tooltip.hideTooltip(); } /* * Externally accessible function (this is attached to the * returned chart function). Allows the visualization to toggle * between "single group" and "split by year" modes. * * displayName is expected to be a string and either 'year' or 'all'. */ chart.toggleDisplay = function (displayName) { if (displayName === 'year') { splitBubbles(); } else { groupBubbles(); } }; // return the chart function from closure. return chart; } /* * Below is the initialization code as well as some helper functions * to create a new bubble chart instance, load the data, and display it. */ // ================================================================================================================= // Below var was removed from this section for dropdown menu purpose // This line has moved inside the display function at the bottom // ================================================================================================================= //var myBubbleChart = bubbleChart(); /* * Function called once data is loaded from CSV. * Calls bubble chart function to display inside #vis div. */ // ================================================================================================================= // Below display function has been commented out for drop down menu purpose // ================================================================================================================= // function display(error, data) { // if (error) { // console.log(error); // } // myBubbleChart('#vis', data); // } /* * Sets up the layout buttons to allow for toggling between view modes. */ function setupButtons() { d3.select('#toolbar') .selectAll('.button') .on('click', function () { // Remove active class from all buttons d3.selectAll('.button').classed('active', false); // Find the button just clicked var button = d3.select(this); // Set it as the active button button.classed('active', true); // Get the id of the button var buttonId = button.attr('id'); // Toggle the bubble chart based on // the currently clicked button. myBubbleChart.toggleDisplay(buttonId); }); } /* * Helper function to convert a number into a string * and add commas to it to improve presentation. */ function addCommas(nStr) { nStr += ''; var x = nStr.split('.'); var x1 = x[0]; var x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } // ================================================================================================================= // Loading CSV file was moved into a function for Dropdown purposes // ================================================================================================================= // Load the data. // d3.csv('data/us_cat_data.csv', display); // ================================================================================================================= // Loading CSV file was moved into a function for menu Dropdown purposes // ================================================================================================================= // Load the data. // d3.csv('data/us_cat_data.csv', display); // ================================================================================================================= // Calling setupButtons was moved into a new function for menu Dropdown purposes // ================================================================================================================= // setup the buttons. // setupButtons(); // =================================================================================================================== // Below display() function has been created, to be called later in mainbubble.js file for drop down menu. // Each country wil have their own display function. displayCOUNTRYNAME() // *************************************************************************************************************** // Remember to change: display country's initial, bubbleChart country's initial and your CSV file path name // *************************************************************************************************************** // =================================================================================================================== function displayMX() { var myBubbleChart = bubbleChartMX(); d3.csv('data/bubble_chart_data/mx_cat_data.csv', function(error, data) { if (error) { console.log(error); } myBubbleChart('#vis', data); }); setupButtons(myBubbleChart); // setup the buttons. }