code
stringlengths
2
1.05M
// Properties starting with _ are meant for the higher-level Nick browser // Properties starting with __ are private to the driver // Read-only properties should be configured as such const TabDriver = require("./TabDriver") //const chromeLauncher = require('chrome-launcher') const CDP = require('chrome-remote-interface') const _ = require("lodash") const toBoolean = require("to-boolean") class BrowserDriver { constructor(nick) { this._nick = nick this._options = nick.options } exit(code) { process.exit(code) } _initialize(callback) { const chromePath = process.env.CHROME_PATH || "google-chrome-beta" const childOptions = [ "--remote-debugging-port=9222", // allow ugly things because we want to scrape without being bothered "--disable-web-security", "--allow-insecure-localhost", "--allow-running-insecure-content", "--allow-file-access-from-files", // set window size `--window-size=${this._options.width},${this._options.height}`, // flags taken from Puppeteer's defaultArgs "--disable-background-networking", "--disable-background-timer-throttling", "--disable-client-side-phishing-detection", "--disable-default-apps", "--disable-extensions", "--disable-hang-monitor", "--disable-popup-blocking", "--disable-prompt-on-repost", "--disable-sync", // google account sync "--disable-translate", // built-in Google Translate stuff "--metrics-recording-only", // record but don't report "--no-first-run", "--safebrowsing-disable-auto-update", "--password-store=basic", "--use-mock-keychain", //"--enable-crash-reporter", //"--enable-logging", //"--v=1", ] if (this._options.headless) { childOptions.push("--disable-gpu") childOptions.push("--headless") childOptions.push("--hide-scrollbars") childOptions.push("--mute-audio") } else { childOptions.push("--enable-automation") // inform user that the browser is automatically controlled } if (this._options.additionalChildOptions) { childOptions.concat(this._options.additionalChildOptions); } // chrome doesnt support proxy auth directly, we'll intercept requests and respond to the auth challenges if (this._options.httpProxy) { const { URL } = require("url") const url = new URL(this._options.httpProxy) // extract auth settings from URL and save them in the options so that all tabs can use them this._options._proxyUsername = url.username this._options._proxyPassword = url.password childOptions.push(`--proxy-server=${url.host}`) } // some systems need this, sometimes if (toBoolean(process.env.NICKJS_NO_SANDBOX || false)) { childOptions.push("--no-sandbox") childOptions.push("--disable-setuid-sandbox") } const child = require("child_process").spawn(chromePath, childOptions) process.on("exit", () => { if (!child.killed) { try { child.kill() } catch (e) {} } }) child.on("error", (err) => { callback(`could not start chrome: ${err}`) // it's alright, _initialize() is wrapped with once() }) if (this._options.debug) { let that = this; child.stdout.on("data", (d) => { if (that._options.childStdout == 'stdout') { process.stdout.write("CHROME STDOUT: " + d.toString()) } else { process.stderr.write("CHROME STDOUT: " + d.toString()) } }) child.stderr.on("data", (d) => { if (that._options.childStderr == 'stdout') { process.stdout.write("CHROME STDERR: " + d.toString()) } else { process.stderr.write("CHROME STDERR: " + d.toString()) } }) const pidusage = require("pidusage") const logChromeMemory = () => { pidusage.stat(child.pid, (err, stat) => { if (!err && stat.cpu && stat.memory) { console.log(`> Chrome: CPU ${Math.round(stat.cpu)}%, memory ${Math.round(stat.memory / (1000 * 1000))}M`) } }) } setInterval(logChromeMemory, 60 * 1000) } else { // still consume output when not in debug mode child.stdout.on("data", (d) => {}) child.stderr.on("data", (d) => {}) } child.on("exit", (code, signal) => { if (signal) { process.stdout.write(`\nFatal: Chrome subprocess killed by signal ${signal}\n\n`) } else { process.stdout.write(`\nFatal: Chrome subprocess exited with code ${code}\n\n`) } for (const tabId in this._nick.tabs) { this._nick.tabs[tabId].driver._chromeHasCrashed() } }) const cleanSocket = (socket) => { socket.removeAllListeners() socket.end() socket.destroy() socket.unref() } const net = require("net") const checkStart = Date.now() let nbChecks = 0 const checkDebuggerPort = () => { setTimeout(() => { const socket = net.createConnection(9222) socket.once("error", (err) => { ++nbChecks cleanSocket(socket) if ((Date.now() - checkStart) > (10 * 1000)) { callback(`could not connect to chrome debugger after ${nbChecks} tries (10s): ${err}`) } else { checkDebuggerPort() } }) socket.once("connect", () => { if (this._options.debug) { console.log(`> It took ${Date.now() - checkStart}ms to start and connect to Chrome (${nbChecks + 1} tries)`) } cleanSocket(socket) callback(null) }) }, Math.min(100 + nbChecks * 50, 500)) } checkDebuggerPort() } _newTabDriver(uniqueTabId, callback) { const connectToTab = (cdpTarget) => { CDP({ target: cdpTarget }, (client) => { const tab = new TabDriver(uniqueTabId, this._options, client, cdpTarget.id) tab._init((err) => { if (err) { callback(err) } else { callback(null, tab) } }) }).on('error', (err) => { callback(`cannot connect to chrome tab: ${err}`) }) } CDP.List((err, tabs) => { if (err) { callback(`could not list chrome tabs: ${err}`) } else { if ((uniqueTabId === 1) && (tabs.length === 1) && (tabs[0].url === "about:blank")) { //console.log("connecting to initial tab") connectToTab(tabs[0]) } else { CDP.New((err, tab) => { if (err) { callback(`cannot create new chrome tab: ${err}`) } else { //console.log("connecting to a new tab") connectToTab(tab) } }) } } }) } // We need an open connection to any Chrome tab to manipulate cookies. Instead of opening // a new socket/tab every time the user makes cookie requests, we use any currently open // tab he has (any tab will do). // This method also handles the error in case there are no open tabs. __getOneTabForCookieRequest(methodName, callback) { const tab = this._nick.tabs[Object.keys(this._nick.tabs)[0]] if (tab) { return tab } else { callback(`${methodName}: could not manipulate cookies because there are no open tabs, please open at least one tab`) return null } } _getAllCookies(callback) { const tab = this.__getOneTabForCookieRequest("getAllCookies", callback) if (tab) { tab.driver._getAllCookies(callback) } } _deleteAllCookies(callback) { const tab = this.__getOneTabForCookieRequest("deleteAllCookies", callback) if (tab) { tab.driver._deleteAllCookies(callback) } } _deleteCookie(name, domain, callback) { const tab = this.__getOneTabForCookieRequest("deleteCookie", callback) if (tab) { tab.driver._deleteCookie(name, domain, callback) } } _setCookie(cookie, callback) { const tab = this.__getOneTabForCookieRequest("setCookie", callback) if (tab) { tab.driver._setCookie(cookie, callback) } } } module.exports = BrowserDriver
import mod1331 from './mod1331'; var value=mod1331+1; export default value;
/** @license ISC License (c) copyright 2018 original and current authors */ /** @author Robert Pearce (rpearce) */ /** isSymbol :: a -> Boolean */ function isSymbol(x) { return typeof x === 'symbol' } module.exports = isSymbol
#!/usr/bin/env node require('./es5-bundle');
var yod = require('yod-mock'); /** * generate number * @return {[type]} return an int */ function generate_number () { return yod('@Int()'); } /** * generate number array * @param {[type]} length array length * @return {[type]} number array */ function generate_number_array (length) { return yod('@Int().repeat(' + length + ')'); } exports.generate_number = generate_number; exports.generate_number_array = generate_number_array
/*2017-9-14 Jfeng Cheng * */ var arr = [1, 2, 3, 4, 5,6,7]; //var arr1 = ['a','b','c']; //console.log(`arr.concat(arr,arr1) => [${arr.concat(arr1)}]`); console.log(`arr.forEach => ${arr.forEach(function(ele){ console.log(ele); })}`); console.log(arr.map(function(ele){ return 2 * ele; })); console.log(arr.filter(function(ele){ return ele >=3; })); console.log(arr.reduce(function(pre,next){ return pre + next; })); console.log(arr.every(function(item){ return item > 0; })); console.log(arr.some(function(item){ return item > 3; }));
import Ember from 'ember'; import DS from 'ember-data'; import Quantifiable from '../objects/quantifiable'; import _ from 'lodash/lodash'; export default DS.Transform.extend({ dofusData: Ember.inject.service('dofusData'), deserialize(rawMetadata) { let dofusData = this.get('dofusData'); let metadata = JSON.parse(rawMetadata); let items = _.reduce(metadata.items, function(quantifiableList, target, itemId) { quantifiableList.push(Quantifiable.create({ item: dofusData.getItem(itemId), target: target })); return quantifiableList; }, []); let stocksMap = _.reduce(items, function(quantifiableMap, quantifiableItem) { _.each(quantifiableItem.get('item.recipe'), function(resourceTarget, resourceId) { if ( ! _.has(metadata.items, resourceId)) { if ( ! _.has(quantifiableMap, resourceId)) { quantifiableMap[resourceId] = Quantifiable.create({ item: dofusData.getItem(resourceId), quantity: _.get(metadata.stocks, resourceId, 0) }); } quantifiableMap[resourceId].increaseTargetOf(parseInt(resourceTarget, 10) * quantifiableItem.get('target')); } }); return quantifiableMap; }, {}); return { items: items, stocks: _.values(stocksMap) }; }, serialize(metadata) { let itemsMap = _.reduce(metadata.items, function(itemsMapBuffer, quantifiableItem) { itemsMapBuffer[quantifiableItem.get('item.id')] = quantifiableItem.get('target'); return itemsMapBuffer; }, {}); let stocksMap = _.reduce(metadata.stocks, function(stocksMapBuffer, quantifiableItem) { if (quantifiableItem.get('quantity') > 0) { stocksMapBuffer[quantifiableItem.get('item.id')] = quantifiableItem.get('quantity'); } return stocksMapBuffer; }, {}); return JSON.stringify({ items: itemsMap, stocks: stocksMap }); } });
import fs from 'fs'; import { toFolders } from './utils'; export default function update(rootFolder, targetPath, locale) { try { const compiledLocale = fs.readFileSync(`${targetPath}/${locale}.yml`, 'utf8'); const updatedFolders = toFolders(rootFolder, compiledLocale, locale); console.log('Folders updated'); return updatedFolders; } catch (err) { console.error(err); } }
'use strict'; var keys; if (Object.keys) { keys = Object.keys; } else { keys = function(obj) { var result = []; for (var key in obj) { result.push(key); } return result; }; } module('loader.js api', { teardown: function() { requirejs.clear(); } }); test('has api', function() { equal(typeof require, 'function'); equal(typeof define, 'function'); equal(define.amd, undefined); ok(define.petal); equal(typeof requirejs, 'function'); equal(typeof requireModule, 'function'); }); test('simple define/require', function() { var fooCalled = 0; define('foo', [], function() { fooCalled++; }); var foo = require('foo'); equal(foo, undefined); equal(fooCalled, 1); deepEqual(keys(requirejs.entries), ['foo']); var fooAgain = require('foo'); equal(fooAgain, undefined); equal(fooCalled, 1); deepEqual(keys(requirejs.entries), ['foo']); }); test('define without deps', function() { var fooCalled = 0; define('foo', function() { fooCalled++; }); var foo = require('foo'); equal(foo, undefined); equal(fooCalled, 1); deepEqual(keys(requirejs.entries), ['foo']); }); test('multiple define/require', function() { define('foo', [], function() { }); deepEqual(keys(requirejs.entries), ['foo']); define('bar', [], function() { }); deepEqual(keys(requirejs.entries), ['foo', 'bar']); }); test('simple import/export', function() { expect(2); define('foo', ['bar'], function(bar) { equal(bar.baz, 'baz'); return bar.baz; }); define('bar', [], function() { return { baz: 'baz' }; }); equal(require('foo'), 'baz'); }); test('simple import/export with `exports`', function() { expect(2); define('foo', ['bar', 'exports'], function(bar, __exports__) { equal(bar.baz, 'baz'); __exports__.baz = bar.baz; }); define('bar', ['exports'], function(__exports__) { __exports__.baz = 'baz'; }); equal(require('foo').baz, 'baz'); }); test('relative import/export', function() { expect(2); define('foo/a', ['./b'], function(bar) { equal(bar.baz, 'baz'); return bar.baz; }); define('foo/b', [], function() { return { baz: 'baz' }; }); equal(require('foo/a'), 'baz'); }); test('deep nested relative import/export', function() { expect(2); define('foo/a/b/c', ['../../b/b/c'], function(bar) { equal(bar.baz, 'baz'); return bar.baz; }); define('foo/b/b/c', [], function() { return { baz: 'baz' }; }); equal(require('foo/a/b/c'), 'baz'); }); test('incorrect lookup paths should fail', function() { define('foo/isolated-container', [], function() { return 'container'; }); define('foo', ['./isolated-container'], function(container) { return { container: container }; }); throws(function() { return require('foo'); }, function(err) { return err.message === 'Could not find module `isolated-container` imported from `foo`'; }); }); test('top-level relative import/export', function() { expect(2); define('foo', ['./bar'], function(bar) { equal(bar.baz, 'baz'); return bar.baz; }); define('bar', [], function() { return { baz: 'baz' }; }); equal(require('foo'), 'baz'); }); test('runtime cycles', function() { define('foo', ['bar', 'exports'], function(bar, __exports__) { __exports__.quz = function() { return bar.baz; }; }); define('bar', ['foo', 'exports'], function(foo, __exports__) { __exports__.baz = function() { return foo.quz; }; }); var foo = require('foo'); var bar = require('bar'); ok(foo.quz()); ok(bar.baz()); equal(foo.quz(), bar.baz, 'cycle foo depends on bar'); equal(bar.baz(), foo.quz, 'cycle bar depends on foo'); }); test('basic CJS mode', function() { define('a/foo', ['require', 'exports', 'module'], function(require, exports, module) { module.exports = { bar: require('./bar').name }; }); define('a/bar', ['require', 'exports', 'module'], function(require, exports, module) { exports.name = 'bar'; }); var foo = require('a/foo'); equal(foo.bar, 'bar'); }); test('pass default deps if arguments are expected and deps not passed', function() { define('foo', function(require, exports, module) { equal(arguments.length, 3); }); require('foo'); }); test('if factory returns a value it is used as export', function() { define('foo', ['require', 'exports', 'module'], function(require, exports, module) { return { bar: 'bar' }; }); var foo = require('foo'); equal(foo.bar, 'bar'); }); test("if a module has no default property assume the return is the default", function() { define('foo', [], function() { return { bar: 'bar' }; }); var foo = require('foo')['default']; equal(foo.bar, 'bar'); }); test("if a CJS style module has no default export assume module.exports is the default", function() { define('Foo', ['require', 'exports', 'module'], function(require, exports, module) { module.exports = function Foo() { this.bar = 'bar'; }; }); var Foo = require('Foo')['default']; var foo = new Foo(); equal(foo.bar, 'bar'); }); test("if a module has no default property assume its export is default (function)", function() { var theFunction = function theFunction() {}; define('foo', ['require', 'exports', 'module'], function(require, exports, module) { return theFunction; }); equal(require('foo')['default'], theFunction); equal(require('foo'), theFunction); }); test("has good error message for missing module", function() { var theFunction = function theFunction() {}; define('foo', ['apple'], function(require, exports, module) { return theFunction; }); throws(function() { require('foo'); }, /Could not find module `apple` imported from `foo`/); }); test("provides good error message when an un-named AMD module is provided", function() { throws(function() { define(function() { }); }, new Error('an unsupported module was defined, expected `define(name, deps, module)` instead got: `1` arguments to define`')); }); test('throws when accessing parent module of root', function() { expect(2); define('foo', ['../a'], function() {}); throws(function() { require('foo'); }, /Cannot access parent module of root/); define('bar/baz', ['../../a'], function() {}); throws(function() { require('bar/baz'); }, /Cannot access parent module of root/); }); test("relative CJS esq require", function() { define('foo/a', ['require'], function(require) { return require('./b'); }); define('foo/b', ['require'], function(require) { return require('./c'); }); define('foo/c', ['require'], function(require) { return 'c-content'; }); equal(require('foo/a'), 'c-content'); }); test("relative CJS esq require (with exports and module');", function() { define('foo/a', ['module', 'exports', 'require'], function(module, exports, require) { module.exports = require('./b'); }); define('foo/b', ['module', 'exports', 'require'], function(module, exports, require) { module.exports = require('./c'); }); define('foo/c', ['module', 'exports', 'require'], function(module, exports, require) { module.exports = 'c-content'; }); equal(require('foo/a'), 'c-content'); }); test('foo foo/index are the same thing', function() { define('foo/index', [] , function() { return { 'default': 'hi' }; }); define('foo', [ ], define.alias('foo/index')); define('bar', ['foo', 'foo/index'] , function(foo, fooIndex) { deepEqual(foo, fooIndex); }); deepEqual(require('foo'), require('foo/index')); }); test('unsee', function() { var counter = 0; define('foo', [] , function() { counter++; return { 'default': 'hi' }; }); equal(counter, 0); require('foo'); equal(counter, 1); require('foo'); equal(counter, 1); require.unsee('foo'); equal(counter, 1); require('foo'); equal(counter, 2); require('foo'); equal(counter, 2); }); module('loader.js mock support', { teardown: function() { requirejs.clear(); } }); test('define with mocked module dependencies', function() { define('foo', [], function() { return 1; }); define('bar', ['foo'], function(foo) { return foo; }); equal(require('bar', { foo: 2 }), 2, 'Able to mock module dependencies'); equal(require('bar'), 1, 'Module dependencies are restored'); define('foo/bar', [], function() { return 3; }); define('foo/baz', ['./bar'], function(baz) { return baz; }); equal(require('foo/baz', { './bar': 4 }), 4, 'mocked module paths can be relative'); equal(require('foo/baz'), 3, 'Module dependencies are restored'); });
/** * Created by FDD on 2016/11/13. */ define(['angularAMD', 'config','util','tooltips', 'jquery', 'angular-ui-router', 'ngDialog'], function (angularAMD, config, util) { // routes var registerRoutes = function ($stateProvider, $urlRouterProvider, $httpProvider) { // defaultPage $urlRouterProvider.otherwise("/app"); $stateProvider .state('app', angularAMD.route({ url: '/app', views: { 'header': { templateUrl: 'views/header/header.html', resolve: { delay: function ($q) { var delay = $q.defer(); require(['headerCtrl'], function () { delay.resolve(); }); return delay.promise; } } }, 'footer': { templateUrl: 'views/footer/footer.html' }, 'nav': { templateUrl: 'views/nav/nav.html', resolve: { delay: function ($q) { var delay = $q.defer(); require(['navCtrl'], function () { delay.resolve(); }); return delay.promise; } } }, 'main': { templateUrl: 'views/main/main.html', resolve: { delay: function ($q) { var delay = $q.defer(); require(['mainCtrl'], function () { delay.resolve(); }); return delay.promise; } } } } })) .state('app.main.mapApi', angularAMD.route({ url: '/mapApi', views: { 'windowLeft@index.app.main': { templateUrl: 'views/mapApi/apiTree/apiTree.html', resolve: { delay: function ($q) { var delay = $q.defer(); require(['apiTreeCtrl'], function () { delay.resolve(); }); return delay.promise; } } }, 'windowRight@index.app.main': { templateUrl: 'views/mapApi/apiContent/apiContent.html', resolve: { delay: function ($q) { var delay = $q.defer(); require(['apiContentCtrl'], function () { delay.resolve(); }); return delay.promise; } } } } })) }; // module var app = angular.module("app", ["ui.router", "ngDialog"]); // config app.config(["$stateProvider", "$urlRouterProvider", '$httpProvider', registerRoutes]); app.run(['$rootScope', '$location', '$state', function ($rootScope,$location,$state) { var windowState = []; // The change of listening to the router $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { }); }]); // bootstrap return angularAMD.bootstrap(app); });
/*! * Build script for www.buildgem.com. * * Copyright (c) 2017-2018 Kieran Potts * MIT License */ 'use strict' var buildgem = require('buildgem') var copy = require('buildgem-copy') var md = require('buildgem-md') var sass = require('buildgem-sass') buildgem() .from('./src') .to('./build') .via([ copy({ sources: { dir: 'verbatim', match: ['**/.*', '**/*.*', 'CNAME'] }, messages: { success: 'Static files copied' } }), md({ sources: { markdown: { dir: 'markdown', match: ['**/*.md', '**/*.markdown'] }, templates: { dir: 'templates', ext: 'html' }, data: { app_name: 'BuildGem' } }, messages: { success: 'HTML files made' } }), sass({ sources: { dir: 'scss', match: ['*.scss'] }, output: { dir: 'static/css', ext: 'min.css', style: 'compressed', map: true }, messages: { success: 'CSS compiled' } }) ]) .rebuild() .listen()
(function() { 'use strict'; angular .module('assessoriaTorrellesApp') .controller('RegisterController', RegisterController); RegisterController.$inject = ['$translate', '$timeout', 'Auth', 'LoginService']; function RegisterController ($translate, $timeout, Auth, LoginService) { var vm = this; vm.doNotMatch = null; vm.error = null; vm.errorUserExists = null; vm.login = LoginService.open; vm.register = register; vm.registerAccount = {}; vm.success = null; $timeout(function (){angular.element('#login').focus();}); function register () { if (vm.registerAccount.password !== vm.confirmPassword) { vm.doNotMatch = 'ERROR'; } else { vm.registerAccount.langKey = $translate.use(); vm.doNotMatch = null; vm.error = null; vm.errorUserExists = null; vm.errorEmailExists = null; Auth.createAccount(vm.registerAccount).then(function () { vm.success = 'OK'; }).catch(function (response) { vm.success = null; if (response.status === 400 && response.data === 'login already in use') { vm.errorUserExists = 'ERROR'; } else if (response.status === 400 && response.data === 'e-mail address already in use') { vm.errorEmailExists = 'ERROR'; } else { vm.error = 'ERROR'; } }); } } } })();
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, hashHistory,IndexRoute} from 'react-router' import { Menuleftarea,Maincontent,RequestInfo } from './components/Main'; import { App,Home,Seach,Data,Zhibo,News,Video,Stack,About,Adright } from './components/Main'; import Ulaction from './components/Ulaction'; ReactDOM.render(<div><Menuleftarea /><Adright /></div>, document.getElementById('app')); ReactDOM.render(( <Router history={hashHistory} > <Route path="/" component={App} > <IndexRoute component={Home} /> <Route path="/seach" component={Seach}/> <Route path="/data" component={Data}/> <Route path="/zhibo" component={Zhibo}/> <Route path="/about" component={About}/> </Route> </Router> ),document.getElementById('meanue')); Ulaction.meanue(); $(function(){ $('#home').css({height:$(window).height()}) })
// Preloader $(window).load(function () { "use strict"; $("#status").fadeOut(); $("#preloader").delay(350).fadeOut("slow"); }); $(document).ready(function () { "use strict"; /*Audio*/ $('#audio-player').mediaelementplayer({ alwaysShowControls: true, features: ['playpause','volume'], audioVolume: 'horizontal', startVolume: 0.45, enableKeyboard: true, iPadUseNativeControls: true, iPhoneUseNativeControls: true, AndroidUseNativeControls: true }); /*XML Feed*/ $('.rssfeed').rssfeed('http://diarioup.com/feed/', { limit: 5, titletag: 'h1', date: false, linktarget: '_blank' }); // set home page text position var windowheight = jQuery(window).height(); if(windowheight < 500) { $('#countdown_dashboard').removeClass('cbox'); } // Toggle nav $(".nav-container").hover(function () { $("nav").stop().fadeIn('fast'); $('.nav-handle').addClass('active'); }, function () { $("nav").fadeOut('fast'); $('.nav-handle').removeClass('active'); }); $(".nav-container").on('click', '.nav-handle', function () { $("nav").fadeToggle('fast'); $(".nav-handle").toggleClass('active'); }); // Show/hide page content on click $(".main-column").each(function () { $(this).find("section:lt(1)").show(); }); $('nav a').click(function () { var index = $('nav a').index(this); $('.main-column').children().hide().eq(index).fadeIn(); }); // Show home panel $('.logo').click(function () { $('.contact-panel').hide(); $('.about-panel').hide(); $('.home-panel').fadeIn(); }); // Subscribe $('#subscribe-submit').click(function () { $('.subscribe-error-field').hide(); var emailReg = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/; var emailVal = $('#subscribe-email').val(); if (emailVal == "" || emailVal == "Email Address *") { $('.subscribe-error-field').html('<i class="fa fa-exclamation"></i>Your email address is required.').fadeIn(); return false; } else if (!emailReg.test(emailVal)) { $('.subscribe-error-field').html('<i class="fa fa-exclamation"></i>Invalid email address.').fadeIn(); return false; } var data_string = $('.subscribe-form').serialize(); $('.btn-subscribe').hide(); $('#subscribe-loading').fadeIn(); $('.subscribe-error-field').fadeOut(); $.ajax({ type: "POST", url: "subscribe.php", data: data_string, //success success: function (data) { $('.subscribe-empty').hide(); $('.subscribe-message').html('<i class="fa fa-check contact-success"></i><div>Thank you! You have been subscribed.<div>').fadeIn(); }, error: function (data) { $('.subscribe-empty').hide(); $('.subscribe-message').html('<i class="fa fa-exclamation contact-error"></i><div>Something went wrong, please try again later.<div>').fadeIn(); } }) //end ajax call return false; }); // Contact $('#contact-submit').click(function () { $('.contact-error-field').hide(); var nameVal = $('input[name=name]').val(); var emailReg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/igm; var emailVal = $('#contact-email').val(); var messageVal = $('textarea[name=message]').val(); //validate if (nameVal == '' || nameVal == 'Name *') { $('.contact-error-field').html('<i class="fa fa-exclamation"></i>Your name is required.').fadeIn(); return false; } if (emailVal == "" || emailVal == "Email Address *") { $('.contact-error-field').html('<i class="fa fa-exclamation"></i>Your email address is required.').fadeIn(); return false; } else if (!emailReg.test(emailVal)) { $('.contact-error-field').html('<i class="fa fa-exclamation"></i>Invalid email address.').fadeIn(); return false; } if (messageVal == '' || messageVal == 'Message *') { $('.contact-error-field').html('<i class="fa fa-exclamation"></i>Please provide a message.').fadeIn(); return false; } var data_string = $('.contact-form').serialize(); $('.btn-contact').hide(); $('#contact-loading').fadeIn(); $('.contact-error-field').fadeOut(); $.ajax({ type: "POST", url: "email.php", data: data_string, //success success: function (data) { $('.btn-contact-container').hide(); $('.contact-message').html('<i class="fa fa-check contact-success"></i><div>Your message has been sent.</div>').fadeIn(); }, error: function (data) { $('.btn-contact-container').hide(); $('.contact-message').html('<i class="fa fa-exclamation contact-error"></i><div>Something went wrong, please try again later.</div>').fadeIn(); } }) //end ajax call return false; }); });
// Dependencies var vows = require('vows'), assert = require('assert'), Path = require('path'); vows.describe('Tests config.util.getConfigSources').addBatch({ 'tests with NODE_CONFIG env set, and --NODE_CONFIG command line flag': { topic: function () { // Change the configuration directory for testing process.env.NODE_CONFIG_DIR = __dirname + '/5-config'; delete process.env.NODE_ENV; process.env.NODE_CONFIG = '{}'; delete process.env.NODE_APP_INSTANCE; process.env.NODE_CONFIG_STRICT_MODE=0; process.argv = ["node","path/to/some.js","--NODE_CONFIG='{}'"]; var config = requireUncached('../lib/config'); return config.util.getConfigSources(); }, 'Two files plus NODE_CONFIG in env and as command line args should result in four entries': function(topic) { assert.equal(topic.length,4); }, "The environment variable and command line args are the last two overrides": function (topic) { assert.equal(topic[2].name,'$NODE_CONFIG'); assert.equal(topic[3].name,"--NODE_CONFIG argument"); }, }, 'tests without NODE_ENV set': { topic: function () { // Change the configuration directory for testing process.env.NODE_CONFIG_DIR = __dirname + '/5-config'; delete process.env.NODE_ENV; delete process.env.NODE_CONFIG; delete process.env.NODE_APP_INSTANCE; process.env.NODE_CONFIG_STRICT_MODE=0; process.argv = []; var config = requireUncached('../lib/config'); return config.util.getConfigSources(); }, 'Two files should result in two entries': function(topic) { assert.equal(topic.length,2); }, "The keys for each object are 'name', 'original', and 'parsed'": function(topic) { assert.deepEqual(Object.keys(topic[0]).sort(), ['name','original','parsed']); }, }, 'tests with NODE_ENV set': { topic: function () { // Change the configuration directory for testing process.env.NODE_CONFIG_DIR = __dirname + '/5-config'; process.env.NODE_ENV='test'; delete process.env.NODE_CONFIG; delete process.env.NODE_APP_INSTANCE; process.argv = []; var config = requireUncached('../lib/config'); return config.util.getConfigSources(); }, 'Two files should result in two entries': function(topic) { assert.equal(topic.length,2); }, "The keys for each object are 'name', 'original', and 'parsed'": function(topic) { assert.deepEqual(Object.keys(topic[0]).sort(), ['name','original','parsed']); }, }, 'Files which return empty objects still end up in getConfigSources()': { topic: function () { // Change the configuration directory for testing process.env.NODE_CONFIG_DIR = __dirname + '/5-config'; process.env.NODE_ENV='empty'; delete process.env.NODE_CONFIG; delete process.env.NODE_APP_INSTANCE; process.argv = []; var config = requireUncached('../lib/config'); return config.util.getConfigSources(); }, 'Three files should result in 3 entries': function(topic) { assert.equal(topic.length,3); }, 'Second file is named empty': function (topic) { assert.equal(Path.basename(topic[1].name), 'empty.json'); }, } }) .export(module); // // Because require'ing config creates and caches a global singleton, // We have to invalidate the cache to build new object based on the environment variables above function requireUncached(module){ delete require.cache[require.resolve(module)]; return require(module); }
import { ADD_PROJECT, FETCH_PROJECTS, EDIT_PROJECT, DELETE_PROJECT } from '../actions'; var list_start; if(window.localStorage.getItem('projectList')){ list_start=JSON.parse(window.localStorage.getItem('projectList')).projects; list_start.forEach((item)=>{ item.date_start=new Date(item.date_start); item.date_end=new Date(item.date_end); }); }else{ list_start = [ { name: 'rotunda', location: 'Warszawa', date_start: new Date(1999,12,12), date_end: new Date(2020,5,8), procedures: [ { name: 'Procedura budowy fundamentów', toDoList: [ {text: 'Wykop wykonany na głębokość minimum 1m',status: true}, {text: 'Wykop wykonany na szerokość od 50 cm do 100 cm',status: false}, {text: 'Brak wód gruntowych',status: false}, ], done:1 }, { name: 'Procedura budowy dachu', toDoList: [ {text: 'Konstrukcja zgodna z projektem',status: false}, {text: 'Belki zabezpieczone przed wilgocią',status: false}, {text: 'Nachylenie dachu przynajmniej 10%',status: false}, ], done: 0 } ], failure: [ {name:"przykladowa usterka",img:null,status:true,desc: "Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio"}, {name:"przykladowa usterka 2",img:null,status:false,desc:"Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio"}] }, { name: 'Pałac kultury', location: 'Warszawa', date_start: new Date(1950,12,2), date_end: new Date(1970,10,5), procedures: [ { name: 'Procedura budowy fundamentów', toDoList: [ {text: 'Wykop wykonany na głębokość minimum 1m',status: true}, {text: 'Wykop wykonany na szerokość od 50 cm do 100 cm',status: false}, {text: 'Brak wód gruntowych',status: false}, ], done:1 },], failure: [] }, { name: 'osiedle "Nowe" Gdynia', location: 'Gdynia', date_start: new Date(2018,1,17), date_end: new Date(2018,11,17), procedures: [], failure: [] }, { name: 'dom Kowalskich', location: 'Kisielice', date_start: new Date(2019,9,11), date_end: new Date(2024,12,11), procedures: [], failure: [] } ]; } export default function(state = list_start,action){ switch(action.type){ case ADD_PROJECT: console.log("adding a project"); return [...state, action.payload]; case EDIT_PROJECT: console.log("editing a project"); var newState = state; newState[action.payload.id] = action.payload.project; return newState; case DELETE_PROJECT: console.log("deleting a project"); var newState = state; newState.splice(action.payload,1); return newState; case FETCH_PROJECTS: return state; default: return state; } }
var Flowy = require('../src/flowy.js');
/* TWITTER BUTTON */ !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');
'use strict'; /** * Created by Drako on 07.04.2014. * Startpunkt der Angular Webapp */ var app = angular.module('RTA',['sails.io','ui.router','d3','ngDragDrop','nvd3ChartDirectives','ui.bootstrap']); //Definitionen der verschiedene Ui States und Auflösung evtl fehlender Daten app.config(function($stateProvider,$locationProvider){ $locationProvider.html5Mode(true); $stateProvider.state("home",{ url:'/', controller:'MainController', templateUrl:'/partials/home.html' }).state("dashboard",{ url:'/dashboard', templateUrl:'/partials/dashboard.html', controller:'DashboardController' }).state('editor',{ url:'/editor', templateUrl:'/partials/editor.html', resolve:{ nodeSystems: function($sailsSocket){ return $sailsSocket.get('/api/nodesystem/'); } }, controller: 'NodeSystemController' }).state('editor.nodesystem',{ url:'/:id', templateUrl:'/partials/editor.nodesystem.html', controller:'EditorController', resolve:{ nodeSystem:function($sailsSocket,$stateParams){ return $sailsSocket.get('/api/nodesystem/'+$stateParams.id) }, eventTypes: function($sailsSocket){ return $sailsSocket.get('/api/type'); } } }).state('types',{ url:'/types', templateUrl:'/partials/types.html', controller:'TypeController', resolve:{ types:function($sailsSocket){ return $sailsSocket.get('/api/type'); } } }).state('types.params',{ url:'/:type', templateUrl:'/partials/types.params.html', controller:'TypeController' }); });
export default function (Vue) { const version = Number(Vue.version.split('.')[0]) if (version >= 2) { const usesInit = Vue.config._lifecycleHooks.indexOf('init') > -1 Vue.mixin(usesInit ? { init: vuexInit } : { beforeCreate: vuexInit }) } else { // override init and inject vuex init procedure // for 1.x backwards compatibility. const _init = Vue.prototype._init Vue.prototype._init = function (options = {}) { options.init = options.init ? [vuexInit].concat(options.init) : vuexInit _init.call(this, options) } } /** * Vuex init hook, injected into each instances init hooks list. */ function vuexInit () { const options = this.$options // store injection if (options.store) { this.$store = options.store } else if (options.parent && options.parent.$store) { this.$store = options.parent.$store } } }
$(document).ready(function(){ /* This code is executed after the DOM has been completely loaded */ $('.nav a,.footer a.up').click(function(e){ // If a link has been clicked, scroll the page to the link's hash target: $.scrollTo( this.hash || 0, 1500); e.preventDefault(); }); });
exports.names = ['!lastseen', '!seen']; exports.hidden = false; exports.enabled = true; exports.matchStart = true; exports.handler = function (data) { var params = _.rest(data.message.split(' '), 1); if (params.length < 1) { bot.sendChat('/me usage: !lastseen username'); return; } username = params.join(' ').trim() usernameFormatted = S(username).chompLeft('@').s; user = _.findWhere(bot.getUsers(), {username: usernameFormatted}); if (user) { bot.sendChat(usernameFormatted + ' is in the room!'); } else { User.find({where: {username: usernameFormatted}}).on('success', function (row) { if (row === null) { bot.sendChat(usernameFormatted + ' was not found.'); } else { bot.sendChat(row.username + ' was last seen ' + timeSince(row.last_seen)); } }); } };
var opts = require("optimist").argv var MessageStream = require("message-stream") var net = require("net") var EventEmitter = require("events").EventEmitter var myIp = require("my-local-ip")() || "localhost" var serverPort = opts.server var seedPort = opts.port var seedHost = opts.host || myIp function Chat(id, name) { var chat = new EventEmitter() chat.setMaxListeners(Infinity) var lastMessage = 0 var history = chat.history = [] var clock = chat.clock = {} chat.send = function send(text) { chat.emit("message", { text: text, id: id, name: name, ts: Date.now() }) } chat.createStream = function () { var stream = MessageStream(function (message) { if (typeof message.since === "number") { history.forEach(function (e) { if (e.ts > message.since) stream.queue(e) }) } else if (message.ts > lastMessage) { chat.emit("message", message, stream) } }) chat.on("message", function (message, source) { if (source !== stream) stream.queue(message) }) stream.queue({ since: lastMessage, id: id }) return stream } chat.on("message", function (message) { lastMessage = message.ts clock[message.id] = message.ts if (message.text) { history.push(message) console.log(message.name, ">", message.text) } }) return chat } var chat = Chat(myIp + ":" + serverPort, opts.name || "Anon") process.stdin.on("data", function (buf) { chat.send(buf.toString()) }) net.createServer(function (stream) { stream.pipe(chat.createStream()).pipe(stream) }).listen(serverPort, myIp) console.log("server listening on " + myIp + ":" + serverPort) function randomPeer(clock) { var peers = Object.keys(clock).map(function (id) { var parts = id.split(":") return { host: parts[0], port: parts[1] } }) return peers[~~(Math.random() * peers.length)] } ;(function connect() { var peer = randomPeer(chat.clock) if (!peer || (peer.host === myIp && +peer.port === serverPort)) { peer = { port: seedPort, host: seedHost } } console.log("client trying to connect to " + peer.host + ":" + peer.port) var client = net.connect(peer.port, peer.host, function () { client.pipe(chat.createStream()).pipe(client) setTimeout(client.end.bind(client), 5000) }) client.on("error", reconnect) client.on("end", reconnect) function reconnect() { client.removeAllListeners() setTimeout(connect, 1000) } })()
var strings = { menu: { course: 'Khóa học', blog: 'Blog' } } export default strings;
const versions = { 0: ({ groupId, memberId }) => { const request = require('./v0/request') const response = require('./v0/response') return { request: request({ groupId, memberId }), response, } }, 1: ({ groupId, memberId }) => { const request = require('./v1/request') const response = require('./v1/response') return { request: request({ groupId, memberId }), response, } }, 2: ({ groupId, memberId }) => { const request = require('./v2/request') const response = require('./v2/response') return { request: request({ groupId, memberId }), response, } }, 3: ({ groupId, memberId, groupInstanceId }) => { const request = require('./v3/request') const response = require('./v3/response') return { request: request({ groupId, members: [{ memberId, groupInstanceId }] }), response, } }, } module.exports = { versions: Object.keys(versions), protocol: ({ version }) => versions[version], }
/* eslint-env node */ 'use strict'; module.exports = { name: '@cardstack/image', isDevelopingAddon() { return process.env.CARDSTACK_DEV; } };
'use strict' const debug = require('debug')('stuco:web:middleware:badgeParam') const Badge = require('../../../../../models/Badge') debug('load parser') const badgeParam = (req, res, next, badgeid) => { debug('parse badgeid parameter', badgeid) if (isNaN(badgeid)) { debug('badgeid is not a number') return res.error('Badge Not Found', 404) } Badge.findOne({ bid: Math.trunc(badgeid) }).then((dbBadge) => { if (dbBadge == null) { debug('return badge failed (not found) "%s"', badgeid) return res.error('Badge Not Found', 404) } debug('return badge succeeded "%s"', badgeid) // Possibly print out badge object req.targetBadge = dbBadge return next() }).catch((dbError) => { debug('return badge failed', badgeid, dbError) return res.error('Badge Not Found', 404) }) } module.exports = badgeParam
function map(key,value) { Meguro.emit(key,key); }
//import System; import System.IO; //import System.Collections; //http://forum.unity3d.com/threads/34015-Newbie-guide-to-Unity-Javascript-%28long%29 public var NumberCaught : int = 0; var Scoreboard : GameObject; var Spawner : Transform; //Legacy var leftSpawner : Transform; var rightSpawner : Transform; //Level Properties var gameLength : float = 15.0; // default is 15 var PlannedButterflys : int = 36 ; // Make this a multiple of 6! or nine var ButterflysRemaining : int; var ButterflyPrefab : GameObject; // get more of these? var Net : GameObject; //make a class for game and level properties, for now, do this var difficulty : int; var ButterflySpeed : float = 1; var ButterFlyFrequency : float = 5;//in seconds var ButterflyNetSide : int ;// 0 is right, 1 is left var AffectedHand : int; var HandBeingUsed : int; var BeeLevel : int = 0; //0 is no bees, 1 is..... //For GUI var selStrings : String[] = ["right", "left"]; var GameRunning : boolean = true; // actually use CancelInvoke(); //all positions? Nine or Six? //This should be an ARRAYY!!! var leftTop : Transform; var leftMid : Transform; var leftBottom : Transform; //no middle (yet) var rightTop : Transform; var rightMid : Transform; var rightBottom : Transform; var hideGUI : boolean; var SideToSpawn : int; //0 is right, 1 is Left? var Countdown : GameObject; var countdownPosition : Transform; var CapturedData : int[] = new int[7];// //WHAT THIS GAME NEEDS IS MORE COWBELL //A to do list by widget /* Choose left or right side for butterfly net choose duration of game choose game mode choose game difficulty game length, default = 15 minutes 1. get all ~9 or six spots 2. Keep track of quadrants where butter flys are caught */ function Start () { //find the scoreboard?? ButterflysRemaining = PlannedButterflys; Spawner = GameObject.Find("Butterfly spawner _ t").GetComponent(Transform);//remove me hideGUI = false; if(Net == null){ Net = GameObject.Find("NetCollider"); }//InvokeRepeating("SpawnButterfly", 3.0, 5.0); } static function SaveTextFile ( fileName : String, fileContent : String ) { var sw : StreamWriter = new StreamWriter ( fileName ); sw.Write ( fileContent ); sw.Close (); print ( "Saved " + fileName ); } function GameStart (){ hideGUI = true; SetNetPosition(ButterflyNetSide); Instantiate(Countdown, countdownPosition.position, countdownPosition.rotation); InvokeRepeating("ChooseFlower", 3.0, 5.0); Net.SendMessage("GameStart"); //level? //Start timer } function LevelStart (){ //what goes here? } function SetNetPosition(Side : int){ //move the net to left or right // 0 is right, 1 is left Net.SendMessage("SetNetPosition", Side); } function GameEnd (){ CancelInvoke();//is this enough? //display score for( var i=0 ; i<CapturedData.Length; i++){ print(CapturedData[i] + " Captures at "+ i + " position " ); } //DETROY ALL THE BUTTERFLYS TRIGUN //display score? //Say great job //level up? //Do next level } function Update () { Scoreboard.guiText.text = NumberCaught.ToString(); if (ButterflysRemaining <= 0){ GameEnd(); } if (Input.GetKeyDown(KeyCode.P)){ //Session data, Date, time, CreateAFile(); } } //Happen at the end of a seesion, could make this happen DURING a session incase of crashes function CreateAFile(){ var TodaysDate = System.DateTime.UtcNow.ToString(); var sw = new StreamWriter("Data"+ TodaysDate + ".txt"); sw.WriteLine("Data for " + TodaysDate); //Session Data //which side is the butterfly net //which side is the affected hand //which side is the patient using to move. // level (tbd); difficulty : int sw.WriteLine(""); //game data //has been caught or not, Time to catch since appeared on screeen, Positon of capture. //non variables: length of game sw.WriteLine(this.name); sw.Write(""); sw.WriteLine(Time.time); sw.WriteLine(" date and time "); // sw.Write( System.DateTime.UtcNow.ToString()); sw.Close(); //this inserts a tab. //+ "\t" + } function PauseButterflys(){ //print("Butterflys paused"); //cancel the butterfly invoke } function UnPauseButterflys(){ } function ChooseFlower(){ var PositionNumber : int; var randomNumber : int = UnityEngine.Random.Range(1,6); //Fing a /* add a value to all positions, if value runs out skip to next position in the line. Sorta Random. */ PositionNumber = randomNumber; ButterflysRemaining--; switch(PositionNumber) { //first 3 left, last three right) case 1: SpawnButterfly(leftSpawner, leftTop, PositionNumber ); break; case 2: SpawnButterfly(leftSpawner, leftMid, PositionNumber ); break; case 3: SpawnButterfly(leftSpawner, leftBottom, PositionNumber ); break; case 4: SpawnButterfly(rightSpawner, rightTop, PositionNumber ); break; case 5: SpawnButterfly(rightSpawner, rightMid, PositionNumber ); break; case 6: SpawnButterfly(rightSpawner, rightBottom, PositionNumber ); break; default: //choose one at random break; } } //From ButterflyBehavior function ButterflyCaught(caughtPosition : int){ NumberCaught++; CapturedData[caughtPosition]++; //Keep trak of positions here. } //OVERLOADING TIME function SpawnButterfly(){ if(ButterflyPrefab != null && GameRunning){ var ButterflyClone = Instantiate(ButterflyPrefab, Spawner.position, Quaternion.identity); //Give the butterfly some preset settings later. } else{ print("prefab is null!"); } } function SpawnButterfly(SpawnPoint : Transform, targetFlower : Transform, PositionNumber : int){ if(ButterflyPrefab != null && GameRunning){ var ButterflyClone = Instantiate(ButterflyPrefab, SpawnPoint.position, Quaternion.identity); ButterflyClone.GetComponent.< ButterflyBehavior >().Target = targetFlower; ButterflyClone.GetComponent.< ButterflyBehavior >().speedAdjust = ButterflySpeed; //Give the butterfly some preset settings later. } else{ print("prefab is null!"); } } //var AffectedHand : String[] = ["right", "left"]; //var HandBeingUsed : String[] = ["right", "left"]; function OnGUI(){ //display options if(!hideGUI){ GUILayout.Label("ButterflyNetSide"); ButterflyNetSide = GUILayout.SelectionGrid(ButterflyNetSide,selStrings,2,"toggle"); GUILayout.Label("AffectedHand"); AffectedHand = GUILayout.SelectionGrid(ButterflyNetSide,selStrings,2,"toggle"); GUILayout.Label("HandBeingUsed"); HandBeingUsed = GUILayout.SelectionGrid(ButterflyNetSide,selStrings,2,"toggle"); if(GUILayout.Button ("Start game")) { GameStart(); } } }
/* */ "format cjs"; /*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.1-master-491d139 */ (function( window, angular, undefined ){ "use strict"; (function() { 'use strict'; MdFabController['$inject'] = ["$scope", "$element", "$animate", "$mdUtil", "$mdConstant", "$timeout"]; angular.module('material.components.fabShared', ['material.core']) .controller('MdFabController', MdFabController); function MdFabController($scope, $element, $animate, $mdUtil, $mdConstant, $timeout) { var vm = this; var initialAnimationAttempts = 0; // NOTE: We use async eval(s) below to avoid conflicts with any existing digest loops vm.open = function() { $scope.$evalAsync("vm.isOpen = true"); }; vm.close = function() { // Async eval to avoid conflicts with existing digest loops $scope.$evalAsync("vm.isOpen = false"); // Focus the trigger when the element closes so users can still tab to the next item $element.find('md-fab-trigger')[0].focus(); }; // Toggle the open/close state when the trigger is clicked vm.toggle = function() { $scope.$evalAsync("vm.isOpen = !vm.isOpen"); }; /* * Angular Lifecycle hook for newer Angular versions. * Bindings are not guaranteed to have been assigned in the controller, but they are in the $onInit hook. */ vm.$onInit = function() { setupDefaults(); setupListeners(); setupWatchers(); fireInitialAnimations(); }; // For Angular 1.4 and older, where there are no lifecycle hooks but bindings are pre-assigned, // manually call the $onInit hook. if (angular.version.major === 1 && angular.version.minor <= 4) { this.$onInit(); } function setupDefaults() { // Set the default direction to 'down' if none is specified vm.direction = vm.direction || 'down'; // Set the default to be closed vm.isOpen = vm.isOpen || false; // Start the keyboard interaction at the first action resetActionIndex(); // Add an animations waiting class so we know not to run $element.addClass('md-animations-waiting'); } function setupListeners() { var eventTypes = [ 'click', 'focusin', 'focusout' ]; // Add our listeners angular.forEach(eventTypes, function(eventType) { $element.on(eventType, parseEvents); }); // Remove our listeners when destroyed $scope.$on('$destroy', function() { angular.forEach(eventTypes, function(eventType) { $element.off(eventType, parseEvents); }); // remove any attached keyboard handlers in case element is removed while // speed dial is open disableKeyboard(); }); } var closeTimeout; function parseEvents(event) { // If the event is a click, just handle it if (event.type == 'click') { handleItemClick(event); } // If we focusout, set a timeout to close the element if (event.type == 'focusout' && !closeTimeout) { closeTimeout = $timeout(function() { vm.close(); }, 100, false); } // If we see a focusin and there is a timeout about to run, cancel it so we stay open if (event.type == 'focusin' && closeTimeout) { $timeout.cancel(closeTimeout); closeTimeout = null; } } function resetActionIndex() { vm.currentActionIndex = -1; } function setupWatchers() { // Watch for changes to the direction and update classes/attributes $scope.$watch('vm.direction', function(newDir, oldDir) { // Add the appropriate classes so we can target the direction in the CSS $animate.removeClass($element, 'md-' + oldDir); $animate.addClass($element, 'md-' + newDir); // Reset the action index since it may have changed resetActionIndex(); }); var trigger, actions; // Watch for changes to md-open $scope.$watch('vm.isOpen', function(isOpen) { // Reset the action index since it may have changed resetActionIndex(); // We can't get the trigger/actions outside of the watch because the component hasn't been // linked yet, so we wait until the first watch fires to cache them. if (!trigger || !actions) { trigger = getTriggerElement(); actions = getActionsElement(); } if (isOpen) { enableKeyboard(); } else { disableKeyboard(); } var toAdd = isOpen ? 'md-is-open' : ''; var toRemove = isOpen ? '' : 'md-is-open'; // Set the proper ARIA attributes trigger.attr('aria-haspopup', true); trigger.attr('aria-expanded', isOpen); actions.attr('aria-hidden', !isOpen); // Animate the CSS classes $animate.setClass($element, toAdd, toRemove); }); } function fireInitialAnimations() { // If the element is actually visible on the screen if ($element[0].scrollHeight > 0) { // Fire our animation $animate.addClass($element, '_md-animations-ready').then(function() { // Remove the waiting class $element.removeClass('md-animations-waiting'); }); } // Otherwise, try for up to 1 second before giving up else if (initialAnimationAttempts < 10) { $timeout(fireInitialAnimations, 100); // Increment our counter initialAnimationAttempts = initialAnimationAttempts + 1; } } function enableKeyboard() { $element.on('keydown', keyPressed); // On the next tick, setup a check for outside clicks; we do this on the next tick to avoid // clicks/touches that result in the isOpen attribute changing (e.g. a bound radio button) $mdUtil.nextTick(function() { angular.element(document).on('click touchend', checkForOutsideClick); }); // TODO: On desktop, we should be able to reset the indexes so you cannot tab through, but // this breaks accessibility, especially on mobile, since you have no arrow keys to press //resetActionTabIndexes(); } function disableKeyboard() { $element.off('keydown', keyPressed); angular.element(document).off('click touchend', checkForOutsideClick); } function checkForOutsideClick(event) { if (event.target) { var closestTrigger = $mdUtil.getClosest(event.target, 'md-fab-trigger'); var closestActions = $mdUtil.getClosest(event.target, 'md-fab-actions'); if (!closestTrigger && !closestActions) { vm.close(); } } } function keyPressed(event) { switch (event.which) { case $mdConstant.KEY_CODE.ESCAPE: vm.close(); event.preventDefault(); return false; case $mdConstant.KEY_CODE.LEFT_ARROW: doKeyLeft(event); return false; case $mdConstant.KEY_CODE.UP_ARROW: doKeyUp(event); return false; case $mdConstant.KEY_CODE.RIGHT_ARROW: doKeyRight(event); return false; case $mdConstant.KEY_CODE.DOWN_ARROW: doKeyDown(event); return false; } } function doActionPrev(event) { focusAction(event, -1); } function doActionNext(event) { focusAction(event, 1); } function focusAction(event, direction) { var actions = resetActionTabIndexes(); // Increment/decrement the counter with restrictions vm.currentActionIndex = vm.currentActionIndex + direction; vm.currentActionIndex = Math.min(actions.length - 1, vm.currentActionIndex); vm.currentActionIndex = Math.max(0, vm.currentActionIndex); // Focus the element var focusElement = angular.element(actions[vm.currentActionIndex]).children()[0]; angular.element(focusElement).attr('tabindex', 0); focusElement.focus(); // Make sure the event doesn't bubble and cause something else event.preventDefault(); event.stopImmediatePropagation(); } function resetActionTabIndexes() { // Grab all of the actions var actions = getActionsElement()[0].querySelectorAll('.md-fab-action-item'); // Disable all other actions for tabbing angular.forEach(actions, function(action) { angular.element(angular.element(action).children()[0]).attr('tabindex', -1); }); return actions; } function doKeyLeft(event) { if (vm.direction === 'left') { doActionNext(event); } else { doActionPrev(event); } } function doKeyUp(event) { if (vm.direction === 'down') { doActionPrev(event); } else { doActionNext(event); } } function doKeyRight(event) { if (vm.direction === 'left') { doActionPrev(event); } else { doActionNext(event); } } function doKeyDown(event) { if (vm.direction === 'up') { doActionPrev(event); } else { doActionNext(event); } } function isTrigger(element) { return $mdUtil.getClosest(element, 'md-fab-trigger'); } function isAction(element) { return $mdUtil.getClosest(element, 'md-fab-actions'); } function handleItemClick(event) { if (isTrigger(event.target)) { vm.toggle(); } if (isAction(event.target)) { vm.close(); } } function getTriggerElement() { return $element.find('md-fab-trigger'); } function getActionsElement() { return $element.find('md-fab-actions'); } } })(); (function() { 'use strict'; /** * The duration of the CSS animation in milliseconds. * * @type {number} */ MdFabSpeedDialFlingAnimation['$inject'] = ["$timeout"]; MdFabSpeedDialScaleAnimation['$inject'] = ["$timeout"]; var cssAnimationDuration = 300; /** * @ngdoc module * @name material.components.fabSpeedDial */ angular // Declare our module .module('material.components.fabSpeedDial', [ 'material.core', 'material.components.fabShared', 'material.components.fabActions' ]) // Register our directive .directive('mdFabSpeedDial', MdFabSpeedDialDirective) // Register our custom animations .animation('.md-fling', MdFabSpeedDialFlingAnimation) .animation('.md-scale', MdFabSpeedDialScaleAnimation) // Register a service for each animation so that we can easily inject them into unit tests .service('mdFabSpeedDialFlingAnimation', MdFabSpeedDialFlingAnimation) .service('mdFabSpeedDialScaleAnimation', MdFabSpeedDialScaleAnimation); /** * @ngdoc directive * @name mdFabSpeedDial * @module material.components.fabSpeedDial * * @restrict E * * @description * The `<md-fab-speed-dial>` directive is used to present a series of popup elements (usually * `<md-button>`s) for quick access to common actions. * * There are currently two animations available by applying one of the following classes to * the component: * * - `md-fling` - The speed dial items appear from underneath the trigger and move into their * appropriate positions. * - `md-scale` - The speed dial items appear in their proper places by scaling from 0% to 100%. * * You may also easily position the trigger by applying one one of the following classes to the * `<md-fab-speed-dial>` element: * - `md-fab-top-left` * - `md-fab-top-right` * - `md-fab-bottom-left` * - `md-fab-bottom-right` * * These CSS classes use `position: absolute`, so you need to ensure that the container element * also uses `position: absolute` or `position: relative` in order for them to work. * * Additionally, you may use the standard `ng-mouseenter` and `ng-mouseleave` directives to * open or close the speed dial. However, if you wish to allow users to hover over the empty * space where the actions will appear, you must also add the `md-hover-full` class to the speed * dial element. Without this, the hover effect will only occur on top of the trigger. * * See the demos for more information. * * ## Troubleshooting * * If your speed dial shows the closing animation upon launch, you may need to use `ng-cloak` on * the parent container to ensure that it is only visible once ready. We have plans to remove this * necessity in the future. * * @usage * <hljs lang="html"> * <md-fab-speed-dial md-direction="up" class="md-fling"> * <md-fab-trigger> * <md-button aria-label="Add..."><md-icon md-svg-src="/img/icons/plus.svg"></md-icon></md-button> * </md-fab-trigger> * * <md-fab-actions> * <md-button aria-label="Add User"> * <md-icon md-svg-src="/img/icons/user.svg"></md-icon> * </md-button> * * <md-button aria-label="Add Group"> * <md-icon md-svg-src="/img/icons/group.svg"></md-icon> * </md-button> * </md-fab-actions> * </md-fab-speed-dial> * </hljs> * * @param {string} md-direction From which direction you would like the speed dial to appear * relative to the trigger element. * @param {expression=} md-open Programmatically control whether or not the speed-dial is visible. */ function MdFabSpeedDialDirective() { return { restrict: 'E', scope: { direction: '@?mdDirection', isOpen: '=?mdOpen' }, bindToController: true, controller: 'MdFabController', controllerAs: 'vm', link: FabSpeedDialLink }; function FabSpeedDialLink(scope, element) { // Prepend an element to hold our CSS variables so we can use them in the animations below element.prepend('<div class="_md-css-variables"></div>'); } } function MdFabSpeedDialFlingAnimation($timeout) { function delayDone(done) { $timeout(done, cssAnimationDuration, false); } function runAnimation(element) { // Don't run if we are still waiting and we are not ready if (element.hasClass('md-animations-waiting') && !element.hasClass('_md-animations-ready')) { return; } var el = element[0]; var ctrl = element.controller('mdFabSpeedDial'); var items = el.querySelectorAll('.md-fab-action-item'); // Grab our trigger element var triggerElement = el.querySelector('md-fab-trigger'); // Grab our element which stores CSS variables var variablesElement = el.querySelector('._md-css-variables'); // Setup JS variables based on our CSS variables var startZIndex = parseInt(window.getComputedStyle(variablesElement).zIndex); // Always reset the items to their natural position/state angular.forEach(items, function(item, index) { var styles = item.style; styles.transform = styles.webkitTransform = ''; styles.transitionDelay = ''; styles.opacity = 1; // Make the items closest to the trigger have the highest z-index styles.zIndex = (items.length - index) + startZIndex; }); // Set the trigger to be above all of the actions so they disappear behind it. triggerElement.style.zIndex = startZIndex + items.length + 1; // If the control is closed, hide the items behind the trigger if (!ctrl.isOpen) { angular.forEach(items, function(item, index) { var newPosition, axis; var styles = item.style; // Make sure to account for differences in the dimensions of the trigger verses the items // so that we can properly center everything; this helps hide the item's shadows behind // the trigger. var triggerItemHeightOffset = (triggerElement.clientHeight - item.clientHeight) / 2; var triggerItemWidthOffset = (triggerElement.clientWidth - item.clientWidth) / 2; switch (ctrl.direction) { case 'up': newPosition = (item.scrollHeight * (index + 1) + triggerItemHeightOffset); axis = 'Y'; break; case 'down': newPosition = -(item.scrollHeight * (index + 1) + triggerItemHeightOffset); axis = 'Y'; break; case 'left': newPosition = (item.scrollWidth * (index + 1) + triggerItemWidthOffset); axis = 'X'; break; case 'right': newPosition = -(item.scrollWidth * (index + 1) + triggerItemWidthOffset); axis = 'X'; break; } var newTranslate = 'translate' + axis + '(' + newPosition + 'px)'; styles.transform = styles.webkitTransform = newTranslate; }); } } return { addClass: function(element, className, done) { if (element.hasClass('md-fling')) { runAnimation(element); delayDone(done); } else { done(); } }, removeClass: function(element, className, done) { runAnimation(element); delayDone(done); } }; } function MdFabSpeedDialScaleAnimation($timeout) { function delayDone(done) { $timeout(done, cssAnimationDuration, false); } var delay = 65; function runAnimation(element) { var el = element[0]; var ctrl = element.controller('mdFabSpeedDial'); var items = el.querySelectorAll('.md-fab-action-item'); // Grab our element which stores CSS variables var variablesElement = el.querySelector('._md-css-variables'); // Setup JS variables based on our CSS variables var startZIndex = parseInt(window.getComputedStyle(variablesElement).zIndex); // Always reset the items to their natural position/state angular.forEach(items, function(item, index) { var styles = item.style, offsetDelay = index * delay; styles.opacity = ctrl.isOpen ? 1 : 0; styles.transform = styles.webkitTransform = ctrl.isOpen ? 'scale(1)' : 'scale(0)'; styles.transitionDelay = (ctrl.isOpen ? offsetDelay : (items.length - offsetDelay)) + 'ms'; // Make the items closest to the trigger have the highest z-index styles.zIndex = (items.length - index) + startZIndex; }); } return { addClass: function(element, className, done) { runAnimation(element); delayDone(done); }, removeClass: function(element, className, done) { runAnimation(element); delayDone(done); } }; } })(); })(window, window.angular);
/** * * Controller * */ import React from 'react'; import PropTypes from 'prop-types'; import { get, map, some } from 'lodash'; import cn from 'classnames'; import { FormattedMessage } from 'react-intl'; import InputCheckbox from '../InputCheckboxPlugin'; import styles from './styles.scss'; class Controller extends React.Component { state = { inputSelected: '', checked: false }; setNewInputSelected = (name) => { this.setState({ inputSelected: name, checked: false }); } handleChange = () => { this.setState({ checked: !this.state.checked }); this.context.selectAllActions(`${this.props.inputNamePath}.controllers.${this.props.name}`, !this.isAllActionsSelected()); } isAllActionsSelected = () => !some(this.props.actions, ['enabled', false]); render() { return ( <div className={styles.controller}> <div className={styles.controllerHeader}> <div>{this.props.name}</div> <div className={styles.separator}></div> <div> <div className={cn(styles.inputCheckbox)}> <div className="form-check"> <label className={cn('form-check-label', styles.label, this.state.checked ? styles.checked : '')} htmlFor={this.props.name}> <input className="form-check-input" checked={this.state.checked} id={this.props.name} name={this.props.name} onChange={this.handleChange} type="checkbox" /> <FormattedMessage id="users-permissions.Controller.selectAll" /> </label> </div> </div> </div> </div> <div className="row"> {map(Object.keys(this.props.actions).sort(), (actionKey) => ( <InputCheckbox inputSelected={this.state.inputSelected} isOpen={this.props.isOpen} key={actionKey} label={actionKey} name={`${this.props.inputNamePath}.controllers.${this.props.name}.${actionKey}.enabled`} setNewInputSelected={this.setNewInputSelected} value={get(this.props.actions[actionKey], 'enabled')} /> ))} </div> </div> ); } } Controller.contextTypes = { selectAllActions: PropTypes.func.isRequired, }; Controller.defaultProps = { actions: {}, inputNamePath: 'permissions.application', name: '', }; Controller.propTypes = { actions: PropTypes.object, inputNamePath: PropTypes.string, isOpen: PropTypes.bool.isRequired, name: PropTypes.string, }; export default Controller;
$(document).ready(function () { $(".before .unselected").click(function () { cssmod($(this)); beforeLevel = (parseInt(this.textContent)); if (afterLevel != 0) { calculateValor(); }; }); $(".after .unselected").click(function () { cssmod($(this)); afterLevel = (parseInt(this.textContent)); if (beforeLevel != 0) { calculateValor(); }; }); $(".atype .unselected").click(function () { cssmod($(this)); armortype = (this.textContent.trim()); if (beforeLevel != 0) { calculateValor(); }; }); }); // Defaults var beforeLevel = 0; var afterLevel = 0; var armortype = "Shield / Offhand / Ring / Cloak / Bracer / Neck" var atype = new Map(); atype.set("Shield / Offhand / Ring / Cloak / Bracer / Neck", 250); atype.set("Trinket / Belt / Shoulder / Gloves / Boots", 400); atype.set("Helm / Legs / Chest", 475); atype.set("1h Agi/Str Weapon", 500); atype.set("1h Int Weapon", 750); atype.set("2h Weapon", 1000); var levelsPossible = [ 210, 213, 216, 220, 223, 226, 229, 233, 236, 239, 242, 246 ]; function cssmod(element) { element.parent().children().removeClass('selected'); element.addClass('selected'); }; function calculateValor() { stages = levelsPossible.indexOf(afterLevel) - levelsPossible.indexOf(beforeLevel) if (stages > 0) { final = stages * atype.get(armortype); $(".result").text("You need : " + final + " Valor"); } else { $(".result").text("You can't downgrade dipshit"); }; };
angular.module('SnowfallModule', []).filter('commafy', function() { return function(input) { if (input.length > 1){ var firstNames = input.map(function(name){ firstName = name.split(' ')[0].split('.')[0]; return firstName; }); return firstNames.join(', '); } else { return input[0]; } }; }); function ThreadCtrl($scope) { $scope.threads = [ { inInbox: true, isSpam: false, isTrash: false, isRead: false, isStarred: true, authors: ['Lily Simonsen'], tags: ['Work'], subject: 'Meeting on Wednesday: come eat donuts!!!', hasAttachment: ' ' }, { inInbox: true, isSpam: false, isTrash: false, isRead: false, isStarred: false, authors: ["Jesse Flores", "Marshall Washington", "Kai Summers"], tags: [], subject: '[pymsp] Looking for a Python tutor', hasAttachment: ' ' }, { inInbox: false, isSpam: false, isTrash: false, isRead: true, isStarred: false, authors: ["Wallace Borrin"], tags: ['Friends'], subject: 'bonjour', hasAttachment: ' ' }, { inInbox: true, isSpam: false, isTrash: false, isRead: true, isStarred: true, authors: ["Ginger Lee", "me"], tags: ['Social', 'Friends'], subject: 'Rhubarb party!', hasAttachment: '📎' } ]; $scope.tags = [ { name: 'Family', color: 'eddf99' }, { name: 'Friends', color: '99ee88' }, { name: 'Work', color: 'ff99cc' }, { name: 'CCBDC', color: '88ffb0' }, { name: 'Social', color: 'aaafef' } ]; // sidebar methods $scope.unreadCount = function(tag) { var count = 0; angular.forEach($scope.threads, function(thread) { var threadCounts = true; if (tag) { threadCounts = thread.tags.indexOf(tag) > -1; } threadCounts = threadCounts && !thread.isRead; count += threadCounts ? 1 : 0; }); return count; }; $scope.allRead = function(tag) { return $scope.unreadCount(tag) === 0; }; // actions bar methods $scope.toggleCheckAll = function() { var checkStatus = false; if ($('.check-all input')[0].checked) { checkStatus = true; } $.each($scope.threads, function(index){ var thread = $scope.threads[index]; thread.isChecked = checkStatus; }); }; $scope.archive = function(){ console.log('clicked'); $.each($scope.threads, function(index){ var thread = $scope.threads[index]; if (thread.isChecked) { thread.inInbox = false; } }); }; $scope.trash = function(){ $.each($scope.threads, function(index){ var thread = $scope.threads[index]; if (thread.isChecked) { thread.isTrash = true; } }); }; $scope.spam = function(){ $.each($scope.threads, function(index){ var thread = $scope.threads[index]; if (thread.isChecked) { thread.isSpam = false; } }); }; // data cleanup stuff // fix relationships of objects $.each($scope.threads, function(index){ var thread = $scope.threads[index]; var new_tags_list = []; $.each(thread.tags, function(jindex){ var tag_name = thread.tags[jindex]; $.each($scope.tags, function(kindex){ var tag = $scope.tags[kindex]; if (tag.name === tag_name) { new_tags_list.push(tag); } }); }); thread.tags = new_tags_list; }); // make all threads unchecked to start $.each($scope.threads, function(index){ var thread = $scope.threads[index]; thread.isChecked = false; }); }
Settings.introText = "Welcome to Spawn Hero RPG!"; Settings.gameWinText = "You win!\n\nPlay again?"; Settings.gameOverText = "You died!\n\nPlay Again?"; Spawn.game = function(){ }
import Joi from 'joi'; import Hoek from 'hoek'; import pkg from '../package.json'; const optionsSchema = Joi.object().keys({ librato : Joi.object().required(), responseTimeKey : Joi.string().optional().default('responseTime'), requestCountKey : Joi.string().optional().default('requestCount'), }).options({ allowUnknown : true, stripUnknown : true, }); function register(server, options, next) { let valid = Joi.validate(options, optionsSchema); if (valid.error) { next(valid.error); return; } options = valid.value; let librato = options.librato; server.ext('onRequest', function(request, reply) { request.plugins.librato = { startTime : Date.now(), }; reply.continue(); }); server.on('response', function(request) { let source = Hoek.reach(request, 'route.settings.id', void 0); let time = Hoek.reach(request, 'plugins.librato.startTime', null); if (time) { librato.measure(options.responseTimeKey, Date.now() - time, { source }); } librato.increment(options.requestCountKey, { source }); }); next(); } register.attributes = { name : pkg.name, version : pkg.version, multiple : false, }; export default register;
"use strict"; let ThrustCommand = require('./ThrustCommand.js'); let MotorStatus = require('./MotorStatus.js'); let Supply = require('./Supply.js'); let ServoCommand = require('./ServoCommand.js'); let RawRC = require('./RawRC.js'); let VelocityXYCommand = require('./VelocityXYCommand.js'); let RC = require('./RC.js'); let PositionXYCommand = require('./PositionXYCommand.js'); let RawImu = require('./RawImu.js'); let Altimeter = require('./Altimeter.js'); let Compass = require('./Compass.js'); let HeadingCommand = require('./HeadingCommand.js'); let ControllerState = require('./ControllerState.js'); let YawrateCommand = require('./YawrateCommand.js'); let MotorCommand = require('./MotorCommand.js'); let RawMagnetic = require('./RawMagnetic.js'); let HeightCommand = require('./HeightCommand.js'); let RuddersCommand = require('./RuddersCommand.js'); let MotorPWM = require('./MotorPWM.js'); let VelocityZCommand = require('./VelocityZCommand.js'); let AttitudeCommand = require('./AttitudeCommand.js'); let LandingActionFeedback = require('./LandingActionFeedback.js'); let PoseGoal = require('./PoseGoal.js'); let PoseFeedback = require('./PoseFeedback.js'); let TakeoffActionFeedback = require('./TakeoffActionFeedback.js'); let LandingAction = require('./LandingAction.js'); let TakeoffActionResult = require('./TakeoffActionResult.js'); let PoseAction = require('./PoseAction.js'); let PoseActionFeedback = require('./PoseActionFeedback.js'); let TakeoffActionGoal = require('./TakeoffActionGoal.js'); let LandingGoal = require('./LandingGoal.js'); let LandingFeedback = require('./LandingFeedback.js'); let TakeoffAction = require('./TakeoffAction.js'); let LandingActionResult = require('./LandingActionResult.js'); let LandingActionGoal = require('./LandingActionGoal.js'); let TakeoffGoal = require('./TakeoffGoal.js'); let LandingResult = require('./LandingResult.js'); let PoseActionResult = require('./PoseActionResult.js'); let PoseActionGoal = require('./PoseActionGoal.js'); let PoseResult = require('./PoseResult.js'); let TakeoffResult = require('./TakeoffResult.js'); let TakeoffFeedback = require('./TakeoffFeedback.js'); module.exports = { ThrustCommand: ThrustCommand, MotorStatus: MotorStatus, Supply: Supply, ServoCommand: ServoCommand, RawRC: RawRC, VelocityXYCommand: VelocityXYCommand, RC: RC, PositionXYCommand: PositionXYCommand, RawImu: RawImu, Altimeter: Altimeter, Compass: Compass, HeadingCommand: HeadingCommand, ControllerState: ControllerState, YawrateCommand: YawrateCommand, MotorCommand: MotorCommand, RawMagnetic: RawMagnetic, HeightCommand: HeightCommand, RuddersCommand: RuddersCommand, MotorPWM: MotorPWM, VelocityZCommand: VelocityZCommand, AttitudeCommand: AttitudeCommand, LandingActionFeedback: LandingActionFeedback, PoseGoal: PoseGoal, PoseFeedback: PoseFeedback, TakeoffActionFeedback: TakeoffActionFeedback, LandingAction: LandingAction, TakeoffActionResult: TakeoffActionResult, PoseAction: PoseAction, PoseActionFeedback: PoseActionFeedback, TakeoffActionGoal: TakeoffActionGoal, LandingGoal: LandingGoal, LandingFeedback: LandingFeedback, TakeoffAction: TakeoffAction, LandingActionResult: LandingActionResult, LandingActionGoal: LandingActionGoal, TakeoffGoal: TakeoffGoal, LandingResult: LandingResult, PoseActionResult: PoseActionResult, PoseActionGoal: PoseActionGoal, PoseResult: PoseResult, TakeoffResult: TakeoffResult, TakeoffFeedback: TakeoffFeedback, };
import { makeStyles } from "@material-ui/core/styles" export const useBoutStyles = makeStyles(theme => ({ noItems: { minHeight: theme.spacing(20), }, hasItems: { minHeight: theme.spacing(20), }, }))
var OverlapKeeper = require(__dirname + '/../../src/utils/OverlapKeeper'); var Body = require(__dirname + '/../../src/objects/Body'); var Circle = require(__dirname + '/../../src/shapes/Circle'); exports.construct = function(test){ var keeper = new OverlapKeeper(); test.done(); }; exports.tick = function(test){ var keeper = new OverlapKeeper(); var bodyA = new Body(); var bodyB = new Body(); var shapeA = new Circle(1); var shapeB = new Circle(1); var keeper = new OverlapKeeper(); keeper.setOverlapping(bodyA, shapeA, bodyB, shapeB); test.equal(keeper.recordPool.length, 0); keeper.tick(); test.equal(keeper.recordPool.length, 0); keeper.tick(); test.equal(keeper.recordPool.length, 1); keeper.setOverlapping(bodyA, shapeA, bodyB, shapeB); test.equal(keeper.recordPool.length, 0); test.done(); }; exports.getEndOverlaps = function(test){ var bodyA = new Body(); var bodyB = new Body(); var bodyC = new Body(); var shapeA = new Circle(1); var shapeB = new Circle(1); var shapeC = new Circle(1); var keeper = new OverlapKeeper(); keeper.setOverlapping(bodyA, shapeA, bodyB, shapeB); var result = keeper.getEndOverlaps(); test.equal(result.length, 0); keeper.tick(); var result = keeper.getEndOverlaps(); test.equal(result.length, 1); keeper.tick(); var result = keeper.getEndOverlaps(); test.equal(result.length, 0); keeper.tick(); keeper.setOverlapping(bodyA, shapeA, bodyB, shapeB); keeper.setOverlapping(bodyC, shapeC, bodyB, shapeB); keeper.setOverlapping(bodyC, shapeC, bodyA, shapeA); var result = keeper.getEndOverlaps(); test.equal(result.length, 0); keeper.tick(); var result = keeper.getEndOverlaps(); test.equal(result.length, 3); test.done(); }; exports.getNewOverlaps = function(test){ var bodyA = new Body(); var bodyB = new Body(); var bodyC = new Body(); var shapeA = new Circle(1); var shapeB = new Circle(1); var shapeC = new Circle(1); var keeper = new OverlapKeeper(); keeper.setOverlapping(bodyA, shapeA, bodyB, shapeB); var result = keeper.getNewOverlaps(); test.equal(result.length, 1); test.equal(result[0].bodyA, bodyA); test.equal(result[0].bodyB, bodyB); test.equal(result[0].shapeA, shapeA); test.equal(result[0].shapeB, shapeB); keeper.tick(); var result = keeper.getNewOverlaps(); test.equal(result.length, 0); keeper.tick(); var result = keeper.getNewOverlaps(); test.equal(result.length, 0); keeper.setOverlapping(bodyA, shapeA, bodyB, shapeB); keeper.setOverlapping(bodyC, shapeC, bodyB, shapeB); keeper.setOverlapping(bodyC, shapeC, bodyA, shapeA); var result = keeper.getNewOverlaps(); test.equal(result.length, 3); test.done(); }; exports.isNewOverlap = function(test){ var bodyA = new Body(); var bodyB = new Body(); var shapeA = new Circle(1); var shapeB = new Circle(1); var keeper = new OverlapKeeper(); keeper.setOverlapping(bodyA, shapeA, bodyB, shapeB); var result = keeper.isNewOverlap(shapeA, shapeB); test.equal(result, true); keeper.tick(); var result = keeper.isNewOverlap(shapeA, shapeB); test.equal(result, false); keeper.tick(); var result = keeper.isNewOverlap(shapeA, shapeB); test.equal(result, false); test.done(); }; exports.getNewBodyOverlaps = function(test){ var keeper = new OverlapKeeper(); var bodyA = new Body(); var bodyB = new Body(); var bodyC = new Body(); var shapeA = new Circle(); var shapeB = new Circle(); var shapeC = new Circle(); keeper.setOverlapping(bodyA, shapeA, bodyB, shapeB); var result = keeper.getNewBodyOverlaps(); test.equal(result.length, 2); keeper.tick(); var result = keeper.getNewBodyOverlaps(); test.equal(result.length, 0); keeper.tick(); keeper.setOverlapping(bodyA, shapeA, bodyB, shapeB); keeper.setOverlapping(bodyC, shapeC, bodyB, shapeB); keeper.setOverlapping(bodyC, shapeC, bodyA, shapeA); var result = keeper.getNewBodyOverlaps(); test.equal(result.length, 6); test.done(); }; exports.getEndBodyOverlaps = function(test){ var bodyA = new Body(); var bodyB = new Body(); var shapeA = new Circle(1); var shapeB = new Circle(1); var keeper = new OverlapKeeper(); keeper.setOverlapping(bodyA, shapeA, bodyB, shapeB); var result = keeper.getEndBodyOverlaps(); test.equal(result.length, 0); keeper.tick(); var result = keeper.getEndBodyOverlaps(); test.equal(result.length, 2); test.done(); };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const path = require("path"); const util = require("util"); const chalk_1 = require("chalk"); const cli_utils_1 = require("@ionic/cli-utils"); const errors_1 = require("@ionic/cli-utils/lib/errors"); const init_1 = require("@ionic/cli-utils/lib/init"); const fs_1 = require("@ionic/cli-framework/utils/fs"); const guards_1 = require("@ionic/cli-utils/guards"); const commands_1 = require("./commands"); exports.namespace = new commands_1.IonicNamespace(); function generateRootPlugin() { return tslib_1.__awaiter(this, void 0, void 0, function* () { const { getPluginMeta } = yield Promise.resolve().then(() => require('@ionic/cli-utils/lib/plugins')); return { namespace: exports.namespace, meta: yield getPluginMeta(__filename), }; }); } exports.generateRootPlugin = generateRootPlugin; function run(pargv, env) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const now = new Date(); let err; let ienv; pargv = init_1.modifyArguments(pargv.slice(2)); env['IONIC_CLI_LIB'] = __filename; const { isSuperAgentError } = yield Promise.resolve().then(() => require('@ionic/cli-utils/guards')); const { isValidationErrorArray } = yield Promise.resolve().then(() => require('@ionic/cli-framework/guards')); const plugin = yield generateRootPlugin(); try { ienv = yield cli_utils_1.generateIonicEnvironment(plugin, pargv, env); } catch (e) { console.error(e.message ? e.message : (e.stack ? e.stack : e)); process.exitCode = 1; return; } try { const config = yield ienv.config.load(); ienv.log.debug(() => util.inspect(ienv.meta, { breakLength: Infinity, colors: chalk_1.default.enabled })); if (env['IONIC_EMAIL'] && env['IONIC_PASSWORD']) { ienv.log.debug(() => `${chalk_1.default.bold('IONIC_EMAIL')} / ${chalk_1.default.bold('IONIC_PASSWORD')} environment variables detected`); if (config.user.email !== env['IONIC_EMAIL']) { ienv.log.debug(() => `${chalk_1.default.bold('IONIC_EMAIL')} mismatch with current session--attempting login`); try { yield ienv.session.login(env['IONIC_EMAIL'], env['IONIC_PASSWORD']); } catch (e) { ienv.log.error(`Error occurred during automatic login via ${chalk_1.default.bold('IONIC_EMAIL')} / ${chalk_1.default.bold('IONIC_PASSWORD')} environment variables.`); throw e; } } } if (ienv.project.directory) { const nodeModulesExists = yield fs_1.pathExists(path.join(ienv.project.directory, 'node_modules')); if (!nodeModulesExists) { const confirm = yield ienv.prompt({ type: 'confirm', name: 'confirm', message: `Looks like a fresh checkout! No ${chalk_1.default.green('./node_modules')} directory found. Would you like to install project dependencies?`, }); if (confirm) { ienv.log.info('Installing dependencies may take several minutes!'); const { pkgManagerArgs } = yield Promise.resolve().then(() => require('@ionic/cli-utils/lib/utils/npm')); const [installer, ...installerArgs] = yield pkgManagerArgs(ienv, { command: 'install' }); yield ienv.shell.run(installer, installerArgs, {}); } } } const argv = init_1.parseArgs(pargv, { boolean: true, string: '_' }); // If an legacy command is being executed inform the user that there is a new command available const foundCommand = init_1.mapLegacyCommand(argv._[0]); if (foundCommand) { ienv.log.msg(`The ${chalk_1.default.green(argv._[0])} command has been renamed. To find out more, run:\n\n` + ` ${chalk_1.default.green(`ionic ${foundCommand} --help`)}\n\n`); } else { const { loadPlugins } = yield Promise.resolve().then(() => require('@ionic/cli-utils/lib/plugins')); try { yield loadPlugins(ienv); } catch (e) { if (e.fatal) { throw e; } ienv.log.error(chalk_1.default.red.bold('Error occurred while loading plugins. CLI functionality may be limited.')); ienv.log.debug(() => chalk_1.default.red(chalk_1.default.bold('Plugin error: ') + (e.stack ? e.stack : e))); } if (ienv.flags.interactive) { if (yield ienv.config.isUpdatingEnabled()) { const { checkForDaemon } = yield Promise.resolve().then(() => require('@ionic/cli-utils/lib/daemon')); yield checkForDaemon(ienv); const { checkForUpdates, getLatestPluginVersion, versionNeedsUpdating } = yield Promise.resolve().then(() => require('@ionic/cli-utils/lib/plugins')); const latestVersion = yield getLatestPluginVersion(ienv, plugin.meta.name, plugin.meta.version); if (latestVersion) { plugin.meta.latestVersion = latestVersion; plugin.meta.updateAvailable = yield versionNeedsUpdating(plugin.meta.version, latestVersion); yield checkForUpdates(ienv); } } } yield ienv.hooks.fire('plugins:init', { env: ienv }); yield exports.namespace.runCommand(ienv, pargv); config.state.lastCommand = now.toISOString(); } } catch (e) { err = e; } try { yield Promise.all([ ienv.config.save(), ienv.project.save(), ienv.daemon.save(), ]); } catch (e) { ienv.log.error(String(e.stack ? e.stack : e)); } if (err) { ienv.tasks.fail(); process.exitCode = 1; if (isValidationErrorArray(err)) { for (let e of err) { ienv.log.error(e.message); } ienv.log.msg(`Use the ${chalk_1.default.green('--help')} flag for more details.`); } else if (isSuperAgentError(err)) { const { formatSuperAgentError } = yield Promise.resolve().then(() => require('@ionic/cli-utils/lib/http')); ienv.log.msg(formatSuperAgentError(err)); } else if (err.code && err.code === 'ENOTFOUND' || err.code === 'ECONNREFUSED') { ienv.log.error(`Network connectivity error occurred, are you offline?\n` + `If you are behind a firewall and need to configure proxy settings, see: ${chalk_1.default.bold('https://ionicframework.com/docs/cli/configuring.html#using-a-proxy')}\n\n` + chalk_1.default.red(String(err.stack ? err.stack : err))); } else if (guards_1.isExitCodeException(err)) { process.exitCode = err.exitCode; if (err.message) { if (err.exitCode > 0) { ienv.log.error(err.message); } else { ienv.log.msg(err.message); } } } else if (err instanceof errors_1.Exception) { ienv.log.error(err.message); } else { ienv.log.msg(chalk_1.default.red(String(err.stack ? err.stack : err))); if (err.stack) { ienv.log.debug(() => chalk_1.default.red(String(err.stack))); } } } yield ienv.close(); }); } exports.run = run;
//@ts-check const debug = require('@tryghost/debug')('api:canary:utils:serializers:output:members'); const {unparse} = require('@tryghost/members-csv'); const labs = require('../../../../../../shared/labs'); module.exports = { hasActiveStripeSubscriptions: createSerializer('hasActiveStripeSubscriptions', passthrough), browse: createSerializer('browse', paginatedMembers), read: createSerializer('read', singleMember), edit: createSerializer('edit', singleMember), add: createSerializer('add', singleMember), editSubscription: createSerializer('editSubscription', singleMember), createSubscription: createSerializer('createSubscription', singleMember), bulkDestroy: createSerializer('bulkDestroy', passthrough), bulkEdit: createSerializer('bulkEdit', bulkAction), exportCSV: createSerializer('exportCSV', exportCSV), importCSV: createSerializer('importCSV', passthrough), stats: createSerializer('stats', passthrough), memberStats: createSerializer('memberStats', passthrough), mrrStats: createSerializer('mrrStats', passthrough), subscriberStats: createSerializer('subscriberStats', passthrough), grossVolumeStats: createSerializer('grossVolumeStats', passthrough), activityFeed: createSerializer('activityFeed', passthrough) }; /** * @template PageMeta * * @param {{data: import('bookshelf').Model[], meta: PageMeta}} page * @param {APIConfig} _apiConfig * @param {Frame} frame * * @returns {{members: SerializedMember[], meta: PageMeta}} */ function paginatedMembers(page, _apiConfig, frame) { return { members: page.data.map(model => serializeMember(model, frame.options)), meta: page.meta }; } /** * @param {import('bookshelf').Model} model * @param {APIConfig} _apiConfig * @param {Frame} frame * * @returns {{members: SerializedMember[]}} */ function singleMember(model, _apiConfig, frame) { return { members: [serializeMember(model, frame.options)] }; } /** * @param {object} bulkActionResult * @param {APIConfig} _apiConfig * @param {Frame} frame * * @returns {{bulk: SerializedBulkAction}} */ function bulkAction(bulkActionResult, _apiConfig, frame) { return { bulk: { action: frame.data.action, meta: { stats: { successful: bulkActionResult.successful, unsuccessful: bulkActionResult.unsuccessful }, errors: bulkActionResult.errors, unsuccessfulData: bulkActionResult.unsuccessfulData } } }; } /** * @template PageMeta * * @param {{data: import('bookshelf').Model[], meta: PageMeta}} page * @param {APIConfig} _apiConfig * @param {Frame} frame * * @returns {string} - A CSV string */ function exportCSV(page, _apiConfig, frame) { debug('exportCSV'); const members = page.data.map(model => serializeMember(model, frame.options)); return unparse(members); } /** * @param {import('bookshelf').Model} member * @param {object} options * * @returns {SerializedMember} */ function serializeMember(member, options) { const json = member.toJSON ? member.toJSON(options) : member; const comped = json.status === 'comped'; const subscriptions = json.subscriptions || []; const serialized = { id: json.id, uuid: json.uuid, email: json.email, name: json.name, note: json.note, geolocation: json.geolocation, subscribed: json.subscribed, created_at: json.created_at, updated_at: json.updated_at, labels: json.labels, subscriptions: subscriptions, avatar_image: json.avatar_image, comped: comped, email_count: json.email_count, email_opened_count: json.email_opened_count, email_open_rate: json.email_open_rate, email_recipients: json.email_recipients, status: json.status }; if (labs.isSet('membersLastSeenFilter')) { serialized.last_seen_at = json.last_seen_at; } if (json.products) { serialized.products = json.products; } return serialized; } /** * @template Data * @param {Data} data * @returns Data */ function passthrough(data) { return data; } /** * @template Data * @template Response * @param {string} debugString * @param {(data: Data, apiConfig: APIConfig, frame: Frame) => Response} serialize - A function to serialize the data into an object suitable for API response * * @returns {(data: Data, apiConfig: APIConfig, frame: Frame) => void} */ function createSerializer(debugString, serialize) { return function serializer(data, apiConfig, frame) { debug(debugString); const response = serialize(data, apiConfig, frame); frame.response = response; }; } /** * @typedef {Object} SerializedMember * @prop {string} id * @prop {string} uuid * @prop {string} email * @prop {string=} name * @prop {string=} note * @prop {null|string} geolocation * @prop {boolean} subscribed * @prop {string} created_at * @prop {string} updated_at * @prop {string[]} labels * @prop {SerializedMemberStripeSubscription[]} subscriptions * @prop {SerializedMemberProduct[]=} products * @prop {string} avatar_image * @prop {boolean} comped * @prop {number} email_count * @prop {number} email_opened_count * @prop {number} email_open_rate * @prop {null|SerializedEmailRecipient[]} email_recipients * @prop {'free'|'paid'} status */ /** * @typedef {Object} SerializedMemberProduct * @prop {string} id * @prop {string} name * @prop {string} slug */ /** * @typedef {Object} SerializedMemberStripeData * @prop {SerializedMemberStripeSubscription[]} subscriptions */ /** * @typedef {Object} SerializedMemberStripeSubscription * * @prop {string} id * @prop {string} status * @prop {string} start_date * @prop {string} default_payment_card_last4 * @prop {string} current_period_end * @prop {boolean} cancel_at_period_end * * @prop {Object} customer * @prop {string} customer.id * @prop {null|string} customer.name * @prop {string} customer.email * * @prop {Object} price * @prop {string} price.id * @prop {string} price.nickname * @prop {number} price.amount * @prop {string} price.interval * @prop {string} price.currency * * @prop {Object} price.product * @prop {string} price.product.id * @prop {string} price.product.product_id */ /** * @typedef {Object} SerializedEmailRecipient * * @prop {string} id * @prop {string} email_id * @prop {string} batch_id * @prop {string} processed_at * @prop {string} delivered_at * @prop {string} opened_at * @prop {string} failed_at * @prop {string} member_uuid * @prop {string} member_email * @prop {string} member_name * @prop {SerializedEmail[]} email */ /** * @typedef {Object} SerializedEmail * * @prop {string} id * @prop {string} post_id * @prop {string} uuid * @prop {string} status * @prop {string} recipient_filter * @prop {null|string} error * @prop {string} error_data * @prop {number} email_count * @prop {number} delivered_count * @prop {number} opened_count * @prop {number} failed_count * @prop {string} subject * @prop {string} from * @prop {string} reply_to * @prop {string} html * @prop {string} plaintext * @prop {boolean} track_opens * @prop {string} created_at * @prop {string} created_by * @prop {string} updated_at * @prop {string} updated_by */ /** * * @typedef {Object} SerializedBulkAction * * @prop {string} action * * @prop {object} meta * @prop {object[]} meta.unsuccessfulData * @prop {Error[]} meta.errors * @prop {object} meta.stats * * @prop {number} meta.stats.successful * @prop {number} meta.stats.unsuccessful */ /** * @typedef {Object} APIConfig * @prop {string} docName * @prop {string} method */ /** * @typedef {Object<string, any>} Frame * @prop {Object} options */
/* */ 'use strict'; Object.defineProperty(exports, "__esModule", {value: true}); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _svgIcon = require('../../svg-icon'); var _svgIcon2 = _interopRequireDefault(_svgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } var ActionOpacity = _react2.default.createClass({ displayName: 'ActionOpacity', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M17.66 8L12 2.35 6.34 8C4.78 9.56 4 11.64 4 13.64s.78 4.11 2.34 5.67 3.61 2.35 5.66 2.35 4.1-.79 5.66-2.35S20 15.64 20 13.64 19.22 9.56 17.66 8zM6 14c.01-2 .62-3.27 1.76-4.4L12 5.27l4.24 4.38C17.38 10.77 17.99 12 18 14H6z'})); } }); exports.default = ActionOpacity; module.exports = exports['default'];
console.log("Hello from the background page"); var desiredURL = "https://www.youtube.com"; var desiredHour = "0"; var desiredMinute = "0"; var desiredZeroTime = false; chrome.alarms.onAlarm.addListener(function(alarm) { console.log("Alarm fired!"); console.log(alarm); console.log("The ms time is now: " + Date.now()); actualURL = desiredURL; if (desiredZeroTime) { actualURL += "#t=0"; } tabProperties = { url: actualURL }; chrome.tabs.create(tabProperties); }); chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { console.log(request); if (request.setValues == false) { // The extension is requesting the current alarm. sendResponse({ hour: desiredHour, minute: desiredMinute, url: desiredURL, zeroTime: desiredZeroTime}); return; } if (request.url == "" || request.url == undefined) { sendResponse({ error: "Invalid URL"}); return; } desiredURL = request.url; desiredZeroTime = request.zeroTime; console.log("zero time: " + desiredZeroTime); dateToFire = new Date(); console.log("NOW: " + dateToFire); chrome.alarms.clearAll(); timeArray = request.time.split(":"); if(timeArray.length != 2) { sendResponse({ error: "Invalid Time"}); return; } desiredHour = timeArray[0]; desiredMinute = timeArray[1]; dateToFire.setHours(desiredHour); dateToFire.setMinutes(desiredMinute); dateToFire.setSeconds(0); console.log("Alarm will fire at: " + dateToFire); timeToFire = dateToFire.getTime(); if (timeToFire < Date.now()) { console.log("Setting time for tomorrow..."); timeToFire += 1000 * 60 * 60 * 24; // Milliseconds / day } else { console.log("Setting time for today..."); } console.log("Time to fire: " + timeToFire); alarmPeriod = 60 * 24; // Minutes / day alarmInfo = { when: timeToFire, periodInMinutes: alarmPeriod}; alarmA = chrome.alarms.create("a", alarmInfo); sendResponse({}); });
/* * * 以下のように使用します *--------------------------------------------------------------------------------------- <html> <head> <script src="http://maps.google.com/maps?file=api&v=2&key=<Google Maps API key>" type="text/javascript"> </script> <script type="text/javascript"> <!--//--><![CDATA[//><!-- var use_onload=true; var plot_mode=1; // 省略可能 var user_list = [ 'foo', 'bar' ]; // 省略可能 var trace_user = 'foo'; // 省略可能 //--><!]]> </script> <script src="/static/script.js" type="text/javascript"> </script> </head> <body> <div id="map" style="width:400px; height:400px"></div> プロットしたいユーザーにチェック<br /> <div id="userlist"></div> <div id="usercontrol"> 注目したいユーザーを選択(選択したユーザーを追いかけるようになります)<br /> <select id="traceuser" onChange="setTraceUser(this.options[this.options.selectedIndex].value)"> </select> </div> </body> </html> *--------------------------------------------------------------------------------------- * * var use_onload=true; // これを定義しないと地図は表示されません。 * // 地図は表示しないけど関数を使いたい時などは定義しないかfalseを設定します * var plot_mode=1; // 定義しないor0のとき軌跡をプロットしません * // 1のとき点でプロットします。 * // 1ユーザーあたり1000ポイントまで描画します。 * // それ以上になったら古いほうから消えていきます * // 2のとき線で描画します。 * // 線の場合すべて描画するので長時間表示するとブラウザが重くなることがあります * var user_list = [ 'foo', 'bar' ]; * // プロットするユーザーを配列で指定します * var trace_user = 'foo'; * // 追いかけるユーザーを指定します */ $(document).ready(function() { // [ADD] //グローバル変数 var map; var markeropts; var geocoder; var share_markers = new Array(); var map_style = ''; var hidelist = 0; var plotmode = 0; // 0=軌跡表示しない、1=点、2=線 var plotcount = 1000; var fromtop = false; var traceuser = ''; var center; var group_revision = ''; var apiview = 0; var prev_trace = ""; var static_file_site = '/img/'; // [CHANGE] var api_site = 'http://imacoco.589406.com'; var timer; var datetimebox; var USTERAM_TV = 'live'; var JUSTIN_TV = 'justin.tv'; // グローバル変数 [ADD] var altitudeGraph = new Array(); var velocityGraph = new Array(); var startPoint = new google.maps.LatLng(35, 137); var nowPoint = new google.maps.LatLng(35, 137); var userExist = false; var distance = new Array(); var hougaku = ['北', '北北東', '北東', '東北東', '東', '東南東', '南東', '南南東', '南', '南南西', '南西', '西南西', '西', '西北西', '北西', '北北西']; //------------------------------------------------------------- // 移動したかどうかをチェックする(1m以上移動したかどうか) /* function checkMoving(lat_from, lon_from, lat_to, lon_to) { var from = new google.maps.LatLng(lat_from, lon_from); var to = new google.maps.LatLng(lat_to, lon_to); return to.distanceFrom(from) > 1; } */ // 注意:簡易的に緯度経度の変化のみ見ることにする function checkMoving(lat_from, lon_from, lat_to, lon_to) { return (lat_from != lat_to || lon_from != lon_to); } // グローバル変数が定義済みかどうか // objを指定すると、obj.vが定義済みかどうかを判定 // 指定がない場合はwindow.v(グローバル変数v)が定義済みかどうかを判定 function isDefined(v, obj) { if (obj == undefined) { obj = 'window'; } var ret = typeof(eval(obj)[v]) != 'undefined'; // alert('variable ' + obj + '.' + v + ' is ' + (ret ? 'defined' : 'undefined')); return ret; } // メッセージ出力 function setMessage(mesg) { var msg = document.getElementById('msg'); if (msg) { msg.innerHTML = mesg; } } // 現在時刻文字列作成 function makeTimeString() { var mySysDate = new Date(); var myYear = mySysDate.getFullYear(); var myMonth = mySysDate.getMonth()+1; var myDate = mySysDate.getDate(); var myHour = mySysDate.getHours(); var myMin = mySysDate.getMinutes(); var mySec = mySysDate.getSeconds(); if (myMonth < 10) { myMonth = "0" + myMonth; } if (myDate < 10) { myDate = "0" + myDate; } if (myHour < 10) { myHour = "0" + myHour; } if (myMin < 10) { myMin = "0" + myMin; } if (mySec < 10) { mySec = "0" + mySec; } return myYear + '-' + myMonth + '-' + myDate + ' ' + myHour + ':' + myMin + ':' + mySec; } // マーカーを消す function removeUserMarker(user) { if (typeof(user.prev_marker) != 'undefined') { map.removeOverlay(user.prev_marker); user.prev_marker = undefined; } if (user.prev_marker2 != undefined) { map.removeOverlay(user.prev_marker2); } if (user.polyline != undefined) { map.removeOverlay(user.polyline); } while (user.track.length > 0) { var mk = user.track.shift(); map.removeOverlay(mk); } if (user.stream_marker) { map.removeOverlay(user.stream_marker); user.stream_marker = undefined; } user.lat = 0; user.lon = 0; } var iconImage = [ { 'path':'/car', 'direction': true, 'ext':'.png', 'w':32, 'h':32, 'ax':16, 'ay':16, 'wax':16, 'way':10, 'path2':'/middle_arrow/arrow-', 'w2':52, 'h2':52, 'ax2':26, 'ay2':26, 'wax2':26, 'way2':20 }, { 'path':'/keitai', 'direction': false, 'ext':'.png', 'w':20, 'h':45, 'ax':10, 'ay':23, 'wax':10, 'way':18 }, { 'path':'http://maps.google.co.jp/mapfiles/ms/icons/plane', 'direction': false, 'ext':'.png', 'w':32, 'h':32, 'ax':16, 'ay':16, 'wax':16, 'way':16 }, { 'path':'/train', 'direction': false, 'ext':'.png', 'w':55, 'h':45, 'ax':28, 'ay':23, 'wax':28, 'way':19 }, { 'path':'/shinkansen', 'direction': false, 'ext':'.png', 'w':44, 'h':42, 'ax':22, 'ay':21, 'wax':22, 'way':17 }, { 'path':'http://maps.google.co.jp/mapfiles/ms/icons/bus', 'direction': false, 'ext':'.png', 'w':32, 'h':32, 'ax':16, 'ay':16, 'wax':16, 'way':16 }, { 'path':'http://maps.google.co.jp/mapfiles/ms/icons/cycling', 'direction': false, 'ext':'.png', 'w':32, 'h':32, 'ax':16, 'ay':16, 'wax':16, 'way':16 }, { 'path':'http://maps.google.co.jp/mapfiles/ms/icons/hiker', 'direction': false, 'ext':'.png', 'w':32, 'h':32, 'ax':16, 'ay':16, 'wax':16, 'way':16 }, { 'path':'http://maps.google.co.jp/mapfiles/ms/icons/motorcycling', 'direction': false, 'ext':'.png', 'w':32, 'h':32, 'ax':16, 'ay':16, 'wax':16, 'way':16 }, { 'path':'http://maps.google.co.jp/mapfiles/ms/icons/helicopter', 'direction': false, 'ext':'.png', 'w':32, 'h':32, 'ax':16, 'ay':16, 'wax':16, 'way':16 }, { 'path':'http://maps.google.co.jp/mapfiles/ms/icons/ferry', 'direction': false, 'ext':'.png', 'w':32, 'h':32, 'ax':16, 'ay':16, 'wax':16, 'way':16 }, ]; var defaultDirectionIcon = new Array(); var directionIcon = new Array(); // streamマーカーの作成 function makeStreamMarker(stream, pt) { var ic = new google.maps.MarkerImage(); if (stream == 'live') { // ustream.tv ic.image = static_file_site + 'ustream.png'; } else if (stream == 'justin.tv') { // justin.tv ic.image = static_file_site + 'justin.png'; } else if (stream.match(/^nicolive/)) { // ニコニコ生放送 ic.image = static_file_site + 'nicolive.png'; } ic.iconSize = new google.maps.Size(16, 16); ic.iconAnchor = new google.maps.Point(-8, -8); ic.infoWindowAnchor = new google.maps.Point(0, 0); var opt = new Object; opt.icon = ic; opt.clickable = false; opt.draggable = false; var marker = new google.maps.Marker(pt, opt); marker.type = stream; return marker; } //現在地アイコンの作成 function makeDirectionIcon(td, type) { var ic = new google.maps.MarkerImage(); var icm; if (iconImage[type]) { icm = iconImage[type]; } else { icm = iconImage[0]; } if (!isNaN(td) && icm.direction) { ic.image = static_file_site + icm.path2 + String(parseInt(td)) + icm.ext; ic.iconSize = new google.maps.Size(icm.w2, icm.h2); ic.iconAnchor = new google.maps.Point(icm.ax2, icm.ay2); ic.infoWindowAnchor = new google.maps.Point(icm.wax2, icm.way2); } else { if (icm.path.substring(0, 7) == "http://") { ic.image = icm.path + icm.ext; } else { ic.image = static_file_site + '/' + icm.path + icm.ext; } ic.iconSize = new google.maps.Size(icm.w, icm.h); ic.iconAnchor = new google.maps.Point(icm.ax, icm.ay); ic.infoWindowAnchor = new google.maps.Point(icm.wax, icm.way); } return ic; } //現在地アイコンの作成 function getDirectionIcon(td, type, username) { if (!isNaN(td) && type == 0) { td = Math.round(td); td %= 360; return defaultDirectionIcon[td]; } else if (type == 99) { if(users[username].twitter_icon == 'no_twitter_id') { return directionIcon[0]; } else if (users[username].twitter_icon) { return users[username].twitter_icon; } else { var req = GXmlHttp.create(); req.open("GET", api_site + "/api/getuserinfo?user=" + username +"&t="+ new Date().getTime() , false); req.send(); if (req.readyState == 4 && req.status == 200 && req.responseText != "") { var res = eval(req.responseText); // 情報ウィンドウ内のHTML if (res && res.result) { if (res.twitter_image_url) { var ic = new google.maps.MarkerImage(); ic.image = res.twitter_image_url; ic.iconSize = new google.maps.Size(32, 32); ic.iconAnchor = new google.maps.Point(16, 16); ic.infoWindowAnchor = new google.maps.Point(16, 16); users[username].twitter_icon = ic; } else { users[username].twitter_icon = 'no_twitter_id'; } } } if (users[username].twitter_icon && users[username].twitter_icon != 'no_twitter_id') { return users[username].twitter_icon } else { return directionIcon[0]; } } } else { return directionIcon[type] } } // マーカー function createClickableMarker(pt, opts, username) { var mk = new google.maps.Marker(pt, opts); mk.user = username; // イベントで使う // 現在時刻(情報ウィンドウ内に表示) mk.plottime = makeTimeString(); // 情報ウィンドウを閉じたときのイベント google.maps.event.addListener(mk, 'infowindowclose', function() { mk.hasInfoWindow = false; setTraceUser(prev_trace); prev_trace = ""; }); // マーカーをクリックしたときのイベント google.maps.event.addListener(mk, 'click', function() { var txt = ""; if (!users[mk.user].user_info || users[mk.user].user_info == "") { // ユーザー情報がなければサーバからとってくる var req = GXmlHttp.create(); req.open("GET",api_site + "/api/getuserinfo?user=" + mk.user +"&t="+ new Date().getTime() , false); req.send(""); if (req.status == 200 && req.responseText != "") { var res = eval(req.responseText); // 情報ウィンドウ内のHTML if (res && res.result) { var txt; if (res.popup) { txt = "<div id='infowindow' style='width:240px'><a href='/gpslive/%user%'>%user%</a>%liveinfo%<hr>" + // [CHANGE] res.popup + "</div>"; } else { txt = "<div id='infowindow' style='width:240px'><a href='/gpslive/%user%'>%user%</a>%liveinfo%<hr>" + // [CHANGE] "最終表示時刻 %plottime%\\n%profile%\\n%userweb%\\n%twitter%\\n%ustream%" + "</div>"; } users[mk.user].jtv = res.jtv users[mk.user].ust = res.ust txt = txt.replace('%profile%', res.url ? '<a target="_blank" href="http://imakoko-gps.appspot.com/home/' + mk.user + '">profile</a>' : ''); // [CHANGE] txt = txt.replace('%userweb%', res.url ? '<a target="_blank" href="' + res.url + '">HomePage</a>' : ''); txt = txt.replace('%twitter%', res.twitter ? '<a target="_blank" href="http://twitter.com/' + res.twitter + '">' + res.twitter + ' on Twitter</a>' : ''); txt = txt.replace('%ustream%', res.ust ? '<a target="_blank" href="http://www.ustream.tv/channel/' + res.ust + '">' + res.ust + ' on USTREAM</a>' : ''); txt = txt.replace('%justin%', res.jtv ? '<a target="_blank" href="http://www.justin.tv/' + res.jtv + '">' + res.jtv + ' on Justin.tv</a>' : ''); users[mk.user].user_info = txt; } else { users[mk.user].user_info = "情報の取得に失敗しました"; } } else { users[mk.user].user_info = "情報の取得に失敗しました"; } } for (var user in users) { if (users[user].prev_marker) { users[user].prev_marker.hasInfoWindow = false; } } users[mk.user].prev_marker.hasInfoWindow = true; users[mk.user].prev_marker.openInfoWindowHtml(updateInformation(mk.user)); if (prev_trace == "") { prev_trace = traceuser; } setTraceUser(mk.user, 14); }); return mk; } function createSharedMarker(pt, key, desc) { var marker = new google.maps.Marker(pt); google.maps.event.addListener(marker, 'click', function() { updateOff(); marker.openInfoWindowHtml('<div><pre>' + desc + '</pre></div><hr><div><button onClick=\"removeSharedMarker(\''+key+'\')\">削除</button></div>'); } ); google.maps.event.addListener(marker, 'infowindowclose', function() { updateOn(); } ); return marker; } function removeSharedMarker(key) { if (!isDefined('group_name') || group_name == '') { alert('グループ表示モードではありません'); return; } var req = GXmlHttp.create(); req.open("GET", "/user/deletemarker?group=" + encodeURIComponent(group_name) + "&key=" + key , false); req.send(""); if (req.status != 200 || req.responseText == "") { alert('サーバでエラーが発生しました'); return false; } var res = eval(req.responseText); // 情報ウィンドウ内のHTML if (res && res.result) { map.removeOverlay(share_markers[key].marker); delete share_markers[key]; alert('削除しました'); return true; } else { alert('サーバでエラーが発生しました:' + res.errmsg); return false; } } function updateInformation(user) { var txt = users[user].user_info. replace(/%user%/g, user). replace(/%plottime%/g, makeTimeString()). replace(/%latitude%/g, users[user].prev_point.lat()). replace(/%longitude%/g, users[user].prev_point.lng()). replace(/%direction%/g, users[user].td). replace(/%altitude%/g, users[user].altitude). replace(/\\n/g, "<br>"). replace(/%hr%/g, "<hr>"); if (users[user].broadcast) { var bc = users[user].broadcast; if (bc == 'live' && users[user].ust) { txt = txt.replace('%liveinfo%', '&nbsp;<a target="_blank" href="http://www.ustream.tv/channel/' + users[user].ust + '"><b>LIVE on USTREAM.tv</b></a>'); txt = txt.replace('%nicolive%', ''); } else if (bc == 'justin.tv' && users[user].jtv) { txt = txt.replace('%nicolive%', ''); txt = txt.replace('%liveinfo%', '&nbsp;<a target="_blank" href="http://www.justin.tv/' + users[user].jtv + '"><b>LIVE on Justin.tv</b></a>'); } else if( users[user].broadcast.match(/^nicolive:(.+)/)) { nicolive = RegExp.$1; txt = txt.replace('%nicolive%', '<a target="_blank" href="http://live.nicovideo.jp/watch/lv' + nicolive + '">ニコニコ生放送中</a>'); txt = txt.replace('%liveinfo%', '&nbsp;<a target="_blank" href="http://live.nicovideo.jp/watch/lv' + nicolive + '"><b>ニコニコ生放送中</b></a>'); } else { txt = txt.replace('%nicolive%', ''); txt = txt.replace('%liveinfo%', ''); } } else { txt = txt.replace('%nicolive%', ''); txt = txt.replace('%liveinfo%', ''); } if (users[user].velocity || users[user].velocity == 0) { txt = txt.replace(/%velocity%/g, users[user].velocity); } else { txt = txt.replace(/%velocity%/g, '非公開'); } var t = document.getElementById('infowindow'); if (t) { t.innerHTML = txt; } return txt; } // 地図のスクロールとマーキング function update() { if (!isDefined('group_name')) { // 位置情報を取得するユーザー var ul = ""; if (isDefined('user_list') && user_list[0] == 'all') { ul = 'all,'; } else { for (var user in users) { if (users[user].watch) { ul += user + ","; } } } if (ul == "") { return false; } ul = 'user=' + ul.substr(0, ul.length-1); } else { ul = 'group=' + group_name; if (group_revision != "") { ul += ('&revision=' + group_revision); } } // 位置情報を取得する /* var request = GXmlHttp.create(); request.open("GET",api_site + "/api/latest?"+ ul + "&for_top=" + (fromtop ? "1" : "0") + "&t="+ new Date().getTime() , true); request.onreadystatechange = */ $.getJSON(api_site + "/api/latest?"+ ul + "&for_top=" + (fromtop ? "1" : "0"), { t : new Date().getTime() }, function(json){ var d = eval(json); if (!d) { // update(); return false; } if (!d.result) { clearInterval(timer); alert(d.errmsg); return false; } if (datetimebox) { datetimebox.innerHTML = makeTimeString(); } // 全体を表示するための範囲情報 var min_lat = 91; var min_lon = 181; var max_lat = -91; var max_lon = -181; var valid_users = 0; /* [ADD] // 共有マーカー表示 if (d.group_updated == undefined || d.group_updated) { if (d.group_revision != undefined) { group_revision = d.group_revision; } if (d.group) { for (var idx in share_markers) { share_markers[idx].valid = false; } for (var grp=0; grp<d.group.length; grp++) { var key = d.group[grp].key; if (share_markers[key] == undefined) { share_markers[key] = new Object(); share_markers[key].marker = createSharedMarker(new google.maps.LatLng(d.group[grp].lat, d.group[grp].lon), key, d.group[grp].desc) map.addOverlay(share_markers[key].marker); } share_markers[key].valid = true; } for (var idx in share_markers) { if (!share_markers[idx].valid) { map.removeOverlay(share_markers[idx].marker); delete share_markers[idx]; } } } } for (var key in share_markers) { var lat = parseFloat(share_markers[key].marker.getLatLng().lat()); var lon = parseFloat(share_markers[key].marker.getLatLng().lng()); min_lat = Math.min(lat, min_lat); max_lat = Math.max(lat, max_lat); min_lon = Math.min(lon, min_lon); max_lon = Math.max(lon, max_lon); valid_users++; } */ for (var u in users) { users[u].update = false; } var viewArea = map.getBounds(); distance = new Array(); // [ADD] // 全員分ループ for (var i=0; i<d.points.length; i++) { var username = d.points[i].user; if (!isDefined(username, 'users')) { initUser(username, true); } var user = users[username]; var data = d.points[i]; user.update = true; // 位置・方位 var lat = parseFloat(data.lat); var lon = parseFloat(data.lon); var td = parseFloat(data.dir); var velocity = parseFloat(data.velocity); var altitude = parseFloat(data.altitude); // 距離計算用配列に格納 // [ADD] var nickname = data.nickname; distanceInit(username, lat, lon, nickname); // 地図の描画範囲外のアイコンは削除する var pt = new google.maps.LatLng(lat, lon); if (traceuser != 'all' && traceuser != username && !viewArea.contains(pt)) { removeUserMarker(user); continue; } // 無効なデータかどうか // if (lat == 0 && lon == 0) { continue; } // 前回の座標と違った場合はプロットする if (checkMoving(user.lat, user.lon, lat, lon)) { // 現在位置に置くマーカー var opts = new Object(); opts.icon = getDirectionIcon(td, data.type, username); opts.title = username; // 現在位置マーカー var mk = createClickableMarker(pt, opts, username); // Broadcastマーカー if (data.ustream_status && data.ustream_status != "offline") { if (!user.stream_marker || user.stream_marker.type != data.ustream_status) { var stream_marker = makeStreamMarker(data.ustream_status, pt); if (user.stream_marker) { map.removeOverlay(user.stream_marker); } user.stream_marker = stream_marker; map.addOverlay(user.stream_marker); } else { user.stream_marker.setLatLng(pt); } } else { if (user.stream_marker) { map.removeOverlay(user.stream_marker) user.stream_marker = 0; } } user.broadcast = data.ustream_status // ニックネームのマーカー var mk1 = new google.maps.Marker(pt, user.user_markeropts); // 前回配置したニックネームマーカーを削除 if (user.prev_marker2 != undefined) { map.removeOverlay(user.prev_marker2); } var hasInfoWindow = false; var prev_trace_tmp = prev_trace; var current_trace = traceuser; if (user.prev_marker != undefined) { // 情報ウィンドウを持っていたかどうか hasInfoWindow = user.prev_marker.hasInfoWindow ? user.prev_marker.hasInfoWindow : false; if (plotmode == 1) { // 描画モードが点 // ひとつ前の場所に点を打つ var mk2 = new google.maps.Marker(user.prev_point, user.markeropts); map.addOverlay(mk2); user.track.push(mk2); // プロット数を制限する if (user.track.length > plotcount) { mk2 = user.track.shift(); map.removeOverlay(mk2); } } else if (plotmode == 2) { // 描画モードが線 // 前のラインを削除 map.removeOverlay(user.polyline); } // 一つ前の現在位置マーカーを削除 map.removeOverlay(user.prev_marker); } if (plotmode == 2) { // 描画モードが線 // 新しくラインを描画 pl = createEncodedPolyline(user, pt); map.addOverlay(pl); user.polyline = pl; } // 新たに現在位置マーカーとニックネームマーカーを描画 map.addOverlay(mk); map.addOverlay(mk1); if (hasInfoWindow) { // 情報ウィンドウを再表示する mk.openInfoWindowHtml(updateInformation(username)); mk.hasInfoWindow = true; prev_trace = prev_trace_tmp; setTraceUser(current_trace); } // 次回のためにマーカーと位置情報を保存 user.prev_marker = mk; user.prev_marker2 = mk1; user.prev_point = pt; user.lat = lat; user.lon = lon; user.td = td; user.altitude = altitude; user.velocity = velocity; if (user.trace) { // 注目しているユーザーに移動 map.panTo(pt); center = map.getCenter(); } // データ表示するユーザー [ADD] if (username == view_user) { userExist = true; if(altitudeGraph.length > plotcount){ altitudeGraph.shift(); } if(velocityGraph.length > plotcount){ velocityGraph.shift(); } if(altitudeGraph.length == 0 && velocityGraph.length == 0){ startPoint = new google.maps.LatLng(lat, lon); } nowPoint = new google.maps.LatLng(lat, lon); altitudeGraph.push(altitude); velocityGraph.push(velocity); // 情報表示ウィンドウ $("#infoTime").html(makeTimeString()); if(isFinite(velocity)){ $("#infoVelocity").html(Math.round(velocity * 10) / 10 + ' km/h'); }else{ $("#infoVelocity").html('--- km/h'); } if(isFinite(altitude)){ $("#infoAltitude").html(Math.round(altitude * 10) / 10 + ' m'); }else{ $("#infoAltitude").html('--- m'); } if(altitudeGraph.length >= 2){ $("#altitudeGraph").sparkline(altitudeGraph, { type: 'line', width: '120px', height: '20px', lineColor:'#0d0', fillColor:'#cfd', spotColor:'#f00', minSpotColor: false, maxSpotColor: false, spotRadius:2, normalRangeMin:0, normalRangeMax:0 }); }else{ $("#altitudeGraph").html(''); } if(velocityGraph.length >= 2){ $("#velocityGraph").sparkline(velocityGraph, { type: 'line', width: '120px', height: '20px', lineColor:'#00f', fillColor:'#cdf', chartRangeMin:0, chartRangeMax:80, spotColor:'#f00', minSpotColor: false, maxSpotColor: false, spotRadius:2 }); }else{ $("#velocityGraph").html(''); } // 背景を点滅させて更新を知らせる $("#info").css("background-color", "#ff9"); $("#info").fadeTo("slow", 1, function(){$("#info").css("background-color", "#ffc")}); $("#info").fadeTo("slow", 0.8); } } min_lat = Math.min(lat, min_lat); max_lat = Math.max(lat, max_lat); min_lon = Math.min(lon, min_lon); max_lon = Math.max(lon, max_lon); valid_users++; } // データ表示するユーザーがいない [ADD] if(userExist && users[view_user].update == false){ // 背景を赤くして更新されていないことを知らせる $("#info").css("background-color", "#faa"); $("#address").fadeOut("slow"); $("#address").html(""); userExist = false; } // 近接センサーパネル [ADD] var distanceSort = new Array(); for (var u in users) { if (!users[u].update) { removeUserMarker(users[u]); }else{ var toPoint = new google.maps.LatLng(distance[u].lat, distance[u].lon); // view_userがオンライン if(isDefined(view_user, 'users') && users[view_user].update){ if(u != view_user){ distanceCalc(u, nowPoint, toPoint); distanceSort.push({key:u,val:distance[u].dist}); } }else{ distanceCalc(u, new google.maps.LatLng(35.658634, 139.745411), toPoint); distanceSort.push({key:u,val:distance[u].dist}); } } } distanceSort.sort(function(a, b) {return Number(a.val) - Number(b.val);}); var tmp = ''; var distanceLengthMax = 5; if(distanceLengthMax > distanceSort.length){ distanceLengthMax = distanceSort.length; } for(var i=0;i<distanceLengthMax;i++){ tmp += '<tr><td class="nickname"><a href="/gpslive/' + distanceSort[i].key + '">' + distance[distanceSort[i].key].nickname + '</a></td><td class="houi"><img src="' + static_file_site + 'green_arrow/arrow-' + distance[distanceSort[i].key].houi + '.png" height="16" width="16" /> ' + hougaku[distance[distanceSort[i].key].houi] + '</td><td class="kyori">' + distance[distanceSort[i].key].kyori + '</td></tr>'; } $("#kinsetsu-table").html(tmp); $("#imacocoUsers").html("(全体:" + d.points.length + "人)"); if (traceuser == 'all' && valid_users > 0) { var avg_lat = (min_lat + max_lat) / 2; var avg_lon = (min_lon + max_lon) / 2; var ct = new google.maps.LatLng(avg_lat, avg_lon); if (valid_users == 1) { map.setCenter(ct, 14); } else { // 全体が表示できる矩形座標を計算 var region = new google.maps.LatLngBounds(new google.maps.LatLng(min_lat, min_lon), new google.maps.LatLng(max_lat, max_lon)); // 全体が表示できるように位置とズームを設定 map.setCenter(ct, map.getBoundsZoomLevel(region)); } center = ct; } } ); } // プロットのON/OFFの切り替え function getCheck(obj) { var user = users[obj.id.substr(3)]; if (user) { user.watch = obj.checked; if (!obj.checked && user.prev_marker) { map.removeOverlay(user.prev_marker); user.prev_marker = null; } } } // 注目するユーザーを設定 function setTraceUser(username, magnify) { // まず全員のフラグをクリア for (var user in users) { users[user].trace = false; } if (username != '__nouser__' && isDefined(username, 'users')) { // alert("setTraceUser("+username+") user found"); // 引数のユーザーがいた var user = users[username]; user.trace = true; if (user.lat != 0 && user.lon != 0) { if (magnify != undefined) { map.setCenter(new google.maps.LatLng(user.lat, user.lon), magnify); } else { map.panTo(new google.maps.LatLng(user.lat, user.lon)); } center = map.getCenter(); } } var sel = document.getElementById("traceuser"); if (sel) { for (var idx = 0; idx < sel.length; idx++) { if (sel.options[idx].value == username) { sel.options.selectedIndex = idx; } } } traceuser = username; } // 描画モードを設定 function setPlotMode(mode) { plotmode = mode; var trace = ''; for (user in users) { if (users[user].trace) { trace = user; } initUser(user, users[user].watch); } if (trace != '') { users[trace].trace = true; } map.clearOverlays(); return false; } // ユーザー一覧をサーバから取得する function loadUserList(watch) { var request = GXmlHttp.create(); request.open("GET",api_site + "/api/user_list?id="+ new Date().getTime() , false); request.send(""); if (request.readyState == 4) { if (request.status != 200 || request.responseText == "") { return false; } var d = eval(request.responseText); if (!d) { // loadUserList(); return false; } if (d.result) { var sel = document.getElementById("traceuser"); if (sel) { sel.length = 2; sel.options[0].value = '__nouser__'; sel.options[0].text = "注目しない"; sel.options.selectedIndex = 0; sel.options[1].value = 'all'; sel.options[1].text = '全体'; } var list = ""; for (var i=0; i<d.list.length; i++) { var username = d.list[i].user; if (!users[username]) { initUser(username, watch); } if (sel) { sel.length++; sel.options[sel.length-1].value = username; sel.options[sel.length-1].text = username; } list += "<span id=\"status_" + username + "\">" + username + "</span><br>"; } var p = document.getElementById("userlist"); if (p) { p.innerHTML = list; } } } return false; } // ユーザー情報を初期化 function initUser(username, flag) { if (username) { var icon = new google.maps.MarkerImage(); icon.image = 'http://www.fujita-lab.com/imakoko' + "/user/" + encodeURIComponent(username) + ".png"; // [CHANGE] icon.iconAnchor = new google.maps.Point(0, 24); var mo = new Object(); mo.icon = icon; mo.clickable = false; user = new Object(); user.lat = 0; user.lon = 0; user.markeropts = markeropts; user.user_markeropts = mo; user.user_marker = new google.maps.Marker(new google.maps.LatLng(0,0), mo); user.linecolor = '#FF0000'; user.linewidth = 2; user.transparent = 0.8; user.watch = flag; user.trace = false; user.track = new Array(); user.plat = 0; user.plon = 0; user.points = ""; user.levels = ""; user.level_len = 0; user.last_level = ""; user.update = false; user.broadcast = ''; users[username] = user; } } // 地図の大きさを変える function setMapSize(w, h) { var d = document.getElementById("map"); if (d && d.style) { var center = map.getCenter(); d.style.width = w; d.style.height = h; map.checkResize(); map.panTo(center); } return false; } //----------------------------------------------- get_browser_width function get_browser_width() { if ( window.innerWidth ) { return window.innerWidth; } else if ( document.documentElement && document.documentElement.clientWidth != 0 ) { return document.documentElement.clientWidth; } else if ( document.body ) { return document.body.clientWidth; } return 0; } //----------------------------------------------- get_browser_height function get_browser_height() { if ( window.innerHeight ) { return window.innerHeight; } else if ( document.documentElement && document.documentElement.clientHeight != 0 ) { return document.documentElement.clientHeight; } else if ( document.body ) { return document.body.clientHeight; } return 0; } function resize() { var winWidth = get_browser_width(); var winHeight = get_browser_height(); var map_div = document.getElementById("map"); if (map_div && map_div.style) { var h = 0; map_div.style.width = (winWidth - 20) + "px"; if (apiview) { if (hidelist) { h = 20; } else { h = 60; } } else { if (hidelist) { h = 150; } else { h = 180; } } map_div.style.height = (winHeight - h) + "px"; } if( map ) { map.checkResize(); map.panTo(center); } } function updateOff() { if (prev_trace == "") { prev_trace = traceuser; setTraceUser('__nouser__'); } } function updateOn() { if (prev_trace != "") { setTraceUser(prev_trace); prev_trace = ""; } } var rmenu; var rmenu_lat; var rmenu_lon; var rmenu_marker; function addMarker() { if (!isDefined('group_name') || group_name == '') { alert('グループ表示モードではありません'); return; } var req = GXmlHttp.create(); var el_desc = document.getElementById("desc"); var data = "group=" + encodeURIComponent(group_name) + "&desc=" + encodeURIComponent(el_desc.value) + "&lat=" + rmenu_lat + "&lon=" + rmenu_lon; req.open("POST", "/user/addmarker" , false); req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); req.send(data); if (req.status != 200 || req.responseText == "") { alert('サーバでエラーが発生しました'); return false; } var res = eval(req.responseText); // 情報ウィンドウ内のHTML if (res && res.result) { alert('登録しました'); return true; } else { alert('サーバでエラーが発生しました:' + res.errmsg); return false; } } function putMarker() { rmenu.style.visibility = "hidden"; rmenu_marker = new google.maps.Marker(new google.maps.LatLng(rmenu_lat, rmenu_lon)); map.addOverlay(rmenu_marker); google.maps.event.addListener(rmenu_marker, 'infowindowclose', function() { map.removeOverlay(rmenu_marker); updateOn(); }); rmenu_marker.openInfoWindow( "説明:<br>" + "<textarea id='desc' rows='4' cols='40'></textarea><br>" + "<button onClick='if (addMarker()) { rmenu_marker.closeInfoWindow(); }'>登録</button><button onClick='rmenu_marker.closeInfoWindow()'>キャンセル</button>" ); } function showAddress(address) { geocoder.getLatLng(address, function(point) { if (!point) { alert(address + " not found"); } else { map.panTo(point); rmenu_lat = point.lat(); rmenu_lon = point.lng(); putMarker(); } } ); } function openSearchWindow() { rmenu.style.visibility = "hidden"; map.openInfoWindow(new google.maps.LatLng(rmenu_lat, rmenu_lon), "Googleマップで検索<br><input size='40' id='keyword'><button onClick='showAddress(document.getElementById(\"keyword\").value)'>検索</button><button onClick='map.closeInfoWindow()'>キャンセル</button>" ); } function CancelEvent(event) { e = event; if (typeof e.preventDefault == 'function') e.preventDefault(); if (typeof e.stopPropagation == 'function') e.stopPropagation(); if (window.event) { window.event.cancelBubble = true; // for IE window.event.returnValue = false; // for IE } } function SignatureBox() {} /* SignatureBox.prototype = new GControl(); SignatureBox.prototype.initialize = function(map) { container = document.createElement("div"); container.style.border = "0px"; container.style.padding = "0px 0px 0px 0px"; container.style.textAlign = "center"; container.innerHTML = '<a href="http://imakoko-gps.appspot.com/" target="_blank"><img src="http://www.fujita-lab.com/imakoko/imakoko.png" height="33" width="114" border="0"></a>'; map.getContainer().appendChild(container); return container; } SignatureBox.prototype.getDefaultPosition = function() { return new ControlPosition(G_ANCHOR_BOTTOM_LEFT, new google.maps.Size(2, 34)); } */ function DateTimeBox() {} /* DateTimeBox.prototype = new GControl(); DateTimeBox.prototype.initialize = function(map) { container = document.createElement("div"); container.id = "DateTime"; container.style.border = "0px"; container.style.padding = "0px 0px 0px 0px"; container.style.textAlign = "left"; // container.style.backgroundColor container.style.color = 'black'; container.style.fontSize = "12px"; container.innerHTML = ''; map.getContainer().appendChild(container); return container; } DateTimeBox.prototype.getDefaultPosition = function() { return new ControlPosition(G_ANCHOR_TOP_RIGHT, new google.maps.Size(6, 28)); } */ function initialize() { if (isDefined('api_view')) { apiview = api_view; } if (isDefined('hide_userlist') && hide_userlist) { var ul = document.getElementById('right'); if (ul) { ul.style.display = 'none'; } var footer = document.getElementById('footer'); if (footer) { footer.style.display = 'none'; } hidelist = 1; } if (isDefined('map_maximize') && map_maximize) { window.onresize = function() { resize(); } resize(); } /* if (isDefined('use_osm') && use_osm) { var copyOSM = new GCopyrightCollection("<a href=\"http://www.openstreetmap.org/\">OpenStreetMap</a>"); copyOSM.addCopyright(new GCopyright(1, new google.maps.LatLngBounds(new google.maps.LatLng(-90,-180), new google.maps.LatLng(90,180)), 0, " ")); var tilesMapnik = new GTileLayer(copyOSM, 1, 17, {tileUrlTemplate: 'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png'}); var tilesOsmarender = new GTileLayer(copyOSM, 1, 17, {tileUrlTemplate: 'http://tah.openstreetmap.org/Tiles/tile/{Z}/{X}/{Y}.png'}); var mapMapnik = new GMapType([tilesMapnik], G_NORMAL_MAP.getProjection(), "Mapnik"); var mapOsmarender = new GMapType([tilesOsmarender], G_NORMAL_MAP.getProjection(), "Osmarend"); myMapTypes.push(mapMapnik); myMapTypes.push(mapOsmarender); } map = new google.maps.Map(document.getElementById('map'), { mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE, map_style] }, center : new google.maps.LatLng(35.658634, 139.745411), mapTypeId: map_style, scaleControl : true, streetViewControl : false, zoom : 10 }); */ // Google Maps API v3 if(map_style){ map = new google.maps.Map(document.getElementById('map'), { mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE, map_style] }, center : new google.maps.LatLng(35.658634, 139.745411), mapTypeId: map_style, scaleControl : true, streetViewControl : false, zoom : 10 }); if(map_style == "OSM"){ var mapTypeIds = []; for(var type in google.maps.MapTypeId) { mapTypeIds.push(google.maps.MapTypeId[type]); } mapTypeIds.push("OSM"); map.mapTypes.set("OSM", new google.maps.ImageMapType({ getTileUrl: function(coord, zoom) { return "http://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png"; }, tileSize: new google.maps.Size(256, 256), name: "OpenStreetMap", maxZoom: 18 })); }else{ var styledMapType = new google.maps.StyledMapType(styles[map_style], {name: map_style}); map.mapTypes.set(map_style, styledMapType); } }else{ map = new google.maps.Map(document.getElementById('map'), { center : new google.maps.LatLng(35.658634, 139.745411), mapTypeId : google.maps.MapTypeId.ROADMAP, scaleControl : true, streetViewControl : false, zoom : 10 }); } map.mapTypes.set("OSM", new google.maps.ImageMapType({ getTileUrl: function(coord, zoom) { return "http://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png"; }, tileSize: new google.maps.Size(256, 256), name: "OpenStreetMap", maxZoom: 18 })); geocoder = new google.maps.Geocoder() if (!isDefined('use_zoom')) { use_zoom = 2; } /* if (!isDefined('use_zoom') || use_zoom) { if ($(document.body).innerHeight() > 600) { // [CHANGE] map.addControl(new GLargeMapControl(), new ControlPosition(G_ANCHOR_TOP_LEFT, new google.maps.Size(5, 50))); // [CHANGE] } else { // [CHANGE] map.addControl(new GSmallMapControl(), new ControlPosition(G_ANCHOR_TOP_LEFT, new google.maps.Size(5, 50))); // [CHANGE] } map.enableContinuousZoom(); map.enableDoubleClickZoom(); map.enableScrollWheelZoom(); google.maps.event.addDomListener(map, "DOMMouseScroll", CancelEvent); // Firefox google.maps.event.addDomListener(map, "mousewheel", CancelEvent); // IE } */ /* controlGMapType = new GMapTypeControl(); // [CHANGE] map.addControl(controlGMapType, new ControlPosition(G_ANCHOR_TOP_RIGHT, new google.maps.Size(315, 5))); // [CHANGE] map.addControl(new GScaleControl(), new ControlPosition(G_ANCHOR_TOP_LEFT, new google.maps.Size(75, 90))); // [CHANGE] */ // new GKeyboardHandler(map); // [ADD] // [ADD] if(!movie_enable){ // map.removeControl(controlGMapType); // map.addControl(controlGMapType, new ControlPosition(G_ANCHOR_TOP_RIGHT, new google.maps.Size(10, 5))); $("#info").css("right", 10); } if (!isDefined('use_minimap') || use_minimap) { // map.addControl(new GOverviewMapControl()); } // map.addControl(new SignatureBox(), new ControlPosition(G_ANCHOR_TOP_LEFT, new google.maps.Size(75, 45))); // [CHANGE] // map.addControl(new DateTimeBox()); // [CHANGE] // datetimebox = document.getElementById("DateTime"); // [CHANGE] // google.maps.event.addListener(map, "click", openMenu); // google.maps.event.addListener(map, "mousedown", updateOff); if (isDefined('map_region')) { var min_lat = 91; var min_lon = 181; var max_lat = -91; var max_lon = -181; for (var idx in map_region) { if (map_region[idx].lat < min_lat) { min_lat = map_region[idx].lat; } if (max_lat < map_region[idx].lat) { max_lat = map_region[idx].lat; } if (map_region[idx].lon < min_lon) { min_lon = map_region[idx].lon; } if (max_lon < map_region[idx].lon) { max_lon = map_region[idx].lon; } } var avg_lat = (min_lat + max_lat) / 2; var avg_lon = (min_lon + max_lon) / 2; var ct = new google.maps.LatLng(avg_lat, avg_lon); // 全体が表示できる矩形座標を計算 var region = new google.maps.LatLngBounds(new google.maps.LatLng(min_lat, min_lon), new google.maps.LatLng(max_lat, max_lon)); // 全体が表示できるように位置とズームを設定 map.setCenter(ct, map.getBoundsZoomLevel(region)); center = ct; } else { var point = new google.maps.LatLng(35.658634, 139.745411); // 初期位置は東京タワー map.setCenter(point, 14); center = point; } if (isDefined('use_rmenu') && use_rmenu) { rmenu = document.createElement("div"); var MapPX = map.getSize(); //右クリックメニューのスタイルを設定。 rmenu.style.visibility = "hidden"; rmenu.style.backgroundColor = "white"; rmenu.style.border = "2px solid black"; rmenu.style.padding = "2px"; rmenu.style.fontSize = "12px"; rmenu.style.cursor = "pointer"; //右クリックメニューの内容(HTML) rmenu.innerHTML = "<div onclick='putMarker()'>この場所を共有する</div><hr>" + "<div onclick='openSearchWindow()'>Googleマップで検索</div>"; //右クリックメニューをmap内に返す map.getContainer().appendChild(rmenu); //右クリック位置を取得してメニューを表示するイベント。pointはgoogle.maps.Size(x,y)で返される。 google.maps.event.addListener(map, "singlerightclick", function(point) { updateOff(); var rmenux = point.x; var rmenuy = point.y; var latlng = map.fromContainerPixelToLatLng(point) rmenu_lat = latlng.lat(); rmenu_lon = latlng.lng(); //MapPX.width、MapPX.heightの後の74・86はメニュー全体の横幅・縦幅。 if(rmenux > (MapPX.width - 74)) { rmenux = MapPX.width - 74; } if(rmenuy > (MapPX.height - 86)) { rmenuy = MapPX.height - 86; } var rmenu_pos = new ControlPosition(G_ANCHOR_TOP_LEFT, new google.maps.Size(rmenux, rmenuy)); rmenu_pos.apply(rmenu); rmenu.style.visibility = "visible"; }); //地図上を左クリックしたらメニューが消える。 google.maps.event.addListener(map, "click", function() { if (rmenu.style.visibility == "visible"){ rmenu.style.visibility = "hidden"; } if (!map.infoWindowEnabled()) { updateOn(); } } ); } var icon = new google.maps.MarkerImage(); icon.image = static_file_site + "aka.png"; icon.iconSize = new google.maps.Size(4, 4); icon.iconAnchor = new google.maps.Point(0, 0); // 標準マーカーの作成 for (var i=0; i<360; i++) { defaultDirectionIcon[i] = makeDirectionIcon(i, 0); } for (var i=0; i<iconImage.length; i++) { directionIcon[i] = makeDirectionIcon(NaN, i); } markeropts = new Object(); markeropts.icon = icon; markeropts.clickable = false; if (isDefined('plot_mode')) { plotmode = plot_mode; } if (isDefined('plot_count')) { plotcount = plot_count; } if (isDefined('from_top')) { fromtop = from_top; } users = new Object(); if (hidelist) { if (isDefined('user_list') && user_list[0] == 'all') { setTraceUser('all'); } } else { if (!isDefined('user_list')) { // loadUserList(false); } else if (user_list[0] == 'all') { // loadUserList(true); setTraceUser('all'); } else { for (var u in user_list) { initUser(user_list[u], true); } } } setTimeout(load_next, 10); } function load_next() { if (isDefined('trace_user')) { if (trace_user != 'all' && trace_user != '__nouser__') { initUser(trace_user, true); } setTraceUser(trace_user); } if (!isDefined('use_update') || use_update) { update(); timer = window.setInterval(update, 10000); // [CHANGE] } } if (typeof use_onload != 'undefined' && use_onload) { window.onload = initialize; } /* * ==================================================================================================== * GPS Live Tracking : Shintaro Inagaki (2008/07/24) * ==================================================================================================== */ var reloadId; var twitterReloadTime = 60 * 1000; var tw_tl_id = 1; var geoCache = null; var docomoMap = null; var emobileMap = null; var uqwimaxMap = null; var geocoder = new google.maps.Geocoder(); $("#address").hide(); $("#chat").hide(); $("#accordion").accordion({ autoHeight: false, collapsible: true }); // Twitterメッセージ表示幅の設定 $("#twitter").css("width", $(document.body).innerWidth() - 455); $(window).bind( 'resize', function() { $("#twitter").css("width", $(document.body).innerWidth() - 455); } ); $("#loadGeocaching").click( function() { if (!geoCache) { geoCache = new GGeoXml("/img/gpslive/japanCaches-target.kml"); // 2008/08/09 } if (this.checked) { map.addOverlay(geoCache); } else { map.removeOverlay(geoCache); } } ); $("#loadDocomo").click( function() { if (!docomoMap) { docomoMap = new GGroundOverlay(static_file_site + "gpslive/layer_docomo_201106.png", new google.maps.LatLngBounds(new google.maps.LatLng(21.75, 120), new google.maps.LatLng(48, 146.25))); // 2011/06 } if (this.checked) { map.addOverlay(docomoMap); } else { map.removeOverlay(docomoMap); } } ); $("#loadEmobile").click( function() { if (!emobileMap) { emobileMap = new GGroundOverlay(static_file_site + "gpslive/layer_emobile_201106.png", new google.maps.LatLngBounds(new google.maps.LatLng(23, 123), new google.maps.LatLng(47, 147))); // 2011/06 } if (this.checked) { map.addOverlay(emobileMap); } else { map.removeOverlay(emobileMap); } } ); $("#loadUqwimax").click( function() { if (!uqwimaxMap) { uqwimaxMap = new GGroundOverlay(static_file_site + "gpslive/layer_uqwimax_201106.png", new google.maps.LatLngBounds(new google.maps.LatLng(25.435, 126.86), new google.maps.LatLng(44.57, 144.94))); // 2011/06 } if (this.checked) { map.addOverlay(uqwimaxMap); } else { map.removeOverlay(uqwimaxMap); } } ); $("#changeMoviePlayerUst").click( function() { $("#justin").hide("fast", function () { $("#ustream").show("fast"); }); $("#movieSize span.moviePlayer:eq(0)").css("background-color", "yellow"); $("#movieSize span.moviePlayer:not(:eq(0))").css("background-color", ""); return false; } ); $("#changeMoviePlayerJtv").click( function() { $("#ustream").hide("fast", function () { $("#justin").show("fast"); }); $("#movieSize span.moviePlayer:eq(1)").css("background-color", "yellow"); $("#movieSize span.moviePlayer:not(:eq(1))").css("background-color", ""); return false; } ); $("#changeMovieSizeBig").click( function() { $("#movie, #moviePlayer, #ustream, #justin, #ustFlash, #jtvFlash").css("width", 400); $("#moviePlayer, #ustream, #justin, #ustFlash, #jtvFlash").css("height", 320); $("#moviePlayer").show("normal"); map.removeControl(controlGMapType); map.addControl(controlGMapType, new ControlPosition(G_ANCHOR_TOP_RIGHT, new google.maps.Size(415, 5))); $("#info").css("right", 415); $("#movieSize span.movieSize:eq(0)").css("background-color", "yellow"); $("#movieSize span.movieSize:not(:eq(0))").css("background-color", ""); return false; } ); $("#changeMovieSizeNormal").click( function() { $("#movie, #moviePlayer, #ustream, #justin, #ustFlash, #jtvFlash").css("width", 300); $("#moviePlayer, #ustream, #justin, #ustFlash, #jtvFlash").css("height", 240); $("#moviePlayer").show("normal"); map.removeControl(controlGMapType); map.addControl(controlGMapType, new ControlPosition(G_ANCHOR_TOP_RIGHT, new google.maps.Size(315, 5))); $("#info").css("right", 315); $("#movieSize span.movieSize:eq(1)").css("background-color", "yellow"); $("#movieSize span.movieSize:not(:eq(1))").css("background-color", ""); return false; } ); $("#changeMovieSizeSmall").click( function() { $("#movie, #moviePlayer, #ustream, #justin, #ustFlash, #jtvFlash").css("width", 200); $("#moviePlayer, #ustream, #justin, #ustFlash, #jtvFlash").css("height", 160); $("#moviePlayer").show("normal"); map.removeControl(controlGMapType); map.addControl(controlGMapType, new ControlPosition(G_ANCHOR_TOP_RIGHT, new google.maps.Size(220, 5))); $("#info").css("right", 215); $("#movieSize span.movieSize:eq(2)").css("background-color", "yellow"); $("#movieSize span.movieSize:not(:eq(2))").css("background-color", ""); return false; } ); $("#changeMovieSizeHide").click( function() { $("#moviePlayer").hide("normal"); map.removeControl(controlGMapType); map.addControl(controlGMapType, new ControlPosition(G_ANCHOR_TOP_RIGHT, new google.maps.Size(220, 5))); $("#info").css("right", 5); $("#movieSize span.movieSize:eq(3)").css("background-color", "yellow"); $("#movieSize span.movieSize:not(:eq(3))").css("background-color", ""); return false; } ); $("#movieSize span.movieSize:eq(1)").css("background-color", "yellow"); $("#movieSize span.moviePlayer:eq(0)").css("background-color", "yellow"); $("#changeChatSizeShow").click( function() { $("#chat").show("normal"); $("#chatSize span.chatSize:eq(0)").css("background-color", "yellow"); $("#chatSize span.chatSize:not(:eq(0))").css("background-color", ""); return false; } ); $("#changeChatSizeHide").click( function() { $("#chat").hide("normal"); $("#chatSize span.chatSize:eq(1)").css("background-color", "yellow"); $("#chatSize span.chatSize:not(:eq(1))").css("background-color", ""); return false; } ); $("#chatSize span.chatSize:eq(1)").css("background-color", "yellow"); // Twitter reloadId = setTimeout(twitterUpdate, 0); function twitterUpdate() { // Twitter読み込み if(twitter_id){ // getTwitterSearch(); } // 逆ジオコーディング if(userExist){ geocoder.getLocations(nowPoint, geocoding); } reloadId = setTimeout(twitterUpdate, twitterReloadTime); } function getTwitterSearch() { var tweet = new Array(); $.ajax( { type : 'GET', url : 'http://search.twitter.com/search.json?q=' + twitter_id, data : { // since_id : tw_tl_id }, dataType : 'jsonp', success : function(json) { for ( var i = json.results.length - 1; i >= 0; i--) { var tw_tl_text = json.results[i]['text']; tw_tl_text = replaceURLWithHTMLLinks(tw_tl_text); var tw_tl_user = json.results[i]['from_user']; var tw_tl_image_url = json.results[i]['profile_image_url']; var tw_tl_created_at = json.results[i]['created_at']; var created_at = tw_tl_created_at.split(" "); // Safari対応 Saf = /a/.__proto__ == '//' if (Saf) { var post_date = new Date(created_at[1] + " " + created_at[2] + ", " + created_at[3] + " " + created_at[4]); } else { var post_date = new Date(created_at[4] + " " + created_at[1] + ", " + created_at[2] + " " + created_at[3]); } post_date.setHours(post_date.getHours() + 9); var year = post_date.getFullYear(); var month = post_date.getMonth() + 1; var day = post_date.getDate(); var hour = post_date.getHours(); hour = (hour < 10) ? "0" + hour : hour; var min = post_date.getMinutes(); min = (min < 10) ? "0" + min : min; var sec = post_date.getSeconds(); sec = (sec < 10) ? "0" + sec : sec; var formated_time = year + '/' + month + '/' + day + ' ' + hour + ':' + min + ':' + sec; if(twitter_id.toLowerCase() == tw_tl_user.toLowerCase()){ tw_tl_text = '<span style="color:#acf;">' + tw_tl_text + '</span>'; } if(json.results[i]['id'] > tw_tl_id){ tweet.unshift('<img src="' + tw_tl_image_url + '" width="16" height="16" />' + '<strong><a href="http://twitter.com/' + tw_tl_user + '" target="_blank">' + tw_tl_user + '</a></strong> ' + tw_tl_text + ' <span class="timeNew">(' + formated_time + ')</span>'); tw_tl_id = json.results[i]['id']; }else{ tweet.unshift('<img src="' + tw_tl_image_url + '" width="16" height="16" />' + '<strong><a href="http://twitter.com/' + tw_tl_user + '" target="_blank">' + tw_tl_user + '</a></strong> ' + tw_tl_text + ' <span class="time">(' + formated_time + ')</span>'); } if (tweet.length > 6) { tweet.pop(); } } }, complete : function() { tweets = ""; for ( var i = 0; i < tweet.length; i++) { tweets += tweet[i] + '<br />'; } $("#twitter").html(tweets); } }); } function geocoding(response) { if (!response || response.Status.code != 200) { $("#address").fadeOut("slow").html(""); } else { var results = response.Placemark; var geocodeAddress = null; var geocodeRoadName = null; var hasAddressFlag = false; for(i=0; i < results.length; i++){ if (!hasAddressFlag && results[i].AddressDetails.Accuracy != 5 && results[i].AddressDetails.Accuracy != 6) { if(results[i].address.indexOf("日本, 〒") == 0){ geocodeAddress = results[i].address.substring(14); }else if(results[i].address.indexOf("日本, ") == 0){ geocodeAddress = results[i].address.substring(4); }else{ geocodeAddress = results[i].address; } hasAddressFlag = true; }else if(results[i].AddressDetails.Accuracy == 6 ){ if(results[i].AddressDetails.Country.Thoroughfare.ThoroughfareName){ geocodeRoadName = results[i].AddressDetails.Country.Thoroughfare.ThoroughfareName; } } } if(!geocodeAddress){ geocodeAddress = "?"; }else if(geocodeRoadName){ geocodeAddress += '<span class="roadName">(' + geocodeRoadName + ')</span>'; } if($("#address").html() == ""){ $("#nickname").hide("slow"); $("#address").html(geocodeAddress).fadeIn("slow"); }else if($("#address").html() != geocodeAddress){ $("#address").fadeOut("slow", function() { $("#address").html(geocodeAddress).fadeIn("slow"); }); } } } function distanceInit(username, lat, lon, nickname) { tmp = new Object(); tmp.lat = lat; tmp.lon = lon; if(nickname.length > 12){ tmp.nickname = nickname.substr(0, 12) + '…'; }else{ tmp.nickname = nickname; } tmp.dist = 0; tmp.kyori = ""; tmp.heading = 0; tmp.houi = ""; distance[username] = tmp; } function distanceCalc(username, from, to) { var fromX = from.lngRadians(); var fromY = from.latRadians(); var toX = to.lngRadians(); var toY = to.latRadians(); var earthRadius = 6378137; var deltaX = earthRadius * (toX - fromX) * Math.cos(fromY); var deltaY = earthRadius * (toY - fromY); var dist = Math.sqrt( Math.pow(deltaX, 2) + Math.pow(deltaY, 2) ); var dist2 = ""; var heading = null; if(dist > 1000){ kyori = Math.round(dist/1000*10)/10; kyori = kyori + " km"; }else{ kyori = Math.round(dist*10)/10; kyori = "<strong>" + kyori + " m</strong>"; } if(deltaX >= 0){ heading = 90 - Math.atan(deltaY/deltaX) / Math.PI * 180; }else{ heading = 90 - Math.atan(deltaY/deltaX) / Math.PI * 180 + 180; } distance[username].dist = dist; distance[username].kyori = kyori; distance[username].heading = heading; distance[username].houi = headingToHoui(heading); } function headingToHoui(heading) { var houi = 0; if (heading < 11.25 || heading >= 348.75) { houi = "0"; }else if (heading < 33.75) { houi = "1"; }else if (heading < 56.25) { houi = "2"; }else if (heading < 78.75) { houi = "3"; }else if (heading < 101.25) { houi = "4"; }else if (heading < 123.75) { houi = "5"; }else if (heading < 146.25) { houi = "6"; }else if (heading < 168.75) { houi = "7"; }else if (heading < 191.25) { houi = "8"; }else if (heading < 213.75) { houi = "9"; }else if (heading < 236.25) { houi = "10"; }else if (heading < 258.75) { houi = "11"; }else if (heading < 281.25) { houi = "12"; }else if (heading < 303.75) { houi = "13"; }else if (heading < 326.25) { houi = "14"; }else{ houi = "15"; } return houi; } function replaceURLWithHTMLLinks(text) { var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i; return text.replace(exp,"<a href='$1' target='_blank'>$1</a>"); } });
var test = require('tape') var extract = require('./') test('simple case', function(t) { var args = ['node', 'index.js', '-t', 'transform'] var argv = extract(args, { t: String }) t.deepEqual(args, ['node', 'index.js']) t.deepEqual(argv, { t: ['transform'] }) t.end() }) test('booleans do not capture next argument', function(t) { var args = ['node', 'index.js', '-t', 'transform'] var argv = extract(args, { t: Boolean }) t.deepEqual(args, ['node', 'index.js', 'transform']) t.deepEqual(argv, { t: true }) t.end() }) test('shorthand args can be excluded individually', function(t) { var args = ['node', 'index.js', '-xyz', 'thing'] var argv = extract(args, { x: Boolean, z: String }) t.deepEqual(args, ['node', 'index.js', '-y']) t.deepEqual(argv, { x: true, z: ['thing'] }) t.end() }) test('ignore after --', function(t) { var args = ['node', 'index.js', '-t', 'transform', '--', '-c', 'another'] var argv = extract(args, { t: Boolean, c: String }) t.deepEqual(args, ['node', 'index.js', 'transform', '--', '-c', 'another']) t.deepEqual(argv, { t: true, c: [] }) t.end() })
import { RECEIVE_INTERIOR, RECEIVE_INTERIOR_MAIN } from '../actions'; import Immutable from 'immutable'; const defaultState = { interior: [], main: [] }; export default function interior(state = defaultState, action) { switch(action.type) { case RECEIVE_INTERIOR: const { interior } = action.payload; // console.log('RECEIVE_INTERIOR: ', action.payload) return Object.assign({}, state, { interior: interior }); case RECEIVE_INTERIOR_MAIN: const { interiorMain } = action.payload; // console.log('RECEIVE_INTERIOR_MAIN:', interiorMain) return Object.assign({}, state, { main: interiorMain }); default: return state; } }
import React from 'react'; import glob from 'styles/app'; import Col from 'react-bootstrap/lib/Col'; import wedding from '../../../../../config/wedding'; /** * * If invitation not found * * @param none * * @return {ReactComponent} */ const supportEmail = ( <a href={`mailto:${wedding.email}?Subject=RSVP not found`} className={glob.email}> {wedding.email} </a> ); const notFound = () => ( <Col xs={12}> <div className={`${glob.card} ${glob.fourOhFour}`}> <h2 style={{ marginTop: '0px' }}>Invitation not found</h2> <h5 style={{ marginBottom: '0px' }}> Please email <br /> {supportEmail} <br /> for support </h5> </div> </Col> ); export default notFound;
Ext.define('App.view.master.location.ListProvinces', { extend: 'Ext.grid.Panel', alias: 'widget.listprovincesGP', store: 'App.store.Provinces', emptyText: 'Empty Province', requires:[ 'App.form.combobox.cbCountries' ], columns: [ { xtype: 'rownumberer', flex: .3 }, { header: 'Name', flex: 1, dataIndex: 'name', editor: { allowBlank: true } }, { hidden: true, header: 'Country', flex: 1, dataIndex: 'parent_id', renderer: function(a,c,rec){ return rec.get('parent_name'); }, editor: { xtype: 'cbCountries', fieldLabel: '' } }, { header: 'Information', flex: 1, dataIndex: 'info', editor: { allowBlank: true } }, // { // header: 'UUID', flex: 1, // dataIndex: 'uuid' // }, // { // header: 'Action', // xtype: 'actioncolumn', // flex: .4, // items: [ // { // iconCls: 'delete', // tooltip: 'Delete', // handler: function (grid, rowIndex, colIndex) { // Ext.MessageBox.confirm('Confirm', 'Are you sure you want to do that?', function (btn, text) { // if (btn == 'yes') { // var rec = grid.getStore().getAt(rowIndex); // grid.getStore().remove(rec); // grid.getStore().sync(); // grid.getStore().load(); // } // }); // } // } // ] // } ], columnLines: true, selModel: 'rowmodel', /*========== Plugins ==========*/ plugins: [ Ext.create('Ext.grid.plugin.RowEditing', { clicksToEdit: !1, pluginId: 'cellEditorProvinces', clicksToMoveEditor: 1 }) ], /*========== DockedItems ==========*/ dockedItems: [ { xtype: 'toolbar', items: [ { action: 'add', text: 'Add', itemId: 'add', iconCls: 'add' }, { action: 'remove', text: 'Remove', itemId: 'remove', iconCls: 'delete', disabled: true } ] }, { xtype: 'pagingtoolbar', dock: 'bottom', store: 'App.store.Provinces', displayInfo: true } ], initComponent: function () { this.callParent(arguments); // Ext.getStore('Provinces').load(); // Ext.getStore(this.store).load(); } });
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var core_1 = require("@angular/core"); var AboutMe = (function () { function AboutMe() { } return AboutMe; }()); AboutMe = __decorate([ core_1.Component({ selector: 'about-me', templateUrl: "./html/about-me.component.html", styleUrls: ['./css/about-me.component.css'] }) ], AboutMe); exports.AboutMe = AboutMe; //# sourceMappingURL=about-me.component.js.map
import insertImage from "./insertImage"; const handleImage = (editorState, character, entityType) => { const re = /!\[([^\]]*)]\(([^)"]+)(?: "([^"]+)")?\)/g; const key = editorState.getSelection().getStartKey(); const text = editorState .getCurrentContent() .getBlockForKey(key) .getText(); const line = `${text}${character}`; let newEditorState = editorState; let matchArr; do { matchArr = re.exec(line); if (matchArr) { newEditorState = insertImage(newEditorState, matchArr, entityType); } } while (matchArr); return newEditorState; }; export default handleImage;
import 'react-native'; import React from 'react'; import renderer from 'react-test-renderer'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import ReduxThunk from 'redux-thunk'; import reducers from '../../src/reducers'; import { CustomSlidingView } from '../../src/components/common/CustomSlidingView'; test('renders correctly', () => { const store = createStore(reducers, {}, applyMiddleware(ReduxThunk)); const tree = renderer.create( <Provider store={store}> <CustomSlidingView threshold={5} tension={50} friction={10} heights={[100, 400]} isOpen clickEvent lockSlider /> </Provider> ).toJSON(); expect(tree).toMatchSnapshot(); });
var keyMirror = require('keymirror'); //eventのコードのmap module.exports = keyMirror({ UPDATE_TEXT: null });
game.resources = [ {name: "background-tiles", type:"image", src: "data/img/background-tiles.png"}, //loads background-tiles {name: "meta-tiles", type:"image", src: "data/img/meta-tiles.png"}, //loads meta-tiles {name: "player", type:"image", src: "data/img/orcSpear.png"}, {name: "tower", type:"image", src: "data/img/tower_round.svg.png"}, {name: "creep1", type:"image", src: "data/img/brainmonster.png"}, {name: "creep2", type:"image", src: "data/img/gloop.png"}, {name: "title-screen", type:"image", src: "data/img/title.png"}, {name: "exp-screen", type:"image", src: "data/img/loadpic.png"}, {name: "gold-screen", type:"image", src: "data/img/spend.png"}, {name: "new-screen", type:"image", src: "data/img/newpic.png"}, {name: "load-screen", type:"image", src: "data/img/loadpic.png"}, {name: "spear", type:"image", src: "data/img/spear.png"}, {name: "minimap", type:"image", src: "data/img/minimap.png"}, /* Graphics. * @example * {name: "example", type:"image", src: "data/img/example.png"}, */ /* Atlases * @example * {name: "example_tps", type: "tps", src: "data/img/example_tps.json"}, */ /* Maps. * @example * {name: "example01", type: "tmx", src: "data/map/example01.tmx"}, * {name: "example01", type: "tmx", src: "data/map/example01.json"}, */ {name: "level01", type: "tmx", src: "data/map/map.tmx"}, //loads test map /* Background music. * @example * {name: "example_bgm", type: "audio", src: "data/bgm/"}, */ {name: "katy1", type: "audio", src: "data/bgm/"} /* Sound effects. * @example * {name: "example_sfx", type: "audio", src: "data/sfx/"} */ ];
var data = [40050, 15060, 8900, 4700, 3800]; var total = 0, width = 400, height = 400, percentages = [], elements = []; // array.sort is failing me function qsort(a) { if (a.length == 0) return []; var left = [], right = [], pivot = a[0]; for (var i = 1; i < a.length; i++) { a[i] > pivot ? left.push(a[i]) : right.push(a[i]); } return qsort(left).concat(pivot, qsort(right)); } // place the largest data point first data = qsort(data); // total the data data.forEach(function(a) { total += a }); document.getElementById('data').innerHTML = '[' + data.join(', ').trim() + ']'; document.getElementById('total').innerHTML = total; data.forEach(function(a) { percentages.push(a / total * 100) }); var randomColour = function() { var result = Math.floor(Math.random() * 16777215).toString(16); if (result.length < 6) result += 0; return result; }; var remainingWidth = width, remainingHeight = height, remainingArea = remainingWidth * remainingHeight, remainingPer = 100; for (var i = 0; i < data.length; i++) { // get the next highest percentage var originalPer = percentages.shift(); // it is ordered // what percentage is our next highest of the remaining var per = originalPer / remainingPer; // adjust the remaining percentage remainingPer -= originalPer; var elw = remainingWidth; var elh = remainingHeight; if (i % 2 == 0) { elw = remainingWidth * per; remainingWidth -= elw; } else { elh = remainingHeight * per; remainingHeight -= elh; } var style = 'background-color:#' + randomColour() + ';'; style += 'width:' + elw + 'px;'; style += 'height:' + elh + 'px;'; var el = '<div class=\"leaf\" style=\"' + style + '\">' + originalPer.toFixed(2) + '%</div>'; elements.push(el); } var treemap = document.getElementById('treemap'); for (var i = 0; i < elements.length; i++) { treemap.innerHTML += elements[i]; }
var url = require('url'); var http = require('http'); var server = http.createServer(function(req, res) { var objUrl = url.parse(req.url); var data = ''; if(objUrl.pathname === '/api/parsetime') { var d = new Date(objUrl.query.slice(4, objUrl.query.length)); var time = {}; time["hour"] = d.getHours(); time["minute"] = d.getMinutes(); time["second"] = d.getSeconds(); data = JSON.stringify(time); res.writeHead(200, {"Content-Type": "application/json"}); } else if(objUrl.pathname === '/api/unixtime') { var d = new Date(objUrl.query.slice(4, objUrl.query.length)); var time = {}; time["unixtime"] = d.getTime(); data = JSON.stringify(time); res.writeHead(200, {"Content-Type": "application/json"}); } else { data = 'hello'; res.writeHead(200, {"Content-Type": "text/plain"}); } res.end(data); }); server.listen(process.argv[2]);
'use strict'; var proxyquire = require('proxyquire'); var EventEmitter = require('events').EventEmitter; var LiePromise = require('lie'); var VPAID_EVENTS = require('../../lib/enums/VPAID_EVENTS'); var HTML_MEDIA_EVENTS = require('../../lib/enums/HTML_MEDIA_EVENTS'); describe('HTMLVideo(container)', function() { var HTMLVideo; var environment, HTMLVideoTracker, EventProxy; var stubs; beforeEach(function() { environment = { canPlay: jasmine.createSpy('canPlay()').and.returnValue(2) }; HTMLVideoTracker = jasmine.createSpy('HTMLVideoTracker()').and.callFake(function(video) { var HTMLVideoTracker_ = require('../../lib/HTMLVideoTracker'); return new HTMLVideoTracker_(video); }); EventProxy = jasmine.createSpy('EventProxy()').and.callFake(function(events) { var EventProxy_ = require('../../lib/EventProxy'); var proxy = new EventProxy_(events); spyOn(proxy, 'from').and.callThrough(); spyOn(proxy, 'to').and.callThrough(); return proxy; }); stubs = { 'events': require('events'), 'lie': LiePromise, '../environment': environment, '../HTMLVideoTracker': HTMLVideoTracker, '../EventProxy': EventProxy, '@noCallThru': true }; HTMLVideo = proxyquire('../../lib/players/HTMLVideo', stubs); }); it('should exist', function() { expect(HTMLVideo).toEqual(jasmine.any(Function)); expect(HTMLVideo.name).toEqual('HTMLVideo'); }); describe('instance:', function() { var container; var player; beforeEach(function() { container = document.createElement('div'); container.style.width = '800px'; container.style.height = '600px'; document.body.appendChild(container); player = new HTMLVideo(container); }); afterEach(function() { document.body.removeChild(container); }); it('should exist', function() { expect(player).toEqual(jasmine.any(EventEmitter)); }); describe('properties:', function() { describe('container', function() { it('should be the container', function() { expect(player.container).toBe(container); }); }); describe('video', function() { it('should be null', function() { expect(player.video).toBeNull(); }); }); describe('adRemainingTime', function() { describe('before the video is loaded', function() { it('should throw an Error', function() { expect(function() { return player.adRemainingTime; }).toThrow(new Error('The <video> has not been loaded.')); }); }); describe('after the video is loaded', function() { beforeEach(function() { player.video = document.createElement('video'); player.video.currentTime = 10; player.video.duration = 30; }); it('should be the duration - currentTime', function() { expect(player.adRemainingTime).toBe(20); }); }); }); describe('adDuration', function() { describe('before the video is loaded', function() { it('should throw an Error', function() { expect(function() { return player.adDuration; }).toThrow(new Error('The <video> has not been loaded.')); }); }); describe('after the video is loaded', function() { beforeEach(function() { player.video = document.createElement('video'); player.video.duration = 60; }); it('should be the duration', function() { expect(player.adDuration).toBe(60); }); }); }); describe('adVolume', function() { describe('before the video is loaded', function() { describe('getting', function() { it('should throw an Error', function() { expect(function() { return player.adVolume; }).toThrow(new Error('The <video> has not been loaded.')); }); }); describe('setting', function() { it('should throw an Error', function() { expect(function() { player.adVolume = 0.8; }).toThrow(new Error('The <video> has not been loaded.')); }); }); }); describe('after the video is loaded', function() { beforeEach(function() { player.video = document.createElement('video'); player.video.volume = 0.75; }); describe('getting', function() { it('should be the volume', function() { expect(player.adVolume).toBe(0.75); }); }); describe('setting', function() { beforeEach(function() { player.adVolume = 0.2; }); it('should set the volume', function() { expect(player.video.volume).toBe(0.2); }); }); }); }); }); describe('methods:', function() { function trigger(target, eventName) { var event = document.createEvent('CustomEvent'); event.initCustomEvent(eventName); target.dispatchEvent(event); } describe('load(mediaFiles)', function() { var mediaFiles; var success, failure; var video; var result; beforeEach(function() { var createElement = document.createElement; mediaFiles = [ { type: 'video/x-flv', width: 300, height: 200, uri: 'http://videos.com/video1.flv' }, { type: 'video/x-flv', width: 400, height: 300, uri: 'http://videos.com/video2.flv' }, { type: 'video/x-flv', width: 500, height: 400, uri: 'http://videos.com/video3.flv' }, { type: 'video/webm', width: 300, height: 200, uri: 'http://videos.com/video1.webm' }, { type: 'video/webm', width: 400, height: 300, uri: 'http://videos.com/video2.webm' }, { type: 'video/webm', width: 500, height: 400, uri: 'http://videos.com/video3.webm' }, { type: 'video/mp4', width: 300, height: 200, uri: 'http://videos.com/video1.mp4' }, { type: 'video/mp4', width: 400, height: 300, uri: 'http://videos.com/video2.mp4' }, { type: 'video/mp4', width: 500, height: 400, uri: 'http://videos.com/video3.mp4' }, { type: 'video/3gp', width: 200, height: 100, uri: 'http://videos.com/video1.3gp' }, { type: 'video/3gp', width: 300, height: 200, uri: 'http://videos.com/video2.3gp' }, { type: 'video/3gp', width: 400, height: 300, uri: 'http://videos.com/video3.3gp' }, ]; success = jasmine.createSpy('success()'); failure = jasmine.createSpy('failure()'); spyOn(document, 'createElement').and.callFake(function(tagName) { var element = createElement.apply(document, arguments); if (tagName.toUpperCase() === 'VIDEO') { element.play = jasmine.createSpy('video.play()'); } return element; }); result = player.load(mediaFiles); result.then(success, failure); video = container.children[0]; }); it('should return a Promise', function() { expect(result).toEqual(jasmine.any(LiePromise)); }); it('should create a <video> in the container', function() { expect(container.children.length).toBe(1); expect(video.tagName).toBe('VIDEO'); expect(video.getAttribute('webkit-playsinline')).toBe('true'); expect(video.style.width).toBe('100%'); expect(video.style.height).toBe('100%'); expect(video.style.display).toBe('block'); expect(video.style.objectFit).toBe('contain'); expect(mediaFiles.map(function(mediaFile) { return mediaFile.uri; })).toContain(video.src); expect(video.preload).toBe('auto'); }); describe('when the video emits "playing"', function() { var AdImpression; beforeEach(function() { AdImpression = jasmine.createSpy('AdImpression()'); player.on(VPAID_EVENTS.AdImpression, AdImpression); trigger(video, HTML_MEDIA_EVENTS.PLAYING); }); it('should emit "AdImpression"', function() { expect(AdImpression).toHaveBeenCalled(); }); describe('twice', function() { beforeEach(function() { AdImpression.calls.reset(); trigger(video, HTML_MEDIA_EVENTS.PLAYING); }); it('should not emit "AdImpression" again', function() { expect(AdImpression).not.toHaveBeenCalled(); }); }); }); describe('when the video emits ' + HTML_MEDIA_EVENTS.ENDED, function() { beforeEach(function() { spyOn(player, 'stopAd').and.callThrough(); trigger(video, HTML_MEDIA_EVENTS.ENDED); }); it('should call stopAd() on itself', function() { expect(player.stopAd).toHaveBeenCalled(); }); }); describe('if the video is clicked', function() { var AdClickThru; beforeEach(function() { AdClickThru = jasmine.createSpy('AdClickThru()'); player.on(VPAID_EVENTS.AdClickThru, AdClickThru); trigger(video, 'click'); }); it('should emit "AdClickThru"', function() { expect(AdClickThru).toHaveBeenCalledWith(null, null, true); }); }); describe('when the video emits "loadedmetadata"', function() { var AdLoaded; var tracker, proxy; beforeEach(function(done) { AdLoaded = jasmine.createSpy('AdLoaded'); player.on(VPAID_EVENTS.AdLoaded, AdLoaded); video.duration = 60; trigger(video, HTML_MEDIA_EVENTS.LOADEDMETADATA); tracker = HTMLVideoTracker.calls.mostRecent().returnValue; proxy = EventProxy.calls.mostRecent().returnValue; result.then(done, done); }); it('should emit AdLoaded', function() { expect(AdLoaded).toHaveBeenCalled(); }); it('should save a reference to the video', function() { expect(player.video).toBe(video); }); it('should create a tracker for the video', function() { expect(HTMLVideoTracker).toHaveBeenCalledWith(video); }); it('should proxy from the tracker to the player', function() { expect(EventProxy).toHaveBeenCalledWith(VPAID_EVENTS); expect(proxy.from).toHaveBeenCalledWith(tracker); expect(proxy.to).toHaveBeenCalledWith(player); }); it('should fulfill the promise', function() { expect(success).toHaveBeenCalledWith(player); }); describe('and then emits "durationchange"', function() { var AdDurationChange; beforeEach(function() { AdDurationChange = jasmine.createSpy('AdDurationChange()'); player.on(VPAID_EVENTS.AdDurationChange, AdDurationChange); trigger(video, HTML_MEDIA_EVENTS.DURATIONCHANGE); }); it('should emit "AdDurationChange"', function() { expect(AdDurationChange).toHaveBeenCalled(); }); }); describe('and then emits "AdVolumeChange"', function() { var AdVolumeChange; beforeEach(function() { AdVolumeChange = jasmine.createSpy('AdVolumeChange()'); player.on(VPAID_EVENTS.AdVolumeChange, AdVolumeChange); trigger(video, HTML_MEDIA_EVENTS.VOLUMECHANGE); }); it('should emit "AdVolumeChange"', function() { expect(AdVolumeChange).toHaveBeenCalled(); }); }); }); describe('if the video emits "error"', function() { var AdError; beforeEach(function(done) { AdError = jasmine.createSpy('AdError()'); player.on(VPAID_EVENTS.AdError, AdError); video.error = new Error('It didn\'t play...'); trigger(video, HTML_MEDIA_EVENTS.ERROR); result.then(done, done); }); it('should emit "AdError"', function() { expect(AdError).toHaveBeenCalledWith(video.error.message); }); it('should reject the Promise', function() { expect(failure).toHaveBeenCalledWith(video.error); }); }); describe('when choosing a video to play', function() { function load(width, height) { container.innerHTML = ''; container.style.width = width + 'px'; container.style.height = height + 'px'; result = player.load(mediaFiles); return container.children[0]; } beforeEach(function() { environment.canPlay.and.callFake(function(type) { switch (type) { case 'video/mp4': case 'video/3gp': return 2; case 'video/webm': return 1; default: return 0; } }); }); it('should choose the video using the size of the container', function() { expect(load(300, 200).src).toBe('http://videos.com/video1.mp4', '300x200'); expect(load(400, 300).src).toBe('http://videos.com/video2.mp4', '400x300'); expect(load(500, 400).src).toBe('http://videos.com/video3.mp4', '500x400'); expect(load(200, 100).src).toBe('http://videos.com/video1.3gp', '200x100'); expect(load(300, 300).src).toBe('http://videos.com/video1.mp4', '300x300'); expect(load(290, 400).src).toBe('http://videos.com/video1.mp4', '290x400'); expect(load(375, 200).src).toBe('http://videos.com/video2.mp4', '375x200'); expect(load(460, 500).src).toBe('http://videos.com/video3.mp4', '460x500'); expect(load(1024, 768).src).toBe('http://videos.com/video3.mp4', '1024x768'); expect(load(50, 50).src).toBe('http://videos.com/video1.3gp', '50x50'); }); describe('if the mediaFiles have a bitrate', function() { beforeEach(function() { mediaFiles = [ { type: 'video/x-flv', width: 300, height: 200, uri: 'http://videos.com/video1.flv' }, { type: 'video/x-flv', width: 400, height: 300, uri: 'http://videos.com/video2.flv' }, { type: 'video/x-flv', width: 500, height: 400, uri: 'http://videos.com/video3.flv' }, { type: 'video/webm', width: 300, height: 200, uri: 'http://videos.com/video1.webm' }, { type: 'video/webm', width: 400, height: 300, uri: 'http://videos.com/video2.webm' }, { type: 'video/webm', width: 500, height: 400, uri: 'http://videos.com/video3.webm' }, { type: 'video/3gp', bitrate: 50, width: 200, height: 100, uri: 'http://videos.com/video1.3gp' }, { type: 'video/3gp', bitrate: 50, width: 300, height: 200, uri: 'http://videos.com/video2.3gp' }, { type: 'video/3gp', bitrate: 50, width: 400, height: 300, uri: 'http://videos.com/video3.3gp' }, { type: 'video/mp4', bitrate: 100, width: 300, height: 200, uri: 'http://videos.com/video1.mp4' }, { type: 'video/mp4', bitrate: 100, width: 400, height: 300, uri: 'http://videos.com/video2.mp4' }, { type: 'video/mp4', bitrate: 100, width: 500, height: 400, uri: 'http://videos.com/video3.mp4' }, ]; }); it('should prefer higher-bitrate videos', function() { expect(load(300, 200).src).toBe('http://videos.com/video1.mp4', '300x200'); expect(load(400, 300).src).toBe('http://videos.com/video2.mp4', '400x300'); expect(load(500, 400).src).toBe('http://videos.com/video3.mp4', '500x400'); expect(load(200, 100).src).toBe('http://videos.com/video1.3gp', '200x100'); }); }); describe('if there are no videos that can confidently play', function() { beforeEach(function() { mediaFiles = [ { type: 'video/x-flv', width: 300, height: 200, uri: 'http://videos.com/video1.flv' }, { type: 'video/x-flv', width: 400, height: 300, uri: 'http://videos.com/video2.flv' }, { type: 'video/x-flv', width: 500, height: 400, uri: 'http://videos.com/video3.flv' }, { type: 'video/webm', width: 300, height: 200, uri: 'http://videos.com/video1.webm' }, { type: 'video/webm', width: 400, height: 300, uri: 'http://videos.com/video2.webm' }, { type: 'video/webm', width: 500, height: 400, uri: 'http://videos.com/video3.webm' } ]; }); it('should use the videos that can maybe play', function() { expect(load(290, 400).src).toBe('http://videos.com/video1.webm', '290x400'); expect(load(375, 200).src).toBe('http://videos.com/video2.webm', '375x200'); expect(load(460, 500).src).toBe('http://videos.com/video3.webm', '460x500'); }); }); describe('if there are no playable videos', function() { beforeEach(function(done) { success.calls.reset(); failure.calls.reset(); mediaFiles = [ { type: 'video/x-flv', width: 300, height: 200, uri: 'http://videos.com/video1.flv' }, { type: 'video/x-flv', width: 400, height: 300, uri: 'http://videos.com/video2.flv' }, { type: 'video/x-flv', width: 500, height: 400, uri: 'http://videos.com/video3.flv' }, ]; load(1024, 768); result.then(success, failure); result.then(done, done); }); it('should reject the Promise', function() { expect(failure).toHaveBeenCalledWith(new Error('There are no playable <MediaFile>s.')); }); }); describe('if the closes match is unplayable', function() { beforeEach(function() { mediaFiles = [ { type: 'video/x-flv', bitrate: 50, width: 100, height: 50, uri: 'http://videos.com/video0.flv' }, { type: 'video/x-flv', width: 300, height: 200, uri: 'http://videos.com/video1.flv' }, { type: 'video/x-flv', width: 400, height: 300, uri: 'http://videos.com/video2.flv' }, { type: 'video/x-flv', width: 500, height: 400, uri: 'http://videos.com/video3.flv' }, { type: 'video/webm', width: 300, height: 200, uri: 'http://videos.com/video1.webm' }, { type: 'video/webm', width: 400, height: 300, uri: 'http://videos.com/video2.webm' }, { type: 'video/webm', width: 500, height: 400, uri: 'http://videos.com/video3.webm' }, { type: 'video/3gp', bitrate: 50, width: 200, height: 100, uri: 'http://videos.com/video1.3gp' }, { type: 'video/3gp', bitrate: 50, width: 300, height: 200, uri: 'http://videos.com/video2.3gp' }, { type: 'video/3gp', bitrate: 50, width: 400, height: 300, uri: 'http://videos.com/video3.3gp' }, { type: 'video/mp4', bitrate: 100, width: 300, height: 200, uri: 'http://videos.com/video1.mp4' }, { type: 'video/mp4', bitrate: 100, width: 400, height: 300, uri: 'http://videos.com/video2.mp4' }, { type: 'video/mp4', bitrate: 100, width: 500, height: 400, uri: 'http://videos.com/video3.mp4' }, ]; }); it('should not use it', function() { expect(load(100, 50).src).toBe('http://videos.com/video1.3gp'); }); }); describe('if no mediaFiles are provided', function() { beforeEach(function(done) { success.calls.reset(); failure.calls.reset(); mediaFiles = []; load(1024, 768); result.then(success, failure); result.then(done, done); }); it('should reject the Promise', function() { expect(failure).toHaveBeenCalledWith(new Error('There are no playable <MediaFile>s.')); }); }); }); }); describe('startAd()', function() { var success, failure; beforeEach(function() { success = jasmine.createSpy('success()'); failure = jasmine.createSpy('failure()'); }); describe('before the video is loaded', function() { beforeEach(function(done) { player.startAd().then(success, failure).then(done, done.fail); }); it('should reject the Promise', function() { expect(failure).toHaveBeenCalledWith(new Error('The <video> has not been loaded.')); }); }); describe('after the video is loaded', function() { var result; beforeEach(function(done) { player.load([{ type: 'video/mp4', bitrate: 100, width: 500, height: 400, uri: 'http://videos.com/video3.mp4' }]).then(function(player) { player.video.play = jasmine.createSpy('video.play()'); }).then(done, done.fail); trigger(container.children[0], HTML_MEDIA_EVENTS.LOADEDMETADATA); }); describe('and before it has played', function() { beforeEach(function() { result = player.startAd(); result.then(success, failure); }); it('should play the video', function() { expect(player.video.play).toHaveBeenCalledWith(); }); describe('when the video emits "playing"', function() { var AdStarted; beforeEach(function(done) { AdStarted = jasmine.createSpy('AdStarted()'); player.on(VPAID_EVENTS.AdStarted, AdStarted); trigger(player.video, HTML_MEDIA_EVENTS.PLAYING); result.then(done, done); }); it('should emit AdStarted', function() { expect(AdStarted).toHaveBeenCalled(); }); it('should fulfill the promise', function() { expect(success).toHaveBeenCalledWith(player); }); }); }); describe('and after is has played', function() { beforeEach(function(done) { trigger(player.video, HTML_MEDIA_EVENTS.PLAYING); result = player.startAd(); result.then(success, failure); result.then(done, done); }); it('should not play the video', function() { expect(player.video.play).not.toHaveBeenCalled(); }); it('should reject the Promise', function() { expect(failure).toHaveBeenCalledWith(new Error('The ad has already been started.')); }); }); }); }); describe('stopAd()', function() { var success, failure; beforeEach(function() { success = jasmine.createSpy('success()'); failure = jasmine.createSpy('failure()'); }); describe('before the video is loaded', function() { beforeEach(function(done) { player.stopAd().then(success, failure).then(done, done.fail); }); it('should reject the Promise', function() { expect(failure).toHaveBeenCalledWith(new Error('The <video> has not been loaded.')); }); }); describe('after the video is loaded', function() { var AdStopped; beforeEach(function(done) { AdStopped = jasmine.createSpy('AdStopped()'); player.on(VPAID_EVENTS.AdStopped, AdStopped); player.video = document.createElement('video'); container.appendChild(player.video); player.stopAd().then(success, failure).then(done, done.fail); }); it('should remove the video from the DOM', function() { expect(container.contains(player.video)).toBe(false, 'Video is still in the DOM!'); }); it('should emit AdStopped', function() { expect(AdStopped).toHaveBeenCalled(); }); it('should fulfill the Promise', function() { expect(success).toHaveBeenCalledWith(player); }); }); }); describe('pauseAd()', function() { var success, failure; beforeEach(function() { success = jasmine.createSpy('success()'); failure = jasmine.createSpy('failure()'); }); describe('before the video is loaded', function() { beforeEach(function(done) { player.pauseAd().then(success, failure).then(done, done.fail); }); it('should reject the Promise', function() { expect(failure).toHaveBeenCalledWith(new Error('The <video> has not been loaded.')); }); }); describe('after the video is loaded', function() { var result; beforeEach(function() { player.video = document.createElement('video'); player.video.pause = jasmine.createSpy('video.pause()'); player.video.paused = false; result = player.pauseAd(); result.then(success, failure); }); it('should pause the video', function() { expect(player.video.pause).toHaveBeenCalledWith(); }); describe('if the video is already paused', function() { beforeEach(function(done) { success.calls.reset(); failure.calls.reset(); player.video.pause.calls.reset(); player.video.paused = true; result = player.pauseAd(); result.then(success, failure); result.then(done, done); }); it('should not pause the video', function() { expect(player.video.pause).not.toHaveBeenCalled(); }); it('should fulfill the Promise', function() { expect(success).toHaveBeenCalledWith(player); }); }); describe('when the video emits "pause"', function() { var AdPaused; beforeEach(function(done) { AdPaused = jasmine.createSpy('AdPaused()'); player.on(VPAID_EVENTS.AdPaused, AdPaused); trigger(player.video, HTML_MEDIA_EVENTS.PAUSE); result.then(done, done); }); it('should emit AdPaused', function() { expect(AdPaused).toHaveBeenCalled(); }); it('should fulfill the promise', function() { expect(success).toHaveBeenCalledWith(player); }); }); }); }); describe('resumeAd()', function() { var success, failure; beforeEach(function() { success = jasmine.createSpy('success()'); failure = jasmine.createSpy('failure()'); }); describe('before the video is loaded', function() { beforeEach(function(done) { player.resumeAd().then(success, failure).then(done, done.fail); }); it('should reject the Promise', function() { expect(failure).toHaveBeenCalledWith(new Error('The <video> has not been loaded.')); }); }); describe('after the video is loaded', function() { var result; beforeEach(function(done) { player.load([{ type: 'video/mp4', bitrate: 100, width: 500, height: 400, uri: 'http://videos.com/video3.mp4' }]).then(function(player) { player.video.play = jasmine.createSpy('video.play()'); player.video.paused = true; }).then(done, done.fail); trigger(container.children[0], HTML_MEDIA_EVENTS.LOADEDMETADATA); }); describe('if the video has not been played', function() { beforeEach(function(done) { result = player.resumeAd(); result.then(success, failure); result.then(done, done); }); it('should not play the video', function() { expect(player.video.play).not.toHaveBeenCalled(); }); it('should reject the Promise', function() { expect(failure).toHaveBeenCalledWith(new Error('The ad has not been started yet.')); }); }); describe('if the video has been played', function() { beforeEach(function() { trigger(player.video, HTML_MEDIA_EVENTS.PLAYING); result = player.resumeAd(); result.then(success, failure); }); it('should play the video', function() { expect(player.video.play).toHaveBeenCalledWith(); }); describe('if the video is already playing', function() { beforeEach(function(done) { success.calls.reset(); failure.calls.reset(); player.video.play.calls.reset(); player.video.paused = false; result = player.resumeAd(); result.then(success, failure); result.then(done, done); }); it('should not play the video', function() { expect(player.video.play).not.toHaveBeenCalled(); }); it('should fulfill the Promise', function() { expect(success).toHaveBeenCalledWith(player); }); }); describe('when the video emits "play"', function() { var AdPlaying; beforeEach(function(done) { AdPlaying = jasmine.createSpy('AdPlaying()'); player.on(VPAID_EVENTS.AdPlaying, AdPlaying); trigger(player.video, HTML_MEDIA_EVENTS.PLAY); result.then(done, done); }); it('should emit AdPlaying', function() { expect(AdPlaying).toHaveBeenCalled(); }); it('should fulfill the promise', function() { expect(success).toHaveBeenCalledWith(player); }); }); }); }); }); }); }); });
'use strict';var Promise=require('../util/promise').Promise;var Status=require('./types').Status;var Conversion=require('./types').Conversion;var BlankArgument=require('./types').BlankArgument;var SelectionType=require('./selection').SelectionType;exports.items=[{ item:'type',name:'boolean',parent:'selection',getSpec:function(){return'boolean';},lookup:[{name:'false',value:false},{name:'true',value:true}],parse:function(arg,context){if(arg.type==='TrueNamedArgument'){return Promise.resolve(new Conversion(true,arg));} if(arg.type==='FalseNamedArgument'){return Promise.resolve(new Conversion(false,arg));} return SelectionType.prototype.parse.call(this,arg,context);},stringify:function(value,context){if(value==null){return'';} return''+value;},getBlank:function(context){return new Conversion(false,new BlankArgument(),Status.VALID,'',Promise.resolve(this.lookup));}}];
(function () { 'use strict'; angular.module("korann.api") .provider('api', function () { var services = {}; this.config = function (serviceName, apiPath) { services[serviceName] = apiPath; }; this.$get = ['apiProxy', function (apiProxy) { // #region initialization var operations = { get: function (path) { return function (id) { var args = [{ name: 'id', value: id }]; return apiProxy.get(path, args); }; }, getAll: function (path) { return function () { return apiProxy.get(path); }; }, getByCategory: function (path) { return function (category) { var args = [{ name: 'category', value: category }]; return apiProxy.get(path, args); }; } }; var builder = {}; for (var name in services) { builder[name] = {}; for (var key in operations) { builder[name][key] = operations[key](services[name]); } } // #region public functions return builder; // #region private functions }]; }); })();
const matches = document.querySelectorAll(`li[data-nav-id$="${window.location.pathname}"]`); if (matches.length > 0) { const menu = matches[0]; menu.classList.add("active"); let maxDepth = 10; // Avoid infinite loop ! let nextAncestor = menu.closest("li[data-nav-id]"); while (maxDepth-- >= 0 && nextAncestor !== null) { nextAncestor.classList.add("parent"); let icon = nextAncestor.querySelector('i.category-icon'); if (icon !== null) { icon.classList.remove('fa-angle-right'); icon.classList.add('fa-angle-down'); } nextAncestor = nextAncestor.parentNode.closest("li[data-nav-id]"); } }
function navService($timeout, $mdSidenav, $log, $rootScope) { /** * Supplies a function that will continue to operate until the * time is up. */ function debounce(func, wait, context) { var timer; return function debounced() { var args = Array.prototype.slice.call(arguments); $timeout.cancel(timer); timer = $timeout(function() { timer = undefined; func.apply(context, args); }, wait || 10); }; } /** * Build handler to open/close a SideNav; when animation finishes * report completion in console */ this.buildToggler = function(navID, context) { return debounce(function() { $mdSidenav(navID).toggle(); }, 200, context); } window.toggleMenu = this.buildToggler('left', $rootScope); } app.service("NavService", navService);
import React from 'react'; import { render } from 'react-dom'; import * as THREE from 'three'; import OrbitControls from './public/dist/OrbitControls' import Main from './components/Main/Main'; import TestView from './components/TestView'; import Header from './components/header/Header'; // import App from './components/App'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; class App extends React.Component { render(){ return ( <div> <Header /> <Main /> <p> Hello REACT!!</p> </div> ) } } render(<App />, document.getElementById('app'));
var Vue = require('lib/vue'); Vue.component('dropdown', { template: __inline('main.html'), props: { 'id': { type: String, 'default': '' }, 'css': { type: String, 'default': '' }, }, ready: function() { } });
module.exports = { remoteUrl : 'mongodb://caseweek:caseweek@jello.modulusmongo.net:27017/o2wijyWi', localUrl: 'mongodb://localhost:27017' };
define(function(require){ var app = require('app'); app.filter('languageFilter', function(data){ }); });
/* eslint-disable no-underscore-dangle */ const debug = require('debug'); const defaultsDeep = require('lodash.defaultsdeep'); const utils = require('../utils'); const { errCode } = utils; const Hs = require('./hs'); const defaultData = require('./data/hs300'); const logDebug = debug('DEBUG'); class Hs300 extends Hs { constructor(data) { super(data); defaultsDeep(this.data, defaultData); this.realtimeV2 = true; this.api['smartlife.iot.smartpowerstrip.manage'] = { get_relationship: errCode(() => { let slot = -1; return { data: Object.keys(this.data.children).map((childId) => { slot += 1; return { child_id: childId, hw_slot: slot }; }), }; }), }; this.api.context.child_ids = (childIds) => { logDebug('context.child_ids', childIds); this.currentContext = []; if (childIds == null || !Array.isArray(childIds)) { this.contextError = this.constructor.error.INVALID_ARGUMENT; return; } if (childIds.length === 0) { return; } for (const childId of childIds) { if ( childId in this.data.children && this.data.children[childId] != null ) { this.currentContext.push(this.data.children[childId]); } else { this.contextError = { err_code: -14, err_msg: 'entry not exist' }; return; } } if (this.currentContext.length === 0) { this.contextError = { err_code: -14, err_msg: 'entry not exist' }; } }; this.api.netif.get_stainfo = errCode(() => { return { ...this.data.netif.stainfo, rssi: this.data.system.sysinfo.rssi, }; }); } initDefaults() { super.initDefaults(); Object.keys(this.data.children).forEach((childId) => { const child = this.data.children[childId]; child.sysinfo.id = this.deviceId + childId; child.emeter = JSON.parse(JSON.stringify(this.data.emeter)); child.schedule = JSON.parse(JSON.stringify(this.data.schedule)); child.anti_theft = JSON.parse(JSON.stringify(this.data.anti_theft)); child.count_down = JSON.parse(JSON.stringify(this.data.count_down)); this.data.children[child.sysinfo.id] = child; delete this.data.children[childId]; }); } get currentContext() { logDebug('get currentContext', this._currentContext); return this._currentContext; } set currentContext(child) { this._currentContext = child; logDebug('set currentContext', this._currentContext); } get children() { return Object.keys(this.data.children).map( (childId) => this.data.children[childId] ); } get sysinfoChildren() { return Object.keys(this.data.children).map( (childId) => this.data.children[childId].sysinfo ); } get sysinfo() { const sysinfo = JSON.parse(JSON.stringify(this.data.system.sysinfo)); sysinfo.children = JSON.parse(JSON.stringify(this.sysinfoChildren)); return sysinfo; } get emeterContext() { return this.contextFirst.emeter; } get scheduleContext() { return this.contextFirst.schedule; } get antiTheftContext() { return this.contextFirst.anti_theft; } get countDownContext() { return this.contextFirst.count_down; } get relayState() { return this.contextFirst.sysinfo.state; } set relayState(relayState) { this.contextDefaultAll.forEach((ctx) => { ctx.sysinfo.state = relayState; }); } get contextDefaultAll() { if (this.contextError) throw this.contextError; if (this.currentContext == null) return this.children; return this.currentContext; } get contextDefaultFirst() { if (this.contextError) throw this.contextError; if (this.currentContext == null) return [this.children[0]]; return this.currentContext; } get contextFirst() { if (this.contextError) throw this.contextError; if (this.currentContext == null) return this.children[0]; return this.currentContext[0]; } } module.exports = Hs300;
Tracker.autorun(() => { });
describe("railsUrlBuilder", function () { 'use strict'; beforeEach(module('rails')); it('should return custom function', inject(function (railsUrlBuilder) { expect(railsUrlBuilder({ url: function () { return 'test' } })()).toEqualData('test') })); it('should return base url when no context object', inject(function (railsUrlBuilder) { expect(railsUrlBuilder({ url: '/books' })()).toEqualData('/books'); })); it('should append id', inject(function (railsUrlBuilder) { expect(railsUrlBuilder({ url: '/books', idAttribute: 'id' })({id: 1})).toEqualData('/books/1'); })); it('should not append id when singular', inject(function (railsUrlBuilder) { expect(railsUrlBuilder({ url: '/book', singular: true })()).toEqualData('/book'); })); it('should use author id for book list', inject(function (railsUrlBuilder) { expect(railsUrlBuilder({ url: '/authors/{{authorId}}/books/{{id}}', idAttribute: 'id' })({authorId: 1})).toEqualData('/authors/1/books'); })); it('should use author id and book id', inject(function (railsUrlBuilder) { expect(railsUrlBuilder({ url: '/authors/{{authorId}}/books/{{id}}', idAttribute: 'id' })({authorId: 1, id: 2})).toEqualData('/authors/1/books/2'); })); describe('custom idAttribute', function () { it('should use different id attribute', inject(function (railsUrlBuilder) { expect(railsUrlBuilder({ url: '/books', idAttribute: 'other_id' })({id: 1, other_id: 30})).toEqualData('/books/30'); })); }); describe('custom interpolation symbols', function() { beforeEach(module(function($interpolateProvider) { $interpolateProvider.startSymbol('--'); $interpolateProvider.endSymbol('--'); })); it('should append id', inject(function (railsUrlBuilder) { expect(railsUrlBuilder({ url: '/books', idAttribute: 'id' })({id: 1})).toEqualData('/books/1'); })); it('should use author id and book id', inject(function (railsUrlBuilder) { expect(railsUrlBuilder({ url: '/authors/--authorId--/books/--id--', idAttribute: 'id' })({authorId: 1, id: 2})).toEqualData('/authors/1/books/2'); })); }); });
// Copyright 2012 Iris Couch, all rights reserved. // // Encode DNS messages var util = require('util') var constants = require('./constants') module.exports = { 'State': State } var SECTIONS = ['question', 'answer', 'authority', 'additional'] function State () { var self = this self.header = Buffer.allocUnsafe(12) self.position = 0 self.question = [] self.answer = [] self.authority = [] self.additional = [] self.domains = {} // The compression lookup table } State.prototype.toBinary = function() { var self = this var bufs = [self.header] self.question .forEach(function(buf) { bufs.push(buf) }) self.answer .forEach(function(buf) { bufs.push(buf) }) self.authority .forEach(function(buf) { bufs.push(buf) }) self.additional.forEach(function(buf) { bufs.push(buf) }) return Buffer.concat(bufs) } State.prototype.message = function(msg) { var self = this // ID self.header.writeUInt16BE(msg.id, 0) // QR, opcode, AA, TC, RD var byte = 0 byte |= msg.type == 'response' ? 0x80 : 0x00 byte |= msg.authoritative ? 0x04 : 0x00 byte |= msg.truncated ? 0x02 : 0x00 byte |= msg.recursion_desired ? 0x01 : 0x00 var opcode_names = ['query', 'iquery', 'status', null, 'notify', 'update'] , opcode = opcode_names.indexOf(msg.opcode) if(opcode == -1 || typeof msg.opcode != 'string') throw new Error('Unknown opcode: ' + msg.opcode) else byte |= (opcode << 3) self.header.writeUInt8(byte, 2) // RA, Z, AD, CD, Rcode byte = 0 byte |= msg.recursion_available ? 0x80 : 0x00 byte |= msg.authenticated ? 0x20 : 0x00 byte |= msg.checking_disabled ? 0x10 : 0x00 byte |= (msg.responseCode & 0x0f) self.header.writeUInt8(byte, 3) self.position = 12 // the beginning of the sections SECTIONS.forEach(function(section) { var records = msg[section] || [] records.forEach(function(rec) { self.record(section, rec) }) }) // Write the section counts. self.header.writeUInt16BE(self.question.length , 4) self.header.writeUInt16BE(self.answer.length , 6) self.header.writeUInt16BE(self.authority.length , 8) self.header.writeUInt16BE(self.additional.length , 10) } State.prototype.record = function(section_name, record) { var self = this var body = [] , buf // Write the record name. buf = self.encode(record.name) body.push(buf) self.position += buf.length var type = constants.type_to_number(record.type) , clas = constants.class_to_number(record.class) // Write the type. buf = Buffer.allocUnsafe(2) buf.writeUInt16BE(type, 0) body.push(buf) self.position += 2 // Write the class. buf = Buffer.allocUnsafe(2) buf.writeUInt16BE(clas, 0) body.push(buf) self.position += 2 if(section_name != 'question') { // Write the TTL. buf = Buffer.allocUnsafe(4) buf.writeUInt32BE(record.ttl || 0, 0) body.push(buf) self.position += 4 // Write the rdata. Update the position now (the rdata length value) in case self.encode() runs. var match, rdata switch (record.class + ' ' + record.type) { case 'IN A': rdata = record.data || '' match = rdata.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/) if(!match) throw new Error('Bad '+record.type+' record data: ' + JSON.stringify(record)) rdata = [ +match[1], +match[2], +match[3], +match[4] ] break case 'IN AAAA': rdata = (record.data || '').split(/:/) if(rdata.length != 8) throw new Error('Bad '+record.type+' record data: ' + JSON.stringify(record)) rdata = rdata.map(pair_to_buf) break case 'IN MX': var host = record.data[1] rdata = [ buf16(record.data[0]) , self.encode(host, 2 + 2) // Adjust for the rdata length + preference values. ] break case 'IN SOA': var mname = self.encode(record.data.mname, 2) // Adust for rdata length , rname = self.encode(record.data.rname, 2 + mname.length) rdata = [ mname , rname , buf32(record.data.serial) , buf32(record.data.refresh) , buf32(record.data.retry) , buf32(record.data.expire) , buf32(record.data.ttl) ] break case 'IN NS': case 'IN PTR': case 'IN CNAME': rdata = self.encode(record.data, 2) // Adjust for the rdata length break case 'IN TXT': rdata = record.data.map(function(part) { part = Buffer.from(part) return [part.length, part] }) break case 'IN SRV': rdata = [ buf16(record.data.priority) , buf16(record.data.weight) , buf16(record.data.port) , self.encode(record.data.target, 2 + 6, 'nocompress') // Offset for rdata length + priority, weight, and port. ] break case 'IN DS': rdata = [ buf16(record.data.key_tag) , Buffer.from([record.data.algorithm]) , Buffer.from([record.data.digest_type]) , Buffer.from(record.data.digest) ] break case 'NONE A': // I think this is no data, from RFC 2136 S. 2.4.3. rdata = [] break default: throw new Error('Unsupported record type: ' + JSON.stringify(record)) } // Write the rdata length. (The position was already updated.) rdata = flat(rdata) buf = Buffer.allocUnsafe(2) buf.writeUInt16BE(rdata.length, 0) body.push(buf) self.position += 2 // Write the rdata. self.position += rdata.length if(rdata.length > 0) body.push(Buffer.from(rdata)) } self[section_name].push(Buffer.concat(body)) } State.prototype.encode = function(full_domain, position_offset, option) { let self = this; let domain = full_domain; domain = domain.replace(/\.$/, '') // Strip the trailing dot. let bodyBuf = Buffer.allocUnsafe(domain.length + 1); let position = this.position + (position_offset || 0); let offset = 0; let max_iterations = 40 // Enough for 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa while (max_iterations-- > 0) { if (domain === '') { // Encode the root domain and be done. return Buffer.concat([bodyBuf, Buffer.from([0])]); } else if (this.domains[domain] && option !== 'nocompress') { // Encode a pointer and be done. return Buffer.concat([ offset === bodyBuf.length ? bodyBuf : bodyBuf.slice(0, offset), Buffer.from([0xc0, this.domains[domain]]) ]); } else { // Encode the next part of the domain, saving its position in the lookup table for later. this.domains[domain] = position + offset; let idx = domain.indexOf('.'), car; if (idx === -1) { car = domain; domain = ''; } else { car = domain.substring(0, idx); domain = domain.substring(idx + 1); } // Write the first part of the domain, with a length prefix. bodyBuf.writeUInt8(car.length, offset); offset++; bodyBuf.write(car, offset, car.length, 'ascii'); offset += car.length; } } throw new Error('Too many iterations encoding domain: ' + full_domain) } // // Utilities // function buf32(value) { var buf = Buffer.allocUnsafe(4) buf.writeUInt32BE(value, 0) return buf } function buf16(value) { var buf = Buffer.allocUnsafe(2) buf.writeUInt16BE(value, 0) return buf } function flat(data) { return Buffer.isBuffer(data) ? Array.prototype.slice.call(data) : Array.isArray(data) ? data.reduce(flatten, []) : [data] } function flatten(state, element) { return (Buffer.isBuffer(element) || Array.isArray(element)) ? state.concat(flat(element)) : state.concat([element]) } function pair_to_buf(pair) { // Convert a string of two hex bytes, e.g. "89ab" to a buffer. if(! pair.match(/^[0-9a-fA-F]{4}$/)) throw new Error('Bad '+record.type+' record data: ' + JSON.stringify(record)) return Buffer.from(pair, 'hex') }
/* eslint max-nested-callbacks: 0, max-len: 0 */ /* global describe, it */ import chai from 'chai'; const expect = chai.expect; chai.use(require(`chai-virtual-dom`)); import Input, {COMPONENT_CLASS as INPUT_CLASS} from './index'; import {COMPONENT_CLASS as INPUT_CONTAINER_CLASS} from './../InputContainer/index'; import Rx from 'rx'; import {h, mockDOMResponse} from '@cycle/dom'; import {decode} from 'ent'; describe(`Input`, () => { it(`should be a function`, () => { expect(Input).to.be.a(`function`); }); it(`should output DOM`, (done) => { const props = {}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with autocapitalize set`, (done) => { const props = {autocapitalize: `words`}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `words`, autocomplete: `off`, autocorrect: `off`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with autocomplete set`, (done) => { const props = {autocomplete: `on`}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `on`, autocorrect: `off`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with autocorrect set`, (done) => { const props = {autocorrect: `on`}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `on`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with autofocus set`, (done) => { const props = {autofocus: true}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, autofocus: true, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with charCounter set`, (done) => { const props = {charCounter: true}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), h(`div.${INPUT_CONTAINER_CLASS}_addOnContent`), ]) ); done(); }); }); it(`should output DOM with errorMessage set`, (done) => { const props = {errorMessage: `there was an error`}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), h(`div.${INPUT_CONTAINER_CLASS}_addOnContent`), ]) ); done(); }); }); it(`should output DOM with isInvalid set`, (done) => { const props = {isInvalid: true}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with label set`, (done) => { const props = {label: `label`}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, `label`), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with list set`, (done) => { const props = {list: `datalist`}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, list: `datalist`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with max set`, (done) => { const props = {max: `5`}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, max: `5`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with maxLength set`, (done) => { const props = {maxLength: 10}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { attributes: {maxlength: 10}, autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with min set`, (done) => { const props = {min: `1`}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, min: `1`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with name set`, (done) => { const props = {name: `fullname`}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, name: `fullname`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with pattern set`, (done) => { const props = {pattern: `[a-zA-Z]*`}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, pattern: `[a-zA-Z]*`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with readonly set`, (done) => { const props = {readonly: true}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { attributes: {readonly: true}, autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with required set`, (done) => { const props = {required: true}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, required: true, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with size set`, (done) => { const props = {size: 10}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, size: 10, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with step set`, (done) => { const props = {step: `3`}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, step: `3`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); it(`should output DOM with type set`, (done) => { const props = {type: `number`}; const props$ = Rx.Observable.just(props); const DOMSource = mockDOMResponse(); const input = Input({DOM: DOMSource, id: ``, props$}); input.DOM.elementAt(0).subscribe((vtree) => { expect(vtree).to.look.like( h(`div.${INPUT_CONTAINER_CLASS}`, [ h(`div.${INPUT_CONTAINER_CLASS}_floatedLabelPlaceholder.atom-Typography--caption`, decode(`&nbsp;`)), h(`div.${INPUT_CONTAINER_CLASS}_inputContent.atom-FlexLayout--horizontal.atom-FlexLayout--end`, h(`div.${INPUT_CONTAINER_CLASS}_labelAndInputContainer.atom-FlexLayout_flex.atom-Layout--relative.atom-Typography--subhead`, [ h(`label.${INPUT_CONTAINER_CLASS}_label`, {hidden: true}), h(`div.${INPUT_CLASS}`, h(`input.${INPUT_CLASS}_input`, { autocapitalize: `none`, autocomplete: `off`, autocorrect: `off`, type: `number`, }) ), ]) ), h(`div.${INPUT_CONTAINER_CLASS}_underline`, [ h(`div.${INPUT_CONTAINER_CLASS}_unfocusedLine.atom-Layout--fit`), h(`div.${INPUT_CONTAINER_CLASS}_focusedLine.atom-Layout--fit`), ]), ]) ); done(); }); }); });
module.exports = { "moveLearnType": { "level": "レベル", "machine": "わざマシン", "egg": "タマゴ", "tutor": "教え", "other": "そのた" }, "move": { "pound": { "name": "はたく", "desc": "" }, "karate-chop": { "name": "からてチョップ", "desc": "" }, "double-slap": { "name": "おうふくビンタ", "desc": "" }, "comet-punch": { "name": "れんぞくパンチ", "desc": "" }, "mega-punch": { "name": "メガトンパンチ", "desc": "" }, "pay-day": { "name": "ネコにこばん", "desc": "" }, "fire-punch": { "name": "ほのおのパンチ", "desc": "" }, "ice-punch": { "name": "れいとうパンチ", "desc": "" }, "thunder-punch": { "name": "かみなりパンチ", "desc": "" }, "scratch": { "name": "ひっかく", "desc": "" }, "vice-grip": { "name": "はさむ", "desc": "" }, "guillotine": { "name": "ハサミギロチン", "desc": "" }, "razor-wind": { "name": "かまいたち", "desc": "" }, "swords-dance": { "name": "つるぎのまい", "desc": "" }, "cut": { "name": "いあいぎり", "desc": "" }, "gust": { "name": "かぜおこし", "desc": "" }, "wing-attack": { "name": "つばさでうつ", "desc": "" }, "whirlwind": { "name": "ふきとばし", "desc": "" }, "fly": { "name": "そらをとぶ", "desc": "" }, "bind": { "name": "しめつける", "desc": "" }, "slam": { "name": "たたきつける", "desc": "" }, "vine-whip": { "name": "つるのムチ", "desc": "" }, "stomp": { "name": "ふみつけ", "desc": "" }, "double-kick": { "name": "にどげり", "desc": "" }, "mega-kick": { "name": "メガトンキック", "desc": "" }, "jump-kick": { "name": "とびげり", "desc": "" }, "rolling-kick": { "name": "まわしげり", "desc": "" }, "sand-attack": { "name": "すなかけ", "desc": "" }, "headbutt": { "name": "ずつき", "desc": "" }, "horn-attack": { "name": "つのでつく", "desc": "" }, "fury-attack": { "name": "みだれづき", "desc": "" }, "horn-drill": { "name": "つのドリル", "desc": "" }, "tackle": { "name": "たいあたり", "desc": "" }, "body-slam": { "name": "のしかかり", "desc": "" }, "wrap": { "name": "まきつく", "desc": "" }, "take-down": { "name": "とっしん", "desc": "" }, "thrash": { "name": "あばれる", "desc": "" }, "double-edge": { "name": "すてみタックル", "desc": "" }, "tail-whip": { "name": "しっぽをふる", "desc": "" }, "poison-sting": { "name": "どくばり", "desc": "" }, "twineedle": { "name": "ダブルニードル", "desc": "" }, "pin-missile": { "name": "ミサイルばり", "desc": "" }, "leer": { "name": "にらみつける", "desc": "" }, "bite": { "name": "かみつく", "desc": "" }, "growl": { "name": "なきごえ", "desc": "" }, "roar": { "name": "ほえる", "desc": "" }, "sing": { "name": "うたう", "desc": "" }, "supersonic": { "name": "ちょうおんぱ", "desc": "" }, "sonic-boom": { "name": "ソニックブーム", "desc": "" }, "disable": { "name": "かなしばり", "desc": "" }, "acid": { "name": "ようかいえき", "desc": "" }, "ember": { "name": "ひのこ", "desc": "" }, "flamethrower": { "name": "かえんほうしゃ", "desc": "" }, "mist": { "name": "しろいきり", "desc": "" }, "water-gun": { "name": "みずでっぽう", "desc": "" }, "hydro-pump": { "name": "ハイドロポンプ", "desc": "" }, "surf": { "name": "なみのり", "desc": "" }, "ice-beam": { "name": "れいとうビーム", "desc": "" }, "blizzard": { "name": "ふぶき", "desc": "" }, "psybeam": { "name": "サイケこうせん", "desc": "" }, "bubble-beam": { "name": "バブルこうせん", "desc": "" }, "aurora-beam": { "name": "オーロラビーム", "desc": "" }, "hyper-beam": { "name": "はかいこうせん", "desc": "" }, "peck": { "name": "つつく", "desc": "" }, "drill-peck": { "name": "ドリルくちばし", "desc": "" }, "submission": { "name": "じごくぐるま", "desc": "" }, "low-kick": { "name": "けたぐり", "desc": "" }, "counter": { "name": "カウンター", "desc": "" }, "seismic-toss": { "name": "ちきゅうなげ", "desc": "" }, "strength": { "name": "かいりき", "desc": "" }, "absorb": { "name": "すいとる", "desc": "" }, "mega-drain": { "name": "メガドレイン", "desc": "" }, "leech-seed": { "name": "やどりぎのたね", "desc": "" }, "growth": { "name": "せいちょう", "desc": "" }, "razor-leaf": { "name": "はっぱカッター", "desc": "" }, "solar-beam": { "name": "ソーラービーム", "desc": "" }, "poison-powder": { "name": "どくのこな", "desc": "" }, "stun-spore": { "name": "しびれごな", "desc": "" }, "sleep-powder": { "name": "ねむりごな", "desc": "" }, "petal-dance": { "name": "はなびらのまい", "desc": "" }, "string-shot": { "name": "いとをはく", "desc": "" }, "dragon-rage": { "name": "りゅうのいかり", "desc": "" }, "fire-spin": { "name": "ほのおのうず", "desc": "" }, "thunder-shock": { "name": "でんきショック", "desc": "" }, "thunderbolt": { "name": "10まんボルト", "desc": "" }, "thunder-wave": { "name": "でんじは", "desc": "" }, "thunder": { "name": "かみなり", "desc": "" }, "rock-throw": { "name": "いわおとし", "desc": "" }, "earthquake": { "name": "じしん", "desc": "" }, "fissure": { "name": "じわれ", "desc": "" }, "dig": { "name": "あなをほる", "desc": "" }, "toxic": { "name": "どくどく", "desc": "" }, "confusion": { "name": "ねんりき", "desc": "" }, "psychic": { "name": "サイコキネシス", "desc": "" }, "hypnosis": { "name": "さいみんじゅつ", "desc": "" }, "meditate": { "name": "ヨガのポーズ", "desc": "" }, "agility": { "name": "こうそくいどう", "desc": "" }, "quick-attack": { "name": "でんこうせっか", "desc": "" }, "rage": { "name": "いかり", "desc": "" }, "teleport": { "name": "テレポート", "desc": "" }, "night-shade": { "name": "ナイトヘッド", "desc": "" }, "mimic": { "name": "ものまね", "desc": "" }, "screech": { "name": "いやなおと", "desc": "" }, "double-team": { "name": "かげぶんしん", "desc": "" }, "recover": { "name": "じこさいせい", "desc": "" }, "harden": { "name": "かたくなる", "desc": "" }, "minimize": { "name": "ちいさくなる", "desc": "" }, "smokescreen": { "name": "えんまく", "desc": "" }, "confuse-ray": { "name": "あやしいひかり", "desc": "" }, "withdraw": { "name": "からにこもる", "desc": "" }, "defense-curl": { "name": "まるくなる", "desc": "" }, "barrier": { "name": "バリアー", "desc": "" }, "light-screen": { "name": "ひかりのかべ", "desc": "" }, "haze": { "name": "くろいきり", "desc": "" }, "reflect": { "name": "リフレクター", "desc": "" }, "focus-energy": { "name": "きあいだめ", "desc": "" }, "bide": { "name": "がまん", "desc": "" }, "metronome": { "name": "ゆびをふる", "desc": "" }, "mirror-move": { "name": "オウムがえし", "desc": "" }, "self-destruct": { "name": "じばく", "desc": "" }, "egg-bomb": { "name": "タマゴばくだん", "desc": "" }, "lick": { "name": "したでなめる", "desc": "" }, "smog": { "name": "スモッグ", "desc": "" }, "sludge": { "name": "ヘドロこうげき", "desc": "" }, "bone-club": { "name": "ホネこんぼう", "desc": "" }, "fire-blast": { "name": "だいもんじ", "desc": "" }, "waterfall": { "name": "たきのぼり", "desc": "" }, "clamp": { "name": "からではさむ", "desc": "" }, "swift": { "name": "スピードスター", "desc": "" }, "skull-bash": { "name": "ロケットずつき", "desc": "" }, "spike-cannon": { "name": "とげキャノン", "desc": "" }, "constrict": { "name": "からみつく", "desc": "" }, "amnesia": { "name": "ドわすれ", "desc": "" }, "kinesis": { "name": "スプーンまげ", "desc": "" }, "soft-boiled": { "name": "タマゴうみ", "desc": "" }, "high-jump-kick": { "name": "とびひざげり", "desc": "" }, "glare": { "name": "へびにらみ", "desc": "" }, "dream-eater": { "name": "ゆめくい", "desc": "" }, "poison-gas": { "name": "どくガス", "desc": "" }, "barrage": { "name": "たまなげ", "desc": "" }, "leech-life": { "name": "きゅうけつ", "desc": "" }, "lovely-kiss": { "name": "あくまのキッス", "desc": "" }, "sky-attack": { "name": "ゴッドバード", "desc": "" }, "transform": { "name": "へんしん", "desc": "" }, "bubble": { "name": "あわ", "desc": "" }, "dizzy-punch": { "name": "ピヨピヨパンチ", "desc": "" }, "spore": { "name": "キノコのほうし", "desc": "" }, "flash": { "name": "フラッシュ", "desc": "" }, "psywave": { "name": "サイコウェーブ", "desc": "" }, "splash": { "name": "はねる", "desc": "" }, "acid-armor": { "name": "とける", "desc": "" }, "crabhammer": { "name": "クラブハンマー", "desc": "" }, "explosion": { "name": "だいばくはつ", "desc": "" }, "fury-swipes": { "name": "みだれひっかき", "desc": "" }, "bonemerang": { "name": "ホネブーメラン", "desc": "" }, "rest": { "name": "ねむる", "desc": "" }, "rock-slide": { "name": "いわなだれ", "desc": "" }, "hyper-fang": { "name": "ひっさつまえば", "desc": "" }, "sharpen": { "name": "かくばる", "desc": "" }, "conversion": { "name": "テクスチャー", "desc": "" }, "tri-attack": { "name": "トライアタック", "desc": "" }, "super-fang": { "name": "いかりのまえば", "desc": "" }, "slash": { "name": "きりさく", "desc": "" }, "substitute": { "name": "みがわり", "desc": "" }, "struggle": { "name": "わるあがき", "desc": "" }, "sketch": { "name": "スケッチ", "desc": "" }, "triple-kick": { "name": "トリプルキック", "desc": "" }, "thief": { "name": "どろぼう", "desc": "" }, "spider-web": { "name": "クモのす", "desc": "" }, "mind-reader": { "name": "こころのめ", "desc": "" }, "nightmare": { "name": "あくむ", "desc": "" }, "flame-wheel": { "name": "かえんぐるま", "desc": "" }, "snore": { "name": "いびき", "desc": "" }, "curse": { "name": "のろい", "desc": "" }, "flail": { "name": "じたばた", "desc": "" }, "conversion-2": { "name": "テクスチャー2", "desc": "" }, "aeroblast": { "name": "エアロブラスト", "desc": "" }, "cotton-spore": { "name": "わたほうし", "desc": "" }, "reversal": { "name": "きしかいせい", "desc": "" }, "spite": { "name": "うらみ", "desc": "" }, "powder-snow": { "name": "こなゆき", "desc": "" }, "protect": { "name": "まもる", "desc": "" }, "mach-punch": { "name": "マッハパンチ", "desc": "" }, "scary-face": { "name": "こわいかお", "desc": "" }, "feint-attack": { "name": "だましうち", "desc": "" }, "sweet-kiss": { "name": "てんしのキッス", "desc": "" }, "belly-drum": { "name": "はらだいこ", "desc": "" }, "sludge-bomb": { "name": "ヘドロばくだん", "desc": "" }, "mud-slap": { "name": "どろかけ", "desc": "" }, "octazooka": { "name": "オクタンほう", "desc": "" }, "spikes": { "name": "まきびし", "desc": "" }, "zap-cannon": { "name": "でんじほう", "desc": "" }, "foresight": { "name": "みやぶる", "desc": "" }, "destiny-bond": { "name": "みちづれ", "desc": "" }, "perish-song": { "name": "ほろびのうた", "desc": "" }, "icy-wind": { "name": "こごえるかぜ", "desc": "" }, "detect": { "name": "みきり", "desc": "" }, "bone-rush": { "name": "ボーンラッシュ", "desc": "" }, "lock-on": { "name": "ロックオン", "desc": "" }, "outrage": { "name": "げきりん", "desc": "" }, "sandstorm": { "name": "すなあらし", "desc": "" }, "giga-drain": { "name": "ギガドレイン", "desc": "" }, "endure": { "name": "こらえる", "desc": "" }, "charm": { "name": "あまえる", "desc": "" }, "rollout": { "name": "ころがる", "desc": "" }, "false-swipe": { "name": "みねうち", "desc": "" }, "swagger": { "name": "いばる", "desc": "" }, "milk-drink": { "name": "ミルクのみ", "desc": "" }, "spark": { "name": "スパーク", "desc": "" }, "fury-cutter": { "name": "れんぞくぎり", "desc": "" }, "steel-wing": { "name": "はがねのつばさ", "desc": "" }, "mean-look": { "name": "くろいまなざし", "desc": "" }, "attract": { "name": "メロメロ", "desc": "" }, "sleep-talk": { "name": "ねごと", "desc": "" }, "heal-bell": { "name": "いやしのすず", "desc": "" }, "return": { "name": "おんがえし", "desc": "" }, "present": { "name": "プレゼント", "desc": "" }, "frustration": { "name": "やつあたり", "desc": "" }, "safeguard": { "name": "しんぴのまもり", "desc": "" }, "pain-split": { "name": "いたみわけ", "desc": "" }, "sacred-fire": { "name": "せいなるほのお", "desc": "" }, "magnitude": { "name": "マグニチュード", "desc": "" }, "dynamic-punch": { "name": "ばくれつパンチ", "desc": "" }, "megahorn": { "name": "メガホーン", "desc": "" }, "dragon-breath": { "name": "りゅうのいぶき", "desc": "" }, "baton-pass": { "name": "バトンタッチ", "desc": "" }, "encore": { "name": "アンコール", "desc": "" }, "pursuit": { "name": "おいうち", "desc": "" }, "rapid-spin": { "name": "こうそくスピン", "desc": "" }, "sweet-scent": { "name": "あまいかおり", "desc": "" }, "iron-tail": { "name": "アイアンテール", "desc": "" }, "metal-claw": { "name": "メタルクロー", "desc": "" }, "vital-throw": { "name": "あてみなげ", "desc": "" }, "morning-sun": { "name": "あさのひざし", "desc": "" }, "synthesis": { "name": "こうごうせい", "desc": "" }, "moonlight": { "name": "つきのひかり", "desc": "" }, "hidden-power": { "name": "めざめるパワー", "desc": "" }, "cross-chop": { "name": "クロスチョップ", "desc": "" }, "twister": { "name": "たつまき", "desc": "" }, "rain-dance": { "name": "あまごい", "desc": "" }, "sunny-day": { "name": "にほんばれ", "desc": "" }, "crunch": { "name": "かみくだく", "desc": "" }, "mirror-coat": { "name": "ミラーコート", "desc": "" }, "psych-up": { "name": "じこあんじ", "desc": "" }, "extreme-speed": { "name": "しんそく", "desc": "" }, "ancient-power": { "name": "げんしのちから", "desc": "" }, "shadow-ball": { "name": "シャドーボール", "desc": "" }, "future-sight": { "name": "みらいよち", "desc": "" }, "rock-smash": { "name": "いわくだき", "desc": "" }, "whirlpool": { "name": "うずしお", "desc": "" }, "beat-up": { "name": "ふくろだたき", "desc": "" }, "fake-out": { "name": "ねこだまし", "desc": "" }, "uproar": { "name": "さわぐ", "desc": "" }, "stockpile": { "name": "たくわえる", "desc": "" }, "spit-up": { "name": "はきだす", "desc": "" }, "swallow": { "name": "のみこむ", "desc": "" }, "heat-wave": { "name": "ねっぷう", "desc": "" }, "hail": { "name": "あられ", "desc": "" }, "torment": { "name": "いちゃもん", "desc": "" }, "flatter": { "name": "おだてる", "desc": "" }, "will-o-wisp": { "name": "おにび", "desc": "" }, "memento": { "name": "おきみやげ", "desc": "" }, "facade": { "name": "からげんき", "desc": "" }, "focus-punch": { "name": "きあいパンチ", "desc": "" }, "smelling-salts": { "name": "きつけ", "desc": "" }, "follow-me": { "name": "このゆびとまれ", "desc": "" }, "nature-power": { "name": "しぜんのちから", "desc": "" }, "charge": { "name": "じゅうでん", "desc": "" }, "taunt": { "name": "ちょうはつ", "desc": "" }, "helping-hand": { "name": "てだすけ", "desc": "" }, "trick": { "name": "トリック", "desc": "" }, "role-play": { "name": "なりきり", "desc": "" }, "wish": { "name": "ねがいごと", "desc": "" }, "assist": { "name": "ねこのて", "desc": "" }, "ingrain": { "name": "ねをはる", "desc": "" }, "superpower": { "name": "ばかぢから", "desc": "" }, "magic-coat": { "name": "マジックコート", "desc": "" }, "recycle": { "name": "リサイクル", "desc": "" }, "revenge": { "name": "リベンジ", "desc": "" }, "brick-break": { "name": "かわらわり", "desc": "" }, "yawn": { "name": "あくび", "desc": "" }, "knock-off": { "name": "はたきおとす", "desc": "" }, "endeavor": { "name": "がむしゃら", "desc": "" }, "eruption": { "name": "ふんか", "desc": "" }, "skill-swap": { "name": "スキルスワップ", "desc": "" }, "imprison": { "name": "ふういん", "desc": "" }, "refresh": { "name": "リフレッシュ", "desc": "" }, "grudge": { "name": "おんねん", "desc": "" }, "snatch": { "name": "よこどり", "desc": "" }, "secret-power": { "name": "ひみつのちから", "desc": "" }, "dive": { "name": "ダイビング", "desc": "" }, "arm-thrust": { "name": "つっぱり", "desc": "" }, "camouflage": { "name": "ほごしょく", "desc": "" }, "tail-glow": { "name": "ほたるび", "desc": "" }, "luster-purge": { "name": "ラスターパージ", "desc": "" }, "mist-ball": { "name": "ミストボール", "desc": "" }, "feather-dance": { "name": "フェザーダンス", "desc": "" }, "teeter-dance": { "name": "フラフラダンス", "desc": "" }, "blaze-kick": { "name": "ブレイズキック", "desc": "" }, "mud-sport": { "name": "どろあそび", "desc": "" }, "ice-ball": { "name": "アイスボール", "desc": "" }, "needle-arm": { "name": "ニードルアーム", "desc": "" }, "slack-off": { "name": "なまける", "desc": "" }, "hyper-voice": { "name": "ハイパーボイス", "desc": "" }, "poison-fang": { "name": "どくどくのキバ", "desc": "" }, "crush-claw": { "name": "ブレイククロー", "desc": "" }, "blast-burn": { "name": "ブラストバーン", "desc": "" }, "hydro-cannon": { "name": "ハイドロカノン", "desc": "" }, "meteor-mash": { "name": "コメットパンチ", "desc": "" }, "astonish": { "name": "おどろかす", "desc": "" }, "weather-ball": { "name": "ウェザーボール", "desc": "" }, "aromatherapy": { "name": "アロマセラピー", "desc": "" }, "fake-tears": { "name": "うそなき", "desc": "" }, "air-cutter": { "name": "エアカッター", "desc": "" }, "overheat": { "name": "オーバーヒート", "desc": "" }, "odor-sleuth": { "name": "かぎわける", "desc": "" }, "rock-tomb": { "name": "がんせきふうじ", "desc": "" }, "silver-wind": { "name": "ぎんいろのかぜ", "desc": "" }, "metal-sound": { "name": "きんぞくおん", "desc": "" }, "grass-whistle": { "name": "くさぶえ", "desc": "" }, "tickle": { "name": "くすぐる", "desc": "" }, "cosmic-power": { "name": "コスモパワー", "desc": "" }, "water-spout": { "name": "しおふき", "desc": "" }, "signal-beam": { "name": "シグナルビーム", "desc": "" }, "shadow-punch": { "name": "シャドーパンチ", "desc": "" }, "extrasensory": { "name": "じんつうりき", "desc": "" }, "sky-uppercut": { "name": "スカイアッパー", "desc": "" }, "sand-tomb": { "name": "すなじごく", "desc": "" }, "sheer-cold": { "name": "ぜったいれいど", "desc": "" }, "muddy-water": { "name": "だくりゅう", "desc": "" }, "bullet-seed": { "name": "タネマシンガン", "desc": "" }, "aerial-ace": { "name": "つばめがえし", "desc": "" }, "icicle-spear": { "name": "つららばり", "desc": "" }, "iron-defense": { "name": "てっぺき", "desc": "" }, "block": { "name": "とおせんぼう", "desc": "" }, "howl": { "name": "とおぼえ", "desc": "" }, "dragon-claw": { "name": "ドラゴンクロー", "desc": "" }, "frenzy-plant": { "name": "ハードプラント", "desc": "" }, "bulk-up": { "name": "ビルドアップ", "desc": "" }, "bounce": { "name": "とびはねる", "desc": "" }, "mud-shot": { "name": "マッドショット", "desc": "" }, "poison-tail": { "name": "ポイズンテール", "desc": "" }, "covet": { "name": "ほしがる", "desc": "" }, "volt-tackle": { "name": "ボルテッカー", "desc": "" }, "magical-leaf": { "name": "マジカルリーフ", "desc": "" }, "water-sport": { "name": "みずあそび", "desc": "" }, "calm-mind": { "name": "めいそう", "desc": "" }, "leaf-blade": { "name": "リーフブレード", "desc": "" }, "dragon-dance": { "name": "りゅうのまい", "desc": "" }, "rock-blast": { "name": "ロックブラスト", "desc": "" }, "shock-wave": { "name": "でんげきは", "desc": "" }, "water-pulse": { "name": "みずのはどう", "desc": "" }, "doom-desire": { "name": "はめつのねがい", "desc": "" }, "psycho-boost": { "name": "サイコブースト", "desc": "" }, "roost": { "name": "はねやすめ", "desc": "" }, "gravity": { "name": "じゅうりょく", "desc": "" }, "miracle-eye": { "name": "ミラクルアイ", "desc": "" }, "wake-up-slap": { "name": "めざましビンタ", "desc": "" }, "hammer-arm": { "name": "アームハンマー", "desc": "" }, "gyro-ball": { "name": "ジャイロボール", "desc": "" }, "healing-wish": { "name": "いやしのねがい", "desc": "" }, "brine": { "name": "しおみず", "desc": "" }, "natural-gift": { "name": "しぜんのめぐみ", "desc": "" }, "feint": { "name": "フェイント", "desc": "" }, "pluck": { "name": "ついばむ", "desc": "" }, "tailwind": { "name": "おいかぜ", "desc": "" }, "acupressure": { "name": "つぼをつく", "desc": "" }, "metal-burst": { "name": "メタルバースト", "desc": "" }, "u-turn": { "name": "とんぼがえり", "desc": "" }, "close-combat": { "name": "インファイト", "desc": "" }, "payback": { "name": "しっぺがえし", "desc": "" }, "assurance": { "name": "ダメおし", "desc": "" }, "embargo": { "name": "さしおさえ", "desc": "" }, "fling": { "name": "なげつける", "desc": "" }, "psycho-shift": { "name": "サイコシフト", "desc": "" }, "trump-card": { "name": "きりふだ", "desc": "" }, "heal-block": { "name": "かいふくふうじ", "desc": "" }, "wring-out": { "name": "しぼりとる", "desc": "" }, "power-trick": { "name": "パワートリック", "desc": "" }, "gastro-acid": { "name": "いえき", "desc": "" }, "lucky-chant": { "name": "おまじない", "desc": "" }, "me-first": { "name": "さきどり", "desc": "" }, "copycat": { "name": "まねっこ", "desc": "" }, "power-swap": { "name": "パワースワップ", "desc": "" }, "guard-swap": { "name": "ガードスワップ", "desc": "" }, "punishment": { "name": "おしおき", "desc": "" }, "last-resort": { "name": "とっておき", "desc": "" }, "worry-seed": { "name": "なやみのタネ", "desc": "" }, "sucker-punch": { "name": "ふいうち", "desc": "" }, "toxic-spikes": { "name": "どくびし", "desc": "" }, "heart-swap": { "name": "ハートスワップ", "desc": "" }, "aqua-ring": { "name": "アクアリング", "desc": "" }, "magnet-rise": { "name": "でんじふゆう", "desc": "" }, "flare-blitz": { "name": "フレアドライブ", "desc": "" }, "force-palm": { "name": "はっけい", "desc": "" }, "aura-sphere": { "name": "はどうだん", "desc": "" }, "rock-polish": { "name": "ロックカット", "desc": "" }, "poison-jab": { "name": "どくづき", "desc": "" }, "dark-pulse": { "name": "あくのはどう", "desc": "" }, "night-slash": { "name": "つじぎり", "desc": "" }, "aqua-tail": { "name": "アクアテール", "desc": "" }, "seed-bomb": { "name": "タネばくだん", "desc": "" }, "air-slash": { "name": "エアスラッシュ", "desc": "" }, "x-scissor": { "name": "シザークロス", "desc": "" }, "bug-buzz": { "name": "むしのさざめき", "desc": "" }, "dragon-pulse": { "name": "りゅうのはどう", "desc": "" }, "dragon-rush": { "name": "ドラゴンダイブ", "desc": "" }, "power-gem": { "name": "パワージェム", "desc": "" }, "drain-punch": { "name": "ドレインパンチ", "desc": "" }, "vacuum-wave": { "name": "しんくうは", "desc": "" }, "focus-blast": { "name": "きあいだま", "desc": "" }, "energy-ball": { "name": "エナジーボール", "desc": "" }, "brave-bird": { "name": "ブレイブバード", "desc": "" }, "earth-power": { "name": "だいちのちから", "desc": "" }, "switcheroo": { "name": "すりかえ", "desc": "" }, "giga-impact": { "name": "ギガインパクト", "desc": "" }, "nasty-plot": { "name": "わるだくみ", "desc": "" }, "bullet-punch": { "name": "バレットパンチ", "desc": "" }, "avalanche": { "name": "ゆきなだれ", "desc": "" }, "ice-shard": { "name": "こおりのつぶて", "desc": "" }, "shadow-claw": { "name": "シャドークロー", "desc": "" }, "thunder-fang": { "name": "かみなりのキバ", "desc": "" }, "ice-fang": { "name": "こおりのキバ", "desc": "" }, "fire-fang": { "name": "ほのおのキバ", "desc": "" }, "shadow-sneak": { "name": "かげうち", "desc": "" }, "mud-bomb": { "name": "どろばくだん", "desc": "" }, "psycho-cut": { "name": "サイコカッター", "desc": "" }, "zen-headbutt": { "name": "しねんのずつき", "desc": "" }, "mirror-shot": { "name": "ミラーショット", "desc": "" }, "flash-cannon": { "name": "ラスターカノン", "desc": "" }, "rock-climb": { "name": "ロッククライム", "desc": "" }, "defog": { "name": "きりばらい", "desc": "" }, "trick-room": { "name": "トリックルーム", "desc": "" }, "draco-meteor": { "name": "りゅうせいぐん", "desc": "" }, "discharge": { "name": "ほうでん", "desc": "" }, "lava-plume": { "name": "ふんえん", "desc": "" }, "leaf-storm": { "name": "リーフストーム", "desc": "" }, "power-whip": { "name": "パワーウィップ", "desc": "" }, "rock-wrecker": { "name": "がんせきほう", "desc": "" }, "cross-poison": { "name": "クロスポイズン", "desc": "" }, "gunk-shot": { "name": "ダストシュート", "desc": "" }, "iron-head": { "name": "アイアンヘッド", "desc": "" }, "magnet-bomb": { "name": "マグネットボム", "desc": "" }, "stone-edge": { "name": "ストーンエッジ", "desc": "" }, "captivate": { "name": "ゆうわく", "desc": "" }, "stealth-rock": { "name": "ステルスロック", "desc": "" }, "grass-knot": { "name": "くさむすび", "desc": "" }, "chatter": { "name": "おしゃべり", "desc": "" }, "judgment": { "name": "さばきのつぶて", "desc": "" }, "bug-bite": { "name": "むしくい", "desc": "" }, "charge-beam": { "name": "チャージビーム", "desc": "" }, "wood-hammer": { "name": "ウッドハンマー", "desc": "" }, "aqua-jet": { "name": "アクアジェット", "desc": "" }, "attack-order": { "name": "こうげきしれい", "desc": "" }, "defend-order": { "name": "ぼうぎょしれい", "desc": "" }, "heal-order": { "name": "かいふくしれい", "desc": "" }, "head-smash": { "name": "もろはのずつき", "desc": "" }, "double-hit": { "name": "ダブルアタック", "desc": "" }, "roar-of-time": { "name": "ときのほうこう", "desc": "" }, "spacial-rend": { "name": "あくうせつだん", "desc": "" }, "lunar-dance": { "name": "みかづきのまい", "desc": "" }, "crush-grip": { "name": "にぎりつぶす", "desc": "" }, "magma-storm": { "name": "マグマストーム", "desc": "" }, "dark-void": { "name": "ダークホール", "desc": "" }, "seed-flare": { "name": "シードフレア", "desc": "" }, "ominous-wind": { "name": "あやしいかぜ", "desc": "" }, "shadow-force": { "name": "シャドーダイブ", "desc": "" }, "hone-claws": { "name": "つめとぎ", "desc": "" }, "wide-guard": { "name": "ワイドガード", "desc": "" }, "guard-split": { "name": "ガードシェア", "desc": "" }, "power-split": { "name": "パワーシェア", "desc": "" }, "wonder-room": { "name": "ワンダールーム", "desc": "" }, "psyshock": { "name": "サイコショック", "desc": "" }, "venoshock": { "name": "ベノムショック", "desc": "" }, "autotomize": { "name": "ボディパージ", "desc": "" }, "rage-powder": { "name": "いかりのこな", "desc": "" }, "telekinesis": { "name": "テレキネシス", "desc": "" }, "magic-room": { "name": "マジックルーム", "desc": "" }, "smack-down": { "name": "うちおとす", "desc": "" }, "storm-throw": { "name": "やまあらし", "desc": "" }, "flame-burst": { "name": "はじけるほのお", "desc": "" }, "sludge-wave": { "name": "ヘドロウェーブ", "desc": "" }, "quiver-dance": { "name": "ちょうのまい", "desc": "" }, "heavy-slam": { "name": "ヘビーボンバー", "desc": "" }, "synchronoise": { "name": "シンクロノイズ", "desc": "" }, "electro-ball": { "name": "エレキボール", "desc": "" }, "soak": { "name": "みずびたし", "desc": "" }, "flame-charge": { "name": "ニトロチャージ", "desc": "" }, "coil": { "name": "とぐろをまく", "desc": "" }, "low-sweep": { "name": "ローキック", "desc": "" }, "acid-spray": { "name": "アシッドボム", "desc": "" }, "foul-play": { "name": "イカサマ", "desc": "" }, "simple-beam": { "name": "シンプルビーム", "desc": "" }, "entrainment": { "name": "なかまづくり", "desc": "" }, "after-you": { "name": "おさきにどうぞ", "desc": "" }, "round": { "name": "りんしょう", "desc": "" }, "echoed-voice": { "name": "エコーボイス", "desc": "" }, "chip-away": { "name": "なしくずし", "desc": "" }, "clear-smog": { "name": "クリアスモッグ", "desc": "" }, "stored-power": { "name": "アシストパワー", "desc": "" }, "quick-guard": { "name": "ファストガード", "desc": "" }, "ally-switch": { "name": "サイドチェンジ", "desc": "" }, "scald": { "name": "ねっとう", "desc": "" }, "shell-smash": { "name": "からをやぶる", "desc": "" }, "heal-pulse": { "name": "いやしのはどう", "desc": "" }, "hex": { "name": "たたりめ", "desc": "" }, "sky-drop": { "name": "フリーフォール", "desc": "" }, "shift-gear": { "name": "ギアチェンジ", "desc": "" }, "circle-throw": { "name": "ともえなげ", "desc": "" }, "incinerate": { "name": "やきつくす", "desc": "" }, "quash": { "name": "さきおくり", "desc": "" }, "acrobatics": { "name": "アクロバット", "desc": "" }, "reflect-type": { "name": "ミラータイプ", "desc": "" }, "retaliate": { "name": "かたきうち", "desc": "" }, "final-gambit": { "name": "いのちがけ", "desc": "" }, "bestow": { "name": "ギフトパス", "desc": "" }, "inferno": { "name": "れんごく", "desc": "" }, "water-pledge": { "name": "みずのちかい", "desc": "" }, "fire-pledge": { "name": "ほのおのちかい", "desc": "" }, "grass-pledge": { "name": "くさのちかい", "desc": "" }, "volt-switch": { "name": "ボルトチェンジ", "desc": "" }, "struggle-bug": { "name": "むしのていこう", "desc": "" }, "bulldoze": { "name": "じならし", "desc": "" }, "frost-breath": { "name": "こおりのいぶき", "desc": "" }, "dragon-tail": { "name": "ドラゴンテール", "desc": "" }, "work-up": { "name": "ふるいたてる", "desc": "" }, "electroweb": { "name": "エレキネット", "desc": "" }, "wild-charge": { "name": "ワイルドボルト", "desc": "" }, "drill-run": { "name": "ドリルライナー", "desc": "" }, "dual-chop": { "name": "ダブルチョップ", "desc": "" }, "heart-stamp": { "name": "ハートスタンプ", "desc": "" }, "horn-leech": { "name": "ウッドホーン", "desc": "" }, "sacred-sword": { "name": "せいなるつるぎ", "desc": "" }, "razor-shell": { "name": "シェルブレード", "desc": "" }, "heat-crash": { "name": "ヒートスタンプ", "desc": "" }, "leaf-tornado": { "name": "グラスミキサー", "desc": "" }, "steamroller": { "name": "ハードローラー", "desc": "" }, "cotton-guard": { "name": "コットンガード", "desc": "" }, "night-daze": { "name": "ナイトバースト", "desc": "" }, "psystrike": { "name": "サイコブレイク", "desc": "" }, "tail-slap": { "name": "スイープビンタ", "desc": "" }, "hurricane": { "name": "ぼうふう", "desc": "" }, "head-charge": { "name": "アフロブレイク", "desc": "" }, "gear-grind": { "name": "ギアソーサー", "desc": "" }, "searing-shot": { "name": "かえんだん", "desc": "" }, "techno-blast": { "name": "テクノバスター", "desc": "" }, "relic-song": { "name": "いにしえのうた", "desc": "" }, "secret-sword": { "name": "しんぴのつるぎ", "desc": "" }, "glaciate": { "name": "こごえるせかい", "desc": "" }, "bolt-strike": { "name": "らいげき", "desc": "" }, "blue-flare": { "name": "あおいほのお", "desc": "" }, "fiery-dance": { "name": "ほのおのまい", "desc": "" }, "freeze-shock": { "name": "フリーズボルト", "desc": "" }, "ice-burn": { "name": "コールドフレア", "desc": "" }, "snarl": { "name": "バークアウト", "desc": "" }, "icicle-crash": { "name": "つららおとし", "desc": "" }, "v-create": { "name": "Vジェネレート", "desc": "" }, "fusion-flare": { "name": "クロスフレイム", "desc": "" }, "fusion-bolt": { "name": "クロスサンダー", "desc": "" }, "flying-press": { "name": "フライングプレス", "desc": "" }, "mat-block": { "name": "たたみがえし", "desc": "" }, "belch": { "name": "ゲップ", "desc": "" }, "rototiller": { "name": "たがやす", "desc": "" }, "sticky-web": { "name": "ねばねばネット", "desc": "" }, "fell-stinger": { "name": "とどめばり", "desc": "" }, "phantom-force": { "name": "ゴーストダイブ", "desc": "" }, "trick-or-treat": { "name": "ハロウィン", "desc": "" }, "noble-roar": { "name": "おたけび", "desc": "" }, "ion-deluge": { "name": "プラズマシャワー", "desc": "" }, "parabolic-charge": { "name": "パラボラチャージ", "desc": "" }, "forest's-curse": { "name": "もりののろい", "desc": "" }, "petal-blizzard": { "name": "はなふぶき", "desc": "" }, "freeze-dry": { "name": "フリーズドライ", "desc": "" }, "disarming-voice": { "name": "チャームボイス", "desc": "" }, "parting-shot": { "name": "すてゼリフ", "desc": "" }, "topsy-turvy": { "name": "ひっくりかえす", "desc": "" }, "draining-kiss": { "name": "ドレインキッス", "desc": "" }, "crafty-shield": { "name": "トリックガード", "desc": "" }, "flower-shield": { "name": "フラワーガード", "desc": "" }, "grassy-terrain": { "name": "グラスフィールド", "desc": "" }, "misty-terrain": { "name": "ミストフィールド", "desc": "" }, "electrify": { "name": "そうでん", "desc": "" }, "play-rough": { "name": "じゃれつく", "desc": "" }, "fairy-wind": { "name": "ようせいのかぜ", "desc": "" }, "moonblast": { "name": "ムーンフォース", "desc": "" }, "boomburst": { "name": "ばくおんぱ", "desc": "" }, "fairy-lock": { "name": "フェアリーロック", "desc": "" }, "king's-shield": { "name": "キングシールド", "desc": "" }, "play-nice": { "name": "なかよくする", "desc": "" }, "confide": { "name": "ないしょばなし", "desc": "" }, "diamond-storm": { "name": "ダイヤストーム", "desc": "" }, "water-shuriken": { "name": "みずしゅりけん", "desc": "" }, "mystical-fire": { "name": "マジカルフレイム", "desc": "" }, "spiky-shield": { "name": "ニードルガード", "desc": "" }, "aromatic-mist": { "name": "アロマミスト", "desc": "" }, "eerie-impulse": { "name": "かいでんぱ", "desc": "" }, "venom-drench": { "name": "ベノムトラップ", "desc": "" }, "powder": { "name": "ふんじん", "desc": "" }, "geomancy": { "name": "ジオコントロール", "desc": "" }, "magnetic-flux": { "name": "じばそうさ", "desc": "" }, "happy-hour": { "name": "ハッピータイム", "desc": "" }, "electric-terrain": { "name": "エレキフィールド", "desc": "" }, "dazzling-gleam": { "name": "マジカルシャイン", "desc": "" }, "celebrate": { "name": "おいわい", "desc": "" }, "hold-hands": { "name": "てをつなぐ", "desc": "" }, "baby-doll-eyes": { "name": "つぶらなひとみ", "desc": "" }, "nuzzle": { "name": "ほっぺすりすり", "desc": "" }, "hold-back": { "name": "てかげん", "desc": "" }, "infestation": { "name": "まとわりつく", "desc": "" }, "power-up-punch": { "name": "グロウパンチ", "desc": "" }, "oblivion-wing": { "name": "デスウイング", "desc": "" }, "land's-wrath": { "name": "グランドフォース", "desc": "" }, "hyperspace-hole": { "name": "いじげんホール", "desc": "" }, "steam-eruption": { "name": "スチームバースト", "desc": "" }, "precipice-blades": { "name": "だんがいのつるぎ", "desc": "" }, "origin-pulse": { "name": "こんげんのはどう", "desc": "" }, "dragon-ascent": { "name": "ガリョウテンセイ", "desc": "" } }, "type": { "normal": "ノーマル", "fire": "ほのお", "water": "みず", "electric": "でんき", "grass": "くさ", "ice": "こおり", "fighting": "かくとう", "poison": "どく", "ground": "じめん", "flying": "ひこう", "psychic": "エスパー", "bug": "むし", "rock": "いわ", "ghost": "ゴースト", "dragon": "ドラゴン", "dark": "あく", "steel": "はがね", "fairy": "フェアリー" }, "name": { "bulbasaur": "フシギダネ", "ivysaur": "フシギソウ", "venusaur": "フシギバナ", "mega-venusaur": "メガフシギバナ", "charmander": "ヒトカゲ", "charmeleon": "リザード", "charizard": "リザードン", "mega-charizard-x": "メガリザードンX", "mega-charizard-y": "メガリザードンY", "squirtle": "ゼニガメ", "wartortle": "カメール", "blastoise": "カメックス", "mega-blastoise": "メガカメックス", "caterpie": "キャタピー", "metapod": "トランセル", "butterfree": "バタフリー", "weedle": "ビードル", "kakuna": "コクーン", "beedrill": "スピアー", "pidgey": "ポッポ", "pidgeotto": "ピジョン", "pidgeot": "ピジョット", "rattata": "コラッタ", "raticate": "ラッタ", "spearow": "オニスズメ", "fearow": "オニドリル", "ekans": "アーボ", "arbok": "アーボック", "pikachu": "ピカチュウ", "raichu": "ライチュウ", "sandshrew": "サンド", "sandslash": "サンドパン", "nidoran♀": "ニドラン♀", "nidorina": "ニドリーナ", "nidoqueen": "ニドクイン", "nidoran♂": "ニドラン♂", "nidorino": "ニドリーノ", "nidoking": "ニドキング", "clefairy": "ピッピ", "clefable": "ピクシー", "vulpix": "ロコン", "ninetales": "キュウコン", "jigglypuff": "プリン", "wigglytuff": "プクリン", "zubat": "ズバット", "golbat": "ゴルバット", "oddish": "ナゾノクサ", "gloom": "クサイハナ", "vileplume": "ラフレシア", "paras": "パラス", "parasect": "パラセクト", "venonat": "コンパン", "venomoth": "モルフォン", "diglett": "ディグダ", "dugtrio": "ダグトリオ", "meowth": "ニャース", "persian": "ペルシアン", "psyduck": "コダック", "golduck": "ゴルダック", "mankey": "マンキー", "primeape": "オコリザル", "growlithe": "ガーディ", "arcanine": "ウインディ", "poliwag": "ニョロモ", "poliwhirl": "ニョロゾ", "poliwrath": "ニョロボン", "abra": "ケーシィ", "kadabra": "ユンゲラー", "alakazam": "フーディン", "mega-alakazam": "メガフーディン", "machop": "ワンリキー", "machoke": "ゴーリキー", "machamp": "カイリキー", "bellsprout": "マダツボミ", "weepinbell": "ウツドン", "victreebel": "ウツボット", "tentacool": "メノクラゲ", "tentacruel": "ドククラゲ", "geodude": "イシツブテ", "graveler": "ゴローン", "golem": "ゴローニャ", "ponyta": "ポニータ", "rapidash": "ギャロップ", "slowpoke": "ヤドン", "slowbro": "ヤドラン", "magnemite": "コイル", "magneton": "レアコイル", "farfetch'd": "カモネギ", "doduo": "ドードー", "dodrio": "ドードリオ", "seel": "パウワウ", "dewgong": "ジュゴン", "grimer": "ベトベター", "muk": "ベトベトン", "shellder": "シェルダー", "cloyster": "パルシェン", "gastly": "ゴース", "haunter": "ゴースト", "gengar": "ゲンガー", "mega-gengar": "メガゲンガー", "onix": "イワーク", "drowzee": "スリープ", "hypno": "スリーパー", "krabby": "クラブ", "kingler": "キングラー", "voltorb": "ビリリダマ", "electrode": "マルマイン", "exeggcute": "タマタマ", "exeggutor": "ナッシー", "cubone": "カラカラ", "marowak": "ガラガラ", "hitmonlee": "サワムラー", "hitmonchan": "エビワラー", "lickitung": "ベロリンガ", "koffing": "ドガース", "weezing": "マタドガス", "rhyhorn": "サイホーン", "rhydon": "サイドン", "chansey": "ラッキー", "tangela": "モンジャラ", "kangaskhan": "ガルーラ", "mega-kangaskhan": "メガガルーラ", "horsea": "タッツー", "seadra": "シードラ", "goldeen": "トサキント", "seaking": "アズマオウ", "staryu": "ヒトデマン", "starmie": "スターミー", "mr-mime": "バリヤード", "scyther": "ストライク", "jynx": "ルージュラ", "electabuzz": "エレブー", "magmar": "ブーバー", "pinsir": "カイロス", "mega-pinsir": "メガカイロス", "tauros": "ケンタロス", "magikarp": "コイキング", "gyarados": "ギャラドス", "mega-gyarados": "メガギャラドス", "lapras": "ラプラス", "ditto": "メタモン", "eevee": "イーブイ", "vaporeon": "シャワーズ", "jolteon": "サンダース", "flareon": "ブースター", "porygon": "ポリゴン", "omanyte": "オムナイト", "omastar": "オムスター", "kabuto": "カブト", "kabutops": "カブトプス", "aerodactyl": "プテラ", "mega-aerodactyl": "メガプテラ", "snorlax": "カビゴン", "articuno": "フリーザー", "zapdos": "サンダー", "moltres": "ファイヤー", "dratini": "ミニリュウ", "dragonair": "ハクリュー", "dragonite": "カイリュー", "mewtwo": "ミュウツー", "mega-mewtwo-x": "メガミュウツーX", "mega-mewtwo-y": "メガミュウツーY", "mew": "ミュウ", "chikorita": "チコリータ", "bayleef": "ベイリーフ", "meganium": "メガニウム", "cyndaquil": "ヒノアラシ", "quilava": "マグマラシ", "typhlosion": "バクフーン", "totodile": "ワニノコ", "croconaw": "アリゲイツ", "feraligatr": "オーダイル", "sentret": "オタチ", "furret": "オオタチ", "hoothoot": "ホーホー", "noctowl": "ヨルノズク", "ledyba": "レディバ", "ledian": "レディアン", "spinarak": "イトマル", "ariados": "アリアドス", "crobat": "クロバット", "chinchou": "チョンチー", "lanturn": "ランターン", "pichu": "ピチュー", "cleffa": "ピィ", "igglybuff": "ププリン", "togepi": "トゲピー", "togetic": "トゲチック", "natu": "ネイティ", "xatu": "ネイティオ", "mareep": "メリープ", "flaaffy": "モココ", "ampharos": "デンリュウ", "mega-ampharos": "メガデンリュウ", "bellossom": "キレイハナ", "marill": "マリル", "azumarill": "マリルリ", "sudowoodo": "ウソッキー", "politoed": "ニョロトノ", "hoppip": "ハネッコ", "skiploom": "ポポッコ", "jumpluff": "ワタッコ", "aipom": "エイパム", "sunkern": "ヒマナッツ", "sunflora": "キマワリ", "yanma": "ヤンヤンマ", "wooper": "ウパー", "quagsire": "ヌオー", "espeon": "エーフィ", "umbreon": "ブラッキー", "murkrow": "ヤミカラス", "slowking": "ヤドキング", "misdreavus": "ムウマ", "unown": "アンノーン", "wobbuffet": "ソーナンス", "girafarig": "キリンリキ", "pineco": "クヌギダマ", "forretress": "フォレトス", "dunsparce": "ノコッチ", "gligar": "グライガー", "steelix": "ハガネール", "snubbull": "ブルー", "granbull": "グランブル", "qwilfish": "ハリーセン", "scizor": "ハッサム", "mega-scizor": "メガハッサム", "shuckle": "ツボツボ", "heracross": "ヘラクロス", "mega-heracross": "メガヘラクロス", "sneasel": "ニューラ", "teddiursa": "ヒメグマ", "ursaring": "リングマ", "slugma": "マグマッグ", "magcargo": "マグカルゴ", "swinub": "ウリムー", "piloswine": "イノムー", "corsola": "サニーゴ", "remoraid": "テッポウオ", "octillery": "オクタン", "delibird": "デリバード", "mantine": "マンタイン", "skarmory": "エアームド", "houndour": "デルビル", "houndoom": "ヘルガー", "mega-houndoom": "メガヘルガー", "kingdra": "キングドラ", "phanpy": "ゴマゾウ", "donphan": "ドンファン", "porygon2": "ポリゴン2", "stantler": "オドシシ", "smeargle": "ドーブル", "tyrogue": "バルキー", "hitmontop": "カポエラー", "smoochum": "ムチュール", "elekid": "エレキッド", "magby": "ブビィ", "miltank": "ミルタンク", "blissey": "ハピナス", "raikou": "ライコウ", "entei": "エンテイ", "suicune": "スイクン", "larvitar": "ヨーギラス", "pupitar": "サナギラス", "tyranitar": "バンギラス", "mega-tyranitar": "メガバンギラス", "lugia": "ルギア", "ho-oh": "ホウオウ", "celebi": "セレビィ", "treecko": "キモリ", "grovyle": "ジュプトル", "sceptile": "ジュカイン", "torchic": "アチャモ", "combusken": "ワカシャモ", "blaziken": "バシャーモ", "mega-blaziken": "メガバシャーモ", "mudkip": "ミズゴロウ", "marshtomp": "ヌマクロー", "swampert": "ラグラージ", "poochyena": "ポチエナ", "mightyena": "グラエナ", "zigzagoon": "ジグザグマ", "linoone": "マッスグマ", "wurmple": "ケムッソ", "silcoon": "カラサリス", "beautifly": "アゲハント", "cascoon": "マユルド", "dustox": "ドクケイル", "lotad": "ハスボー", "lombre": "ハスブレロ", "ludicolo": "ルンパッパ", "seedot": "タネボー", "nuzleaf": "コノハナ", "shiftry": "ダーテング", "taillow": "スバメ", "swellow": "オオスバメ", "wingull": "キャモメ", "pelipper": "ペリッパー", "ralts": "ラルトス", "kirlia": "キルリア", "gardevoir": "サーナイト", "mega-gardevoir": "メガサーナイト", "surskit": "アメタマ", "masquerain": "アメモース", "shroomish": "キノココ", "breloom": "キノガッサ", "slakoth": "ナマケロ", "vigoroth": "ヤルキモノ", "slaking": "ケッキング", "nincada": "ツチニン", "ninjask": "テッカニン", "shedinja": "ヌケニン", "whismur": "ゴニョニョ", "loudred": "ドゴーム", "exploud": "バクオング", "makuhita": "マクノシタ", "hariyama": "ハリテヤマ", "azurill": "ルリリ", "nosepass": "ノズパス", "skitty": "エネコ", "delcatty": "エネコロロ", "sableye": "ヤミラミ", "mawile": "クチート", "mega-mawile": "メガクチート", "aron": "ココドラ", "lairon": "コドラ", "aggron": "ボスゴドラ", "mega-aggron": "メガボスゴドラ", "meditite": "アサナン", "medicham": "チャーレム", "mega-medicham": "メガチャーレム", "electrike": "ラクライ", "manectric": "ライボルト", "mega-manectric": "メガライボルト", "plusle": "プラスル", "minun": "マイナン", "volbeat": "バルビート", "illumise": "イルミーゼ", "roselia": "ロゼリア", "gulpin": "ゴクリン", "swalot": "マルノーム", "carvanha": "キバニア", "sharpedo": "サメハダー", "wailmer": "ホエルコ", "wailord": "ホエルオー", "numel": "ドンメル", "camerupt": "バクーダ", "torkoal": "コータス", "spoink": "バネブー", "grumpig": "ブーピッグ", "spinda": "パッチール", "trapinch": "ナックラー", "vibrava": "ビブラーバ", "flygon": "フライゴン", "cacnea": "サボネア", "cacturne": "ノクタス", "swablu": "チルット", "altaria": "チルタリス", "zangoose": "ザングース", "seviper": "ハブネーク", "lunatone": "ルナトーン", "solrock": "ソルロック", "barboach": "ドジョッチ", "whiscash": "ナマズン", "corphish": "ヘイガニ", "crawdaunt": "シザリガー", "baltoy": "ヤジロン", "claydol": "ネンドール", "lileep": "リリーラ", "cradily": "ユレイドル", "anorith": "アノプス", "armaldo": "アーマルド", "feebas": "ヒンバス", "milotic": "ミロカロス", "castform": "ポワルン", "kecleon": "カクレオン", "shuppet": "カゲボウズ", "banette": "ジュペッタ", "mega-banette": "メガジュペッタ", "duskull": "ヨマワル", "dusclops": "サマヨール", "tropius": "トロピウス", "chimecho": "チリーン", "absol": "アブソル", "mega-absol": "メガアブソル", "wynaut": "ソーナノ", "snorunt": "ユキワラシ", "glalie": "オニゴーリ", "spheal": "タマザラシ", "sealeo": "トドグラー", "walrein": "トドゼルガ", "clamperl": "パールル", "huntail": "ハンテール", "gorebyss": "サクラビス", "relicanth": "ジーランス", "luvdisc": "ラブカス", "bagon": "タツベイ", "shelgon": "コモルー", "salamence": "ボーマンダ", "beldum": "ダンバル", "metang": "メタング", "metagross": "メタグロス", "regirock": "レジロック", "regice": "レジアイス", "registeel": "レジスチル", "latias": "ラティアス", "latios": "ラティオス", "kyogre": "カイオーガ", "groudon": "グラードン", "rayquaza": "レックウザ", "jirachi": "ジラーチ", "deoxys-normal-forme": "デオキシス (ノーマルフォルム)", "deoxys-attack-forme": "デオキシス (アタックフォルム)", "deoxys-defense-forme": "デオキシス (ディフェンスフォルム)", "deoxys-speed-forme": "デオキシス (スピードフォルム)", "turtwig": "ナエトル", "grotle": "ハヤシガメ", "torterra": "ドダイトス", "chimchar": "ヒコザル", "monferno": "モウカザル", "infernape": "ゴウカザル", "piplup": "ポッチャマ", "prinplup": "ポッタイシ", "empoleon": "エンペルト", "starly": "ムックル", "staravia": "ムクバード", "staraptor": "ムクホーク", "bidoof": "ビッパ", "bibarel": "ビーダル", "kricketot": "コロボーシ", "kricketune": "コロトック", "shinx": "コリンク", "luxio": "ルクシオ", "luxray": "レントラー", "budew": "スボミー", "roserade": "ロズレイド", "cranidos": "ズガイドス", "rampardos": "ラムパルド", "shieldon": "タテトプス", "bastiodon": "トリデプス", "burmy": "ミノムッチ", "wormadam-plant-cloak": "ミノマダム (くさきのミノ)", "wormadam-sandy-cloak": "ミノマダム (すなちのミノ)", "wormadam-trash-cloak": "ミノマダム (ゴミのミノ)", "mothim": "ガーメイル", "combee": "ミツハニー", "vespiquen": "ビークイン", "pachirisu": "パチリス", "buizel": "ブイゼル", "floatzel": "フローゼル", "cherubi": "チェリンボ", "cherrim": "チェリム", "shellos": "カラナクシ", "gastrodon": "トリトドン", "ambipom": "エテボース", "drifloon": "フワンテ", "drifblim": "フワライド", "buneary": "ミミロル", "lopunny": "ミミロップ", "mismagius": "ムウマージ", "honchkrow": "ドンカラス", "glameow": "ニャルマー", "purugly": "ブニャット", "chingling": "リーシャン", "stunky": "スカンプー", "skuntank": "スカタンク", "bronzor": "ドーミラー", "bronzong": "ドータクン", "bonsly": "ウソハチ", "mime-jr": "マネネ", "happiny": "ピンプク", "chatot": "ペラップ", "spiritomb": "ミカルゲ", "gible": "フカマル", "gabite": "ガバイト", "garchomp": "ガブリアス", "mega-garchomp": "メガガブリアス", "munchlax": "ゴンベ", "riolu": "リオル", "lucario": "ルカリオ", "mega-lucario": "メガルカリオ", "hippopotas": "ヒポポタス", "hippowdon": "カバルドン", "skorupi": "スコルピ", "drapion": "ドラピオン", "croagunk": "グレッグル", "toxicroak": "ドクロッグ", "carnivine": "マスキッパ", "finneon": "ケイコウオ", "lumineon": "ネオラント", "mantyke": "タマンタ", "snover": "ユキカブリ", "abomasnow": "ユキノオー", "mega-abomasnow": "メガユキノオー", "weavile": "マニューラ", "magnezone": "ジバコイル", "lickilicky": "ベロベルト", "rhyperior": "ドサイドン", "tangrowth": "モジャンボ", "electivire": "エレキブル", "magmortar": "ブーバーン", "togekiss": "トゲキッス", "yanmega": "メガヤンマ", "leafeon": "リーフィア", "glaceon": "グレイシア", "gliscor": "グライオン", "mamoswine": "マンムー", "porygon-z": "ポリゴンZ", "gallade": "エルレイド", "probopass": "ダイノーズ", "dusknoir": "ヨノワール", "froslass": "ユキメノコ", "rotom": "ロトム", "rotom-heat-rotom": "ヒートロトム", "rotom-wash-rotom": "ウオッシュロトム", "rotom-frost-rotom": "フロストロトム", "rotom-fan-rotom": "スピンロトム", "rotom-mow-rotom": "カットロトム", "uxie": "ユクシー", "mesprit": "エムリット", "azelf": "アグノム", "dialga": "ディアルガ", "palkia": "パルキア", "heatran": "ヒードラン", "regigigas": "レジギガス", "giratina-altered-forme": "ギラティナ (アナザーフォルム)", "giratina-origin-forme": "ギラティナ (オリジンフォルム)", "cresselia": "クレセリア", "phione": "フィオネ", "manaphy": "マナフィ", "darkrai": "ダークライ", "shaymin-land-forme": "シェイミ (ランドフォルム)", "shaymin-sky-forme": "シェイミ (スカイフォルム)", "arceus": "アルセウス", "victini": "ビクティニ", "snivy": "ツタージャ", "servine": "ジャノビー", "serperior": "ジャローダ", "tepig": "ポカブ", "pignite": "チャオブー", "emboar": "エンブオー", "oshawott": "ミジュマル", "dewott": "フタチマル", "samurott": "ダイケンキ", "patrat": "ミネズミ", "watchog": "ミルホッグ", "lillipup": "ヨーテリー", "herdier": "ハーデリア", "stoutland": "ムーランド", "purrloin": "チョロネコ", "liepard": "レパルダス", "pansage": "ヤナップ", "simisage": "ヤナッキー", "pansear": "バオップ", "simisear": "バオッキー", "panpour": "ヒヤップ", "simipour": "ヒヤッキー", "munna": "ムンナ", "musharna": "ムシャーナ", "pidove": "マメパト", "tranquill": "ハトーボー", "unfezant": "ケンホロウ", "blitzle": "シママ", "zebstrika": "ゼブライカ", "roggenrola": "ダンゴロ", "boldore": "ガントル", "gigalith": "ギガイアス", "woobat": "コロモリ", "swoobat": "ココロモリ", "drilbur": "モグリュー", "excadrill": "ドリュウズ", "audino": "タブンネ", "timburr": "ドッコラー", "gurdurr": "ドテッコツ", "conkeldurr": "ローブシン", "tympole": "オタマロ", "palpitoad": "ガマガル", "seismitoad": "ガマゲロゲ", "throh": "ナゲキ", "sawk": "ダゲキ", "sewaddle": "クルミル", "swadloon": "クルマユ", "leavanny": "ハハコモリ", "venipede": "フシデ", "whirlipede": "ホイーガ", "scolipede": "ペンドラー", "cottonee": "モンメン", "whimsicott": "エルフーン", "petilil": "チュリネ", "lilligant": "ドレディア", "basculin": "バスラオ", "sandile": "メグロコ", "krokorok": "ワルビル", "krookodile": "ワルビアル", "darumaka": "ダルマッカ", "darmanitan-standard-mode": "ヒヒダルマ (ノーマルモード)", "darmanitan-zen-mode": "ヒヒダルマ (ダルマモード)", "maractus": "マラカッチ", "dwebble": "イシズマイ", "crustle": "イワパレス", "scraggy": "ズルッグ", "scrafty": "ズルズキン", "sigilyph": "シンボラー", "yamask": "デスマス", "cofagrigus": "デスカーン", "tirtouga": "プロトーガ", "carracosta": "アバゴーラ", "archen": "アーケン", "archeops": "アーケオス", "trubbish": "ヤブクロン", "garbodor": "ダストダス", "zorua": "ゾロア", "zoroark": "ゾロアーク", "minccino": "チラーミィ", "cinccino": "チラチーノ", "gothita": "ゴチム", "gothorita": "ゴチミル", "gothitelle": "ゴチルゼル", "solosis": "ユニラン", "duosion": "ダブラン", "reuniclus": "ランクルス", "ducklett": "コアルヒー", "swanna": "スワンナ", "vanillite": "バニプッチ", "vanillish": "バニリッチ", "vanilluxe": "バイバニラ", "deerling": "シキジカ", "sawsbuck": "メブキジカ", "emolga": "エモンガ", "karrablast": "カブルモ", "escavalier": "シュバルゴ", "foongus": "タマゲタケ", "amoonguss": "モロバレル", "frillish": "プルリル", "jellicent": "ブルンゲル", "alomomola": "ママンボウ", "joltik": "バチュル", "galvantula": "デンチュラ", "ferroseed": "テッシード", "ferrothorn": "ナットレイ", "klink": "ギアル", "klang": "ギギアル", "klinklang": "ギギギアル", "tynamo": "シビシラス", "eelektrik": "シビビール", "eelektross": "シビルドン", "elgyem": "リグレー", "beheeyem": "オーベム", "litwick": "ヒトモシ", "lampent": "ランプラー", "chandelure": "シャンデラ", "axew": "キバゴ", "fraxure": "オノンド", "haxorus": "オノノクス", "cubchoo": "クマシュン", "beartic": "ツンベアー", "cryogonal": "フリージオ", "shelmet": "チョボマキ", "accelgor": "アギルダー", "stunfisk": "マッギョ", "mienfoo": "コジョフー", "mienshao": "コジョンド", "druddigon": "クリムガン", "golett": "ゴビット", "golurk": "ゴルーグ", "pawniard": "コマタナ", "bisharp": "キリキザン", "bouffalant": "バッフロン", "rufflet": "ワシボン", "braviary": "ウォーグル", "vullaby": "バルチャイ", "mandibuzz": "バルジーナ", "heatmor": "クイタラン", "durant": "アイアント", "deino": "モノズ", "zweilous": "ジヘッド", "hydreigon": "サザンドラ", "larvesta": "メラルバ", "volcarona": "ウルガモス", "cobalion": "コバルオン", "terrakion": "テラキオン", "virizion": "ビリジオン", "tornadus-incarnate-forme": "トルネロス (けしんフォルム)", "tornadus-therian-forme": "トルネロス (れいじゅうフォルム)", "thundurus-incarnate-forme": "ボルトロス (けしんフォルム)", "thundurus-therian-forme": "ボルトロス (れいじゅうフォルム)", "reshiram": "レシラム", "zekrom": "ゼクロム", "landorus-incarnate-forme": "ランドロス (けしんフォルム)", "landorus-therian-forme": "ランドロス (れいじゅうフォルム)", "kyurem-kyurem": "キュレム", "kyurem-white-kyurem": "ホワイトキュレム", "kyurem-black-kyurem": "ブラックキュレム", "keldeo-ordinary-forme": "ケルディオ (いつものすがた)", "keldeo-resolute-forme": "ケルディオ (かくごのすがた)", "meloetta-aria-forme": "メロエッタ (ボイスフォルム)", "meloetta-pirouette-forme": "メロエッタ (ステップフォルム)", "genesect": "ゲノセクト", "chespin": "ハリマロン", "quilladin": "ハリボーグ", "chesnaught": "ブリガロン", "fennekin": "フォッコ", "braixen": "テールナー", "delphox": "マフォクシー", "froakie": "ケロマツ", "frogadier": "ゲコガシラ", "greninja": "ゲッコウガ", "bunnelby": "ホルビー", "diggersby": "ホルード", "fletchling": "ヤヤコマ", "fletchinder": "ヒノヤコマ", "talonflame": "ファイアロー", "scatterbug": "コフキムシ", "spewpa": "コフーライ", "vivillon": "ビビヨン", "litleo": "シシコ", "pyroar": "カエンジシ", "flabébé": "フラベベ", "floette": "フラエッテ", "florges": "フラージェス", "skiddo": "メェークル", "gogoat": "ゴーゴート", "pancham": "ヤンチャム", "pangoro": "ゴロンダ", "furfrou": "トリミアン", "espurr": "ニャスパー", "meowstic-male": "ニャオニクス (♂)", "meowstic-female": "ニャオニクス (♀)", "honedge": "ヒトツキ", "doublade": "ニダンギル", "aegislash-blade-forme": "ギルガルド (ブレードフォルム)", "aegislash-shield-forme": "ギルガルド (シールドフォルム)", "spritzee": "シュシュプ", "aromatisse": "フレフワン", "swirlix": "ペロッパフ", "slurpuff": "ペロリーム", "inkay": "マーイーカ", "malamar": "カラマネロ", "binacle": "カメテテ", "barbaracle": "ガメノデス", "skrelp": "クズモー", "dragalge": "ドラミドロ", "clauncher": "ウデッポウ", "clawitzer": "ブロスター", "helioptile": "エリキテル", "heliolisk": "エレザード", "tyrunt": "チゴラス", "tyrantrum": "ガチゴラス", "amaura": "アマルス", "aurorus": "アマルルガ", "sylveon": "ニンフィア", "hawlucha": "ルチャブル", "dedenne": "デデンネ", "carbink": "メレシー", "goomy": "ヌメラ", "sliggoo": "ヌメイル", "goodra": "ヌメルゴン", "klefki": "クレッフィ", "phantump": "ボクレー", "trevenant": "オーロット", "pumpkaboo-average-size": "バケッチャ (ふつうのサイズ)", "pumpkaboo-small-size": "バケッチャ (ちいさいサイズ)", "pumpkaboo-large-size": "バケッチャ (おおきいサイズ)", "pumpkaboo-super-size": "バケッチャ (とくだいサイズ)", "gourgeist-average-size": "パンプジン (ふつうのサイズ)", "gourgeist-small-size": "パンプジン (ちいさいサイズ)", "gourgeist-large-size": "パンプジン (おおきいサイズ)", "gourgeist-super-size": "パンプジン (とくだいサイズ)", "bergmite": "カチコール", "avalugg": "クレベース", "noibat": "オンバット", "noivern": "オンバーン", "xerneas": "ゼルネアス", "yveltal": "イベルタル", "zygarde": "ジガルデ", "diancie": "ディアンシー", "mega-diancie": "メガディアンシー", "hoopa": "フーパ", "volcanion": "ボルケニオン", "mega-sceptile": "メガジュカイン", "mega-swampert": "メガラグラージ", "mega-slowbro": "メガヤドラン", "mega-sableye": "メガヤミラミ", "mega-sharpedo": "メガサメハダー", "mega-camerupt": "メガバクーダ", "mega-altaria": "メガチルタリス", "mega-salamence": "メガボーマンダ", "mega-metagross": "メガメタグロス", "mega-rayquaza": "メガレックウザ", "mega-lopunny": "メガミミロップ", "mega-gallade": "メガエルレイド", "mega-audino": "メガタブンネ", "primal-kyogre": "ゲンシカイオーガ", "primal-groudon": "ゲンシグラードン", "mega-beedrill": "メガスピアー", "mega-pidgeot": "メガピジョット", "mega-latias": "メガラティアス", "mega-latios": "メガラティオス", "mega-steelix": "メガハガネール", "mega-glalie": "メガオニゴーリ" }, "ability": { "adaptability": { "name": "てきおうりょく", "desc": "自分の「タイプ」と同じ「タイプ」の技のダメージが1.5倍ではなく2倍になる。" }, "aerilate": { "name": "スカイスキン", "desc": "自分の「ノーマル」タイプの技が「ひこう」タイプになり、さらに威力が1.3倍になる。" }, "aftermath": { "name": "ゆうばく", "desc": "直接攻撃でひんしになったとき、相手の最大HPの1/4のダメージを与える。" }, "air-lock": { "name": "エアロック", "desc": "全てのポケモンに対しての天気の影響がなくなる。" }, "analytic": { "name": "アナライズ", "desc": "自分の攻撃がターンで一番最後の時、技の威力が1.3倍になる。" }, "anger-point": { "name": "いかりのつぼ", "desc": "自分への攻撃が急所に当たると、「こうげき」ランクが最大まで上がる。" }, "anticipation": { "name": "きけんよち", "desc": "戦闘に出てきた時、相手が「こうかは ばつぐん」や一撃必殺となる技を持っているかが分かる。技の名前などは分からない。" }, "arena-trap": { "name": "ありじごく", "desc": "相手は逃げたり、ポケモンを交代することができなくなる。ただし、相手が「ひこう」タイプや「ゴースト」タイプ、特性「ふゆう」の場合は効果がない。 / 野生のポケモンと出会いやすくなる。" }, "aroma-veil": { "name": "アロマベール", "desc": "自分と味方へのメンタル攻撃技「アンコール」「いちゃもん」「かいふくふうじ」「かなしばり」「ちょうはつ」「メロメロ」を無効化する。" }, "aura-break": { "name": "オーラブレイク", "desc": "お互いのポケモンの特性「フェアリーオーラ」「ダークオーラ」の効果において、威力が4/3倍ではなく3/4倍(0.75倍)になる。" }, "bad-dreams": { "name": "ナイトメア", "desc": "相手が「ねむり」状態の時、HPを減らす。" }, "battle-armor": { "name": "カブトアーマー", "desc": "自分への攻撃は急所に当たらない。" }, "big-pecks": { "name": "はとむね", "desc": "相手の「ぼうぎょ」ランクを下げる技や特性の効果を受けない。" }, "blaze": { "name": "もうか", "desc": "HPが1/3以下の時、「ほのお」タイプの技の威力が1.5倍になる。" }, "bulletproof": { "name": "ぼうだん", "desc": "たま・爆弾系の技「アイスボール」「アシッドボム」「ウェザーボール」「エナジーボール」「エレキボール」「オクタンほう」「かえんだん」「がんせきほう」「きあいだま」「ジャイロボール」「シャドーボール」「タネばくだん」「タネマシンガン」「タマゴばくだん」「たまなげ」「でんじほう」「どろばくだん」「はどうだん」「ヘドロばくだん」「マグネットボム」「ミストボール」を無効化する。" }, "cheek-pouch": { "name": "ほおぶくろ", "desc": "自分の持っている「きのみ」を食べる時、本来の効果に加えて、さらにHPも最大HPの1/3回復する。" }, "chlorophyll": { "name": "ようりょくそ", "desc": "天気が「はれ」の時、「すばやさ」が2倍になる。" }, "clear-body": { "name": "クリアボディ", "desc": "相手の「のうりょく」ランクを下げる技や特性の効果を受けない。" }, "cloud-nine": { "name": "ノーてんき", "desc": "全てのポケモンに対しての天気の影響がなくなる。" }, "color-change": { "name": "へんしょく", "desc": "技を受けると、その技のタイプになる。" }, "competitive": { "name": "かちき", "desc": "相手の技や特性で「のうりょく」ランクが下がると、「とくこう」ランクが2段階上がる。" }, "compoundeyes": { "name": "ふくがん", "desc": "命中率が1.3倍になる。 / 「てもち」の先頭にいると道具を持った野生のポケモンと出会いやすくなる。" }, "contrary": { "name": "あまのじゃく", "desc": "「のうりょく」ランクを変化させる技の効果が逆になる(1段階上がるものは1段階下がる)。" }, "cursed-body": { "name": "のろわれボディ", "desc": "相手から攻撃技を受けた時、30%の確率で3ターンの間、その相手の技を「かなしばり」状態にする。" }, "cute-charm": { "name": "メロメロボディ", "desc": "直接攻撃を受けると、30%の確率で相手を「メロメロ」状態にする。性別が同じ場合や、性別不明の場合は効果がない。 / 異なる性別の野生のポケモンと出会いやすくなる。" }, "damp": { "name": "しめりけ", "desc": "全てのポケモンは技「じばく」「だいばくはつ」及び、特性「ゆうばく」が無効になる。" }, "dark-aura": { "name": "ダークオーラ", "desc": "お互いのすべてのポケモンの「あく」タイプの技の威力が4/3倍(1.33倍)になる。" }, "defeatist": { "name": "よわき", "desc": "自分のHPが半分以下になると、「こうげき」「とくこう」が半減する。" }, "defiant": { "name": "まけんき", "desc": "相手の技や特性で「のうりょく」ランクが下がった時、自分の「こうげき」ランクが2段階上がる。" }, "delta-stream": { "name": "デルタストリーム", "desc": "戦闘に出ている間、天気が「らんきりゅう」になる。 / 技「あまごい」「にほんばれ」「すなあらし」「あられ」が失敗する。 / 特性「あめふらし」「ひでり」「すなおこし」「ゆきふらし」が発動しなくなる。 / ひこうタイプのポケモンの弱点となるタイプの技のダメージが、通常のダメージになる。" }, "desolate-land": { "name": "おわりのだいち", "desc": "戦闘に出ている間、天気が「ひざしがとてもつよい」状態になる。 / 特性「ひでり」による「ひざしがつよい」状態と同じ効果を、ポケモンやポケモンの技に対して与える。 / 技「あまごい」「にほんばれ」「すなあらし」「あられ」が失敗する。 / 特性「あめふらし」「ひでり」「すなおこし」「ゆきふらし」が発動しなくなる。 / みずタイプの攻撃技が無効になる。" }, "download": { "name": "ダウンロード", "desc": "相手の「ぼうぎょ」が「とくぼう」より低い場合は「こうげき」ランクを、「とくぼう」の方が低い場合は「とくこう」ランクを1段階上げる。" }, "drizzle": { "name": "あめふらし", "desc": "戦闘に出ると5ターンの間、天気が「あめ」になる。" }, "drought": { "name": "ひでり", "desc": "戦闘に出ると5ターンの間、天気が「はれ」になる。" }, "dry-skin": { "name": "かんそうはだ", "desc": "「ほのお」タイプの技の受けるダメージが1.25倍になる。「みず」タイプの技を受けると、ダメージを受けずHPが最大HPの1/4回復する。また、天気が「はれ」の時は毎ターン最大HPの1/8のダメージを受け、「あめ」の時は毎ターンHPが最大HPの1/8回復する。" }, "early-bird": { "name": "はやおき", "desc": "「ねむり」状態の時、ねむり状態のターン経過が2倍になり、通常より早く回復する。" }, "effect-spore": { "name": "ほうし", "desc": "直接攻撃を受けると、30%の確率で相手を「どく」「まひ」「ねむり」状態のいずれかにする。" }, "fairy-aura": { "name": "フェアリーオーラ", "desc": "お互いのすべてのポケモンの「フェアリー」タイプの技の威力が4/3倍(1.33倍)になる。" }, "filter": { "name": "フィルター", "desc": "タイプ相性が「こうかは ばつぐん」の技の受けるダメージが3/4になる。例えば、2倍弱点の場合は1.5倍のダメージになる。" }, "flame-body": { "name": "ほのおのからだ", "desc": "直接攻撃を受けると、30%の確率で相手を「やけど」状態にする。 / 「てもち」にいると、ポケモンのタマゴが2倍かえりやすくなる。" }, "flare-boost": { "name": "ねつぼうそう", "desc": "「やけど」状態の時、自分の特殊技の威力が1.5倍になる。" }, "flash-fire": { "name": "もらいび", "desc": "「ほのお」タイプの技のダメージや効果を受けず、以後自分の「ほのお」タイプの技の威力が1.5倍になる。" }, "flower-gift": { "name": "フラワーギフト", "desc": "天気が「はれ」の時、すべての味方の「こうげき」「とくぼう」が1.5倍になる。" }, "flower-veil": { "name": "フラワーベール", "desc": "味方すべての「くさ」タイプのポケモンは「のうりょく」ランクが下がらず、状態異常にもならない。" }, "forecast": { "name": "てんきや", "desc": "天気が「はれ」の時は「ほのお」タイプに、「あめ」の時は「みず」タイプに、「あられ」の時は「こおり」タイプになり、姿がそれぞれ変化する。" }, "forewarn": { "name": "よちむ", "desc": "戦闘に出ると相手の覚えている技のうち、最も威力の高い技の名前が分かる。同じ威力の技がある場合はランダム。" }, "friend-guard": { "name": "フレンドガード", "desc": "自分以外の味方が受けるダメージが3/4に軽減される。(ダブルバトル・トリプルバトル用)" }, "frisk": { "name": "おみとおし", "desc": "戦闘に出てきた時、すべての相手の持っている道具の名前が分かる。" }, "fur-coat": { "name": "ファーコート", "desc": "物理攻撃の受けるダメージが半減する。" }, "gale-wings": { "name": "はやてのつばさ", "desc": "優先度0の「ひこう」タイプの技を「すばやさ」に関係なく先制攻撃できる。(優先度:+1)" }, "gluttony": { "name": "くいしんぼう", "desc": "通常より早く、HPが最大HPの半分以下になると「きのみ」を使う。" }, "gooey": { "name": "ぬめぬめ", "desc": "直接攻撃を受けると、相手の「すばやさ」ランクを1段階下げる。" }, "grass-pelt": { "name": "くさのけがわ", "desc": "グラスフィールドの時、「ぼうぎょ」が1.5倍になる。" }, "guts": { "name": "こんじょう", "desc": "状態異常の時、「こうげき」が1.5倍になる。またその時、「やけど」状態による「こうげき」半減の効果を受けない。" }, "harvest": { "name": "しゅうかく", "desc": "ターン終了時、そのターン自分が使用した「きのみ」が50%の確率で元に戻る。天気が「はれ」の時は100%の確率で元に戻る。" }, "healer": { "name": "いやしのこころ", "desc": "毎ターン終了時、1/3の確率で自分以外の味方の状態異常が治る。" }, "heatproof": { "name": "たいねつ", "desc": "「ほのお」タイプの技を受けた時と、「やけど」状態によるダメージが半減する。" }, "heavy-metal": { "name": "ヘヴィメタル", "desc": "自分の「おもさ」が2倍になる。(技「ヘビーボンバー」などで有効)" }, "honey-gather": { "name": "みつあつめ", "desc": "道具を持っていない時、戦闘後にどうぐ「あまいミツ」を拾ってくることがある。戦闘に参加しなくてもよい。レベルが高い程、拾ってくる確率が上がる。" }, "huge-power": { "name": "ちからもち", "desc": "自分の物理技の威力が2倍になる。" }, "hustle": { "name": "はりきり", "desc": "「こうげき」が1.5倍になるが、物理攻撃の命中率が0.8倍になる。 / レベルの高い野生のポケモンと出会いやすくなる。" }, "hydration": { "name": "うるおいボディ", "desc": "天気が「あめ」の時、ターン終了時に状態異常が回復する。" }, "hyper-cutter": { "name": "かいりきバサミ", "desc": "「こうげき」ランクが下がらない。" }, "ice-body": { "name": "アイスボディ", "desc": "天気が「あられ」の時、ダメージを受けず、毎ターン終了時にHPが最大HPの1/16回復する。" }, "illuminate": { "name": "はっこう", "desc": " / 野生のポケモンと出会いやすくなる。" }, "illusion": { "name": "イリュージョン", "desc": "手持ちの最後のポケモンの姿と名前で戦闘に出る。「タイプ」や「のうりょく」に変化はない。ダメージを受けると元に戻る。" }, "immunity": { "name": "めんえき", "desc": "「どく」状態にならない。" }, "imposter": { "name": "かわりもの", "desc": "戦闘に出ると、相手のポケモンに変身し、「へんしん」状態になる。" }, "infiltrator": { "name": "すりぬけ", "desc": "相手の「リフレクター」「ひかりのかべ」「しろいきり」「しんぴのまもり」「みがわり」の効果を受けない。" }, "inner-focus": { "name": "せいしんりょく", "desc": "相手の技で「ひるみ」状態にならない。技「きあいパンチ」には影響しない。" }, "insomnia": { "name": "ふみん", "desc": "「ねむり」状態にならない。技「ねむる」を使えない。" }, "intimidate": { "name": "いかく", "desc": "戦闘に出たときに相手の「こうげき」ランクを1段階下げる。 / レベルの低い野生のポケモンと出会いにくくなる。" }, "iron-barbs": { "name": "てつのトゲ", "desc": "直接攻撃を受けると、相手のHPを相手の最大HPの1/8減らす。" }, "iron-fist": { "name": "てつのこぶし", "desc": "パンチ系の技「アームハンマー」「かみなりパンチ」「きあいパンチ」「グロウパンチ」「コメットパンチ」「シャドーパンチ」「スカイアッパー」「ドレインパンチ」「ばくれつパンチ」「バレットパンチ」「ピヨピヨパンチ」「ほのおのパンチ」「マッハパンチ」「メガトンパンチ」「れいとうパンチ」「れんぞくパンチ」の威力が1.2倍になる。" }, "justified": { "name": "せいぎのこころ", "desc": "「あく」タイプの技を受けると、「こうげき」ランクが1段階上がる。" }, "keen-eye": { "name": "するどいめ", "desc": "命中率ランクが下がらない。相手の回避率ランクが上がっていても、影響を受けない。 / レベルの低い野生のポケモンと出会いにくくなる。" }, "klutz": { "name": "ぶきよう", "desc": "持っている道具の効果が発揮されない。" }, "leaf-guard": { "name": "リーフガード", "desc": "天気が「はれ」の時、状態異常にならない。" }, "levitate": { "name": "ふゆう", "desc": "「じめん」タイプの技を受けない。" }, "light-metal": { "name": "ライトメタル", "desc": "自分の「おもさ」が半分になる。(技「けたぐり」「くさむすび」対策などで有効)" }, "lightningrod": { "name": "ひらいしん", "desc": "「でんき」タイプの技を受けるとダメージが無効化され、逆に「とくこう」ランクが1段階上がる。またダブルバトル・トリプルバトルの時、自分以外の全てのポケモンの「でんき」タイプの技の攻撃対象が自分になる。" }, "limber": { "name": "じゅうなん", "desc": "「まひ」状態にならない。" }, "liquid-ooze": { "name": "ヘドロえき", "desc": "HPを吸い取る技「きゅうけつ」「ギガドレイン」「すいとる」「ドレインキッス」「ドレインパンチ」「メガドレイン」「やどりぎのタネ」を受けた時、逆に相手にダメージを与える。" }, "magic-bounce": { "name": "マジックミラー", "desc": "技「マジックコート」で跳ね返すことのできる技を跳ね返せる。" }, "magic-guard": { "name": "マジックガード", "desc": "直接のダメージ以外を受けない。具体的には、「どく」「やけど」状態や特性「さめはだ」「てつのトゲ」「ヘドロえき」「ゆうばく」、天気「あられ」「すなあらし」、技「あくむ」「うずしお」「からではさむ」「しめつける」「ステルスロック」「すなじごく」「どくびし」「のろい」「はじけるほのお」「ふんじん」「ほのおのうず」「ほのおのちかい」「まきつく」「まきびし」「マグマストーム」「まとわりつく」「やどりぎのタネ」によるダメージ、反動のある技による反動ダメージや失敗時に受けるダメージ、道具「いのちのたま」「くっつきバリ」「くろいヘドロ」「ゴツゴツメット」の効果によるダメージを受けない。ただし「こんらん」「じばく」「だいばくはつ」「わるあがき」などには影響しない。" }, "magician": { "name": "マジシャン", "desc": "自分の攻撃時、技を当てた相手が持っている道具を奪う。" }, "magma-armor": { "name": "マグマのよろい", "desc": "「こおり」状態にならない。 / 「てもち」にいると、ポケモンのタマゴが2倍かえりやすくなる。" }, "magnet-pull": { "name": "じりょく", "desc": "相手の「はがね」タイプのポケモンは逃げたり、ポケモンを交代することができなくなる。 / 「はがね」タイプの野生のポケモンと出会いやすくなる。" }, "marvel-scale": { "name": "ふしぎなうろこ", "desc": "状態異常の時、「ぼうぎょ」が1.5倍になる。" }, "mega-launcher": { "name": "メガランチャー", "desc": "波動系の技「あくのはどう」「はどうだん」「みずのはどう」「りゅうのはどう」の技の威力が1.5倍になり、「いやしのはどう」は最大HPの3/4回復する。" }, "minus": { "name": "マイナス", "desc": "特性「プラス」のポケモンが戦闘にいると「とくこう」が1.5倍になる。" }, "mold-breaker": { "name": "かたやぶり", "desc": "相手の特性の影響を受けずに攻撃できる。ただし、攻撃後に受ける効果は消えない。" }, "moody": { "name": "ムラっけ", "desc": "ターン終了時、いずれかの「のうりょく」ランクが2段階上がり、別の「のうりょく」ランクが1段階下がる。" }, "motor-drive": { "name": "でんきエンジン", "desc": "「でんき」タイプの技を受けるとダメージや効果はなくなり、「すばやさ」ランクが1段階上がる。" }, "moxie": { "name": "じしんかじょう", "desc": "自分の技で相手を倒すと、「こうげき」ランクが1段階上がる。" }, "multiscale": { "name": "マルチスケイル", "desc": "自分の残りHPが最大値の時、受けるダメージが半減される。" }, "multitype": { "name": "マルチタイプ", "desc": "持っている「プレート」に対応して「タイプ」が変化する。" }, "mummy": { "name": "ミイラ", "desc": "直接攻撃を受けると、相手の特性を「ミイラ」にする(相手の本来の特性を無効化する)。" }, "natural-cure": { "name": "しぜんかいふく", "desc": "他のポケモンに交代すると異常状態が回復する。" }, "no-guard": { "name": "ノーガード", "desc": "お互いに技が命中率・回避率に関係なく必ず命中する。 / 野生のポケモンと出会いやすくなる。" }, "normalize": { "name": "ノーマルスキン", "desc": "自分の全ての技が「ノーマル」タイプになる。" }, "oblivious": { "name": "どんかん", "desc": "「メロメロ」「ちょうはつ」「ゆうわく」状態にならない。" }, "overcoat": { "name": "ぼうじん", "desc": "天気「あられ」「すなあらし」によるダメージを受けない。粉系の技「いかりのこな」「キノコのほうし」「しびれごな」「どくのこな」「ねむりごな」「ふんじん」「わたほうし」、特性「ほうし」の効果を受けない。" }, "overgrow": { "name": "しんりょく", "desc": "HPが1/3以下の時、「くさ」タイプの技の威力が1.5倍になる。" }, "own-tempo": { "name": "マイペース", "desc": "「こんらん」状態にならない。" }, "parental-bond": { "name": "おやこあい", "desc": "同じ技を1ターンに2回攻撃できる。2回目の攻撃は、威力が半分になる。能力ランクを下げるなどの効果は2回分与えられる。1ターンに連続して攻撃する技や、複数の相手に攻撃する技の場合は2回攻撃できない" }, "pickpocket": { "name": "わるいてぐせ", "desc": "直接攻撃を受けた時、相手の持っている道具を奪う。" }, "pick-up": { "name": "ものひろい", "desc": "毎ターン終了時に、そのターンに相手が使った道具を拾って自分のものにする。自分が道具を持っていない時のみ発動する。 / 道具を持っていない時、戦闘後に10%の確率で道具を拾ってくる。戦闘に参加しなくてもよい。レベルに応じて拾ってくる道具が変化する。" }, "pixilate": { "name": "フェアリースキン", "desc": "自分の「ノーマル」タイプの技が「フェアリー」タイプになり、さらに威力が1.3倍になる。" }, "plus": { "name": "プラス", "desc": "特性「マイナス」のポケモンが戦闘にいると「とくこう」が1.5倍になる。" }, "poison-heal": { "name": "ポイズンヒール", "desc": "「どく」状態の時毎ターン、HPが減らずに最大HPの1/8だけ回復する。「もうどく」状態でも回復量は変わらない。" }, "poison-point": { "name": "どくのトゲ", "desc": "直接攻撃を受けると、30%の確率で相手を「どく」状態にする。" }, "poison-touch": { "name": "どくしゅ", "desc": "相手に直接攻撃をすると、30%の確率で相手を「どく」状態にする。" }, "prankster": { "name": "いたずらごころ", "desc": "優先度0の変化技を「すばやさ」に関係なく先制攻撃できる。(優先度:+1)" }, "pressure": { "name": "プレッシャー", "desc": "技を受けた時、技のPPを2減らす。 / レベルの高い野生のポケモンと出会いやすくなる。" }, "primordial-sea": { "name": "はじまりのうみ", "desc": "戦闘に出ている間、天気が「つよいあめ」になる。 / 特性「あめふらし」による「あめ」状態と同じ効果を、ポケモンやポケモンの技に対して与える。 / 技「あまごい」「にほんばれ」「すなあらし」「あられ」が失敗する。 / 特性「あめふらし」「ひでり」「すなおこし」「ゆきふらし」が発動しなくなる。 / ほのおタイプの攻撃技が無効になる。" }, "protean": { "name": "へんげんじざい", "desc": "自分の技を出すタイミングで、自分のタイプが技と同じタイプになる。" }, "pure-power": { "name": "ヨガパワー", "desc": "自分の物理技の威力が2倍になる。" }, "quick-feet": { "name": "はやあし", "desc": "状態異常の時、「すばやさ」が1.5倍になる。 / 野生のポケモンと出会いにくくなる。" }, "rain-dish": { "name": "あめうけざら", "desc": "天気が「あめ」の時毎ターン、HPが最大HPの1/16回復する。" }, "rattled": { "name": "びびり", "desc": "「ゴースト」「むし」「あく」タイプの技を受けた時、「すばやさ」ランクが1段階上がる。" }, "reckless": { "name": "すてみ", "desc": "技「アフロブレイク」「ウッドハンマー」「じごくぐるま」「すてみタックル」「とっしん」「とびげり」「とびひざげり」「もろはのずつき」「フレアドライブ」「ブレイブバード」「ボルテッカー」「ワイルドボルト」の威力が1.2倍になる。" }, "refrigerate": { "name": "フリーズスキン", "desc": "自分の「ノーマル」タイプの技が「こおり」タイプになり、さらに威力が1.3倍になる。" }, "regenerator": { "name": "さいせいりょく", "desc": "他のポケモンに交代するとHPが最大HPの1/3回復する。" }, "rivalry": { "name": "とうそうしん", "desc": "性別が同じ相手に対しては「こうげき」「とくこう」が1.25倍になるが、異なる場合は0.75倍になる。性別のないポケモンの場合は効果がない。" }, "rock-head": { "name": "いしあたま", "desc": "技「アフロブレイク」「ウッドハンマー」「じごくぐるま」「すてみタックル」「とっしん」「フレアドライブ」「ブレイブバード」「ボルテッカー」「もろはのずつき」「ワイルドボルト」の反動を受けない。技「わるあがき」の反動は受ける。" }, "rough-skin": { "name": "さめはだ", "desc": "直接攻撃を受けると、相手のHPを相手の最大HPの1/8減らす。" }, "run-away": { "name": "にげあし", "desc": "野生のポケモンとの戦闘の場合、必ず逃げられる。" }, "sand-force": { "name": "すなのちから", "desc": "天気が「すなあらし」の時、自分の「じめん」「いわ」「はがね」タイプの技の威力が1.3倍になる。また、「すなあらし」によるダメージを受けない。" }, "sand-rush": { "name": "すなかき", "desc": "天気が「すなあらし」の時、「すばやさ」が2倍になる。また、「すなあらし」によるダメージを受けない。" }, "sand-stream": { "name": "すなおこし", "desc": "戦闘に出ると5ターンの間、天気が「すなあらし」になる。" }, "sand-veil": { "name": "すながくれ", "desc": "天気が「すなあらし」の時、回避率が上がる。また、「すなあらし」によるダメージを受けない。 / フィールドの天気が「すなあらし」の時、野生のポケモンと出会いにくくなる。" }, "sap-sipper": { "name": "そうしょく", "desc": "「くさ」タイプの技を受けると技が無効化され、「こうげき」ランクが1段階上がる。" }, "scrappy": { "name": "きもったま", "desc": "相手が「ゴースト」タイプでも、「ノーマル」「かくとう」タイプの技が等倍で当たる。" }, "serene-grace": { "name": "てんのめぐみ", "desc": "技の追加効果の発生率が2倍になる。" }, "shadow-tag": { "name": "かげふみ", "desc": "相手は逃げたり、ポケモンを交代することができなくなる。お互いが特性「かげふみ」の場合は無効になる。「ゴースト」タイプには無効。" }, "shed-skin": { "name": "だっぴ", "desc": "ターンごとに1/3の確率で状態異常が治る。" }, "sheer-force": { "name": "ちからずく", "desc": "追加効果のある技を使うと、追加効果が発動しない代わりに威力が1.3倍になる。" }, "shell-armor": { "name": "シェルアーマー", "desc": "自分への攻撃は急所に当たらない。" }, "shield-dust": { "name": "りんぷん", "desc": "技の追加効果を受けない。" }, "simple": { "name": "たんじゅん", "desc": "「のうりょく」ランクの変化が2倍になる。" }, "skill-link": { "name": "スキルリンク", "desc": "2~5回連続で当たる技が必ず5回当たる。" }, "slow-start": { "name": "スロースタート", "desc": "戦闘に出てから5ターンの間、「こうげき」「すばやさ」が半分になる。" }, "sniper": { "name": "スナイパー", "desc": "自分の攻撃が急所に当たると、ダメージが1.5倍ではなく2.25倍になる。" }, "snow-cloak": { "name": "ゆきがくれ", "desc": "天気が「あられ」の時、相手の技の命中率が0.8倍になる。また、「あられ」によるダメージを受けない。 / フィールドの天気が「あられ」の時、野生のポケモンと出会いにくくなる。" }, "snow-warning": { "name": "ゆきふらし", "desc": "戦闘に出ると5ターンの間、天気が「あられ」になる。" }, "solar-power": { "name": "サンパワー", "desc": "天気が「はれ」の時、「とくこう」が1.5倍になるが、毎ターン終了時に最大HPの1/8のダメージを受ける。" }, "solid-rock": { "name": "ハードロック", "desc": "タイプ相性が「こうかは ばつぐん」の技の受けるダメージが3/4になる。例えば、2倍弱点の場合は1.5倍のダメージになる。" }, "soundproof": { "name": "ぼうおん", "desc": "音の技「いびき」「いやしのすず」「いやなおと」「うたう」「エコーボイス」「おしゃべり」「おたけび」「きんぞくおん」「くさぶえ」「さわぐ」「すてゼリフ」「チャームボイス」「ちょうおんぱ」「ないしょばなし」「なきごえ」「バークアウト」「ハイパーボイス」「ばくおんぱ」「ほえる」「ほろびのうた」「むしのさざめき」「りんしょう」を受けない。" }, "speed-boost": { "name": "かそく", "desc": "毎ターン、「すばやさ」ランクが1段階ずつ上がる。" }, "stall": { "name": "あとだし", "desc": "技を出す順番が必ず一番最後になる。" }, "stance-change": { "name": "バトルスイッチ", "desc": "攻撃技を使用する場合ブレードフォルムになり(攻撃・特攻が高い)、技「キングシールド」を使用するとシールドフォルムになる(防御・特防が高い)。" }, "static": { "name": "せいでんき", "desc": "直接攻撃を受けると、30%の確率で相手を「まひ」状態にする。 / 「でんき」タイプの野生のポケモンと出会いやすくなる。" }, "steadfast": { "name": "ふくつのこころ", "desc": "相手の技でひるむと、「すばやさ」ランクが1段階上がる。" }, "stench": { "name": "あくしゅう", "desc": "相手に技のダメージを与えると、10%の確率でひるませる。 / 野生のポケモンと出会いにくくなる。" }, "sticky-hold": { "name": "ねんちゃく", "desc": "持っている道具を相手に奪われない。 / 「てもち」の先頭にいると釣りが成功しやすくなる。" }, "storm-drain": { "name": "よびみず", "desc": "「みず」タイプの技を受けるとダメージが無効化され、逆に「とくこう」ランクが1段階上がる。またダブルバトル・トリプルバトルの時、自分以外の全てのポケモンの「みず」タイプの技の攻撃対象が自分になる。" }, "strong-jaw": { "name": "がんじょうあご", "desc": "あごやキバを使って攻撃する技「かみつく」「かみくだく」「ひっさつまえば」「ほのおのキバ」「かみなりのキバ」「こおりのキバ」「どくどくのキバ」の威力が1.5倍になる。" }, "sturdy": { "name": "がんじょう", "desc": "HPが最大の時、「ひんし」状態になるダメージを受けても必ず1残る。また、一撃で「ひんし」になる技「じわれ」「ぜったいれいど」「つのドリル」「ハサミギロチン」を受けない。" }, "suction-cups": { "name": "きゅうばん", "desc": "相手を交代させる技「ふきとばし」「ほえる」「ドラゴンテール」の効果を受けない。 / 「てもち」の先頭にいると釣りが成功しやすくなる。" }, "super-luck": { "name": "きょううん", "desc": "急所ランクが1段階上がった状態となり、自分の攻撃が急所に当たりやすくなる。" }, "swarm": { "name": "むしのしらせ", "desc": "HPが1/3以下の時、「むし」タイプの技の威力が1.5倍になる。" }, "sweet-veil": { "name": "スイートベール", "desc": "自分や味方のポケモンは「ねむり」状態にならない。" }, "swift-swim": { "name": "すいすい", "desc": "天気が「あめ」の時、「すばやさ」が2倍になる。" }, "symbiosis": { "name": "きょうせい", "desc": "味方に道具を渡せるようになる。" }, "synchronize": { "name": "シンクロ", "desc": "「どく」「まひ」「やけど」状態になった時、相手も同じ状態異常になる。 / 同じ「せいかく」の野生のポケモンと出会いやすくなる。" }, "tangled-feet": { "name": "ちどりあし", "desc": "「こんらん」状態の時、回避率が上がる。" }, "technician": { "name": "テクニシャン", "desc": "威力が60以下の技の威力が1.5倍になる。威力の変動する技や、威力が修正された場合も影響する。" }, "telepathy": { "name": "テレパシー", "desc": "味方の技のダメージを受けない。" }, "teravolt": { "name": "テラボルテージ", "desc": "相手の特性の影響を受けずに攻撃できる。ただし、攻撃後に受ける効果は消えない。" }, "thick-fat": { "name": "あついしぼう", "desc": "「ほのお」「こおり」タイプの技を受けた時、ダメージが半減する。" }, "tinted-lens": { "name": "いろめがね", "desc": "自分の技のタイプ相性が「こうかは いまひとつのようだ」の場合、1/2倍の時は通常に、1/4倍の時は1/2倍になる。" }, "torrent": { "name": "げきりゅう", "desc": "HPが1/3以下の時、「みず」タイプの技の威力が1.5倍になる。" }, "tough-claws": { "name": "かたいツメ", "desc": "直接攻撃する技の威力が1.3倍になる。" }, "toxic-boost": { "name": "どくぼうそう", "desc": "「どく」「もうどく」状態の時、自分の物理技の威力が1.5倍になる。" }, "trace": { "name": "トレース", "desc": "相手と同じ特性になる。相手が2体いる場合はランダムにどちらかの特性が選ばれる。相手の特性が「てんきや」「トレース」「バトルスイッチ」の場合は効果がない。" }, "truant": { "name": "なまけ", "desc": "1ターンおきにしか技が使えない。" }, "turboblaze": { "name": "ターボブレイズ", "desc": "相手の特性の影響を受けずに攻撃できる。ただし、攻撃後に受ける効果は消えない。" }, "unaware": { "name": "てんねん", "desc": "相手の「のうりょく」ランクの変化の影響を受けない。" }, "unburden": { "name": "かるわざ", "desc": "持っている道具がなくなると「すばやさ」が2倍になる。再び道具を持つと元に戻る。最初から道具を持っていない場合は効果がない。" }, "unnerve": { "name": "きんちょうかん", "desc": "すべての相手は「きのみ」を使用できなくなる。" }, "victory-star": { "name": "しょうりのほし", "desc": "自分と味方の技の命中率が上がる。" }, "vital-spirit": { "name": "やるき", "desc": "「ねむり」状態にならない。技「ねむる」を使えない。 / レベルの高い野生のポケモンと出会いやすくなる。" }, "volt-absorb": { "name": "ちくでん", "desc": "「でんき」タイプの技を受けるとダメージや効果はなくなり、最大HPの1/4回復する。" }, "water-absorb": { "name": "ちょすい", "desc": "「みず」タイプの技を受けるとダメージや効果はなくなり、最大HPの1/4回復する。" }, "water-veil": { "name": "みずのベール", "desc": "「やけど」状態にならない。" }, "weak-armor": { "name": "くだけるよろい", "desc": "物理技を受けると、「ぼうぎょ」ランクが1段階下がり、「すばやさ」ランクが1段階上がる。" }, "white-smoke": { "name": "しろいけむり", "desc": "相手の「のうりょく」ランクを下げる技や特性の効果を受けない。 / 野生のポケモンと出会いにくくなる。" }, "wonder-guard": { "name": "ふしぎなまもり", "desc": "タイプ相性が「こうかは ばつぐん」でない技のダメージを受けない。ただし、タイプ相性に関係のない技は影響しない。" }, "wonder-skin": { "name": "ミラクルスキン", "desc": "相手の変化技の命中する確率が50%より大きい場合、命中率が50%になる。" }, "zen-mode": { "name": "ダルマモード", "desc": "自分の残りHPが半分以下になるとフォルムチェンジする。回復して半分より多くなると元に戻る。" } } };
scope({c0_Front:3, c0_Generator:3, c0_Intermediate:3, c0_Representation:4, c0_alloy:3, c0_ast2ast:3, c0_ast2ir:3, c0_ast2text:3, c0_claferLib:3, c0_common:3, c0_desClafer:3, c0_desugarer:3, c0_experimental:3, c0_findDuplicates:3, c0_front:3, c0_generator:3, c0_inheritanceFlattener:3, c0_inheritanceResolver:3, c0_input:33, c0_intermediate:3, c0_io:33, c0_ir2ir:12, c0_ir2text:3, c0_layoutResolver:3, c0_lexer:3, c0_mapper:3, c0_nameResolution:3, c0_nameResolver:3, c0_optimizer:3, c0_output:33, c0_parser:3, c0_prettyPrinter:3, c0_resolver:3, c0_scopeAnalysis:3, c0_setUid:3, c0_stable:3, c0_stats:3, c0_stringAnalyzer:3, c0_text2tokens:3, c0_tokens2ast:3, c0_tokens2tokens:3, c0_transformer:3, c0_typeResolver:3, c0_xml:3, c0_xsdSchema:3}); defaultScope(1); intRange(-8, 7); stringLength(16); c0_claferLib = Abstract("c0_claferLib"); c0_Representation = Abstract("c0_Representation"); c0_io = Abstract("c0_io"); c0_Front = Abstract("c0_Front"); c0_Intermediate = Abstract("c0_Intermediate"); c0_text2tokens = Abstract("c0_text2tokens").extending(c0_io); c0_tokens2tokens = Abstract("c0_tokens2tokens").extending(c0_io); c0_tokens2ast = Abstract("c0_tokens2ast").extending(c0_io); c0_ast2ast = Abstract("c0_ast2ast").extending(c0_io); c0_ast2text = Abstract("c0_ast2text").extending(c0_io); c0_ast2ir = Abstract("c0_ast2ir").extending(c0_io); c0_ir2ir = Abstract("c0_ir2ir").extending(c0_io); c0_ir2text = Abstract("c0_ir2text").extending(c0_io); c0_Generator = Abstract("c0_Generator").extending(c0_ir2text); c0_claferCompiler = Clafer("c0_claferCompiler").withCard(1, 1).extending(c0_claferLib); c0_claferIG = Clafer("c0_claferIG").withCard(1, 1).extending(c0_claferLib); c0_claferMOO = Clafer("c0_claferMOO").withCard(1, 1).extending(c0_claferLib); c0_moo = c0_claferMOO.addChild("c0_moo").withCard(1, 1); c0_common = c0_claferLib.addChild("c0_common").withCard(1, 1); c0_front = c0_claferLib.addChild("c0_front").withCard(1, 1).extending(c0_Front); c0_intermediate = c0_claferLib.addChild("c0_intermediate").withCard(1, 1).extending(c0_Intermediate); c0_optimizer = c0_claferLib.addChild("c0_optimizer").withCard(1, 1); c0_generator = c0_claferLib.addChild("c0_generator").withCard(1, 1).withGroupCard(1, 1).extending(c0_Generator); c0_text = Clafer("c0_text").withCard(1, 1).extending(c0_Representation); c0_tokens = Clafer("c0_tokens").withCard(1, 1).extending(c0_Representation); c0_ast = Clafer("c0_ast").withCard(1, 1).extending(c0_Representation); c0_ir = Clafer("c0_ir").withCard(1, 1).extending(c0_Representation); c0_input = c0_io.addChild("c0_input").withCard(1, 1); c0_output = c0_io.addChild("c0_output").withCard(1, 1); c0_lexer = c0_Front.addChild("c0_lexer").withCard(1, 1).extending(c0_text2tokens); c0_layoutResolver = c0_Front.addChild("c0_layoutResolver").withCard(0, 1).withGroupCard(1, 1).extending(c0_tokens2tokens); c0_stable = c0_layoutResolver.addChild("c0_stable").withCard(0, 1); c0_experimental = c0_layoutResolver.addChild("c0_experimental").withCard(0, 1); c0_parser = c0_Front.addChild("c0_parser").withCard(1, 1).extending(c0_tokens2ast); c0_mapper = c0_Front.addChild("c0_mapper").withCard(1, 1).extending(c0_ast2ast); c0_prettyPrinter = c0_Front.addChild("c0_prettyPrinter").withCard(0, 1).extending(c0_ast2text); c0_desugarer = c0_Intermediate.addChild("c0_desugarer").withCard(1, 1).extending(c0_ast2ir); c0_findDuplicates = c0_Intermediate.addChild("c0_findDuplicates").withCard(0, 1); c0_resolver = c0_Intermediate.addChild("c0_resolver").withCard(0, 1).extending(c0_ir2ir); c0_setUid = c0_resolver.addChild("c0_setUid").withCard(1, 1); c0_inheritanceFlattener = c0_resolver.addChild("c0_inheritanceFlattener").withCard(0, 1); c0_nameResolution = c0_resolver.addChild("c0_nameResolution").withCard(1, 1); c0_nameResolver = c0_nameResolution.addChild("c0_nameResolver").withCard(0, 1); c0_inheritanceResolver = c0_nameResolution.addChild("c0_inheritanceResolver").withCard(1, 1); c0_typeResolver = c0_nameResolution.addChild("c0_typeResolver").withCard(1, 1); c0_transformer = c0_Intermediate.addChild("c0_transformer").withCard(1, 1).extending(c0_ir2ir); c0_stringAnalyzer = c0_Intermediate.addChild("c0_stringAnalyzer").withCard(0, 1).extending(c0_ir2ir); c0_scopeAnalysis = c0_Intermediate.addChild("c0_scopeAnalysis").withCard(0, 1).extending(c0_ir2ir); c0_alloy = c0_Generator.addChild("c0_alloy").withCard(0, 1); c0_stats = c0_Generator.addChild("c0_stats").withCard(0, 1); c0_xml = c0_Generator.addChild("c0_xml").withCard(0, 1); c0_desClafer = c0_Generator.addChild("c0_desClafer").withCard(0, 1); c0_xsdSchema = c0_Generator.addChild("c0_xsdSchema").withCard(0, 1); c0_input.refTo(c0_Representation); c0_output.refTo(c0_Representation); c0_text2tokens.addConstraint(and(equal(joinRef(join($this(), c0_input)), global(c0_text)), equal(joinRef(join($this(), c0_output)), global(c0_tokens)))); c0_tokens2tokens.addConstraint(and(equal(joinRef(join($this(), c0_input)), global(c0_tokens)), equal(joinRef(join($this(), c0_output)), global(c0_tokens)))); c0_tokens2ast.addConstraint(and(equal(joinRef(join($this(), c0_input)), global(c0_tokens)), equal(joinRef(join($this(), c0_output)), global(c0_ast)))); c0_ast2ast.addConstraint(and(equal(joinRef(join($this(), c0_input)), global(c0_ast)), equal(joinRef(join($this(), c0_output)), global(c0_ast)))); c0_ast2text.addConstraint(and(equal(joinRef(join($this(), c0_input)), global(c0_ast)), equal(joinRef(join($this(), c0_output)), global(c0_text)))); c0_ast2ir.addConstraint(and(equal(joinRef(join($this(), c0_input)), global(c0_ast)), equal(joinRef(join($this(), c0_output)), global(c0_ir)))); c0_ir2ir.addConstraint(and(equal(joinRef(join($this(), c0_input)), global(c0_ir)), equal(joinRef(join($this(), c0_output)), global(c0_ir)))); c0_ir2text.addConstraint(and(equal(joinRef(join($this(), c0_input)), global(c0_ir)), equal(joinRef(join($this(), c0_output)), global(c0_text)))); c0_nameResolver.addConstraint(some(join(joinParent(joinParent(joinParent($this()))), c0_findDuplicates))); c0_alloy.addConstraint(and(some(join(global(c0_Intermediate), c0_stringAnalyzer)), some(join(global(c0_Intermediate), c0_scopeAnalysis)))); c0_desClafer.addConstraint(some(join(global(c0_Front), c0_prettyPrinter)));
var path = require('path'); var gulp = require('gulp'); var conf = require('./conf'); var $ = require('gulp-load-plugins')(); gulp.task('deploy', ['build:examples'], function() { return gulp.src(path.join(conf.paths.examplesDist, '/**/*')) .pipe($.ghPages()) .on('end', function () { gulp.src(path.join(conf.paths.examplesDist)) .pipe($.clean({force: true})); }); });
/* * Core plugin implementation */ function QTip(target, options, id, attr) { // Elements and ID this.id = id; this.target = target; this.tooltip = NULL; this.elements = { target: target }; // Internal constructs this._id = NAMESPACE + '-' + id; this.timers = { img: {} }; this.options = options; this.plugins = {}; // Cache object this.cache = { event: {}, target: $(), disabled: FALSE, attr: attr, onTooltip: FALSE, lastClass: '' }; // Set the initial flags this.rendered = this.destroyed = this.disabled = this.waiting = this.hiddenDuringWait = this.positioning = this.triggering = this.preshow = FALSE; } PROTOTYPE = QTip.prototype; PROTOTYPE._when = function(deferreds) { return $.when.apply($, deferreds); }; PROTOTYPE.render = function(show) { if (this.rendered && !this.destroyed && (show || this.options.show.ready)) { this.toggle(TRUE, this.cache.event, FALSE); return this; } if(this.rendered || this.destroyed) { return this; } // If tooltip has already been rendered, exit var self = this, options = this.options, cache = this.cache, elements = this.elements, text = options.content.text, title = options.content.title, button = options.content.button, posOptions = options.position, namespace = '.'+this._id+' ', deferreds = [], tooltip; // Add ARIA attributes to target $.attr(this.target[0], 'aria-describedby', this._id); // Create public position object that tracks current position corners cache.posClass = this._createPosClass( (this.position = { my: posOptions.my, at: posOptions.at }).my ); // Create tooltip element this.tooltip = elements.tooltip = tooltip = $('<div/>', { 'id': this._id, 'class': [ NAMESPACE, CLASS_DEFAULT, options.style.classes, cache.posClass ].join(' '), 'width': options.style.width || '', 'height': options.style.height || '', 'tracking': posOptions.target === 'mouse' && posOptions.adjust.mouse, /* ARIA specific attributes */ 'role': 'alert', 'aria-live': 'polite', 'aria-atomic': FALSE, 'aria-describedby': this._id + '-content', 'aria-hidden': TRUE }) .toggleClass(CLASS_DISABLED, this.disabled) .attr(ATTR_ID, this.id) .data(NAMESPACE, this) .appendTo(posOptions.container) .append( // Create content element elements.content = $('<div />', { 'class': NAMESPACE + '-content', 'id': this._id + '-content', 'aria-atomic': TRUE }) ); // Set rendered flag and prevent redundant reposition calls for now this.rendered = -1; this.positioning = TRUE; // Create title... if(title) { this._createTitle(); // Update title only if its not a callback (called in toggle if so) if(!$.isFunction(title)) { deferreds.push( this._updateTitle(title, FALSE) ); } } // Create button if(button) { this._createButton(); } // Set proper rendered flag and update content if not a callback function (called in toggle) if(!$.isFunction(text)) { deferreds.push( this._updateContent(text, FALSE) ); } this.rendered = TRUE; // Setup widget classes this._setWidget(); // Initialize 'render' plugins $.each(PLUGINS, function(name) { var instance; if(this.initialize === 'render' && (instance = this(self))) { self.plugins[name] = instance; } }); // Unassign initial events and assign proper events this._unassignEvents(); this._assignEvents(); // When deferreds have completed this._when(deferreds).then(function() { if (self.destroyed) { // The tooltip was destroyed before the render was complete. Just drop further processing return; } // tooltiprender event self._trigger('render'); // Reset flags self.positioning = FALSE; // Show tooltip if not hidden during wait period if(!self.hiddenDuringWait && (options.show.ready || show)) { self.toggle(TRUE, cache.event, FALSE); } self.hiddenDuringWait = FALSE; }); // Expose API QTIP.api[this.id] = this; return this; }; PROTOTYPE.destroy = function(immediate) { // Set flag the signify destroy is taking place to plugins // and ensure it only gets destroyed once! if(this.destroyed) { return this.target; } function process() { if(this.destroyed) { return; } this.destroyed = TRUE; var target = this.target, title = target.attr(oldtitle), timer; // Destroy tooltip if rendered if(this.rendered) { this.tooltip.stop(1,0).find('*').remove().end().remove(); } // Destroy all plugins $.each(this.plugins, function(name) { this.destroy && this.destroy(); }); // Clear timers for(timer in this.timers) { clearTimeout(this.timers[timer]); } // Remove api object and ARIA attributes target.removeData(NAMESPACE) .removeAttr(ATTR_ID) .removeAttr(ATTR_HAS) .removeAttr('aria-describedby'); // Reset old title attribute if removed if(this.options.suppress && title) { target.attr('title', title).removeAttr(oldtitle); } // Remove qTip events associated with this API this._unassignEvents(); // Remove ID from used id objects, and delete object references // for better garbage collection and leak protection this.options = this.elements = this.cache = this.timers = this.plugins = this.mouse = NULL; // Delete epoxsed API object delete QTIP.api[this.id]; } // If an immediate destroy is needed if((immediate !== TRUE || this.triggering === 'hide') && this.rendered) { this.tooltip.one('tooltiphidden', $.proxy(process, this)); !this.triggering && this.hide(); } // If we're not in the process of hiding... process else { process.call(this); } return this.target; };
import { GLSL3, NoBlending, RawShaderMaterial, Uniform } from 'three'; import vertexShader from '../shaders/FlowPass.vert.js'; import fragmentShader from '../shaders/FlowPass.frag.js'; export class FlowMaterial extends RawShaderMaterial { constructor() { super({ glslVersion: GLSL3, uniforms: { tMap: new Uniform(null), tFlow: new Uniform(null) }, vertexShader, fragmentShader, blending: NoBlending, depthWrite: false, depthTest: false }); } }
import {strict as assert} from "assert"; import {Author, Blog, CheckResult, Client, Comment, CommentType} from "../lib/index.js"; /** Tests the features of the `Client` class. */ describe("Client", function() { this.timeout(15000); // The default test client. const blog = new Blog(new URL("https://docs.belin.io/akismet.js")); const _client = new Client(process.env.AKISMET_API_KEY, blog, {isTest: true}); // A message marked as ham. let author = new Author("192.168.0.1", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0", { name: "Akismet", role: "administrator", url: new URL("https://docs.belin.io/akismet.js") }); const _ham = new Comment(author, { content: "I'm testing out the Service API.", referrer: new URL("https://www.npmjs.com/package/@cedx/akismet"), type: CommentType.comment }); // A message marked as spam. author = new Author("127.0.0.1", "Spam Bot/6.6.6", { email: "akismet-guaranteed-spam@example.com", name: "viagra-test-123" }); const _spam = new Comment(author, { content: "Spam!", type: CommentType.trackback }); describe(".checkComment()", function() { it("should return `CheckResult.isHam` for valid comment (e.g. ham)", async function() { assert.equal(await _client.checkComment(_ham), CheckResult.isHam); }); it("should return `CheckResult.isSpam` for invalid comment (e.g. spam)", async function() { const result = await _client.checkComment(_spam); assert(result == CheckResult.isSpam || result == CheckResult.isPervasiveSpam); }); }); describe(".submitHam()", function() { it("should complete without any error", async function() { try { await _client.submitHam(_ham); } catch (err) { assert.fail(err.message); } }); }); describe(".submitSpam()", function() { it("should complete without any error", async function() { try { await _client.submitSpam(_spam); } catch (err) { assert.fail(err.message); } }); }); describe(".verifyKey()", function() { it("should return `true` for a valid API key", async function() { assert(await _client.verifyKey()); }); it("should return `false` for an invalid API key", async function() { const client = new Client("0123456789-ABCDEF", _client.blog, {isTest: true}); assert.equal(await client.verifyKey(), false); }); }); });
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * BillEntry Schema */ var BillEntrySchema = new Schema({ outsideKnitter: { type: String, required: 'Please fill outsideKnitter name' }, billNo: { type: String, required: 'Please fill billNo name' }, billDate: { type: Date, required: 'Please fill billDate name' }, jobNo: { type: String, required: 'Please fill jobNo name' }, amount: { type: Number, required: 'Please fill amount name' }, partyDeliveryChallanNo: { type: String, required: 'Please fill partyDeliveryChallanNo name' }, date: { type: Date, required: 'Please fill date name' }, inwardKgs: { type: Number, required: 'Please fill inwardKgs name' }, include: { type: String, required: 'Please fill include name' }, remarks: { type: String, required: 'Please fill remarks name' }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('BillEntry', BillEntrySchema);
describe('listTo', function() { it('should return all numbers from 2 up to but excluding a given number', function() { expect(listTo(6)).to.eql([2, 3, 4, 5]); }); }); describe('primeSift', function() { it('should return all prime numbers less than a given number', function() { expect(primeSift(13)).to.eql([2, 3, 5, 7, 11]); }); });
var app = angular.module('myApp'); app.controller('checkWeatherController', function ($scope, $http, uiGmapGoogleMapApi, httpWeatherRequestService) { $scope.shownWeather = false; $scope.map = { center: { latitude: 0, longitude: 0 }, zoom: 2, markers: [], events: { tilesloaded: function (map) { $scope.directionsDisplay.setMap(map); } } }; $scope.search = ''; $scope.options = { types: '(cities)' }; $scope.details = ''; $scope.itemNumber = 3; $scope.results =[]; uiGmapGoogleMapApi.then(function(maps) { $scope.gMaps = maps; $scope.initializeDirections(); $scope.directionsService = new maps.DirectionsService; }); $scope.addMarker = function (search) { $scope.cleanUp(); $scope.getWeather(search); var marker = { id: Date.now(), coords: { latitude: $scope.details.geometry.location.lat(), longitude: $scope.details.geometry.location.lng() } }; $scope.map.zoom = 7; $scope.map.center = { latitude: $scope.details.geometry.location.lat(), longitude: $scope.details.geometry.location.lng() }; $scope.map.markers.push(marker); $scope.displayDrivingDirections(); }; $scope.displayDrivingDirections = function() { var markers = $scope.map.markers; if (markers.length > 1) { var directionsServiceRequest = { origin: $scope.getLocation(markers[0].coords.latitude, markers[0].coords.longitude), destination: $scope.getLocation(markers[markers.length-1].coords.latitude, markers[markers.length-1].coords.longitude), waypoints: [], optimizeWaypoints: false, provideRouteAlternatives: false, travelMode: $scope.gMaps.TravelMode.DRIVING, unitSystem: $scope.gMaps.UnitSystem.METRIC }; if (markers.length > 2) { for(var i = 1; i <= markers.length-1; i++){ directionsServiceRequest.waypoints.push({ location: $scope.getLocation(markers[i].coords.latitude, markers[i].coords.longitude), stopover: true }); } } $scope.directionsService.route(directionsServiceRequest, function (response, status) { if (status == $scope.gMaps.DirectionsStatus.OK) { $scope.directionsDisplay.setDirections(response); } }); } }; $scope.getLocation = function(latitude, longitude) { return latitude + "," + longitude; }; $scope.cleanUp = function() { if ($scope.map.markers.length >= $scope.itemNumber) { $scope.map.markers =[]; $scope.initializeDirections(); } if ($scope.results.length >= $scope.itemNumber) { $scope.results =[]; } }; $scope.initializeDirections = function() { if ($scope.directionsDisplay) { // fallback to clear the previous directions $scope.directionsDisplay.setMap(null); $scope.directionsDisplay = null; } $scope.directionsDisplay = new $scope.gMaps.DirectionsRenderer({ preserveViewport: true, suppressMarkers: true }); }; $scope.results = httpWeatherRequestService.results; $scope.getWeather = httpWeatherRequestService.getWeather; while ($scope.results.length > $scope.itemNumber) { $scope.results.pop(); } })
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _Base = require('./Base'); var _Base2 = _interopRequireDefault(_Base); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } /** * Responsive media embed wrapper */ var Embed = function Embed(_ref, _ref2) { var rebass = _ref2.rebass; var ratio = _ref.ratio, children = _ref.children, props = _objectWithoutProperties(_ref, ['ratio', 'children']); var childProps = { style: { position: 'absolute', width: '100%', height: '100%', top: 0, bottom: 0, left: 0, border: 0 } }; var styledChildren = _react2.default.Children.map(children, function (child) { return _react2.default.cloneElement(child, childProps); }); return _react2.default.createElement(_Base2.default, _extends({}, props, { className: 'Embed', children: styledChildren, baseStyle: { position: 'relative', height: 0, padding: 0, paddingBottom: ratio * 100 + '%', overflow: 'hidden' } })); }; Embed.propTypes = { /** * Aspect ratio for the embed. * Divide height over width to calculate. * E.g. ratio={9/16} */ ratio: _react2.default.PropTypes.number }; Embed.defaultProps = { ratio: 9 / 16 }; Embed.contextTypes = { rebass: _react2.default.PropTypes.object }; exports.default = Embed;
/* * grunt-asset-version-json * https://github.com/andyford/grunt-asset-version-json * * Based on: * https://github.com/hariadi/grunt-assets-wp * * Copyright (c) 2013 Andy Ford * Licensed under the MIT license. */ 'use strict'; var fs = require('fs') , path = require('path') , crypto = require('crypto'); module.exports = function(grunt) { grunt.registerMultiTask('asset_version_json', 'Rename assets files with hash and store hashes in a JSON file', function() { var dest = this.data.dest , options = this.options({ encoding: 'utf8', algorithm: 'md5', format: true, length: 4, rename: false }); this.files.forEach(function(files) { files.src.forEach(function (file) { if (file.length === 0) { grunt.log.warn('src does not exist'); return false; } if ( ! fs.existsSync(dest)) { grunt.log.warn(dest + ' does not exist.'); return false; } var basename = path.basename , name = basename(file) , content = grunt.file.read(file) , hash = crypto.createHash(options.algorithm).update(content, options.encoding).digest('hex') , jsoncontent , suffix = hash.slice(0, options.length) , ext = path.extname(file) , newName = options.format ? [suffix, basename(file, ext), ext.slice(1)].join('.') : [basename(file, ext), suffix, ext.slice(1)].join('.'); // Copy/rename file base on hash and format var resultPath = path.resolve(path.dirname(file), newName); if (options.rename) { fs.renameSync(file, resultPath); } else { grunt.file.copy(file, resultPath); } grunt.log.writeln(' ' + file.grey + (' changed to ') + newName.green); // Write new hashes to revs/hashes tracking JSON file jsoncontent = grunt.file.readJSON(dest); jsoncontent[file] = suffix; grunt.file.write(dest, JSON.stringify(jsoncontent, null, 2)); grunt.log.writeln(' ' + dest.grey + (' updated hash: ') + suffix.green); }); }); }); };
import React from 'react'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; const ConfirmDialog = ({ open, handleClose, handleSubmit, title, children, ...rest }) => { const actions = [ <FlatButton label="Cancel" onTouchTap={ handleClose } />, <FlatButton label="Submit" onTouchTap={ handleSubmit } />, ]; return ( <Dialog title={ title } actions={ actions } open={ open } onRequestClose={ handleClose } {...rest}> { children } </Dialog> ); }; export default ConfirmDialog;
angular.module('ngAwesome.filters') .filter('extract', function() { return function(array, property) { var result; if (!angular.isObject(array) || !angular.isString(property)) { return; } if (!angular.isArray(array)) { return [array[property]]; } result = []; angular.forEach(array, function(object) { result.push(object[property]); }); return result; }; });
var googletag = googletag || {}; googletag.cmd = googletag.cmd || []; (function() { var gads = document.createElement('script'); gads.async = true; gads.type = 'text/javascript'; var useSSL = 'https:' == document.location.protocol; gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js'; var node = document.getElementsByTagName('script')[0]; node.parentNode.insertBefore(gads, node); })(); googletag.cmd.push(function() { googletag.defineSlot('/5805113/TexasTribune_Content_StoryPage_BTF_RightRail2_MediumRectangle_300x250', [300, 250], 'div-gpt-ad-1406570316312-1').addService(googletag.pubads()); googletag.pubads().enableSingleRequest(); googletag.enableServices(); }); googletag.cmd.push(function() { googletag.display('div-gpt-ad-1406570316312-1'); });
const linkStyle = { cursor: 'pointer', textDecoration: 'none', opacity: 1, transition: 'opacity .15s ease-in', ':hover': { opacity: 0.5, transition: 'opacity .15s ease-in', }, ':focus': { opacity: 0.5, transition: 'opacity .15s ease-in', }, ':active': { opacity: 0.5, transition: 'opacity .15s ease-out', }, }; export default linkStyle;
import { List } from 'immutable'; import { expect } from 'chai'; import { function1, function2 } from '../client/src/core'; describe('application logic', () => { // let state = setupState(); it('setups initial state correctly', () => { expect(state.has('bla bla')).to.be.true; expect(state.has('bla bla')).to.be.true; }); describe('does X correctly', () => { // ... }); });
import 'normalize.css'; import 'bootstrap/scss/bootstrap.scss'; import '../scss/main.scss'; import {displayResolution, winHei, winWid} from './modules/display'; let divID = document.getElementById("button"); let inputButton = document.getElementById("inpBut"); let inputWidth = document.getElementById("inpWid"); let divBox = document.getElementById("box"); function scaling(element, width) { let _height = Math.floor((winHei() / winWid()) * width); // console.log(_height); element.style.height = _height + "px"; element.style.width = width + "px"; } divID.onclick = function() { alert("Your resolution is: " + displayResolution()); } inputButton.onclick = function() { let reg = new RegExp("^[0-9]*$"); let value = inputWidth.value; if (value === "") { alert("Input width is null!"); } else { if (!reg.test(value)) { alert("Please input a number!"); } else { scaling(divBox, value); // console.log(value); } } } window.onload = function() { divBox.style.height = winHei() + "px"; divBox.style.width = winWid() + "px"; }
var task1 = { render: function(){ document.getElementById("screenX").textContent = window.screenX; document.getElementById("screenY").textContent = window.screenY; document.getElementById("screenWidth").textContent = window.innerWidth; document.getElementById("screenHeight").textContent = window.innerHeight; document.getElementById("location").textContent = window.location; }, resize: function(){ window.addEventListner("resize", this.render); }, devInfo: function() { var btnDev = document.getElementById("dev-info"); btnDev.addEventListner("click", function() { }); } } task1.render(); task1.resize(); task1.devInfo();
var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist'), filename: 'build.js' }, watch: true, watchOptions: { poll: true }, module: { rules: [ { test: /\.html$/, loader: 'html-loader' }, { test: /\.vue$/, loader: 'vue-loader', options: { loaders: {} // other vue-loader options go here } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ] }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js' } }, devServer: { historyApiFallback: true, noInfo: true }, performance: { hints: false }, devtool: '#eval-source-map', plugins: [ new HtmlWebpackPlugin({ template: 'index.html', inject: 'body', hash: true }) ] } if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, compress: { warnings: false } }), new webpack.LoaderOptionsPlugin({ minimize: true }) ]) };
module.exports.tasks = { injector: { options: { template: '<%= src %>index.html', destFile : '<%= dist %>index.html', relative: true, addRootSlash: false }, local_dependencies: { files: { 'index.html': [ '<%= dist %>vendor.js', '<%= dist %>app.module.js', '<%= dist %>**/*.js', '<%= dist %>templates.js', '<%= dist %>**/vendor/**/*.css', '<%= dist %>**/*.css' ] } } } };
"use strict"; module.exports = function(grunt) { // подключаем плагин load-grunt-tasks, чтобы не перечислять все прочие плагины require("load-grunt-tasks")(grunt); require('time-grunt')(grunt); // описываем задачи, которые планируем использовать (их запуск - см. низ этого файла) grunt.initConfig({ // компилируем препроцессор less: { style: { files: { // в какой файл, из какого файла "css/style.css": "less/style.less", "css/normalize.css": "less/normalize.less" } } }, // обрабатываем postcss-ом (там только autoprefixer, на самом деле) postcss: { options: { processors: [ // автопрефиксер и его настройки require("autoprefixer")({browsers: [ "last 1 version", "last 2 Chrome versions", "last 2 Firefox versions", "last 2 Opera versions", "last 2 Edge versions" ]}) ] }, style: { src: "css/style.css" } }, // локальный сервер, автообновление browserSync: { server: { bsFiles: { src: [ "*.html", "css/*.css" ] }, options: { server: ".", watchTask: true, notify: false, open: true, ui: false } } }, // слежение за файлами watch: { files: ["less/**/*.less"], tasks: ["less", "postcss"], options: { spawn: false } }, csso: { style : { options: { report: "gzip" }, files: { "css/style.min.css": ["css/style.css"] } } } // concat: { // options: { // separator: ';', // }, // dist: { // src: ['js/test1.js', 'js/test2.js'], // dest: 'build/main.js', // } // }, // uglify: { // dist: { // src: ['build/main.js'], // dest: 'build/main.min.js' // } // } }); grunt.registerTask("serve", ["browserSync", "watch"]); grunt.registerTask("build", [ "less", "postcss" // "csso", // "concat", // "uglify" ]); };
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.m.Text sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control'], function(jQuery, library, Control) { "use strict"; /** * Constructor for a new Text. * * @param {string} [sId] ID for the new control, generated automatically if no ID is given * @param {object} [mSettings] Initial settings for the new control * * @class * The Text control can be used for embedding longer text paragraphs, that need text wrapping, into your application. * @extends sap.ui.core.Control * @implements sap.ui.core.IShrinkable * * @author SAP SE * @version 1.32.10 * * @constructor * @public * @alias sap.m.Text * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var Text = Control.extend("sap.m.Text", /** @lends sap.m.Text.prototype */ { metadata : { interfaces : [ "sap.ui.core.IShrinkable" ], library : "sap.m", properties : { /** * Determines the text to be displayed. */ text : {type : "string", defaultValue : '', bindable : "bindable"}, /** * Available options for the text direction are LTR and RTL. By default the control inherits the text direction from its parent control. */ textDirection : {type : "sap.ui.core.TextDirection", group : "Appearance", defaultValue : sap.ui.core.TextDirection.Inherit}, /** * Enables text wrapping. */ wrapping : {type : "boolean", group : "Appearance", defaultValue : true}, /** * Sets the horizontal alignment of the text. */ textAlign : {type : "sap.ui.core.TextAlign", group : "Appearance", defaultValue : sap.ui.core.TextAlign.Begin}, /** * Sets the width of the Text control. By default, the Text control uses the full width available. Set this property to restrict the width to a custom value. */ width : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null}, /** * Limits the number of lines for wrapping texts. * * Note: The multi-line overflow indicator depends on the browser line clamping support. For such browsers, this will be shown as ellipsis, for the other browsers the overflow will just be hidden. * @since 1.13.2 */ maxLines : {type : "int", group : "Appearance", defaultValue : null} } }}); /** * Default line height value as a number when line-height is normal. * * This value is required during max-height calculation for the browsers that do not support line-clamping. * It is better to define line-height in CSS instead of "normal" to get consistent maxLines results since normal line-height * not only varies from browser to browser but they also vary from one font face to another and can also vary within a given face. * * Default value is 1.2 * * @since 1.22 * @protected * @type {number} */ Text.prototype.normalLineHeight = 1.2; /** * Determines per instance whether line height should be cached or not. * * Default value is true. * * @since 1.22 * @protected * @type {boolean} */ Text.prototype.cacheLineHeight = true; /** * Ellipsis(…) text to indicate more text when clampText function is used. * * Can be overwritten with 3dots(...) if fonts do not support this UTF-8 character. * * @since 1.13.2 * @protected * @type {string} */ Text.prototype.ellipsis = '…'; /** * Defines whether browser supports native line clamp or not * * @since 1.13.2 * @returns {boolean} * @protected * @readonly * @static */ Text.hasNativeLineClamp = (function() { return (typeof document.documentElement.style.webkitLineClamp != "undefined"); })(); /** * To prevent from the layout thrashing of the textContent call, this method * first tries to set the nodeValue of the first child if it exists. * * @param {HTMLElement} oDomRef DOM reference of the text node container. * @param {String} [sNodeValue] new Node value. * @since 1.30.3 * @protected * @static */ Text.setNodeValue = function(oDomRef, sNodeValue) { sNodeValue = sNodeValue || ""; var aChildNodes = oDomRef.childNodes; if (aChildNodes.length == 1) { aChildNodes[0].nodeValue = sNodeValue; } else { oDomRef.textContent = sNodeValue; } }; // suppress invalidation of text property setter Text.prototype.setText = function(sText) { this.setProperty("text", sText , true); // check text dom ref var oDomRef = this.getTextDomRef(); if (oDomRef) { // update the node value of the DOM text Text.setNodeValue(oDomRef, this.getText(true)); // toggles the sapMTextBreakWord class when the text value is changed if (this.getWrapping()) { // no space text must break if (sText && !/\s/.test(sText)) { this.$().addClass("sapMTextBreakWord"); } else { this.$().removeClass("sapMTextBreakWord"); } } } return this; }; // returns the text value and normalize line-ending character for rendering Text.prototype.getText = function(bNormalize) { var sText = this.getProperty("text"); // handle line ending characters for renderer if (bNormalize) { return sText.replace(/\\r\\n|\\n/g, "\n"); } return sText; }; // required adaptations after rendering Text.prototype.onAfterRendering = function() { // check visible, max-lines and line-clamping support if (this.getVisible() && this.hasMaxLines() && !this.canUseNativeLineClamp()) { // set max-height for maxLines support this.clampHeight(); } }; /** * Determines whether max lines should be rendered or not. * * @since 1.22 * @protected * @returns {HTMLElement|null} */ Text.prototype.hasMaxLines = function() { return (this.getWrapping() && this.getMaxLines() > 1); }; /** * Returns the text node container's DOM reference. * * This can be different from getDomRef when inner wrapper is needed. * * @since 1.22 * @protected * @returns {HTMLElement|null} */ Text.prototype.getTextDomRef = function() { if (!this.getVisible()) { return null; } if (this.hasMaxLines()) { return this.getDomRef("inner"); } return this.getDomRef(); }; /** * Decides whether the control can use native line clamp feature or not. * * In RTL mode native line clamp feature is not supported. * * @since 1.20 * @protected * @return {Boolean} */ Text.prototype.canUseNativeLineClamp = function() { // has line clamp feature if (!Text.hasNativeLineClamp) { return false; } // is text direction rtl var oDirection = sap.ui.core.TextDirection; if (this.getTextDirection() == oDirection.RTL) { return false; } // is text direction inherited as rtl if (this.getTextDirection() == oDirection.Inherit && sap.ui.getCore().getConfiguration().getRTL()) { return false; } return true; }; /** * Caches and returns the computed line height of the text. * * @since 1.22 * @protected * @see sap.m.Text#cacheLineHeight * @param {HTMLElement} [oDomRef] DOM reference of the text container. * @returns {Number} returns calculated line-height */ Text.prototype.getLineHeight = function(oDomRef) { // return cached value if possible and available if (this.cacheLineHeight && this._fLineHeight) { return this._fLineHeight; } // check whether dom ref exist or not oDomRef = oDomRef || this.getTextDomRef(); if (!oDomRef) { return 0; } // check line-height var oStyle = window.getComputedStyle(oDomRef), sLineHeight = oStyle.lineHeight, fLineHeight; // calculate line-height in px if (/px$/i.test(sLineHeight)) { // we can rely on calculated px line-height value fLineHeight = parseFloat(sLineHeight); } else if (/^normal$/i.test(sLineHeight)) { // use default value to calculate normal line-height fLineHeight = parseFloat(oStyle.fontSize) * this.normalLineHeight; } else { // calculate line-height with using font-size and line-height fLineHeight = parseFloat(oStyle.fontSize) * parseFloat(sLineHeight); } // on rasterizing the font, sub pixel line-heights are converted to integer // for most of the font rendering engine but this is not the case for firefox if (!sap.ui.Device.browser.firefox) { fLineHeight = Math.floor(fLineHeight); } // cache line height if (this.cacheLineHeight && fLineHeight) { this._fLineHeight = fLineHeight; } // return return fLineHeight; }; /** * Returns the max height according to max lines and line height calculation. * * This is not calculated max-height! * * @since 1.22 * @protected * @param {HTMLElement} [oDomRef] DOM reference of the text container. * @returns {Number} */ Text.prototype.getClampHeight = function(oDomRef) { oDomRef = oDomRef || this.getTextDomRef(); return this.getMaxLines() * this.getLineHeight(oDomRef); }; /** * Sets the max-height to support maxLines property. * * @since 1.22 * @protected * @param {HTMLElement} [oDomRef] DOM reference of the text container. * @returns {Number} calculated max height value */ Text.prototype.clampHeight = function(oDomRef) { oDomRef = oDomRef || this.getTextDomRef(); if (!oDomRef) { return 0; } // calc the max height and set on dom var iMaxHeight = this.getClampHeight(oDomRef); if (iMaxHeight) { oDomRef.style.maxHeight = iMaxHeight + "px"; } return iMaxHeight; }; /** * Clamps the wrapping text according to max lines and returns the found ellipsis position. * * Parameters can be used for better performance. * * @param {HTMLElement} [oDomRef] DOM reference of the text container. * @param {number} [iStartPos] Start point of the ellipsis search. * @param {number} [iEndPos] End point of the ellipsis search. * @returns {number|undefined} Returns found ellipsis position or undefined * @since 1.20 * @protected */ Text.prototype.clampText = function(oDomRef, iStartPos, iEndPos) { // check DOM reference oDomRef = oDomRef || this.getTextDomRef(); if (!oDomRef) { return; } // init var iEllipsisPos; var sText = this.getText(true); var iMaxHeight = this.getClampHeight(oDomRef); // init positions iStartPos = iStartPos || 0; iEndPos = iEndPos || sText.length; // update only the node value without layout thrashing Text.setNodeValue(oDomRef, sText.slice(0, iEndPos)); // if text overflow if (oDomRef.scrollHeight > iMaxHeight) { // cache values var oStyle = oDomRef.style, sHeight = oStyle.height, sEllipsis = this.ellipsis, iEllipsisLen = sEllipsis.length; // set height during ellipsis search oStyle.height = iMaxHeight + "px"; // implementing binary search to find the position of ellipsis // complexity O(logn) so 1024 characters text can be found within 10 steps! while ((iEndPos - iStartPos) > iEllipsisLen) { // check the middle position and update text iEllipsisPos = (iStartPos + iEndPos) >> 1; // update only the node value without layout thrashing Text.setNodeValue(oDomRef, sText.slice(0, iEllipsisPos - iEllipsisLen) + sEllipsis); // check overflow if (oDomRef.scrollHeight > iMaxHeight) { iEndPos = iEllipsisPos; } else { iStartPos = iEllipsisPos; } } // last check maybe we overflowed on last character if (oDomRef.scrollHeight > iMaxHeight && iStartPos > 0) { iEllipsisPos = iStartPos; oDomRef.textContent = sText.slice(0, iEllipsisPos - iEllipsisLen) + sEllipsis; } // reset height oStyle.height = sHeight; } // return the found position return iEllipsisPos; }; return Text; }, /* bExport= */ true);
import React, { Component } from 'react'; import { View, Slider } from 'react-native'; import { observer } from 'mobx-react/native'; import { Container, Header, Content, Button, Title, Spinner, Card, CardItem, Text, Icon, Left, Right, Body, H1 } from 'native-base'; import { Item, ItemIcon, ItemContent, ItemText, Note, List } from 'carbon-native'; import nowPlayingStore from '../stores/now_playing_store'; import streamsStore from '../stores/streams_store'; import icon from '../services/icon'; import Toast from '../services/toast'; @observer export default class NowPlaying extends Component { componentDidMount = () => { nowPlayingStore.reload(); } changeVolumeDelayed = (newVolume) => { clearTimeout(this.volumeChangeTimeout); this.volumeChangeTimeout = setTimeout(() => { nowPlayingStore.changeVolume(parseInt(newVolume * 10, 10) * 10); }, 1000); } playPredefined = async (stream) => { Toast.show('Wait...'); try { await stream.play(); Toast.show('Done!'); await nowPlayingStore.reload(); } catch (e) { Toast.show('Error!'); } } render = () => ( <Container style={{ backgroundColor: '#ffffff' }}> <Header> <Left> <Button transparent onPress={() => this.props.navigation.goBack()}> <Icon name={icon('arrow-back')} /> </Button> </Left> <Body> <Title>Now playing</Title> </Body> <Right> <Button transparent onPress={() => { this.props.navigation.navigate('StreamsSearch'); }}> <Icon name={icon('search')} /> </Button> </Right> </Header> <Content> <Card> { nowPlayingStore.isWorking && <View> <CardItem header> <Text>Reloading...</Text> </CardItem> <CardItem> <Spinner color="#f95346" /> </CardItem> </View> } { !nowPlayingStore.isWorking && <View> <CardItem header> <Text>Stream info</Text> </CardItem> <CardItem> <Body> <H1>{nowPlayingStore.nowPlayingName}</H1> <Text>{nowPlayingStore.nowPlayingUrl}</Text> </Body> </CardItem> <CardItem header> <Body> <Text>Volume</Text> </Body> </CardItem> <CardItem> <Body> <Slider style={{ width: '100%' }} minimumTrackTintColor="#f95346" thumbTintColor="#9e3128" onValueChange={v => this.changeVolumeDelayed(v)} value={nowPlayingStore.volume / 100} /> </Body> </CardItem> </View> } <View> <CardItem header> <Text>Predefined streams</Text> </CardItem> <List> { streamsStore.predefined.map(stream => ( <Item key={stream.id} onPress={() => this.playPredefined(stream)}> <ItemIcon> <Icon name={icon('play')} /> </ItemIcon> <ItemContent> <ItemText>{stream.name}</ItemText> <Note>{stream.genre}</Note> </ItemContent> </Item> )) } </List> </View> </Card> </Content> </Container> ) }
if (jasmine.TrivialConsoleReporter) { describe("TrivialConsoleReporter", function() { //keep these literal. otherwise the test loses value as a test. function green(str) { return '\033[32m' + str + '\033[0m'; } function red(str) { return '\033[31m' + str + '\033[0m'; } function yellow(str) { return '\033[33m' + str + '\033[0m'; } function prefixGreen(str) { return '\033[32m' + str; } function prefixRed(str) { return '\033[31m' + str; } var newline = "\n"; var passingSpec = { results: function(){ return {passed: function(){return true;}}; } }, failingSpec = { results: function(){ return {passed: function(){return false;}}; } }, skippedSpec = { results: function(){ return {skipped: true}; } }, passingRun = { results: function(){ return {failedCount: 0, items_: [null, null, null]}; } }, failingRun = { results: function(){ return {failedCount: 7, items_: [null, null, null]}; } }; function repeatedlyInvoke(f, times) { for(var i=0; i<times; i++) f(times+1); } function repeat(thing, times) { var arr = []; for(var i=0; i<times; i++) arr.push(thing); return arr; } var fiftyRedFs = repeat(red("F"), 50).join(""), fiftyGreenDots = repeat(green("."), 50).join(""); function simulateRun(reporter, specResults, suiteResults, finalRunner, startTime, endTime) { reporter.reportRunnerStarting(); for(var i=0; i<specResults.length; i++) reporter.reportSpecResults(specResults[i]); for(i=0; i<suiteResults.length; i++) reporter.reportSuiteResults(suiteResults[i]); reporter.runnerStartTime = startTime; reporter.now = function(){return endTime;}; reporter.reportRunnerResults(finalRunner); } beforeEach(function() { this.out = (function(){ var output = ""; return { print:function(str) {output += str;}, getOutput:function(){return output;}, clear: function(){output = "";} }; })(); this.done = false var self = this this.reporter = new jasmine.TrivialConsoleReporter(this.out.print, function(runner){ self.done = true }); }); describe('Integration', function(){ it("prints the proper output under a pass scenario. small numbers.", function(){ simulateRun(this.reporter, repeat(passingSpec, 3), [], { results:function(){ return { items_: [null, null, null], totalCount: 7, failedCount: 0 }; } }, 1000, 1777); expect(this.out.getOutput()).toEqual( [ "Started", green(".") + green(".") + green("."), "", "Finished in 0.777 seconds", green("3 specs, 7 expectations, 0 failures"), "" ].join("\n") + "\n" ); }); it("prints the proper output under a pass scenario. large numbers.", function(){ simulateRun(this.reporter, repeat(passingSpec, 57), [], { results:function(){ return { items_: [null, null, null], totalCount: 7, failedCount: 0 }; } }, 1000, 1777); expect(this.out.getOutput()).toEqual( [ "Started", green(".") + green(".") + green(".") + green(".") + green(".") + //50 green dots green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + green(".") + newline + green(".") + green(".") + green(".") + green(".") + green(".") + //7 green dots green(".") + green("."), "", "Finished in 0.777 seconds", green("3 specs, 7 expectations, 0 failures"), "" ].join("\n") + "\n" ); }); it("prints the proper output under a failure scenario.", function(){ simulateRun(this.reporter, [failingSpec, passingSpec, failingSpec], [{description:"The oven", results:function(){ return { items_:[ {failedCount:2, description:"heats up", items_:[ {trace:{stack:"stack trace one\n second line"}}, {trace:{stack:"stack trace two"}} ]} ] }; }}, {description:"The washing machine", results:function(){ return { items_:[ {failedCount:2, description:"washes clothes", items_:[ {trace:{stack:"stack trace one"}} ]} ] }; }} ], { results:function(){ return { items_: [null, null, null], totalCount: 7, failedCount: 2 }; } }, 1000, 1777); expect(this.out.getOutput()).toEqual( [ "Started", red("F") + green(".") + red("F"), "", "The oven heats up", " stack trace one", " second line", " stack trace two", "", "The washing machine washes clothes", " stack trace one", "", "Finished in 0.777 seconds", red("3 specs, 7 expectations, 2 failures"), "" ].join("\n") + "\n" ); }); }); describe('A Test Run', function(){ describe('Starts', function(){ it("prints Started", function(){ this.reporter.reportRunnerStarting(); expect(this.out.getOutput()).toEqual( "Started" + newline ); }); }); describe('A spec runs', function(){ it("prints a green dot if the spec passes", function(){ this.reporter.reportSpecResults(passingSpec); expect(this.out.getOutput()).toEqual( green(".") ); }); it("prints a red dot if the spec fails", function(){ this.reporter.reportSpecResults(failingSpec); expect(this.out.getOutput()).toEqual( red("F") ); }); it("prints a yellow star if the spec was skipped", function(){ this.reporter.reportSpecResults(skippedSpec); expect(this.out.getOutput()).toEqual( yellow("*") ); }); }); describe('Many specs run', function(){ it("starts a new line every 50 specs", function(){ var self = this; repeatedlyInvoke(function(){self.reporter.reportSpecResults(failingSpec);}, 49); expect(this.out.getOutput()). toEqual(repeat(red("F"), 49).join("")); repeatedlyInvoke(function(){self.reporter.reportSpecResults(failingSpec);}, 3); expect(this.out.getOutput()). toEqual(fiftyRedFs + newline + red("F") + red("F")); repeatedlyInvoke(function(){self.reporter.reportSpecResults(failingSpec);}, 48); repeatedlyInvoke(function(){self.reporter.reportSpecResults(passingSpec);}, 2); expect(this.out.getOutput()). toEqual(fiftyRedFs + newline + fiftyRedFs + newline + green(".") + green(".")); }); }); describe('A suite runs', function(){ it("remembers suite results", function(){ var emptyResults = function(){return {items_:[]};}; this.reporter.reportSuiteResults({description:"Oven", results:emptyResults}); this.reporter.reportSuiteResults({description:"Mixer", results:emptyResults}); var self = this; var descriptions = []; for(var i=0; i<self.reporter.suiteResults.length; i++) descriptions.push(self.reporter.suiteResults[i].description); expect(descriptions).toEqual(["Oven", "Mixer"]); }); it("creates a description out of the current suite and any parent suites", function(){ var emptyResults = function(){return {items_:[]};}; var grandparentSuite = {description:"My house", results:emptyResults}; var parentSuite = {description:"kitchen", parentSuite: grandparentSuite, results:emptyResults}; this.reporter.reportSuiteResults({description:"oven", parentSuite: parentSuite, results:emptyResults}); expect(this.reporter.suiteResults[0].description).toEqual("My house kitchen oven"); }); it("gathers failing spec results from the suite. the spec must have a description.", function(){ this.reporter.reportSuiteResults({description:"Oven", results:function(){ return { items_:[ {failedCount:0, description:"specOne"}, {failedCount:99, description:"specTwo"}, {failedCount:0, description:"specThree"}, {failedCount:88, description:"specFour"}, {failedCount:3} ] }; }}); expect(this.reporter.suiteResults[0].failedSpecResults). toEqual([ {failedCount:99, description:"specTwo"}, {failedCount:88, description:"specFour"} ]); }); }); describe('Finishes', function(){ describe('Spec failure information', function(){ it("prints suite and spec descriptions together as a sentence", function(){ this.reporter.suiteResults = [ {description:"The oven", failedSpecResults:[ {description:"heats up", items_:[]}, {description:"cleans itself", items_:[]} ]}, {description:"The mixer", failedSpecResults:[ {description:"blends things together", items_:[]} ]} ]; this.reporter.reportRunnerResults(failingRun); expect(this.out.getOutput()).toContain("The oven heats up"); expect(this.out.getOutput()).toContain("The oven cleans itself"); expect(this.out.getOutput()).toContain("The mixer blends things together"); }); it("prints stack trace of spec failure", function(){ this.reporter.suiteResults = [ {description:"The oven", failedSpecResults:[ {description:"heats up", items_:[ {trace:{stack:"stack trace one"}}, {trace:{stack:"stack trace two"}} ]} ]} ]; this.reporter.reportRunnerResults(failingRun); expect(this.out.getOutput()).toContain("The oven heats up"); expect(this.out.getOutput()).toContain("stack trace one"); expect(this.out.getOutput()).toContain("stack trace two"); }); }); describe('Finished line', function(){ it("prints the elapsed time in the summary message", function(){ this.reporter.now = function(){return 1000;}; this.reporter.reportRunnerStarting(); this.reporter.now = function(){return 1777;}; this.reporter.reportRunnerResults(passingRun); expect(this.out.getOutput()).toContain("0.777 seconds"); }); it("prints round time numbers correctly", function(){ var self = this; function run(startTime, endTime) { self.out.clear(); self.reporter.runnerStartTime = startTime; self.reporter.now = function(){return endTime;}; self.reporter.reportRunnerResults(passingRun); } run(1000, 11000); expect(this.out.getOutput()).toContain("10 seconds"); run(1000, 2000); expect(this.out.getOutput()).toContain("1 seconds"); run(1000, 1100); expect(this.out.getOutput()).toContain("0.1 seconds"); run(1000, 1010); expect(this.out.getOutput()).toContain("0.01 seconds"); run(1000, 1001); expect(this.out.getOutput()).toContain("0.001 seconds"); }); it("prints the full finished message", function(){ this.reporter.now = function(){return 1000;}; this.reporter.reportRunnerStarting(); this.reporter.now = function(){return 1777;}; this.reporter.reportRunnerResults(failingRun); expect(this.out.getOutput()).toContain("Finished in 0.777 seconds"); }); }); describe("specs/expectations/failures summary", function(){ it("prints statistics in green if there were no failures", function() { this.reporter.reportRunnerResults({ results:function(){return {items_: [null, null, null], totalCount: 7, failedCount: 0};} }); expect(this.out.getOutput()). toContain("3 specs, 7 expectations, 0 failures"); }); it("prints statistics in red if there was a failure", function() { this.reporter.reportRunnerResults({ results:function(){return {items_: [null, null, null], totalCount: 7, failedCount: 3};} }); expect(this.out.getOutput()). toContain("3 specs, 7 expectations, 3 failures"); }); it("handles pluralization with 1's ones appropriately", function() { this.reporter.reportRunnerResults({ results:function(){return {items_: [null], totalCount: 1, failedCount: 1};} }); expect(this.out.getOutput()). toContain("1 spec, 1 expectation, 1 failure"); }); }); describe("done callback", function(){ it("calls back when done", function() { expect(this.done).toBeFalsy(); this.reporter.reportRunnerResults({ results:function(){return {items_: [null, null, null], totalCount: 7, failedCount: 0};} }); expect(this.done).toBeTruthy(); }); }); }); }); }); }
var Button = Button || function(root) { Button._super.constructor.call(this, root); this._mouseArea = new MouseArea(this); this._textures = {}; this._onEnter = function(button) { this.setDiffuseMap(this._textures.hover) }; this._onLeave = function(button) { this.setDiffuseMap(this._textures.default) }; this._onPressed = function(button) { this.setDiffuseMap(this._textures.pressed) }; this._onReleased = function(button) { this.setDiffuseMap(this._textures.hover) }; this._onDown = function(button) { }; this._onEnter.ctx = this; this._onLeave.ctx = this; this._onPressed.ctx = this; this._onReleased.ctx = this; this._onDown.ctx = this; this._mouseArea.setOnEnter(this._onEnter); this._mouseArea.setOnLeave(this._onLeave); this._mouseArea.setOnPressed(this._onPressed); this._mouseArea.setOnReleased(this._onReleased); this._mouseArea.setOnDown(this._onDown); } _.inherit(Button, Widget); _.extend(Button.prototype, { setActivated: function(v) { this._mouseArea.setActivated(v); }, setTextures: function(texture, hover, pressed) { this._textures.default = texture !== null ? texture : this._textures.default; this._textures.hover = hover !== null ? hover : this._textures.hover; this._textures.pressed = pressed !== null ? pressed : this._textures.pressed; if (this._textures.hover == null) { this._textures.hover = this._textures.default; } if (this._textures.pressed == null) { this._textures.pressed = this._textures.default; } this.setDiffuseMap(texture); }, setOnEnter: function(func, ctx) { var self = this; this._onEnter = function(button) { func.call(self._onEnter.ctx, button); self.setDiffuseMap(self._textures.default); } this._onEnter.ctx = ctx || this; this._mouseArea.setOnEnter(this._onEnter); }, setOnLeave: function(func, ctx) { var self = this; this._onLeave = function(button) { func.call(self._onLeave.ctx, button); self.setDiffuseMap(self._textures.default); } this._onLeave.ctx = ctx || this; this._mouseArea.setOnLeave(this._onLeave); }, setOnPressed: function(func, ctx) { var self = this; this._onPressed = function(button) { func.call(self._onPressed.ctx, button); self.setDiffuseMap(self._textures.pressed); } this._onPressed.ctx = ctx || this; this._mouseArea.setOnPressed(this._onPressed); }, setOnReleased: function(func, ctx) { var self = this; this._onReleased = function(button) { func.call(self._onReleased.ctx, button); self.setDiffuseMap(self._textures.hover); } this._onReleased.ctx = ctx || this; this._mouseArea.setOnReleased(this._onReleased); }, setOnDown: function(func, ctx) { var self = this; this._onDown = function(button) { func.call(self._onDown.ctx, button); func(button, this); } this._onDown.ctx = ctx || this; this._mouseArea.setOnDown(this._onDown); } });
import React from 'react'; import { connect } from 'react-redux'; import AddForm from './AddForm'; import ListForm from './ListForm'; const App = connect()( () => ( <div> <div> [Display System Message] </div> <AddForm /> <ListForm /> </div> ) ); export default App;
/** * @jsx React.DOM */ bone.router({ overview: function() { React.renderComponent(UI({section: "wallet", wallet: "overview"}), document.getElementById('snowcoins-react')); }, redirect: function() { bone.router.navigate('overview'); }, wallet: function(wallet,moon) { React.renderComponent(UI({section: "wallet", wallet: wallet, moon: moon}), document.getElementById('snowcoins-react')); }, settings: function(moon) { React.renderComponent(UI({section: "inqueue", moon: moon}), document.getElementById('snowcoins-react')); }, receive: function(moon) { React.renderComponent(UI({section: "inqueue", moon: moon}), document.getElementById('snowcoins-react')); }, inqueue: function(moon) { React.renderComponent(UI({section: "inqueue", moon: moon}), document.getElementById('snowcoins-react')); }, }); bone.router.routes[snowPath.root] = "redirect"; bone.router.routes[snowPath.root + snowPath.wallet] = "overview"; bone.router.routes[snowPath.root + snowPath.wallet + "/:wallet/:moon"] = "wallet"; bone.router.routes[snowPath.root + snowPath.receive + "/:moon"] = "receive"; bone.router.routes[snowPath.root + snowPath.settings + "/:moon"] = "settings" ; bone.router.routes[snowPath.root + snowPath.inqueue + "/:moon"] = "inqueue"; bone.router.start({pushState: true});
socket.on('disconnect', function() { sAccount.contacts.forEach(function(contact) { var eventName = "event:" + contact.accountId; app.removeEventListener(eventName, handleContactEvent); console.log("Unsubscribing from " + eventName); }); });
var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var expose = require('expose-loader'); module.exports = { devtool: 'sourcemap', entry: {}, module: { loaders: [ {test: require.resolve("jquery"), loader: "expose?$!expose?jQuery"}, {test: /\.js$/, exclude: [/app\/lib/, /node_modules/], loader: 'ng-annotate!babel'}, {test: /\.html$/, loader: 'raw'}, {test: /\.styl$/, loader: 'style!css!stylus'}, {test: /\.css$/, loader: 'style!css'}, {test: /\.less$/, loader: 'style!css!less'}, {test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff'}, {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'}, {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'}, {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'} ] }, plugins: [ // Injects bundles in your index.html instead of wiring all manually. // It also adds hash to all injected assets so we don't have problems // with cache purging during deployment. new HtmlWebpackPlugin({ template: 'client/index.html', inject: 'body', hash: true }), // Automatically move all modules defined outside of application directory to vendor bundle. // If you are using more complicated project structure, consider to specify common chunks manually. new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module, count) { return module.resource && module.resource.indexOf(path.resolve(__dirname, 'client')) === -1; } }) ] };
/** * Route.js * * @author: Harish Anchu <harishanchu@gmail.com> * @copyright Copyright (c) 2015-2016, QuorraJS. * @license See LICENSE.txt */ var _ = require('lodash'); var routeCompiler = require('./routeCompiler'); var str = require('../support/str'); var MethodValidator = require('./matching/MethodValidator'); var HostValidator = require('./matching/HostValidator'); var SchemeValidator = require('./matching/SchemeValidator'); var UriValidator = require('./matching/UriValidator'); var xregexp = require('xregexp'); function Route(methods, uri, action, filter) { /** * The URI pattern the route responds to. * * @var {string} * @protected */ this.__uri = uri; /** * The array of matched parameters. * * @var {Array} * @protected */ this.__parameters; /** * The parameter names for the route. * * @var {Array|null} */ this.__parameterNames; /** * The route action object. * * @var {Object} * @protected */ this.__action = this.__parseAction(action); /** * The HTTP methods the route responds to. * * @var{Array} * @protected */ this.__methods = parseArray(methods); if (isset(this.__action['prefix'])) { this.prefix(this.__action['prefix']); } /** * The regular expression requirements. * * @var {Object} * @protected */ this.__wheres = {}; /** * @type {null} * @protected */ this.__compiled = null; /** * Filter service instance. * * @var {object} * @protected */ this.__filter = filter; /** * @type {Array} * @private */ this.__requirements = []; /** * @type {Array} * @private */ this.__defaults = []; } /** * The validators used by the routes. * * @var {function[]} * @static */ Route.validators; /** * Parse the route action into a standard array. * * @param {function|Array} action * @return {Array} * @protected */ Route.prototype.__parseAction = function (action) { // If the action is already a Closure instance, we will just set that instance // as the "uses" property, because there is nothing else we need to do when // it is available. Otherwise we will need to find it in the action list. if (typeof action === 'function') { var temp = {}; temp['uses'] = action; return temp; } // If no "uses" property has been set, we will dig through the array to find a // Closure instance within this list. We will set the first Closure we come // across into the "uses" property that will get fired off by this route. else if (!isset(action['uses'])) { action['uses'] = this.__findClosure(action); } return action; }; /** * Find the Closure in an action array. * * @param {Array} action * @return {function} * @protected */ Route.prototype.__findClosure = function (action) { action = parseArray(action); return _.find(action, function (value) { return typeof value === 'function'; }); }; /** * Add a prefix to the route URI. * * @param {string} prefix * @return Route */ Route.prototype.prefix = function (prefix) { this.__uri = str.rtrim(prefix, '/') + '/' + str.ltrim(this.__uri, '/'); return this; }; /** * Get the domain defined for the route. * * @return string|null */ Route.prototype.domain = function () { return isset(this.__action['domain']) ? this.__action['domain'] : ''; }; /** * Get the URI that the route responds to. * * @return {string} */ Route.prototype.getUri = Route.prototype.uri = function () { return this.__uri; }; /** * Run the route action and return the response. * * @param {object} request * @param {object} response */ Route.prototype.run = function (request, response) { var parameters = _.filter(request.routeParameters, function (p) { return isset(p); }); parameters.unshift(request, response); this.__action['uses'].apply(this, parameters); }; /** * Parse arguments to the where method into an array. * * @param {Object} name * @param {String} expression * @return {object} * @protected */ Route.prototype.__parseWhere = function (name, expression) { if (isObject(name)) { return name; } else { var temp = {}; temp[name] = expression; return temp; } }; /** * Set a regular expression requirement on the route. * * @param {Array|String} name * @param {String} expression * @return Route */ Route.prototype.where = function (name, expression) { if (!isset(expression)) expression = null; var whereObject = this.__parseWhere(name, expression); for (name in whereObject) { if (whereObject.hasOwnProperty(name)) { this.__wheres[name] = whereObject[name]; } } return this; }; /** * Get the HTTP verbs the route responds to. * * @return {Array} */ Route.prototype.methods = function () { return this.__methods; }; /** * Get the optional parameters for the route. * * @return {Array} * @protected */ Route.prototype.__extractOptionalParameters = function () { var matchRegex = /\{(\w+?)\?\}/g; var match; var matches = []; while ((match = matchRegex.exec(this.__uri)) && matches.push(match[1])) { } return matches.length ? arrayFillKeys(matches, null) : []; }; /** * Compile the route into a CompiledRoute instance. * * @return {void} * @protected */ Route.prototype.__compileRoute = function () { if (this.__compiled == null) { var optionals = this.__extractOptionalParameters(); this.__setDefaults(optionals); this.__setRequirements(this.__wheres); this.__compiled = routeCompiler.compile(this); } }; /** * Get the name of the route instance. * * @return string */ Route.prototype.getName = function () { return isset(this.__action['as']) ? this.__action['as'] : null; }; /** * Get the action name for the route. * * @return {String} */ Route.prototype.getActionName = function () { return isset(this.__action['controller']) ? this.__action['controller'] : 'Closure'; }; /** * Get the action object for the route. * * @return Object */ Route.prototype.getAction = function () { return this.__action; }; /** * Set the action object for the route. * * @param action * @return Route */ Route.prototype.setAction = function (action) { this.__action = action; return this; }; /** * Get the HTTP verbs the route responds to. * * @return {Array} */ Route.prototype.methods = function () { if (this.__methods.indexOf('GET') !== -1 && this.__methods.indexOf('HEAD') === -1) { this.__methods.push('HEAD'); } return this.__methods; }; /** * Determine if the route only responds to HTTP requests. * * @return {boolean} */ Route.prototype.httpOnly = function () { return !!(this.__action['http'] && this.__action['http'] === true); }; /** * Determine if the route only responds to HTTPS requests. * * @return {boolean} */ Route.prototype.secure = function () { return !!(this.__action['https'] && this.__action['https'] === true); }; /** * Get the route validators for the instance. * * @return {Array} */ Route.prototype.getValidators = function () { if (isset(Route.validators)) return Route.validators; // To match the route, we will use a chain of responsibility pattern with the // validator implementations. We will spin through each one making sure it // passes and then we will know if the route as a whole matches request. return Route.validators = [ new MethodValidator, new SchemeValidator, new HostValidator, new UriValidator ]; }; /** * Determine if the route matches given request. * * @param request * @param {boolean} includingMethod * @return {boolean} */ Route.prototype.matches = function (request, includingMethod) { if (!isset(includingMethod)) includingMethod = true; this.__compileRoute(); var validators = this.getValidators(); var validator; var k; for (k in validators) { if (validators.hasOwnProperty(k)) { validator = validators[k]; if (!includingMethod && validator instanceof MethodValidator) continue; if (!validator.matches(this, request)) return false; } } return true; }; /** * Bind the route to a given request for execution. * * @param request * @returns {Route} */ Route.prototype.bind = function (request) { this.__compileRoute(); this.bindParameters(request); return this; }; /** * Extract the parameter list from the request. * * @param request * @return {Array} */ Route.prototype.bindParameters = function (request) { // If the route has a regular expression for the path part of the URI, we will // compile that and get the parameter matches for this path. var pathParameters = this.__bindPathParameters(request); pathParameters.shift(); delete pathParameters['index']; delete pathParameters['input']; var params = this.matchToKeys( pathParameters ); // If the route has a regular expression for the host part of the URI, we will // compile that and get the parameter matches for this domain. We will then // merge them into this parameters object so that this object is completed. if (!isNull(this.__compiled.getHostRegex())) { params = this.__bindHostParameters( request, params ); } return request.params = this.__replaceDefaults(params); }; /** * Get the parameter matches for the path portion of the URI. * * @param request * @return {Array} */ Route.prototype.__bindPathParameters = function (request) { var uriPath = ('/' + str.trim(request.path, '/') == "" ? "/" : '/' + str.trim(request.path, '/')); return xregexp.exec(uriPath, this.__compiled.getRegex()); }; /** * Extract the parameter list from the host part of the request. * * @param request * @param parameters * @return {Array} */ Route.prototype.__bindHostParameters = function (request, parameters) { var matches = xregexp.exec(request.host, this.__compiled.getHostRegex()); matches.shift(); delete matches['index']; delete matches['input']; return _.merge(this.matchToKeys(matches), parameters); }; /** * Combine a set of parameter matches with the route's keys. * * @param {Array} matches * @return {Object} */ Route.prototype.matchToKeys = function (matches) { var parameterNames = this.parameterNames(); if (parameterNames.length == 0) return []; var key, parameters = {}; for (key in parameterNames) { if (isset(matches[parameterNames[key]])) parameters[parameterNames[key]] = matches[parameterNames[key]]; } Object.keys(parameters).filter(function (value) { return !(_.isString(value) && value.length > 0); }).forEach(function (v) { delete parameters[v]; }); return parameters; }; /** * Get all of the parameter names for the route. * * @return array */ Route.prototype.parameterNames = function () { if (isset(this.__parameterNames)) return this.__parameterNames; return this.__parameterNames = this.__compileParameterNames(); }; /** * Get the parameter names for the route. * * @return {Array} */ Route.prototype.__compileParameterNames = function () { var matches = [], pattern = /\{(.*?)\}/g; var match; while ((match = pattern.exec(this.domain() + this.__uri)) && matches.push(match[1])) { } return matches.map(function (m) { return str.trim(m, '?'); }); }; /** * Replace null parameters with their defaults. * * @param {Array} parameters * @return {Array} */ Route.prototype.__replaceDefaults = function (parameters) { var key, value; for (key in parameters) { if (parameters.hasOwnProperty(key)) { value = isset(parameters[key]) ? parameters[key] : objectGet(this.__defaults, key); } } return parameters; }; /** * Get the compiled version of the route. * * @return {CompiledRoute} */ Route.prototype.getCompiled = function () { return this.__compiled; }; /** * Get the "before" filters for the route. * * @return {Object} */ Route.prototype.beforeFilters = function () { if (!isset(this.__action['before'])) return {}; return this.__filter.parseFilters(this.__action['before']); }; /** * Checks if a default value is set for the given variable. * * @param {String} name A variable name * * @return {boolean} true if the default value is set, false otherwise */ Route.prototype.hasDefault = function (name) { return name in this.__defaults; }; /** * Returns the pattern for the path without optional symbol(?). * * @return {String} The path pattern */ Route.prototype.getPath = function () { return '/' + str.ltrim(this.__uri.replace(/\{(\w*?)\?\}/g, '{$1}').trim(), '/'); }; /** * Sets the defaults. * * @param {Array} defaults The defaults * * @return Route The current Route instance */ Route.prototype.__setDefaults = function (defaults) { if (!isset(defaults)) defaults = []; this.__defaults = []; return this.__addDefaults(defaults); }; /** * Adds defaults. * * This method implements a fluent interface. * * @param {Array} defaults The defaults * * @return Route The current Route instance */ Route.prototype.__addDefaults = function (defaults) { var name, defaultVal; for (name in defaults) { defaultVal = defaults[name]; this.__defaults[name] = defaultVal; } this.__compiled = null; return this; }; /** * Sets the requirements. * * This method implements a fluent interface. * * @param {Array} requirements The requirements * * @return Route The current Route instance */ Route.prototype.__setRequirements = function (requirements) { this.__requirements = []; return this.__addRequirements(requirements); }; /** * Adds requirements. * * This method implements a fluent interface. * * @param {Array} requirements The requirements * * @return Route The current Route instance */ Route.prototype.__addRequirements = function (requirements) { var key, regex; for (key in requirements) { if (requirements.hasOwnProperty(key)) { regex = requirements[key]; this.__requirements[key] = this.__sanitizeRequirement(key, regex); } } this.__compiled = null; return this; }; /** * @param key * @param regex * @returns {*} * @private */ Route.prototype.__sanitizeRequirement = function (key, regex) { if (!_.isString(regex)) { throw new Error('Routing requirement for ' + key + ' must be a string.'); } if ('' !== regex && '^' === regex[0]) { regex = regex.substr(1); // returns false for a single character if (regex === "") regex = false; } if ('$' === regex.substr(-1)) { regex = regex.slice(0, -1); } if ('' === regex) { throw new Error('Routing requirement for ' + key + ' cannot be empty.'); } return regex; }; /** * Returns the requirement for the given key. * * @param {String} key The key * * @return {String | null} The regex or null when not given */ Route.prototype.getRequirement = function (key) { return isset(this.__requirements[key]) ? this.__requirements[key] : null; }; module.exports = Route;
var User = require('./User'); var user = new User('jinfei'); user.sex = '男'; user.skill = ['java','c','c#','android']; console.log(user);
jest.autoMockOff() import { Board } from 'firmata' import Kefir from 'kefir' import oneWire from '../oneWire' describe('#sensors.oneWire', () => { pit('should emit error if an search error occured', () => { return new Promise((resolve) => { let board = new Board() board.sendOneWireSearch.mockImplementation((pin, cb) => { cb(new Error('Search error')) }) let hasError = false oneWire(board, 1, 0, jest.genMockFn()).onError((error) => { hasError = true expect(error.message).toBe('Search error') }).onEnd(() => { expect(hasError).toBe(true) resolve() }) }) }) pit('should emit error if sensor with pin and index does not exist', () => { return new Promise((resolve) => { let board = new Board() board.sendOneWireSearch.mockImplementation((pin, cb) => { cb(null, [[0xC0, 0xFF, 0xEE], [0xD0, 0x0D]]) }) let hasError = false oneWire(board, 1, 2, jest.genMockFn()).onError((error) => { hasError = true expect(error.message).toBe('OneWire sensor on pin 1 with index 2 does not exist.') }).onEnd(() => { expect(hasError).toBe(true) resolve() }) }) }) pit('should call sensor if find address', () => { return new Promise((resolve) => { let board = new Board() let addresses = [[0xC0, 0xFF, 0xEE]] board.sendOneWireSearch.mockImplementation((pin, cb) => { cb(null, addresses) }) let sensor = jest.genMockFn().mockReturnValue(Kefir.interval(1000, 42)) oneWire(board, 1, 0, sensor).onValue((value) => { expect(value).toBe(42) expect(sensor).toBeCalledWith(board, 1, addresses[0]) resolve() }) jest.runOnlyPendingTimers() }) }) })