code
stringlengths 2
1.05M
|
---|
/* eslint-env mocha */
const path = require('path');
const should = require('should');
const { openDb, closeDb } = require('../../lib/db');
const gtfs = require('../..');
const config = {
agencies: [{
agency_key: 'caltrain',
path: path.join(__dirname, '../fixture/caltrain_20160406.zip')
}],
verbose: false
};
describe('gtfs.getLevels():', () => {
before(async () => {
await openDb(config);
await gtfs.import(config);
});
after(async () => {
await closeDb();
});
it('should return empty array if no levels', async () => {
const levelId = 'not_real';
const results = await gtfs.getLevels({
level_id: levelId
});
should.exists(results);
results.should.have.length(0);
});
});
|
(function($) {
var UserInputView = Backbone.View.extend({
el : '#UserInput',
initialize : function() {
this.helloListView = new HelloListView();
},
events : {
'click button' : 'addToHelloCollection'
},
addToHelloCollection : function(e) {
var hello = new Hello({
name : this.$('input').val()
});
this.helloListView.collection.add(hello);
}
});
var Hello = Backbone.Model.extend({
initialize : function() {
this.name = 'name'
}
});
var HelloView = Backbone.View.extend({
tagName : 'li',
render : function() {
$(this.el).html('Hello ' + this.model.get('name'));
return this;
}
});
var HelloList = Backbone.Collection.extend({
model : Hello
});
var HelloListView = Backbone.View.extend({
el : '#HelloList',
initialize : function() {
_.bindAll(this, 'render', 'appendToHelloUL');
this.collection = new HelloList();
this.collection.bind('add', this.appendToHelloUL);
},
render:function(){
$.each(this.collection.models, function(i, helloModel){
self.appendToHelloUL(helloModel);
});
},
appendToHelloUL : function(helloModel) {
var helloView = new HelloView({
model : helloModel
});
$(this.el).append(helloView.render().el);
}
});
new UserInputView();
})(jQuery);
|
// This file defines an API that would be nice, but it's not required
// Initialize the editor
var editor = new Editor("");
// Activate/deactivate the editor
editor.active(true || false);
// Set a new action
editor.add("", {
shortcut: {} || "" || false, // The key for Ctrl+key or { key: "esc" }
menu: {} || "" || false, // The html or icon to show
init: function(){} || false, // Called when activating an editor
action: function(){} || false, // Click or shortcut for that action
destroy: function(){} || false // Deactivating an editor
});
// The editor is initialized or re-activated
editor.on("init", function(){});
// Some action is triggered for any reason
editor.on("action", function(){});
// Registered action
editor.on("action:save", function(){});
// The editor is destroyed or de-activated
editor.on("destroy", function(){});
// The editor re-reads its data
editor.on("refresh", function(){});
// Some part of the editor is clicked or touched
editor.on("click", function(){});
// Some key is introduced (for example, "tab")
editor.on("key", function(){});
editor.on("select", function(){});
// Special events
editor.on("<event>:before", function(){});
editor.on("<event>:pre", function(){});
editor.on("<event>:post", function(){});
editor.on("<event>:after", function(){});
editor.on("<event>:none", function(){});
// Example (not part of the API)
editor.action.list = { actionname1: function(){}, actionname2: function(){} };
editor.menu.inline.list = { actionname1: "html1", actionname2: "html2" };
editor.menu.block.list = { actionname1: "html1", actionname2: "html2" };
editor.menu.list = {};
editor.shortcuts.list = { actionname1: { control: true, keyCode: 16 }, actionname2: { control: false, keyCode: 27 } };
editor.shortcuts.get(e);
|
var quizQuistions = {
name:"Super Hero Name Quiz",
description:"How many super heroes can you name?",
headline:"What is the real name of ",
mainquestionList: [
{ "questionName": "Superman", "answer": "Clarke" },
{ "questionName": "Batman", "answer": "Bruce" },
{ "question": "Wonder Woman", "answer": "Dianna" }
]
}
// dom element grab
var $finalScore = document.getElementById("score");
var $ListOfquestions = document.getElementById('displayQuestion');
var $ListOfFeedback = document.getElementById('feedback')
var $startButton = document.getElementById('button');
var $mainForm = document.getElementById('mainform');
var $clockTimer = document.getElementById('clocktimer');
function updateDom(element, content, klass){
var p = element.firstChild || document.createElement("p");
p.textContent = content;
element.appendChild(p);
if(klass){
p.className = klass;
}
}
//hide function
function hide(element){
element.style.display = "none";
}
//hide show button
function show(element){
element.style.display = "block";
}
// event listener for click button
$startButton.addEventListener('click', function (){
play(quizQuistions);
}, false);
// Initial hide main form
hide($mainForm);
function play(quizQuistions){
var score = 0;
updateDom($finalScore, score);
// initialize time and set up an interval that counts down every second
var time = 20;
updateDom($clockTimer, time);
var interval = window.setInterval(timeCoutdown, 1000)
//hide button but show form
hide($startButton);
show($mainForm);
// main form event listener
$mainForm.addEventListener('submit', function(event){
event.preventDefault();
check($mainForm[0].value);
}, false);
var i = 0;
chooseQuestion();
function chooseQuestion(){
var questionVal = quizQuistions.mainquestionList[i].questionName;
ask(questionVal);
}
function ask(questionAskParamater) {
updateDom($ListOfquestions, quizQuistions.headline + questionAskParamater )
$mainForm[0].value = "";
$mainForm[0].focus();
}
function check(answer) {
if(answer === quizQuistions.mainquestionList[i].answer){
updateDom($ListOfFeedback, "Answer Correct", "right");
score++;
updateDom($finalScore, score);
} else {
updateDom($ListOfFeedback, "Answer Wrong", "wrong");
}
// check if any quistion available
i++
if(i === quizQuistions.mainquestionList.length){
finalGameOver()
} else {
chooseQuestion();
}
}
// time countdown and decrease the time
function timeCoutdown(){
time --;
updateDom($clockTimer, time);
if(time <= 0){
finalGameOver();
}
}
// game over
function finalGameOver(){
updateDom($ListOfquestions, "Gameover, Your scored is " +score+ " points");
window.clearInterval(interval);
hide($mainForm);
show($startButton);
}
}
|
#!/usr/bin/env node
/**
* @file stream.js
*
* Custom object to inherit from EventEmitter, with the help of `util'
*
*/
var events = require('events');
function Stream() {
events.EventEmitter.call(this);
}
util.inherits(Stream, events,EventEmitter);
|
/**
* Created by admin on 14.09.2015.
*/
var gulp = require('gulp');
var less = require('gulp-less');
var csso = require('gulp-csso');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var sourcemaps = require('gulp-sourcemaps');
var ngAnnotate = require('gulp-ng-annotate');
gulp.task('js', function () {
gulp.src(['js/**/*.js'])
.pipe(sourcemaps.init())
.pipe(concat('app.js'))
.pipe(ngAnnotate())
.pipe(uglify())
.pipe(sourcemaps.write())
.pipe(gulp.dest('./dist/js'));
});
gulp.task('css', function () {
gulp.src('./less/**/*.less')
.pipe(concat('styles.less'))
.pipe(less())
.pipe(gulp.dest('./css'))
.pipe(csso())
.pipe(gulp.dest('./dist/css'));
});
gulp.task('images', function () {
gulp.src('./img/**/*')
.pipe(imagemin())
.pipe(gulp.dest('./dist/img'));
});
gulp.task('watch', function () {
gulp.watch('./less/**/*.less', function() {
gulp.run('css');
});
gulp.watch('./img/**/*', function() {
gulp.run('images');
});
gulp.watch('./js/**/*', function() {
gulp.run('js');
});
});
gulp.task('build', function () {
gulp.run('js');
gulp.run('css');
gulp.run('images');
});
|
import marked from 'marked';
import { isAbsolutePath, getPath, getParentPath } from '../router/util';
import { isFn, merge, cached, isPrimitive } from '../util/core';
import { tree as treeTpl } from './tpl';
import { genTree } from './gen-tree';
import { slugify } from './slugify';
import { emojify } from './emojify';
import { getAndRemoveConfig } from './utils';
import { imageCompiler } from './compiler/image';
import { highlightCodeCompiler } from './compiler/code';
import { paragraphCompiler } from './compiler/paragraph';
import { taskListCompiler } from './compiler/taskList';
import { taskListItemCompiler } from './compiler/taskListItem';
import { linkCompiler } from './compiler/link';
const cachedLinks = {};
const compileMedia = {
markdown(url) {
return {
url,
};
},
mermaid(url) {
return {
url,
};
},
iframe(url, title) {
return {
html: `<iframe src="${url}" ${title ||
'width=100% height=400'}></iframe>`,
};
},
video(url, title) {
return {
html: `<video src="${url}" ${title || 'controls'}>Not Support</video>`,
};
},
audio(url, title) {
return {
html: `<audio src="${url}" ${title || 'controls'}>Not Support</audio>`,
};
},
code(url, title) {
let lang = url.match(/\.(\w+)$/);
lang = title || (lang && lang[1]);
if (lang === 'md') {
lang = 'markdown';
}
return {
url,
lang,
};
},
};
export class Compiler {
constructor(config, router) {
this.config = config;
this.router = router;
this.cacheTree = {};
this.toc = [];
this.cacheTOC = {};
this.linkTarget = config.externalLinkTarget || '_blank';
this.linkRel =
this.linkTarget === '_blank' ? config.externalLinkRel || 'noopener' : '';
this.contentBase = router.getBasePath();
const renderer = this._initRenderer();
this.heading = renderer.heading;
let compile;
const mdConf = config.markdown || {};
if (isFn(mdConf)) {
compile = mdConf(marked, renderer);
} else {
marked.setOptions(
merge(mdConf, {
renderer: merge(renderer, mdConf.renderer),
})
);
compile = marked;
}
this._marked = compile;
this.compile = text => {
let isCached = true;
// eslint-disable-next-line no-unused-vars
const result = cached(_ => {
isCached = false;
let html = '';
if (!text) {
return text;
}
if (isPrimitive(text)) {
html = compile(text);
} else {
html = compile.parser(text);
}
html = config.noEmoji ? html : emojify(html);
slugify.clear();
return html;
})(text);
const curFileName = this.router.parse().file;
if (isCached) {
this.toc = this.cacheTOC[curFileName];
} else {
this.cacheTOC[curFileName] = [...this.toc];
}
return result;
};
}
/**
* Pulls content from file and renders inline on the page as a embedded item.
*
* This allows you to embed different file types on the returned
* page.
* The basic format is:
* ```
* [filename](_media/example.md ':include')
* ```
*
* @param {string} href The href to the file to embed in the page.
* @param {string} title Title of the link used to make the embed.
*
* @return {type} Return value description.
*/
compileEmbed(href, title) {
const { str, config } = getAndRemoveConfig(title);
let embed;
title = str;
if (config.include) {
if (!isAbsolutePath(href)) {
href = getPath(
process.env.SSR ? '' : this.contentBase,
getParentPath(this.router.getCurrentPath()),
href
);
}
let media;
if (config.type && (media = compileMedia[config.type])) {
embed = media.call(this, href, title);
embed.type = config.type;
} else {
let type = 'code';
if (/\.(md|markdown)/.test(href)) {
type = 'markdown';
} else if (/\.mmd/.test(href)) {
type = 'mermaid';
} else if (/\.html?/.test(href)) {
type = 'iframe';
} else if (/\.(mp4|ogg)/.test(href)) {
type = 'video';
} else if (/\.mp3/.test(href)) {
type = 'audio';
}
embed = compileMedia[type].call(this, href, title);
embed.type = type;
}
embed.fragment = config.fragment;
return embed;
}
}
_matchNotCompileLink(link) {
const links = this.config.noCompileLinks || [];
for (let i = 0; i < links.length; i++) {
const n = links[i];
const re = cachedLinks[n] || (cachedLinks[n] = new RegExp(`^${n}$`));
if (re.test(link)) {
return link;
}
}
}
_initRenderer() {
const renderer = new marked.Renderer();
const { linkTarget, linkRel, router, contentBase } = this;
const _self = this;
const origin = {};
/**
* Render anchor tag
* @link https://github.com/markedjs/marked#overriding-renderer-methods
* @param {String} text Text content
* @param {Number} level Type of heading (h<level> tag)
* @returns {String} Heading element
*/
origin.heading = renderer.heading = function(text, level) {
let { str, config } = getAndRemoveConfig(text);
const nextToc = { level, title: str };
if (/<!-- {docsify-ignore} -->/g.test(str)) {
str = str.replace('<!-- {docsify-ignore} -->', '');
nextToc.title = str;
nextToc.ignoreSubHeading = true;
}
if (/{docsify-ignore}/g.test(str)) {
str = str.replace('{docsify-ignore}', '');
nextToc.title = str;
nextToc.ignoreSubHeading = true;
}
if (/<!-- {docsify-ignore-all} -->/g.test(str)) {
str = str.replace('<!-- {docsify-ignore-all} -->', '');
nextToc.title = str;
nextToc.ignoreAllSubs = true;
}
if (/{docsify-ignore-all}/g.test(str)) {
str = str.replace('{docsify-ignore-all}', '');
nextToc.title = str;
nextToc.ignoreAllSubs = true;
}
const slug = slugify(config.id || str);
const url = router.toURL(router.getCurrentPath(), { id: slug });
nextToc.slug = url;
_self.toc.push(nextToc);
return `<h${level} id="${slug}"><a href="${url}" data-id="${slug}" class="anchor"><span>${str}</span></a></h${level}>`;
};
origin.code = highlightCodeCompiler({ renderer });
origin.link = linkCompiler({
renderer,
router,
linkTarget,
linkRel,
compilerClass: _self,
});
origin.paragraph = paragraphCompiler({ renderer });
origin.image = imageCompiler({ renderer, contentBase, router });
origin.list = taskListCompiler({ renderer });
origin.listitem = taskListItemCompiler({ renderer });
renderer.origin = origin;
return renderer;
}
/**
* Compile sidebar
* @param {String} text Text content
* @param {Number} level Type of heading (h<level> tag)
* @returns {String} Sidebar element
*/
sidebar(text, level) {
const { toc } = this;
const currentPath = this.router.getCurrentPath();
let html = '';
if (text) {
html = this.compile(text);
} else {
for (let i = 0; i < toc.length; i++) {
if (toc[i].ignoreSubHeading) {
const deletedHeaderLevel = toc[i].level;
toc.splice(i, 1);
// Remove headers who are under current header
for (
let j = i;
deletedHeaderLevel < toc[j].level && j < toc.length;
j++
) {
toc.splice(j, 1) && j-- && i++;
}
i--;
}
}
const tree = this.cacheTree[currentPath] || genTree(toc, level);
html = treeTpl(tree, '<ul>{inner}</ul>');
this.cacheTree[currentPath] = tree;
}
return html;
}
/**
* Compile sub sidebar
* @param {Number} level Type of heading (h<level> tag)
* @returns {String} Sub-sidebar element
*/
subSidebar(level) {
if (!level) {
this.toc = [];
return;
}
const currentPath = this.router.getCurrentPath();
const { cacheTree, toc } = this;
toc[0] && toc[0].ignoreAllSubs && toc.splice(0);
toc[0] && toc[0].level === 1 && toc.shift();
for (let i = 0; i < toc.length; i++) {
toc[i].ignoreSubHeading && toc.splice(i, 1) && i--;
}
const tree = cacheTree[currentPath] || genTree(toc, level);
cacheTree[currentPath] = tree;
this.toc = [];
return treeTpl(tree);
}
header(text, level) {
return this.heading(text, level);
}
article(text) {
return this.compile(text);
}
/**
* Compile cover page
* @param {Text} text Text content
* @returns {String} Cover page
*/
cover(text) {
const cacheToc = this.toc.slice();
const html = this.compile(text);
this.toc = cacheToc.slice();
return html;
}
}
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _webpackDevServer = __webpack_require__(1);
var _webpackDevServer2 = _interopRequireDefault(_webpackDevServer);
var _webpack = __webpack_require__(2);
var _webpack2 = _interopRequireDefault(_webpack);
var _webpackConfigDev = __webpack_require__(3);
var _webpackConfigDev2 = _interopRequireDefault(_webpackConfigDev);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var server = new _webpackDevServer2.default((0, _webpack2.default)(_webpackConfigDev2.default), {
publicPath: _webpackConfigDev2.default.output.publicPath,
hot: true
});
server.listen(8080, 'localhost', function () {
console.log("Dev-Server with Hot Reloading");
});
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = require("webpack-dev-server");
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = require("webpack");
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var webpack = __webpack_require__(2);
module.exports = {
entry: ['webpack-dev-server/client?http://localhost:8080', 'webpack/hot/only-dev-server', './src/client/main'],
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'react-hot!babel-loader?presets[]=es2015&presets[]=es2016&presets[]=react'
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
output: {
path: __dirname + '/public/js',
publicPath: 'http://localhost:8080/js/',
filename: 'application.js'
},
plugins: [new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurrenceOrderPlugin()]
};
/***/ }
/******/ ]);
|
/*** @jsx React.DOM */
var React = require('react');
var JigsawStore = require('../stores/JigsawStore');
var JigsawActions = require('../actions/JigsawActions');
/**
* A button to update the random number generator seed.
* @type {*|Function}
*/
var Randomizer = React.createClass({
getInitialState: function() {
return {seed: JigsawStore.getRandSeed()};
},
componentDidMount: function() {
JigsawStore.addChangeListener(this._onChange);
},
componentWillUnmount: function() {
JigsawStore.removeChangeListener(this._onChange);
},
render: function() {
var disabled = ! this.state.canRedo;
return (
<button className="btn btn-default" onClick={this._randomize}>Randomize</button>
);
},
_randomize: function() {
JigsawActions.randomize();
return false;
},
_onChange: function() {
this.setState({seed: JigsawStore.getRandSeed()})
}
});
module.exports = Randomizer;
|
lychee.define('fertilizer.Main').requires([
'lychee.Input',
'lychee.data.JSON',
'fertilizer.data.Filesystem',
'fertilizer.data.Shell',
'fertilizer.template.html.Application',
'fertilizer.template.html.Library',
'fertilizer.template.html-nwjs.Application',
'fertilizer.template.html-nwjs.Library',
'fertilizer.template.html-webview.Application',
'fertilizer.template.html-webview.Library',
'fertilizer.template.node.Application',
'fertilizer.template.node.Library'
]).includes([
'lychee.event.Emitter'
]).exports(function(lychee, fertilizer, global, attachments) {
var _lychee = lychee;
var _path = require('path');
var _JSON = lychee.data.JSON;
/*
* FEATURE DETECTION
*/
var _defaults = {
project: null,
identifier: null,
settings: null
};
/*
* IMPLEMENTATION
*/
var Class = function(settings) {
this.settings = lychee.extendunlink({}, _defaults, settings);
this.defaults = lychee.extendunlink({}, this.settings);
lychee.event.Emitter.call(this);
/*
* INITIALIZATION
*/
var that = this;
this.bind('load', function() {
var identifier = this.settings.identifier || null;
var project = this.settings.project || null;
var data = this.settings.settings || null;
if (identifier !== null && project !== null && data !== null) {
var platform = data.tags.platform[0] || null;
var variant = data.variant || null;
var settings = _JSON.decode(_JSON.encode(lychee.extend({}, data, {
debug: false,
sandbox: true,
type: 'export'
})));
var profile = {};
if (settings.profile instanceof Object) {
profile = settings.profile;
}
if (platform !== null && variant.match(/application|library/)) {
if (settings.packages instanceof Array) {
settings.packages = settings.packages.map(function(pkg) {
var id = pkg[0];
var path = _path.resolve(project, pkg[1]);
return [ id, path ];
});
}
var that = this;
var environment = new lychee.Environment(settings);
_lychee.setEnvironment(environment);
environment.debug = true;
environment.init(function(sandbox) {
if (sandbox !== null) {
// IMPORTANT: Don't use Environment's imperative API here!
// Environment identifier is /libraries/lychee/main instead of /libraries/lychee/html/main
environment.id = project + '/' + identifier.split('/').pop();
environment.type = 'build';
environment.debug = that.defaults.settings.debug;
environment.sandbox = that.defaults.settings.sandbox;
_lychee.setEnvironment(null);
that.trigger('init', [ project, identifier, platform, variant, environment, profile ]);
} else {
console.error('fertilizer: FAILURE ("' + project + ' | ' + identifier + '") at "load" event');
if (typeof environment.global.console.serialize === 'function') {
var debug = environment.global.console.serialize();
if (debug.blob !== null) {
(debug.blob.stderr || '').trim().split('\n').map(function(line) {
return (line.indexOf(':') !== -1 ? line.split(':')[1].trim() : '');
}).forEach(function(line) {
console.error('fertilizer: ' + line);
});
}
}
that.destroy();
}
});
return true;
}
}
console.error('fertilizer: FAILURE ("' + project + ' | ' + identifier + '") at "load" event');
this.destroy();
return false;
}, this, true);
this.bind('init', function(project, identifier, platform, variant, environment, profile) {
if (typeof fertilizer.template[platform] === 'object') {
var construct = fertilizer.template[platform][variant.charAt(0).toUpperCase() + variant.substr(1).toLowerCase()] || null;
if (construct !== null) {
var template = new construct({
environment: environment,
profile: profile,
filesystem: new fertilizer.data.Filesystem(project + '/build/' + identifier),
shell: new fertilizer.data.Shell(project + '/build/' + identifier)
});
template.then('configure');
template.then('build');
template.then('package');
template.bind('complete', function() {
console.info('fertilizer: SUCCESS ("' + project + ' | ' + identifier + '")');
this.destroy();
}, this);
template.bind('error', function(event) {
console.error('fertilizer: FAILURE ("' + project + ' | ' + identifier + '") at "' + event + '" event');
this.destroy();
}, this);
template.init();
return true;
}
}
console.error('fertilizer: FAILURE ("' + project + ' | ' + identifier + '") at "init" event');
this.destroy();
return false;
}, this, true);
};
Class.prototype = {
/*
* MAIN API
*/
init: function() {
this.trigger('load', []);
},
destroy: function() {
this.trigger('destroy', []);
}
};
return Class;
});
|
(function () {
'use strict';
angular
.module('templateApp')
.controller('Page2Detail', Page2Detail);
Page2Detail.$inject = ['$routeParams', '$firebaseObject', 'FIREBASE_URL'];
/* @ngInject */
function Page2Detail($routeParams, $firebaseObject, FIREBASE_URL) {
/* jshint validthis: true */
var vm = this;
vm.title = 'Meeting Detail';
var ref = new Firebase(FIREBASE_URL + '/users/' + $routeParams.uid + '/meetings/' + $routeParams.meetingId);
vm.meeting = $firebaseObject(ref);
vm.meeting.$loaded(function(){
vm.dateTime = new Date(vm.meeting.date);
});
}
})();
|
import Discover from 'node-discover';
import EventEmitter from 'events';
export default class Discovery extends EventEmitter {
constructor(channel = 'handover') {
super();
this.channel = channel;
this.d = Discover();
this.d.join(this.channel, this.handleReceive.bind(this));
}
stop() {
this.d.leave(this.channel);
this.d.stop();
}
send(data) {
this.d.send(this.channel, data);
}
handleReceive(data, obj) {
this.emit('receive', {
address: this.findNodeById(obj.iid).address,
data: data,
obj: obj
});
}
findNodeById(id) {
var node;
this.d.eachNode((n) => {
if (n.id === id) {
node = n;
}
});
return node;
}
}
|
/**
* keta 1.11.0
* Build 2021-04-21T15:24:16.331Z
*
* Copyright Kiwigrid GmbH 2014-2021
* http://kiwigrid.github.io/keta/
*
* Licensed under MIT License
* https://raw.githubusercontent.com/kiwigrid/keta/master/LICENSE
*/
"use strict";angular.module("keta.services.TagSet",["keta.services.Tag"]).provider("ketaTagSet",function(){this.$get=function(){var TagSetInstance=function(){var that=this,tags=[],tagsAsHierarchy={};that.getTags=function(){return tags},that.getTagsAsHierarchy=function(){return tagsAsHierarchy},that.add=function(tag){return angular.isDefined(tagsAsHierarchy[tag.getGuid()])&&angular.isDefined(tagsAsHierarchy[tag.getGuid()][tag.getName()])||(angular.isDefined(tagsAsHierarchy[tag.getGuid()])||(tagsAsHierarchy[tag.getGuid()]={}),tagsAsHierarchy[tag.getGuid()][tag.getName()]=tag,tags.push(tag)),that},that.remove=function(tag){return angular.isDefined(tagsAsHierarchy[tag.getGuid()][tag.getName()])&&(delete tagsAsHierarchy[tag.getGuid()][tag.getName()],0===Object.keys(tagsAsHierarchy[tag.getGuid()]).length&&delete tagsAsHierarchy[tag.getGuid()],tags.splice(tags.indexOf(tag),1)),that}};return{create:function(){return new TagSetInstance}}}});
//# sourceMappingURL=tag-set.min.js.map
|
import {NotFound} from '.'
import {shallowRender} from '../../utils/testUtils'
import {expect} from 'chai'
import {findWithType, findAllWithType} from 'react-shallow-testutils'
describe('frontend not found view', () => {
it('renders not found', () => {
const component = shallowRender(NotFound, { className: 'MyComponent' })
expect(findWithType(component, 'h1').props.children).to.equal('Not found')
})
})
|
/* Requirements */
var express = require('express');
var app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
, mongoose = require('mongoose');
/* Initialization */
server.listen(3333);
mongoose.connect('mongodb://localhost/test');
/* Global variable setup */
var serverRoot = __dirname;
var Schema = mongoose.Schema;
/* DB Schemas */
var adminSchema = new Schema({
first_name: String,
last_name: String,
email: {type: [String], index: true},
password: String,
session_key: String
});
var userSchema = new Schema({
first_name: String,
last_name: String,
email: {type: [String], index: true},
secret_key: String,
has_voted: Boolean
});
/* Models */
var Admin = mongoose.model('Admin', adminSchema);
var User = mongoose.model('User', userSchema);
/* Get the server up and running */
app.use(express.static(serverRoot));
app.use(express.bodyParser());
app.get('/', function (req, res) {
res.sendfile(serverRoot + '/index.html');
});
app.post('/authenticate', function(req, res) {
var date = new Date();
console.log("Authentication request received at " + date);
Admin.findOne({email: req.body.email}, function(err, result) {
if(err) {
console.log("Error: " + err);
throw(err);
}
if(!result) {
//response to client for user not found/invalid email address
res.send(401, {invalid_email: true});
}
else {
if(req.body.password !== result.password) {
//response to client for invalid password
res.send(401, {invalid_password: true});
}
else {
//res.cookie('admin_id', )
res.send({we: "fuckingdidit"});
}
}
});
});
|
/*Problem 8. Number as words
Write a script that converts a number in the range [0
999]
to words, corresponding to its English pronunciation.*/
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
var numbers = [0, 9, 10, 12, 19, 25, 98, 98, 273, 400, 501, 617, 711, 999];
for(var ind = 0; ind < numbers.length; ind++){
console.log(numbers[ind] + '\t' + getString(numbers[ind]));
}
function getString(number){
var text = '',
hundreds = Math.floor(number / 100) % 10,
tens = Math.floor(number / 10) % 10,
ones = number % 10;
if(!hundreds && !tens && !ones){
text = 'zero';
}
if (hundreds) {
text += getDigit(hundreds) + ' hundred';
}
if (tens || ones) {
if (text.length) {
text += ' and ';
}
if (tens) {
if (tens === 1) {
return (text + getTeens(tens * 10 + ones)).capitalize();
}
text += getTens(tens);
}
if (ones) {
if(tens){
text += ' ';
}
text += getDigit(ones);
}
}
return text.capitalize();
}
function getDigit (digit) {
switch(digit){
case 0: return 'zero';
case 1: return 'one';
case 2: return 'two';
case 3: return 'three';
case 4: return 'four';
case 5: return 'five';
case 6: return 'six';
case 7: return 'seven';
case 8: return 'eight';
case 9: return 'nine';
default: return '';
}
}
function getTens (digit) {
switch(digit){
case 2: return 'twenty';
case 3: return 'thirty';
case 4: return 'forty';
case 5: return 'fifty';
case 6: return 'sixty';
case 7: return 'seventy';
case 8: return 'eighty';
case 9: return 'ninety';
default: return '';
}
}
function getTeens (digit) {
switch(digit){
case 10: return 'ten';
case 11: return 'eleven';
case 12: return 'twelve';
case 13: return 'thirteen';
case 14: return 'fourteen';
case 15: return 'fifteen';
case 16: return 'sixteen';
case 17: return 'seventeen';
case 18: return 'eighteen';
case 19: return 'nineteen';
default: return '';
}
}
|
class UserInput {
constructor(game) {
this.game = game;
this.keyCodeMapper = {
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
}
getUserInput(){
window.addEventListener("keydown", this.sendUserInput.bind(this));
}
sendUserInput(event) {
var input = this.keyCodeMapper[event.keyCode];
var previousDirection = this.game.snake.direction;
this.game.snake.setDirection(input, previousDirection);
}
}
module.exports = UserInput;
|
import { describe, it } from 'mocha';
import Immutable from 'immutable';
import deepFreeze from 'deep-freeze';
import { createStore } from 'redux';
import { createReducerTest, executeCbs } from './helpers';
import { defaultState as objDefaultState, actions as objActions } from './objectState/index';
import { defaultState as arrDefaultState, actions as arrActions } from './arrayState/index';
import { pathReducer } from '../';
const subscribedCbs = [];
const immObjDefaultState = Immutable.fromJS(objDefaultState); // Immutable state
const immArrDefaultState = Immutable.fromJS(arrDefaultState); // Immutable state
const objReducer = (state = immObjDefaultState, action = {}) => {
executeCbs(subscribedCbs, state, action);
// We return original state in order to not mutate it,
// So every test is done over the same initial state
return state;
};
const arrReducer = (state = immArrDefaultState, action = {}) => {
executeCbs(subscribedCbs, state, action);
// We return original state in order to not mutate it,
// So every test is done over the same initial state
return state;
};
deepFreeze(immObjDefaultState);
deepFreeze(immArrDefaultState);
deepFreeze(objActions);
deepFreeze(arrActions);
export default function executeTest() {
describe('Immutable object state store', () => {
const store = createStore(objReducer);
const test = createReducerTest(store, subscribedCbs, immObjDefaultState);
let action;
for (action in objActions) {
// test(..) ensures the state is defaultState before each dispatch
if (objActions.hasOwnProperty(action)) {
it(`dispatch ${objActions[action].type} action`, test(objActions[action]));
}
}
});
describe('Immutable array state store', () => {
const store = createStore(arrReducer);
const test = createReducerTest(store, subscribedCbs, immArrDefaultState);
let action;
for (action in arrActions) {
// test(..) ensures the state is defaultState before each dispatch
if (arrActions.hasOwnProperty(action)) {
it(`dispatch ${arrActions[action].type} action`, test(arrActions[action]));
}
}
});
describe('Immutable object state store with pathReducer wrapper', () => {
let action;
it('store should be correctly created with pathReducer wrapper', () => {
createStore(pathReducer(objReducer));
});
for (action in objActions) {
if (objActions.hasOwnProperty(action)) {
// We need to recreate store as the state is being modified after each dispatch
const store = createStore(pathReducer(objReducer));
const test = createReducerTest(store, subscribedCbs, immObjDefaultState, false);
it(`dispatch ${objActions[action].type} action`, test(objActions[action]));
}
}
});
describe('Immutable array state store with pathReducer wrapper', () => {
let action;
it('store should be correctly created with pathReducer wrapper', () => {
createStore(pathReducer(objReducer));
});
for (action in arrActions) {
if (arrActions.hasOwnProperty(action)) {
// We need to recreate store as the state is being modified after each dispatch
const store = createStore(pathReducer(arrReducer));
const test = createReducerTest(store, subscribedCbs, immArrDefaultState, false);
it(`dispatch ${arrActions[action].type} action`, test(arrActions[action]));
}
}
});
}
|
import Washi from '../washi'
describe('Chain', function() {
it('can chain objects', function() {
var obj = {}
var mock = jest.fn()
Washi.$.chain(obj).tap(mock)
expect(mock.mock.calls[0][0]).toEqual(obj)
})
it('can chain arrays', function() {
var arr = [1]
var result = Washi.$
.chain(arr)
.map(function(i) {
return i + 1
})
.valueOf()
expect(result).toEqual([2])
})
it('has access to the element on calls', function() {
var el = document.createElement('button')
var mock = jest.fn()
Washi.$
.chain(el)
.tap(mock)
.tap(mock)
expect(mock.mock.calls[0][0]).toEqual(el)
})
it('can chain multiple times', function() {
var el = document.createElement('button')
var mock = jest.fn()
Washi.$
.chain(el)
.tap(mock)
.tap(mock)
expect(mock.mock.calls.length).toEqual(2)
})
it('returns the result of a previous chain to the next if provided', function() {
var el = document.createElement('button')
var mock = jest.fn()
var result = Washi.$([el, el])
.map(function(el) {
return el.tagName
})
.reduce(function(a, b) {
return [a, b].join(' ')
}, '')
.valueOf()
.trim()
expect(result).toEqual('BUTTON BUTTON')
})
})
|
/*
* Kendo UI Complete v2013.2.918 (http://kendoui.com)
* Copyright 2013 Telerik AD. All rights reserved.
*
* Kendo UI Complete commercial licenses may be obtained at
* https://www.kendoui.com/purchase/license-agreement/kendo-ui-complete-commercial.aspx
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
kendo_module({
id: "mobile.shim",
name: "Shim",
category: "mobile",
description: "Mobile Shim",
depends: [ "popup" ],
hidden: true
});
(function($, undefined) {
var kendo = window.kendo,
ui = kendo.mobile.ui,
Popup = kendo.ui.Popup,
SHIM = '<div class="km-shim"/>',
Widget = ui.Widget;
var Shim = Widget.extend({
init: function(element, options) {
var that = this,
app = kendo.mobile.application,
osname = app ? app.os.name : kendo.support.mobileOS.name,
ioswp = osname === "ios" || osname === "wp" || app.os.skin,
bb = osname === "blackberry",
align = options.align || (ioswp ? "bottom center" : bb ? "center right" : "center center"),
position = options.position || (ioswp ? "bottom center" : bb ? "center right" : "center center"),
effect = options.effect || (ioswp ? "slideIn:up" : bb ? "slideIn:left" : "fade:in"),
shim = $(SHIM).handler(that).hide();
Widget.fn.init.call(that, element, options);
that.shim = shim;
that.element = element;
if (!that.options.modal) {
that.shim.on("up", "hide");
}
(app ? app.element : $(document.body)).append(shim);
that.popup = new Popup(that.element, {
anchor: shim,
modal: true,
appendTo: shim,
origin: align,
position: position,
animation: {
open: {
effects: effect,
duration: that.options.duration
},
close: {
duration: that.options.duration
}
},
deactivate: function() {
shim.hide();
},
open: function() {
shim.show();
}
});
kendo.notify(that);
},
options: {
name: "Shim",
modal: true,
align: undefined,
position: undefined,
effect: undefined,
duration: 200
},
show: function() {
this.shim.css("height", this.shim.parent()[0].scrollHeight);
this.popup.open();
},
hide: function(e) {
if (!e || !$.contains(this.shim[0], e.target)) {
this.popup.close();
}
},
destroy: function() {
Widget.fn.destroy.call(this);
this.shim.kendoDestroy();
this.popup.destroy();
this.shim.remove();
}
});
ui.plugin(Shim);
})(window.kendo.jQuery);
|
import { StyleSheet } from 'react-native';
import { PRIMARY_COLOR, COLOR_WHITE } from '../../styles/colors';
const styles = StyleSheet.create({
toolbar: {
height: 56,
backgroundColor: PRIMARY_COLOR
},
container: {
flex: 1,
backgroundColor: PRIMARY_COLOR,
},
contentContaier: {
padding: 30,
},
registerButton: {
backgroundColor: COLOR_WHITE,
padding: 20,
borderRadius: 6,
marginBottom: 20,
alignItems: 'center'
},
registerButtonTitle: {
fontSize: 18,
color: PRIMARY_COLOR,
}
});
export { styles as default };
|
import { connect } from 'react-redux';
import Head from '../components/Head';
function mapStateToProps(state) {
return {
title: state.db.title,
...state.theme
}
}
export default connect(mapStateToProps)(Head);
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
var React;
var ReactDOM;
var ReactDOMComponentTree;
var ReactTestUtils;
var SelectEventPlugin;
describe('SelectEventPlugin', () => {
function extract(node, topLevelEvent) {
return SelectEventPlugin.extractEvents(
topLevelEvent,
ReactDOMComponentTree.getInstanceFromNode(node),
{target: node},
node,
);
}
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
ReactTestUtils = require('react-dom/test-utils');
// TODO: can we express this test with only public API?
ReactDOMComponentTree = require('../../client/ReactDOMComponentTree')
.default;
SelectEventPlugin = require('../SelectEventPlugin').default;
});
it('should skip extraction if no listeners are present', () => {
class WithoutSelect extends React.Component {
render() {
return <input type="text" />;
}
}
var rendered = ReactTestUtils.renderIntoDocument(<WithoutSelect />);
var node = ReactDOM.findDOMNode(rendered);
node.focus();
// It seems that .focus() isn't triggering this event in our test
// environment so we need to ensure it gets set for this test to be valid.
var fakeNativeEvent = function() {};
fakeNativeEvent.target = node;
ReactTestUtils.simulateNativeEventOnNode('topFocus', node, fakeNativeEvent);
var mousedown = extract(node, 'topMouseDown');
expect(mousedown).toBe(null);
var mouseup = extract(node, 'topMouseUp');
expect(mouseup).toBe(null);
});
it('should extract if an `onSelect` listener is present', () => {
class WithSelect extends React.Component {
render() {
return <input type="text" onSelect={this.props.onSelect} />;
}
}
var cb = jest.fn();
var rendered = ReactTestUtils.renderIntoDocument(
<WithSelect onSelect={cb} />,
);
var node = ReactDOM.findDOMNode(rendered);
node.selectionStart = 0;
node.selectionEnd = 0;
node.focus();
var focus = extract(node, 'topFocus');
expect(focus).toBe(null);
var mousedown = extract(node, 'topMouseDown');
expect(mousedown).toBe(null);
var mouseup = extract(node, 'topMouseUp');
expect(mouseup).not.toBe(null);
expect(typeof mouseup).toBe('object');
expect(mouseup.type).toBe('select');
expect(mouseup.target).toBe(node);
});
});
|
function output(x) {
document.getElementById("output").innerHTML += x + "\n";
}
function main () {
try {
do_tests();
} catch (e) {
alert(JSON.stringify(e));
}
}
var hex_digit_value = { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4,
"5": 5, "6": 6, "7": 7, "8": 8, "9": 9,
"a": 10, "A": 10,
"b": 11, "B": 11,
"c": 12, "C": 12,
"d": 13, "D": 13,
"e": 14, "E": 14,
"f": 15, "F": 15 };
function from_hex(s) {
if (s.length & 1) throw { message: "from_hex: odd-length input" };
var result = new Uint8Array(s.length / 2);
for (var i = 0; i < s.length; i += 2) {
var v1 = hex_digit_value[s[i]];
var v2 = hex_digit_value[s[i+1]];
if ((typeof v1 === "undefined")) throw { message: "Illegal hex digit: " + s[i] };
if ((typeof v2 === "undefined")) throw { message: "Illegal hex digit: " + s[i+1] };
result[i >> 1] = (v1 << 4) | v2;
}
return result;
}
function do_tests() {
output("Starting...");
output(scrypt.to_hex(from_hex("0123456789abcdef")));
output("");
function check(password, salt, n, r, p, expected_hex) {
var expected = from_hex(expected_hex);
var startTime = new Date().getTime();
var actual = scrypt.crypto_scrypt(scrypt.encode_utf8(password),
scrypt.encode_utf8(salt),
n, r, p, expected.length);
var stopTime = new Date().getTime();
output("Milliseconds for "+password+"/"+salt+"/"+n+"/"+r+"/"+p+": " +
(stopTime - startTime));
if (scrypt.to_hex(actual) !== expected_hex) {
output("FAILED");
output("expected: " + expected_hex);
output("actual: " + scrypt.to_hex(actual));
}
}
check("", "", 16, 1, 1, "77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906");
check("password", "NaCl", 1024, 8, 16, "fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640");
check("pleaseletmein", "SodiumChloride", 16384, 8, 1, "7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887");
// Disabled: wayyyy too slow.
//
// check("pleaseletmein", "SodiumChloride", 1048576, 8, 1, "2101cb9b6a511aaeaddbbe09cf70f881ec568d574a2ffd4dabe5ee9820adaa478e56fd8f4ba5d09ffa1c6d927c40f4c337304049e8a952fbcbf45c6fa77a41a4");
output("");
output("...done.");
}
window.onload = main;
|
(function () {
'use strict';
angular
.module('certificates.admin')
.controller('CertificatesAdminListController', CertificatesAdminListController);
CertificatesAdminListController.$inject = ['CertificateService'];
function CertificatesAdminListController(CertificatesService) {
var vm = this;
vm.certificates = CertificatesService.query();
}
}());
|
/*******************************
* 名称:详情
* 作者:rubbish.boy@163.com
*******************************
*/
//获取应用实例
var app = getApp()
var config={
//页面的初始数据
data: {
title : '名片介绍',
userInfo : {},
session_id :'',
requestlock :true,
domainName : app.globalData.domainName,
dataid :"",
infodata :{}
},
//生命周期函数--监听页面加载
onLoad: function (options) {
var that = this
//调用应用实例的方法获取全局数据
app.getUserInfo(function(userInfo){
//更新数据
that.setData({
userInfo:userInfo
})
})
//异步获取缓存session_id
wx.getStorage({
key: 'session_id',
success: function(res) {
that.setData({
session_id:res.data
})
that.get_info(options.id);
}
})
that.setData({
dataid:options.id
})
},
//生命周期函数--监听页面初次渲染完成
onReady: function() {
// Do something when page ready.
},
//生命周期函数--监听页面显示
onShow: function() {
// Do something when page show.
if(this.data.requestlock==false)
{
this.get_info(this.data.dataid);
}
else
{
this.setData({
requestlock:false
})
}
},
//生命周期函数--监听页面隐藏
onHide: function() {
// Do something when page hide.
},
//生命周期函数--监听页面卸载
onUnload: function() {
// Do something when page close.
},
//页面相关事件处理函数--监听用户下拉动作
onPullDownRefresh: function() {
// Do something when pull down.
this.get_info(this.data.dataid,"onPullDownRefresh");
},
//页面上拉触底事件的处理函数
onReachBottom: function() {
// Do something when page reach bottom.
},
//导航处理函数
bindNavigateTo: function(action)
{
app.bindNavigateTo(action.target.dataset.action,action.target.dataset.params)
},
//页面打开导航处理函数
bindRedirectTo: function(action)
{
app.bindRedirectTo(action.target.dataset.action,action.target.dataset.params)
},
//跳转到 tabBar 页面
bindSwitchTo: function(action)
{
app.bindSwitchTo(action.target.dataset.action)
},
//获取详情数据
get_info: function(id,actionway="")
{
var that = this
var post_data={token:app.globalData.token,session_id:that.data.session_id,id:id}
app.action_loading();
app.func.http_request_action(app.globalData.domainName+app.globalData.api.api_businesscard_info,post_data,function(resback){
if(resback.status==1)
{
app.action_loading_hidden();
that.setData({
infodata:resback.resource
})
if(actionway=="onPullDownRefresh")
{
setTimeout(function(){
wx.stopPullDownRefresh()
},800)
}
}
else
{
app.action_loading_hidden();
var msgdata=new Object
msgdata.totype=3
msgdata.msg=resback.info
app.func.showToast_default(msgdata);
//console.log('获取用户登录态失败!' + resback.info);
}
})
},
//删除请求
del_action:function(action)
{
var that = this
var post_data={token:app.globalData.token,session_id:that.data.session_id,actiondata:action.target.dataset}
app.func.showModal("确定要执行删除?",function(resback){
if(resback.confirm)
{
app.func.http_request_action(app.globalData.domainName+app.globalData.api.api_del,post_data,function(resback){
if(resback.status==1)
{
var msgdata=new Object
msgdata.totype=3
msgdata.msg=resback.info
app.func.showToast_success(msgdata);
}
else
{
var msgdata=new Object
msgdata.totype=3
msgdata.msg=resback.info
app.func.showToast_default(msgdata);
//console.log('获取用户登录态失败!' + resback.info);
}
})
}
else
{
var msgdata=new Object
msgdata.url=""
msgdata.msg="取消"
app.func.showToast_default(msgdata);
}
})
},
//拨号请求
makePhoneCall:function(action)
{
app.func.makePhoneCall(action.target.dataset.phoneNumber)
},
}
Page(config)
|
v = JSONSchema({
k1: {
type: String
},
k2: {
type: Number
},
k3: {
type: Boolean
},
k4: [{
x: {
type: Number
},
y: {
type: String
}
}],
k5: {
type: Date
},
k6: {
x: {
type: Boolean
},
y: {
type: Date
},
z: {
m: {
type: String
},
n: {
type: Date
}
}
}
});
r = v.validate({
k1: '1',
k2: 10,
k3: true,
k4: [{
x: 10,
y: "sdf"
},
{
x: '20',
y: "sdgfds"
}
],
k5: new Date(),
k6: {
x: false,
y: new Date(),
z: {
n: "sdfgfdg",
m: new Date()
}
}
})
console.log(r);
|
import color from 'color';
import { Platform } from 'react-native';
/* This is an example of a theme */
export default {
// Badge
badgeBg: '#ED1727',
badgeColor: '#fff',
// Button
btnFontFamily: (Platform.OS === 'ios') ? 'HelveticaNeue' : 'Roboto_medium',
btnDisabledBg: '#b5b5b5',
btnDisabledClr: '#f1f1f1',
get btnPrimaryBg() {
return this.brandPrimary;
},
get btnPrimaryColor() {
return this.inverseTextColor;
},
get btnInfoBg() {
return this.brandInfo;
},
get btnInfoColor() {
return this.inverseTextColor;
},
get btnSuccessBg() {
return this.brandSuccess;
},
get btnSuccessColor() {
return this.inverseTextColor;
},
get btnDangerBg() {
return this.brandDanger;
},
get btnDangerColor() {
return this.inverseTextColor;
},
get btnWarningBg() {
return this.brandWarning;
},
get btnWarningColor() {
return this.inverseTextColor;
},
get btnTextSize() {
return (Platform.OS === 'ios') ? this.fontSizeBase * 1.1 :
this.fontSizeBase - 1;
},
get btnTextSizeLarge() {
return this.fontSizeBase * 1.5;
},
get btnTextSizeSmall() {
return this.fontSizeBase * 0.8;
},
get borderRadiusLarge() {
return this.fontSizeBase * 3.8;
},
buttonPadding: 6,
get iconSizeLarge() {
return this.iconFontSize * 1.5;
},
get iconSizeSmall() {
return this.iconFontSize * 0.6;
},
// Card
cardDefaultBg: '#fff',
// Check Box
checkboxBgColor: '#039BE5',
checkboxSize: 23,
checkboxTickColor: '#fff',
// Color
brandPrimary: '#5067FF',
brandInfo: '#5bc0de',
brandSuccess: '#5cb85c',
brandDanger: '#d9534f',
brandWarning: '#f0ad4e',
brandSidebar: '#252932',
// Font
fontFamily: (Platform.OS === 'ios') ? 'HelveticaNeue' : 'Roboto',
fontSizeBase: 15,
get fontSizeH1() {
return this.fontSizeBase * 1.8;
},
get fontSizeH2() {
return this.fontSizeBase * 1.6;
},
get fontSizeH3() {
return this.fontSizeBase * 1.4;
},
// Footer
footerHeight: 55,
footerDefaultBg: (Platform.OS === 'ios') ? '#F8F8F8' : '#4179F7',
// FooterTab
tabBarTextColor: (Platform.OS === 'ios') ? '#6b6b6b' : '#b3c7f9',
tabBarActiveTextColor: (Platform.OS === 'ios') ? '#007aff' : '#fff',
tabActiveBgColor: (Platform.OS === 'ios') ? '#cde1f9' : undefined,
// Header
iosToolbarBtnColor: '#007aff',
toolbarDefaultBg: (Platform.OS === 'ios') ? '#F8F8F8' : '#4179F7',
toolbarHeight: (Platform.OS === 'ios') ? 64 : 56,
toolbarIconSize: (Platform.OS === 'ios') ? 20 : 22,
toolbarInputColor: '#CECDD2',
toolbarInverseBg: '#222',
toolbarTextColor: (Platform.OS === 'ios') ? '#000' : '#fff',
get statusBarColor() {
return color(this.toolbarDefaultBg).darken(0.2).hexString();
},
// Icon
iconFamily: 'Ionicons',
iconFontSize: (Platform.OS === 'ios') ? 30 : 28,
iconMargin: 7,
// InputGroup
inputFontSize: 15,
inputBorderColor: '#D9D5DC',
inputSuccessBorderColor: '#2b8339',
inputErrorBorderColor: '#ed2f2f',
get inputColor() {
return this.textColor;
},
get inputColorPlaceholder() {
return '#575757';
},
inputGroupMarginBottom: 10,
inputHeightBase: 40,
inputPaddingLeft: 5,
get inputPaddingLeftIcon() {
return this.inputPaddingLeft * 8;
},
// Line Height
btnLineHeight: 19,
lineHeightH1: 32,
lineHeightH2: 27,
lineHeightH3: 22,
iconLineHeight: (Platform.OS === 'ios') ? 37 : 30,
lineHeight: (Platform.OS === 'ios') ? 20 : 24,
// List
listBorderColor: '#ddd',
listDividerBg: '#ddd',
listItemHeight: 45,
listItemPadding: 9,
listNoteColor: '#808080',
listNoteSize: 13,
// Progress Bar
defaultProgressColor: '#E4202D',
inverseProgressColor: '#1A191B',
// Radio Button
radioBtnSize: (Platform.OS === 'ios') ? 25 : 23,
radioColor: '#7e7e7e',
get radioSelectedColor() {
return color(this.radioColor).darken(0.2).hexString();
},
// Spinner
defaultSpinnerColor: '#45D56E',
inverseSpinnerColor: '#1A191B',
// Tabs
tabBgColor: '#F8F8F8',
tabFontSize: 15,
tabTextColor: '#fff',
// Text
textColor: '#000',
inverseTextColor: '#fff',
// Title
titleFontSize: (Platform.OS === 'ios') ? 17 : 19,
subTitleFontSize: (Platform.OS === 'ios') ? 12 : 14,
subtitleColor: '#8e8e93',
// Other
borderRadiusBase: (Platform.OS === 'ios') ? 5 : 2,
borderWidth: 1,
contentPadding: 10,
get darkenHeader() {
return color(this.tabBgColor).darken(0.03).hexString();
},
dropdownBg: '#000',
dropdownLinkColor: '#414142',
inputLineHeight: 24,
jumbotronBg: '#C9C9CE',
jumbotronPadding: 30,
};
|
'use strict';
var _ = require('lodash');
var request = require('request');
var VERSION = require('../package.json').version;
var REST_BASE_URL = 'https://api.spike.cc/v1/';
/**
* SpikeAPI
*/
function SpikeAPI(options) {
this.options = _.assign({
secretKey: '',
publishableKey: ''
}, options);
this.requestDefaults = {
auth: {
user: this.options.secretKey,
pass: ''
},
headers: {
'Accept': '*/*',
'Connection': 'close',
'User-Agent': 'node-spike-api/' + VERSION
},
json: true
};
}
/**
* Create a new charge by REST API.
* @param {object} chargeData Data of charge.
* @param {function} callback function(err, result)
*/
SpikeAPI.prototype.postCharge = function(chargeData, callback) {
chargeData = _.assign({
currency: '', // Currency billing amount. ['USD'|'JPY']
amount: 0, // Amount of the billing.
card: '', // Token that has been acquired in SPIKE Checkout.
products: [] // Array of Product instance for billing.
}, chargeData);
// validate argments
var isValid = _validateArgs([
'String', 'Number', 'String', 'Array', 'Function'
], [
chargeData.currency,
chargeData.amount,
chargeData.card,
chargeData.products,
callback
]);
if (isValid !== true) {
return isValid.callback(isValid.err);
}
var url = REST_BASE_URL + 'charges';
// create form data
var formData = {
amount: chargeData.amount,
currency: chargeData.currency,
card: chargeData.card,
products: JSON.stringify(chargeData.products)
};
var options = _.assign(this.requestDefaults, {
form: formData
});
// post API
this._request('post', url, options, callback);
};
/**
* Get a charge info by REST API.
* @param {string} id Charge ID.
* @param {function} callback function(err, result)
*/
SpikeAPI.prototype.getCharge = function(id, callback) {
// validate argments
var isValid = _validateArgs([
'String', 'Function'
], arguments);
if (isValid !== true) {
return isValid.callback(isValid.err);
}
var url = REST_BASE_URL + 'charges/' + id;
var options = this.requestDefaults;
// get API
this._request('get', url, options, callback);
};
/**
* Refund the charge of specified ID by REST API.
* @param {string} id charge id.
* @param {function} callback function(err, result)
*/
SpikeAPI.prototype.refundCharge = function(id, callback) {
// validate argments
var isValid = _validateArgs([
'String', 'Function'
], arguments);
if (isValid !== true) {
return isValid.callback(isValid.err);
}
var url = REST_BASE_URL + 'charges/' + id + '/refund';
var options = this.requestDefaults;
// post API
this._request('post', url, options, callback);
};
/**
* Get a charge list by REST API.
* @param {number} limit Acquisition number of list.
* @param {function} callback function(err, result)
*/
SpikeAPI.prototype.getChargeList = function(limit, callback) {
// validate argments
if (_.isFunction(limit)) {
callback = limit;
limit = 10;
}
var isValid = _validateArgs([
'Number', 'Function'
], arguments, 1);
if (isValid !== true) {
return isValid.callback(isValid.err);
}
var url = REST_BASE_URL + 'charges?limit=' + limit;
var options = this.requestDefaults;
// get API
this._request('get', url, options, callback);
};
/**
* Create a new token by REST API.
* @param {object} cardData Data of card.
* @param {function} callback function(err, result)
*/
SpikeAPI.prototype.postToken = function(cardData, callback) {
cardData = _.assign({
'card[number]': 4444333322221111, // Number of credit card
'card[exp_month]': 1, // Expire month of credit card
'card[exp_year]': 2020, // Expire year of credit card
'card[cvc]': 111, // Cvc of credit card
'card[name]': '', // Name of credit card holder
'currency': 'JPY', // Currency code
'email': '' // Email of credit card holder
}, cardData);
// validate argments
var isValid = _validateArgs([
'Number',
'Number',
'Number',
'Number',
'String',
'String',
'String',
'Function'
], [
cardData['card[number]'],
cardData['card[exp_month]'],
cardData['card[exp_year]'],
cardData['card[cvc]'],
cardData['card[name]'],
cardData.currency,
cardData.email,
callback
]);
if (isValid !== true) {
return isValid.callback(isValid.err);
}
var url = REST_BASE_URL + 'tokens';
var options = _.assign(this.requestDefaults, {
form: cardData
});
// post API
this._request('post', url, options, callback);
};
/**
* Return token information of specified token ID by REST API.
* @param {string} id token id
* @param {function} callback function(err, result)
*/
SpikeAPI.prototype.getToken = function(id, callback) {
// validate argments
var isValid = _validateArgs([
'String', 'Function'
], arguments);
if (isValid !== true) {
return isValid.callback(isValid.err);
}
var url = REST_BASE_URL + 'tokens/' + id;
var options = this.requestDefaults;
// get API
this._request('get', url, options, callback);
};
// Request API
SpikeAPI.prototype._request = function(method, url, options, callback) {
method = method.toLowerCase();
request[method](url, options, function(err, res, body) {
if (err) {
return callback(err);
}
if (res.statusCode >= 400) {
return callback(new Error(res.headers.status), body);
}
return callback(null, body);
});
};
// validate argments
function _validateArgs(argTypes, args, minArgs) {
var isInvalid = false;
minArgs = _.isNumber(minArgs) ? minArgs : argTypes.length;
if (args.length < minArgs) {
return _returnError(args);
}
for(var i = 0, l = argTypes.length; i < l; i++) {
var argType = argTypes[i];
var arg = args[i];
if (args.length === argTypes.length && !_['is' + argType](arg)) {
isInvalid = true;
break;
}
}
if (isInvalid) {
return _returnError(args);
} else {
return true;
}
}
function _returnError(args) {
var err = new Error('Invalid argments.');
var callback = null;
_.each(args, function(arg) {
if (_.isFunction(arg)) {
callback = arg;
}
});
if (_.isFunction(callback)) {
return {
callback: callback,
err: err
};
} else {
throw err;
}
}
/**
* Product
*/
function Product(attrs) {
this.attrs = _.assign({
id: '',
title: '',
description: '',
language: 'EN',
price: 0,
currency: '',
count: 0,
stock: 0
}, attrs);
}
/**
* getter
* @param {string} attr Name of attribute.
* @returns {stirng|number} Value of attribute.
*/
Product.prototype.get = function(attr) {
return this.attrs[attr];
};
/**
* setter
* @param {string} attr Name of attribute.
* @param {string|number} value Value of attribute.
*/
Product.prototype.set = function(attr, value) {
if (!_.isUndefined(this.attrs[attr])) {
this.attrs[attr] = value;
}
};
/**
* return JSON Object
* @returns {object} JSON Object
*/
Product.prototype.toJSON = function() {
return this.attrs;
};
// exports
module.exports = {
SpikeAPI: SpikeAPI,
Product: Product
};
|
var translattionTable = {
"search": "Buscar",
"emptyTable": "",
"decimal": "",
"info": "Mostrando _START_ a _END_ de _TOTAL_ entradas",
"infoEmpty": "",
"infoFiltered": "(filtradas de _MAX_ entradas)",
"infoPostFix": "",
"thousands": ",",
"lengthMenu": "Mostrar _MENU_",
"loadingRecords": "Cargando...",
"processing": "Procesando...",
"zeroRecords": "",
"paginate": {
"first": "Primera",
"last": "Última",
"next": ">",
"previous": "<"
}
};
|
'use strict';
const { expect } = require('chai');
const _ = require('lodash');
const sinon = require('sinon');
const run = require('../../../src/lib/run');
describe('Command runner library', () => {
describe('run method', () => {
const data = [
{
name: 'first',
words: ['foo', 'bar'],
},
{
name: 'second',
words: ['baz', 'quux'],
},
];
it('should handle a basic expression', () => {
expect(run.run(data, '["foo"]')).to.eql(['foo']);
});
it('should handle an object', () => {
expect(
run.run(data, '{"foo": "bar"}')
).to.eql({ foo: 'bar' });
});
describe('provided variables to the command', () => {
it('should include parsed data as "d"', () => {
expect(
run.run(data, '{"word": d[1].words[0]}')
).to.eql({ word: 'baz' });
});
it('should include the chain as "c"', () => {
expect(
run.run(data, 'c.get(0).value()')
).to.eql(data[0]);
});
it('should include lodash as "_"', () => {
expect(
run.run(data, 'c.get("0.words").map(_.capitalize).value()')
).to.eql(['Foo', 'Bar']);
});
describe('"p"', () => {
beforeEach(() => {
sinon.spy(console, 'json');
});
afterEach(() => {
console.json.restore();
});
it('should include console.json as "p"', () => {
// console.json does not document its return value,
// so don't test for it
run.run(data, 'p(d)');
sinon.assert.calledOnce(console.json);
sinon.assert.calledWithExactly(console.json, data);
});
it('should return the first item passed to it', () => {
expect(
run.run(data, 'p(d,d)')
).to.eql(data);
});
});
it('should not include other variables leaked into scope', () => {
expect(
_.bind(run.run, run, data, 'command')
).to.throw();
});
});
});
});
|
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync');
function isOnlyChange(event) {
return event.type === 'changed';
}
module.exports = function(options) {
var watch = function(srcDir, watchOptions) {
return function() {
if (!watchOptions) {
watchOptions = {};
}
watchOptions.watchSrcLess = watchOptions.watchSrcLess || true;
watchOptions.watchSrcHtml = watchOptions.watchSrcHtml || true;
watchOptions.srcJs = watchOptions.srcJs || '/**/*.js';
gulp.watch([options.app + '/*.html', 'bower.json'], ['inject']);
if (watchOptions.watchSrcLess) {
gulp.watch([
srcDir + '/**/*.less'
], function(event) {
if(isOnlyChange(event)) {
gulp.start('styles');
} else {
gulp.start('inject');
}
});
}
gulp.watch([srcDir + watchOptions.srcJs, options.app + '/**/*.js'], function(event) {
if(isOnlyChange(event)) {
gulp.start('scripts');
} else {
gulp.start('inject');
}
});
var htmlToWatch = [options.app + '/*.html'];
if (watchOptions.watchSrcHtml) {
htmlToWatch.push(srcDir + '/**/*.html');
}
return gulp.watch(htmlToWatch, function(event) {
browserSync.reload(event.path);
});
};
};
gulp.task('watch', ['inject'], watch(options.src));
gulp.task('watch:dist', ['inject:dist'], watch(options.dist, {watchSrcLess: false, watchSrcHtml: false, srcJs: 'angular-notification-icons.js'}));
gulp.task('watch:dist:min', ['inject:dist:min'], watch(options.dist, {watchSrcLess: false, watchSrcHtml: false, srcJs: 'angular-notification-icons.min.js'}));
};
|
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var UIEle = Class.$extend({
__classvars__ : {
UI_ELEMENT_TABLE : [],
UI_POPUP_TABLE : [],
UI_OPEN_POPUP : undefined
},
__init__ : function(dom) {
this.dom_jq = $(dom);
UIEle.UI_ELEMENT_TABLE.push(this);
},
UIEleHovered : function(event) {
//$(event.delegateTarget).css("cursor","pointer");
////console.debug(event.data.$this.testvar)
},
UIEleUnhovered : function(event) {
//$(event.delegateTarget).css("cursor","auto");
////console.debug(event.data.$this.testvar)
},
UIEleClicked : function(event) {
/*$this = event.data.$this;
if ( $this instanceof UIMenubarEle ) {
//console.debug("menu bar");
}
else if ( $this instanceof UIPopupEle ) {
//console.debug("popup");
}*/
////console.debug(event.data.$this.testvar)
}
});
var UIMenubar = UIEle.$extend({
__init__ : function(dom, data_target) {
this.$super(dom);
this.menus = [];
mb = this;
this.dom_jq.children(".menu_bar_item").each(function( index ) {
mb.menus.push(new UIMenubarPopup(this, mb));
});
this.data_target = data_target;
}
});
var UIPopup = UIEle.$extend({
__init__ : function(dom) {
this.$super(dom);
this.dom_jq.append( "<div class=\"popup_window\"></div>" );
this.dom_jq.children(".popup_window").append( this.dom_jq.children("ul") );
this.dom_jq.children("ul").remove();
this.dom_jq.mouseenter({$this:this}, this.UIEleHovered);
this.dom_jq.mouseleave({$this:this}, this.UIEleUnhovered);
this.dom_jq.click({$this:this}, this.UIEleClicked);
$("html").click(this.clickOutside);
$(window).resize(this.resizeWindow);
// initilaize all of the sub menu items
pu = this;
this.dom_jq.find("li").each(function(index){
if (!$(this).hasClass("disabled") && !$(this).hasClass("active") ) {
pu.setSubStatus($(this), "on");
}
});
this.fade_duration = 50;
UIEle.UI_POPUP_TABLE.push(this);
},
setSubStatus : function(sub_item, status) {
switch ( status ) {
case "on":
sub_item.mouseenter({$this:this}, this.UIEleSubHovered);
sub_item.mouseleave({$this:this}, this.UIEleSubUnhovered);
sub_item.click({$this:this}, this.UIEleSubClicked);
if ( sub_item.hasClass("disabled") )
sub_item.removeClass("disabled");
if ( sub_item.hasClass("active") )
sub_item.removeClass("active");
break;
case "disabled":
if ( sub_item.hasClass("active") )
sub_item.removeClass("active");
if ( !sub_item.hasClass("disabled") )
sub_item.addClass("disabled");
sub_item.off("click");
sub_item.off("mouseenter");
sub_item.off("mouseleave");
break;
case "active":
if ( sub_item.hasClass("disabled") )
sub_item.removeClass("disabled");
if ( sub_item.hasClass("active") )
sub_item.addClass("active");
sub_item.off("click");
sub_item.off("mouseenter");
sub_item.off("mouseleave");
break;
}
},
UIEleSubHovered : function(event) {
$(event.delegateTarget).css("cursor","pointer");
$(event.delegateTarget).addClass("hovered");
},
UIEleSubUnhovered : function(event) {
$(event.delegateTarget).css("cursor","auto");
$(event.delegateTarget).removeClass("hovered");
},
UIEleSubClicked : function(event) {
event.stopPropagation();
$this = event.data.$this;
$(event.delegateTarget).removeClass("hovered");
setTimeout(function() {
$(event.delegateTarget).addClass("active");
setTimeout(function() {
$(event.delegateTarget).removeClass("active");
$this.hidePopup();
$this.doAction(event);
},100);
},100);
},
clickOutside : function(event) {
if ( UIEle.UI_OPEN_POPUP )
UIEle.UI_OPEN_POPUP.hidePopup();
},
resizeWindow : function(event) {
if ( UIEle.UI_OPEN_POPUP ) {
UIEle.UI_OPEN_POPUP.positionPopup();
}
},
UIEleHovered : function(event) {
$this = event.data.$this;
$(event.delegateTarget).css("cursor","pointer");
if ( UIEle.UI_OPEN_POPUP != $this )
$(event.delegateTarget).addClass("hovered");
},
UIEleUnhovered : function(event) {
$this = event.data.$this;
$(event.delegateTarget).css("cursor","auto");
if ( UIEle.UI_OPEN_POPUP != $this )
$(event.delegateTarget).removeClass("hovered");
},
UIEleClicked : function(event) {
event.stopPropagation();
$this = event.data.$this;
if ( UIEle.UI_OPEN_POPUP ) {
if ( UIEle.UI_OPEN_POPUP == $this ) {
UIEle.UI_OPEN_POPUP.hidePopup();
} else {
UIEle.UI_OPEN_POPUP.hidePopup($this);
}
} else {
$this.showPopup();
}
},
hidePopup : function(calling_obj) {
//$this = this;
UIEle.UI_OPEN_POPUP.dom_jq.removeClass("active");
UIEle.UI_OPEN_POPUP.active_popup_jq.fadeOut( UIEle.UI_OPEN_POPUP.fade_duration, function() {
UIEle.UI_OPEN_POPUP.active_popup_jq.remove();
UIEle.UI_OPEN_POPUP.active_popup_jq = undefined;
UIEle.UI_OPEN_POPUP = undefined;
if ( calling_obj )
calling_obj.showPopup();
});
},
showPopup : function() {
UIEle.UI_OPEN_POPUP = this;
this.dom_jq.removeClass("hovered");
this.dom_jq.addClass("active");
// clone the menu item
this.active_popup_jq = this.dom_jq.children(".popup_window").clone(true, true).appendTo("#uber");
this.active_popup_jq.fadeIn($this.fade_duration);
this.active_popup_jq.css({"position":"absolute"});
this.positionPopup();
},
positionPopup : function() {
if ( this.dom_jq.offset().left + this.active_popup_jq.outerWidth() >= $(window).width() ) {
//the popup will appear off the right edge of the window
//align the right edge of the popup with the right edge of the parent element
left = this.dom_jq.offset().left + this.dom_jq.outerWidth() - this.active_popup_jq.outerWidth();
} else {
//position the popup normally
////align the left edge of the popup with the left edge of the parent element
left = this.dom_jq.offset().left;
}
if ( this.dom_jq.offset().top + this.dom_jq.outerHeight() + this.active_popup_jq.outerHeight() >= $(window).height() ) {
//the popup will appear off the bottom of the screen
//align the bottom of the popup with the bottom of the parent element
top = this.dom_jq.offset().top + this.dom_jq.outerHeight() - this.active_popup_jq.outerHeight();
} else {
//position the popup normally
//align the top of the popup with the bottom of the parent element
top = this.dom_jq.offset().top + this.dom_jq.outerHeight();
}
this.active_popup_jq.offset({ top: top, left: left });
}
});
var UIMenubarPopup = UIPopup.$extend({
__init__ : function(dom, parent_menubar) {
this.$super(dom);
this.parent_menubar = parent_menubar;
this.name = this.dom_jq.children("p").text();
//This is for testing
/*
action = this.dom_jq.find(".menu_bar_action");
if (action.hasClass('dialog'))
new UIModalDialog(action);
*/
},
doAction : function(event) {
action = $(event.delegateTarget).children(".menu_bar_action");
////console.debug(action.hasClass('dialog'));
//link = $(event.delegateTarget).children(".menu_bar_link");
if (action.hasClass('dialog'))
new UIModalDialog(action);
if (action.hasClass('link'))
document.location.href = action.children("a").attr("href");
},
showPopup : function() {
this.$super();
////console.debug(this.name);
if ( this.name == "Action" ) {
if ( Object.size(this.parent_menubar.data_target.server_data.selected) > 0 ) {
this.setSubStatus(this.active_popup_jq.find(".disabled"), "on");
}
}
////console.debug(Object.size(this.parent_menubar.data_target.server_data.selected));
}
});
var UIButton = UIEle.$extend({
__init__ : function(dom, callBack, callBackParams) {
this.$super(dom);
this.callBack = callBack;
////console.debug(data);
this.callBackParams = callBackParams;
this.dom_jq.mouseenter({$this:this}, this.UIEleHovered);
this.dom_jq.mouseleave({$this:this}, this.UIEleUnhovered);
this.dom_jq.click({$this:this}, this.UIEleClicked);
},
UIEleHovered : function(event) {
$(event.delegateTarget).css("cursor","pointer");
$(event.delegateTarget).addClass("hovered");
},
UIEleUnhovered : function(event) {
$(event.delegateTarget).css("cursor","auto");
$(event.delegateTarget).removeClass("hovered");
},
UIEleClicked : function(event) {
$this = event.data.$this;
$this.callBack($this.callBackParams);
}
});
var UICheckbox = UIEle.$extend({
__init__ : function(dom, callBack, callBackParams) {
//build the checkbox. this will be sent to the UIEle init
name = $(dom).attr("name");
label_text = $(dom).siblings("label").text();
$(dom).after("<div class=\"checkbox\"><div class=\"checkbox_box\"></div><div class=\"checkbox_label\">{{label text}}</div></div>".replace("{{label text}}",label_text));
new_dom = $(dom).siblings(".checkbox");
$(dom).siblings("label").remove();
$(dom).remove();
//now call the super with the new dom element.
this.$super(new_dom);
this.callBack = callBack;
this.name = name;
this.selected = false;
this.callBackParams = callBackParams;
this.dom_jq.mouseenter({$this:this}, this.UIEleHovered);
this.dom_jq.mouseleave({$this:this}, this.UIEleUnhovered);
this.dom_jq.click({$this:this}, this.UIEleClicked);
},
UIEleHovered : function(event) {
$(event.delegateTarget).css("cursor","pointer");
$(event.delegateTarget).addClass("hovered");
},
UIEleUnhovered : function(event) {
$(event.delegateTarget).css("cursor","auto");
$(event.delegateTarget).removeClass("hovered");
},
UIEleClicked : function(event) {
$this = event.data.$this;
if ( $this.selected ) {
$(event.delegateTarget).removeClass("selected");
$this.selected = false;
} else {
$(event.delegateTarget).addClass("selected");
$this.selected = true;
}
//$this.callBack($this.callBackParams);
}
});
var UIModalDialog = UIEle.$extend({
__init__ : function(dom) {
this.$super(dom);
// we always have these two
new UIButton(this.dom_jq.find( "[name='cancel']" ), this.doCancel, {$this:this});
new UIButton(this.dom_jq.find( "[name='go']" ), this.doGo, {$this:this});
//look for checkboxes
this.dom_jq.find( "[type='checkbox']" ).each( function (index) {
new UICheckbox(this);
});
$(window).resize({$this:this}, this.resizeWindow);
this.fade_duration = 100;
this.showDialog();
},
doCancel : function(params) {
$this = params.$this;
$this.hideDialog();
},
doGo : function(params) {
$this = params.$this;
//$this.hideDialog();
},
showDialog : function() {
// create an overlay to capture all events outside the dialog box
this.overlay = $("<div class=\"overlay\"></div>").appendTo("#uber");
this.overlay.css({"position":"absolute", "display":"none"});
this.overlay.offset(
{ top: 0,
left: 0
});
this.overlay.width($(window).width());
this.overlay.height($("html").height());
this.overlay.fadeIn($this.fade_duration);
// clone the menu item
this.active_dialog = this.dom_jq.clone(true, true).appendTo("#uber");
this.active_dialog.fadeIn(this.fade_duration);
this.active_dialog.css({"position":"absolute"});
this.positionDialog();
},
hideDialog : function() {
this.active_dialog.fadeOut(this.fade_duration);
$this = this;
this.overlay.fadeOut(this.fade_duration, function() {
$this.active_dialog.remove();
$this.overlay.remove();
});
},
positionDialog : function() {
this.active_dialog.offset(
{ top: $(window).height()/2.0 - this.active_dialog.outerHeight()/2.0,
left: $(window).width()/2.0 - this.active_dialog.outerWidth()/2.0
});
},
resizeWindow : function(event) {
$this = event.data.$this;
$this.positionDialog();
}
});
var UISingleSelectPopup = UIPopup.$extend({
__init__ : function(dom, callBack, callBackParams) {
this.$super(dom);
this.callBackParams = callBackParams;
this.setSelection(this.dom_jq.find(".selected").text());
this.callBack = callBack;
},
setSelection : function(value) {
selection = this.dom_jq.children("p");
if ( selection.length == 0 ) {
this.dom_jq.append("<p>"+value+"</p>");
} else {
this.dom_jq.children("p").text(value);
}
//this.dom_jq.append("<p>"+value+"</p>");
this.callBackParams.selection = value;
},
doAction : function(event) {
this.setSelection($(event.delegateTarget).text());
this.callBack(this.callBackParams);
}
});
|
app.controller('gregorianToJalaliCrtl', function($scope,dateConvertor) {
/**
* validate date
* @returns {undefined}
*/
$scope.allValidation = function () {
$scope.validateGregorianYear();
$scope.validateGregorianMonth();
$scope.validateGregorianDay();
}
/**
* convert date
* @returns {undefined}
*/
$scope.convert = function () {
$scope.allValidation();
if(!$scope.greToShFrm.$invalid) {
// convert to jalali date
var date=dateConvertor.gregorianToJalali($scope.fromGreToShYear,$scope.fromGreToShMonth,$scope.fromGreToShDay);
// showing converted date
$scope.setConvertedDate(date[2]+' '+dateConvertor.getMonthName(date[1],'jalali')+' '+date[0]);
}
}
/**
* validate gregorian year
* @returns {undefined}
*/
$scope.validateGregorianYear = function() {
var result=true;
var yearValue=$scope.fromGreToShYear;
var itemInvalid=false;
var formInvalid=false;
if(!yearValue) {
$scope.fromGreToShYearMessage='سال را وارد نمائید';
itemInvalid=true;
formInvalid=true;
result=false;
}
if(yearValue <= 0) {
$scope.fromGreToShYearMessage='سال را صحیح وارد نمائید';
itemInvalid=true;
formInvalid=true;
}
$scope.greToShFrm.fromGreToShYear.$invalid=itemInvalid;
$scope.greToShFrm.$invalid=formInvalid;
};
/**
* validate gregorian moth
* @returns {undefined}
*/
$scope.validateGregorianMonth = function () {
if(!$scope.greToShFrm.fromGreToShYear.$invalid) {
var result=true;
var itemInvalid=false;
var formInvalid=false;
var monthValue=$scope.fromGreToShMonth;
if(!monthValue) {
$scope.fromGreToShMonthMessage='ماه را وارد نمائید';
itemInvalid=true;
formInvalid=true;
result=false;
}
if(result && (monthValue < 1 || monthValue > 12)) {
$scope.fromGreToShMonthMessage='ماه باید عددی بین 1 تا 12 باشد';
itemInvalid=true;
formInvalid=true;
}
$scope.greToShFrm.fromGreToShMonth.$invalid=itemInvalid;
$scope.greToShFrm.$invalid=formInvalid;
}
};
/**
* validate gregorian day
* @returns {undefined}
*/
$scope.validateGregorianDay = function () {
if(!$scope.greToShFrm.fromGreToShYear.$invalid && !$scope.greToShFrm.fromGreToShMonth.$invalid) {
var result=true;
var itemInvalid=false;
var formInvalid=false;
var yearValue=$scope.fromGreToShYear;
var monthValue=$scope.fromGreToShMonth;
var dayValue=$scope.fromGreToShDay;
if(!dayValue) {
$scope.fromGreToShDayMessage='روز را وارد نمائید';
itemInvalid=true;
formInvalid=true;
result=false;
}
if(result) {
// var dayResult=true;
if(dayValue < 1 || dayValue > 31) {
$scope.fromGreToShDayMessage='روز باید عددی بین 1 تا 31 باشد';
itemInvalid=true;
formInvalid=true;
// dayResult=false;
}
}
$scope.greToShFrm.fromGreToShDay.$invalid=itemInvalid;
$scope.greToShFrm.$invalid=formInvalid;
}
};
/**
*
* set value of converted date
* @param {string} value
* @returns {undefined}
*/
$scope.setConvertedDate = function(value) {
$scope.convertedDate=value;
};
/**
* empty converted date
* @returns {undefined}
*/
$scope.emptyConvertedDate = function() {
$scope.convertedDate='';
};
});
|
import ProjectLibraryModel from './project-library.model';
let libraries = {
angular: new ProjectLibraryModel(1, 'Angular', require('../../../../images/logos/angular.svg')),
angularJS: new ProjectLibraryModel(2, 'AngularJS', require('../../../../images/logos/angularjs.png')),
jQuery: new ProjectLibraryModel(3, 'jQuery', require('../../../../images/logos/jquery.png')),
cordova: new ProjectLibraryModel(4, 'Cordova/PhoneGap', require('../../../../images/logos/cordova.png')),
materialDesignNG1: new ProjectLibraryModel(5, 'Material Design (AngularJS 1.x.x)', null),
firebase: new ProjectLibraryModel(6, 'Firebase PaaS', null),
dotNET: new ProjectLibraryModel(7, '.NET', null)
};
export default libraries;
|
// flow-typed signature: e9b84c500ccc61d64c1ca78e43399035
// flow-typed version: <<STUB>>/gatsby-link_v^1.6.35/flow_v0.68.0
/**
* This is an autogenerated libdef stub for:
*
* 'gatsby-link'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'gatsby-link' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
// Filename aliases
declare module 'gatsby-link/index' {
declare module.exports: $Exports<'gatsby-link'>;
}
declare module 'gatsby-link/index.js' {
declare module.exports: $Exports<'gatsby-link'>;
}
|
/// <reference path="../jquery-1.7.1-vsdoc.js" />
var Audio = {
//-- Functions
Initialize: function () {
Audio.player = $('audio').get(0);
$('#Audio_PlayButton').on('click', Audio.Handlers.Button.Play);
$('audio').on('ended', Audio.Handlers.Events.Ended);
$('audio').on('pause', Audio.Handlers.Events.Pause);
$('audio').on('play', Audio.Handlers.Events.Play);
$('audio').on('timeupdate', Audio.Handlers.Events.TimeUpdate);
},
Notify: function (title, text, sticky, time) {
$.gritter.add({
title: title,
text: text,
sticky: sticky,
time: time
});
},
Refresh: function () {
},
Source: function (dataURI) {
Audio.player.src = dataURI;
Audio.player.load();
return (Audio.player.src = dataURI);
},
Play: function () {
Audio.Handlers.Button.Play();
},
//-- Event Handlers
Handlers: {
Button: {
Play: function () {
if (Audio.player.paused) {
Audio.player.play();
}
else {
Audio.player.pause();
}
}
},
Events: {
Ended: function (e) {
$('#Audio_PlayButton > i').addClass('icon-play').removeClass('icon-pause');
},
Play: function (e) {
$('#Audio_PlayButton > i').removeClass('icon-play').addClass('icon-pause');
},
Pause: function (e) {
$('#Audio_PlayButton > i').addClass('icon-play').removeClass('icon-pause');
},
TimeUpdate: function (e) {
$('#Audio_Progress').css('width', e.target.currentTime / e.target.duration * 100 + '%');
}
}
},
//-- Settings & Persistence
Settings: {
},
//-- Internal Vars
player: null
};
|
"use strict";
const {XMLParser, XMLBuilder, XMLValidator} = require("../src/fxp");
const he = require("he");
describe("XMLParser", function() {
it("should parse attributes with valid names", function() {
const xmlData = `<issue _ent-ity.23="Mjg2MzY2OTkyNA==" state="partial" version="1"></issue>`;
const expected = {
"issue": {
"_ent-ity.23": "Mjg2MzY2OTkyNA==",
"state": "partial",
"version": 1
}
};
const options = {
attributeNamePrefix: "",
ignoreAttributes: false,
parseAttributeValue: true
};
const parser = new XMLParser(options);
let result = parser.parse(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
result = XMLValidator.validate(xmlData);
expect(result).toBe(true);
});
it("should parse attributes with newline char", function() {
const xmlData = `<element id="7" data="foo\nbar" bug="true"/>`;
const expected = {
"element": {
"id": 7,
"data": `foo\nbar`,
"bug": true
}
};
const options = {
attributeNamePrefix: "",
ignoreAttributes: false,
parseAttributeValue: true
};
const parser = new XMLParser(options);
let result = parser.parse(xmlData);
// console.log(JSON.stringify(result,null,4));
// expect(result).toEqual(expected);
result = XMLValidator.validate(xmlData);
expect(result).toBe(true);
});
it("should parse attributes separated by newline char", function() {
const xmlData = `<element
id="7" data="foo bar" bug="true"/>`;
const expected = {
"element": {
"id": 7,
"data": "foo bar",
"bug": true
}
};
const options = {
attributeNamePrefix: "",
ignoreAttributes: false,
parseAttributeValue: true
};
const parser = new XMLParser(options);
let result = parser.parse(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
result = XMLValidator.validate(xmlData);
expect(result).toBe(true);
});
it("should parse Boolean Attributes", function() {
const xmlData = `<element id="7" str="" data><selfclosing/><selfclosing /><selfclosingwith attr/></element>`;
const expected = {
"element": {
"id": 7,
"str": "",
"data": true,
"selfclosing": [
"",
""
],
"selfclosingwith": {
"attr": true
}
}
};
const options = {
attributeNamePrefix: "",
ignoreAttributes: false,
parseAttributeValue: true,
allowBooleanAttributes: true
};
const parser = new XMLParser(options);
let result = parser.parse(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
result = XMLValidator.validate(xmlData, {
allowBooleanAttributes: true
});
expect(result).toBe(true);
});
it("should not remove xmlns when namespaces are not set to be ignored", function() {
const xmlData = `<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"></project>`;
const expected = {
"project": {
"xmlns": "http://maven.apache.org/POM/4.0.0",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:schemaLocation": "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
}
};
const options = {
attributeNamePrefix: "",
ignoreAttributes: false
};
const parser = new XMLParser(options);
let result = parser.parse(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
result = XMLValidator.validate(xmlData, {
allowBooleanAttributes: true
});
expect(result).toBe(true);
});
it("should remove xmlns when namespaces are set to be ignored", function() {
const xmlData = `<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi-ns="http://www.w3.org/2001/XMLSchema-instance" xsi-ns:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"></project>`;
const expected = {
"project": {
//"xmlns": "http://maven.apache.org/POM/4.0.0",
//"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"schemaLocation": "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
}
};
const options = {
attributeNamePrefix: "",
ignoreAttributes: false,
removeNSPrefix: true
}
const parser = new XMLParser(options);
let result = parser.parse(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
result = XMLValidator.validate(xmlData, {
allowBooleanAttributes: true
});
expect(result).toBe(true);
});
it("should not parse attributes with name start with number", function() {
const xmlData = `<issue 35entity="Mjg2MzY2OTkyNA==" ></issue>`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "Attribute '35entity' is an invalid name.",
"line": 1,
"col": 8
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should not parse attributes with invalid char", function() {
const xmlData = `<issue enti+ty="Mjg2MzY2OTkyNA=="></issue>`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "Attribute 'enti+ty' is an invalid name.",
"line": 1,
"col": 8
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should not parse attributes in closing tag", function() {
const xmlData = `<issue></issue invalid="true">`;
const expected = {
"err": {
"code": "InvalidTag",
"msg": "Closing tag 'issue' can't have attributes or invalid starting.",
"line": 1,
"col": 8
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should err for invalid atributes", function() {
const xmlData = `<rootNode =''></rootNode>`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "Attribute '''' has no space in starting.",
"line": 1,
"col": 12
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should validate xml with atributes", function() {
const xmlData = `<rootNode attr="123"><tag></tag><tag>1</tag><tag>val</tag></rootNode>`;
const result = XMLValidator.validate(xmlData);
expect(result).toBe(true);
});
it("should validate xml atribute has '>' in value", function() {
const xmlData = `<rootNode attr="123>234"><tag></tag><tag>1</tag><tag>val</tag></rootNode>`;
const result = XMLValidator.validate(xmlData);
expect(result).toBe(true);
});
it("should not validate xml with invalid atributes", function() {
const xmlData = `<rootNode attr="123><tag></tag><tag>1</tag><tag>val</tag></rootNode>`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "Attributes for 'rootNode' have open quote.",
"line": 1,
"col": 10
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should not validate xml with invalid attributes when duplicate attributes present", function() {
const xmlData = `<rootNode abc='123' abc="567" />`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "Attribute 'abc' is repeated.",
"line": 1,
"col": 22
}
};
const result = XMLValidator.validate(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
});
it("should not validate xml with invalid attributes when no space between 2 attributes", function() {
const xmlData = `<rootNode abc='123'bc='567' />`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "Attribute 'bc' has no space in starting.",
"line": 1,
"col": 21
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should not validate a tag with attribute presents without value ", function() {
const xmlData = `<rootNode ab cd='ef'></rootNode>`;
const expected = {
"err": {
"code": "InvalidAttr",
"msg": "boolean attribute 'ab' is not allowed.",
"line": 1,
"col": 11
}
};
const result = XMLValidator.validate(xmlData);
expect(result).toEqual(expected);
});
it("should not validate xml with invalid attributes presents without value", function() {
const xmlData = `<rootNode 123 abc='123' bc='567' />`;
const expected = {
"err": {
"code": "InvalidAttr",
// "msg": "attribute 123 is an invalid name."
"msg": "boolean attribute '123' is not allowed.",
"line": 1,
"col": 12
}
};
const result = XMLValidator.validate(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
});
it("should validate xml with attributeshaving openquote in value", function () {
const xmlData = "<rootNode 123 abc='1\"23' bc=\"56'7\" />";
const expected = {
"err": {
"code": "InvalidAttr",
// "msg": "attribute 123 is an invalid name."
"msg": "boolean attribute '123' is not allowed.",
"line": 1,
"col": 12
}
};
const result = XMLValidator.validate(xmlData);
//console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
});
it("should parse and build with tag name 'attributes' ", function() {
const XMLdata = `
<test attr="test bug">
<a name="a">123</a>
<b name="b"/>
<attributes>
<attribute datatype="string" name="DebugRemoteType">dev</attribute>
<attribute datatype="string" name="DebugWireType">2</attribute>
<attribute datatype="string" name="TypeIsVarchar">1</attribute>
</attributes>
</test>`;
const options = {
ignoreAttributes: false,
format: true,
preserveOrder: true,
suppressEmptyNode: true,
unpairedTags: ["star"]
};
const parser = new XMLParser(options);
let result = parser.parse(XMLdata);
// console.log(JSON.stringify(result, null,4));
const builder = new XMLBuilder(options);
const output = builder.build(result);
// console.log(output);
expect(output.replace(/\s+/g, "")).toEqual(XMLdata.replace(/\s+/g, ""));
});
});
|
import express from 'express';
import helpers from '../helpers';
import controller from '../controllers/voteController';
const router = express.Router();
router.get('/', helpers.isAuth, controller.initialize, controller.canVoteUT100, (req, res) => {
res.locals.moduleTitle = 'Votar';
res.locals.module = () => 'vote';
res.locals.active = {
vote: true
};
res.render('index');
});
router.get('/ultratop100', controller.initialize, controller.verifyRewardUT100, controller.handleRewardUT100);
export default router;
|
var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
var fs = require('fs');
var path = require('path');
exports.up = function(db, callback) {
var filePath = path.join(__dirname + '/sqls/20160708081226-readme-in-versions-up.sql');
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
if (err) return callback(err);
console.log('received data: ' + data);
db.runSql(data, function(err) {
if (err) return callback(err);
callback();
});
});
};
exports.down = function(db, callback) {
var filePath = path.join(__dirname + '/sqls/20160708081226-readme-in-versions-down.sql');
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
if (err) return callback(err);
console.log('received data: ' + data);
db.runSql(data, function(err) {
if (err) return callback(err);
callback();
});
});
};
|
'use strict';
var Primus = require('primus')
, emitter = require('../')
, http = require('http').Server
, expect = require('expect.js')
, opts = { transformer: 'websockets' }
, primus
, srv;
// creates the client
function client(srv, primus, port){
var addr = srv.address();
var url = 'http://' + addr.address + ':' + (port || addr.port);
return new primus.Socket(url);
}
// creates the server
function server(srv, opts) {
return Primus(srv, opts).use('emitter', emitter);
}
describe('primus-emitter', function () {
beforeEach(function beforeEach(done) {
srv = http();
primus = server(srv, opts);
done();
});
afterEach(function afterEach(done) {
primus.end();
done();
});
it('should have required methods', function (done) {
//primus.save('testt.js');
srv.listen(function () {
primus.on('connection', function (spark) {
expect(spark.reserved).to.be.a('function');
expect(spark.send).to.be.a('function');
expect(spark.on).to.be.a('function');
done();
});
var cl = client(srv, primus);
expect(cl.reserved).to.be.a('function');
});
});
it('should emit event from server', function (done) {
srv.listen(function () {
primus.on('connection', function (spark) {
spark.send('news', 'data');
});
var cl = client(srv, primus);
cl.on('news', function (data) {
expect(data).to.be('data');
done();
});
});
});
it('should emit object from server', function (done) {
var msg = { hi: 'hello', num: 123456 };
srv.listen(function () {
primus.on('connection', function (spark) {
spark.send('news', msg);
});
var cl = client(srv, primus);
cl.on('news', function (data) {
expect(data).to.be.eql(msg);
done();
});
});
});
it('should support ack from server', function (done) {
var msg = { hi: 'hello', num: 123456 };
srv.listen(function () {
primus.on('connection', function (spark) {
spark.send('news', msg, function (err, res) {
expect(res).to.be('received');
expect(err).to.be.eql(null);
done();
});
});
var cl = client(srv, primus);
cl.on('news', function (data, fn) {
fn(null, 'received');
});
});
});
it('should emit event from client', function (done) {
srv.listen(function () {
primus.on('connection', function (spark) {
spark.on('news', function (data) {
expect(data).to.be('data');
done();
});
});
var cl = client(srv, primus);
cl.send('news', 'data');
});
});
it('should emit object from client', function (done) {
var msg = { hi: 'hello', num: 123456 };
srv.listen(function () {
primus.on('connection', function (spark) {
spark.on('news', function (data) {
expect(data).to.be.eql(msg);
done();
});
});
var cl = client(srv, primus);
cl.send('news', msg);
});
});
it('should support ack from client', function (done) {
var msg = { hi: 'hello', num: 123456 };
srv.listen(function () {
primus.on('connection', function (spark) {
spark.on('news', function (data, fn) {
fn(null, 'received');
});
});
var cl = client(srv, primus);
cl.send('news', msg, function (err, res) {
expect(res).to.be('received');
expect(err).to.be.eql(null);
done();
});
});
});
it('should support broadcasting from server', function (done) {
var total = 0;
srv.listen(function () {
primus.on('connection', function (spark) {
if (3 === ++total) primus.send('news', 'hi');
});
var cl1 = client(srv, primus)
, cl2 = client(srv, primus)
, cl3 = client(srv, primus);
cl1.on('news', function (msg) {
expect(msg).to.be('hi');
finish();
});
cl2.on('news', function (msg) {
expect(msg).to.be('hi');
finish();
});
cl3.on('news', function (msg) {
expect(msg).to.be('hi');
finish();
});
function finish() {
if (1 > --total) done();
}
});
});
it('should return `Primus` instance when broadcasting from server', function () {
expect(primus.send('news')).to.be.a(Primus);
srv.listen();
});
it('`Client#send` should not trigger `Spark` reserved events', function (done) {
var events = Object.keys(primus.Spark.prototype.reserved.events);
srv.listen(function () {
primus.on('connection', function (spark) {
events.forEach(function (ev) {
spark.on(ev, function (data) {
if ('not ignored' === data) {
done(new Error('should be ignored'));
}
});
});
});
});
var cl = client(srv, primus);
cl.on('open', function () {
events.forEach(function (ev) {
cl.send(ev, 'not ignored');
});
done();
});
});
it('`Spark#send` should not trigger client reserved events', function (done) {
srv.listen(function () {
primus.on('connection', function (spark) {
events.forEach(function (ev) {
spark.send(ev, 'not ignored');
});
done();
});
});
var cl = client(srv, primus)
, events = Object.keys(cl.reserved.events);
events.forEach(function (ev) {
cl.on(ev, function (data) {
if ('not ignored' === data) {
done(new Error('should be ignored'));
}
});
});
});
it('should only listen to event once when binding with `once`', function (done) {
srv.listen(function () {
primus.on('connection', function (spark) {
spark.once('news', function (data) {
expect(data).to.be('once');
done();
});
});
var cl = client(srv, primus);
cl.send('news', 'once');
cl.send('news', 'once');
});
});
});
|
import React from 'react';
import styled from 'styled-components';
const Emoji = ({ className, svg }) => (
<span className={className} dangerouslySetInnerHTML={{ __html: svg }} />
);
const StyledEmoji = styled(Emoji)`
display: inline-block;
width: 1.5em;
`;
export default StyledEmoji;
|
var opener = require("opener");
module.exports = {
run : function (){
opener(packageJson.docs);
}
}
|
import _curry3 from './internal/_curry3';
/**
* `o` is a curried composition function that returns a unary function.
* Like [`compose`](#compose), `o` performs right-to-left function composition.
* Unlike [`compose`](#compose), the rightmost function passed to `o` will be
* invoked with only one argument. Also, unlike [`compose`](#compose), `o` is
* limited to accepting only 2 unary functions. The name o was chosen because
* of its similarity to the mathematical composition operator ∘.
*
* @func
* @memberOf R
* @since v0.24.0
* @category Function
* @sig (b -> c) -> (a -> b) -> a -> c
* @param {Function} f
* @param {Function} g
* @return {Function}
* @see R.compose, R.pipe
* @example
*
* var classyGreeting = name => "The name's " + name.last + ", " + name.first + " " + name.last
* var yellGreeting = R.o(R.toUpper, classyGreeting);
* yellGreeting({first: 'James', last: 'Bond'}); //=> "THE NAME'S BOND, JAMES BOND"
*
* R.o(R.multiply(10), R.add(10))(-4) //=> 60
*
* @symb R.o(f, g, x) = f(g(x))
*/
var o = _curry3(function o(f, g, x) {
return f(g(x));
});
export default o;
|
/*
*--------------------------------------------------------------------
* jQuery-Plugin "lookupreferer -config.js-"
* Version: 3.0
* Copyright (c) 2018 TIS
*
* Released under the MIT License.
* http://tis2010.jp/license.txt
* -------------------------------------------------------------------
*/
jQuery.noConflict();
(function($,PLUGIN_ID){
"use strict";
var vars={
fieldtable:null,
fieldinfos:{}
};
var functions={
fieldsort:function(layout){
var codes=[];
$.each(layout,function(index,values){
switch (values.type)
{
case 'ROW':
$.each(values.fields,function(index,values){
/* exclude spacer */
if (!values.elementId) codes.push(values.code);
});
break;
case 'GROUP':
$.merge(codes,functions.fieldsort(values.layout));
break;
case 'SUBTABLE':
$.each(values.fields,function(index,values){
/* exclude spacer */
if (!values.elementId) codes.push(values.code);
});
break;
}
});
return codes;
}
};
/*---------------------------------------------------------------
initialize fields
---------------------------------------------------------------*/
kintone.api(kintone.api.url('/k/v1/app/form/layout',true),'GET',{app:kintone.app.getId()},function(resp){
var sorted=functions.fieldsort(resp.layout);
/* get fieldinfo */
kintone.api(kintone.api.url('/k/v1/app/form/fields',true),'GET',{app:kintone.app.getId()},function(resp){
var config=kintone.plugin.app.getConfig(PLUGIN_ID);
vars.fieldinfos=$.fieldparallelize(resp.properties);
$.each(sorted,function(index){
if (sorted[index] in vars.fieldinfos)
{
var fieldinfo=vars.fieldinfos[sorted[index]];
if (fieldinfo.lookup)
$('select#field').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label));
}
});
/* initialize valiable */
vars.fieldtable=$('.fields').adjustabletable({
add:'img.add',
del:'img.del'
});
var add=false;
var fields=[];
if (Object.keys(config).length!==0)
{
fields=JSON.parse(config['fields']);
for (var i=0;i<fields.length;i++)
{
if (add) vars.fieldtable.addrow();
else add=true;
$('select#field',vars.fieldtable.rows.last()).val(fields[i]);
}
}
},function(error){});
},function(error){});
/*---------------------------------------------------------------
button events
---------------------------------------------------------------*/
$('button#submit').on('click',function(e){
var row=null;
var config=[];
var fields=[];
/* check values */
for (var i=0;i<vars.fieldtable.rows.length;i++)
{
row=vars.fieldtable.rows.eq(i);
if ($('select#field',row).val().length==0) continue;
fields.push($('select#field',row).val());
}
if (fields.length==0)
{
swal('Error!','ルックアップアプリ表示フィールドは1つ以上指定して下さい。','error');
return;
}
/* setup config */
config['fields']=JSON.stringify(fields);
/* save config */
kintone.plugin.app.setConfig(config);
});
$('button#cancel').on('click',function(e){
history.back();
});
})(jQuery,kintone.$PLUGIN_ID);
|
// calculate the area of a circle based on its radius
function calcCircleArea(r) {
var area = Math.PI * Math.pow(r, 2); // area is pi times radius squared
return area;
}
console.log(calcCircleArea(35))
|
/*jslint node: true */
'use strict';
var dotenv = require ( 'dotenv' ).config(),
Promise = require ( 'bluebird' ),
_ = require ( 'lodash' ),
sprintf = require ( 'sprintf' ),
mysql = require ( 'mysql' ),
chalk = require ( 'chalk' );
// ////////////////////////////////////////////////////////////////////////////
//
// common requirements,
var constant_server_restapi = require ( '../common/constant_server_restapi' );
var _controllerBase = require ( './_controllerBase' )();
module.exports = function ( )
{
var vm = this || {};
vm._service_name = 'account';
var api =
{
ctor : ctor
};
function ctor ( central_relay, storage_agent, protect_agent, restapi_agent )
{
return _controllerBase.bind_ctor (
vm, service_init, service_name, central_relay,
storage_agent, protect_agent, restapi_agent
);
}
function service_name ( )
{
return vm._service_name;
}
function service_init ( )
{
return new Promise ( function ( resolve, reject )
{
var express = vm.restapi_agent.express_get ();
express.post ( '/v1/' + vm._service_name, on_restapi_post );
resolve ( true );
} );
}
/**
*
* @param req.body.accountId
*/
function fetch ( req, res, next )
{
var sp_script = sprintf ( 'CALL %s( %s );',
'sp_account_fetch',
mysql.escape ( req.body.accountId )
);
return _controllerBase.sp_exec ( req, res, next, vm, sp_script );
}
/**
*
* @param req.body.userName
* @param req.body.password
*/
function write ( req, res, next )
{
var account_salt = vm.protect_agent.compose_salt ( );
var account_hash = vm.protect_agent.encrypt_pass ( req.body.password, account_salt );
var sp_script;
sp_script = sprintf ( 'CALL %s( %s );',
'sp_account_fetch_user',
mysql.escape ( req.body.userName )
);
vm.storage_agent.connection_exec ( sp_script ).then (
function ( value )
{
var result_len = value[0].length;
if ( 0 < result_len )
{
return value;
} else
{
sp_script = sprintf ( 'CALL %s( %s, %s, %s );',
'sp_account_write',
mysql.escape ( req.body.userName ),
mysql.escape ( account_salt ),
mysql.escape ( account_hash )
);
return vm.storage_agent.connection_exec ( sp_script );
}
},
function ( error )
{
throw ( error );
}
).then (
function ( value )
{
var retval = _.omit ( value[0][0],
[
'accountId',
'salt',
'hash'
] );
return _controllerBase.request_status_send ( res, 200, retval );
},
function ( error )
{
return _controllerBase.request_status_send ( res, 400, error );
}
);
}
function accountToken_verify ( token )
{
return new Promise ( function ( resolve, reject )
{
var retval = vm.protect_agent.token_verify ( token );
resolve ( retval );
} );
}
function accountToken_write ( fetch_user_result )
{
return new Promise ( function ( resolve, reject )
{
var payload =
{
userName : fetch_user_result.userName
};
var jwt_token = vm.protect_agent.token_sign ( payload );
var sp_script = sprintf ( 'CALL %s( %s, %s );',
'sp_accountToken_write',
mysql.escape ( fetch_user_result.accountId ),
mysql.escape ( jwt_token )
);
vm.storage_agent.connection_exec ( sp_script ).then (
function ( value )
{
resolve ( value[0][0] );
},
function ( error )
{
throw ( error );
}
).catch (
function ( ex )
{
reject ( ex );
}
);
} );
}
function accountToken_fetch_account ( fetch_user_result )
{
return new Promise ( function ( resolve, reject )
{
var sp_script = sprintf ( 'CALL %s( %s );',
'sp_accountToken_fetch_account',
mysql.escape ( fetch_user_result.accountId )
);
vm.storage_agent.connection_exec ( sp_script ).then (
function ( value )
{
var result_len = value[0].length;
if ( 1 > result_len )
{
throw ( 'account token not found' );
}
resolve ( value[0][0] );
},
function ( error )
{
throw ( error );
}
).catch (
function ( ex )
{
reject ( ex );
}
);
} );
}
/**
* Login with userName & token
* @param req.body.userName
* @param req.body.token
*/
function login ( req, res, next )
{
var account_salt = vm.protect_agent.compose_salt ( );
var account_hash = vm.protect_agent.encrypt_pass ( req.body.password, account_salt );
var sp_script = sprintf ( 'CALL %s( %s );',
'sp_account_fetch_user',
mysql.escape ( req.body.userName )
);
var fetch_user_result;
vm.storage_agent.connection_exec ( sp_script ).then (
function ( value )
{
var result_len = value[0].length;
if ( 1 > result_len )
{
throw ( 'account not found' );
}
fetch_user_result = value[0][0];
fetch_user_result.confirmed = vm.protect_agent.confirm_hash (
req.body.password,
fetch_user_result.salt,
fetch_user_result.hash
);
if ( true !== fetch_user_result.confirmed )
{
throw ( 'try again' );
}
return accountToken_fetch_account ( fetch_user_result );
},
function ( error )
{
throw ( error );
}
).then (
function ( value )
{
// account already has an accountToken, return it.
return value;
},
function ( error )
{
// no account token, make a token. return it
return accountToken_write ( fetch_user_result );
}
).then (
function ( value )
{
var retval =
{
userName : req.body.userName,
success : fetch_user_result.confirmed,
token : value.token
};
return _controllerBase.request_status_send ( res, 200, retval );
},
function ( error )
{
throw ( error );
}
).catch (
function ( error )
{
return _controllerBase.request_status_send ( res, 400, error );
}
);
}
/**
* Login with userName & password
* @param req.body.userName
* @param req.body.token
*/
function check ( req, res, next )
{
if ( ! req.body.userName )
{
return request_status_send ( res, 400, 'no' );
}
if ( ! req.body.token )
{
return request_status_send ( res, 400, 'no' );
}
console.log ( vm._service_name, '::check', req.body.userName );
console.log ( vm._service_name, '::check', req.body.token );
accountToken_verify ( req.body.token ).then (
function ( value )
{
// verify it is one of our tokens
if ( ! value )
{
throw ( 'account token verification failure' );
}
console.log ( 'account token, ' );
console.log ( value );
console.log ( '' );
if ( value.userName !== req.body.userName )
{
throw ( 'account token verification failure, token forgery' );
}
// token is valid
// confirm the user is valid
var sp_script = sprintf ( 'CALL %s( %s );',
'sp_account_fetch_user',
mysql.escape ( req.body.userName )
);
return vm.storage_agent.connection_exec ( sp_script );
},
function ( error )
{
throw ( error );
}
).then (
function ( value )
{
var result_len = value[0].length;
if ( 1 > result_len )
{
throw ( 'account not found' );
}
return _controllerBase.request_status_send ( res, 200, 'ok' );
},
function ( error )
{
throw ( error );
}
).catch (
function ( ex )
{
return _controllerBase.request_status_send ( res, 400, ex );
}
);
}
function on_restapi_post ( req, res, next )
{
if ( req.body.fetch ) return fetch ( req, res, next );
if ( req.body.write ) return write ( req, res, next );
if ( req.body.login ) return login ( req, res, next );
if ( req.body.check ) return check ( req, res, next );
return _controllerBase.request_status_send ( res, 400, { error : 'bad request' } );
}
return api;
};
|
import uiRouter from 'angular-ui-router';
import ngRoute from 'angular-route';
import ContactController from './contact.controller';
import ContactResourceService from './contact-resource.service';
import ConfirmClick from '../directives/confirm-click';
export default angular.module('Contact', [
uiRouter,
ngRoute
])
.controller('contactController', ContactController)
.service('contactResourceService', ContactResourceService)
.directive('confirmClick', ConfirmClick)
.name;
|
var common = require('../common');
var assert = common.assert;
var SandboxedModule = require(common.dir.lib + '/sandboxed_module');
(function testRequire() {
var foo = SandboxedModule.load('../fixture/foo').exports;
assert.strictEqual(foo.foo, 'foo');
assert.strictEqual(foo.bar, 'bar');
})();
|
'use strict';
/* global describe it */
// core modules
var assert = require('assert');
// local modules
var makeValueFullResult = require('../../lib/consumers/makeValueFullResult.js');
var single = require('../../lib/consumers/single.js');
var Stream = require('../../lib/streams/stream.js');
describe('makeValueFullResult', function() {
it('makes value full result', function() {
var stream = Stream('x');
var consumer = makeValueFullResult(single('x'));
var parseResult = consumer.consume(stream);
assert.equal(parseResult.value.name, '"x"');
assert.equal(parseResult.value.value, 'x');
assert.equal(parseResult.value.accepted, true);
assert.equal(parseResult.value.valid, true);
assert.equal(parseResult.value.invalidations.length, 0);
assert.equal(parseResult.value.location.length, 2);
});
});
|
import traverse from "../../../traversal";
import object from "../../../helpers/object";
import * as util from "../../../util";
import * as t from "../../../types";
import values from "lodash/object/values";
import extend from "lodash/object/extend";
function isLet(node, parent) {
if (!t.isVariableDeclaration(node)) return false;
if (node._let) return true;
if (node.kind !== "let") return false;
// https://github.com/babel/babel/issues/255
if (isLetInitable(node, parent)) {
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
declar.init ||= t.identifier("undefined");
}
}
node._let = true;
node.kind = "var";
return true;
}
function isLetInitable(node, parent) {
return !t.isFor(parent) || !t.isFor(parent, { left: node });
}
function isVar(node, parent) {
return t.isVariableDeclaration(node, { kind: "var" }) && !isLet(node, parent);
}
function standardizeLets(declars) {
for (var i = 0; i < declars.length; i++) {
delete declars[i]._let;
}
}
export function check(node) {
return t.isVariableDeclaration(node) && (node.kind === "let" || node.kind === "const");
}
export function VariableDeclaration(node, parent, scope, file) {
if (!isLet(node, parent)) return;
if (isLetInitable(node) && file.transformers["es6.blockScopingTDZ"].canRun()) {
var nodes = [node];
for (var i = 0; i < node.declarations.length; i++) {
var decl = node.declarations[i];
if (decl.init) {
var assign = t.assignmentExpression("=", decl.id, decl.init);
assign._ignoreBlockScopingTDZ = true;
nodes.push(t.expressionStatement(assign));
}
decl.init = file.addHelper("temporal-undefined");
}
node._blockHoist = 2;
return nodes;
}
}
export function Loop(node, parent, scope, file) {
var init = node.left || node.init;
if (isLet(init, node)) {
t.ensureBlock(node);
node.body._letDeclarators = [init];
}
var blockScoping = new BlockScoping(this, node.body, parent, scope, file);
return blockScoping.run();
}
export function BlockStatement(block, parent, scope, file) {
if (!t.isLoop(parent)) {
var blockScoping = new BlockScoping(null, block, parent, scope, file);
blockScoping.run();
}
}
export { BlockStatement as Program };
function replace(node, parent, scope, remaps) {
if (!t.isReferencedIdentifier(node, parent)) return;
var remap = remaps[node.name];
if (!remap) return;
var ownBinding = scope.getBindingIdentifier(node.name);
if (ownBinding === remap.binding) {
node.name = remap.uid;
} else {
// scope already has it's own binding that doesn't
// match the one we have a stored replacement for
if (this) this.skip();
}
}
var replaceVisitor = {
enter: replace
};
function traverseReplace(node, parent, scope, remaps) {
replace(node, parent, scope, remaps);
scope.traverse(node, replaceVisitor, remaps);
}
var letReferenceBlockVisitor = {
enter(node, parent, scope, state) {
if (this.isFunction()) {
scope.traverse(node, letReferenceFunctionVisitor, state);
return this.skip();
}
}
};
var letReferenceFunctionVisitor = {
enter(node, parent, scope, state) {
// not a direct reference
if (!this.isReferencedIdentifier()) return;
// this scope has a variable with the same name so it couldn't belong
// to our let scope
if (scope.hasOwnBinding(node.name)) return;
// not a part of our scope
if (!state.letReferences[node.name]) return;
state.closurify = true;
}
};
var hoistVarDeclarationsVisitor = {
enter(node, parent, scope, self) {
if (this.isForStatement()) {
if (isVar(node.init, node)) {
node.init = t.sequenceExpression(self.pushDeclar(node.init));
}
} else if (this.isFor()) {
if (isVar(node.left, node)) {
node.left = node.left.declarations[0].id;
}
} else if (isVar(node, parent)) {
return self.pushDeclar(node).map(t.expressionStatement);
} else if (this.isFunction()) {
return this.skip();
}
}
};
var loopLabelVisitor = {
enter(node, parent, scope, state) {
if (this.isLabeledStatement()) {
state.innerLabels.push(node.label.name);
}
}
};
var loopNodeTo = function (node) {
if (t.isBreakStatement(node)) {
return "break";
} else if (t.isContinueStatement(node)) {
return "continue";
}
};
var loopVisitor = {
enter(node, parent, scope, state) {
var replace;
if (this.isLoop()) {
state.ignoreLabeless = true;
scope.traverse(node, loopVisitor, state);
state.ignoreLabeless = false;
}
if (this.isFunction() || this.isLoop()) {
return this.skip();
}
var loopText = loopNodeTo(node);
if (loopText) {
if (node.label) {
// we shouldn't be transforming this because it exists somewhere inside
if (state.innerLabels.indexOf(node.label.name) >= 0) {
return;
}
loopText = `${loopText}|${node.label.name}`;
} else {
// we shouldn't be transforming these statements because
// they don't refer to the actual loop we're scopifying
if (state.ignoreLabeless) return;
// break statements mean something different in this context
if (t.isBreakStatement(node) && t.isSwitchCase(parent)) return;
}
state.hasBreakContinue = true;
state.map[loopText] = node;
replace = t.literal(loopText);
}
if (this.isReturnStatement()) {
state.hasReturn = true;
replace = t.objectExpression([
t.property("init", t.identifier("v"), node.argument || t.identifier("undefined"))
]);
}
if (replace) {
replace = t.returnStatement(replace);
return t.inherits(replace, node);
}
}
};
class BlockScoping {
/**
* Description
*/
constructor(loopPath?: TraversalPath, block: Object, parent: Object, scope: Scope, file: File) {
this.parent = parent;
this.scope = scope;
this.block = block;
this.file = file;
this.outsideLetReferences = object();
this.hasLetReferences = false;
this.letReferences = block._letReferences = object();
this.body = [];
if (loopPath) {
this.loopParent = loopPath.parent;
this.loopLabel = t.isLabeledStatement(this.loopParent) && this.loopParent.label;
this.loop = loopPath.node;
}
}
/**
* Start the ball rolling.
*/
run() {
var block = this.block;
if (block._letDone) return;
block._letDone = true;
var needsClosure = this.getLetReferences();
// this is a block within a `Function/Program` so we can safely leave it be
if (t.isFunction(this.parent) || t.isProgram(this.block)) return;
// we can skip everything
if (!this.hasLetReferences) return;
if (needsClosure) {
this.wrapClosure();
} else {
this.remap();
}
if (this.loopLabel && !t.isLabeledStatement(this.loopParent)) {
return t.labeledStatement(this.loopLabel, this.loop);
}
}
/**
* Description
*/
remap() {
var hasRemaps = false;
var letRefs = this.letReferences;
var scope = this.scope;
// alright, so since we aren't wrapping this block in a closure
// we have to check if any of our let variables collide with
// those in upper scopes and then if they do, generate a uid
// for them and replace all references with it
var remaps = object();
for (var key in letRefs) {
// just an Identifier node we collected in `getLetReferences`
// this is the defining identifier of a declaration
var ref = letRefs[key];
if (scope.parentHasBinding(key) || scope.hasGlobal(key)) {
var uid = scope.generateUidIdentifier(ref.name).name;
ref.name = uid;
hasRemaps = true;
remaps[key] = remaps[uid] = {
binding: ref,
uid: uid
};
}
}
if (!hasRemaps) return;
//
var loop = this.loop;
if (loop) {
traverseReplace(loop.right, loop, scope, remaps);
traverseReplace(loop.test, loop, scope, remaps);
traverseReplace(loop.update, loop, scope, remaps);
}
scope.traverse(this.block, replaceVisitor, remaps);
}
/**
* Description
*/
wrapClosure() {
var block = this.block;
var outsideRefs = this.outsideLetReferences;
// remap loop heads with colliding variables
if (this.loop) {
for (var name in outsideRefs) {
var id = outsideRefs[name];
if (this.scope.hasGlobal(id.name) || this.scope.parentHasBinding(id.name)) {
delete outsideRefs[id.name];
delete this.letReferences[id.name];
this.scope.rename(id.name);
this.letReferences[id.name] = id;
outsideRefs[id.name] = id;
}
}
}
// if we're inside of a for loop then we search to see if there are any
// `break`s, `continue`s, `return`s etc
this.has = this.checkLoop();
// hoist var references to retain scope
this.hoistVarDeclarations();
// turn outsideLetReferences into an array
var params = values(outsideRefs);
// build the closure that we're going to wrap the block with
var fn = t.functionExpression(null, params, t.blockStatement(block.body));
fn._aliasFunction = true;
// replace the current block body with the one we're going to build
block.body = this.body;
// build a call and a unique id that we can assign the return value to
var call = t.callExpression(fn, params);
var ret = this.scope.generateUidIdentifier("ret");
// handle generators
var hasYield = traverse.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES);
if (hasYield) {
fn.generator = true;
call = t.yieldExpression(call, true);
}
// handlers async functions
var hasAsync = traverse.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES);
if (hasAsync) {
fn.async = true;
call = t.awaitExpression(call, true);
}
this.build(ret, call);
}
/**
* Description
*/
getLetReferences() {
var block = this.block;
var declarators = block._letDeclarators || [];
var declar;
//
for (var i = 0; i < declarators.length; i++) {
declar = declarators[i];
extend(this.outsideLetReferences, t.getBindingIdentifiers(declar));
}
//
if (block.body) {
for (i = 0; i < block.body.length; i++) {
declar = block.body[i];
if (isLet(declar, block)) {
declarators = declarators.concat(declar.declarations);
}
}
}
//
for (i = 0; i < declarators.length; i++) {
declar = declarators[i];
var keys = t.getBindingIdentifiers(declar);
extend(this.letReferences, keys);
this.hasLetReferences = true;
}
// no let references so we can just quit
if (!this.hasLetReferences) return;
// set let references to plain var references
standardizeLets(declarators);
var state = {
letReferences: this.letReferences,
closurify: false
};
// traverse through this block, stopping on functions and checking if they
// contain any local let references
this.scope.traverse(this.block, letReferenceBlockVisitor, state);
return state.closurify;
}
/**
* If we're inside of a loop then traverse it and check if it has one of
* the following node types `ReturnStatement`, `BreakStatement`,
* `ContinueStatement` and replace it with a return value that we can track
* later on.
*
* @returns {Object}
*/
checkLoop() {
var state = {
hasBreakContinue: false,
ignoreLabeless: false,
innerLabels: [],
hasReturn: false,
isLoop: !!this.loop,
map: {}
};
this.scope.traverse(this.block, loopLabelVisitor, state);
this.scope.traverse(this.block, loopVisitor, state);
return state;
}
/**
* Hoist all var declarations in this block to before it so they retain scope
* once we wrap everything in a closure.
*/
hoistVarDeclarations() {
traverse(this.block, hoistVarDeclarationsVisitor, this.scope, this);
}
/**
* Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with
* their declarations hoisted to before the closure wrapper.
*/
pushDeclar(node: { type: "VariableDeclaration" }): Array<Object> {
this.body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) {
return t.variableDeclarator(declar.id);
})));
var replace = [];
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
if (!declar.init) continue;
var expr = t.assignmentExpression("=", declar.id, declar.init);
replace.push(t.inherits(expr, declar));
}
return replace;
}
/**
* Push the closure to the body.
*/
build(ret: { type: "Identifier" }, call: { type: "CallExpression" }) {
var has = this.has;
if (has.hasReturn || has.hasBreakContinue) {
this.buildHas(ret, call);
} else {
this.body.push(t.expressionStatement(call));
}
}
/**
* Description
*/
buildHas(ret: { type: "Identifier" }, call: { type: "CallExpression" }) {
var body = this.body;
body.push(t.variableDeclaration("var", [
t.variableDeclarator(ret, call)
]));
var loop = this.loop;
var retCheck;
var has = this.has;
var cases = [];
if (has.hasReturn) {
// typeof ret === "object"
retCheck = util.template("let-scoping-return", {
RETURN: ret
});
}
if (has.hasBreakContinue) {
for (var key in has.map) {
cases.push(t.switchCase(t.literal(key), [has.map[key]]));
}
if (has.hasReturn) {
cases.push(t.switchCase(null, [retCheck]));
}
if (cases.length === 1) {
var single = cases[0];
body.push(this.file.attachAuxiliaryComment(t.ifStatement(
t.binaryExpression("===", ret, single.test),
single.consequent[0]
)));
} else {
// #998
for (var i = 0; i < cases.length; i++) {
var caseConsequent = cases[i].consequent[0];
if (t.isBreakStatement(caseConsequent) && !caseConsequent.label) {
caseConsequent.label = this.loopLabel ||= this.file.scope.generateUidIdentifier("loop");
}
}
body.push(this.file.attachAuxiliaryComment(t.switchStatement(ret, cases)));
}
} else {
if (has.hasReturn) {
body.push(this.file.attachAuxiliaryComment(retCheck));
}
}
}
}
|
'use strict';
angular.module('adds').controller('QuestionController', ['$scope',
function($scope) {
// Question controller logic
// ...
}
]);
|
/* jshint esversion : 6 */
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '@mysql',
database : 'node-backend'
});
connection.connect();
// dummy function pour vérifier si la connectione à la base est bien établie
connection.query('SELECT 42 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('DATABASE SAYS => The solution is', results[0].solution);
});
const get = (clbk, id) => {
var query;
if (id) query = `SELECT id, mail, avatar, about, is_admin FROM users WHERE id = ${connection.escape(id)}`;
else query = 'SELECT id, mail, avatar, about, is_admin FROM users';
connection.query(query, (error, results, fields) => {
if (error) throw error; // en cas d'erreur, une exception est levée
clbk(results); // on passe les résultats de la requête en argument de la fonction callback
});
};
const checkMail = (clbk, mail) => {
const query = `SELECT COUNT(*) as count FROM users WHERE mail = ${connection.escape(mail)}`;
connection.query(query, (error, results, fields) => {
if (error) throw error; // en cas d'erreur, une exception est levée
clbk(results); // passe les résultats de requête en arg du callback
});
};
const register = (clbk, data) => {
checkMail(res => {
// console.log(res);
if (res[0].count > 0) { // cette adresse mail est déjà en base
return clbk({error: true, message: "mail already exists"});
}
// la base ne contient pas encore cette adresse mail, poursuivons l'insertion
let query = `INSERT INTO users (mail, password) VALUES
(${connection.escape(data.mail)}, ${connection.escape(data.password)})`;
connection.query(query, (error, results, fields) => {
if (error) throw error;
results.error = false;
results.message = "tadaa : you're now registered !!!";
clbk(results);
});
}, data.mail);
};
const remove = (clbk, id) => {
const query = `DELETE FROM users WHERE id = ${connection.escape(id)}`;
connection.query(query, (error, results, fields) => {
if (error) throw error; // en cas d'erreur, une exception est levée
results.error = false;
results.message = "user has been removed from database";
clbk(results); // on passe les résultats de la requête en argument de la fonction callback
});
};
const login = (clbk, data) => {
const q = `SELECT id, mail, avatar, about, is_admin FROM users WHERE mail = '${data.mail}' AND password = '${data.password}' GROUP BY id`;
// console.log(q);
connection.query(q, (error, results, fields) => {
if (error) throw error;
const tmp = results[0] || results;
const res = {};
if (Array.isArray(tmp) && !tmp.length) {
res.message = "Mauvais mail ou mot de passe";
} else {
res.user = tmp;
res.message = "Yay : You're now logged in !!";
}
clbk(res);
});
};
const patchAbout = (clbk, about, id) => {
const q = `UPDATE users SET about = ${connection.escape(about)} WHERE id = ${id}`;
// console.log(q);
connection.query(q, (error, results, fields) => {
if (error) throw error;
clbk(results);
});
};
const patchAvatar = (clbk, avatar, id) => {
const q = `UPDATE users SET avatar = ${connection.escape(avatar)} WHERE id = ${id}`;
// console.log(q);
connection.query(q, (error, results, fields) => {
if (error) throw error;
clbk(results);
});
};
module.exports = {
register,
get,
login,
patch: {
about: patchAbout,
avatar: patchAvatar,
},
remove: remove,
};
|
import './fileUpload.js';
import './fileGallery.html';
import './files.html';
import './files.scss';
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
value(callback, type, quality) {
let binStr = atob(this.toDataURL(type, quality).split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len);
for (let i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
callback(new Blob([arr], { type: type || 'image/png' }));
},
});
}
const currentlyEditedFile = new ReactiveVar(undefined);
const fileBrowserCallback = new ReactiveVar(undefined);
Meteor.startup(function () {
_.extend(UltiSite, {
fileBrowserShowDialog(id, callback) {
UltiSite.State.set('fileBrowserFolder', id);
fileBrowserCallback.set(callback);
UltiSite.showModal('fileBrowserDialog');
},
fileBrowserHideDialog() {
UltiSite.hideModal();
},
});
});
Template.registerHelper('fileRootFolder', function () {
return UltiSite.Folders.findOne(UltiSite.settings().rootFolderId);
});
const getIcon = function () {
let file = this;
if (!file.type && this.file) { file = this.file; }
if (!file.type) { return 'fa-question'; }
if (file.type.indexOf('image') === 0) { return 'fa-file-image-o'; } else if (file.type.indexOf('video') === 0) { return 'fa-file-video-o'; }
return 'fa-file-o';
};
// FUTURE: add editing capabilities
Template.editFileDialog.helpers({
file() {
return currentlyEditedFile.get();
},
icon: getIcon,
assozierteElemente() {
return UltiSite.getAnyById(currentlyEditedFile.get().associated);
},
});
Template.fileBrowser.onCreated(function () {
UltiSite.State.set('fileBrowserFolder', UltiSite.settings().rootFolderId);
UltiSite.State.setDefault('fileBrowserGalleryView', false);
this.autorun(() => {
const id = FlowRouter.getParam('_id');
const dataId = Template.currentData().fileBrowserFolder;
if (dataId) {
UltiSite.State.set('fileBrowserFolder', dataId);
} else
if (id) {
UltiSite.State.set('fileBrowserFolder', id);
}
});
this.autorun(() => {
this.subscribe('Files', UltiSite.State.get('fileBrowserFolder'));
});
this.readme = new ReactiveVar();
this.autorun(() => {
const readmeFile = UltiSite.Documents.findOne({
associated: UltiSite.State.get('fileBrowserFolder'),
name: 'README.md',
});
if (readmeFile) {
HTTP.get(readmeFile.url(), (err, res) => {
if (!err) { this.readme.set(res.content); }
});
} else { this.readme.set(undefined); }
});
});
Template.fileBrowser.events({
'click .toggle-gallery-view': function(e, t) {
e.preventDefault();
UltiSite.State.set('fileBrowserGalleryView', !UltiSite.State.get('fileBrowserGalleryView'));
},
'click .btn-new-folder': function(e, t) {
e.preventDefault();
console.log('Add folder', e);
UltiSite.Folders.insert({
rename: true,
name: 'Neuer Ordner',
associated: [UltiSite.State.get('fileBrowserFolder')],
});
},
});
Template.fileBrowser.helpers({
galleryView() {
return UltiSite.State.get('fileBrowserGalleryView');
},
readme() {
return Template.instance().readme.get();
},
curFolder() {
return UltiSite.getAnyById(UltiSite.State.get('fileBrowserFolder')) || { _id: UltiSite.State.get('fileBrowserFolder') };
},
rootFolder() {
return UltiSite.getAnyById(UltiSite.settings().rootFolderId);
},
});
Template.fileBrowserItem.events({
'click .remove-file': function(e, t) {
e.preventDefault();
UltiSite.confirmDialog(`Willst du die Datei ${this.name} wirklich löschen?`, () => {
Meteor.call('removeFile', this._id);
});
},
'click .edit-file': function(e) {
e.preventDefault();
currentlyEditedFile.set(this);
$('#editFileDialog').modal('show');
},
'click .select-file': function(e, t) {
e.preventDefault();
e.stopPropagation();
const callback = fileBrowserCallback.get();
if (callback) { callback(this); }
},
});
Template.fileBrowserItem.helpers({
needsSelect() {
return fileBrowserCallback.get();
},
icon: getIcon,
});
Template.fileBrowserDialog.onCreated(function () {
const self = this;
this.initialFolder = UltiSite.State.get('fileBrowserFolder');
this.activePane = new ReactiveVar(this.initialFolder);
});
Template.fileBrowserDialog.onDestroyed(function () {
fileBrowserCallback.set(null);
});
Template.fileBrowserDialog.events({
'hidden.bs.modal .modal': function(e, t) {
fileBrowserCallback.set(null);
},
'click .action-switch-source': function(e, t) {
e.preventDefault();
if (t.$(e.currentTarget).attr('data-value') !== 'search') { UltiSite.State.set('fileBrowserFolder', t.$(e.currentTarget).attr('data-value')); }
t.activePane.set(t.$(e.currentTarget).attr('data-value'));
},
'click .action-select-nothing': function(e) {
e.preventDefault();
const callback = fileBrowserCallback.get();
if (callback) {
callback(null);
}
},
});
Template.fileBrowserDialog.helpers({
initialFolder() {
return Template.instance().initialFolder;
},
fileBrowserFolder() {
return UltiSite.State.get('fileBrowserFolder');
},
activePane() {
return Template.instance().activePane.get();
},
dialogSelection() {
return fileBrowserCallback.get();
},
});
const helpers = {
icon: getIcon,
folder() {
return UltiSite.getAnyById(UltiSite.State.get('fileBrowserFolder')) || {};
},
files() {
return _.sortBy(UltiSite.Images.find({
associated: UltiSite.State.get('fileBrowserFolder'),
}).fetch().concat(
UltiSite.Documents.find({
associated: UltiSite.State.get('fileBrowserFolder'),
}).fetch()), function (doc) {
return doc.created;
});
},
folders() {
const folders = [];
if (this.type === 'folder') {
const folder = UltiSite.Folders.findOne(this._id);
if (folder && folder.associated.length > 0) {
folders.push({ name: '..', isParent: true, _id: folder.associated[0], type: 'folder' });
}
}
return folders.concat(UltiSite.Folders.find({
associated: UltiSite.State.get('fileBrowserFolder'),
}).fetch());
},
fileActions() {
const element = UltiSite.getAnyById(this._id);
if (!element) { return []; }
if (element.type === 'tournament') {
const tournament = UltiSite.getTournament(element._id);
if (!tournament) { return []; }
const elems = tournament.teams.map(function (elem) {
return {
text: `Teamfoto:${elem.name}`,
action(file) {
console.log('Updating teamfoto');
UltiSite.Images.update(file._id, {
$addToSet: {
associated: elem._id,
},
});
},
};
});
return elems;
}
},
};
Template.fileBrowserList.onCreated(function () {
console.log('List: onCreated');
const self = this;
});
Template.fileBrowserList.onRendered(function () {
console.log('List: onRendered');
});
Template.fileBrowserList.helpers(_.extend({}, helpers));
Template.fileBrowserList.events({
'click .folder-link': function(e, t) {
UltiSite.State.set('fileBrowserFolder', this._id);
e.preventDefault();
},
'click .remove-folder': function(e, t) {
e.preventDefault();
UltiSite.Folders.remove({
_id: this._id,
});
},
'click .rename-folder': function(e, t) {
e.preventDefault();
const input = $(e.currentTarget);
UltiSite.Folders.update({
_id: this._id,
}, {
$set: {
rename: true,
},
});
},
'change .folder-name': function(e, t) {
e.preventDefault();
const input = $(e.currentTarget);
UltiSite.Folders.update({
_id: input.data('id'),
}, {
$set: {
name: input.val(),
},
$unset: {
rename: 1,
},
});
},
});
Template.fileBrowserGallery.onCreated(function () {
console.log('Gallery created for ID', this.data);
const self = this;
});
Template.fileBrowserGallery.helpers(helpers);
Template.fileBrowserGallery.events({
'click .action-open-folder': function(e, t) {
e.preventDefault();
UltiSite.State.set('fileBrowserFolder', this._id);
},
});
Template.fileBrowserGalleryItem.events({
'click .file-browser-gallery-item .image': function() {
try {
if (Template.instance().$('.file-browser-item').parent('#fileBrowserDialog')) {
const callback = fileBrowserCallback.get();
if (callback) {
callback(this.file);
return;
}
}
} catch (err) { }
FlowRouter.go('image', {
_id: this.file._id,
associated: this.associatedId,
});
},
'click .file-browser-gallery-item .icon-image': function() {
try {
if (Template.instance().$('.file-browser-item').parent('#fileBrowserDialog')) {
const callback = fileBrowserCallback.get();
if (callback) {
callback(this.file);
return;
}
}
} catch (err) { }
window.open(this.file.url(), '_blank');
},
'click .remove-file': function(e, t) {
e.preventDefault();
UltiSite.confirmDialog(`Willst du die Datei ${this.file.name} wirklich löschen?`, () => {
Meteor.call('removeFile', this.file._id);
});
},
'click .edit-file': function(e) {
e.preventDefault();
currentlyEditedFile.set(this.file);
$('#editFileDialog').modal('show');
},
'click .select-file': function(e, t) {
e.preventDefault();
e.stopPropagation();
const callback = fileBrowserCallback.get();
if (callback) { callback(this.file); }
},
'click .custom-action': function(e, t) {
e.preventDefault();
// e.stopPropagation();
console.log('Custom:', this);
this.action(t.data.file);
},
});
Template.fileBrowserGalleryItem.helpers(helpers);
Template.folderTreeItem.helpers({
isSelectedFolder() {
return this._id === UltiSite.State.get('fileBrowserFolder');
},
folders() {
return UltiSite.Folders.find({
associated: this._id,
});
},
});
|
import Ember from 'ember';
import { moduleFor, test } from 'ember-qunit';
// The default (application) serializer is the DRF adapter.
// see app/serializers/application.js
moduleFor('serializer:application', 'DRFSerializer', {});
test('normalizeResponse - results', function(assert) {
let serializer = this.subject();
serializer._super = sinon.spy();
let primaryModelClass = {modelName: 'person'};
let payload = {
count: 'count',
next: '/api/posts/?page=3',
previous: '/api/posts/?page=1',
other: 'stuff',
results: ['result']
};
serializer.normalizeResponse('store', primaryModelClass, payload, 1, 'requestType');
assert.equal(serializer._super.callCount, 1);
assert.equal(serializer._super.lastCall.args[0],'store');
assert.propEqual(serializer._super.lastCall.args[1], primaryModelClass);
assert.equal(serializer._super.lastCall.args[3], 1);
assert.equal(serializer._super.lastCall.args[4], 'requestType');
let modifiedPayload = serializer._super.lastCall.args[2];
assert.equal('result', modifiedPayload[primaryModelClass.modelName][0]);
assert.ok(modifiedPayload.meta);
assert.equal(modifiedPayload.meta['next'], 3);
assert.equal(modifiedPayload.meta['previous'], 1);
// Unknown metadata has been passed along to the meta object.
assert.equal(modifiedPayload.meta['other'], 'stuff');
});
test('normalizeResponse - results (cursor pagination)', function(assert) {
let serializer = this.subject();
serializer._super = sinon.spy();
let primaryModelClass = {modelName: 'person'};
let payload = {
next: '/api/posts/?page=3',
previous: '/api/posts/?page=1',
other: 'stuff',
results: ['result']
};
serializer.normalizeResponse('store', primaryModelClass, payload, 1, 'requestType');
assert.equal(serializer._super.callCount, 1);
assert.equal(serializer._super.lastCall.args[0],'store');
assert.propEqual(serializer._super.lastCall.args[1], primaryModelClass);
assert.equal(serializer._super.lastCall.args[3], 1);
assert.equal(serializer._super.lastCall.args[4], 'requestType');
let modifiedPayload = serializer._super.lastCall.args[2];
assert.equal('result', modifiedPayload[primaryModelClass.modelName][0]);
assert.ok(modifiedPayload.meta);
assert.equal(modifiedPayload.meta['next'], 3);
assert.equal(modifiedPayload.meta['previous'], 1);
// Unknown metadata has been passed along to the meta object.
assert.equal(modifiedPayload.meta['other'], 'stuff');
});
test('normalizeResponse - no results', function(assert) {
let serializer = this.subject();
serializer._super = sinon.stub().returns('extracted array');
let primaryModelClass = {modelName: 'person'};
let payload = {other: 'stuff'};
let result = serializer.normalizeResponse('store', primaryModelClass, payload, 1, 'requestType');
assert.equal(result, 'extracted array');
let convertedPayload = {};
convertedPayload[primaryModelClass.modelName] = payload;
assert.ok(serializer._super.calledWith('store', primaryModelClass, convertedPayload, 1, 'requestType'),
'_super not called properly');
});
test('serializeIntoHash', function(assert) {
var serializer = this.subject();
serializer.serialize = sinon.stub().returns({serialized: 'record'});
var hash = {existing: 'hash'};
serializer.serializeIntoHash(hash, 'type', 'record', 'options');
assert.ok(serializer.serialize.calledWith(
'record', 'options'
), 'serialize not called properly');
assert.deepEqual(hash, {serialized: 'record', existing: 'hash'});
});
test('keyForAttribute', function(assert) {
var serializer = this.subject();
var result = serializer.keyForAttribute('firstName');
assert.equal(result, 'first_name');
});
test('keyForRelationship', function(assert) {
var serializer = this.subject();
var result = serializer.keyForRelationship('projectManagers', 'hasMany');
assert.equal(result, 'project_managers');
});
test('extractPageNumber', function(assert) {
var serializer = this.subject();
assert.equal(serializer.extractPageNumber('http://xmpl.com/a/p/?page=3234'), 3234,
'extractPageNumber failed on absolute URL');
assert.equal(serializer.extractPageNumber('/a/p/?page=3234'), 3234,
'extractPageNumber failed on relative URL');
assert.equal(serializer.extractPageNumber(null), null,
'extractPageNumber failed on null URL');
assert.equal(serializer.extractPageNumber('/a/p/'), null,
'extractPageNumber failed on URL without query params');
assert.equal(serializer.extractPageNumber('/a/p/?ordering=-timestamp&user=123'), null,
'extractPageNumber failed on URL with other query params');
assert.equal(serializer.extractPageNumber('/a/p/?fpage=23&pages=[1,2,3],page=123g&page=g123'), null,
'extractPageNumber failed on URL with similar query params');
});
test('extractRelationships', function(assert) {
assert.expect(47);
// Generates a payload hash for the specified urls array. This is used to generate
// new payloads to test with different the relationships types.
function ResourceHash(urls) {
this.id = 1;
var letter = 'a';
var self = this;
urls.forEach(function(url) {
self[letter] = url;
letter = String.fromCharCode(letter.charCodeAt(0) + 1);
});
}
// Generates a typeClass object for the specified relationship and payload. This is used to generate
// new stubbed out typeClasses to test with different the relationships types and payload.
function TypeClass(relationship, resourceHash) {
this.eachRelationship = function(callback, binding) {
for (var key in resourceHash) {
if (resourceHash.hasOwnProperty(key) && key !== 'links' && key !== 'id') {
callback.call(binding, key, {kind: relationship});
}
}
};
}
// More URLs can be tested by adding them to the correct section and adjusting
// the expectedPayloadKeys and the expectedLinksKeys variables.
var testURLs = [
// Valid relationship URLs.
'/api/users/1',
'https://example.com/api/users/1',
'http://example.com/api/users/1',
'//example.com/api/users/1',
// Invalid relationship URLs
'api',
'ftp://example.com//api/users/1',
'http//example.com/api/users/1',
'https//example.com/api/users/1',
'///example.com/api/users/1',
'',
null
];
// Error messages.
var missingKeyMessage = 'Modified payload for the %@ relationship is missing the %@ property.';
var wrongSizePayloadMessage = 'Modified payload for the %@ relationship is not the correct size.';
var wrongSizeLinksMessage = 'The links hash for the %@ relationship is not the correct size.';
var serializer = this.subject();
// Add a spy to _super because we only want to test our code.
serializer._super = sinon.spy();
// Test with hasMany and belongsTo relationships.
var validRelationships = ['hasMany', 'belongsTo'];
validRelationships.forEach(function(relationship) {
var resourceHash = new ResourceHash(testURLs);
serializer.extractRelationships(new TypeClass(relationship, resourceHash), resourceHash);
assert.equal(Object.keys(resourceHash).length, 9, Ember.String.fmt(wrongSizePayloadMessage, [relationship]));
// 'j' & 'k' need to be handled separately because they are false values.
var expectedPayloadKeys = ['id', 'links', 'e', 'f', 'g', 'h', 'i'];
expectedPayloadKeys.forEach(function(key) {
assert.ok(resourceHash[key], Ember.String.fmt(missingKeyMessage, [relationship, key]));
});
assert.equal(resourceHash['j'], '', Ember.String.fmt(missingKeyMessage, [relationship, 'j']));
assert.equal(resourceHash['k'], null, Ember.String.fmt(missingKeyMessage, [relationship], 'k'));
assert.equal(Object.keys(resourceHash.links).length, 4, Ember.String.fmt(wrongSizeLinksMessage, [relationship]));
var i = 0;
var expectedLinksKeys = ['a', 'b', 'c', 'd'];
expectedLinksKeys.forEach(function(key) {
assert.equal(resourceHash.links[key], testURLs[i],
Ember.String.fmt('Links value of property %@ in the %@ relationship is not correct.', [key, relationship]));
i++;
});
});
assert.equal(serializer._super.callCount, 2, '_super() was not called once for each relationship.');
// Test with an unknown relationship.
var relationship = 'xxUnknownXX';
var payload = new ResourceHash(testURLs);
serializer.extractRelationships(new TypeClass(relationship, payload), payload);
assert.equal(Object.keys(payload).length, 13, Ember.String.fmt(wrongSizePayloadMessage, [relationship]));
// 'j' & 'k' need to be handled separately because they are false values.
var expectedPayloadKeys = ['id', 'links', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
expectedPayloadKeys.forEach(function(key) {
assert.ok(payload[key], Ember.String.fmt(missingKeyMessage, [relationship, key]));
});
assert.equal(payload['j'], '', Ember.String.fmt(missingKeyMessage, [relationship, 'j']));
assert.equal(payload['k'], null, Ember.String.fmt(missingKeyMessage, [relationship], 'k'));
assert.equal(Object.keys(payload.links).length, 0, Ember.String.fmt(wrongSizeLinksMessage, [relationship]));
assert.equal(serializer._super.callCount, 3, Ember.String.fmt('_super() was not called for the %@ relationship.', [relationship]));
});
|
define(['plugins/router', 'durandal/app', 'services/config', 'services/datacontext', 'services/logger','knockout'], function (router, app, config, datacontext, logger,ko) {
var routes = ko.observableArray([]);
var isAdminUser = ko.observable();
var showSplash = ko.observable(false);
var vm = {
router: router,
showSplash:showSplash,
isAdminUser:isAdminUser,
routes:routes,
activate: activate,
deactivate:deactivate
};
return vm;
//called automatically by Durandal
function activate() {
return datacontext.fetchMetadata().then(function() {
return true;
}).then(function() {
return datacontext.getUserAccountDataLocal()
.then(function () {
return isAdminUser(datacontext.checkAdmin());
});
}).then(function() {
window.globalRoutes.forEach(function(r) {
routes.push(r);
});
return router.map(routes()).buildNavigationModel();
}).then(function () {
setupRouter();
return boot();
}).fail(function(e) {
return logger.log(e.message,null,null,true);
});
}
function setupRouter() {
return router.mapUnknownRoutes('dashboard/index', 'not-found');
}
function boot() {
return router.activate();
}
function deactivate() {
return true;
}
});
|
/**
* @license Highmaps JS v9.3.2 (2021-11-29)
* @module highcharts/modules/tilemap
* @requires highcharts
* @requires highcharts/modules/map
*
* Tilemap module
*
* (c) 2010-2021 Highsoft AS
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../Series/Tilemap/TilemapSeries.js';
|
/* Zepto 1.1.3 - zepto event ajax form ie detect - zeptojs.com/license */
var Zepto = (function() {
var undefined, key, $, classList, emptyArray = [], slice = emptyArray.slice, filter = emptyArray.filter,
document = window.document,
elementDisplay = {}, classCache = {},
cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 },
fragmentRE = /^\s*<(\w+|!)[^>]*>/,
singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rootNodeRE = /^(?:body|html)$/i,
capitalRE = /([A-Z])/g,
// special attributes that should be get/set via method calls
methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ],
table = document.createElement('table'),
tableRow = document.createElement('tr'),
containers = {
'tr': document.createElement('tbody'),
'tbody': table, 'thead': table, 'tfoot': table,
'td': tableRow, 'th': tableRow,
'*': document.createElement('div')
},
readyRE = /complete|loaded|interactive/,
simpleSelectorRE = /^[\w-]*$/,
class2type = {},
toString = class2type.toString,
zepto = {},
camelize, uniq,
tempParent = document.createElement('div'),
propMap = {
'tabindex': 'tabIndex',
'readonly': 'readOnly',
'for': 'htmlFor',
'class': 'className',
'maxlength': 'maxLength',
'cellspacing': 'cellSpacing',
'cellpadding': 'cellPadding',
'rowspan': 'rowSpan',
'colspan': 'colSpan',
'usemap': 'useMap',
'frameborder': 'frameBorder',
'contenteditable': 'contentEditable'
},
isArray = Array.isArray ||
function(object){ return object instanceof Array }
zepto.matches = function(element, selector) {
if (!selector || !element || element.nodeType !== 1) return false
var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
element.oMatchesSelector || element.matchesSelector
if (matchesSelector) return matchesSelector.call(element, selector)
// fall back to performing a selector:
var match, parent = element.parentNode, temp = !parent
if (temp) (parent = tempParent).appendChild(element)
match = ~zepto.qsa(parent, selector).indexOf(element)
temp && tempParent.removeChild(element)
return match
}
function type(obj) {
return obj == null ? String(obj) :
class2type[toString.call(obj)] || "object"
}
function isFunction(value) { return type(value) == "function" }
function isWindow(obj) { return obj != null && obj == obj.window }
function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }
function isObject(obj) { return type(obj) == "object" }
function isPlainObject(obj) {
return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
}
function likeArray(obj) { return typeof obj.length == 'number' }
function compact(array) { return filter.call(array, function(item){ return item != null }) }
function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array }
camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
function dasherize(str) {
return str.replace(/::/g, '/')
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
.replace(/_/g, '-')
.toLowerCase()
}
uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) }
function classRE(name) {
return name in classCache ?
classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)'))
}
function maybeAddPx(name, value) {
return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value
}
function defaultDisplay(nodeName) {
var element, display
if (!elementDisplay[nodeName]) {
element = document.createElement(nodeName)
document.body.appendChild(element)
display = getComputedStyle(element, '').getPropertyValue("display")
element.parentNode.removeChild(element)
display == "none" && (display = "block")
elementDisplay[nodeName] = display
}
return elementDisplay[nodeName]
}
function children(element) {
return 'children' in element ?
slice.call(element.children) :
$.map(element.childNodes, function(node){ if (node.nodeType == 1) return node })
}
// `$.zepto.fragment` takes a html string and an optional tag name
// to generate DOM nodes nodes from the given html string.
// The generated DOM nodes are returned as an array.
// This function can be overriden in plugins for example to make
// it compatible with browsers that don't support the DOM fully.
zepto.fragment = function(html, name, properties) {
var dom, nodes, container
// A special case optimization for a single tag
if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1))
if (!dom) {
if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
if (!(name in containers)) name = '*'
container = containers[name]
container.innerHTML = '' + html
dom = $.each(slice.call(container.childNodes), function(){
container.removeChild(this)
})
}
if (isPlainObject(properties)) {
nodes = $(dom)
$.each(properties, function(key, value) {
if (methodAttributes.indexOf(key) > -1) nodes[key](value)
else nodes.attr(key, value)
})
}
return dom
}
// `$.zepto.Z` swaps out the prototype of the given `dom` array
// of nodes with `$.fn` and thus supplying all the Zepto functions
// to the array. Note that `__proto__` is not supported on Internet
// Explorer. This method can be overriden in plugins.
zepto.Z = function(dom, selector) {
dom = dom || []
dom.__proto__ = $.fn
dom.selector = selector || ''
return dom
}
// `$.zepto.isZ` should return `true` if the given object is a Zepto
// collection. This method can be overriden in plugins.
zepto.isZ = function(object) {
return object instanceof zepto.Z
}
// `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and
// takes a CSS selector and an optional context (and handles various
// special cases).
// This method can be overriden in plugins.
zepto.init = function(selector, context) {
var dom
// If nothing given, return an empty Zepto collection
if (!selector) return zepto.Z()
// Optimize for string selectors
else if (typeof selector == 'string') {
selector = selector.trim()
// If it's a html fragment, create nodes from it
// Note: In both Chrome 21 and Firefox 15, DOM error 12
// is thrown if the fragment doesn't begin with <
if (selector[0] == '<' && fragmentRE.test(selector))
dom = zepto.fragment(selector, RegExp.$1, context), selector = null
// If there's a context, create a collection on that context first, and select
// nodes from there
else if (context !== undefined) return $(context).find(selector)
// If it's a CSS selector, use it to select nodes.
else dom = zepto.qsa(document, selector)
}
// If a function is given, call it when the DOM is ready
else if (isFunction(selector)) return $(document).ready(selector)
// If a Zepto collection is given, just return it
else if (zepto.isZ(selector)) return selector
else {
// normalize array if an array of nodes is given
if (isArray(selector)) dom = compact(selector)
// Wrap DOM nodes.
else if (isObject(selector))
dom = [selector], selector = null
// If it's a html fragment, create nodes from it
else if (fragmentRE.test(selector))
dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null
// If there's a context, create a collection on that context first, and select
// nodes from there
else if (context !== undefined) return $(context).find(selector)
// And last but no least, if it's a CSS selector, use it to select nodes.
else dom = zepto.qsa(document, selector)
}
// create a new Zepto collection from the nodes found
return zepto.Z(dom, selector)
}
// `$` will be the base `Zepto` object. When calling this
// function just call `$.zepto.init, which makes the implementation
// details of selecting nodes and creating Zepto collections
// patchable in plugins.
$ = function(selector, context){
return zepto.init(selector, context)
}
function extend(target, source, deep) {
for (key in source)
if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
if (isPlainObject(source[key]) && !isPlainObject(target[key]))
target[key] = {}
if (isArray(source[key]) && !isArray(target[key]))
target[key] = []
extend(target[key], source[key], deep)
}
else if (source[key] !== undefined) target[key] = source[key]
}
// Copy all but undefined properties from one or more
// objects to the `target` object.
$.extend = function(target){
var deep, args = slice.call(arguments, 1)
if (typeof target == 'boolean') {
deep = target
target = args.shift()
}
args.forEach(function(arg){ extend(target, arg, deep) })
return target
}
// `$.zepto.qsa` is Zepto's CSS selector implementation which
// uses `document.querySelectorAll` and optimizes for some special cases, like `#id`.
// This method can be overriden in plugins.
zepto.qsa = function(element, selector){
var found,
maybeID = selector[0] == '#',
maybeClass = !maybeID && selector[0] == '.',
nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked
isSimple = simpleSelectorRE.test(nameOnly)
return (isDocument(element) && isSimple && maybeID) ?
( (found = element.getElementById(nameOnly)) ? [found] : [] ) :
(element.nodeType !== 1 && element.nodeType !== 9) ? [] :
slice.call(
isSimple && !maybeID ?
maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class
element.getElementsByTagName(selector) : // Or a tag
element.querySelectorAll(selector) // Or it's not simple, and we need to query all
)
}
function filtered(nodes, selector) {
return selector == null ? $(nodes) : $(nodes).filter(selector)
}
$.contains = function(parent, node) {
return parent !== node && parent.contains(node)
}
function funcArg(context, arg, idx, payload) {
return isFunction(arg) ? arg.call(context, idx, payload) : arg
}
function setAttribute(node, name, value) {
value == null ? node.removeAttribute(name) : node.setAttribute(name, value)
}
// access className property while respecting SVGAnimatedString
function className(node, value){
var klass = node.className,
svg = klass && klass.baseVal !== undefined
if (value === undefined) return svg ? klass.baseVal : klass
svg ? (klass.baseVal = value) : (node.className = value)
}
// "true" => true
// "false" => false
// "null" => null
// "42" => 42
// "42.5" => 42.5
// "08" => "08"
// JSON => parse if valid
// String => self
function deserializeValue(value) {
var num
try {
return value ?
value == "true" ||
( value == "false" ? false :
value == "null" ? null :
!/^0/.test(value) && !isNaN(num = Number(value)) ? num :
/^[\[\{]/.test(value) ? $.parseJSON(value) :
value )
: value
} catch(e) {
return value
}
}
$.type = type
$.isFunction = isFunction
$.isWindow = isWindow
$.isArray = isArray
$.isPlainObject = isPlainObject
$.isEmptyObject = function(obj) {
var name
for (name in obj) return false
return true
}
$.inArray = function(elem, array, i){
return emptyArray.indexOf.call(array, elem, i)
}
$.camelCase = camelize
$.trim = function(str) {
return str == null ? "" : String.prototype.trim.call(str)
}
// plugin compatibility
$.uuid = 0
$.support = { }
$.expr = { }
$.map = function(elements, callback){
var value, values = [], i, key
if (likeArray(elements))
for (i = 0; i < elements.length; i++) {
value = callback(elements[i], i)
if (value != null) values.push(value)
}
else
for (key in elements) {
value = callback(elements[key], key)
if (value != null) values.push(value)
}
return flatten(values)
}
$.each = function(elements, callback){
var i, key
if (likeArray(elements)) {
for (i = 0; i < elements.length; i++)
if (callback.call(elements[i], i, elements[i]) === false) return elements
} else {
for (key in elements)
if (callback.call(elements[key], key, elements[key]) === false) return elements
}
return elements
}
$.grep = function(elements, callback){
return filter.call(elements, callback)
}
if (window.JSON) $.parseJSON = JSON.parse
// Populate the class2type map
$.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase()
})
// Define methods that will be available on all
// Zepto collections
$.fn = {
// Because a collection acts like an array
// copy over these useful array functions.
forEach: emptyArray.forEach,
reduce: emptyArray.reduce,
push: emptyArray.push,
sort: emptyArray.sort,
indexOf: emptyArray.indexOf,
concat: emptyArray.concat,
// `map` and `slice` in the jQuery API work differently
// from their array counterparts
map: function(fn){
return $($.map(this, function(el, i){ return fn.call(el, i, el) }))
},
slice: function(){
return $(slice.apply(this, arguments))
},
ready: function(callback){
// need to check if document.body exists for IE as that browser reports
// document ready when it hasn't yet created the body element
if (readyRE.test(document.readyState) && document.body) callback($)
else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false)
return this
},
get: function(idx){
return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length]
},
toArray: function(){ return this.get() },
size: function(){
return this.length
},
remove: function(){
return this.each(function(){
if (this.parentNode != null)
this.parentNode.removeChild(this)
})
},
each: function(callback){
emptyArray.every.call(this, function(el, idx){
return callback.call(el, idx, el) !== false
})
return this
},
filter: function(selector){
if (isFunction(selector)) return this.not(this.not(selector))
return $(filter.call(this, function(element){
return zepto.matches(element, selector)
}))
},
add: function(selector,context){
return $(uniq(this.concat($(selector,context))))
},
is: function(selector){
return this.length > 0 && zepto.matches(this[0], selector)
},
not: function(selector){
var nodes=[]
if (isFunction(selector) && selector.call !== undefined)
this.each(function(idx){
if (!selector.call(this,idx)) nodes.push(this)
})
else {
var excludes = typeof selector == 'string' ? this.filter(selector) :
(likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector)
this.forEach(function(el){
if (excludes.indexOf(el) < 0) nodes.push(el)
})
}
return $(nodes)
},
has: function(selector){
return this.filter(function(){
return isObject(selector) ?
$.contains(this, selector) :
$(this).find(selector).size()
})
},
eq: function(idx){
return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1)
},
first: function(){
var el = this[0]
return el && !isObject(el) ? el : $(el)
},
last: function(){
var el = this[this.length - 1]
return el && !isObject(el) ? el : $(el)
},
find: function(selector){
var result, $this = this
if (typeof selector == 'object')
result = $(selector).filter(function(){
var node = this
return emptyArray.some.call($this, function(parent){
return $.contains(parent, node)
})
})
else if (this.length == 1) result = $(zepto.qsa(this[0], selector))
else result = this.map(function(){ return zepto.qsa(this, selector) })
return result
},
closest: function(selector, context){
var node = this[0], collection = false
if (typeof selector == 'object') collection = $(selector)
while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))
node = node !== context && !isDocument(node) && node.parentNode
return $(node)
},
parents: function(selector){
var ancestors = [], nodes = this
while (nodes.length > 0)
nodes = $.map(nodes, function(node){
if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) {
ancestors.push(node)
return node
}
})
return filtered(ancestors, selector)
},
parent: function(selector){
return filtered(uniq(this.pluck('parentNode')), selector)
},
children: function(selector){
return filtered(this.map(function(){ return children(this) }), selector)
},
contents: function() {
return this.map(function() { return slice.call(this.childNodes) })
},
siblings: function(selector){
return filtered(this.map(function(i, el){
return filter.call(children(el.parentNode), function(child){ return child!==el })
}), selector)
},
empty: function(){
return this.each(function(){ this.innerHTML = '' })
},
// `pluck` is borrowed from Prototype.js
pluck: function(property){
return $.map(this, function(el){ return el[property] })
},
show: function(){
return this.each(function(){
this.style.display == "none" && (this.style.display = '')
if (getComputedStyle(this, '').getPropertyValue("display") == "none")
this.style.display = defaultDisplay(this.nodeName)
})
},
replaceWith: function(newContent){
return this.before(newContent).remove()
},
wrap: function(structure){
var func = isFunction(structure)
if (this[0] && !func)
var dom = $(structure).get(0),
clone = dom.parentNode || this.length > 1
return this.each(function(index){
$(this).wrapAll(
func ? structure.call(this, index) :
clone ? dom.cloneNode(true) : dom
)
})
},
wrapAll: function(structure){
if (this[0]) {
$(this[0]).before(structure = $(structure))
var children
// drill down to the inmost element
while ((children = structure.children()).length) structure = children.first()
$(structure).append(this)
}
return this
},
wrapInner: function(structure){
var func = isFunction(structure)
return this.each(function(index){
var self = $(this), contents = self.contents(),
dom = func ? structure.call(this, index) : structure
contents.length ? contents.wrapAll(dom) : self.append(dom)
})
},
unwrap: function(){
this.parent().each(function(){
$(this).replaceWith($(this).children())
})
return this
},
clone: function(){
return this.map(function(){ return this.cloneNode(true) })
},
hide: function(){
return this.css("display", "none")
},
toggle: function(setting){
return this.each(function(){
var el = $(this)
;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide()
})
},
prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') },
next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') },
html: function(html){
return arguments.length === 0 ?
(this.length > 0 ? this[0].innerHTML : null) :
this.each(function(idx){
var originHtml = this.innerHTML
$(this).empty().append( funcArg(this, html, idx, originHtml) )
})
},
text: function(text){
return arguments.length === 0 ?
(this.length > 0 ? this[0].textContent : null) :
this.each(function(){ this.textContent = (text === undefined) ? '' : ''+text })
},
attr: function(name, value){
var result
return (typeof name == 'string' && value === undefined) ?
(this.length == 0 || this[0].nodeType !== 1 ? undefined :
(name == 'value' && this[0].nodeName == 'INPUT') ? this.val() :
(!(result = this[0].getAttribute(name)) && name in this[0]) ? this[0][name] : result
) :
this.each(function(idx){
if (this.nodeType !== 1) return
if (isObject(name)) for (key in name) setAttribute(this, key, name[key])
else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name)))
})
},
removeAttr: function(name){
return this.each(function(){ this.nodeType === 1 && setAttribute(this, name) })
},
prop: function(name, value){
name = propMap[name] || name
return (value === undefined) ?
(this[0] && this[0][name]) :
this.each(function(idx){
this[name] = funcArg(this, value, idx, this[name])
})
},
data: function(name, value){
var data = this.attr('data-' + name.replace(capitalRE, '-$1').toLowerCase(), value)
return data !== null ? deserializeValue(data) : undefined
},
val: function(value){
return arguments.length === 0 ?
(this[0] && (this[0].multiple ?
$(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') :
this[0].value)
) :
this.each(function(idx){
this.value = funcArg(this, value, idx, this.value)
})
},
offset: function(coordinates){
if (coordinates) return this.each(function(index){
var $this = $(this),
coords = funcArg(this, coordinates, index, $this.offset()),
parentOffset = $this.offsetParent().offset(),
props = {
top: coords.top - parentOffset.top,
left: coords.left - parentOffset.left
}
if ($this.css('position') == 'static') props['position'] = 'relative'
$this.css(props)
})
if (this.length==0) return null
var obj = this[0].getBoundingClientRect()
return {
left: obj.left + window.pageXOffset,
top: obj.top + window.pageYOffset,
width: Math.round(obj.width),
height: Math.round(obj.height)
}
},
css: function(property, value){
if (arguments.length < 2) {
var element = this[0], computedStyle = getComputedStyle(element, '')
if(!element) return
if (typeof property == 'string')
return element.style[camelize(property)] || computedStyle.getPropertyValue(property)
else if (isArray(property)) {
var props = {}
$.each(isArray(property) ? property: [property], function(_, prop){
props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))
})
return props
}
}
var css = ''
if (type(property) == 'string') {
if (!value && value !== 0)
this.each(function(){ this.style.removeProperty(dasherize(property)) })
else
css = dasherize(property) + ":" + maybeAddPx(property, value)
} else {
for (key in property)
if (!property[key] && property[key] !== 0)
this.each(function(){ this.style.removeProperty(dasherize(key)) })
else
css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';'
}
return this.each(function(){ this.style.cssText += ';' + css })
},
index: function(element){
return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0])
},
hasClass: function(name){
if (!name) return false
return emptyArray.some.call(this, function(el){
return this.test(className(el))
}, classRE(name))
},
addClass: function(name){
if (!name) return this
return this.each(function(idx){
classList = []
var cls = className(this), newName = funcArg(this, name, idx, cls)
newName.split(/\s+/g).forEach(function(klass){
if (!$(this).hasClass(klass)) classList.push(klass)
}, this)
classList.length && className(this, cls + (cls ? " " : "") + classList.join(" "))
})
},
removeClass: function(name){
return this.each(function(idx){
if (name === undefined) return className(this, '')
classList = className(this)
funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){
classList = classList.replace(classRE(klass), " ")
})
className(this, classList.trim())
})
},
toggleClass: function(name, when){
if (!name) return this
return this.each(function(idx){
var $this = $(this), names = funcArg(this, name, idx, className(this))
names.split(/\s+/g).forEach(function(klass){
(when === undefined ? !$this.hasClass(klass) : when) ?
$this.addClass(klass) : $this.removeClass(klass)
})
})
},
scrollTop: function(value){
if (!this.length) return
var hasScrollTop = 'scrollTop' in this[0]
if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset
return this.each(hasScrollTop ?
function(){ this.scrollTop = value } :
function(){ this.scrollTo(this.scrollX, value) })
},
scrollLeft: function(value){
if (!this.length) return
var hasScrollLeft = 'scrollLeft' in this[0]
if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset
return this.each(hasScrollLeft ?
function(){ this.scrollLeft = value } :
function(){ this.scrollTo(value, this.scrollY) })
},
position: function() {
if (!this.length) return
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset()
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( $(elem).css('margin-top') ) || 0
offset.left -= parseFloat( $(elem).css('margin-left') ) || 0
// Add offsetParent borders
parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0
parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
}
},
offsetParent: function() {
return this.map(function(){
var parent = this.offsetParent || document.body
while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static")
parent = parent.offsetParent
return parent
})
}
}
// for now
$.fn.detach = $.fn.remove
// Generate the `width` and `height` functions
;['width', 'height'].forEach(function(dimension){
var dimensionProperty =
dimension.replace(/./, function(m){ return m[0].toUpperCase() })
$.fn[dimension] = function(value){
var offset, el = this[0]
if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] :
isDocument(el) ? el.documentElement['scroll' + dimensionProperty] :
(offset = this.offset()) && offset[dimension]
else return this.each(function(idx){
el = $(this)
el.css(dimension, funcArg(this, value, idx, el[dimension]()))
})
}
})
function traverseNode(node, fun) {
fun(node)
for (var key in node.childNodes) traverseNode(node.childNodes[key], fun)
}
// Generate the `after`, `prepend`, `before`, `append`,
// `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods.
adjacencyOperators.forEach(function(operator, operatorIndex) {
var inside = operatorIndex % 2 //=> prepend, append
$.fn[operator] = function(){
// arguments can be nodes, arrays of nodes, Zepto objects and HTML strings
var argType, nodes = $.map(arguments, function(arg) {
argType = type(arg)
return argType == "object" || argType == "array" || arg == null ?
arg : zepto.fragment(arg)
}),
parent, copyByClone = this.length > 1
if (nodes.length < 1) return this
return this.each(function(_, target){
parent = inside ? target : target.parentNode
// convert all methods to a "before" operation
target = operatorIndex == 0 ? target.nextSibling :
operatorIndex == 1 ? target.firstChild :
operatorIndex == 2 ? target :
null
nodes.forEach(function(node){
if (copyByClone) node = node.cloneNode(true)
else if (!parent) return $(node).remove()
traverseNode(parent.insertBefore(node, target), function(el){
if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' &&
(!el.type || el.type === 'text/javascript') && !el.src)
window['eval'].call(window, el.innerHTML)
})
})
})
}
// after => insertAfter
// prepend => prependTo
// before => insertBefore
// append => appendTo
$.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){
$(html)[operator](this)
return this
}
})
zepto.Z.prototype = $.fn
// Export internal API functions in the `$.zepto` namespace
zepto.uniq = uniq
zepto.deserializeValue = deserializeValue
$.zepto = zepto
return $
})()
window.Zepto = Zepto
window.$ === undefined && (window.$ = Zepto)
;(function($){
var _zid = 1, undefined,
slice = Array.prototype.slice,
isFunction = $.isFunction,
isString = function(obj){ return typeof obj == 'string' },
handlers = {},
specialEvents={},
focusinSupported = 'onfocusin' in window,
focus = { focus: 'focusin', blur: 'focusout' },
hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' }
specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents'
function zid(element) {
return element._zid || (element._zid = _zid++)
}
function findHandlers(element, event, fn, selector) {
event = parse(event)
if (event.ns) var matcher = matcherFor(event.ns)
return (handlers[zid(element)] || []).filter(function(handler) {
return handler
&& (!event.e || handler.e == event.e)
&& (!event.ns || matcher.test(handler.ns))
&& (!fn || zid(handler.fn) === zid(fn))
&& (!selector || handler.sel == selector)
})
}
function parse(event) {
var parts = ('' + event).split('.')
return {e: parts[0], ns: parts.slice(1).sort().join(' ')}
}
function matcherFor(ns) {
return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)')
}
function eventCapture(handler, captureSetting) {
return handler.del &&
(!focusinSupported && (handler.e in focus)) ||
!!captureSetting
}
function realEvent(type) {
return hover[type] || (focusinSupported && focus[type]) || type
}
function add(element, events, fn, data, selector, delegator, capture){
var id = zid(element), set = (handlers[id] || (handlers[id] = []))
events.split(/\s/).forEach(function(event){
if (event == 'ready') return $(document).ready(fn)
var handler = parse(event)
handler.fn = fn
handler.sel = selector
// emulate mouseenter, mouseleave
if (handler.e in hover) fn = function(e){
var related = e.relatedTarget
if (!related || (related !== this && !$.contains(this, related)))
return handler.fn.apply(this, arguments)
}
handler.del = delegator
var callback = delegator || fn
handler.proxy = function(e){
e = compatible(e)
if (e.isImmediatePropagationStopped()) return
e.data = data
var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args))
if (result === false) e.preventDefault(), e.stopPropagation()
return result
}
handler.i = set.length
set.push(handler)
if ('addEventListener' in element)
element.addEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
})
}
function remove(element, events, fn, selector, capture){
var id = zid(element)
;(events || '').split(/\s/).forEach(function(event){
findHandlers(element, event, fn, selector).forEach(function(handler){
delete handlers[id][handler.i]
if ('removeEventListener' in element)
element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
})
})
}
$.event = { add: add, remove: remove }
$.proxy = function(fn, context) {
if (isFunction(fn)) {
var proxyFn = function(){ return fn.apply(context, arguments) }
proxyFn._zid = zid(fn)
return proxyFn
} else if (isString(context)) {
return $.proxy(fn[context], fn)
} else {
throw new TypeError("expected function")
}
}
$.fn.bind = function(event, data, callback){
return this.on(event, data, callback)
}
$.fn.unbind = function(event, callback){
return this.off(event, callback)
}
$.fn.one = function(event, selector, data, callback){
return this.on(event, selector, data, callback, 1)
}
var returnTrue = function(){return true},
returnFalse = function(){return false},
ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$)/,
eventMethods = {
preventDefault: 'isDefaultPrevented',
stopImmediatePropagation: 'isImmediatePropagationStopped',
stopPropagation: 'isPropagationStopped'
}
function compatible(event, source) {
if (source || !event.isDefaultPrevented) {
source || (source = event)
$.each(eventMethods, function(name, predicate) {
var sourceMethod = source[name]
event[name] = function(){
this[predicate] = returnTrue
return sourceMethod && sourceMethod.apply(source, arguments)
}
event[predicate] = returnFalse
})
if (source.defaultPrevented !== undefined ? source.defaultPrevented :
'returnValue' in source ? source.returnValue === false :
source.getPreventDefault && source.getPreventDefault())
event.isDefaultPrevented = returnTrue
}
return event
}
function createProxy(event) {
var key, proxy = { originalEvent: event }
for (key in event)
if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key]
return compatible(proxy, event)
}
$.fn.delegate = function(selector, event, callback){
return this.on(event, selector, callback)
}
$.fn.undelegate = function(selector, event, callback){
return this.off(event, selector, callback)
}
$.fn.live = function(event, callback){
$(document.body).delegate(this.selector, event, callback)
return this
}
$.fn.die = function(event, callback){
$(document.body).undelegate(this.selector, event, callback)
return this
}
$.fn.on = function(event, selector, data, callback, one){
var autoRemove, delegator, $this = this
if (event && !isString(event)) {
$.each(event, function(type, fn){
$this.on(type, selector, data, fn, one)
})
return $this
}
if (!isString(selector) && !isFunction(callback) && callback !== false)
callback = data, data = selector, selector = undefined
if (isFunction(data) || data === false)
callback = data, data = undefined
if (callback === false) callback = returnFalse
return $this.each(function(_, element){
if (one) autoRemove = function(e){
remove(element, e.type, callback)
return callback.apply(this, arguments)
}
if (selector) delegator = function(e){
var evt, match = $(e.target).closest(selector, element).get(0)
if (match && match !== element) {
evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element})
return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1)))
}
}
add(element, event, callback, data, selector, delegator || autoRemove)
})
}
$.fn.off = function(event, selector, callback){
var $this = this
if (event && !isString(event)) {
$.each(event, function(type, fn){
$this.off(type, selector, fn)
})
return $this
}
if (!isString(selector) && !isFunction(callback) && callback !== false)
callback = selector, selector = undefined
if (callback === false) callback = returnFalse
return $this.each(function(){
remove(this, event, callback, selector)
})
}
$.fn.trigger = function(event, args){
event = (isString(event) || $.isPlainObject(event)) ? $.Event(event) : compatible(event)
event._args = args
return this.each(function(){
// items in the collection might not be DOM elements
if('dispatchEvent' in this) this.dispatchEvent(event)
else $(this).triggerHandler(event, args)
})
}
// triggers event handlers on current element just as if an event occurred,
// doesn't trigger an actual event, doesn't bubble
$.fn.triggerHandler = function(event, args){
var e, result
this.each(function(i, element){
e = createProxy(isString(event) ? $.Event(event) : event)
e._args = args
e.target = element
$.each(findHandlers(element, event.type || event), function(i, handler){
result = handler.proxy(e)
if (e.isImmediatePropagationStopped()) return false
})
})
return result
}
// shortcut methods for `.bind(event, fn)` for each event type
;('focusin focusout load resize scroll unload click dblclick '+
'mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave '+
'change select keydown keypress keyup error').split(' ').forEach(function(event) {
$.fn[event] = function(callback) {
return callback ?
this.bind(event, callback) :
this.trigger(event)
}
})
;['focus', 'blur'].forEach(function(name) {
$.fn[name] = function(callback) {
if (callback) this.bind(name, callback)
else this.each(function(){
try { this[name]() }
catch(e) {}
})
return this
}
})
$.Event = function(type, props) {
if (!isString(type)) props = type, type = props.type
var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true
if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name])
event.initEvent(type, bubbles, true)
return compatible(event)
}
})(Zepto)
;(function($){
var jsonpID = 0,
document = window.document,
key,
name,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
scriptTypeRE = /^(?:text|application)\/javascript/i,
xmlTypeRE = /^(?:text|application)\/xml/i,
jsonType = 'application/json',
htmlType = 'text/html',
blankRE = /^\s*$/
// trigger a custom event and return false if it was cancelled
function triggerAndReturn(context, eventName, data) {
var event = $.Event(eventName)
$(context).trigger(event, data)
return !event.isDefaultPrevented()
}
// trigger an Ajax "global" event
function triggerGlobal(settings, context, eventName, data) {
if (settings.global) return triggerAndReturn(context || document, eventName, data)
}
// Number of active Ajax requests
$.active = 0
function ajaxStart(settings) {
if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart')
}
function ajaxStop(settings) {
if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop')
}
// triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable
function ajaxBeforeSend(xhr, settings) {
var context = settings.context
if (settings.beforeSend.call(context, xhr, settings) === false ||
triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false)
return false
triggerGlobal(settings, context, 'ajaxSend', [xhr, settings])
}
function ajaxSuccess(data, xhr, settings, deferred) {
var context = settings.context, status = 'success'
settings.success.call(context, data, status, xhr)
if (deferred) deferred.resolveWith(context, [data, status, xhr])
triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data])
ajaxComplete(status, xhr, settings)
}
// type: "timeout", "error", "abort", "parsererror"
function ajaxError(error, type, xhr, settings, deferred) {
var context = settings.context
settings.error.call(context, xhr, type, error)
if (deferred) deferred.rejectWith(context, [xhr, type, error])
triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error || type])
ajaxComplete(type, xhr, settings)
}
// status: "success", "notmodified", "error", "timeout", "abort", "parsererror"
function ajaxComplete(status, xhr, settings) {
var context = settings.context
settings.complete.call(context, xhr, status)
triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings])
ajaxStop(settings)
}
// Empty function, used as default callback
function empty() {}
$.ajaxJSONP = function(options, deferred){
if (!('type' in options)) return $.ajax(options)
var _callbackName = options.jsonpCallback,
callbackName = ($.isFunction(_callbackName) ?
_callbackName() : _callbackName) || ('jsonp' + (++jsonpID)),
script = document.createElement('script'),
originalCallback = window[callbackName],
responseData,
abort = function(errorType) {
$(script).triggerHandler('error', errorType || 'abort')
},
xhr = { abort: abort }, abortTimeout
if (deferred) deferred.promise(xhr)
$(script).on('load error', function(e, errorType){
clearTimeout(abortTimeout)
$(script).off().remove()
if (e.type == 'error' || !responseData) {
ajaxError(null, errorType || 'error', xhr, options, deferred)
} else {
ajaxSuccess(responseData[0], xhr, options, deferred)
}
window[callbackName] = originalCallback
if (responseData && $.isFunction(originalCallback))
originalCallback(responseData[0])
originalCallback = responseData = undefined
})
if (ajaxBeforeSend(xhr, options) === false) {
abort('abort')
return xhr
}
window[callbackName] = function(){
responseData = arguments
}
script.src = options.url.replace(/\?(.+)=\?/, '?$1=' + callbackName)
document.head.appendChild(script)
if (options.timeout > 0) abortTimeout = setTimeout(function(){
abort('timeout')
}, options.timeout)
return xhr
}
$.ajaxSettings = {
// Default type of request
type: 'GET',
// Callback that is executed before request
beforeSend: empty,
// Callback that is executed if the request succeeds
success: empty,
// Callback that is executed the the server drops error
error: empty,
// Callback that is executed on request complete (both: error and success)
complete: empty,
// The context for the callbacks
context: null,
// Whether to trigger "global" Ajax events
global: true,
// Transport
xhr: function () {
return new window.XMLHttpRequest()
},
// MIME types mapping
// IIS returns Javascript as "application/x-javascript"
accepts: {
script: 'text/javascript, application/javascript, application/x-javascript',
json: jsonType,
xml: 'application/xml, text/xml',
html: htmlType,
text: 'text/plain'
},
// Whether the request is to another domain
crossDomain: false,
// Default timeout
timeout: 0,
// Whether data should be serialized to string
processData: true,
// Whether the browser should be allowed to cache GET responses
cache: true
}
function mimeToDataType(mime) {
if (mime) mime = mime.split(';', 2)[0]
return mime && ( mime == htmlType ? 'html' :
mime == jsonType ? 'json' :
scriptTypeRE.test(mime) ? 'script' :
xmlTypeRE.test(mime) && 'xml' ) || 'text'
}
function appendQuery(url, query) {
if (query == '') return url
return (url + '&' + query).replace(/[&?]{1,2}/, '?')
}
// serialize payload and append it to the URL for GET requests
function serializeData(options) {
if (options.processData && options.data && $.type(options.data) != "string")
options.data = $.param(options.data, options.traditional)
if (options.data && (!options.type || options.type.toUpperCase() == 'GET'))
options.url = appendQuery(options.url, options.data), options.data = undefined
}
$.ajax = function(options){
var settings = $.extend({}, options || {}),
deferred = $.Deferred && $.Deferred()
for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key]
ajaxStart(settings)
if (!settings.crossDomain) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) &&
RegExp.$2 != window.location.host
if (!settings.url) settings.url = window.location.toString()
serializeData(settings)
if (settings.cache === false) settings.url = appendQuery(settings.url, '_=' + Date.now())
var dataType = settings.dataType, hasPlaceholder = /\?.+=\?/.test(settings.url)
if (dataType == 'jsonp' || hasPlaceholder) {
if (!hasPlaceholder)
settings.url = appendQuery(settings.url,
settings.jsonp ? (settings.jsonp + '=?') : settings.jsonp === false ? '' : 'callback=?')
return $.ajaxJSONP(settings, deferred)
}
var mime = settings.accepts[dataType],
headers = { },
setHeader = function(name, value) { headers[name.toLowerCase()] = [name, value] },
protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol,
xhr = settings.xhr(),
nativeSetHeader = xhr.setRequestHeader,
abortTimeout
if (deferred) deferred.promise(xhr)
if (!settings.crossDomain) setHeader('X-Requested-With', 'XMLHttpRequest')
setHeader('Accept', mime || '*/*')
if (mime = settings.mimeType || mime) {
if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0]
xhr.overrideMimeType && xhr.overrideMimeType(mime)
}
if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET'))
setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded')
if (settings.headers) for (name in settings.headers) setHeader(name, settings.headers[name])
xhr.setRequestHeader = setHeader
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
xhr.onreadystatechange = empty
clearTimeout(abortTimeout)
var result, error = false
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) {
dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type'))
result = xhr.responseText
try {
// http://perfectionkills.com/global-eval-what-are-the-options/
if (dataType == 'script') (1,eval)(result)
else if (dataType == 'xml') result = xhr.responseXML
else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result)
} catch (e) { error = e }
if (error) ajaxError(error, 'parsererror', xhr, settings, deferred)
else ajaxSuccess(result, xhr, settings, deferred)
} else {
ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr, settings, deferred)
}
}
}
if (ajaxBeforeSend(xhr, settings) === false) {
xhr.abort()
ajaxError(null, 'abort', xhr, settings, deferred)
return xhr
}
if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name]
var async = 'async' in settings ? settings.async : true
xhr.open(settings.type, settings.url, async, settings.username, settings.password)
for (name in headers) nativeSetHeader.apply(xhr, headers[name])
if (settings.timeout > 0) abortTimeout = setTimeout(function(){
xhr.onreadystatechange = empty
xhr.abort()
ajaxError(null, 'timeout', xhr, settings, deferred)
}, settings.timeout)
// avoid sending empty string (#319)
xhr.send(settings.data ? settings.data : null)
return xhr
}
// handle optional data/success arguments
function parseArguments(url, data, success, dataType) {
if ($.isFunction(data)) dataType = success, success = data, data = undefined
if (!$.isFunction(success)) dataType = success, success = undefined
return {
url: url
, data: data
, success: success
, dataType: dataType
}
}
$.get = function(/* url, data, success, dataType */){
return $.ajax(parseArguments.apply(null, arguments))
}
$.post = function(/* url, data, success, dataType */){
var options = parseArguments.apply(null, arguments)
options.type = 'POST'
return $.ajax(options)
}
$.getJSON = function(/* url, data, success */){
var options = parseArguments.apply(null, arguments)
options.dataType = 'json'
return $.ajax(options)
}
$.fn.load = function(url, data, success){
if (!this.length) return this
var self = this, parts = url.split(/\s/), selector,
options = parseArguments(url, data, success),
callback = options.success
if (parts.length > 1) options.url = parts[0], selector = parts[1]
options.success = function(response){
self.html(selector ?
$('<div>').html(response.replace(rscript, "")).find(selector)
: response)
callback && callback.apply(self, arguments)
}
$.ajax(options)
return this
}
var escape = encodeURIComponent
function serialize(params, obj, traditional, scope){
var type, array = $.isArray(obj), hash = $.isPlainObject(obj)
$.each(obj, function(key, value) {
type = $.type(value)
if (scope) key = traditional ? scope :
scope + '[' + (hash || type == 'object' || type == 'array' ? key : '') + ']'
// handle data in serializeArray() format
if (!scope && array) params.add(value.name, value.value)
// recurse into nested objects
else if (type == "array" || (!traditional && type == "object"))
serialize(params, value, traditional, key)
else params.add(key, value)
})
}
$.param = function(obj, traditional){
var params = []
params.add = function(k, v){ this.push(escape(k) + '=' + escape(v)) }
serialize(params, obj, traditional)
return params.join('&').replace(/%20/g, '+')
}
})(Zepto)
;(function($){
$.fn.serializeArray = function() {
var result = [], el
$([].slice.call(this.get(0).elements)).each(function(){
el = $(this)
var type = el.attr('type')
if (this.nodeName.toLowerCase() != 'fieldset' &&
!this.disabled && type != 'submit' && type != 'reset' && type != 'button' &&
((type != 'radio' && type != 'checkbox') || this.checked))
result.push({
name: el.attr('name'),
value: el.val()
})
})
return result
}
$.fn.serialize = function(){
var result = []
this.serializeArray().forEach(function(elm){
result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value))
})
return result.join('&')
}
$.fn.submit = function(callback) {
if (callback) this.bind('submit', callback)
else if (this.length) {
var event = $.Event('submit')
this.eq(0).trigger(event)
if (!event.isDefaultPrevented()) this.get(0).submit()
}
return this
}
})(Zepto)
;(function($){
// __proto__ doesn't exist on IE<11, so redefine
// the Z function to use object extension instead
if (!('__proto__' in {})) {
$.extend($.zepto, {
Z: function(dom, selector){
dom = dom || []
$.extend(dom, $.fn)
dom.selector = selector || ''
dom.__Z = true
return dom
},
// this is a kludge but works
isZ: function(object){
return $.type(object) === 'array' && '__Z' in object
}
})
}
// getComputedStyle shouldn't freak out when called
// without a valid element as argument
try {
getComputedStyle(undefined)
} catch(e) {
var nativeGetComputedStyle = getComputedStyle;
window.getComputedStyle = function(element){
try {
return nativeGetComputedStyle(element)
} catch(e) {
return null
}
}
}
})(Zepto)
;(function($){
function detect(ua){
var os = this.os = {}, browser = this.browser = {},
webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/),
android = ua.match(/(Android);?[\s\/]+([\d.]+)?/),
osx = !!ua.match(/\(Macintosh\; Intel /),
ipad = ua.match(/(iPad).*OS\s([\d_]+)/),
ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/),
iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),
touchpad = webos && ua.match(/TouchPad/),
kindle = ua.match(/Kindle\/([\d.]+)/),
silk = ua.match(/Silk\/([\d._]+)/),
blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/),
bb10 = ua.match(/(BB10).*Version\/([\d.]+)/),
rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/),
playbook = ua.match(/PlayBook/),
chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/),
firefox = ua.match(/Firefox\/([\d.]+)/),
ie = ua.match(/MSIE\s([\d.]+)/) || ua.match(/Trident\/[\d](?=[^\?]+).*rv:([0-9.].)/),
webview = !chrome && ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/),
safari = webview || ua.match(/Version\/([\d.]+)([^S](Safari)|[^M]*(Mobile)[^S]*(Safari))/)
// Todo: clean this up with a better OS/browser seperation:
// - discern (more) between multiple browsers on android
// - decide if kindle fire in silk mode is android or not
// - Firefox on Android doesn't specify the Android version
// - possibly devide in os, device and browser hashes
if (browser.webkit = !!webkit) browser.version = webkit[1]
if (android) os.android = true, os.version = android[2]
if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.')
if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.')
if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null
if (webos) os.webos = true, os.version = webos[2]
if (touchpad) os.touchpad = true
if (blackberry) os.blackberry = true, os.version = blackberry[2]
if (bb10) os.bb10 = true, os.version = bb10[2]
if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2]
if (playbook) browser.playbook = true
if (kindle) os.kindle = true, os.version = kindle[1]
if (silk) browser.silk = true, browser.version = silk[1]
if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true
if (chrome) browser.chrome = true, browser.version = chrome[1]
if (firefox) browser.firefox = true, browser.version = firefox[1]
if (ie) browser.ie = true, browser.version = ie[1]
if (safari && (osx || os.ios)) {browser.safari = true; if (osx) browser.version = safari[1]}
if (webview) browser.webview = true
os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
(firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)))
os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos || blackberry || bb10 ||
(chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
(firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))))
}
detect.call($, navigator.userAgent)
// make available to unit tests
$.__detect = detect
})(Zepto)
|
var mailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var config = require('../config');
var util = require('util');
var transport = mailer.createTransport(smtpTransport(config.mail_opts));
//域名domain没有的时留空,devMode下读取host
var SITE_ROOT_URL = 'http://' + ((config.domain && !config.devMode)?config.domain:(config.host+":"+config.port));
/**
* Send an email
* @param {Object} data 邮件对象
*/
var sendMail = function (data) {
//need_active_mail=false不发送邮件
if (!config.need_active_mail) {
return;
}
// 遍历邮件数组,发送每一封邮件,如果有发送失败的,就再压入数组,同时触发mailEvent事件
transport.sendMail(data, function (err) {
if (err) {
// 写为日志
console.log(err);
}
});
};
exports.sendMail = sendMail;
/**
* 发送激活通知邮件
* @param {String} who 接收人的邮件地址
* @param {String} token 重置用的token字符串
* @param {String} name 接收人的用户名
*/
exports.sendActiveMail = function (who, token, name) {
var from = util.format('%s <%s>', config.name, config.mail_opts.auth.user);
var to = who;
var subject = config.name + '帐号激活';
var html = '<p>您好:' + name + '</p>' +
'<p>我们收到您在' + config.name + '的注册信息,请点击下面的链接来激活帐户:</p>' +
'<a href = "' + SITE_ROOT_URL + '/active_account?key=' + token + '&name=' + name + '">激活链接</a>' +
'<p>若您没有在' + config.name + '填写过注册信息,说明有人滥用了您的电子邮箱,请删除此邮件,我们对给您造成的打扰感到抱歉。</p>' +
'<p>' + config.name + ' 谨上。</p>';
exports.sendMail({
from: from,
to: to,
subject: subject,
html: html
});
};
/**
* 发送密码重置通知邮件
* @param {String} who 接收人的邮件地址
* @param {String} token 重置用的token字符串
* @param {String} name 接收人的用户名
*/
exports.sendResetPassMail = function (who, token, name) {
var from = util.format('%s <%s>', config.name, config.mail_opts.auth.user);
var to = who;
var subject = config.name + '密码重置';
var html = '<p>您好:' + name + '</p>' +
'<p>我们收到您在' + config.name + '重置密码的请求,请在24小时内单击下面的链接来重置密码:</p>' +
'<a href="' + SITE_ROOT_URL + '/reset_pass?key=' + token + '&name=' + name + '">重置密码链接</a>' +
'<p>若您没有在' + config.name + '填写过注册信息,说明有人滥用了您的电子邮箱,请删除此邮件,我们对给您造成的打扰感到抱歉。</p>' +
'<p>' + config.name + ' 谨上。</p>';
exports.sendMail({
from: from,
to: to,
subject: subject,
html: html
});
};
|
import React from 'react';
import IconBase from 'react-icon-base';
export default class FaUserMd extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m13.1 30q0 0.6-0.5 1t-1 0.4-1-0.4-0.4-1 0.4-1 1-0.4 1 0.4 0.5 1z m22.8 1.4q0 2.7-1.6 4.2t-4.3 1.5h-19.5q-2.7 0-4.4-1.5t-1.6-4.2q0-1.6 0.1-3t0.6-3 1-3 1.8-2.3 2.7-1.4q-0.5 1.2-0.5 2.7v4.6q-1.3 0.4-2.1 1.5t-0.7 2.5q0 1.8 1.2 3t3 1.3 3.1-1.3 1.2-3q0-1.4-0.8-2.5t-2-1.5v-4.6q0-1.4 0.5-2 3 2.3 6.6 2.3t6.6-2.3q0.6 0.6 0.6 2v1.5q-2.4 0-4.1 1.6t-1.7 4.1v2q-0.7 0.6-0.7 1.5 0 0.9 0.7 1.6t1.5 0.6 1.5-0.6 0.6-1.6q0-0.9-0.7-1.5v-2q0-1.2 0.9-2t2-0.9 2 0.9 0.8 2v2q-0.7 0.6-0.7 1.5 0 0.9 0.6 1.6t1.5 0.6 1.6-0.6 0.6-1.6q0-0.9-0.7-1.5v-2q0-1.5-0.8-2.9t-2.1-2.1q0-0.2 0-0.9t0-1.1 0-0.9-0.2-1.1-0.3-0.8q1.5 0.3 2.7 1.3t1.8 2.3 1.1 3 0.5 3 0.1 3z m-7.1-20q0 3.6-2.5 6.1t-6.1 2.5-6-2.5-2.6-6.1 2.6-6 6-2.5 6.1 2.5 2.5 6z"/></g>
</IconBase>
);
}
}
|
class KnormError extends Error {
constructor(...args) {
const [message] = args;
const hasMessage = typeof message === 'string';
super(hasMessage ? message : undefined);
if (!hasMessage) {
this.message = this.formatMessage(...args);
}
this.name = this.constructor.name;
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = new Error(this.message).stack;
}
}
formatMessage(message) {
return message;
}
}
export { KnormError };
|
import { AsyncStorage } from 'react-native';
import {applyMiddleware, compose, createStore} from 'redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import client from './apolloClient';
import { initialState as configs } from '../reducers/configurations';
import rootReducer from '../reducers/index'
import {autoRehydrate, persistStore} from "redux-persist";
const isProduction = process.env.NODE_ENV !== 'development';
const isClient = typeof document !== 'undefined';
const initialState = {
configs,
};
/* Commonly used middlewares and enhancers */
/* See: http://redux.js.org/docs/advanced/Middleware.html*/
const middlewares = [thunk, client.middleware()];
const enhancers = [];
if (!isProduction && isClient) {
const loggerMiddleware = createLogger();
middlewares.push(loggerMiddleware);
if (typeof devToolsExtension === 'function') {
const devToolsExtension = window.devToolsExtension;
enhancers.push(devToolsExtension());
}
}
const composedEnhancers = compose(
applyMiddleware(...middlewares),
...enhancers
);
/* Hopefully by now you understand what a store is and how redux uses them,
* But if not, take a look at: https://github.com/reactjs/redux/blob/master/docs/api/createStore.md
* And https://egghead.io/lessons/javascript-redux-implementing-store-from-scratch
*/
const store = createStore(
rootReducer,
initialState,
composedEnhancers,
autoRehydrate(),
);
// Add the autoRehydrate middleware to your redux store
//const store_ = createStore(rootReducer, autoRehydrate());
//const createStoreWithMiddleware = applyMiddleware(...middlewares)(store);
/* See: https://github.com/reactjs/react-router-redux/issues/305 */
//export const history = syncHistoryWithStore(browserHistory, store);
/* Hot reloading of reducers. How futuristic!! */
/*if (module.hot) {
module.hot.accept('./reducers', () => {
/!*eslint-disable *!/ // Allow require
const nextRootReducer = require('./reducers').default;
/!*eslint-enable *!/
store.replaceReducer(nextRootReducer);
});
}*/
//export { store };
export default configureStore = (navReducer, onComplete) => {
let store = createStore(
rootReducer,
initialState,
composedEnhancers,
autoRehydrate(),
);
persistStore(store, { storage: AsyncStorage }, onComplete);
return store;
};
|
// @ts-check
/*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* @typedef {import('playwright').Page} Page
*/
const
h = include('tests/helpers');
/** @param {Page} page */
module.exports = (page) => {
beforeEach(async () => {
await page.evaluate(() => {
globalThis.removeCreatedComponents();
});
});
describe('b-checkbox simple usage', () => {
const
q = '[data-id="target"]';
it('providing of attributes', async () => {
await init({id: 'foo', name: 'bla'});
const
input = await page.$('#foo');
expect(
await input.evaluate((ctx) => [
ctx.tagName,
ctx.type,
ctx.name,
ctx.checked
])
).toEqual(['INPUT', 'checkbox', 'bla', false]);
});
it('checked checkbox', async () => {
const target = await init({checked: true, value: 'bar'});
expect(
await target.evaluate((ctx) => ctx.value)
).toBe('bar');
});
it('non-changeable checkbox', async () => {
const target = await init({changeable: false});
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
await page.click(q);
expect(
await target.evaluate((ctx) => ctx.value)
).toBeTrue();
await page.click(q);
expect(
await target.evaluate((ctx) => ctx.value)
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.uncheck())
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
});
it('checking a non-defined value (user actions)', async () => {
const target = await init();
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
await page.click(q);
expect(
await target.evaluate((ctx) => ctx.value)
).toBeTrue();
await page.click(q);
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
});
it('checking a predefined value (user actions)', async () => {
const target = await init({value: 'bar'});
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
await page.click(q);
expect(
await target.evaluate((ctx) => ctx.value)
).toBe('bar');
await page.click(q);
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
});
it('checking a non-defined value (API)', async () => {
const target = await init();
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
expect(
await target.evaluate((ctx) => ctx.check())
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.value)
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.uncheck())
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
expect(
await target.evaluate((ctx) => ctx.toggle())
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.toggle())
).toBeUndefined();
});
it('checking a predefined value (API)', async () => {
const target = await init({value: 'bar'});
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
expect(
await target.evaluate((ctx) => ctx.check())
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.value)
).toBe('bar');
expect(
await target.evaluate((ctx) => ctx.uncheck())
).toBeTrue();
expect(
await target.evaluate((ctx) => ctx.value)
).toBeUndefined();
expect(
await target.evaluate((ctx) => ctx.toggle())
).toBe('bar');
expect(
await target.evaluate((ctx) => ctx.toggle())
).toBeUndefined();
});
it('checkbox with a `label` prop', async () => {
const target = await init({
label: 'Foo'
});
expect(
await target.evaluate((ctx) => ctx.block.element('label').textContent.trim())
).toEqual('Foo');
const selector = await target.evaluate(
(ctx) => `.${ctx.block.element('label').className.split(' ').join('.')}`
);
await page.click(selector);
expect(
await target.evaluate((ctx) => ctx.value)
).toBeTrue();
});
async function init(attrs = {}) {
await page.evaluate((attrs) => {
const scheme = [
{
attrs: {
'data-id': 'target',
...attrs
}
}
];
globalThis.renderComponents('b-checkbox', scheme);
}, attrs);
return h.component.waitForComponent(page, q);
}
});
};
|
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import Collapse from '../Collapse';
import withStyles from '../styles/withStyles';
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
marginTop: 8,
marginLeft: 12, // half icon
paddingLeft: 8 + 12, // margin + half icon
paddingRight: 8,
borderLeft: `1px solid ${
theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[600]
}`,
},
/* Styles applied to the root element if `last={true}` (controlled by `Step`). */
last: {
borderLeft: 'none',
},
/* Styles applied to the Transition component. */
transition: {},
});
const StepContent = React.forwardRef(function StepContent(props, ref) {
const {
active,
alternativeLabel,
children,
classes,
className,
completed,
last,
optional,
orientation,
TransitionComponent = Collapse,
transitionDuration: transitionDurationProp = 'auto',
TransitionProps,
...other
} = props;
if (process.env.NODE_ENV !== 'production') {
if (orientation !== 'vertical') {
console.error(
'Material-UI: <StepContent /> is only designed for use with the vertical stepper.',
);
}
}
let transitionDuration = transitionDurationProp;
if (transitionDurationProp === 'auto' && !TransitionComponent.muiSupportAuto) {
transitionDuration = undefined;
}
return (
<div className={clsx(classes.root, { [classes.last]: last }, className)} ref={ref} {...other}>
<TransitionComponent
in={active}
className={classes.transition}
timeout={transitionDuration}
unmountOnExit
{...TransitionProps}
>
{children}
</TransitionComponent>
</div>
);
});
StepContent.propTypes = {
/**
* @ignore
* Expands the content.
*/
active: PropTypes.bool,
/**
* @ignore
* Set internally by Step when it's supplied with the alternativeLabel prop.
*/
alternativeLabel: PropTypes.bool,
/**
* Step content.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* @ignore
*/
completed: PropTypes.bool,
/**
* @ignore
*/
last: PropTypes.bool,
/**
* @ignore
* Set internally by Step when it's supplied with the optional prop.
*/
optional: PropTypes.bool,
/**
* @ignore
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical']),
/**
* The component used for the transition.
*/
TransitionComponent: PropTypes.elementType,
/**
* Adjust the duration of the content expand transition.
* Passed as a prop to the transition component.
*
* Set to 'auto' to automatically calculate transition time based on height.
*/
transitionDuration: PropTypes.oneOfType([
PropTypes.number,
PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }),
PropTypes.oneOf(['auto']),
]),
/**
* Props applied to the `Transition` element.
*/
TransitionProps: PropTypes.object,
};
export default withStyles(styles, { name: 'MuiStepContent' })(StepContent);
|
var fs = require("fs");
var http = require("http");
var fileName = __dirname + "/ipsum.txt";
var server = http.createServer(function (req, res) {
fs.exists(fileName, function(exists) {
if (exists) {
fs.stat(fileName, function(error, stats) {
if (error) {
throw error;
}
if (stats.isFile()) {
var stream = fs.createReadStream(fileName);
stream.pipe(res);
}
});
}
});
}).listen(process.env.PORT || 8000, process.env.HOST || "0.0.0.0", function() {
console.log("HTTP Server Started. Listening on " + server.address().address + " : Port " + server.address().port);
});
|
angular
.module('ScheduleModule')
.controller('DialogController',
function($scope, $rootScope, $mdDialog, scheduleHourService, orientation, users, user, newScheduleHour,
saveEnum, serverService, authorityEnum, userService) {
var self = this;
var workplaces = $rootScope.properties.workplaces;
var tempAddedScheduleHours = $scope.sch.tempAddedScheduleHours;
var tempRemovedScheduleHours = $scope.sch.tempRemovedScheduleHours;
var index, existsInTemp, scheduleHours;
var ordered = userService.getArrayOfIdsOrderedBy(users, 'name');
var nonordered = userService.getArrayOfIds(users);
serverService.getScheduleDataFromServerByCurrentWeek($scope.sch.currentWeek).then(function(answer) {
scheduleHours = answer.concat($scope.sch.tempAddedScheduleHours);
scheduleHours = scheduleHourService.scheduleHoursWithoutTemp(scheduleHours, $scope.sch.tempRemovedScheduleHours);
self.prefs = scheduleHourService
.checkScheduleForOpenMenu(newScheduleHour, scheduleHours, tempAddedScheduleHours, orientation, users, workplaces);
});
self.isAdmin = user.authority === authorityEnum.ADMIN;
self.saveEnum = saveEnum;
self.save = function(saveState, data) {
if (saveState === saveEnum.PLACE) newScheduleHour.place = data;
if (saveState === saveEnum.PERSONID) newScheduleHour.peopleId = nonordered[ordered.indexOf(data)];
if (saveState === saveEnum.DISABLED) newScheduleHour.peopleId = 0;
if(!self.isAdmin) {
tempAddedScheduleHours.push(newScheduleHour);
scheduleHours.push(newScheduleHour);
$scope.sch.scheduleHours = scheduleHours;
}
if(self.isAdmin)
serverService.addScheduleHour(newScheduleHour, scheduleHours).then(function(answer) {
$scope.sch.scheduleHours = answer;
});
$mdDialog.hide();
};
self.replace = function(targetScheduleHour, data, saveState) {
if(!self.isAdmin) {
index = tempAddedScheduleHours.indexOf(targetScheduleHour);
existsInTemp = index !== -1;
if(existsInTemp)
tempAddedScheduleHours.splice(index, 1);
else
tempRemovedScheduleHours.push(newScheduleHour);
index = scheduleHours.indexOf(targetScheduleHour);
scheduleHours.splice(index, 1);
targetScheduleHour = angular.copy(targetScheduleHour);
if (saveState === saveEnum.PLACE) targetScheduleHour.place = data;
if (saveState === saveEnum.PERSONID) targetScheduleHour.peopleId = nonordered[ordered.indexOf(data)];
tempAddedScheduleHours.push(targetScheduleHour);
scheduleHours.push(targetScheduleHour);
$scope.sch.scheduleHours = scheduleHours;
}
if(self.isAdmin)
serverService.replaceScheduleHour(targetScheduleHour, scheduleHours, saveState, data).then(function(answer) {
$scope.sch.scheduleHours = answer;
});
$mdDialog.hide();
};
self.remove = function(targetScheduleHour) {
if(!self.isAdmin) {
index = tempAddedScheduleHours.indexOf(targetScheduleHour);
existsInTemp = index !== -1;
if(existsInTemp)
tempAddedScheduleHours.splice(index, 1);
else
tempRemovedScheduleHours.push(targetScheduleHour);
index = scheduleHours.indexOf(targetScheduleHour);
scheduleHours.splice(index, 1);
$scope.sch.scheduleHours = scheduleHours;
}
if(self.isAdmin)
serverService.removeScheduleHour(targetScheduleHour, scheduleHours).then(function(answer) {
$scope.sch.scheduleHours = answer;
});
$mdDialog.hide();
};
self.extend = function(targetScheduleHour) {
var activeRange = moment.duration(5, 'hours')
.afterMoment(moment(newScheduleHour.dateHourStart).minute(0).second(0));
var shRange = moment.duration(targetScheduleHour.hours, 'hours')
.afterMoment(moment(targetScheduleHour.dateHourStart).minute(0).second(0));
var unionRange = activeRange.union(shRange);
var unionScheduleHour = {
dateHourStart: unionRange.start().format('YYYY-MM-DD HH:mm:ss'),
hours: unionRange.length("hours"),
peopleId: targetScheduleHour.peopleId,
place: targetScheduleHour.place
};
if(!self.isAdmin) {
index = tempAddedScheduleHours.indexOf(targetScheduleHour);
existsInTemp = index !== -1;
if(existsInTemp)
tempAddedScheduleHours.splice(index, 1);
else
tempRemovedScheduleHours.push(targetScheduleHour);
index = scheduleHours.indexOf(targetScheduleHour);
scheduleHours.splice(index, 1);
tempAddedScheduleHours.push(unionScheduleHour);
scheduleHours.push(unionScheduleHour);
$scope.sch.scheduleHours = scheduleHours;
}
if(self.isAdmin)
serverService.extendScheduleHour(targetScheduleHour, unionScheduleHour, scheduleHours).then(function(answer) {
$scope.sch.scheduleHours = answer;
});
$mdDialog.hide();
};
self.hide = function() {
$mdDialog.hide();
};
}
);
|
'use strict';
module.exports = function (t, a) {
a(t(), false, "Undefined");
a(t(1), false, "Primitive");
a(t({}), false, "Objectt");
a(t({
toString: function () {
return '[object Error]';
}
}), false,
"Fake error");
a(t(new Error()), true, "Error");
a(t(new EvalError()), true, "EvalError");
a(t(new RangeError()), true, "RangeError");
a(t(new ReferenceError()), true, "ReferenceError");
a(t(new SyntaxError()), true, "SyntaxError");
a(t(new TypeError()), true, "TypeError");
a(t(new URIError()), true, "URIError");
};
|
var config = require('./config'),
db;
function warn() {
console.warn('[WARN] MongoDB:', [].join.call(arguments, ' '));
}
function getDB(done) {
if (db) return done(db);
if (!config.mongoURI) return warn('No DB configured!');
require('mongodb').MongoClient.connect(config.mongoURI, function(err, _db) {
if (err) return warn('Failed to connect ->', err.message);
db = _db;
done(db);
});
}
function store(coll, data) {
data.now = new Date().toISOString();
getDB(function(db) {
db.collection(coll).insert(data, function(err) {
if (err) warn('Failed to insert to', coll, '->', err.message);
// Do nothing
});
});
}
exports.getEmailsByTo = function(to, done) {
getDB(function(db) {
db.collection(config.emailsCollection).find({to:to}).toArray(done);
});
};
exports.storeEmail = function(data) {
store(config.emailsCollection, data);
};
exports.storeError = function(data) {
store(config.errorsCollection, data);
};
|
export default class TeamScoreModel {
constructor(props) {
this.id = props.id
this.teamId = props.team_id
this.defencePoints = props.defence_points
this.attackPoints = props.attack_points
}
get totalPoints() {
return this.defencePoints + this.attackPoints
}
}
|
// Multiform extraction
|
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module', '../util/data'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module, require('../util/data'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod, global.data);
global.attached = mod.exports;
}
})(this, function (exports, module, _utilData) {
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _data = _interopRequireDefault(_utilData);
module.exports = function (opts) {
return function () {
var info = (0, _data['default'])(this, 'lifecycle/' + opts.id);
if (info.attached) return;
info.attached = true;
info.detached = false;
opts.attached(this);
};
};
});
|
var Col = require('./Col')
module.exports = Col
// export { default } from './Col'
|
// ___ ____ __ __
// / _ `/ _ \\ \ /
// \_,_/ .__/_\_\
// /_/
//
// 過去は未来によって変えられる。
//
// Copyright (c) 2014 Kenan Sulayman aka apx
//
// Based on third-party code:
//
// Copyright (c) 2010 Tom Hughes-Croucher
//
// 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.
var dgram = require("dgram"),
util = require("util");
var host = "localhost",
port = process.env.port || 53;
const rev = 13;
var server = dgram.createSocket("udp4");
var dnx = Object.create({
records: {},
addRecord: function (domain) {
this.records[domain] = {
in: {
a: []//,
// not implemented
}
};
var qname = this.toolchain.utils.domainToQname(domain);
return {
delegate: function (r) {
if ( typeof r.rdata === "string" ) {
r.rdata = this.toolchain.utils.ip2dec(r.rdata);
}
if ( !r["qname"] ) {
r["qname"] = qname;
}
r["zname"] = domain;
if ( !this.records[domain] )
this.records[domain] = {};
if ( !this.records[domain]["in"] )
this.records[domain]["in"] = {};
if ( !this.records[domain]["in"][r.type || "a"] )
this.records[domain]["in"][r.type || "a"] = [];
return this.records[domain]["in"][r.type || "a"].push(r), r;
}.bind(this)
};
},
server: server,
toolchain: require("./lib/toolchain")
});
server.on("message", function(msg, rinfo) {
// parse query
var q = dnx.toolchain.processRequest(msg);
// build response
var buf = dnx.toolchain.createResponse(q, dnx.records);
dnx.server.send(buf, 0, buf.length, rinfo.port, rinfo.address);
});
server.addListener("error", function(e) {
throw e;
});
var config = require("./config.json");
Object.keys(config).forEach(function (e) {
var r = dnx.addRecord(e)
config[e].forEach(function (rx) {
r.delegate(rx);
})
})
server.bind(port, host);
console.log([
" __ ",
" ___/ /__ __ __",
"/ _ / _ \\\\ \\ /",
"\\_,_/_//_/_\\_\\",
" \t",
"[dnx r" + rev + "]",
""
].join("\n"))
require("dns").resolve(host, function (err, data) {
var revlookup = data ? " (" + data.join(", ") + ")" : "";
console.log("Delegation:");
Object.keys(dnx.records).forEach(function (d) {
console.log("\t=> ", d);
Object.keys(dnx.records[d]).forEach(function (c) {
Object.keys(dnx.records[d][c]).forEach(function (r) {
console.log("\t\t" + c + ": " + r + ":");
dnx.records[d][c][r].forEach(function (rx) {
console.log("\t\t\t", rx.qname, " (" + rx["zname"] + "): ", util.inspect(rx, {depth: null}).split("{ ").join("{\n ").split("\n").join("\n\t\t\t\t").split(" }").join("\n\t\t\t }"))
})
})
});
})
process.stdout.write("\nStarted server: " + host + revlookup + ", using port " + port + ".");
});
|
'use strict'
import trumpet from 'trumpet'
import { trumpetInnerText } from './index'
import JsonStream from 'JSONStream'
// Myfox page not found is a code 200... must fix it!
const notFound200 = function () {
const parser = trumpet()
parser.select('head title', trumpetInnerText((data) => {
parser.status = 200
if (data.indexOf('Page not found') !== -1) {
parser.status = 404
const error = new Error('Page not found case returned by Myfox.')
error.status = 404
return parser.emit('error', error)
}
}))
return parser
}
// Myfox code KO is a code 200... must fix it and return error messages.
const codeKo200 = function () {
const parser = JsonStream.parse('code')
parser.on('data', (data) => {
if (data === 'KO') {
const error = new Error('Code KO returned by Myfox.')
error.status = 400
return parser.emit('error', error)
}
})
return parser
}
export { notFound200 as notFound200 }
export { codeKo200 as codeKo200 }
|
const chalk = require('chalk');
const { curry } = require('ramda');
const log = curry((color, string) => console.info(color(string)));
const good = log(chalk.green);
const info = log(chalk.cyan);
const warn = log(chalk.magenta);
const bad = log(chalk.red.bold);
module.exports = (server, port) => {
const resolve = (signal) => {
info('\n');
info(`Signal ${signal} received`);
info(`Express is shutting down on http://localhost:${port}`);
server.close();
good('\nThe server shutdown gracefully');
};
const reject = (signal, error) => {
warn('\nThe server did NOT shutdown gracefully\n');
bad(error);
};
const shutdown = (signal) => {
try {
resolve(signal);
process.exit(0);
} catch (error) {
reject(signal, error);
process.exit(-1);
}
};
const signals = ['SIGTERM', 'SIGHUP', 'SIGINT'];
signals.forEach(signal => process.on(signal, () => shutdown(signal)));
};
|
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const WebpackShellPlugin = require('webpack-shell-plugin');
const { join, resolve } = require('path');
var BUILD_DIR = resolve(__dirname, '../../priv/static');
var APP_DIR = __dirname;
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var config = {
entry:{
'app.bundle': [resolve(__dirname, 'js/App.jsx')],
'store.bundle': [resolve(__dirname, 'js/app/store.js')],
'dependencies.bundle': [
"react",
"react-dom",
"react-redux",
"redux-thunk",
"redux-logger",
"react-router-redux",
"react-router-dom",
"history",
"react-apollo",
"qrcode.react",
"graphql-tag",
"react-select",
"apollo-phoenix-websocket",
"jquery",
"phoenix",
"bootstrap",
]
},
output: {
path: BUILD_DIR,
publicPath: '/js',
filename: 'js/[name].js'
},
plugins: [
new WebpackShellPlugin({onBuildStart:['cp -R ../shared .']}),
new webpack.SourceMapDevToolPlugin(),
new ExtractTextPlugin('css/app.css', { allChunks: true }),
new webpack.EnvironmentPlugin({
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
DEBUG: process.env.NODE_ENV == 'development'
}),
new webpack.optimize.CommonsChunkPlugin({ name: "dependencies.bundle", filename: 'js/[name].js', minChunks: Infinity }),
// new webpack.ProvidePlugin({
// Promise: 'babel-polyfill'
// }),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
}),
new CopyWebpackPlugin([{ from: resolve(join(__dirname, "./assets")) }], { ignore: [resolve(join(__dirname, '.gitkeep'))] })
],
resolve: {
extensions: ['.json', '.jsx', '.js']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
include: __dirname,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015', 'react', 'stage-0'],
plugins: ['transform-decorators-legacy', 'transform-class-properties', ["resolver", { "resolveDirs": [resolve(join(__dirname, 'js'))] }]]
}
}
},
{
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" }
]
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
//resolve-url-loader may be chained before sass-loader if necessary
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: 'graphql-tag/loader',
}
// { test: /\.png$/, loader: "url-loader?limit=100000" },
// { test: /\.jpg$/, loader: "file-loader" },
// { test: /\.(woff2?|svg)$/, loader: 'url?limit=10000' },
// { test: /\.(ttf|eot)$/, loader: 'file' },
// { test: /\.json$/, loader: "json-loader" }
]
}
};
module.exports = config;
|
var classNames = require('classnames');
var React = require('react/addons');
var Tappable = require('react-tappable');
var Transition = React.addons.CSSTransitionGroup;
var defaultControllerState = {
direction: 0,
fade: false,
leftArrow: false,
leftButtonDisabled: false,
leftIcon: '',
leftLabel: '',
leftAction: null,
rightArrow: false,
rightButtonDisabled: false,
rightIcon: '',
rightLabel: '',
rightAction: null,
title: ''
};
function newState (from) {
var ns = Object.assign({}, defaultControllerState);
if (from) Object.assign(ns, from);
delete ns.name; // may leak from props
return ns;
}
var NavigationBar = React.createClass({
contextTypes: {
app: React.PropTypes.object
},
propTypes: {
name: React.PropTypes.string
},
getInitialState () {
return newState(this.props);
},
componentDidMount () {
if (this.props.name) {
this.context.app.navigationBars[this.props.name] = this;
}
},
componentWillUnmount () {
if (this.props.name) {
delete this.context.app.navigationBars[this.props.name];
}
},
componentWillReceiveProps (nextProps) {
this.setState(newState(nextProps));
if (nextProps.name !== this.props.name) {
if (nextProps.name) {
this.context.app.navigationBars[nextProps.name] = this;
}
if (this.props.name) {
delete this.context.app.navigationBars[this.props.name];
}
}
},
update (state) {
state = newState(state);
// console.info('Updating NavigationBar ' + this.props.name, state);
this.setState(newState(state));
},
updateWithTransition (state, transition) {
state = newState(state);
if (transition === ('show-from-right' || 'reveal-from-left')) {
state.direction = 1;
} else if (transition === ('reveal-from-right' || 'show-from-left')) {
state.direction = -1;
} else if (transition === 'fade') {
state.fade = true;
}
// console.info('Updating NavigationBar ' + this.props.name + ' with transition ' + transition, state);
this.setState(state);
},
renderLeftButton () {
var className = classNames('NavigationBarLeftButton', {
'has-icon': this.state.leftArrow || this.state.leftIcon
});
return (
<Tappable onTap={this.state.leftAction} className={className} disabled={this.state.leftButtonDisabled} component="button">
{this.renderLeftArrow()}
{this.renderLeftIcon()}
{this.renderLeftLabel()}
</Tappable>
);
},
renderLeftArrow () {
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade || this.state.direction) {
transitionName = 'NavigationBarTransition-Fade';
}
var arrow = this.state.leftArrow ? <span className="NavigationBarLeftArrow" /> : null;
return (
<Transition transitionName={transitionName}>
{arrow}
</Transition>
);
},
renderLeftIcon () {
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade || this.state.direction) {
transitionName = 'NavigationBarTransition-Fade';
}
var className = classNames('NavigationBarLeftIcon', this.state.leftIcon);
var icon = this.state.leftIcon ? <span className={className} /> : null;
return (
<Transition transitionName={transitionName}>
{icon}
</Transition>
);
},
renderLeftLabel () {
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade) {
transitionName = 'NavigationBarTransition-Fade';
} else if (this.state.direction > 0) {
transitionName = 'NavigationBarTransition-Forwards';
} else if (this.state.direction < 0) {
transitionName = 'NavigationBarTransition-Backwards';
}
return (
<Transition transitionName={transitionName}>
<span key={Date.now()} className="NavigationBarLeftLabel">{this.state.leftLabel}</span>
</Transition>
);
},
renderTitle () {
var title = this.state.title ? <span key={Date.now()} className="NavigationBarTitle">{this.state.title}</span> : null;
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade) {
transitionName = 'NavigationBarTransition-Fade';
} else if (this.state.direction > 0) {
transitionName = 'NavigationBarTransition-Forwards';
} else if (this.state.direction < 0) {
transitionName = 'NavigationBarTransition-Backwards';
}
return (
<Transition transitionName={transitionName}>
<Tappable onTap={this.state.titleAction}>
{title}
</Tappable>
</Transition>
);
},
renderRightButton () {
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade || this.state.direction) {
transitionName = 'NavigationBarTransition-Fade';
}
var button = (this.state.rightIcon || this.state.rightLabel) ? (
<Tappable key={Date.now()} onTap={this.state.rightAction} className="NavigationBarRightButton" disabled={this.state.rightButtonDisabled} component="button">
{this.renderRightLabel()}
{this.renderRightIcon()}
</Tappable>
) : null;
return (
<Transition transitionName={transitionName}>
{button}
</Transition>
);
},
renderRightIcon () {
if (!this.state.rightIcon) return null;
var className = classNames('NavigationBarRightIcon', this.state.rightIcon);
return <span className={className} />;
},
renderRightLabel () {
return this.state.rightLabel ? <span key={Date.now()} className="NavigationBarRightLabel">{this.state.rightLabel}</span> : null;
},
render () {
var className = classNames('NavigationBar', {
'has-left-arrow': this.state.leftArrow,
'has-left-icon': this.state.leftIcon,
'has-left-label': this.state.leftLabel,
'has-right-icon': this.state.rightIcon,
'has-right-label': this.state.rightLabel
});
return (
<div className={className}>
{this.renderLeftButton()}
{this.renderTitle()}
{this.renderRightButton()}
</div>
);
}
});
/*
function createController () {
var state = newState();
var listeners = [];
return {
update (ns) {
state = newState(ns);
listeners.forEach(fn => fn());
},
getState () {
return state;
},
addListener (fn) {
listeners.push(fn);
},
removeListener (fn) {
listeners = listeners.filter(i => fn !== i);
}
};
}
*/
export default NavigationBar;
|
define(['../../game', 'collectableItem', 'states/levels/LevelState'], function (game, CollectableItem, Parent) {
var map,
levelThreeFirstLayerBackground,
levelThreeSecondLayerPlatforms,
shampoosGroup,
shampoosCoordinates;
function Level3State() {
};
Level3State.prototype = new Parent();
Level3State.prototype.constructor = Level3State;
Level3State.prototype.preload = function () {
this.load.tilemap('LevelThreeMap', 'levels/LevelThreeMap.json', null, Phaser.Tilemap.TILED_JSON);
this.load.image('background', 'images/L3-CosmeticShop/wallpapers/golden-sands-beach-13840-1920x1200.jpg');
this.load.image('platforms', 'images/L3-CosmeticShop/bamboo-platform(32x32).ss.png');
this.load.image('shampoo', 'images/L3-CosmeticShop/shampoo.png');
};
Level3State.prototype.update = function () {
Parent.prototype.update.call(this, levelThreeSecondLayerPlatforms, shampoosGroup);
if (this.player.points === 410) {
this.player.level = 4;
game.state.start('level4', true, false, this.player, this.engine);
}
};
Level3State.prototype.createMap = function () {
// Load level one map
map = game.add.tilemap('LevelThreeMap');
map.addTilesetImage('background', 'background');
map.addTilesetImage('platforms', 'platforms');
levelThreeFirstLayerBackground = map.createLayer('LevelThree - background');
levelThreeFirstLayerBackground.resizeWorld();
levelThreeFirstLayerBackground.wrap = true;
levelThreeSecondLayerPlatforms = map.createLayer('LevelThree - platforms');
levelThreeSecondLayerPlatforms.resizeWorld();
levelThreeSecondLayerPlatforms.wrap = true;
// Set collision between player and platforms
map.setCollisionByExclusion([0], true, levelThreeSecondLayerPlatforms);
showLevelPrehistory();
};
Level3State.prototype.initializePlayer = function () {
//Place player graphics at the map
this.player.placeAtMap(50, 120);
Parent.prototype.initializePlayer.call(this);
};
Level3State.prototype.initializeCollectableItems = function () {
//Create shampoos
shampoosGroup = this.add.group();
shampoosGroup.enableBody = true;
shampoosCoordinates = [
{x: 50, y: 420},
{x: 185, y: 65},
{x: 215, y: 65},
{x: 195, y: 350},
{x: 315, y: 320},
{x: 350, y: 450},
{x: 510, y: 160},
{x: 415, y: 65},
{x: 595, y: 320},
{x: 700, y: 64},
{x: 670, y: 450},
{x: 990, y: 350},
{x: 1020, y: 350},
{x: 900, y: 65},
{x: 940, y: 65},
{x: 980, y: 65},
{x: 1130, y: 255},
{x: 1275, y: 195},
{x: 1400, y: 290},
{x: 1370, y: 290}
];
for (var i = 0; i < shampoosCoordinates.length; i += 1) {
var currentShampoo = shampoosCoordinates[i];
var x = currentShampoo.x;
var y = currentShampoo.y;
new CollectableItem(x, y, shampoosGroup, 'shampoo');
}
};
function showLevelPrehistory() {
var body = document.getElementsByTagName('body')[0],
div = document.createElement('div'),
span,
spanText,
divPrehistory,
spanInDivPrehistory,
spanInDivPrehistoryText,
continueGameButton,
continueGameButtonText,
playButton;
div.id = 'prehistory-main-background';
span = document.createElement('span');
span.id = 'current-level';
spanText = document.createTextNode('Level 3');
span.textContent = spanText.textContent;
divPrehistory = document.createElement('div');
divPrehistory.id = 'divPrehistory';
divPrehistory.style.backgroundImage = "url('images/Prehistory/paper-roll.png')";
spanInDivPrehistory = document.createElement('span');
spanInDivPrehistory.id = 'prehistory-span-text';
spanInDivPrehistoryText = document.createTextNode('Enough with these silly games – StarCraft, MarCraft...! Let’s do ' +
'something for the girls! We need to create a cosmetics shop! Wait a minute! A cosmetics shop! ' +
'What the hell!?!?!Yeah, that right! Everyone can learn S# only a few are those who can master the OOP that goes with it. ' +
'Saddy Kopper is one of them. But in that crazy girl dimension (somewhere in Waka waka eh eh) the young Kopper must ' +
'create a cosmestics shop. In order to complete this task, he needs to collect all shampoos. If the Amazons are merciful ' +
'(they will be - Saddy is very charming), they will reveal the secret of mastering OOP.');
spanInDivPrehistory.textContent = spanInDivPrehistoryText.textContent;
divPrehistory.appendChild(spanInDivPrehistory);
continueGameButton = document.createElement('button');
continueGameButton.className = 'hvr-border-fade';
continueGameButton.id = 'continue';
continueGameButtonText = document.createTextNode('Continue');
continueGameButton.textContent = continueGameButtonText.textContent;
div.appendChild(span);
div.appendChild(divPrehistory);
div.appendChild(continueGameButton);
div.style.backgroundImage = "url('images/Game Over - messages background/L3-beach.jpg')";
body.appendChild(div);
playButton = document.getElementById('continue');
playButton.onclick = function () {
div.removeChild(span);
div.removeChild(divPrehistory);
div.removeChild(continueGameButton);
body.removeChild(div);
};
}
return Level3State;
});
|
// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;(function ( $, window, document, undefined ) {
"use strict";
// undefined is used here as the undefined global variable in ECMAScript 3 is
// mutable (ie. it can be changed by someone else). undefined isn"t really being
// passed in so we can ensure the value of it is truly undefined. In ES5, undefined
// can no longer be modified.
// window and document are passed through as local variable rather than global
// as this (slightly) quickens the resolution process and can be more efficiently
// minified (especially when both are regularly referenced in your plugin).
// Create the defaults once
var pluginName = "niceCharCounter",
defaults = {
limit: 100,
descending: true,
warningPercent: 70,
clearLimitColor: "#29b664",
warningColor: "#c0392b",
overColor: "#e74c3c",
counter: "#counter",
hardLimit: false,
text: "{{counter}}",
onType: function(){
//console.log("On Type");
},
clearLimitTrigger: function(){
//console.log("Clear Limit Trigger");
},
onClearLimit: function(){
//console.log("On Clear Limit");
},
warningTrigger: function(){
//console.log("Warning Trigger");
},
onWarning: function(){
//console.log("On Warning");
},
overTrigger: function(){
//console.log("Over Trigger");
},
onOver: function(){
//console.log("On Over");
}
};
// The actual plugin constructor
function Plugin (element, options) {
this.element = element;
// jQuery has an extend method which merges the contents of two or
// more objects, storing the result in the first object. The first object
// is generally empty as we don"t want to alter the default options for
// future instances of the plugin
this.settings = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.currentState = "";
var warningFactor = Math.round((this.settings.limit * this.settings.warningPercent) / 100);
this.warningFactor = this.settings.limit - warningFactor;
this.init();
var _this = this;
$(this.element).keyup(function(){
var $this= $(this);
var total = $this.val().length;
_this.doAction(total);
});
}
// Avoid Plugin.prototype conflicts
$.extend(Plugin.prototype, {
tey: function(){
console.log("tey");
},
init: function () {
if (this.settings.hardLimit) {
$(this.element).attr("maxlength", this.settings.limit);
}
var text = this.settings.text.replace("{{counter}}", "<span class=\"nice-remaining\"></span>");
text = text.replace("{{limit}}", "<span class=\"nice-limit\">" + this.settings.limit + "</span>");
/**
* Verifica se tem alguma coisa com o padrao [singular, plural] e marca os spans
* devidos
*/
var pattern = /\[\w+\,\s?\w+\]/g; // [singular, plural]
var result = text.match(pattern); // Pega todas as ocorrencias
console.log(result);
if (result) {
$.each(result, function(index, val) {
var words = val.replace(/\[/g, "").replace(/\]/g, "").split(",");
var singular = words[0];
var plural = words[1];
text = text.replace(val, "<span class=\"nice-inflector\" data-singular="+singular+" data-plural="+plural+"></span>");
});
}
if ($(this.settings.counter).length < 1) {
console.error("You have to set the counter");
return false;
}
$(this.settings.counter).html(text);
$(this.settings.counter).children("span.charsValue").css("color", this.settings.clearLimitColor);
this.doAction($(this.element).val().length);
},
doAction: function (total) {
var $span = $(this.settings.counter).children("span.nice-remaining");
var remaining = this.settings.limit - total;
var remainingPercent = Math.round((total * 100) / this.settings.limit);
remainingPercent = (remainingPercent < 100) ? remainingPercent : 100;
var ui = {tota: total, remaining: remaining, remainingPercent: remainingPercent};
if (this.settings.warningPercent > 0 && remaining <= this.warningFactor && remaining >= 0) {
$span.css("color", this.settings.warningColor); // quase
this.settings.onWarning(ui);
this.setStateAndTrigger("warning", ui);
} else if (remaining < 0) {
$span.css("color", this.settings.overColor); // estourou
this.settings.onOver(ui);
this.setStateAndTrigger("over", ui);
} else{
$span.css("color", this.settings.clearLimitColor); // acima do warning
this.settings.onClearLimit(ui);
this.setStateAndTrigger("clearLimit", ui);
}
var descending = this.settings.descending;
$("span.nice-inflector").each(function(){
var $this = $(this);
var factor = (descending) ? remaining : total;
var word = (factor === 1 || factor === 0) ? $this.data("singular") : $this.data("plural");
$this.text(word);
});
this.settings.onType(ui, this.currentState, this.settings);
if (this.settings.descending) {
$span.html(remaining);
} else {
$span.html(total);
}
},
setStateAndTrigger: function (state, ui){
if (state !== this.currentState) {
this.settings[state + "Trigger"](ui, this.setting);
}
this.currentState = state;
}
});
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[ pluginName ] = function ( options ) {
return this.each(function() {
if ( !$.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
}
});
};
})( jQuery, window, document );
|
function goMain(){
window.location.href = 'main.html';
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:8d51e43626611f90ffa2bf855ceaf2c501b01a5a083681b6a9426092bd85651f
size 3788
|
(function (angular) {
// Create all modules and define dependencies to make sure they exist
// and are loaded in the correct order to satisfy dependency injection
// before all nested files are concatenated by Gulp
// Config
angular.module('df.validator.config', [])
.value('df.validator.config', {
debug: true
});
// Modules
angular.module('df.validator.services', []);
angular.module('df.validator',
[
'df.validator.config',
'df.validator.services'
]);
})(angular);
/**
* Created by nikita on 12/29/14.
*/
'use strict';
angular.module('df.validator')
.service('defaultValidationRules', function ($interpolate, $q, $filter, $parse) {
function invalid(value, object, options) {
var msg = options.message ? options.message : this.message;
msg = $interpolate(msg)(angular.extend({value: value, object: object}, options));
throw msg;
//return $q.reject(msg);
}
return {
required: {
message: 'This field is required',
validate: function (value, object, options) {
options = options || {};
if (!value || value.length === 0) {
return invalid.apply(this, [value, object, options]);
}
return true;
}
},
minlength: {
message: 'Must be at least {{rule}} characters',
validate: function (value, object, options) {
options = angular.isObject(options) ? options : {rule: options};
if (!value || value.length < options.rule) {
return invalid.apply(this, [value, object, options]);
}
return true;
}
},
maxlength: {
message: 'Must be fewer than {{rule}} characters',
validate: function (value, object, options) {
options = angular.isObject(options) ? options : {rule: options};
if (value && value.length > options.rule) {
return invalid.apply(this, [value, object, options]);
}
return true;
}
},
equal: {
message: 'Must be equal',
validate: function (value, context, options) {
options = angular.isObject(options) ? options : {rule: options};
var secondVal = angular.isObject(options.rule) && options.rule.field ? $parse(options.rule.field)(context) : options.rule;
var compareByVal = options.rule.byValue || false;
if (compareByVal && value !== secondVal){
return invalid.apply(this, [value, context, options]);
}
if (!compareByVal && value != secondVal){
return invalid.apply(this, [value, context, options]);
}
return true;
}
},
notEqual: {
message: 'Must be equal',
validate: function (value, context, options) {
options = angular.isObject(options) ? options : {rule: options};
var secondVal = angular.isObject(options.rule) && options.rule.field ? $parse(options.rule.field)(context) : options.rule;
var compareByVal = options.rule.byValue || false;
if (compareByVal && value === secondVal){
return invalid.apply(this, [value, context, options]);
}
if (!compareByVal && value == secondVal){
return invalid.apply(this, [value, context, options]);
}
return true;
}
},
type: {
message: 'Must be an {{rule}}',
validate: function (value, object, options) {
options = angular.isObject(options) ? options : {rule: options};
if (value) {
var stringValue = value.toString();
} else {
return true;
}
if (options.rule === 'integer' && stringValue && !stringValue.match(/^\-*[0-9]+$/)) {
return invalid.apply(this, [value, object, options]);
}
if (options.rule === 'number' && stringValue && !stringValue.match(/^\-*[0-9\.]+$/)) {
return invalid.apply(this, [value, object, options]);
}
if (options.rule === 'negative' && stringValue && !stringValue.match(/^\-[0-9\.]+$/)) {
return invalid.apply(this, [value, object, options]);
}
if (options.rule === 'positive' && stringValue && !stringValue.match(/^[0-9\.]+$/)) {
return invalid.apply(this, [value, object, options]);
}
if (options.rule === 'email' && stringValue && !stringValue.match(/^.+@.+$/)) {
return invalid.apply(this, [value, object, options]);
}
if (options.rule === 'phone' && stringValue && !stringValue.match(/^\+?[0-9\-]+\*?$/)) {
return invalid.apply(this, [value, object, options]);
}
return true;
}
},
pattern: {
message: 'Invalid format',
validate: function (value, object, options) {
options = angular.isObject(options) ? options : {rule: options};
var pattern = options.rule instanceof RegExp ? options.rule : new RegExp(options.rule);
if (value && !pattern.exec(value)) {
return invalid.apply(this, [value, object, options]);
}
return true;
}
},
custom: {
message: 'Invalid value',
validate: function (value, object, options) {
return options.rule(value, object, options);
}
},
email:{
message: 'Invalid email address',
validate: function(value, context, options){
options = angular.isObject(options) ? options : {rule: options};
var emailRe = /^([\w\-_+]+(?:\.[\w\-_+]+)*)@((?:[\w\-]+\.)*\w[\w\-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
value += '';
if ( ! emailRe.test(value) ) return invalid.apply(this, [value, context, options]);
if ( /\@.*\@/.test(value) ) return invalid.apply(this, [value, context, options]);
if ( /\@.*_/.test(value) ) return invalid.apply(this, [value, context, options]);
return true;
}
},
lessThan: {
message: 'This field should be less than {{errorField}}',
validate: function (value, context, options) {
options = angular.isObject(options) ? options : {rule: options};
options.rule = angular.isString(options.rule) ? options.rule.split(/[ ,;]+/).filter(Boolean) : [options.rule];
var parsedValue = parseFloat(value);
var isNumber = true;
if (isNaN(parsedValue)){
isNumber = false;
} else {
value = parsedValue;
}
for (var i = 0; i < options.rule.length; i++){
var errorName = null;
var shouldBeLess = context[options.rule[i]] || options.rule[i];
if (!shouldBeLess){
continue;
}
if (isNumber) {
if (isNaN(parseFloat(shouldBeLess))){
continue;
}
errorName = shouldBeLess = parseFloat(shouldBeLess);
}
if (value > shouldBeLess) {
//var tmp = $filter('humanize')($filter('tableize')(options.rule[i]));
errorName = errorName === null ? $filter('humanize')($filter('tableize')(options.rule[i])) : errorName;
return invalid.apply(this, [value, context, angular.extend(options, {errorField: errorName})]);
}
}
return true;
}
}
};
});
/**
* Created by nikita
*/
(function () {
'use strict';
/**
* Some of the code below was filched from https://github.com/bvaughn/angular-form-for
*/
angular.module('df.validator')
.service('dfValidationUtils', function () {
function dfValidationUtils() {
}
dfValidationUtils.prototype = {
/**
* Crawls an object and returns a flattened set of all attributes using dot notation.
* This converts an Object like: {foo: {bar: true}, baz: true}
* Into an Array like ['foo', 'foo.bar', 'baz']
* @param {Object} object Object to be flattened
* @returns {Array} Array of flattened keys (perhaps containing dot notation)
*/
flattenObjectKeys: function (object) {
var keys = [];
var queue = [
{
object: object,
prefix: null
}
];
while (true) {
if (queue.length === 0) {
break;
}
var data = queue.pop();
var prefix = data.prefix ? data.prefix + '.' : '';
if (typeof data.object === 'object') {
for (var prop in data.object) {
var path = prefix + prop;
keys.push(path);
queue.push({
object: data.object[prop],
prefix: path
});
}
}
}
return keys;
}
};
return new dfValidationUtils();
});
})();
/**
* Created by nikita on 12/29/14.
*/
angular.module('df.validator')
.service('formValidator', function ($q, dfValidationUtils, $parse, validatorRulesCollection) {
/**
* @class
* @constructor
*/
function FormValidator() {
}
/**
*
* @type {FormValidator}
*/
FormValidator.prototype = {
/**
* @method
* @description
* Strip array brackets from field names so that object values can be mapped to rules.
* For instance:
* 'foo[0].bar' should be validated against 'foo.collection.fields.bar'.
*/
$getRulesForFieldName: function (validationRules, fieldName) {
fieldName = fieldName.replace(/\[[^\]]+\]/g, '.collection.fields');
return $parse(fieldName)(validationRules);
},
/**
* @method
* @description
* Validates the object against all rules in the validationRules.
* This method returns a promise to be resolved on successful validation,
* Or rejected with a map of field-name to error-message.
* @param {Object} object Form-data object object is contained within
* @param {Object} validationRules Set of named validation rules
* @returns {Promise} To be resolved or rejected based on validation success or failure.
*/
validateAll: function (object, validationRules) {
throw 'Not Implemented';
//var fields = dfValidationUtils.flattenObjectKeys(validationRules);
//return this.validateFields(object, fields, validationRules);
},
/**
* @method
* @param {*} viewValue
* @param {*} modelValue
* @param {*} object
* @param {string} fieldName
* @param {*} validationRules
* @return {promise}
*/
validateField: function (viewValue, modelValue, object, fieldName, validationRules) {
validationRules = angular.copy(validationRules);
var rules = this.$getRulesForFieldName(validationRules, fieldName);
var value = modelValue || viewValue;
var validationPromises = [];
if (angular.isString(value)) {
value = value.replace(/\s+$/, '');
}
if (!rules){
return $q.resolve();
}
var defer = $q.defer();
(function shiftRule(rules) {
var rule = rules.shift();
function processRule(rule) {
var returnValue;
if (validatorRulesCollection.has(rule.name)) {
var validationRule = validatorRulesCollection.get(rule.name);
try {
returnValue = validationRule.validate(value, object, rule);
} catch (error) {
return $q.reject(error.message || error || validationRule.message);
}
if (angular.isObject(returnValue) && angular.isFunction(returnValue.then)) {
return returnValue.then(
function (reason) {
return $q.when(reason);
},
function (reason) {
return $q.reject(reason || validationRule.message);
});
} else if (returnValue) {
return $q.when(returnValue);
} else {
return $q.reject(validationRule.message);
}
}
return $q.reject('Unknown validation rule with name ' + rule.name);
}
return processRule(rule)
.then(function () {
if (rules.length === 0) {
return defer.resolve();
}
return shiftRule(rules);
})
.catch(defer.reject);
}(rules));
return defer.promise;
}
};
return new FormValidator();
})
;
/**
* Created by nikita on 12/29/14.
*/
angular.module('df.validator')
.service('objectValidator',
/**
*
* @param $q
* @param dfValidationUtils
* @param $parse
* @param {ValidatorRulesCollection} validatorRulesCollection
*/
function ($q, dfValidationUtils, $parse, validatorRulesCollection) {
/**
* @class
* @constructor
*/
function ObjectValidator() {
}
/**
*
* @type ObjectValidator
*/
ObjectValidator.prototype = {
/**
* @method
* @description
* Strip array brackets from field names so that object values can be mapped to rules.
* For instance:
* 'foo[0].bar' should be validated against 'foo.collection.fields.bar'.
*/
$getRulesForFieldName: function (validationRules, fieldName) {
fieldName = fieldName.replace(/\[[^\]]+\]/g, '.collection.fields');
return $parse(fieldName)(validationRules);
},
/**
* @method
* @description
* Validates the object against all rules in the validationRules.
* This method returns a promise to be resolved on successful validation,
* Or rejected with a map of field-name to error-message.
* @param {Object} object Form-data object object is contained within
* @param {Object} validationRules Set of named validation rules
* @returns {Promise} To be resolved or rejected based on validation success or failure.
*/
validateAll: function (object, validationRules) {
var fields = dfValidationUtils.flattenObjectKeys(validationRules);
return this.validateFields(object, fields, validationRules);
},
/**
* @method
* @description
* Validates the values in object with the rules defined in the current validationRules.
* This method returns a promise to be resolved on successful validation,
* Or rejected with a map of field-name to error-message.
* @param {Object} object Form-data object object is contained within
* @param {Array} fieldNames Whitelist set of fields to validate for the given object; values outside of this list will be ignored
* @param {Object} validationRules Set of named validation rules
* @returns {Promise} To be resolved or rejected based on validation success or failure.
*/
validateFields: function (object, fieldNames, validationRules) {
validationRules = angular.copy(validationRules);
var deferred = $q.defer();
var promises = [];
var errorMap = {};
angular.forEach(fieldNames, function (fieldName) {
var rules = this.$getRulesForFieldName(validationRules, fieldName);
if (rules) {
var promise;
promise = this.validateField(object, fieldName, validationRules);
promise.then(
angular.noop,
function (error) {
$parse(fieldName).assign(errorMap, error);
});
promises.push(promise);
}
}, this);
$q.all(promises).then(
deferred.resolve,
function () {
deferred.reject(errorMap);
});
return deferred.promise;
},
/**
* @method
* @param object
* @param fieldName
* @param validationRules
* @return {*}
*/
validateField: function (object, fieldName, validationRules) {
var rules = this.$getRulesForFieldName(validationRules, fieldName);
var value = $parse(fieldName)(object);
var validationPromises = [];
if (angular.isString(value)) {
value = value.replace(/\s+$/, '');
}
var defer = $q.defer();
(function shiftRule(rules) {
var rule = rules.shift();
function processRule(rule) {
var returnValue;
if (validatorRulesCollection.has(rule.name)) {
var validationRule = validatorRulesCollection.get(rule.name);
var ruleOptions = rule;
try {
returnValue = validationRule.validate(value, object, ruleOptions);
} catch (error) {
return $q.reject(error || validationRule.message);
}
if (angular.isObject(returnValue) && angular.isFunction(returnValue.then)) {
return returnValue.then(
function (reason) {
return $q.when(reason);
},
function (reason) {
return $q.reject(reason || validationRule.message);
});
} else if (returnValue) {
return $q.when(returnValue);
} else {
return $q.reject(validationRule.message);
}
}
return $q.reject('Unknown validation rule with name ' + ruleName);
}
return processRule(rules)
.then(function () {
if (rules.length === 0) {
return defer.resolve();
}
return shiftRule(rules);
})
.catch(defer.reject);
}(rules));
return defer.promise;
},
/**
* Convenience method for determining if the specified collection is flagged as required (aka min length).
*/
isCollectionRequired: function (fieldName, validationRules) {
var rules = this.$getRulesForFieldName(validationRules, fieldName);
return rules &&
rules.collection &&
rules.collection.min &&
(angular.isObject(rules.collection.min) ? rules.collection.min.rule : rules.collection.min);
},
/**
* Convenience method for determining if the specified field is flagged as required.
*/
isFieldRequired: function (fieldName, validationRules) {
var rules = this.$getRulesForFieldName(validationRules, fieldName);
return rules &&
rules.required &&
(angular.isObject(rules.required) ? rules.required.rule : rules.required);
}
};
return new ObjectValidator();
})
;
/**
* Created by nikita on 12/29/14.
*/
angular.module('df.validator')
.provider('validator', function ($provide) {
var schemas = {};
this.add = function (name, schema) {
schemas[name] = schema;
return this;
};
this.addCollection = function (col) {
var self = this;
angular.forEach(col, function (schema, type) {
self.add(type, schema.validators || schema);
});
};
this.remove = function (name) {
delete schemas[name];
return this;
};
this.has = function (name) {
return schemas[name] !== undefined;
};
this.get = function (name) {
return schemas[name] || {};
};
var provider = this;
this.$get =
/**
*
* @param $q
* @param {ObjectValidator} objectValidator
* @param {FormValidator} formValidator
* @param {ValidatorRulesCollection} validatorRulesCollection
*/
function ($q, objectValidator, formValidator, validatorRulesCollection) {
/**
* @class
* @constructor
*/
function Validator() {
}
/**
*
* @type Validator
*/
Validator.prototype = {
add: function add(name, schema) {
provider.add(name, schema);
return this;
},
remove: function remove(name) {
provider.remove(name);
return this;
},
has: function has(name) {
return provider.has(name);
},
get: function get(name) {
return provider.get(name);
},
addRule: function addRule(name, rule) {
validatorRulesCollection.add(name, rule);
return this;
},
removeRule: function removeRule(name) {
validatorRulesCollection.remove(name);
return this;
},
hasRule: function hasRule(name) {
return validatorRulesCollection.has(name);
},
getRule: function getRule(name) {
return validatorRulesCollection.get(name);
},
getValidationRules: function getValidationRules(schema) {
schema = angular.isFunction(schema) ? this.get(schema.constructor.name) : schema;
schema = angular.isString(schema) ? this.get(schema) : schema;
return schema;
},
validate: function validate(object, schema) {
schema = angular.isObject(schema) ? schema : this.getValidationRules(schema || object);
return objectValidator.validateAll(object, schema);
},
validateField: function validateField(object, fields, schema) {
var fieldNames = angular.isString(fields) ? [fields] : fields;
return objectValidator.validateFields(object, fieldNames, this.getValidationRules(schema || object));
},
validateFormField: function (viewValue, modelValue, model, field, schema) {
return formValidator.validateField(viewValue, modelValue, model, field, schema);
}
};
return new Validator();
};
});
/**
* @ngdoc Services
* @name ValidatorRulesCollection
* @description
* ValidatorRulesCollection service used by EntityBundle to manage validation rules by name.
*/
'use strict';
angular.module('df.validator')
.service('validatorRulesCollection', function ValidatorRulesCollection($q, defaultValidationRules) {
var validators = {};
/**
* Use this method to add new rule to the validation collection.
* @memberof ValidatorRulesCollection
*/
this.add = function (name, rule) {
if (angular.isFunction(rule)) {
rule = {
message: 'Invalid value',
validate: rule
};
}
if (!angular.isFunction(rule.validate)) {
throw 'Invalid validator object type';
}
validators[name] = rule;
return this;
};
/**
* Use this method to remove existed rule from the validation collection.
* @memberof ValidatorRulesCollection
*/
this.remove = function (name) {
delete validators[name];
return this;
};
/**
* Use this method to check is rule existe inside the validation collection.
* @memberof ValidatorRulesCollection
*/
this.has = function (name) {
return validators[name];
};
/**
* Use this method to get the rule from the validation collection.
* @memberof ValidatorRulesCollection
*/
this.get = function (name) {
return validators[name];
};
//---- add pre defined validator rules to the validation collection
var self = this;
angular.forEach(defaultValidationRules, function (rule, name) {
self.add(name, rule);
});
});
|
var assert = require('assert');
var wdQuery = require('../index.js');
describe('wd-query', function () {
describe('injected browser executing a Google Search', function () {
var browser, $;
before(function(){
browser = this.browser;
$ = wdQuery(browser);
});
it('performs as expected', function (done) {
browser.get('http://google.com')
.then(function () {
return $('input[name=q]').val('webdriver');
})
.then(function () {
return $('input[name=q]').val();
})
.then(function (val) {
return assert.equal(val, 'webdriver');
})
.then(function(){
return $('body').isDisplayed();
})
.then(function(isDisplayed){
assert.ok(isDisplayed);
done();
});
});
});
});
|
/* eslint no-var: [0] */
var path = require('path'),
assign = require('object-assign'),
pick = require('lodash.pick');
var browserWindowDefaults = {
width: 600,
height: 600
};
var webPreferencesDefaults = {
nodeIntegration: false,
javascript: true,
webSecurity: false
};
module.exports = function(browserWindowSettings) {
var browserWindowOpts,
webPreferences;
browserWindowOpts = pick(browserWindowSettings || {}, [
'width',
'height',
'x',
'y',
'useContentSize',
'webPreferences'
]);
browserWindowOpts = assign({}, browserWindowDefaults, browserWindowOpts, {
show: false
});
webPreferences = pick(browserWindowOpts.webPreferences || {}, [
'nodeIntegration',
'partition',
'zoomFactor',
'javascript',
'webSecurity',
'allowDisplayingInsecureContent',
'allowRunningInsecureContent',
'images',
'java',
'webgl',
'webaudio',
'plugins',
'experimentalFeatures',
'experimentalCanvasFeatures',
'overlayScrollbars',
'overlayFullscreenVideo',
'sharedWorker',
'directWrite'
]);
browserWindowOpts.webPreferences = assign({}, webPreferencesDefaults, webPreferences, {
preload: path.join(__dirname, 'preload.js')
});
return browserWindowOpts;
};
|
function load_servers(addr)
{
//ajax
$.get(addr,function(json,status){
// same as loadServers(addr)
serversElement = document.getElementById("servers-list");
var innerHtmls = "";
for (var obj in json) {
innerHtmls = innerHtmls +
" <li><a href=\"server.html?id="+json[obj].id+"\">"+
json[obj].displayName+"</a></li>"
}
console.log(json);
serversElement.innerHTML=innerHtmls;
//add to ServersPage
$.each(json,function(idx, obj) {
if(obj.id == window.servername)
{
$("#displayName").text(obj.displayName);
}
});
});
}
function load_hoststatus()
{
$("#id").text(window.servername);
console.log(window.hosts);
//ajax
$.get("/data/host-status.json",function(data,status){
window.hosts_status = data;
$.each(data, function(idx,obj) {
if(obj.id == window.servername)
{
$("#address").text(obj.address);
$("#ip").text(obj.ip);
$("#link").attr("href","http://"+obj.address);
$("#status").text(obj.status);
$("#delay").text(obj.delay);
switch(obj.status)
{
case "online": $(".panel-default").addClass("panel-success");break;
case "offline": $(".panel-default").addClass("panel-danger");break;
case "unknown": $(".panel-default").addClass("panel-warning");break;
}
datestr = /Date\((\d+)\)/.exec(obj.time.value)[1];
$("#time").text(new Date(parseInt(datestr)));
}
})
});
}
$(document).ready(function() {
load_servers("../../servers.json");
load_hoststatus();
});
|
/**
* Test case for knListItemArrowIcon.
* Runs with mocha.
*/
"use strict";
const knListItemArrowIcon = require('../lib/kn_list_item_arrow_icon.js'),
assert = require('assert');
describe('kn-list-item-arrow-icon', () => {
before((done) => {
done();
});
after((done) => {
done();
});
it('Kn list item arrow icon', (done) => {
done();
});
});
|
Mobird.defineModule('modules/scroller', function(require, exports, module) {
var elementStyle = document.createElement('div').style;
var vendor = (function() {
var vendors = ['t', 'webkitT', 'MozT', 'msT', 'OT'],
transform,
i = 0,
l = vendors.length;
for (; i < l; i++) {
transform = vendors[i] + 'ransform';
if (transform in elementStyle) {
return vendors[i].substr(0, vendors[i].length - 1);
}
}
return false;
})();
function prefixStyle(style) {
if (vendor === false) {
return false;
}
if (vendor === '') {
return style;
}
return vendor + style.charAt(0).toUpperCase() + style.substr(1);
}
var transformPrefix = prefixStyle('transform');
var utils = {
addEvent: function(el, type, fn, capture) {
el.addEventListener(type, fn, !!capture);
},
removeEvent: function(el, type, fn, capture) {
el.removeEventListener(type, fn, !!capture);
},
prefixPointerEvent: function(pointerEvent) {
return window.MSPointerEvent ?
'MSPointer' + pointerEvent.charAt(9).toUpperCase() + pointerEvent.substr(10) :
pointerEvent;
},
momentum: function(current, start, time, lowerMargin, wrapperSize, deceleration) {
var distance = current - start,
speed = Math.abs(distance) / time,
destination,
duration;
deceleration = deceleration === undefined ? 0.0006 : deceleration;
destination = current + (speed * speed) / (2 * deceleration) * (distance < 0 ? -1 : 1);
duration = speed / deceleration;
if (destination < lowerMargin) {
destination = wrapperSize ? lowerMargin - (wrapperSize / 2.5 * (speed / 8)) : lowerMargin;
distance = Math.abs(destination - current);
duration = distance / speed;
} else if (destination > 0) {
destination = wrapperSize ? wrapperSize / 2.5 * (speed / 8) : 0;
distance = Math.abs(current) + destination;
duration = distance / speed;
}
return {
destination: Math.round(destination),
duration: duration
};
},
hasTransform: transformPrefix !== false,
hasPerspective: prefixStyle('perspective') in elementStyle,
hasTouch: 'ontouchstart' in window,
hasPointer: window.PointerEvent || window.MSPointerEvent, // IE10 is prefixed
hasTransition: prefixStyle('transition') in elementStyle,
isBadAndroid: /Android /.test(window.navigator.appVersion) && !(/Chrome\/\d/.test(window.navigator.appVersion)),
style: {
transform: transformPrefix,
transitionTimingFunction: prefixStyle('transitionTimingFunction'),
transitionDuration: prefixStyle('transitionDuration'),
transitionDelay: prefixStyle('transitionDelay'),
transformOrigin: prefixStyle('transformOrigin')
},
hasClass: function(e, c) {
var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
return re.test(e.className);
},
addClass: function(e, c) {
if (utils.hasClass(e, c)) {
return;
}
var newclass = e.className.split(' ');
newclass.push(c);
e.className = newclass.join(' ');
},
removeClass: function(e, c) {
if (!utils.hasClass(e, c)) {
return;
}
var re = new RegExp("(^|\\s)" + c + "(\\s|$)", 'g');
e.className = e.className.replace(re, ' ');
},
offset: function(el) {
var left = -el.offsetLeft,
top = -el.offsetTop;
// jshint -W084
while (el = el.offsetParent) {
left -= el.offsetLeft;
top -= el.offsetTop;
}
// jshint +W084
return {
left: left,
top: top
};
},
preventDefaultException: function(el, exceptions) {
for (var i in exceptions) {
if (exceptions[i].test(el[i])) {
return true;
}
}
return false;
},
eventType: {
touchstart: 1,
touchmove: 1,
touchend: 1,
mousedown: 2,
mousemove: 2,
mouseup: 2,
pointerdown: 3,
pointermove: 3,
pointerup: 3,
MSPointerDown: 3,
MSPointerMove: 3,
MSPointerUp: 3
},
ease: {
quadratic: {
style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
fn: function(k) {
return k * (2 - k);
}
},
circular: {
style: 'cubic-bezier(0.1, 0.57, 0.1, 1)', // Not properly "circular" but this looks better, it should be (0.075, 0.82, 0.165, 1)
fn: function(k) {
return Math.sqrt(1 - (--k * k));
}
},
back: {
style: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)',
fn: function(k) {
var b = 4;
return (k = k - 1) * k * ((b + 1) * k + b) + 1;
}
},
bounce: {
style: '',
fn: function(k) {
if ((k /= 1) < (1 / 2.75)) {
return 7.5625 * k * k;
} else if (k < (2 / 2.75)) {
return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
} else if (k < (2.5 / 2.75)) {
return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
} else {
return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
}
}
},
elastic: {
style: '',
fn: function(k) {
var f = 0.22,
e = 0.4;
if (k === 0) {
return 0;
}
if (k == 1) {
return 1;
}
return (e * Math.pow(2, -10 * k) * Math.sin((k - f / 4) * (2 * Math.PI) / f) + 1);
}
}
},
tap: function(e, eventName) {
var ev = document.createEvent('Event');
ev.initEvent(eventName, true, true);
ev.pageX = e.pageX;
ev.pageY = e.pageY;
e.target.dispatchEvent(ev);
},
click: function(e) {
var target = e.target,
ev;
if (!(/(SELECT|INPUT|TEXTAREA)/i).test(target.tagName)) {
ev = document.createEvent('MouseEvents');
ev.initMouseEvent('click', true, true, e.view, 1,
target.screenX, target.screenY, target.clientX, target.clientY,
e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
0, null);
ev._constructed = true;
target.dispatchEvent(ev);
}
}
};
function Scroller(el, options) {
this.wrapper = typeof el == 'string' ? document.querySelector(el) : el;
this.scroller = this.wrapper.children[0];
this.scrollerStyle = this.scroller.style; // cache style for better performance
this.options = {
resizeScrollbars: true,
mouseWheelSpeed: 20,
snapThreshold: 0.334,
// INSERT POINT: OPTIONS
startX: 0,
startY: 0,
scrollY: true,
directionLockThreshold: 5,
momentum: true,
bounce: true,
bounceTime: 600,
bounceEasing: '',
preventDefault: true,
preventDefaultException: {
tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/
},
HWCompositing: true,
useTransition: true,
useTransform: true
};
for (var i in options) {
this.options[i] = options[i];
}
// Normalize options
this.translateZ = this.options.HWCompositing && utils.hasPerspective ? ' translateZ(0)' : '';
this.options.useTransition = utils.hasTransition && this.options.useTransition;
this.options.useTransform = utils.hasTransform && this.options.useTransform;
this.options.eventPassthrough = this.options.eventPassthrough === true ? 'vertical' : this.options.eventPassthrough;
this.options.preventDefault = !this.options.eventPassthrough && this.options.preventDefault;
// If you want eventPassthrough I have to lock one of the axes
this.options.scrollY = this.options.eventPassthrough == 'vertical' ? false : this.options.scrollY;
this.options.scrollX = this.options.eventPassthrough == 'horizontal' ? false : this.options.scrollX;
// With eventPassthrough we also need lockDirection mechanism
this.options.freeScroll = this.options.freeScroll && !this.options.eventPassthrough;
this.options.directionLockThreshold = this.options.eventPassthrough ? 0 : this.options.directionLockThreshold;
this.options.bounceEasing = typeof this.options.bounceEasing == 'string' ? utils.ease[this.options.bounceEasing] || utils.ease.circular : this.options.bounceEasing;
this.options.resizePolling = this.options.resizePolling === undefined ? 60 : this.options.resizePolling;
if (this.options.tap === true) {
this.options.tap = 'tap';
}
if (this.options.shrinkScrollbars == 'scale') {
this.options.useTransition = false;
}
this.options.invertWheelDirection = this.options.invertWheelDirection ? -1 : 1;
// INSERT POINT: NORMALIZATION
// Some defaults
this.x = 0;
this.y = 0;
this.directionX = 0;
this.directionY = 0;
this._events = {};
// INSERT POINT: DEFAULTS
this._init();
this.refresh();
this.scrollTo(this.options.startX, this.options.startY);
this.enable();
}
Scroller.prototype = {
_init: function() {
this._initEvents();
if (this.options.scrollbars || this.options.indicators) {
this._initIndicators();
}
if (this.options.mouseWheel) {
this._initWheel();
}
if (this.options.snap) {
this._initSnap();
}
if (this.options.keyBindings) {
this._initKeys();
}
// INSERT POINT: _init
},
destroy: function() {
this._initEvents(true);
this._execEvent('destroy');
},
_transitionEnd: function(e) {
if (e.target != this.scroller || !this.isInTransition) {
return;
}
this._transitionTime();
if (!this.resetPosition(this.options.bounceTime)) {
this.isInTransition = false;
this._execEvent('scrollEnd');
}
},
_start: function(e) {
// React to left mouse button only
if (utils.eventType[e.type] != 1) {
if (e.button !== 0) {
return;
}
}
if (!this.enabled || (this.initiated && utils.eventType[e.type] !== this.initiated)) {
return;
}
if (this.options.preventDefault && !utils.isBadAndroid && !utils.preventDefaultException(e.target, this.options.preventDefaultException)) {
e.preventDefault();
}
var point = e.touches ? e.touches[0] : e,
pos;
this.initiated = utils.eventType[e.type];
this.moved = false;
this.distX = 0;
this.distY = 0;
this.directionX = 0;
this.directionY = 0;
this.directionLocked = 0;
this._transitionTime();
this.startTime = Mobird.now();
if (this.options.useTransition && this.isInTransition) {
this.isInTransition = false;
pos = this.getComputedPosition();
this._translate(Math.round(pos.x), Math.round(pos.y));
this._execEvent('scrollEnd');
} else if (!this.options.useTransition && this.isAnimating) {
this.isAnimating = false;
this._execEvent('scrollEnd');
}
this.startX = this.x;
this.startY = this.y;
this.absStartX = this.x;
this.absStartY = this.y;
this.pointX = point.pageX;
this.pointY = point.pageY;
this._execEvent('beforeScrollStart');
},
_move: function(e) {
if (!this.enabled || utils.eventType[e.type] !== this.initiated) {
return;
}
if (this.options.preventDefault) { // increases performance on Android? TODO: check!
e.preventDefault();
}
var point = e.touches ? e.touches[0] : e,
deltaX = point.pageX - this.pointX,
deltaY = point.pageY - this.pointY,
timestamp = Mobird.now(),
newX, newY,
absDistX, absDistY;
this.pointX = point.pageX;
this.pointY = point.pageY;
this.distX += deltaX;
this.distY += deltaY;
absDistX = Math.abs(this.distX);
absDistY = Math.abs(this.distY);
// We need to move at least 10 pixels for the scrolling to initiate
if (timestamp - this.endTime > 300 && (absDistX < 10 && absDistY < 10)) {
return;
}
// If you are scrolling in one direction lock the other
if (!this.directionLocked && !this.options.freeScroll) {
if (absDistX > absDistY + this.options.directionLockThreshold) {
this.directionLocked = 'h'; // lock horizontally
} else if (absDistY >= absDistX + this.options.directionLockThreshold) {
this.directionLocked = 'v'; // lock vertically
} else {
this.directionLocked = 'n'; // no lock
}
}
if (this.directionLocked == 'h') {
if (this.options.eventPassthrough == 'vertical') {
e.preventDefault();
} else if (this.options.eventPassthrough == 'horizontal') {
this.initiated = false;
return;
}
deltaY = 0;
} else if (this.directionLocked == 'v') {
if (this.options.eventPassthrough == 'horizontal') {
e.preventDefault();
} else if (this.options.eventPassthrough == 'vertical') {
this.initiated = false;
return;
}
deltaX = 0;
}
deltaX = this.hasHorizontalScroll ? deltaX : 0;
deltaY = this.hasVerticalScroll ? deltaY : 0;
newX = this.x + deltaX;
newY = this.y + deltaY;
// Slow down if outside of the boundaries
if (newX > 0 || newX < this.maxScrollX) {
newX = this.options.bounce ? this.x + deltaX / 3 : newX > 0 ? 0 : this.maxScrollX;
}
if (newY > 0 || newY < this.maxScrollY) {
newY = this.options.bounce ? this.y + deltaY / 3 : newY > 0 ? 0 : this.maxScrollY;
}
this.directionX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
this.directionY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
if (!this.moved) {
this._execEvent('scrollStart');
}
this.moved = true;
this._translate(newX, newY);
/* REPLACE START: _move */
if (timestamp - this.startTime > 300) {
this.startTime = timestamp;
this.startX = this.x;
this.startY = this.y;
}
/* REPLACE END: _move */
},
_end: function(e) {
if (!this.enabled || utils.eventType[e.type] !== this.initiated) {
return;
}
if (this.options.preventDefault && !utils.preventDefaultException(e.target, this.options.preventDefaultException)) {
e.preventDefault();
}
var point = e.changedTouches ? e.changedTouches[0] : e,
momentumX,
momentumY,
duration = Mobird.now() - this.startTime,
newX = Math.round(this.x),
newY = Math.round(this.y),
distanceX = Math.abs(newX - this.startX),
distanceY = Math.abs(newY - this.startY),
time = 0,
easing = '';
this.isInTransition = 0;
this.initiated = 0;
this.endTime = Mobird.now();
// reset if we are outside of the boundaries
if (this.resetPosition(this.options.bounceTime)) {
return;
}
this.scrollTo(newX, newY); // ensures that the last position is rounded
// we scrolled less than 10 pixels
if (!this.moved) {
if (this.options.tap) {
utils.tap(e, this.options.tap);
}
if (this.options.click) {
utils.click(e);
}
this._execEvent('scrollCancel');
return;
}
if (this._events.flick && duration < 200 && distanceX < 100 && distanceY < 100) {
this._execEvent('flick');
return;
}
// start momentum animation if needed
if (this.options.momentum && duration < 300) {
momentumX = this.hasHorizontalScroll ? utils.momentum(this.x, this.startX, duration, this.maxScrollX, this.options.bounce ? this.wrapperWidth : 0, this.options.deceleration) : {
destination: newX,
duration: 0
};
momentumY = this.hasVerticalScroll ? utils.momentum(this.y, this.startY, duration, this.maxScrollY, this.options.bounce ? this.wrapperHeight : 0, this.options.deceleration) : {
destination: newY,
duration: 0
};
newX = momentumX.destination;
newY = momentumY.destination;
time = Math.max(momentumX.duration, momentumY.duration);
this.isInTransition = 1;
}
if (this.options.snap) {
var snap = this._nearestSnap(newX, newY);
this.currentPage = snap;
time = this.options.snapSpeed || Math.max(
Math.max(
Math.min(Math.abs(newX - snap.x), 1000),
Math.min(Math.abs(newY - snap.y), 1000)
), 300);
newX = snap.x;
newY = snap.y;
this.directionX = 0;
this.directionY = 0;
easing = this.options.bounceEasing;
}
// INSERT POINT: _end
if (newX != this.x || newY != this.y) {
// change easing function when scroller goes out of the boundaries
if (newX > 0 || newX < this.maxScrollX || newY > 0 || newY < this.maxScrollY) {
easing = utils.ease.quadratic;
}
this.scrollTo(newX, newY, time, easing);
return;
}
this._execEvent('scrollEnd');
},
_resize: function() {
var that = this;
clearTimeout(this.resizeTimeout);
this.resizeTimeout = setTimeout(function() {
that.refresh();
}, this.options.resizePolling);
},
resetPosition: function(time) {
var x = this.x,
y = this.y;
time = time || 0;
if (!this.hasHorizontalScroll || this.x > 0) {
x = 0;
} else if (this.x < this.maxScrollX) {
x = this.maxScrollX;
}
if (!this.hasVerticalScroll || this.y > 0) {
y = 0;
} else if (this.y < this.maxScrollY) {
y = this.maxScrollY;
}
if (x == this.x && y == this.y) {
return false;
}
this.scrollTo(x, y, time, this.options.bounceEasing);
return true;
},
disable: function() {
this.enabled = false;
},
enable: function() {
this.enabled = true;
},
refresh: function() {
var rf = this.wrapper.offsetHeight; // Force reflow
this.wrapperWidth = this.wrapper.clientWidth;
this.wrapperHeight = this.wrapper.clientHeight;
/* REPLACE START: refresh */
this.scrollerWidth = this.scroller.offsetWidth;
this.scrollerHeight = this.scroller.offsetHeight;
this.maxScrollX = this.wrapperWidth - this.scrollerWidth;
this.maxScrollY = this.wrapperHeight - this.scrollerHeight;
/* REPLACE END: refresh */
this.hasHorizontalScroll = this.options.scrollX && this.maxScrollX < 0;
this.hasVerticalScroll = this.options.scrollY && this.maxScrollY < 0;
if (!this.hasHorizontalScroll) {
this.maxScrollX = 0;
this.scrollerWidth = this.wrapperWidth;
}
if (!this.hasVerticalScroll) {
this.maxScrollY = 0;
this.scrollerHeight = this.wrapperHeight;
}
this.endTime = 0;
this.directionX = 0;
this.directionY = 0;
this.wrapperOffset = utils.offset(this.wrapper);
this._execEvent('refresh');
this.resetPosition();
// INSERT POINT: _refresh
},
on: function(type, fn) {
if (!this._events[type]) {
this._events[type] = [];
}
this._events[type].push(fn);
},
off: function(type, fn) {
if (!this._events[type]) {
return;
}
var index = this._events[type].indexOf(fn);
if (index > -1) {
this._events[type].splice(index, 1);
}
},
_execEvent: function(type) {
if (!this._events[type]) {
return;
}
var i = 0,
l = this._events[type].length;
if (!l) {
return;
}
for (; i < l; i++) {
this._events[type][i].apply(this, [].slice.call(arguments, 1));
}
},
scrollBy: function(x, y, time, easing) {
x = this.x + x;
y = this.y + y;
time = time || 0;
this.scrollTo(x, y, time, easing);
},
scrollTo: function(x, y, time, easing) {
easing = easing || utils.ease.circular;
this.isInTransition = this.options.useTransition && time > 0;
if (!time || (this.options.useTransition && easing.style)) {
this._transitionTimingFunction(easing.style);
this._transitionTime(time);
this._translate(x, y);
} else {
this._animate(x, y, time, easing.fn);
}
},
scrollToElement: function(el, time, offsetX, offsetY, easing) {
el = el.nodeType ? el : this.scroller.querySelector(el);
if (!el) {
return;
}
var pos = utils.offset(el);
pos.left -= this.wrapperOffset.left;
pos.top -= this.wrapperOffset.top;
// if offsetX/Y are true we center the element to the screen
if (offsetX === true) {
offsetX = Math.round(el.offsetWidth / 2 - this.wrapper.offsetWidth / 2);
}
if (offsetY === true) {
offsetY = Math.round(el.offsetHeight / 2 - this.wrapper.offsetHeight / 2);
}
pos.left -= offsetX || 0;
pos.top -= offsetY || 0;
pos.left = pos.left > 0 ? 0 : pos.left < this.maxScrollX ? this.maxScrollX : pos.left;
pos.top = pos.top > 0 ? 0 : pos.top < this.maxScrollY ? this.maxScrollY : pos.top;
time = time === undefined || time === null || time === 'auto' ? Math.max(Math.abs(this.x - pos.left), Math.abs(this.y - pos.top)) : time;
this.scrollTo(pos.left, pos.top, time, easing);
},
_transitionTime: function(time) {
time = time || 0;
this.scrollerStyle[utils.style.transitionDuration] = time + 'ms';
if (!time && utils.isBadAndroid) {
this.scrollerStyle[utils.style.transitionDuration] = '0.001s';
}
if (this.indicators) {
for (var i = this.indicators.length; i--;) {
this.indicators[i].transitionTime(time);
}
}
// INSERT POINT: _transitionTime
},
_transitionTimingFunction: function(easing) {
this.scrollerStyle[utils.style.transitionTimingFunction] = easing;
if (this.indicators) {
for (var i = this.indicators.length; i--;) {
this.indicators[i].transitionTimingFunction(easing);
}
}
// INSERT POINT: _transitionTimingFunction
},
_translate: function(x, y) {
if (this.options.useTransform) {
/* REPLACE START: _translate */
this.scrollerStyle[utils.style.transform] = 'translate(' + x + 'px,' + y + 'px)' + this.translateZ;
/* REPLACE END: _translate */
} else {
x = Math.round(x);
y = Math.round(y);
this.scrollerStyle.left = x + 'px';
this.scrollerStyle.top = y + 'px';
}
this.x = x;
this.y = y;
if (this.indicators) {
for (var i = this.indicators.length; i--;) {
this.indicators[i].updatePosition();
}
}
// INSERT POINT: _translate
},
_initEvents: function(remove) {
var eventType = remove ? utils.removeEvent : utils.addEvent,
target = this.options.bindToWrapper ? this.wrapper : window;
eventType(window, 'orientationchange', this);
eventType(window, 'resize', this);
if (this.options.click) {
eventType(this.wrapper, 'click', this, true);
}
if (!this.options.disableMouse) {
eventType(this.wrapper, 'mousedown', this);
eventType(target, 'mousemove', this);
eventType(target, 'mousecancel', this);
eventType(target, 'mouseup', this);
}
if (utils.hasPointer && !this.options.disablePointer) {
eventType(this.wrapper, utils.prefixPointerEvent('pointerdown'), this);
eventType(target, utils.prefixPointerEvent('pointermove'), this);
eventType(target, utils.prefixPointerEvent('pointercancel'), this);
eventType(target, utils.prefixPointerEvent('pointerup'), this);
}
if (utils.hasTouch && !this.options.disableTouch) {
eventType(this.wrapper, 'touchstart', this);
eventType(target, 'touchmove', this);
eventType(target, 'touchcancel', this);
eventType(target, 'touchend', this);
}
eventType(this.scroller, 'transitionend', this);
eventType(this.scroller, 'webkitTransitionEnd', this);
eventType(this.scroller, 'oTransitionEnd', this);
eventType(this.scroller, 'MSTransitionEnd', this);
},
getComputedPosition: function() {
var matrix = window.getComputedStyle(this.scroller, null),
x, y;
if (this.options.useTransform) {
matrix = matrix[utils.style.transform].split(')')[0].split(', ');
x = +(matrix[12] || matrix[4]);
y = +(matrix[13] || matrix[5]);
} else {
x = +matrix.left.replace(/[^-\d.]/g, '');
y = +matrix.top.replace(/[^-\d.]/g, '');
}
return {
x: x,
y: y
};
},
_initIndicators: function() {
var interactive = this.options.interactiveScrollbars,
customStyle = typeof this.options.scrollbars != 'string',
indicators = [],
indicator;
var that = this;
this.indicators = [];
if (this.options.scrollbars) {
// Vertical scrollbar
if (this.options.scrollY) {
indicator = {
el: createDefaultScrollbar('v', interactive, this.options.scrollbars),
interactive: interactive,
defaultScrollbars: true,
customStyle: customStyle,
resize: this.options.resizeScrollbars,
shrink: this.options.shrinkScrollbars,
fade: this.options.fadeScrollbars,
listenX: false
};
this.wrapper.appendChild(indicator.el);
indicators.push(indicator);
}
// Horizontal scrollbar
if (this.options.scrollX) {
indicator = {
el: createDefaultScrollbar('h', interactive, this.options.scrollbars),
interactive: interactive,
defaultScrollbars: true,
customStyle: customStyle,
resize: this.options.resizeScrollbars,
shrink: this.options.shrinkScrollbars,
fade: this.options.fadeScrollbars,
listenY: false
};
this.wrapper.appendChild(indicator.el);
indicators.push(indicator);
}
}
if (this.options.indicators) {
// TODO: check concat compatibility
indicators = indicators.concat(this.options.indicators);
}
for (var i = indicators.length; i--;) {
this.indicators.push(new Indicator(this, indicators[i]));
}
// TODO: check if we can use array.map (wide compatibility and performance issues)
function _indicatorsMap(fn) {
for (var i = that.indicators.length; i--;) {
fn.call(that.indicators[i]);
}
}
if (this.options.fadeScrollbars) {
this.on('scrollEnd', function() {
_indicatorsMap(function() {
this.fade();
});
});
this.on('scrollCancel', function() {
_indicatorsMap(function() {
this.fade();
});
});
this.on('scrollStart', function() {
_indicatorsMap(function() {
this.fade(1);
});
});
this.on('beforeScrollStart', function() {
_indicatorsMap(function() {
this.fade(1, true);
});
});
}
this.on('refresh', function() {
_indicatorsMap(function() {
this.refresh();
});
});
this.on('destroy', function() {
_indicatorsMap(function() {
this.destroy();
});
delete this.indicators;
});
},
_initWheel: function() {
utils.addEvent(this.wrapper, 'wheel', this);
utils.addEvent(this.wrapper, 'mousewheel', this);
utils.addEvent(this.wrapper, 'DOMMouseScroll', this);
this.on('destroy', function() {
utils.removeEvent(this.wrapper, 'wheel', this);
utils.removeEvent(this.wrapper, 'mousewheel', this);
utils.removeEvent(this.wrapper, 'DOMMouseScroll', this);
});
},
_wheel: function(e) {
if (!this.enabled) {
return;
}
e.preventDefault();
e.stopPropagation();
var wheelDeltaX, wheelDeltaY,
newX, newY,
that = this;
if (this.wheelTimeout === undefined) {
that._execEvent('scrollStart');
}
// Execute the scrollEnd event after 400ms the wheel stopped scrolling
clearTimeout(this.wheelTimeout);
this.wheelTimeout = setTimeout(function() {
that._execEvent('scrollEnd');
that.wheelTimeout = undefined;
}, 400);
if ('deltaX' in e) {
if (e.deltaMode === 1) {
wheelDeltaX = -e.deltaX * this.options.mouseWheelSpeed;
wheelDeltaY = -e.deltaY * this.options.mouseWheelSpeed;
} else {
wheelDeltaX = -e.deltaX;
wheelDeltaY = -e.deltaY;
}
} else if ('wheelDeltaX' in e) {
wheelDeltaX = e.wheelDeltaX / 120 * this.options.mouseWheelSpeed;
wheelDeltaY = e.wheelDeltaY / 120 * this.options.mouseWheelSpeed;
} else if ('wheelDelta' in e) {
wheelDeltaX = wheelDeltaY = e.wheelDelta / 120 * this.options.mouseWheelSpeed;
} else if ('detail' in e) {
wheelDeltaX = wheelDeltaY = -e.detail / 3 * this.options.mouseWheelSpeed;
} else {
return;
}
wheelDeltaX *= this.options.invertWheelDirection;
wheelDeltaY *= this.options.invertWheelDirection;
if (!this.hasVerticalScroll) {
wheelDeltaX = wheelDeltaY;
wheelDeltaY = 0;
}
if (this.options.snap) {
newX = this.currentPage.pageX;
newY = this.currentPage.pageY;
if (wheelDeltaX > 0) {
newX--;
} else if (wheelDeltaX < 0) {
newX++;
}
if (wheelDeltaY > 0) {
newY--;
} else if (wheelDeltaY < 0) {
newY++;
}
this.goToPage(newX, newY);
return;
}
newX = this.x + Math.round(this.hasHorizontalScroll ? wheelDeltaX : 0);
newY = this.y + Math.round(this.hasVerticalScroll ? wheelDeltaY : 0);
if (newX > 0) {
newX = 0;
} else if (newX < this.maxScrollX) {
newX = this.maxScrollX;
}
if (newY > 0) {
newY = 0;
} else if (newY < this.maxScrollY) {
newY = this.maxScrollY;
}
this.scrollTo(newX, newY, 0);
// INSERT POINT: _wheel
},
_initSnap: function() {
this.currentPage = {};
if (typeof this.options.snap == 'string') {
this.options.snap = this.scroller.querySelectorAll(this.options.snap);
}
this.on('refresh', function() {
var i = 0,
l,
m = 0,
n,
cx, cy,
x = 0,
y,
stepX = this.options.snapStepX || this.wrapperWidth,
stepY = this.options.snapStepY || this.wrapperHeight,
el;
this.pages = [];
if (!this.wrapperWidth || !this.wrapperHeight || !this.scrollerWidth || !this.scrollerHeight) {
return;
}
if (this.options.snap === true) {
cx = Math.round(stepX / 2);
cy = Math.round(stepY / 2);
while (x > -this.scrollerWidth) {
this.pages[i] = [];
l = 0;
y = 0;
while (y > -this.scrollerHeight) {
this.pages[i][l] = {
x: Math.max(x, this.maxScrollX),
y: Math.max(y, this.maxScrollY),
width: stepX,
height: stepY,
cx: x - cx,
cy: y - cy
};
y -= stepY;
l++;
}
x -= stepX;
i++;
}
} else {
el = this.options.snap;
l = el.length;
n = -1;
for (; i < l; i++) {
if (i === 0 || el[i].offsetLeft <= el[i - 1].offsetLeft) {
m = 0;
n++;
}
if (!this.pages[m]) {
this.pages[m] = [];
}
x = Math.max(-el[i].offsetLeft, this.maxScrollX);
y = Math.max(-el[i].offsetTop, this.maxScrollY);
cx = x - Math.round(el[i].offsetWidth / 2);
cy = y - Math.round(el[i].offsetHeight / 2);
this.pages[m][n] = {
x: x,
y: y,
width: el[i].offsetWidth,
height: el[i].offsetHeight,
cx: cx,
cy: cy
};
if (x > this.maxScrollX) {
m++;
}
}
}
this.goToPage(this.currentPage.pageX || 0, this.currentPage.pageY || 0, 0);
// Update snap threshold if needed
if (this.options.snapThreshold % 1 === 0) {
this.snapThresholdX = this.options.snapThreshold;
this.snapThresholdY = this.options.snapThreshold;
} else {
this.snapThresholdX = Math.round(this.pages[this.currentPage.pageX][this.currentPage.pageY].width * this.options.snapThreshold);
this.snapThresholdY = Math.round(this.pages[this.currentPage.pageX][this.currentPage.pageY].height * this.options.snapThreshold);
}
});
this.on('flick', function() {
var time = this.options.snapSpeed || Math.max(
Math.max(
Math.min(Math.abs(this.x - this.startX), 1000),
Math.min(Math.abs(this.y - this.startY), 1000)
), 300);
this.goToPage(
this.currentPage.pageX + this.directionX,
this.currentPage.pageY + this.directionY,
time
);
});
},
_nearestSnap: function(x, y) {
if (!this.pages.length) {
return {
x: 0,
y: 0,
pageX: 0,
pageY: 0
};
}
var i = 0,
l = this.pages.length,
m = 0;
// Check if we exceeded the snap threshold
if (Math.abs(x - this.absStartX) < this.snapThresholdX &&
Math.abs(y - this.absStartY) < this.snapThresholdY) {
return this.currentPage;
}
if (x > 0) {
x = 0;
} else if (x < this.maxScrollX) {
x = this.maxScrollX;
}
if (y > 0) {
y = 0;
} else if (y < this.maxScrollY) {
y = this.maxScrollY;
}
for (; i < l; i++) {
if (x >= this.pages[i][0].cx) {
x = this.pages[i][0].x;
break;
}
}
l = this.pages[i].length;
for (; m < l; m++) {
if (y >= this.pages[0][m].cy) {
y = this.pages[0][m].y;
break;
}
}
if (i == this.currentPage.pageX) {
i += this.directionX;
if (i < 0) {
i = 0;
} else if (i >= this.pages.length) {
i = this.pages.length - 1;
}
x = this.pages[i][0].x;
}
if (m == this.currentPage.pageY) {
m += this.directionY;
if (m < 0) {
m = 0;
} else if (m >= this.pages[0].length) {
m = this.pages[0].length - 1;
}
y = this.pages[0][m].y;
}
return {
x: x,
y: y,
pageX: i,
pageY: m
};
},
goToPage: function(x, y, time, easing) {
easing = easing || this.options.bounceEasing;
if (x >= this.pages.length) {
x = this.pages.length - 1;
} else if (x < 0) {
x = 0;
}
if (y >= this.pages[x].length) {
y = this.pages[x].length - 1;
} else if (y < 0) {
y = 0;
}
var posX = this.pages[x][y].x,
posY = this.pages[x][y].y;
time = time === undefined ? this.options.snapSpeed || Math.max(
Math.max(
Math.min(Math.abs(posX - this.x), 1000),
Math.min(Math.abs(posY - this.y), 1000)
), 300) : time;
this.currentPage = {
x: posX,
y: posY,
pageX: x,
pageY: y
};
this.scrollTo(posX, posY, time, easing);
},
next: function(time, easing) {
var x = this.currentPage.pageX,
y = this.currentPage.pageY;
x++;
if (x >= this.pages.length && this.hasVerticalScroll) {
x = 0;
y++;
}
this.goToPage(x, y, time, easing);
},
prev: function(time, easing) {
var x = this.currentPage.pageX,
y = this.currentPage.pageY;
x--;
if (x < 0 && this.hasVerticalScroll) {
x = 0;
y--;
}
this.goToPage(x, y, time, easing);
},
_initKeys: function(e) {
// default key bindings
var keys = {
pageUp: 33,
pageDown: 34,
end: 35,
home: 36,
left: 37,
up: 38,
right: 39,
down: 40
};
var i;
// if you give me characters I give you keycode
if (typeof this.options.keyBindings == 'object') {
for (i in this.options.keyBindings) {
if (typeof this.options.keyBindings[i] == 'string') {
this.options.keyBindings[i] = this.options.keyBindings[i].toUpperCase().charCodeAt(0);
}
}
} else {
this.options.keyBindings = {};
}
for (i in keys) {
this.options.keyBindings[i] = this.options.keyBindings[i] || keys[i];
}
utils.addEvent(window, 'keydown', this);
this.on('destroy', function() {
utils.removeEvent(window, 'keydown', this);
});
},
_key: function(e) {
if (!this.enabled) {
return;
}
var snap = this.options.snap, // we are using this alot, better to cache it
newX = snap ? this.currentPage.pageX : this.x,
newY = snap ? this.currentPage.pageY : this.y,
now = Mobird.now(),
prevTime = this.keyTime || 0,
acceleration = 0.250,
pos;
if (this.options.useTransition && this.isInTransition) {
pos = this.getComputedPosition();
this._translate(Math.round(pos.x), Math.round(pos.y));
this.isInTransition = false;
}
this.keyAcceleration = now - prevTime < 200 ? Math.min(this.keyAcceleration + acceleration, 50) : 0;
switch (e.keyCode) {
case this.options.keyBindings.pageUp:
if (this.hasHorizontalScroll && !this.hasVerticalScroll) {
newX += snap ? 1 : this.wrapperWidth;
} else {
newY += snap ? 1 : this.wrapperHeight;
}
break;
case this.options.keyBindings.pageDown:
if (this.hasHorizontalScroll && !this.hasVerticalScroll) {
newX -= snap ? 1 : this.wrapperWidth;
} else {
newY -= snap ? 1 : this.wrapperHeight;
}
break;
case this.options.keyBindings.end:
newX = snap ? this.pages.length - 1 : this.maxScrollX;
newY = snap ? this.pages[0].length - 1 : this.maxScrollY;
break;
case this.options.keyBindings.home:
newX = 0;
newY = 0;
break;
case this.options.keyBindings.left:
newX += snap ? -1 : 5 + this.keyAcceleration >> 0;
break;
case this.options.keyBindings.up:
newY += snap ? 1 : 5 + this.keyAcceleration >> 0;
break;
case this.options.keyBindings.right:
newX -= snap ? -1 : 5 + this.keyAcceleration >> 0;
break;
case this.options.keyBindings.down:
newY -= snap ? 1 : 5 + this.keyAcceleration >> 0;
break;
default:
return;
}
if (snap) {
this.goToPage(newX, newY);
return;
}
if (newX > 0) {
newX = 0;
this.keyAcceleration = 0;
} else if (newX < this.maxScrollX) {
newX = this.maxScrollX;
this.keyAcceleration = 0;
}
if (newY > 0) {
newY = 0;
this.keyAcceleration = 0;
} else if (newY < this.maxScrollY) {
newY = this.maxScrollY;
this.keyAcceleration = 0;
}
this.scrollTo(newX, newY, 0);
this.keyTime = now;
},
_animate: function(destX, destY, duration, easingFn) {
var that = this,
startX = this.x,
startY = this.y,
startTime = Mobird.now(),
destTime = startTime + duration;
function step() {
var now = Mobird.now(),
newX, newY,
easing;
if (now >= destTime) {
that.isAnimating = false;
that._translate(destX, destY);
if (!that.resetPosition(that.options.bounceTime)) {
that._execEvent('scrollEnd');
}
return;
}
now = (now - startTime) / duration;
easing = easingFn(now);
newX = (destX - startX) * easing + startX;
newY = (destY - startY) * easing + startY;
that._translate(newX, newY);
if (that.isAnimating) {
Mobird.requestAnimationFrame(step);
}
}
this.isAnimating = true;
step();
},
handleEvent: function(e) {
switch (e.type) {
case 'touchstart':
case 'pointerdown':
case 'MSPointerDown':
case 'mousedown':
this._start(e);
break;
case 'touchmove':
case 'pointermove':
case 'MSPointerMove':
case 'mousemove':
this._move(e);
break;
case 'touchend':
case 'pointerup':
case 'MSPointerUp':
case 'mouseup':
case 'touchcancel':
case 'pointercancel':
case 'MSPointerCancel':
case 'mousecancel':
this._end(e);
break;
case 'orientationchange':
case 'resize':
this._resize();
break;
case 'transitionend':
case 'webkitTransitionEnd':
case 'oTransitionEnd':
case 'MSTransitionEnd':
this._transitionEnd(e);
break;
case 'wheel':
case 'DOMMouseScroll':
case 'mousewheel':
this._wheel(e);
break;
case 'keydown':
this._key(e);
break;
case 'click':
if (!e._constructed) {
e.preventDefault();
e.stopPropagation();
}
break;
}
}
};
function createDefaultScrollbar(direction, interactive, type) {
var scrollbar = document.createElement('div'),
indicator = document.createElement('div');
if (type === true) {
scrollbar.style.cssText = 'position:absolute;z-index:9999';
indicator.style.cssText = '-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);border-radius:3px';
}
indicator.className = 'mo-scroll-bar-indicator';
if (direction == 'h') {
if (type === true) {
scrollbar.style.cssText += ';height:7px;left:2px;right:2px;bottom:0';
indicator.style.height = '100%';
}
scrollbar.className = 'mo-scroll-bar-h';
} else {
if (type === true) {
scrollbar.style.cssText += ';width:7px;bottom:2px;top:2px;right:1px';
indicator.style.width = '100%';
}
scrollbar.className = 'mo-scroll-bar-v';
}
scrollbar.style.cssText += ';overflow:hidden';
if (!interactive) {
scrollbar.style.pointerEvents = 'none';
}
scrollbar.appendChild(indicator);
return scrollbar;
}
function Indicator(scroller, options) {
this.wrapper = typeof options.el == 'string' ? document.querySelector(options.el) : options.el;
this.wrapperStyle = this.wrapper.style;
this.indicator = this.wrapper.children[0];
this.indicatorStyle = this.indicator.style;
this.scroller = scroller;
this.options = {
listenX: true,
listenY: true,
interactive: false,
resize: true,
defaultScrollbars: false,
shrink: false,
fade: false,
speedRatioX: 0,
speedRatioY: 0
};
for (var i in options) {
this.options[i] = options[i];
}
this.sizeRatioX = 1;
this.sizeRatioY = 1;
this.maxPosX = 0;
this.maxPosY = 0;
if (this.options.interactive) {
if (!this.options.disableTouch) {
utils.addEvent(this.indicator, 'touchstart', this);
utils.addEvent(window, 'touchend', this);
}
if (!this.options.disablePointer) {
utils.addEvent(this.indicator, utils.prefixPointerEvent('pointerdown'), this);
utils.addEvent(window, utils.prefixPointerEvent('pointerup'), this);
}
if (!this.options.disableMouse) {
utils.addEvent(this.indicator, 'mousedown', this);
utils.addEvent(window, 'mouseup', this);
}
}
if (this.options.fade) {
this.wrapperStyle[utils.style.transform] = this.scroller.translateZ;
this.wrapperStyle[utils.style.transitionDuration] = utils.isBadAndroid ? '0.001s' : '0ms';
this.wrapperStyle.opacity = '0';
}
}
Indicator.prototype = {
handleEvent: function(e) {
switch (e.type) {
case 'touchstart':
case 'pointerdown':
case 'MSPointerDown':
case 'mousedown':
this._start(e);
break;
case 'touchmove':
case 'pointermove':
case 'MSPointerMove':
case 'mousemove':
this._move(e);
break;
case 'touchend':
case 'pointerup':
case 'MSPointerUp':
case 'mouseup':
case 'touchcancel':
case 'pointercancel':
case 'MSPointerCancel':
case 'mousecancel':
this._end(e);
break;
}
},
destroy: function() {
if (this.options.interactive) {
utils.removeEvent(this.indicator, 'touchstart', this);
utils.removeEvent(this.indicator, utils.prefixPointerEvent('pointerdown'), this);
utils.removeEvent(this.indicator, 'mousedown', this);
utils.removeEvent(window, 'touchmove', this);
utils.removeEvent(window, utils.prefixPointerEvent('pointermove'), this);
utils.removeEvent(window, 'mousemove', this);
utils.removeEvent(window, 'touchend', this);
utils.removeEvent(window, utils.prefixPointerEvent('pointerup'), this);
utils.removeEvent(window, 'mouseup', this);
}
if (this.options.defaultScrollbars) {
this.wrapper.parentNode.removeChild(this.wrapper);
}
},
_start: function(e) {
var point = e.touches ? e.touches[0] : e;
e.preventDefault();
e.stopPropagation();
this.transitionTime();
this.initiated = true;
this.moved = false;
this.lastPointX = point.pageX;
this.lastPointY = point.pageY;
this.startTime = Mobird.now();
if (!this.options.disableTouch) {
utils.addEvent(window, 'touchmove', this);
}
if (!this.options.disablePointer) {
utils.addEvent(window, utils.prefixPointerEvent('pointermove'), this);
}
if (!this.options.disableMouse) {
utils.addEvent(window, 'mousemove', this);
}
this.scroller._execEvent('beforeScrollStart');
},
_move: function(e) {
var point = e.touches ? e.touches[0] : e,
deltaX, deltaY,
newX, newY,
timestamp = Mobird.now();
if (!this.moved) {
this.scroller._execEvent('scrollStart');
}
this.moved = true;
deltaX = point.pageX - this.lastPointX;
this.lastPointX = point.pageX;
deltaY = point.pageY - this.lastPointY;
this.lastPointY = point.pageY;
newX = this.x + deltaX;
newY = this.y + deltaY;
this._pos(newX, newY);
// INSERT POINT: indicator._move
e.preventDefault();
e.stopPropagation();
},
_end: function(e) {
if (!this.initiated) {
return;
}
this.initiated = false;
e.preventDefault();
e.stopPropagation();
utils.removeEvent(window, 'touchmove', this);
utils.removeEvent(window, utils.prefixPointerEvent('pointermove'), this);
utils.removeEvent(window, 'mousemove', this);
if (this.scroller.options.snap) {
var snap = this.scroller._nearestSnap(this.scroller.x, this.scroller.y);
var time = this.options.snapSpeed || Math.max(
Math.max(
Math.min(Math.abs(this.scroller.x - snap.x), 1000),
Math.min(Math.abs(this.scroller.y - snap.y), 1000)
), 300);
if (this.scroller.x != snap.x || this.scroller.y != snap.y) {
this.scroller.directionX = 0;
this.scroller.directionY = 0;
this.scroller.currentPage = snap;
this.scroller.scrollTo(snap.x, snap.y, time, this.scroller.options.bounceEasing);
}
}
if (this.moved) {
this.scroller._execEvent('scrollEnd');
}
},
transitionTime: function(time) {
time = time || 0;
this.indicatorStyle[utils.style.transitionDuration] = time + 'ms';
if (!time && utils.isBadAndroid) {
this.indicatorStyle[utils.style.transitionDuration] = '0.001s';
}
},
transitionTimingFunction: function(easing) {
this.indicatorStyle[utils.style.transitionTimingFunction] = easing;
},
refresh: function() {
this.transitionTime();
if (this.options.listenX && !this.options.listenY) {
this.indicatorStyle.display = this.scroller.hasHorizontalScroll ? 'block' : 'none';
} else if (this.options.listenY && !this.options.listenX) {
this.indicatorStyle.display = this.scroller.hasVerticalScroll ? 'block' : 'none';
} else {
this.indicatorStyle.display = this.scroller.hasHorizontalScroll || this.scroller.hasVerticalScroll ? 'block' : 'none';
}
if (this.scroller.hasHorizontalScroll && this.scroller.hasVerticalScroll) {
utils.addClass(this.wrapper, 'mo-scroll-bar');
utils.addClass(this.wrapper, 'mo-scroll-bar-both');
utils.removeClass(this.wrapper, 'iScrollLoneScrollbar');
if (this.options.defaultScrollbars && this.options.customStyle) {
if (this.options.listenX) {
this.wrapper.style.right = '8px';
} else {
this.wrapper.style.bottom = '8px';
}
}
} else {
utils.addClass(this.wrapper, 'mo-scroll-bar');
utils.removeClass(this.wrapper, 'mo-scroll-bar-both');
utils.addClass(this.wrapper, 'mo-scroll-bar-lo');
if (this.options.defaultScrollbars && this.options.customStyle) {
if (this.options.listenX) {
this.wrapper.style.right = '2px';
} else {
this.wrapper.style.bottom = '2px';
}
}
}
var r = this.wrapper.offsetHeight; // force refresh
if (this.options.listenX) {
this.wrapperWidth = this.wrapper.clientWidth;
if (this.options.resize) {
this.indicatorWidth = Math.max(Math.round(this.wrapperWidth * this.wrapperWidth / (this.scroller.scrollerWidth || this.wrapperWidth || 1)), 8);
this.indicatorStyle.width = this.indicatorWidth + 'px';
} else {
this.indicatorWidth = this.indicator.clientWidth;
}
this.maxPosX = this.wrapperWidth - this.indicatorWidth;
if (this.options.shrink == 'clip') {
this.minBoundaryX = -this.indicatorWidth + 8;
this.maxBoundaryX = this.wrapperWidth - 8;
} else {
this.minBoundaryX = 0;
this.maxBoundaryX = this.maxPosX;
}
this.sizeRatioX = this.options.speedRatioX || (this.scroller.maxScrollX && (this.maxPosX / this.scroller.maxScrollX));
}
if (this.options.listenY) {
this.wrapperHeight = this.wrapper.clientHeight;
if (this.options.resize) {
this.indicatorHeight = Math.max(Math.round(this.wrapperHeight * this.wrapperHeight / (this.scroller.scrollerHeight || this.wrapperHeight || 1)), 8);
this.indicatorStyle.height = this.indicatorHeight + 'px';
} else {
this.indicatorHeight = this.indicator.clientHeight;
}
this.maxPosY = this.wrapperHeight - this.indicatorHeight;
if (this.options.shrink == 'clip') {
this.minBoundaryY = -this.indicatorHeight + 8;
this.maxBoundaryY = this.wrapperHeight - 8;
} else {
this.minBoundaryY = 0;
this.maxBoundaryY = this.maxPosY;
}
this.maxPosY = this.wrapperHeight - this.indicatorHeight;
this.sizeRatioY = this.options.speedRatioY || (this.scroller.maxScrollY && (this.maxPosY / this.scroller.maxScrollY));
}
this.updatePosition();
},
updatePosition: function() {
var x = this.options.listenX && Math.round(this.sizeRatioX * this.scroller.x) || 0,
y = this.options.listenY && Math.round(this.sizeRatioY * this.scroller.y) || 0;
if (!this.options.ignoreBoundaries) {
if (x < this.minBoundaryX) {
if (this.options.shrink == 'scale') {
this.width = Math.max(this.indicatorWidth + x, 8);
this.indicatorStyle.width = this.width + 'px';
}
x = this.minBoundaryX;
} else if (x > this.maxBoundaryX) {
if (this.options.shrink == 'scale') {
this.width = Math.max(this.indicatorWidth - (x - this.maxPosX), 8);
this.indicatorStyle.width = this.width + 'px';
x = this.maxPosX + this.indicatorWidth - this.width;
} else {
x = this.maxBoundaryX;
}
} else if (this.options.shrink == 'scale' && this.width != this.indicatorWidth) {
this.width = this.indicatorWidth;
this.indicatorStyle.width = this.width + 'px';
}
if (y < this.minBoundaryY) {
if (this.options.shrink == 'scale') {
this.height = Math.max(this.indicatorHeight + y * 3, 8);
this.indicatorStyle.height = this.height + 'px';
}
y = this.minBoundaryY;
} else if (y > this.maxBoundaryY) {
if (this.options.shrink == 'scale') {
this.height = Math.max(this.indicatorHeight - (y - this.maxPosY) * 3, 8);
this.indicatorStyle.height = this.height + 'px';
y = this.maxPosY + this.indicatorHeight - this.height;
} else {
y = this.maxBoundaryY;
}
} else if (this.options.shrink == 'scale' && this.height != this.indicatorHeight) {
this.height = this.indicatorHeight;
this.indicatorStyle.height = this.height + 'px';
}
}
this.x = x;
this.y = y;
if (this.scroller.options.useTransform) {
this.indicatorStyle[utils.style.transform] = 'translate(' + x + 'px,' + y + 'px)' + this.scroller.translateZ;
} else {
this.indicatorStyle.left = x + 'px';
this.indicatorStyle.top = y + 'px';
}
},
_pos: function(x, y) {
if (x < 0) {
x = 0;
} else if (x > this.maxPosX) {
x = this.maxPosX;
}
if (y < 0) {
y = 0;
} else if (y > this.maxPosY) {
y = this.maxPosY;
}
x = this.options.listenX ? Math.round(x / this.sizeRatioX) : this.scroller.x;
y = this.options.listenY ? Math.round(y / this.sizeRatioY) : this.scroller.y;
this.scroller.scrollTo(x, y);
},
fade: function(val, hold) {
if (hold && !this.visible) {
return;
}
clearTimeout(this.fadeTimeout);
this.fadeTimeout = null;
var time = val ? 250 : 500,
delay = val ? 0 : 300;
val = val ? '1' : '0';
this.wrapperStyle[utils.style.transitionDuration] = time + 'ms';
this.fadeTimeout = setTimeout((function(val) {
this.wrapperStyle.opacity = val;
this.visible = +val;
}).bind(this, val), delay);
}
};
module.exports = Scroller;
});
|
/*global $:true, Backbone:true, _:true, App:true */
/*jshint browser:true */
/*jshint strict:false */
App.Models.Controller = Backbone.Model.extend({
defaults: {
socket: false
},
initialize: function(opts) {
}
});
|
/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
const documents = {
indexList: []
};
const elements = {
indexInput: null,
indexTable: null
};
function isCorrect(index) {
return index.length === 6;
}
function addIndex(index) {
documents.indexList.push(index);
elements.indexTable.append('<tr><td>' + index + '</td></tr>');
}
function sendToPrint() {
const toPush = '';
if (documents.indexList.length % 6 !== 0) {
while (documents.indexList.length % 6 !== 0) {
documents.indexList.push(toPush);
}
}
nw.Window.open('modules/f20-print/html/print.html', { 'show': false }, (win) => {
win.maximize();
// data is the list
win.window.data = documents.indexList;
});
}
function initModule() {
elements.indexInput = $('#indexInput');
elements.indexInput.mask('999999');
elements.indexTable = $('#indexTable');
$('#addIndexButton').button().click((event) => {
const index = elements.indexInput.val();
if (isCorrect(index)) {
addIndex(index);
} else {
alert(global.strings.f20_print.badFormat);
}
elements.indexInput.focus();
});
$('#printIndexesButton').button().click((event) => {
sendToPrint();
});
}
|
export {default} from 'ember-frost-demo-components/components/frost-file-node/component'
|
import { getEvent, eventMap } from '../../src/module/moveRow/event';
import { EMPTY_TPL_KEY } from '../../src/common/constants';
describe('drag', () => {
describe('getEvent', () => {
let events = null;
beforeEach(() => {
});
afterEach(() => {
events = null;
});
it('基础验证', () => {
expect(getEvent).toBeDefined();
expect(getEvent.length).toBe(1);
});
it('执行验证', () => {
events = getEvent('test');
expect(events.start.events).toBe('mousedown.gmLineDrag');
expect(events.start.target).toBe('test');
expect(events.start.selector).toBe(`tr:not([${EMPTY_TPL_KEY}])`);
expect(events.doing.events).toBe('mousemove.gmLineDrag');
expect(events.doing.target).toBe('body');
expect(events.doing.selector).toBeUndefined();
expect(events.abort.events).toBe('mouseup.gmLineDrag');
expect(events.abort.target).toBe('body');
expect(events.abort.selector).toBeUndefined();
});
});
describe('eventMap', () => {
it('基础验证', () => {
expect(eventMap).toEqual({});
});
});
});
|
output = function() {
navigator.camera.getPicture(function(imageData) {
cb({ imageData: $.create(imageData) });
}, function(err) {
cb({ error: $.create(err) });
}, {
quality: $.quality,
sourceType: Camera.PictureSourceType[$.sourceType],
allowEdit: $.allowEdit,
encodingType: Camera.EncodingType[$.encodingType],
targetWidth: $.targetWidth,
targetHeight: $.targetHeight
});
};
|
'use strict'
const execa = require('execa')
const chalk = require('chalk')
const figures = require('figures')
const ora = require('ora')
module.exports = function fetchRemote(flags) {
// git fetch
let args = ['fetch']
// fetch with prune?
if (!flags.skipPrune) {
// git fetch -p
args.push('-p')
}
let spin = ora(chalk.dim('Fetching remote')).start()
return execa('git', args).then(() => {
spin.stop()
console.log(
chalk.green(figures.tick) +
chalk.dim(' Fetched remote')
)
})
}
|
/*
RequireJS 2.1.6 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
Available via the MIT or new BSD license.
see: http://github.com/jrburke/requirejs for details
*/
var requirejs,require,define;
(function(global){var req,s,head,baseElement,dataMain,src,interactiveScript,currentlyAddingScript,mainScript,subPath,version="2.1.6",commentRegExp=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,cjsRequireRegExp=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,jsSuffixRegExp=/\.js$/,currDirRegExp=/^\.\//,op=Object.prototype,ostring=op.toString,hasOwn=op.hasOwnProperty,ap=Array.prototype,apsp=ap.splice,isBrowser=!!(typeof window!=="undefined"&&navigator&&window.document),isWebWorker=!isBrowser&&typeof importScripts!==
"undefined",readyRegExp=isBrowser&&navigator.platform==="PLAYSTATION 3"?/^complete$/:/^(complete|loaded)$/,defContextName="_",isOpera=typeof opera!=="undefined"&&opera.toString()==="[object Opera]",contexts={},cfg={},globalDefQueue=[],useInteractive=false;function isFunction(it){return ostring.call(it)==="[object Function]"}function isArray(it){return ostring.call(it)==="[object Array]"}function each(ary,func){if(ary){var i;for(i=0;i<ary.length;i+=1)if(ary[i]&&func(ary[i],i,ary))break}}function eachReverse(ary,
func){if(ary){var i;for(i=ary.length-1;i>-1;i-=1)if(ary[i]&&func(ary[i],i,ary))break}}function hasProp(obj,prop){return hasOwn.call(obj,prop)}function getOwn(obj,prop){return hasProp(obj,prop)&&obj[prop]}function eachProp(obj,func){var prop;for(prop in obj)if(hasProp(obj,prop))if(func(obj[prop],prop))break}function mixin(target,source,force,deepStringMixin){if(source)eachProp(source,function(value,prop){if(force||!hasProp(target,prop))if(deepStringMixin&&typeof value!=="string"){if(!target[prop])target[prop]=
{};mixin(target[prop],value,force,deepStringMixin)}else target[prop]=value});return target}function bind(obj,fn){return function(){return fn.apply(obj,arguments)}}function scripts(){return document.getElementsByTagName("script")}function defaultOnError(err){throw err;}function getGlobal(value){if(!value)return value;var g=global;each(value.split("."),function(part){g=g[part]});return g}function makeError(id,msg,err,requireModules){var e=new Error(msg+"\nhttp://requirejs.org/docs/errors.html#"+id);
e.requireType=id;e.requireModules=requireModules;if(err)e.originalError=err;return e}if(typeof define!=="undefined")return;if(typeof requirejs!=="undefined"){if(isFunction(requirejs))return;cfg=requirejs;requirejs=undefined}if(typeof require!=="undefined"&&!isFunction(require)){cfg=require;require=undefined}function newContext(contextName){var inCheckLoaded,Module,context,handlers,checkLoadedTimeoutId,config={waitSeconds:7,baseUrl:"./",paths:{},pkgs:{},shim:{},config:{}},registry={},enabledRegistry=
{},undefEvents={},defQueue=[],defined={},urlFetched={},requireCounter=1,unnormalizedCounter=1;function trimDots(ary){var i,part;for(i=0;ary[i];i+=1){part=ary[i];if(part==="."){ary.splice(i,1);i-=1}else if(part==="..")if(i===1&&(ary[2]===".."||ary[0]===".."))break;else if(i>0){ary.splice(i-1,2);i-=2}}}function normalize(name,baseName,applyMap){var pkgName,pkgConfig,mapValue,nameParts,i,j,nameSegment,foundMap,foundI,foundStarMap,starI,baseParts=baseName&&baseName.split("/"),normalizedBaseParts=baseParts,
map=config.map,starMap=map&&map["*"];if(name&&name.charAt(0)===".")if(baseName){if(getOwn(config.pkgs,baseName))normalizedBaseParts=baseParts=[baseName];else normalizedBaseParts=baseParts.slice(0,baseParts.length-1);name=normalizedBaseParts.concat(name.split("/"));trimDots(name);pkgConfig=getOwn(config.pkgs,pkgName=name[0]);name=name.join("/");if(pkgConfig&&name===pkgName+"/"+pkgConfig.main)name=pkgName}else if(name.indexOf("./")===0)name=name.substring(2);if(applyMap&&map&&(baseParts||starMap)){nameParts=
name.split("/");for(i=nameParts.length;i>0;i-=1){nameSegment=nameParts.slice(0,i).join("/");if(baseParts)for(j=baseParts.length;j>0;j-=1){mapValue=getOwn(map,baseParts.slice(0,j).join("/"));if(mapValue){mapValue=getOwn(mapValue,nameSegment);if(mapValue){foundMap=mapValue;foundI=i;break}}}if(foundMap)break;if(!foundStarMap&&starMap&&getOwn(starMap,nameSegment)){foundStarMap=getOwn(starMap,nameSegment);starI=i}}if(!foundMap&&foundStarMap){foundMap=foundStarMap;foundI=starI}if(foundMap){nameParts.splice(0,
foundI,foundMap);name=nameParts.join("/")}}return name}function removeScript(name){if(isBrowser)each(scripts(),function(scriptNode){if(scriptNode.getAttribute("data-requiremodule")===name&&scriptNode.getAttribute("data-requirecontext")===context.contextName){scriptNode.parentNode.removeChild(scriptNode);return true}})}function hasPathFallback(id){var pathConfig=getOwn(config.paths,id);if(pathConfig&&isArray(pathConfig)&&pathConfig.length>1){removeScript(id);pathConfig.shift();context.require.undef(id);
context.require([id]);return true}}function splitPrefix(name){var prefix,index=name?name.indexOf("!"):-1;if(index>-1){prefix=name.substring(0,index);name=name.substring(index+1,name.length)}return[prefix,name]}function makeModuleMap(name,parentModuleMap,isNormalized,applyMap){var url,pluginModule,suffix,nameParts,prefix=null,parentName=parentModuleMap?parentModuleMap.name:null,originalName=name,isDefine=true,normalizedName="";if(!name){isDefine=false;name="_@r"+(requireCounter+=1)}nameParts=splitPrefix(name);
prefix=nameParts[0];name=nameParts[1];if(prefix){prefix=normalize(prefix,parentName,applyMap);pluginModule=getOwn(defined,prefix)}if(name)if(prefix)if(pluginModule&&pluginModule.normalize)normalizedName=pluginModule.normalize(name,function(name){return normalize(name,parentName,applyMap)});else normalizedName=normalize(name,parentName,applyMap);else{normalizedName=normalize(name,parentName,applyMap);nameParts=splitPrefix(normalizedName);prefix=nameParts[0];normalizedName=nameParts[1];isNormalized=
true;url=context.nameToUrl(normalizedName)}suffix=prefix&&!pluginModule&&!isNormalized?"_unnormalized"+(unnormalizedCounter+=1):"";return{prefix:prefix,name:normalizedName,parentMap:parentModuleMap,unnormalized:!!suffix,url:url,originalName:originalName,isDefine:isDefine,id:(prefix?prefix+"!"+normalizedName:normalizedName)+suffix}}function getModule(depMap){var id=depMap.id,mod=getOwn(registry,id);if(!mod)mod=registry[id]=new context.Module(depMap);return mod}function on(depMap,name,fn){var id=depMap.id,
mod=getOwn(registry,id);if(hasProp(defined,id)&&(!mod||mod.defineEmitComplete)){if(name==="defined")fn(defined[id])}else{mod=getModule(depMap);if(mod.error&&name==="error")fn(mod.error);else mod.on(name,fn)}}function onError(err,errback){var ids=err.requireModules,notified=false;if(errback)errback(err);else{each(ids,function(id){var mod=getOwn(registry,id);if(mod){mod.error=err;if(mod.events.error){notified=true;mod.emit("error",err)}}});if(!notified)req.onError(err)}}function takeGlobalQueue(){if(globalDefQueue.length){apsp.apply(defQueue,
[defQueue.length-1,0].concat(globalDefQueue));globalDefQueue=[]}}handlers={"require":function(mod){if(mod.require)return mod.require;else return mod.require=context.makeRequire(mod.map)},"exports":function(mod){mod.usingExports=true;if(mod.map.isDefine)if(mod.exports)return mod.exports;else return mod.exports=defined[mod.map.id]={}},"module":function(mod){if(mod.module)return mod.module;else return mod.module={id:mod.map.id,uri:mod.map.url,config:function(){var c,pkg=getOwn(config.pkgs,mod.map.id);
c=pkg?getOwn(config.config,mod.map.id+"/"+pkg.main):getOwn(config.config,mod.map.id);return c||{}},exports:defined[mod.map.id]}}};function cleanRegistry(id){delete registry[id];delete enabledRegistry[id]}function breakCycle(mod,traced,processed){var id=mod.map.id;if(mod.error)mod.emit("error",mod.error);else{traced[id]=true;each(mod.depMaps,function(depMap,i){var depId=depMap.id,dep=getOwn(registry,depId);if(dep&&!mod.depMatched[i]&&!processed[depId])if(getOwn(traced,depId)){mod.defineDep(i,defined[depId]);
mod.check()}else breakCycle(dep,traced,processed)});processed[id]=true}}function checkLoaded(){var map,modId,err,usingPathFallback,waitInterval=config.waitSeconds*1E3,expired=waitInterval&&context.startTime+waitInterval<(new Date).getTime(),noLoads=[],reqCalls=[],stillLoading=false,needCycleCheck=true;if(inCheckLoaded)return;inCheckLoaded=true;eachProp(enabledRegistry,function(mod){map=mod.map;modId=map.id;if(!mod.enabled)return;if(!map.isDefine)reqCalls.push(mod);if(!mod.error)if(!mod.inited&&expired)if(hasPathFallback(modId)){usingPathFallback=
true;stillLoading=true}else{noLoads.push(modId);removeScript(modId)}else if(!mod.inited&&mod.fetched&&map.isDefine){stillLoading=true;if(!map.prefix)return needCycleCheck=false}});if(expired&&noLoads.length){err=makeError("timeout","Load timeout for modules: "+noLoads,null,noLoads);err.contextName=context.contextName;return onError(err)}if(needCycleCheck)each(reqCalls,function(mod){breakCycle(mod,{},{})});if((!expired||usingPathFallback)&&stillLoading)if((isBrowser||isWebWorker)&&!checkLoadedTimeoutId)checkLoadedTimeoutId=
setTimeout(function(){checkLoadedTimeoutId=0;checkLoaded()},50);inCheckLoaded=false}Module=function(map){this.events=getOwn(undefEvents,map.id)||{};this.map=map;this.shim=getOwn(config.shim,map.id);this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};Module.prototype={init:function(depMaps,factory,errback,options){options=options||{};if(this.inited)return;this.factory=factory;if(errback)this.on("error",errback);else if(this.events.error)errback=bind(this,function(err){this.emit("error",
err)});this.depMaps=depMaps&&depMaps.slice(0);this.errback=errback;this.inited=true;this.ignore=options.ignore;if(options.enabled||this.enabled)this.enable();else this.check()},defineDep:function(i,depExports){if(!this.depMatched[i]){this.depMatched[i]=true;this.depCount-=1;this.depExports[i]=depExports}},fetch:function(){if(this.fetched)return;this.fetched=true;context.startTime=(new Date).getTime();var map=this.map;if(this.shim)context.makeRequire(this.map,{enableBuildCallback:true})(this.shim.deps||
[],bind(this,function(){return map.prefix?this.callPlugin():this.load()}));else return map.prefix?this.callPlugin():this.load()},load:function(){var url=this.map.url;if(!urlFetched[url]){urlFetched[url]=true;context.load(this.map.id,url)}},check:function(){if(!this.enabled||this.enabling)return;var err,cjsModule,id=this.map.id,depExports=this.depExports,exports=this.exports,factory=this.factory;if(!this.inited)this.fetch();else if(this.error)this.emit("error",this.error);else if(!this.defining){this.defining=
true;if(this.depCount<1&&!this.defined){if(isFunction(factory)){if(this.events.error&&this.map.isDefine||req.onError!==defaultOnError)try{exports=context.execCb(id,factory,depExports,exports)}catch(e){err=e}else exports=context.execCb(id,factory,depExports,exports);if(this.map.isDefine){cjsModule=this.module;if(cjsModule&&cjsModule.exports!==undefined&&cjsModule.exports!==this.exports)exports=cjsModule.exports;else if(exports===undefined&&this.usingExports)exports=this.exports}if(err){err.requireMap=
this.map;err.requireModules=this.map.isDefine?[this.map.id]:null;err.requireType=this.map.isDefine?"define":"require";return onError(this.error=err)}}else exports=factory;this.exports=exports;if(this.map.isDefine&&!this.ignore){defined[id]=exports;if(req.onResourceLoad)req.onResourceLoad(context,this.map,this.depMaps)}cleanRegistry(id);this.defined=true}this.defining=false;if(this.defined&&!this.defineEmitted){this.defineEmitted=true;this.emit("defined",this.exports);this.defineEmitComplete=true}}},
callPlugin:function(){var map=this.map,id=map.id,pluginMap=makeModuleMap(map.prefix);this.depMaps.push(pluginMap);on(pluginMap,"defined",bind(this,function(plugin){var load,normalizedMap,normalizedMod,name=this.map.name,parentName=this.map.parentMap?this.map.parentMap.name:null,localRequire=context.makeRequire(map.parentMap,{enableBuildCallback:true});if(this.map.unnormalized){if(plugin.normalize)name=plugin.normalize(name,function(name){return normalize(name,parentName,true)})||"";normalizedMap=
makeModuleMap(map.prefix+"!"+name,this.map.parentMap);on(normalizedMap,"defined",bind(this,function(value){this.init([],function(){return value},null,{enabled:true,ignore:true})}));normalizedMod=getOwn(registry,normalizedMap.id);if(normalizedMod){this.depMaps.push(normalizedMap);if(this.events.error)normalizedMod.on("error",bind(this,function(err){this.emit("error",err)}));normalizedMod.enable()}return}load=bind(this,function(value){this.init([],function(){return value},null,{enabled:true})});load.error=
bind(this,function(err){this.inited=true;this.error=err;err.requireModules=[id];eachProp(registry,function(mod){if(mod.map.id.indexOf(id+"_unnormalized")===0)cleanRegistry(mod.map.id)});onError(err)});load.fromText=bind(this,function(text,textAlt){var moduleName=map.name,moduleMap=makeModuleMap(moduleName),hasInteractive=useInteractive;if(textAlt)text=textAlt;if(hasInteractive)useInteractive=false;getModule(moduleMap);if(hasProp(config.config,id))config.config[moduleName]=config.config[id];try{req.exec(text)}catch(e){return onError(makeError("fromtexteval",
"fromText eval for "+id+" failed: "+e,e,[id]))}if(hasInteractive)useInteractive=true;this.depMaps.push(moduleMap);context.completeLoad(moduleName);localRequire([moduleName],load)});plugin.load(map.name,localRequire,load,config)}));context.enable(pluginMap,this);this.pluginMaps[pluginMap.id]=pluginMap},enable:function(){enabledRegistry[this.map.id]=this;this.enabled=true;this.enabling=true;each(this.depMaps,bind(this,function(depMap,i){var id,mod,handler;if(typeof depMap==="string"){depMap=makeModuleMap(depMap,
this.map.isDefine?this.map:this.map.parentMap,false,!this.skipMap);this.depMaps[i]=depMap;handler=getOwn(handlers,depMap.id);if(handler){this.depExports[i]=handler(this);return}this.depCount+=1;on(depMap,"defined",bind(this,function(depExports){this.defineDep(i,depExports);this.check()}));if(this.errback)on(depMap,"error",bind(this,this.errback))}id=depMap.id;mod=registry[id];if(!hasProp(handlers,id)&&mod&&!mod.enabled)context.enable(depMap,this)}));eachProp(this.pluginMaps,bind(this,function(pluginMap){var mod=
getOwn(registry,pluginMap.id);if(mod&&!mod.enabled)context.enable(pluginMap,this)}));this.enabling=false;this.check()},on:function(name,cb){var cbs=this.events[name];if(!cbs)cbs=this.events[name]=[];cbs.push(cb)},emit:function(name,evt){each(this.events[name],function(cb){cb(evt)});if(name==="error")delete this.events[name]}};function callGetModule(args){if(!hasProp(defined,args[0]))getModule(makeModuleMap(args[0],null,true)).init(args[1],args[2])}function removeListener(node,func,name,ieName){if(node.detachEvent&&
!isOpera){if(ieName)node.detachEvent(ieName,func)}else node.removeEventListener(name,func,false)}function getScriptData(evt){var node=evt.currentTarget||evt.srcElement;removeListener(node,context.onScriptLoad,"load","onreadystatechange");removeListener(node,context.onScriptError,"error");return{node:node,id:node&&node.getAttribute("data-requiremodule")}}function intakeDefines(){var args;takeGlobalQueue();while(defQueue.length){args=defQueue.shift();if(args[0]===null)return onError(makeError("mismatch",
"Mismatched anonymous define() module: "+args[args.length-1]));else callGetModule(args)}}context={config:config,contextName:contextName,registry:registry,defined:defined,urlFetched:urlFetched,defQueue:defQueue,Module:Module,makeModuleMap:makeModuleMap,nextTick:req.nextTick,onError:onError,configure:function(cfg){if(cfg.baseUrl)if(cfg.baseUrl.charAt(cfg.baseUrl.length-1)!=="/")cfg.baseUrl+="/";var pkgs=config.pkgs,shim=config.shim,objs={paths:true,config:true,map:true};eachProp(cfg,function(value,
prop){if(objs[prop])if(prop==="map"){if(!config.map)config.map={};mixin(config[prop],value,true,true)}else mixin(config[prop],value,true);else config[prop]=value});if(cfg.shim){eachProp(cfg.shim,function(value,id){if(isArray(value))value={deps:value};if((value.exports||value.init)&&!value.exportsFn)value.exportsFn=context.makeShimExports(value);shim[id]=value});config.shim=shim}if(cfg.packages){each(cfg.packages,function(pkgObj){var location;pkgObj=typeof pkgObj==="string"?{name:pkgObj}:pkgObj;location=
pkgObj.location;pkgs[pkgObj.name]={name:pkgObj.name,location:location||pkgObj.name,main:(pkgObj.main||"main").replace(currDirRegExp,"").replace(jsSuffixRegExp,"")}});config.pkgs=pkgs}eachProp(registry,function(mod,id){if(!mod.inited&&!mod.map.unnormalized)mod.map=makeModuleMap(id)});if(cfg.deps||cfg.callback)context.require(cfg.deps||[],cfg.callback)},makeShimExports:function(value){function fn(){var ret;if(value.init)ret=value.init.apply(global,arguments);return ret||value.exports&&getGlobal(value.exports)}
return fn},makeRequire:function(relMap,options){options=options||{};function localRequire(deps,callback,errback){var id,map,requireMod;if(options.enableBuildCallback&&callback&&isFunction(callback))callback.__requireJsBuild=true;if(typeof deps==="string"){if(isFunction(callback))return onError(makeError("requireargs","Invalid require call"),errback);if(relMap&&hasProp(handlers,deps))return handlers[deps](registry[relMap.id]);if(req.get)return req.get(context,deps,relMap,localRequire);map=makeModuleMap(deps,
relMap,false,true);id=map.id;if(!hasProp(defined,id))return onError(makeError("notloaded",'Module name "'+id+'" has not been loaded yet for context: '+contextName+(relMap?"":". Use require([])")));return defined[id]}intakeDefines();context.nextTick(function(){intakeDefines();requireMod=getModule(makeModuleMap(null,relMap));requireMod.skipMap=options.skipMap;requireMod.init(deps,callback,errback,{enabled:true});checkLoaded()});return localRequire}mixin(localRequire,{isBrowser:isBrowser,toUrl:function(moduleNamePlusExt){var ext,
index=moduleNamePlusExt.lastIndexOf("."),segment=moduleNamePlusExt.split("/")[0],isRelative=segment==="."||segment==="..";if(index!==-1&&(!isRelative||index>1)){ext=moduleNamePlusExt.substring(index,moduleNamePlusExt.length);moduleNamePlusExt=moduleNamePlusExt.substring(0,index)}return context.nameToUrl(normalize(moduleNamePlusExt,relMap&&relMap.id,true),ext,true)},defined:function(id){return hasProp(defined,makeModuleMap(id,relMap,false,true).id)},specified:function(id){id=makeModuleMap(id,relMap,
false,true).id;return hasProp(defined,id)||hasProp(registry,id)}});if(!relMap)localRequire.undef=function(id){takeGlobalQueue();var map=makeModuleMap(id,relMap,true),mod=getOwn(registry,id);delete defined[id];delete urlFetched[map.url];delete undefEvents[id];if(mod){if(mod.events.defined)undefEvents[id]=mod.events;cleanRegistry(id)}};return localRequire},enable:function(depMap){var mod=getOwn(registry,depMap.id);if(mod)getModule(depMap).enable()},completeLoad:function(moduleName){var found,args,mod,
shim=getOwn(config.shim,moduleName)||{},shExports=shim.exports;takeGlobalQueue();while(defQueue.length){args=defQueue.shift();if(args[0]===null){args[0]=moduleName;if(found)break;found=true}else if(args[0]===moduleName)found=true;callGetModule(args)}mod=getOwn(registry,moduleName);if(!found&&!hasProp(defined,moduleName)&&mod&&!mod.inited)if(config.enforceDefine&&(!shExports||!getGlobal(shExports)))if(hasPathFallback(moduleName))return;else return onError(makeError("nodefine","No define call for "+
moduleName,null,[moduleName]));else callGetModule([moduleName,shim.deps||[],shim.exportsFn]);checkLoaded()},nameToUrl:function(moduleName,ext,skipExt){var paths,pkgs,pkg,pkgPath,syms,i,parentModule,url,parentPath;if(req.jsExtRegExp.test(moduleName))url=moduleName+(ext||"");else{paths=config.paths;pkgs=config.pkgs;syms=moduleName.split("/");for(i=syms.length;i>0;i-=1){parentModule=syms.slice(0,i).join("/");pkg=getOwn(pkgs,parentModule);parentPath=getOwn(paths,parentModule);if(parentPath){if(isArray(parentPath))parentPath=
parentPath[0];syms.splice(0,i,parentPath);break}else if(pkg){if(moduleName===pkg.name)pkgPath=pkg.location+"/"+pkg.main;else pkgPath=pkg.location;syms.splice(0,i,pkgPath);break}}url=syms.join("/");url+=ext||(/\?/.test(url)||skipExt?"":".js");url=(url.charAt(0)==="/"||url.match(/^[\w\+\.\-]+:/)?"":config.baseUrl)+url}return config.urlArgs?url+((url.indexOf("?")===-1?"?":"&")+config.urlArgs):url},load:function(id,url){req.load(context,id,url)},execCb:function(name,callback,args,exports){return callback.apply(exports,
args)},onScriptLoad:function(evt){if(evt.type==="load"||readyRegExp.test((evt.currentTarget||evt.srcElement).readyState)){interactiveScript=null;var data=getScriptData(evt);context.completeLoad(data.id)}},onScriptError:function(evt){var data=getScriptData(evt);if(!hasPathFallback(data.id))return onError(makeError("scripterror","Script error for: "+data.id,evt,[data.id]))}};context.require=context.makeRequire();return context}req=requirejs=function(deps,callback,errback,optional){var context,config,
contextName=defContextName;if(!isArray(deps)&&typeof deps!=="string"){config=deps;if(isArray(callback)){deps=callback;callback=errback;errback=optional}else deps=[]}if(config&&config.context)contextName=config.context;context=getOwn(contexts,contextName);if(!context)context=contexts[contextName]=req.s.newContext(contextName);if(config)context.configure(config);return context.require(deps,callback,errback)};req.config=function(config){return req(config)};req.nextTick=typeof setTimeout!=="undefined"?
function(fn){setTimeout(fn,4)}:function(fn){fn()};if(!require)require=req;req.version=version;req.jsExtRegExp=/^\/|:|\?|\.js$/;req.isBrowser=isBrowser;s=req.s={contexts:contexts,newContext:newContext};req({});each(["toUrl","undef","defined","specified"],function(prop){req[prop]=function(){var ctx=contexts[defContextName];return ctx.require[prop].apply(ctx,arguments)}});if(isBrowser){head=s.head=document.getElementsByTagName("head")[0];baseElement=document.getElementsByTagName("base")[0];if(baseElement)head=
s.head=baseElement.parentNode}req.onError=defaultOnError;req.load=function(context,moduleName,url){var config=context&&context.config||{},node;if(isBrowser){node=config.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script");node.type=config.scriptType||"text/javascript";node.charset="utf-8";node.async=true;node.setAttribute("data-requirecontext",context.contextName);node.setAttribute("data-requiremodule",moduleName);if(node.attachEvent&&!(node.attachEvent.toString&&
node.attachEvent.toString().indexOf("[native code")<0)&&!isOpera){useInteractive=true;node.attachEvent("onreadystatechange",context.onScriptLoad)}else{node.addEventListener("load",context.onScriptLoad,false);node.addEventListener("error",context.onScriptError,false)}node.src=url;currentlyAddingScript=node;if(baseElement)head.insertBefore(node,baseElement);else head.appendChild(node);currentlyAddingScript=null;return node}else if(isWebWorker)try{importScripts(url);context.completeLoad(moduleName)}catch(e){context.onError(makeError("importscripts",
"importScripts failed for "+moduleName+" at "+url,e,[moduleName]))}};function getInteractiveScript(){if(interactiveScript&&interactiveScript.readyState==="interactive")return interactiveScript;eachReverse(scripts(),function(script){if(script.readyState==="interactive")return interactiveScript=script});return interactiveScript}if(isBrowser)eachReverse(scripts(),function(script){if(!head)head=script.parentNode;dataMain=script.getAttribute("data-main");if(dataMain){mainScript=dataMain;if(!cfg.baseUrl){src=
mainScript.split("/");mainScript=src.pop();subPath=src.length?src.join("/")+"/":"./";cfg.baseUrl=subPath}mainScript=mainScript.replace(jsSuffixRegExp,"");if(req.jsExtRegExp.test(mainScript))mainScript=dataMain;cfg.deps=cfg.deps?cfg.deps.concat(mainScript):[mainScript];return true}});define=function(name,deps,callback){var node,context;if(typeof name!=="string"){callback=deps;deps=name;name=null}if(!isArray(deps)){callback=deps;deps=null}if(!deps&&isFunction(callback)){deps=[];if(callback.length){callback.toString().replace(commentRegExp,
"").replace(cjsRequireRegExp,function(match,dep){deps.push(dep)});deps=(callback.length===1?["require"]:["require","exports","module"]).concat(deps)}}if(useInteractive){node=currentlyAddingScript||getInteractiveScript();if(node){if(!name)name=node.getAttribute("data-requiremodule");context=contexts[node.getAttribute("data-requirecontext")]}}(context?context.defQueue:globalDefQueue).push([name,deps,callback])};define.amd={jQuery:true};req.exec=function(text){return eval(text)};req(cfg)})(this);
|
const { massiveHide } = require('../coreFunctions');
const header = {
init: () => {
constructor();
setupLogo();
},
};
const constructor = () => {
headerContainer = body.find('#header');
const breadcrumbContainer = body.find('.bread-container')
const hideElements = [
headerContainer.find('#station-logo'),
headerContainer.find('#header-menu'),
headerContainer.find('#header-actions-ul'),
headerContainer.find('#header-facebook-like'),
];
massiveHide(hideElements);
headerContainer.addClass('mo-header-container');
breadcrumbContainer.addClass('mo-breadcrumb-container');
}
const setupLogo = () => {
const logoContainer = `
<a href="/vale-tudo_f_57" class="mo-logo-container">
<div class="mo-logo-image sprite-vtMini"></div>
<div class="mo-logo-text">VT Mobile</div>
</a>
<div class="mo-login-container">
<a href="https://acesso.uol.com.br/login.html?skin=forum-jogos&dest=REDIR|mlocal.forum.jogos.uol.com.br" class="mo-login-button fa fa-user fa-2x"></a>
</div>
`;
headerContainer.append(logoContainer);
}
module.exports = header;
|
"use strict";
const btc = require("./coins/btc.js");
module.exports = {
"BTC": btc,
"coins":["BTC"]
};
|
"use strict";
module.exports = {
test_page: "tests/index.html?hidepassed",
disable_watching: true,
launch_in_ci: ["Chrome"],
launch_in_dev: [],
browser_start_timeout: 120,
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
process.env.CI ? "--no-sandbox" : null,
"--headless",
"--disable-dev-shm-usage",
"--disable-software-rasterizer",
"--mute-audio",
"--remote-debugging-port=0",
"--window-size=1440,900",
].filter(Boolean),
},
},
};
|
const greeting = (name) => {
const element = document.querySelector('.js-greeting');
if (element) {
element.innerHTML = name;
}
};
export default greeting;
|
define(function(require,exports, module) {
var $ = require('jquery');
var React = require('react');
var Backbone = require('backbone');
var MyTable = require('./components/table/Table');
var ReactApp={
getJsonData:function(data){
alert('收集数据!'+data);
},
getInstance:function(model,options){
var modelData = new Backbone.Model(model);
React.render(React.createElement(MyTable, {data: modelData, onGetJsonData: this.getJsonData}), $('#example')[0]);
}
};
return ReactApp;
});
|
import Backend from 'i18next-xhr-backend';
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.plugin('aurelia-i18n', (i18n) => {
i18n.i18next.use(Backend);
return i18n.setup({
backend: {
loadPath: './locales/{{lng}}/{{ns}}.json',
},
lng : 'en',
fallbackLng : 'en'
});
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.