text
stringlengths
2
6.14k
/** * The packages we are using **/ var gulp = require('gulp'); var sass = require('gulp-sass'); var browserSync = require('browser-sync'); var prefix = require('gulp-autoprefixer'); var plumber = require('gulp-plumber'); var uglify = require('gulp-uglify'); var rename = require("gulp-rename"); var imagemin = require("gulp-imagemin"); var pngquant = require('imagemin-pngquant'); var include = require("gulp-include"); /** * * Styles * - Compile * - Compress/Minify * - Catch errors (gulp-plumber) * - Autoprefixer * **/ gulp.task('sass', function() { gulp.src('scss/**/*.scss') .pipe(sass({outputStyle: 'compressed'})) .on('error', sass.logError) .pipe(prefix('last 2 versions', '> 1%', 'ie 8', 'Android 2', 'Firefox ESR')) .pipe(plumber()) .pipe(gulp.dest('css')); }); /** * * BrowserSync.io * - Watch CSS, JS & HTML for changes * - View project at: localhost:3000 * **/ gulp.task('browser-sync', function() { browserSync.init(['css/*.css', 'js/**/*.js', 'index.html'], { server: { baseDir: './' } }); }); /** * * Javascript * - Uglify * **/ gulp.task('scripts', function() { gulp.src('js/*.js') .pipe(include()) .pipe(uglify()) .pipe(rename({ dirname: "min", suffix: ".min", })) .pipe(gulp.dest('js')) }); /** * * Images * - Compress them! * **/ gulp.task('images', function () { return gulp.src('images/*') .pipe(imagemin({ progressive: true, svgoPlugins: [{removeViewBox: false}], use: [pngquant()] })) .pipe(gulp.dest('images')); }); /** * * Default task * - Runs sass, browser-sync and scripts * - Watchs for file changes for scripts and sass/css * **/ gulp.task('watch', ['sass', 'browser-sync', 'scripts'], function () { gulp.watch('scss/**/*.scss', ['sass']); gulp.watch('js/*.js', ['scripts']); }); gulp.task('default', ['sass', 'scripts', 'images']);
export { default as Campaigns } from './Campaigns'; export { default as campaign } from './campaign';
import dian from '../../dian/index'; var app = getApp(); Page({ data: { dataList: [] }, /** * 进入页面 */ onLoad: function () { }, /** * */ onShow: function () { var that = this; if (!app.data.rankLoaded) {//未加载数据则加载 dian.request({ loading: true, url: '/spriderproject/rank/list', success: function (res) { that.setData({ dataList: JSON.parse(res.data.data) }); app.data.rankLoaded = true;//加载完成 } }); } }, /** *下拉刷新 */ onPullDownRefresh: function () { wx.stopPullDownRefresh(); var that = this; dian.request({ loading: true, url: '/spriderproject/rank/list', success: function (res) { that.setData({ dataList: JSON.parse(res.data.data) }); app.data.rankLoaded = true;//加载完成 } }); }, onShareAppMessage: function () { return { title: '赞赏排行榜', desc: '微信支付开源(小程序+服务器源码)', path: '/pages/rank/rank' } } })
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var RestaurantSchema = new Schema({ name: { type: String, unique: true }, hits: { type: Number } }); RestaurantSchema.statics.getAll = function(cb) { this.find({}, cb); }; RestaurantSchema.statics.removeById = function(id, cb) { this.remove({ _id: id }, cb); }; mongoose.model('Restaurant', RestaurantSchema);
'use strict'; var util = require('util'); var template = '' + '<section class="CG2-livecode" %s>' + '<header class="CG2-livecode__header">' + '<div class="CG2-livecode__label">%s</div>' + '<div class="CG2-livecode__nav">' + '<ul>%s</ul>' + '</div>' + '</header>' + '<div class="CG2-livecode__body">%s</div>' + '</section>'; var sourceTemplate = '' + '<li>' + '<a href="%s">ソースコード</a>' + '</li>'; var newTabTemplate = '' + '<li>' + '<a href="%s">新規タブで開く</a>' + '</li>'; /** * div.Demoを整形する * * @param {HTMLDocument} $ * cheerio */ module.exports = function($) { $('.Demo').each(function(idx, el) { var $el = $(el); var $h1 = $el.find('h1').first(); var $a = $el.find('a').first(); var $iframe = $el.find('iframe').first(); var srcUrl = $a.attr('href'); var iframeSrc = $iframe.attr('src') || $iframe.attr('data-src'); var defferedAttr = $iframe.attr('data-deferred') ? 'data-livecode-deferred' : ''; var title = $h1 ? $h1.text() : ''; var innerUl = _getLi(srcUrl, iframeSrc); var content = $.html($iframe); var demo = $(util.format(template, defferedAttr, title, innerUl, content)); $el.replaceWith(demo); }); }; /** * ツールボタンたちのulの中身を返す * * @param {string} srcUrl * ソースコードのURL * @param {string} iframeSrc * iframeのURL * */ function _getLi(srcUrl, iframeSrc) { var innerUl = []; if (srcUrl) { innerUl.push(util.format(sourceTemplate, srcUrl)); } if (iframeSrc) { innerUl.push(util.format(newTabTemplate, iframeSrc)); } return innerUl.join(''); }
constants = { weatherCity: 'Seattle', twitterAt: 'ReutersTech', twitterId: '685274550158753792', setup: true }
var gulp = require('gulp'); gulp.task('templates', function () { var angularTemplatecache = require('gulp-angular-templatecache'); var htmlmin = require('gulp-htmlmin'); var rename = require('gulp-rename'); var uglifyjs = require('gulp-uglifyjs'); var ngAnnotate = require('gulp-ng-annotate'); return gulp.src(['src/**/*.html', '!src/index.html']) .pipe(htmlmin({ removeComments: true, collapseWhitespace: true, conservativeCollapse: true, keepClosingSlash: true, caseSensitive: true })) .pipe(angularTemplatecache({ root: null, module: 'sw.ui.md' })) .pipe(rename('swagger-ui-material.templates.js')) .pipe(gulp.dest('dist/scripts')) .pipe(ngAnnotate()) .pipe(uglifyjs('swagger-ui-material.templates.min.js')) .pipe(gulp.dest('dist/scripts')); });
{ writeFiles(DIR, { "__tests__/a-banana.js": ` test('banana', () => expect(1).toBe(1)); test('abc', () => console.log(process.cwd())); `, "jest.config.js": `module.exports = {testRegex: '.*-banana.js'};`, "package.json": "{}", "some/nested/directory/file.js": "// nothing special" }); const { stderr, status, stdout } = runJest( path.join(DIR, "some", "nested", "directory"), ["-w=1", "--ci=false"], { skipPkgJsonCheck: true } ); expect( stdout.replace(/^\W+(.*)integration_tests/gm, "<<REPLACED>>") ).toMatchSnapshot(); const { rest, summary } = extractSummary(stderr); expect(status).toBe(0); expect(rest).toMatchSnapshot(); expect(summary).toMatchSnapshot(); }
(function () { 'use strict'; angular.module('firebase.config', []); })();
// Given a positive integer, return its corresponding column title as appear in an Excel sheet. // // For example: // // 1 -> A // 2 -> B // 3 -> C // ... // 26 -> Z // 27 -> AA // 28 -> AB const lookup = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; /** * @param {number} n * @return {string} */ var convertToTitle = function(n) { let result = ''; while (n !== 0) { let value = n % 26; if (value === 0) { value = 25; n -= 26; } else { value--; } result = lookup[value] + result; n = Math.floor(n / 26); } return result; };
/* global describe, it, require */ 'use strict'; // MODULES // var // Expectation library: chai = require( 'chai' ), // Module to be tested: log2 = require( './../lib/number.js' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'number log2', function tests() { it( 'should export a function', function test() { expect( log2 ).to.be.a( 'function' ); }); it( 'should compute the base-2 logarithm', function test() { assert.closeTo( log2( 7 ), 2.807354922, 1e-7 ); assert.closeTo( log2( 90 ), 6.491853096, 1e-7 ); assert.closeTo( log2( 300 ), 8.22881869, 1e-7 ); }); it( 'should return `NaN` if provided with a negative number', function test() { var val; val = log2( -9 ); assert.isTrue( val !== val ); val = log2( -7 ); assert.isTrue( val !== val ); val = log2( -81 ); assert.isTrue( val !== val ); }); });
/* This file is part of Ext JS 4 Copyright (c) 2011 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. */ /** * @class FeedViewer.FeedPanel * @extends Ext.panel.Panel * * Shows a list of available feeds. Also has the ability to add/remove and load feeds. * * @constructor * Create a new Feed Panel * @param {Object} config The config object */ Ext.define('message.MessageTypesPanel', { extend: 'Ext.panel.Panel', animCollapse: true, layout: 'fit', title: 'Categorie', initComponent: function(){ Ext.apply(this, { items: this.createView() }); this.addEvents( 'feedremove', 'feedselect' ); this.callParent(arguments); }, createView: function(){ this.view = Ext.create('widget.dataview', { store: Ext.create('Ext.data.Store', { model: 'MessageType', data: this.feeds }), selModel: { mode: 'SINGLE', listeners: { scope: this, selectionchange: this.onSelectionChange } }, listeners: { scope: this, contextmenu: this.onContextMenu, viewready: this.onViewReady }, trackOver: true, cls: 'feed-list', itemSelector: '.feed-list-item', overItemCls: 'feed-list-item-hover', tpl: '<tpl for="."><div class="feed-list-item">{title}</div></tpl>' }); return this.view; }, onViewReady: function(){ this.view.getSelectionModel().select(this.view.store.first()); }, onSelectionChange: function(){ var selected = this.getSelectedItem(); // this.toolbar.getComponent('remove').setDisabled(!selected); this.loadFeed(selected); }, onLoadClick: function(){ this.loadFeed(this.menu.activeFeed); }, loadFeed: function(rec){ alert('click'); if (rec) { this.fireEvent('feedselect', this, rec.get('title'), rec.get('url')); } }, getSelectedItem: function(){ return this.view.getSelectionModel().getSelection()[0] || false; }, onContextMenu: function(view, index, el, event){ var menu = this.menu; event.stopEvent(); menu.activeFeed = view.store.getAt(index); menu.showAt(event.getXY()); } });
'use strict'; const isEmpty = require('lodash.isempty'); const aggregator = require('./aggregator'); module.exports = { open(context) { this.make = context.messageMaker('domains').make; // '*.requestCounts, 'domains.summary' context.filterRegistry.registerFilterForType([], 'domains.summary'); this.browsertime = false; }, processMessage(message, queue) { const make = this.make; switch (message.type) { case 'browsertime.setup': { this.browsertime = true; break; } case 'browsertime.har': { aggregator.addToAggregate(message.data, message.url); break; } case 'webpagetest.har': { // Only collect WebPageTest data if we don't run Browsertime if (this.browsertime === false) { aggregator.addToAggregate(message.data, message.url); } break; } case 'sitespeedio.summarize': { const summary = aggregator.summarize(); if (!isEmpty(summary)) { for (let group of Object.keys(summary.groups)) { queue.postMessage( make('domains.summary', summary.groups[group], { group }) ); } } break; } } } };
var hbs = require('handlebars'); var bluebird = require('bluebird'); var fs = bluebird.promisifyAll(require('fs')); var path = require('path'); var browserify = require('browserify'); var es = require('event-stream'); var _ = require('lodash'); var log = logger.child({module: 'views'}); var Cacher = require('../utils/cacher'); module.exports = function(pth, url) { assignHelpers(pth); var compiledHelpers = compileHelpers(pth); //Create our caches var cache = new Cacher.Multi(fetchTemplate.bind(null, pth), checkTemplate.bind(null, pth)); var layoutCache = new Cacher(fetchLayout.bind(null, pth), checkLayout.bind(null, pth)); //Render a specific view function* render(name, params) { var data; var self = this; var layout = yield layoutCache.get(); var template = yield cache.get(name); log.info({view: name, format: this.request.query.format}, 'Rendering view'); //Assign data based on the request type if(this.request.query.format) { var result = {}; if(this.request.query.format.indexOf('d') !== -1) { data = yield getData(); result.data = data.template; result.layoutData = data.layout; } if(this.request.query.format.indexOf('t') !== -1) { result.template = template.string; } this.body = result; } else { data = yield getData(); //Attach either the data or a rendered view this.body = layout.frame({ basepath: BASEPATH, body: layout.layout(_.merge({ body: template.compiled(_.merge(data.template, {layout: data.layout})) }, data.layout)) }); } function *getData() { var data = { layout: yield layout.fn.apply(self), template: yield template.fn.apply(self, params) }; data.layout.basepath = BASEPATH; return data; } } //Our middleware to attach a view return function* (next) { var redirect = this.redirect; //Monkeypatch redirect to preserve our format parameter this.redirect = function(path, alt) { redirect.call(this, path + (this.query.format ? '?format=' + this.query.format : ''), alt); }; this.view = render; this.set('Request-Path', this.path); if(this.path === url) { this.body = yield compiledHelpers; this.type = 'text/javascript'; } else if(this.path === '/' && this.query.format === 'l') { //Always send our layout if requested on our root path this.body = {layout: (yield layoutCache.get()).string}; } else { yield next; } }; }; //Compile our handlebars helpers from a specific path and then run them through browserify //Allows us to serve them to the client function compileHelpers(pth) { return new Promise(function(resolve, reject) { var filenames = fs.readdirSync(path.join(pth, 'helpers')); var contents = filenames.reduce(function(sum, name) { return sum + 'hbs.registerHelper("'+name.split('.')[0]+'", require("./'+name+'"));\n'; }, 'var hbs = require("handlebars");\n'); var b = browserify(es.readArray([contents]), {basedir: path.join(process.cwd(), pth, 'helpers')}); b.require('handlebars'); b.bundle(function(err, src) { if(err) { log.warn(err, 'Failed to compile handlebars helpers'); reject(err); } else { log.debug('Compiled helpers to be served to the client'); resolve(src); } }); }); } //Register our handlebars helpers function assignHelpers(pth) { var helpers = require('require-directory')(module, path.join('..', pth, 'helpers')); _.each(helpers, function(helper, name) { name = name.split('.')[0]; if(!hbs.helpers[name]) { hbs.registerHelper(name, helper); log.debug({name: name}, 'Loaded helper'); } }); } //Load a template from disk, compile and return it function *fetchTemplate(pth, name, prev) { var fn; log.debug({view: name}, 'Loading template.hbs from disk'); if(prev && prev.fn) { fn = prev.fn; } else { try { fn = require(path.join(process.cwd(), pth, name, 'data.js')); } catch(e) { if(e.code !== 'MODULE_NOT_FOUND') { throw e; } fn = function *() {}; } } var template = yield fs.readFileAsync(path.join(process.cwd(), pth, name, 'template.hbs'), 'utf8'); return { fn: fn, string: template, compiled: hbs.compile(template) }; } //Get the time for a template function *checkTemplate(pth, name) { var stats = yield fs.lstatAsync(path.join(process.cwd(), pth, name, 'template.hbs')); return stats.mtime; } //Load the layout from disk, function *fetchLayout(pth, prev) { var fn; if(prev && prev.fn) { fn = prev.fn; } else { try { fn = require(path.join(process.cwd(), pth, 'layout.js')); log.debug('layout.js loaded'); } catch(e) { fn = function(cb) {cb();}; log.debug('No layout.js file found'); } } log.debug('Reloading layout.hbs from disk'); log.debug('Reloading frame.hbs from disk'); var layout = yield fs.readFileAsync(path.join(process.cwd(), pth, 'layout.hbs'), 'utf8'); var frame = yield fs.readFileAsync(path.join(process.cwd(), pth, 'frame.hbs'), 'utf8'); return { fn: fn, string: layout, layout: hbs.compile(layout), frame: hbs.compile(frame) }; } //Get the last modified time of the layout function *checkLayout(pth) { var layout = fs.lstatAsync(path.join(process.cwd(), pth, 'layout.hbs')); var frame = fs.lstatAsync(path.join(process.cwd(), pth, 'frame.hbs')); return Math.max(layout.mtime, frame.mtime); }
import Ember from 'ember'; import Application from '../../app'; import config from '../../config/environment'; export default function startApp (attrs) { let application; let attributes = Ember.merge({}, config.APP); attributes = Ember.merge(attributes, attrs); Ember.run(() => { application = Application.create(attributes); application.setupForTesting(); application.injectTestHelpers(); }); return application; }
'use strict'; angular.module('users') .controller('LoadProfileCtrl', ['$scope', '$routeParams', function ($scope, $routeParams) { $scope.storage.save('token', $routeParams.token); $scope.$window.location.href = "/"; }]);
import { CHECK_VIDEO_DATA, ADD_VIDEO } from '../actions/miniBrowser' import React, { Component } from 'react' import { insertDoc } from '../api/pouchdb' const ls = window.require('local-storage') const initialMiniBrowserState = { checker_video_doc: null, checker_video_id: null } export function miniBrowserState(state = initialMiniBrowserState, action) { switch (action.type) { // 비디오 체크 case CHECK_VIDEO_DATA: return { ...state, checker_video_id: action.result.id, checker_video_doc: action.result } // 비디오 추가. case ADD_VIDEO: action.event.target.blur() const ignire = ls('Ignore_video_id') if (!state.checker_video_id) return state // 무시상태 체크. if (ignire == state.checker_video_id) { console.log('저장이 무시 됨.') return state } const ipcRenderer = window.require('electron').ipcRenderer const id = new Date().toISOString() const doc = state.checker_video_doc const video_id = state.checker_video_id const video = { _id: id, vid: doc.id, channelId: doc.channelId, description: doc.description, link: doc.link, kind: doc.kind, publishedAt: doc.publishedAt, thumbnails: doc.thumbnails, title: doc.title } insertDoc(video, (err, res) => { if (err) return console.log(err) console.log(res) ls('Ignore_video_id', video_id) ipcRenderer.send('리스트-새로고침', 0) }) return { ...state, checker_video_id: null, checker_video_doc: null } default: return state } }
// 登录校验 $.ajax({ type: 'GET', url: 'http://localhost:5000/api/session', dataType: 'json', success: function(data) { if (data == undefined || data.length == 0) { toastr.error('非法登录!'); window.location.href = 'login.html'; } else { add_note(data[0]); } } }); var noteSize = 0; $.ajax({ type: 'GET', url: 'http://localhost:5000/api/note', dataType: 'json', success: function(note) { $.ajax({ type: 'GET', url: 'http://localhost:5000/api/student', dataType: 'json', success: function(studentList) { var studentName = ''; var index = 0; var noteHTML = ''; note.map(function(noteItem) { noteSize++; if (index < 7) { index++; studentList.map(function(student) { if (student.id == noteItem.noterID) { studentName = student.name; } }); noteHTML += '<li>'; noteHTML += '<p>'; noteHTML += '<span>'; noteHTML += studentName; noteHTML += '</span>'; noteHTML += '<span>'; noteHTML += noteItem.noteTime.replace(/T/, ' '); noteHTML += '</span>'; noteHTML += '</p>'; noteHTML += '<p>'; noteHTML += noteItem.content; noteHTML += '</p>'; noteHTML += '</li>'; } }); $('#content').find('ul').html(noteHTML); } }) } }); function add_note(session) { $('form').validate({ submitHandler: function(form) { $.ajax({ type: 'POST', url: 'http://localhost:5000/api/note', headers: { 'Content-Type': 'application/json' }, data: JSON.stringify({ id: noteSize + 1, noterID: session.id, content: $('textarea').val(), noteTime: getTime(new Date()) }), dataType: 'json', success: function(data) { if (data > 0) { toastr.success('添加成功!'); } else { toastr.error('会话异常终止!'); } } }); } }); } function getTime(date) { if(date == null) { date = new Date(); } var y = date.getFullYear(); var M = date.getMonth() + 1; var d = date.getDate(); var h = date.getHours(); var m = date.getMinutes(); var s = date.getSeconds(); var html = y + "-"; if(M < 10) { html += "0"; } html += M + "-"; if(d < 10) { html += "0"; } html += d + " "; if(h < 10) { html += "0"; } html += h + ":"; if(m < 10) { html += "0"; } html += m + ":"; if(s < 10) { html += "0"; } html += s; return html; }
'use strict'; var pkg = require('inside')('package'); module.exports = require('express').Router() .use(require('./middleware/auth')) .use('/token', require('./token')) .use('/users', require('./user')) .get('/', function (req, res) { res.json({name: pkg.name, version: pkg.version}); }) .use(function (err, req, res, next) { if (!err) return next(); res.format({ json: function () { res.status(err.status || 500); if (!err.status) { console.error(err.stack); return res.json({name: 'InternalError', message: 'Oops! Something went wrong.'}); } res.json({ name : err.name, message : err.message, code : err.code }); } }); });
module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ (function(module, exports, __webpack_require__) { __webpack_require__(268); module.exports = __webpack_require__(268); /***/ }), /***/ 268: /***/ (function(module, exports) { (function( window, undefined ) { kendo.cultures["ne-IN"] = { name: "ne-IN", numberFormat: { pattern: ["-n"], decimals: 0, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n%","%n"], decimals: 0, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { name: "Indian Rupee", abbr: "INR", pattern: ["-$n","$n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "₹" } }, calendars: { standard: { days: { names: ["आइतवार","सोमवार","मङ्गलवार","बुधवार","बिहीवार","शुक्रवार","शनिवार"], namesAbbr: ["आइत","सोम","मङ्गल","बुध","बिही","शुक्र","शनि"], namesShort: ["आइत","सोम","मङ्गल","बुध","बिही","शुक्र","शनि"] }, months: { names: ["जनवरी","फरवरी","मार्च","अप्रेल","मई","जुन","जुलाई","अगस्त","सेप्टेम्बर","अक्टोबर","नोभेम्बर","दिसम्बर"], namesAbbr: ["जन","फेब","मार्च","अप्रि","मे","जुन","जुला","अग","सेप्ट","अक्टो","नोभे","डिसे"] }, AM: ["पूर्वाह्न","पूर्वाह्न","पूर्वाह्न"], PM: ["अपराह्न","अपराह्न","अपराह्न"], patterns: { d: "yyyy-MM-dd", D: "yyyy MMMM d, dddd", F: "yyyy MMMM d, dddd HH:mm:ss", g: "yyyy-MM-dd HH:mm", G: "yyyy-MM-dd HH:mm:ss", m: "MMMM d", M: "MMMM d", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "yyyy MMMM", Y: "yyyy MMMM" }, "/": "-", ":": ":", firstDay: 0 } } } })(this); /***/ }) /******/ });
// this is needed for hmr-redux-mapper to identify the reducer name used by these actions export const PRM_ACTION_FILE_FOR_REDUCER = 'store1'; export const action1 = {}; export const action2 = {};
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Voting Schema */ var VotingSchema = new Schema({ election: { type: String, default: '', required: '', trim: true }, voter: { type: String, default: '', required: '', trim: true }, choice: { type: String, default: '', required: '', trim: true }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Voting', VotingSchema);
'use strict'; var Pinkie = require('pinkie'); var PromishClass = require('../../lib/promish-class'); var PinkiePromish = PromishClass(Pinkie); var shpecs = require('../test-utils/shpecs'); var shpecList = [ 'all', 'any', 'apply', 'bluebird', 'call', 'catch', 'constructor', 'defer', 'delay', 'finally', 'map', 'method', 'promisify-all', 'race', 'reduce', 'reject', 'resolve', 'some', 'spread', 'then', ]; describe.only('PinkiePromish', function() { shpecs(PinkiePromish, shpecList); });
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import CourseConceptQuestion from 'app/components/Course/CourseConceptQuestion'; class CourseConceptDetail extends Component { render() { const { email, example, questions, rule, title } = this.props; return ( <div className="Course__concept-detail"> <div className="Course__section-title"> {title} </div> <div className="Course__concept-detail-rule"> {rule} </div> <div className="Course__concept-detail-example"> {example} </div> <div className="Course__concept-detail-questions"> <div className="Course__concept-detail-sub-title"> Practice questions </div> { email ? ( questions.map((item, index) => { return ( <CourseConceptQuestion key={index} number={index + 1} {...item} /> ); }) ) : ( <div className="Course__practice-questions-restricted"> <Link to="/buy"> <button className="Button Button--orange">Get access</button> to the practice questions! </Link> {/*<div className="Course__practice-questions-restricted-sample"> <CourseConceptQuestion number={1} {...questions[0]} isSample /> </div>*/} </div> ) } </div> </div> ); } } export default CourseConceptDetail;
'use strict'; var _isDirty = require('../isDirty'); var _isDirty2 = _interopRequireDefault(_isDirty); var _plain = require('../../structure/plain'); var _plain2 = _interopRequireDefault(_plain); var _expectations = require('../../structure/plain/expectations'); var _expectations2 = _interopRequireDefault(_expectations); var _immutable = require('../../structure/immutable'); var _immutable2 = _interopRequireDefault(_immutable); var _expectations3 = require('../../structure/immutable/expectations'); var _expectations4 = _interopRequireDefault(_expectations3); var _addExpectations = require('../../__tests__/addExpectations'); var _addExpectations2 = _interopRequireDefault(_addExpectations); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var describeIsDirty = function describeIsDirty(name, structure, expect) { var isDirty = (0, _isDirty2.default)(structure); var fromJS = structure.fromJS; var getIn = structure.getIn; describe(name, function () { it('should return a function', function () { expect(isDirty('foo')).toBeA('function'); }); it('should return false when values not present', function () { expect(isDirty('foo')(fromJS({ form: {} }))).toBe(false); }); it('should return false when values are pristine', function () { expect(isDirty('foo')(fromJS({ form: { foo: { initial: { dog: 'Snoopy', cat: 'Garfield' }, values: { dog: 'Snoopy', cat: 'Garfield' } } } }))).toBe(false); }); it('should return true when values are dirty', function () { expect(isDirty('foo')(fromJS({ form: { foo: { initial: { dog: 'Snoopy', cat: 'Garfield' }, values: { dog: 'Odie', cat: 'Garfield' } } } }))).toBe(true); }); it('should use getFormState if provided', function () { expect(isDirty('foo', function (state) { return getIn(state, 'someOtherSlice'); })(fromJS({ someOtherSlice: { foo: { initial: { dog: 'Snoopy', cat: 'Garfield' }, values: { dog: 'Odie', cat: 'Garfield' } } } }))).toBe(true); }); }); }; describeIsDirty('isDirty.plain', _plain2.default, (0, _addExpectations2.default)(_expectations2.default)); describeIsDirty('isDirty.immutable', _immutable2.default, (0, _addExpectations2.default)(_expectations4.default));
// (function () { // Handlebars.registerHelper('index_i18n', function () { // return "sitesIndex_" + TAPi18n.getLanguage(); // }); // })(); Template.sitesIndex.helpers({ }); console.log('worrked')
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose');
try{ //we are always under /admin/ history.replaceState({}, "Admin Interface", "/admin/"); try{ $(document.getElementsByName("allowedEmails")).each(function(){ //create tokenfields var me = $(this); me.tokenfield().closest("form").on("submit", function(){ //disable them just in time for form submission me.tokenfield("destroy"); }); }); } catch(e){} } catch(e){}
// FIRST TIME ONLY- run: // ./node_modules/.bin/webdriver-manager update // // Try: `npm run webdriver:update` // // AND THEN EVERYTIME ... // 1. Compile with `tsc` // 2. Make sure the test server (e.g., http-server: localhost:8080) is running. // 3. ./node_modules/.bin/protractor protractor.config.js // // To do all steps, try: `npm run e2e` var fs = require('fs'); var path = require('canonical-path'); var _ = require('lodash'); exports.config = { directConnect: true, // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'chrome' }, // Framework to use. Jasmine is recommended. framework: 'jasmine', // For angular tests useAllAngular2AppRoots: true, // Base URL for application server baseUrl: 'http://localhost:8080', // doesn't seem to work. // resultJsonOutputFile: "foo.json", onPrepare: function() { //// SpecReporter //var SpecReporter = require('jasmine-spec-reporter'); //jasmine.getEnv().addReporter(new SpecReporter({displayStacktrace: 'none'})); //// jasmine.getEnv().addReporter(new SpecReporter({displayStacktrace: 'all'})); // debugging // console.log('browser.params:' + JSON.stringify(browser.params)); var appDir = browser.params.appDir; if (appDir) { if (appDir.match('/ts') != null) { browser.appIsTs = true; } else if (appDir.match('/js') != null) { browser.appIsJs = true; } else if (appDir.match('/dart') != null) { browser.appIsDart = true; } else { browser.appIsUnknown = true; } } else { browser.appIsUnknown = true; } jasmine.getEnv().addReporter(new Reporter( browser.params )) ; global.describeIf = describeIf; global.itIf = itIf; global.sendKeys = sendKeys; // Allow changing bootstrap mode to NG1 for upgrade tests global.setProtractorToNg1Mode = function() { browser.useAllAngular2AppRoots = false; browser.rootEl = 'body'; var disableNgAnimate = function() { angular.module('disableNgAnimate', []).run(['$animate', function($animate) { $animate.enabled(false); }]); }; browser.addMockModule('disableNgAnimate', disableNgAnimate); }; }, jasmineNodeOpts: { // defaultTimeoutInterval: 60000, defaultTimeoutInterval: 10000, showTiming: true, print: function() {} }, beforeLaunch: function() { // add TS support for specs require('ts-node').register(); } }; function describeIf(cond, name, func) { if (cond) { describe(name, func); } else { xdescribe(name, func); } } function itIf(cond, name, func) { if (cond) { it(name, func); } else { xit(name, func); } } // Hack - because of bug with protractor send keys // Hack - because of bug with send keys function sendKeys(element, str) { return str.split('').reduce(function (promise, char) { return promise.then(function () { return element.sendKeys(char); }); }, element.getAttribute('value')); // better to create a resolved promise here but ... don't know how with protractor; } // See http://jasmine.github.io/2.1/custom_reporter.html function Reporter(options) { var _defaultOutputFile = path.resolve(process.cwd(), "../../../../", 'protractor-results.txt'); options.outputFile = options.outputFile || _defaultOutputFile; var _root = { appDir: options.appDir, suites: [] }; log('AppDir: ' + options.appDir, +1); var _currentSuite; this.suiteStarted = function(suite) { _currentSuite = { description: suite.description, status: null, specs: [] }; _root.suites.push(_currentSuite); log('Suite: ' + suite.description, +1); }; this.suiteDone = function(suite) { var statuses = _currentSuite.specs.map(function(spec) { return spec.status; }); statuses = _.uniq(statuses); var status = statuses.indexOf('failed') >= 0 ? 'failed' : statuses.join(', '); _currentSuite.status = status; log('Suite ' + _currentSuite.status + ': ' + suite.description, -1); }; this.specStarted = function(spec) { }; this.specDone = function(spec) { var currentSpec = { description: spec.description, status: spec.status }; if (spec.failedExpectations.length > 0) { currentSpec.failedExpectations = spec.failedExpectations; } _currentSuite.specs.push(currentSpec); log(spec.status + ' - ' + spec.description); if (spec.status === 'failed') { spec.failedExpectations.forEach(function(err) { log(err.message); }); } }; this.jasmineDone = function() { outputFile = options.outputFile; //// Alternate approach - just stringify the _root - not as pretty //// but might be more useful for automation. // var output = JSON.stringify(_root, null, 2); var output = formatOutput(_root); fs.appendFileSync(outputFile, output); }; // for output file output function formatOutput(output) { var indent = ' '; var pad = ' '; var results = []; results.push('AppDir:' + output.appDir); output.suites.forEach(function(suite) { results.push(pad + 'Suite: ' + suite.description + ' -- ' + suite.status); pad+=indent; suite.specs.forEach(function(spec) { results.push(pad + spec.status + ' - ' + spec.description); if (spec.failedExpectations) { pad+=indent; spec.failedExpectations.forEach(function (fe) { results.push(pad + 'message: ' + fe.message); }); pad=pad.substr(2); } }); pad = pad.substr(2); results.push(''); }); results.push(''); return results.join('\n'); } // for console output var _pad; function log(str, indent) { _pad = _pad || ''; if (indent == -1) { _pad = _pad.substr(2); } console.log(_pad + str); if (indent == 1) { _pad = _pad + ' '; } } }
(function (ns, $) { "use strict"; if (ns.Extensions.Handlers.RemoveSkipLinks) return; ns.Extensions.Handlers.RemoveSkipLinks = function () { var _init = function () { var desc = $(this).find("#u1st_Skip-links"); if (desc) { $("#u1st_Skip-links").remove(); } }, handler = { handle: function () { _init(); }, dispose: function () { } }; return handler; }; ns.Extensions.Extesion.addHandler("RemoveSkipLinks", ns.handlerTarget.page, 20000, null, null, ns.Extensions.Handlers.RemoveSkipLinks.handle, ns.Extensions.Handlers.RemoveSkipLinks.dispose, null); })(User1st.Web, uf$);
var searchData= [ ['match_5fparser_2ecpp',['match_parser.cpp',['../match__parser_8cpp.html',1,'']]], ['match_5fparser_2ehpp',['match_parser.hpp',['../match__parser_8hpp.html',1,'']]] ];
#! /usr/bin/env node var spawn = require('child_process').spawn; var PUsage = require('./lib/pusage.js'); var fs = require('fs'); module.exports = PUsage; if (require.main !== module) return; var optimist = require('optimist') .usage('Usage: $0 [OPTIONS] <PID|PROCESS_NAME>...') .alias('h', 'help') .describe('h', 'Display this message.') .alias('i', 'interval') .describe('i', 'Polling interval (ms) for gathering stats.') .default('i', 500) .alias('e', 'execute') .describe('e', 'Execute a command and monitor its system usage.') .default('e', false) .alias('o', 'outfile') .describe('o', 'File to write to. Defaults to stdout.') .default('o', '-'); var argv = optimist.argv; if (argv.help || (argv._.length < 1 && !argv.e)) { optimist.showHelp(); process.exit(); } var opts = { interval: argv.interval }; if (argv.outfile === '-') opts.logStream = process.stdout; else opts.logFile = argv.outfile; var toWatch = []; if (argv.e) { var args = argv.e.split(' '); var child = spawn(args.shift(), args); toWatch.push(child.pid); child.stdout.pipe(fs.createWriteStream('/dev/null')); child.on('exit', process.exit); } var proc; for (var i = 0; (proc = argv._[i]); i++) { if (parseInt(proc, 10).toString() === proc) proc = parseInt(proc, 10); toWatch.push(proc); } var pusage = PUsage(opts); toWatch.forEach(function(proc) { pusage.watch(proc); });
// Testacular configuration // base path, that will be used to resolve files and exclude basePath = ''; // list of files / patterns to load in the browser files = [ JASMINE, JASMINE_ADAPTER, 'app/scripts/vendor/angular.js', 'test/lib/angular-mocks.js', 'app/scripts/*.js', 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ]; // list of files to exclude exclude = [ ]; // test results reporter to use // possible values: dots || progress reporter = 'progress'; // web server port port = 8080; // cli runner port runnerPort = 9100; // enable / disable colors in the output (reporters and logs) colors = true; // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel = LOG_INFO; // enable / disable watching file and executing tests whenever any file changes autoWatch = false; // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari // - PhantomJS browsers = ['PhantomJS']; // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun = false;
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Settings = mongoose.model('Setting'), _ = require('lodash'); exports.index = function(req, res) { res.render('index', { user: req.user || null, request: req }); }; exports.saveSetting = function(req, res) { var setting = new Settings(req.body); setting.save(function(err, reSetting){ if(err) { return res.status(500).send({ message: errorHandler.getErrorMessage(err) }); } return res.json(reSetting); }); } var initSetting = function(settingName, settingValue) { console.log("initializing setting"); var setting = new Settings({ name: settingName, value: settingValue }); setting.save(); }; exports.changeSetting = function(req, res) { //console.log(JSON.stringify(req.query)); if(req.query.settingName && req.query.settingValue) //single setting { var settingName = req.query.settingName; var settingValue = req.query.settingValue; //console.log('saving setting: '+settingName+' val: '+settingValue); Settings.update( {name: settingName}, {$set: {value: settingValue}}, {}, function(err, rowsAffected) { //console.log('updated '+rowsAffected); }); Settings.findOne({name: settingName}).exec(function(err,setting){ if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else if(!setting) { initSetting(settingName, settingValue); } else { res.json(setting); } }); } else { //else return all settings, not implemented res.json({}); } }; exports.getSettings = function(req, res) { if(req.query.settingName) //single setting { var settingName = req.query.settingName; Settings.findOne({name: settingName}).exec(function(err,setting){ if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { //console.log("sending setting " + JSON.stringify(setting)); return res.json(setting); } }); } else if(req.query.category) //single category { Settings.find({category: req.query.category}).exec(function(err,settings){ if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { //console.log("sending setting " + JSON.stringify(setting)); return res.json(settings); } }); } else { //else return all settings, not implemented return res.status(500).send({ message: 'not implemented' }); } }; exports.updateSetting = function(req, res) { var setting = req.setting; setting = _.extend(setting, req.body); setting.save(function(err, updated) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { return res.json(updated); } }); } exports.deleteSetting = function(req, res) { var setting = req.setting; setting.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.status(200).send({ message: 'setting deleted' }); } }); }; exports.settingByID = function(req, res, next, id) { Settings.findById(id).exec(function(err, setting) { if (err) return next(err); if (!setting) return next(new Error('Failed to load setting ' + id)); req.setting = setting; next(); }); };
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.enterMode = CKEDITOR.ENTER_BR; config.shiftEnterMode = CKEDITOR.ENTER_P; };
'use strict'; var React = require('react/addons'); var DocumentTitle = require('react-document-title'); module.exports = React.createClass({ render: function() { return ( <DocumentTitle title="404: Not Found"> <h1> not found page </h1> </DocumentTitle> ); } });
var config = require("../../lib/config")() , statsEngine = require("../../lib/stats") , MongoClient = require("mongodb").MongoClient , dummyStats = require("../../lib/dummy-stats") , async = require("async") , expect = require("chai").expect , _ = require("underscore") ; describe("Database Stats", function() { var db, stats; before(function(done) { var dbURI, dbName = "t"+(new Date()).getTime(); dbURI = "mongodb://"+config.getMongoServer(); dbURI +="/"+dbName; async.waterfall([ function(next) { MongoClient.connect(dbURI,next); }, function(dbIn,next) { db = dbIn; var statsEngines = { dummyStats1:dummyStats(), dummyStats2:dummyStats() }; stats = statsEngine(db,statsEngines); next(); } ],done); }); after(function(done) { async.waterfall( [ function(next) { db.dropDatabase(next); } ],done); }); it("should be able to add a stat", function(done) { async.waterfall( [ function(next) { stats.addResult({winner:["player1"],loser:["player2"],margin:3},next); }, function(results,next) { ["dummyStats1","dummyStats2"].forEach(function(key) { expect(results).to.include.keys(key); expect(_.findWhere(results[key],{name:"player1",rank:3})).to. be.ok; expect(_.findWhere(results[key],{name:"player2",rank:-3})).to. be.ok; }); stats.getStats(next); }, function(results,next) { ["dummyStats1","dummyStats2"].forEach(function(key) { expect(results).to.include.keys(key); expect(results[key].name).to.be.equal("Test Stats"); expect(results[key].description).to.be.equal( "Test Stats Description"); expect(_.findWhere(results[key].stats,{name:"player1",rank:3})).to. be.ok; expect(_.findWhere(results[key].stats,{name:"player2",rank:-3})).to. be.ok; }); next(); }, ],done); }); it("should be able to update the stats", function(done) { async.waterfall( [ function(next) { stats.addResult({winner:["player3"],loser:["player4"],margin:30},next); }, function(results,next) { ["dummyStats1","dummyStats2"].forEach(function(key) { expect(results).to.include.keys(key); expect(_.findWhere(results[key],{name:"player3",rank:30})).to. be.ok; expect(_.findWhere(results[key],{name:"player4",rank:-30})).to. be.ok; }); stats.addResult({winner:["player4"],loser:["player3"],margin:3},next); }, function(results,next) { ["dummyStats1","dummyStats2"].forEach(function(key) { expect(results).to.include.keys(key); expect(_.findWhere(results[key],{name:"player3",rank:27})).to. be.ok; expect(_.findWhere(results[key],{name:"player4",rank:-27})).to. be.ok; }); stats.getStats(next); }, function(results,next) { ["dummyStats1","dummyStats2"].forEach(function(key) { expect(results).to.include.keys(key); expect(results[key].name).to.be.equal("Test Stats"); expect(results[key].description).to.be.equal( "Test Stats Description"); expect(_.findWhere(results[key].stats,{name:"player3",rank:27})).to. be.ok; expect(_.findWhere(results[key].stats,{name:"player4",rank:-27})).to. be.ok; }); next(); }, ],done); }); });
var counter = require('../utils/counter') module.exports = function(app) { return { get: function(req, res, next) { res.send({tipbox: counter.getCounter('tipbox'), tip: counter.getCounter('tip')}); } } };
module.exports = [{ input : [2736], output : 7236 }, { input : [9973], output : 9973 }];
import 'bootstrap'; export function configure(aurelia) { aurelia.use .standardConfiguration() .globalResources([ 'filter-array' ]) .developmentLogging(); aurelia.start().then(a => a.setRoot()); }
'use strict'; jest.dontMock('../../scripts/pages/BackupRestore.js'); jest.mock('../../scripts/stores/BackupStore.js'); jest.mock('../../scripts/stores/WorkoutStore.js'); jest.mock('../../scripts/stores/ExerciseStore.js'); jest.mock('../../scripts/stores/TrainingStore.js'); jest.mock('../../scripts/actions/BackupStoreActionCreators.js'); jest.mock('../../scripts/actions/AppStateActionCreators.js'); let React = require('react/addons'), Immutable = require('immutable'), BackupStoreActionCreators = require('../../scripts/actions/BackupStoreActionCreators.js'), AppStateActionCreators = require('../../scripts/actions/AppStateActionCreators.js'), BackupStore = require('../../scripts/stores/BackupStore.js'), WorkoutStore = require('../../scripts/stores/WorkoutStore.js'), ExerciseStore = require('../../scripts/stores/ExerciseStore.js'), TrainingStore = require('../../scripts/stores/TrainingStore.js'), BackupRestore = require('../../scripts/pages/BackupRestore.js'); let TestUtils = React.addons.TestUtils; window.requestFileSystem = true; describe("BackupRestore", () => { var backupRestore; beforeEach(() => { BackupStore.getBackups.mockImplementation(() => { return Immutable.fromJS([ ]); }); backupRestore = TestUtils.renderIntoDocument(<BackupRestore />); }); afterEach(() => { BackupStore.getBackups.mockClear(); backupRestore.componentWillUnmount(); AppStateActionCreators.openModal.mockClear(); }); it("renders a Backup/Restore Page", () => { expect(TestUtils.isCompositeComponent(backupRestore)).toEqual(true); expect(backupRestore.getDOMNode().className).toEqual('page backup'); }); it("renders a feature unavailability page on desktop", () => { window.requestFileSystem = false; backupRestore = TestUtils.renderIntoDocument(<BackupRestore />); expect(backupRestore.getDOMNode().className).toEqual('page backup disabled'); window.requestFileSystem = true; }); it("shows a loading indicator if it is loading", () => { BackupStore.getLoading.mockImplementation(() => { return true; }); backupRestore = TestUtils.renderIntoDocument(<BackupRestore />); expect(TestUtils.findRenderedDOMComponentWithClass(backupRestore, 'loading')).not.toBeUndefined(); }); it("gets the backups on change", () => { backupRestore._onChange(); expect(BackupStore.getBackups.mock.calls.length).toBe(2); }); describe("handleBackup", () => { it("calls addBackup with the current data", () => { backupRestore.handleBackup(); expect(ExerciseStore.getExercises.mock.calls.length).toBe(1); expect(TrainingStore.getTrainings.mock.calls.length).toBe(1); expect(WorkoutStore.getWorkouts.mock.calls.length).toBe(1); expect(BackupStoreActionCreators.addBackup.mock.calls.length).toBe(1); }); }); describe("handleRestore", () => { it("opens a modal and shows a dialog for restoring a backup", () => { backupRestore.handleRestore(null, {label: 'helloBackup'}); expect(AppStateActionCreators.openModal.mock.calls.length).toBe(1); }); it("closes the modal and restores the Backup", () => { backupRestore.handleRestoreClick({label: 'helloBackup'}); expect(AppStateActionCreators.closeModal.mock.calls.length).toBe(1); expect(BackupStoreActionCreators.restoreFromBackup.mock.calls.length).toBe(1); }); }); });
$.post($('#resend-email').data('url')); $('#resend-email').on('click', function () { $("#email-sending").show(); $("#email-send-success").hide(); $.post($(this).data('url'), function (json) { }, 'json').complete(function () { $("#email-sending").hide(); $("#email-send-success").show(); }); });
'use strict'; const mongoose = require('mongoose'); const toolSchema = mongoose.Schema({ ownerId: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'user'}, serialNumber: {type: Number}, toolName: {type: String, required: true}, toolDescription: {type: String, required: true}, toolInstructions: {type: String}, picURI: {type: String}, category: {type: String, required: true}, isCheckedOut: {type: Boolean, default: false}, }); module.exports = mongoose.model('tool', toolSchema);
(function (global, factory) { if (typeof define === 'function' && define.amd) { define(['exports', './internal/deprecation'], factory); } else if (typeof exports !== 'undefined') { factory(exports, require('./internal/deprecation')); } else { var mod = { exports: {} }; factory(mod.exports, global.deprecation); global.cssDeprecationWarnings = mod.exports; } })(this, function (exports, _internalDeprecation) { 'use strict'; (0, _internalDeprecation.css)('.aui-dropdown2-trigger.aui-style-dropdown2triggerlegacy1', { displayName: 'Dropdown2 legacy trigger' }); (0, _internalDeprecation.css)('.aui-message span.aui-icon', { displayName: 'Message icon span' }); (0, _internalDeprecation.css)('.aui-zebra', { displayName: 'Zebra table rows' }); (0, _internalDeprecation.css)('.aui-nav-pagination > li.aui-nav-current', { alternativeName: 'aui-nav-selected' }); (0, _internalDeprecation.css)('.aui-tabs.vertical-tabs', { displayName: 'Vertical tabs' }); (0, _internalDeprecation.css)('form.aui span.content'); (0, _internalDeprecation.css)(['form.aui .button', 'form.aui .buttons-container'], { displayName: 'Unprefixed buttons', alternativeName: 'aui-button and aui-buttons' }); (0, _internalDeprecation.css)(['form.aui .icon-date', 'form.aui .icon-range', 'form.aui .icon-help', 'form.aui .icon-required', 'form.aui .icon-inline-help', 'form.aui .icon-users', '.aui-icon-date', '.aui-icon-range', '.aui-icon-help', '.aui-icon-required', '.aui-icon-users', '.aui-icon-inline-help'], { displayName: 'Form icons' }); (0, _internalDeprecation.css)(['.aui-icon.icon-move-d', '.aui-icon.icon-move', '.aui-icon.icon-dropdown-d', '.aui-icon.icon-dropdown', '.aui-icon.icon-dropdown-active-d', '.aui-icon.icon-dropdown-active', '.aui-icon.icon-minimize-d', '.aui-icon.icon-minimize', '.aui-icon.icon-maximize-d', '.aui-icon.icon-maximize'], { displayName: 'Core icons' }); (0, _internalDeprecation.css)(['.aui-message.error', '.aui-message.warning', '.aui-message.hint', '.aui-message.info', '.aui-message.success'], { displayName: 'Unprefixed message types AUI-2150' }); (0, _internalDeprecation.css)(['.aui-dropdown2 .active', '.aui-dropdown2 .checked', '.aui-dropdown2 .disabled', '.aui-dropdown2 .interactive'], { displayName: 'Unprefixed dropdown2 css AUI-2150' }); (0, _internalDeprecation.css)(['aui-page-header-marketing', 'aui-page-header-hero'], { displayName: 'Marketing style headings' }); }); //# sourceMappingURL=../../js/aui/css-deprecation-warnings.js.map
/*jslint node: true */ "use strict"; var utils = require("../utils"); var log = require("npmlog"); module.exports = function(mergeWithDefaults, api, ctx) { return function sendSticker(sticker_id, thread_id, callback) { if(!callback) callback = function() {}; if (typeof sticker_id !== "number" && typeof sticker_id !== "string") return callback({error: "Sticker_id should be of type number or string and not " + typeof msg + "."}); if (typeof thread_id !== "number" && typeof thread_id !== "string") return callback({error: "Thread_id should be of type number or string and not " + typeof thread_id + "."}); var form = mergeWithDefaults({ 'client' : 'mercury', 'message_batch[0][action_type]' : 'ma-type:user-generated-message', 'message_batch[0][author]' : 'fbid:' + ctx.userId, 'message_batch[0][timestamp]' : Date.now(), 'message_batch[0][timestamp_absolute]' : 'Today', 'message_batch[0][timestamp_relative]' : utils.genTimestampRelative(), 'message_batch[0][timestamp_time_passed]' : '0', 'message_batch[0][is_unread]' : false, 'message_batch[0][is_cleared]' : false, 'message_batch[0][is_forward]' : false, 'message_batch[0][is_filtered_content]' : false, 'message_batch[0][is_spoof_warning]' : false, 'message_batch[0][source]' : 'source:chat:web', 'message_batch[0][source_tags][0]' : 'source:chat', 'message_batch[0][body]' : '', 'message_batch[0][html_body]' : false, 'message_batch[0][ui_push_phase]' : 'V3', 'message_batch[0][status]' : '0', 'message_batch[0][message_id]' : utils.generateMessageID(ctx.clientid), 'message_batch[0][manual_retry_cnt]' : '0', 'message_batch[0][thread_fbid]' : thread_id, 'message_batch[0][sticker_id]' : sticker_id, 'message_batch[0][has_attachment]' : true, 'message_batch[0][client_thread_id]' : "user:"+thread_id, 'message_batch[0][signatureID]' : utils.getSignatureId() }); api.getUserInfo(thread_id, function(err, res) { // This means that thread_id is the id of a user, and the chat // is a single person chat if(!(res instanceof Array)) { form['message_batch[0][client_thread_id]'] = "user:"+thread_id; form['message_batch[0][specific_to_list][0]'] = "fbid:"+thread_id; form['message_batch[0][specific_to_list][1]'] = "fbid:"+ctx.userId; } if(ctx.globalOptions.pageId) { form['message_batch[0][author]'] = "fbid:" + ctx.globalOptions.pageId; form['message_batch[0][specific_to_list][1]'] = "fbid:" + ctx.globalOptions.pageId; form['message_batch[0][creator_info][creatorID]'] = ctx.userId; form['message_batch[0][creator_info][creatorType]'] = "direct_admin"; // form['message_batch[0][creator_info][creatorName]'] = Marc Zuckerbot form['message_batch[0][creator_info][labelType]'] = "sent_message"; form['message_batch[0][creator_info][pageID]'] = ctx.globalOptions.pageId; form['request_user_id'] = ctx.globalOptions.pageId; form['message_batch[0][creator_info][profileURI]'] = "https://www.facebook.com/profile.php?id=" + ctx.userId; } utils.post("https://www.facebook.com/ajax/mercury/send_messages.php", ctx.jar, form) .then(utils.parseResponse) .then(function(resData) { if (!resData) return callback({error: "Send message failed."}); if(resData.error) return callback(resData); callback(); }) .catch(function(err) { log.error("ERROR in sendSticker --> ", err); return callback(err); }); }); }; };
import Ember from 'ember'; export default Ember.Controller.extend({ application: Ember.inject.controller('application'), isSaving: false, actions: { save(skill) { this.set('isSaving', true); skill.save({ adapterOptions: { meta: { filename: skill.get('filename'), sequence_delete: skill.get('sequence_delete') } } }).then(() => { this.set('isSaving', false); this.get('application').send('reload'); this.transitionToRoute('skill', skill.get('slug')); }, (failure) => { this.set('isSaving', false); console.log('something went wrong'); console.log(failure); }); } } });
/** * el.js v0.3 - A JavaScript Node Creation Tool * * https://github.com/markgandolfo/el.js * * Copyright 2013 Mark Gandolfo and other contributors * Released under the MIT license. * http://en.wikipedia.org/wiki/MIT_License */ window.el = (function () { var el = function(tagName, attrs, child) { // Pattern to match id & class names var pattern = /([a-z]+|#[\w-\d]+|\.[\w\d-]+)/g if(arguments.length === 2) { if(attrs instanceof Array || typeof attrs === 'function' || typeof attrs === 'string' || attrs.constructor !== Object ) { child = attrs; attrs = undefined; } } // does the user pass attributes in, if not set an empty object up attrs = typeof attrs !== 'undefined' ? attrs : {}; child = typeof child !== 'undefined' ? child : []; child = child instanceof Array ? child : [child]; // run the pattern over the tagname in an attempt to pull out class & id attributes // shift the first record out as it's the element name matched = tagName.match(pattern); tagName = matched[0]; matched.shift(); // Iterate over the matches and concat the attrs to either class or id keys in attrs json object for (var m in matched) { if(matched[m][0] == '.') { if(attrs['class'] == undefined) { attrs['class'] = matched[m].substring(1, matched[m].length); } else { attrs['class'] = attrs['class'] + ' ' + matched[m].substring(1, matched[m].length); } } else if(matched[m][0] == '#') { if(attrs['id'] == undefined) { attrs['id'] = matched[m].substring(1, matched[m].length) } else { // Feels dirty having multiple id's, but it's allowed: http://www.w3.org/TR/selectors/#id-selectors attrs['id'] = attrs['id'] + ' ' + matched[m].substring(1, matched[m].length); } } } // create the element var el = document.createElement(tagName); for(var i = 0; i < child.length; i += 1) { (function(child){ switch(typeof child) { case 'object': el.appendChild(child); break; case 'function': var discardDoneCallbackResult = false; var doneCallback = function doneCallback(content) { if (!discardDoneCallbackResult) { el.appendChild(content); } } var result = child.apply(null, [doneCallback]) if(typeof result != 'undefined') { discardDoneCallbackResult = true; el.appendChild(result); } break; case 'string': el.appendChild(document.createTextNode(child)); default: //??? } }(child[i])); } for (var key in attrs) { if (attrs.hasOwnProperty(key)) { el.setAttribute(key, attrs[key]); } } return el; }; // alias el.create = el.c = el; // vanity methods el.img = function(attrs) { return this.create('img', attrs); }; el.a = function(attrs, child) { return this.create('a', attrs, child); }; el.div = function(attrs, child) { return this.create('div', attrs, child); }; el.p = function(attrs, child) { return this.create('p', attrs, child); }; el.input = function(attrs, child) { return this.create('input', attrs); }; return el; }());
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _basic = require('./basic'); var _basic2 = _interopRequireDefault(_basic); var _mono = require('./mono'); var _mono2 = _interopRequireDefault(_mono); var _dark = require('./dark'); var _dark2 = _interopRequireDefault(_dark); var _biblio = require('./biblio'); var _biblio2 = _interopRequireDefault(_biblio); var _hello = require('./hello'); var _hello2 = _interopRequireDefault(_hello); var _pink = require('./pink'); var _pink2 = _interopRequireDefault(_pink); var _bold = require('./bold'); var _bold2 = _interopRequireDefault(_bold); var _blue = require('./blue'); var _blue2 = _interopRequireDefault(_blue); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { basic: _basic2.default, mono: _mono2.default, dark: _dark2.default, biblio: _biblio2.default, hello: _hello2.default, pink: _pink2.default, bold: _bold2.default, blue: _blue2.default };
(function() { var app = angular.module('findFilm', []); // AIzaSyDDRFC6h1sm7wS3tOxUQNXOA82xnU5auh4 app.directive('filmForm', function(){ return { restrict : 'E', templateUrl : 'film-form.html' }; }); app.controller('SubmitFilmController', ['$http', 'filmGlobal', function($http, filmGlobal){ var film = {}; var titleG = filmGlobal.title; this.findFilm = function(film) { this.ajaxCall(film); }; this.ajaxCall = function(film, Scopes) { var filmObj = this; filmObj.details = []; $http.get('http://www.omdbapi.com/?t='+film.title+'&y=&plot=full&r=json').success(function(data){ filmObj.details = data; filmObj.details.show = true; filmGlobal.title = film.title; filmGlobal.show = filmObj.details.show; }); } }]); app.factory('filmGlobal', function ($rootScope) { var filmG = { title : '', show : false }; return filmG; }); app.controller('NetflixController', ['$http', 'filmGlobal', function($http, filmGlobal){ var netflix = {}; //var titleG = filmGlobal.title; this.show = true; this.netflixCheck = function(){ this.show = true; var titleG = filmGlobal.title; //console.log(Scopes.get('SubmitFilmController', filmObj)); //var filmTitle = angular.element(document.getElementById("filmTitle").innerHTML); var netflixObj = this; netflixObj.details = []; $http.get('http://netflixroulette.net/api/api.php?title='+titleG) .success(function(data){ netflixObj.details = data; netflixObj.details.show = true; }); }; }]); app.controller('CinemaController', ['$http', 'filmGlobal', function($http, filmGlobal){ var cinema = {}; //var titleG = filmGlobal.title; this.cinemaCheck = function(){ var titleG = filmGlobal.title; //console.log(Scopes.get('SubmitFilmController', filmObj)); //var filmTitle = angular.element(document.getElementById("filmTitle").innerHTML); var cinemaObj = this; cinemaObj.details = []; $http.get('http://www.cinetecadibologna.it/api/GetSchedule') .success(function(data){ cinemaObj.details = data; }); }; }]); app.directive('youtubeTrailer', function(){ return { restrict : 'E', templateUrl : 'trailer.html' }; }); app.controller('YoutubeTrailer', ['filmGlobal', function(filmGlobal){ this.videoStart = function(){ var query = filmGlobal.title + ' trailer'; var video = gapi.client.youtube.search.list({ part: "snippet", type: "video", q: query, maxResults: 1 }); video.execute(function(response) { console.log(response); this.id = response.items[0].id.videoId; this.iframe = '<iframe class="video w100" width="100%" height="360" src="//www.youtube.com/embed/'+this.id+'" frameborder="0" allowfullscreen></iframe>'; $('.trailer').append(this.iframe); /* $.each(results.items, function(index, item) { $.get("tpl/item.html", function(data) { $("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId}])); }); }); console.warn(response);*/ }); } }]); })();
var object = require("cloud/object.js"); /** * Checks the existence of a specific object * @param {String} objectName * @param {String} objectId * @return {Promise} */ var needs = function(objectName, objectId) { var promise = new Parse.Promise(); var query = new Parse.Query(object[objectName]); query .get(objectId) .then(function(object) { promise.resolve(object); }, function() { promise.reject(); }); return promise; }; exports.Product = function(productId){ return needs("Product", productId); }; exports.User = function(userId){ return needs("User", userId); };
angular.module('myApp.apiInterfaceSrv', []) .service('apiInterfaceSrv', function($rootScope, productsSrv, modalSrv){ var apiInterface = { items:[], fetch: function() { productsSrv.fetch(function (dataResponse) { apiInterface.items = dataResponse.data; }) }, add: function(){ modalSrv.show('components/modal/modal-add-product-tpl.html', null, 'lm', function (model) { var product = _.pick(model, 'title', 'description', 'price', 'img'); productsSrv.add(product, function (responseData) { apiInterface.items.unshift(responseData.data); }); }) }, update: function (item) { productsSrv.update(item, function () { $rootScope.common.unsaved = false; }); }, delete: function (item) { modalSrv.show('components/modal/modal-remove-product-tpl.html', null, 'sm', function (model) { productsSrv.delete({id: item.id}, function(dataResponse){ if(dataResponse.status){ apiInterface.items = _.without(apiInterface.items, _.findWhere(apiInterface.items, {id: item.id})); $timeout(function() { alert('element: ' + item.title + ' został usunięty z powodu:\n' + model.reason); }) } }) }) } } return apiInterface; })
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var util_1 = require("../../../util/util"); /** * Created by yefs on 2017/7/11. * 原生存储 * */ var StorageNative = (function () { function StorageNative() { } StorageNative.prototype.saveObject = function (key, value) { localStorage.setItem(key, util_1.stringify(value)); }; StorageNative.prototype.getObject = function (key, defaule) { var value = localStorage.getItem(key); if (value) { value = JSON.parse(value); } else { value = defaule; } return value; }; return StorageNative; }()); StorageNative.decorators = [ { type: core_1.Injectable }, ]; /** @nocollapse */ StorageNative.ctorParameters = function () { return []; }; exports.StorageNative = StorageNative;
// images-model.js - A mongoose model // // See http://mongoosejs.com/docs/models.html // for more of what you can do here. module.exports = function (app) { const mongooseClient = app.get('mongooseClient'); const images = new mongooseClient.Schema({ property_id: { type: String, required: true }, position: { type: Number, required: false, default:0 }, cover: { type: Boolean, required: true, default:false }, path:{ type: String, required: true }, createdAt: { type: Date, default: Date.now }, updatedAt: { type: Date, default: Date.now } }); return mongooseClient.model('images', images); };
'use strict'; const addAnalytics = (request, reply, callback) => { console.log('addAnalytics'); request.response.source.analytics = 'this could be different for each request or user'; callback(null, true); }; addAnalytics.applyPoint = 'onPostHandler'; module.exports = addAnalytics;
var classJson_1_1StaticString = [ [ "StaticString", "classJson_1_1StaticString.html#afb6baf1ec078ce76f0b0f9b39d19437f", null ], [ "c_str", "classJson_1_1StaticString.html#ad6be703d432d108623bb0aa06b0b90ca", null ], [ "operator const char *", "classJson_1_1StaticString.html#a256a6cc0c630aef670848a0f11707b62", null ] ];
var menu = new Vue({ el: '#menu', data: { getinfotomenu(obj){ menu.$data.user = obj }, user:null } })
//----------------------------Table Dialog--------------------------- function discardTableData(){$('#diaMakeTable').removeData();} function prepareTableDia() { $('#btnAddField').on('click',doAddField); $('#btnDropField').on('click',doDropField); $('#btnMakeTable').on('click',doMakeTable); $('#btnShowSQL').on('click',doShowSQL); $('#btnCloseMakeTableDia').on('click',closeMakeTableDialog); $('.fupdn').on('click',reorderFields); $('#divTblRecreate').buttonset(); } function setupTableDia() { $('#selTableCollation').val('-'); $('#inpTableName').val(''); $('#tbdyTableFields').html(''); _selRow = -1; fluidDialog(); showError(msgs_.howToSelect,true); } function reorderFields(e) { if (-1 === _selRow) { showError(msgs_.noRowSelected) ; return; } var fields = $('#diaMakeTable').data('fields'), newPos = _selRow + 1 - parseInt($(e.delegateTarget).attr('id').reverse()); if ((0 > newPos) || (fields.count <= newPos)) return; fields.swap(_selRow,newPos); _selRow = newPos; refillTableFields(); } function uniqueTableName(tname) { var ct = currentTables(); if (-1 < ct.indexOf(tname)) { showError(msgs_.needUniqueTableName); return false; } return true; } function haveFields(fields) { if (0 === fields.length) { showError(msgs_.noFields); return false; } else return true; } function createTableTail() { var coll = $('#selTableCollation option:selected').val(), ngn = $('#selTableEngine option:selected').val(), tail = ('-' == ngn)?') ':"\n) ENGINE='{eng}'".format({eng:ngn}), endBit =('-' == coll)?'':" COLLATE '{co}'".format({co:coll}); return tail + endBit; } function _createTableSQL() { var i,f,fields = $('#diaMakeTable').data('fields'), tname = $('#inpTableName').val(), rcr = (1 === parseInt($('input[name=recreate]:checked').attr('id').reverse())), head = (rcr)?'DROP TABLE IF EXISTS `{nt}`; ':''; head += 'CREATE TABLE'; if (haveFields(fields) && nameCheck(tname,'table',1) && (rcr || uniqueTableName(tname))) { var sql = "{hd} `{tn}` (\n".format({hd:head,tn:tname,nt:tname}), tail = createTableTail(); for(i=0;i < fields.length;i++) { f = fields[i]; sql += fieldSQL(f,(0 === i)); } sql += createTableTail(); sql = sql.replaceAll(' ',' '); sql = sql.replaceAll(' )',')'); return sql; } else return ''; } function doShowSQL() { var sql = _createTableSQL(); if (0 < sql.length) _doEditSQL(sql); } function doMakeTable() { var sql = _createTableSQL(), db = $('#selDBs option:selected').val(); if (0 === sql.length) return; var data = JSON.stringify([db,sql]); $.post('php/maketable.php',data,afterMakeTable).error(function(){showError(msgs_.unMakeTable);}); } function afterMakeTable(data) { try { data = JSON.parse(data); switch(data.code) { case -7:showError(msgs_.dbsDown);break; case -6:showError(msgs_.noData);break; case -5:showError(msgs_.invPostData);break; case -4:showError(msgs_.noSuchDB);break; case -3:showError(msgs_.dbSelect);break; case -2:showPDOError(data.data);break; case -1:showError(msgs_.pdoX.format({xx:data.data}));break; case 0:showPDOEror(data.data);break; case 1:displayRunResult(data.data[0]); fluidDialog(); break; } } catch(err){showError(err);} }
// Handler for weather requests // const debug = require('debug')('aymiebot:weatherHandler') const weatherHelper = require('./weatherHandlerHelper') function weatherHandler (msg) { let zip = msg.msgArray[2] Promise.all([weatherHelper.getForecast(zip), weatherHelper.getLocation(zip)]) .then((weather) => { sendWeather(msg, weather) }) } function sendWeather (msg, weather) { let message = '```Markdown\n' + `Weather Forecast - ${weather[0].day} - ${weather[1]}\n` + `Temperature - High of ${weather[0].high}°F and Low of ${weather[0].low}°F\n` + `${weather[0].forecast}\n` + '```' // console.log(message) msg.channel.sendMessage(message) } module.exports.weatherHandler = weatherHandler
'use strict'; /** * Module dependencies */ var _ = require('lodash'), path = require('path'), mongoose = require('mongoose'), Exam = mongoose.model('Exam'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')); /** * Create an exam */ exports.create = function (req, res) { var exam = new Exam(req.body); exam.user = req.user; exam.save(function (err) { if (err) { return res.status(422).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(exam); } }); }; /** * Show the current exam */ exports.read = function (req, res) { // convert mongoose document to JSON var exam = req.exam ? req.exam.toJSON() : {}; res.json(exam); }; /** * Update an exam */ exports.update = function (req, res) { var exam = req.exam; // exam.ansers.push(req.body.answer[req.body.answer.length - 1]); // push answer exam.answers = req.body.answers; exam.points = req.body.points; exam.state = req.body.state; exam.save(function (err) { if (err) { return res.status(422).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(exam); } }); }; /** * Delete an exam */ exports.delete = function (req, res) { var exam = req.exam; exam.remove(function (err) { if (err) { return res.status(422).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(exam); } }); }; /** * List of Exams */ exports.list = function (req, res) { Exam.find().sort('-created').populate('user', 'displayName').exec(function (err, exams) { if (err) { return res.status(422).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(exams); } }); }; /** * List of exams by connected owner */ exports.listByConnectedOwner = function (req, res) { Exam.find().populate('user', 'displayName').populate('form') .where('owner').equals(req.user.id) .exec(function (err, exams) { if (err) { return res.status(422).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(exams); } }); }; /** * Exam middleware */ exports.examByID = function (req, res, next, id) { if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).send({ message: 'Exam is invalid' }); } Exam.findById(id) .populate('user', 'displayName') .populate('owner', 'displayName') .populate('form') .populate('answers') .exec(function (err, exam) { if (err) { return next(err); } else if (!exam) { return res.status(404).send({ message: 'No exam with that identifier has been found' }); } req.exam = exam; next(); }); };
'use strict'; var Bartender = require('./bartender'); require('should'); xdescribe('Making a drink', function () { describe('Charging for drinks', function () { it('Should charge $9.99 for a mockito', function () { var bartender = new Bartender(); var cost = bartender.makeADrink('mockito'); cost.should.equal(9.99); }); }); });
import { Category } from 'iab-vast-model' export default ($category) => { const category = new Category() category.authority = $category.authority category.code = $category._value return category }
/* jshint node:true */ 'use strict'; //../dist/options.html をindexにして静的サーバを起動させる var http = require('http'), url = require('url'), path = require('path'), fs = require('fs'), port = process.argv[2] || 3333; http.createServer(function(request, response) { var Response = { '200': function(file/*, filename*/) { //var extname = path.extname(filename); var header = { 'Access-Control-Allow-Origin':'*', 'Pragma': 'no-cache', 'Cache-Control' : 'no-cache' }; response.writeHead(200, header); response.write(file, 'binary'); response.end(); }, '404':function(){ response.writeHead(404, {'Content-Type': 'text/plain'}); response.write('404 Not Found\n'); response.end(); }, '500':function(err){ response.writeHead(500, {'Content-Type': 'text/plain'}); response.write(err + '\n'); response.end(); } }; var uri = url.parse(request.url).pathname, filename = path.join(process.cwd(), 'dist', uri); //filename = path.join('dist/', uri); fs.exists(filename, function(exists){ console.log(filename+' '+exists); if (!exists) { Response['404'](); return ; } if (fs.statSync(filename).isDirectory()) { filename += '/index.html'; } fs.readFile(filename, 'binary', function(err, file){ if (err) { Response['500'](err); return; } Response['200'](file, filename); }); }); }).listen(parseInt(port, 10)); console.log('Server running at http://localhost:' + port );
'use strict'; var express = require('express'); var controller = require('./crawler.controller.js'); var router = express.Router(); router.get('/', controller.index); router.get('/:id', controller.show); router.post('/search-social', controller.searchSocial); router.post('/', controller.create); router.put('/:id', controller.update); router.patch('/:id', controller.update); router.delete('/:id', controller.destroy); module.exports = router;
import React from 'react'; import classes from './CardOptionsButton.scss'; const CardOptionsButton = () => { return ( <button className={classes['option-button']}> <i className='glyphicon glyphicon-cog' /> </button> ); }; export default CardOptionsButton;
var Backbone = require("backbone"); var NCAnno = require("../models/ncanno"); var $ = jQuery = require("jquery"); var bootstrap = require("bootstrap"); var AnnoView = Backbone.View.extend({ events: { "click #annook": "applyAnno", "click #wc1": "selectWc1", "click #hg1": "selectHg1", "click #sg1": "selectSg1", "click #wc2": "selectWc2", "click #hg2": "selectHg2", "click #sg2": "selectSg2", "click #st1": "selectStericityCis", "click #st2": "selectStericityTrans" }, initialize: function(b1, b2, st, edge, cyEle){ var el = document.createElement("div"); cyEle.parentNode.appendChild(el); this.setElement(el); this.anno = new NCAnno(b1, b2, st, edge); //CSS this.defineStyle(); this.render(); }, applyAnno: function(){ var e1 = this.anno.get("base1"); var e2 = this.anno.get("base2"); var st = this.anno.get("stericity"); this.anno.get("edge")._private.classes = {}; this.anno.get("edge").addClass(e1 + e2 + st); this.remove(); }, render: function(){ //HTML SETUP var res1 = this.anno.get("edge").source().data("label"); var res2 = this.anno.get("edge").target().data("label"); var edefs = this.anno.getLabels(); this.el.innerHTML += "<div class='col-md-4'>" + "<span>Residue: " + res1 + "</span>" + "<div class='dropdown'>" + "<button class='btn btn-default dropdown-toggle' type='button' id='menu1' data-toggle='dropdown'>" + edefs[0] + "<span class='caret'></span></button>" + "<ul class='dropdown-menu' role='menu' aria-labelledby='menu1'>" + "<li role='presentation'><span class='text-muted' id='wc1' style='cursor: pointer;'>Watson-Crick</span></li>" + "<li role='presentation'><span class='text-muted' id='hg1' style='cursor: pointer;'>Hoogsteen</span></li>" + "<li role='presentation'><span class='text-muted' id='sg1' style='cursor: pointer;'>Sugar</span></li>" + "</ul>" + "</div>" + "</div>"; this.el.innerHTML += "<div class='col-md-4'>" + "<span>Residue: " + res2 + "</span>" + "<div class='dropdown'>" + "<button class='btn btn-default dropdown-toggle' type='button' id='menu2' data-toggle='dropdown'>" + edefs[1] + "<span class='caret'></span></button>" + "<ul class='dropdown-menu' role='menu' aria-labelledby='menu2'>" + "<li role='presentation'><span class='text-muted' id='wc2' style='cursor: pointer;'>Watson-Crick</span></li>" + "<li role='presentation'><span class='text-muted' id='hg2' style='cursor: pointer;'>Hoogsteen</span></li>" + "<li role='presentation'><span class='text-muted' id='sg2' style='cursor: pointer;'>Sugar</span></li>" + "</ul>" + "</div>" + "</div>"; this.el.innerHTML += "" + "<div class='col-md-3'><div class='dropdown'>" + "<button class='btn btn-default dropdown-toggle' type='button' id='menu3' data-toggle='dropdown' style='margin-top: 19px;'>" + edefs[2] + "<span class='caret'></span></button>" + "<ul class='dropdown-menu'>" + "<li role='presentation'><span class='text-muted' id='st1' style='cursor: pointer;'>cis</span></li>" + "<li role='presentation'><span class='text-muted' id='st2' style='cursor: pointer;'>trans</span></li>" + "</ul>" + "</div></div>"; this.el.innerHTML += "<div class='col-md-1'><button class='btn btn-default' type='button' id='annook' style='margin-top: 19px;'>OK" + "</button></div>"; }, defineStyle: function(){ var st = this.el.style; st.display = "block"; st.position = "absolute"; st.left = "1%"; st.width = "435px"; st.height = "170px"; st.padding = "10px"; st.paddingRight = "55px"; st.border = "1px solid black"; st.borderRadius = "1px"; st.backgroundColor = "#F6F6F6"; st.overflow = "auto"; st.fontWeight = "bold"; st.textAlign = "center"; st.zIndex = 1002; }, selectWc1: function(){ this.anno.set("base1", "wc"); document.getElementById("menu1").innerHTML = "Watson-Crick<span class='caret'></span>"; }, selectHg1: function(){ this.anno.set("base1", "hg"); document.getElementById("menu1").innerHTML = "Hoogsteen<span class='caret'></span>"; }, selectSg1: function(){ this.anno.set("base1", "sg"); document.getElementById("menu1").innerHTML = "Sugar<span class='caret'></span>"; }, selectWc2: function(){ this.anno.set("base2", "wc"); document.getElementById("menu2").innerHTML = "Watson-Crick<span class='caret'></span>"; }, selectHg2: function(){ this.anno.set("base2", "hg"); document.getElementById("menu2").innerHTML = "Hoogsteen<span class='caret'></span>"; }, selectSg2: function(){ this.anno.set("base2", "sg"); document.getElementById("menu2").innerHTML = "Sugar<span class='caret'></span>"; }, selectStericityCis: function(){ this.anno.set("stericity", "cis"); document.getElementById("menu3").innerHTML = "Cis<span class='caret'></span>"; }, selectStericityTrans: function(){ this.anno.set("stericity", "trans"); document.getElementById("menu3").innerHTML = "Trans<span class='caret'></span>"; } }); module.exports = AnnoView;
const axios = require('axios').default; console.log("Requesting data from dependent-service:1337"); (async () => { try { const resp = await axios.get("http://ds/customers"); console.log(resp.data); } catch (err) { console.error(err); } })();
(function () { // All browser based JavaScript is run in the global scope. This means that we should use // IIFEs in order to self-contain our logic and avoid collisions. // We will learn how to export code properly soon // Updating this will cause updates to appear on the page! var biographyPageOptions = { name: "Phil Barresi", hobby: "Making Coffee", favoriteVegetable: "Brussel Sprouts", // Seriously favoriteProgrammingLanguage: "JavaScript", // obviously currentProject: "w2p", currentProjectDescription: "w2p is a worker-to-promise library that will allow you to call functions on web workers, and use the results as promises!" }; // We can store references to elements in variables! // We use the DOM API to query elements // One very fast query is: document.getElementById // the document object represents the actual entry point into the DOM API // We query and store two elements so that we don't have to re-query each time WE WANT TO USE IT var myHeaderElement = document.getElementById("header"); var contentAreaElement = document.getElementById("content"); // We can also create an element -- it won't appear until we add to it! // Let's create an unordered list var listOfDetails = document.createElement("ul"); // We're going to use a timeout so that you can see the page before we add to it, then after // The setTimeout function takes 2 parameters: a function, and a number of milliseconds // it will run the function after the number of milliseconds provided // this is asynchronous! The code does not stop and wait for the timeout to occur console.log("Before the timeout"); setTimeout(function () { console.log("In the timeout"); // let's use the data in biographyPageOptions to update the page! // we can change the title easily; notice, it updates instantly document.title = biographyPageOptions.name; // For each element, we can manipulate them in many ways. // One way is to set the entire content of the element with innerHTML, passing an HTML string myHeaderElement.innerHTML = "My name is " + biographyPageOptions.name; /* var biographyPageOptions = { name: "Phil Barresi", hobby: "Making Coffee", favoriteVegetable: "Brussel Sprouts", // Seriously favoriteProgrammingLanguage: "JavaScript", // obviously currentProject: "w2p", currentProjectDescription: "w2p is a worker-to-promise library that will allow you to call functions on web workers, and use the results as promises!" }; */ // Let's create a list item to the unordered list for every detail var hobbyItem = document.createElement("li"); hobbyItem.innerHTML = "My hobby is " + biographyPageOptions.hobby; listOfDetails.appendChild(hobbyItem); var veggie = document.createElement("li"); veggie.innerHTML = "My favorite vegetable is " + biographyPageOptions.favoriteVegetable; listOfDetails.appendChild(veggie); var language = document.createElement("li"); language.innerHTML = "My favorite language is " + biographyPageOptions.favoriteProgrammingLanguage; listOfDetails.appendChild(language); var currentProject = document.createElement("li"); var descriptionText = document.createTextNode("I am currently working on a project"); // We can add text as well! currentProject.appendChild(descriptionText); var subDetailsList = document.createElement("ul"); var projectName = document.createElement("li"); projectName.innerHTML = "I am working on a project called" + biographyPageOptions.currentProject; subDetailsList.appendChild(projectName); var projectDescription = document.createElement("li"); projectDescription.innerHTML = biographyPageOptions.currentProjectDescription; subDetailsList.appendChild(projectDescription); // We can then add a new child, the whole list! currentProject.appendChild(subDetailsList); // and then add the whole current project element to the detail list listOfDetails.appendChild(currentProject); // Notice, it's still not on the page! Now let's append our // list to the content area in another second and a half so we can notice that setTimeout(function () { contentAreaElement.appendChild(listOfDetails) }, 1500); }, 3500); console.log("After the timeout"); })();
import { Locale } from '../../../../src/locale'; import { TranslationChain } from '../../../../src/core/chain/translation-chain'; import { Magnitude, OrderOfMagnitude } from '../../../../src/core/types/magnitude'; import { Unit } from '../../../../src/core/types/unit'; import { OrderOfMagnitudes } from '../../../../src/core/constants/number/order-of-magnitudes'; let translationChain = null; beforeEach(() => { translationChain = new TranslationChain(); }); describe('the TranslationChain class', () => { it('handles null value for adding magnitude', () => { expect(x => translationChain.addMagnitude(null)).toThrow(Locale.Error.InvalidArgMagnitude); });Locale.Error.InvalidArgUnit it('handles undefined value for adding magnitude', () => { let test = {}; expect(x => translationChain.addMagnitude(test.notDefined)).toThrow(Locale.Error.InvalidArgMagnitude); }); it('handles null value for adding unit', () => { expect(x => translationChain.addUnit(null)).toThrow(Locale.Error.InvalidArgUnit); }); it('handles undefined value for adding unit', () => { let test = {}; expect(x => translationChain.addUnit(test.notDefined)).toThrow(Locale.Error.InvalidArgUnit); }); it('translates 0', () => { let grand = new OrderOfMagnitude('grand', 1000); translationChain.addOrderOfMagnitude(grand); expect(translationChain.translate(0)).toBe("0"); }); it('translates with a single chain element', () => { let grand = new OrderOfMagnitude('grand', 1000); translationChain.addOrderOfMagnitude(grand); expect(translationChain.translate(1000)).toBe("1 grand"); }); it('translates with value in multiple magnitudes', () => { translationChain.addOrderOfMagnitude(OrderOfMagnitudes.Million); translationChain.addOrderOfMagnitude(OrderOfMagnitudes.Billion); translationChain.addOrderOfMagnitude(OrderOfMagnitudes.Trillion); let value = OrderOfMagnitudes.Million.getValue() * OrderOfMagnitudes.Trillion.getValue(); expect(translationChain.translate(value)).toBe("1 x 10^6 trillion"); }); it('translates with value in multiple magnitudes with addMagnitudes', () => { translationChain.addOrderOfMagnitudes([OrderOfMagnitudes.Million, OrderOfMagnitudes.Billion, OrderOfMagnitudes.Trillion]); let value = OrderOfMagnitudes.Million.getValue() * OrderOfMagnitudes.Trillion.getValue(); expect(translationChain.translate(value)).toBe("1 x 10^6 trillion"); }); it('translates a very large value', () => { translationChain.addOrderOfMagnitudes([OrderOfMagnitudes.Million, OrderOfMagnitudes.Billion, OrderOfMagnitudes.Trillion]); let value = OrderOfMagnitudes.Million.getValue() * OrderOfMagnitudes.Decillion.getValue(); expect(translationChain.translate(value)).toBe("1 x 10^27 trillion"); }); it('translates with units and OrderOfMagnitudes', () => { let mm = new Unit("millimeters", 0); translationChain.addUnit(mm); let feet = new Unit("feet", 304.8); translationChain.addUnit(feet); translationChain.addOrderOfMagnitude(OrderOfMagnitudes.Million); translationChain.addOrderOfMagnitude(OrderOfMagnitudes.Billion); let value = OrderOfMagnitudes.Million.getValue() * feet.getValue(); expect(translationChain.translate(value)).toBe("1 million feet"); }); it('translates with multiple units', () => { let mm = new Unit("millimeters", 0); let feet = new Unit("feet", 304.8); translationChain.addUnits([mm, feet]); let value = 100 * feet.getValue(); expect(translationChain.translate(value)).toBe("100 feet"); }); it('translates with unit and magnitude but value is within units', () => { let mm = new Unit("millimeters", 0); translationChain.addUnit(mm); let feet = new Unit("feet", 304.8); translationChain.addUnit(feet); translationChain.addOrderOfMagnitude(OrderOfMagnitudes.Million); let value = 100 * feet.getValue(); expect(translationChain.translate(value)).toBe("100 feet"); }); it('translates with interleaved magnitudes', () => { translationChain.addOrderOfMagnitude(OrderOfMagnitudes.Million); translationChain.addOrderOfMagnitude(OrderOfMagnitudes.Trillion); let value = OrderOfMagnitudes.Billion.getValue(); expect(translationChain.translate(value)).toBe("1,000 million"); }); it('translates with rounding', () => { translationChain.addOrderOfMagnitude(OrderOfMagnitudes.Million); let value = 1.256 * OrderOfMagnitudes.Million.getValue(); expect(translationChain.translate(value)).toBe("1.26 million"); }); });
/** * Created by petkevich_a on 02.12.13. */ 'use strict'; var _gaq = _gaq || []; angular.module('analytics', []).run(['$http', function($http) { _gaq.push(['_setAccount', 'UA-46135659-1']); _gaq.push(['_trackPageview']); var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); }]).service('analytics', function($rootScope, $window, $location, $routeParams) { $rootScope.$on('$viewContentLoaded', track); var track = function() { var path = convertPathToQueryString($location.path(), $routeParams) $window._gaq.push(['_trackPageview', path]); }; var convertPathToQueryString = function(path, $routeParams) { for (var key in $routeParams) { var queryParam = '/' + $routeParams[key]; path = path.replace(queryParam, ''); } var querystring = decodeURIComponent($.param($routeParams)); if (querystring === '') return path; return path + "?" + querystring; }; });
var chai = require('chai'); var should = chai.should(); var categoriesCollection = require('../../../lib/model/response/categoriesCollection'); describe('categories collection model test', function () { var total = 11; var categories = ['categories']; it('should create model', function (done) { var categoriesCollectionModel = new categoriesCollection.CategoriesCollection( total, categories ); should.exist(categoriesCollectionModel); categoriesCollectionModel.total.should.be.equal(total); categoriesCollectionModel.categories.should.be.equal(categories); done(); }); it('should create model by builder', function (done) { var categoriesCollectionModel = new categoriesCollection.CategoriesCollectionBuilder() .withTotal(total) .withCategories(categories) .build(); should.exist(categoriesCollectionModel); categoriesCollectionModel.total.should.be.equal(total); categoriesCollectionModel.categories.should.be.equal(categories); done(); }); });
var pkg = require('../package.json') , fs = require('fs') , path = require('path') , swig = require('gulp-swig') , marked = require('swig-marked') , es = require('event-stream') , util = require('gulp-util') , rename = require('gulp-rename') // , debug = require('gulp-debug') , glob = require('glob') , Q = require('q') ; module.exports = function (gulp, config) { var demoMeta = [], promises = []; //parse each demo glob('demos/*/', function(err, dirs) { //build individual demos dirs.forEach(function(dir) { var metaFile = dir + 'meta.json'; var readmeFile = dir + 'README.md'; var readme = false; if (!fs.existsSync(metaFile)) { return; } if (fs.existsSync(readmeFile)) { readme = fs.readFileSync(readmeFile, {encoding: 'utf8'}); } //TODO: make async var data = JSON.parse(fs.readFileSync(metaFile)); data.path = dir; demoMeta.push(data); var demoTarget = config.target + data.dir; var deferred = Q.defer(); promises.push(deferred.promise); var demoScripts = glob.sync(dir + 'js/**/*.js').map(function(file) { return path.relative(dir, file); }); //TODO: resolve all scripts var swigOpts = { setup: function(swig) { marked.useTag(swig, 'markdown'); }, data: { meta: data, readme: (readme === false) ? 'No README provided.' : readme, scripts: data.scripts, demoScripts: demoScripts } }; //copy files, render template es.merge( gulp.src(data.path + 'js/**/*.js').pipe(gulp.dest(demoTarget+'/js/')), gulp.src(data.path + 'assets/**/*.*').pipe(gulp.dest(demoTarget+'/assets/')), gulp.src('util/docs/templates/demo.swig.html').pipe(swig(swigOpts)).pipe(rename('index.html')).pipe(gulp.dest(demoTarget)) ).on('end', function() { deferred.resolve(true); }); }); //set up parsing main demo index var deferred = Q.defer(); promises.push(deferred.promise); var swigOpts = { data: { version: pkg.version, baseurl: config.baseurl, demos: demoMeta } }; //now render main demo file //and copy shared assets es.merge( gulp.src('util/docs/templates/demos.index.swig.html').pipe(swig(swigOpts)).pipe(rename('index.html')).pipe(gulp.dest(config.target)), gulp.src('demos/shared/**/').pipe(gulp.dest(config.target + 'shared/')) ).on('end', function() { deferred.resolve(true); }); return Q.all(promises); }); };
/** * Created by benjamin on 22.03.2016. */ angular.module('imageShopAdm.album', []) .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $stateProvider .state('albums', { url: '/albums', templateUrl: "views/adm/album/album.html", controller: 'AlbumCtrl as ctrl', data: { permissions: { except: ['anonymous'], redirectTo: 'auth' } } }) }]) .controller('AlbumCtrl', ['$state', '$http', '$rootScope', '$uibModal', '$location', function ($state, $http, $rootScope, $uibModal, $location) { var vm = this; this.runningProcesses = {}; this.getAlbums = function () { $http.get('api/albums').then(function (response) { if (response.data.error) { alert("Error"); } else { vm.albums = response.data.data; } }, function (response) { alert("Failure"); }); }; var init = function () { vm.getAlbums(); }; init(); this.delete = function (id) { if (confirm('Delete Album ' + id + '?')) { $http.delete('api/albums/' + id).then(function (response) { vm.getAlbums(); }, function (response) { console.log(response); }); } }; this.openCreateAlbumModal = function () { var modalInstance = $uibModal.open({ templateUrl: 'views/adm/album/createAlbumDialog.html', controller: 'AlbumDetailDialogController as ctrl' }); modalInstance.album = { name: null, path: null, public: false }; modalInstance.result.then(function (album) { var config = { headers: { 'Content-Type': 'application/json;' } }; $http.post('api/albums', album, config).then(function (response) { if (response.status === 201) {//Created vm.getAlbums(); } }, function (response) { console.log(response); }); }); }; this.openEditAlbumModal = function (id) { $http.get('api/albums/' + id).then(function (response) { var modalInstance = $uibModal.open({ templateUrl: 'views/adm/album/createAlbumDialog.html', controller: 'AlbumDetailDialogController as ctrl' }); response.data.public = response.data.public === 1; modalInstance.album = response.data; modalInstance.result.then(function (album) { var config = { headers: { 'Content-Type': 'application/json;' } }; $http.put('api/albums/' + id, album, config).then(function (response) { if (response.status === 200) {//Updated vm.getAlbums(); } }, function (response) { console.log(response); }); }); }); }; this.process = function (id) { this.runningProcesses[id] = true; $http.post('api/albums/process/' + id).then(function (response) { if (response.status === 200) { alert('Done'); } else { alert('Failure'); } vm.runningProcesses[id] = false; }, function (response) { alert("Error"); vm.runningProcesses[id] = false; }); } this.disabled = function (id) { return !!vm.runningProcesses[id]; } }]).controller('AlbumDetailDialogController', ['$uibModalInstance', function ($uibModalInstance) { this.album = $uibModalInstance.album; this.ok = function () { $uibModalInstance.close(this.album); }; this.cancel = function () { $uibModalInstance.dismiss(); }; }]).directive('albumElement', function () { return { restrict: 'A', templateUrl: 'views/adm/album/listelement.html', scope: { album: '=album', controller: '=controller' } }; });
/* ##################################################################### # # Project : Modal Login with jQuery Effects # Author : Rodrigo Amarante (rodrigockamarante) # Version : 1.0 # Created : 07/29/2015 # Last Change : 08/04/2015 # ##################################################################### */ $(function() { var $formLogin = $('#login-form'); var $formLost = $('#lost-form'); var $formRegister = $('#register-form'); var $divForms = $('#div-forms'); var $modalAnimateTime = 300; var $msgAnimateTime = 150; var $msgShowTime = 2000; $("form").submit(function () { switch(this.id) { case "login-form": var data = $("#login-form").serialize(), msgbox = $("#div-login-msg"), btn = $('#register-button'); btn.attr("disabled", "disabled").html("Подождите..."); $.ajax({ type: "POST", dataType: 'json', url: "/?_do=auth::signIn", data: data, success: function(a){ btn.removeAttr("disabled"); if(a.success){ window.location = "/?_page=profile"; }else{ msgbox.html( $('<div>').addClass("alert alert-danger").html(a.message) ); btn.html("Войти"); //msgbox.html(a.message); } } }); return false; break; case "lost-form": var $ls_email=$('#lost_email').val(); if ($ls_email == "ERROR") { msgChange($('#div-lost-msg'), $('#icon-lost-msg'), $('#text-lost-msg'), "error", "glyphicon-remove", "Send error"); } else { msgChange($('#div-lost-msg'), $('#icon-lost-msg'), $('#text-lost-msg'), "success", "glyphicon-ok", "Send OK"); } return false; break; case "register-form": var form = $("#register-form"), msgbox = $("#div-login-msg"), data = form.serialize(); $.ajax({ type: "POST", dataType: 'json', url: "/?_do=register::signUp", data: data, success: function(a){ console.log(a); if(a.success){ alert('ok'); window.location = window.location; }else{ $('<div>').addClass("alert alert-success").prependTo(msgbox) //msgbox.html(a.message); } } }); break; default: return false; } return false; }); $('#login_register_btn').click( function () { modalAnimate($formLogin, $formRegister) }); $('#register_login_btn').click( function () { modalAnimate($formRegister, $formLogin); }); $('#login_lost_btn').click( function () { modalAnimate($formLogin, $formLost); }); $('#lost_login_btn').click( function () { modalAnimate($formLost, $formLogin); }); $('#lost_register_btn').click( function () { modalAnimate($formLost, $formRegister); }); $('#register_lost_btn').click( function () { modalAnimate($formRegister, $formLost); }); function modalAnimate ($oldForm, $newForm) { var $oldH = $oldForm.height(); var $newH = $newForm.height(); $divForms.css("height",$oldH); $oldForm.fadeToggle($modalAnimateTime, function(){ $divForms.animate({height: $newH}, $modalAnimateTime, function(){ $newForm.fadeToggle($modalAnimateTime); }); }); } function msgFade ($msgId, $msgText) { $msgId.fadeOut($msgAnimateTime, function() { $(this).text($msgText).fadeIn($msgAnimateTime); }); } function msgChange($divTag, $iconTag, $textTag, $divClass, $iconClass, $msgText) { var $msgOld = $divTag.text(); msgFade($textTag, $msgText); $divTag.addClass($divClass); $iconTag.removeClass("glyphicon-chevron-right"); $iconTag.addClass($iconClass + " " + $divClass); setTimeout(function() { msgFade($textTag, $msgOld); $divTag.removeClass($divClass); $iconTag.addClass("glyphicon-chevron-right"); $iconTag.removeClass($iconClass + " " + $divClass); }, $msgShowTime); } });/** * Created by Александр on 24.01.2016. */
import "locale"; d3.locale.pt_BR = d3.locale({ decimal: ',', thousands: '.', grouping: [3], currency: ['R$', ''], dateTime: '%A, %e de %B de %Y. %X', date: '%d/%m/%Y', time: '%H:%M:%S', periods: ['AM', 'PM'], days: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'], shortDays: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'], months: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'], shortMonths: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'] });
import React, { Component } from 'react'; class Banner extends Component { render () { return ( <img src={require('./palestine_banner.png')} alt='palestine' /> ); } } export default Banner;
var util = require('./util'); var rule = require('./rule'); var semver = require('semver'); module.exports = function migration() { return Migration.apply(null, arguments); }; module.exports.Migration = Migration; /** * A more clever conversion rule, able to reverse its actions. * * Depending on whether converting from a greater version to a smaller or * vice versa, the conversion rule calls either the `up` or `down` function. * @constructor * @param {Object} params parameters for instantiating the object * @param {semver.Range|semver.SemVer|String} params.from the version to start from * @param {semver.Range|semver.SemVer|String} params.to the version to convert to * @param {Function} params.up the function to execute when upgrading * @param {Function} params.down the function to execute when downgrading */ function Migration(params) { if (typeof params !== 'object') return new Migration({ from: arguments[0], to: arguments[1], up: arguments[2], down: arguments[3] }); if (params instanceof Migration) return params; if (!(this instanceof Migration)) return new Migration(params); this.up = params.up; this.down = params.down; rule.Rule.call(this, params); } util.inherits(Migration, rule.Rule); Migration.prototype.test = function (from, to) { var up = this.up; var down = this.down; var sat = [ util.satisfy(from, this.from), util.satisfy(from, this.to), util.satisfy(to, this.to), util.satisfy(to, this.from) ]; function step() { var fn = semver.lte(step.from, step.to) ? up : down; return step.fn.apply(this, [step.from, step.to].concat(arguments)); } step.from = sat[0] || (sat[3] && sat[1]); step.to = sat[2] || (sat[1] && sat[3]); step.rule = this; return ( step.from || step.to ) && step; };
/** * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time to build CKEditor again. * * If you would like to build CKEditor online again * (for example to upgrade), visit one the following links: * * (1) http://ckeditor.com/builder * Visit online builder to build CKEditor from scratch. * * (2) http://ckeditor.com/builder/9a3e3e22618d16deb0d908cae0499489 * Visit online builder to build CKEditor, starting with the same setup as before. * * (3) http://ckeditor.com/builder/download/9a3e3e22618d16deb0d908cae0499489 * Straight download link to the latest version of CKEditor (Optimized) with the same setup as before. * * NOTE: * This file is not used by CKEditor, you may remove it. * Changing this file will not change your CKEditor configuration. */ var CKBUILDER_CONFIG = { skin: 'moono-lisa', preset: 'standard', ignore: [ '.DS_Store', '.bender', '.editorconfig', '.gitattributes', '.gitignore', '.idea', '.jscsrc', '.jshintignore', '.jshintrc', '.mailmap', '.travis.yml', 'bender-err.log', 'bender-out.log', 'bender.ci.js', 'bender.js', 'dev', 'gruntfile.js', 'less', 'node_modules', 'package.json', 'tests' ], plugins : { 'a11yhelp' : 1, 'about' : 1, 'basicstyles' : 1, 'blockquote' : 1, 'clipboard' : 1, 'contextmenu' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'filebrowser' : 1, 'floatingspace' : 1, 'format' : 1, 'horizontalrule' : 1, 'htmlwriter' : 1, 'image' : 1, 'indentlist' : 1, 'link' : 1, 'list' : 1, 'magicline' : 1, 'maximize' : 1, 'pastefromword' : 1, 'pastetext' : 1, 'removeformat' : 1, 'resize' : 1, 'scayt' : 1, 'showborders' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tableselection' : 1, 'tabletools' : 1, 'texzilla' : 1, 'toolbar' : 1, 'undo' : 1, 'wsc' : 1, 'wysiwygarea' : 1 }, languages : { 'en' : 1 } };
var schema = require('./models'); console.log("Migrating models..."); schema.automigrate(); console.log("..done! :)");
'use strict'; /** * @ngdoc function * @name myApp.controller:controller.management * @author yianni.ververis@qlik.com * @description * # controller.management */ var controller = ($scope, $rootScope, $location, $injector, qlik, api, app, ga) => { var me = {}; me.init = () => { $rootScope.page = 'management'; $rootScope.vars = { title: 'MANAGEMENT OVERVIEW', } $scope.checked = false; $scope.multiGetObject = { title: 'Cost Analysis', items: [ { label: 'Cost vs Budget', objects: [ { label: 'System', id:'fJcxaEu' }, { label: 'Portfolio', id:'EDLPMcM' }, { label: 'System Type', id:'jVjbZDP' }, { label: 'Lifecycle', id:'FnEHdj' }, { label: 'Year Month', id:'WBCETJz' }, ] }, { label: 'Cost Types Break-Down', objects: [ { label: 'System', id:'36359fd9-63ad-473a-a84a-a869e6acbd99' }, { label: 'Portfolio', id:'8987e51f-465a-46ab-b08d-da145d7abb5a' }, { label: 'System Type', id:'2bac5c5f-0765-4491-a1f6-fa43c1744a3a' }, { label: 'Lifecycle', id:'b5962127-4a08-4bd9-b0a1-44dc4b8f0029' }, { label: 'Year Month', id:'1f793799-30d9-4fe7-b681-91551bc91bb8' }, ] } ] }; $scope.multiGetObjectViz = { title: 'Cost Analysis', items: [ { label: 'Cost vs Budget', objects: [ { label: 'Portfolio', type:'combochart', columns:['Portfolio','=sum({<Type={AM}>}[Cost] * History* _CurrYTD)','=sum({<Type={AM}>}[Cost Budget] * History* _CurrYTD)'] }, { label: 'System Type', type:'combochart', columns:['System Type','=sum({<Type={AM}>}[Cost] * History* _CurrYTD)','=sum({<Type={AM}>}[Cost Budget] * History* _CurrYTD)'] }, ] }, { label: 'Cost Types Break-Down', objects: [ { label: 'Portfolio', id:'8987e51f-465a-46ab-b08d-da145d7abb5a' }, { label: 'System Type', id:'2bac5c5f-0765-4491-a1f6-fa43c1744a3a' }, { label: 'Lifecycle', id:'b5962127-4a08-4bd9-b0a1-44dc4b8f0029' }, { label: 'System', id:'36359fd9-63ad-473a-a84a-a869e6acbd99' }, { label: 'Year Month', id:'1f793799-30d9-4fe7-b681-91551bc91bb8' }, ] } ] }; } me.boot = () => { me.init(); me.events(); app.log('Management loaded: ', 'Success!'); }; me.events = () => { // For debugging selections uncommment the line below // qlik.app.getObject('CurrentSelections', 'CurrentSelections'); qlik.app.getObject('kRJUp', 'kRJUp'); ga.pageview(); } me.boot(); }; controller.$inject = ['$scope', '$rootScope', '$location', '$injector', 'qlik', 'api', 'app', 'ga']; angular.module('controller.management', []) .controller('controller.management', controller);
//--exports module.exports.id = 'ae8d63c6-858d-4ecf-8eaf-431f9a67742f'; module.exports.title = 'Errored migration'; module.exports.time = '1383598261250'; //--dependencies module.exports.dependencies = [ 'aa22c294-bc63-4fd3-babc-b7b597353892' ]; //--migrate function module.exports.up = function up(mig, flok, done) { done(new Error('oops')); }; //--backout function module.exports.down = function down(mig, flok, done) { done(); };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _filter2 = require('lodash/filter'); var _filter3 = _interopRequireDefault(_filter2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _raf = require('raf'); var _raf2 = _interopRequireDefault(_raf); var _util = require('./util'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var alpha = function alpha(begin, end, k) { return begin + (end - begin) * k; }; var needContinue = function needContinue(_ref) { var from = _ref.from, to = _ref.to; return from !== to; }; /* * @description: cal new from value and velocity in each stepper * @return: { [styleProperty]: { from, to, velocity } } */ var calStepperVals = function calStepperVals(easing, preVals, steps) { var nextStepVals = (0, _util.mapObject)(function (key, val) { if (needContinue(val)) { var _easing = easing(val.from, val.to, val.velocity), _easing2 = _slicedToArray(_easing, 2), newX = _easing2[0], newV = _easing2[1]; return _extends({}, val, { from: newX, velocity: newV }); } return val; }, preVals); if (steps < 1) { return (0, _util.mapObject)(function (key, val) { if (needContinue(val)) { return _extends({}, val, { velocity: alpha(val.velocity, nextStepVals[key].velocity, steps), from: alpha(val.from, nextStepVals[key].from, steps) }); } return val; }, preVals); } return calStepperVals(easing, nextStepVals, steps - 1); }; // configure update function exports.default = function (from, to, easing, duration, render) { var interKeys = (0, _util.getIntersectionKeys)(from, to); var timingStyle = interKeys.reduce(function (res, key) { return _extends({}, res, _defineProperty({}, key, [from[key], to[key]])); }, {}); var stepperStyle = interKeys.reduce(function (res, key) { return _extends({}, res, _defineProperty({}, key, { from: from[key], velocity: 0, to: to[key] })); }, {}); var cafId = -1; var preTime = void 0; var beginTime = void 0; var update = function update() { return null; }; var getCurrStyle = function getCurrStyle() { return (0, _util.mapObject)(function (key, val) { return val.from; }, stepperStyle); }; var shouldStopAnimation = function shouldStopAnimation() { return !(0, _filter3.default)(stepperStyle, needContinue).length; }; // stepper timing function like spring var stepperUpdate = function stepperUpdate(now) { if (!preTime) { preTime = now; } var deltaTime = now - preTime; var steps = deltaTime / easing.dt; stepperStyle = calStepperVals(easing, stepperStyle, steps); // get union set and add compatible prefix render(_extends({}, from, to, getCurrStyle(stepperStyle))); preTime = now; if (!shouldStopAnimation()) { cafId = (0, _raf2.default)(update); } }; // t => val timing function like cubic-bezier var timingUpdate = function timingUpdate(now) { if (!beginTime) { beginTime = now; } var t = (now - beginTime) / duration; var currStyle = (0, _util.mapObject)(function (key, val) { return alpha.apply(undefined, _toConsumableArray(val).concat([easing(t)])); }, timingStyle); // get union set and add compatible prefix render(_extends({}, from, to, currStyle)); if (t < 1) { cafId = (0, _raf2.default)(update); } else { var finalStyle = (0, _util.mapObject)(function (key, val) { return alpha.apply(undefined, _toConsumableArray(val).concat([easing(1)])); }, timingStyle); render(_extends({}, from, to, finalStyle)); } }; update = easing.isStepper ? stepperUpdate : timingUpdate; // return start animation method return function () { (0, _raf2.default)(update); // return stop animation method return function () { (0, _raf.cancel)(cafId); }; }; };
import React from 'react'; import { useSelector } from 'react-redux'; import { Set, Text } from 'react-raphael'; import { isArray, map } from 'lodash'; import { BOARD_TYPES, NOTE_NUMS } from 'components/constants'; import { selectors as boardsSelectors } from 'redux/boards'; import './styles.less'; function Notes({ click, hide, index, width, x, y }) { const notesCell = useSelector(state => boardsSelectors.getCellIndex(state, BOARD_TYPES.NOTES, index)); return !hide ? ( <Set> {map(NOTE_NUMS, n => { const noteOffset = (n + 2) % 3; const noteRow = n <= 3 ? 1 : n > 3 && n <= 6 ? 2 : 3; return notesCell && isArray(notesCell) && notesCell.indexOf(n) > -1 ? ( <Text text={n.toString()} key={`${index}-note-${n.toString()}`} x={x + (width / 4 * noteOffset) + 12.5} y={y + noteRow * 15 - 5} styleName={'text'} click={click} /> ) : null; })} </Set> ) : null; } export default Notes;
/** * This file is part of the gina package. * Copyright (c) 2014 Rhinostone <gina@rhinostone.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ 'use strict'; /** * @class Inherits * * @package gina.utils * @namesame gina.utils.inherits * @author Rhinostone <gina@rhinostone.com> * * @api Public * */ function Inherits(a, b) { /** * init * @constructor * */ var init = function(a, b) { var err = check(a, b); if (!err) { var z = ( function() { var cache = a; return function() { //super class if (this) { this.prototype = {}; //makes it compatible with node.js classes like EventEmitter for (var prop in b.prototype) { if (!this[prop]) { this[prop] = b.prototype[prop]; //this.prototype[prop] = b.prototype[prop] } } //this.prototype.name = b.name; b.apply(this, arguments); cache.apply(this, arguments) } } }()); //makes it compatible with node.js classes like EventEmitter if (b.prototype == undefined) { b.prototype = {} } a.prototype = Object.create(b.prototype, {}); z.prototype = Object.create(a.prototype, {}); return z } else { throw new Error(err) } } var check = function(a, b) { if ( typeof(a) == 'undefined' || typeof(b) == 'undefined') { return 'inherits(a, b): neither [ a ] nor [ b ] can\'t be undefined or null' } return false } return init }; module.exports = Inherits()
'use strict'; /*jshint asi: true */ var readlineMatchToken = require('..') , test = require('trap').test , harness = require('readline-testharness') , createHarness = harness.create , hns , cursorAfter , cursorBefore function createrli() { var rli = harness.rli() rli.line = '' rli._ttyWrite = function (code, key) { if (!cursorBefore) this.line += key.name else this.line = this.line.slice(0, cursorBefore) + key.name + this.line.slice(cursorBefore) // move cursor behind entered char this.cursor = cursorAfter || this.line.length; } return rli; } function setup() { cursorAfter = cursorBefore = undefined readlineMatchToken.interval = 10 hns = createHarness(readlineMatchToken, createrli) hns.reset() } test('given rli line "(.." and I enter ")" and wait', function (t) { setup() hns.rli.line = '(..' hns.key(')') t.equal(hns.rli.moveCursor.pop(), -4, 'moves cursor onto matching paren') setTimeout(t.cb( function () { t.equal(hns.rli.moveCursor.pop(), undefined, 'keeps cursor there for given interval') }) , readlineMatchToken.interval / 2 ) setTimeout(t.cb( function () { t.equal(hns.rli.moveCursor.pop(), 4, 'moves cursor back after interval passed') }) , readlineMatchToken.interval ) }) test('given rli line "(.." and I enter ")" and enter a [space] right after', function (t) { setup() hns.rli.line = '(..' hns.key(')') t.equal(hns.rli.moveCursor.pop(), -4, 'moves cursor onto matching paren') hns.key('space') t.equal(hns.rli.moveCursor.pop(), 4, 'moves cursor back as [space] is entered') }); test('given rli line "function foo () { console.log("hello world"); " and I enter "}"', function (t) { setup() hns.rli.line = 'function foo () { console.log("hello world"); ' hns.key('}') t.equal(hns.rli.moveCursor.pop(), -31, 'moves cursor onto matching brace') }); test('given rli line "function foo () console.log("hello world"); }", the cursor is before "console" and I enter "{"', function (t) { setup() // 0123456789012345 hns.rli.line = 'function foo () console.log("hello world"); }' cursorBefore = 15 cursorAfter = 16 hns.key('{') t.equal(hns.rli.moveCursor.pop(), 29, 'moves cursor onto matching close brace') });
var gulp = require("gulp"); var concat = require("gulp-concat"); var uglify = require("gulp-uglify"); var rename = require("gulp-rename"); var sourcemaps = require('gulp-sourcemaps'); var babel = require('gulp-babel'); var concat = require('gulp-concat'); var serve = require('gulp-serve'); var paths = { babel : './src/**/*.js', css : "src/*/*.css" }; gulp.task("uglify", function() { gulp.src(["dist/pullrefresh.js"]) // Read the files .pipe(uglify()) // Minify .pipe(rename({extname: ".min.js"})) // Rename to ng-quick-date.min.js .pipe(gulp.dest("dist")) // Write minified to disk }); gulp.task("css", function() { gulp.src(paths.css) // Read the files .pipe(concat("pullrefresh.css")) // Combine into 1 file .pipe(gulp.dest("dist")); }); gulp.task('compile', function () { gulp.src(paths.babel) .pipe(sourcemaps.init()) .pipe(babel({ presets: ['es2015'] })) .pipe(concat('pullrefresh.js')) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('dist')); }); gulp.task('serve', serve({ root : ['./'] })); gulp.task("build", function() { gulp.start("compile"); gulp.start("uglify"); gulp.start("css"); }); gulp.task('default', function () { gulp.start('serve'); gulp.watch(paths.css, ['css']); gulp.watch(paths.babel, ['compile']); });
'use strict'; module.exports.tasks = { // WIREDEP wiredep: { task: { directory: 'app/bower_components', src: ['app/index.html', './karma.conf.js'], } } };
describe('(Component) TestContainer', () => { it('exists', () => { }) })
window.onload=init; //Onload Init Application function init(){ var user_cards=localStorage.getItem("github_user"); user_cards=JSON.parse(user_cards); var app=new GithubApp(user_cards); } //NameSpaced App (function(){ var GithubApp=function(userlists){ this.data=userlists || []; this.BaseURL="https://api.github.com/users/"; // Retrieve the template data from the HTML (jQuery is used here). template = $('#handlebars-demo').html(); // Compile the template data into a function this.templateScript = Handlebars.compile(template); this.renderView(); this.bindEvents(); } //Renders View GithubApp.prototype.renderView=function(){ var _this=this; var html=_this.templateScript(_this.data); // Insert the HTML code into the page $("#disp_users").empty(); $("#disp_users").append(html); localStorage.setItem("github_user", JSON.stringify(_this.data)); this.bindCardEvents(); } //Bind Component Events GithubApp.prototype.bindEvents = function() { var _this=this; $("#search_user").on('keyup',function(event){ if(event.which==13){ _this.removeAlerts(); _this.addUser(); } }); $("#search_btn").on('click',function(event){ _this.removeAlerts(); _this.addUser(); }); $(".close").on('click',function(event){ _this.removeAlerts(); }); $("#srt_asc_name").on('click',function(event){ _this.sortNameAscending(); }); $("#srt_desc_name").on('click',function(event){ _this.sortNameDescending(); }); $("#srt_asc_location").on('click',function(event){ _this.sortLocationAscending(); }); $("#srt_desc_location").on('click',function(event){ _this.sortLocationDescending(); }); $("#sort_follwers").on('click',function(event){ _this.sortFollowers(); }); } GithubApp.prototype.removeAlerts=function(){ $("#danger_noexist").removeClass("display"); $("#danger_added").removeClass("display"); $("#danger_noexist").addClass("display_none"); $("#danger_added").addClass("display_none"); } //Bind Card Event Handlers GithubApp.prototype.bindCardEvents=function(){ var _this=this; $(".cancel_btn").on('click',function(event){ var removeIndex=_this.data.map(function(x) {return x.login; }).indexOf(this.id); if(removeIndex!=-1){ _this.data.splice(removeIndex,1); _this.renderView(); } event.stopPropagation(); }); $(".profile-container").on('click',function(event){ window.open('https://github.com/'+this.id, '_blank'); }); } //Add User Data GithubApp.prototype.addUser=function(){ var _this=this; $("#preloader").addClass("display"); var apiurl=_this.BaseURL+$("#search_user").val(); $.ajax({ context: _this, url:apiurl, success:_this.createUser, error:_this.displayError }) }; //Display Error on Ajax req. GithubApp.prototype.displayError=function(){ $("#preloader").removeClass("display"); $("#preloader").addClass("display_none"); $("#danger_noexist").addClass("display"); } //Create User object GithubApp.prototype.createUser=function(response){ var _this=this; var obj={ image: response.avatar_url, followers: response.followers, location:response.location || "-", name:response.name || "-", login:response.login } $("#preloader").removeClass("display"); $("#preloader").addClass("display_none"); if(_this.data.map(function(x) {return x.login; }).indexOf(obj.login)==-1){ _this.data.push(obj); _this.renderView(); $("#search_user").val(null); } else { $("#danger_added").addClass("display"); } }; //Sort name Ascending GithubApp.prototype.sortNameAscending=function(){ for(var i=0;i<this.data.length;i++){ for(var j=i+1;j<this.data.length;j++) { if(this.data[i].name>this.data[j].name) { var temp=this.data[i]; this.data[i]=this.data[j]; this.data[j]=temp; } } } this.renderView(); } //Sort Name Descending GithubApp.prototype.sortNameDescending=function(){ for(var i=0;i<this.data.length;i++){ for(var j=i+1;j<this.data.length;j++) { if(this.data[i].name<this.data[j].name) { var temp=this.data[i]; this.data[i]=this.data[j]; this.data[j]=temp; } } } this.renderView(); } //Sort location Ascending GithubApp.prototype.sortLocationAscending=function(){ for(var i=0;i<this.data.length;i++){ for(var j=i+1;j<this.data.length;j++) { if(this.data[i].location>this.data[j].location) { var temp=this.data[i]; this.data[i]=this.data[j]; this.data[j]=temp; } } } this.renderView(); } //Sort Location Descending GithubApp.prototype.sortLocationDescending=function(){ for(var i=0;i<this.data.length;i++){ for(var j=i+1;j<this.data.length;j++) { if(this.data[i].location<this.data[j].location) { var temp=this.data[i]; this.data[i]=this.data[j]; this.data[j]=temp; } } } this.renderView(); } //Sort Followers Ascscending only GithubApp.prototype.sortFollowers=function(){ for(var i=0;i<this.data.length;i++){ for(var j=i+1;j<this.data.length;j++) { if(this.data[i].followers>this.data[j].followers) { var temp=this.data[i]; this.data[i]=this.data[j]; this.data[j]=temp; } } } this.renderView(); } window.GithubApp=GithubApp; })();
import React, { forwardRef, Fragment, useRef, useImperativeHandle } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import Box from '../box'; import theme from './theme.css'; import uiUtilities from '@teamleader/ui-utilities'; const Link = forwardRef( ( { badged, children, className, disabled, icon, iconPlacement, element, inherit, inverse, selected, onMouseUp, onMouseLeave, ...others }, ref, ) => { const linkRef = useRef(); useImperativeHandle(ref, () => linkRef.current); const blur = () => { const currentLinkRef = linkRef.current; if (currentLinkRef.blur) { currentLinkRef.blur(); } }; const handleMouseUp = (event) => { blur(); onMouseUp && onMouseUp(event); }; const handleMouseLeave = (event) => { blur(); onMouseLeave && onMouseLeave(event); }; const classNames = cx( uiUtilities['reset-font-smoothing'], theme['link'], { [theme['is-badged']]: badged, [theme['is-disabled']]: disabled, [theme['is-inherit']]: inherit, [theme['is-inverse']]: inverse, [theme['is-selected']]: selected, [theme['has-icon']]: icon, }, className, ); const ChildrenWrapper = icon ? 'span' : Fragment; return ( <Box element={element} ref={linkRef} className={classNames} data-teamleader-ui="link" onMouseUp={handleMouseUp} onMouseLeave={handleMouseLeave} {...others} > {icon && iconPlacement === 'left' && icon} <ChildrenWrapper>{children}</ChildrenWrapper> {icon && iconPlacement === 'right' && icon} </Box> ); }, ); Link.propTypes = { /** If true, component will be rendered with badged hover effect. */ badged: PropTypes.bool, /** The content to display inside the link. */ children: PropTypes.any.isRequired, /** A class name for the link to give custom styles. */ className: PropTypes.string, /** If true, component will be disabled. */ disabled: PropTypes.bool, /** The icon displayed inside the button. */ icon: PropTypes.element, /** The position of the icon inside the button. */ iconPlacement: PropTypes.oneOf(['left', 'right']), /** If true, the link style inherits the parent element style. */ inherit: PropTypes.bool, /** If true, the underline behavior will be inverted. */ inverse: PropTypes.bool, /** A custom element to be rendered */ element: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), /** Callback function that is fired when mouse leaves the component. */ onMouseLeave: PropTypes.func, /** Callback function that is fired when the mouse button is released. */ onMouseUp: PropTypes.func, /** If true, component will be shown in a selected state */ selected: PropTypes.bool, }; Link.defaultProps = { badged: false, className: '', disabled: false, element: 'a', iconPlacement: 'left', inherit: true, inverse: false, }; Link.displayName = 'Link'; export default Link;
/** * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash modularize modern exports="node" -o ./modern/` * Copyright 2012-2014 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ var createCallback = require('../functions/createCallback'), filter = require('./filter'); /** * The opposite of `_.filter`; this method returns the elements of a * collection that the callback does **not** return truey for. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that failed the callback check. * @example * * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [1, 3, 5] * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true } * ]; * * // using "_.pluck" callback shorthand * _.reject(characters, 'blocked'); * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] * * // using "_.where" callback shorthand * _.reject(characters, { 'age': 36 }); * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] */ function reject(collection, callback, thisArg) { callback = createCallback(callback, thisArg, 3); return filter(collection, function(value, index, collection) { return !callback(value, index, collection); }); } module.exports = reject;
'use strict'; /** * Module dependencies. */ var debug = require('debug')('mquery-cache') , EventEmitter = require('events').EventEmitter , util = require('util') , _ = require('underscore') ; /** * Default object hashing algorithm to return a unique * key representation of an object. * * @param {Object} query * @return {String} hash * @api private */ function keyhasher(query){ debug('Beginning key hash'); var keyData = { options: query._mongooseOptions, collection: query._collection.collection.name, conditions: query._conditions, fields: query._fields, path: query._path, distinct: query._distinct } , key = JSON.stringify(keyData); debug('Hashed key [ %s ] with data %j', key, keyData); return key; } /** * CachedQuery constructor. * * @param {String|Number} key * @param {Object} query * @param {Mixed} data * @param {String|Number} ttl * @return {CachedQuery} this * @api private */ function CachedQuery(key,query,data,ttl){ // this.query = query; this.ttl = ttl; this._data = data; this.key = key; this.refreshing = false; } util.inherits(CachedQuery, EventEmitter); Object.defineProperty(CachedQuery.prototype, 'data', { get: function(){ return this._data || null; }, set: function(val){ var oldval = this._data; this._data = val; debug('Cache [ %s ] refreshed',this.key); this.emit('refresh',val,oldval); } }); /** * TTLCacheCollection constructor. * * @param {Array} values * @return {TTLCacheCollection} this * @api private */ function TTLCacheCollection(values){ this.values = values || {}; this._ttlIntervals = {}; } util.inherits(TTLCacheCollection, EventEmitter); TTLCacheCollection.prototype.add = function(cache){ debug('Adding cache [ %s ] to collection',cache.key); var _this = this; this.remove(cache.key,true); this.values[ cache.key] = cache; this._ttlIntervals[ cache.key] = setTimeout(function(){ debug('Cache [ %s ] expired',cache.key); delete _this.values[ cache.key]; delete _this._ttlIntervals[ cache.key] _this.emit('expire'); }, cache.ttl*1000); this.emit('add',cache,this); } TTLCacheCollection.prototype.remove = function(key,silent){ if(this._ttlIntervals[ key]) { debug('Removing cache [ %s ] from collection',key); clearTimeout(this._ttlIntervals[ key]); delete this._ttlIntervals[ key]; delete this.values[ key]; if(!silent) this.emit('remove'); } } TTLCacheCollection.prototype.get = function(key){ return this.values[ key]; } /** * Expose module. */ module.exports = function(Query, Promise, options){ var caches = new TTLCacheCollection , opts = { ttl: 10, hasher: keyhasher } ; // Combine default and user defined options. options = _.extend(opts, options || {}); // Hash function. var hashCacheKey = options.hasher; /** * Cache setter. Calling this method on a query * will trigger cache to be turned on with the * supplied ttl. * * @param {Number|String} ttl * @return {Query} this * @api public */ Query.prototype.cache = function(ttl){ // debug('Checking query operation [%s] for cacheability', this.op); // Restrict caching to `find` operations only. if(/^(find)(?![a-z]+(update))/ig.test(this.op)&&ttl) { debug('Caching query %j', this._mongooseOptions); // Capture current exec method to call later. var exec = this.exec; /** * Overwrite default Query.exec and call it only * when there is no cache to return. * * @param {String} op * @param {Function} callback * @return {Promise} promise * @api public */ this.exec = function(op, callback){ debug('Executing cachable query'); // Generate query key and check for existing cache. var key = hashCacheKey(this) , cache = caches.get(key) ; // debug('Validating cache for key %s', key); // Check arguments. if( 'function' === typeof op){ callback = op; op = null; }else if( 'string' === typeof op){ this.op = op; } // if cache exists validate and return it. if(cache&&cache.refreshing===false){ debug('Cached results found for key', key); // Create promise to send data back through callback. var promise = new Promise(); if(callback) promise.addBack(callback); // Resolve promise with cached data. return promise.resolve(null, cache.data); } // Otherwise query the database as normal. else{ debug('No cache found for query %j', this.options); // Create cache instance cache = cache || new CachedQuery(key, this, null, ttl || options.ttl); // Checking if another request is already updating cached query if(cache.refreshing){ // Create promise to send data back through callback. var promise = new Promise(); // cache.once('refresh', function(val,oldval){ debug('Cache refreshed results'); promise.resolve(null, val); }); }else{ // cache.refreshing = true; // Execute query var promise = exec.apply( this, arguments); // Get notified when promise has been // resolved and cache results. promise.addBack( function(err,results){ if(results) { debug('Promise returned results'); // cache.refreshing = false; // cache.data = results; // Set cache in caches caches.add(cache); } }); } // return promise; } } }else if(!ttl){ caches.remove(hashCacheKey(this)); } return this; }; }
import React from 'react'; import PropTypes from 'prop-types'; import FlashError from './FlashError'; export default class ErrorBoundary extends React.PureComponent { constructor(props) { super(props); this.state = { error: null, }; } componentDidCatch(error) { this.setState({error: error}); } render() { if (this.state.error) { return <FlashError error={this.state.error}/>; } return this.props.children; } } ErrorBoundary.propTypes = { children: PropTypes.element.isRequired, };
/** * @license * Copyright 2010, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains functions every webgl program will need * a version of one way or another. * * Instead of setting up a context manually it is recommended to * use. This will check for success or failure. On failure it * will attempt to present an approriate message to the user. * * gl = WebGLUtils.setupWebGL(canvas); * * For animated WebGL apps use of setTimeout or setInterval are * discouraged. It is recommended you structure your rendering * loop like this. * * function render() { * window.requestAnimFrame(render, canvas); * * // do rendering * ... * } * render(); * * This will call your rendering function up to the refresh rate * of your display but will stop rendering if your app is not * visible. */ var WebGLUtils = function() { /** * Creates the HTLM for a failure message * @param {string} msg * @return {string} The html. */ var makeFailHTML = function(msg) { return '' + '<table style="background-color: #8CE; width: 100%; height: 100%;"><tr>' + '<td align="center">' + '<div style="display: table-cell; vertical-align: middle;">' + '<div style="">' + msg + '</div>' + '</div>' + '</td></tr></table>'; }; /** * Message for getting a webgl browser * @type {string} */ var GET_A_WEBGL_BROWSER = '' + 'This page requires a browser that supports WebGL.<br/>' + '<a href="http://get.webgl.org">Click here to upgrade your browser.</a>'; /** * Mesasge for need better hardware * @type {string} */ var OTHER_PROBLEM = '' + "It doesn't appear your computer can support WebGL.<br/>" + '<a href="http://get.webgl.org/troubleshooting/">Click here for more information.</a>'; /** * Creates a webgl context. If creation fails it will * change the contents of the container of the <canvas> * tag to an error message with the correct links for WebGL. * @param {HTMLCanvasElement} canvas The canvas element to create a context from. * @param {*=} opt_attribs Any creation attributes you want to pass in. * @param {function(string)=} opt_onError A function to call if there is an error during creation. * @return {WebGLRenderingContext} The created context. */ var setupWebGL = function(canvas, opt_attribs, opt_onError) { function handleCreationError(msg) { var container = canvas.parentNode; if (container) { var str = window.WebGLRenderingContext ? OTHER_PROBLEM : GET_A_WEBGL_BROWSER; if (msg) { str += "<br/><br/>Status: " + msg; } container.innerHTML = makeFailHTML(str); } }; opt_onError = opt_onError || handleCreationError; if (canvas.addEventListener) { canvas.addEventListener("webglcontextcreationerror", function(event) { opt_onError(event.statusMessage); }, false); } var context = create3DContext(canvas, opt_attribs); if (!context) { if (!window.WebGLRenderingContext) { opt_onError(""); } } return context; }; /** * Creates a webgl context. * @param {!HTMLCanvasElement} canvas The canvas tag to get context * from. If one is not passed in one will be created. * @return {WebGLRenderingContext|null} The created context. */ var create3DContext = function(canvas, opt_attribs) { var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"]; var context = null; for (var ii = 0; ii < names.length; ++ii) { try { context = /** @type {WebGLRenderingContext} */ (canvas.getContext(names[ii], opt_attribs)); } catch(e) {} if (context) { break; } } return context; } return { create3DContext: create3DContext, setupWebGL: setupWebGL }; }(); /** * Provides requestAnimationFrame in a cross browser way. */ window.requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) { window.setTimeout(callback, 1000/60); }; })();
import {Button} from 'widget/button' import {compose} from 'compose' import {connect, select} from 'store' import Portal from 'widget/portal' import PropTypes from 'prop-types' import React from 'react' import styles from './menu.module.css' const mapStateToProps = () => ({ appDimensions: select('dimensions') }) class Menu extends React.Component { state = {} button = React.createRef() menuStyle() { const {appDimensions} = this.props const buttonPosition = this.button.current.getBoundingClientRect() const maxHeight = appDimensions.height - buttonPosition.bottom - 10 const width = '20rem' return { top: buttonPosition.bottom, left: `calc(${buttonPosition.right}px - ${width})`, right: buttonPosition.right, width, maxWidth: width, height: 'fit-content', maxHeight, } } toggleOpen() { this.setState(({open}) => ({open: !open})) } render() { const {disabled, children} = this.props const {open} = this.state return <React.Fragment> <span ref={this.button}> <Button chromeless look='transparent' size='large' shape='circle' icon='bars' disabled={disabled} onClick={() => this.toggleOpen()}/> </span> {open ? <Portal type='global'> <MenuContext.Provider value={this}> <div className={styles.captureClicks} onClick={() => this.toggleOpen()}/> <ul className={styles.list} style={this.menuStyle()}> {children} </ul> </MenuContext.Provider> </Portal> : null} </React.Fragment> } } Menu.propTypes = { appDimensions: PropTypes.object, children: PropTypes.any, className: PropTypes.string, disabled: PropTypes.any, onClick: PropTypes.func } export default compose( Menu, connect(mapStateToProps) ) const MenuContext = React.createContext() export const MenuItem = ({onSelect, children}) => <MenuContext.Consumer> {menu => <li className={styles.menuItem} onClick={e => { menu.toggleOpen() onSelect && onSelect(e) }}>{children}</li> } </MenuContext.Consumer> MenuItem.propTypes = { children: PropTypes.any, onSelect: PropTypes.func }
var React = require('react-native'); var { AppRegistry, } = React; var PasswordGesture = require('react-native-gesture-password'); var Password1 = ''; var AppDemo = createReactClass({ // Example for check password onEnd: function(password) { if (password == '123') { this.setState({ status: 'right', message: 'Password is right, success.' }); // your codes to close this view } else { this.setState({ status: 'wrong', message: 'Password is wrong, try again.' }); } }, onStart: function() { this.setState({ status: 'normal', message: 'Please input your password.' }); }, // Example for set password /* onEnd: function(password) { if ( Password1 === '' ) { // The first password Password1 = password; this.setState({ status: 'normal', message: 'Please input your password secondly.' }); } else { // The second password if ( password === Password1 ) { this.setState({ status: 'right', message: 'Your password is set to ' + password }); Password1 = ''; // your codes to close this view } else { this.setState({ status: 'wrong', message: 'Not the same, try again.' }); } } }, onStart: function() { if ( Password1 === '') { this.setState({ message: 'Please input your password.' }); } else { this.setState({ message: 'Please input your password secondly.' }); } }, */ getInitialState: function() { return { message: 'Please input your password.', status: 'normal' } }, render: function() { return ( <PasswordGesture ref='pg' status={this.state.status} message={this.state.message} onStart={() => this.onStart()} onEnd={(password) => this.onEnd(password)} /> ); } }); AppRegistry.registerComponent('AppDemo', () => AppDemo);
'use strict'; var http = require('http'), spotify = require('spotify-node-applescript'), express = require('express'); var app = express(); app.get('/', function (request, response) { response.send('ok'); }); app.post('/skip', function (request, response) { spotify.next(function () { response.set('Connection', 'close'); console.log("Skipped to next track"); response.send('ok'); }); }); app.listen(3000); console.log("Listening on port 3000");
version https://git-lfs.github.com/spec/v1 oid sha256:53d32de02f1b42ece2e9db45e92ffc2feb05486776853be8b2cdfb2abf4d04e0 size 82
import attr from "ember-data/attr"; import Model from "ember-data/model"; export default Model.extend({ version: attr( "string", { defaultValue: "" } ), checkagain: attr( "number", { defaultValue: 0 } ) }).reopenClass({ toString() { return "Versioncheck"; } });
var inputFileName = process.argv[2] || './data/dependenciesGraph.out.graph'; var path = require('path'); // You'll need to run git clone git@gist.github.com:8e8fa57c7ee1350e3491.git // in the export folder to get this path: var outputDir = 'export/8e8fa57c7ee1350e3491'; var count = process.argv[3] || 1000; var prefix = process.argv[4] || ''; var centrality = require('ngraph.centrality'); var fromjson = require('ngraph.fromjson'); var pagerank = require('ngraph.pagerank'); var hitsrank = require('ngraph.hits'); var fs = require('fs'); var graph = fromjson(fs.readFileSync(inputFileName, 'utf8')); var dumpTime = (new Date().toUTCString()); saveFile( '01.most-dependent-upon.md', centrality.degree(graph, 'in'), '# Top ' + count + ' most depended-upon packages' ); saveFile( '02.with-most-dependencies.md', centrality.degree(graph, 'out'), '# Top ' + count + ' packages with most dependencies' ); saveFile( '03.pagerank.md', pagerank(graph, 0.85, 1e-10), '# Top ' + count + ' packages with highest Pagerank' ); saveFile( '04.hits-rank.md', hitsrank(graph), '# Top ' + count + ' packages with highest authority in HITS rank', hitsSort, hitsPrint ); function saveFile(fileName, data, header, sort, print) { var name = path.join(outputDir, prefix + fileName); var fd = fs.openSync(name, 'w') fs.writeSync(fd, '* Date: ' + dumpTime + '\n'); fs.writeSync(fd, '* Input file: `' + inputFileName + '`\n'); fs.writeSync(fd, '\n'); fs.writeSync(fd, header + '\n'); printTop(fd, data, sort, print); fs.writeSync(fd, '\n'); fs.writeSync(fd, 'Data generated by https://github.com/anvaka/npmrank\n'); fs.closeSync(fd); } return; function printTop(fd, stats, sort, print) { sort = sort || byValue; print = print || toLink; var allKeys = Object.keys(stats); var idx = 0; var packages = allKeys.sort(sortProxy) .slice(0, Math.min(count, allKeys.length)) .map(mapProxy) .join('\n'); fs.writeSync(fd, '\n'); fs.writeSync(fd, packages); fs.writeSync(fd, '\n'); function sortProxy(x, y) { return sort(stats, x, y); } function mapProxy(x) { return print(stats, x, idx++); } function byValue(stats, x, y) { return stats[y] - stats[x]; } function toLink(stats, x, idx) { return idx + '. [' + x + '](https://www.npmjs.org/package/' + x + ') - ' + stats[x]; } } function hitsSort(stats, x, y) { return stats[y].authority - stats[x].authority; } function hitsPrint(stats, x, idx) { return idx + '. [' + x + '](https://www.npmjs.org/package/' + x + ') - ' + stats[x].authority; }
function solve(args) { // ThirdDigit // const args = ['9999799']; var number = +args[0]; var thirdDigit = (Math.floor(number / 100)) % 10; var targetDigit = 7; console.log((thirdDigit == targetDigit) ? 'true' : 'false ' + thirdDigit); }