code
stringlengths
2
1.05M
module.exports = function (grunt) { // Define a zip task grunt.initConfig({ zip: { 'build/release/lambda-cd.zip': ['index.js', 'node_modules/**'] } }); // Load in `grunt-zip` grunt.loadNpmTasks('grunt-zip'); };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _db = require('../db'); var _db2 = _interopRequireDefault(_db); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class User { static findOne(...args) { return _db2.default.table('users').where(...args).first('id', 'email'); } static findOneAccessToken(userId) { return _db2.default.table('users').leftJoin('user_claims', 'users.id', 'user_claims.user_id').where({ 'user_claims.user_id': userId }).first('email', 'type', 'value'); } static findOneByLogin(provider, key) { return _db2.default.table('users').leftJoin('user_logins', 'users.id', 'user_logins.user_id').where({ 'user_logins.name': provider, 'user_logins.key': key }).first('id', 'email'); } static any(...args) { return _db2.default.raw('SELECT EXISTS ?', _db2.default.table('users').where(...args).select(_db2.default.raw('1'))).then(x => x.rows[0].exists); } static create(user) { return _db2.default.table('users').insert(user, ['id', 'email']).then(x => x[0]); } static setClaims(userId, provider, providerKey, claims) { return _db2.default.transaction(trx => Promise.all([trx.table('user_logins').insert({ user_id: userId, name: provider, key: providerKey }), ...claims.map(claim => trx.raw('SELECT EXISTS ?', trx.table('user_claims').where({ user_id: userId, type: claim.type })).then(x => x.rows[0].exists ? // eslint-disable-line no-confusing-arrow trx.table('user_claims').where({ user_id: userId, type: claim.type }).update({ value: claim.value }) : trx.table('user_claims').insert({ user_id: userId, type: claim.type, value: claim.value })))])); } } /** * Node.js API Starter Kit (https://reactstarter.com/nodejs) * * Copyright © 2016-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ exports.default = User; //# sourceMappingURL=User.js.map
import Authentication from './app/utils/authentication'; import { app, BrowserWindow, ipcMain, Menu, shell } from 'electron'; let menu; let template; let mainWindow = null; if (process.env.NODE_ENV === 'development') { require('electron-debug')(); } app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); }); app.on('ready', () => { if (mainWindow) return; Authentication.authorized(() => { global.vkAccount = Authentication.defaultAccount(); mainWindow = new BrowserWindow({ show: false, width: 1024, height: 728 }); mainWindow.loadURL(`file://${__dirname}/app/app.html`); mainWindow.webContents.on('did-finish-load', () => { mainWindow.show(); mainWindow.focus(); }); mainWindow.on('closed', () => { mainWindow = null; }); if (process.env.NODE_ENV === 'development') { mainWindow.openDevTools(); } if (process.platform === 'darwin') { template = [{ label: 'Electron', submenu: [{ label: 'About ElectronReact', selector: 'orderFrontStandardAboutPanel:' }, { type: 'separator' }, { label: 'Services', submenu: [] }, { type: 'separator' }, { label: 'Hide ElectronReact', accelerator: 'Command+H', selector: 'hide:' }, { label: 'Hide Others', accelerator: 'Command+Shift+H', selector: 'hideOtherApplications:' }, { label: 'Show All', selector: 'unhideAllApplications:' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click() { app.quit(); } }] }, { label: 'Edit', submenu: [{ label: 'Undo', accelerator: 'Command+Z', selector: 'undo:' }, { label: 'Redo', accelerator: 'Shift+Command+Z', selector: 'redo:' }, { type: 'separator' }, { label: 'Cut', accelerator: 'Command+X', selector: 'cut:' }, { label: 'Copy', accelerator: 'Command+C', selector: 'copy:' }, { label: 'Paste', accelerator: 'Command+V', selector: 'paste:' }, { label: 'Select All', accelerator: 'Command+A', selector: 'selectAll:' }] }, { label: 'View', submenu: (process.env.NODE_ENV === 'development') ? [{ label: 'Reload', accelerator: 'Command+R', click() { mainWindow.restart(); } }, { label: 'Toggle Full Screen', accelerator: 'Ctrl+Command+F', click() { mainWindow.setFullScreen(!mainWindow.isFullScreen()); } }, { label: 'Toggle Developer Tools', accelerator: 'Alt+Command+I', click() { mainWindow.toggleDevTools(); } }] : [{ label: 'Toggle Full Screen', accelerator: 'Ctrl+Command+F', click() { mainWindow.setFullScreen(!mainWindow.isFullScreen()); } }] }, { label: 'Window', submenu: [{ label: 'Minimize', accelerator: 'Command+M', selector: 'performMiniaturize:' }, { label: 'Close', accelerator: 'Command+W', selector: 'performClose:' }, { type: 'separator' }, { label: 'Bring All to Front', selector: 'arrangeInFront:' }] }, { label: 'Help', submenu: [{ label: 'Learn More', click() { shell.openExternal('http://electron.atom.io'); } }, { label: 'Documentation', click() { shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme'); } }, { label: 'Community Discussions', click() { shell.openExternal('https://discuss.atom.io/c/electron'); } }, { label: 'Search Issues', click() { shell.openExternal('https://github.com/atom/electron/issues'); } }] }]; menu = Menu.buildFromTemplate(template); Menu.setApplicationMenu(menu); } else { template = [{ label: '&File', submenu: [{ label: '&Open', accelerator: 'Ctrl+O' }, { label: '&Close', accelerator: 'Ctrl+W', click() { mainWindow.close(); } }] }, { label: '&View', submenu: (process.env.NODE_ENV === 'development') ? [{ label: '&Reload', accelerator: 'Ctrl+R', click() { mainWindow.restart(); } }, { label: 'Toggle &Full Screen', accelerator: 'F11', click() { mainWindow.setFullScreen(!mainWindow.isFullScreen()); } }, { label: 'Toggle &Developer Tools', accelerator: 'Alt+Ctrl+I', click() { mainWindow.toggleDevTools(); } }] : [{ label: 'Toggle &Full Screen', accelerator: 'F11', click() { mainWindow.setFullScreen(!mainWindow.isFullScreen()); } }] }, { label: 'Help', submenu: [{ label: 'Learn More', click() { shell.openExternal('http://electron.atom.io'); } }, { label: 'Documentation', click() { shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme'); } }, { label: 'Community Discussions', click() { shell.openExternal('https://discuss.atom.io/c/electron'); } }, { label: 'Search Issues', click() { shell.openExternal('https://github.com/atom/electron/issues'); } }] }]; menu = Menu.buildFromTemplate(template); mainWindow.setMenu(menu); } }); }); ipcMain.on('start-authentication', (event) => { const auth = new Authentication((token) => { Authentication.addToken(token, () => { event.sender.send('finish-authentication', token); }); }); });
define([ 'component/alt/blink/controller' ], function(){ return ['$scope', '$routeParams', '$log', function($scope, $routeParams, $log){ }]; });
// @flow import React, { PureComponent } from 'react'; export class MenubarItem extends PureComponent { render() { return <li>{this.props.children}</li>; } }
module.exports = { describe (label, fn) { return this._descriptionBlock('describe')(label, fn) }, context (label, fn) { return this._descriptionBlock('context')(label, fn) }, ddescribe (label, fn) { return this._descriptionBlock('describe', { runOnly: true })(label, fn) }, ccontext (label, fn) { return this._descriptionBlock('context', { runOnly: true })(label, fn) }, _descriptionBlock (type, options = {}) { const T = this return function analyzeOrExec (label, fn) { if ( T.deepLevel === 0 && options.runOnly && !T.excludedSuite(T.onlySuites, label) && !T.onlySuitesAsUserParams ) { T.onlySuites.push(label) } if (T.deepLevel === 0 && T.preventsSuiteFromRunning(label)) { return } return T.analyzing ? analizeBlock(label, fn) : describeBlock(label, fn) } function analizeBlock (label, fn) { if (T.deepLevel === 0) { var testSuite = describeBlock.bind(this, label, fn) T.currentRootDescribeBlock = testSuite T.suites.push(testSuite) } T.deepLevel++ fn() T.deepLevel-- } function describeBlock (label, fn) { if (T.deepLevel === 0 && T.preventsSuiteFromRunning(label)) { return } T.describeMessages.push(T.message(type, label, T.deepLevel)) T.deepLevel++ fn() T.itBlockRunLevel = T.deepLevel T.describeMessages = [] T._contextBlocks.forEach(filterFromSameLevel) T.deepLevel-- } function filterFromSameLevel (blockName) { T[blockName + 'Blocks'] = T[blockName + 'Blocks'].filter(differentLevel) function differentLevel (obj) { return obj.deepLevel !== T.deepLevel } } }, preventsSuiteFromRunning (label) { const T = this // allows to pass { label: '...', fn: ... } as arg if (label.label) label = label.label return ( T.excludedSuite(label) || (T.onlySuites.some(isInclusionOnly) && !T.onlySuites.some(included)) ) function isInclusionOnly (onlySuite) { return !onlySuite.startsWith('~') } function included (onlySuite) { return onlySuite === label } }, excludedSuite (label) { const T = this return T.onlySuites.some(excluded) function excluded (onlySuite) { if (onlySuite.startsWith('~')) { if (onlySuite.replace('~', '') === label) { return true } } } } }
define([ 'lodash', './support/jquery.mockjax', './responses/licensing/applications-top5-lastweek', './responses/licensing/applications-detail-lastweek', './responses/licensing/conversion-series', './responses/licensing/applications-top5authorities-weekly', './responses/licensing/applications-top5licences-weekly', './responses/licensing/applications-total-weekly', './responses/licensing/all-entities' ], function (_) { // use XMLHttpRequest for cross domain mock calls on IE // as mockjax does not replace XDomainRequest $.ajaxPrefilter( function( options, originalOptions, jqXHR ) { options.crossDomain = false; }); $.mockjaxSettings.log = true; $.mockjaxSettings.responseTime = 300; var responses = Array.prototype.slice.call(arguments, 2); for (var i = 0, ni = responses.length; i < ni; i++) { var response = new responses[i]() $.mockjax(_.bind(response.getDefinition, response)); }; });
/*global Motio */ jQuery(function ($) { 'use strict'; var windowSpy = new $.Espy(window); // ========================================================================== // Header clouds // ========================================================================== (function () { var header = $('header')[0]; var headerClouds = new Motio(header, { fps: 30, speedX: 60, bgWidth: 1024, bgHeight: 1024 }); // Play only when in the viewport windowSpy.add(header, function (entered) { headerClouds[entered ? 'play' : 'pause'](); }); }()); // ========================================================================== // Examples // ========================================================================== // Panning (function () { var $example = $('#panning .example'); var frame = $example.find('.frame')[0]; var offset = $example.offset(); var motio = new Motio(frame, { fps: 30, bgWidth: 1024, bgHeight: 1024 }); // Play/Pause when mouse enters/leaves the frame $example.on('mouseenter mouseleave', function (event) { if (event.type === 'mouseenter') { motio.play(); } else { motio.pause(); } }); // Update example offset offset on window resize $(window).on('resize', function () { offset = $example.offset(); }); // Update the animation speed & direction based on a cursor position $example.on('mousemove', function (event) { motio.set('speedX', event.pageX - offset.left - motio.width / 2); motio.set('speedY', event.pageY - offset.top - motio.height / 2); }); }()); // Sprite $('a[data-toggle="tab"][href=#sprite]').one('shown', function () { var $example = $('#sprite .example'); var frame = $example.find('.frame')[0]; var motio = new Motio(frame, { fps: 10, frames: 14 }); // Play when mouse enters the frame, and pause when it leaves $example.on('mouseenter mouseleave', function (event) { motio[event.type === 'mouseenter' ? 'play' : 'pause'](); }); }); // 360 view $('a[data-toggle="tab"][href=#circview]').one('shown', function () { var $example = $('#circview .example'); var exampleLeft = $example.offset().left; var exampleWidth = $example.width(); var frame = $example.find('.frame')[0]; var motio = new Motio(frame, { frames: 18 }); // Update example left offset on window resize $(window).on('resize', function () { exampleLeft = $example.offset().left; }); // Activate frame based on the cursor position $example.on('mousemove', function (event) { motio.to(Math.floor(motio.frames / exampleWidth * (event.pageX - exampleLeft)), true); }); }); // Extreme spriting - minigame // This is really dumb, and on top of that adapted from older version of Motio, so please ignore. $('a[data-toggle="tab"][href=#game]').one('shown', function () { var $game = $('#game .frame'); var pos = 350; var $char = $game.find('.char').css({ left: pos + 'px' }); var posMax = $game.innerWidth() - $char.innerWidth(); var facing = 'right'; var moveSpeed = 300; var moveFps = 30; var pressed = []; var inAction = 0; var isRunning = 0; var mIndex; var listenOn = [37,39,32,66]; var $mations = $char.children(); var mations = { right: { stand: $mations.filter('.stand').motio({ frames: 8, startPaused: 1, fps: 10 }), run: $mations.filter('.run' ).motio({ frames: 6, startPaused: 1, fps: 10 }), jump: $mations.filter('.jump' ).motio({ frames: 10, startPaused: 1, fps: 15 }), kick: $mations.filter('.kick' ).motio({ frames: 9, startPaused: 1, fps: 15 }) }, left: { stand: $mations.filter('.stand_left').motio({ frames: 8, startPaused: 1, fps: 10 }), run: $mations.filter('.run_left' ).motio({ frames: 6, startPaused: 1, fps: 10 }), jump: $mations.filter('.jump_left' ).motio({ frames: 10, startPaused: 1, fps: 15 }), kick: $mations.filter('.kick_left' ).motio({ frames: 9, startPaused: 1, fps: 15 }) } }; // Hide everything on start $mations.hide(); // Start with standing animation mations[facing].stand.show().motio('play'); // Resets the stance back to running or standing after actions like kick function resetStance() { /*jshint validthis:true */ inAction = 0; $(this.element).hide(); mations[facing][isRunning ? 'run' : 'stand'].show().motio('play'); } // Keydown handlers $(document).on('keydown', function (event) { if ($.inArray(event.which, listenOn) === -1 || pressed[event.which]) { return; } pressed[event.which] = true; var request; switch (event.which) { // Left arrow case 37: request = 'run'; facing = 'left'; break; // Right arrow case 39: request = 'run'; facing = 'right'; break; // Spacebar case 32: request = 'jump'; break; // B case 66: request = 'kick'; break; } // Show concerned animation $mations.hide().motio('toStart', true); mations[facing][request].show(); if (request === 'run') { inAction = 0; mIndex = clearTimeout(mIndex); isRunning = 1; move(); mations[facing][request].motio('play'); } else { inAction = 1; mations[facing][request].motio('toEnd', resetStance); } return false; }); // Keyup handlers $(document).on('keyup', function (event) { if ($.inArray(event.which, listenOn) === -1) { return; } pressed[event.which] = false; var released; switch (event.which) { // Left & arrow case 37: released = 'left'; break; // Right arrow case 39: released = 'right'; break; } if (isRunning && facing === released) { mations[released].run.hide().motio('toStart', true); isRunning = 0; mIndex = clearTimeout(mIndex); if (!inAction) { mations[facing].stand.show().motio('play'); } } return false; }); // Move function function move() { if (pos === 0 && facing === 'left' || pos === posMax && facing === 'right') { return; } pos += (facing === 'right' ? moveSpeed : -moveSpeed) / moveFps; if (pos < 0) { pos = 0; } else if (pos > posMax) { pos = posMax; } $char[0].style.left = pos + 'px'; mIndex = setTimeout(move, 1000 / moveFps); } }); });
module.exports = { bind : function (app, assetPath) { app.get('/', function (req, res) { res.render('example-0', {'assetPath' : assetPath}); }); // **************** // WHITEHALL // **************** app.get('/whitehall/create-a-programme', function (req, res) { res.render('whitehall/create-a-programme', {'assetPath' : assetPath}); }); // **************** // POLICIES // **************** // Scheme prototype - Universal Credit app.get('/government/policies/universal-credit', function (req, res) { res.render('friday/universal-credit', {'assetPath' : assetPath}); }); app.get('/government/policies/universal-credit/timeline', function (req, res) { res.render('friday/universal-credit-background-chrono', {'assetPath' : assetPath}); }); app.get('/government/policies/universal-credit/background/alternative', function (req, res) { res.render('friday/universal-credit-background', {'assetPath' : assetPath}); }); app.get('/government/policies/universal-credit/background/alternative-2', function (req, res) { res.render('friday/universal-credit-background-alternative', {'assetPath' : assetPath}); }); // Scheme prototype (old) - Universal Credit, for BBC testing app.get('/policy/universal-credit', function (req, res) { res.render('universal-credit', {'assetPath' : assetPath}); }); // Policy area - Benefits Reform app.get('/government/policies/benefits-reform', function (req, res) { res.render('friday/benefits-reform', {'assetPath' : assetPath}); }); // Top-level policies with new friendlier names, various browsing methods app.get('/policies-renamed', function (req, res) { res.render('policies-renamed', {'assetPath' : assetPath}); }); app.get('/policies-renamed-by-topic', function (req, res) { res.render('policies-renamed-by-topic', {'assetPath' : assetPath}); }); app.get('/policies-renamed-list', function (req, res) { res.render('policies-renamed-list', {'assetPath' : assetPath}); }); // Anna's list of policies prototype, at higher level app.get('/policies/rural-and-countryside', function (req, res) { res.render('schemes-2', {'assetPath' : assetPath}); }); // Anna's scheme prototype using the Work Programme app.get('/policy/prototype', function (req, res) { res.render('policy-prototype-2', {'assetPath' : assetPath}); }); app.get('/policy/prototype/latest', function (req, res) { res.render('policy-prototype-latest', {'assetPath' : assetPath}); }); // List of policy areas, filter for "crime", then go through to // the "window" of latest stuff app.get('/policies', function (req, res) { res.render('policies/topics.html', {'assetPath' : assetPath}); }); app.get('/policies/crime-and-policing', function (req, res) { res.render('policies/crime-and-policing.html', {'assetPath' : assetPath}); }); app.get('/policies/crime-and-policing-latest', function (req, res) { res.render('policies/crime-and-policing-latest.html', {'assetPath' : assetPath}); }); // Policy prototypes (Early years childcare) // List of topics, then go through to early years childcare page with // a "window" at the bottom // If you click on any of the "see more" links you get to // example 3, which is a filtered publication list by policy topic app.get('/schools-colleges', function (req, res) { res.render('example-0', {'assetPath' : assetPath }); }); app.get('/schools-colleges/early-learning-childcare', function (req, res) { res.render('example-1', {'assetPath' : assetPath }); }); / * Alternative URLs, retained to avoid breaking existing links */ app.get('/example-0', function (req, res) { res.render('example-0', {'assetPath' : assetPath }); }); app.get('/example-1', function (req, res) { res.render('example-1', {'assetPath' : assetPath }); }); app.get('/example-1a', function (req, res) { res.render('example-1a', {'assetPath' : assetPath }); }); app.get('/example-3', function (req, res) { res.render('example-3', {'assetPath' : assetPath }); }); // INCOMPLETE app.get('/publications-with-better-search', function (req, res) { res.render('publications-with-better-search', {'assetPath' : assetPath}); }); app.get('/schemes', function (req, res) { res.render('schemes', {'assetPath' : assetPath}); }); // **************** // ARCHIVING // **************** // Change history prototypes (Outer space licence) app.get('/apply-for-a-license-under-the-outer-space-act-1986', function (req, res) { res.render('apply-for-a-license-under-the-outer-space-act-1986', {'assetPath' : assetPath}); }); app.get('/info/apply-for-a-license-under-the-outer-space-act-1986', function (req, res) { res.render('apply-for-a-license-under-the-outer-space-act-1986-info', {'assetPath' : assetPath}); }); app.get('/apply-for-a-license-under-the-outer-space-act-1986/v1', function (req, res) { res.render('apply-for-a-license-under-the-outer-space-act-1986-version', {'assetPath' : assetPath}); }); // Archiving prototypes (Governors' handbook) app.get('/governors-handbook', function (req, res) { res.render('governors-handbook', {'assetPath' : assetPath}); }); app.get('/info/governors-handbook', function (req, res) { res.render('governors-handbook-info', {'assetPath' : assetPath}); }); app.get('/governors-handbook/v1', function (req, res) { res.render('governors-handbook-version', {'assetPath' : assetPath}); }); // Archiving prototypes (Building services) // Click on linked page, goes through to 410 page, you can then // see the inverted page. app.get('/archive', function (req, res) { res.render('archive-1', {'assetPath' : assetPath}); }); /* External page */ app.get('/building-construction-and-property-services', function (req, res) { res.render('archive-2', {'assetPath' : assetPath}); }); /* 410 page */ app.get('/archive/building-construction-and-property-services', function (req, res) { res.render('archive-4', {'assetPath' : assetPath}); }); /* Inverted CSS */ app.get('/archive/building-construction-and-property-services-2', function (req, res) { res.render('archive-3', {'assetPath' : assetPath}); }); /* Interstitial */ app.get('/archive/building-construction-and-property-services-3', function (req, res) { res.render('archive-5', {'assetPath' : assetPath}); }); /* Tumbleweed */ // Archiving and 410 prototypes (G-Cloud) // Google search, Google results with archived link, // goes through to 410 page, you can then see the inverted page app.get('/google', function (req, res) { res.render('archive/google-search', {'assetPath' : assetPath}); }); app.get('/google-results', function (req, res) { res.render('archive/google-results', {'assetPath' : assetPath}); }); app.get('/410', function (req, res) { res.render('archive/cloudstore-410', {'assetPath' : assetPath}); }); app.get('/archive/how-to-use-cloudstore', function (req, res) { res.render('archive/cloudstore', {'assetPath' : assetPath}); }); // **************** // FRONT-END PERFORMANCE // Looking at ways to speed up page rendering. // **************** // Logging prototypes. app.get('/logging', function (req, res) { res.render('logging/logging-1', {'assetPath' : assetPath}); }); app.get('/logging-async', function (req, res) { res.render('logging/logging-2', {'assetPath' : assetPath}); }); app.get('/logging-reordered', function (req, res) { res.render('logging/logging-3', {'assetPath' : assetPath}); }); app.get('/logging-async-filament', function (req, res) { res.render('logging/logging-4', {'assetPath' : assetPath}); }); app.get('/logging-async-filament-with-reorder', function (req, res) { res.render('logging/logging-5', {'assetPath' : assetPath}); }); } };
define(function() { /** * Clipboard class. * @constructor */ function Clipboard() { this.items = []; } /** * Makes a copy of an array of selected objects (components or slides). * * @param {Component[]|Slide[]} items Array of items to copy. */ Clipboard.prototype.setItems = function(items) { if (items.length) { this.items = items.slice(0); } }; /** * @returns {Component[]|Slide[]} Array of cloned objects (components or slides). */ Clipboard.prototype.getItems = function() { return $.map(this.items, function(item) { return item.clone(); }); }; return Clipboard; });
export const hangouts = {"viewBox":"0 0 20 20","children":[{"name":"path","attribs":{"d":"M10,0C5.25,0,1.4,3.806,1.4,8.5C1.4,13.194,5.25,17,10,17v3c3.368-1.672,8.6-5.305,8.6-11.5C18.6,3.806,14.75,0,10,0z\r\n\t M9,9.741c0,1.328-1.021,2.422-2.32,2.538c-0.123,0.011-0.228-0.088-0.228-0.211v-0.852c0-0.106,0.079-0.194,0.184-0.21\r\n\tC7.167,10.93,7.573,10.519,7.683,10H5.732C5.328,10,5,9.672,5,9.268V6.732C5,6.328,5.328,6,5.732,6h2.536C8.672,6,9,6.328,9,6.732\r\n\tV9.741z M15,9.741c0,1.328-1.021,2.422-2.32,2.538c-0.123,0.011-0.228-0.088-0.228-0.211v-0.852c0-0.106,0.079-0.194,0.184-0.21\r\n\tc0.531-0.077,0.937-0.487,1.047-1.006h-1.951C11.328,10,11,9.672,11,9.268V6.732C11,6.328,11.328,6,11.732,6h2.536\r\n\tC14.672,6,15,6.328,15,6.732V9.741z"}}]};
(function() { 'use strict'; var app = angular.module('anmApp', [ // Angular Module 'ngRoute', 'ui.bootstrap', // Controllers 'anmApp.main', 'anmApp.signup', 'anmApp.signin', 'anmApp.task', 'anmApp.updateTask', 'anmApp.createTask', 'anmApp.turnPage', // Services 'anmApp.services', // Directive 'anmApp.directive' ]); // define router app.config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({redirectTo: '/'}); }]); // define constant app.constant('config', { apiUrl: 'http://localhost:30001/services/', perPageCount: 5 }); // define filter app.filter('range', function() { return function(input, end, begin) { input = []; begin = begin || 0; for (var i = begin; i < end; i++) { input.push(i); } return input; }; }); app.run(['$rootScope', 'config', function($rootScope, config) { $rootScope.itemsPerPages = 5; }]); }());
$(function(){"use strict";$("h1").on("click",function(){alert("Ey! Qué fue ese click? Soy un título principal!")}),$("img").on("click",function(){alert("Sacá esa manito!")})}),function(){"use strict";for(var n,o=function(){},e=["assert","clear","count","debug","dir","dirxml","error","exception","group","groupCollapsed","groupEnd","info","log","markTimeline","profile","profileEnd","table","time","timeEnd","timeStamp","trace","warn"],i=e.length,t=window.console=window.console||{};i--;)n=e[i],t[n]||(t[n]=o)}();
(function () { var _ = require("lodash"), getSyllableCount = require("../../twitter-poetry/lib/twitter_poetry").getSyllableCount; // TODO npm install var Hypher = require('hypher'), english = require('hyphenation.en-gb'), h = new Hypher(english); /** 0 = never choose off-beat notes 1 = choose off-beat notes with the same frequency as on-beat notes 2 = be twice as likely to choose off-beat notes 999999 = always choose off-beat notes */ var SYNCOPATION_PREFERENCE = 2; var TOTAL_AVAILABLE_BEATS = 16; var END_SPACE_PREFERENCE = 3; /** Takes a word like marathon, identifies it as a 3-syllable word, and returns a rhythm for laying out that word, like [0, 2, 3]. The zero is the first impulse, which we don't know yet if that's on a beat or offbeat, or which beat. But in any case, the next impulse comes 2 eighth notes later, and the last impulse is an eighth note after that. */ var getWordCluster = function (word) { var wordLength = h.hyphenate(word).length, wordCluster = [0]; _.times(wordLength - 1, function (n) { // each note within a word is either an eight note or a quarter note wordCluster.push(wordCluster[n] + 1 + Math.floor(Math.random() * 2)) }); return wordCluster; }; // the spaces before, after, and between the words var getBetweenWordSpaces = function (spacesCount, beatsToFill) { var betweenWordSpaces = []; _.times(spacesCount, function (n) { betweenWordSpaces.push(0); }); _.times(beatsToFill, function (n) { var spaceToAddTo = Math.min(Math.floor(Math.random() * spacesCount * END_SPACE_PREFERENCE), spacesCount - 1); betweenWordSpaces[spaceToAddTo]++; }); return betweenWordSpaces; } /** Each line is two bars of 4/4. Rhythm can happen on eighth notes. The notes are 0-indexed. So 0 is the downbeat of the first bar. 3 is the upbeat of beat 2 of the first bar. {0, 3} means that there's a note on the downbeat and the upbeat of 2. {1, 8} means that there's a note on the upbeat of 1 and the downbeat of the second bar these numbers can therefore range from 0 to 15. @lyrics {Array{String}} */ var getRhythm = function (lyrics) { var rhythm = []; _.each(lyrics, function (line) { var words = line.split(/\s+/); var wordClusters = _.map(words, getWordCluster); var lineSyllableCount = _.reduce(words, function (memo, word) { return memo + h.hyphenate(word).length; }, 0); var betweenWordSpaces = getBetweenWordSpaces(words.length + 1, TOTAL_AVAILABLE_BEATS - lineSyllableCount); var rhythmLine = []; var ticker = 0; _.times(words.length, function (n) { ticker += betweenWordSpaces[n]; _.each(wordClusters[n], function (impulseIndex) { rhythmLine.push(ticker + impulseIndex); }); ticker += _.last(wordClusters[n]); ticker++; }); rhythm.push(rhythmLine); }); return rhythm; }; exports.getRhythm = getRhythm; }());
// Regular expression that matches all symbols in the Hangul Jamo Extended-A block as per Unicode v6.0.0: /[\uA960-\uA97F]/;
// Marionette.StateRegion // -------------------- // v0.1.0 // // Copyright (c) 2014 Mattias Rydengren <mattias.rydengren@coderesque.com> // Distributed under MIT license Marionette.StateRegion = (function (Marionette, Backbone, _) { 'use strict'; function ensure(obj, message) { if (!obj) { throw new Error(message); } return obj; } return Marionette.Region.extend({ initialize: function() { ensure(this.initialView, 'Missing `initialState`'); ensure(this.views, 'Missing `states`'); }, createView: function(ViewType) { return new ViewType({ model: this.model, collection: this.collection }); }, display: function(options) { options = options || {}; this.model = options.model; this.collection = options.collection; this._transition(this.initialView); }, _listen: function(view) { var self = this; _.each(this.views, function (ViewType, key) { view.on(key, function () { self._transition(key); }); }); }, _transition: function(key) { var ViewType = ensure(this.views[key], 'Missing `ViewType` for "' + key + '"'); var view = this.createView(ViewType); this._listen(view); this.show(view); } }); })(Marionette, Backbone, _);
/** * @format * @flow strict-local */ import React from 'react'; import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, Button, Alert, Platform, } from 'react-native'; import {Header, Colors} from 'react-native/Libraries/NewAppScreen'; import RNCalendarEvents from 'react-native-calendar-events'; const App: () => React$Node = () => { return ( <> <StatusBar barStyle="dark-content" /> <SafeAreaView> <ScrollView contentInsetAdjustmentBehavior="automatic" style={styles.scrollView}> <Header /> {global.HermesInternal == null ? null : ( <View style={styles.engine}> <Text style={styles.footer}>Engine: Hermes</Text> </View> )} <View style={styles.body}> <View style={styles.sectionContainer}> <Text style={styles.sectionTitle}>Read/Write Auth</Text> <Text style={styles.sectionDescription}> <Button title="Request auth" onPress={() => { RNCalendarEvents.requestPermissions().then( (result) => { Alert.alert('Auth requested', result); }, (result) => { console.error(result); }, ); }} /> <Text>{'\n'}</Text> <Button title="Check auth" onPress={() => { RNCalendarEvents.checkPermissions().then( (result) => { Alert.alert('Auth check', result); }, (result) => { console.error(result); }, ); }} /> </Text> </View> {Platform.OS === 'android' && ( <View style={styles.sectionContainer}> <Text style={styles.sectionTitle}>Read-Only Auth</Text> <Text style={styles.sectionDescription}> <Button title="Request auth" onPress={() => { RNCalendarEvents.requestPermissions(true).then( (result) => { Alert.alert('Read-only Auth requested', result); }, (result) => { console.error(result); }, ); }} /> <Text>{'\n'}</Text> <Button title="Check auth" onPress={() => { RNCalendarEvents.checkPermissions(true).then( (result) => { Alert.alert('Read-only Auth check', result); }, (result) => { console.error(result); }, ); }} /> </Text> </View> )} <View style={styles.sectionContainer}> <Text style={styles.sectionTitle}>Calendars</Text> <Text style={styles.sectionDescription}> <Button title="Find calendars" onPress={() => { RNCalendarEvents.findCalendars().then( (result) => { Alert.alert( 'Calendars', result .reduce((acc, cal) => { acc.push(cal.title); return acc; }, []) .join('\n'), ); }, (result) => { console.error(result); }, ); }} /> </Text> </View> </View> </ScrollView> </SafeAreaView> </> ); }; const styles = StyleSheet.create({ scrollView: { backgroundColor: Colors.lighter, }, engine: { position: 'absolute', right: 0, }, body: { backgroundColor: Colors.white, }, sectionContainer: { marginTop: 32, paddingHorizontal: 24, }, sectionTitle: { fontSize: 24, fontWeight: '600', color: Colors.black, }, sectionDescription: { marginTop: 8, fontSize: 18, fontWeight: '400', color: Colors.dark, }, highlight: { fontWeight: '700', }, footer: { color: Colors.dark, fontSize: 12, fontWeight: '600', padding: 4, paddingRight: 12, textAlign: 'right', }, }); export default App;
'use strict'; const Stats = require('fast-stats').Stats, get = require('lodash.get'), set = require('lodash.set'); function percentileName(percentile) { if (percentile === 0) { return 'min'; } else if (percentile === 100) { return 'max'; } else { return 'p' + String(percentile).replace('.', '_'); } } module.exports = { /** * Create or update a fast-stats#Stats object in target at path. */ pushStats(target, path, data) { if (typeof data !== 'number') throw new Error(`Tried to add ${data} to stats for path ${path}`); const stats = get(target, path, new Stats()); stats.push(data); set(target, path, stats); }, pushGroupStats(target, domainTarget, path, data) { this.pushStats(target, path, data); this.pushStats(domainTarget, path, data); }, /** * Summarize stats and put result in target at path */ setStatsSummary(target, path, stats) { set(target, path, this.summarizeStats(stats)); }, summarizeStats(stats, options) { if (stats.length === 0) { return undefined; } options = options || {}; let percentiles = options.percentiles || [0, 90, 100]; let decimals = options.decimals || 0; let data = { median: stats.median().toFixed(decimals), mean: stats.amean().toFixed(decimals) }; percentiles.forEach((p) => { let name = percentileName(p); const percentile = stats.percentile(p); if (Number.isFinite(percentile)) { data[name] = percentile.toFixed(decimals); } else { throw new Error('Failed to calculate ' + name + ' for stats: ' + JSON.stringify(stats, null, 2)); } }); if (options.includeSum) { data.sum = stats.Σ().toFixed(decimals); } return data; } };
import {spy, stub} from 'sinon'; import then from './then'; describe('then test creator', () => { it('throws error when there is no store', () => { const test = then([() => {}, () => {}]); (() => test.call({})).should.throw(); }); it('applies assertion on result of argument-less selector', () => { const assertion = spy(); const selector = () => {}; const select = stub(); const result = 'This is a result of selector call.'; select.withArgs(selector).returns(result); then([selector, assertion]).call({store: {select}}); assertion.should.have.been.calledOnce(); assertion.should.have.been.calledWith(result); }); it('applies assertion on result of selector with arguments', () => { const assertion = spy(); const selector = () => {}; const select = stub(); const result = 'This is a result of a different selector call.'; select.withArgs(selector, 1, 'A', 3).returns(result); then([selector, 1, 'A', 3, assertion]).call({store: {select}}); assertion.should.have.been.calledOnce(); assertion.should.have.been.calledWith(result); }); });
'use strict'; const internals = {}; // http://data.iana.org/TLD/tlds-alpha-by-domain.txt // # Version 2019032300, Last Updated Sat Mar 23 07:07:02 2019 UTC internals.tlds = [ 'AAA', 'AARP', 'ABARTH', 'ABB', 'ABBOTT', 'ABBVIE', 'ABC', 'ABLE', 'ABOGADO', 'ABUDHABI', 'AC', 'ACADEMY', 'ACCENTURE', 'ACCOUNTANT', 'ACCOUNTANTS', 'ACO', 'ACTOR', 'AD', 'ADAC', 'ADS', 'ADULT', 'AE', 'AEG', 'AERO', 'AETNA', 'AF', 'AFAMILYCOMPANY', 'AFL', 'AFRICA', 'AG', 'AGAKHAN', 'AGENCY', 'AI', 'AIG', 'AIGO', 'AIRBUS', 'AIRFORCE', 'AIRTEL', 'AKDN', 'AL', 'ALFAROMEO', 'ALIBABA', 'ALIPAY', 'ALLFINANZ', 'ALLSTATE', 'ALLY', 'ALSACE', 'ALSTOM', 'AM', 'AMERICANEXPRESS', 'AMERICANFAMILY', 'AMEX', 'AMFAM', 'AMICA', 'AMSTERDAM', 'ANALYTICS', 'ANDROID', 'ANQUAN', 'ANZ', 'AO', 'AOL', 'APARTMENTS', 'APP', 'APPLE', 'AQ', 'AQUARELLE', 'AR', 'ARAB', 'ARAMCO', 'ARCHI', 'ARMY', 'ARPA', 'ART', 'ARTE', 'AS', 'ASDA', 'ASIA', 'ASSOCIATES', 'AT', 'ATHLETA', 'ATTORNEY', 'AU', 'AUCTION', 'AUDI', 'AUDIBLE', 'AUDIO', 'AUSPOST', 'AUTHOR', 'AUTO', 'AUTOS', 'AVIANCA', 'AW', 'AWS', 'AX', 'AXA', 'AZ', 'AZURE', 'BA', 'BABY', 'BAIDU', 'BANAMEX', 'BANANAREPUBLIC', 'BAND', 'BANK', 'BAR', 'BARCELONA', 'BARCLAYCARD', 'BARCLAYS', 'BAREFOOT', 'BARGAINS', 'BASEBALL', 'BASKETBALL', 'BAUHAUS', 'BAYERN', 'BB', 'BBC', 'BBT', 'BBVA', 'BCG', 'BCN', 'BD', 'BE', 'BEATS', 'BEAUTY', 'BEER', 'BENTLEY', 'BERLIN', 'BEST', 'BESTBUY', 'BET', 'BF', 'BG', 'BH', 'BHARTI', 'BI', 'BIBLE', 'BID', 'BIKE', 'BING', 'BINGO', 'BIO', 'BIZ', 'BJ', 'BLACK', 'BLACKFRIDAY', 'BLOCKBUSTER', 'BLOG', 'BLOOMBERG', 'BLUE', 'BM', 'BMS', 'BMW', 'BN', 'BNL', 'BNPPARIBAS', 'BO', 'BOATS', 'BOEHRINGER', 'BOFA', 'BOM', 'BOND', 'BOO', 'BOOK', 'BOOKING', 'BOSCH', 'BOSTIK', 'BOSTON', 'BOT', 'BOUTIQUE', 'BOX', 'BR', 'BRADESCO', 'BRIDGESTONE', 'BROADWAY', 'BROKER', 'BROTHER', 'BRUSSELS', 'BS', 'BT', 'BUDAPEST', 'BUGATTI', 'BUILD', 'BUILDERS', 'BUSINESS', 'BUY', 'BUZZ', 'BV', 'BW', 'BY', 'BZ', 'BZH', 'CA', 'CAB', 'CAFE', 'CAL', 'CALL', 'CALVINKLEIN', 'CAM', 'CAMERA', 'CAMP', 'CANCERRESEARCH', 'CANON', 'CAPETOWN', 'CAPITAL', 'CAPITALONE', 'CAR', 'CARAVAN', 'CARDS', 'CARE', 'CAREER', 'CAREERS', 'CARS', 'CARTIER', 'CASA', 'CASE', 'CASEIH', 'CASH', 'CASINO', 'CAT', 'CATERING', 'CATHOLIC', 'CBA', 'CBN', 'CBRE', 'CBS', 'CC', 'CD', 'CEB', 'CENTER', 'CEO', 'CERN', 'CF', 'CFA', 'CFD', 'CG', 'CH', 'CHANEL', 'CHANNEL', 'CHARITY', 'CHASE', 'CHAT', 'CHEAP', 'CHINTAI', 'CHRISTMAS', 'CHROME', 'CHRYSLER', 'CHURCH', 'CI', 'CIPRIANI', 'CIRCLE', 'CISCO', 'CITADEL', 'CITI', 'CITIC', 'CITY', 'CITYEATS', 'CK', 'CL', 'CLAIMS', 'CLEANING', 'CLICK', 'CLINIC', 'CLINIQUE', 'CLOTHING', 'CLOUD', 'CLUB', 'CLUBMED', 'CM', 'CN', 'CO', 'COACH', 'CODES', 'COFFEE', 'COLLEGE', 'COLOGNE', 'COM', 'COMCAST', 'COMMBANK', 'COMMUNITY', 'COMPANY', 'COMPARE', 'COMPUTER', 'COMSEC', 'CONDOS', 'CONSTRUCTION', 'CONSULTING', 'CONTACT', 'CONTRACTORS', 'COOKING', 'COOKINGCHANNEL', 'COOL', 'COOP', 'CORSICA', 'COUNTRY', 'COUPON', 'COUPONS', 'COURSES', 'CR', 'CREDIT', 'CREDITCARD', 'CREDITUNION', 'CRICKET', 'CROWN', 'CRS', 'CRUISE', 'CRUISES', 'CSC', 'CU', 'CUISINELLA', 'CV', 'CW', 'CX', 'CY', 'CYMRU', 'CYOU', 'CZ', 'DABUR', 'DAD', 'DANCE', 'DATA', 'DATE', 'DATING', 'DATSUN', 'DAY', 'DCLK', 'DDS', 'DE', 'DEAL', 'DEALER', 'DEALS', 'DEGREE', 'DELIVERY', 'DELL', 'DELOITTE', 'DELTA', 'DEMOCRAT', 'DENTAL', 'DENTIST', 'DESI', 'DESIGN', 'DEV', 'DHL', 'DIAMONDS', 'DIET', 'DIGITAL', 'DIRECT', 'DIRECTORY', 'DISCOUNT', 'DISCOVER', 'DISH', 'DIY', 'DJ', 'DK', 'DM', 'DNP', 'DO', 'DOCS', 'DOCTOR', 'DODGE', 'DOG', 'DOHA', 'DOMAINS', 'DOT', 'DOWNLOAD', 'DRIVE', 'DTV', 'DUBAI', 'DUCK', 'DUNLOP', 'DUNS', 'DUPONT', 'DURBAN', 'DVAG', 'DVR', 'DZ', 'EARTH', 'EAT', 'EC', 'ECO', 'EDEKA', 'EDU', 'EDUCATION', 'EE', 'EG', 'EMAIL', 'EMERCK', 'ENERGY', 'ENGINEER', 'ENGINEERING', 'ENTERPRISES', 'EPSON', 'EQUIPMENT', 'ER', 'ERICSSON', 'ERNI', 'ES', 'ESQ', 'ESTATE', 'ESURANCE', 'ET', 'ETISALAT', 'EU', 'EUROVISION', 'EUS', 'EVENTS', 'EVERBANK', 'EXCHANGE', 'EXPERT', 'EXPOSED', 'EXPRESS', 'EXTRASPACE', 'FAGE', 'FAIL', 'FAIRWINDS', 'FAITH', 'FAMILY', 'FAN', 'FANS', 'FARM', 'FARMERS', 'FASHION', 'FAST', 'FEDEX', 'FEEDBACK', 'FERRARI', 'FERRERO', 'FI', 'FIAT', 'FIDELITY', 'FIDO', 'FILM', 'FINAL', 'FINANCE', 'FINANCIAL', 'FIRE', 'FIRESTONE', 'FIRMDALE', 'FISH', 'FISHING', 'FIT', 'FITNESS', 'FJ', 'FK', 'FLICKR', 'FLIGHTS', 'FLIR', 'FLORIST', 'FLOWERS', 'FLY', 'FM', 'FO', 'FOO', 'FOOD', 'FOODNETWORK', 'FOOTBALL', 'FORD', 'FOREX', 'FORSALE', 'FORUM', 'FOUNDATION', 'FOX', 'FR', 'FREE', 'FRESENIUS', 'FRL', 'FROGANS', 'FRONTDOOR', 'FRONTIER', 'FTR', 'FUJITSU', 'FUJIXEROX', 'FUN', 'FUND', 'FURNITURE', 'FUTBOL', 'FYI', 'GA', 'GAL', 'GALLERY', 'GALLO', 'GALLUP', 'GAME', 'GAMES', 'GAP', 'GARDEN', 'GB', 'GBIZ', 'GD', 'GDN', 'GE', 'GEA', 'GENT', 'GENTING', 'GEORGE', 'GF', 'GG', 'GGEE', 'GH', 'GI', 'GIFT', 'GIFTS', 'GIVES', 'GIVING', 'GL', 'GLADE', 'GLASS', 'GLE', 'GLOBAL', 'GLOBO', 'GM', 'GMAIL', 'GMBH', 'GMO', 'GMX', 'GN', 'GODADDY', 'GOLD', 'GOLDPOINT', 'GOLF', 'GOO', 'GOODYEAR', 'GOOG', 'GOOGLE', 'GOP', 'GOT', 'GOV', 'GP', 'GQ', 'GR', 'GRAINGER', 'GRAPHICS', 'GRATIS', 'GREEN', 'GRIPE', 'GROCERY', 'GROUP', 'GS', 'GT', 'GU', 'GUARDIAN', 'GUCCI', 'GUGE', 'GUIDE', 'GUITARS', 'GURU', 'GW', 'GY', 'HAIR', 'HAMBURG', 'HANGOUT', 'HAUS', 'HBO', 'HDFC', 'HDFCBANK', 'HEALTH', 'HEALTHCARE', 'HELP', 'HELSINKI', 'HERE', 'HERMES', 'HGTV', 'HIPHOP', 'HISAMITSU', 'HITACHI', 'HIV', 'HK', 'HKT', 'HM', 'HN', 'HOCKEY', 'HOLDINGS', 'HOLIDAY', 'HOMEDEPOT', 'HOMEGOODS', 'HOMES', 'HOMESENSE', 'HONDA', 'HONEYWELL', 'HORSE', 'HOSPITAL', 'HOST', 'HOSTING', 'HOT', 'HOTELES', 'HOTELS', 'HOTMAIL', 'HOUSE', 'HOW', 'HR', 'HSBC', 'HT', 'HU', 'HUGHES', 'HYATT', 'HYUNDAI', 'IBM', 'ICBC', 'ICE', 'ICU', 'ID', 'IE', 'IEEE', 'IFM', 'IKANO', 'IL', 'IM', 'IMAMAT', 'IMDB', 'IMMO', 'IMMOBILIEN', 'IN', 'INC', 'INDUSTRIES', 'INFINITI', 'INFO', 'ING', 'INK', 'INSTITUTE', 'INSURANCE', 'INSURE', 'INT', 'INTEL', 'INTERNATIONAL', 'INTUIT', 'INVESTMENTS', 'IO', 'IPIRANGA', 'IQ', 'IR', 'IRISH', 'IS', 'ISELECT', 'ISMAILI', 'IST', 'ISTANBUL', 'IT', 'ITAU', 'ITV', 'IVECO', 'JAGUAR', 'JAVA', 'JCB', 'JCP', 'JE', 'JEEP', 'JETZT', 'JEWELRY', 'JIO', 'JLL', 'JM', 'JMP', 'JNJ', 'JO', 'JOBS', 'JOBURG', 'JOT', 'JOY', 'JP', 'JPMORGAN', 'JPRS', 'JUEGOS', 'JUNIPER', 'KAUFEN', 'KDDI', 'KE', 'KERRYHOTELS', 'KERRYLOGISTICS', 'KERRYPROPERTIES', 'KFH', 'KG', 'KH', 'KI', 'KIA', 'KIM', 'KINDER', 'KINDLE', 'KITCHEN', 'KIWI', 'KM', 'KN', 'KOELN', 'KOMATSU', 'KOSHER', 'KP', 'KPMG', 'KPN', 'KR', 'KRD', 'KRED', 'KUOKGROUP', 'KW', 'KY', 'KYOTO', 'KZ', 'LA', 'LACAIXA', 'LADBROKES', 'LAMBORGHINI', 'LAMER', 'LANCASTER', 'LANCIA', 'LANCOME', 'LAND', 'LANDROVER', 'LANXESS', 'LASALLE', 'LAT', 'LATINO', 'LATROBE', 'LAW', 'LAWYER', 'LB', 'LC', 'LDS', 'LEASE', 'LECLERC', 'LEFRAK', 'LEGAL', 'LEGO', 'LEXUS', 'LGBT', 'LI', 'LIAISON', 'LIDL', 'LIFE', 'LIFEINSURANCE', 'LIFESTYLE', 'LIGHTING', 'LIKE', 'LILLY', 'LIMITED', 'LIMO', 'LINCOLN', 'LINDE', 'LINK', 'LIPSY', 'LIVE', 'LIVING', 'LIXIL', 'LK', 'LLC', 'LOAN', 'LOANS', 'LOCKER', 'LOCUS', 'LOFT', 'LOL', 'LONDON', 'LOTTE', 'LOTTO', 'LOVE', 'LPL', 'LPLFINANCIAL', 'LR', 'LS', 'LT', 'LTD', 'LTDA', 'LU', 'LUNDBECK', 'LUPIN', 'LUXE', 'LUXURY', 'LV', 'LY', 'MA', 'MACYS', 'MADRID', 'MAIF', 'MAISON', 'MAKEUP', 'MAN', 'MANAGEMENT', 'MANGO', 'MAP', 'MARKET', 'MARKETING', 'MARKETS', 'MARRIOTT', 'MARSHALLS', 'MASERATI', 'MATTEL', 'MBA', 'MC', 'MCKINSEY', 'MD', 'ME', 'MED', 'MEDIA', 'MEET', 'MELBOURNE', 'MEME', 'MEMORIAL', 'MEN', 'MENU', 'MERCKMSD', 'METLIFE', 'MG', 'MH', 'MIAMI', 'MICROSOFT', 'MIL', 'MINI', 'MINT', 'MIT', 'MITSUBISHI', 'MK', 'ML', 'MLB', 'MLS', 'MM', 'MMA', 'MN', 'MO', 'MOBI', 'MOBILE', 'MOBILY', 'MODA', 'MOE', 'MOI', 'MOM', 'MONASH', 'MONEY', 'MONSTER', 'MOPAR', 'MORMON', 'MORTGAGE', 'MOSCOW', 'MOTO', 'MOTORCYCLES', 'MOV', 'MOVIE', 'MOVISTAR', 'MP', 'MQ', 'MR', 'MS', 'MSD', 'MT', 'MTN', 'MTR', 'MU', 'MUSEUM', 'MUTUAL', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NAB', 'NADEX', 'NAGOYA', 'NAME', 'NATIONWIDE', 'NATURA', 'NAVY', 'NBA', 'NC', 'NE', 'NEC', 'NET', 'NETBANK', 'NETFLIX', 'NETWORK', 'NEUSTAR', 'NEW', 'NEWHOLLAND', 'NEWS', 'NEXT', 'NEXTDIRECT', 'NEXUS', 'NF', 'NFL', 'NG', 'NGO', 'NHK', 'NI', 'NICO', 'NIKE', 'NIKON', 'NINJA', 'NISSAN', 'NISSAY', 'NL', 'NO', 'NOKIA', 'NORTHWESTERNMUTUAL', 'NORTON', 'NOW', 'NOWRUZ', 'NOWTV', 'NP', 'NR', 'NRA', 'NRW', 'NTT', 'NU', 'NYC', 'NZ', 'OBI', 'OBSERVER', 'OFF', 'OFFICE', 'OKINAWA', 'OLAYAN', 'OLAYANGROUP', 'OLDNAVY', 'OLLO', 'OM', 'OMEGA', 'ONE', 'ONG', 'ONL', 'ONLINE', 'ONYOURSIDE', 'OOO', 'OPEN', 'ORACLE', 'ORANGE', 'ORG', 'ORGANIC', 'ORIGINS', 'OSAKA', 'OTSUKA', 'OTT', 'OVH', 'PA', 'PAGE', 'PANASONIC', 'PARIS', 'PARS', 'PARTNERS', 'PARTS', 'PARTY', 'PASSAGENS', 'PAY', 'PCCW', 'PE', 'PET', 'PF', 'PFIZER', 'PG', 'PH', 'PHARMACY', 'PHD', 'PHILIPS', 'PHONE', 'PHOTO', 'PHOTOGRAPHY', 'PHOTOS', 'PHYSIO', 'PIAGET', 'PICS', 'PICTET', 'PICTURES', 'PID', 'PIN', 'PING', 'PINK', 'PIONEER', 'PIZZA', 'PK', 'PL', 'PLACE', 'PLAY', 'PLAYSTATION', 'PLUMBING', 'PLUS', 'PM', 'PN', 'PNC', 'POHL', 'POKER', 'POLITIE', 'PORN', 'POST', 'PR', 'PRAMERICA', 'PRAXI', 'PRESS', 'PRIME', 'PRO', 'PROD', 'PRODUCTIONS', 'PROF', 'PROGRESSIVE', 'PROMO', 'PROPERTIES', 'PROPERTY', 'PROTECTION', 'PRU', 'PRUDENTIAL', 'PS', 'PT', 'PUB', 'PW', 'PWC', 'PY', 'QA', 'QPON', 'QUEBEC', 'QUEST', 'QVC', 'RACING', 'RADIO', 'RAID', 'RE', 'READ', 'REALESTATE', 'REALTOR', 'REALTY', 'RECIPES', 'RED', 'REDSTONE', 'REDUMBRELLA', 'REHAB', 'REISE', 'REISEN', 'REIT', 'RELIANCE', 'REN', 'RENT', 'RENTALS', 'REPAIR', 'REPORT', 'REPUBLICAN', 'REST', 'RESTAURANT', 'REVIEW', 'REVIEWS', 'REXROTH', 'RICH', 'RICHARDLI', 'RICOH', 'RIGHTATHOME', 'RIL', 'RIO', 'RIP', 'RMIT', 'RO', 'ROCHER', 'ROCKS', 'RODEO', 'ROGERS', 'ROOM', 'RS', 'RSVP', 'RU', 'RUGBY', 'RUHR', 'RUN', 'RW', 'RWE', 'RYUKYU', 'SA', 'SAARLAND', 'SAFE', 'SAFETY', 'SAKURA', 'SALE', 'SALON', 'SAMSCLUB', 'SAMSUNG', 'SANDVIK', 'SANDVIKCOROMANT', 'SANOFI', 'SAP', 'SARL', 'SAS', 'SAVE', 'SAXO', 'SB', 'SBI', 'SBS', 'SC', 'SCA', 'SCB', 'SCHAEFFLER', 'SCHMIDT', 'SCHOLARSHIPS', 'SCHOOL', 'SCHULE', 'SCHWARZ', 'SCIENCE', 'SCJOHNSON', 'SCOR', 'SCOT', 'SD', 'SE', 'SEARCH', 'SEAT', 'SECURE', 'SECURITY', 'SEEK', 'SELECT', 'SENER', 'SERVICES', 'SES', 'SEVEN', 'SEW', 'SEX', 'SEXY', 'SFR', 'SG', 'SH', 'SHANGRILA', 'SHARP', 'SHAW', 'SHELL', 'SHIA', 'SHIKSHA', 'SHOES', 'SHOP', 'SHOPPING', 'SHOUJI', 'SHOW', 'SHOWTIME', 'SHRIRAM', 'SI', 'SILK', 'SINA', 'SINGLES', 'SITE', 'SJ', 'SK', 'SKI', 'SKIN', 'SKY', 'SKYPE', 'SL', 'SLING', 'SM', 'SMART', 'SMILE', 'SN', 'SNCF', 'SO', 'SOCCER', 'SOCIAL', 'SOFTBANK', 'SOFTWARE', 'SOHU', 'SOLAR', 'SOLUTIONS', 'SONG', 'SONY', 'SOY', 'SPACE', 'SPORT', 'SPOT', 'SPREADBETTING', 'SR', 'SRL', 'SRT', 'SS', 'ST', 'STADA', 'STAPLES', 'STAR', 'STARHUB', 'STATEBANK', 'STATEFARM', 'STC', 'STCGROUP', 'STOCKHOLM', 'STORAGE', 'STORE', 'STREAM', 'STUDIO', 'STUDY', 'STYLE', 'SU', 'SUCKS', 'SUPPLIES', 'SUPPLY', 'SUPPORT', 'SURF', 'SURGERY', 'SUZUKI', 'SV', 'SWATCH', 'SWIFTCOVER', 'SWISS', 'SX', 'SY', 'SYDNEY', 'SYMANTEC', 'SYSTEMS', 'SZ', 'TAB', 'TAIPEI', 'TALK', 'TAOBAO', 'TARGET', 'TATAMOTORS', 'TATAR', 'TATTOO', 'TAX', 'TAXI', 'TC', 'TCI', 'TD', 'TDK', 'TEAM', 'TECH', 'TECHNOLOGY', 'TEL', 'TELEFONICA', 'TEMASEK', 'TENNIS', 'TEVA', 'TF', 'TG', 'TH', 'THD', 'THEATER', 'THEATRE', 'TIAA', 'TICKETS', 'TIENDA', 'TIFFANY', 'TIPS', 'TIRES', 'TIROL', 'TJ', 'TJMAXX', 'TJX', 'TK', 'TKMAXX', 'TL', 'TM', 'TMALL', 'TN', 'TO', 'TODAY', 'TOKYO', 'TOOLS', 'TOP', 'TORAY', 'TOSHIBA', 'TOTAL', 'TOURS', 'TOWN', 'TOYOTA', 'TOYS', 'TR', 'TRADE', 'TRADING', 'TRAINING', 'TRAVEL', 'TRAVELCHANNEL', 'TRAVELERS', 'TRAVELERSINSURANCE', 'TRUST', 'TRV', 'TT', 'TUBE', 'TUI', 'TUNES', 'TUSHU', 'TV', 'TVS', 'TW', 'TZ', 'UA', 'UBANK', 'UBS', 'UCONNECT', 'UG', 'UK', 'UNICOM', 'UNIVERSITY', 'UNO', 'UOL', 'UPS', 'US', 'UY', 'UZ', 'VA', 'VACATIONS', 'VANA', 'VANGUARD', 'VC', 'VE', 'VEGAS', 'VENTURES', 'VERISIGN', 'VERSICHERUNG', 'VET', 'VG', 'VI', 'VIAJES', 'VIDEO', 'VIG', 'VIKING', 'VILLAS', 'VIN', 'VIP', 'VIRGIN', 'VISA', 'VISION', 'VISTAPRINT', 'VIVA', 'VIVO', 'VLAANDEREN', 'VN', 'VODKA', 'VOLKSWAGEN', 'VOLVO', 'VOTE', 'VOTING', 'VOTO', 'VOYAGE', 'VU', 'VUELOS', 'WALES', 'WALMART', 'WALTER', 'WANG', 'WANGGOU', 'WARMAN', 'WATCH', 'WATCHES', 'WEATHER', 'WEATHERCHANNEL', 'WEBCAM', 'WEBER', 'WEBSITE', 'WED', 'WEDDING', 'WEIBO', 'WEIR', 'WF', 'WHOSWHO', 'WIEN', 'WIKI', 'WILLIAMHILL', 'WIN', 'WINDOWS', 'WINE', 'WINNERS', 'WME', 'WOLTERSKLUWER', 'WOODSIDE', 'WORK', 'WORKS', 'WORLD', 'WOW', 'WS', 'WTC', 'WTF', 'XBOX', 'XEROX', 'XFINITY', 'XIHUAN', 'XIN', 'XN--11B4C3D', 'XN--1CK2E1B', 'XN--1QQW23A', 'XN--2SCRJ9C', 'XN--30RR7Y', 'XN--3BST00M', 'XN--3DS443G', 'XN--3E0B707E', 'XN--3HCRJ9C', 'XN--3OQ18VL8PN36A', 'XN--3PXU8K', 'XN--42C2D9A', 'XN--45BR5CYL', 'XN--45BRJ9C', 'XN--45Q11C', 'XN--4GBRIM', 'XN--54B7FTA0CC', 'XN--55QW42G', 'XN--55QX5D', 'XN--5SU34J936BGSG', 'XN--5TZM5G', 'XN--6FRZ82G', 'XN--6QQ986B3XL', 'XN--80ADXHKS', 'XN--80AO21A', 'XN--80AQECDR1A', 'XN--80ASEHDB', 'XN--80ASWG', 'XN--8Y0A063A', 'XN--90A3AC', 'XN--90AE', 'XN--90AIS', 'XN--9DBQ2A', 'XN--9ET52U', 'XN--9KRT00A', 'XN--B4W605FERD', 'XN--BCK1B9A5DRE4C', 'XN--C1AVG', 'XN--C2BR7G', 'XN--CCK2B3B', 'XN--CG4BKI', 'XN--CLCHC0EA0B2G2A9GCD', 'XN--CZR694B', 'XN--CZRS0T', 'XN--CZRU2D', 'XN--D1ACJ3B', 'XN--D1ALF', 'XN--E1A4C', 'XN--ECKVDTC9D', 'XN--EFVY88H', 'XN--ESTV75G', 'XN--FCT429K', 'XN--FHBEI', 'XN--FIQ228C5HS', 'XN--FIQ64B', 'XN--FIQS8S', 'XN--FIQZ9S', 'XN--FJQ720A', 'XN--FLW351E', 'XN--FPCRJ9C3D', 'XN--FZC2C9E2C', 'XN--FZYS8D69UVGM', 'XN--G2XX48C', 'XN--GCKR3F0F', 'XN--GECRJ9C', 'XN--GK3AT1E', 'XN--H2BREG3EVE', 'XN--H2BRJ9C', 'XN--H2BRJ9C8C', 'XN--HXT814E', 'XN--I1B6B1A6A2E', 'XN--IMR513N', 'XN--IO0A7I', 'XN--J1AEF', 'XN--J1AMH', 'XN--J6W193G', 'XN--JLQ61U9W7B', 'XN--JVR189M', 'XN--KCRX77D1X4A', 'XN--KPRW13D', 'XN--KPRY57D', 'XN--KPU716F', 'XN--KPUT3I', 'XN--L1ACC', 'XN--LGBBAT1AD8J', 'XN--MGB9AWBF', 'XN--MGBA3A3EJT', 'XN--MGBA3A4F16A', 'XN--MGBA7C0BBN0A', 'XN--MGBAAKC7DVF', 'XN--MGBAAM7A8H', 'XN--MGBAB2BD', 'XN--MGBAH1A3HJKRD', 'XN--MGBAI9AZGQP6J', 'XN--MGBAYH7GPA', 'XN--MGBB9FBPOB', 'XN--MGBBH1A', 'XN--MGBBH1A71E', 'XN--MGBC0A9AZCG', 'XN--MGBCA7DZDO', 'XN--MGBERP4A5D4AR', 'XN--MGBGU82A', 'XN--MGBI4ECEXP', 'XN--MGBPL2FH', 'XN--MGBT3DHD', 'XN--MGBTX2B', 'XN--MGBX4CD0AB', 'XN--MIX891F', 'XN--MK1BU44C', 'XN--MXTQ1M', 'XN--NGBC5AZD', 'XN--NGBE9E0A', 'XN--NGBRX', 'XN--NODE', 'XN--NQV7F', 'XN--NQV7FS00EMA', 'XN--NYQY26A', 'XN--O3CW4H', 'XN--OGBPF8FL', 'XN--OTU796D', 'XN--P1ACF', 'XN--P1AI', 'XN--PBT977C', 'XN--PGBS0DH', 'XN--PSSY2U', 'XN--Q9JYB4C', 'XN--QCKA1PMC', 'XN--QXAM', 'XN--RHQV96G', 'XN--ROVU88B', 'XN--RVC1E0AM3E', 'XN--S9BRJ9C', 'XN--SES554G', 'XN--T60B56A', 'XN--TCKWE', 'XN--TIQ49XQYJ', 'XN--UNUP4Y', 'XN--VERMGENSBERATER-CTB', 'XN--VERMGENSBERATUNG-PWB', 'XN--VHQUV', 'XN--VUQ861B', 'XN--W4R85EL8FHU5DNRA', 'XN--W4RS40L', 'XN--WGBH1C', 'XN--WGBL6A', 'XN--XHQ521B', 'XN--XKC2AL3HYE2A', 'XN--XKC2DL3A5EE0H', 'XN--Y9A3AQ', 'XN--YFRO4I67O', 'XN--YGBI2AMMX', 'XN--ZFR164B', 'XXX', 'XYZ', 'YACHTS', 'YAHOO', 'YAMAXUN', 'YANDEX', 'YE', 'YODOBASHI', 'YOGA', 'YOKOHAMA', 'YOU', 'YOUTUBE', 'YT', 'YUN', 'ZA', 'ZAPPOS', 'ZARA', 'ZERO', 'ZIP', 'ZM', 'ZONE', 'ZUERICH', 'ZW' ]; // Keep as upper-case to make updating from source easier module.exports = new Set(internals.tlds.map((tld) => tld.toLowerCase()));
// List of tuners module.exports = { props: ['tuners', 'tuner'], template: require('./tuner-list.html'), methods: { onTunerChanged(e) { let tuner = null; if (e.target.selectedIndex === 0) { tuner = null; } else { tuner = e.target.options[e.target.selectedIndex].value; tuner = this.tuners.find(t => t.name === tuner); } return this.$emit('tuner-changed', tuner); }, }, };
/* jshint node: true */ /* global require, module */ var EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); var app = new EmberAddon({ snippetPaths: ['tests/dummy/snippets'], snippetSearchPaths: ['app', 'tests/dummy/app', 'addon'], minifyJS: { enabled: false } }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. module.exports = app.toTree();
'use strict'; process.env.NODE_ENV = 'test'; const test = require('tape-catch'); const app = require('./../app/app'); const request = require('supertest'); const mongoose = require('mongoose'); const Config = require('./../app/config'); const user = require('./../app/models/user'); let token = ''; let task_id = ''; let config = new Config(); test('test config', function(t){ process.env.NODE_ENV = 'test'; config = new Config(); t.ok(typeof config.database !== 'undefined', 'Set test db'); t.ok(typeof config.secret !== 'undefined', 'Set test secret'); process.env.NODE_ENV = 'development'; config = new Config(); t.ok(typeof config.database !== 'undefined', 'Set development db'); t.ok(typeof config.secret !== 'undefined', 'Set development secret'); process.env.NODE_ENV = 'production'; config = new Config(); t.ok(typeof config.database !== 'undefined', 'Set production db'); t.ok(typeof config.secret !== 'undefined', 'Set production secret'); process.env.NODE_ENV = 'bla'; config = new Config(); t.ok(typeof config.database !== 'undefined', 'Set db'); t.ok(typeof config.secret !== 'undefined', 'Set secret'); process.env.NODE_ENV = 'test'; config = new Config(); t.end(); }) test('return welcome message', function (t) { request(app) .get('/') .expect(200) .end(function(err, result){ t.error(err, 'No errors'); t.equal(result.text, 'Hello! Welcome in our API', 'Returns hello'); t.end(); }); }) test('add user', function(t){ user.add({ name: 'Test', mail: 'test@test.com', password: 'test' }, function(err, res){ t.error(err, 'No error while adding test user'); t.equal(res.mail, 'test@test.com', 'Return user'); t.end(); }) }) test('authentication - no user', function(t){ request(app) .post('/authenticate') .send({"name": "yolo"}) .expect(200) .end(function(err, result){ t.error(err, 'No errors'); t.equal(result.text, '{\"success\":false,\"message\":\"Authentication failed. User not found.\"}'); t.end(); }); }) test('authentication - success', function(t){ request(app) .post('/authenticate') .send({"name": "Test", "password": "test"}) .expect(200) .end(function(err, result){ t.error(err, 'No errors'); const res = JSON.parse(result.text); token = res.token; t.equal(res.success, true, 'Logged - token given'); t.end(); }); }) test('authentication - wrong password', function(t){ request(app) .post('/authenticate') .send({"name": "Test"}) .expect(200) .end(function(err, result){ t.error(err, 'No errors'); t.equal(result.text, '{\"success\":false,\"message\":\"Authentication failed. Wrong password.\"}'); t.end(); }); }) test('get /users', function (t){ request(app) .get('/users') .set('x-access-token', token) .expect(200) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); t.notEqual(result.text, '[]', 'User on list'); t.end(); }); }) test('get /users/username', function(t){ request(app) .get('/users/Test') .set('x-access-token', token) .expect(200) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); const user = JSON.parse(result.text); t.equal(user.mail, 'test@test.com', 'User returned') t.end(); }) }) test('get /users/username - wrong username', function(t){ request(app) .get('/users/Testowo') .set('x-access-token', token) .expect(400) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); const user = JSON.parse(result.text); t.equal(user.success, false, 'Failed'); t.equal(user.message, 'User not found.', 'User not found'); t.end(); }) }) test('addUser', function(t){ const user = require('./../app/models/user'); user.add({ name: 'Test', mail: 'test@test.com' }, function(err, result){ t.equal(err.errors.password.kind, "required", "Password required error"); }) user.add({ name: 'Test', mail: 'test@test', password: 'test' }, function(err, result){ t.equal(err.errors.mail.kind, "user defined", "Wrong email"); }) user.add({ name: 'Tests', mail: 'test@test.com', password: 'test' }, function(err, result){ t.equal(err.errors.mail.kind, "Duplicate value", "Duplicate email"); }) user.add({ name: 'Test', mail: 'test@test.pl', password: 'test' }, function(err, result){ t.equal(err.errors.name.kind, "Duplicate value", "Duplicate name"); t.end(); }) }) test('addUser route error printing', function(t){ request(app) .post('/users') .send({ name: 'Test', mail: 'test@test.com', password: 'test' }) .set('x-access-token', token) .expect(400) .end(function(err, result){ const errors = JSON.parse(result.text); t.equal(errors.errors.name.kind, 'Duplicate value', 'Error returned'); t.end(); }); }) test('addUser route', function(t){ request(app) .post('/users') .send({ name: 'Test2', mail: 'test2@test.com', password: 'test' }) .set('x-access-token', token) .expect(200) .end(function(err, result){ const newUser = JSON.parse(result.text); t.equal(newUser.mail, 'test2@test.com', 'User returned'); t.end(); }); }) // TODO: fix update to return no document when you try to update one that does not exist test('update /users/:user_name - fail', function(t){ request(app) .post('/users/gddfdfs') .send({ name: 'Test3', mail: 'test2@test.com', password: 'test'}) .set('x-access-token', token) .expect(400) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); const user = JSON.parse(result.text); t.equal(user.message, 'User does not exist.', 'User does not exist.'); t.end(); }) }) test('update /users/:user_name', function(t){ request(app) .post('/users/Test2') .send({ name: 'Test3', mail: 'test2@test.com', password: 'test'}) .set('x-access-token', token) .expect(200) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); const user = JSON.parse(result.text); t.equal(user.name, 'Test3', 'User updated'); t.end(); }) }) test('update /users/:user_name - fail validation', function(t){ request(app) .post('/users/Test3') .send({ name: 'Test3', mail: 'test2@test'}) .set('x-access-token', token) .expect(400) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); const user = JSON.parse(result.text); t.equal(user.name, 'ValidationError', 'Validation error'); t.end(); }) }) test('remove user', function(t){ request(app) .delete('/users/Test3') .set('x-access-token', token) .expect(200) .end(function(err, result){ const removedUser = JSON.parse(result.text); t.equal(removedUser.mail, 'test2@test.com', 'Removed user returned'); t.end(); }) }) test('remove user fail', function(t){ request(app) .delete('/users/Test4') .set('x-access-token', token) .expect(400) .end(function(err, result){ const info = JSON.parse(result.text); t.equal(info.message, 'User does not exist.', 'Cannot remove user that not exist'); t.end(); }) }) test('checking if authenticated', function(t){ request(app) .post('/authenticate') .send({"name": "Test", "password": "test"}) .expect(200) .end(function(err, result){ const res = JSON.parse(result.text); const token = res.token; request(app) .get('/tasks') .set('x-access-token', token) .expect(200) .end(function(err, result){ t.error(err, 'No errors'); t.equal(result.text, '[]', 'Empty tasks list'); t.end(); }) }); }) test('add task', function(t){ request(app) .post('/tasks') .send({ name: 'Testowe zadanko', user: 'Test'}) .set('x-access-token', token) .expect(200) .end(function(err, result){ const task = JSON.parse(result.text); task_id = task._id; t.equal(task.name, 'Testowe zadanko', 'New task added'); t.end(); }) }) test('add task fail', function(t){ request(app) .post('/tasks') .send({ name: 'Testowe zadanko', user: 'Yolo453'}) .set('x-access-token', token) .expect(200) .end(function(err, result){ const error = JSON.parse(result.text); t.equal(error.name, 'ValidationError', 'New task failed to add'); t.end(); }) }) test('get /tasks/taskid', function(t){ request(app) .get('/tasks/'+task_id) .set('x-access-token', token) .expect(200) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); const task = JSON.parse(result.text); t.equal(task.name, 'Testowe zadanko', 'Task returned') t.end(); }) }) // TODO: fix tests to be unbreakable - no need to manual database clear when previous tests fail test('get /tasks/:task_id - wrong id', function(t){ request(app) .get('/tasks/fdsfdsf') .set('x-access-token', token) .expect(400) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); const task = JSON.parse(result.text); t.equal(task.success, false, 'Failed'); t.equal(task.message, 'Task not found.', 'Task not found'); t.end(); }) }) test('update /tasks/:task_id - fail', function(t){ request(app) .post('/tasks/gddfdfs') .send({ name: 'Testowe zadanko 2', user: 'Test'}) .set('x-access-token', token) .expect(400) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); const task = JSON.parse(result.text); t.equal(task.name, 'CastError', 'Could not update task.'); t.end(); }) }) test('update /tasks/:task_id - fail', function(t){ request(app) .post('/tasks/507f1f77bcf86cd799439011') .send({ name: 'Testowe zadanko 2', user: 'Test'}) .set('x-access-token', token) .expect(400) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); const task = JSON.parse(result.text); t.equal(task.message, 'Task does not exist.', 'Could not update task.'); t.end(); }) }) test('update /tasks/:task_id', function(t){ request(app) .post('/tasks/'+task_id) .send({ name: 'Testowe zadanko 2', user: 'Test'}) .set('x-access-token', token) .expect(200) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); const task = JSON.parse(result.text); t.equal(task.name, 'Testowe zadanko 2', 'Task updated'); t.end(); }) }) test('update /tasks/:task_id - failed validation', function(t){ request(app) .post('/tasks/'+task_id) .send({ name: 'Testowe zadanko 2', user: 'Testowo'}) .set('x-access-token', token) .expect(400) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); const task = JSON.parse(result.text); t.equal(task.message, 'Validation failed', 'Failed'); t.end(); }) }) //test to check validators on update test('remove /tasks/:task_id', function(t){ request(app) .delete('/tasks/'+task_id) .set('x-access-token', token) .expect(200) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); const task = JSON.parse(result.text); t.equal(task._id, task_id, 'Task removed.') t.end(); }) }) test('remove /tasks/:task_id - wrong id', function(t){ request(app) .delete('/tasks/jdfkjdsf') .set('x-access-token', token) .expect(400) .expect('Content-Type', 'application\/json; charset=utf-8') .end(function(err, result){ t.error(err, 'No errors'); const task = JSON.parse(result.text); t.equal(task.success, false, 'Failed'); t.equal(task.message, 'Task not found.', 'Task not found'); t.end(); }) }) test('get tasks not done', function(t){ request(app) .get('/tasks/?status=todo') .set('x-access-token', token) .expect(200) .end(function(err, result){ t.error(err, 'No errors'); t.equal(result.text, '[]', 'Empty tasks list'); t.end(); }); }) test('get tasks done', function(t){ request(app) .get('/tasks/?status=done') .set('x-access-token', token) .expect(200) .end(function(err, result){ t.error(err, 'No errors'); t.equal(result.text, '[]', 'Empty tasks list'); t.end(); }); }) test('get tasks cancelled', function(t){ request(app) .get('/tasks/?status=cancelled') .set('x-access-token', token) .expect(200) .end(function(err, result){ t.error(err, 'No errors'); t.equal(result.text, '[]', 'Empty tasks list'); t.end(); }); }) test('get tasks by priority', function(t){ request(app) .get('/tasks/?sort=priority') .set('x-access-token', token) .expect(200) .end(function(err, result){ t.error(err, 'No errors'); t.equal(result.text, '[]', 'Empty tasks list'); t.end(); }); }) test('get tasks by size', function(t){ request(app) .get('/tasks/?sort=size') .set('x-access-token', token) .expect(200) .end(function(err, result){ t.error(err, 'No errors'); t.equal(result.text, '[]', 'Empty tasks list'); t.end(); }); }) test('get tasks by deadline', function(t){ request(app) .get('/tasks/?sort=deadline') .set('x-access-token', token) .expect(200) .end(function(err, result){ t.error(err, 'No errors'); t.equal(result.text, '[]', 'Empty tasks list'); t.end(); }); }) test('get tasks by project', function(t){ request(app) .get('/tasks/?sort=project') .set('x-access-token', token) .expect(200) .end(function(err, result){ t.error(err, 'No errors'); t.equal(result.text, '[]', 'Empty tasks list'); t.end(); }); }) test('get tasks by real size', function(t){ request(app) .get('/tasks/?sort=real-size') .set('x-access-token', token) .expect(200) .end(function(err, result){ t.error(err, 'No errors'); t.equal(result.text, '[]', 'Empty tasks list'); t.end(); }); }) test('get tasks by tag', function(t){ request(app) .get('/tasks/?tag=test') .set('x-access-token', token) .expect(200) .end(function(err, result){ t.error(err, 'No errors'); t.equal(result.text, '[]', 'Empty tasks list'); t.end(); }); }) test('isLogged wrong token', function(t){ request(app) .get('/tasks') .set('x-access-token', 'token') .expect(400) .end(function(err, result){ const res = JSON.parse(result.text); t.error(err, 'No errors'); t.equal(res.message, 'Failed to authenticate token.', 'wrong token'); t.end(); }); }) test('isLogged without token', function(t){ request(app) .post('/authenticate') .send({"name": "Test", "password": "test"}) .expect(200) .end(function(err, result){ request(app) .get('/tasks') .expect(400) .end(function(err, result){ const res = JSON.parse(result.text); t.error(err, 'No errors'); t.equal(res.message, 'No token provided.', 'No token send'); t.end(); }) }); }); test.onFinish(function(){ mongoose.connect(config.database, function(){ mongoose.connection.db.dropDatabase(); process.exit(0); }); });
"use strict"; const PutIoHelper_1 = require('../helpers/PutIoHelper'); class Transfers extends PutIoHelper_1.PutIoHelper { getTransfersList() { return this.requestData('GET', 'transfers/list', []); } addTransfer(urls) { const paramaters = []; const transferURL = { urls: `[${urls.toString}]` }; paramaters.push(JSON.stringify(transferURL)); return this.requestData('POST', 'transfers/add-multi', paramaters); } getTransferId(id) { return this.requestData('GET', `transfers/${id}`, []); } getTransferInfo(url) { const paramaters = []; const transferURL = { urls: `${url}` }; paramaters.push(JSON.stringify(transferURL)); return this.requestData('POST', 'transfers/info', paramaters); } retryTransfer(id) { const paramaters = []; const transferId = { id: `${id}` }; paramaters.push(JSON.stringify(transferId)); return this.requestData('POST', 'transfers/retry', paramaters); } cancelTransfers(transferIds) { const paramaters = []; const transferIdsToCancel = { transfer_ids: `${transferIds.toString()}` }; paramaters.push(JSON.stringify(transferIdsToCancel)); return this.requestData('POST', 'transfers/cancel', paramaters); } cleanTransfers() { return this.requestData('POST', 'transfers/clean', []); } } exports.Transfers = Transfers; //# sourceMappingURL=Transfers.js.map
define(['exports', './collection-strategy'], function (exports, _collectionStrategy) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var MapCollectionStrategy = (function (_CollectionStrategy) { _inherits(MapCollectionStrategy, _CollectionStrategy); function MapCollectionStrategy() { _classCallCheck(this, MapCollectionStrategy); _CollectionStrategy.apply(this, arguments); } MapCollectionStrategy.prototype.getCollectionObserver = function getCollectionObserver(items) { return this.observerLocator.getMapObserver(items); }; MapCollectionStrategy.prototype.processItems = function processItems(items) { var _this = this; var viewFactory = this.viewFactory; var viewSlot = this.viewSlot; var index = 0; var overrideContext = undefined; var view = undefined; items.forEach(function (value, key) { overrideContext = _this.createFullOverrideContext(value, index, items.size, key); view = viewFactory.create(); view.bind(undefined, overrideContext); viewSlot.add(view); ++index; }); }; MapCollectionStrategy.prototype.handleChanges = function handleChanges(map, records) { var _this2 = this; var viewSlot = this.viewSlot; var key = undefined; var i = undefined; var ii = undefined; var view = undefined; var overrideContext = undefined; var removeIndex = undefined; var record = undefined; var rmPromises = []; var viewOrPromise = undefined; for (i = 0, ii = records.length; i < ii; ++i) { record = records[i]; key = record.key; switch (record.type) { case 'update': removeIndex = this._getViewIndexByKey(key); viewOrPromise = viewSlot.removeAt(removeIndex, true); if (viewOrPromise instanceof Promise) { rmPromises.push(viewOrPromise); } overrideContext = this.createFullOverrideContext(map.get(key), removeIndex, map.size, key); view = this.viewFactory.create(); view.bind(undefined, overrideContext); viewSlot.insert(removeIndex, view); break; case 'add': overrideContext = this.createFullOverrideContext(map.get(key), map.size - 1, map.size, key); view = this.viewFactory.create(); view.bind(undefined, overrideContext); viewSlot.insert(map.size - 1, view); break; case 'delete': if (record.oldValue === undefined) { return; } removeIndex = this._getViewIndexByKey(key); viewOrPromise = viewSlot.removeAt(removeIndex, true); if (viewOrPromise instanceof Promise) { rmPromises.push(viewOrPromise); } break; case 'clear': viewSlot.removeAll(true); break; default: continue; } } if (rmPromises.length > 0) { Promise.all(rmPromises).then(function () { _this2.updateOverrideContexts(0); }); } else { this.updateOverrideContexts(0); } }; MapCollectionStrategy.prototype._getViewIndexByKey = function _getViewIndexByKey(key) { var viewSlot = this.viewSlot; var i = undefined; var ii = undefined; var child = undefined; for (i = 0, ii = viewSlot.children.length; i < ii; ++i) { child = viewSlot.children[i]; if (child.overrideContext[this.key] === key) { return i; } } }; return MapCollectionStrategy; })(_collectionStrategy.CollectionStrategy); exports.MapCollectionStrategy = MapCollectionStrategy; });
'use strict'; var errorPage = require('../../lib/serve/error_page'), extend = require('extend'), sharedOptions = require('./shared_options'), Server = require('../../lib/serve/server'); var build = require('./build').handler; module.exports.command = 'serve [input..]'; module.exports.description = 'generate, update, and display HTML documentation'; /** * Add yargs parsing for the serve command * @param {Object} yargs module instance * @returns {Object} yargs with options * @private */ module.exports.builder = extend( {}, sharedOptions.sharedOutputOptions, sharedOptions.sharedInputOptions, { port: { describe: 'port for the local server', type: 'number', default: 4001 } }); /** * Wrap the documentation build command along with a server, making it possible * to preview changes live * @private * @param {Object} argv cli input * @returns {undefined} has side effects */ module.exports.handler = function serve(argv) { argv._handled = true; var server = new Server(argv.port); server.on('listening', function () { process.stdout.write('documentation.js serving on port ' + argv.port + '\n'); }); build(extend({}, { format: 'html' }, argv), function (err, output) { if (err) { return server.setFiles([errorPage(err)]).start(); } server.setFiles(output).start(); }); };
/// <reference path="../../typings/validator/validator.d.ts" /> System.register([], function (exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; var Property; return { setters: [], execute: function () {/// <reference path="../../typings/validator/validator.d.ts" /> Property = (function () { function Property() { this.name = ''; this.description = ''; this.type = 'Text'; this.fieldType = 'Enter'; this.options = []; this.format = []; } Property.isValid = function (prop, value) { var valid; try { valid = Property._validMap[prop.type](value); } catch (err) { throw new TypeError('Could not be validated against existing type'); } finally { return valid; } }; Property.fromValue = function (prop, value) { if (!Property.isValid(prop, value)) { return Property._asType[prop.type](value); } return value; }; Property.inferOptions = function (values, clean) { if (clean === void 0) { clean = true; } var options = {}; values.forEach(function (d) { if (d.length < 64) { if (clean) { d = d.trim().toLowerCase(); } options[d] = options[d] + 1 || 0; } }); return { options: Object.keys(options), values: values }; }; Property.fromJSType = function (value) { var rbType = "None"; var missingPatterns = ["", " ", "na", "n/a", "null", "undefined", "missing", "-"]; var missingTest = value.trim().toLowerCase(); if (missingTest.indexOf(missingTest) === -1) { return rbType; } var jsTypeString = typeof value; switch (jsTypeString) { case 'number': if (Property._validMap["Number"](value)) { rbType = "Number"; } break; case 'string': if (Property._validMap["Text"](value)) { rbType = "Text"; } if (Property._validMap["Location"](value)) { rbType = "Location"; } if (Property._validMap["Boolean"](value)) { rbType = "Boolean"; } break; case 'boolean': if (Property._validMap["Boolean"](value)) { rbType = "Boolean"; } default: break; } return rbType; }; return Property; }()); Property.propertyTypes = ['Number', 'Text', 'Page', 'Link', 'Boolean', 'Date', 'Location']; Property.fieldTypes = ['Enter', 'Select', 'Check']; Property._validMap = { "Number": function (value) { var valid = typeof value === 'number'; if (valid) { valid = isFinite(value); } return valid; }, "Text": function (value) { var valid = typeof value === 'string'; return valid; }, "Page": function (value) { var pattern = /@Page\({(.?)}\)/; var valid = pattern.exec(value) !== null; return valid; }, "Link": function (value) { var valid = encodeURIComponent(value) === value; return valid; }, "Boolean": function (value) { var valid = typeof value === 'boolean'; return valid; }, "Date": function (value) { var valid = Object.prototype.toString.call(value) === "[object Date]"; if (valid) { valid = !isNaN(value.getTime()); } return valid; }, "Location": function (value) { var allowedProps = ["type", "geometry"]; var valid = false; try { var geojson = JSON.parse(value); valid = typeof geojson === 'object'; for (var prop in geojson) { valid = allowedProps.indexOf(prop) !== -1; } valid = geojson.type === 'Feature'; } catch (err) { valid = false; } finally { return valid; } } }; Property._asType = { "Number": function (value) { var numberVal = parseFloat(value); if (isFinite(numberVal)) { return numberVal; } return NaN; }, "Text": function (value) { var textVal = value.toString(); return textVal; }, "Page": function (value) { var pageValue = value.toString(); return pageValue; }, "Link": function (value) { var linkValue = encodeURIComponent(value); return linkValue; }, "Boolean": function (value) { var boolVal = false; if (typeof value === 'string') { if (value.trim().toLowerCase() === 'true') { boolVal = true; } if (value.trim().toLowerCase() === 'false') { boolVal = false; } } return boolVal; }, "Date": function (value) { var dateVal = new Date(value); return dateVal; }, "Location": function (value) { //todo } }; exports_1("Property", Property); } }; }); //# sourceMappingURL=property.js.map
// Cache selectors var lastId, topMenu = $("#responsive-menu"), topMenuHeight = topMenu.outerHeight()+15, // All list items menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function(){ var item = $($(this).attr("href")); if (item.length) { return item; } }); // Bind click handler to menu items // so we can get a fancy scroll animation menuItems.click(function(e){ var href = $(this).attr("href"), offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1; $('html, body').stop().animate({ scrollTop: offsetTop }, 300); e.preventDefault(); }); // Bind to scroll $(window).scroll(function(){ // Get container scroll position var fromTop = $(this).scrollTop()+topMenuHeight; // Get id of current scroll item var cur = scrollItems.map(function(){ if ($(this).offset().top < fromTop) return this; }); // Get the id of the current element cur = cur[cur.length-1]; var id = cur && cur.length ? cur[0].id : ""; if (lastId !== id) { lastId = id; // Set/remove active class menuItems .parent().removeClass("active") .end().filter("[href='#"+id+"']").parent().addClass("active"); } });
import * as M from "@effectful/core"; // *- when it is the last statement (function () { var e, ex; function _1() { e = ex; return M.chain(eff(3), _2); } function _2() {} });
$(function(){ var binds = []; var edit_index = -1; var edit_key_id = null; function loadBindsFromJSON(file) { // Load Binds $.get("data/" + file, function(data) { binds = JSON.parse(data); binds.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); } // Stupid hack to clear them for now function clearBinds() { $("#bind_container h2").html(""); $("#bind_container div").css("background-color",""); $("#bind_container div").attr("title",""); $("#bind_container div").removeClass("has_action"); } // Initial load loadBindsFromJSON("ninja_binds.txt"); /* * Other */ $(".key").each(function() { $(this).prepend('<i class="fa fa-pencil"></i>'); }); $(".key i").click(function() { var $key_editor = $("#key_editor"); var key_id = $(this).parent("div").attr("id"); var key_name = $(this).siblings("div").html(); $key_editor.show(); $("h3 span", $key_editor).html(key_name); //console.log(binds); // Look for the bind in the JSON binds.forEach(function(e, i, a) { var key = Object.keys(e)[0]; if (key == key_id) { var bind = e[key]; console.log(e[key]); console.log(i); edit_index = i; edit_key_id = key_id; $("#edit_key_title").val(bind.title); $("#edit_key_action").val(bind.action); if (bind.color != "") { $('#picker').colpickSetColor(bind.color); } else { $('#picker').colpickSetColor("#ffffff"); } return false; } }); }); $("#key_save").click(function() { console.log(binds[edit_index]); console.log(binds[edit_index][edit_key_id]); var bind = binds[edit_index][edit_key_id]; var $bind = $("#" + edit_key_id); bind.title = $("#edit_key_title").val(); bind.action = $("#edit_key_action").val(); bind.color = "#" + $(".colpick_hex_field input").val(); console.log(bind); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } }); $('#picker').colpick({ flat:true, layout:'hex', colorScheme:'dark', submit:0 }); $("#about").click(function() { $("#about-info").show(); }); $("#parse").click(function() { $("#parse-my-config").show(); }); $("#download").click(function() { var b = kbx_to_xon(binds); $("#d_my_config").val(b.join("\n")); $("#download-my-config").show(); }); $("#download2").click(function() { $("#d_my_kbx").val(JSON.stringify(binds)); $("#download-my-kbx").show(); }); $("#load").click(function() { $("#load-my-kbx").show(); }); $("#parse_it").click(function() { clearBinds(); var data = $("#my_config").val(); var cfg_array = data.split("\n"); var b = xon_to_kbx(cfg_array); b.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); $("#load_my_kbx").click(function() { clearBinds(); var data = $("#my_kbx").val(); var b = JSON.parse(data); b.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; // loop through the JSON and apply it to the HTML // Load New if (bind.title != "" || bind.color != "") { var $bind = $("#" + key); if (bind.action != "") { $bind.attr("title", bind.action); $bind.addClass("has_action"); } if (bind.color != "") { $bind.css("background-color", bind.color); } if (bind.title != "") { $("h2", $bind).html(bind.title); } } }); }); $(".close").click(function() { var parent = $(this).parent().attr("id"); $("#" + parent).hide(); }); /* * Examples for debugging */ $("#kbx-to-xon").click(function(e) { kbx_to_xon(binds); }); $("#parse-vanilla").click(function(e) { // cfg to kbx JSON $.get("data/vanilla-config.cfg", function(data) { var cfg_array = data.split("\n"); xon_to_kbx(cfg_array); }); e.preventDefault(); }); $("#load-parsed-cfg").click(function(e) { clearBinds(); loadBindsFromJSON("vanilla_binds.txt"); }); $("#load-ninja-binds").click(function(e) { clearBinds(); loadBindsFromJSON("ninja_binds.txt"); }); /* * Parsing Functions */ // object to map kbx names to xonotic cfg var kbx_names = { "esc": "escape", "backtick": "backquote", "up": "uparrow", "right": "rightarrow", "down": "downarrow", "left": "leftarrow", "num_0": "kp_ins", "num_period": "kp_del", "num_3": "kp_pgdn", "num_6": "kp_rightarrow", "num_9": "kp_pgup", "num_8": "kp_uparrow", "num_7": "kp_home", "num_4": "kp_leftarrow", "num_1": "kp_end", "num_2": "kp_downarrow", "num_5": "kp_5", "num_enter": "kp_enter", "num_plus": "kp_plus", "num_minus": "kp_minus", "num_multiply": "kp_multiply", "num_slash": "kp_slash", "minus": "-", "plus": "=", "left_bracket": "[", "right_bracket": "]", "space_bar": "space", "mouse_wheel_up": "mwheelup", "mouse_wheel_down": "mwheeldown" }; // object to map xonotic cfg names to kbx var xon_names = { "escape": "esc", "backquote": "backtick", "-": "minus", "=": "plus", "[": "left_bracket", "]": "right_bracket", "space": "space_bar", "uparrow": "up", "leftarrow": "left", "downarrow": "down", "rightarrow": "right", "kp_slash": "num_slash", "kp_multiply": "num_multiply", "kp_minus": "num_minus", "kp_home": "num_7", "kp_uparrow": "num_8", "kp_pgup": "num_9", "kp_plus": "num_plus", "kp_leftarrow": "num_4", "kp_5": "num_5", "kp_rightarrow": "num_6", "kp_end": "num_1", "kp_downarrow": "num_2", "kp_pgdn": "num_3", "kp_enter": "num_enter", "kp_ins": "num_0", "kp_del": "num_period", "mwheelup": "mouse_wheel_up", "mwheeldown": "mouse_wheel_down" }; function kbx_to_xon(kbx_json) { var output = []; kbx_json.forEach(function(e, i, a) { var key = Object.keys(e)[0]; var bind = e[key]; var k = key.replace("key_",""); if (kbx_names[k] != undefined) { output.push('bind ' + kbx_names[k] + ' "' + bind.action + '" // ' + bind.title); } else { output.push('bind ' + k + ' "' + bind.action + '" // ' + bind.title); } }); console.log(output.join("\n")); return output; } function xon_to_kbx(cfg_array) { var output = []; cfg_array.forEach(function(e, i, a) { var re = /^bind (.+) "(.+)"( (.+))?/i; var raw = e.match(re); if (raw) { //console.log(raw); var bind = raw[1].toLowerCase(); var action = raw[2]; var key = xon_names[bind] || bind; key = "key_" + key; var o = {}; o[key] = { "title": action, "action": action, "color": "" }; output.push(o); } else { console.warn(e); } }); console.log(output); console.log(JSON.stringify(output)); return output; } });
/* @flow * */ jest.unmock('../array.js'); jest.unmock('../../../definition/def.js'); import {isArray} from '../array.js'; import {RunTimeCheckE, ePrint} from '../../../definition/def.js'; describe('test isArray()', () => { it('will throw when value is not a Array', function() { const v = {0:'1', 1:'22', 2:'aaa'}; expect(() => { isArray(v); }).toThrow(new RunTimeCheckE(`value:(${ePrint(v)}) is not a Array.`)); }); it('will return the passed in value when its a Array', function() { const v = [1, 2, 'a', 'bbb']; const rt:mixed[] = isArray(v); expect(rt).toEqual(v); }); });
/* AngularJS v1.2.16 (c) 2010-2014 Google, Inc. http://angularjs.org License: MIT */ (function (H, a, A) { 'use strict'; function D(p, g) { g = g || {}; a.forEach(g, function (a, c) { delete g[c] }); for (var c in p)!p.hasOwnProperty(c) || "$" === c.charAt(0) && "$" === c.charAt(1) || (g[c] = p[c]); return g } var v = a.$$minErr("$resource"), C = /^(\.[a-zA-Z_$][0-9a-zA-Z_$]*)+$/; a.module("ngResource", ["ng"]).factory("$resource", ["$http", "$q", function (p, g) { function c(a, c) { this.template = a; this.defaults = c || {}; this.urlParams = {} } function t(n, w, l) { function r(h, d) { var e = {}; d = x({}, w, d); s(d, function (b, d) { u(b) && (b = b()); var k; if (b && b.charAt && "@" == b.charAt(0)) { k = h; var a = b.substr(1); if (null == a || "" === a || "hasOwnProperty" === a || !C.test("." + a))throw v("badmember", a); for (var a = a.split("."), f = 0, c = a.length; f < c && k !== A; f++) { var g = a[f]; k = null !== k ? k[g] : A } } else k = b; e[d] = k }); return e } function e(a) { return a.resource } function f(a) { D(a || {}, this) } var F = new c(n); l = x({}, B, l); s(l, function (h, d) { var c = /^(POST|PUT|PATCH)$/i.test(h.method); f[d] = function (b, d, k, w) { var q = {}, n, l, y; switch (arguments.length) { case 4: y = w, l = k; case 3: case 2: if (u(d)) { if (u(b)) { l = b; y = d; break } l = d; y = k } else { q = b; n = d; l = k; break } case 1: u(b) ? l = b : c ? n = b : q = b; break; case 0: break; default: throw v("badargs", arguments.length); } var t = this instanceof f, m = t ? n : h.isArray ? [] : new f(n), z = {}, B = h.interceptor && h.interceptor.response || e, C = h.interceptor && h.interceptor.responseError || A; s(h, function (a, b) { "params" != b && ("isArray" != b && "interceptor" != b) && (z[b] = G(a)) }); c && (z.data = n); F.setUrlParams(z, x({}, r(n, h.params || {}), q), h.url); q = p(z).then(function (b) { var d = b.data, k = m.$promise; if (d) { if (a.isArray(d) !== !!h.isArray)throw v("badcfg", h.isArray ? "array" : "object", a.isArray(d) ? "array" : "object"); h.isArray ? (m.length = 0, s(d, function (b) { m.push(new f(b)) })) : (D(d, m), m.$promise = k) } m.$resolved = !0; b.resource = m; return b }, function (b) { m.$resolved = !0; (y || E)(b); return g.reject(b) }); q = q.then(function (b) { var a = B(b); (l || E)(a, b.headers); return a }, C); return t ? q : (m.$promise = q, m.$resolved = !1, m) }; f.prototype["$" + d] = function (b, a, k) { u(b) && (k = a, a = b, b = {}); b = f[d].call(this, b, this, a, k); return b.$promise || b } }); f.bind = function (a) { return t(n, x({}, w, a), l) }; return f } var B = { get: {method: "GET"}, save: {method: "POST"}, query: {method: "GET", isArray: !0}, remove: {method: "DELETE"}, "delete": {method: "DELETE"} }, E = a.noop, s = a.forEach, x = a.extend, G = a.copy, u = a.isFunction; c.prototype = { setUrlParams: function (c, g, l) { var r = this, e = l || r.template, f, p, h = r.urlParams = {}; s(e.split(/\W/), function (a) { if ("hasOwnProperty" === a)throw v("badname"); !/^\d+$/.test(a) && (a && RegExp("(^|[^\\\\]):" + a + "(\\W|$)").test(e)) && (h[a] = !0) }); e = e.replace(/\\:/g, ":"); g = g || {}; s(r.urlParams, function (d, c) { f = g.hasOwnProperty(c) ? g[c] : r.defaults[c]; a.isDefined(f) && null !== f ? (p = encodeURIComponent(f).replace(/%40/gi, "@").replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "%20").replace(/%26/gi, "&").replace(/%3D/gi, "=").replace(/%2B/gi, "+"), e = e.replace(RegExp(":" + c + "(\\W|$)", "g"), function (a, c) { return p + c })) : e = e.replace(RegExp("(/?):" + c + "(\\W|$)", "g"), function (a, c, d) { return "/" == d.charAt(0) ? d : c + d }) }); e = e.replace(/\/+$/, "") || "/"; e = e.replace(/\/\.(?=\w+($|\?))/, "."); c.url = e.replace(/\/\\\./, "/."); s(g, function (a, e) { r.urlParams[e] || (c.params = c.params || {}, c.params[e] = a) }) } }; return t }]) })(window, window.angular); //# sourceMappingURL=angular-resource.min.js.map
import React, { Component } from 'react'; import { observer, inject } from 'mobx-react'; import { Link } from 'react-router-dom'; import classNames from 'classnames'; class Member extends Component { constructor(props) { super(props); const { member } = props this.state = { edit: false, name: member.get('name'), phone_number: member.get('phone_number') } } render() { const { edit, name, phone_number } = this.state; const { member, store } = this.props; if (edit) { return ( <tr> <td><input className="input" value={name} onChange={(e) => { this.setState({ name: e.target.value }) }} /></td> <td><input className="input" value={phone_number} onChange={(e) => { this.setState({ phone_number: e.target.value }) }} /></td> <td> <a className="button is-white is-primary" onClick={async () => { await member.save({ name, phone_number }) this.setState({ edit: false }) }}> <span>Done</span> <span className="icon is-small"> <i className="fa fa-check"></i> </span> </a> </td> </tr> ) } return ( <tr className={classNames({ 'is-selected': store.active === member.id })}> <td><Link to={`/family/${member.id}`} onClick={() => store.active = member.id}>{member.get('name')}</Link></td> <td>{member.get('phone_number')}</td> <td> <a className="button is-white" onClick={() => { this.setState({ edit: true }) }}> <span>Edit</span> <span className="icon is-small"> <i className="fa fa-edit"></i> </span> </a> <a className="button is-white is-danger" onClick={() => { member.destroy(); }}> <span>Remove</span> <span className="icon is-small"> <i className="fa fa-times"></i> </span> </a> </td> </tr> ) } } export default inject('store')(observer(Member))
const Timer = require('timer-machine') const CLI = require('clui') const _ = require('ramda') const functionList = exports // stopwatch :: () -> Function const stopwatch = module.exports.stopwatch = () => { function closure () { closure.status = !closure.status closure.status ? closure.timer.start() : closure.timer.stop() return closure.status } closure.status = false closure.timer = new Timer() return closure } // spinner :: () -> Function const spinner = module.exports.spinner = () => { function closure () { closure.status = !closure.status closure.status ? closure.spinner.start() : closure.spinner.stop() return closure.status } closure.status = false closure.spinner = new CLI.Spinner('Performing the task ', ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷']) return closure } // launcher :: [string] -> Function const launcher = module.exports.launcher = (arr) => { function closure () { _.forEach(function (str) { closure[str]() }, arr) } _.forEach(function (str) { closure[str] = functionList[str]() }, arr) return closure }
"use strict"; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- function getUrlVars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- function Init() { // get url vals var urlVars = getUrlVars(); /* if (urlVars["word"]) { var wordOk = checkDictionary(urlVars["word"]); alert(urlVars["word"] + " " + wordOk + " " + getScore(urlVars["word"])); } */ window.addEventListener('keydown', ev_keydown, false); var testRoomA = g_factory.CreateTestRoomA(); g_scene.setCurrentRoom(testRoomA); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- function ev_keydown(ev) { // refocus the command box document.commandBox.command.focus(); if (ev.which == 38 || ev.which == 40) // up or down { g_commandIdx += ev.which == 38 ? -1 : 1; if (g_commandIdx < 0) g_commandIdx = 0; if (g_commandIdx >= g_enteredCommands.length) { g_commandIdx = g_enteredCommands.length; document.commandBox.command.value = ""; } else { document.commandBox.command.value = g_enteredCommands[g_commandIdx]; } } else if (ev.which == 27) //esc { g_commandIdx = g_enteredCommands.length; document.commandBox.command.value = ""; } }
#!/usr/bin/env node 'use strict'; var meow = require('meow'); var speedtest = require('speedtest-net'); var updateNotifier = require('update-notifier'); var roundTo = require('round-to'); var chalk = require('chalk'); var logUpdate = require('log-update'); var elegantSpinner = require('elegant-spinner'); var cli = meow({ help: [ 'Usage', ' $ speed-test' ] }); updateNotifier({pkg: cli.pkg}).notify(); var stats = { ping: '', download: '', upload: '' }; var state = 'ping'; var frame = elegantSpinner(); function getSpinner(x) { return state === x ? chalk.cyan.dim(frame()) : ''; } function render() { logUpdate([ '', ' Ping ' + stats.ping + getSpinner('ping'), ' Download ' + stats.download + getSpinner('download'), ' Upload ' + stats.upload + getSpinner('upload') ].join('\n')); } var st = speedtest({maxTime: 20000}); setInterval(render, 50); st.once('testserver', function (server) { state = 'download'; stats.ping = chalk.cyan(Math.round(server.bestPing) + chalk.dim(' ms')); stats.ping = chalk.bold(stats.ping); }); st.once('downloadspeed', function (speed) { state = 'upload'; stats.download = chalk.cyan(roundTo(speed, 1) + chalk.dim(' Mbps')); stats.download = chalk.bold(stats.download); }); st.once('uploadspeed', function (speed) { state = ''; stats.upload = chalk.cyan(roundTo(speed, 1) + chalk.dim(' Mbps')); stats.upload = chalk.bold(stats.upload); render(); process.exit(); }); st.on('error', function (err) { console.error(err); process.exit(1); });
/*jshint expr: true*/ "use strict"; var chai = require("chai"); var expect = chai.expect; chai.config.includeStack = true; var request = require("supertest"); var alexaAppServer = require("../index"); var fs = require("fs"); describe("Alexa App Server with Examples & Pre/Post functions", function() { var testServer, fired; var sampleLaunchReq; before(function() { fired = {}; testServer = alexaAppServer.start({ port: 3000, server_root: 'examples', pre: function(appServer) { fired.pre = true; }, post: function(appServer) { fired.post = true; }, preRequest: function(json, request, response) { fired.preRequest = true; }, postRequest: function(json, request, response) { fired.postRequest = true; } }); sampleLaunchReq = JSON.parse(fs.readFileSync("test/sample-launch-req.json", 'utf8')); }); after(function() { testServer.stop(); }); it("mounts hello world app (GET)", function() { return request(testServer.express) .get('/alexa/hello_world') .expect(200).then(function(response) { expect(fired.pre).to.equal(true); expect(fired.post).to.equal(true); // only called for actual Alexa requests expect(fired.preRequest).to.equal(undefined); expect(fired.postRequest).to.equal(undefined); }); }); it("mounts hello world app (POST)", function() { return request(testServer.express) .post('/alexa/hello_world') .send(sampleLaunchReq) .expect(200).then(function(response) { expect(fired.pre).to.equal(true); expect(fired.post).to.equal(true); expect(fired.preRequest).to.equal(true); expect(fired.postRequest).to.equal(true); }); }); });
/** * _____ __ * / ___// /_ _____ * \__ \/ / / / / _ \ * ___/ / / /_/ / __/ * /____/_/\__, /\___/ * /____/ * Copyright 2017 Slye Development Team. All Rights Reserved. * Licence: MIT License */ /** * Make an instance of Esy and load configurations * @param argv */ function load(argv) { const esy = require('../src/index'); esy.configs.load(argv['config']); esy.cache.load(); // Load all extra modules that starts with esy- // var dependencies = []; // try{ // var stdout = require('child_process').execSync('npm ls --json'); // dependencies = Object.keys((JSON.parse(stdout))['dependencies']); // } catch (e){ // console.error(`Can not load list of modules.`) // }finally { // dependencies = dependencies.filter(n => n !== 'esy-language' && n.startsWith('esy-')) // for (var dependency of dependencies) { // try { // esy.modules.load(dependency) // } catch (e) { // console.error(`Can not load module <${dependency }>`); // } // } // } if (argv.environments) esy.configs.set('environments', argv.environments, false); var modules = esy.configs.get('modules'); if (typeof modules !== 'object' || modules.length === undefined) modules = []; for (module of modules) { try { esy.modules.load(module) } catch (e) { console.error(`Can not load module <${module}>`); throw e; } } return esy; } module.exports = load;
const request = require('request') const {NotFoundError, TranslationError} = require('../core/errors') const RoutesService = require('../routes/service') function getUri(robot) { if (robot === 'julinha') { return 'http://' + process.env.JULINHA_TRANSLATOR_HOST + ':3000/json' } return 'http://' + process.env.JULINHO_TRANSLATOR_HOST + ':3000/json' } async function walk(req, res, next) { try { const routesService = new RoutesService(res.locals.databaseConnection) const {route: name, robot} = req.body const route = await routesService.findByName(name) if (!route || Object.keys(route).length === 0) { throw new NotFoundError() } const options = { method: 'POST', uri: getUri(robot), body: JSON.stringify(route) } request(options, err => { if (err) { throw new TranslationError() } res.json({ message: 'Route sent with success!' }) }) } catch (err) { if (err.name === NotFoundError.name) { return res.status(404).json({ message: 'Route not found' }) } if (err.name === TranslationError.name) { return res.status(500).json({ message: 'Not possible to translate route' }) } next(err) } } module.exports = { walk }
(function () { 'use strict'; //best practice angular.module('scrumboard.demo') .directive('scrumboardCard', CardDirective); function CardDirective() { return { //return template html templateUrl: '/static/html/card.html', //restrict as HTML element 'E' restrict: 'E', //New attribute controller to handle updating card details controller: ['$scope', '$http', function ($scope, $http) { var url = '/scrumboard/cards/' + $scope.card.id + '/'; $scope.destList = $scope.list; //assign the current list to the card //once found the url from $scope, PUT the card info $scope.update = function() { return $http.put( url, $scope.card ); }; function removeCardFromList(card, list) { var cards = list.cards; cards.splice( cards.indexOf(card),1); } //Delete cards and splice it out of the list $scope.delete = function() { $http.delete(url).then( function() { removeCardFromList($scope.card, $scope.list); } ); }; //Moves the card from one list to another list $scope.move = function () { if ($scope.destList === undefined) { return; } //takes id of list user select and assigns it to destList.id $scope.card.list = $scope.destList.id; //save the card to the server and run update() which updates the view $scope.update().then(function() { removeCardFromList($scope.card, $scope.list); $scope.destList.cards.push($scope.card); }); } //let angular delay the update so we don't constantly hit the API/database... //It will wait 500 ms, then it will update the model $scope.modelOptions = { debounce: 500 }; }] }; } })();
var express = require('express'); var mysql = require('mysql'); var conf = require('./config.js'); var Q = require('q'); var pool = mysql.createPool(conf.db_conn); exports.connection = { query: function () { var queryArgs = Array.prototype.slice.call(arguments), events = [], eventNameIndex = {}; pool.getConnection(function (err, conn) { if (err) { if (eventNameIndex.error) { eventNameIndex.error(); } } if (conn) { var q = conn.query.apply(conn, queryArgs); q.on('end', function () { conn.release(); }); events.forEach(function (args) { q.on.apply(q, args); }); } }); return { on: function (eventName, callback) { events.push(Array.prototype.slice.call(arguments)); eventNameIndex[eventName] = callback; return this; } }; } };
'use strict'; module.exports = function(app, passport, express, data) { let aboutRouter = new express.Router(), aboutController = require('../controllers/about-controller')(data); aboutRouter .get('/api/about', aboutController.getDetails); app.use(aboutRouter); };
var nextButton = {name: "<em>N</em>ext", classString: "btn-next", onclick: guiders.next}, closeButton = {name: "<em>C</em>lose", classString: "btn-close", onclick: onCloseCallBack}, prevButton = {name: "<em>P</em>revious", classString: "btn-prv", onclick: guiders.prev}; // STEP #1 : Présentation guiders.createGuider({ buttons: [nextButton, closeButton], description: "To make sure you know how to benefit from all functionalities, we are now going to explore the champions module together. In order to compare the important statistics such as life points or attacks damage, the Champions benchmark allows you to confront any champion you choose against any other one.<i>Note : You can interrupt the tour by clicking 'Close' at all times.</i><i>Note 2 : press 'N' to show the next step, and 'P' to go back. Press 'C' to discontinue the tour.</i>", id: "first", next: "second", overlay: true, title: "Guide tour <span class='shortcut'>(Shortcut: G)</span>" }); /* .show() means that this guider will get shown immediately after creation. */ // STEP #2 : Aperçu champion guiders.createGuider({ //attachTo: "div.champions-handler-container ul#isotope-list li.champion", buttons: [prevButton, nextButton, closeButton], description: "Click on any champion to view their statistics at level 1, their purchase price in influence points and riot points.", id: "second", next: "third", highlight: "div.champion-benchmark-container ul#isotope-list li.champion", overlay: true, title: "Champion quick overview" }); // STEP #3 : liste de comparaison guiders.createGuider({ buttons: [prevButton, nextButton, closeButton], description: "You are offered two possibilities to add a champion in the list of comparison:<ul><li>Drag and drop a champion into comparison list</li><li>Double click on a champion</li></ul><i>Note: The first champion on the list (the higher up one, on the left) is considered as the reference champion.</i>", id: "third", next: "fourth", highlight: "div.champion-benchmark-container ul.action-buttons li.comparison-list", overlay: true, title: "Comparison List <span class='shortcut'>(Shortcut: L)</spanv>" }); // STEP #4 : Affiner le filtrage guiders.createGuider({ buttons: [prevButton, nextButton, closeButton], description: "The quickest way to find a champion is to type in the beginning or full name of it. You can also filter champions according to their default tags.<br /><i>Note: in the bottom on the right of the menu 'Filter', a button appears when you apply a filter. It enables to add all filtered champions together to the comparison list.</i>", id: "fourth", next: "finally", highlight: "div.champion-benchmark-container ul.action-buttons li#filters-block, div.champion-benchmark-container ul.action-buttons li.search-action", overlay: true, title: "Filter by tags and search <span class='shortcut'>(Shortcut: F and S)</span>" }); // STEP #5 : Aller à la page de comparaison guiders.createGuider({ buttons: [prevButton, {name: "End of guide tour, thank you !", classString: "btn-close", onclick: onCloseCallBack}], description: "Two champions from the list are needed to make a comparison. Note that you can compare 64 champions simultaneously.", id: "finally", highlight: "div.champion-benchmark-container ul.action-buttons li.btn-compare", overlay: true, title: "To compare champions <span class='shortcut'>(Shortcut: C)</span>" });
"use strict"; //alias const that = require('./JSON'); module.exports = that;
;(function(){ 'use strict'; angular.module("wishListApp") .factory("firebaseFactory", function($http, $location){ var url = "https://x-masswishlist.firebaseio.com/wishes/"; function getWishes(cb){ $http.get(url + ".json") .success(function(data){ cb(data); }) .error(function(err){ console.log(err); }) } function addNewWish(wish, cb){ $http.post(url + ".json", wish) .success(function(data){ cb(data); }) .error(function(err){ console.log(err); }) } function removeWish(id, cb){ $http.delete(url + id + '.json') .success(function(data){ cb(data); }) .error(function(err){ console.log(err); }) } function editWish(wish, cb){ $http.patch(url + $location.$$path + ".json" , wish) .success(function(data){ cb(data); }) .error(function(err){ console.log(err); }) } return {getWishes: getWishes, addNewWish: addNewWish, removeWish: removeWish, editWish: editWish } }) })();
const withPrefix = name => `@registrationForm/${name}` export const CHANGE_NICKNAME = withPrefix('CHANGE_NICKNAME') export const CHANGE_USERNAME = withPrefix('CHANGE_USERNAME') export const CHANGE_PASSWORD = withPrefix('CHANGE_PASSWORD')
"use strict"; /** * Logger, 18.12.2013 Spaceify Oy * * @class Logger */ function Logger(config, class_) { var self = this; var isNodeJs = (typeof window === "undefined" ? true : false); self.RETURN = 1; var LOG = "log"; var DIR = "dir"; var INFO = "info"; self.ERROR = "error"; var ERROR = self.ERROR; var WARN = "warn"; self.FORCE = "force"; var FORCE = self.FORCE; var STDOUT = "stdout"; // Labels -- -- -- -- -- -- -- -- -- -- // var labels = {}; labels[LOG] = "[i] "; labels[DIR] = "[d] "; labels[INFO] = "[i] "; labels[ERROR] = "[e] "; labels[WARN] = "[w] "; labels[FORCE] = ""; labels[STDOUT] = ""; var showLabels = true; // -- -- -- -- -- -- -- -- -- -- // var enabled = (config ? config : {}); // Local: enabled = true (default), not enabled = false enabled[LOG] = (typeof enabled[LOG] !== "undefined" ? enabled[LOG] : true); enabled[DIR] = (typeof enabled[DIR] !== "undefined" ? enabled[DIR] : true); enabled[INFO] = (typeof enabled[INFO] !== "undefined" ? enabled[INFO] : true); enabled[ERROR] = (typeof enabled[ERROR] !== "undefined" ? enabled[ERROR] : true); enabled[WARN] = (typeof enabled[WARN] !== "undefined" ? enabled[WARN] : true); enabled[FORCE] = true; enabled[STDOUT] = true; // -- -- -- -- -- -- -- -- -- -- // self.log = function() { out(LOG, false, arguments); } self.dir = function() { out(DIR, false, arguments); } self.info = function() { out(INFO, false, arguments); } self.error = function() { out(ERROR, false, arguments); } self.warn = function() { out(WARN, false, arguments); } self.force = function() { out(FORCE, false, arguments); } self.stdout = function() { out(STDOUT, true, arguments); } // -- -- -- -- -- -- -- -- -- -- // var out = function(type, useStdout) { if (!enabled[type] && type != FORCE) return; var str = ""; var strs = self.convertArguments(arguments[2]); var strp = null; for (var i = 0; i < strs.length; i++) // Concatenate strings passed in the arguments, separate strings with space { strp = (typeof strs[i] == "string" ? strs[i] : JSON.stringify(strs[i])); str += (str != "" && str != "\n" && str != "\r" && str != "\r\n" ? " " : "") + strp; } if (type == ERROR) { str += new Error().stack; } str = str.replace(/[\x00-\x09\x0b-\x0c\x0e-\x1f]/g, ""); // Replace control characters 0-9, 11-12, 14-31 if (!useStdout && showLabels) { var dateString = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, ''); str = dateString +" "+labels[type]+"["+class_+"] "+ str; } if (isNodeJs) { if (!useStdout) // console.log prints new line console.log(str); else // stdout.write doesn't process.stdout.write(str); } else { if (type == DIR && console.dir) console.dir(str); else if (type == ERROR && console.error) console.error(str); else if (type == INFO && console.info) console.info(str); else if (type == WARN && console.warn) console.warn(str); else console.log(str); } }; self.setOptions = function(options) { if (typeof options.enabled !== "undefined") { for (var type in options.enabled) { enabled[type] = options.enabled[type]; } } if (typeof options.showLabels !== "undefined") showLabels = options.showLabels; }; self.clone = function(logger) { var enabled_ = logger.getEnabled(); enabled[LOG] = enabled_[LOG]; enabled[DIR] = enabled_[DIR]; enabled[INFO] = enabled_[INFO]; enabled[ERROR] = enabled_[ERROR]; enabled[WARN] = enabled_[WARN]; }; self.getEnabled = function() { return enabled; }; /** * Clone the values from this instance of the logger to the global base configuration * => Other instance of the logger get the same values as this instance */ self.cloneInstanceToBaseConfiguration = function() { var iLogger; var globalObj = (typeof(window) === "undefined" ? global : window); if (globalObj.speBaseConfig_ && globalObj.speBaseConfig_.logger) { iLogger = globalObj.speBaseConfig_.logger; for (var i in iLogger) { if (i != class_) { iLogger[i][LOG] = enabled[LOG]; iLogger[i][DIR] = enabled[DIR]; iLogger[i][INFO] = enabled[INFO]; iLogger[i][ERROR] = enabled[ERROR]; iLogger[i][WARN] = enabled[WARN]; } } } }; /** * Convert arguments to array and sanitize empty arguments */ self.convertArguments = function() { var args; if (Object.keys(arguments[0]).length == 0) { args = [""]; } else { args = Array.prototype.slice.call(arguments[0]); } return args; } } Logger.createLogger_ = function(class_) { //console.log("Logger::CreateLogger() creating new logger for "+class_); var lib; var Config; if (typeof window === "undefined") { try { Config = require("./config.js"); } catch (e) { var apipath = "/var/lib/spaceify/code/"; Config = require(apipath + "config.js"); } } else if (typeof window !== "undefined") { lib = (window.WEBPACK_MAIN_LIBRARY ? window.WEBPACK_MAIN_LIBRARY : window); Config = (lib.Config ? lib.Config : null); } var config = Config.getConfig(); //console.log("Logger::getLogger()" + JSON.stringify(config)); var loggerConfig = {}; // Get base config Config.overrideConfigValues(loggerConfig, config.logger.defaultLoggerConfig); // Override with class-specific properties if (config.logger.hasOwnProperty(class_)) { Config.overrideConfigValues(loggerConfig, config.logger[class_]); } // Override with global override Config.overrideConfigValues(loggerConfig, config.logger.globalConfigOverride); // Apply the "all" keyword var all_ = (typeof loggerConfig.all !== "undefined" ? loggerConfig.all : null); if (all_ !== null) // Class specific override { loggerConfig['log'] = all_; loggerConfig['dir'] = all_; loggerConfig['info'] = all_; loggerConfig['error'] = all_; loggerConfig['warn'] = all_; } return new Logger(loggerConfig, class_); }; Logger.getLogger = function(class_) { if (!class_) class_ = "mainlog"; var globalObj = null; if (typeof(window) === "undefined") //nodejs globalObj = global; else globalObj = window; if (!globalObj.hasOwnProperty("speLoggerInstances_")) { globalObj["speLoggerInstances_"] = new Object(); } if (!globalObj.speLoggerInstances_.hasOwnProperty(class_)) { globalObj.speLoggerInstances_[class_] = Logger.createLogger_(class_); } return globalObj.speLoggerInstances_[class_]; }; if (typeof exports !== "undefined") module.exports = Logger;
// All symbols in the Domino Tiles block as per Unicode v5.1.0: [ '\uD83C\uDC30', '\uD83C\uDC31', '\uD83C\uDC32', '\uD83C\uDC33', '\uD83C\uDC34', '\uD83C\uDC35', '\uD83C\uDC36', '\uD83C\uDC37', '\uD83C\uDC38', '\uD83C\uDC39', '\uD83C\uDC3A', '\uD83C\uDC3B', '\uD83C\uDC3C', '\uD83C\uDC3D', '\uD83C\uDC3E', '\uD83C\uDC3F', '\uD83C\uDC40', '\uD83C\uDC41', '\uD83C\uDC42', '\uD83C\uDC43', '\uD83C\uDC44', '\uD83C\uDC45', '\uD83C\uDC46', '\uD83C\uDC47', '\uD83C\uDC48', '\uD83C\uDC49', '\uD83C\uDC4A', '\uD83C\uDC4B', '\uD83C\uDC4C', '\uD83C\uDC4D', '\uD83C\uDC4E', '\uD83C\uDC4F', '\uD83C\uDC50', '\uD83C\uDC51', '\uD83C\uDC52', '\uD83C\uDC53', '\uD83C\uDC54', '\uD83C\uDC55', '\uD83C\uDC56', '\uD83C\uDC57', '\uD83C\uDC58', '\uD83C\uDC59', '\uD83C\uDC5A', '\uD83C\uDC5B', '\uD83C\uDC5C', '\uD83C\uDC5D', '\uD83C\uDC5E', '\uD83C\uDC5F', '\uD83C\uDC60', '\uD83C\uDC61', '\uD83C\uDC62', '\uD83C\uDC63', '\uD83C\uDC64', '\uD83C\uDC65', '\uD83C\uDC66', '\uD83C\uDC67', '\uD83C\uDC68', '\uD83C\uDC69', '\uD83C\uDC6A', '\uD83C\uDC6B', '\uD83C\uDC6C', '\uD83C\uDC6D', '\uD83C\uDC6E', '\uD83C\uDC6F', '\uD83C\uDC70', '\uD83C\uDC71', '\uD83C\uDC72', '\uD83C\uDC73', '\uD83C\uDC74', '\uD83C\uDC75', '\uD83C\uDC76', '\uD83C\uDC77', '\uD83C\uDC78', '\uD83C\uDC79', '\uD83C\uDC7A', '\uD83C\uDC7B', '\uD83C\uDC7C', '\uD83C\uDC7D', '\uD83C\uDC7E', '\uD83C\uDC7F', '\uD83C\uDC80', '\uD83C\uDC81', '\uD83C\uDC82', '\uD83C\uDC83', '\uD83C\uDC84', '\uD83C\uDC85', '\uD83C\uDC86', '\uD83C\uDC87', '\uD83C\uDC88', '\uD83C\uDC89', '\uD83C\uDC8A', '\uD83C\uDC8B', '\uD83C\uDC8C', '\uD83C\uDC8D', '\uD83C\uDC8E', '\uD83C\uDC8F', '\uD83C\uDC90', '\uD83C\uDC91', '\uD83C\uDC92', '\uD83C\uDC93', '\uD83C\uDC94', '\uD83C\uDC95', '\uD83C\uDC96', '\uD83C\uDC97', '\uD83C\uDC98', '\uD83C\uDC99', '\uD83C\uDC9A', '\uD83C\uDC9B', '\uD83C\uDC9C', '\uD83C\uDC9D', '\uD83C\uDC9E', '\uD83C\uDC9F' ];
var client_config = require('./client-config.js'); var io = require("socket.io-client"); var Server = require('./bs_cli_server.js'); // Define your own sensor var Sensor = require('./bs_cli_sensor.js'); var testSensor = new Sensor(); var thisServer = new Server(client_config.host, client_config.port, client_config.appkey).connect(function (socket) { setInterval(function () { data = testSensor.data(); console.log('Trying to posting data...:', data); // Server accepts this data // and then wrap it // { // "data": HERE, // "time": time // } thisServer.postData(data); }, 1000); });
import bcrypt from 'bcrypt-nodejs' import { dd } from 'server/resources/logger' import db from 'server/resources/db' import User from 'server/models/User' import Login from 'server/models/Login' const TABLE = 'users'; class UserRepository { constructor() { this.error = this.error.bind(this) } login({ email, password }) { return User.where({email}).fetch().then((user) => { if (! user) { return Promise.resolve(null) } if (bcrypt.compareSync(password, user.get('password'))) { return Promise.resolve(user); } return Promise.resolve(null) }, (err) => { return Promise.reject(err) }) } login({ email, password }) { return User.where({email}).fetch().then((user) => { if (! user) { return Promise.resolve(null) } if (bcrypt.compareSync(password, user.get('password'))) { return Promise.resolve(user); } return Promise.resolve(null) }, (err) => { return Promise.reject(err) }) } facebookLogin({ id, email, first_name, last_name }) { return this.getByEmail(email).then((user) => { if (user) { return user.save({ first_name, last_name, facebook_id: id }).then((user) => { return Promise.resolve(user) }) } else { return new User({ email, first_name, last_name, facebook_id: id }).save().then((user) => { return Promise.resolve(user) }) } }, (err) => { return Promise.reject(err) }) } signup({ email, firstName, lastName, password }) { return new User({ email, first_name: firstName, last_name: lastName, password: bcrypt.hashSync(password) }).save() } forgotPassword({ email }) { return Promise.resolve(null) } resetPassword({ password, token }) { return Promise.resolve(null) } changePassword({ currentPassword, newPassword }) { return Promise.resolve(null) } getById(id) { return User.where({id}).fetch() } getByEmail(email) { return User.where({email}).fetch() } registerSuccessfulLogin({ user, ip }) { new Login({ user_id: user.get('id'), created_at: new Date(), ip }).save() } error(err) { dd(err) throw new Error('ERROR') } } export default new UserRepository()
var http = require('http'); var EventEmitter = require('events').EventEmitter; var url = require('url'); var path = require('path'); var deepEqual = require('./deep_equal'); var pending = 0; var test = module.exports = function (name, cb) { if (typeof name === 'function') { cb = name; name = undefined; } var t = new Test(name, test.push); pending ++; t.on('testEnd', function () { pending --; process.nextTick(function () { if (pending <= 0) t.push('end', {}); harness.emit('end', t); }); }); cb(t); }; var harness = test.harness = new EventEmitter; var testId = 0; function Test (name, push) { this.id = testId ++; this.push = push; push('testBegin', { name : name, testId : this.id }); this.counts = { plan : undefined, pass : 0, fail : 0 }; this.windows = []; } Test.prototype = new EventEmitter; Test.prototype.assert = function (res) { if (res.ok) this.counts.pass ++ else this.counts.fail ++ if (this.counts.plan !== undefined && this.counts.pass + this.counts.fail > this.counts.plan) { this.push('fail', { type : 'fail', ok : false, found : this.counts.fail + this.counts.pass, wanted : this.counts.plan, name : 'more tests run than planned', testId : this.id }); } res.testId = this.id; this.push('assert', res); if (!res.ok) res.stack = stack(); if (this.counts.plan !== undefined && this.counts.plan === this.counts.pass + this.counts.fail) { this.end(); } }; Test.prototype.ok = function (value, name) { this.assert({ type : 'ok', ok : !!value, name : name, found : Boolean(value), wanted : true }); }; Test.prototype.notOk = function (value, name) { this.assert({ type : 'ok', ok : !!!value, name : name, found : Boolean(value), wanted : false }); }; Test.prototype.fail = function (value, name) { this.assert({ type : 'fail', ok : false, name : name, found : value, wanted : undefined, stack : stack() }); }; Test.prototype.equal = function (found, wanted, name) { this.assert({ type : 'equal', ok : found == wanted, name : name, found : found, wanted : wanted }); }; Test.prototype.notEqual = function (found, wanted, name) { this.assert({ type : 'notEqual', ok : found != wanted, name : name, found : found, wanted : wanted }); }; Test.prototype.deepEqual = function (found, wanted, name) { this.assert({ type : 'deepEqual', ok : deepEqual(found, wanted), name : name, found : found, wanted : wanted }); }; Test.prototype.notDeepEqual = function (found, wanted, name) { this.assert({ type : 'notDeepEqual', ok : !deepEqual(found, wanted), name : name, found : found, wanted : wanted }); }; Test.prototype.strictEqual = function (found, wanted, name) { this.assert({ type : 'strictEqual', ok : found === wanted, name : name, found : found, wanted : wanted }); }; Test.prototype.notStrictEqual = function (found, wanted, name) { this.assert({ type : 'strictEqual', ok : found !== wanted, name : name, found : found, wanted : wanted }); }; function checkThrows (shouldThrow, fn, expected, name) { if (typeof expected === 'string') { name = expected; expected = null; } var ok = !shouldThrow, err = undefined; try { fn() } catch (e) { ok = !ok; err = e; } this.assert({ type : shouldThrow ? 'throws' : 'doesNotThrow', ok : ok, found : err, expected : expected }); } Test.prototype['throws'] = function (fn, expected, name) { checkThrows.call(this, true, fn, expected, name); }; Test.prototype.doesNotThrow = function (fn, expected, name) { checkThrows.call(this, false, fn, expected, name); }; Test.prototype.ifError = function (err, name) { this.assert({ type : 'ifError', ok : !!!err, name : name, found : err, wanted : undefined }); }; Test.prototype.plan = function (n) { if (this.counts.plan === undefined) { this.counts.plan = n; } else { this.counts.plan += n; } this.push('plan', { testId : this.id, n : n }); }; Test.prototype.log = function (msg) { this.push('log', { testId : this.id, message : msg }); }; Test.prototype.end = function () { if (this.counts.plan !== undefined && this.counts.plan > this.counts.fail + this.counts.pass) { this.push('planFail', { type : 'fail', ok : false, found : this.counts.fail + this.counts.pass, wanted : this.counts.plan, name : 'more tests planned than run', testId : this.id }); } if (!this.ended) { this.ended = true; this.push('testEnd', { testId : this.id }); this.emit('testEnd'); } }; if (process.title === "node") { var jsdom = (require)('jsdom'); var fs = require('fs'); var emptyHtml = '<html><head></head><body></body></html>'; var jqueryWin = jsdom.jsdom( '<html><head><script>' + fs.readFileSync(__dirname + '/../vendor/jquery-1.6.min.js', 'utf8') + '</script></head><body></body></html>' ).createWindow(); Test.prototype.createWindow = function (url, opts, cb) { if (typeof url === 'object') { cb = opts; opts = url; url = opts.url; } if (typeof opts === 'function') { cb = opts; opts = {}; } if (!opts) opts = {}; opts.url = url; var win = createWindow(this, opts, cb); this.windows.push(win); return win; }; Test.prototype.submitForm = function (form, params, cb) { if (typeof params === 'function') { cb = params; params = {}; } if (!params) params = {}; if (form[0]) { if (form[0] instanceof jsdom.defaultLevel.HTMLFormElement || form[0].elements) { form = form[0]; } } if (!form.elements) { this.fail('encountered a non-form element'); return; } var pairs = []; var len = 0; for (var i = 0; i < form.elements.length; i++) { if (form.elements[i].name) { len += form.elements[i].name.length + 1 + form.elements[i].value.length; pairs.push( escape(form.elements[i].name) + '=' + escape(form.elements[i].value) ); } } var data = pairs.join('&'); var pwin = form.ownerDocument.parentWindow; var opts = { url : form.action || pwin.location.href.split('?')[0], method : form.method || 'GET', data : data, headers : params.headers || {} }; if (!opts.url.match(/^https?:/)) { opts.url = pwin.location.protocol + '//' + pwin.location.host + path.resolve(path.dirname(pwin.location.path), opts.url) ; } if (opts.method === 'POST') { if (!opts.headers['content-length'] && opts.headers['transfer-encoding'] !== 'chunked') { opts.headers['content-length'] = len + 1; } } var win = createWindow(this, opts, cb); this.windows.push(win); return win; }; function createWindow (self, opts, cb) { if (opts.url && !opts.host) { var u = url.parse(opts.url); opts.path = u.pathname + (u.search || ''); opts.host = u.hostname; opts.port = u.port || (u.proto === 'https' ? 443 : 80); } if (!opts.headers) opts.headers = {}; opts.method = (opts.method || 'GET').toUpperCase(); if (opts.data) { if (opts.method === 'GET') { opts.path = opts.path.split('?')[0] + '?' + opts.data; } else if (opts.method === 'POST') { if (!opts.headers['content-length'] && opts.headers['transfer-encoding'] !== 'chunked') { opts.headers['content-length'] = opts.data.length; } } } if (!opts.url) { opts.url = (opts.proto.replace(/:\/*$/, '') || 'http') + opts.host + (opts.port ? ':' + opts.port : '') + (opts.path || '/') ; } var doc = jsdom.jsdom(emptyHtml, '3', { deferClose : true, url : opts.url }); var win = doc.createWindow(); win.addEventListener('load', function () { var ts = doc.getElementsByTagName('title'); if (ts.length) doc.title = ts[0] && ts[0].textContent || ''; try { cb(win, function (x, y) { return y === undefined ? jqueryWin.$(x, doc) : jqueryWin.$(x, y) }); } catch (err) { self.assert({ type : 'error', error : err }); self.end(); } }); var req = http.request(opts, function (res) { res.on('data', function (buf) { doc.write(buf.toString()); }); res.on('end', function () { doc.close(); }); }); if (opts.method === 'POST' && opts.data) { req.write(opts.data + '\r\n'); } req.end(); return win; } } function stack () { var lines = new Error().stack.split('\n').slice(4,-4); return lines.join('\n'); }
/** * Created by User on 5/2/2016. */ $('body').hide(); var testinglabel = $('#testing101'); var logOutButton = $('#logOutButton'); var employeeName = $('#empName'); var getURL = window.location; var baseUrl = getURL.protocol + "//" + getURL.host + "/" + getURL.pathname.split("/")[1]; var employeeid = $('#employeeid'); $.post(baseUrl + "/get_emp_id", function(id){ if($.trim(id[0]) != "-1") { empId = $.trim(id[0]); empName = $.trim(id[1]); //alert(empId); employeeName.text(empId); employeeid.val(empName); //alert(employeeid.val()); $('body').show(); } else { //alert(id); window.location.href = baseUrl; } }, "json"); logOutButton.click(function () { window.location.href = baseUrl; $.post(baseUrl + "/log_out", function(id){ }); });
var validator = require('validator'), Q = require('q'), _ = require('lodash'); var Value = function(field, input) { this.promise = Q([]); this.set(input, field); }; Value.prototype.then = function () { if (!(this.input && this.field)) { var reject = Q.reject('Both the field and input are required inorder to validate'); return reject.then.apply(reject, arguments); } return this.promise.then.apply(this.promise, arguments); }; Value.prototype.set = function set(input,field) { this.input = input || this.input || {}; this.field = field || this.field; return this; }; Value.prototype.getValue = function(){ return this.input[this.field]; }; Value.prototype.custom = function(customValidator, scope) { var that = this; function wrapper(errors) { var promise; if (_.isFunction(customValidator)) { customValidator = scope ? _.bind(customValidator, scope) : customValidator; promise = Q(customValidator(that.getValue())); } else { promise = customValidator; } return promise.then(function(e) { if (_.isArray(e)) { errors = errors.concat(e); } else if (_.isString(e)) { errors.push(e); } return Q(errors); }); } this.promise = this.promise.then(wrapper); return this; }; for (var name in validator) { (function(functionName) { Value.prototype[functionName] = function() { var args = arguments; this.custom(function(value){ var validatorArgs = [value].concat(args); if(!validator[functionName].apply(validator, validatorArgs)){ return 'Value "'+value + '" failed '+ functionName + ' validator'; } }); return this; }; })(name); // jshint ignore:line } module.exports = function(field, input){ return new Value(field, input); };
var geodesic_cluster_6_0 = { "properties": { "cluster": 0, "popupContent": "This is cluster 0 for ROBBERY", "style": { "opacity": 1, "color": "black", "fillColor": "#0ad81f", "fillOpacity": 0, "weight": 3 } }, "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [ -87.9187138, 43.050992 ], [ -87.9018474, 43.0455371 ], [ -87.893889, 43.05248 ], [ -87.8917625, 43.0545739 ], [ -87.8802084, 43.065957 ], [ -87.8884402, 43.0814671 ], [ -87.9136954, 43.089021 ], [ -87.9171363, 43.0892916 ], [ -87.925668, 43.0875518 ], [ -87.9274298, 43.0858265 ], [ -87.923117, 43.063394 ] ] ] } }; var geodesic_cluster_6_1 = { "properties": { "cluster": 1, "popupContent": "This is cluster 1 for ROBBERY", "style": { "opacity": 1, "color": "black", "fillColor": "#0ad81f", "fillOpacity": 0, "weight": 3 } }, "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [ -87.9318091, 43.1050186 ], [ -87.958313, 43.120332 ], [ -87.974771, 43.112276 ], [ -87.9910453, 43.0902782 ], [ -87.9849764, 43.0710642 ], [ -87.9830192, 43.0686367 ], [ -87.9695803, 43.0711055 ], [ -87.9359614, 43.0825256 ] ] ] } }; var geodesic_cluster_6_2 = { "properties": { "cluster": 2, "popupContent": "This is cluster 2 for ROBBERY", "style": { "opacity": 1, "color": "black", "fillColor": "#0ad81f", "fillOpacity": 0, "weight": 3 } }, "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [ -87.9571962, 43.1477866 ], [ -88.0052145, 43.1841662 ], [ -88.028687, 43.183281 ], [ -88.0462172, 43.1496937 ], [ -88.0438987, 43.1361638 ], [ -88.0316577, 43.1336466 ], [ -88.0051485, 43.134413 ] ] ] } }; var geodesic_cluster_6_3 = { "properties": { "cluster": 3, "popupContent": "This is cluster 3 for ROBBERY", "style": { "opacity": 1, "color": "black", "fillColor": "#0ad81f", "fillOpacity": 0, "weight": 3 } }, "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [ -88.05492950000001, 43.1157707 ], [ -88.0477026, 43.1045441 ], [ -88.0253252, 43.0734124 ], [ -88.0116804, 43.0755908 ], [ -87.9891349, 43.10147 ], [ -87.98406, 43.115442 ], [ -87.983253, 43.117741 ], [ -87.98988, 43.125835 ], [ -87.998636, 43.126501 ], [ -88.022013, 43.123767 ], [ -88.0423976, 43.1199087 ] ] ] } }; var geodesic_cluster_6_4 = { "properties": { "cluster": 4, "popupContent": "This is cluster 4 for ROBBERY", "style": { "opacity": 1, "color": "black", "fillColor": "#0ad81f", "fillOpacity": 0, "weight": 3 } }, "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [ -87.95921, 43.022838 ], [ -88.029719, 42.981297 ], [ -88.0181679, 42.973985 ], [ -87.9506496, 42.941668 ], [ -87.899261, 42.959491 ], [ -87.8827022, 42.9867163 ], [ -87.88910159999999, 42.991826 ], [ -87.9187283, 43.0150067 ], [ -87.931728, 43.023404 ], [ -87.9477602, 43.028274 ] ] ] } }; var geodesic_cluster_6_5 = { "properties": { "cluster": 5, "popupContent": "This is cluster 5 for ROBBERY", "style": { "opacity": 1, "color": "black", "fillColor": "#0ad81f", "fillOpacity": 0, "weight": 3 } }, "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [ -87.978356, 43.0659909 ], [ -88.0276826, 43.0361921 ], [ -87.957105, 43.033431 ], [ -87.922715, 43.038343 ], [ -87.9272894, 43.055139 ], [ -87.9315511, 43.0674688 ], [ -87.937336, 43.0757639 ], [ -87.9424767, 43.0753336 ] ] ] } };
'use strict'; //Games service used for communicating with the articles REST endpoints angular.module('games').factory('Games', ['$resource', function ($resource) { return $resource('api/games/:gameId', { gameId: '@_id' }); } ]);
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Button from '@material-ui/core/Button'; const useStyles = makeStyles(theme => ({ button: { margin: theme.spacing(1), }, input: { display: 'none', }, })); function ContainedButtons() { const classes = useStyles(); return ( <div> <Button variant="contained" className={classes.button}> Default </Button> <Button variant="contained" color="primary" className={classes.button}> Primary </Button> <Button variant="contained" color="secondary" className={classes.button}> Secondary </Button> <Button variant="contained" color="secondary" disabled className={classes.button}> Disabled </Button> <Button variant="contained" href="#contained-buttons" className={classes.button}> Link </Button> <input accept="image/*" className={classes.input} id="contained-button-file" multiple type="file" /> <label htmlFor="contained-button-file"> <Button variant="contained" component="span" className={classes.button}> Upload </Button> </label> </div> ); } export default ContainedButtons;
version https://git-lfs.github.com/spec/v1 oid sha256:4c7c6f11844b73ed3ecd8fb166b236ada2fa7190f291636f873e06123fa3feeb size 3211
// Copyright (c) 2011-2012 Turbulenz Limited /*global TurbulenzEngine*/ /*global Uint8Array*/ /*global window*/ "use strict"; ; var TARLoader = (function () { function TARLoader() { } TARLoader.prototype.processBytes = function (bytes) { var offset = 0; var totalSize = bytes.length; function skip(limit) { offset += limit; } function getString(limit) { var index = offset; var nextOffset = (index + limit); var c = bytes[index]; var ret; if (c && 0 < limit) { index += 1; var s = new Array(limit); var n = 0; do { s[n] = c; n += 1; c = bytes[index]; index += 1; } while(c && n < limit); while (s[n - 1] === 32) { n -= 1; } s.length = n; ret = String.fromCharCode.apply(null, s); } else { ret = ''; } offset = nextOffset; return ret; } function getNumber(text) { /*jshint regexp: false*/ text = text.replace(/[^\d]/g, ''); /*jshint regexp: true*/ return parseInt('0' + text, 8); } var header = { fileName: null, //mode : null, //uid : null, //gid : null, length: 0, //lastModified : null, //checkSum : null, fileType: null, //linkName : null, ustarSignature: null, //ustarVersion : null, //ownerUserName : null, //ownerGroupName : null, //deviceMajor : null, //deviceMinor : null, fileNamePrefix: null }; function parseHeader(header) { header.fileName = getString(100); skip(8); //header.mode = getString(8); skip(8); //header.uid = getString(8); skip(8); //header.gid = getString(8); header.length = getNumber(getString(12)); skip(12); //header.lastModified = getString(12); skip(8); //header.checkSum = getString(8); header.fileType = getString(1); skip(100); //header.linkName = getString(100); header.ustarSignature = getString(6); skip(2); //header.ustarVersion = getString(2); skip(32); //header.ownerUserName = getString(32); skip(32); //header.ownerGroupName = getString(32); skip(8); //header.deviceMajor = getString(8); skip(8); //header.deviceMinor = getString(8); header.fileNamePrefix = getString(155); offset += 12; } var gd = this.gd; var mipmaps = this.mipmaps; var ontextureload = this.ontextureload; var result = true; this.texturesLoading = 0; var that = this; function onload(texture) { that.texturesLoading -= 1; if (texture) { ontextureload(texture); } else { offset = totalSize; result = false; } } while ((offset + 512) <= totalSize) { parseHeader(header); if (0 < header.length) { var fileName; if (header.fileName === "././@LongLink") { // name in next chunk fileName = getString(256); offset += 256; parseHeader(header); } else { if (header.fileNamePrefix && header.ustarSignature === "ustar") { fileName = (header.fileNamePrefix + header.fileName); } else { fileName = header.fileName; } } if ('' === header.fileType || '0' === header.fileType) { //console.log('Loading "' + fileName + '" (' + header.length + ')'); this.texturesLoading += 1; gd.createTexture({ src: fileName, data: bytes.subarray(offset, (offset + header.length)), mipmaps: mipmaps, onload: onload }); } offset += (Math.floor((header.length + 511) / 512) * 512); } } bytes = null; return result; }; TARLoader.prototype.isValidHeader = function ( /* header */ ) { return true; }; TARLoader.create = function (params) { var loader = new TARLoader(); loader.gd = params.gd; loader.mipmaps = params.mipmaps; loader.ontextureload = params.ontextureload; loader.onload = params.onload; loader.onerror = params.onerror; loader.texturesLoading = 0; var src = params.src; if (src) { loader.src = src; var xhr; if (window.XMLHttpRequest) { xhr = new window.XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new window.ActiveXObject("Microsoft.XMLHTTP"); } else { if (params.onerror) { params.onerror(0); } return null; } xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (!TurbulenzEngine || !TurbulenzEngine.isUnloading()) { var xhrStatus = xhr.status; var xhrStatusText = xhr.status !== 0 && xhr.statusText || 'No connection'; // Fix for loading from file if (xhrStatus === 0 && (window.location.protocol === "file:" || window.location.protocol === "chrome-extension:")) { xhrStatus = 200; } // Sometimes the browser sets status to 200 OK when the connection is closed // before the message is sent (weird!). // In order to address this we fail any completely empty responses. // Hopefully, nobody will get a valid response with no headers and no body! if (xhr.getAllResponseHeaders() === "") { var noBody; if (xhr.responseType === "arraybuffer") { noBody = !xhr.response; } else if (xhr.mozResponseArrayBuffer) { noBody = !xhr.mozResponseArrayBuffer; } else { noBody = !xhr.responseText; } if (noBody) { if (loader.onerror) { loader.onerror(0); } // break circular reference xhr.onreadystatechange = null; xhr = null; return; } } if (xhrStatus === 200 || xhrStatus === 0) { var buffer; if (xhr.responseType === "arraybuffer") { buffer = xhr.response; } else if (xhr.mozResponseArrayBuffer) { buffer = xhr.mozResponseArrayBuffer; } else { /*jshint bitwise: false*/ var text = xhr.responseText; var numChars = text.length; buffer = []; buffer.length = numChars; for (var i = 0; i < numChars; i += 1) { buffer[i] = (text.charCodeAt(i) & 0xff); } /*jshint bitwise: true*/ } if (loader.processBytes(new Uint8Array(buffer))) { if (loader.onload) { var callOnload = function callOnloadFn() { if (0 < loader.texturesLoading) { if (!TurbulenzEngine || !TurbulenzEngine.isUnloading()) { window.setTimeout(callOnload, 100); } } else { loader.onload(true, xhrStatus); } }; callOnload(); } } else { if (loader.onerror) { loader.onerror(xhrStatus); } } } else { if (loader.onerror) { loader.onerror(xhrStatus); } } } // break circular reference xhr.onreadystatechange = null; xhr = null; } }; xhr.open("GET", params.src, true); if (typeof xhr.responseType === "string" || (xhr.hasOwnProperty && xhr.hasOwnProperty("responseType"))) { xhr.responseType = "arraybuffer"; } else if (xhr.overrideMimeType) { xhr.overrideMimeType("text/plain; charset=x-user-defined"); } else { xhr.setRequestHeader("Content-Type", "text/plain; charset=x-user-defined"); } xhr.send(null); } return loader; }; TARLoader.version = 1; return TARLoader; })();
(function(module) { var projectController = {}; projectController.reveal = function() { $('#about').fadeOut(); $('#projects').fadeIn(); }; module.projectController = projectController; })(window);
'use strict'; var assert = require('assert'); var fs = require('fs'); var mixin = require('rework-plugin-mixin'); var opacity = require('../opacity'); var rework = require('rework'); describe('opacity()', function () { var expected = fs.readFileSync('test/fixtures/expected.css', 'utf-8').toString().trim(); var original = fs.readFileSync('test/fixtures/original.css', 'utf-8').toString().trim(); var actual = rework(original).use(mixin({ opacity: opacity })).toString(); it('inserts the MS opacity filter and preserves the value tail', function () { assert.equal(actual, expected); }); });
var $M = require("@effectful/debugger"), $x = $M.context, $ret = $M.ret, $unhandled = $M.unhandled, $m = $M.module("file.js", null, typeof module === "undefined" ? null : module, null, "$", { __webpack_require__: typeof __webpack_require__ !== "undefined" && __webpack_require__ }, null), $s$1 = [{ a: [1, "1:9-1:10"] }, null, 0], $s$2 = [{ i: [1, "2:6-2:7"] }, $s$1, 1], $m$0 = $M.fun("m$0", "file.js", null, null, [], 0, 2, "1:0-11:0", 160, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $l[1] = $m$1($); $.goto = 2; continue; case 1: $.goto = 2; return $unhandled($.error); case 2: return $ret($.result); default: throw new Error("Invalid state"); } }, null, null, 0, [[0, "1:0-10:1", $s$1], [16, "11:0-11:0", $s$1], [16, "11:0-11:0", $s$1]]), $m$1 = $M.fun("m$1", "a", null, $m$0, [], 1, 2, "1:0-10:1", 128, function ($, $l, $p) { var $1; for (;;) switch ($.state = $.goto) { case 0: $l[1] = 0; $.goto = 1; ($x.call = eff)($l[1]); $.state = 1; case 1: $1 = $l[1]; $l[1] = $1 + 1; if ($1) { $.goto = 2; ($x.call = eff1)($l[1]); $.state = 2; } else { $.goto = 2; ($x.call = eff2)($l[1]); $.state = 2; } case 2: $.goto = 4; ($x.call = eff)($l[1]); continue; case 3: $.goto = 4; return $unhandled($.error); case 4: return $ret($.result); default: throw new Error("Invalid state"); } }, null, null, 1, [[2, "3:2-3:8", $s$2], [2, "5:4-5:11", $s$2], [2, "9:2-9:8", $s$2], [16, "10:1-10:1", $s$2], [16, "10:1-10:1", $s$2]]); $M.moduleExports();
import { Injectable, Inject } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { FreshModel } from '../models/fresh.model'; import { map, startWith } from 'rxjs/operators'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; @Injectable() export class ResumeService { resume$; src; constructor (@Inject(HttpClient) http) { // http bindings for a GET request this.http = http; // pre-load the data this.resume$ = this.loadResume(); } loadResume(path) { if (path || this.src) { return this.resume$ = this.http.get(path || this.src) .pipe( map(res => new FreshModel(res)), startWith(new FreshModel()) ); } } }
const ipcRenderer = require('electron').ipcRenderer; angular.module('EmailApp', []) .controller('EmailCtrl', ['$scope', function($scope) { var emailCtrl = this; emailCtrl.selectedEmail = undefined; emailCtrl.isSelected = function(email) { if (email.email === emailCtrl.selectedEmail) return true; return false; } emailCtrl.selectEmail = function(email) { emailCtrl.selectedEmail = email.email; } emailCtrl.refresh = function() { console.log('Refreshing...'); ipcRenderer.sendSync('CLI', './db_service/db_service.native -force-retrieval-job'); var dbInfo = JSON.parse(ipcRenderer.sendSync('CLI', './db_service/db_service.native -show-emails')).emails.map(function (elem) { elem.subject = decodeURIComponent(elem.subject.replace(/\+/g, '%20')); elem.body = decodeURIComponent(elem.body.replace(/\+/g, '%20')); if (elem.subject.includes('1801')) elem.fraud = true; return elem; }); console.log(dbInfo); emailCtrl.emails = dbInfo; emailSearch({value: ''}); } emailCtrl.currentComposeState = '+'; emailCtrl.currentComposeEmail = {}; emailCtrl.compose = function() { if (emailCtrl.currentComposeState === '+') { emailCtrl.currentComposeState = 'X'; } else { emailCtrl.currentComposeState = '+'; emailCtrl.currentComposeEmail = {}; } } emailCtrl.sendMail = function() { ipcRenderer.sendSync('CLI', `java -jar mailrunner.jar ${encodeURIComponent(emailCtrl.currentComposeEmail.recipients)} ${encodeURIComponent(emailCtrl.currentComposeEmail.subject)} ${encodeURIComponent(emailCtrl.currentComposeEmail.body)}`); emailCtrl.compose(); emailCtrl.emailSent = true; setTimeout(function() { emailCtrl.emailSent = false; $scope.$apply(); }, 1500); } emailCtrl.emailSent = false; emailSearch = function(search) { if (search.value === '') { $scope.displayedEmails = emailCtrl.emails; } else { var query = search.value.toLowerCase(); $scope.displayedEmails = emailCtrl.emails.filter(function(email){ if (email.from.toLowerCase().includes(query) || email.subject.toLowerCase().includes(query) || email.body.toLowerCase().includes(query)) { console.log('true'); return true; } console.log('false'); return false; }) console.log($scope.displayedEmails); } emailCtrl.lolbugfix = "bugfix1"; $scope.$apply(); setTimeout(function() { emailCtrl.lolbugfix = "bugfix2"; $scope.$apply(); }, 10); } emailCtrl.emails = [ { from: 'Sender Name 1', subject: 'Subjecto yo', body: 'Example body text', attachments: undefined }, { from: 'Sender Name 1 pls', subject: 'Subjecto yo awif iwe feo iwe fewoi fwjf wi', body: 'Example body text', attachments: undefined }, { from: 'Sender Name 1', subject: 'pls', body: 'Example body text', attachments: undefined } ]; $scope.displayedEmails = emailCtrl.emails; }]);
import React, { Component } from 'react'; import CSSTransitionGroup from 'react-addons-css-transition-group'; // ES6 import SaveButton from './saveButton'; import FacebookProvider, { Share} from 'react-facebook'; export default class Edit extends Component { constructor(props) { super(props); this.state = { message: "", isyoId: "" }; this.showBody = this.showBody.bind(this); console.log("edit.js constructor",this.props); var that = this; // TODO model内 で処理するようリファクタリングする $.ajax({ url: '/api/isyos?filter={"where":{"hash":"' + this.props.params.isyoHash + '"}}', type: 'GET', success: function(res) { console.log("editjs get api success",res); // this.setState({data: data}) var body = res[0].body; var hash = res[0].hash; that.setState({message: body,isyoId:hash}); }, }).fail((responseData) => { if (responseData.responseCode) { console.error(responseData.responseCode); } }); } componentDidMount() { console.log("componentDidMount"); } componentWillUnmount() { console.log("componentWillUnmount"); } // viewChange(view){ // console.log("call viewChange in input.js",view); // // console.log(this.state); // // this.setState(state); // // // var state = {route:view}; // // this.setState(state); // } showBody(data){ console.log("input.js",data); data = "<p>" + data.replace("\n","</p><p>") + "</p>"; this.setState({show:true,message:data}); } // // hideBody(){ // this.setState({show:false}); // } handleChange(e){ this.setState({message: e.target.value}); } // onChangeText(e){ // console.log("onChangeText"); // } render(){ return ( <div className="bgimage"> <div className="container"> <div className="form-group"> <textarea id="body" name="body" className="form-control" rows="20" value={this.state.message} onChange={this.handleChange.bind(this)} /> <input id="isyoId" name="isyoId" type="hidden" value={this.state.isyoId} /> <p>※書いた内容は書いた本人しか見れません。</p> <p>※今後のversion upで、課金した人にだけ公開する機能を作成予定です。</p> <SaveButton showBody={this.showBody}/> </div> </div> </div> ); } }
import { Provider } from 'react-redux'; import DevTools from '../../containers/DevToolsWindow'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; /* tslint:disable:no-unused-expression */ React; /* tslint:enable:no-unused-expression */ export default function createDevToolsWindow(store) { 'use strict'; const win = window.open(null, 'redux-devtools', // give it a name so it reuses the same window `width=400,height=${window.outerHeight},menubar=no,location=no,resizable=yes,scrollbars=no,status=no`); // reload in case it's reusing the same window with the old content win.location.reload(); // wait a little bit for it to reload, then render setTimeout(() => { // Wait for the reload to prevent: // "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element." win.document.write('<div id="react-devtools-root"></div>'); win.document.body.style.margin = '0'; ReactDOM.render(React.createElement(Provider, {"store": store}, React.createElement(DevTools, null)), win.document.getElementById('react-devtools-root')); }, 10); }
var trips = [ { "brewery":"Breckenridge Brewery", "distance":16.8*2, "riders":["Steve", "Allie", "Chris"], "image": "breckenridge-9-3.jpg", "date":new Date(2016, 9, 3), "lat":39.593721, "lon":-105.023341, "notes": "The first trip of the tour, before the tour was officially the tour!", "gpx": "breckenridge-9-3-2016.gpx" }, { "brewery":"Denver Beer Co", "distance":5.5*2, "riders":["Steve", "Allie", "Chris", "Rachel"], "image": "denver_beer_co_2_18.jpg", "date":new Date(2017, 2, 18), "lat":39.758234, "lon":-105.007370, "notes": "An unplanned stop, but we definitely rolled up on bikes and counting it.", "gpx": "denver_beer_co_cruise_2_18_2017.gpx" }, { "brewery":"TRVE Brewing Co", "distance":6.3*2, "riders":["Steve", "Allie", "Jenny", "Bailey"], "image": "trve_3_4.jpg", "date":new Date(2017, 3, 4), "lat":39.719919, "lon":-104.987686, "notes":"Yeah, the route is correct. 4th brewery is the charm, apparently vertical WI IDs are tricky to get served with.", "gpx": "trve_brew_co_3_4_2017.gpx" }, { "brewery":"Green Mountain Beer Company", "distance":30.3, "riders":["Steve", "Rachel", "Chris"], "image": "green_mtn_4_16_2017.jpg", "date":new Date(2017, 4, 16), "lat":39.669945, "lon":-105.113684, "notes":"First 'official' stop of the tour, in the sense we actually planned it and said that's what it's for. And Platson got new wheels!", "gpx": "green_mtn_4_16_2017.gpx" }, { "brewery":"Station 26 Brewing Co", "distance":16.3, "riders":["Steve", "Rachel", "Chris"], "image": "station26_4_22_2017.jpg", "date":new Date(2017, 4, 22), "lat":39.769584, "lon":-104.90598, "notes":"To Station 26 for the Wild game. And REI, cause sometimes you have some beer and wanna go to the garage sale (the pic is of some swag)", "gpx": "station26_4_22_2017.gpx" }, { "brewery":"Odyssey Beerwerks", "distance":21.4, "riders":["Steve", "Rachel", "Chris", "Allie", "Sari"], "image": "odyssey_4_23_2017.jpg", "date":new Date(2017, 4, 23), "lat":39.800852, "lon":-105.058954, "notes":"The largest brew crew to date. First time going to the Arvada 'hood, too.", "gpx": "odyssey_4_23_2017.gpx" }, { "brewery":"Mountain Toad Brewery", "distance":35.4, "riders":["Steve", "Chris", "Allie"], "image": "mountain_toad_5_6_17.jpg", "date":new Date(2017, 5, 6), "lat":39.758134, "lon":-105.224165, "notes":"Getting to Golden was at least twice as hard as getting back! Pretty nummy beer.", "gpx": "mountain_toad_5_6_17.gpx" }, { "brewery":"Golden City Brewery", "distance":34, "riders":["Steve", "John", "Sari"], "image": "gcb_5_13.jpg", "date":new Date(2017, 5, 13), "lat":39.754677, "lon":-105.223686, "notes":"Hot day and a beautiful ride. Got 3 flats on the way back so I didn't make the full round trip, had to call for backup.", "gpx": "gcb_5_13.gpx" }, { "brewery":"Dry Dock Brewing Co - South Dock", "distance":32.2, "riders":["Steve", "Chris"], "image": "dry_dock_south_7_8_17.jpg", "date":new Date(2017, 7, 8), "lat":39.652665, "lon":-104.81204, "notes":"First ride from the new place, also transported some camping equipment while we were at it. Apricot beers were favorites.", "gpx": "dry_dock_south_7_8_17.gpx" }, { "brewery":"Boulder Beer Co", "distance":82.2, "riders":["Steve", "Chris"], "image": "boulder_beer_co_7_22_17.jpg", "date":new Date(2017, 7, 22), "lat":40.0265719, "lon":-105.24805650000002, "notes":"Longest tour trip so far! And ran out of paved trail for a couple sections.", "gpx": "boulder_beer_co_7_22_17.gpx" }, { "brewery":"Breckenridge Brewery (trip #2)", "distance":50.2, "riders":["Steve", "Allie"], "image": "breckenridge_8_12_17.jpg", "date":new Date(2017, 8, 12), "lat":39.593113, "lon":-105.023949, "notes": "We actually planned on a bigger circle up to Dry Dock North, but weather got really nasty when we got to Littleton, so we ducked in here instead!", "gpx": "breckenridge_8_12_17.gpx" }, { "brewery":"Saint Patrick's Brewery", "distance":55.2, "riders":["Steve", "Chris"], "image": "", "date":new Date(2018, 1, 13), "lat":39.612762, "lon":-105.02449999999999, "notes": "First ride of a new year. Went up through Denver each way, started a little chilly but turned out to be a nice day. Actually tried to go to Locavore but couldn't find it and happened to end up in Saint Patrick's parking lot while looking for it. Turned out to be a win though, great beer, and more affordable than most breweries in the area.", "gpx": "saint_patricks_1_13_18.gpx" }, { "brewery":"Joyride Brewing Company", "distance":38, "riders":["Steve", "Chris", "Dave"], "image": "", "date":new Date(2018, 3, 30), "lat":39.753134, "lon":-105.053452, "notes": "Went out after work, it's a nice area over by Sloan's Lake. Computer died on the way back, so the route isn't complete, but you get the idea.", "gpx": "joyride_brew_3_30_18.gpx" }, { "brewery":"Lost Highway Brewing Company", "distance":33.96, "riders":["Steve", "Jimmy", "Sean", "Ken"], "image": "lost_highway_5_28.jpeg", "date":new Date(2018, 5, 28), "lat":39.601885, "lon":-104.840546, "notes": "After the usual great Saturday morning Adventure Cycling route down to Meridian for laps, we went to recover at Lost Highway. We got there more than an hour before they were supposed to open, but we must have looked pitiful enough because she was kind enough to let us in early. Great beer and a great place.", "gpx": "chenango_lost_highway.gpx" }, { "brewery":"Great Divide", "distance":123.39, "riders":["Steve", "Bill", "Amanda", "Ben", "Chris", "Allie"], "image": "great_divide_6_9.jpeg", "date":new Date(2018, 6, 9), "lat":39.770259, "lon":-104.97919, "notes": "The (first) big one! Five of us set out to do a whole century, and two made it the distance, but we still all managed to get to Great Divide when all said and done. The route was fun, incredibly hot though. It was well over 90 degrees for much of the way. Getting back on the bike after a couple beers at the end (just to get back home) was the hardest part. This was a great day.", "gpx": "great_divide_century.gpx" }, ] function setTotalMilesMsg(miles) { $("#total_mileage").text(Math.round(miles) + " total tour miles in " + trips.length + " trips to date."); } // draw a marker for all trips $(document).ready(function() { var mapboxUrl = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1Ijoic2phcnZpcyIsImEiOiJjaXpieXdtM2ExYmFsMzJxaWN3bGhpMmU2In0.gKtkxDAwHZIbdLmpXPZlAA'; // The starting coords and zoom just look good. Selecting a marker will zoom to fit the route. var map = L.map('map').setView([39.758234, -105.007370], 9.5); L.tileLayer(mapboxUrl, { maxZoom: 30, // credit our tools attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' + '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="http://mapbox.com">Mapbox</a>', id: 'mapbox.streets' }).addTo(map); var img_prefix = "../images/grin_n_spin/" var res_prefix = "../resources/grin-n-spin/" var mileage = 0 trips.forEach(function(trip, i) { var micon = L.AwesomeMarkers.icon({ icon: '', markerColor: 'darkblue', prefix: 'fa', html: (i+1) }) L.marker([trip.lat, trip.lon], {icon: micon}).addTo(map) .bindPopup('<b><big>' + trip.brewery + '</b></big><br>' + '<div style="display:flex;">' + '<div style="float:left; margin:0.5em;"><a href=' + img_prefix + trip.image + '><img width=160em src=' + img_prefix + trip.image + '></a></div>' + '<div style="flex-grow:1; word-wrap:break-word;">' + trip.notes + '<ul>' + '<li>' + trip.date.getMonth() + '-' + trip.date.getDate() + '-' + trip.date.getFullYear() + '</li>' + '<li>' + trip.riders.join(', ') + '</li>' + '<li>' + trip.distance + ' miles</li>' + '</ul>' + '</div>' + '</div>', {'maxWidth':'400'} ) .on("click", function() { if(typeof gpxLayer !== 'undefined') {map.removeLayer(gpxLayer);} if(this.getPopup().isOpen() && trip.gpx !== 'undefined' && trip.gpx !== null) { gpxLayer = new L.GPX(res_prefix + trip.gpx, {async: true, marker_options: { startIconUrl: null, endIconUrl: null, shadowUrl: null }}).on('loaded', function(e) { map.fitBounds(e.target.getBounds())}); gpxLayer.addTo(map); } }); // Add to table as well var table = document.getElementById("trip_table"); var row = table.insertRow(i); row.insertCell(0).innerHTML = i+1; row.insertCell(1).innerHTML = trip.brewery; row.insertCell(2).innerHTML = trip.date.getMonth() + '-' + trip.date.getDate() + '-' + trip.date.getFullYear(); row.insertCell(3).innerHTML = trip.riders.join(', '); row.insertCell(4).innerHTML = trip.distance + ' miles'; mileage += trip.distance; setTotalMilesMsg(mileage); }) });
/** * Created by marto on 31-Oct-16. */ 'use strict' const crypto = require('crypto') module.exports = { generateSalt: () => crypto.randomBytes(128).toString('base64'), generateHashedPassword: (salt, pwd) => crypto.createHmac('sha256', salt).update(pwd).digest('hex') }
const React = require('react') const FlatButton = require('material-ui/FlatButton').default const RaisedButton = require('material-ui/RaisedButton').default module.exports = class ModalOKCancel extends React.Component { render () { const cancelStyle = { marginRight: 10, color: 'black' } const { cancelText, onCancel, okText, onOK } = this.props return ( <div className='float-right'> <FlatButton className='control cancel' style={cancelStyle} label={cancelText} onClick={onCancel} /> <RaisedButton className='control ok' primary label={okText} onClick={onOK} autoFocus /> </div> ) } }
'use strict'; // USUARIOS CRUD var Museo = require('../../models/model'); /* Rutas que terminan en /tipoAnalisis // router.route('/tipoAnalisis') */ // POST /tipoAnalisis exports.create = function (req, res) { // bodyParser debe hacer la magia var tipo = req.body.tipo; var subTipo = req.body.subTipo; var valorPredeterminado = req.body.valorPredeterminado; var tipoAnalisis = Museo.TipoAnalisis.build({ tipo: tipo, subTipo: subTipo, valorPredeterminado: valorPredeterminado }); tipoAnalisis.add(function (success) { res.json({ message: 'TipoAnalisis creado!' }); }, function (err) { res.send(err); }); }; /* (trae todos los tipoAnalisis) // GET /tipoAnalisis */ exports.list = function (req, res) { var tipoAnalisis = Museo.TipoAnalisis.build(); tipoAnalisis.retrieveAll(function (tipoAnalisis) { if (tipoAnalisis) { res.json(tipoAnalisis); } else { res.send(401, 'No se encontraron TipoAnalisis'); } }, function (error) { res.send('TipoAnalisis no encontrado'); }); }; /* Rutas que terminan en /tipoAnalisis/:tipoAnalisisId // router.route('/tipoAnalisis/:tipoAnalisisId') // PUT /tipoAnalisis/:tipoAnalisisId // Actualiza tipoAnalisis */ exports.update = function (req, res) { var tipoAnalisis = Museo.TipoAnalisis.build(); tipoAnalisis.tipo = req.body.tipo; tipoAnalisis.subTipo = req.body.subTipo; tipoAnalisis.valorPredeterminado = req.body.valorPredeterminado; tipoAnalisis.updateById(req.params.tipoAnalisisId, function (success) { if (success) { res.json({ message: 'TipoAnalisis actualizado!' }); } else { res.send(401, 'TipoAnalisis no encontrado'); } }, function (error) { res.send('TipoAnalisis no encontrado'); }); }; // GET /tipoAnalisis/:tipoAnalisisId // Toma un tipoAnalisis por id exports.read = function (req, res) { var tipoAnalisis = Museo.TipoAnalisis.build(); tipoAnalisis.retrieveById(req.params.tipoAnalisisId, function (tipoAnalisis) { if (tipoAnalisis) { res.json(tipoAnalisis); } else { res.send(401, 'TipoAnalisis no encontrado'); } }, function (error) { res.send('TipoAnalisis no encontrado'); }); }; // DELETE /tipoAnalisis/tipoAnalisisId // Borra el tipoAnalisisId exports.delete = function (req, res) { var tipoAnalisis = Museo.TipoAnalisis.build(); tipoAnalisis.removeById(req.params.tipoAnalisisId, function (tipoAnalisis) { if (tipoAnalisis) { res.json({ message: 'TipoAnalisis borrado!' }); } else { res.send(401, 'TipoAnalisis no encontrado'); } }, function (error) { res.send('TipoAnalisis no encontrado'); }); };
import Dexie from 'dexie' export class PizzaList { constructor () { this.db = new Dexie('pizzeria') this.db.version(1).stores({ pizzas: '++id, name' }) this.db.open() } addPizza (pizza) { return this.db.pizzas.add(pizza).then(() => console.log(pizza.name, 'à bien été ajouté dans la BDD.'), (err) => { console.log(err) throw err.message }) } findPizzaByTopping (topping) { return this.pizzas.filter(pizza => pizza.toppings.indexOf(topping) !== -1) } }
require({ packages: [ 'app', 'dojo', 'dojox', { name: 'jquery', location: './jquery', main: 'jquery' }, { name: 'jquery-mobile-bower', location: './jquery-mobile-bower', main: 'js/jquery.mobile-1.4.5' }, { name: 'proj4', location: './proj4/dist', main: 'proj4-src' } ] });
function showPopup(url, cb) { url = appendUrlParameter(url, 'simple'); $.ajax(url).done(function(rawContent) { var content = $(rawContent); var stylesheets = content.filter('link'); var scripts = content.filter('script[src]'); var showFunc = function() { var elementsToAdd = content.find('.content-wrapper'); var popupDiv = $('<div class="popup"></div>'); var coverDiv = $('<div class="cover"></div>'); var closeLink = $('<a class="popup-close" href="#"><i class="icon icon-close"></i></a>'); popupDiv.append(elementsToAdd); popupDiv.prepend(closeLink); closeLink.click(function(e) { e.preventDefault(); closePopup(popupDiv); }); //get stuff into dom $('body').append(coverDiv); $('body').append(popupDiv); //download the scripts $.each(scripts, function(i, script) { var location = $(script).attr('src'); if ($('script[src=\'' + location + '\']').length > 0) return; $.getScript(location); }); //hide stuff coverDiv.hide(); popupDiv.hide(); //position the popup popupDiv.position({ collision: 'fit', of: $(window), my: 'center center-10%', at: 'center center'}); //show stuff coverDiv.fadeIn(); popupDiv.fadeIn(); //focus first input or link popupDiv.find('a:not(.popup-close), input').eq(0).focus(); //bind escape key popupDiv.bind('keydown', function(e) { if (e.keyCode == 27) closePopup(popupDiv); }); //trap [tab] into popup $('*').bind('focusin', popupTabFix); //execute custom callback if (typeof(cb) !== 'undefined') { cb(popupDiv); } }; stylesheets = stylesheets.filter(function(i, stylesheet) { return $('link[href=\'' + $(stylesheet).attr('href') + '\']').length == 0; }); if (stylesheets.length > 0) { stylesheets.last().load(showFunc); $('head').append(stylesheets); } else { showFunc(); } }).fail(function(rawContent) { alert('Error!'); }); } function closePopup(popupDiv) { $(popupDiv).prevAll('.cover:first').fadeOut(function() { $(this).remove(); }); $(popupDiv).fadeOut(function() { $(this).remove(); }); $('*').unbind('focusin', popupTabFix); } function popupTabFix(e) { if ($(e.target).parents('.popup').length == 0) $('.popup a, .popup input').eq(0).focus(); }
let bcrypt_util = require('../encryption_utils/bcrypt_util'); let constants = require('../constants'); let jwt = require('jsonwebtoken'); exports.authenticate = function(req, callback) { bcrypt_util.compare(req.body.password, req.body.email, function(err, res){ if (err) { callback(err, false); } else if (res) { var token = jwt.sign({email: req.body.email}, constants.secret, { expiresIn : constants.jwt_expires_in }); callback(null, {message: constants.success_messages.authenticated, token: token}); } else { callback({"message": cosntants.error_messages.invalid_email_or_password}, false); } }) };
/* *-------------------------------------------------------------------- * jQuery-Plugin "freeesections -config.js-" * Version: 1.0 * Copyright (c) 2018 TIS * * Released under the MIT License. * http://tis2010.jp/license.txt * ------------------------------------------------------------------- */ jQuery.noConflict(); (function($,PLUGIN_ID){ "use strict"; var vars={ fieldinfos:{} }; var functions={ fieldsort:function(layout){ var codes=[]; $.each(layout,function(index,values){ switch (values.type) { case 'ROW': $.each(values.fields,function(index,values){ /* exclude spacer */ if (!values.elementId) codes.push(values.code); }); break; case 'GROUP': $.merge(codes,functions.fieldsort(values.layout)); break; } }); return codes; } }; /*--------------------------------------------------------------- initialize fields ---------------------------------------------------------------*/ kintone.api(kintone.api.url('/k/v1/app/form/layout',true),'GET',{app:kintone.app.getId()},function(resp){ var sorted=functions.fieldsort(resp.layout); /* get fieldinfo */ kintone.api(kintone.api.url('/k/v1/app/form/fields',true),'GET',{app:kintone.app.getId()},function(resp){ var config=kintone.plugin.app.getConfig(PLUGIN_ID); vars.fieldinfos=resp.properties; $.each(sorted,function(index){ if (sorted[index] in vars.fieldinfos) { var fieldinfo=vars.fieldinfos[sorted[index]]; /* check field type */ switch (fieldinfo.type) { case 'NUMBER': /* exclude lookup */ if (!fieldinfo.lookup) $('select#id').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label)); break; case 'SINGLE_LINE_TEXT': /* exclude lookup */ if (!fieldinfo.lookup) { $('select#name').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label)); $('select#shortcut1').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label)); $('select#shortcut2').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label)); } break; } } }); /* initialize valiable */ if (Object.keys(config).length!==0) { $('select#id').val(config['id']); $('select#name').val(config['name']); $('select#shortcut1').val(config['shortcut1']); $('select#shortcut2').val(config['shortcut2']); $('input#freeeappid').val(config['freeeappid']); $('input#freeesecret').val(config['freeesecret']); } },function(error){}); },function(error){}); /*--------------------------------------------------------------- button events ---------------------------------------------------------------*/ $('button#submit').on('click',function(e){ var config=[]; /* check values */ if (!$('input#freeeappid').val()) { swal('Error!','FreeeAppIDを入力して下さい。','error'); return; } if (!$('input#freeesecret').val()) { swal('Error!','FreeeSecretを入力して下さい。','error'); return; } if (!$('select#id').val()) { swal('Error!','部門IDフィールドを選択して下さい。','error'); return; } if (!$('select#name').val()) { swal('Error!','部門名フィールドを選択して下さい。','error'); return; } /* setup config */ config['id']=$('select#id').val(); config['name']=$('select#name').val(); config['shortcut1']=$('select#shortcut1').val(); config['shortcut2']=$('select#shortcut2').val(); config['freeeappid']=$('input#freeeappid').val(); config['freeesecret']=$('input#freeesecret').val(); /* save config */ kintone.plugin.app.setConfig(config); }); $('button#cancel').on('click',function(e){ history.back(); }); })(jQuery,kintone.$PLUGIN_ID);
import EmberRouter from '@ember/routing/router'; import config from './config/environment'; const Router = EmberRouter.extend({ location: config.locationType, rootURL: config.rootURL }); Router.map(function() { this.route('posts', function() {}); this.route('about'); this.route('team'); this.route('candy'); this.route('friendship-status', function() {}); this.route('promise'); }); export default Router;
function contextMenusOnClick(info,tab,opt) { var balloon; chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab chrome.tabs.executeScript(tab.id,{file:'js/content.js',allFrames:true},function() { chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab chrome.tabs.sendRequest(tab.id,{'method':'prepareBalloon'},function(){ var F = info.selectionText; $.ajax({ url : 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate', data : { 'appId' : '76518BFCEBBF18E107C7073FBD4A735001B56BB1', 'text' : F, 'from' : opt.split("|")[0], 'to' : opt.split("|")[1], 'contentType' : 'text/plain' }, 'success' : function(T) { T = T.replace(/^"|"$/gi,''); chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab chrome.tabs.executeScript(tab.id,{file:'js/content.js',allFrames:true},function() {injCallBack(T)}); }); }, 'error' : function(jqXHR, textStatus, errorThrown) { var T = 'ERROR! ' + textStatus; chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab chrome.tabs.executeScript(tab.id,{file:'js/content.js',allFrames:true},function() {injCallBack(T)}); }); } }); }) }); }); }); } var injCallBack = function(S){ chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab chrome.tabs.sendRequest(tab.id,{'method':'getContextMenus','string':S}, getRequestResponseCallback) }); } var getRequestResponseCallback = function getRequestResponseCallback(response) { /* * TODO */ }; function createcontextMenusOption(opt){ var optString = ''; var L = JSONSwitch(LANGUAGES); optString += opt.split('|')[0] ? L[opt.split('|')[0]] : t('detectLanguage'); optString += ' » '; optString += opt.split('|')[1] ? L[opt.split('|')[1]] : t('detectLanguage'); chrome.contextMenus.create({ "title": optString, "contexts":['selection'], "onclick": function(opt){ return function(info,tab) { contextMenusOnClick(info,tab,opt) } }(opt) }); } function start() { if(localStorage.getItem('version') === null) { localStorage.setItem('version','0'); } if(localStorage.getItem('version') !== null && localStorage.getItem('version') !== '1.1.8.3'){ window.open('info.html'); localStorage.setItem('version','1.1.8.3'); } if (localStorage.getItem('from') === null) { localStorage.setItem('from', ''); } if (localStorage.getItem('to') === null) { localStorage.setItem('to', ''); } if (localStorage.getItem('preferred') === null) { localStorage.setItem('preferred', JSON.stringify(["|"+window.navigator.language])); window.open('options.html'); } var preferred = JSON.parse(localStorage.getItem('preferred')); chrome.contextMenus.removeAll(); for (var i = 0, max = preferred.length; i < max; i++) { createcontextMenusOption(preferred[i]); } } $(document).ready(function(){ LANGUAGES = {}; LOCALE = ""; chrome.i18n.getAcceptLanguages( function(L) { LOCALE = L[0]; currentLanguages = Microsoft.Translator.GetLanguages(); languageNames = Microsoft.Translator.getLanguageNames(LOCALE); for(var i = 0; i < currentLanguages.length; i++) { LANGUAGES[languageNames[i]] = currentLanguages[i]; } start(); } ); });
;(function() { "use strict"; var BaseController = require("BaseController"); new BaseController({ siteName: "iHeartRadio", play: ".player-controls .icon-play", pause: ".player-controls .icon-pause", playNext: ".player-controls .icon-skip", mute: ".player-controls .icon-volume", like: ".player-controls .icon-thumb-up-unfilled", dislike: ".player-controls .icon-thumb-down-unfilled", playState: ".player-controls .icon-pause", song: "a.player-song", artist: "a.player-artist" }); })();
module.exports = function (grunt) { var config = grunt.file.readJSON('fs.json'); console.log(config.appId, config.appKey); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { js: { src: [ 'src/*' ], dest: 'dist/tracker.js' } }, uglify: { js: { files: { 'dist/ugly.js': ['dist/tracker.js'] } } }, watch: { files: [ 'src/*', 'examples/*.html' ], tasks: ['concat', 'replace'] }, replace: { dist: { options: { patterns: [ { match: '__APP_ID__', replacement: config.appId }, { match: '__APP_KEY__', replacement: config.appKey }, { match: '../src', replacement: '../../src' }, { match: '../vendor', replacement: '../../vendor' }, { match: './stylesheets', replacement: '.././stylesheets' } ] }, files: [ { expand: true, flatten: true, src: ['examples/*.html'], dest: 'examples/replace/' } ] } } }); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-replace'); grunt.registerTask('default', ['concat:js', 'uglify:js', 'replace']); };
/* eslint-env mocha */ import { expect } from 'chai'; import { isNotEqual } from '../src'; describe('isNotEqual', () => { it('should return error message if validation fails', () => { expect(isNotEqual('same string', 'same string', 'error_not_equal')).to.equal('error_not_equal'); }); it('should return true if validation fails and no error message is specified', () => { expect(isNotEqual('same string', 'same string')).to.equal(true); }); it('should return undefined if value passes check', () => { expect(isNotEqual('first string', 'second string', 'error_not_equal')).to.equal(undefined); }); });
/** * Created by charlie on 10/11/16. */ module.exports = { // Event namespace actions NS_EVENT_FORM_ADD_FIELD: 'vh.form.addField', NS_EVENT_FORM_REMOVE_FIELD: 'vh.form.removeField', NS_EVENT_FORM_ITEM_XNATIVE_BLUR: 'vh.form.item.xnative.blur', NS_EVENT_FORM_ITEM_XNATIVE_CHANGE: 'vh.form.item.xnative.change' }
import GMGrid from "./GMGrid"; export default GMGrid;
"use strict"; /** * Users * @module users */ module.exports = api => { return { /** * Retrieve a user object. * @example * const { meta, data } = await pnut.user("me"); * @param {string|Number} userId - A user id * @param {Object} [params] - Additional URI parameters * @returns {Promise} */ user(userId, params = {}) { return api.request(`/users/${userId}`, { params: params }); }, /** * Retrieve a users avatar image. * @example * const { meta, data } = await pnut.avatar("me"); * @param {string|Number} userId - A user id * @param {boolean} [true] - Should the return value be prebuffered via the fetch API? * @returns {Promise} */ avatar(userId, buffered = true) { let options = buffered ? { resultAs: "buffer" } : { resultAs: "response" }; return api.request(`/users/${userId}/avatar`, options); }, /** * Upload a new avatar image * // TODO: Client side form example * @param {object} form - A valid DOM node of a form with a file field named "avatar" * @returns {Promise} */ uploadAvatar(form) { return api.request(`/users/me/avatar`, { httpMethod: "POST", dataAs: "dom-node", data: form }); }, /** * Upload a new cover image * // TODO: Client side form example * @param {object} form - A valid DOM node of a form with a file field named "cover" * @returns {Promise} */ uploadCover(form) { return api.request(`/users/me/cover`, { httpMethod: "POST", dataAs: "dom-node", data: form }); }, /** * Retrieve a users cover image. * * @example * const { meta, data } = await pnut.cover("me"); * @param {string|Number} userId - A user id * @param {boolean} [true] - Should the return value be prebuffered via the fetch API? * @returns {Promise} */ cover(userId, buffered = true) { let options = buffered ? { resultAs: "buffer" } : { resultAs: "response" }; return api.request(`/users/${userId}/cover`, options); }, /** * Retrieve a list of specified user objects. Only retrieves the first 200 found. * * @example * const { meta, data } pnut.users(1,15,127); * @param {...string|Number} userIds - 1 or more user ids * @returns {Promise} */ users(...userIds) { return api.request(`/users`, { params: { ids: userIds } }); }, /** * Retrieve posts mentioning the specified user. * * @example * const { meta, data } = await pnut.mentions(1); * @param {string|Number} userid - A user id * @param {Object} [params] - Additional URI parameters * @returns {Promise} */ mentions(userId, params = {}) { return api.request(`/users/${userId}/mentions`, { params: params }); }, /** * Retrieve posts created by a specific user. * * @example * const { meta, data } = pnut.postsFrom(1); * @param {string|Number} userId - A user id * @param {Object} [params] - Additional URI parameters * @returns {Promise} */ postsFrom(userId, params = {}) { return api.request(`/users/${userId}/posts`, { params: params }); }, /** * Replaces the authenticated user's profile. Anything not included is removed. * * @example * const { meta, data } = await pnut.replaceProfile({ * timezone: "Europe/Berlin", * name: "Robert" * }); * @param {Object} profile - Object with the required API parameters * @returns {Promise} */ replaceProfile(profile = {}) { return api.request("/users/me", { httpMethod: "PUT", data: profile }); }, /** * Updates only specified parts of the authenticated user's profile. * * @example * const { meta, data } = await pnut.updateProfile({ * timezone: "Europe/Berlin", * name: "Robert" * }); * @param {Object} profile - Object with the require API parameters * @returns {Promise} */ updateProfile(profile = {}) { return api.request("/users/me", { httpMethod: "PATCH", data: profile }); }, /** * Retrieve a list of user objects that the specified user is following. * * @example * const { meta, data } = await pnut.following(1); * @param {string|Number} userId - A user id * @param {Object} [params] - Additional URI parameters * @returns {Promise} */ following(userId, params = {}) { return api.request(`/users/${userId}/following`, { params: params }); }, /** * Retrieve a list of user objects that are following the specified user. * * @example * const { meta, data } = await pnut.followers(1); * @param {string|Number} userId - A user id * @param {Object} [params] - Additional URI parameters * @returns {Promise} */ followers(userId, params = {}) { return api.request(`/users/${userId}/followers`, { params: params }); }, /** * Follow a user. * * @example * const { meta, data } = await pnut.follow(1); * @param {string|Number} userId - id of user to follow * @returns {Promise} */ follow(userId) { return api.request(`/users/${userId}/follow`, { httpMethod: "PUT" }); }, /** * Unfollow a user. * * @example * const { meta, data } = await const { meta, data } = await pnut.unfollow(1); * @param {string|Number} userId - id of the user to unfollow * @returns {Promise} */ unfollow(userId) { return api.request(`/users/${userId}/follow`, { httpMethod: "DELETE" }); }, /** * Retrieve a list of muted users. * * @example * const { meta, data } = await pnut.muted(); * @param {Object} [params] - Additional URI parameters * @returns {Promise} */ muted(params = {}) { return api.request(`/users/me/muted`, { params: params }); }, /** * Mute a user. * * @example * const { meta, data } = await pnut.mute(1); * @param {string|Number} userId - id of the user to mute * @returns {Promise} */ mute(userId) { return api.request(`/users/${userId}/mute`, { httpMethod: "PUT" }); }, /** * Unmute a user. * * @example * const { meta, data } = await pnut.unmute(1); * @param {string|Number} userId - id of the user to unmute * @returns {Promise} */ unmute(userId) { return api.request(`/users/${userId}/mute`, { httpMethod: "DELETE" }); }, /** * Retrieve a list of blocked users. * * @example * const { meta, data } = await pnut.blocked(); * @param {Object} [params] - Additional URI parameters * @returns {Promise} */ blocked(params = {}) { return api.request( `/users/me/blocked`, { httpMethod: "GET" }, { params: params } ); }, /** * Block a user. * * @example * const { meta, data } = await pnut.block(1); * @param {string|Number} userId - id of the user to block. * @returns {Promise} */ block(userId) { return api.request(`/users/${userId}/block`, { httpMethod: "PUT" }); }, /** * Unblock a user. * * @example * const { meta, data } = await pnut.unblock(1); * @param {string} userId - id of the user to unblock. * @returns {Promise} */ unblock(userId) { return api.request(`/users/${userId}/block`, { httpMethod: "DELETE" }); }, /** * Retrieve all users' presence statuses that are not "offline". * * @example * const { meta, data } = await pnut.presence(); * @param {Object} [params] - Additional URI parameters * @returns {Promise} */ presence(params = {}) { return api.request("/presence", { params: params }); }, /** * Retrieve a user's presence. * const { meta, data } = await presenceOf("me"); * @param {string} userId - A user id * @param {Object} [params] - Additional URI parameters * @returns {Promise} */ presenceOf(userId, params = {}) { return api.request(`/presence/${userId}`, { params: params }); }, /** * Update a user's presence. * const { meta, data } = await updatePresence("my status"); * @param {string} msg - An optional status message * @returns {Promise} */ updatePresence(msg) { let params = { httpMethod: "PUT" }; if (msg) { params.data = { presence: msg }; } return api.request("/users/me/presence", params); }, /** * Retrieve a list of users filtered by the given criteria. * * @example * const { meta, data } = await pnut.searchUsers({ * q: "news", * types: "feed" * }); * @param {Object} params */ searchUsers(params = {}) { return api.request("/users/search", { params: params }); } }; };
easepack .set('useEs2015', true) .set('output', './dist') .set('publicPath', '//cdn.cn/') .set('useCommonsChunk', true) easepack .media('m1') .set('useCommonsChunk', { url: 'a[name].[ext]?[hash]', vendor: {name: 'vendorb'} }) easepack .match('*.{js,html}')
var assert = require('assert'); testEn(); testDe(); testPtBr(); testRu(); testEs(); testCs(); testSk(); function testEn() { describe('the pluralizer for the "en" locale', function() { var pluralize = require('./en'); it('should be a function', function() { assert.isFunction(pluralize); }); it('should output the correct pluralizations', function() { var entry = { zero: 'no items', one: 'one item', other: '%(count)s items' }; assert.equal(pluralize(entry, 0), 'no items'); assert.equal(pluralize(entry, 1), 'one item'); assert.equal(pluralize(entry, 2), '%(count)s items'); assert.equal(pluralize(entry, 42), '%(count)s items'); }); }); } function testDe() { describe('the pluralizer for the "de" locale', function() { var pluralize = require('./de'); it('should be a function', function() { assert.isFunction(pluralize); }); it('should output the correct pluralizations', function() { var entry = { zero: 'keine Einträge', one: 'ein Eintrag', other: '%(count)s Einträge' }; assert.equal(pluralize(entry, 0), 'keine Einträge'); assert.equal(pluralize(entry, 1), 'ein Eintrag'); assert.equal(pluralize(entry, 2), '%(count)s Einträge'); assert.equal(pluralize(entry, 42), '%(count)s Einträge'); }); }); } function testPtBr() { describe('the pluralizer for the "pt-br" locale', function() { var pluralize = require('./pt-br'); it('should be a function', function() { assert.isFunction(pluralize); }); it('should output the correct pluralizations', function() { var entry = { zero: 'nenhuma entrada', one: 'uma entrada', other: '%(count)s entradas' }; assert.equal(pluralize(entry, 0), 'nenhuma entrada'); assert.equal(pluralize(entry, 1), 'uma entrada'); assert.equal(pluralize(entry, 2), '%(count)s entradas'); assert.equal(pluralize(entry, 42), '%(count)s entradas'); }); }); } function testRu() { describe('the pluralizer for the "ru" locale', function() { var pluralize = require('./ru'); it('should be a function', function() { assert.isFunction(pluralize); }); it('should output the correct pluralizations', function() { var entry = { zero: 'no items', one: 'one', few: 'few', many: 'many', other: '%(count)s items' }; assert.equal(pluralize(entry, 0), 'no items'); assert.equal(pluralize(entry, 1), 'one'); assert.equal(pluralize(entry, 21), 'one'); assert.equal(pluralize(entry, 101), 'one'); assert.equal(pluralize(entry, 2), 'few'); assert.equal(pluralize(entry, 34), 'few'); assert.equal(pluralize(entry, 53), 'few'); assert.equal(pluralize(entry, 5), 'many'); assert.equal(pluralize(entry, 11), 'many'); assert.equal(pluralize(entry, 38), 'many'); assert.equal(pluralize(entry, 3.14), '%(count)s items'); assert.equal(pluralize(entry, 2.78), '%(count)s items'); }); }); } function testEs() { describe('the pluralizer for the "es" locale', function() { var pluralize = require('./es'); it('should be a function', function() { assert.isFunction(pluralize); }); it('should output the correct pluralizations', function() { var entry = { zero: 'No hay elementos', one: 'Un elemento', other: '%(count)s elementos' }; assert.equal(pluralize(entry, 0), 'No hay elementos'); assert.equal(pluralize(entry, 1), 'Un elemento'); assert.equal(pluralize(entry, 2), '%(count)s elementos'); assert.equal(pluralize(entry, 42), '%(count)s elementos'); }); }); } function testCs() { describe('the pluralizer for the "cs" locale', function () { var pluralize = require('./cs'); it('should be a function', function () { assert.isFunction(pluralize); }); it('should output the correct pluralizations', function () { var entry = { zero: 'žádná položka', one: 'jedna položka', few: '%(count)s položky', other: '%(count)s položek' }; assert.equal(pluralize(entry, 0), 'žádná položka'); assert.equal(pluralize(entry, 1), 'jedna položka'); assert.equal(pluralize(entry, 2), '%(count)s položky'); assert.equal(pluralize(entry, 5), '%(count)s položek'); }); }); } function testSk() { describe('the pluralizer for the "sk" locale', function () { var pluralize = require('./sk'); it('should be a function', function () { assert.isFunction(pluralize); }); it('should output the correct pluralizations', function () { var entry = { zero: 'žiadna položka', one: 'jedna položka', few: '%(count)s položky', other: '%(count)s položiek' }; assert.equal(pluralize(entry, 0), 'žiadna položka'); assert.equal(pluralize(entry, 1), 'jedna položka'); assert.equal(pluralize(entry, 2), '%(count)s položky'); assert.equal(pluralize(entry, 5), '%(count)s položiek'); }); }); } /* Helper Functions */ assert.isFunction = function(value, message) { assert.equal(Object.prototype.toString.call(value), '[object Function]', message || (value + ' is not a function')); };
/** * @ignore * single tab panel. * @author yiminghe@gmail.com */ var Container = require('component/container'); /** * KISSY.Tabs.Panel.xclass: 'tabs-panel'. * @class KISSY.Tabs.Panel * @extends KISSY.Component.Container */ module.exports = Container.extend({ isTabsPanel: 1, beforeCreateDom: function (renderData) { var self = this; renderData.elAttrs.role = 'tabpanel'; if (renderData.selected) { renderData.elCls.push(self.getBaseCssClasses('selected')); } else { renderData.elAttrs['aria-hidden'] = false; } }, _onSetSelected: function (v) { var el = this.$el; var selectedCls = this.getBaseCssClasses('selected'); el[v ? 'addClass' : 'removeClass'](selectedCls) .attr('aria-hidden', !v); } }, { ATTRS: { allowTextSelection: { value: true }, focusable: { value: false }, handleGestureEvents: { value: false }, /** * whether selected * @cfg {Boolean} selected */ /** * @ignore */ selected: { render: 1, sync: 0, parse: function (el) { return el.hasClass(this.getBaseCssClass('selected')); } } }, xclass: 'tabs-panel' });
// ++ export function increment( index ) { return { type: 'INCREMENT_VOTES', index } } // + comment export function addComment( postId, author, comment ) { return { type: 'ADD_COMMENT', postId, author, comment } } // - comment export function removeComment( postId, i ) { return { type: 'REMOVE_COMMENT', i, postId } }
import React,{ PropTypes, Component } from 'react'; import classnames from 'classnames'; import ClassNameMixin from './utils/ClassNameMixin.js'; /** * 分页组件 * @class Paging * @constructor * @module ui * @extends Component * @requires React classnames * @since 0.1.0 * @demo paging.js {js} * @show true * @author min.xiao@dianping.com * */ @ClassNameMixin export default class Paging extends Component{ static propTypes = { /** * 总页数 * @property currentPage * @type Integer * @default 1 * */ currentPage: PropTypes.number.isRequired, /** * 每页显示多少条数据 * @property pageSize * @type Integer * @default 20 * */ pageSize: PropTypes.number.isRequired, /** * 数据总数 * @property total * @type Integer * */ total: PropTypes.number.isRequired, /** * 点击分页回调 * @property pageCallback * @type Function * */ pageCallback: PropTypes.func, /** * * @property activeClass * @type String * @default active * */ activeClass: PropTypes.string, classPrefix: PropTypes.string, componentTag: PropTypes.string, /** * 开启选择每页显示数量选项 * @property showItemsNumber * @type Boolean * */ showItemsNumber:PropTypes.bool } static defaultProps = { activeClass:'active', currentPage:1, pageSize:20, classPrefix:'paging', componentTag:'div', /** * 跟showItemsNumber一起使用 arguments{pageSize} * @property loadPageCallback * */ loadPageCallback:function(){ console.warn('Is not defined loadPageCallback'); } }; /** * @constructor * @param props {Object} * @param context {Object} * */ constructor(props, context) { super(props, context); /** * @type Integer * @default * */ this.pages=this.getPages(); this.index = 0; this.number = 5; /** * @type Boolean * @default false * */ this.init = false; //总数:this.total this.state = { /** * 当前页 * @type Integer * */ currentPage:this.props.currentPage, defaultNumber:this.props.pageSize }; } /** * 上一页 * @method prev * */ prev(){ this.gotoPage(this.props.currentPage-1 ); } /** * 下一页 * @method prev * */ next(){ this.gotoPage(this.props.currentPage+1); } /** * 获取页大小 * @method getPages * @return {Integer} * */ getPages(){ return Math.ceil(this.props.total/this.props.pageSize); } /** * 跳转至N页 * @method goto * @param page {Integer} 页码,从1开始 * @private * @return {Array} * */ goto(page = this.state.currentPage){ this.pages=this.getPages(); if(page <=1){ page = 1; } if(page >= this.pages){ page = this.pages; } /*if(this.init){ this.setState({ currentPage:page }); this.init = false; }*/ return this.generate(); } /** * 跳转至N页 * @method gotoPage * @param index {Integer} 页码,从1开始 * @return {Array} * */ gotoPage(index){ this.init=true; this.props.pageCallback && this.props.pageCallback(index ); return this.goto(index); } /** * 生成页码 * @method generate * @return {Array} * */ generate(){ const {currentPage,activeClass} = this.props; let i=1, htmlList = [], distance = 4, len = currentPage+distance; i =currentPage<=6 ? i:currentPage-distance; i = i<=1?1:i; len = len>this.pages ? this.pages : len; if(currentPage>1){ htmlList.push(<a href="javascript:void(0);" key="上一页" className="" onClick={::this.prev}>上一页</a>); } //9 ....4....|. if(currentPage>=7){ htmlList.push(<a href="javascript:void(0);" key={1} onClick={::this.gotoPage.bind(this,1)}>{1}</a>); htmlList.push(<a href="javascript:void(0);" key="...上一页">...</a>); //i+=1; } for(;i<=len;i++){ htmlList.push(<a href="javascript:void(0);" key={i} onClick={this.gotoPage.bind(this,i)} className={classnames({ [this.getClassName(activeClass) ]: i==currentPage } ) } >{i}</a> ); } //pages-currentPage = let bt = this.pages-currentPage; if(bt>=7 ){ htmlList.push(<a href="javascript:void(0);" key="...下一页">...</a>); htmlList.push(<a href="javascript:void(0);" key={this.pages} onClick={::this.gotoPage.bind(this,this.pages)}>{this.pages}</a>); } if(this.pages>1 && currentPage!=this.pages){ htmlList.push(<a href="javascript:void(0);" key="下一页" onClick={::this.next}>下一页</a>); } return htmlList; } changePageSizeHandler(e){ let val = e.target.value; //this.setState({ // defaultNumber:val*1 //}); let {loadPageCallback} = this.props; loadPageCallback && (loadPageCallback(val) ); this.setState({ defaultNumber:val }); } accordingNumber(){ let opts = [],num=10; for(let i=1;i<11;i++){ opts.push(<option value={num*i} key={num*i}>{num*i}</option>); } return ( <span style={{ marginRight:'20px' }}> 每页显示&nbsp;&nbsp; <select defaultValue={this.props.pageSize} onChange={::this.changePageSizeHandler}> { opts } </select> &nbsp;&nbsp;页 </span> ); } /** * @method render * @return {ReactElement} * */ render(){ const {componentTag:Component,activeClass,showItemsNumber} = this.props; return ( <Component className={classnames(this.getClassName('container')) }> {showItemsNumber ? this.accordingNumber():null} {this.goto() } <span className='info'> <span className={classnames(this.getClassName(activeClass)) }> {this.props.currentPage} </span>/{this.getPages()},共{this.props.total}条 </span> </Component> ); } }
import EntityManager from './EntityManager'; import { ContractSliceGuaranteeService } from '../../services'; /** * Identity's contract slice guarantee - manually defined managers (if no tree structure is defined etc.) * * @author Vít Švanda */ export default class ContractSliceGuaranteeManager extends EntityManager { constructor() { super(); this.service = new ContractSliceGuaranteeService(); } getService() { return this.service; } getEntityType() { return 'ContractSliceGuarantee'; } getCollectionType() { return 'contractSliceGuarantees'; } }
const BasicColorTheme = require('./templates/BasicColorTheme') const ColorSchemeTransformations = require('./ColorSchemeTransformations') const BasicTiming = require('./timings/BasicTiming') module.exports = { name: 'Secret: Jonathan', enabled: secrets => secrets.indexOf('jonathan') > -1, theme: BasicColorTheme( ColorSchemeTransformations.fromObjectStrings, BasicTiming, [{ background: { 'background-image': 'url(\'../img/jonathan-1.png\')', 'background-size': '300%' }, text: 'red', subtext: 'white', contrast: '#444' }, { background: { 'background-image': 'url(\'../img/jonathan-1.png\')', 'background-size': '233%' }, text: 'orange', subtext: 'white', contrast: '#444' }, { background: { 'background-image': 'url(\'../img/jonathan-1.png\')', 'background-size': '166%' }, text: 'yellow', subtext: 'white', contrast: '#444' }, { background: { 'background-image': 'url(\'../img/jonathan-1.png\')', 'background-size': '100%' }, text: 'lime', subtext: 'white', contrast: '#444' }], { holiday: { background: { 'background-image': 'url(\'../img/jonathan-1.png\')', 'background-size': '100%' }, text: 'magenta', subtext: 'white', contrast: '#444' }, weekend: { background: { 'background-image': 'url(\'../img/jonathan-1.png\')', 'background-size': '100%' }, text: 'cyan', subtext: 'white', contrast: '#444' } } ) }
var Plugin = require('nokomis/plugin') var Domain = require('domain') var ErrorPage = require('error-page') var _ = require('underscore') module.exports = Plugin.extend({ initialize: function(config) { this.config = config || {} }, run: function(instance, callback) { var req = instance.req var res = instance.res var config = this.config var defaultErrorPageConfig = { 401: handle401.bind(instance), 403: handle403.bind(instance), 404: handle404.bind(instance), 500: handle500.bind(instance), '*': handleError.bind(instance), debug: false } // setup error-page module var errorPageConfig = _.extend(defaultErrorPageConfig, config) instance.error = new ErrorPage(req, res, errorPageConfig) // Use a node Domain to handle all // unexpected errors in one location var domain = Domain.create() domain.add(req) domain.add(res) domain.add(instance) domain.on('error', function(err) { try { if (instance.error) { instance.error(err) } else { res.statusCode = 500 res.setHeader('content-type', 'text/plain') res.end('Server Error\n' + err.message) } // don't destroy the domain before sending the error res.on('close', function() { domain.dispose() }) // but don't wait forever setTimeout(function() { domain.dispose() }, 1000) // close down the server so a fresh worker can be started req.client.server.close() } catch (err) { console.error('The request\'s domain error handler failed unexpectedly.') domain.dispose() } }) callback() } }) /** * Handle 401 error * * @param {Object} req * @param {Object} res * @param {Object} data * @api private */ function handle401(req, res, data) { return handleError.call(this, req, res, data, 'errors/401') } /** * Handle 403 error * * @param {Object} req * @param {Object} res * @param {Object} data * @api private */ function handle403(req, res, data) { return handleError.call(this, req, res, data, 'errors/403') } /** * Handle 404 error * * @param {Object} req * @param {Object} res * @param {Object} data * @api private */ function handle404(req, res, data) { return handleError.call(this, req, res, data, 'errors/404') } /** * Handle 500 error * * @param {Object} req * @param {Object} res * @param {Object} data * @api private */ function handle500(req, res, data) { return handleError.call(this, req, res, data, 'errors/500') } /** * Handle all response errors * * @param {Object} req * @param {Object} res * @param {Object} data * @param {String} template * @api private */ function handleError(req, res, data, template) { req.log.error('Responding with error', data) var config = this.config || {} if (config.NODE_ENV != 'development') { delete data.options delete data.stack delete data.error } this.template = template || 'errors/default' this.templateOptions.layout = 'errors/layout' this.model = data return this._render(template, data) }
/* jshint node:true, laxbreak: true */ 'use strict'; // Sets up the tasks that lints css and js files. // @task: /gulp-config/lint.js /////////////////////////////////////////////////////////////////////////// // Required modules. /////////////////////////////////////////////////////////////////////////// var csslint = require('gulp-csslint'); var jshint = require('gulp-jshint'); var path = require('path'); var buildConfig = require('./../build-config'); /////////////////////////////////////////////////////////////////////////// // Create Tasks /////////////////////////////////////////////////////////////////////////// /** * The class that holds all of our gulp tasks for this configuration. * * @class GulpTask * @param {gulp} gulp * @param {object} buildEnv * @constructor */ var GulpTask = function(gulp, buildEnv) { /** * The GulpJS object. * * @default null * @property {gulp} * @type {gulp} */ this.gulp = gulp; /** * The build environment info. * * @default null * @property buildEnv * @type {object} */ this.buildEnv = buildEnv; // Initialize the gulp tasks. this.init(); }; var proto = GulpTask.prototype; /** * Initializes the gulp tasks. * * @method init * @returns void */ proto.init = function() { this.gulp.task('csslint', this.cssLint.bind(this)); this.gulp.task('jshint', this.jsHint.bind(this)); }; /** * Lints the css files for any errors. * * @method cssLint * @returns {gulp} */ proto.cssLint = function() { return this.gulp.src(path.join(buildConfig.DIR_TMP, buildConfig.DIR_ASSETS + '/**/*.css')) .pipe(csslint('.csslintrc')) .pipe(csslint.reporter()); }; /** * Runs the jshint validation based on the .jshintrc * validation rules. * * @method jsHint * @returns {gulp} */ proto.jsHint = function() { return this.gulp.src(path.join(buildConfig.DIR_SRC, 'scripts/**/*.js')) .pipe(jshint()) .pipe(jshint.reporter('default')); }; /////////////////////////////////////////////////////////////////////////// // Export object /////////////////////////////////////////////////////////////////////////// module.exports = GulpTask;
'use strict'; var server = require('nachos-server-api'); var Q = require('q'); var debug = require('debug')('nachosPackageManager:publish'); var fstream = require('fstream'); var tar = require('tar'); var jf = require('jsonfile'); var path = require('path'); var zlib = require('zlib'); var fs = require('fs'); var os = require('os'); var _ = require('lodash'); var auth = require('../auth'); var validOs = ['win32', 'linux', 'darwin']; var validTargetArch = ['ia32', 'x64']; /** * Publish a package * * @param {string} source Source directory * @param {string} targetOS Target operating system * @param {string} targetArch Target arch * @returns {Q.promise} Publish succeeded */ module.exports = function (source, targetOS, targetArch) { if (!source) { return Q.reject(new TypeError('nachos-package-manager publish: source directory must be provided')); } else if (typeof source !== 'string') { return Q.reject(new TypeError('nachos-package-manager publish: source directory must be a string')); } if (!targetOS) { return Q.reject(new TypeError('nachos-package-manager publish: target os must be provided')); } else if (typeof targetOS !== 'string') { return Q.reject(new TypeError('nachos-package-manager publish: target os must be a string')); } else if (!_.contains(validOs, targetOS.toLowerCase())) { return Q.reject(new TypeError('nachos-package-manager publish: target os must be one of the following ' + validOs)); } if (!targetArch) { return Q.reject(new TypeError('nachos-package-manager publish: target arch must be provided')); } else if (typeof targetArch !== 'string') { return Q.reject(new TypeError('nachos-package-manager publish: target arch must be a string')); } else if (!_.contains(validTargetArch, targetArch.toLowerCase())) { return Q.reject(new TypeError('nachos-package-manager publish: target arch must be one of the following ' + validTargetArch)); } debug('publishing directory %s to %s %s', source, targetOS, targetArch); var client = server(); var tempFile = path.join(os.tmpdir(), 'this-should-be-a-long-name-so-there-will-be-no-collision.tgz'); return auth.get() .then(function (token) { if (!token) { return Q.reject(new Error('There is no logged-in user.')); } client.setToken(token); return Q.nfcall(jf.readFile, path.join(source, 'nachos.json')); }) .then(function (data) { debug('nachos.json: %j', data); if (data.private) { return Q.reject('can\'t publish private package'); } var deferred = Q.defer(); fstream.Reader(source) .pipe(tar.Pack({fromBase: true})) .pipe(zlib.Gzip()) .pipe(fs.createWriteStream(tempFile)) .on('finish', function () { client.packages.upload({'package': fstream.Reader(tempFile)}, { package: data.name, os: targetOS, arch: targetArch }) .then(function () { deferred.resolve(); }, function (err) { debug('upload error: %j', err); if (err.response && err.response.statusCode === 403) { return Q.reject('permission denied, you are not an owner of this package'); } return Q.reject(err); }) .catch(function (err) { deferred.reject(err); }) .finally(function () { return Q.nfcall(fs.unlink, tempFile); }); }); return deferred.promise; }); };
require('coffee-script'); var utils = require('../lib/utils'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports['utils'] = { setUp:function (done) { // setup here done(); }, 'endsWith':function (test) { test.expect(5); test.equal(utils.endsWith('', 'def'), false); test.equal(utils.endsWith('abc', ''), true); test.equal(utils.endsWith('abcdef', 'def'), true); test.equal(utils.endsWith('abcDef', 'Def'), true); test.equal(utils.endsWith('abc.', '.'), true); test.done(); } };
import React from "react"; import R from "ramda"; import { Col } from "reactstrap"; import { isBasic, getCheckpointsCodes } from "../../selectors/board"; export default ({ user, src, pos, board, inCard }) => { const boardCheckpointIds = getCheckpointsCodes(board); const units = board.units; return ( <Col title={user.name} xs={4} className={"text-center top-item top-item" + pos} > <img src={src} /> <h4 style={{ overflow: "hidden", whiteSpace: "nowrap" }}> {user.name} </h4> <p> {isBasic(board) || inCard ? <span>{user.score} {units}</span> : <span> { R.intersection( user.__do_not_checkpoints_codes, boardCheckpointIds ).length } / {boardCheckpointIds.length} {" "} ({user.score} {board.units}) </span>} </p> <div className={"pod pod" + pos}> {pos} </div> </Col> ); };
'use strict'; angular.module('ctm.filters', []) .filter('hasValue', function () { return function (inputs, values) { if(!angular.isArray(inputs)) { inputs = [inputs]; } if(!angular.isArray(values)) { values = [values]; } for (var i = 0; i < inputs.length; i++) { for (var j = 0; j < values.length; j++) { if (inputs[i] === values[j]) { return true; } } } return false; }; }) ;
// @flow class Node<T> { data: T; prev: ?Node<T>; next: ?Node<T>; constructor(data: T, prev: ?Node<T>) { this.data = data; this.prev = prev; } getData(): T { return this.data; } getPrev(): ?Node<T> { return this.prev; } setPrev(prev: ?Node<T>): void { this.prev = prev; } getNext(): ?Node<T> { return this.next; } setNext(next: ?Node<T>): void { this.next = next; } } class DoublyLinkedList<T> { head: ?Node<T> = null; tail: ?Node<T> = null; getHead(): ?Node<T> { return this.head; } getTail(): ?Node<T> { return this.tail; } add(data: T): void { let currentNode = this.head; let newNode; if (this.head === null) { newNode = new Node(data, null); this.head = newNode; this.tail = newNode; } while (currentNode) { if (typeof currentNode.getNext() === 'undefined') { newNode = new Node(data, currentNode); this.tail = newNode; currentNode.setNext(newNode); return; } currentNode = currentNode.getNext(); } } remove(data: T): void { let currentNode = this.head; let previousNode: ?Node<T>; let nextNode: ?Node<T>; if (currentNode === null) { throw new Error('Cannot remove from empty DLL'); } if (this.head && this.head.getData() === data) { if (this.head.next) { this.head = this.head.next; this.head.prev = null; } else { this.head = null; this.tail = null; } } else if (this.tail && this.tail.getData() === data) { if (this.tail.prev) { this.tail = this.tail.prev; this.tail.setNext(null); } } else { while (currentNode && typeof currentNode !== 'undefined') { if (currentNode.getPrev() === null) { previousNode = null; } else { previousNode = currentNode.getPrev(); } if (currentNode.next && typeof currentNode.next !== 'undefined') { nextNode = currentNode.next; } else { nextNode = null; } if (currentNode.getData() === data) { if (nextNode) { currentNode = nextNode; } else { if (previousNode) { previousNode.setNext(null); } return; } if (currentNode.getPrev() === null) { currentNode.setPrev(null); } else if (currentNode && previousNode) { currentNode.setPrev(previousNode); previousNode.setNext(currentNode); } return; } currentNode = nextNode; } } } reverse(): DoublyLinkedList<T> { const reversedDLL = new DoublyLinkedList(); let currentNode = this.tail; while (currentNode) { reversedDLL.add(currentNode.getData()); currentNode = currentNode.getPrev(); } return reversedDLL; } elementAt(index: number): ?Node<T> { let currentNode = this.head; for (let i = 0; i <= index; i += 1) { if (i === index) { return currentNode; } if (currentNode && currentNode.next) { currentNode = currentNode.next; } else { currentNode = null; } } return null; } elementDataAt(index: number): ?T { const element = this.elementAt(index); if (element) { return element.getData(); } return null; } } export default DoublyLinkedList;
var SfzSoundfont = require('./../').Soundfont, should = require('chai').should(), fs = require('fs'); describe('Encoding a SFZ soundfont string', function () { it('should always return a string', function () { var data = fs.readFileSync('./tests/resources/with-groups.sfz', 'utf-8'), soundfont = SfzSoundfont.parse(data); soundfont.toString().should.be.a('string'); soundfont = new SfzSoundfont(); soundfont.toString().should.be.a('string'); }); it('should return a string matching its input', function () { var data = fs.readFileSync('./tests/resources/with-groups.sfz', 'utf-8'), soundfont = SfzSoundfont.parse(data), reencodedSoundfont = SfzSoundfont.parse(soundfont.toString()); reencodedSoundfont.should.deep.equal(soundfont); }) });
"use strict"; var event = { "Origin": "https://www.youtube.com/watch?v=0z9yS1-We6U", "Bucket": "video-qa-mzplus-com", "UserMetaData": { "miid": "E1337", "page": "101", "part": "11" } }; var PullOrigin2S3 = require("./PullOrigin2S3"); PullOrigin2S3.pull(event, null);
/** * Dist Class */ import Holder from './holder'; import Node from './node'; export default class Dist { constructor() { this.nodes = [] } createNode(opts) { opts = opts || {}; if ( opts.id && typeof opts.id !== 'string' ) { throw 'Node id should be string!'; }; if ( this.nodes.map(node => node.id).indexOf(opts.id) != -1 ) { throw 'Attempt to create Node with already taken id!'; }; const node = new Node({ id: opts.id, timeout: opts.timeout, onCreate: opts.onCreate, onDestroy: opts.onDestroy, onMessage: opts.onMessage, onRecreate: opts.onRecreate, distData: opts.distData, }); this.nodes.push(node); return node; } createNodes(nodeOpts) { if ( typeof nodeOpts === 'number' ) { let nodes = []; for ( let i = 0; i < nodeOpts; i++) nodes.push(this.createNode()); return nodes; } else if ( Object.prototype.toString.call(nodeOpts) === '[object Array]' ) { return nodeOpts.map(opts => this.createNode(opts)); }; } destroyNode(node) { this.nodes.splice(this.nodes.indexOf(node.id), 1); return node.destroy(); } destroyNodes(nodes) { if ( Object.prototype.toString.call(nodes) !== '[object Array]' ) { throw 'Dist#destroyNodes(nodeList) takes array of nodes as argument!'; }; nodes.forEach(node => { node.destroy(); this.nodes.splice(this.nodes.indexOf(node.id), 1); }); } getNode(id) { return this.nodes.filter(node => node.id === id)[0]; } getNodes(idList) { return this.nodes.filter(node => idList.indexOf(node.id) != -1 ); } recreateNode(node) { node.recreate(); } createHolder() { return new Holder() } }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import naviStore from 'stores/naviStore'; export default class PageTitle extends Component { static propTypes = { title: PropTypes.node.isRequired, }; constructor(props) { super(props); naviStore.setBreadcrumbTitle(props.title); } componentDidUpdate(prevProps) { const { title } = this.props; if (prevProps.title !== title) { naviStore.setBreadcrumbTitle(title); } } render() { return <h1>{this.props.title}</h1>; } }