text
stringlengths 18
215k
|
|---|
<?php
namespace Terrific\Composition\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\SerializerBundle\Annotation\ReadOnly;
use JMS\SerializerBundle\Annotation\Type;
use JMS\SerializerBundle\Annotation\Exclude;
use JMS\SerializerBundle\Annotation\Groups;
use JMS\SerializerBundle\Annotation\Accessor;
/**
* Terrific\Composition\Entity\Module
*
* @ORM\Table(name="module")
* @ORM\Entity(repositoryClass="Terrific\Composition\Entity\ModuleRepository")
*/
class Module
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @Groups({"project_list", "project_details", "module_list", "module_details"})
* @ReadOnly
*/
private $id;
/**
* @ORM\Column(name="in_work", type="boolean")
* @Type("boolean")
* @Groups({"project_list", "project_details", "module_list", "module_details"})
*/
private $inWork = false;
/**
* @ORM\Column(name="shared", type="boolean")
* @Type("boolean")
* @Groups({"project_list", "project_details", "module_list", "module_details"})
*/
private $shared = false;
/**
* @ORM\Column(name="title", type="string", length=255)
* @Type("string")
* @Groups({"project_list", "project_details", "module_list", "module_details"})
*/
private $title;
/**
* @ORM\Column(name="description", type="text")
* @Type("string")
* @Groups({"project_list", "project_details", "module_list", "module_details"})
*/
private $description;
/**
* @ORM\ManyToOne(targetEntity="Project")
* @Type("integer")
* @Groups({"module_details"})
*/
private $project;
/**
* @ORM\OneToOne(targetEntity="Snippet")
* @Type("Terrific\Composition\Entity\Snippet")
* @Groups({"module_details"})
*/
private $markup;
/**
* @ORM\OneToOne(targetEntity="Snippet")
* @Type("Terrific\Composition\Entity\Snippet")
* @Groups({"module_details"})
*/
private $style;
/**
* @ORM\OneToOne(targetEntity="Snippet")
* @Type("Terrific\Composition\Entity\Snippet")
* @Groups({"module_details"})
*/
private $script;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* @param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* @param text $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* @return text
*/
public function getDescription()
{
return $this->description;
}
/**
* Set markup
*
* @param Terrific\Composition\Entity\Snippet $markup
*/
public function setMarkup(\Terrific\Composition\Entity\Snippet $markup)
{
$this->markup = $markup;
}
/**
* Get markup
*
* @return Terrific\Composition\Entity\Snippet
*/
public function getMarkup()
{
return $this->markup;
}
/**
* Set style
*
* @param Terrific\Composition\Entity\Snippet $style
*/
public function setStyle(\Terrific\Composition\Entity\Snippet $style)
{
$this->style = $style;
}
/**
* Get style
*
* @return Terrific\Composition\Entity\Snippet
*/
public function getStyle()
{
return $this->style;
}
/**
* Set script
*
* @param Terrific\Composition\Entity\Snippet $script
*/
public function setScript(\Terrific\Composition\Entity\Snippet $script)
{
$this->script = $script;
}
/**
* Get script
*
* @return Terrific\Composition\Entity\Snippet
*/
public function getScript()
{
return $this->script;
}
/**
* Set project
*
* @param Terrific\Composition\Entity\Project $project
* @return Module
*/
public function setProject(\Terrific\Composition\Entity\Project $project = null)
{
$this->project = $project;
return $this;
}
/**
* Get project
*
* @return Terrific\Composition\Entity\Project
*/
public function getProject()
{
return $this->project;
}
/**
* Set inWork
*
* @param boolean $inWork
* @return Module
*/
public function setInWork($inWork)
{
$this->inWork = $inWork;
return $this;
}
/**
* Get inWork
*
* @return boolean
*/
public function getInWork()
{
return $this->inWork;
}
/**
* Set shared
*
* @param boolean $shared
* @return Module
*/
public function setShared($shared)
{
$this->shared = $shared;
return $this;
}
/**
* Get shared
*
* @return boolean
*/
public function getShared()
{
return $this->shared;
}
}
|
b'What is -28 + 37 + -23 - (1 - 1)?\n'
|
using System.Collections.Generic;
namespace ConsoleDemo.Visitor.v0
{
public class CommandsManager
{
readonly List<object> items = new List<object>();
// The client class has a structure (a list in this case) of items (commands).
// The client knows how to iterate through the structure
// The client would need to do different operations on the items from the structure when iterating it
}
}
|
//
// STShare.h
// Loopy
//
// Created by David Jedeikin on 10/23/13.
// Copyright (c) 2013 ShareThis. All rights reserved.
//
#import "STAPIClient.h"
#import <Foundation/Foundation.h>
#import <Social/Social.h>
@interface STShareActivityUI : NSObject
@property (nonatomic, strong) UIViewController *parentController;
@property (nonatomic, strong) STAPIClient *apiClient;
- (id)initWithParent:(UIViewController *)parent apiClient:(STAPIClient *)client;
- (NSArray *)getDefaultActivities:(NSArray *)activityItems;
- (UIActivityViewController *)newActivityViewController:(NSArray *)shareItems withActivities:(NSArray *)activities;
- (SLComposeViewController *)newActivityShareController:(id)activityObj;
- (void)showActivityViewDialog:(UIActivityViewController *)activityController completion:(void (^)(void))completion;
- (void)handleShareDidBegin:(NSNotification *)notification;
- (void)handleShareDidComplete:(NSNotification *)notification;
@end
|
package fr.pizzeria.admin.web;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
@WebServlet("/login")
public class LoginController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login/login.jsp");
rd.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String email = req.getParameter("email");
String password = req.getParameter("password");
if (StringUtils.isBlank(email) || StringUtils.isBlank(password))
{
resp.sendError(400, "Non non non ! Zone interdite");
}
else if ( StringUtils.equals(email, "[email protected]")
&& StringUtils.equals(password, "admin"))
{
HttpSession session = req.getSession();
session.setAttribute("email", email);
resp.sendRedirect(req.getContextPath() + "/pizzas/list");
}
else
{
resp.setStatus(403);
req.setAttribute("msgerr", "Ooppps noooo");
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login/login.jsp");
rd.forward(req, resp);
}
}
}
|
.highlight { background-color: black; }
.highlight .hll { background-color: #404040 }
.highlight .c { color: #999999; font-style: italic } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .g { color: #d0d0d0 } /* Generic */
.highlight .k { color: #6ab825; font-weight: bold } /* Keyword */
.highlight .l { color: #d0d0d0 } /* Literal */
.highlight .n { color: #d0d0d0 } /* Name */
.highlight .o { color: #d0d0d0 } /* Operator */
.highlight .x { color: #d0d0d0 } /* Other */
.highlight .p { color: #d0d0d0 } /* Punctuation */
.highlight .cm { color: #999999; font-style: italic } /* Comment.Multiline */
.highlight .cp { color: #cd2828; font-weight: bold } /* Comment.Preproc */
.highlight .c1 { color: #999999; font-style: italic } /* Comment.Single */
.highlight .cs { color: #e50808; font-weight: bold; background-color: #520000 } /* Comment.Special */
.highlight .gd { color: #d22323 } /* Generic.Deleted */
.highlight .ge { color: #d0d0d0; font-style: italic } /* Generic.Emph */
.highlight .gr { color: #d22323 } /* Generic.Error */
.highlight .gh { color: #ffffff; font-weight: bold } /* Generic.Heading */
.highlight .gi { color: #589819 } /* Generic.Inserted */
.highlight .go { color: #cccccc } /* Generic.Output */
.highlight .gp { color: #aaaaaa } /* Generic.Prompt */
.highlight .gs { color: #d0d0d0; font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #ffffff; text-decoration: underline } /* Generic.Subheading */
.highlight .gt { color: #d22323 } /* Generic.Traceback */
.highlight .kc { color: #6ab825; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #6ab825; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #6ab825; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #6ab825 } /* Keyword.Pseudo */
.highlight .kr { color: #6ab825; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #6ab825; font-weight: bold } /* Keyword.Type */
.highlight .ld { color: #d0d0d0 } /* Literal.Date */
.highlight .m { color: #3677a9 } /* Literal.Number */
.highlight .s { color: #ed9d13 } /* Literal.String */
.highlight .na { color: #bbbbbb } /* Name.Attribute */
.highlight .nb { color: #24909d } /* Name.Builtin */
.highlight .nc { color: #447fcf; text-decoration: underline } /* Name.Class */
.highlight .no { color: #40ffff } /* Name.Constant */
.highlight .nd { color: #ffa500 } /* Name.Decorator */
.highlight .ni { color: #d0d0d0 } /* Name.Entity */
.highlight .ne { color: #bbbbbb } /* Name.Exception */
.highlight .nf { color: #447fcf } /* Name.Function */
.highlight .nl { color: #d0d0d0 } /* Name.Label */
.highlight .nn { color: #447fcf; text-decoration: underline } /* Name.Namespace */
.highlight .nx { color: #d0d0d0 } /* Name.Other */
.highlight .py { color: #d0d0d0 } /* Name.Property */
.highlight .nt { color: #6ab825; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #40ffff } /* Name.Variable */
.highlight .ow { color: #6ab825; font-weight: bold } /* Operator.Word */
.highlight .w { color: #666666 } /* Text.Whitespace */
.highlight .mf { color: #3677a9 } /* Literal.Number.Float */
.highlight .mh { color: #3677a9 } /* Literal.Number.Hex */
.highlight .mi { color: #3677a9 } /* Literal.Number.Integer */
.highlight .mo { color: #3677a9 } /* Literal.Number.Oct */
.highlight .sb { color: #ed9d13 } /* Literal.String.Backtick */
.highlight .sc { color: #ed9d13 } /* Literal.String.Char */
.highlight .sd { color: #ed9d13 } /* Literal.String.Doc */
.highlight .s2 { color: #ed9d13 } /* Literal.String.Double */
.highlight .se { color: #ed9d13 } /* Literal.String.Escape */
.highlight .sh { color: #ed9d13 } /* Literal.String.Heredoc */
.highlight .si { color: #ed9d13 } /* Literal.String.Interpol */
.highlight .sx { color: #ffa500 } /* Literal.String.Other */
.highlight .sr { color: #ed9d13 } /* Literal.String.Regex */
.highlight .s1 { color: #ed9d13 } /* Literal.String.Single */
.highlight .ss { color: #ed9d13 } /* Literal.String.Symbol */
.highlight .bp { color: #24909d } /* Name.Builtin.Pseudo */
.highlight .vc { color: #40ffff } /* Name.Variable.Class */
.highlight .vg { color: #40ffff } /* Name.Variable.Global */
.highlight .vi { color: #40ffff } /* Name.Variable.Instance */
.highlight .il { color: #3677a9 } /* Literal.Number.Integer.Long */
|
b'What is the value of (-39 + 15 - -19) + (34 - (-7 - -4))?\n'
|
b'What is (8 + -7 - (2 + -1)) + -12 + 4?\n'
|
b'Evaluate 8 + (7 + -12 - (12 + -2 + -9)).\n'
|
System.register(["angular2/test_lib", "angular2/src/test_lib/test_bed", "angular2/src/core/annotations_impl/annotations", "angular2/src/core/annotations_impl/view", "angular2/src/core/compiler/dynamic_component_loader", "angular2/src/core/compiler/element_ref", "angular2/src/directives/if", "angular2/src/render/dom/direct_dom_renderer", "angular2/src/dom/dom_adapter"], function($__export) {
"use strict";
var AsyncTestCompleter,
beforeEach,
ddescribe,
xdescribe,
describe,
el,
dispatchEvent,
expect,
iit,
inject,
beforeEachBindings,
it,
xit,
TestBed,
Component,
View,
DynamicComponentLoader,
ElementRef,
If,
DirectDomRenderer,
DOM,
ImperativeViewComponentUsingNgComponent,
ChildComp,
DynamicallyCreatedComponentService,
DynamicComp,
DynamicallyCreatedCmp,
DynamicallyLoaded,
DynamicallyLoaded2,
DynamicallyLoadedWithHostProps,
Location,
MyComp;
function main() {
describe('DynamicComponentLoader', function() {
describe("loading into existing location", (function() {
it('should work', inject([TestBed, AsyncTestCompleter], (function(tb, async) {
tb.overrideView(MyComp, new View({
template: '<dynamic-comp #dynamic></dynamic-comp>',
directives: [DynamicComp]
}));
tb.createView(MyComp).then((function(view) {
var dynamicComponent = view.rawView.locals.get("dynamic");
expect(dynamicComponent).toBeAnInstanceOf(DynamicComp);
dynamicComponent.done.then((function(_) {
view.detectChanges();
expect(view.rootNodes).toHaveText('hello');
async.done();
}));
}));
})));
it('should inject dependencies of the dynamically-loaded component', inject([TestBed, AsyncTestCompleter], (function(tb, async) {
tb.overrideView(MyComp, new View({
template: '<dynamic-comp #dynamic></dynamic-comp>',
directives: [DynamicComp]
}));
tb.createView(MyComp).then((function(view) {
var dynamicComponent = view.rawView.locals.get("dynamic");
dynamicComponent.done.then((function(ref) {
expect(ref.instance.dynamicallyCreatedComponentService).toBeAnInstanceOf(DynamicallyCreatedComponentService);
async.done();
}));
}));
})));
it('should allow to destroy and create them via viewcontainer directives', inject([TestBed, AsyncTestCompleter], (function(tb, async) {
tb.overrideView(MyComp, new View({
template: '<div><dynamic-comp #dynamic template="if: ctxBoolProp"></dynamic-comp></div>',
directives: [DynamicComp, If]
}));
tb.createView(MyComp).then((function(view) {
view.context.ctxBoolProp = true;
view.detectChanges();
var dynamicComponent = view.rawView.viewContainers[0].views[0].locals.get("dynamic");
dynamicComponent.done.then((function(_) {
view.detectChanges();
expect(view.rootNodes).toHaveText('hello');
view.context.ctxBoolProp = false;
view.detectChanges();
expect(view.rawView.viewContainers[0].views.length).toBe(0);
expect(view.rootNodes).toHaveText('');
view.context.ctxBoolProp = true;
view.detectChanges();
var dynamicComponent = view.rawView.viewContainers[0].views[0].locals.get("dynamic");
return dynamicComponent.done;
})).then((function(_) {
view.detectChanges();
expect(view.rootNodes).toHaveText('hello');
async.done();
}));
}));
})));
}));
describe("loading next to an existing location", (function() {
it('should work', inject([DynamicComponentLoader, TestBed, AsyncTestCompleter], (function(loader, tb, async) {
tb.overrideView(MyComp, new View({
template: '<div><location #loc></location></div>',
directives: [Location]
}));
tb.createView(MyComp).then((function(view) {
var location = view.rawView.locals.get("loc");
loader.loadNextToExistingLocation(DynamicallyLoaded, location.elementRef).then((function(ref) {
expect(view.rootNodes).toHaveText("Location;DynamicallyLoaded;");
async.done();
}));
}));
})));
it('should return a disposable component ref', inject([DynamicComponentLoader, TestBed, AsyncTestCompleter], (function(loader, tb, async) {
tb.overrideView(MyComp, new View({
template: '<div><location #loc></location></div>',
directives: [Location]
}));
tb.createView(MyComp).then((function(view) {
var location = view.rawView.locals.get("loc");
loader.loadNextToExistingLocation(DynamicallyLoaded, location.elementRef).then((function(ref) {
loader.loadNextToExistingLocation(DynamicallyLoaded2, location.elementRef).then((function(ref2) {
expect(view.rootNodes).toHaveText("Location;DynamicallyLoaded;DynamicallyLoaded2;");
ref2.dispose();
expect(view.rootNodes).toHaveText("Location;DynamicallyLoaded;");
async.done();
}));
}));
}));
})));
it('should update host properties', inject([DynamicComponentLoader, TestBed, AsyncTestCompleter], (function(loader, tb, async) {
tb.overrideView(MyComp, new View({
template: '<div><location #loc></location></div>',
directives: [Location]
}));
tb.createView(MyComp).then((function(view) {
var location = view.rawView.locals.get("loc");
loader.loadNextToExistingLocation(DynamicallyLoadedWithHostProps, location.elementRef).then((function(ref) {
ref.instance.id = "new value";
view.detectChanges();
var newlyInsertedElement = DOM.childNodesAsList(view.rootNodes[0])[1];
expect(newlyInsertedElement.id).toEqual("new value");
async.done();
}));
}));
})));
}));
describe('loading into a new location', (function() {
it('should allow to create, update and destroy components', inject([TestBed, AsyncTestCompleter], (function(tb, async) {
tb.overrideView(MyComp, new View({
template: '<imp-ng-cmp #impview></imp-ng-cmp>',
directives: [ImperativeViewComponentUsingNgComponent]
}));
tb.createView(MyComp).then((function(view) {
var userViewComponent = view.rawView.locals.get("impview");
userViewComponent.done.then((function(childComponentRef) {
view.detectChanges();
expect(view.rootNodes).toHaveText('hello');
childComponentRef.instance.ctxProp = 'new';
view.detectChanges();
expect(view.rootNodes).toHaveText('new');
childComponentRef.dispose();
expect(view.rootNodes).toHaveText('');
async.done();
}));
}));
})));
}));
});
}
$__export("main", main);
return {
setters: [function($__m) {
AsyncTestCompleter = $__m.AsyncTestCompleter;
beforeEach = $__m.beforeEach;
ddescribe = $__m.ddescribe;
xdescribe = $__m.xdescribe;
describe = $__m.describe;
el = $__m.el;
dispatchEvent = $__m.dispatchEvent;
expect = $__m.expect;
iit = $__m.iit;
inject = $__m.inject;
beforeEachBindings = $__m.beforeEachBindings;
it = $__m.it;
xit = $__m.xit;
}, function($__m) {
TestBed = $__m.TestBed;
}, function($__m) {
Component = $__m.Component;
}, function($__m) {
View = $__m.View;
}, function($__m) {
DynamicComponentLoader = $__m.DynamicComponentLoader;
}, function($__m) {
ElementRef = $__m.ElementRef;
}, function($__m) {
If = $__m.If;
}, function($__m) {
DirectDomRenderer = $__m.DirectDomRenderer;
}, function($__m) {
DOM = $__m.DOM;
}],
execute: function() {
ImperativeViewComponentUsingNgComponent = (function() {
var ImperativeViewComponentUsingNgComponent = function ImperativeViewComponentUsingNgComponent(self, dynamicComponentLoader, renderer) {
var div = el('<div></div>');
renderer.setImperativeComponentRootNodes(self.parentView.render, self.boundElementIndex, [div]);
this.done = dynamicComponentLoader.loadIntoNewLocation(ChildComp, self, div, null);
};
return ($traceurRuntime.createClass)(ImperativeViewComponentUsingNgComponent, {}, {});
}());
Object.defineProperty(ImperativeViewComponentUsingNgComponent, "annotations", {get: function() {
return [new Component({selector: 'imp-ng-cmp'}), new View({renderer: 'imp-ng-cmp-renderer'})];
}});
Object.defineProperty(ImperativeViewComponentUsingNgComponent, "parameters", {get: function() {
return [[ElementRef], [DynamicComponentLoader], [DirectDomRenderer]];
}});
ChildComp = (function() {
var ChildComp = function ChildComp() {
this.ctxProp = 'hello';
};
return ($traceurRuntime.createClass)(ChildComp, {}, {});
}());
Object.defineProperty(ChildComp, "annotations", {get: function() {
return [new Component({selector: 'child-cmp'}), new View({template: '{{ctxProp}}'})];
}});
DynamicallyCreatedComponentService = (function() {
var DynamicallyCreatedComponentService = function DynamicallyCreatedComponentService() {
;
};
return ($traceurRuntime.createClass)(DynamicallyCreatedComponentService, {}, {});
}());
DynamicComp = (function() {
var DynamicComp = function DynamicComp(loader, location) {
this.done = loader.loadIntoExistingLocation(DynamicallyCreatedCmp, location);
};
return ($traceurRuntime.createClass)(DynamicComp, {}, {});
}());
Object.defineProperty(DynamicComp, "annotations", {get: function() {
return [new Component({selector: 'dynamic-comp'})];
}});
Object.defineProperty(DynamicComp, "parameters", {get: function() {
return [[DynamicComponentLoader], [ElementRef]];
}});
DynamicallyCreatedCmp = (function() {
var DynamicallyCreatedCmp = function DynamicallyCreatedCmp(a) {
this.greeting = "hello";
this.dynamicallyCreatedComponentService = a;
};
return ($traceurRuntime.createClass)(DynamicallyCreatedCmp, {}, {});
}());
Object.defineProperty(DynamicallyCreatedCmp, "annotations", {get: function() {
return [new Component({
selector: 'hello-cmp',
injectables: [DynamicallyCreatedComponentService]
}), new View({template: "{{greeting}}"})];
}});
Object.defineProperty(DynamicallyCreatedCmp, "parameters", {get: function() {
return [[DynamicallyCreatedComponentService]];
}});
DynamicallyLoaded = (function() {
var DynamicallyLoaded = function DynamicallyLoaded() {
;
};
return ($traceurRuntime.createClass)(DynamicallyLoaded, {}, {});
}());
Object.defineProperty(DynamicallyLoaded, "annotations", {get: function() {
return [new Component({selector: 'dummy'}), new View({template: "DynamicallyLoaded;"})];
}});
DynamicallyLoaded2 = (function() {
var DynamicallyLoaded2 = function DynamicallyLoaded2() {
;
};
return ($traceurRuntime.createClass)(DynamicallyLoaded2, {}, {});
}());
Object.defineProperty(DynamicallyLoaded2, "annotations", {get: function() {
return [new Component({selector: 'dummy'}), new View({template: "DynamicallyLoaded2;"})];
}});
DynamicallyLoadedWithHostProps = (function() {
var DynamicallyLoadedWithHostProps = function DynamicallyLoadedWithHostProps() {
this.id = "default";
};
return ($traceurRuntime.createClass)(DynamicallyLoadedWithHostProps, {}, {});
}());
Object.defineProperty(DynamicallyLoadedWithHostProps, "annotations", {get: function() {
return [new Component({
selector: 'dummy',
hostProperties: {'id': 'id'}
}), new View({template: "DynamicallyLoadedWithHostProps;"})];
}});
Location = (function() {
var Location = function Location(elementRef) {
this.elementRef = elementRef;
};
return ($traceurRuntime.createClass)(Location, {}, {});
}());
Object.defineProperty(Location, "annotations", {get: function() {
return [new Component({selector: 'location'}), new View({template: "Location;"})];
}});
Object.defineProperty(Location, "parameters", {get: function() {
return [[ElementRef]];
}});
MyComp = (function() {
var MyComp = function MyComp() {
this.ctxBoolProp = false;
};
return ($traceurRuntime.createClass)(MyComp, {}, {});
}());
Object.defineProperty(MyComp, "annotations", {get: function() {
return [new Component({selector: 'my-comp'}), new View({directives: []})];
}});
}
};
});
//# sourceMappingURL=dynamic_component_loader_spec.es6.map
//# sourceMappingURL=./dynamic_component_loader_spec.js.map
|
import {Component} from 'react'
export class Greeter {
constructor (message) {
this.greeting = message;
}
greetFrom (...names) {
let suffix = names.reduce((s, n) => s + ", " + n.toUpperCase());
return "Hello, " + this.greeting + " from " + suffix;
}
greetNTimes ({name, times}) {
let greeting = this.greetFrom(name);
for (let i = 0; i < times; i++) {
console.log(greeting)
}
}
}
new Greeter("foo").greetNTimes({name: "Webstorm", times: 3})
function foo (x, y, z) {
var i = 0;
var x = {0: "zero", 1: "one"};
var a = [0, 1, 2];
var foo = function () {
}
var asyncFoo = async (x, y, z) => {
}
var v = x.map(s => s.length);
if (!i > 10) {
for (var j = 0; j < 10; j++) {
switch (j) {
case 0:
value = "zero";
break;
case 1:
value = "one";
break;
}
var c = j > 5 ? "GT 5" : "LE 5";
}
} else {
var j = 0;
try {
while (j < 10) {
if (i == j || j > 5) {
a[j] = i + j * 12;
}
i = (j << 2) & 4;
j++;
}
do {
j--;
} while (j > 0)
} catch (e) {
alert("Failure: " + e.message);
} finally {
reset(a, i);
}
}
}
|
//-------------------------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// CHeapPtr for VB
//
//-------------------------------------------------------------------------------------------------
#pragma once
template <typename T>
class VBHeapPtr :
public CHeapPtrBase<T, VBAllocator>
{
public:
VBHeapPtr() throw() : CHeapPtrBase<T, VBAllocator>()
{
}
VBHeapPtr(VBHeapPtr<T>& p) throw() :
CHeapPtrBase<T, VBAllocator>(p)
{
}
explicit VBHeapPtr(T* p) throw() :
CHeapPtrBase<T, VBAllocator>(p)
{
}
explicit VBHeapPtr(size_t elements)
{
Allocate(elements);
}
VBHeapPtr<T>& operator=(VBHeapPtr<T>& p) throw()
{
CHeapPtrBase<T, VBStandardallocator>::operator=(p);
return *this;
}
// Allocate a buffer with the given number of elements. Allocator
// will succeed or throw
void Allocate(size_t nElements = 1) throw()
{
SafeInt<size_t> total = nElements;
total *= sizeof(T);
// Uses VBAllocator::Allocate which will succeed or throw
AllocateBytes(total.Value());
}
// Reallocate the buffer to hold a given number of elements. Allocator
// will succeed or throw
void Reallocate(size_t nElements) throw()
{
SafeInt<size_t> total = nElements;
total *= sizeof(T);
// Uses VBAllocator::Allocate which will succeed or throw
ReallocateBytes(total.Value());
}
};
|
b'Calculate -1 - (19 - -13 - 22).\n'
|
b'What is -529 + 546 + 0 + 3?\n'
|
b'Evaluate 3 + -1 - -3 - (-11 + -47 + 54).\n'
|
# Les patrons de conception
## Bibliothèque d'exemples en Java
Ce dossier est un aide mémoire.
Il consiste à répertorier les patrons de conception en Java.
### [La liste des exemples](https://github.com/ewenb/Java_patterns)
* COMPOSITE : Il dispose les objets dans des structures arborescentes
ex1 : Un exemple basique
* VISITEUR : Il permet de proposer plusieurs interprétations de la structure sans toucher au Composite
ex1 : Un exemple basique.
|
$context.section('Простое связывание', 'Иерархическое связывание с данными с использованием простых и составных ключей');
//= require data-basic
$context.section('Форматирование', 'Механизм одностороннего связывания (one-way-binding)');
//= require data-format
$context.section('Настройка', 'Управление изменением виджета при обновлении данных');
//= require data-binding
$context.section('Динамическое связывание', 'Управление коллекцией элементов виджета через источник данных');
//= require data-dynamic
$context.section('Общие данные');
//= require data-share
$context.section('"Грязные" данные', 'Уведомление родительских источников данных о том, что значение изменилось');
//= require data-dirty
|
b'Calculate (6 - (-11 + 31)) + 18 + -3.\n'
|
import java.text.NumberFormat;
// ****************************************************************
// ManageAccounts.java
// Use Account class to create and manage Sally and Joe's bank accounts
public class ManageAccounts
{
public static void main(String[] args)
{
Account acct1, acct2;
NumberFormat usMoney = NumberFormat.getCurrencyInstance();
//create account1 for Sally with $1000
acct1 = new Account(1000, "Sally", 1111);
//create account2 for Joe with $500
acct2 = new Account(500, "Joe", 1212);
//deposit $100 to Joe's account
acct2.deposit(100);
//print Joe's new balance (use getBalance())
System.out.println("Joe's new balance: " + usMoney.format(acct2.getBalance()));
//withdraw $50 from Sally's account
acct1.withdraw(50);
//print Sally's new balance (use getBalance())
System.out.println("Sally's new balance: " + usMoney.format(acct1.getBalance()));
//charge fees to both accounts
System.out.println("Sally's new balance after the fee is charged: " + usMoney.format(acct1.chargeFee()));
System.out.println("Joe's new balance after the fee is charged: " + usMoney.format(acct2.chargeFee()));
//change the name on Joe's account to Joseph
acct2.changeName("Joseph");
//print summary for both accounts
System.out.println(acct1);
System.out.println(acct2);
//close and display Sally's account
acct1.close();
System.out.println(acct1);
//consolidate account test (doesn't work as acct1
Account newAcct = Account.consolidate(acct1, acct2);
System.out.println(acct1);
}
}
|
/* MIT License (From https://choosealicense.com/ )
Copyright (c) 2017 Jonathan Burget [email protected]
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.*/
#include "TigerEngine.h"
// Global variable so the objects are not lost
static TIGValue *theNumberStack;
static TIGValue *theStringStack;
static int stackNumber;
static char *stackString;
// ************* For debugging Purposes *************
TIGValue *TIGStringNumberStack(void)
{
return theNumberStack;
}
TIGValue *TIGStringStringStack(void)
{
return theStringStack;
}
// ************* For debugging Purposes *************
void TIGStringStartStack(const char *startStackString)
{
// If there is another start stack called before the end stack free it
if (stackString != NULL)
{
free(stackString);
stackString = NULL;
}
if (startStackString == NULL)
{
stackNumber++;
}
else
{
stackString = (char *)malloc((strlen(startStackString) + 1) * sizeof(char));
if (startStackString != NULL)
{
strcpy(stackString, startStackString);
}
}
}
void TIGStringEndStack(const char *endStackString)
{
if (endStackString != NULL)
{
while (theStringStack != NULL)
{
TIGValue *theNextStack = theStringStack->nextStack;
// 0 means both strings are the same
if (strcmp(theStringStack->stackString, endStackString) == 0)
{
theStringStack = TIGStringDestroy(theStringStack);
}
theStringStack = theNextStack;
}
}
else
{
while (theNumberStack != NULL)
{
TIGValue *theNextStack = theNumberStack->nextStack;
if (theNumberStack->stackNumber == stackNumber)
{
theNumberStack = TIGStringDestroy(theNumberStack);
}
theNumberStack = theNextStack;
}
}
// If there is another end or start stack string called before this end stack free it
if (stackString != NULL)
{
free(stackString);
stackString = NULL;
}
if (endStackString == NULL)
{
stackNumber--;
}
}
TIGValue *TIGStringCreate(TIGValue *tigString, TIGBool useStack)
{
tigString = (TIGValue *)malloc(1 * sizeof(TIGValue));
if (tigString == NULL)
{
#ifdef TIG_DEBUG
printf("ERROR Function:TIGStringCreate() Variable:tigString Equals:NULL\n");
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
if (useStack)
{
if (stackString != NULL)
{
if (theStringStack == NULL)
{
tigString->nextStack = NULL;
}
// Add the last added TIGString to the new tigString's ->nextStack
else
{
tigString->nextStack = theStringStack;
}
tigString->stackNumber = -1;
tigString->stackString = (char *)malloc((strlen(stackString) + 1) * sizeof(char));
if (tigString->stackString != NULL)
{
strcpy(tigString->stackString, stackString);
}
else
{
#ifdef TIG_DEBUG
printf("ERROR Function:TIGStringCreate() Variable:tigString->stackString Equals:NULL\n");
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
}
// This adds the new tigString to the global TIGString stack
theStringStack = tigString;
}
else
{
if (theNumberStack == NULL)
{
tigString->nextStack = NULL;
}
// Add the last added TIGString to the new tigString's ->nextStack
else
{
tigString->nextStack = theNumberStack;
}
tigString->stackNumber = stackNumber;
tigString->stackString = NULL;
// This adds the tigString to the global TIGString stack
theNumberStack = tigString;
}
}
else
{
tigString->nextStack = NULL;
tigString->stackString = NULL;
tigString->stackNumber = -2;
}
tigString->nextLevel = NULL;
tigString->thisLevel = NULL;
tigString->number = 0.0;
// Sets the TIGObject's string to an empty string
tigString->string = NULL;
// object type
tigString->type = "String";
return tigString;
}
TIGValue *TIGStringDestroy(TIGValue *tigString)
{
// If the "tigString" pointer has already been used free it
if (tigString != NULL)
{
if (strcmp(tigString->type, "String") != 0)
{
#ifdef TIG_DEBUG
printf("ERROR Function:TIGStringDestroy() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type);
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return tigString;
}
if (tigString->string != NULL)
{
free(tigString->string);
tigString->string = NULL;
}
if (tigString->stackString != NULL)
{
free(tigString->stackString);
tigString->stackString = NULL;
}
tigString->number = 0.0;
tigString->stackNumber = 0;
tigString->type = NULL;
tigString->nextStack = NULL;
tigString->nextLevel = NULL;
tigString->thisLevel = NULL;
free(tigString);
tigString = NULL;
}
return tigString;
}
TIGValue *TIGStr(const char *string)
{
return TIGStringInput(NULL, string);
}
TIGValue *TIGStringInput(TIGValue *tigString, const char *string)
{
return TIGStringStackInput(tigString, string, TIGYes);
}
TIGValue *TIGStringStackInput(TIGValue *tigString, const char *string, TIGBool useStack)
{
if (tigString == NULL)
{
tigString = TIGStringCreate(tigString, useStack);
if (tigString == NULL)
{
#ifdef TIG_DEBUG
printf("ERROR Function:TIGStringStackInput() Variable:tigString Equals:NULL\n");
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
}
else if (strcmp(tigString->type, "String") != 0)
{
#ifdef TIG_DEBUG
printf("ERROR Function:TIGStringStackInput() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type);
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
// If there is already a string free it
if (tigString->string != NULL)
{
free(tigString->string);
tigString->string = NULL;
}
tigString->string = (char *)malloc((strlen(string) + 1) * sizeof(char));
if (tigString->string == NULL || string == NULL)
{
#ifdef TIG_DEBUG
if (string == NULL)
{
printf("ERROR Function:TIGStringStackInput() Variable:string Equals:NULL\n");
}
if (tigString->string == NULL)
{
printf("ERROR Function:TIGStringStackInput() Variable:tigString->string Equals:NULL\n");
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
else
{
strcpy(tigString->string, string);
}
return tigString;
}
char *TIGStringOutput(TIGValue *tigString)
{
if (tigString == NULL || tigString->string == NULL || strcmp(tigString->type, "String") != 0)
{
#ifdef TIG_DEBUG
if (tigString == NULL)
{
printf("ERROR Function:TIGStringOutput() Variable:tigString Equals:NULL\n");
}
else
{
if (tigString->string == NULL)
{
printf("ERROR Function:TIGStringOutput() Variable:tigString->string Equals:NULL\n");
}
if (strcmp(tigString->type, "String") != 0)
{
printf("ERROR Function:TIGStringOutput() Variable:tigString->string Equals:%s Valid:\"String\"\n", tigString->type);
}
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
else
{
return tigString->string;
}
}
TIGInteger TIGStringLength(TIGValue *tigString)
{
if (tigString == NULL || tigString->string == NULL || strcmp(tigString->type, "String") != 0)
{
#ifdef TIG_DEBUG
if (tigString == NULL)
{
printf("ERROR Function:TIGStringLength() Variable:tigString Equals:NULL\n");
}
else
{
if (tigString->string == NULL)
{
printf("ERROR Function:TIGStringLength() Variable:tigString->string Equals:NULL\n");
}
if (strcmp(tigString->type, "String") != 0)
{
printf("ERROR Function:TIGStringLength() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type);
}
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return -1;
}
//if (tigString != NULL && tigString->string != NULL && strcmp(tigString->type, "String") == 0)
else
{
return (int)strlen(tigString->string);
}
}
TIGValue *TIGStringInsertStringAtIndex(TIGValue *tigString1, TIGValue *tigString2, int index)
{
if (tigString1 == NULL || tigString2 == NULL || strcmp(tigString1->type, "String") != 0 || strcmp(tigString2->type, "String") != 0
|| index < 0 || index > TIGStringLength(tigString1))
{
#ifdef TIG_DEBUG
if (tigString1 == NULL)
{
printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:tigString1 Equals:NULL\n");
}
else if (strcmp(tigString1->type, "String") != 0)
{
printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:tigNumber Equals:%s Valid:\"String\"\n", tigString1->type);
}
if (tigString2 == NULL)
{
printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:tigString2 Equals:NULL\n");
}
else if (strcmp(tigString2->type, "String") != 0)
{
printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:tigNumber Equals:%s Valid:\"String\"\n", tigString2->type);
}
if (index < 0 || index > TIGStringLength(tigString1))
{
printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:index Equals:%d Valid:0 to %d\n", index, TIGStringLength(tigString1));
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
char *newString = (char *)malloc(strlen(tigString1->string) + strlen(tigString2->string) + 1);
if (index == strlen(tigString1->string))
{
strcat(newString, tigString1->string);
strcat(newString, tigString2->string);
}
else
{
char character[2];
int i;
for (i = 0; i < strlen(tigString1->string); i++)
{
character[0] = tigString1->string[i];
character[1] = '\0';
if (index == i)
{
strcat(newString, tigString2->string);
}
strcat(newString, character);
}
}
TIGValue *theString = TIGStringInput(NULL, newString);
free(newString);
newString = NULL;
return theString;
}
TIGValue *TIGStringCharacterAtIndex(TIGValue *tigString, int index)
{
if (tigString == NULL || index < 0 || index >= TIGStringLength(tigString))
{
#ifdef TIG_DEBUG
if (tigString == NULL)
{
printf("ERROR Function:TIGStringCharacterAtIndex() Variable:tigString Equals:NULL\n");
}
if (index < 0 || index >= TIGStringLength(tigString))
{
printf("ERROR Function:TIGStringCharacterAtIndex() Variable:index Equals:%d Valid:0 to %d\n", index, TIGStringLength(tigString) - 1);
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
char *character = TIGStringOutput(tigString);
return TIGStringWithFormat(NULL, "%c", character[index]);
}
void TIGStringRemoveCharacterAtIndex(TIGValue *tigString, int index)
{
if (tigString == NULL || index < 0 || index >= TIGStringLength(tigString))
{
#ifdef TIG_DEBUG
if (tigString == NULL)
{
printf("ERROR Function:TIGStringRemoveCharacterAtIndex() Variable:tigString Equals:NULL\n");
}
if (index < 0 || index >= TIGStringLength(tigString))
{
printf("ERROR Function:TIGStringRemoveCharacterAtIndex() Variable:index Equals:%d Valid:0 to %d\n", index, TIGStringLength(tigString) - 1);
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return;
}
int length = TIGStringLength(tigString);
char *characters = TIGStringOutput(tigString);
// Since a character is being removed don't add +1 to the malloc length
char *newCharacters = (char *)malloc(length * sizeof(char));
int newIndex = 0;
int i;
for (i = 0; i < length; i++)
{
if (index != i)
{
newCharacters[newIndex] = characters[i];
newIndex++;
}
}
TIGStringInput(tigString, newCharacters);
free(newCharacters);
newCharacters = NULL;
}
TIGValue *TIGStringFromNumber(TIGValue *tigNumber)
{
if (tigNumber == NULL || strcmp(tigNumber->type, "Number") != 0)
{
#ifdef TIG_DEBUG
if (tigNumber == NULL)
{
printf("ERROR Function:TIGStringFromNumber() Variable:tigNumber Equals:NULL\n");
}
else if (strcmp(tigNumber->type, "Number") != 0)
{
printf("ERROR Function:TIGStringFromNumber() Variable:tigNumber->type Equals:%s Valid:\"Number\"\n", tigNumber->type);
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
else
{
int stringLength = snprintf( NULL, 0, "%f", tigNumber->number) + 1;
char *stringBuffer = (char *)malloc(stringLength * sizeof(char));
if (stringBuffer == NULL)
{
#ifdef TIG_DEBUG
printf("ERROR Function:TIGStringFromNumber() Variable:stringBuffer Equals:NULL\n");
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
snprintf(stringBuffer, stringLength, "%f", tigNumber->number);
TIGValue *tigString = TIGStringInput(NULL, stringBuffer);
free(stringBuffer);
stringBuffer = NULL;
return tigString;
}
}
TIGBool TIGStringEqualsString(TIGValue *tigString1, TIGValue *tigString2)
{
if (tigString1 != NULL && strcmp(tigString1->type, "String") == 0 && tigString2 != NULL && strcmp(tigString2->type, "String") == 0
&& strcmp(tigString1->string, tigString2->string) == 0)
{
return TIGYes;
}
return TIGNo;
}
TIGValue *TIGStringObjectType(TIGValue *tigObject)
{
if (tigObject == NULL || tigObject->type == NULL)
{
#ifdef TIG_DEBUG
if (tigObject == NULL)
{
printf("ERROR Function:TIGStringObjectType() Variable:tigObject Equals:NULL\n");
}
else if (tigObject->type == NULL)
{
printf("ERROR Function:TIGStringObjectType() Variable:tigObject->type Equals:NULL\n");
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
return TIGStringInput(NULL, tigObject->type);
}
TIGValue *TIGStringAddEscapeCharacters(TIGValue *tigString)
{
if (tigString == NULL || strcmp(tigString->type, "String") != 0)
{
#ifdef TIG_DEBUG
if (tigString == NULL)
{
printf("ERROR Function:TIGStringAddEscapeCharacters() Variable:tigString Equals:NULL\n");
}
else if (strcmp(tigString->type, "String") != 0)
{
printf("ERROR Function:TIGStringAddEscapeCharacters() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type);
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
char *string = tigString->string;
int extraCount = 0;
int i;
for (i = 0; i < strlen(string); i++)
{
switch (string[i])
{
case '"':
case '\\':
case '/':
case '\b':
case '\f':
case '\n':
case '\r':
case '\t':
extraCount++;
break;
}
}
if (extraCount > 0)
{
char *newString = (char *)malloc((strlen(string) + extraCount + 1) * sizeof(char));
int index = 0;
if (newString == NULL)
{
#ifdef TIG_DEBUG
printf("ERROR Function:TIGStringAddEscapeCharacters() Variable:newString Equals:NULL\n");
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
for (i = 0; i < strlen(string); i++)
{
switch (string[i])
{
case '\"':
newString[index] = '\\';
newString[index + 1] = '"';
index += 2;
break;
case '\\':
newString[index] = '\\';
newString[index + 1] = '\\';
index += 2;
break;
case '/':
newString[index] = '\\';
newString[index + 1] = '/';
index += 2;
break;
case '\b':
newString[index] = '\\';
newString[index + 1] = 'b';
index += 2;
break;
case '\f':
newString[index] = '\\';
newString[index + 1] = 'f';
index += 2;
break;
case '\n':
newString[index] = '\\';
newString[index + 1] = 'n';
index += 2;
break;
case '\r':
newString[index] = '\\';
newString[index + 1] = 'r';
index += 2;
break;
case '\t':
newString[index] = '\\';
newString[index + 1] = 't';
index += 2;
break;
default:
newString[index] = string[i];
index++;
break;
}
}
TIGValue *theNewTIGString = TIGStringInput(NULL, newString);
free(newString);
newString = NULL;
return theNewTIGString;
}
return tigString;
}
TIGValue *TIGStringRemoveEscapeCharacters(TIGValue *tigString)
{
if (tigString == NULL || strcmp(tigString->type, "String") != 0)
{
#ifdef TIG_DEBUG
if (tigString == NULL)
{
printf("ERROR Function:TIGStringRemoveEscapeCharacters() Variable:tigString Equals:NULL\n");
}
else if (strcmp(tigString->type, "String") != 0)
{
printf("ERROR Function:TIGStringRemoveEscapeCharacters() Variable:tigObject->type Equals:%s Valid:\"String\"\n", tigString->type);
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
char *string = tigString->string;
int extraCount = 0;
int i;
for (i = 0; i < strlen(string); i++)
{
if (string[i] == '\\')
{
switch (string[i + 1])
{
case '"':
case '\\':
case '/':
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
extraCount++;
// Below makes sure it is not read as something like \\t instead of \\ and \t
i++;
break;
}
}
}
//printf("extraCount %d\n", extraCount);
if (extraCount > 0)
{
char *newString = (char *)malloc(((strlen(string) - extraCount) + 1) * sizeof(char));
int index = 0;
if (newString == NULL)
{
#ifdef TIG_DEBUG
printf("ERROR Function:TIGStringRemoveEscapeCharacters() Variable:newString Equals:NULL\n");
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
for (i = 0; i < strlen(string); i++)
{
if (string[i] == '\\')
{
switch (string[i + 1])
{
case '\"':
newString[index] = '"';
index++;
i++;
break;
case '\\':
newString[index] = '\\';
index++;
i++;
break;
case '/':
newString[index] = '/';
index++;
i++;
break;
case 'b':
newString[index] = '\b';
index++;
i++;
break;
case 'f':
newString[index] = '\f';
index++;
i++;
break;
case 'n':
newString[index] = '\n';
index++;
i++;
break;
case 'r':
newString[index] = '\r';
index++;
i++;
break;
case 't':
newString[index] = '\t';
index++;
i++;
break;
}
}
else
{
newString[index] = string[i];
index++;
}
}
newString[index] = '\0';
TIGValue *theNewTIGString = TIGStringInput(NULL, newString);
if (newString != NULL)
{
free(newString);
newString = NULL;
}
return theNewTIGString;
}
return tigString;
}
TIGValue *TIGStringWithFormat(TIGValue *tigString, const char *format, ...)
{
va_list arguments;
// Find out how long the string is when the arguments are converted to text
va_start(arguments, format);
int stringLength = vsnprintf( NULL, 0, format, arguments) + 1;
va_end(arguments);
// Create the new buffer with the new string length
char *stringBuffer = (char *)malloc(stringLength * sizeof(char));
if (stringBuffer == NULL)
{
#ifdef TIG_DEBUG
printf("ERROR Function:TIGStringWithFormat() Variable:stringBuffer Equals:NULL\n");
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
else
{
// Use the new length of text and add the arguments to the new string buffer
va_start(arguments, format);
vsnprintf(stringBuffer, stringLength, format, arguments);
va_end(arguments);
if (stringBuffer != NULL)
{
if (tigString == NULL)
{
tigString = TIGStringInput(tigString, stringBuffer);
}
else if (tigString->string != NULL && strcmp(tigString->type, "String") == 0)
{
//printf("Length: %d\n", (int)(strlen(tigString->string) + stringLength));
// stringLength already has +1 added to it for the '\0' so adding another +1 below is not necessary
tigString->string = (char *)realloc(tigString->string, (strlen(tigString->string) + stringLength) * sizeof(char));
strcat(tigString->string, stringBuffer);
}
}
else
{
#ifdef TIG_DEBUG
if (tigString->string == NULL)
{
printf("ERROR Function:TIGStringWithFormat() Variable:tigString->string Equals:NULL\n");
}
if (strcmp(tigString->type, "String") != 0)
{
printf("ERROR Function:TIGStringWithFormat() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type);
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
free(stringBuffer);
stringBuffer = NULL;
}
return tigString;
}
TIGValue *TIGStringWithAddedString(TIGValue *oldTigString, TIGValue *newTigString)
{
if (oldTigString == NULL || newTigString == NULL || oldTigString->string == NULL)
{
#ifdef TIG_DEBUG
if (oldTigString == NULL)
{
printf("ERROR Function:TIGStringWithAddedString() Variable:oldTigString Equals:NULL\n");
}
else if (oldTigString->string == NULL)
{
printf("ERROR Function:TIGStringWithAddedString() Variable:oldTigString->string Equals:NULL\n");
}
if (newTigString == NULL)
{
printf("ERROR Function:TIGStringWithAddedString() Variable:newTigString Equals:NULL\n");
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
oldTigString = TIGStringInsertStringAtIndex(oldTigString, newTigString, (int)strlen(oldTigString->string));
return oldTigString;
}
TIGValue *TIGStringFromObject(TIGValue *tigObject)
{
if (tigObject == NULL || strcmp(tigObject->type, "Object") != 0)
{
#ifdef TIG_DEBUG
if (tigObject == NULL)
{
printf("ERROR Function:TIGStringFromObject() Variable:tigObject Equals:NULL\n");
}
else if (strcmp(tigObject->type, "Object") != 0)
{
printf("ERROR Function:TIGStringFromObject() Variable:tigObject->type Equals:%s Valid:\"Object\"\n", tigObject->type);
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
TIGObjectStartStack(NULL);
TIGArrayStartStack(NULL);
TIGNumberStartStack(NULL);
TIGValue *theString = TIGStringFromObjectWithLevel(NULL, tigObject, 1, TIGYes);
TIGNumberEndStack(NULL);
TIGArrayEndStack(NULL);
TIGObjectEndStack(NULL);
return theString;
}
TIGValue *TIGStringFromObjectForNetwork(TIGValue *tigObject)
{
if (tigObject == NULL || strcmp(tigObject->type, "Object") != 0)
{
#ifdef TIG_DEBUG
if (tigObject == NULL)
{
printf("ERROR Function:TIGStringFromObjectForNetwork() Variable:tigObject Equals:NULL\n");
}
else if (strcmp(tigObject->type, "Object") != 0)
{
printf("ERROR Function:TIGStringFromObjectForNetwork() Variable:tigObject->type Equals:%s Valid:\"Object\"\n", tigObject->type);
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
TIGObjectStartStack(NULL);
TIGArrayStartStack(NULL);
TIGNumberStartStack(NULL);
TIGValue *theString = TIGStringFromObjectWithLevel(NULL, tigObject, 1, TIGNo);
TIGNumberEndStack(NULL);
TIGArrayEndStack(NULL);
TIGObjectEndStack(NULL);
return theString;
}
TIGValue *TIGStringFromArray(TIGValue *tigArray)
{
if (tigArray == NULL || strcmp(tigArray->type, "Array") != 0)
{
#ifdef TIG_DEBUG
if (tigArray == NULL)
{
printf("ERROR Function:TIGStringFromArray() Variable:tigArray Equals:NULL\n");
}
else if (strcmp(tigArray->type, "Array") != 0)
{
printf("ERROR Function:TIGStringFromArray() Variable:tigArray->type Equals:%s Valid:\"Array\"\n", tigArray->type);
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
TIGObjectStartStack(NULL);
TIGArrayStartStack(NULL);
TIGNumberStartStack(NULL);
TIGValue *theString = TIGStringFromObjectWithLevel(NULL, tigArray, 1, TIGYes);
TIGNumberEndStack(NULL);
TIGArrayEndStack(NULL);
TIGObjectEndStack(NULL);
return theString;
}
TIGValue *TIGStringFromArrayForNetwork(TIGValue *tigArray)
{
if (tigArray == NULL || strcmp(tigArray->type, "Array") != 0)
{
#ifdef TIG_DEBUG
if (tigArray == NULL)
{
printf("ERROR Function:TIGStringFromArrayForNetwork() Variable:tigArray Equals:NULL\n");
}
else if (strcmp(tigArray->type, "Array") != 0)
{
printf("ERROR Function:TIGStringFromArrayForNetwork() Variable:tigArray->type Equals:%s Valid:\"Array\"\n", tigArray->type);
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return NULL;
}
TIGObjectStartStack(NULL);
TIGArrayStartStack(NULL);
TIGNumberStartStack(NULL);
TIGValue *theString = TIGStringFromObjectWithLevel(NULL, tigArray, 1, TIGNo);
TIGNumberEndStack(NULL);
TIGArrayEndStack(NULL);
TIGObjectEndStack(NULL);
return theString;
}
// The JSON string outputs a TIGString but the functions below have their own stack
TIGValue *TIGStringFromObjectWithLevel(TIGValue *tigString, TIGValue *tigValue, int level, TIGBool useEscapeCharacters)
{
int i;
if (strcmp(tigValue->type, "Array") == 0)
{
TIGValue *theTIGStringTabs = NULL;
TIGValue *theTIGStringEndTab = NULL;
if (useEscapeCharacters)
{
for (i = 0; i < level; i++)
{
theTIGStringTabs = TIGStringWithFormat(theTIGStringTabs, "\t");
if (i < level - 1)
{
theTIGStringEndTab = TIGStringWithFormat(theTIGStringEndTab, "\t");
}
}
tigString = TIGStringWithFormat(tigString, "[\n");
}
else
{
tigString = TIGStringWithFormat(tigString, "[");
}
for (i = 0; i < TIGArrayCount(tigValue); i++)
{
TIGValue *theTIGValue = TIGArrayValueAtIndex(tigValue, i);
if (useEscapeCharacters)
{
tigString = TIGStringWithAddedString(tigString, theTIGStringTabs);
}
tigString = TIGStringFromObjectWithLevel(tigString, theTIGValue, level + 1, useEscapeCharacters);
if (useEscapeCharacters)
{
if (i < TIGArrayCount(tigValue) - 1)
{
tigString = TIGStringWithFormat(tigString, ",\n");
}
else
{
tigString = TIGStringWithFormat(tigString, "\n");
}
}
else
{
if (i < TIGArrayCount(tigValue) - 1)
{
tigString = TIGStringWithFormat(tigString, ",");
}
}
}
if (level > 1 && useEscapeCharacters)
{
tigString = TIGStringWithAddedString(tigString, theTIGStringEndTab);
}
tigString = TIGStringWithFormat(tigString, "]");
}
else if (strcmp(tigValue->type, "Number") == 0)
{
if (tigValue->string != NULL)
{
if (strcmp(tigValue->string, "false") == 0 || strcmp(tigValue->string, "true") == 0)
{
tigString = TIGStringWithAddedString(tigString, TIGStringInput(NULL, tigValue->string));
}
}
else
{
tigString = TIGStringWithAddedString(tigString, TIGStringFromNumber(tigValue));
}
}
else if (strcmp(tigValue->type, "Object") == 0)
{
TIGValue *theTIGArrayStrings = TIGArrayOfObjectStrings(tigValue);
TIGValue *theTIGArrayValues = TIGArrayOfObjectValues(tigValue);
TIGValue *theTIGStringTabs = NULL;
TIGValue *theTIGStringEndTab = NULL;
if (useEscapeCharacters)
{
for (i = 0; i < level; i++)
{
theTIGStringTabs = TIGStringWithFormat(theTIGStringTabs, "\t");
if (i < level - 1)
{
theTIGStringEndTab = TIGStringWithFormat(theTIGStringEndTab, "\t");
}
}
tigString = TIGStringWithFormat(tigString, "{\n");
}
else
{
tigString = TIGStringWithFormat(tigString, "{");
}
for (i = 0; i < TIGArrayCount(theTIGArrayStrings); i++)
{
TIGValue *theTIGString = TIGArrayValueAtIndex(theTIGArrayStrings, i);
TIGValue *theTIGValue = TIGArrayValueAtIndex(theTIGArrayValues, i);
if (useEscapeCharacters)
{
tigString = TIGStringWithAddedString(tigString, theTIGStringTabs);
tigString = TIGStringWithFormat(tigString, "\"%s\": ", TIGStringOutput(TIGStringAddEscapeCharacters(theTIGString)));
}
else
{
tigString = TIGStringWithFormat(tigString, "\"%s\":", TIGStringOutput(TIGStringAddEscapeCharacters(theTIGString)));
}
tigString = TIGStringFromObjectWithLevel(tigString, theTIGValue, level + 1, useEscapeCharacters);
if (useEscapeCharacters)
{
if (i < TIGArrayCount(theTIGArrayStrings) - 1)
{
tigString = TIGStringWithFormat(tigString, ",\n");
}
else
{
tigString = TIGStringWithFormat(tigString, "\n");
}
}
else
{
if (i < TIGArrayCount(theTIGArrayStrings) - 1)
{
tigString = TIGStringWithFormat(tigString, ",");
}
}
}
if (level > 1 && useEscapeCharacters)
{
tigString = TIGStringWithAddedString(tigString, theTIGStringEndTab);
}
tigString = TIGStringWithFormat(tigString, "}");
}
else if (strcmp(tigValue->type, "String") == 0)
{
tigString = TIGStringWithFormat(tigString, "\"%s\"", TIGStringOutput(TIGStringAddEscapeCharacters(tigValue)));
}
return tigString;
}
void TIGStringWriteWithFilename(TIGValue *tigString, TIGValue *filenameString)
{
if (tigString == NULL || filenameString == NULL || strcmp(tigString->type, "String") != 0 || strcmp(filenameString->type, "String") != 0)
{
#ifdef TIG_DEBUG
if (tigString == NULL)
{
printf("ERROR Function:TIGStringWriteWithFilename() Variable:tigString Equals:NULL\n");
}
else if (strcmp(tigString->type, "String") != 0)
{
printf("ERROR Function:TIGStringWriteWithFilename() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type);
}
if (filenameString == NULL)
{
printf("ERROR Function:TIGStringWriteWithFilename() Variable:filenameString Equals:NULL\n");
}
else if (strcmp(filenameString->type, "String") != 0)
{
printf("ERROR Function:TIGStringWriteWithFilename() Variable:filenameString->type Equals:%s Valid:\"String\"\n", filenameString->type);
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
}
else
{
FILE *theFile = fopen(filenameString->string, "w");
if (theFile != NULL)
{
fprintf(theFile, "%s", tigString->string);
}
else
{
#ifdef TIG_DEBUG
printf("ERROR Function:TIGStringWriteWithFilename() Variable:theFile Equals:NULL\n");
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
}
fclose(theFile);
}
}
TIGValue *TIGStringReadFromFilename(TIGValue *filenameString)
{
if (filenameString == NULL || filenameString->string == NULL || strcmp(filenameString->type, "String") != 0)
{
if (filenameString == NULL)
{
printf("ERROR Function:TIGStringWriteWithFilename() Variable:tigString Equals:NULL\n");
}
else
{
if (strcmp(filenameString->type, "String") != 0)
{
printf("ERROR Function:TIGStringWriteWithFilename() Variable:filenameString->type Equals:%s Valid:\"String\"\n", filenameString->type);
}
if (filenameString->string == NULL)
{
printf("ERROR Function:TIGStringWriteWithFilename() Variable:filenameString->string Equals:NULL\n");
}
}
return NULL;
}
FILE *theFile = fopen(filenameString->string, "r");
int index = 0, block = 1, maxBlockLength = 100;
char *newString = NULL;
char *buffer = malloc(maxBlockLength * sizeof(char));
if (theFile == NULL)
{
#ifdef TIG_DEBUG
printf("ERROR Function:TIGStringReadFromFilename() Variable:theFile Equals:NULL\n");
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
if (buffer != NULL)
{
free(buffer);
buffer = NULL;
}
fclose(theFile);
return NULL;
}
if (buffer == NULL)
{
#ifdef TIG_DEBUG
printf("ERROR Function:TIGStringReadFromFilename() Variable:buffer Equals:NULL\n");
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
fclose(theFile);
return NULL;
}
while (1)
{
buffer[index] = fgetc(theFile);
if ((buffer[index] != EOF && index >= maxBlockLength - 2) || buffer[index] == EOF)
{
int stringLength;
buffer[index + 1] = '\0';
if (newString == NULL)
{
stringLength = 0;
}
else
{
stringLength = (int)strlen(newString);
}
if (buffer[index] == EOF)
{
//printf("END Buffer: %d String Length: %d\n", (int)strlen(buffer), stringLength);
// Since the "buffer" variable already has '\0' +1 is not needed
newString = realloc(newString, (strlen(buffer) + stringLength) * sizeof(char));
}
else
{
//printf("Buffer: %d String Length: %d\n", (int)strlen(buffer), stringLength);
newString = realloc(newString, (strlen(buffer) + stringLength) * sizeof(char));
}
if (newString == NULL)
{
#ifdef TIG_DEBUG
printf("ERROR Function:TIGStringReadFromFilename() Variable:newString Equals:NULL\n");
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
free(buffer);
buffer = NULL;
fclose(theFile);
return NULL;
}
strcat(newString, buffer);
if (buffer[index] == EOF)
{
//printf("Total String Length: %d", (int)strlen(newString));
// Since the "buffer" always uses the same size block '\0' with -1 is needed for the last index number
newString[strlen(newString) - 1] = '\0';
free(buffer);
buffer = NULL;
break;
}
else
{
free(buffer);
buffer = NULL;
buffer = malloc(maxBlockLength * sizeof(char));
index = -1;
block++;
}
}
index++;
}
fclose(theFile);
TIGValue *theString = TIGStringInput(NULL, newString);
free(newString);
newString = NULL;
return theString;
}
TIGBool TIGStringPrefix(TIGValue *tigString, TIGValue *tigStringPrefix)
{
if (tigString == NULL || strcmp(tigString->type, "String") != 0 || tigStringPrefix == NULL || strcmp(tigStringPrefix->type, "String") != 0)
{
#ifdef TIG_DEBUG
if (tigString == NULL)
{
printf("ERROR Function:TIGStringPrefix() Variable:tigString Equals:NULL\n");
}
else if (strcmp(tigString->type, "String") != 0)
{
printf("ERROR Function:TIGStringPrefix() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type);
}
if (tigStringPrefix == NULL)
{
printf("ERROR Function:TIGStringPrefix() Variable:tigStringPrefix Equals:NULL\n");
}
else if (strcmp(tigStringPrefix->type, "String") != 0)
{
printf("ERROR Function:TIGStringPrefix() Variable:tigStringPrefix->type Equals:%s Valid:\"String\"\n", tigStringPrefix->type);
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return TIGNo;
}
if (strlen(tigString->string) > 0 && strlen(tigStringPrefix->string) > 0)
{
int i;
for (i = 0; i < strlen(tigString->string); i++)
{
if (tigString->string[i] == tigStringPrefix->string[i])
{
// The prefix has been found
if (i >= strlen(tigStringPrefix->string) - 1)
{
return TIGYes;
}
}
else
{
return TIGNo;
}
}
}
return TIGNo;
}
TIGBool TIGStringSuffix(TIGValue *tigString, TIGValue *tigStringSuffix)
{
if (tigString == NULL || strcmp(tigString->type, "String") != 0 || tigStringSuffix == NULL || strcmp(tigStringSuffix->type, "String") != 0)
{
#ifdef TIG_DEBUG
if (tigString == NULL)
{
printf("ERROR Function:TIGStringSuffix() Variable:tigString Equals:NULL\n");
}
else if (strcmp(tigString->type, "String") != 0)
{
printf("ERROR Function:TIGStringSuffix() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type);
}
if (tigStringSuffix == NULL)
{
printf("ERROR Function:TIGStringSuffix() Variable:tigStringSuffix Equals:NULL\n");
}
else if (strcmp(tigStringSuffix->type, "String") != 0)
{
printf("ERROR Function:TIGStringSuffix() Variable:tigStringSuffix->type Equals:%s Valid:\"String\"\n", tigStringSuffix->type);
}
#ifdef TIG_DEBUG_ASSERT
assert(0);
#endif
#endif
return TIGNo;
}
if (strlen(tigString->string) > 0 && strlen(tigStringSuffix->string) > 0)
{
int suffixIndex = 0, suffixTotal = (int)strlen(tigStringSuffix->string), index = 0, total = (int)strlen(tigString->string);
while (1)
{
if (tigString->string[total - index - 1] == tigStringSuffix->string[suffixTotal - suffixIndex - 1])
{
// The suffix was found
if (suffixIndex >= suffixTotal - 1)
{
return TIGYes;
}
suffixIndex++;
index++;
}
else
{
return TIGNo;
}
}
}
return TIGNo;
}
|
using System.Collections.Generic;
using UnityEngine;
using System;
namespace AI
{
public class GreedyAIController : PlayerController
{
enum NextState
{
Wait, Draw, Play
}
private NextState nextState;
Dictionary<DominoController, List<DominoController>> placesToPlay = null;
private void Update()
{
switch (nextState)
{
case NextState.Wait:
return;
case NextState.Draw:
if (history.horizontalDominoes.Count > 0)
{
placesToPlay = PlacesToPlay();
if (placesToPlay.Count == 0)
{
base.DrawDomino();
placesToPlay = PlacesToPlay();
if (placesToPlay.Count == 0)
{
nextState = NextState.Wait;
gameController.PlayerIsBlocked(this);
return;
}
}
}
nextState = NextState.Play;
break;
case NextState.Play:
List<ChosenWayToPlay> waysToPlay = new List<ChosenWayToPlay>();
if (history.horizontalDominoes.Count == 0)
{
foreach (DominoController domino in dominoControllers)
{
waysToPlay.Add(new ChosenWayToPlay(domino, null));
}
}
else
{
foreach (KeyValuePair<DominoController, List<DominoController>> entry in placesToPlay)
{
List<DominoController> list = entry.Value;
foreach (DominoController chosenPlace in list)
{
ChosenWayToPlay chosenWayToPlay = new ChosenWayToPlay(entry.Key, chosenPlace);
waysToPlay.Add(chosenWayToPlay);
}
}
}
// From small to large
waysToPlay.Sort(delegate (ChosenWayToPlay x, ChosenWayToPlay y)
{
int xScore = GetScoreOfChosenWay(x);
int yScore = GetScoreOfChosenWay(y);
return xScore - yScore;
});
ChosenWayToPlay bestWayToPlay = waysToPlay[waysToPlay.Count - 1];
PlaceDomino(bestWayToPlay.chosenDomino, bestWayToPlay.chosenPlace, history);
dominoControllers.Remove(bestWayToPlay.chosenDomino);
// Debug
Debug.Log("Chosen Domino: " + bestWayToPlay.chosenDomino.leftValue + ", " + bestWayToPlay.chosenDomino.rightValue + ", " + bestWayToPlay.chosenDomino.upperValue + ", " + bestWayToPlay.chosenDomino.lowerValue);
if (bestWayToPlay.chosenPlace != null)
{
Debug.Log("Chosen Place: " + bestWayToPlay.chosenPlace.leftValue + ", " + bestWayToPlay.chosenPlace.rightValue + ", " + bestWayToPlay.chosenPlace.upperValue + ", " + bestWayToPlay.chosenPlace.lowerValue);
}
Debug.Log(Environment.StackTrace);
nextState = NextState.Wait;
gameController.PlayerPlayDomino(this, bestWayToPlay.chosenDomino, bestWayToPlay.chosenPlace);
break;
}
}
public override void PlayDomino()
{
nextState = NextState.Draw;
}
private Dictionary<DominoController, List<DominoController>> PlacesToPlay()
{
Dictionary<DominoController, List<DominoController>> placesToPlay = new Dictionary<DominoController, List<DominoController>>(dominoControllers.Count * 4);
foreach (DominoController domino in dominoControllers)
{
// Add places can be played for each domino
List<DominoController> places = base.ListOfValidPlaces(domino);
if (places == null)
{
continue;
}
placesToPlay.Add(domino, places);
}
return placesToPlay;
}
private int GetScoreOfChosenWay(ChosenWayToPlay wayToPlay)
{
int score = 0;
// If history has no domino
if (history.horizontalDominoes.Count == 0)
{
if (wayToPlay.chosenDomino.direction == DominoController.Direction.Horizontal)
{
int value = wayToPlay.chosenDomino.leftValue + wayToPlay.chosenDomino.rightValue;
score = (value % 5 == 0) ? value : 0;
}
else
{
int value = wayToPlay.chosenDomino.upperValue + wayToPlay.chosenDomino.lowerValue;
score = (value % 5 == 0) ? value : 0;
}
return score;
}
// Else that history has at least 1 domino
DominoController copiedDomino = Instantiate<DominoController>(wayToPlay.chosenDomino);
HistoryController copiedHistory = Instantiate<HistoryController>(history);
// Simulate to place a domino and then calculate the sum
PlaceDomino(copiedDomino, wayToPlay.chosenPlace, copiedHistory);
copiedHistory.Add(copiedDomino, wayToPlay.chosenPlace);
score = Utility.GetSumOfHistoryDominoes(copiedHistory.horizontalDominoes, copiedHistory.verticalDominoes, copiedHistory.spinner);
score = score % 5 == 0 ? score : 0;
Destroy(copiedDomino.gameObject);
Destroy(copiedHistory.gameObject);
return score;
}
private void PlaceDomino(DominoController chosenDomino, DominoController chosenPlace, HistoryController history)
{
DominoController clickedDomino = chosenPlace;
int horizontalLen = history.horizontalDominoes.Count;
int verticalLen = history.verticalDominoes.Count;
if (chosenDomino != null)
{
if (chosenPlace != null)
{
if (chosenPlace == history.horizontalDominoes[0])
{
if (clickedDomino.leftValue == -1)
{
if (chosenDomino.upperValue == clickedDomino.upperValue || chosenDomino.lowerValue == clickedDomino.upperValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.upperValue == clickedDomino.upperValue)
chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue);
else
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
return;
}
}
else
{
if (chosenDomino.upperValue == clickedDomino.leftValue && chosenDomino.upperValue == chosenDomino.lowerValue)
{
chosenPlace = clickedDomino;
return;
}
else if (chosenDomino.upperValue == clickedDomino.leftValue || chosenDomino.lowerValue == clickedDomino.leftValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.upperValue == clickedDomino.leftValue)
chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue);
else
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
return;
}
}
}
if (clickedDomino == history.horizontalDominoes[horizontalLen - 1])
{
if (clickedDomino.leftValue == -1)
{
if (chosenDomino.upperValue == clickedDomino.upperValue || chosenDomino.lowerValue == clickedDomino.upperValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.upperValue == clickedDomino.upperValue)
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
else
chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue);
return;
}
}
else
{
if (chosenDomino.upperValue == clickedDomino.rightValue && chosenDomino.upperValue == chosenDomino.lowerValue)
{
chosenPlace = clickedDomino;
return;
}
else if (chosenDomino.upperValue == clickedDomino.rightValue || chosenDomino.lowerValue == clickedDomino.rightValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.upperValue == clickedDomino.rightValue)
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
else
chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue);
return;
}
}
}
if (verticalLen > 0 && clickedDomino == history.verticalDominoes[0])
{
if (clickedDomino.leftValue == -1)
{
if (chosenDomino.upperValue == clickedDomino.upperValue && chosenDomino.upperValue == chosenDomino.lowerValue)
{
chosenPlace = clickedDomino;
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
return;
}
else if (chosenDomino.upperValue == clickedDomino.upperValue || chosenDomino.lowerValue == clickedDomino.upperValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.upperValue == clickedDomino.upperValue)
chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue);
return;
}
}
else
{
if (chosenDomino.upperValue == clickedDomino.leftValue || chosenDomino.lowerValue == clickedDomino.leftValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.upperValue == clickedDomino.leftValue)
chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue);
return;
}
}
}
if (verticalLen > 0 && clickedDomino == history.verticalDominoes[verticalLen - 1])
{
if (clickedDomino.leftValue == -1)
{
if (chosenDomino.upperValue == clickedDomino.lowerValue && chosenDomino.upperValue == chosenDomino.lowerValue)
{
chosenPlace = clickedDomino;
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
return;
}
else if (chosenDomino.upperValue == clickedDomino.lowerValue || chosenDomino.lowerValue == clickedDomino.lowerValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.lowerValue == clickedDomino.lowerValue)
chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue);
return;
}
}
else
{
if (chosenDomino.upperValue == clickedDomino.leftValue || chosenDomino.lowerValue == clickedDomino.leftValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.lowerValue == clickedDomino.leftValue)
chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue);
return;
}
}
}
}
else
{
if (chosenDomino.upperValue != chosenDomino.lowerValue)
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
}
}
}
}
}
|
b'(-16 - (0 - 14)) + 7 + -3\n'
|
async function test(object) {
for (var key in object) {
await key;
}
}
|
'use strict';
var clear = require('es5-ext/array/#/clear')
, eIndexOf = require('es5-ext/array/#/e-index-of')
, setPrototypeOf = require('es5-ext/object/set-prototype-of')
, callable = require('es5-ext/object/valid-callable')
, d = require('d')
, ee = require('event-emitter')
, Symbol = require('es6-symbol')
, iterator = require('es6-iterator/valid-iterable')
, forOf = require('es6-iterator/for-of')
, Iterator = require('./lib/iterator')
, isNative = require('./is-native-implemented')
, call = Function.prototype.call, defineProperty = Object.defineProperty
, SetPoly, getValues;
module.exports = SetPoly = function (/*iterable*/) {
var iterable = arguments[0];
if (!(this instanceof SetPoly)) return new SetPoly(iterable);
if (this.__setData__ !== undefined) {
throw new TypeError(this + " cannot be reinitialized");
}
if (iterable != null) iterator(iterable);
defineProperty(this, '__setData__', d('c', []));
if (!iterable) return;
forOf(iterable, function (value) {
if (eIndexOf.call(this, value) !== -1) return;
this.push(value);
}, this.__setData__);
};
if (isNative) {
if (setPrototypeOf) setPrototypeOf(SetPoly, Set);
SetPoly.prototype = Object.create(Set.prototype, {
constructor: d(SetPoly)
});
}
ee(Object.defineProperties(SetPoly.prototype, {
add: d(function (value) {
if (this.has(value)) return this;
this.emit('_add', this.__setData__.push(value) - 1, value);
return this;
}),
clear: d(function () {
if (!this.__setData__.length) return;
clear.call(this.__setData__);
this.emit('_clear');
}),
delete: d(function (value) {
var index = eIndexOf.call(this.__setData__, value);
if (index === -1) return false;
this.__setData__.splice(index, 1);
this.emit('_delete', index, value);
return true;
}),
entries: d(function () { return new Iterator(this, 'key+value'); }),
forEach: d(function (cb/*, thisArg*/) {
var thisArg = arguments[1], iterator, result, value;
callable(cb);
iterator = this.values();
result = iterator._next();
while (result !== undefined) {
value = iterator._resolve(result);
call.call(cb, thisArg, value, value, this);
result = iterator._next();
}
}),
has: d(function (value) {
return (eIndexOf.call(this.__setData__, value) !== -1);
}),
keys: d(getValues = function () { return this.values(); }),
size: d.gs(function () { return this.__setData__.length; }),
values: d(function () { return new Iterator(this); }),
toString: d(function () { return '[object Set]'; })
}));
defineProperty(SetPoly.prototype, Symbol.iterator, d(getValues));
defineProperty(SetPoly.prototype, Symbol.toStringTag, d('c', 'Set'));
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function(){
var div = document.getElementById('content');
var div1 = document.getElementById('leftbox');
div.style.height = document.body.clientHeight + 'px';
div1.style.height = div.style.height;
var contentToRemove = document.querySelectorAll(".collapsed-navbox");
$(contentToRemove).hide();
var oritop = -100;
$(window).scroll(function() {
var scrollt = window.scrollY;
var elm = $("#leftbox");
if(oritop < 0) {
oritop= elm.offset().top;
}
if(scrollt >= oritop) {
elm.css({"position": "fixed", "top": 0, "left": 0});
}
else {
elm.css("position", "static");
}
});
/*$(window).resize(function() {
var wi = $(window).width();
$("p.testp").text('Screen width is currently: ' + wi + 'px.');
});
$(window).resize(function() {
var wi = $(window).width();
if (wi <= 767){
var contentToRemove = document.querySelectorAll(".fullscreen-navbox");
$(contentToRemove).hide();
var contentToRemove = document.querySelectorAll(".collapsed-navbox");
$(contentToRemove).show();
$("#leftbox").css("width","30px");
$("#content").css("width","90%");
}else if (wi > 800){
var contentToRemove = document.querySelectorAll(".fullscreen-navbox");
$(contentToRemove).show();
var contentToRemove = document.querySelectorAll(".collapsed-navbox");
$(contentToRemove).hide();
$("#leftbox").css("width","15%");
$("#content").css("width","85%");
}
});*/
});
|
b'Calculate -55 - (15 + -49) - -13.\n'
|
b'-6 - (1 - (-7 + -5 - -20))\n'
|
b'(13 - -36) + -14 + -2 + (-4 - -11)\n'
|
b'Calculate -32 - -1 - (-8 + (-17 - (-14 - 3))).\n'
|
b'Evaluate (-8 + 3 - -16 - 5) + (-1 - 13).\n'
|
package com.malalaoshi.android.ui.dialogs;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.malalaoshi.android.R;
import com.malalaoshi.android.core.network.api.ApiExecutor;
import com.malalaoshi.android.core.network.api.BaseApiContext;
import com.malalaoshi.android.core.stat.StatReporter;
import com.malalaoshi.android.core.utils.MiscUtil;
import com.malalaoshi.android.entity.Comment;
import com.malalaoshi.android.network.Constants;
import com.malalaoshi.android.network.api.PostCommentApi;
import com.malalaoshi.android.ui.widgets.DoubleImageView;
import org.json.JSONException;
import org.json.JSONObject;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by donald on 2017/6/29.
*/
public class CommentDialog extends BaseDialog {
private static String ARGS_DIALOG_COMMENT_TYPE = "comment type";
private static String ARGS_DIALOG_TEACHER_NAME = "teacher name";
private static String ARGS_DIALOG_TEACHER_AVATAR = "teacher avatar";
private static String ARGS_DIALOG_LECTURER_NAME = "lecturer name";
private static String ARGS_DIALOG_LECTURER_AVATAR = "lecturer avatar";
private static String ARGS_DIALOG_ASSIST_NAME = "assist name";
private static String ARGS_DIALOG_ASSIST_AVATAR = "assist avatar";
private static String ARGS_DIALOG_COURSE_NAME = "course name";
private static String ARGS_DIALOG_COMMENT = "comment";
private static String ARGS_DIALOG_TIMESLOT = "timeslot";
@Bind(R.id.div_comment_dialog_avatar)
DoubleImageView mDivCommentDialogAvatar;
@Bind(R.id.tv_comment_dialog_teacher_course)
TextView mTvCommentDialogTeacherCourse;
@Bind(R.id.rb_comment_dialog_score)
RatingBar mRbCommentDialogScore;
@Bind(R.id.et_comment_dialog_input)
EditText mEtCommentDialogInput;
@Bind(R.id.tv_comment_dialog_commit)
TextView mTvCommentDialogCommit;
@Bind(R.id.iv_comment_dialog_close)
ImageView mIvCommentDialogClose;
private int mCommentType;
private String mTeacherName;
private String mTeacherAvatar;
private String mLeactureAvatar;
private String mLeactureName;
private String mAssistantAvatar;
private String mAssistantName;
private String mCourseName;
private Comment mComment;
private long mTimeslot;
private OnCommentResultListener mResultListener;
public CommentDialog(Context context) {
super(context);
}
public CommentDialog(Context context, Bundle bundle) {
super(context);
if (bundle != null) {
mCommentType = bundle.getInt(ARGS_DIALOG_COMMENT_TYPE);
if (mCommentType == 0) {
mTeacherName = bundle.getString(ARGS_DIALOG_TEACHER_NAME, "");
mTeacherAvatar = bundle.getString(ARGS_DIALOG_TEACHER_AVATAR, "");
} else if (mCommentType == 1) {
mLeactureAvatar = bundle.getString(ARGS_DIALOG_LECTURER_AVATAR, "");
mLeactureName = bundle.getString(ARGS_DIALOG_LECTURER_NAME, "");
mAssistantAvatar = bundle.getString(ARGS_DIALOG_ASSIST_AVATAR, "");
mAssistantName = bundle.getString(ARGS_DIALOG_ASSIST_NAME, "");
}
mCourseName = bundle.getString(ARGS_DIALOG_COURSE_NAME, "");
mComment = bundle.getParcelable(ARGS_DIALOG_COMMENT);
mTimeslot = bundle.getLong(ARGS_DIALOG_TIMESLOT, 0L);
}
initView();
}
private void initView() {
setCancelable(false);
if (mCommentType == 0)
mDivCommentDialogAvatar.loadImg(mTeacherAvatar, "", DoubleImageView.LOAD_SIGNLE_BIG);
else if (mCommentType == 1)
mDivCommentDialogAvatar.loadImg(mLeactureAvatar, mAssistantAvatar, DoubleImageView.LOAD_DOUBLE);
if (mComment != null) {
StatReporter.commentPage(true);
updateUI(mComment);
mRbCommentDialogScore.setIsIndicator(true);
mEtCommentDialogInput.setFocusableInTouchMode(false);
mEtCommentDialogInput.setCursorVisible(false);
mTvCommentDialogCommit.setText("查看评价");
} else {
StatReporter.commentPage(false);
mTvCommentDialogCommit.setText("提交");
mRbCommentDialogScore.setIsIndicator(false);
mEtCommentDialogInput.setFocusableInTouchMode(true);
mEtCommentDialogInput.setCursorVisible(true);
}
mTvCommentDialogTeacherCourse.setText(mCourseName);
mRbCommentDialogScore.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
if (mComment == null){
if (fromUser && rating > 0 && mEtCommentDialogInput.getText().length() > 0){
mTvCommentDialogCommit.setEnabled(true);
}else {
mTvCommentDialogCommit.setEnabled(false);
}
}
}
});
mEtCommentDialogInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (mComment == null){
if (s.length() > 0 && mRbCommentDialogScore.getRating() > 0){
mTvCommentDialogCommit.setEnabled(true);
}else {
mTvCommentDialogCommit.setEnabled(false);
}
}
}
});
}
@Override
protected View getView() {
View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_comment_v2, null);
ButterKnife.bind(this, view);
return view;
}
private void updateUI(Comment comment) {
if (comment != null) {
mRbCommentDialogScore.setRating(comment.getScore());
mEtCommentDialogInput.setText(comment.getContent());
} else {
mRbCommentDialogScore.setRating(0);
mEtCommentDialogInput.setText("");
}
}
@Override
protected int getDialogStyleId() {
return 0;
}
public static CommentDialog newInstance(Context context, String lecturerName, String lecturerAvatarUrl, String assistName, String assistAvatarUrl, String courseName,
Long timeslot, Comment comment) {
Bundle args = new Bundle();
args.putInt(ARGS_DIALOG_COMMENT_TYPE, 1);
args.putString(ARGS_DIALOG_LECTURER_NAME, lecturerName);
args.putString(ARGS_DIALOG_LECTURER_AVATAR, lecturerAvatarUrl);
args.putString(ARGS_DIALOG_ASSIST_NAME, assistName);
args.putString(ARGS_DIALOG_ASSIST_AVATAR, assistAvatarUrl);
args.putString(ARGS_DIALOG_COURSE_NAME, courseName);
args.putParcelable(ARGS_DIALOG_COMMENT, comment);
args.putLong(ARGS_DIALOG_TIMESLOT, timeslot);
// f.setArguments(args);
CommentDialog f = new CommentDialog(context, args);
return f;
}
public void setOnCommentResultListener(OnCommentResultListener listener) {
mResultListener = listener;
}
public static CommentDialog newInstance(Context context, String teacherName, String teacherAvatarUrl, String courseName,
Long timeslot, Comment comment) {
Bundle args = new Bundle();
args.putInt(ARGS_DIALOG_COMMENT_TYPE, 0);
args.putString(ARGS_DIALOG_TEACHER_NAME, teacherName);
args.putString(ARGS_DIALOG_TEACHER_AVATAR, teacherAvatarUrl);
args.putString(ARGS_DIALOG_COURSE_NAME, courseName);
args.putParcelable(ARGS_DIALOG_COMMENT, comment);
args.putLong(ARGS_DIALOG_TIMESLOT, timeslot);
// f.setArguments(args);
CommentDialog f = new CommentDialog(context, args);
return f;
}
@OnClick({R.id.tv_comment_dialog_commit, R.id.iv_comment_dialog_close})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.tv_comment_dialog_commit:
commit();
dismiss();
break;
case R.id.iv_comment_dialog_close:
dismiss();
break;
}
}
private void commit() {
StatReporter.commentSubmit();
if (mComment != null) {
dismiss();
return;
}
float score = mRbCommentDialogScore.getRating();
if (score == 0.0) {
MiscUtil.toast(R.string.rate_the_course);
return;
}
String content = mEtCommentDialogInput.getText().toString();
if (TextUtils.isEmpty(content)) {
MiscUtil.toast(R.string.write_few_reviews);
return;
}
JSONObject json = new JSONObject();
try {
json.put(Constants.TIMESLOT, mTimeslot);
json.put(Constants.SCORE, score);
json.put(Constants.CONTENT, content);
} catch (JSONException e) {
e.printStackTrace();
return;
}
ApiExecutor.exec(new PostCommentRequest(this, json.toString()));
}
public interface OnCommentResultListener {
void onSuccess(Comment comment);
}
private static final class PostCommentRequest extends BaseApiContext<CommentDialog, Comment> {
private String body;
public PostCommentRequest(CommentDialog commentDialog, String body) {
super(commentDialog);
this.body = body;
}
@Override
public Comment request() throws Exception {
return new PostCommentApi().post(body);
}
@Override
public void onApiSuccess(@NonNull Comment response) {
get().commentSucceed(response);
}
@Override
public void onApiFailure(Exception exception) {
get().commentFailed();
}
}
private void commentFailed() {
MiscUtil.toast(R.string.comment_failed);
}
private void commentSucceed(Comment response) {
MiscUtil.toast(R.string.comment_succeed);
if (mResultListener != null)
mResultListener.onSuccess(response);
dismiss();
}
}
|
b'Calculate 12 - (8 + 7) - -21.\n'
|
b'Evaluate 6 + (2 + -13 + 2 + 2 - 19).\n'
|
b'12 + -1 - (40 + -32 + -15)\n'
|
b'Calculate 10 - (-14 - -7) - 25.\n'
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { TPromise, Promise } from 'vs/base/common/winjs.base';
import { xhr } from 'vs/base/common/network';
import { IConfigurationRegistry, Extensions } from 'vs/platform/configuration/common/configurationRegistry';
import strings = require('vs/base/common/strings');
import nls = require('vs/nls');
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import platform = require('vs/platform/platform');
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { BaseRequestService } from 'vs/platform/request/common/baseRequestService';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { assign } from 'vs/base/common/objects';
import { IXHROptions, IXHRResponse } from 'vs/base/common/http';
import { request } from 'vs/base/node/request';
import { getProxyAgent } from 'vs/base/node/proxy';
import { createGunzip } from 'zlib';
import { Stream } from 'stream';
interface IHTTPConfiguration {
http?: {
proxy?: string;
proxyStrictSSL?: boolean;
};
}
export class RequestService extends BaseRequestService {
private disposables: IDisposable[];
private proxyUrl: string = null;
private strictSSL: boolean = true;
constructor(
@IWorkspaceContextService contextService: IWorkspaceContextService,
@IConfigurationService configurationService: IConfigurationService,
@ITelemetryService telemetryService?: ITelemetryService
) {
super(contextService, telemetryService);
this.disposables = [];
const config = configurationService.getConfiguration<IHTTPConfiguration>();
this.configure(config);
const disposable = configurationService.onDidUpdateConfiguration(e => this.configure(e.config));
this.disposables.push(disposable);
}
private configure(config: IHTTPConfiguration) {
this.proxyUrl = config.http && config.http.proxy;
this.strictSSL = config.http && config.http.proxyStrictSSL;
}
makeRequest(options: IXHROptions): TPromise<IXHRResponse> {
let url = options.url;
if (!url) {
throw new Error('IRequestService.makeRequest: Url is required.');
}
// Support file:// in native environment through XHR
if (strings.startsWith(url, 'file://')) {
return xhr(options).then(null, (xhr: XMLHttpRequest) => {
if (xhr.status === 0 && xhr.responseText) {
return xhr; // loading resources locally returns a status of 0 which in WinJS is an error so we need to handle it here
}
return <any>Promise.wrapError({ status: 404, responseText: nls.localize('localFileNotFound', "File not found.")});
});
}
return super.makeRequest(options);
}
protected makeCrossOriginRequest(options: IXHROptions): TPromise<IXHRResponse> {
const { proxyUrl, strictSSL } = this;
const agent = getProxyAgent(options.url, { proxyUrl, strictSSL });
options = assign({}, options);
options = assign(options, { agent, strictSSL });
return request(options).then(result => new TPromise<IXHRResponse>((c, e, p) => {
const res = result.res;
let stream: Stream = res;
if (res.headers['content-encoding'] === 'gzip') {
stream = stream.pipe(createGunzip());
}
const data: string[] = [];
stream.on('data', c => data.push(c));
stream.on('end', () => {
const status = res.statusCode;
if (options.followRedirects > 0 && (status >= 300 && status <= 303 || status === 307)) {
let location = res.headers['location'];
if (location) {
let newOptions = {
type: options.type, url: location, user: options.user, password: options.password, responseType: options.responseType, headers: options.headers,
timeout: options.timeout, followRedirects: options.followRedirects - 1, data: options.data
};
xhr(newOptions).done(c, e, p);
return;
}
}
const response: IXHRResponse = {
responseText: data.join(''),
status,
getResponseHeader: header => res.headers[header],
readyState: 4
};
if ((status >= 200 && status < 300) || status === 1223) {
c(response);
} else {
e(response);
}
});
}, err => {
let message: string;
if (agent) {
message = 'Unable to to connect to ' + options.url + ' through a proxy . Error: ' + err.message;
} else {
message = 'Unable to to connect to ' + options.url + '. Error: ' + err.message;
}
return TPromise.wrapError<IXHRResponse>({
responseText: message,
status: 404
});
}));
}
dispose(): void {
this.disposables = dispose(this.disposables);
}
}
// Configuration
let confRegistry = <IConfigurationRegistry>platform.Registry.as(Extensions.Configuration);
confRegistry.registerConfiguration({
id: 'http',
order: 15,
title: nls.localize('httpConfigurationTitle', "HTTP configuration"),
type: 'object',
properties: {
'http.proxy': {
type: 'string',
pattern: '^https?://[^:]+(:\\d+)?$|^$',
description: nls.localize('proxy', "The proxy setting to use. If not set will be taken from the http_proxy and https_proxy environment variables")
},
'http.proxyStrictSSL': {
type: 'boolean',
default: true,
description: nls.localize('strictSSL', "Whether the proxy server certificate should be verified against the list of supplied CAs.")
}
}
});
|
from api_request import Api
from util import Util
from twocheckout import Twocheckout
class Sale(Twocheckout):
def __init__(self, dict_):
super(self.__class__, self).__init__(dict_)
@classmethod
def find(cls, params=None):
if params is None:
params = dict()
response = cls(Api.call('sales/detail_sale', params))
return response.sale
@classmethod
def list(cls, params=None):
if params is None:
params = dict()
response = cls(Api.call('sales/list_sales', params))
return response.sale_summary
def refund(self, params=None):
if params is None:
params = dict()
if hasattr(self, 'lineitem_id'):
params['lineitem_id'] = self.lineitem_id
url = 'sales/refund_lineitem'
elif hasattr(self, 'invoice_id'):
params['invoice_id'] = self.invoice_id
url = 'sales/refund_invoice'
else:
params['sale_id'] = self.sale_id
url = 'sales/refund_invoice'
return Sale(Api.call(url, params))
def stop(self, params=None):
if params is None:
params = dict()
if hasattr(self, 'lineitem_id'):
params['lineitem_id'] = self.lineitem_id
return Api.call('sales/stop_lineitem_recurring', params)
elif hasattr(self, 'sale_id'):
active_lineitems = Util.active(self)
if dict(active_lineitems):
result = dict()
i = 0
for k, v in active_lineitems.items():
lineitem_id = v
params = {'lineitem_id': lineitem_id}
result[i] = Api.call('sales/stop_lineitem_recurring', params)
i += 1
response = { "response_code": "OK",
"response_message": str(len(result)) + " lineitems stopped successfully"
}
else:
response = {
"response_code": "NOTICE",
"response_message": "No active recurring lineitems"
}
else:
response = { "response_code": "NOTICE",
"response_message": "This method can only be called on a sale or lineitem"
}
return Sale(response)
def active(self):
active_lineitems = Util.active(self)
if dict(active_lineitems):
result = dict()
i = 0
for k, v in active_lineitems.items():
lineitem_id = v
result[i] = lineitem_id
i += 1
response = { "response_code": "ACTIVE",
"response_message": str(len(result)) + " active recurring lineitems"
}
else:
response = {
"response_code": "NOTICE","response_message":
"No active recurring lineitems"
}
return Sale(response)
def comment(self, params=None):
if params is None:
params = dict()
params['sale_id'] = self.sale_id
return Sale(Api.call('sales/create_comment', params))
def ship(self, params=None):
if params is None:
params = dict()
params['sale_id'] = self.sale_id
return Sale(Api.call('sales/mark_shipped', params))
|
# mpps
web repository
|
b'What is the value of 21 - -2 - (2 + 11)?\n'
|
b'Calculate (0 - (-9 + 19)) + (6 - 3).\n'
|
b'Evaluate -1 + (5 - 5) - -3 - -10.\n'
|
b'What is 1 + 9 + (5 + -10 - 2) + 6?\n'
|
b'Calculate -8 - (19 - -5) - -14.\n'
|
b'Evaluate 2 + (6 + -4 + -18 - -9).\n'
|
b'Evaluate -17 + 17 + -6 - -2.\n'
|
'use strict';
const TYPE = Symbol.for('type');
class Data {
constructor(options) {
// File details
this.filepath = options.filepath;
// Type
this[TYPE] = 'data';
// Data
Object.assign(this, options.data);
}
}
module.exports = Data;
|
// The following are instance methods and variables
var Note = Class.create({
initialize: function(id, is_new, raw_body) {
if (Note.debug) {
console.debug("Note#initialize (id=%d)", id)
}
this.id = id
this.is_new = is_new
this.document_observers = [];
// Cache the elements
this.elements = {
box: $('note-box-' + this.id),
corner: $('note-corner-' + this.id),
body: $('note-body-' + this.id),
image: $('image')
}
// Cache the dimensions
this.fullsize = {
left: this.elements.box.offsetLeft,
top: this.elements.box.offsetTop,
width: this.elements.box.clientWidth,
height: this.elements.box.clientHeight
}
// Store the original values (in case the user clicks Cancel)
this.old = {
raw_body: raw_body,
formatted_body: this.elements.body.innerHTML
}
for (p in this.fullsize) {
this.old[p] = this.fullsize[p]
}
// Make the note translucent
if (is_new) {
this.elements.box.setOpacity(0.2)
} else {
this.elements.box.setOpacity(0.5)
}
if (is_new && raw_body == '') {
this.bodyfit = true
this.elements.body.style.height = "100px"
}
// Attach the event listeners
this.elements.box.observe("mousedown", this.dragStart.bindAsEventListener(this))
this.elements.box.observe("mouseout", this.bodyHideTimer.bindAsEventListener(this))
this.elements.box.observe("mouseover", this.bodyShow.bindAsEventListener(this))
this.elements.corner.observe("mousedown", this.resizeStart.bindAsEventListener(this))
this.elements.body.observe("mouseover", this.bodyShow.bindAsEventListener(this))
this.elements.body.observe("mouseout", this.bodyHideTimer.bindAsEventListener(this))
this.elements.body.observe("click", this.showEditBox.bindAsEventListener(this))
this.adjustScale()
},
// Returns the raw text value of this note
textValue: function() {
if (Note.debug) {
console.debug("Note#textValue (id=%d)", this.id)
}
return this.old.raw_body.strip()
},
// Removes the edit box
hideEditBox: function(e) {
if (Note.debug) {
console.debug("Note#hideEditBox (id=%d)", this.id)
}
var editBox = $('edit-box')
if (editBox != null) {
var boxid = editBox.noteid
$("edit-box").stopObserving()
$("note-save-" + boxid).stopObserving()
$("note-cancel-" + boxid).stopObserving()
$("note-remove-" + boxid).stopObserving()
$("note-history-" + boxid).stopObserving()
$("edit-box").remove()
}
},
// Shows the edit box
showEditBox: function(e) {
if (Note.debug) {
console.debug("Note#showEditBox (id=%d)", this.id)
}
this.hideEditBox(e)
var insertionPosition = Note.getInsertionPosition()
var top = insertionPosition[0]
var left = insertionPosition[1]
var html = ""
html += '<div id="edit-box" style="top: '+top+'px; left: '+left+'px; position: absolute; visibility: visible; z-index: 100; background: white; border: 1px solid black; padding: 12px;">'
html += '<form onsubmit="return false;" style="padding: 0; margin: 0;">'
html += '<textarea rows="7" id="edit-box-text" style="width: 350px; margin: 2px 2px 12px 2px;">' + this.textValue() + '</textarea>'
html += '<input type="submit" value="Save" name="save" id="note-save-' + this.id + '">'
html += '<input type="submit" value="Cancel" name="cancel" id="note-cancel-' + this.id + '">'
html += '<input type="submit" value="Remove" name="remove" id="note-remove-' + this.id + '">'
html += '<input type="submit" value="History" name="history" id="note-history-' + this.id + '">'
html += '</form>'
html += '</div>'
$("note-container").insert({bottom: html})
$('edit-box').noteid = this.id
$("edit-box").observe("mousedown", this.editDragStart.bindAsEventListener(this))
$("note-save-" + this.id).observe("click", this.save.bindAsEventListener(this))
$("note-cancel-" + this.id).observe("click", this.cancel.bindAsEventListener(this))
$("note-remove-" + this.id).observe("click", this.remove.bindAsEventListener(this))
$("note-history-" + this.id).observe("click", this.history.bindAsEventListener(this))
$("edit-box-text").focus()
},
// Shows the body text for the note
bodyShow: function(e) {
if (Note.debug) {
console.debug("Note#bodyShow (id=%d)", this.id)
}
if (this.dragging) {
return
}
if (this.hideTimer) {
clearTimeout(this.hideTimer)
this.hideTimer = null
}
if (Note.noteShowingBody == this) {
return
}
if (Note.noteShowingBody) {
Note.noteShowingBody.bodyHide()
}
Note.noteShowingBody = this
if (Note.zindex >= 9) {
/* don't use more than 10 layers (+1 for the body, which will always be above all notes) */
Note.zindex = 0
for (var i=0; i< Note.all.length; ++i) {
Note.all[i].elements.box.style.zIndex = 0
}
}
this.elements.box.style.zIndex = ++Note.zindex
this.elements.body.style.zIndex = 10
this.elements.body.style.top = 0 + "px"
this.elements.body.style.left = 0 + "px"
var dw = document.documentElement.scrollWidth
this.elements.body.style.visibility = "hidden"
this.elements.body.style.display = "block"
if (!this.bodyfit) {
this.elements.body.style.height = "auto"
this.elements.body.style.minWidth = "140px"
var w = null, h = null, lo = null, hi = null, x = null, last = null
w = this.elements.body.offsetWidth
h = this.elements.body.offsetHeight
if (w/h < 1.6180339887) {
/* for tall notes (lots of text), find more pleasant proportions */
lo = 140, hi = 400
do {
last = w
x = (lo+hi)/2
this.elements.body.style.minWidth = x + "px"
w = this.elements.body.offsetWidth
h = this.elements.body.offsetHeight
if (w/h < 1.6180339887) lo = x
else hi = x
} while ((lo < hi) && (w > last))
} else if (this.elements.body.scrollWidth <= this.elements.body.clientWidth) {
/* for short notes (often a single line), make the box no wider than necessary */
// scroll test necessary for Firefox
lo = 20, hi = w
do {
x = (lo+hi)/2
this.elements.body.style.minWidth = x + "px"
if (this.elements.body.offsetHeight > h) lo = x
else hi = x
} while ((hi - lo) > 4)
if (this.elements.body.offsetHeight > h)
this.elements.body.style.minWidth = hi + "px"
}
if (Prototype.Browser.IE) {
// IE7 adds scrollbars if the box is too small, obscuring the text
if (this.elements.body.offsetHeight < 35) {
this.elements.body.style.minHeight = "35px"
}
if (this.elements.body.offsetWidth < 47) {
this.elements.body.style.minWidth = "47px"
}
}
this.bodyfit = true
}
this.elements.body.style.top = (this.elements.box.offsetTop + this.elements.box.clientHeight + 5) + "px"
// keep the box within the document's width
var l = 0, e = this.elements.box
do { l += e.offsetLeft } while (e = e.offsetParent)
l += this.elements.body.offsetWidth + 10 - dw
if (l > 0)
this.elements.body.style.left = this.elements.box.offsetLeft - l + "px"
else
this.elements.body.style.left = this.elements.box.offsetLeft + "px"
this.elements.body.style.visibility = "visible"
},
// Creates a timer that will hide the body text for the note
bodyHideTimer: function(e) {
if (Note.debug) {
console.debug("Note#bodyHideTimer (id=%d)", this.id)
}
this.hideTimer = setTimeout(this.bodyHide.bindAsEventListener(this), 250)
},
// Hides the body text for the note
bodyHide: function(e) {
if (Note.debug) {
console.debug("Note#bodyHide (id=%d)", this.id)
}
this.elements.body.hide()
if (Note.noteShowingBody == this) {
Note.noteShowingBody = null
}
},
addDocumentObserver: function(name, func)
{
document.observe(name, func);
this.document_observers.push([name, func]);
},
clearDocumentObservers: function(name, handler)
{
for(var i = 0; i < this.document_observers.length; ++i)
{
var observer = this.document_observers[i];
document.stopObserving(observer[0], observer[1]);
}
this.document_observers = [];
},
// Start dragging the note
dragStart: function(e) {
if (Note.debug) {
console.debug("Note#dragStart (id=%d)", this.id)
}
this.addDocumentObserver("mousemove", this.drag.bindAsEventListener(this))
this.addDocumentObserver("mouseup", this.dragStop.bindAsEventListener(this))
this.addDocumentObserver("selectstart", function() {return false})
this.cursorStartX = e.pointerX()
this.cursorStartY = e.pointerY()
this.boxStartX = this.elements.box.offsetLeft
this.boxStartY = this.elements.box.offsetTop
this.boundsX = new ClipRange(5, this.elements.image.clientWidth - this.elements.box.clientWidth - 5)
this.boundsY = new ClipRange(5, this.elements.image.clientHeight - this.elements.box.clientHeight - 5)
this.dragging = true
this.bodyHide()
},
// Stop dragging the note
dragStop: function(e) {
if (Note.debug) {
console.debug("Note#dragStop (id=%d)", this.id)
}
this.clearDocumentObservers()
this.cursorStartX = null
this.cursorStartY = null
this.boxStartX = null
this.boxStartY = null
this.boundsX = null
this.boundsY = null
this.dragging = false
this.bodyShow()
},
ratio: function() {
return this.elements.image.width / this.elements.image.getAttribute("large_width")
// var ratio = this.elements.image.width / this.elements.image.getAttribute("large_width")
// if (this.elements.image.scale_factor != null)
// ratio *= this.elements.image.scale_factor;
// return ratio
},
// Scale the notes for when the image gets resized
adjustScale: function() {
if (Note.debug) {
console.debug("Note#adjustScale (id=%d)", this.id)
}
var ratio = this.ratio()
for (p in this.fullsize) {
this.elements.box.style[p] = this.fullsize[p] * ratio + 'px'
}
},
// Update the note's position as it gets dragged
drag: function(e) {
var left = this.boxStartX + e.pointerX() - this.cursorStartX
var top = this.boxStartY + e.pointerY() - this.cursorStartY
left = this.boundsX.clip(left)
top = this.boundsY.clip(top)
this.elements.box.style.left = left + 'px'
this.elements.box.style.top = top + 'px'
var ratio = this.ratio()
this.fullsize.left = left / ratio
this.fullsize.top = top / ratio
e.stop()
},
// Start dragging the edit box
editDragStart: function(e) {
if (Note.debug) {
console.debug("Note#editDragStart (id=%d)", this.id)
}
var node = e.element().nodeName
if (node != 'FORM' && node != 'DIV') {
return
}
this.addDocumentObserver("mousemove", this.editDrag.bindAsEventListener(this))
this.addDocumentObserver("mouseup", this.editDragStop.bindAsEventListener(this))
this.addDocumentObserver("selectstart", function() {return false})
this.elements.editBox = $('edit-box');
this.cursorStartX = e.pointerX()
this.cursorStartY = e.pointerY()
this.editStartX = this.elements.editBox.offsetLeft
this.editStartY = this.elements.editBox.offsetTop
this.dragging = true
},
// Stop dragging the edit box
editDragStop: function(e) {
if (Note.debug) {
console.debug("Note#editDragStop (id=%d)", this.id)
}
this.clearDocumentObservers()
this.cursorStartX = null
this.cursorStartY = null
this.editStartX = null
this.editStartY = null
this.dragging = false
},
// Update the edit box's position as it gets dragged
editDrag: function(e) {
var left = this.editStartX + e.pointerX() - this.cursorStartX
var top = this.editStartY + e.pointerY() - this.cursorStartY
this.elements.editBox.style.left = left + 'px'
this.elements.editBox.style.top = top + 'px'
e.stop()
},
// Start resizing the note
resizeStart: function(e) {
if (Note.debug) {
console.debug("Note#resizeStart (id=%d)", this.id)
}
this.cursorStartX = e.pointerX()
this.cursorStartY = e.pointerY()
this.boxStartWidth = this.elements.box.clientWidth
this.boxStartHeight = this.elements.box.clientHeight
this.boxStartX = this.elements.box.offsetLeft
this.boxStartY = this.elements.box.offsetTop
this.boundsX = new ClipRange(10, this.elements.image.clientWidth - this.boxStartX - 5)
this.boundsY = new ClipRange(10, this.elements.image.clientHeight - this.boxStartY - 5)
this.dragging = true
this.clearDocumentObservers()
this.addDocumentObserver("mousemove", this.resize.bindAsEventListener(this))
this.addDocumentObserver("mouseup", this.resizeStop.bindAsEventListener(this))
e.stop()
this.bodyHide()
},
// Stop resizing teh note
resizeStop: function(e) {
if (Note.debug) {
console.debug("Note#resizeStop (id=%d)", this.id)
}
this.clearDocumentObservers()
this.boxCursorStartX = null
this.boxCursorStartY = null
this.boxStartWidth = null
this.boxStartHeight = null
this.boxStartX = null
this.boxStartY = null
this.boundsX = null
this.boundsY = null
this.dragging = false
e.stop()
},
// Update the note's dimensions as it gets resized
resize: function(e) {
var width = this.boxStartWidth + e.pointerX() - this.cursorStartX
var height = this.boxStartHeight + e.pointerY() - this.cursorStartY
width = this.boundsX.clip(width)
height = this.boundsY.clip(height)
this.elements.box.style.width = width + "px"
this.elements.box.style.height = height + "px"
var ratio = this.ratio()
this.fullsize.width = width / ratio
this.fullsize.height = height / ratio
e.stop()
},
// Save the note to the database
save: function(e) {
if (Note.debug) {
console.debug("Note#save (id=%d)", this.id)
}
var note = this
for (p in this.fullsize) {
this.old[p] = this.fullsize[p]
}
this.old.raw_body = $('edit-box-text').value
this.old.formatted_body = this.textValue()
// FIXME: this is not quite how the note will look (filtered elems, <tn>...). the user won't input a <script> that only damages him, but it might be nice to "preview" the <tn> here
this.elements.body.update(this.textValue())
this.hideEditBox(e)
this.bodyHide()
this.bodyfit = false
var params = {
"id": this.id,
"note[x]": this.old.left,
"note[y]": this.old.top,
"note[width]": this.old.width,
"note[height]": this.old.height,
"note[body]": this.old.raw_body
}
if (this.is_new) {
params["note[post_id]"] = Note.post_id
}
notice("Saving note...")
new Ajax.Request('/note/update.json', {
parameters: params,
onComplete: function(resp) {
var resp = resp.responseJSON
if (resp.success) {
notice("Note saved")
var note = Note.find(resp.old_id)
if (resp.old_id < 0) {
note.is_new = false
note.id = resp.new_id
note.elements.box.id = 'note-box-' + note.id
note.elements.body.id = 'note-body-' + note.id
note.elements.corner.id = 'note-corner-' + note.id
}
note.elements.body.innerHTML = resp.formatted_body
note.elements.box.setOpacity(0.5)
note.elements.box.removeClassName('unsaved')
} else {
notice("Error: " + resp.reason)
note.elements.box.addClassName('unsaved')
}
}
})
e.stop()
},
// Revert the note to the last saved state
cancel: function(e) {
if (Note.debug) {
console.debug("Note#cancel (id=%d)", this.id)
}
this.hideEditBox(e)
this.bodyHide()
var ratio = this.ratio()
for (p in this.fullsize) {
this.fullsize[p] = this.old[p]
this.elements.box.style[p] = this.fullsize[p] * ratio + 'px'
}
this.elements.body.innerHTML = this.old.formatted_body
e.stop()
},
// Remove all references to the note from the page
removeCleanup: function() {
if (Note.debug) {
console.debug("Note#removeCleanup (id=%d)", this.id)
}
this.elements.box.remove()
this.elements.body.remove()
var allTemp = []
for (i=0; i<Note.all.length; ++i) {
if (Note.all[i].id != this.id) {
allTemp.push(Note.all[i])
}
}
Note.all = allTemp
Note.updateNoteCount()
},
// Removes a note from the database
remove: function(e) {
if (Note.debug) {
console.debug("Note#remove (id=%d)", this.id)
}
this.hideEditBox(e)
this.bodyHide()
this_note = this
if (this.is_new) {
this.removeCleanup()
notice("Note removed")
} else {
notice("Removing note...")
new Ajax.Request('/note/update.json', {
parameters: {
"id": this.id,
"note[is_active]": "0"
},
onComplete: function(resp) {
var resp = resp.responseJSON
if (resp.success) {
notice("Note removed")
this_note.removeCleanup()
} else {
notice("Error: " + resp.reason)
}
}
})
}
e.stop()
},
// Redirect to the note's history
history: function(e) {
if (Note.debug) {
console.debug("Note#history (id=%d)", this.id)
}
this.hideEditBox(e)
if (this.is_new) {
notice("This note has no history")
} else {
location.href = '/history?search=notes:' + this.id
}
e.stop()
}
})
// The following are class methods and variables
Object.extend(Note, {
zindex: 0,
counter: -1,
all: [],
display: true,
debug: false,
// Show all notes
show: function() {
if (Note.debug) {
console.debug("Note.show")
}
$("note-container").show()
},
// Hide all notes
hide: function() {
if (Note.debug) {
console.debug("Note.hide")
}
$("note-container").hide()
},
// Find a note instance based on the id number
find: function(id) {
if (Note.debug) {
console.debug("Note.find")
}
for (var i=0; i<Note.all.size(); ++i) {
if (Note.all[i].id == id) {
return Note.all[i]
}
}
return null
},
// Toggle the display of all notes
toggle: function() {
if (Note.debug) {
console.debug("Note.toggle")
}
if (Note.display) {
Note.hide()
Note.display = false
} else {
Note.show()
Note.display = true
}
},
// Update the text displaying the number of notes a post has
updateNoteCount: function() {
if (Note.debug) {
console.debug("Note.updateNoteCount")
}
if (Note.all.length > 0) {
var label = ""
if (Note.all.length == 1)
label = "note"
else
label = "notes"
$('note-count').innerHTML = "This post has <a href=\"/note/history?post_id=" + Note.post_id + "\">" + Note.all.length + " " + label + "</a>"
} else {
$('note-count').innerHTML = ""
}
},
// Create a new note
create: function() {
if (Note.debug) {
console.debug("Note.create")
}
Note.show()
var insertion_position = Note.getInsertionPosition()
var top = insertion_position[0]
var left = insertion_position[1]
var html = ''
html += '<div class="note-box unsaved" style="width: 150px; height: 150px; '
html += 'top: ' + top + 'px; '
html += 'left: ' + left + 'px;" '
html += 'id="note-box-' + Note.counter + '">'
html += '<div class="note-corner" id="note-corner-' + Note.counter + '"></div>'
html += '</div>'
html += '<div class="note-body" title="Click to edit" id="note-body-' + Note.counter + '"></div>'
$("note-container").insert({bottom: html})
var note = new Note(Note.counter, true, "")
Note.all.push(note)
Note.counter -= 1
},
// Find a suitable position to insert new notes
getInsertionPosition: function() {
if (Note.debug) {
console.debug("Note.getInsertionPosition")
}
// We want to show the edit box somewhere on the screen, but not outside the image.
var scroll_x = $("image").cumulativeScrollOffset()[0]
var scroll_y = $("image").cumulativeScrollOffset()[1]
var image_left = $("image").positionedOffset()[0]
var image_top = $("image").positionedOffset()[1]
var image_right = image_left + $("image").width
var image_bottom = image_top + $("image").height
var left = 0
var top = 0
if (scroll_x > image_left) {
left = scroll_x
} else {
left = image_left
}
if (scroll_y > image_top) {
top = scroll_y
} else {
top = image_top + 20
}
if (top > image_bottom) {
top = image_top + 20
}
return [top, left]
}
})
|
/* eslint-disable no-console */
const buildData = require('./build_data');
const buildSrc = require('./build_src');
const buildCSS = require('./build_css');
let _currBuild = null;
// if called directly, do the thing.
buildAll();
function buildAll() {
if (_currBuild) return _currBuild;
return _currBuild =
Promise.resolve()
.then(() => buildCSS())
.then(() => buildData())
.then(() => buildSrc())
.then(() => _currBuild = null)
.catch((err) => {
console.error(err);
_currBuild = null;
process.exit(1);
});
}
module.exports = buildAll;
|
/* Copyright (c) 2018 Dennis Wölfing
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* kernel/include/dennix/clock.h
* System clocks.
*/
#ifndef _DENNIX_CLOCK_H
#define _DENNIX_CLOCK_H
#define CLOCK_MONOTONIC 0
#define CLOCK_REALTIME 1
#define CLOCK_PROCESS_CPUTIME_ID 2
#define CLOCK_THREAD_CPUTIME_ID 3
#define TIMER_ABSTIME 1
#endif
|
b'What is 25 + -9 + -9 + 10?\n'
|
b'1 + -3 + (3 - -6) - (-28 + 34)\n'
|
var fusepm = require('./fusepm');
module.exports = fixunoproj;
function fixunoproj () {
var fn = fusepm.local_unoproj(".");
fusepm.read_unoproj(fn).then(function (obj) {
var inc = [];
if (obj.Includes) {
var re = /\//;
for (var i=0; i<obj.Includes.length;i++) {
if (obj.Includes[i] === '*') {
inc.push('./*.ux');
inc.push('./*.uno');
inc.push('./*.uxl');
}
else if (!obj.Includes[i].match(re)) {
inc.push('./' + obj.Includes[i]);
}
else {
inc.push(obj.Includes[i]);
}
}
}
else {
inc = ['./*.ux', './*.uno', './*.uxl'];
}
if (!obj.Version) {
obj.Version = "0.0.0";
}
obj.Includes = inc;
fusepm.save_unoproj(fn, obj);
}).catch(function (e) {
console.log(e);
});
}
|
b'What is 3 + -4 + (-20 - (-40 + 24))?\n'
|
<?php
/* TwigBundle:Exception:traces.html.twig */
class __TwigTemplate_034400bfb816a72b7b3da36dd2d8e07ee89621bac614688be25a4e8ff872b3ad extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<div class=\"block\">
";
// line 2
if (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) > 0)) {
// line 3
echo " <h2>
<span><small>[";
// line 4
echo twig_escape_filter($this->env, (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) - (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position"))) + 1), "html", null, true);
echo "/";
echo twig_escape_filter($this->env, ((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) + 1), "html", null, true);
echo "]</small></span>
";
// line 5
echo $this->env->getExtension('code')->abbrClass($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "class", array()));
echo ": ";
echo $this->env->getExtension('code')->formatFileFromText(nl2br(twig_escape_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "message", array()), "html", null, true)));
echo "
";
// line 6
ob_start();
// line 7
echo " <a href=\"#\" onclick=\"toggle('traces-";
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "', 'traces'); switchIcons('icon-traces-";
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-open', 'icon-traces-";
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-close'); return false;\">
<img class=\"toggle\" id=\"icon-traces-";
// line 8
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: ";
echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("inline") : ("none"));
echo "\" />
<img class=\"toggle\" id=\"icon-traces-";
// line 9
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: ";
echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("none") : ("inline"));
echo "\" />
</a>
";
echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
// line 12
echo " </h2>
";
} else {
// line 14
echo " <h2>Stack Trace</h2>
";
}
// line 16
echo "
<a id=\"traces-link-";
// line 17
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "\"></a>
<ol class=\"traces list-exception\" id=\"traces-";
// line 18
echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true);
echo "\" style=\"display: ";
echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("block") : ("none"));
echo "\">
";
// line 19
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array()));
foreach ($context['_seq'] as $context["i"] => $context["trace"]) {
// line 20
echo " <li>
";
// line 21
$this->loadTemplate("TwigBundle:Exception:trace.html.twig", "TwigBundle:Exception:traces.html.twig", 21)->display(array("prefix" => (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "i" => $context["i"], "trace" => $context["trace"]));
// line 22
echo " </li>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['i'], $context['trace'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 24
echo " </ol>
</div>
";
}
public function getTemplateName()
{
return "TwigBundle:Exception:traces.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 101 => 24, 94 => 22, 92 => 21, 89 => 20, 85 => 19, 79 => 18, 75 => 17, 72 => 16, 68 => 14, 64 => 12, 56 => 9, 50 => 8, 41 => 7, 39 => 6, 33 => 5, 27 => 4, 24 => 3, 22 => 2, 19 => 1,);
}
}
/* <div class="block">*/
/* {% if count > 0 %}*/
/* <h2>*/
/* <span><small>[{{ count - position + 1 }}/{{ count + 1 }}]</small></span>*/
/* {{ exception.class|abbr_class }}: {{ exception.message|nl2br|format_file_from_text }} */
/* {% spaceless %}*/
/* <a href="#" onclick="toggle('traces-{{ position }}', 'traces'); switchIcons('icon-traces-{{ position }}-open', 'icon-traces-{{ position }}-close'); return false;">*/
/* <img class="toggle" id="icon-traces-{{ position }}-close" alt="-" src="data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=" style="display: {{ 0 == count ? 'inline' : 'none' }}" />*/
/* <img class="toggle" id="icon-traces-{{ position }}-open" alt="+" src="data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7" style="display: {{ 0 == count ? 'none' : 'inline' }}" />*/
/* </a>*/
/* {% endspaceless %}*/
/* </h2>*/
/* {% else %}*/
/* <h2>Stack Trace</h2>*/
/* {% endif %}*/
/* */
/* <a id="traces-link-{{ position }}"></a>*/
/* <ol class="traces list-exception" id="traces-{{ position }}" style="display: {{ 0 == count ? 'block' : 'none' }}">*/
/* {% for i, trace in exception.trace %}*/
/* <li>*/
/* {% include 'TwigBundle:Exception:trace.html.twig' with { 'prefix': position, 'i': i, 'trace': trace } only %}*/
/* </li>*/
/* {% endfor %}*/
/* </ol>*/
/* </div>*/
/* */
|
var groove = require('groove');
var semver = require('semver');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var mkdirp = require('mkdirp');
var fs = require('fs');
var uuid = require('./uuid');
var path = require('path');
var Pend = require('pend');
var DedupedQueue = require('./deduped_queue');
var findit = require('findit2');
var shuffle = require('mess');
var mv = require('mv');
var MusicLibraryIndex = require('music-library-index');
var keese = require('keese');
var safePath = require('./safe_path');
var PassThrough = require('stream').PassThrough;
var url = require('url');
var dbIterate = require('./db_iterate');
var log = require('./log');
var importUrlFilters = require('./import_url_filters');
var youtubeSearch = require('./youtube_search');
var yauzl = require('yauzl');
var importFileFilters = [
{
name: 'zip',
fn: importFileAsZip,
},
{
name: 'song',
fn: importFileAsSong,
},
];
module.exports = Player;
ensureGrooveVersionIsOk();
var cpuCount = 1;
var PLAYER_KEY_PREFIX = "Player.";
var LIBRARY_KEY_PREFIX = "Library.";
var LIBRARY_DIR_PREFIX = "LibraryDir.";
var QUEUE_KEY_PREFIX = "Playlist.";
var PLAYLIST_KEY_PREFIX = "StoredPlaylist.";
var LABEL_KEY_PREFIX = "Label.";
var PLAYLIST_META_KEY_PREFIX = "StoredPlaylistMeta.";
// db: store in the DB
var DB_PROPS = {
key: {
db: true,
clientVisible: true,
clientCanModify: false,
type: 'string',
},
name: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
artistName: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
albumArtistName: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
albumName: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
compilation: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'boolean',
},
track: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'integer',
},
trackCount: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'integer',
},
disc: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'integer',
},
discCount: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'integer',
},
duration: {
db: true,
clientVisible: true,
clientCanModify: false,
type: 'float',
},
year: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'integer',
},
genre: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
file: {
db: true,
clientVisible: true,
clientCanModify: false,
type: 'string',
},
mtime: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'integer',
},
replayGainAlbumGain: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'float',
},
replayGainAlbumPeak: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'float',
},
replayGainTrackGain: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'float',
},
replayGainTrackPeak: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'float',
},
composerName: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
performerName: {
db: true,
clientVisible: true,
clientCanModify: true,
type: 'string',
},
lastQueueDate: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'date',
},
fingerprint: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'array_of_integer',
},
playCount: {
db: true,
clientVisible: false,
clientCanModify: false,
type: 'integer',
},
labels: {
db: true,
clientVisible: true,
clientCanModify: false,
type: 'set',
},
};
var PROP_TYPE_PARSERS = {
'string': function(value) {
return value ? String(value) : "";
},
'date': function(value) {
if (!value) return null;
var date = new Date(value);
if (isNaN(date.getTime())) return null;
return date;
},
'integer': parseIntOrNull,
'float': parseFloatOrNull,
'boolean': function(value) {
return value == null ? null : !!value;
},
'array_of_integer': function(value) {
if (!Array.isArray(value)) return null;
value = value.map(parseIntOrNull);
for (var i = 0; i < value.length; i++) {
if (value[i] == null) return null;
}
return value;
},
'set': function(value) {
var result = {};
for (var key in value) {
result[key] = 1;
}
return result;
},
};
var labelColors = [
"#e11d21", "#eb6420", "#fbca04", "#009800",
"#006b75", "#207de5", "#0052cc", "#5319e7",
"#f7c6c7", "#fad8c7", "#fef2c0", "#bfe5bf",
"#bfdadc", "#bfd4f2", "#c7def8", "#d4c5f9",
];
// how many GrooveFiles to keep open, ready to be decoded
var OPEN_FILE_COUNT = 8;
var PREV_FILE_COUNT = Math.floor(OPEN_FILE_COUNT / 2);
var NEXT_FILE_COUNT = OPEN_FILE_COUNT - PREV_FILE_COUNT;
var DB_SCALE = Math.log(10.0) * 0.05;
var REPLAYGAIN_PREAMP = 0.75;
var REPLAYGAIN_DEFAULT = 0.25;
Player.REPEAT_OFF = 0;
Player.REPEAT_ALL = 1;
Player.REPEAT_ONE = 2;
Player.trackWithoutIndex = trackWithoutIndex;
Player.setGrooveLoggingLevel = setGrooveLoggingLevel;
util.inherits(Player, EventEmitter);
function Player(db, config) {
EventEmitter.call(this);
this.setMaxListeners(0);
this.db = db;
this.musicDirectory = config.musicDirectory;
this.dbFilesByPath = {};
this.dbFilesByLabel = {};
this.libraryIndex = new MusicLibraryIndex({
searchFields: MusicLibraryIndex.defaultSearchFields.concat('file'),
});
this.addQueue = new DedupedQueue({
processOne: this.addToLibrary.bind(this),
// limit to 1 async operation because we're blocking on the hard drive,
// it's faster to read one file at a time.
maxAsync: 1,
});
this.dirs = {};
this.dirScanQueue = new DedupedQueue({
processOne: this.refreshFilesIndex.bind(this),
// only 1 dir scanning can happen at a time
// we'll pass the dir to scan as the ID so that not more than 1 of the
// same dir can queue up
maxAsync: 1,
});
this.dirScanQueue.on('error', function(err) {
log.error("library scanning error:", err.stack);
});
this.disableFsRefCount = 0;
this.playlist = {};
this.playlists = {};
this.currentTrack = null;
this.tracksInOrder = []; // another way to look at playlist
this.grooveItems = {}; // maps groove item id to track
this.seekRequestPos = -1; // set to >= 0 when we want to seek
this.invalidPaths = {}; // files that could not be opened
this.playlistItemDeleteQueue = [];
this.dontBelieveTheEndOfPlaylistSentinelItsATrap = false;
this.queueClearEncodedBuffers = false;
this.repeat = Player.REPEAT_OFF;
this.desiredPlayerHardwareState = null; // true: normal hardware playback. false: dummy
this.pendingPlayerAttachDetach = null;
this.isPlaying = false;
this.trackStartDate = null;
this.pausedTime = 0;
this.autoDjOn = false;
this.autoDjHistorySize = 10;
this.autoDjFutureSize = 10;
this.ongoingScans = {};
this.scanQueue = new DedupedQueue({
processOne: this.performScan.bind(this),
maxAsync: cpuCount,
});
this.headerBuffers = [];
this.recentBuffers = [];
this.newHeaderBuffers = [];
this.openStreamers = [];
this.expectHeaders = true;
// when a streaming client connects we send them many buffers quickly
// in order to get the stream started, then we slow down.
this.encodeQueueDuration = config.encodeQueueDuration;
this.groovePlaylist = groove.createPlaylist();
this.groovePlayer = null;
this.grooveEncoder = groove.createEncoder();
this.grooveEncoder.encodedBufferSize = 128 * 1024;
this.detachEncoderTimeout = null;
this.pendingEncoderAttachDetach = false;
this.desiredEncoderAttachState = false;
this.flushEncodedInterval = null;
this.groovePlaylist.pause();
this.volume = this.groovePlaylist.gain;
this.grooveEncoder.formatShortName = "mp3";
this.grooveEncoder.codecShortName = "mp3";
this.grooveEncoder.bitRate = config.encodeBitRate * 1000;
this.importProgress = {};
this.lastImportProgressEvent = new Date();
// tracking playCount
this.previousIsPlaying = false;
this.playingStart = new Date();
this.playingTime = 0;
this.lastPlayingItem = null;
this.googleApiKey = config.googleApiKey;
this.ignoreExtensions = config.ignoreExtensions.map(makeLower);
}
Player.prototype.initialize = function(cb) {
var self = this;
var startupTrackInfo = null;
initLibrary(function(err) {
if (err) return cb(err);
cacheTracksArray(self);
self.requestUpdateDb();
cacheAllOptions(function(err) {
if (err) return cb(err);
setInterval(doPersistCurrentTrack, 10000);
if (startupTrackInfo) {
self.seek(startupTrackInfo.id, startupTrackInfo.pos);
} else {
playlistChanged(self);
}
lazyReplayGainScanPlaylist(self);
cb();
});
});
function initLibrary(cb) {
var pend = new Pend();
pend.go(cacheAllDb);
pend.go(cacheAllDirs);
pend.go(cacheAllQueue);
pend.go(cacheAllPlaylists);
pend.go(cacheAllLabels);
pend.wait(cb);
}
function cacheAllPlaylists(cb) {
cacheAllPlaylistMeta(function(err) {
if (err) return cb(err);
cacheAllPlaylistItems(cb);
});
function cacheAllPlaylistMeta(cb) {
dbIterate(self.db, PLAYLIST_META_KEY_PREFIX, processOne, cb);
function processOne(key, value) {
var playlist = deserializePlaylist(value);
self.playlists[playlist.id] = playlist;
}
}
function cacheAllPlaylistItems(cb) {
dbIterate(self.db, PLAYLIST_KEY_PREFIX, processOne, cb);
function processOne(key, value) {
var playlistIdEnd = key.indexOf('.', PLAYLIST_KEY_PREFIX.length);
var playlistId = key.substring(PLAYLIST_KEY_PREFIX.length, playlistIdEnd);
var playlistItem = JSON.parse(value);
self.playlists[playlistId].items[playlistItem.id] = playlistItem;
}
}
}
function cacheAllLabels(cb) {
dbIterate(self.db, LABEL_KEY_PREFIX, processOne, cb);
function processOne(key, value) {
var labelId = key.substring(LABEL_KEY_PREFIX.length);
var labelEntry = JSON.parse(value);
self.libraryIndex.addLabel(labelEntry);
}
}
function cacheAllQueue(cb) {
dbIterate(self.db, QUEUE_KEY_PREFIX, processOne, cb);
function processOne(key, value) {
var plEntry = JSON.parse(value);
self.playlist[plEntry.id] = plEntry;
}
}
function cacheAllOptions(cb) {
var options = {
repeat: null,
autoDjOn: null,
autoDjHistorySize: null,
autoDjFutureSize: null,
hardwarePlayback: null,
volume: null,
currentTrackInfo: null,
};
var pend = new Pend();
for (var name in options) {
pend.go(makeGetFn(name));
}
pend.wait(function(err) {
if (err) return cb(err);
if (options.repeat != null) {
self.setRepeat(options.repeat);
}
if (options.autoDjOn != null) {
self.setAutoDjOn(options.autoDjOn);
}
if (options.autoDjHistorySize != null) {
self.setAutoDjHistorySize(options.autoDjHistorySize);
}
if (options.autoDjFutureSize != null) {
self.setAutoDjFutureSize(options.autoDjFutureSize);
}
if (options.volume != null) {
self.setVolume(options.volume);
}
startupTrackInfo = options.currentTrackInfo;
var hardwarePlaybackValue = options.hardwarePlayback == null ? true : options.hardwarePlayback;
// start the hardware player first
// fall back to dummy
self.setHardwarePlayback(hardwarePlaybackValue, function(err) {
if (err) {
log.error("Unable to attach hardware player, falling back to dummy.", err.stack);
self.setHardwarePlayback(false);
}
cb();
});
});
function makeGetFn(name) {
return function(cb) {
self.db.get(PLAYER_KEY_PREFIX + name, function(err, value) {
if (!err && value != null) {
try {
options[name] = JSON.parse(value);
} catch (err) {
cb(err);
return;
}
}
cb();
});
};
}
}
function cacheAllDirs(cb) {
dbIterate(self.db, LIBRARY_DIR_PREFIX, processOne, cb);
function processOne(key, value) {
var dirEntry = JSON.parse(value);
self.dirs[dirEntry.dirName] = dirEntry;
}
}
function cacheAllDb(cb) {
var scrubCmds = [];
dbIterate(self.db, LIBRARY_KEY_PREFIX, processOne, scrubAndCb);
function processOne(key, value) {
var dbFile = deserializeFileData(value);
// scrub duplicates
if (self.dbFilesByPath[dbFile.file]) {
scrubCmds.push({type: 'del', key: key});
} else {
self.libraryIndex.addTrack(dbFile);
self.dbFilesByPath[dbFile.file] = dbFile;
for (var labelId in dbFile.labels) {
var files = self.dbFilesByLabel[labelId];
if (files == null) files = self.dbFilesByLabel[labelId] = {};
files[dbFile.key] = dbFile;
}
}
}
function scrubAndCb() {
if (scrubCmds.length === 0) return cb();
log.warn("Scrubbing " + scrubCmds.length + " duplicate db entries");
self.db.batch(scrubCmds, function(err) {
if (err) log.error("Unable to scrub duplicate tracks from db:", err.stack);
cb();
});
}
}
function doPersistCurrentTrack() {
if (self.isPlaying) {
self.persistCurrentTrack();
}
}
};
function startEncoderAttach(self, cb) {
if (self.desiredEncoderAttachState) return;
self.desiredEncoderAttachState = true;
if (self.pendingEncoderAttachDetach) return;
self.pendingEncoderAttachDetach = true;
self.grooveEncoder.attach(self.groovePlaylist, function(err) {
self.pendingEncoderAttachDetach = false;
if (err) {
self.desiredEncoderAttachState = false;
cb(err);
} else if (!self.desiredEncoderAttachState) {
startEncoderDetach(self, cb);
}
});
}
function startEncoderDetach(self, cb) {
if (!self.desiredEncoderAttachState) return;
self.desiredEncoderAttachState = false;
if (self.pendingEncoderAttachDetach) return;
self.pendingEncoderAttachDetach = true;
self.grooveEncoder.detach(function(err) {
self.pendingEncoderAttachDetach = false;
if (err) {
self.desiredEncoderAttachState = true;
cb(err);
} else if (self.desiredEncoderAttachState) {
startEncoderAttach(self, cb);
}
});
}
Player.prototype.getBufferedSeconds = function() {
if (this.recentBuffers.length < 2) return 0;
var firstPts = this.recentBuffers[0].pts;
var lastPts = this.recentBuffers[this.recentBuffers.length - 1].pts;
var frameCount = lastPts - firstPts;
var sampleRate = this.grooveEncoder.actualAudioFormat.sampleRate;
return frameCount / sampleRate;
};
Player.prototype.attachEncoder = function(cb) {
var self = this;
cb = cb || logIfError;
if (self.flushEncodedInterval) return cb();
log.debug("first streamer connected - attaching encoder");
self.flushEncodedInterval = setInterval(flushEncoded, 100);
startEncoderAttach(self, cb);
function flushEncoded() {
if (!self.desiredEncoderAttachState || self.pendingEncoderAttachDetach) return;
var playHead = self.groovePlayer.position();
if (!playHead.item) return;
var plItems = self.groovePlaylist.items();
// get rid of old items
var buf;
while (buf = self.recentBuffers[0]) {
/*
log.debug(" buf.item " + buf.item.file.filename + "\n" +
"playHead.item " + playHead.item.file.filename + "\n" +
" playHead.pos " + playHead.pos + "\n" +
" buf.pos " + buf.pos);
*/
if (isBufOld(buf)) {
self.recentBuffers.shift();
} else {
break;
}
}
// poll the encoder for more buffers until either there are no buffers
// available or we get enough buffered
while (self.getBufferedSeconds() < self.encodeQueueDuration) {
buf = self.grooveEncoder.getBuffer();
if (!buf) break;
if (buf.buffer) {
if (buf.item) {
if (self.expectHeaders) {
log.debug("encoder: got first non-header");
self.headerBuffers = self.newHeaderBuffers;
self.newHeaderBuffers = [];
self.expectHeaders = false;
}
self.recentBuffers.push(buf);
for (var i = 0; i < self.openStreamers.length; i += 1) {
self.openStreamers[i].write(buf.buffer);
}
} else if (self.expectHeaders) {
// this is a header
log.debug("encoder: got header");
self.newHeaderBuffers.push(buf.buffer);
} else {
// it's a footer, ignore the fuck out of it
log.debug("ignoring encoded audio footer");
}
} else {
// end of playlist sentinel
log.debug("encoder: end of playlist sentinel");
if (self.queueClearEncodedBuffers) {
self.queueClearEncodedBuffers = false;
self.clearEncodedBuffer();
self.emit('seek');
}
self.expectHeaders = true;
}
}
function isBufOld(buf) {
// typical case
if (buf.item.id === playHead.item.id) {
return playHead.pos > buf.pos;
}
// edge case
var playHeadIndex = -1;
var bufItemIndex = -1;
for (var i = 0; i < plItems.length; i += 1) {
var plItem = plItems[i];
if (plItem.id === playHead.item.id) {
playHeadIndex = i;
} else if (plItem.id === buf.item.id) {
bufItemIndex = i;
}
}
return playHeadIndex > bufItemIndex;
}
}
function logIfError(err) {
if (err) {
log.error("Unable to attach encoder:", err.stack);
}
}
};
Player.prototype.detachEncoder = function(cb) {
cb = cb || logIfError;
this.clearEncodedBuffer();
this.queueClearEncodedBuffers = false;
clearInterval(this.flushEncodedInterval);
this.flushEncodedInterval = null;
startEncoderDetach(this, cb);
this.grooveEncoder.removeAllListeners();
function logIfError(err) {
if (err) {
log.error("Unable to detach encoder:", err.stack);
}
}
};
Player.prototype.deleteDbMtimes = function(cb) {
cb = cb || logIfDbError;
var updateCmds = [];
for (var key in this.libraryIndex.trackTable) {
var dbFile = this.libraryIndex.trackTable[key];
delete dbFile.mtime;
persistDbFile(dbFile, updateCmds);
}
this.db.batch(updateCmds, cb);
};
Player.prototype.requestUpdateDb = function(dirName, cb) {
var fullPath = path.resolve(this.musicDirectory, dirName || "");
this.dirScanQueue.add(fullPath, {
dir: fullPath,
}, cb);
};
Player.prototype.refreshFilesIndex = function(args, cb) {
var self = this;
var dir = args.dir;
var dirWithSlash = ensureSep(dir);
var walker = findit(dirWithSlash, {followSymlinks: true});
var thisScanId = uuid();
var delCmds = [];
walker.on('directory', function(fullDirPath, stat, stop, linkPath) {
var usePath = linkPath || fullDirPath;
var dirName = path.relative(self.musicDirectory, usePath);
var baseName = path.basename(dirName);
if (isFileIgnored(baseName)) {
stop();
return;
}
var dirEntry = self.getOrCreateDir(dirName, stat);
if (usePath === dirWithSlash) return; // ignore root search path
var parentDirName = path.dirname(dirName);
if (parentDirName === '.') parentDirName = '';
var parentDirEntry = self.getOrCreateDir(parentDirName);
parentDirEntry.dirEntries[baseName] = thisScanId;
});
walker.on('file', function(fullPath, stat, linkPath) {
var usePath = linkPath || fullPath;
var relPath = path.relative(self.musicDirectory, usePath);
var dirName = path.dirname(relPath);
if (dirName === '.') dirName = '';
var baseName = path.basename(relPath);
if (isFileIgnored(baseName)) return;
var extName = path.extname(relPath);
if (isExtensionIgnored(self, extName)) return;
var dirEntry = self.getOrCreateDir(dirName);
dirEntry.entries[baseName] = thisScanId;
var fileMtime = stat.mtime.getTime();
onAddOrChange(self, relPath, fileMtime);
});
walker.on('error', function(err) {
walker.stop();
cleanupAndCb(err);
});
walker.on('end', function() {
var dirName = path.relative(self.musicDirectory, dir);
checkDirEntry(self.dirs[dirName]);
cleanupAndCb();
function checkDirEntry(dirEntry) {
if (!dirEntry) return;
var id;
var baseName;
var i;
var deletedFiles = [];
var deletedDirs = [];
for (baseName in dirEntry.entries) {
id = dirEntry.entries[baseName];
if (id !== thisScanId) deletedFiles.push(baseName);
}
for (i = 0; i < deletedFiles.length; i += 1) {
baseName = deletedFiles[i];
delete dirEntry.entries[baseName];
onFileMissing(dirEntry, baseName);
}
for (baseName in dirEntry.dirEntries) {
id = dirEntry.dirEntries[baseName];
var childEntry = self.dirs[path.join(dirEntry.dirName, baseName)];
checkDirEntry(childEntry);
if (id !== thisScanId) deletedDirs.push(baseName);
}
for (i = 0; i < deletedDirs.length; i += 1) {
baseName = deletedDirs[i];
delete dirEntry.dirEntries[baseName];
onDirMissing(dirEntry, baseName);
}
self.persistDirEntry(dirEntry);
}
});
function cleanupAndCb(err) {
if (delCmds.length > 0) {
self.db.batch(delCmds, logIfDbError);
self.emit('deleteDbTrack');
}
cb(err);
}
function onDirMissing(parentDirEntry, baseName) {
var dirName = path.join(parentDirEntry.dirName, baseName);
log.debug("directory deleted:", dirName);
var dirEntry = self.dirs[dirName];
var watcher = dirEntry.watcher;
if (watcher) watcher.close();
delete self.dirs[dirName];
delete parentDirEntry.dirEntries[baseName];
}
function onFileMissing(parentDirEntry, baseName) {
var relPath = path.join(parentDirEntry.dirName, baseName);
log.debug("file deleted:", relPath);
delete parentDirEntry.entries[baseName];
var dbFile = self.dbFilesByPath[relPath];
if (dbFile) {
// batch up some db delete commands to run after walking the file system
delDbEntryCmds(self, dbFile, delCmds);
}
}
};
Player.prototype.watchDirEntry = function(dirEntry) {
var self = this;
var changeTriggered = null;
var fullDirPath = path.join(self.musicDirectory, dirEntry.dirName);
var watcher;
try {
watcher = fs.watch(fullDirPath, onChange);
watcher.on('error', onWatchError);
} catch (err) {
log.warn("Unable to fs.watch:", err.stack);
watcher = null;
}
dirEntry.watcher = watcher;
function onChange(eventName) {
if (changeTriggered) clearTimeout(changeTriggered);
changeTriggered = setTimeout(function() {
changeTriggered = null;
log.debug("dir updated:", dirEntry.dirName);
self.dirScanQueue.add(fullDirPath, { dir: fullDirPath });
}, 100);
}
function onWatchError(err) {
log.error("watch error:", err.stack);
}
};
Player.prototype.getOrCreateDir = function (dirName, stat) {
var dirEntry = this.dirs[dirName];
if (!dirEntry) {
dirEntry = this.dirs[dirName] = {
dirName: dirName,
entries: {},
dirEntries: {},
watcher: null, // will be set just below
mtime: stat && stat.mtime,
};
} else if (stat && dirEntry.mtime !== stat.mtime) {
dirEntry.mtime = stat.mtime;
}
if (!dirEntry.watcher) this.watchDirEntry(dirEntry);
return dirEntry;
};
Player.prototype.getCurPos = function() {
return this.isPlaying ?
((new Date() - this.trackStartDate) / 1000.0) : this.pausedTime;
};
function startPlayerSwitchDevice(self, wantHardware, cb) {
self.desiredPlayerHardwareState = wantHardware;
if (self.pendingPlayerAttachDetach) return;
self.pendingPlayerAttachDetach = true;
if (self.groovePlayer) {
self.groovePlayer.removeAllListeners();
self.groovePlayer.detach(onDetachComplete);
} else {
onDetachComplete();
}
function onDetachComplete(err) {
if (err) return cb(err);
self.groovePlayer = groove.createPlayer();
self.groovePlayer.deviceIndex = wantHardware ? null : groove.DUMMY_DEVICE;
self.groovePlayer.attach(self.groovePlaylist, function(err) {
self.pendingPlayerAttachDetach = false;
if (err) return cb(err);
if (self.desiredPlayerHardwareState !== wantHardware) {
startPlayerSwitchDevice(self, self.desiredPlayerHardwareState, cb);
} else {
cb();
}
});
}
}
Player.prototype.setHardwarePlayback = function(value, cb) {
var self = this;
cb = cb || logIfError;
value = !!value;
if (value === self.desiredPlayerHardwareState) return cb();
startPlayerSwitchDevice(self, value, function(err) {
if (err) return cb(err);
self.clearEncodedBuffer();
self.emit('seek');
self.groovePlayer.on('nowplaying', onNowPlaying);
self.persistOption('hardwarePlayback', self.desiredPlayerHardwareState);
self.emit('hardwarePlayback', self.desiredPlayerHardwareState);
cb();
});
function onNowPlaying() {
var playHead = self.groovePlayer.position();
var decodeHead = self.groovePlaylist.position();
if (playHead.item) {
var nowMs = (new Date()).getTime();
var posMs = playHead.pos * 1000;
self.trackStartDate = new Date(nowMs - posMs);
self.currentTrack = self.grooveItems[playHead.item.id];
playlistChanged(self);
self.currentTrackChanged();
} else if (!decodeHead.item) {
if (!self.dontBelieveTheEndOfPlaylistSentinelItsATrap) {
// both play head and decode head are null. end of playlist.
log.debug("end of playlist");
self.currentTrack = null;
playlistChanged(self);
self.currentTrackChanged();
}
}
}
function logIfError(err) {
if (err) {
log.error("Unable to set hardware playback mode:", err.stack);
}
}
};
Player.prototype.startStreaming = function(resp) {
this.headerBuffers.forEach(function(headerBuffer) {
resp.write(headerBuffer);
});
this.recentBuffers.forEach(function(recentBuffer) {
resp.write(recentBuffer.buffer);
});
this.cancelDetachEncoderTimeout();
this.attachEncoder();
this.openStreamers.push(resp);
this.emit('streamerConnect', resp.client);
};
Player.prototype.stopStreaming = function(resp) {
for (var i = 0; i < this.openStreamers.length; i += 1) {
if (this.openStreamers[i] === resp) {
this.openStreamers.splice(i, 1);
this.emit('streamerDisconnect', resp.client);
break;
}
}
};
Player.prototype.lastStreamerDisconnected = function() {
log.debug("last streamer disconnected");
this.startDetachEncoderTimeout();
if (!this.desiredPlayerHardwareState && this.isPlaying) {
this.emit("autoPause");
this.pause();
}
};
Player.prototype.cancelDetachEncoderTimeout = function() {
if (this.detachEncoderTimeout) {
clearTimeout(this.detachEncoderTimeout);
this.detachEncoderTimeout = null;
}
};
Player.prototype.startDetachEncoderTimeout = function() {
var self = this;
self.cancelDetachEncoderTimeout();
// we use encodeQueueDuration for the encoder timeout so that we are
// guaranteed to have audio available for the encoder in the case of
// detaching and reattaching the encoder.
self.detachEncoderTimeout = setTimeout(timeout, self.encodeQueueDuration * 1000);
function timeout() {
if (self.openStreamers.length === 0 && self.isPlaying) {
log.debug("detaching encoder");
self.detachEncoder();
}
}
};
Player.prototype.deleteFiles = function(keys) {
var self = this;
var delCmds = [];
for (var i = 0; i < keys.length; i += 1) {
var key = keys[i];
var dbFile = self.libraryIndex.trackTable[key];
if (!dbFile) continue;
var fullPath = path.join(self.musicDirectory, dbFile.file);
delDbEntryCmds(self, dbFile, delCmds);
fs.unlink(fullPath, logIfError);
}
if (delCmds.length > 0) {
self.emit('deleteDbTrack');
self.db.batch(delCmds, logIfError);
}
function logIfError(err) {
if (err) {
log.error("Error deleting files:", err.stack);
}
}
};
function delDbEntryCmds(self, dbFile, dbCmds) {
// delete items from the queue that are being deleted from the library
var deleteQueueItems = [];
for (var queueId in self.playlist) {
var queueItem = self.playlist[queueId];
if (queueItem.key === dbFile.key) {
deleteQueueItems.push(queueId);
}
}
self.removeQueueItems(deleteQueueItems);
// delete items from playlists that are being deleted from the library
var playlistRemovals = {};
for (var playlistId in self.playlists) {
var playlist = self.playlists[playlistId];
var removals = [];
playlistRemovals[playlistId] = removals;
for (var playlistItemId in playlist.items) {
var playlistItem = playlist.items[playlistItemId];
if (playlistItem.key === dbFile.key) {
removals.push(playlistItemId);
}
}
}
self.playlistRemoveItems(playlistRemovals);
self.libraryIndex.removeTrack(dbFile.key);
delete self.dbFilesByPath[dbFile.file];
var baseName = path.basename(dbFile.file);
var parentDirName = path.dirname(dbFile.file);
if (parentDirName === '.') parentDirName = '';
var parentDirEntry = self.dirs[parentDirName];
if (parentDirEntry) delete parentDirEntry[baseName];
dbCmds.push({type: 'del', key: LIBRARY_KEY_PREFIX + dbFile.key});
}
Player.prototype.setVolume = function(value) {
value = Math.min(2.0, value);
value = Math.max(0.0, value);
this.volume = value;
this.groovePlaylist.setGain(value);
this.persistOption('volume', this.volume);
this.emit("volumeUpdate");
};
Player.prototype.importUrl = function(urlString, cb) {
var self = this;
cb = cb || logIfError;
var filterIndex = 0;
tryImportFilter();
function tryImportFilter() {
var importFilter = importUrlFilters[filterIndex];
if (!importFilter) return cb();
importFilter.fn(urlString, callNextFilter);
function callNextFilter(err, dlStream, filenameHintWithoutPath, size) {
if (err || !dlStream) {
if (err) {
log.error(importFilter.name + " import filter error, skipping:", err.stack);
}
filterIndex += 1;
tryImportFilter();
return;
}
self.importStream(dlStream, filenameHintWithoutPath, size, cb);
}
}
function logIfError(err) {
if (err) {
log.error("Unable to import by URL.", err.stack, "URL:", urlString);
}
}
};
Player.prototype.importNames = function(names, cb) {
var self = this;
var pend = new Pend();
var allDbFiles = [];
names.forEach(function(name) {
pend.go(function(cb) {
youtubeSearch(name, self.googleApiKey, function(err, videoUrl) {
if (err) {
log.error("YouTube search error, skipping " + name + ": " + err.stack);
cb();
return;
}
self.importUrl(videoUrl, function(err, dbFiles) {
if (err) {
log.error("Unable to import from YouTube: " + err.stack);
} else if (!dbFiles) {
log.error("Unrecognized YouTube URL: " + videoUrl);
} else if (dbFiles.length > 0) {
allDbFiles = allDbFiles.concat(dbFiles);
}
cb();
});
});
});
});
pend.wait(function() {
cb(null, allDbFiles);
});
};
Player.prototype.importStream = function(readStream, filenameHintWithoutPath, size, cb) {
var self = this;
var ext = path.extname(filenameHintWithoutPath);
var tmpDir = path.join(self.musicDirectory, '.tmp');
var id = uuid();
var destPath = path.join(tmpDir, id + ext);
var calledCallback = false;
var writeStream = null;
var progressTimer = null;
var importEvent = {
id: id,
filenameHintWithoutPath: filenameHintWithoutPath,
bytesWritten: 0,
size: size,
date: new Date(),
};
readStream.on('error', cleanAndCb);
self.importProgress[importEvent.id] = importEvent;
self.emit('importStart', importEvent);
mkdirp(tmpDir, function(err) {
if (calledCallback) return;
if (err) return cleanAndCb(err);
writeStream = fs.createWriteStream(destPath);
readStream.pipe(writeStream);
progressTimer = setInterval(checkProgress, 100);
writeStream.on('close', onClose);
writeStream.on('error', cleanAndCb);
function checkProgress() {
importEvent.bytesWritten = writeStream.bytesWritten;
self.maybeEmitImportProgress();
}
function onClose(){
if (calledCallback) return;
checkProgress();
self.importFile(destPath, filenameHintWithoutPath, function(err, dbFiles) {
if (calledCallback) return;
if (err) {
cleanAndCb(err);
} else {
calledCallback = true;
cleanTimer();
delete self.importProgress[importEvent.id];
self.emit('importEnd', importEvent);
cb(null, dbFiles);
}
});
}
});
function cleanTimer() {
if (progressTimer) {
clearInterval(progressTimer);
progressTimer = null;
}
}
function cleanAndCb(err) {
if (writeStream) {
fs.unlink(destPath, onUnlinkDone);
writeStream = null;
}
cleanTimer();
if (calledCallback) return;
calledCallback = true;
delete self.importProgress[importEvent.id];
self.emit('importAbort', importEvent);
cb(err);
function onUnlinkDone(err) {
if (err) {
log.warn("Unable to clean up temp file:", err.stack);
}
}
}
};
Player.prototype.importFile = function(srcFullPath, filenameHintWithoutPath, cb) {
var self = this;
cb = cb || logIfError;
var filterIndex = 0;
log.debug("importFile open file:", srcFullPath);
disableFsListenRef(self, tryImportFilter);
function tryImportFilter() {
var importFilter = importFileFilters[filterIndex];
if (!importFilter) return cleanAndCb();
importFilter.fn(self, srcFullPath, filenameHintWithoutPath, callNextFilter);
function callNextFilter(err, dbFiles) {
if (err || !dbFiles) {
if (err) {
log.debug(importFilter.name + " import filter error, skipping:", err.message);
}
filterIndex += 1;
tryImportFilter();
return;
}
cleanAndCb(null, dbFiles);
}
}
function cleanAndCb(err, dbFiles) {
if (!dbFiles) {
fs.unlink(srcFullPath, logIfUnlinkError);
}
disableFsListenUnref(self);
cb(err, dbFiles);
}
function logIfUnlinkError(err) {
if (err) {
log.error("unable to unlink file:", err.stack);
}
}
function logIfError(err) {
if (err) {
log.error("unable to import file:", err.stack);
}
}
};
Player.prototype.maybeEmitImportProgress = function() {
var now = new Date();
var passedTime = now - this.lastImportProgressEvent;
if (passedTime > 500) {
this.lastImportProgressEvent = now;
this.emit("importProgress");
}
};
Player.prototype.persistDirEntry = function(dirEntry, cb) {
cb = cb || logIfError;
this.db.put(LIBRARY_DIR_PREFIX + dirEntry.dirName, serializeDirEntry(dirEntry), cb);
function logIfError(err) {
if (err) {
log.error("unable to persist db entry:", dirEntry, err.stack);
}
}
};
Player.prototype.persistDbFile = function(dbFile, updateCmds) {
this.libraryIndex.addTrack(dbFile);
this.dbFilesByPath[dbFile.file] = dbFile;
persistDbFile(dbFile, updateCmds);
};
Player.prototype.persistOneDbFile = function(dbFile, cb) {
cb = cb || logIfDbError;
var updateCmds = [];
this.persistDbFile(dbFile, updateCmds);
this.db.batch(updateCmds, cb);
};
Player.prototype.persistOption = function(name, value, cb) {
this.db.put(PLAYER_KEY_PREFIX + name, JSON.stringify(value), cb || logIfError);
function logIfError(err) {
if (err) {
log.error("unable to persist player option:", err.stack);
}
}
};
Player.prototype.addToLibrary = function(args, cb) {
var self = this;
var relPath = args.relPath;
var mtime = args.mtime;
var fullPath = path.join(self.musicDirectory, relPath);
log.debug("addToLibrary open file:", fullPath);
groove.open(fullPath, function(err, file) {
if (err) {
self.invalidPaths[relPath] = err.message;
cb();
return;
}
var dbFile = self.dbFilesByPath[relPath];
var filenameHintWithoutPath = path.basename(relPath);
var newDbFile = grooveFileToDbFile(file, filenameHintWithoutPath, dbFile);
newDbFile.file = relPath;
newDbFile.mtime = mtime;
var pend = new Pend();
pend.go(function(cb) {
log.debug("addToLibrary close file:", file.filename);
file.close(cb);
});
pend.go(function(cb) {
self.persistOneDbFile(newDbFile, function(err) {
if (err) log.error("Error saving", relPath, "to db:", err.stack);
cb();
});
});
self.emit('updateDb');
pend.wait(cb);
});
};
Player.prototype.updateTags = function(obj) {
var updateCmds = [];
for (var key in obj) {
var dbFile = this.libraryIndex.trackTable[key];
if (!dbFile) continue;
var props = obj[key];
for (var propName in DB_PROPS) {
var prop = DB_PROPS[propName];
if (! prop.clientCanModify) continue;
if (! (propName in props)) continue;
var parser = PROP_TYPE_PARSERS[prop.type];
dbFile[propName] = parser(props[propName]);
}
this.persistDbFile(dbFile, updateCmds);
}
if (updateCmds.length > 0) {
this.db.batch(updateCmds, logIfDbError);
this.emit('updateDb');
}
};
Player.prototype.insertTracks = function(index, keys, tagAsRandom) {
if (keys.length === 0) return [];
if (index < 0) index = 0;
if (index > this.tracksInOrder.length) index = this.tracksInOrder.length;
var trackBeforeIndex = this.tracksInOrder[index - 1];
var trackAtIndex = this.tracksInOrder[index];
var prevSortKey = trackBeforeIndex ? trackBeforeIndex.sortKey : null;
var nextSortKey = trackAtIndex ? trackAtIndex.sortKey : null;
var items = {};
var ids = [];
var sortKeys = keese(prevSortKey, nextSortKey, keys.length);
keys.forEach(function(key, i) {
var id = uuid();
var sortKey = sortKeys[i];
items[id] = {
key: key,
sortKey: sortKey,
};
ids.push(id);
});
this.addItems(items, tagAsRandom);
return ids;
};
Player.prototype.appendTracks = function(keys, tagAsRandom) {
return this.insertTracks(this.tracksInOrder.length, keys, tagAsRandom);
};
// items looks like {id: {key, sortKey}}
Player.prototype.addItems = function(items, tagAsRandom) {
var self = this;
tagAsRandom = !!tagAsRandom;
var updateCmds = [];
for (var id in items) {
var item = items[id];
var dbFile = self.libraryIndex.trackTable[item.key];
if (!dbFile) continue;
dbFile.lastQueueDate = new Date();
self.persistDbFile(dbFile, updateCmds);
var queueItem = {
id: id,
key: item.key,
sortKey: item.sortKey,
isRandom: tagAsRandom,
grooveFile: null,
pendingGrooveFile: false,
deleted: false,
};
self.playlist[id] = queueItem;
persistQueueItem(queueItem, updateCmds);
}
if (updateCmds.length > 0) {
self.db.batch(updateCmds, logIfDbError);
playlistChanged(self);
lazyReplayGainScanPlaylist(self);
}
};
Player.prototype.playlistCreate = function(id, name) {
if (this.playlists[id]) {
log.warn("tried to create playlist with same id as existing");
return;
}
var playlist = {
id: id,
name: name,
mtime: new Date().getTime(),
items: {},
};
this.playlists[playlist.id] = playlist;
this.persistPlaylist(playlist);
this.emit('playlistCreate', playlist);
return playlist;
};
Player.prototype.playlistRename = function(playlistId, newName) {
var playlist = this.playlists[playlistId];
if (!playlist) return;
playlist.name = newName;
playlist.mtime = new Date().getTime();
this.persistPlaylist(playlist);
this.emit('playlistUpdate', playlist);
};
Player.prototype.playlistDelete = function(playlistIds) {
var delCmds = [];
for (var i = 0; i < playlistIds.length; i += 1) {
var playlistId = playlistIds[i];
var playlist = this.playlists[playlistId];
if (!playlist) continue;
for (var id in playlist.items) {
var item = playlist.items[id];
if (!item) continue;
delCmds.push({type: 'del', key: playlistItemKey(playlist, item)});
delete playlist.items[id];
}
delCmds.push({type: 'del', key: playlistKey(playlist)});
delete this.playlists[playlistId];
}
if (delCmds.length > 0) {
this.db.batch(delCmds, logIfDbError);
this.emit('playlistDelete');
}
};
Player.prototype.playlistAddItems = function(playlistId, items) {
var playlist = this.playlists[playlistId];
if (!playlist) return;
var updateCmds = [];
for (var id in items) {
var item = items[id];
var dbFile = this.libraryIndex.trackTable[item.key];
if (!dbFile) continue;
var playlistItem = {
id: id,
key: item.key,
sortKey: item.sortKey,
};
playlist.items[id] = playlistItem;
updateCmds.push({
type: 'put',
key: playlistItemKey(playlist, playlistItem),
value: serializePlaylistItem(playlistItem),
});
}
if (updateCmds.length > 0) {
playlist.mtime = new Date().getTime();
updateCmds.push({
type: 'put',
key: playlistKey(playlist),
value: serializePlaylist(playlist),
});
this.db.batch(updateCmds, logIfDbError);
this.emit('playlistUpdate', playlist);
}
};
Player.prototype.playlistRemoveItems = function(removals) {
var updateCmds = [];
for (var playlistId in removals) {
var playlist = this.playlists[playlistId];
if (!playlist) continue;
var ids = removals[playlistId];
var dirty = false;
for (var i = 0; i < ids.length; i += 1) {
var id = ids[i];
var item = playlist.items[id];
if (!item) continue;
dirty = true;
updateCmds.push({type: 'del', key: playlistItemKey(playlist, item)});
delete playlist.items[id];
}
if (dirty) {
playlist.mtime = new Date().getTime();
updateCmds.push({
type: 'put',
key: playlistKey(playlist),
value: serializePlaylist(playlist),
});
}
}
if (updateCmds.length > 0) {
this.db.batch(updateCmds, logIfDbError);
this.emit('playlistUpdate');
}
};
// items looks like {playlistId: {id: {sortKey}}}
Player.prototype.playlistMoveItems = function(updates) {
var updateCmds = [];
for (var playlistId in updates) {
var playlist = this.playlists[playlistId];
if (!playlist) continue;
var playlistDirty = false;
var update = updates[playlistId];
for (var id in update) {
var playlistItem = playlist.items[id];
if (!playlistItem) continue;
var updateItem = update[id];
playlistItem.sortKey = updateItem.sortKey;
playlistDirty = true;
updateCmds.push({
type: 'put',
key: playlistItemKey(playlist, playlistItem),
value: serializePlaylistItem(playlistItem),
});
}
if (playlistDirty) {
playlist.mtime = new Date().getTime();
updateCmds.push({
type: 'put',
key: playlistKey(playlist),
value: serializePlaylist(playlist),
});
}
}
if (updateCmds.length > 0) {
this.db.batch(updateCmds, logIfDbError);
this.emit('playlistUpdate');
}
};
Player.prototype.persistPlaylist = function(playlist, cb) {
cb = cb || logIfDbError;
var key = playlistKey(playlist);
var payload = serializePlaylist(playlist);
this.db.put(key, payload, cb);
};
Player.prototype.labelCreate = function(id, name) {
if (id in this.libraryIndex.labelTable) {
log.warn("tried to create label that already exists");
return;
}
var color = labelColors[Math.floor(Math.random() * labelColors.length)];
var labelEntry = {id: id, name: name, color: color};
this.libraryIndex.addLabel(labelEntry);
var key = LABEL_KEY_PREFIX + id;
this.db.put(key, JSON.stringify(labelEntry), logIfDbError);
this.emit('labelCreate');
};
Player.prototype.labelRename = function(id, name) {
var labelEntry = this.libraryIndex.labelTable[id];
if (!labelEntry) return;
labelEntry.name = name;
this.libraryIndex.addLabel(labelEntry);
var key = LABEL_KEY_PREFIX + id;
this.db.put(key, JSON.stringify(labelEntry), logIfDbError);
this.emit('labelRename');
};
Player.prototype.labelColorUpdate = function(id, color) {
var labelEntry = this.libraryIndex.labelTable[id];
if (!labelEntry) return;
labelEntry.color = color;
this.libraryIndex.addLabel(labelEntry);
var key = LABEL_KEY_PREFIX + id;
this.db.put(key, JSON.stringify(labelEntry), logIfDbError);
this.emit('labelColorUpdate');
};
Player.prototype.labelDelete = function(ids) {
var updateCmds = [];
var libraryChanged = false;
for (var i = 0; i < ids.length; i++) {
var labelId = ids[i];
if (!(labelId in this.libraryIndex.labelTable)) continue;
this.libraryIndex.removeLabel(labelId);
var key = LABEL_KEY_PREFIX + labelId;
updateCmds.push({type: 'del', key: key});
// clean out references from the library
var files = this.dbFilesByLabel[labelId];
for (var fileId in files) {
var dbFile = files[fileId];
delete dbFile.labels[labelId];
persistDbFile(dbFile, updateCmds);
libraryChanged = true;
}
delete this.dbFilesByLabel[labelId];
}
if (updateCmds.length === 0) return;
this.db.batch(updateCmds, logIfDbError);
if (libraryChanged) {
this.emit('updateDb');
}
this.emit('labelDelete');
};
Player.prototype.labelAdd = function(additions) {
this.changeLabels(additions, true);
};
Player.prototype.labelRemove = function(removals) {
this.changeLabels(removals, false);
};
Player.prototype.changeLabels = function(changes, isAdd) {
var self = this;
var updateCmds = [];
for (var id in changes) {
var labelIds = changes[id];
var dbFile = this.libraryIndex.trackTable[id];
if (!dbFile) continue;
if (labelIds.length === 0) continue;
var changedTrack = false;
for (var i = 0; i < labelIds.length; i++) {
var labelId = labelIds[i];
var filesByThisLabel = self.dbFilesByLabel[labelId];
if (isAdd) {
if (labelId in dbFile.labels) continue; // already got it
dbFile.labels[labelId] = 1;
if (filesByThisLabel == null) filesByThisLabel = self.dbFilesByLabel[labelId] = {};
filesByThisLabel[dbFile.key] = dbFile;
} else {
if (!(labelId in dbFile.labels)) continue; // already gone
delete dbFile.labels[labelId];
delete filesByThisLabel[dbFile.key];
}
changedTrack = true;
}
if (changedTrack) {
this.persistDbFile(dbFile, updateCmds);
}
}
if (updateCmds.length === 0) return;
this.db.batch(updateCmds, logIfDbError);
this.emit('updateDb');
};
Player.prototype.clearQueue = function() {
this.removeQueueItems(Object.keys(this.playlist));
};
Player.prototype.removeAllRandomQueueItems = function() {
var idsToRemove = [];
for (var i = 0; i < this.tracksInOrder.length; i += 1) {
var track = this.tracksInOrder[i];
if (track.isRandom && track !== this.currentTrack) {
idsToRemove.push(track.id);
}
}
return this.removeQueueItems(idsToRemove);
};
Player.prototype.shufflePlaylist = function() {
if (this.tracksInOrder.length === 0) return;
if (this.autoDjOn) return this.removeAllRandomQueueItems();
var sortKeys = this.tracksInOrder.map(function(track) {
return track.sortKey;
});
shuffle(sortKeys);
// fix sortKey and index properties
var updateCmds = [];
for (var i = 0; i < this.tracksInOrder.length; i += 1) {
var track = this.tracksInOrder[i];
track.index = i;
track.sortKey = sortKeys[i];
persistQueueItem(track, updateCmds);
}
this.db.batch(updateCmds, logIfDbError);
playlistChanged(this);
};
Player.prototype.removeQueueItems = function(ids) {
if (ids.length === 0) return;
var delCmds = [];
var currentTrackChanged = false;
for (var i = 0; i < ids.length; i += 1) {
var id = ids[i];
var item = this.playlist[id];
if (!item) continue;
delCmds.push({type: 'del', key: QUEUE_KEY_PREFIX + id});
if (item.grooveFile) this.playlistItemDeleteQueue.push(item);
if (item === this.currentTrack) {
var nextPos = this.currentTrack.index + 1;
for (;;) {
var nextTrack = this.tracksInOrder[nextPos];
var nextTrackId = nextTrack && nextTrack.id;
this.currentTrack = nextTrackId && this.playlist[nextTrack.id];
if (!this.currentTrack && nextPos < this.tracksInOrder.length) {
nextPos += 1;
continue;
}
break;
}
if (this.currentTrack) {
this.seekRequestPos = 0;
}
currentTrackChanged = true;
}
delete this.playlist[id];
}
if (delCmds.length > 0) this.db.batch(delCmds, logIfDbError);
playlistChanged(this);
if (currentTrackChanged) {
this.currentTrackChanged();
}
};
// items looks like {id: {sortKey}}
Player.prototype.moveQueueItems = function(items) {
var updateCmds = [];
for (var id in items) {
var track = this.playlist[id];
if (!track) continue; // race conditions, etc.
track.sortKey = items[id].sortKey;
persistQueueItem(track, updateCmds);
}
if (updateCmds.length > 0) {
this.db.batch(updateCmds, logIfDbError);
playlistChanged(this);
}
};
Player.prototype.moveRangeToPos = function(startPos, endPos, toPos) {
var ids = [];
for (var i = startPos; i < endPos; i += 1) {
var track = this.tracksInOrder[i];
if (!track) continue;
ids.push(track.id);
}
this.moveIdsToPos(ids, toPos);
};
Player.prototype.moveIdsToPos = function(ids, toPos) {
var trackBeforeIndex = this.tracksInOrder[toPos - 1];
var trackAtIndex = this.tracksInOrder[toPos];
var prevSortKey = trackBeforeIndex ? trackBeforeIndex.sortKey : null;
var nextSortKey = trackAtIndex ? trackAtIndex.sortKey : null;
var sortKeys = keese(prevSortKey, nextSortKey, ids.length);
var updateCmds = [];
for (var i = 0; i < ids.length; i += 1) {
var id = ids[i];
var queueItem = this.playlist[id];
if (!queueItem) continue;
queueItem.sortKey = sortKeys[i];
persistQueueItem(queueItem, updateCmds);
}
if (updateCmds.length > 0) {
this.db.batch(updateCmds, logIfDbError);
playlistChanged(this);
}
};
Player.prototype.pause = function() {
if (!this.isPlaying) return;
this.isPlaying = false;
this.pausedTime = (new Date() - this.trackStartDate) / 1000;
this.groovePlaylist.pause();
this.cancelDetachEncoderTimeout();
playlistChanged(this);
this.currentTrackChanged();
};
Player.prototype.play = function() {
if (!this.currentTrack) {
this.currentTrack = this.tracksInOrder[0];
} else if (!this.isPlaying) {
this.trackStartDate = new Date(new Date() - this.pausedTime * 1000);
}
this.groovePlaylist.play();
this.startDetachEncoderTimeout();
this.isPlaying = true;
playlistChanged(this);
this.currentTrackChanged();
};
// This function should be avoided in favor of seek. Note that it is called by
// some MPD protocol commands, because the MPD protocol is stupid.
Player.prototype.seekToIndex = function(index, pos) {
var track = this.tracksInOrder[index];
if (!track) return null;
this.currentTrack = track;
this.seekRequestPos = pos;
playlistChanged(this);
this.currentTrackChanged();
return track;
};
Player.prototype.seek = function(id, pos) {
var track = this.playlist[id];
if (!track) return null;
this.currentTrack = this.playlist[id];
this.seekRequestPos = pos;
playlistChanged(this);
this.currentTrackChanged();
return track;
};
Player.prototype.next = function() {
return this.skipBy(1);
};
Player.prototype.prev = function() {
return this.skipBy(-1);
};
Player.prototype.skipBy = function(amt) {
var defaultIndex = amt > 0 ? -1 : this.tracksInOrder.length;
var currentIndex = this.currentTrack ? this.currentTrack.index : defaultIndex;
var newIndex = currentIndex + amt;
return this.seekToIndex(newIndex, 0);
};
Player.prototype.setRepeat = function(value) {
value = Math.floor(value);
if (value !== Player.REPEAT_ONE &&
value !== Player.REPEAT_ALL &&
value !== Player.REPEAT_OFF)
{
return;
}
if (value === this.repeat) return;
this.repeat = value;
this.persistOption('repeat', this.repeat);
playlistChanged(this);
this.emit('repeatUpdate');
};
Player.prototype.setAutoDjOn = function(value) {
value = !!value;
if (value === this.autoDjOn) return;
this.autoDjOn = value;
this.persistOption('autoDjOn', this.autoDjOn);
this.emit('autoDjOn');
this.checkAutoDj();
};
Player.prototype.setAutoDjHistorySize = function(value) {
value = Math.floor(value);
if (value === this.autoDjHistorySize) return;
this.autoDjHistorySize = value;
this.persistOption('autoDjHistorySize', this.autoDjHistorySize);
this.emit('autoDjHistorySize');
this.checkAutoDj();
};
Player.prototype.setAutoDjFutureSize = function(value) {
value = Math.floor(value);
if (value === this.autoDjFutureSize) return;
this.autoDjFutureSize = value;
this.persistOption('autoDjFutureSize', this.autoDjFutureSize);
this.emit('autoDjFutureSize');
this.checkAutoDj();
};
Player.prototype.stop = function() {
this.isPlaying = false;
this.cancelDetachEncoderTimeout();
this.groovePlaylist.pause();
this.seekRequestPos = 0;
this.pausedTime = 0;
playlistChanged(this);
};
Player.prototype.clearEncodedBuffer = function() {
while (this.recentBuffers.length > 0) {
this.recentBuffers.shift();
}
};
Player.prototype.getSuggestedPath = function(track, filenameHint) {
var p = "";
if (track.albumArtistName) {
p = path.join(p, safePath(track.albumArtistName));
} else if (track.compilation) {
p = path.join(p, safePath(this.libraryIndex.variousArtistsName));
} else if (track.artistName) {
p = path.join(p, safePath(track.artistName));
}
if (track.albumName) {
p = path.join(p, safePath(track.albumName));
}
var t = "";
if (track.track != null) {
t += safePath(zfill(track.track, 2)) + " ";
}
t += safePath(track.name + path.extname(filenameHint));
return path.join(p, t);
};
Player.prototype.queueScan = function(dbFile) {
var self = this;
var scanKey, scanType;
if (dbFile.albumName) {
scanType = 'album';
scanKey = self.libraryIndex.getAlbumKey(dbFile);
} else {
scanType = 'track';
scanKey = dbFile.key;
}
if (self.scanQueue.idInQueue(scanKey)) {
return;
}
self.scanQueue.add(scanKey, {
type: scanType,
key: scanKey,
});
};
Player.prototype.performScan = function(args, cb) {
var self = this;
var scanType = args.type;
var scanKey = args.key;
// build list of files we want to open
var dbFilesToOpen;
if (scanType === 'album') {
var albumKey = scanKey;
self.libraryIndex.rebuildTracks();
var album = self.libraryIndex.albumTable[albumKey];
if (!album) {
log.warn("wanted to scan album with key", JSON.stringify(albumKey), "but no longer exists.");
cb();
return;
}
log.debug("Scanning album for loudness:", JSON.stringify(albumKey));
dbFilesToOpen = album.trackList;
} else if (scanType === 'track') {
var trackKey = scanKey;
var dbFile = self.libraryIndex.trackTable[trackKey];
if (!dbFile) {
log.warn("wanted to scan track with key", JSON.stringify(trackKey), "but no longer exists.");
cb();
return;
}
log.debug("Scanning track for loudness:", JSON.stringify(trackKey));
dbFilesToOpen = [dbFile];
} else {
throw new Error("unexpected scan type: " + scanType);
}
// open all the files in the list
var pend = new Pend();
// we're already doing multiple parallel scans. within each scan let's
// read one thing at a time to avoid slamming the system.
pend.max = 1;
var grooveFileList = [];
var files = {};
dbFilesToOpen.forEach(function(dbFile) {
pend.go(function(cb) {
var fullPath = path.join(self.musicDirectory, dbFile.file);
log.debug("performScan open file:", fullPath);
groove.open(fullPath, function(err, file) {
if (err) {
log.error("Error opening", fullPath, "in order to scan:", err.stack);
} else {
var fileInfo;
files[file.id] = fileInfo = {
dbFile: dbFile,
loudnessDone: false,
fingerprintDone: false,
};
self.ongoingScans[dbFile.key] = fileInfo;
grooveFileList.push(file);
}
cb();
});
});
});
var scanPlaylist;
var endOfPlaylistPend = new Pend();
var scanDetector;
var scanDetectorAttached = false;
var endOfDetectorCb;
var scanFingerprinter;
var scanFingerprinterAttached = false;
var endOfFingerprinterCb;
pend.wait(function() {
// emit this because we updated ongoingScans
self.emit('scanProgress');
scanPlaylist = groove.createPlaylist();
scanPlaylist.setFillMode(groove.ANY_SINK_FULL);
scanDetector = groove.createLoudnessDetector();
scanFingerprinter = groove.createFingerprinter();
scanDetector.on('info', onLoudnessInfo);
scanFingerprinter.on('info', onFingerprinterInfo);
var pend = new Pend();
pend.go(attachLoudnessDetector);
pend.go(attachFingerprinter);
pend.wait(onEverythingAttached);
});
function onEverythingAttached(err) {
if (err) {
log.error("Error attaching:", err.stack);
cleanupAndCb();
return;
}
grooveFileList.forEach(function(file) {
scanPlaylist.insert(file);
});
endOfPlaylistPend.wait(function() {
for (var fileId in files) {
var fileInfo = files[fileId];
var dbFile = fileInfo.dbFile;
self.persistOneDbFile(dbFile);
self.emit('scanComplete', dbFile);
}
cleanupAndCb();
});
}
function attachLoudnessDetector(cb) {
scanDetector.attach(scanPlaylist, function(err) {
if (err) return cb(err);
scanDetectorAttached = true;
endOfPlaylistPend.go(function(cb) {
endOfDetectorCb = cb;
});
cb();
});
}
function attachFingerprinter(cb) {
scanFingerprinter.attach(scanPlaylist, function(err) {
if (err) return cb(err);
scanFingerprinterAttached = true;
endOfPlaylistPend.go(function(cb) {
endOfFingerprinterCb = cb;
});
cb();
});
}
function onLoudnessInfo() {
var info;
while (info = scanDetector.getInfo()) {
var gain = groove.loudnessToReplayGain(info.loudness);
var dbFile;
var fileInfo;
if (info.item) {
fileInfo = files[info.item.file.id];
fileInfo.loudnessDone = true;
dbFile = fileInfo.dbFile;
log.info("loudness scan file complete:", dbFile.name,
"gain", gain, "duration", info.duration);
dbFile.replayGainTrackGain = gain;
dbFile.replayGainTrackPeak = info.peak;
dbFile.duration = info.duration;
checkUpdateGroovePlaylist(self);
self.emit('scanProgress');
} else {
log.debug("loudness scan complete:", JSON.stringify(scanKey), "gain", gain);
for (var fileId in files) {
fileInfo = files[fileId];
dbFile = fileInfo.dbFile;
dbFile.replayGainAlbumGain = gain;
dbFile.replayGainAlbumPeak = info.peak;
}
checkUpdateGroovePlaylist(self);
if (endOfDetectorCb) {
endOfDetectorCb();
endOfDetectorCb = null;
}
return;
}
}
}
function onFingerprinterInfo() {
var info;
while (info = scanFingerprinter.getInfo()) {
if (info.item) {
var fileInfo = files[info.item.file.id];
fileInfo.fingerprintDone = true;
var dbFile = fileInfo.dbFile;
log.info("fingerprint scan file complete:", dbFile.name);
dbFile.fingerprint = info.fingerprint;
self.emit('scanProgress');
} else {
log.debug("fingerprint scan complete:", JSON.stringify(scanKey));
if (endOfFingerprinterCb) {
endOfFingerprinterCb();
endOfFingerprinterCb = null;
}
return;
}
}
}
function cleanupAndCb() {
grooveFileList.forEach(function(file) {
pend.go(function(cb) {
var fileInfo = files[file.id];
var dbFile = fileInfo.dbFile;
delete self.ongoingScans[dbFile.key];
log.debug("performScan close file:", file.filename);
file.close(cb);
});
});
if (scanDetectorAttached) pend.go(detachLoudnessScanner);
if (scanFingerprinterAttached) pend.go(detachFingerprinter);
pend.wait(function(err) {
// emit this because we changed ongoingScans above
self.emit('scanProgress');
cb(err);
});
}
function detachLoudnessScanner(cb) {
scanDetector.detach(cb);
}
function detachFingerprinter(cb) {
scanFingerprinter.detach(cb);
}
};
Player.prototype.checkAutoDj = function() {
var self = this;
if (!self.autoDjOn) return;
// if no track is playing, assume the first track is about to be
var currentIndex = self.currentTrack ? self.currentTrack.index : 0;
var deleteCount = Math.max(currentIndex - self.autoDjHistorySize, 0);
if (self.autoDjHistorySize < 0) deleteCount = 0;
var addCount = Math.max(self.autoDjFutureSize + 1 - (self.tracksInOrder.length - currentIndex), 0);
var idsToDelete = [];
for (var i = 0; i < deleteCount; i += 1) {
idsToDelete.push(self.tracksInOrder[i].id);
}
var keys = getRandomSongKeys(addCount);
self.removeQueueItems(idsToDelete);
self.appendTracks(keys, true);
function getRandomSongKeys(count) {
if (count === 0) return [];
var neverQueued = [];
var sometimesQueued = [];
for (var key in self.libraryIndex.trackTable) {
var dbFile = self.libraryIndex.trackTable[key];
if (dbFile.lastQueueDate == null) {
neverQueued.push(dbFile);
} else {
sometimesQueued.push(dbFile);
}
}
// backwards by time
sometimesQueued.sort(function(a, b) {
return b.lastQueueDate - a.lastQueueDate;
});
// distribution is a triangle for ever queued, and a rectangle for never queued
// ___
// /| |
// / | |
// /__|_|
var maxWeight = sometimesQueued.length;
var triangleArea = Math.floor(maxWeight * maxWeight / 2);
if (maxWeight === 0) maxWeight = 1;
var rectangleArea = maxWeight * neverQueued.length;
var totalSize = triangleArea + rectangleArea;
if (totalSize === 0) return [];
// decode indexes through the distribution shape
var keys = [];
for (var i = 0; i < count; i += 1) {
var index = Math.random() * totalSize;
if (index < triangleArea) {
// triangle
keys.push(sometimesQueued[Math.floor(Math.sqrt(index))].key);
} else {
keys.push(neverQueued[Math.floor((index - triangleArea) / maxWeight)].key);
}
}
return keys;
}
};
Player.prototype.currentTrackChanged = function() {
this.persistCurrentTrack();
this.emit('currentTrack');
};
Player.prototype.persistCurrentTrack = function(cb) {
// save the current track and time to db
var currentTrackInfo = {
id: this.currentTrack && this.currentTrack.id,
pos: this.getCurPos(),
};
this.persistOption('currentTrackInfo', currentTrackInfo, cb);
};
Player.prototype.sortAndQueueTracks = function(tracks) {
// given an array of tracks, sort them according to the library sorting
// and then queue them in the best place
if (!tracks.length) return;
var sortedTracks = sortTracks(tracks);
this.queueTracks(sortedTracks);
};
Player.prototype.sortAndQueueTracksInPlaylist = function(playlist, tracks, previousKey, nextKey) {
if (!tracks.length) return;
var sortedTracks = sortTracks(tracks);
var items = {};
var sortKeys = keese(previousKey, nextKey, tracks.length);
for (var i = 0; i < tracks.length; i += 1) {
var track = tracks[i];
var sortKey = sortKeys[i];
var id = uuid();
items[id] = {
key: track.key,
sortKey: sortKey,
};
}
this.playlistAddItems(playlist.id, items);
};
Player.prototype.queueTrackKeys = function(trackKeys, previousKey, nextKey) {
if (!trackKeys.length) return;
if (previousKey == null && nextKey == null) {
var defaultPos = this.getDefaultQueuePosition();
previousKey = defaultPos.previousKey;
nextKey = defaultPos.nextKey;
}
var items = {};
var sortKeys = keese(previousKey, nextKey, trackKeys.length);
for (var i = 0; i < trackKeys.length; i += 1) {
var trackKey = trackKeys[i];
var sortKey = sortKeys[i];
var id = uuid();
items[id] = {
key: trackKey,
sortKey: sortKey,
};
}
this.addItems(items, false);
};
Player.prototype.queueTracks = function(tracks, previousKey, nextKey) {
// given an array of tracks, and a previous sort key and a next sort key,
// call addItems correctly
var trackKeys = tracks.map(function(track) {
return track.key;
}).filter(function(key) {
return !!key;
});
return this.queueTrackKeys(trackKeys, previousKey, nextKey);
};
Player.prototype.getDefaultQueuePosition = function() {
var previousKey = this.currentTrack && this.currentTrack.sortKey;
var nextKey = null;
var startPos = this.currentTrack ? this.currentTrack.index + 1 : 0;
for (var i = startPos; i < this.tracksInOrder.length; i += 1) {
var track = this.tracksInOrder[i];
var sortKey = track.sortKey;
if (track.isRandom) {
nextKey = sortKey;
break;
}
previousKey = sortKey;
}
return {
previousKey: previousKey,
nextKey: nextKey
};
};
function persistDbFile(dbFile, updateCmds) {
updateCmds.push({
type: 'put',
key: LIBRARY_KEY_PREFIX + dbFile.key,
value: serializeFileData(dbFile),
});
}
function persistQueueItem(item, updateCmds) {
updateCmds.push({
type: 'put',
key: QUEUE_KEY_PREFIX + item.id,
value: serializeQueueItem(item),
});
}
function onAddOrChange(self, relPath, fileMtime, cb) {
cb = cb || logIfError;
// check the mtime against the mtime of the same file in the db
var dbFile = self.dbFilesByPath[relPath];
if (dbFile) {
var dbMtime = dbFile.mtime;
if (dbMtime >= fileMtime) {
// the info we have in our db for this file is fresh
cb(null, dbFile);
return;
}
}
self.addQueue.add(relPath, {
relPath: relPath,
mtime: fileMtime,
});
self.addQueue.waitForId(relPath, function(err) {
var dbFile = self.dbFilesByPath[relPath];
cb(err, dbFile);
});
function logIfError(err) {
if (err) {
log.error("Unable to add to queue:", err.stack);
}
}
}
function checkPlayCount(self) {
if (self.isPlaying && !self.previousIsPlaying) {
self.playingStart = new Date(new Date() - self.playingTime);
self.previousIsPlaying = true;
}
self.playingTime = new Date() - self.playingStart;
if (self.currentTrack === self.lastPlayingItem) return;
if (self.lastPlayingItem) {
var dbFile = self.libraryIndex.trackTable[self.lastPlayingItem.key];
if (dbFile) {
var minAmt = 15 * 1000;
var maxAmt = 4 * 60 * 1000;
var halfAmt = dbFile.duration / 2 * 1000;
if (self.playingTime >= minAmt && (self.playingTime >= maxAmt || self.playingTime >= halfAmt)) {
dbFile.playCount += 1;
self.persistOneDbFile(dbFile);
self.emit('play', self.lastPlayingItem, dbFile, self.playingStart);
self.emit('updateDb');
}
}
}
self.lastPlayingItem = self.currentTrack;
self.previousIsPlaying = self.isPlaying;
self.playingStart = new Date();
self.playingTime = 0;
}
function disableFsListenRef(self, fn) {
self.disableFsRefCount += 1;
if (self.disableFsRefCount === 1) {
log.debug("pause dirScanQueue");
self.dirScanQueue.setPause(true);
self.dirScanQueue.waitForProcessing(fn);
} else {
fn();
}
}
function disableFsListenUnref(self) {
self.disableFsRefCount -= 1;
if (self.disableFsRefCount === 0) {
log.debug("unpause dirScanQueue");
self.dirScanQueue.setPause(false);
} else if (self.disableFsRefCount < 0) {
throw new Error("disableFsListenUnref called too many times");
}
}
function operatorCompare(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}
function disambiguateSortKeys(self) {
var previousUniqueKey = null;
var previousKey = null;
self.tracksInOrder.forEach(function(track, i) {
if (track.sortKey === previousKey) {
// move the repeat back
track.sortKey = keese(previousUniqueKey, track.sortKey);
previousUniqueKey = track.sortKey;
} else {
previousUniqueKey = previousKey;
previousKey = track.sortKey;
}
});
}
// generate self.tracksInOrder from self.playlist
function cacheTracksArray(self) {
self.tracksInOrder = Object.keys(self.playlist).map(trackById);
self.tracksInOrder.sort(asc);
self.tracksInOrder.forEach(function(track, index) {
track.index = index;
});
function asc(a, b) {
return operatorCompare(a.sortKey, b.sortKey);
}
function trackById(id) {
return self.playlist[id];
}
}
function lazyReplayGainScanPlaylist(self) {
// clear the queue since we're going to completely rebuild it anyway
// this allows the following priority code to work.
self.scanQueue.clear();
// prioritize the currently playing track, followed by the next tracks,
// followed by the previous tracks
var albumGain = {};
var start1 = self.currentTrack ? self.currentTrack.index : 0;
var i;
for (i = start1; i < self.tracksInOrder.length; i += 1) {
checkScan(self.tracksInOrder[i]);
}
for (i = 0; i < start1; i += 1) {
checkScan(self.tracksInOrder[i]);
}
function checkScan(track) {
var dbFile = self.libraryIndex.trackTable[track.key];
if (!dbFile) return;
var albumKey = self.libraryIndex.getAlbumKey(dbFile);
var needScan =
dbFile.fingerprint == null ||
dbFile.replayGainAlbumGain == null ||
dbFile.replayGainTrackGain == null ||
(dbFile.albumName && albumGain[albumKey] && albumGain[albumKey] !== dbFile.replayGainAlbumGain);
if (needScan) {
self.queueScan(dbFile);
} else {
albumGain[albumKey] = dbFile.replayGainAlbumGain;
}
}
}
function playlistChanged(self) {
cacheTracksArray(self);
disambiguateSortKeys(self);
if (self.currentTrack) {
self.tracksInOrder.forEach(function(track, index) {
var prevDiff = self.currentTrack.index - index;
var nextDiff = index - self.currentTrack.index;
var withinPrev = prevDiff <= PREV_FILE_COUNT && prevDiff >= 0;
var withinNext = nextDiff <= NEXT_FILE_COUNT && nextDiff >= 0;
var shouldHaveGrooveFile = withinPrev || withinNext;
var hasGrooveFile = track.grooveFile != null || track.pendingGrooveFile;
if (hasGrooveFile && !shouldHaveGrooveFile) {
self.playlistItemDeleteQueue.push(track);
} else if (!hasGrooveFile && shouldHaveGrooveFile) {
preloadFile(self, track);
}
});
} else {
self.isPlaying = false;
self.cancelDetachEncoderTimeout();
self.trackStartDate = null;
self.pausedTime = 0;
}
checkUpdateGroovePlaylist(self);
performGrooveFileDeletes(self);
self.checkAutoDj();
checkPlayCount(self);
self.emit('queueUpdate');
}
function performGrooveFileDeletes(self) {
while (self.playlistItemDeleteQueue.length) {
var item = self.playlistItemDeleteQueue.shift();
// we set this so that any callbacks that return which were trying to
// set the grooveItem can check if the item got deleted
item.deleted = true;
if (!item.grooveFile) continue;
log.debug("performGrooveFileDeletes close file:", item.grooveFile.filename);
var grooveFile = item.grooveFile;
item.grooveFile = null;
closeFile(grooveFile);
}
}
function preloadFile(self, track) {
var relPath = self.libraryIndex.trackTable[track.key].file;
var fullPath = path.join(self.musicDirectory, relPath);
track.pendingGrooveFile = true;
log.debug("preloadFile open file:", fullPath);
// set this so that we know we want the file preloaded
track.deleted = false;
groove.open(fullPath, function(err, file) {
track.pendingGrooveFile = false;
if (err) {
log.error("Error opening", relPath, err.stack);
return;
}
if (track.deleted) {
log.debug("preloadFile close file (already deleted):", file.filename);
closeFile(file);
return;
}
track.grooveFile = file;
checkUpdateGroovePlaylist(self);
});
}
function checkUpdateGroovePlaylist(self) {
if (!self.currentTrack) {
self.groovePlaylist.clear();
self.grooveItems = {};
return;
}
var groovePlaylist = self.groovePlaylist.items();
var playHead = self.groovePlayer.position();
var playHeadItemId = playHead.item && playHead.item.id;
var groovePlIndex = 0;
var grooveItem;
if (playHeadItemId) {
while (groovePlIndex < groovePlaylist.length) {
grooveItem = groovePlaylist[groovePlIndex];
if (grooveItem.id === playHeadItemId) break;
// this groove playlist item is before the current playhead. delete it!
self.groovePlaylist.remove(grooveItem);
delete self.grooveItems[grooveItem.id];
groovePlIndex += 1;
}
}
var plItemIndex = self.currentTrack.index;
var plTrack;
var currentGrooveItem = null; // might be different than playHead.item
var groovePlItemCount = 0;
var gainAndPeak;
while (groovePlIndex < groovePlaylist.length) {
grooveItem = groovePlaylist[groovePlIndex];
var grooveTrack = self.grooveItems[grooveItem.id];
// now we have deleted all items before the current track. we are now
// comparing the libgroove playlist and the groovebasin playlist
// side by side.
plTrack = self.tracksInOrder[plItemIndex];
if (grooveTrack === plTrack) {
// if they're the same, we advance
// but we might have to correct the gain
gainAndPeak = calcGainAndPeak(plTrack);
self.groovePlaylist.setItemGain(grooveItem, gainAndPeak.gain);
self.groovePlaylist.setItemPeak(grooveItem, gainAndPeak.peak);
currentGrooveItem = currentGrooveItem || grooveItem;
groovePlIndex += 1;
incrementPlIndex();
continue;
}
// this groove track is wrong. delete it.
self.groovePlaylist.remove(grooveItem);
delete self.grooveItems[grooveItem.id];
groovePlIndex += 1;
}
// we still need to add more libgroove playlist items, but this one has
// not yet finished loading from disk. We must take note of this so that
// if we receive the end of playlist sentinel, we start playback again
// once this track has finished loading.
self.dontBelieveTheEndOfPlaylistSentinelItsATrap = true;
while (groovePlItemCount < NEXT_FILE_COUNT) {
plTrack = self.tracksInOrder[plItemIndex];
if (!plTrack) {
// we hit the end of the groove basin playlist. we're done adding tracks
// to the libgroove playlist.
self.dontBelieveTheEndOfPlaylistSentinelItsATrap = false;
break;
}
if (!plTrack.grooveFile) {
break;
}
// compute the gain adjustment
gainAndPeak = calcGainAndPeak(plTrack);
grooveItem = self.groovePlaylist.insert(plTrack.grooveFile, gainAndPeak.gain, gainAndPeak.peak);
self.grooveItems[grooveItem.id] = plTrack;
currentGrooveItem = currentGrooveItem || grooveItem;
incrementPlIndex();
}
if (currentGrooveItem && self.seekRequestPos >= 0) {
var seekPos = self.seekRequestPos;
// we want to clear encoded buffers after the seek completes, e.g. after
// we get the end of playlist sentinel
self.clearEncodedBuffer();
self.queueClearEncodedBuffers = true;
self.groovePlaylist.seek(currentGrooveItem, seekPos);
self.seekRequestPos = -1;
if (self.isPlaying) {
var nowMs = (new Date()).getTime();
var posMs = seekPos * 1000;
self.trackStartDate = new Date(nowMs - posMs);
} else {
self.pausedTime = seekPos;
}
self.currentTrackChanged();
}
function calcGainAndPeak(plTrack) {
// if the previous item is the previous item from the album, or the
// next item is the next item from the album, use album replaygain.
// else, use track replaygain.
var dbFile = self.libraryIndex.trackTable[plTrack.key];
var albumMode = albumInfoMatch(-1) || albumInfoMatch(1);
var gain = REPLAYGAIN_PREAMP;
var peak;
if (dbFile.replayGainAlbumGain != null && albumMode) {
gain *= dBToFloat(dbFile.replayGainAlbumGain);
peak = dbFile.replayGainAlbumPeak || 1.0;
} else if (dbFile.replayGainTrackGain != null) {
gain *= dBToFloat(dbFile.replayGainTrackGain);
peak = dbFile.replayGainTrackPeak || 1.0;
} else {
gain *= REPLAYGAIN_DEFAULT;
peak = 1.0;
}
return {gain: gain, peak: peak};
function albumInfoMatch(dir) {
var otherPlTrack = self.tracksInOrder[plTrack.index + dir];
if (!otherPlTrack) return false;
var otherDbFile = self.libraryIndex.trackTable[otherPlTrack.key];
if (!otherDbFile) return false;
var albumMatch = self.libraryIndex.getAlbumKey(dbFile) === self.libraryIndex.getAlbumKey(otherDbFile);
if (!albumMatch) return false;
// if there are no track numbers then it's hardly an album, is it?
if (dbFile.track == null || otherDbFile.track == null) {
return false;
}
var trackMatch = dbFile.track + dir === otherDbFile.track;
if (!trackMatch) return false;
return true;
}
}
function incrementPlIndex() {
groovePlItemCount += 1;
if (self.repeat !== Player.REPEAT_ONE) {
plItemIndex += 1;
if (self.repeat === Player.REPEAT_ALL && plItemIndex >= self.tracksInOrder.length) {
plItemIndex = 0;
}
}
}
}
function isFileIgnored(basename) {
return (/^\./).test(basename) || (/~$/).test(basename);
}
function isExtensionIgnored(self, extName) {
var extNameLower = extName.toLowerCase();
for (var i = 0; i < self.ignoreExtensions.length; i += 1) {
if (self.ignoreExtensions[i] === extNameLower) {
return true;
}
}
return false;
}
function deserializeFileData(dataStr) {
var dbFile = JSON.parse(dataStr);
for (var propName in DB_PROPS) {
var propInfo = DB_PROPS[propName];
if (!propInfo) continue;
var parser = PROP_TYPE_PARSERS[propInfo.type];
dbFile[propName] = parser(dbFile[propName]);
}
return dbFile;
}
function serializeQueueItem(item) {
return JSON.stringify({
id: item.id,
key: item.key,
sortKey: item.sortKey,
isRandom: item.isRandom,
});
}
function serializePlaylistItem(item) {
return JSON.stringify({
id: item.id,
key: item.key,
sortKey: item.sortKey,
});
}
function trackWithoutIndex(category, dbFile) {
var out = {};
for (var propName in DB_PROPS) {
var prop = DB_PROPS[propName];
if (!prop[category]) continue;
// save space by leaving out null and undefined values
var value = dbFile[propName];
if (value == null) continue;
if (prop.type === 'set') {
out[propName] = copySet(value);
} else {
out[propName] = value;
}
}
return out;
}
function serializeFileData(dbFile) {
return JSON.stringify(trackWithoutIndex('db', dbFile));
}
function serializeDirEntry(dirEntry) {
return JSON.stringify({
dirName: dirEntry.dirName,
entries: dirEntry.entries,
dirEntries: dirEntry.dirEntries,
mtime: dirEntry.mtime,
});
}
function filenameWithoutExt(filename) {
var ext = path.extname(filename);
return filename.substring(0, filename.length - ext.length);
}
function closeFile(file) {
file.close(function(err) {
if (err) {
log.error("Error closing", file, err.stack);
}
});
}
function parseTrackString(trackStr) {
if (!trackStr) return {};
var parts = trackStr.split('/');
if (parts.length > 1) {
return {
value: parseIntOrNull(parts[0]),
total: parseIntOrNull(parts[1]),
};
}
return {
value: parseIntOrNull(parts[0]),
};
}
function parseIntOrNull(n) {
n = parseInt(n, 10);
if (isNaN(n)) return null;
return n;
}
function parseFloatOrNull(n) {
n = parseFloat(n);
if (isNaN(n)) return null;
return n;
}
function grooveFileToDbFile(file, filenameHintWithoutPath, object) {
object = object || {key: uuid()};
var parsedTrack = parseTrackString(file.getMetadata("track"));
var parsedDisc = parseTrackString(
file.getMetadata("disc") ||
file.getMetadata("TPA") ||
file.getMetadata("TPOS"));
object.name = (file.getMetadata("title") || filenameWithoutExt(filenameHintWithoutPath) || "").trim();
object.artistName = (file.getMetadata("artist") || "").trim();
object.composerName = (file.getMetadata("composer") ||
file.getMetadata("TCM") || "").trim();
object.performerName = (file.getMetadata("performer") || "").trim();
object.albumArtistName = (file.getMetadata("album_artist") || "").trim();
object.albumName = (file.getMetadata("album") || "").trim();
object.compilation = !!(parseInt(file.getMetadata("TCP"), 10) ||
parseInt(file.getMetadata("TCMP"), 10) ||
file.getMetadata("COMPILATION") ||
file.getMetadata("Compilation") ||
file.getMetadata("cpil") ||
file.getMetadata("WM/IsCompilation"));
object.track = parsedTrack.value;
object.trackCount = parsedTrack.total;
object.disc = parsedDisc.value;
object.discCount = parsedDisc.total;
object.duration = file.duration();
object.year = parseIntOrNull(file.getMetadata("date"));
object.genre = file.getMetadata("genre");
object.replayGainTrackGain = parseFloatOrNull(file.getMetadata("REPLAYGAIN_TRACK_GAIN"));
object.replayGainTrackPeak = parseFloatOrNull(file.getMetadata("REPLAYGAIN_TRACK_PEAK"));
object.replayGainAlbumGain = parseFloatOrNull(file.getMetadata("REPLAYGAIN_ALBUM_GAIN"));
object.replayGainAlbumPeak = parseFloatOrNull(file.getMetadata("REPLAYGAIN_ALBUM_PEAK"));
object.labels = {};
return object;
}
function uniqueFilename(filename) {
// break into parts
var dirname = path.dirname(filename);
var basename = path.basename(filename);
var extname = path.extname(filename);
var withoutExt = basename.substring(0, basename.length - extname.length);
var match = withoutExt.match(/_(\d+)$/);
var withoutMatch;
var number;
if (match) {
number = parseInt(match[1], 10);
if (!number) number = 0;
withoutMatch = withoutExt.substring(0, match.index);
} else {
number = 0;
withoutMatch = withoutExt;
}
number += 1;
// put it back together
var newBasename = withoutMatch + "_" + number + extname;
return path.join(dirname, newBasename);
}
function dBToFloat(dB) {
return Math.exp(dB * DB_SCALE);
}
function ensureSep(dir) {
return (dir[dir.length - 1] === path.sep) ? dir : (dir + path.sep);
}
function ensureGrooveVersionIsOk() {
var ver = groove.getVersion();
var verStr = ver.major + '.' + ver.minor + '.' + ver.patch;
var reqVer = '>=4.1.1';
if (semver.satisfies(verStr, reqVer)) return;
log.fatal("Found libgroove", verStr, "need", reqVer);
process.exit(1);
}
function playlistItemKey(playlist, item) {
return PLAYLIST_KEY_PREFIX + playlist.id + '.' + item.id;
}
function playlistKey(playlist) {
return PLAYLIST_META_KEY_PREFIX + playlist.id;
}
function serializePlaylist(playlist) {
return JSON.stringify({
id: playlist.id,
name: playlist.name,
mtime: playlist.mtime,
});
}
function deserializePlaylist(str) {
var playlist = JSON.parse(str);
playlist.items = {};
return playlist;
}
function zfill(number, size) {
number = String(number);
while (number.length < size) number = "0" + number;
return number;
}
function setGrooveLoggingLevel() {
switch (log.level) {
case log.levels.Fatal:
case log.levels.Error:
case log.levels.Info:
case log.levels.Warn:
groove.setLogging(groove.LOG_QUIET);
break;
case log.levels.Debug:
groove.setLogging(groove.LOG_INFO);
break;
}
}
function importFileAsSong(self, srcFullPath, filenameHintWithoutPath, cb) {
groove.open(srcFullPath, function(err, file) {
if (err) return cb(err);
var newDbFile = grooveFileToDbFile(file, filenameHintWithoutPath);
var suggestedPath = self.getSuggestedPath(newDbFile, filenameHintWithoutPath);
var pend = new Pend();
pend.go(function(cb) {
log.debug("importFileAsSong close file:", file.filename);
file.close(cb);
});
pend.go(function(cb) {
tryMv(suggestedPath, cb);
});
pend.wait(function(err) {
if (err) return cb(err);
cb(null, [newDbFile]);
});
function tryMv(destRelPath, cb) {
var destFullPath = path.join(self.musicDirectory, destRelPath);
// before importFileAsSong is called, file system watching is disabled.
// So we can safely move files into the library without triggering an
// update db.
mv(srcFullPath, destFullPath, {mkdirp: true, clobber: false}, function(err) {
if (err) {
if (err.code === 'EEXIST') {
tryMv(uniqueFilename(destRelPath), cb);
} else {
cb(err);
}
return;
}
onAddOrChange(self, destRelPath, (new Date()).getTime(), function(err, dbFile) {
if (err) return cb(err);
newDbFile = dbFile;
cb();
});
});
}
});
}
function importFileAsZip(self, srcFullPath, filenameHintWithoutPath, cb) {
yauzl.open(srcFullPath, function(err, zipfile) {
if (err) return cb(err);
var allDbFiles = [];
var pend = new Pend();
zipfile.on('error', handleError);
zipfile.on('entry', onEntry);
zipfile.on('end', onEnd);
function onEntry(entry) {
if (/\/$/.test(entry.fileName)) {
// ignore directories
return;
}
pend.go(function(cb) {
zipfile.openReadStream(entry, function(err, readStream) {
if (err) {
log.warn("Error reading zip file:", err.stack);
cb();
return;
}
var entryBaseName = path.basename(entry.fileName);
self.importStream(readStream, entryBaseName, entry.uncompressedSize, function(err, dbFiles) {
if (err) {
log.warn("unable to import entry from zip file:", err.stack);
} else if (dbFiles) {
allDbFiles = allDbFiles.concat(dbFiles);
}
cb();
});
});
});
}
function onEnd() {
pend.wait(function() {
unlinkZipFile();
cb(null, allDbFiles);
});
}
function handleError(err) {
unlinkZipFile();
cb(err);
}
function unlinkZipFile() {
fs.unlink(srcFullPath, function(err) {
if (err) {
log.error("Unable to remove zip file after importing:", err.stack);
}
});
}
});
}
// sort keys according to how they appear in the library
function sortTracks(tracks) {
var lib = new MusicLibraryIndex();
tracks.forEach(function(track) {
lib.addTrack(track);
});
lib.rebuildTracks();
var results = [];
lib.artistList.forEach(function(artist) {
artist.albumList.forEach(function(album) {
album.trackList.forEach(function(track) {
results.push(track);
});
});
});
return results;
}
function logIfDbError(err) {
if (err) {
log.error("Unable to update DB:", err.stack);
}
}
function makeLower(str) {
return str.toLowerCase();
}
function copySet(set) {
var out = {};
for (var key in set) {
out[key] = 1;
}
return out;
}
|
# ASConfigCreator
[](https://travis-ci.org/Eernie/ASConfigCreator)
[](https://coveralls.io/github/Eernie/ASConfigCreator?branch=develop)
[](https://maven-badges.herokuapp.com/maven-central/nl.eernie.as/ASConfigCreator)
Sourcecontrol for you application server configuration.
## Builing the source
Its as easy as using maven:
```bash
mvn install
```
## Usage
There are two ways to use the application, directly or trough the maven plugin.
### Direct
For the direct approach you'll have to setup some configuration:
```java
Configuration configuration = new Configuration();
configuration.getContexts().addAll(Arrays.asList(contexts));
configuration.getApplicationServers().addAll(applicationServers);
configuration.setOutputDirectoryPath(outputDirectory);
ASConfigCreator asConfigCreator = new ASConfigCreator(configuration);
asConfigCreator.createConfigFiles(masterFile.getAbsolutePath());
```
### Maven plugin
For the maven plugin you can use the following snippet:
```xml
<plugin>
<groupId>nl.eernie.as</groupId>
<artifactId>ASConfigCreator-maven-plugin</artifactId>
<version>[latestVersion]</version>
<configuration>
<settingsFile>${basedir}/settings.properties</settingsFile>
</configuration>
</plugin>
```
|
from corecat.constants import OBJECT_CODES, MODEL_VERSION
from ._sqlalchemy import Base, CoreCatBaseMixin
from ._sqlalchemy import Column, \
Integer, \
String, Text
class Project(CoreCatBaseMixin, Base):
"""Project Model class represent for the 'projects' table
which is used to store project's basic information."""
# Add the real table name here.
# TODO: Add the database prefix here
__tablename__ = 'project'
# Column definition
project_id = Column('id', Integer,
primary_key=True,
autoincrement=True
)
project_name = Column('name', String(100),
nullable=False
)
project_description = Column('description', Text,
nullable=True
)
# Relationship
# TODO: Building relationship
def __init__(self, project_name,
created_by_user_id,
**kwargs):
"""
Constructor of Project Model Class.
:param project_name: Name of the project.
:param created_by_user_id: Project is created under this user ID.
:param project_description: Description of the project.
"""
self.set_up_basic_information(
MODEL_VERSION[OBJECT_CODES['Project']],
created_by_user_id
)
self.project_name = project_name
self.project_description = kwargs.get('project_description', None)
|
import React from 'react';
import { TypeChooser } from 'react-stockcharts/lib/helper'
import Chart from './Chart'
import { getData } from './util';
class ChartComponent extends React.Component {
componentDidMount () {
getData().then(data => {
this.setState({ data})
})
}
render () {
if (this.state == null) {
return <div>
Loading...
</div>
}
return (
<Chart type='hybrid' data={this.state.data} />
)
}
}
export default ChartComponent;
|
b'What is (-3 - -1) + (-4 - (10 + 14 + -15))?\n'
|
{% from "components/table.html" import list_table, field, right_aligned_field_heading, row_heading, notification_status_field %}
{% from "components/page-footer.html" import page_footer %}
<div class="ajax-block-container" aria-labelledby='pill-selected-item'>
<div class="dashboard-table bottom-gutter-3-2">
{% call(item, row_number) list_table(
[notification],
caption=None,
caption_visible=False,
empty_message=None,
field_headings=[
'Recipient',
'Status'
],
field_headings_visible=False
) %}
{% call row_heading() %}
<p class="govuk-body">{{ item.to }}</p>
{% endcall %}
{{ notification_status_field(item) }}
{% endcall %}
{% if more_than_one_page %}
<p class="table-show-more-link">
Only showing the first 50 rows
</p>
{% endif %}
</div>
</div>
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleCiphers.Models
{
public static class ArrayOperations
{
// Содержится ли text в encAbc. Если да, то возвращаются индексы в encAbc
// a b text = 1
// a 1 2 return x = 0, y = 0
// b 3 4 abc[0,0] = aa - расшифрованный
// encAbc[0,0] = 1 - зашифрованный
public static bool ContainsIn(string text, string[,] encAbc, out int x, out int y)
{
for (var i = 0; i < encAbc.GetLength(0); i++)
{
for (var j = 0; j < encAbc.GetLength(1); j++)
{
if (text != encAbc[i, j]) continue;
x = i;
y = j;
return true;
}
}
x = -1;
y = -1;
return false;
}
public static string[,] Turn1DTo2D(string[] encAbc)
{
var arr = new string[1, encAbc.Length];
for (var i = 0; i < encAbc.Length; i++)
{
arr[0, i] = $"{encAbc[i]}";
}
return arr;
}
}
}
|
b'Calculate 352 + -392 + (2 - -51).\n'
|
b'(9 + -9 - (6 + 0)) + (-36 - -36)\n'
|
b'What is (-4 - (16 - 47)) + (-15 - -1)?\n'
|
b'(-2 - (-8 - 3)) + -32 + 20\n'
|
b'What is 1 + 2 - (-23 + 39 - 16)?\n'
|
var PassThrough = require('stream').PassThrough
describe('Object Streams', function () {
it('should be supported', function (done) {
var app = koala()
app.use(function* (next) {
var body = this.body = new PassThrough({
objectMode: true
})
body.write({
message: 'a'
})
body.write({
message: 'b'
})
body.end()
})
request(app.listen())
.get('/')
.expect(200)
.expect([{
message: 'a'
}, {
message: 'b'
}], done)
})
})
|
b'Calculate 3 + (5 - -4) + 82 + -87.\n'
|
require 'optparse'
require 'pathname'
module EdifactConverter
class CommandLineParser
class << self
attr_writer :options
def options
@options ||= {}
end
def parser
@parser ||= begin
OptionParser.new do|opts|
opts.banner = "Usage: #{$COMMAND_NAME} [options] file"
opts.on( '-x', '--xml', 'Convert from Edifact to XML' ) do
options[:source] = :edifact
end
opts.on( '-e', '--edi', 'Convert from XML to Edifact' ) do
options[:source] = :xml
end
opts.on( '-1', '--xml11', 'Only convert to XML 1-1') do
options[:xml11] = true
end
opts.on( '-f', '--format', 'Format edifact output with newlines') do
options[:format] = true
end
opts.on( '--html', 'Only convert to XML 1-1') do
options[:html] = true
end
opts.on( '-l', '--logfile FILE', 'Write log to FILE' ) do |file|
options[:logfile] = file
end
opts.on( '-o', '--output FILE', 'Write output to FILE' ) do |file|
options[:to_file] = file
end
opts.on( '-v', '--version', "Prints version of #{$COMMAND_NAME}") do
puts "#{$COMMAND_NAME} version #{VERSION}"
exit
end
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end
end
end
def parse
parser.parse!
if ARGV.size != 1
puts "Wrong number of arguments, run #{$COMMAND_NAME} -h for a list of possible arguments."
exit
end
options[:input] = Pathname.new ARGV.first
unless options[:source]
if options[:input].extname =~ /xml/
options[:source] = :xml
else
options[:source] = :edifact
end
end
options
end
end
end
end
|
b'Evaluate -2 + 4 + 5 - (-21 + 31) - -19.\n'
|
{% extends "base.html" %}
{% block content %}
<div class="container">
<form action="" method="POST" enctype="multipart/form-data">
{{ form.hidden_tag() }}
<p>
Descriptive Name:
{{ form.descriptive_name(size = 50) }}
{% for error in form.descriptive_name.errors %}
<span style="color: red;">[{{error}}]</span>
{% endfor %}
</p>
<p>
Table Name:
{{ form.table_name(size = 30) }}
{% for error in form.table_name.errors %}
<span style="color: red;">[{{error}}]</span>
{% endfor %}
</p>
<p>
<input type="submit" value="Create Table"> | <input type="reset" value="Clear"> | <a href="{{ url_for('admin') }}">
<input type="button" value="Cancel" /></a>
</p>
</form>
</div>
{% endblock %}
|
b'Evaluate 0 - -4 - (1509 + -1496).\n'
|
/**
* Created by Keerthikan on 29-Apr-17.
*/
export {expenseSpyFactory} from './expense-spy-factory';
export {compensationSpyFactory} from './compensation-spy-factory';
|
b'Calculate 5 + -26 + 16 + 2 + 1.\n'
|
def add_age
puts "How old are you?"
age = gets.chomp
puts "In 10 years you will be:"
puts age.to_i + 10
puts "In 20 years you will be:"
puts age.to_i + 20
puts "In 30 years you will be:"
puts age.to_i + 30
puts "In 40 years you will be:"
puts age.to_i + 40
end
add_age
|
# MondrianRedisSegmentCache
Mondrian ships with an in memory segment cache that is great for standalone deployments of Mondrian, but doesn't
scale out with multiple nodes. An interface is provided for extending Mondrian with a shared Segment Cache and
examples of other implementations are in the links below.
In order to use Mondrian with Redis (our preferred caching layer) and Ruby (our preferred language -- Jruby) we had
to implement the SegmentCache interface from Mondrian and use the Redis notifications api.
Mondrian's segment cache needs to be able to get/set/remove cache items and also get any updates from the caching server
as other nodes are getting/setting/removing entries. This means that we need to use both the notifications and subscribe
api's from Redis.
http://stackoverflow.com/questions/17533594/implementing-a-mondrian-shared-segmentcache
http://mondrian.pentaho.com/api/mondrian/spi/SegmentCache.html
https://github.com/pentaho/mondrian/blob/master/src/main/mondrian/rolap/cache/MemorySegmentCache.java
https://github.com/webdetails/cdc
http://redis.io/topics/notifications
## Installation
Add this line to your application's Gemfile:
gem 'mondrian_redis_segment_cache'
And then execute:
$ bundle
Or install it yourself as:
$ gem install mondrian_redis_segment_cache
## Usage
If using Rails you can put the configuration in an initializer
```ruby
require 'redis'
require 'mondrian_redis_segment_cache'
# Setup a Redis connection
MONDRIAN_REDIS_CONNECTION = Redis.new(:url => "redis://localhost:1234/2")
MONDRIAN_SEGMENT_CACHE = ::MondrianRedisSegmentCache::Cache.new(MONDRIAN_REDIS_CONNECTION)
# Register the segment cache with the Mondrian Injector
::Java::MondrianSpi::SegmentCache::SegmentCacheInjector::add_cache(MONDRIAN_SEGMENT_CACHE)
```
In Redis we use the notifications api, so you must turn it on!
It is off by default because it is a new feature and can be CPU intensive. Redis does a ton, so there is a minimum of notifications
that must be turned on for this gem to work.
`notify-keyspace-events Egex$`
This tells Redis to publish keyevent events (which means we can subscribe to things like set/del) and to publish the generic commands
(like DEL, EXPIRE) and finally String commands (like SET)
The SegmentCache uses these notifications to keep Mondrian in sync across your Mondrian instances.
It also eager loads the current cached items into the listeners when they are added to the cache. This allows
an existing cache to be reused between deploys.
Cache expiry is handled by the options `:ttl` and `:expires_at`
If you want a static ttl (time to live) then each key that is inserted will be set to expire after the ttl completes. This is
not always optimal for an analytics cache and you may want all keys to expire at the same time (potentially on a daily basis).
If you want all keys to expire at the same time you should use `:expires_at` in the options hash. This should be the hour that
you want all keys to expire on. 1 being 1am, 2 being 2am, 15 being 3pm and so on.
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
|
export function wedgeYZ(a, b) {
return a.y * b.z - a.z * b.y;
}
export function wedgeZX(a, b) {
return a.z * b.x - a.x * b.z;
}
export function wedgeXY(a, b) {
return a.x * b.y - a.y * b.x;
}
|
/* Copyright information is at end of file */
#include "xmlrpc_config.h"
#include <stddef.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "stdargx.h"
#include "xmlrpc-c/base.h"
#include "xmlrpc-c/base_int.h"
#include "xmlrpc-c/string_int.h"
static void
getString(xmlrpc_env *const envP,
const char **const formatP,
va_listx *const argsP,
xmlrpc_value **const valPP) {
const char *str;
size_t len;
str = (const char *) va_arg(argsP->v, char*);
if (*(*formatP) == '#') {
++(*formatP);
len = (size_t) va_arg(argsP->v, size_t);
} else
len = strlen(str);
*valPP = xmlrpc_string_new_lp(envP, len, str);
}
static void
getWideString(xmlrpc_env *const envP ATTR_UNUSED,
const char **const formatP ATTR_UNUSED,
va_listx *const argsP ATTR_UNUSED,
xmlrpc_value **const valPP ATTR_UNUSED) {
#if HAVE_UNICODE_WCHAR
wchar_t *wcs;
size_t len;
wcs = (wchar_t*) va_arg(argsP->v, wchar_t*);
if (**formatP == '#') {
(*formatP)++;
len = (size_t) va_arg(argsP->v, size_t);
} else
len = wcslen(wcs);
*valPP = xmlrpc_string_w_new_lp(envP, len, wcs);
#endif /* HAVE_UNICODE_WCHAR */
}
static void
getBase64(xmlrpc_env *const envP,
va_listx *const argsP,
xmlrpc_value **const valPP) {
unsigned char *value;
size_t length;
value = (unsigned char *) va_arg(argsP->v, unsigned char*);
length = (size_t) va_arg(argsP->v, size_t);
*valPP = xmlrpc_base64_new(envP, length, value);
}
static void
getValue(xmlrpc_env *const envP,
const char **const format,
va_listx *const argsP,
xmlrpc_value **const valPP);
static void
getArray(xmlrpc_env *const envP,
const char **const formatP,
char const delimiter,
va_listx *const argsP,
xmlrpc_value **const arrayPP) {
xmlrpc_value *arrayP;
arrayP = xmlrpc_array_new(envP);
/* Add items to the array until we hit our delimiter. */
while (**formatP != delimiter && !envP->fault_occurred) {
xmlrpc_value *itemP;
if (**formatP == '\0')
xmlrpc_env_set_fault(
envP, XMLRPC_INTERNAL_ERROR,
"format string ended before closing ')'.");
else {
getValue(envP, formatP, argsP, &itemP);
if (!envP->fault_occurred) {
xmlrpc_array_append_item(envP, arrayP, itemP);
xmlrpc_DECREF(itemP);
}
}
}
if (envP->fault_occurred)
xmlrpc_DECREF(arrayP);
*arrayPP = arrayP;
}
static void
getStructMember(xmlrpc_env *const envP,
const char **const formatP,
va_listx *const argsP,
xmlrpc_value **const keyPP,
xmlrpc_value **const valuePP) {
/* Get the key */
getValue(envP, formatP, argsP, keyPP);
if (!envP->fault_occurred) {
if (**formatP != ':')
xmlrpc_env_set_fault(
envP, XMLRPC_INTERNAL_ERROR,
"format string does not have ':' after a "
"structure member key.");
else {
/* Skip over colon that separates key from value */
(*formatP)++;
/* Get the value */
getValue(envP, formatP, argsP, valuePP);
}
if (envP->fault_occurred)
xmlrpc_DECREF(*keyPP);
}
}
static void
getStruct(xmlrpc_env *const envP,
const char **const formatP,
char const delimiter,
va_listx *const argsP,
xmlrpc_value **const structPP) {
xmlrpc_value *structP;
structP = xmlrpc_struct_new(envP);
if (!envP->fault_occurred) {
while (**formatP != delimiter && !envP->fault_occurred) {
xmlrpc_value *keyP;
xmlrpc_value *valueP;
getStructMember(envP, formatP, argsP, &keyP, &valueP);
if (!envP->fault_occurred) {
if (**formatP == ',')
(*formatP)++; /* Skip over the comma */
else if (**formatP == delimiter) {
/* End of the line */
} else
xmlrpc_env_set_fault(
envP, XMLRPC_INTERNAL_ERROR,
"format string does not have ',' or ')' after "
"a structure member");
if (!envP->fault_occurred)
/* Add the new member to the struct. */
xmlrpc_struct_set_value_v(envP, structP, keyP, valueP);
xmlrpc_DECREF(valueP);
xmlrpc_DECREF(keyP);
}
}
if (envP->fault_occurred)
xmlrpc_DECREF(structP);
}
*structPP = structP;
}
static void
mkArrayFromVal(xmlrpc_env *const envP,
xmlrpc_value *const value,
xmlrpc_value **const valPP) {
if (xmlrpc_value_type(value) != XMLRPC_TYPE_ARRAY)
xmlrpc_env_set_fault(envP, XMLRPC_INTERNAL_ERROR,
"Array format ('A'), non-array xmlrpc_value");
else
xmlrpc_INCREF(value);
*valPP = value;
}
static void
mkStructFromVal(xmlrpc_env *const envP,
xmlrpc_value *const value,
xmlrpc_value **const valPP) {
if (xmlrpc_value_type(value) != XMLRPC_TYPE_STRUCT)
xmlrpc_env_set_fault(envP, XMLRPC_INTERNAL_ERROR,
"Struct format ('S'), non-struct xmlrpc_value");
else
xmlrpc_INCREF(value);
*valPP = value;
}
static void
getValue(xmlrpc_env *const envP,
const char **const formatP,
va_listx *const argsP,
xmlrpc_value **const valPP) {
/*----------------------------------------------------------------------------
Get the next value from the list. *formatP points to the specifier
for the next value in the format string (i.e. to the type code
character) and we move *formatP past the whole specifier for the
next value. We read the required arguments from 'argsP'. We return
the value as *valPP with a reference to it.
For example, if *formatP points to the "i" in the string "sis",
we read one argument from 'argsP' and return as *valP an integer whose
value is the argument we read. We advance *formatP to point to the
last 's' and advance 'argsP' to point to the argument that belongs to
that 's'.
-----------------------------------------------------------------------------*/
char const formatChar = *(*formatP)++;
switch (formatChar) {
case 'i':
*valPP =
xmlrpc_int_new(envP, (xmlrpc_int32) va_arg(argsP->v,
xmlrpc_int32));
break;
case 'b':
*valPP =
xmlrpc_bool_new(envP, (xmlrpc_bool) va_arg(argsP->v,
xmlrpc_bool));
break;
case 'd':
*valPP =
xmlrpc_double_new(envP, (double) va_arg(argsP->v, double));
break;
case 's':
getString(envP, formatP, argsP, valPP);
break;
case 'w':
getWideString(envP, formatP, argsP, valPP);
break;
case 't':
*valPP = xmlrpc_datetime_new_sec(envP, va_arg(argsP->v, time_t));
break;
case '8':
*valPP = xmlrpc_datetime_new_str(envP, va_arg(argsP->v, char*));
break;
case '6':
getBase64(envP, argsP, valPP);
break;
case 'n':
*valPP =
xmlrpc_nil_new(envP);
break;
case 'I':
*valPP =
xmlrpc_i8_new(envP, (xmlrpc_int64) va_arg(argsP->v,
xmlrpc_int64));
break;
case 'p':
*valPP =
xmlrpc_cptr_new(envP, (void *) va_arg(argsP->v, void*));
break;
case 'A':
mkArrayFromVal(envP,
(xmlrpc_value *) va_arg(argsP->v, xmlrpc_value*),
valPP);
break;
case 'S':
mkStructFromVal(envP,
(xmlrpc_value *) va_arg(argsP->v, xmlrpc_value*),
valPP);
break;
case 'V':
*valPP = (xmlrpc_value *) va_arg(argsP->v, xmlrpc_value*);
xmlrpc_INCREF(*valPP);
break;
case '(':
getArray(envP, formatP, ')', argsP, valPP);
if (!envP->fault_occurred) {
XMLRPC_ASSERT(**formatP == ')');
(*formatP)++; /* Skip over closing parenthesis */
}
break;
case '{':
getStruct(envP, formatP, '}', argsP, valPP);
if (!envP->fault_occurred) {
XMLRPC_ASSERT(**formatP == '}');
(*formatP)++; /* Skip over closing brace */
}
break;
default: {
const char *const badCharacter = xmlrpc_makePrintableChar(
formatChar);
xmlrpc_env_set_fault_formatted(
envP, XMLRPC_INTERNAL_ERROR,
"Unexpected character '%s' in format string", badCharacter);
xmlrpc_strfree(badCharacter);
}
}
}
void
xmlrpc_build_value_va(xmlrpc_env *const envP,
const char *const format,
va_list const args,
xmlrpc_value **const valPP,
const char **const tailP) {
XMLRPC_ASSERT_ENV_OK(envP);
XMLRPC_ASSERT(format != NULL);
if (strlen(format) == 0)
xmlrpc_faultf(envP, "Format string is empty.");
else {
va_listx currentArgs;
const char *formatCursor;
init_va_listx(¤tArgs, args);
formatCursor = &format[0];
getValue(envP, &formatCursor, ¤tArgs, valPP);
if (!envP->fault_occurred)
XMLRPC_ASSERT_VALUE_OK(*valPP);
*tailP = formatCursor;
}
}
xmlrpc_value *
xmlrpc_build_value(xmlrpc_env *const envP,
const char *const format,
...) {
va_list args;
xmlrpc_value *retval;
const char *suffix;
va_start(args, format);
xmlrpc_build_value_va(envP, format, args, &retval, &suffix);
va_end(args);
if (!envP->fault_occurred) {
if (*suffix != '\0')
xmlrpc_faultf(envP, "Junk after the format specifier: '%s'. "
"The format string must describe exactly "
"one XML-RPC value "
"(but it might be a compound value "
"such as an array)",
suffix);
if (envP->fault_occurred)
xmlrpc_DECREF(retval);
}
return retval;
}
/* Copyright (C) 2001 by First Peer, Inc. All rights reserved.
** Copyright (C) 2001 by Eric Kidd. All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
** SUCH DAMAGE. */
|
b'What is -3 + (-3 - (2 - (-5 + 1 + 8)))?\n'
|
module TweetStream
class Terminated < ::StandardError; end
class Error < ::StandardError; end
class ConnectionError < TweetStream::Error; end
# A ReconnectError is raised when the maximum number of retries has
# failed to re-establish a connection.
class ReconnectError < StandardError
attr_accessor :timeout, :retries
def initialize(timeout, retries)
self.timeout = timeout
self.retries = retries
super("Failed to reconnect after #{retries} tries.")
end
end
end
|
class CreateLists < ActiveRecord::Migration[5.1]
def change
create_table :lists do |t|
t.string :letter
t.string :tax_reference
t.string :list_type
t.date :date_list
t.timestamps
end
end
end
|
package org.anodyneos.xp.tag.core;
import javax.servlet.jsp.el.ELException;
import org.anodyneos.xp.XpException;
import org.anodyneos.xp.XpOutput;
import org.anodyneos.xp.tagext.XpTagSupport;
import org.xml.sax.SAXException;
/**
* @author jvas
*/
public class DebugTag extends XpTagSupport {
public DebugTag() {
super();
}
/* (non-Javadoc)
* @see org.anodyneos.xp.tagext.XpTag#doTag(org.anodyneos.xp.XpContentHandler)
*/
public void doTag(XpOutput out) throws XpException, ELException, SAXException {
XpOutput newOut = new XpOutput(new DebugCH(System.err, out.getXpContentHandler()));
getXpBody().invoke(newOut);
}
}
|
b'-3 + 11 - 2 - (6 - -1 - -3)\n'
|
b'What is -5 - -1 - (-95 - -110)?\n'
|
b'What is 22 + 7 + 13 + -29 - 16?\n'
|
b'Evaluate -20 + 3 + 23 + -14 + -15.\n'
|
/*!
* jQuery JavaScript Library v1.8.3 -css,-effects,-offset,-dimensions
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: Mon Nov 19 2012 11:58:00 GMT-0800 (PST)
*/
(function( window, undefined ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
navigator = window.navigator,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Save a reference to some core methods
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// scripts is true for back-compat
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
return jQuery.merge( this, selector );
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// 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: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( 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.8.3 -css,-effects,-offset,-dimensions",
// 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 core_slice.call( this );
},
// 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[ this.length + num ] : 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.merge( this.constructor(), 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 ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
eq: function( i ) {
i = +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( core_slice.apply( this, arguments ),
"slice", core_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 || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_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() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// 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 plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// 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 ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// 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 jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
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 || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
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 || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; 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 retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key,
ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else 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 {
// 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 top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
function() {
var returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
eventName,
i,
isSupported,
clickFn,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
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 instead)
style: /top/.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.5/.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: ( input.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: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: ( document.compatMode === "CSS1Compat" ),
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", clickFn = function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent("onclick");
div.detachEvent( "onclick", clickFn );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
input.setAttribute( "checked", "checked" );
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Run tests that need a body at doc ready
jQuery(function() {
var container, div, tds, marginDiv,
divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild( marginDiv );
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
container.style.zoom = 1;
}
// Null elements to avoid leaks in IE
body.removeChild( container );
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
fragment.removeChild( div );
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
// Remove at next major release (1.9/2.0)
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery.removeData( elem, type + "queue", true );
jQuery.removeData( elem, key, true );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
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( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook, fixSpecified,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea|)$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var removes, className, elem, c, cl, i, l;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
removes = ( value || "" ).split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
className = (" " + elem.className + " ").replace( rclass, " " );
// loop over each item in the removal list
for ( c = 0, cl = removes.length; c < cl; c++ ) {
// Remove until there is nothing to remove,
while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {
className = className.replace( " " + removes[ c ] + " " , " " );
}
}
elem.className = value ? jQuery.trim( className ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, 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( core_rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated 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 + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific 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;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
attrFn: {},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.split( core_rspace );
for ( ; i < attrNames.length; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// 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/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.value = value + "" );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// 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 to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
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, selector, mappedTypes ) {
var t, tns, type, origType, namespaces, origCount,
j, events, special, eventType, handleObj,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, "events", true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
type = event.type || event,
namespaces = [];
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
for ( old = elem; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old === (elem.ownerDocument || document) ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = core_slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
event.metaKey = !!event.metaKey;
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.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)
} else {
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
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "_submit_attached" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "_submit_attached", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "_change_attached", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = 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;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
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 contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var cachedruns,
dirruns,
sortOrder,
siblingCheck,
assertGetIdNotName,
document = window.document,
docElem = document.documentElement,
strundefined = "undefined",
hasDuplicate = false,
baseHasDuplicate = true,
done = 0,
slice = [].slice,
push = [].push,
expando = ( "sizcache" + Math.random() ).replace( ".", "" ),
// Regex
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)",
pos = ":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)",
combinators = whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*",
groups = "(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|" + attributes + "|" + pseudos.replace( 2, 7 ) + "|[^\\\\(),])+",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcombinators = new RegExp( "^" + combinators ),
// All simple (non-comma) selectors, excluding insignifant trailing whitespace
rgroups = new RegExp( groups + "?(?=" + whitespace + "*,|$)", "g" ),
// A selector, or everything after leading whitespace
// Optionally followed in either case by a ")" for terminating sub-selectors
rselector = new RegExp( "^(?:(?!,)(?:(?:^|,)" + whitespace + "*" + groups + ")*?|" + whitespace + "*(.*?))(\\)|$)" ),
// All combinators and selector components (attribute test, tag, pseudo, etc.), the latter appearing together when consecutive
rtokens = new RegExp( groups.slice( 19, -6 ) + "\\x20\\t\\r\\n\\f>+~])+|" + combinators, "g" ),
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
rsibling = /[\x20\t\r\n\f]*[+~]/,
rendsWithNot = /:not\($/,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rbackslash = /\\(?!\\)/g,
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "[-", "[-\\*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|nth|last|first)-child(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"POS": new RegExp( pos, "ig" ),
// For use in libraries implementing .is()
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" )
},
classCache = {},
cachedClasses = [],
compilerCache = {},
cachedSelectors = [],
// Mark a function for use in filtering
markFunction = function( fn ) {
fn.sizzleFilter = true;
return fn;
},
// Returns a function to use in pseudos for input types
createInputFunction = function( type ) {
return function( elem ) {
// Check the input's nodeName and type
return elem.nodeName.toLowerCase() === "input" && elem.type === type;
};
},
// Returns a function to use in pseudos for buttons
createButtonFunction = function( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
},
// Used for testing something on an element
assert = function( fn ) {
var pass = false,
div = document.createElement("div");
try {
pass = fn( div );
} catch (e) {}
// release memory in IE
div = null;
return pass;
},
// Check if attributes should be retrieved by attribute nodes
assertAttributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
}),
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
assertUsableName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = document.getElementsByName &&
// buggy browsers will return fewer than the correct 2
document.getElementsByName( expando ).length ===
// buggy browsers will return more than the correct 0
2 + document.getElementsByName( expando + 0 ).length;
assertGetIdNotName = !document.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
}),
// Check if the browser returns only elements
// when doing getElementsByTagName("*")
assertTagNameNoComments = assert(function( div ) {
div.appendChild( document.createComment("") );
return div.getElementsByTagName("*").length === 0;
}),
// Check if getAttribute returns normalized href attributes
assertHrefNotNormalized = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}),
// Check if getElementsByClassName can be trusted
assertUsableClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return false;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
return div.getElementsByClassName("e").length !== 1;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var match, elem, xml, m,
nodeType = context.nodeType;
if ( nodeType !== 1 && nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
xml = isXML( context );
if ( !xml && !seed ) {
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
}
// All others
return select( selector, context, results, seed, xml );
};
var Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
match: matchExpr,
order: [ "ID", "TAG" ],
attrHandle: {},
createPseudo: markFunction,
find: {
"ID": assertGetIdNotName ?
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
} :
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
},
"TAG": assertTagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
var elem,
tmp = [],
i = 0;
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
}
},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( rbackslash, "" );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr.CHILD
1 type (only|nth|...)
2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
3 xn-component of xn+y argument ([+-]?\d*n|)
4 sign of xn-component
5 x of xn-component
6 sign of y-component
7 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1] === "nth" ) {
// nth-child requires argument
if ( !match[2] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );
match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );
// other types prohibit arguments
} else if ( match[2] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var argument,
unquoted = match[4];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Relinquish our claim on characters in `unquoted` from a closing parenthesis on
if ( unquoted && (argument = rselector.exec( unquoted )) && argument.pop() ) {
match[0] = match[0].slice( 0, argument[0].length - unquoted.length - 1 );
unquoted = argument[0].slice( 0, -1 );
}
// Quoted or unquoted, we have the full argument
// Return only captures needed by the pseudo filter method (type and argument)
match.splice( 2, 3, unquoted || match[3] );
return match;
}
},
filter: {
"ID": assertGetIdNotName ?
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
return elem.getAttribute("id") === id;
};
} :
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === id;
};
},
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className ];
if ( !pattern ) {
pattern = classCache[ className ] = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" );
cachedClasses.push( className );
// Avoid too large of a cache
if ( cachedClasses.length > Expr.cacheLength ) {
delete classCache[ cachedClasses.shift() ];
}
}
return function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
};
},
"ATTR": function( name, operator, check ) {
if ( !operator ) {
return function( elem ) {
return Sizzle.attr( elem, name ) != null;
};
}
return function( elem ) {
var result = Sizzle.attr( elem, name ),
value = result + "";
if ( result == null ) {
return operator === "!=";
}
switch ( operator ) {
case "=":
return value === check;
case "!=":
return value !== check;
case "^=":
return check && value.indexOf( check ) === 0;
case "*=":
return check && value.indexOf( check ) > -1;
case "$=":
return check && value.substr( value.length - check.length ) === check;
case "~=":
return ( " " + value + " " ).indexOf( check ) > -1;
case "|=":
return value === check || value.substr( 0, check.length + 1 ) === check + "-";
}
};
},
"CHILD": function( type, argument, first, last ) {
if ( type === "nth" ) {
var doneName = done++;
return function( elem ) {
var parent, diff,
count = 0,
node = elem;
if ( first === 1 && last === 0 ) {
return true;
}
parent = elem.parentNode;
if ( parent && (parent[ expando ] !== doneName || !elem.sizset) ) {
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.sizset = ++count;
if ( node === elem ) {
break;
}
}
}
parent[ expando ] = doneName;
}
diff = elem.sizset - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
};
}
return function( elem ) {
var 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;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
}
};
},
"PSEUDO": function( pseudo, argument, context, xml ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
var fn = Expr.pseudos[ pseudo ] || Expr.pseudos[ pseudo.toLowerCase() ];
if ( !fn ) {
Sizzle.error( "unsupported pseudo: " + pseudo );
}
// The user may set fn.sizzleFilter to indicate
// that arguments are needed to create the filter function
// just as Sizzle does
if ( !fn.sizzleFilter ) {
return fn;
}
return fn( argument, context, xml );
}
},
pseudos: {
"not": markFunction(function( selector, context, xml ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var matcher = compile( selector.replace( rtrim, "$1" ), context, xml );
return function( elem ) {
return !matcher( elem );
};
}),
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
var nodeType;
elem = elem.firstChild;
while ( elem ) {
if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {
return false;
}
elem = elem.nextSibling;
}
return true;
},
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"text": function( elem ) {
var type, attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
(type = elem.type) === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );
},
// Input types
"radio": createInputFunction("radio"),
"checkbox": createInputFunction("checkbox"),
"file": createInputFunction("file"),
"password": createInputFunction("password"),
"image": createInputFunction("image"),
"submit": createButtonFunction("submit"),
"reset": createButtonFunction("reset"),
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"focus": function( elem ) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href);
},
"active": function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
"first": function( elements, argument, not ) {
return not ? elements.slice( 1 ) : [ elements[0] ];
},
"last": function( elements, argument, not ) {
var elem = elements.pop();
return not ? elements : [ elem ];
},
"even": function( elements, argument, not ) {
var results = [],
i = not ? 1 : 0,
len = elements.length;
for ( ; i < len; i = i + 2 ) {
results.push( elements[i] );
}
return results;
},
"odd": function( elements, argument, not ) {
var results = [],
i = not ? 0 : 1,
len = elements.length;
for ( ; i < len; i = i + 2 ) {
results.push( elements[i] );
}
return results;
},
"lt": function( elements, argument, not ) {
return not ? elements.slice( +argument ) : elements.slice( 0, +argument );
},
"gt": function( elements, argument, not ) {
return not ? elements.slice( 0, +argument + 1 ) : elements.slice( +argument + 1 );
},
"eq": function( elements, argument, not ) {
var elem = elements.splice( +argument, 1 );
return not ? elements : elem;
}
}
};
// Deprecated
Expr.setFilters["nth"] = Expr.setFilters["eq"];
// Back-compat
Expr.filters = Expr.pseudos;
// IE6/7 return a modified href
if ( !assertHrefNotNormalized ) {
Expr.attrHandle = {
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
};
}
// Add getElementsByName if usable
if ( assertUsableName ) {
Expr.order.push("NAME");
Expr.find["NAME"] = function( name, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
};
}
// Add getElementsByClassName if usable
if ( assertUsableClassName ) {
Expr.order.splice( 1, 0, "CLASS" );
Expr.find["CLASS"] = function( className, context, xml ) {
if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
return context.getElementsByClassName( className );
}
};
}
// If slice is not available, provide a backup
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem, results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
var isXML = Sizzle.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).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Element contains another
var contains = Sizzle.contains = docElem.compareDocumentPosition ?
function( a, b ) {
return !!( a.compareDocumentPosition( b ) & 16 );
} :
docElem.contains ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );
} :
function( a, b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
return false;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
var getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
} else {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
}
return ret;
};
Sizzle.attr = function( elem, name ) {
var attr,
xml = isXML( elem );
if ( !xml ) {
name = name.toLowerCase();
}
if ( Expr.attrHandle[ name ] ) {
return Expr.attrHandle[ name ]( elem );
}
if ( assertAttributes || xml ) {
return elem.getAttribute( name );
}
attr = elem.getAttributeNode( name );
return attr ?
typeof elem[ name ] === "boolean" ?
elem[ name ] ? name : null :
attr.specified ? attr.value : null :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
// 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() {
return (baseHasDuplicate = 0);
});
if ( docElem.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return ( !a.compareDocumentPosition || !b.compareDocumentPosition ?
a.compareDocumentPosition :
a.compareDocumentPosition(b) & 4
) ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
i = 1;
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
function multipleContexts( selector, contexts, results, seed ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results, seed );
}
}
function handlePOSGroup( selector, posfilter, argument, contexts, seed, not ) {
var results,
fn = Expr.setFilters[ posfilter.toLowerCase() ];
if ( !fn ) {
Sizzle.error( posfilter );
}
if ( selector || !(results = seed) ) {
multipleContexts( selector || "*", contexts, (results = []), seed );
}
return results.length > 0 ? fn( results, argument, not ) : [];
}
function handlePOS( selector, context, results, seed, groups ) {
var match, not, anchor, ret, elements, currentContexts, part, lastIndex,
i = 0,
len = groups.length,
rpos = matchExpr["POS"],
// This is generated here in case matchExpr["POS"] is extended
rposgroups = new RegExp( "^" + rpos.source + "(?!" + whitespace + ")", "i" ),
// This is for making sure non-participating
// matching groups are represented cross-browser (IE6-8)
setUndefined = function() {
var i = 1,
len = arguments.length - 2;
for ( ; i < len; i++ ) {
if ( arguments[i] === undefined ) {
match[i] = undefined;
}
}
};
for ( ; i < len; i++ ) {
// Reset regex index to 0
rpos.exec("");
selector = groups[i];
ret = [];
anchor = 0;
elements = seed;
while ( (match = rpos.exec( selector )) ) {
lastIndex = rpos.lastIndex = match.index + match[0].length;
if ( lastIndex > anchor ) {
part = selector.slice( anchor, match.index );
anchor = lastIndex;
currentContexts = [ context ];
if ( rcombinators.test(part) ) {
if ( elements ) {
currentContexts = elements;
}
elements = seed;
}
if ( (not = rendsWithNot.test( part )) ) {
part = part.slice( 0, -5 ).replace( rcombinators, "$&*" );
}
if ( match.length > 1 ) {
match[0].replace( rposgroups, setUndefined );
}
elements = handlePOSGroup( part, match[1], match[2], currentContexts, elements, not );
}
}
if ( elements ) {
ret = ret.concat( elements );
if ( (part = selector.slice( anchor )) && part !== ")" ) {
if ( rcombinators.test(part) ) {
multipleContexts( part, ret, results, seed );
} else {
Sizzle( part, context, results, seed ? seed.concat(elements) : elements );
}
} else {
push.apply( results, ret );
}
} else {
Sizzle( selector, context, results, seed );
}
}
// Do not sort if this is a single filter
return len === 1 ? results : Sizzle.uniqueSort( results );
}
function tokenize( selector, context, xml ) {
var tokens, soFar, type,
groups = [],
i = 0,
// Catch obvious selector issues: terminal ")"; nonempty fallback match
// rselector never fails to match *something*
match = rselector.exec( selector ),
matched = !match.pop() && !match.pop(),
selectorGroups = matched && selector.match( rgroups ) || [""],
preFilters = Expr.preFilter,
filters = Expr.filter,
checkContext = !xml && context !== document;
for ( ; (soFar = selectorGroups[i]) != null && matched; i++ ) {
groups.push( tokens = [] );
// Need to make sure we're within a narrower context if necessary
// Adding a descendant combinator will generate what is needed
if ( checkContext ) {
soFar = " " + soFar;
}
while ( soFar ) {
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
soFar = soFar.slice( match[0].length );
// Cast descendant combinators to space
matched = tokens.push({ part: match.pop().replace( rtrim, " " ), captures: match });
}
// Filters
for ( type in filters ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match, context, xml )) ) ) {
soFar = soFar.slice( match.shift().length );
matched = tokens.push({ part: type, captures: match });
}
}
if ( !matched ) {
break;
}
}
}
if ( !matched ) {
Sizzle.error( selector );
}
return groups;
}
function addCombinator( matcher, combinator, context ) {
var dir = combinator.dir,
doneName = done++;
if ( !matcher ) {
// If there is no matcher to check, check against the context
matcher = function( elem ) {
return elem === context;
};
}
return combinator.first ?
function( elem, context ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 ) {
return matcher( elem, context ) && elem;
}
}
} :
function( elem, context ) {
var cache,
dirkey = doneName + "." + dirruns,
cachedkey = dirkey + "." + cachedruns;
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 ) {
if ( (cache = elem[ expando ]) === cachedkey ) {
return elem.sizset;
} else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {
if ( elem.sizset ) {
return elem;
}
} else {
elem[ expando ] = cachedkey;
if ( matcher( elem, context ) ) {
elem.sizset = true;
return elem;
}
elem.sizset = false;
}
}
}
};
}
function addMatcher( higher, deeper ) {
return higher ?
function( elem, context ) {
var result = deeper( elem, context );
return result && higher( result === true ? elem : result, context );
} :
deeper;
}
// ["TAG", ">", "ID", " ", "CLASS"]
function matcherFromTokens( tokens, context, xml ) {
var token, matcher,
i = 0;
for ( ; (token = tokens[i]); i++ ) {
if ( Expr.relative[ token.part ] ) {
matcher = addCombinator( matcher, Expr.relative[ token.part ], context );
} else {
token.captures.push( context, xml );
matcher = addMatcher( matcher, Expr.filter[ token.part ].apply( null, token.captures ) );
}
}
return matcher;
}
function matcherFromGroupMatchers( matchers ) {
return function( elem, context ) {
var matcher,
j = 0;
for ( ; (matcher = matchers[j]); j++ ) {
if ( matcher(elem, context) ) {
return true;
}
}
return false;
};
}
var compile = Sizzle.compile = function( selector, context, xml ) {
var tokens, group, i,
cached = compilerCache[ selector ];
// Return a cached group function if already generated (context dependent)
if ( cached && cached.context === context ) {
return cached;
}
// Generate a function of recursive functions that can be used to check each element
group = tokenize( selector, context, xml );
for ( i = 0; (tokens = group[i]); i++ ) {
group[i] = matcherFromTokens( tokens, context, xml );
}
// Cache the compiled function
cached = compilerCache[ selector ] = matcherFromGroupMatchers( group );
cached.context = context;
cached.runs = cached.dirruns = 0;
cachedSelectors.push( selector );
// Ensure only the most recent are cached
if ( cachedSelectors.length > Expr.cacheLength ) {
delete compilerCache[ cachedSelectors.shift() ];
}
return cached;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
var select = function( selector, context, results, seed, xml ) {
// Remove excessive whitespace
selector = selector.replace( rtrim, "$1" );
var elements, matcher, i, len, elem, token,
type, findContext, notTokens,
match = selector.match( rgroups ),
tokens = selector.match( rtokens ),
contextNodeType = context.nodeType;
// POS handling
if ( matchExpr["POS"].test(selector) ) {
return handlePOS( selector, context, results, seed, match );
}
if ( seed ) {
elements = slice.call( seed, 0 );
// To maintain document order, only narrow the
// set if there is one group
} else if ( match && match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
if ( tokens.length > 1 && contextNodeType === 9 && !xml &&
(match = matchExpr["ID"].exec( tokens[0] )) ) {
context = Expr.find["ID"]( match[1], context, xml )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().length );
}
findContext = ( (match = rsibling.exec( tokens[0] )) && !match.index && context.parentNode ) || context;
// Get the last token, excluding :not
notTokens = tokens.pop();
token = notTokens.split(":not")[0];
for ( i = 0, len = Expr.order.length; i < len; i++ ) {
type = Expr.order[i];
if ( (match = matchExpr[ type ].exec( token )) ) {
elements = Expr.find[ type ]( (match[1] || "").replace( rbackslash, "" ), findContext, xml );
if ( elements == null ) {
continue;
}
if ( token === notTokens ) {
selector = selector.slice( 0, selector.length - notTokens.length ) +
token.replace( matchExpr[ type ], "" );
if ( !selector ) {
push.apply( results, slice.call(elements, 0) );
}
}
break;
}
}
}
// Only loop over the given elements once
// If selector is empty, we're already done
if ( selector ) {
matcher = compile( selector, context, xml );
dirruns = matcher.dirruns++;
if ( elements == null ) {
elements = Expr.find["TAG"]( "*", (rsibling.test( selector ) && context.parentNode) || context );
}
for ( i = 0; (elem = elements[i]); i++ ) {
cachedruns = matcher.runs++;
if ( matcher(elem, context) ) {
results.push( elem );
}
}
}
return results;
};
if ( document.querySelectorAll ) {
(function() {
var disconnectedMatch,
oldSelect = select,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
rbuggyQSA = [],
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
// A support test would require too much code (would include document ready)
// just skip matchesSelector for :active
rbuggyMatches = [":active"],
matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector;
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
div.innerHTML = "<select><option selected></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here (do not put tests after this one)
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE9 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<p test=''></p>";
if ( div.querySelectorAll("[test^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here (do not put tests after this one)
div.innerHTML = "<input type='hidden'>";
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push(":enabled", ":disabled");
}
});
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
select = function( selector, context, results, seed, xml ) {
// Only use querySelectorAll when not filtering,
// when this is not xml,
// and when no QSA bugs apply
if ( !seed && !xml && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
if ( context.nodeType === 9 ) {
try {
push.apply( results, slice.call(context.querySelectorAll( selector ), 0) );
return results;
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var old = context.getAttribute("id"),
nid = old || expando,
newContext = rsibling.test( selector ) && context.parentNode || context;
if ( old ) {
nid = nid.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
try {
push.apply( results, slice.call( newContext.querySelectorAll(
selector.replace( rgroups, "[id='" + nid + "'] $&" )
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
return oldSelect( selector, context, results, seed, xml );
};
if ( matches ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
try {
matches.call( div, "[test!='']:sizzle" );
rbuggyMatches.push( Expr.match.PSEUDO );
} catch ( e ) {}
});
// rbuggyMatches always contains :active, so no need for a length check
rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );
Sizzle.matchesSelector = function( elem, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyMatches always contains :active, so no need for an existence check
if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && (!rbuggyQSA || !rbuggyQSA.test( expr )) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
}
})();
}
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, l, length, n, r, ret,
self = this;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
ret = this.pushStack( "", "find", selector );
for ( 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 ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; 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 && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// 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 ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
// 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;
}
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
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 sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "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.merge( [], 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 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
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;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === 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;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
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, "", "" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "X<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
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 ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : 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.nodeType === 11 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
}
},
after: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (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() {
var elem,
i = 0;
for ( ; (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( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( !isDisconnected( this[0] ) ) {
// 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 );
}
});
}
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = [].concat.apply( [], args );
var results, first, fragment, iNoClone,
i = 0,
value = args[0],
scripts = [],
l = this.length;
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback );
});
}
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] ) {
results = jQuery.buildFragment( args, this, scripts );
fragment = results.fragment;
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
// Fragments from the fragment cache must always be cloned and never used in place.
for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
i === iNoClone ?
fragment :
jQuery.clone( fragment, true, true )
);
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
if ( jQuery.ajax ) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
if ( nodeName === "object" ) {
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// Only cache "small" (1/2 KB) HTML 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
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ];
cachehit = fragment !== undefined;
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment;
}
}
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 elems,
i = 0,
ret = [],
insert = jQuery( selector ),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( ; i < l; i++ ) {
elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
clone;
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
safe = context === document && safeFragment,
ret = [];
// Ensure that context is a document
if ( !context || typeof context.createDocumentFragment === "undefined" ) {
context = document;
}
// Use the already-created safe fragment if context permits
for ( i = 0; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Ensure a safe container in which to render the html
safe = safe || createSafeFragment( context );
div = context.createElement("div");
safe.appendChild( div );
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Go to html and back, then peel off extra wrappers
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
depth = wrap[0];
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>
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 ( 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;
// Take out of fragment container (we need a fresh div each time)
div.parentNode.removeChild( div );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
jQuery.merge( ret, elem );
}
}
// Fix #11356: Clear elements from safeFragment
if ( div ) {
elem = div = safe = null;
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
for ( i = 0; (elem = ret[i]) != null; i++ ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
}
// Append elements to a provided document fragment
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function( elems, /* internal */ acceptData ) {
var data, id, elem, type,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
jQuery.deletedIds.push( id );
}
}
}
}
}
});
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
})();
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
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.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// 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 ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.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" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType, list, placeBefore,
dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),
i = 0,
length = dataTypes.length;
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var selection,
list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters );
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
// Don't do a request if no elements are being requested
if ( !this.length ) {
return this;
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// Request the remote document
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params,
complete: function( jqXHR, status ) {
if ( callback ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
}
}
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
// 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( responseText.replace( rscript, "" ) )
// Locate the specified elements
.find( selector ) :
// If not, just inject the full result
responseText );
});
return this;
};
// 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.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // ifModified key
ifModifiedKey,
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || strAbort;
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ ifModifiedKey ] = modified;
}
modified = jqXHR.getResponseHeader("Etag");
if ( modified ) {
jQuery.etag[ ifModifiedKey ] = modified;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.always( tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace );
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv, conv2, current, tmp,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ],
converters = {},
i = 0;
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
var oldCallbacks = [],
rquestion = /\?/,
rjsonp = /(=)\?(?=&|$)|\?\?/,
nonce = jQuery.now();
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
data = s.data,
url = s.url,
hasCallback = s.jsonp !== false,
replaceInUrl = hasCallback && rjsonp.test( url ),
replaceInData = hasCallback && !replaceInUrl && typeof data === "string" &&
!( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&
rjsonp.test( data );
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
overwritten = window[ callbackName ];
// Insert callback into url or form data
if ( replaceInUrl ) {
s.url = url.replace( rjsonp, "$1" + callbackName );
} else if ( replaceInData ) {
s.data = data.replace( rjsonp, "$1" + callbackName );
} else if ( hasCallback ) {
s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// 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 );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var xhrCallbacks,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( e ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback, 0 );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
|
RSpec.describe AuthorizeIf do
let(:controller) {
double(:dummy_controller, controller_name: "dummy", action_name: "index").
extend(AuthorizeIf)
}
describe "#authorize_if" do
context "when object is given" do
it "returns true if truthy object is given" do
expect(controller.authorize_if(true)).to eq true
expect(controller.authorize_if(Object.new)).to eq true
end
it "raises NotAuthorizedError if falsey object is given" do
expect {
controller.authorize_if(false)
}.to raise_error(AuthorizeIf::NotAuthorizedError)
expect {
controller.authorize_if(nil)
}.to raise_error(AuthorizeIf::NotAuthorizedError)
end
end
context "when object and block are given" do
it "allows exception customization through the block" do
expect {
controller.authorize_if(false) do |exception|
exception.message = "Custom Message"
exception.context[:request_ip] = "192.168.1.1"
end
}.to raise_error(AuthorizeIf::NotAuthorizedError, "Custom Message") do |exception|
expect(exception.message).to eq("Custom Message")
expect(exception.context[:request_ip]).to eq("192.168.1.1")
end
end
end
context "when no arguments are given" do
it "raises ArgumentError" do
expect {
controller.authorize_if
}.to raise_error(ArgumentError)
end
end
end
describe "#authorize" do
context "when corresponding authorization rule exists" do
context "when rule does not accept parameters" do
it "returns true if rule returns true" do
controller.define_singleton_method(:authorize_index?) { true }
expect(controller.authorize).to eq true
end
end
context "when rule accepts parameters" do
it "calls rule with given parameters" do
class << controller
def authorize_index?(param_1, param_2:)
param_1 || param_2
end
end
expect(controller.authorize(false, param_2: true)).to eq true
end
end
context "when block is given" do
it "passes block through to `authorize_if` method" do
controller.define_singleton_method(:authorize_index?) { false }
expect {
controller.authorize do |exception|
exception.message = "passed through"
end
}.to raise_error(AuthorizeIf::NotAuthorizedError, "passed through") do |exception|
expect(exception.message).to eq("passed through")
end
end
end
end
context "when corresponding authorization rule does not exist" do
it "raises MissingAuthorizationRuleError" do
expect {
controller.authorize
}.to raise_error(
AuthorizeIf::MissingAuthorizationRuleError,
"No authorization rule defined for action dummy#index. Please define method #authorize_index? for #{controller.class.name}"
)
end
end
end
end
|
package com.github.kwoin.kgate.core.sequencer;
import com.github.kwoin.kgate.core.message.Message;
import com.github.kwoin.kgate.core.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.CountDownLatch;
/**
* @author P. WILLEMET
*/
public abstract class AbstractSequencer<T extends Message> implements Iterator<T> {
private final Logger logger = LoggerFactory.getLogger(AbstractSequencer.class);
protected Session<T> session;
protected boolean hasNext;
protected final ByteArrayOutputStream baos = new ByteArrayOutputStream();
protected @Nullable CountDownLatch oppositeSessionSignal;
public void setSession(Session<T> session) {
this.session = session;
hasNext = !session.getInput().isInputShutdown();
}
@Override
public boolean hasNext() {
hasNext &= !session.getInput().isClosed();
return hasNext;
}
@Override
@Nullable
public T next() {
if(!hasNext())
throw new NoSuchElementException();
baos.reset();
if(oppositeSessionSignal != null) {
try {
oppositeSessionSignal.await();
} catch (InterruptedException e) {
logger.warn("Waiting for opposite session signal interrupted");
oppositeSessionSignal = null;
}
}
try {
return readNextMessage();
} catch (SocketException e) {
logger.debug("Input read() interrupted because socket has been closed");
hasNext = false;
return null;
} catch (IOException e) {
logger.error("Unexpected error while reading next message", e);
return null;
} finally {
resetState();
}
}
protected abstract T readNextMessage() throws IOException;
protected abstract void resetState();
protected void waitForOppositeSessionSignal() {
if(oppositeSessionSignal == null) {
logger.debug("Wait for opposite session...");
oppositeSessionSignal = new CountDownLatch(1);
}
}
public void oppositeSessionSignal() {
if(oppositeSessionSignal != null) {
logger.debug("wait for opposite session RELEASED");
oppositeSessionSignal.countDown();
}
}
protected byte readByte() throws IOException {
int read = session.getInput().getInputStream().read();
baos.write(read);
return (byte) read;
}
protected byte[] readBytes(int n) throws IOException {
byte[] bytes = new byte[n];
for (int i = 0; i < n; i++)
bytes[i] = readByte();
return bytes;
}
protected byte[] readUntil(byte[] end, boolean withEnd) throws IOException {
int read;
int cursor = 0;
ByteArrayOutputStream tmpBaos = new ByteArrayOutputStream();
while(cursor < end.length) {
read = readByte();
cursor = read == end[cursor] ? cursor + 1 : 0;
tmpBaos.write(read);
}
byte[] bytes = tmpBaos.toByteArray();
return withEnd ? bytes : Arrays.copyOf(bytes, bytes.length - end.length);
}
}
|
b'What is the value of (-6 - (-35 + 16)) + -7 + -4?\n'
|
/*
* 94 shifted lines of 72 ASCII characters.
*/
static const char *characters[] = {
"!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefgh",
"\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghi",
"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghij",
"$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijk",
"%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijkl",
"&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklm",
"'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmn",
"()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmno",
")*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnop",
"*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopq",
"+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqr",
",-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrs",
"-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrst",
"./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstu",
"/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuv",
"0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvw",
"123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwx",
"23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxy",
"3456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz",
"456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{",
"56789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|",
"6789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}",
"789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",
"89:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!",
"9:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"",
":;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#",
";<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$",
"<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%",
"=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&",
">?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'",
"?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'(",
"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*",
"BCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+",
"CDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,",
"DEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-",
"EFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-.",
"FGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./",
"GHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0",
"HIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./01",
"IJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./012",
"JKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123",
"KLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./01234",
"LMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./012345",
"MNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456",
"NOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./01234567",
"OPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./012345678",
"PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789",
"QRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:",
"RSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;",
"STUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<",
"TUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=",
"UVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>",
"VWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?",
"WXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@",
"XYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@A",
"YZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@AB",
"Z[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABC",
"[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCD",
"\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDE",
"]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEF",
"^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFG",
"_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGH",
"`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHI",
"abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJ",
"bcdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJK",
"cdefghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKL",
"defghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLM",
"efghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMN",
"fghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO",
"ghijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOP",
"hijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQ",
"ijklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQR",
"jklmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRS",
"klmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRST",
"lmnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU",
"mnopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUV",
"nopqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVW",
"opqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWX",
"pqrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXY",
"qrstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"rstuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[",
"stuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\",
"tuvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]",
"uvwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^",
"vwxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_",
"wxyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`",
"xyz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`a",
"yz{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`ab",
"z{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abc",
"{|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcd",
"|}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcde",
"}~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdef",
"~!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefg"
};
|
b'Evaluate 0 - 0 - (14 + -58 + 39).\n'
|
b'Calculate -10 + -11 - 0 - (-8 + 0).\n'
|
b'What is the value of 1 + (4 - (15 + -20))?\n'
|
//
// LightningSendDownView.h
// TNTLoveFreshBee
//
// Created by apple on 16/10/14.
// Copyright © 2016年 LiDan. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol didLightningSendDownViewCommitDelegate <NSObject>
@optional
- (void)didLightningSendDownViewCommit;
@end
@interface LightningSendDownView : UIView
@property(weak,nonatomic) id<didLightningSendDownViewCommitDelegate>delegate;
@end
|
[See html formatted version](https://huasofoundries.github.io/google-maps-documentation/MapPanes.html)
MapPanes interface
------------------
google.maps.MapPanes interface
Properties
[floatPane](#MapPanes.floatPane)
**Type:** Element
This pane contains the info window. It is above all map overlays. (Pane 4).
[mapPane](#MapPanes.mapPane)
**Type:** Element
This pane is the lowest pane and is above the tiles. It may not receive DOM events. (Pane 0).
[markerLayer](#MapPanes.markerLayer)
**Type:** Element
This pane contains markers. It may not receive DOM events. (Pane 2).
[overlayLayer](#MapPanes.overlayLayer)
**Type:** Element
This pane contains polylines, polygons, ground overlays and tile layer overlays. It may not receive DOM events. (Pane 1).
[overlayMouseTarget](#MapPanes.overlayMouseTarget)
**Type:** Element
This pane contains elements that receive DOM events. (Pane 3).
|
using Radical.Reflection;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace Radical.Windows
{
static class PropertyInfoExtensions
{
public static string GetDisplayName(this PropertyInfo propertyInfo)
{
if (propertyInfo != null && propertyInfo.IsAttributeDefined<DisplayAttribute>())
{
var a = propertyInfo.GetAttribute<DisplayAttribute>();
return a.GetName();
}
if (propertyInfo != null && propertyInfo.IsAttributeDefined<DisplayNameAttribute>())
{
var a = propertyInfo.GetAttribute<DisplayNameAttribute>();
return a.DisplayName;
}
return null;
}
}
}
|
b'Evaluate 0 - 3 - -10 - 3.\n'
|
<h1><?=$title?></h1>
<h5>Ordered by Points</h5>
<?php foreach ($users as $user) : ?>
<div class="mini-profile left">
<img class="gravatar left" src="<?= $this->mzHelpers->get_gravatar($user->email, 128); ?>" alt="">
<div class="info">
<a href="<?= $this->url->create('users/id/' . $user->id ); ?>"><?= $user->username ?></a> <br>
Points: <?= $user->points ?>
</div>
</div>
<?php endforeach; ?>
|
b'What is the value of -5 - (2 + -4 + (12 - (4 + 1)))?\n'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.