text
stringlengths
2
6.14k
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; const core_1 = require('@angular/core'); let NotificationService = class NotificationService { constructor() { this._notifier = alertify; } printSuccessMessage(message) { this._notifier.success(message); } printErrorMessage(message) { this._notifier.error(message); } printConfirmationDialog(message, okCallback) { this._notifier.confirm(message, function (e) { if (e) { okCallback(); } else { } }); } }; NotificationService = __decorate([ core_1.Injectable(), __metadata('design:paramtypes', []) ], NotificationService); exports.NotificationService = NotificationService;
/** * StoneShadow :: This class is used for drawing stone shadows on the board. */ /** * Module definition and dependencies */ angular.module('ngGo.Board.Object.StoneShadow.Service', [ 'ngGo', 'ngGo.Board.Object.Service', ]) /** * Factory definition */ .factory('StoneShadow', function() { /** * Constructor */ const StoneShadow = { /** * Draw a stone shadow */ draw(stone) { //No context? if (!this.context) { return; } //Don't draw shadows if there is stone alpha or if explicitly stated if ((stone.alpha && stone.alpha < 1) || stone.shadow === false) { return; } //Get coordinates and stone radius const x = this.board.getAbsX(stone.x); const y = this.board.getAbsY(stone.y); const s = this.board.getCellSize(); const r = Math.max( 0, this.board.theme.get('stone.radius', s, stone.scale) - 0.5 ); //Get theme properties const blur = this.board.theme.get('shadow.blur', s); const offsetX = this.board.theme.get('shadow.offsetX', s); const offsetY = this.board.theme.get('shadow.offsetY', s); const shadowColor = this.board.theme.get('shadow.color'); //Configure context this.context.fillStyle = this.context.createRadialGradient( x + offsetX, y + offsetY, r - 1 - blur, x + offsetX, y + offsetY, r + blur ); this.context.fillStyle.addColorStop(0, shadowColor); this.context.fillStyle.addColorStop(1, 'rgba(0,0,0,0)'); //Draw shadow this.context.beginPath(); this.context.arc(x + offsetX, y + offsetY, r + blur, 0, 2 * Math.PI, true); this.context.fill(); }, /** * Clear a stone shadow */ clear(stone) { //NOTE: this method is currently not in use due to the overlapping shadows //problem. Instead, the entire shadow layer is simply cleared and redrawn //when removing stones. The multiple canvasses solution from WGo didn't //seem appropriate either, so for now we will leave it at this. //No context? if (!this.context) { return; } //Don't draw shadows if there is stone alpha or if explicitly stated if ((stone.alpha && stone.alpha < 1) || stone.shadow === false) { return; } //Get coordinates and stone radius const x = this.board.getAbsX(stone.x); const y = this.board.getAbsY(stone.y); const s = this.board.getCellSize(); const r = this.board.theme.get('stone.radius', s); //Clear a generous rectangle this.context.clearRect(x - 1.2 * r, y - 1.2 * r, 2.4 * r, 2.4 * r); }, }; //Return return StoneShadow; });
'use strict'; var THREE = require('three'); var TWEEN = require('tween.js'); var glslify = require('glslify'); var Events = require('../../events/Events'); var State = require('../../state/State'); var MathUtils = require('../utils/MathUtils'); function Sky () { var geometry = new THREE.SphereBufferGeometry(100, 64, 64); var material = new THREE.ShaderMaterial( { uniforms: { colorTop: { type: 'c', value: new THREE.Color(0x353449) }, colorBottom: { type: 'c', value: new THREE.Color(0xBC483E) } }, vertexShader: glslify('../shaders/sky.vert'), fragmentShader: glslify('../shaders/sky.frag'), side: THREE.BackSide } ); THREE.Mesh.call(this, geometry, material); this.isSkyFading = false; this.sunrise = 0; this.isSkyStorming = false; this.thunder = 0; this.scene = State.get('scene'); Events.on('updateScene', this.update.bind(this)); Events.on('stageChanged', this.stageChanged.bind(this)); Events.on('stormStarted', this.stormStarted.bind(this)); // this.material.uniforms.colorTop.value = new THREE.Color(0x33b66d); // this.material.uniforms.colorBottom.value = new THREE.Color(0x4bb8dd); // this.scene.fog.color = new THREE.Color(0x4bb8dd); } Sky.prototype = Object.create(THREE.Mesh.prototype); Sky.prototype.update = function (delta, time) { // console.log(this.sunrise); if (this.isSkyStorming) { this.material.uniforms.colorTop.value = new THREE.Color(MathUtils.blendColors(0x999999, 0xffffff, this.thunder)); this.material.uniforms.colorBottom.value = new THREE.Color(MathUtils.blendColors(0xffffff, 0x4bb8dd, this.thunder)); this.scene.fog.color = new THREE.Color(MathUtils.blendColors(0xffffff, 0x4bb8dd, this.thunder)); return; } if (this.isSkyFading) { this.material.uniforms.colorTop.value = new THREE.Color(MathUtils.blendColors(0x353449, 0x33b66d, this.sunrise)); this.material.uniforms.colorBottom.value = new THREE.Color(MathUtils.blendColors(0xBC483E, 0x4bb8dd, this.sunrise)); this.scene.fog.color = new THREE.Color(MathUtils.blendColors(0xBC483E, 0x4bb8dd, this.sunrise)); } // if (this.isStorming) { // // } }; Sky.prototype.stormStarted = function (newStage) { // One frame for the thunder this.isSkyStorming = true; var self = this; new TWEEN.Tween(this).to({ thunder: 1 }, 400) .easing(TWEEN.Easing.Quadratic.In) .onComplete(function () { self.isSkyStorming = false; }) .start(); // this.material.uniforms.colorTop.value = new THREE.Color(0xffffff); // this.material.uniforms.colorBottom.value = new THREE.Color(0x4bb8dd); // this.scene.fog.color = new THREE.Color(0x4bb8dd); }; Sky.prototype.stageChanged = function (newStage) { var self = this; switch (newStage) { case 'ending': if (State.get('endMode') === 1) { new TWEEN.Tween(this).to({ sunrise: 1 }, 15000) .easing(TWEEN.Easing.Quadratic.In) .start(); this.isSkyFading = true; } break; } }; module.exports = Sky;
"use strict"; angular.module("ehelseEditor").factory("Action", ["$rootScope", "StorageHandler", "ServiceFunction", function($rootScope, StorageHandler, ServiceFunction) { var actions = []; var actions_dict = {}; var actions_option_list = []; init(); function init(){ try{ Array.prototype.push.apply(actions, StorageHandler.getActions().actions); generateActionsOptionList(actions); generateActionsDict(actions); } catch(error){ $rootScope.notifyError("Handlinger kunne ikke lastes: " + error, 6000); console.log("Actions did not load " + error); } } /** * Function used to clear all lists and dicts used in Action. */ function clear(){ actions.length = 0; actions_dict = {}; actions_option_list.length = 0; } /** * Function creating a new action * @returns Action */ function newAction(){ return { id: null, name: "", description: "", isArchived: 0 }; } /** * Function updating the content of the a object to match the content of b * * This is done to take advantage of angular listening of changes to an object. * If the object is changed insted of replaced is the cahnge reflected in the gui. * @param a * @param b */ function set(a, b){ a.id = b.id; a.name = b.name; a.description = b.description; a.isArchived = b.isArchived; } /** * Add a newly created Action to the list of actions and regenerates the action_dict and the actions_options_list * @param action */ function add(action){ actions.push(action); generateActionsDict(actions); generateActionsOptionList(actions); } /** * Function returning a clone of a Action object. * * The object can then be changed while maintaining a copy of the original action * @param action * @returns Action */ function clone(action){ var a = {}; set(a, action); return a; } /** * Function generating an name, value pairs to be used in option lists. * @param actions */ function generateActionsOptionList(actions){ actions_option_list.length = 0; for (var i = 0; i < actions.length; i++) { actions_option_list.push({ name: actions[i].name, value: actions[i].id, isArchived: actions[i].isArchived }); } } /** * Function generating a dict of actions with the actions id as key. * * Used to display the name of the action in places were only the id is available * @param actions */ function generateActionsDict(actions){ for(var i = 0; i < actions.length; i++){ actions_dict[actions[i].id] = actions[i]; } } function initNewActionValues(action){ action.id = ServiceFunction.generateNewId(actions); action.isArchived = 0; } /** * Function posting or updating an action based on if the action has an id or not. * @param action */ function submit(action){ //Having an id indicates the action is stored in the database and only needs to be updated if(action.id){ try{ set(actions_dict[action.id], action); generateActionsDict(actions); generateActionsOptionList(actions); $rootScope.notifySuccess("Handling ble oppdatert", 1000); } catch(error){ $rootScope.notifyError("Handling ble ikke oppdatert: " + error, 6000); console.log("Action could not be updated" + error); } } else{ try{ initNewActionValues(action); add(action); $rootScope.notifySuccess("Ny handling ble opprettet", 1000); } catch(error){ $rootScope.notifyError("Handling kunne ikke opprettes: " + error, 6000); console.log("Action could not be created" + error); } } } /** * Function removing an action from the action list and regeneration action_dict and action_option_list * @param action */ function archiveAction(action) { action.isArchived = 1; generateActionsDict(actions); generateActionsOptionList(actions) } /** * Function deleting an action from the database * @param action */ function deleteAction(action) { try{ archiveAction(action); $rootScope.notifySuccess("Handling ble arkivert!", 1000); } catch(error){ $rootScope.notifyError("Handling ble ikke arkivert: " + error, 6000); console.log("Action could not be archived" + error); } } function getAllAsDict(){ return actions_dict; } function getAll(){ return actions; } function getAllAsOptionsList(){ return actions_option_list; } function getById(id){ return actions_dict[id]; } return { clear: clear, init: init, new: newAction, clone: clone, submit: submit, delete: deleteAction, getById : getById, getAll : getAll, getAllAsDict: getAllAsDict, getAllAsOptionsList : getAllAsOptionsList }; }]);
// This module simulates the propeller and its interaction with hull and engine. function PropellerInteraction(ship, states, propeller, rho = 1025) { StateModule.call(this, ship, states); // get resistance results in N, W from vessel state this.propeller = propeller; if (typeof this.states.discrete.FloatingCondition === "undefined") { this.setDraft(); } if (typeof this.states.discrete.Speed === "undefined") { // if vessel does not have a speed state this.setSpeed(); // use its design speed } this.speedState = this.states.discrete.Speed.state; this.floatState = this.states.discrete.FloatingCondition.state; this.resistanceState = this.states.discrete.HullResistance.state; this.rho = rho; // kg/m³ this.output = ["propulsion"]; this.cacheDependence = ["FloatingCondition", "Speed"]; this.cache = {}; } PropellerInteraction.prototype = Object.create(StateModule.prototype); Object.assign(PropellerInteraction.prototype, { constructor: PropellerInteraction, }); Object.defineProperties(PropellerInteraction.prototype, { propulsion: StateModule.prototype.memoized(function() { // convert vessel speed from knots to m/s if (this.speedSI === 0) { console.error("Speed equals to zero, try getPropResult() method to get boolard pull or use changeSpeed() method to set a non null value.") } var speedSI = 0.514444 * this.speedState.speed; var lcb = 100 * (this.floatState.LCB - (this.floatState.minXs + this.floatState.LWL / 2)) / this.floatState.LWL; // % var Va = speedSI / (1 - this.resistanceState.w); // m/s var T = this.resistanceState.Rtadd / (this.propeller.noProps * (1 - this.resistanceState.t)); // N, thrust var acoeff = T / (this.rho * Math.pow(this.propeller.D * Va, 2)); var bcoeff = this.propeller.beta2; var ccoeff = -this.propeller.beta1; var J = (-bcoeff + Math.pow(Math.pow(bcoeff, 2) - 4 * acoeff * ccoeff, 0.5)) / (2 * acoeff); var n = Va / (J * this.propeller.D); // rps // var npm = 60*n; var KT = this.propeller.beta1 - this.propeller.beta2 * J; var KQ = this.propeller.gamma1 - this.propeller.gamma2 * J; var eta0 = J * KT / (2 * Math.PI * KQ); var etar; if (this.propeller.noProps === 1) { etar = 0.9922 - 0.05908 * this.propeller.AeAo + 0.07424 * (this.floatState.Cp - 0.0225 * lcb); } else if (this.propeller.noProps === 2) { etar = 0.9737 + 0.111 * (this.floatState.Cp - 0.0225 * lcb) - 0.06325 * this.propeller.P / this.propeller.D; } var eta = eta0 * this.resistanceState.etah * etar; var Ps = this.resistanceState.Pe / eta; // W, required brake power return {eta, Ps, n, Va}; }, "propulsion") });
ace.define("ace/snippets/django",["require","exports","module"], function(require, exports, module) { "use strict"; exports.snippetText = "# Model Fields\n\ \n\ # Note: Optional arguments are using defaults that match what Django will use\n\ # as a default, e.g. with max_length fields. Doing this as a form of self\n\ # documentation and to make it easy to know whether you should override the\n\ # default or not.\n\ \n\ # Note: Optional arguments that are booleans will use the opposite since you\n\ # can either not specify them, or override them, e.g. auto_now_add=False.\n\ \n\ snippet auto\n\ ${1:FIELDNAME} = models.AutoField(${2})\n\ snippet bool\n\ ${1:FIELDNAME} = models.BooleanField(${2:default=True})\n\ snippet char\n\ ${1:FIELDNAME} = models.CharField(max_length=${2}${3:, blank=True})\n\ snippet comma\n\ ${1:FIELDNAME} = models.CommaSeparatedIntegerField(max_length=${2}${3:, blank=True})\n\ snippet date\n\ ${1:FIELDNAME} = models.DateField(${2:auto_now_add=True, auto_now=True}${3:, blank=True, null=True})\n\ snippet datetime\n\ ${1:FIELDNAME} = models.DateTimeField(${2:auto_now_add=True, auto_now=True}${3:, blank=True, null=True})\n\ snippet decimal\n\ ${1:FIELDNAME} = models.DecimalField(max_digits=${2}, decimal_places=${3})\n\ snippet email\n\ ${1:FIELDNAME} = models.EmailField(max_length=${2:75}${3:, blank=True})\n\ snippet file\n\ ${1:FIELDNAME} = models.FileField(upload_to=${2:path/for/upload}${3:, max_length=100})\n\ snippet filepath\n\ ${1:FIELDNAME} = models.FilePathField(path=${2:\"/abs/path/to/dir\"}${3:, max_length=100}${4:, match=\"*.ext\"}${5:, recursive=True}${6:, blank=True, })\n\ snippet float\n\ ${1:FIELDNAME} = models.FloatField(${2})\n\ snippet image\n\ ${1:FIELDNAME} = models.ImageField(upload_to=${2:path/for/upload}${3:, height_field=height, width_field=width}${4:, max_length=100})\n\ snippet int\n\ ${1:FIELDNAME} = models.IntegerField(${2})\n\ snippet ip\n\ ${1:FIELDNAME} = models.IPAddressField(${2})\n\ snippet nullbool\n\ ${1:FIELDNAME} = models.NullBooleanField(${2})\n\ snippet posint\n\ ${1:FIELDNAME} = models.PositiveIntegerField(${2})\n\ snippet possmallint\n\ ${1:FIELDNAME} = models.PositiveSmallIntegerField(${2})\n\ snippet slug\n\ ${1:FIELDNAME} = models.SlugField(max_length=${2:50}${3:, blank=True})\n\ snippet smallint\n\ ${1:FIELDNAME} = models.SmallIntegerField(${2})\n\ snippet text\n\ ${1:FIELDNAME} = models.TextField(${2:blank=True})\n\ snippet time\n\ ${1:FIELDNAME} = models.TimeField(${2:auto_now_add=True, auto_now=True}${3:, blank=True, null=True})\n\ snippet url\n\ ${1:FIELDNAME} = models.URLField(${2:verify_exists=False}${3:, max_length=200}${4:, blank=True})\n\ snippet xml\n\ ${1:FIELDNAME} = models.XMLField(schema_path=${2:None}${3:, blank=True})\n\ # Relational Fields\n\ snippet fk\n\ ${1:FIELDNAME} = models.ForeignKey(${2:OtherModel}${3:, related_name=''}${4:, limit_choices_to=}${5:, to_field=''})\n\ snippet m2m\n\ ${1:FIELDNAME} = models.ManyToManyField(${2:OtherModel}${3:, related_name=''}${4:, limit_choices_to=}${5:, symmetrical=False}${6:, through=''}${7:, db_table=''})\n\ snippet o2o\n\ ${1:FIELDNAME} = models.OneToOneField(${2:OtherModel}${3:, parent_link=True}${4:, related_name=''}${5:, limit_choices_to=}${6:, to_field=''})\n\ \n\ # Code Skeletons\n\ \n\ snippet form\n\ class ${1:FormName}(forms.Form):\n\ \"\"\"${2:docstring}\"\"\"\n\ ${3}\n\ \n\ snippet model\n\ class ${1:ModelName}(models.Model):\n\ \"\"\"${2:docstring}\"\"\"\n\ ${3}\n\ \n\ class Meta:\n\ ${4}\n\ \n\ def __unicode__(self):\n\ ${5}\n\ \n\ def save(self, force_insert=False, force_update=False):\n\ ${6}\n\ \n\ @models.permalink\n\ def get_absolute_url(self):\n\ return ('${7:view_or_url_name}' ${8})\n\ \n\ snippet modeladmin\n\ class ${1:ModelName}Pages(admin.ModelAdmin):\n\ ${2}\n\ \n\ admin.site.register($1, $1Admin)\n\ \n\ snippet tabularinline\n\ class ${1:ModelName}Inline(admin.TabularInline):\n\ model = $1\n\ \n\ snippet stackedinline\n\ class ${1:ModelName}Inline(admin.StackedInline):\n\ model = $1\n\ \n\ snippet r2r\n\ return render_to_response('${1:template.html}', {\n\ ${2}\n\ }${3:, context_instance=RequestContext(request)}\n\ )\n\ "; exports.scope = "django"; });
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { PropTypes } from 'react'; import cx from 'classnames'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './ZNavigationIn.css'; import Link from '../Link'; class ZNavigationIn extends React.Component { static propTypes = { className: PropTypes.string, }; render() { return ( <div className={cx(s.root, this.props.className)} role="ZNavigation"> <Link className={s.link} to="/settings">Settings</Link> <Link className={s.link} to="/logout">Log out</Link> </div> ); } } export default withStyles(s)(ZNavigationIn);
import Keet, { html } from '../' import { getId } from '../utils' class App extends Keet { el = 'app' text = 'foo' condition = false componentDidUpdate () { console.assert(getId('app').innerHTML === '<div id="foo" bar="">foo</div>', 'attributes with handlebars') } render () { return html` <div id={{text}} {{condition?foo:bar}}>{{text}}</div> ` } } export default new App()
module.exports = function(grunt) { grunt.initConfig({ clean: { appStyles: { src: [ 'public/dist/app.less', 'public/dist/app.css', ] }, appScripts: { src: ['public/dist/app.js'] } }, concat: { appStyles: { src: ['public/styles/**/*.less'], dest: 'public/dist/app.less' }, appScripts: { src: ['public/scripts/**/*.js'], dest: 'public/dist/app.js' } }, cssmin: { appStyles: { files: { 'public/dist/app.min.css': ['public/dist/app.css'] } } }, jshint: { files: [ 'Gruntfile.js', 'public/scripts/**/*.js', 'spec/**/*.js' ], options: { jshintrc: '.jshintrc' } }, less: { appStyles: { options: { // Path to look for @import directives. paths: ['public/styles'] }, files: { 'public/dist/app.css': 'public/dist/app.less' } } }, uglify: { appScripts: { files: { 'public/dist/app.min.js': ['public/dist/app.js'] } } }, watch: { all: { files: [ 'Gruntfile.js', 'public/index.html', 'public/partials/**/*.html', 'public/scripts/**/*.js', 'public/styles/**/*.less' ], tasks: ['default'], options: { spawn: false, livereload: true } } } }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', [ 'jshint', 'concat:appStyles', 'less:appStyles', 'cssmin:appStyles', 'concat:appScripts', 'uglify:appScripts', 'clean:appStyles', 'clean:appScripts' ]); };
/** * Module dependencies. */ var Check = require('../../../models/check'); var CheckEvent = require('../../../models/checkEvent'); var CheckHourlyStat = require('../../../models/checkHourlyStat'); var CheckDailyStat = require('../../../models/checkDailyStat'); var CheckMonthlyStat = require('../../../models/checkMonthlyStat'); /** * Check Routes */ module.exports = function(app) { app.get('/checks', function(req, res, next) { var query = {}; if (req.query.tag) { query.tags = req.query.tag; } Check .find(query) .sort({ isUp: 1, lastChanged: -1 }) .exec(function(err, checks) { if (err) return next(err); res.json(checks); }); }); app.get('/checks/needingPoll', function(req, res, next) { Check .needingPoll() .select({qos: 0}) .exec(function(err, checks) { if (err) return next(err); res.json(checks); }); }); // check route middleware var loadCheck = function(req, res, next) { Check .find({ _id: req.params.id }) .select({qos: 0}) .findOne(function(err, check) { if (err) return next(err); if (!check) return res.json(404, { error: 'failed to load check ' + req.params.id }); req.check = check; next(); }); }; app.get('/checks/:id', loadCheck, function(req, res, next) { res.json(req.check); }); app.get('/checks/:id/pause', loadCheck, function(req, res, next) { req.check.togglePause(); req.check.save(function(err) { if (err) return next(new Error('failed to toggle pause on check' + req.params.id)); new CheckEvent({ timestamp: new Date(), check: req.check, tags: req.check.tags, message: req.check.isPaused ? 'paused' : 'restarted' }).save(); res.redirect(app.route + '/checks/' + req.params.id); }); }); app.put('/check/:id/test', function (req, res, next) { Check.update({ _id: req.params.id }, { lastTested: new Date() }, function(err, numberAffected) { if (err) return next(err); res.json({ numberAffected: numberAffected }); }); }); app.get('/checks/:id/stat/:period/:timestamp', loadCheck, function(req, res, next) { req.check.getSingleStatForPeriod(req.params.period, new Date(parseInt(req.params.timestamp)), function(err, stat) { if (err) return next(err); res.json(stat); }); }); app.get('/checks/:id/stats/:type', loadCheck, function(req, res, next) { req.check.getStatsForPeriod(req.params.type, req.query.begin, req.query.end, function(err, stats) { if(err) return next(err); res.json(stats); }); }); app.get('/checks/:id/events', function(req, res, next) { var query = { check: req.params.id, timestamp: { $gte: req.query.begin || new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) } }; if (req.query.end) { query.timestamp.$lte = req.query.end; } CheckEvent .find(query) .sort({ timestamp: -1 }) .select({tags: 0}) .limit(100) .exec(function(err, events) { if (err) return next(err); CheckEvent.aggregateEventsByDay(events, function(err, aggregatedEvents) { if(err) return next(err); res.json(aggregatedEvents); }); }); }); };
const commander = require('../'); // These are tests of the Help class, not of the Command help. // There is some overlap with the higher level Command tests (which predate Help). describe('longestOptionTermLength', () => { test('when no option then returns zero', () => { const program = new commander.Command(); program.helpOption(false); const helper = new commander.Help(); expect(helper.longestOptionTermLength(program, helper)).toEqual(0); }); test('when just implicit help option returns length of help flags', () => { const program = new commander.Command(); const helper = new commander.Help(); expect(helper.longestOptionTermLength(program, helper)).toEqual('-h, --help'.length); }); test('when multiple option then returns longest length', () => { const longestOptionFlags = '-l, --longest <value>'; const program = new commander.Command(); program .option('--before', 'optional description of flags') .option(longestOptionFlags) .option('--after'); const helper = new commander.Help(); expect(helper.longestOptionTermLength(program, helper)).toEqual(longestOptionFlags.length); }); });
'use strict'; 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 _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var React = require('react'); var ReactDOM = require('react-dom'); var GeminiScrollbar = require('gemini-scrollbar'); var PropTypes = require('prop-types'); var ReactGeminiScrollbar = function (_React$Component) { _inherits(ReactGeminiScrollbar, _React$Component); function ReactGeminiScrollbar() { _classCallCheck(this, ReactGeminiScrollbar); return _possibleConstructorReturn(this, (ReactGeminiScrollbar.__proto__ || Object.getPrototypeOf(ReactGeminiScrollbar)).apply(this, arguments)); } _createClass(ReactGeminiScrollbar, [{ key: 'componentDidMount', value: function componentDidMount() { this.scrollbar = new GeminiScrollbar({ element: ReactDOM.findDOMNode(this), autoshow: this.props.autoshow, forceGemini: this.props.forceGemini, createElements: false, onResize: this.props.onResize, minThumbSize: this.props.minThumbSize }).create(); } /** * Holds the reference to the GeminiScrollbar instance. * @property scrollbar <public> [Object] */ }, { key: 'componentDidUpdate', value: function componentDidUpdate() { this.scrollbar.update(); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (this.scrollbar) { this.scrollbar.destroy(); } this.scrollbar = null; } }, { key: 'render', value: function render() { var _props = this.props, className = _props.className, children = _props.children, autoshow = _props.autoshow, forceGemini = _props.forceGemini, onResize = _props.onResize, minThumbSize = _props.minThumbSize, other = _objectWithoutProperties(_props, ['className', 'children', 'autoshow', 'forceGemini', 'onResize', 'minThumbSize']); var classes = ''; if (className) { classes += ' ' + className; } return React.createElement( 'div', _extends({}, other, { className: classes }), React.createElement( 'div', { className: 'gm-scrollbar -vertical' }, React.createElement('div', { className: 'thumb' }) ), React.createElement( 'div', { className: 'gm-scrollbar -horizontal' }, React.createElement('div', { className: 'thumb' }) ), React.createElement( 'div', { className: 'gm-scroll-view' }, children ) ); } }]); return ReactGeminiScrollbar; }(React.Component); ReactGeminiScrollbar.propTypes = { autoshow: PropTypes.bool, forceGemini: PropTypes.bool, onResize: PropTypes.func, minThumbSize: PropTypes.number }; ReactGeminiScrollbar.defaultProps = { autoshow: false, forceGemini: false, minThumbSize: 20 }; module.exports = ReactGeminiScrollbar;
'use strict'; function Layout () { this.indent = 4; this.columns = process.stdout.columns; } Layout.prototype.layoutPoint = function (point, indent) { var bullet = '-', indents = [[]], i, c, current, result = [], temp = point.text.split(''); function addToIndent () { this.unshift(' '); } function finalize (current) { var indent = indents.shift(); Array.prototype.unshift.apply(current, indent); if (!indents.length) { indents.unshift(indent); } result.push(current); } if (!!point.label) { if (point.label !== true) { bullet = '' + point.label; } Array.apply(null, {length : this.indent}).forEach(addToIndent, indents[0]); indents.unshift([]); if (bullet.length < this.indent) { Array.apply(null, {length : this.indent - bullet.length}).forEach(addToIndent, indents[0]); Array.prototype.unshift.apply(indents[0], bullet.split('')); } else { indents[0] = bullet.split(''); indents[0].push(' '); } } while (temp.length > 1) { while (temp.length && (c = temp.shift()) === ' '); temp.unshift(c); current = temp.splice(0, this.columns - indents[0].length); if ((c = temp.shift()) === ' ') { finalize(current); } else { if (c !== undefined) { temp.unshift(c); } while (temp.length && (c = current.pop()) !== ' ') { temp.unshift(c); } if (current.length === 0) { current = temp.splice(0, this.columns); } finalize(current); } } return result.map(function (d) { return d.join(''); }); } module.exports = Layout;
({ baseUrl: '.', paths: { lodash: '../../node_modules/lodash/dist/lodash', moment: '../../node_modules/moment/moment' }, name: 'run', out: 'bundle.js', wrap: true, optimize: 'none' })
const path = require('path'); const Promise = require("bluebird"); const SIMPLE_APP = path.join(__dirname, '../test-server'); const app = require(path.join(SIMPLE_APP, 'server/server.js')); Promise.map(["AccessToken", "Book", "Member"], model => { return app.models[model].destroyAll(null, {skipAcl: true}) }).then(() => { console.log("Deleted ..."); process.exit(); }).catch(err => { console.err(err); });
/** * * @authors (nowdence@aliyun.com) * @date 2015-09-16 22:34:09 * @version $Id$ */ /* 定义一个Calculator类*/ function Calculator() { this.calculate = function(num1, num2, oper) { var res = 0; switch (oper) { case "+": res = num1 + num2; break; case "-": res = num1 - num2; break; case "*": res = num1 * num2; break; case "/": if (num2 == 0) { alert("除数不能为0"); res = "∞"; } else { res = num1 / num2; }; break; } return res; } } //创建对象 var calculator = new Calculator(); /*定义全局变量*/ var val = 0; //放置输入的值 var xval = 0; //保存转换Number类型的值 var temp = 0; //保存第一次输入的值 var oper = ""; //保存输入的操作符 /*获取输入数字*/ function inputEvent(e) { val = e.value var xsval = document.getElementById("inp1"); xsval.value += val; //连续输入数字(String类型) //转换Number类型 xval = parseFloat(xsval.value); } /*获取第一行的数据*/ function inputPCB(e) { //window.alert(e.value); var xsval = document.getElementById("inp1"); if (e.value == "Clear") { xsval.value = ""; } else if (e.value == "Square") { //计算平方 xsval.value = Math.pow(xsval.value, 2); } } /*输入操作符*/ function inputOper(e) { oper = e.value; //window.alert(typeof oper); //oper=oper.substr(0); if (e.value == "+") { var xsval = document.getElementById("inp1"); //保存上次计算结果,并对字符串进行转换Number类型 temp = parseFloat(xsval.value); //第一次输入的值设置为空 xsval.value = ""; } else if (e.value == "-") { var xsval = document.getElementById("inp1"); temp = parseFloat(xsval.value); xsval.value = ""; } else if (e.value == "*") { var xsval = document.getElementById("inp1"); temp = parseFloat(xsval.value); xsval.value = ""; } else if (e.value == "/") { var xsval = document.getElementById("inp1"); temp = parseFloat(xsval.value); xsval.value = ""; } } /*计算结果*/ function inputEquel(e) { var xsval = document.getElementById("inp1"); if (e.value == "=") { xsval.value = temp + oper + xval + "=" + calculator.calculate(temp, xval, oper); } }
import d3 from "d3"; import notchedRect from "./notchedRect"; import roundRect from "./roundRect"; import sensorRange from "./sensorRange"; import sensorReading from "./sensorReading"; import bumper from "./bumper"; import {degToRad} from "../../common"; import dimensions from "../../dimensions"; // sensor settings let irWidth = dimensions.ir.width; let frontIRRange = dimensions.ir.front.range; let frontIRAngle = dimensions.ir.front.angle; let sideIRRange = dimensions.ir.side.range; let sideIRAngle = dimensions.ir.side.angle; let usWidth = dimensions.us.width; let usRange = dimensions.us.range; let usAngle = dimensions.us.angle; // robot settings let width = dimensions.base.width; let height = dimensions.base.height; let halfWidth = width / 2; let halfHeight = height / 2; let topBaseNotch = dimensions.base.top.notch; let bottomBaseNotch = dimensions.base.bottom.notch; let topBaseWidth = dimensions.base.top.width; let baseDiff = (width - topBaseWidth) / 2; let wheelRadius = dimensions.wheel.radius; let wheelWidth = dimensions.wheel.width; let rasPiWidth = dimensions.raspi.width; let rasPiHeight = dimensions.raspi.height; let bumperOffset = dimensions.bumper.offset; export default function appendRobot(selection) { selection.each(function() { let root = d3.select(this) .classed("robot", true); // SENSORS let sensors = root.append("g") .classed("sensors", true); // left bumper let leftBumper = sensors.append("path") .attr("class", "bumper left-bumper") .attr("d", bumper(-width/2-bumperOffset, -width/2-bumperOffset, width/2, height/2-wheelRadius, bottomBaseNotch)); // right bumper let rightBumper = sensors.append("path") .attr("class", "bumper right-bumper") .attr("transform", "scale(-1,1)") .attr("d", bumper(-width/2-bumperOffset, -width/2-bumperOffset, width/2, height/2-wheelRadius, bottomBaseNotch)); // left IR sensor let leftFrontIR = sensors.append("g") .attr("transform", "translate(-9,-9)") .append("g") .attr("class", "left-ir-sensor") leftFrontIR.append("path") .attr("class", "sensor-range") .attr("d", sensorRange(irWidth, frontIRRange, frontIRAngle)); leftFrontIR.append("path") .attr("class", "left-ir-reading"); // right IR sensor let rightFrontIR = sensors.append("g") .attr("transform", "translate(9,-9)") .append("g") .attr("class", "right-ir-sensor") rightFrontIR.append("path") .attr("class", "sensor-range") .attr("d", sensorRange(irWidth, frontIRRange, frontIRAngle)); rightFrontIR.append("path") .attr("class", "right-ir-reading"); // left side IR sensor let leftSideIR = sensors.append("g") .attr("transform", "translate(-10,6) rotate(-90)"); leftSideIR.append("path") .attr("class", "left-side-ir-sensor sensor-range") .attr("d", sensorRange(irWidth, sideIRRange, sideIRAngle)); leftSideIR.append("path") .attr("class", "left-side-ir-reading"); // right side IR sensor let rightSideIR = sensors.append("g") .attr("transform", "translate(10,6) rotate(90)"); rightSideIR.append("path") .attr("class", "right-side-ir-sensor sensor-range") .attr("d", sensorRange(irWidth, sideIRRange, sideIRAngle)); rightSideIR.append("path") .attr("class", "right-side-ir-reading"); // ulstrasound sensor let ultrasound = sensors.append("g") .attr("transform", "translate(0,-4)"); ultrasound.append("path") .attr("class", "us-sensor sensor-range") .attr("d", sensorRange(usWidth, usRange, usAngle)); ultrasound.append("path") .attr("class", "us-reading"); // ROBOT let robot = root.append("g") .attr("transform", `translate(${-width/2}, ${-height/2})`); // the bottom base robot.append("path") .attr("class", "base bottom") .attr("d", notchedRect(0, 0, width, height, bottomBaseNotch)); // left wheel robot.append("rect") .attr("class", "wheel") .attr("x", 0) .attr("y", halfHeight - wheelRadius) .attr("width", wheelWidth) .attr("height", 2 * wheelRadius); // right wheel robot.append("rect") .attr("class", "wheel") .attr("x", width - wheelWidth) .attr("y", halfHeight - wheelRadius) .attr("width", wheelWidth) .attr("height", 2 * wheelRadius); // the top base robot.append("path") .attr("class", "base top") .attr("d", notchedRect(baseDiff, 0, topBaseWidth, height, topBaseNotch)); // the red button robot.append("circle") .attr("class", "stop-button") .attr("cx", halfWidth) .attr("cy", height - 4) .attr("r", 1.25); // the raspberry pi robot.append("path") .attr("class", "raspberry-pi") .attr("d", roundRect(halfWidth - rasPiWidth/2, 1, rasPiWidth, rasPiHeight, 0.35)); }); }
import './signup.styl'; import {SignupController as controller} from './signup.controller'; import template from './signup.html'; export const signupDirective = () => { return { template, controller, controllerAs: 'vm', scope: {}, restrict: 'E', replace: true }; };
//= link_directory ../javascripts/unity .js //= link_directory ../stylesheets/unity .css
var express = require('express'); var router = express.Router(); var mongo = require('mongodb'); var db = require('monk')('mongodb://shane:6a9e49a7@ds133340.mlab.com:33340/lionra-ireland'); router.get('/show/:category', function(req, res, next) { var posts = db.get('posts'); posts.find({category: req.params.category},{},function(err, posts){ res.render('index',{ 'title': req.params.category, 'posts': posts }); }); }); router.get('/add', function(req, res, next) { res.render('addcategory',{ 'title': 'Add Category' }); }); router.post('/add', function(req, res, next) { // Get Form Values var name = req.body.name; // Form Validation req.checkBody('name','Name field is required').notEmpty(); // Check Errors var errors = req.validationErrors(); if(errors){ res.render('addpost',{ "errors": errors }); } else { var categories = db.get('categories'); categories.insert({ "name": name, }, function(err, post){ if(err){ res.send(err); } else { req.flash('success','Category Added'); res.location('/'); res.redirect('/'); } }); } }); module.exports = router;
const mongodb = require('mongodb'); Promise = require('bluebird'); const boom = require('boom'); const monglock = require('../lib/index'); exports.main = { 'setUp': function(callback) { mongodb.MongoClient.connect('mongodb://database:27017') .then((conn) => { this.conn = conn; return conn.db('test').collection('test'); }) .then((testCol) => { return testCol.remove({}); }) .then(() => { callback(); }) .catch((err) => { throw err; }) }, 'tearDown': function(callback) { const testCol = this.conn.db('test').collection('test'); testCol.drop() .then(() => { this.conn.close(true); }) .then(() => { callback(); }) .catch((err) => { console.log(err); throw err; }) }, 'basic_functionality': function(test) { test.expect(8); const testCol = this.conn.db('test').collection('test'); var writeLock = null; var timestamp = null; testCol.insertOne({'_id': 1}).then(() => { writeLock = monglock.writeLock({'collection': testCol, 'locktimeout': 1000, 'boom': boom}); return writeLock.acquire({'_id': 1}); }).then(() => { return testCol.findOne({'_id': 1}).then((value) => { timestamp = value.lock.timestamp; test.ok(value.lock && value.lock.active === true && value.lock.timestamp, "Confirming that initial acquisition works"); }); }).then(() => { return writeLock.acquire({'_id': 2}).catch((err) => { test.ok(err && err.output && err.output.payload && err.output.payload.statusCode == 404 && err.output.payload.message == 'RessourceNotFound', "Confirming that acquisition on non-existent ressource fails with the right error"); }); }).then(() => { return writeLock.acquire({'_id': 1}).catch((err) => { test.ok(err && err.output && err.output.payload && err.output.payload.statusCode == 409 && err.output.payload.message == 'LockAlreadyTaken', "Confirming that acquisition on ressource with pre-existing lock fails with the right error"); }); }).then(() => { return writeLock.release({'_id': 2}).catch((err) => { test.ok(err && err.output && err.output.payload && err.output.payload.statusCode == 404 && err.output.payload.message == 'RessourceNotFound', "Confirming that release on non-existent ressource fails with the right error"); }); }).then(() => { return writeLock.release({'_id': 1}).then(() => { return testCol.findOne({'_id': 1}); }).then((value) => { test.ok(value.lock && value.lock.active === false, "Confirming that releasing a ressource works"); }); }).then(() => { return writeLock.acquire({'_id': 1}).then(() => { return testCol.findOne({'_id': 1}); }).then((value) => { test.ok(value.lock && value.lock.active === true && value.lock.timestamp && value.lock.timestamp != timestamp, "Confirming that further acquisition works"); timestamp = value.lock.timestamp; }); }).then(() => { return new Promise((resolve, reject) => { setTimeout(() => { return writeLock.acquire({'_id': 1}).then(() => { return testCol.findOne({'_id': 1}); }).then((value) => { test.ok(value.lock && value.lock.active === true && value.lock.timestamp && value.lock.timestamp != timestamp, "Confirming that lock timeout works"); resolve(); }).catch((err) => { reject(err); }); }, 1100); }); }).then(() => { return writeLock.release({'_id': 1}, {'timestamp': timestamp}).catch((err) => { test.ok(err && err.output && err.output.payload && err.output.payload.statusCode == 409 && err.output.payload.message == 'LockWasReacquired', "Confirming that lock-reaquisiation after timeout is reported if timestamp is passed to release"); }); }).catch((err) => { console.log(err); }).finally(() => { test.done(); }); } }
/* jshint node: true, strict: true */ "use strict"; var http = require('http'), app = require('./app.js'), config = require('./config.js'), log = require('./log.js'), ws = require('./websocket.js'), server = http.createServer(app); // Max out the number of socket connections. // Default concurrent sockets in node.js is 5. We need more! http.globalAgent.maxSockets = Infinity; // Load websocket ws.init(server); // Start http server server.listen(config.get('httpServerPort')); log.info('Web Rebels Counter running at http://localhost:' + config.get('httpServerPort') + '/'); log.info('Serving static files from ' + config.get('docRoot')); // Catch uncaught exceptions, log it and take down server in a nice way. // Upstart or forever should handle kicking the process back into life! process.on('uncaughtException', function(err) { log.error('shutdown - server taken down by force due to a uncaughtException'); log.error(err.message); log.error(err.stack); process.exit(1); }); // Listen for SIGINT (Ctrl+C) and do a gracefull takedown of the server process.on('SIGINT', function() { log.info('shutdown - taking down server gracefully'); process.exit(0); });
import { GET_GROUP_USERS_SUCCESS, GET_GROUP_USERS_FAILURE, LOGOUT_USER } from '../../constants'; /** * @function users * @description reducer that sets the redux state * with an array of users in the selected group * @param {array} state * @param {Object} action * @returns {array} group users */ export default (state = [], action) => { switch (action.type) { case GET_GROUP_USERS_SUCCESS: return action.response.data.users; case GET_GROUP_USERS_FAILURE: return []; case LOGOUT_USER: return []; default: return state; } };
$(function() { // challenge 1 - model default attribute AppointmentList = Backbone.Collection.extend({ url:domainURL+'/appointments', model: Appointment }); var appointment; window.appointments = new AppointmentList(); appointment = new Appointment({title:"Meet Josh"}); var AppointmentView; AppointmentView = Backbone.View.extend({ template :_.template("<span><%= title %></span> <a id='CancelBtn' href='#'>Cancel</a>"), events:{ "dblclick span":"notify", "click #CancelBtn":"cancelApp" }, cancelApp:function( ){ this.model.cancel( ); }, notify: function( ){ alert(this.model.get("title")); }, render: function(){ this.$el.html(this.template(this.model.toJSON())); return this; } }); var AppointmentListView = Backbone.View.extend({ initialize: function(){ this.collection.on("add",this.addOne,this); this.collection.on("reset",this.render,this); }, render:function( ){ this.addAll( ); return this; }, addOne: function(model){ var itemView = new AppointmentView({model:model}); this.$el.append(itemView.render( ).el); }, addAll:function(){ this.collection.forEach(this.addOne,this); } }); window.appointmentsView = new AppointmentListView({collection:appointments}); appointments.fetch({ success:function( ){ $("#app").html(appointmentsView.render().el); } }); });
'use strict'; const _ = require('lodash'); const fs = require('fs'); const browserify = require('browserify'); const dependencies = require('./dependencies'); function buildApp() { const browserifyBundle = browserify('src/app.js', {debug: true}); browserifyBundle.transform('babelify', { presets: ['es2015'] }); _.each(dependencies(), function(lib) { browserifyBundle.external(lib); }); browserifyBundle.bundle().pipe(fs.createWriteStream('static/js/app.js')); } buildApp();
/** * 表格预设置信息 * * @namespace * @name Row * @memberOf ui.Grid */ define([ './msg' ], function(MSG) { /** * @lends ui.Grid.Row# */ return { /** * 可否修改 * * @default true * @type Boolean */ enable_edit : true, /** * 可否删除 * * @default true * @type Boolean */ enable_delete : true, /** * 可否选择 * * @default true * @type Boolean */ enable_check : true }; });
import AppDispatcher from '../dispatcher/FluxDispatcher'; import DeviceConstants from '../constants/DeviceConstants'; import { EventEmitter } from 'events'; const CHANGE_EVENT = 'change'; let error = null; let device = null; let list = {}; class DeviceStore extends EventEmitter { getDevice() { return device; } getList() { return list; } getError() { return error; } emitChange() { this.emit(CHANGE_EVENT); } addChangeListener(callback) { this.on(CHANGE_EVENT, callback); } removeChangeListener(callback) { this.removeListener(CHANGE_EVENT, callback); } } let _deviceStore = new DeviceStore(); export default _deviceStore; AppDispatcher.register((payload) => { let action = payload.action; switch(action.type) { case DeviceConstants.FETCH_CONFIG_OK: device = action.data.device; error = action.data.error; _deviceStore.emitChange(); break; case DeviceConstants.FETCH_CONFIG_KO: device = action.data.device; error = action.data.error; _deviceStore.emitChange(); break; case DeviceConstants.FETCH_CONFIG_NOT_FOUND: device = action.data.device; error = action.data.error; _deviceStore.emitChange(); break; case DeviceConstants.FETCH_ALL_OK: list = action.data.devices; error = action.data.error; _deviceStore.emitChange(); break; case DeviceConstants.FETCH_ALL_KO: list = action.data.devices; error = action.data.error; _deviceStore.emitChange(); break; default: break; } });
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdSimCardAlert(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M36 4c2.2 0 4 1.8 4 4v32c0 2.2-1.8 4-4 4H12c-2.2 0-4-1.8-4-4l.05-24L20 4h16zM26 34v-4h-4v4h4zm0-8V16h-4v10h4z" /> </IconBase> ); } export default MdSimCardAlert;
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('care-team', 'Unit | Serializer | CareTeam', { needs: [ 'serializer:care-team', 'model:identifier', 'model:codeable-concept', 'model:reference', 'model:period', 'model:care-team-participant', 'model:annotation', 'model:meta', 'model:narrative', 'model:resource', 'model:extension' ] }); test('it serializes records', function(assert) { const record = this.subject(), serializeRecord = record.serialize(); assert.ok(serializeRecord); });
(function(){ function EventManager() { this.listeners = {}; } EventManager.prototype.subscribe = function subscribe(event, fn) { if (!this.listeners[event]) { this.listeners[event] = []; } this.listeners[event].push(fn); } EventManager.prototype.unsubscribe = function unsubscribe(event, fn) { var eventListeners = null; if ((eventListeners = this.listeners[event])) { for (var i = 0, len = eventListeners.length; i < len; i++) { if (eventListeners[i] === fn) { eventListeners.splice(i, 1); break; } } } } EventManager.prototype.publish = function publish(event) { if (!this.listeners[event]) return; var eventListeners = this.listeners[event]; var args = Array.prototype.slice.call(arguments, 1); var evt = new EventManager.Event(event, false); for (var i = 0, len = eventListeners.length; i < len; i++) { eventListeners[i].apply(this, [evt].concat(args)); } return evt; } EventManager.Event = function Event(type, bubbles) { this.bubbles = bubbles; this.cancelBubble = false; this.cancelable = false; this.currentTarget = null; this.defaultPrevented = false; this.eventPhase = this.NONE; this.target = null; this.timeStamp = (new Date).getTime(); this.type = type; this.isTrusted = true; } EventManager.Event.prototype.NONE = 0; EventManager.Event.prototype.CAPTURING_PHASE = 1; EventManager.Event.prototype.AT_TARGET = 2; EventManager.Event.prototype.BUBBLING_PHASE = 3; EventManager.Event.prototype.preventDefault = function preventDefault() { this.defaultPrevented = true; } EventManager.Event.prototype.stopImmediatePropagation = function stopImmediatePropagation() { throw "Not implemented yet!"; } EventManager.Event.prototype.stopPropagation = function stopPropagation() { throw "Not implemented yet!"; } /* global define:true module:true window: true */ if (typeof define === 'function' && define['amd']) { define(function() { return EventManager; }); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = EventManager; } else if (typeof this !== 'undefined') { this['EventManager'] = EventManager; } }).call(this);
var expect = require('expect.js'); var path = require('path'); describe('unit - hasher', function () { this.timeout(30000); context('', function () { it('successfully creates hash from package dependencies', function (done) { var pkg = { devDependencies: { 'expect.js': '^0.3.1', 'mini-mock': '^0.0.3', mocha: '^3.2.0' }, dependencies: { archiver: '^1.3.0', async: '^2.3.0', bluebird: '^3.5.0', chalk: '^1.1.3', 'cross-spawn': '^5.1.0', dockerode: '^2.4.3', events: '^1.1.1', 'fast-diff': '^1.1.1', figures: '^2.0.0', 'happner-serial-mocha': 'git+https://github.com/happner/happner-serial-mocha.git', 'log-update': '^2.0.0', 'node-cmd': '^3.0.0', 'simple-git': '^1.70.0', 'stable-node-version': '^1.0.0', 'test-metrics': 'git+https://github.com/happner/test-metrics.git', 'text-table': '^0.2.0' } }; var Hasher = require('../../../lib/utils/package-hasher'); var hasher = new Hasher(); var result = hasher.createPackageHash(pkg); expect(result).to.be(1556671475); done(); }); }); });
$(function() { var timer = $('#timer') , bar = timer.find('.progress-bar'); var timeout = +bar.attr('data-timeout'); if (timeout !== 0) { var progress = setInterval(function() { var remain = +bar.attr('data-remain') , percent = 100 * (remain / timeout); bar.css('width', percent + '%'); if (remain > 0) { bar.attr('data-remain', remain - 1); } else { clearInterval(progress); } }, 1000); } });
'use strict'; KlarkModule(module, 'krkMiddlewareParameterValidator', function(q, _, krkParameterValidator) { var defaultPagination = { page: 1, count: 50 }; return { crud: { retrieve: crudRetrieveValidator, retrieveAll: crudRetrieveAllValidator, create: crudCreateValidator, update: crudUpdateValidator, delete: crudDeleteValidator }, paginationValidator, modelValidator }; function crudRetrieveValidator() { return idValidator; } function crudRetrieveAllValidator(model) { return function(req, res, next) { var params = paginationValidator(req); krkParameterValidator.checkForErrors(params, req, res, function(hasError) { if (hasError) { return next(hasError); } checkPossibleModelQueryParameters(model, req, res) .then(function() { next(); }) .catch(function(reason) { res.locals.errors.add('INVALID_PARAMS', reason); next(true); }) }); } }//uniqueBy function checkPossibleModelQueryParameters(model, req, res) { var pathnames = []; model.schema.eachPath(function(pathname) { if (pathname.indexOf('.') === -1 && req.query[pathname]) { pathnames.push(pathname); } }); if (req.query.uniqueBy) { const indexOfUniqueKey = pathnames.indexOf(req.query.uniqueBy); if (indexOfUniqueKey !== -1) { res.locals.params.uniqueBy = req.query.uniqueBy; } } var filters = {}; var partialValidations = _.map(pathnames, function(pathname) { return { path: pathname, value: req.query[pathname], onValidate: function(v) { return filters[pathname] = v; } }; }); res.locals.params.filters = filters; return krkParameterValidator.modelPartialValidator(model, partialValidations); } function crudCreateValidator(model) { return function(req, res, next) { return modelValidator(model, req, res, next); }; } function crudUpdateValidator(model) { return function(req, res, next) { modelValidator(model, req, res, function(error) { if (error) { return next(true); } return idValidator(req, res, next); }); }; } function crudDeleteValidator() { return idValidator; } function idValidator(req, res, next) { res.locals.params.id = krkParameterValidator.validations.paramId(req); krkParameterValidator.checkForErrors(res.locals.params, req, res, next); } function modelValidator(model, req, res, next) { var recordParam = req.body[model.modelName]; var record = new model(recordParam); record.validate(krkParameterValidator.checkForMongoValidationErrors(req, res, next, function() { res.locals.params[model.modelName] = recordParam; next(); })); } function paginationValidator(req) { var validators = krkParameterValidator.partialValidations(req); var pagination = _.defaults({ page: validators.queryPage(), count: validators.queryCount(), sortBy: validators.querySortBy(), asc: validators.queryAsc() }, defaultPagination); var params = { pagination }; return params; } });
let DataTable = { template: '<div>123</div>' }; export default DataTable;
/* Copyright JS Foundation and other contributors, https://js.foundation/ 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. 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 <COPYRIGHT HOLDER> 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. */ 'use strict'; var esprima = require('../'), evaluateTestCase = require('./utils/evaluate-testcase'), createTestCases = require('./utils/create-testcases'), errorToObject = require('./utils/error-to-object'), fs = require('fs'), path = require('path'), diff = require('json-diff').diffString, total = 0, result, failures = [], cases = {}, context = { source: '', result: null }, tick = new Date(), testCase, header; function generateTestCase(testCase) { var options, tree, filePath, fileName; fileName = testCase.key + ".tree.json"; try { options = { jsx: true, loc: true, range: true, tokens: true, sourceType: testCase.key.match(/\.module$/) ? 'module' : 'script' }; tree = esprima.parse(testCase.case, options); tree = JSON.stringify(tree, null, 4); } catch (e) { if (typeof e.index === 'undefined') { console.error("Failed to generate test result."); throw e; } tree = errorToObject(e); tree.description = e.description; tree = JSON.stringify(tree); fileName = testCase.key + ".failure.json"; } filePath = path.join(__dirname, 'fixtures', fileName); fs.writeFileSync(filePath, tree); console.error("Done."); } cases = createTestCases(); total = Object.keys(cases).length; Object.keys(cases).forEach(function (key) { testCase = cases[key]; if (testCase.hasOwnProperty('tree') || testCase.hasOwnProperty('tokens') || testCase.hasOwnProperty('failure') || testCase.hasOwnProperty('result')) { try { evaluateTestCase(testCase); } catch (e) { if (!e.expected) { throw e; } e.source = testCase.case || testCase.key; failures.push(e); } } else { console.error('Incomplete test case:' + testCase.key + '. Generating test result...'); generateTestCase(testCase); } }); tick = (new Date()) - tick; header = total + ' tests. ' + failures.length + ' failures. ' + tick + ' ms'; if (failures.length) { console.error(header); failures.forEach(function (failure) { var expectedObject, actualObject; try { expectedObject = JSON.parse(failure.expected); actualObject = JSON.parse(failure.actual); console.error(failure.source + ': Expected\n ' + failure.expected.split('\n').join('\n ') + '\nto match\n ' + failure.actual + '\nDiff:\n' + diff(expectedObject, actualObject)); } catch (ex) { console.error(failure.source + ': Expected\n ' + failure.expected.split('\n').join('\n ') + '\nto match\n ' + failure.actual); } }); } else { console.log(header); } process.exit(failures.length === 0 ? 0 : 1);
/** * 原生Promise的实现 * */ 'use strict'; var p = new Promise(function(resolve,reject){ setTimeout(function(){ resolve('success'); },2000) }); var tt = p.then(function(res){ console.log(res); var pIn = new Promise(function(resolve){ resolve('in s') }); return pIn; },function(reject){ console.log(reject); }).then(function(res){ console.log(res); },function(reject){ console.log(reject); });
import { resizedImageUrl } from "schema/image/resized" describe("Image", () => { describe("resizedImageUrl", () => { const image = { original_height: 2333, original_width: 3500, image_url: "https://xxx.cloudfront.net/xxx/:version.jpg", image_versions: ["large"], } it("takes an image response with options and resizes it to fit", () => { expect(resizedImageUrl(image, { width: 500, height: 500 })).toEqual({ factor: 0.14285714285714285, height: 333, width: 500, url: "https://gemini.cloudfront.test/?resize_to=fit&width=500&height=333&quality=95&src=https%3A%2F%2Fxxx.cloudfront.net%2Fxxx%2Flarge.jpg", // eslint-disable-line }) }) it("takes an image response with options (just one dimension) and resizes it to fit", () => { expect(resizedImageUrl(image, { width: 500 })).toEqual({ factor: 0.14285714285714285, height: 333, width: 500, url: "https://gemini.cloudfront.test/?resize_to=fit&width=500&height=333&quality=95&src=https%3A%2F%2Fxxx.cloudfront.net%2Fxxx%2Flarge.jpg", // eslint-disable-line }) }) it("returns a resized image URL when existing image dimensions are lacking", () => { expect( resizedImageUrl( { image_url: "https://xxx.cloudfront.net/xxx/:version.jpg", image_versions: ["large"], }, { width: 500, height: 500, } ) ).toEqual({ factor: Infinity, width: null, height: null, url: "https://gemini.cloudfront.test/?resize_to=fit&width=500&height=500&quality=95&src=https%3A%2F%2Fxxx.cloudfront.net%2Fxxx%2Flarge.jpg", // eslint-disable-line }) }) }) })
/** * @flow */ import { applyMiddleware } from 'redux' import thunk from 'redux-thunk' import { logger } from './logger' export const middleware = applyMiddleware(thunk, logger)
import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; export default class SimpleTooltip extends React.Component { static propTypes = { tooltips: PropTypes.object.isRequired, children: PropTypes.node.isRequired, title: PropTypes.string.isRequired, } componentDidMount() { this.disposable = this.props.tooltips.add(ReactDOM.findDOMNode(this.child), {title: () => this.props.title}); } componentWillUnmount() { this.disposable.dispose(); } componentDidUpdate(prevProps) { if (prevProps.title !== this.props.title) { this.disposable.dispose(); this.disposable = this.props.tooltips.add(ReactDOM.findDOMNode(this.child), {title: () => this.props.title}); } } render() { const child = React.Children.only(this.props.children); return React.cloneElement(child, {ref: e => { this.child = e; }}); } }
/* global Blob */ import Ember from 'ember'; const { $: { Event } } = Ember; function createFile(content = ['test'], options = {}) { let { name, type } = options; let file = new Blob(content, { type: type ? type : 'text/plain' }); file.name = name ? name : 'test.txt'; return file; } export function uploadFile($element, content, options) { let file = createFile(content, options); let event = Event('change', { // eslint-disable-line new-cap testingFiles: [file] }); $element.trigger(event); }
var crypto = require('crypto'), fs = require('fs'), _ = require('underscore'); function makeWhiteCardId(setId, index, inline) { return setId + ':w:' + index; } function normalizeWhiteCard(setId, index, obj) { var result = null; if (_(obj).isString()) { result = { inline: obj }; } else { result = obj; } // if we don't have a unique id, generate one if (!result.id) { result.id = makeWhiteCardId(setId, index, obj.inline); } // if we don't have a "card form", generate it from the inline form; sentence-case, add final period if (!result.card) { var card = obj; card = card[0].toUpperCase() + card.substr(1); card += '.'; result.card = card; } return result; } function makeBlackCardId(setId, index, card) { return setId + ':k:' + index; } function normalizeBlackCard(setId, index, obj) { // TODO: replace _+ with something that we turn into a pretty underline/drag target on the client var result = null; if (_(obj).isString()) { result = { card: obj }; } else { result = obj; } // if we don't have a unique id, generate one if (!result.id) { result.id = makeBlackCardId(setId, index, obj.card); } // if we don't have a "finished form", generate it from the card form; replace blanks with white-card insertion points if (!result.finished) { var index = 0; var previous; var finished = obj; // detect arity: count number of _+ matches // generate finished form: replace _+ matches with mustaches for white cards do { previous = finished; finished = previous.replace(/_+/, '{{card[' + index + ']}}'); } while (previous != finished && ++index); if (index == 0) { // we didn't replace any underscores with mustaches; implicit arity is 1 result.arity = 1; } else { // we replaced (index) underscores with mustaches result.arity = index; } result.finished = finished; } return result; } module.exports = (function () { function Cardset(path) { var json = fs.readFileSync(path, { encoding: 'utf8' }), o = JSON.parse(json); this.name = o['name']; this.description = o['description']; this.copyright = o['copyright']; this.locale = o['lang']; var setKey = this.name + '|' + this.description; var shasum = crypto.createHash('sha1'); shasum.update(setKey, 'utf8'); var setId = shasum.digest('hex'); this.blackCards = _(o['black_cards']).map(function (card, index, list) { return normalizeBlackCard(setId, index, card); }); this.whiteCards = _(o['white_cards']).map(function (card, index, list) { return normalizeWhiteCard(setId, index, card); }); } return Cardset; })();
'use strict'; angular.module('timerApp', ['ngRoute', 'ajoslin.mobile-navigate', 'ngTouch', 'ui.bootstrap', 'LP.services', 'LP.config']) .config(function($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .when('/Timer', { templateUrl: 'views/timepicker.modal.html', controller: 'TimepickerModalCtrl', resolve: { title: function(){ return 'Timer'; }, timeId: function(){ return 'timer'; } } }) .when('/IntervalTimer', { templateUrl: 'views/timepicker.modal.html', controller: 'TimepickerModalCtrl', resolve: { title: function(){ return 'Interval'; }, timeId: function(){ return 'intervalTimer'; } } }) .when('/Settings', { templateUrl: 'views/settings.html', controller: 'SettingsCtrl' }) .when('/Info', { templateUrl: 'views/info.html', controller: 'InfoCtrl' }) .otherwise({ redirectTo: '/' }); }).value('appProperties', { version: '0.0.1' });
define([ 'jidejs/base/Class', 'jidejs/base/ObservableProperty', 'jidejs/ui/Control', 'jidejs/ui/Skin', 'text!./Switch.html' ], function( Class, ObservableProperty, Control, Skin, SwitchTemplate ) { function Switch(config) { installer(this); Control.call(this, config || {}); this.classList.add('jide-extra-switch'); } Class(Switch).extends(Control).def({ checked: false, checkedText: null, uncheckedText: null, dispose: function() { installer.dispose(this); Control.prototype.dispose.call(this); } }); var installer = ObservableProperty.install(Switch, 'checked', 'checkedText', 'uncheckedText'); Switch.Skin = Skin.create(Skin, { template: SwitchTemplate, toggleCheckedState: function() { var toggle = this.component; toggle.checked = !toggle.checked; } }); return Switch; });
var settings = require('../settings'); var dbI = settings.databaseInfo; module.exports = db = require('mongoose'); var auth = dbI.username ? ('' + dbI.username + ':' + dbI.password + '@') : ''; var host = dbI.host || '202.206.221.105'; var port = dbI.port || 27017; var dbn = dbI.db; db.connect('mongodb://' + auth + host + ':' + port + '/' + dbn); db.connection.on('error', console.error.bind(console, 'connection error:'));
module.exports = (sequelize, DataTypes) => { const StaffMember = sequelize.define('StaffMember', { username: DataTypes.STRING, password: DataTypes.STRING, firstName: DataTypes.STRING, lastName: DataTypes.STRING, }, { freezeTableName: true, classMethods: { associate: (models) => { StaffMember.hasMany(models.Client, { foreignKey: 'caseManagerId', as: 'Clients', }); StaffMember.hasMany(models.CaseNote, { foreignKey: 'author' }); StaffMember.belongsToMany(models.Role, { through: 'StaffMemberRole', foreignKey: 'roleId', otherKey: 'staffMemberId', }); }, }, }); return StaffMember; };
Number.prototype.isPrime = function() { if (this < 2) { return false; } for (var counter = 2; counter <= Math.sqrt(this); counter++) { if (this % counter == 0) { return false; } } return true; }; String.prototype.addNumerically = function(otherString) { var topNumber = this; var bottomNumber = otherString; var sum = []; if (parseInt(bottomNumber) > parseInt(topNumber)) { topNumber = otherString; bottomNumber = this; } while (bottomNumber.length < topNumber.length) { bottomNumber = '0' + bottomNumber; } topNumber.split('').forEach(function(topDigit, index) { var bottomDigit = parseInt(bottomNumber[index]) || 0; sum.push(parseInt(topDigit) + bottomDigit); }) sum = sum.reverse(); sum.forEach(function(digit, index) { var digits = digit.toString().split(''); if (digits.length > 1) { sum[index] = digits[1]; var existingDigit = sum[index + 1] || '0' sum[index + 1] = parseInt(existingDigit) + parseInt(digits[0]); } }); return sum.reverse().join(''); }; String.prototype.multiplyBy = function(otherString) { var timesToAdd = parseInt(this); var product = "0"; for (var counter = 0; counter < timesToAdd; counter++) { product = product.addNumerically(otherString); } return product; }; Number.prototype.primeFactors = function() { if (this.isPrime()) { return this; } var possibleFactor = 2 while (this % possibleFactor != 0) { possibleFactor++; } return [possibleFactor, (this / possibleFactor).primeFactors()].join(',').split(',').map(function(element) { return parseInt(element); }); }; // too slow to be worth anything with large numbers: // String.prototype.powerNumerically = function(otherString) { // var originalNumber = this; // var product = this; // for (var counter = 1; counter < parseInt(otherString); counter++) { // console.log(product); // product = product.multiplyBy(originalNumber); // } // return product; // } // combinations = function(options, length) { // if (typeof options[0] != "object") { // options = options.map(function(e) { // return [e]; // }) // } // if (length == 1) { // return options; // } // var combos = []; // for (var currentIndex = 0; currentIndex < length; currentIndex++) { // for (var otherIndex = currentIndex; otherIndex < length; otherIndex++) { // // options is an array of arrays... // var nextOption = options[currentIndex]; // nextOption.push(options[otherIndex]); // combos.push(nextOption); // } // } // return combinations(combos, length - 1); // } // function getCombinations(chars) { // var result = []; // var f = function(prefix, chars) { // for (var i = 0; i < chars.length; i++) { // result.push(prefix + chars[i]); // f(prefix + chars[i], chars.slice(i + 1)); // } // } // f('', chars); // return result; // } // console.log(getCombinations([1, 22, 3]))
import React from 'react' import BrandGallery from '../components/BrandGallery' export default () => ( <BrandGallery brand='Carol Dias' /> )
import postcss from 'postcss'; import test from 'ava'; import plugin from './'; // function execPlugin(input, onResolved, onRejected, opts = {}) { // postcss([ plugin(opts) ]).process(input).then(); // } // // function handleRejected(t, input, onRejected, opts = {}) { // execPlugin(input, function () { // t.fail(); // }, onRejected, opts); // } // // function handleResolved(t, input, onResolved, opts = {}) { // execPlugin(input, onResolved, function () { // t.fail(); // }, opts); // } function deepEqual(t, input, output, opts = {}) { return postcss([ plugin(opts) ]).process(input) .then( result => { t.deepEqual(result.css, output); t.deepEqual(result.warnings().length, 0); }); } function processCSS(input, opts = {}) { return postcss([ plugin(opts) ]).process(input); } test('@define-grid invalid parameter', t => { var input = '@define-grid mygrid1 { @define-media phone {} }'; t.throws(processCSS(input), /.*invalid parameter.*/); }); test('@define-grid grid media redeclaration', t => { var input = '@define-grid mygrid2 { ' + '@define-media phone (min-width: 100px) {} ' + '@define-media phone (min-width: 100px) {} }'; t.throws(processCSS(input), /.*grid media redeclaration.*/); }); test('@define-grid remove after processing', t => { var input = '@define-grid mygrid3 { ' + '@define-media phone (min-width: 100px) {} }'; return deepEqual(t, input, ''); }); test('@grid-media', t => { var input = '@define-grid mygrid4 { ' + '@define-media phone (min-width: 100px) {} } ' + 'a { @grid-media mygrid4 phone { display: none; } }'; return deepEqual(t, input, 'a { }\n@media (min-width: 100px) {\n ' + 'a {\n display: none\n }\n}'); });
$(document).ready(function() { $('.counter') .draggable({delay: 200}) .on('dblclick', function() { if ($(this).attr('class').indexOf('front') > 0) { $(this).removeClass('front').addClass('back'); } else { $(this).removeClass('back').addClass('front'); } }); var eventCardCounter = 1; $('.card') .draggable({delay: 200}) .on('dblclick', function() { if ($(this).attr('class').indexOf('front') > 0) { $(this).removeClass('front').addClass('back') eventCardCounter -= 1; } else { $(this).removeClass('back').addClass('front').css('z-index', eventCardCounter); eventCardCounter += 1; } }); $('.dice').on('click', function() { $(this).effect('highlight', {color: 'cyan'}, 'fast'); var number = Math.floor(Math.random() * 6) + 1; $(this).attr('id', 'D'+number); }); // shuffle cards var cards = $('.card.back').shuffle(); for (var i = 0; i < cards.length; i++) { $(cards[i]).css('z-index', i+1); } });
var through = require('through2'); var path = require('path'); var File = require('vinyl'); module.exports = function () { var dictionary = Object.create(null); function bufferFiles(file, enc, cb) { var fileName = path.basename(file.path); var dirName = path.dirname(file.path); if (fileName == 'package.json') { //if not at base directory (we don't want to generate files outside of the base) if (file.relative != fileName) { dictionary[dirName] = dictionary[dirName] || {}; dictionary[dirName].pjson = file.clone({ deep: false, contents: false }); } } else if (fileName == 'index.js') { //if not at base directory (we don't want to generate files outside of the base) if (file.relative != fileName) { dictionary[dirName] = dictionary[dirName] || {}; dictionary[dirName].index = file.clone({ deep: false, contents: false }); } } this.push(file); cb(); } function endStream(cb) { for (dirName in dictionary) { var newModule; var record = dictionary[dirName]; if (record.pjson) { var mainVal = JSON.parse(record.pjson.contents.toString()).main; var importPath = path.basename(dirName) + '/' + mainVal; newModule = new File({ cwd: record.pjson.cwd, base: record.pjson.base, path: dirName + '.js', contents: new Buffer('export * from \'' + importPath + '\';') }); } else if (record.index) { var importPath = './' + path.basename(dirName) + '/index'; newModule = new File({ cwd: record.index.cwd, base: record.index.base, path: dirName + '.js', contents: new Buffer('export * from \'' + importPath + '\';') }); } this.push(newModule); } cb(); } return through.obj(bufferFiles, endStream); }
'use strict'; var assert = require('assert'); //var npm-top-md = require('../'); // test 1 assert(true);
import mergeMixins from '../src/merge-mixins'; describe('merge mixins module', () => { it('merge mixins into options', () => { const readyCalls = []; const mixin3 = { properties: { x: 'x3', }, ready() { readyCalls.push(`${this}3`); }, customProperty: 'test3', }; const mixin1 = { mixins: [mixin3], properties: { x: 'x1', z: 'z1', }, ready() { readyCalls.push(`${this}1`); }, customProperty: 'test1', }; const mixin2 = { properties: { x: 'x2', z: 'z2', }, ready() { readyCalls.push(`${this}2`); }, customProperty: 'test2', }; const options = { mixins: [mixin1, mixin2], properties: { x: 'x', y: 'y', }, ready() { readyCalls.push(this); }, customProperty: 'test', }; const mergedOptions = mergeMixins(options); expect(mergedOptions.mixins).toBeUndefined(); expect(mergedOptions.properties).toEqual({ x: { type: 'x' }, y: { type: 'y' }, z: { type: 'z1' }, }); expect(mergedOptions.customProperty).toBe('test'); mergedOptions.ready.call('ready'); expect(readyCalls).toEqual(['ready2', 'ready3', 'ready1', 'ready']); }); });
webpackJsonp([0xa7f31e1aeaea],{611:function(a,e){a.exports={pathContext:{}}}}); //# sourceMappingURL=path---contact-a0e39f21c11f6a62c5ab.js.map
const mix = require('laravel-mix'), DashboardPlugin = require('webpack-dashboard/plugin'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel application. By default, we are compiling the Sass | file for the application as well as bundling up all the JS files. | */ mix.webpackConfig({ module: { noParse: /node_modules\/localforage\/dist\/localforage.js/ }, plugins: [new DashboardPlugin()] }); mix .js('resources/assets/js/app.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css') .disableNotifications();
var url = require('url'); var logger = require('../tools/logger'); var redis = require('../tools/redis'); var fetch = require('node-fetch'); var md5 = require('blueimp-md5'); module.exports = function (req, res) { var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; var query = url.parse(req.url,true).query; var aid = query.aid; var appkey = '4ebafd7c4951b366'; var secret = '8cb98205e9b2ad3669aad0fce12a4c13'; redis.client.get(`bilibilicid${aid}`, function(err, reply) { if (reply) { logger.info(`Video Bilibili AV${aid} form redis, IP: ${ip}`); var sign = md5(`appkey=${appkey}&cid=${reply}&otype=json&quality=2&type=mp4${secret}`); fetch(`https://interface.bilibili.com/playurl?appkey=${appkey}&cid=${reply}&otype=json&quality=2&type=mp4&sign=${sign}`).then( response => response.text() ).then((data) => { res.send(data); } ).catch( e => logger.error("Video Bilibilib Error: getting data", e) ); } else { logger.info(`Video Bilibili AV${aid} form origin, IP: ${ip}`); fetch(`http://www.bilibili.com/widget/getPageList?aid=${aid}`).then( response => response.json() ).then((data) => { redis.set(`bilibilicid${aid}`, data[0].cid); var sign = md5(`appkey=${appkey}&cid=${data[0].cid}&otype=json&quality=2&type=mp4${secret}`); fetch(`https://interface.bilibili.com/playurl?appkey=${appkey}&cid=${data[0].cid}&otype=json&quality=2&type=mp4&sign=${sign}`).then( response => response.text() ).then((data) => { res.send(data); } ).catch( e => logger.error("Video Bilibilib Error: getting data", e) ); } ).catch( e => logger.error("Video Bilibilib Error: getting cid", e) ); } }); };
/********************************************** * Author : @Author * Timestamp : @Timestamp **********************************************/ var d1 = require("deviceone"); var app = d1.sm("do_App"); app.on("loaded", function () { this.openPage("source://do_ScrollView/view/index.ui"); });
app.controller('VipCtrl', function($scope, $http, $state) { $http.get('/reception/consumer/info').success(function(response){ if (response.status == 1) { $scope.consumer = response.contents.consumer; $state } else { $state.go('login'); } }); })
(function($) { $.fn.anToolbar = function(options) { // Function to add button to dropdown function addButtonToDropdown(dropdownMenu, button) { button = button.get(0); // Create li element li = $('<li><a></a></li>'); li.children('a').html(button.innerHTML); // Move all attributes for (i = 0; i < button.attributes.length; i++) { var a = button.attributes[i]; li.attr(a.name, a.value); } // Remove and add classes li.removeClass($.fn.anToolbar.defaults.removeClass); li.removeClass($.fn.anToolbar.defaults.addClass); dropdownMenu.prepend(li); } return this.each(function() { // Initiate default options $.fn.anToolbar.defaults = { // Adds css class to item when moved into dropdown addClass: '', // Adds a divider in dropdown for btn-groups divider: true, // Set HTML of dropdown button dropdownHTML: '<i class="icon-chevron-down"></i>', // Set position of dropdown dropdownPosition: 'right', // Decide if buttons should be moved from last or first move: 'last', // Removes css class to item when moved into dropdown removeClass: 'btn' }; // Extend default options options = $.extend($.fn.anToolbar.defaults, options); // Toolbar element var $this = $(this); // Calculate items width width = 0; $.each($(this).children(), function(key,value){ width += $(value).outerWidth(); }); // Check if need to add dropdown if ($(this).width() < width){ dropdown = '<div class="dropdown btn-group"><a class="dropdown-toggle btn" role="button" data-toggle="dropdown" href="#">' + $.fn.anToolbar.defaults.dropdownHTML + '</a><ul class="dropdown-menu" role="menu"></ul></div>'; // Decide side of dropdown if (options.dropdownPosition == 'right'){ $(this).append(dropdown); } else if (options.dropdownPosition == 'left'){ $(this).prepend(dropdown); } } dropdownMenu = $this.children('.dropdown').children('.dropdown-menu'); // Add items to dropdown until items fit in container while ($(this).width() < width){ // Get tool to be moved tool = $($(this).children(":not('.dropdown'):" + options.move)); // If tool is btn-group, add all btn to dropdown if (tool.hasClass('btn-group')){ // Add divider if dropdown is not empty and activated if (!dropdownMenu.is(':empty') && $.fn.anToolbar.defaults.divider){ dropdownMenu.prepend($('<li class="divider"></li>')); } tool.children().each(function(key, value){ addButtonToDropdown(dropdownMenu, $(value)); }); } else if(tool.is('button')){ addButtonToDropdown(dropdownMenu, tool); } tool.remove(); // Recalculate width width = 0; $.each($(this).children(), function(key, value){ width += $(value).outerWidth(); }); } }); } })(jQuery);
// # formatic /* The root formatic component. The root formatic component is actually two components. The main component is a controlled component where you must pass the value in with each render. This is actually wrapped in another component which allows you to use formatic as an uncontrolled component where it retains the state of the value. The wrapper is what is actually exported. */ 'use strict'; var React = require('react'); var _ = require('./undash'); var utils = require('./utils'); var defaultConfigPlugin = require('./default-config'); var createConfig = function (...args) { var plugins = [defaultConfigPlugin].concat(args); return plugins.reduce(function (config, plugin) { if (_.isFunction(plugin)) { var extensions = plugin(config); if (extensions) { _.extend(config, extensions); } } else { _.extend(config, plugin); } return config; }, {}); }; var defaultConfig = createConfig(); // The main formatic component that renders the form. var FormaticControlledClass = React.createClass({ displayName: 'FormaticControlled', // Respond to any value changes. onChange: function (newValue, info) { if (!this.props.onChange) { return; } info = _.extend({}, info); info.path = this.props.config.fieldValuePath(info.field); this.props.onChange(newValue, info); }, // Respond to any actions other than value changes. (For example, focus and // blur.) onAction: function (info) { if (!this.props.onAction) { return; } info = _.extend({}, info); info.path = this.props.config.fieldValuePath(info.field); this.props.onAction(info); }, // Render the root component by delegating to the config. render: function () { var config = this.props.config; return config.renderFormaticComponent(this); } }); var FormaticControlled = React.createFactory(FormaticControlledClass); // A wrapper component that is actually exported and can allow formatic to be // used in an "uncontrolled" manner. (See uncontrolled components in the React // documentation for an explanation of the difference.) module.exports = React.createClass({ displayName: 'Formatic', // Export some stuff as statics. statics: { createConfig: createConfig, availableMixins: { clickOutside: require('./mixins/click-outside.js'), field: require('./mixins/field.js'), helper: require('./mixins/helper.js'), resize: require('./mixins/resize.js'), scroll: require('./mixins/scroll.js'), undoStack: require('./mixins/undo-stack.js') }, plugins: { bootstrap: require('./plugins/bootstrap'), meta: require('./plugins/meta'), reference: require('./plugins/reference'), elementClasses: require('./plugins/element-classes') }, utils: utils }, // If we got a value, treat this component as controlled. Either way, retain // the value in the state. getInitialState: function () { return { isControlled: !_.isUndefined(this.props.value), value: _.isUndefined(this.props.value) ? this.props.defaultValue : this.props.value }; }, // If this is a controlled component, change our state to reflect the new // value. For uncontrolled components, ignore any value changes. componentWillReceiveProps: function (newProps) { if (this.state.isControlled) { if (!_.isUndefined(newProps.value)) { this.setState({ value: newProps.value }); } } }, // If this is an uncontrolled component, set our state to reflect the new // value. Either way, call the onChange callback. onChange: function (newValue, info) { if (!this.state.isControlled) { this.setState({ value: newValue }); } if (!this.props.onChange) { return; } this.props.onChange(newValue, info); }, // Any actions should be sent to the generic onAction callback but also split // into discreet callbacks per action. onAction: function (info) { if (this.props.onAction) { this.props.onAction(info); } var action = utils.dashToPascal(info.action); if (this.props['on' + action]) { this.props['on' + action](info); } }, // Render the wrapper component (by just delegating to the main component). render: function () { var config = this.props.config || defaultConfig; var value = this.state.value; if (this.state.isControlled) { if (!this.props.onChange) { console.log('You should supply an onChange handler if you supply a value.'); } } var props = { config: config, // Allow field templates to be passed in as `field` or `fields`. After this, stop // calling them fields. fieldTemplate: this.props.field, fieldTemplates: this.props.fields, value: value, onChange: this.onChange, onAction: this.onAction }; _.each(this.props, function (propValue, key) { if (!(key in props)) { props[key] = propValue; } }); return FormaticControlled(props); } });
var express = require('express'); var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var app = express(); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); console.log('running'); /** * Development Settings */ if (app.get('env') === 'development') { console.log("development"); // This will change in production since we'll be using the dist folder // This covers serving up the index page app.use(express.static(path.join(__dirname, './client/.tmp'))); app.use(express.static(path.join(__dirname, './client/app'))); // Error Handling app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } /** * Production Settings */ if (app.get('env') === 'production') { console.log("production"); // changes it to use the optimized version for production app.use(express.static(path.join(__dirname, '/server/dist'))); // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); } // Register routes var router = express.Router(); var allRoutes = require("./server/routes/index"); allRoutes.init(router); // All routes will be prefixed with /api app.use('/api', router); module.exports = app;
var fs = require('fs'); var glob = require('glob'); var MyParser = require('./MyParser'); // NOTE: YOU CAN CONFIGURE PATTERN IN `./config.json` FILE. var options = require('./config.json'); var pattern = options.pattern; var prefix = options.prefix; var modules = {}; function processFile(filename) { return MyParser(filename, prefix).getTree(); } glob(pattern, {}, function(err, files) { modules = files.map(processFile).reduce(function(result, current) { result[current.name] = current; return result; }, {}); // Each module has now children list without complete information. // We must map children list in each module // and bind objects in this list to the module nodes we gathered . for (var moduleName in modules) { if (modules.hasOwnProperty(moduleName)) { var module = modules[moduleName]; module.children = module.children.map(function(module) { return modules[module.name]; }); } } // Deep-first visiting with duplicate omitting (it prevents infinite recurrence). function makeVisit(callbacks) { return function visit(node, visited) { if (!visited) visited = []; visited.push(node.name); callbacks.onNodeStart(node); if (node.children) { callbacks.onChildrenStart(node); node.children.forEach(function(child) { // TODO check why child is undefined/null sometimes // it was previously: // if (visited.indexOf(child.name) == -1) // but there was an error. if (child && visited.indexOf(child.name) == -1) visit(child, visited); }); callbacks.onChildrenEnd(node); } callbacks.onNodeEnd(node); visited.pop(node.name); } } var outputTree = {children: []}; // TODO move these variables to make them local. var current = outputTree; var stack = []; var outputHtml = ''; var visit = makeVisit({ onNodeStart: function(node) { outputHtml += '<li>' + node.name; var newCurrent = {name: node.name, children: []}; current.children.push(newCurrent); stack.push(current); current = newCurrent; }, onNodeEnd: function(node) { outputHtml += '</li>'; current = stack.pop(); }, onChildrenStart: function(node) { outputHtml += '<ul>'; }, onChildrenEnd: function(node) { outputHtml += '</ul>'; } }); for (var m in modules) { if (modules.hasOwnProperty(m)) { visit(modules[m]); } } fs.writeFileSync('output.html', '<ul>' + outputHtml + '</ul>'); fs.writeFileSync('./output.json', JSON.stringify(outputTree)); });
'use strict'; app.factory('ordersService', ['$http', 'ngAuthSettings', function ($http, ngAuthSettings) { var serviceBase = ngAuthSettings.apiServiceBaseUri; var ordersServiceFactory = {}; var _getOrders = function () { return $http.get(serviceBase + 'api/orders').then(function (results) { return results; }); }; var _deleteOrder = function (id) { return $http.delete(serviceBase + 'api/orders/'+ id).then(function (results) { return results; }); }; var _addOrder = function (model) { return $http.post(serviceBase + 'api/orders/Post', model).then(function (results) { return results; }); }; ordersServiceFactory.getOrders = _getOrders; ordersServiceFactory.deleteOrder = _deleteOrder; ordersServiceFactory.addOrder = _addOrder; return ordersServiceFactory; }]);
console.log('remotify content script running'); chrome.runtime.onConnect.addListener(function listener(port) { console.assert(port.name == "remotify"); chrome.runtime.onConnect.removeListener(listener); var player = document.querySelector('#app-player'); var sendMessageToPlayer = function(e) { if (e.origin != 'https://play.spotify.com') return; console.log('[TO PLAYER] >>',e.origin,e.data); try { port.postMessage({type: "message_to_player", payload: e.data}); } catch (e) { // assume all errors are fatal and remove ourselves player.contentWindow.removeEventListener('message', sendMessageToPlayer); port.disconnect(); } }; var bridgeTeardown = function() { console.log('bridge teardown...'); player.contentWindow.removeEventListener('message', sendMessageToPlayer); port.disconnect(); }; port.onMessage.addListener(function(request) { console.log('R <<', request); switch(request.type) { case "bridge_setup": if (!player) { port.postMessage({type: "bridge_setup_result", success: false, payload: null}); } else { port.postMessage({ type: "bridge_setup_result", success: true, payload: { height: player.offsetHeight, width: player.offsetWidth, url: player.src } }); player.contentWindow.addEventListener('message', sendMessageToPlayer); } break; case "bridge_teardown": bridgeTeardown(); break; case "message_from_player": console.log('[FROM PLAYER] <<', request.payload); var e = new MessageEvent('message', { data: request.payload, origin: 'https://play.spotify.com', source: player.contentWindow }); window.dispatchEvent(e); break; default: console.warn('[remotify] unhandled request type', request.type); } }); port.onDisconnect.addListener(function() { console.log('port disconnected...'); bridgeTeardown(); }); });
import React, { createElement } from "react" import { Router } from "@reach/router" import { ScrollContext } from "gatsby-react-router-scroll" import { shouldUpdateScroll, init as navigationInit, RouteUpdates, } from "./navigation" import { apiRunner } from "./api-runner-browser" import syncRequires from "./sync-requires" import pages from "./pages.json" import loader from "./loader" import JSONStore from "./json-store" import EnsureResources from "./ensure-resources" import { reportError, clearError } from "./error-overlay-handler" if (window.__webpack_hot_middleware_reporter__ !== undefined) { const overlayErrorID = `webpack` // Report build errors window.__webpack_hot_middleware_reporter__.useCustomOverlay({ showProblems(type, obj) { if (type !== `errors`) { clearError(overlayErrorID) return } reportError(overlayErrorID, obj[0]) }, clear() { clearError(overlayErrorID) }, }) } navigationInit() class RouteHandler extends React.Component { render() { let { location } = this.props // check if page exists - in dev pages are sync loaded, it's safe to use // loader.getPage let page = loader.getPage(location.pathname) if (page) { return ( <EnsureResources location={location}> {locationAndPageResources => ( <RouteUpdates location={location}> <ScrollContext location={location} shouldUpdateScroll={shouldUpdateScroll} > <JSONStore pages={pages} {...this.props} {...locationAndPageResources} /> </ScrollContext> </RouteUpdates> )} </EnsureResources> ) } else { const dev404Page = pages.find(p => /^\/dev-404-page\/?$/.test(p.path)) const Dev404Page = syncRequires.components[dev404Page.componentChunkName] if (!loader.getPage(`/404.html`)) { return ( <RouteUpdates location={location}> <Dev404Page pages={pages} {...this.props} /> </RouteUpdates> ) } return ( <EnsureResources location={location}> {locationAndPageResources => ( <RouteUpdates location={location}> <Dev404Page pages={pages} custom404={ <JSONStore pages={pages} {...this.props} {...locationAndPageResources} /> } {...this.props} /> </RouteUpdates> )} </EnsureResources> ) } } } const Root = () => createElement( Router, { basepath: __PATH_PREFIX__, }, createElement(RouteHandler, { path: `/*` }) ) // Let site, plugins wrap the site e.g. for Redux. const WrappedRoot = apiRunner( `wrapRootElement`, { element: <Root /> }, <Root />, ({ result, plugin }) => { return { element: result } } ).pop() export default () => WrappedRoot
import addGuildLogWidgets from './addGuildLogWidgets'; import addLogColoring from './addLogColoring'; export default function guildLog() { addLogColoring('GuildLog', 1, 3); addGuildLogWidgets(); }
app.controller('discoverCtrl', ['stremio', '$scope', 'metadata', function mainController(stremio, $scope, metadata) { var PAGE_LEN = 140; $scope.selected = { type: "movie", genre: null, limit: PAGE_LEN, sort: null }; // selected category, genre var loading = true, genres = $scope.genres = { }, items = []; var delayedApply = _.debounce(function() { !$scope.$phase && $scope.$apply() }, 300); // Genres list var updateGenresFromAddons = _.debounce(function() { Object.keys(stremio.supportedTypes).forEach(function(type) { stremio.meta.find({ query: { type: type }, complete: true, popular: true, limit: 300, projection: { type: 1, genre:1 /*, popularity: 1*/ } }, function(err, res) { if (res) res.forEach(addCategories); delayedApply(); }); }); }); $scope.$watchCollection(function() { return Object.keys(stremio.supportedTypes).sort() }, _.debounce(function() { if (!_.isEmpty(stremio.supportedTypes)) updateGenresFromAddons(); })); $scope.genres = { }; // genres by type // Categories var addCategories = function(meta) { if (! $scope.genres[meta.type]) $scope.genres[meta.type] = { }; if (meta.genre) meta.genre.forEach(function(g) { $scope.genres[meta.type][g] = true }); // WARNING: meta.categories can also be used for items which have .genre; we'll clutter the UI though }; // Sorts var defaultSorts = [ { prop: null, name: "SORT_TRENDING" }, { prop: "imdbRating", name: "SORT_RATING", types: ["movie", "series"], addon: "com.linvo.cinemeta" }, { prop: "name", name: "SORT_ALPHABET", types: ["movie", "series"], addon: "com.linvo.cinemeta" }, { prop: "released", name: "SORT_YEAR", types: ["movie", "series"], addon: "com.linvo.cinemeta" } // consider year ]; $scope.sorts = [].concat(defaultSorts); // we set it on updateSelected $scope.$watchCollection(function() { return stremio.sorts.map(function(x) { return x.prop }) }, function() { $scope.sorts = _.uniq(stremio.sorts.concat(defaultSorts), "prop"); //if (!$scope.selected.userSetSort) $scope.selected.sort = $scope.sorts.filter($scope.supportSort)[0].prop; }); $scope.supportSort = function(sort) { if (!sort) return false; if (sort.noDiscoverTab) return false; return !sort.types || sort.types.indexOf($scope.selected.type) > -1; } /* * Main query & catalogue retrieval */ var asked, loaded; $scope.$watch("selected", function(selected) { if (! selected) return; if ($scope.loading) return; $scope.loading = true; $scope.items = { }; // Reset list, UX touch //userSetItem = false; loaded = 0; asked = 0; // Build query var sort = selected.sort || "popularity"; var q = { query: { type: selected.type }, popular: true, complete: true, sort: _.object([ sort ], [ -1 ]), limit: 70, skip: selected.loaded, }; if (selected.genre == "oscar") q.query.awards = { oscar: 1 }; // oscar winners special case else if (selected.genre) q.query.genre = selected.genre; if (sort.match("^popularities")) q.query[selected.sort] = { $gt: 0 }; // only popular items if (sort.match("popularity")) q.query.poster = { $nin: [null, "", "N/A"] }; // default sort, add that to query; LEGACY if (sort.match("released")) { q.limit = 420; q.sort = { "popularities.moviedb": -1 } }; // year-based sort, show movies for a lot of years // Pick add-ons var addons = stremio.get("meta.find", q); $scope.sorts.forEach(function(s) { if ((!s.types || s.types.indexOf(selected.type) > -1) && s.prop === sort && s.addon) { addons = addons.filter(function(x) { return x.identifier() === s.addon }) } }); //if (addons[0] && addons[0].manifest.countrySpecific && stremio.countryCode) q.countryCode = stremio.countryCode.toLowerCase(); var all = [ ]; $scope.loading = true; // WARNING: for now, we only set that on initial load; it's not good UX to set it when loading more items requestRes(); $scope.loadNextPage = function() { if ($scope.selected.sort && !$scope.selected.sort.match("^popularit")) return; // no infinite scroll for non-popularity/popularities props if (asked > loaded) return; // no more to ask for requestRes(); }; function requestRes() { q.skip = loaded; asked = loaded + 70; stremio.fallthrough([].concat(addons), "meta.find", q, receiveRes); }; function receiveRes(err, res, service) { if (Array.isArray(res)) { console.log("Discover pulled "+res.length+" from "+service.identifier()+" (first pick "+addons[0].identifier()+") for type "+q.query.type); res = res.map(function(m) { return new metadata(m) }); all = _.uniq(all.concat(res), "_id"); loaded = all.length; //$scope.items = groupResults(selected, all); $scope.items = all; //if (!sc) $scope.info = (all[0] && all[0].tvguide_short) ? null : all[0]; } $scope.loading = false; delayedApply(); } }, true); $scope.selectItem = function(item) { $scope.selectedItem = item; } return self; }]);
var app = require('./helpers/app'); var should = require('should'), supertest = require('supertest'); describe('flights', function() { it('should return correct info of flight 18', function(done) { supertest(app) .get('/flight/18') .expect(200) .end(function(err,res) { res.status.should.equal(200); done(); }); }); it('should return 404 for invalid flight', function(done) { supertest(app) .get('/flight/1') .expect(404) .end(function(err,res) { res.status.should.equal(404); done(); }); }); it('should mark flight 18 as arriver', function(done) { supertest(app) .put('/flight/18/arrived') .expect(200) .end(function(err,res) { res.status.should.equal(200); res.body.status.should.equal('done'); supertest(app) .get('/flight/18') .expect(200) .end(function(err,res) { res.status.should.equal(200); res.body.arrival.should.not.equal(undefined); done(); }); }); }); });
/* eslint-env mocha */ import chai, { expect } from 'chai' import chaiHttp from 'chai-http' import { createServer } from '../server' chai.use(chaiHttp) import fakeDB from '../server/fakeDB.js' const server = createServer({ nodeEnv: 'test', webConcurrency: process.env.WEB_CONCURRENCY || 1, port: process.env.PORT || 5000, timeout: 29000 }) describe('API', () => { it('should list ALL trips on api/v0/trips GET', (done) => { chai.request(server) .get('/api/v0/trips') .end((err, res) => { expect(res.status).to.equal(200) expect(res).to.be.json expect(res.text).to.be.an('string') expect(res.text).to.equal(JSON.stringify(fakeDB)) done() }) }) it('should list ONE trip on api/v0/trips/:slug GET', (done) => { const trip = { id: '128sd043hd', title: 'Kilimanjaro', slug: 'kilimanjaro', content: 'Lorem Khaled Ipsum is a major key to success. The weather is amazing, walk with me through the pathway of more success. Take this journey with me, Lion! We don’t see them, we will never see them. Find peace, life is like a water fall, you’ve gotta flow. Wraith talk. You see the hedges, how I got it shaped up? It’s important to shape up your hedges, it’s like getting a haircut, stay fresh. A major key, never panic. Don’t panic, when it gets crazy and rough, don’t panic, stay calm.' } chai.request(server) .get(`/api/v0/trips/${trip.slug}`) .end((err, res) => { expect(res.status).to.equal(200) expect(res).to.be.json expect(res.text).to.be.an('string') expect(res.text).to.equal(JSON.stringify(trip)) done() }) }) })
var fs = require('fs') var chalk = require('chalk') var dnsServer = require('./dns-server') var routerServer = require('./http-router') var procs = require('./procs') var config = require('../config') var util = require('util') function log(str) { util.log(chalk.red('[daemon] ') + str) } module.exports = { start: function() { log('Start') this.katon = routerServer.createServer() this.dns = dnsServer.createServer() log('Loading procs') procs.load() log('Starting DNS server on port ' + config.dnsPort) this.dns.listen(config.dnsPort, function() { log('DNS server started') }) log('Starting katon server on port ' + config.katonPort) this.katon.listen(config.katonPort, function() { log('Katon server started') }) }, stop: function(callback) { log('Stop') this.katon.close(function() { log('Katon server stopped') }) this.dns.close(function() { log('DNS server stopped') }) for (var id in procs.list) { procs.list[id].stop() } setTimeout(callback, 1000) } }
var app = angular.module('app'); app.controller('demo', ['$scope', function ($scope) { $scope.onReady = function ($ueditor) { console.log("onReady"); console.log($ueditor); }; $scope.onContentChange = function ($content) { console.log("onContentChange"); console.log($content); } $scope.setting = { toolbars: [ ['fullscreen', 'source', 'undo', 'redo', 'bold'] ], autoHeightEnabled: true, autoFloatEnabled: true }; }]);
// Action Cable provides the framework to deal with WebSockets in Rails. // You can generate new channels where WebSocket features live using the `rails generate channel` command. // // require action_cable // require_self // require_tree ./channels // (function() { // this.App || (this.App = {}); // // App.cable = ActionCable.createConsumer(); // // }).call(this);
export const FETCH_REVIEW_INFO = 'FETCH_REVIEW_INFO'
var React = require('react'); var Modal = require('react-bootstrap').Modal; var Button = require('react-bootstrap').Button; var Input = require('react-bootstrap').Input; var DateTimeField = require('react-bootstrap-datetimepicker'); var NewFeatureRequest = React.createClass({ getInitialState: function() { return { showModal: false, title: null, description: null, client: 'Client A', clientPriority: null, targetDate: null, ticketURL: null, productArea: 'Policies' } }, render: function() { return ( <div> <Button className="new-feature-request btn-success" onClick={ this.onOpenModal }>New Feature Request</Button> <Modal show={ this.state.showModal } onHide={ this.onCloseModal } className="static-modal"> <Modal.Header> New Feature Request </Modal.Header> <Modal.Body> <Input type="text" label="Title" value={ this.state.title } onChange={ this.onTitleChange } /> <Input type="text" label="Description" value={ this.state.description } onChange={ this.onDescriptionChange }/> <Input type="select" label="Client" value={ this.state.client } onChange={ this.onClientChange }> <option value="Client A">Client A</option> <option value="Client B">Client B</option> <option value="Client C">Client C</option> </Input> <Input type="number" label="Client Priority" value={ this.state.clientPriority } onChange={ this.onClientPriorityChange }/> <label>Target Date</label> <DateTimeField onChange={ this.onTargetDateChange } defaultText="Select Date" /> <Input type="text" label="Ticket URL" value={ this.state.ticketURL } onChange={ this.onTicketURLChange }/> <Input type="select" label="Product Area" value={ this.state.productArea } onChange={ this.onProductAreaChange }> <option value="Policies">Policies</option> <option value="Billing">Billing</option> <option value="Claims">Claims</option> <option value="Reports">Reports</option> </Input> </Modal.Body> <Modal.Footer> <Button className='close-new-feature-request' onClick={ this.onCloseModal }>Close</Button> <Button className='create-new-feature-request btn-success' bStyle="primary" onClick={ this.onSubmit }>Create</Button> </Modal.Footer> </Modal> </div> ); }, onOpenModal: function() { this.setState({ showModal: true }); }, onCloseModal: function(e) { this.setState({ showModal: false }); }, onSubmit: function() { var featureRequest = { title: this.state.title, description: this.state.description, client: this.state.client, clientPriority: this.state.clientPriority, targetDate: this.state.targetDate, ticketURL: this.state.ticketURL, productArea: this.state.productArea }; fetch('/api/feature-requests', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': ' application/json' }, body: JSON.stringify({ featureRequest: featureRequest }) }).then(function(response) { response.text().then(function(responseText) { this.setState({ showModal: false, title: null, description: null, client: 'Client A', clientPriority: null, targetDate: null, ticketURL: null, productArea: 'Policies' }); this.props.reload(); this.onCloseModal(); }.bind(this)); }.bind(this)); }, onTitleChange: function(e) { this.setState({ title: e.target.value }); }, onDescriptionChange: function(e) { this.setState({ description: e.target.value }); }, onClientChange: function(e) { this.setState({ client: e.target.value }); }, onClientPriorityChange: function(e) { this.setState({ clientPriority: e.target.value }); }, onTargetDateChange: function(date) { this.setState({ targetDate: date }); }, onTicketURLChange: function(e) { this.setState({ ticketURL: e.target.value }); }, onProductAreaChange: function(e) { this.setState({ productArea: e.target.value }); } }); module.exports = NewFeatureRequest;
import expect from 'expect'; import reducer from '../../src/code/reducers/'; import { navigateToCurrentRoute, actionTypes as types } from '../../src/code/actions'; describe('navigateToCurrentRoute action', () => { const validLevel = 0, validMission = 1, validChallenge = 2, currentRouteAction = { type: types.NAVIGATED, level: validLevel, mission: validMission, challenge: validChallenge, skipRouteChange: true, meta: { logTemplateState: true, dontLog: ["skipRouteChange"], itsLog: { "actor": "USER", "action": "NAVIGATED", "target": "CHALLENGE" } } }, challengeAction = { type: types.NAVIGATED, level: validLevel, mission: validMission, challenge: validChallenge, route: "/1/2/3", meta: { "itsLog": { "actor": "USER", "action": "NAVIGATED", "target": "CHALLENGE" }, logTemplateState: true } }; const dispatch = expect.createSpy(); const getState = () => ({ routeSpec: {level: 0, mission: 0, challenge: 0}, gems: [[[], [[0], [1]]]], authoring: { "challenges": {"empty": {}}, "application": { "levels": [ { "missions": [ { "challenges": [] }, { "challenges": [{"id": "empty"}, {"id": "empty"}, {"id": "empty"}] }, { "challenges": [{"id": "empty"}] }, ] } ] } } }); it("should dispatch a navigateToCurrentRoute action when a valid challenge is specified", () => { navigateToCurrentRoute({level: validLevel, mission: validMission, challenge: validChallenge})(dispatch, getState); expect(dispatch.calls[0].arguments).toEqual([currentRouteAction]); }); it("should dispatch a navigateToChallenge action to the nearest valid challenge" + " when an invalid challenge is specified", () => { navigateToCurrentRoute({level: 0, mission: 1, challenge: 5})(dispatch, getState); expect(dispatch.calls[1].arguments).toEqual([challengeAction]); }); it("should dispatch a navigateToChallenge action to the nearest unlocked challenge" + " when a locked challenge is specified", () => { navigateToCurrentRoute({level: 0, mission: 2, challenge: 0})(dispatch, getState); expect(dispatch.calls[1].arguments).toEqual([challengeAction]); }); describe('the reducer', () => { it('should update the state to match the expected state when we navigate to a valid challenge', () => { let defaultState = reducer(undefined, {}); let initialState = defaultState.merge({ routeSpec: {level: 0, mission: 0, challenge: 0}, authoring: { "challenges": { "test": { template: "GenomePlayground", "initialDrake": { "alleles": "a:T,b:T", "sex": 1 } }, "empty": {}}, "application": { "levels": [ { "missions": [ { "challenges": [] }, { "challenges": [{"id": "empty"}, {"id": "empty"}, {"id": "test"}] } ] } ] } } }); let nextState = reducer(initialState, currentRouteAction); // By starting with nextState and merging in what we expect, we eliminate // all other properties from consideration. This is particularly an issue // for challenge navigation, which triggers loadStateFromAuthoring(), which // makes a large number of changes to the state that have nothing to do with // the navigation action itself. These loadStateFromAuthoring() changes tend // to change frequently, at least during these early days of new challenge // development. Requiring navigation unit tests to be modified whenever // loadStateFromAuthoring() changes leads to brittle unit tests. If one // wanted to unit test the loadStateFromAuthoring() changes, it could be // done with a unit test of that function directly. expect(nextState).toEqual(nextState.merge({ routeSpec: {level: 0, mission: 1, challenge: 2}, template: "GenomePlayground", challenges: 3, trialSuccess: false, })); }); }); });
//on button click $("html").on("click", "#getGeneration", function(){ //if year and month is entered //parseInt and check range for both as validation (will not pass with wrong range or letters included, etc) if(parseInt($("#yearInput").val()) >= 1753 && parseInt($("#yearInput").val()) <= 9999 && parseInt($("#monthInput").val()) >= 1 && parseInt($("#monthInput").val()) <= 12) { //get month of specfied year from api $.get("/api/"+$("#yearInput").val()+"/"+$("#monthInput").val(), function(data){ $("#generationOutput").html(data) $("#generationOutput").find("pre").addClass("singleMonth animated fadeIn") }) } //if month doesn't pass or isn't entered else if(parseInt($("#yearInput").val()) >= 1753 && parseInt($("#yearInput").val()) <= 9999) { //get month of specfied year from api $.get("/api/"+$("#yearInput").val(), function(data){ $("#generationOutput").html(data) $("#generationOutput").find("pre").addClass("animated fadeIn") }) } else { $("#generationOutput").html("<p class='centered'>There was an error with that request, please try again!</p>") } })
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "default", { enumerable: true, get: function get() { return _uxcoreTooltip.default; } }); var _uxcoreTooltip = _interopRequireDefault(require("uxcore-tooltip")); module.exports = exports.default;
if (!String.prototype.bind) { String.prototype.bind = function (model) { var result; result = this.replace(/.*data\-bind\-content="(\w+)".*/g, function (match, firstGroup) { var index = match.indexOf('>'); return match.slice(0, index + 1) + model[firstGroup] + match.slice(index + 1); }); result = result.replace(/.*data\-bind\-href="(\w+)".*/g, function (match, firstGroup) { var index = match.indexOf('>'); return match.slice(0, index) + ' href="' + model[firstGroup] + '"' + match.slice(index); }); result = result.replace(/.*data\-bind\-class="(\w+)".*/g, function (match, firstGroup) { var index = match.indexOf('>'); return match.slice(0, index) + ' class="' + model[firstGroup] + '"' + match.slice(index); }); return result; }; } var str = '<a data-bind-content="name" data-bind-href="link" data-bind-class="name"></a>'; console.log(str); console.log(str.bind({name: 'Elena', link: 'http://telerikacademy.com'}));
var http=require("http"); http.createServer(function(req,res){ res.writeHead(200,{'Content-Type': 'text/html'}); res.write('<h1>Hello World</h1>'); res.end('<p>加油加油~~</p>'); }).listen(3000); console.log("3000服务器已经被打开");
/************************************************* Attributes: *************************************************/ PointController.prototype.dataLoader; PointController.prototype.textureLayer; PointController.prototype.pointsLayer; PointController.prototype.rawData; PointController.prototype.daySlider; PointController.prototype.texOptions = [4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]; PointController.prototype.pointSizeOptions = [0.1, 0.2, 0.5, 0.7, 1.0, 1.5, 2.0, 3.0, 5.0, 7.0]; PointController.prototype.dataDirOptions = ['data/tmp/FunctDay1_csv/', 'data/tmp/FunctDay3_csv/', 'data/tmp/FunctDay7_csv/', 'data/tmp/FunctDay14_csv/']; /************************************************* Constructors: *************************************************/ function PointController(dataLoader, rootNode, data) { this.dataLoader = dataLoader; this.textureLayer = dataLoader.textureLayer; this.pointsLayer = dataLoader.pointLayer; this.rawData = data; this.init(rootNode); } /************************************************* Methods: *************************************************/ PointController.prototype.init = function(rootNode) { this.initPage(rootNode); } PointController.prototype.initPage = function(rootNode) { var self = this; var self = this; d3.text("point.html", "text/plain", function(error, data) { if (error != null) { console.warn(error); } else { $(rootNode).append(data); var margin = { top: 5, right: 10, bottom: 5, left: 10, }; var textureDimension = new SliderBrush("td.textureSlider", 7, [0, self.texOptions.length - 1], [200, 42], margin, self.onNewTextureDimension()); var scaleDimension = new SliderBrush("td.scaleSlider", 2, [0, self.texOptions.length - 1], [200, 42], margin, self.onNewScaleDimension()); var pointSize = new SliderBrush("td.pointSlider", 2, [0, self.pointSizeOptions.length - 1], [200, 42], margin, self.onNewPointSize()); self.daySlider = new SliderBrush("td.daySlider", 0, [0, self.dataDirOptions.length - 1], [200, 42], margin, self.onNewDay()); self.initKeyPress(); $("input.textureCheckBox").on("change", self.onCheckBoxChange(self.dataLoader.showTexture)); $("input.pointsCheckBox").on("change", self.onCheckBoxChange(self.dataLoader.showPoints)); } }); } PointController.prototype.initKeyPress = function() { var self = this; document.onkeydown = checkKey; function checkKey(e) { e = e || window.event; if (e.keyCode == '39') { self.daySlider.incValue(self.daySlider); } else if (e.keyCode == '37') { self.daySlider.decValue(self.daySlider); } else if (e.keyCode == '78') { self.daySlider.incValue(self.daySlider); } else if (e.keyCode == '66') { self.daySlider.decValue(self.daySlider); } } } PointController.prototype.setRawData = function(data) { var self = this; self.rawData = data; if ($("input.textureCheckBox").is(':checked')) { self.dataLoader.showTexture(self.dataLoader, self.rawData); } if ($("input.pointsCheckBox").is(':checked')) { self.dataLoader.showPoints(self.dataLoader, self.rawData); } } PointController.prototype.onCheckBoxChange = function(show) { var self = this; return function() { if ($(this).is(':checked')) { show(self.dataLoader, self.rawData); } else { show(self.dataLoader, []); } } } PointController.prototype.onNewTextureDimension = function() { var self = this; return function(value) { self.dataLoader.texHeight = self.texOptions[value]; self.dataLoader.texWidth = self.texOptions[value]; if ($("input.textureCheckBox").is(':checked')) { self.dataLoader.showTexture(self.dataLoader, self.rawData); } } } PointController.prototype.onNewScaleDimension = function() { var self = this; return function(value) { self.dataLoader.colorTexHeight = self.texOptions[value]; if ($("input.textureCheckBox").is(':checked')) { self.dataLoader.showTexture(self.dataLoader, self.rawData); } if ($("input.pointsCheckBox").is(':checked')) { self.dataLoader.showPoints(self.dataLoader, self.rawData); } } } PointController.prototype.onNewPointSize = function() { var self = this; return function(value) { self.dataLoader.pointSize = self.pointSizeOptions[value]; if ($("input.pointsCheckBox").is(':checked')) { self.dataLoader.showPoints(self.dataLoader, self.rawData); } } } PointController.prototype.onNewDay = function() { var self = this; return function(value) { self.dataLoader.reloadDataToMap(self.dataLoader, self.dataDirOptions[value]); if ($("input.textureCheckBox").is(':checked')) { self.dataLoader.showTexture(self.dataLoader, self.rawData); } if ($("input.pointsCheckBox").is(':checked')) { self.dataLoader.showPoints(self.dataLoader, self.rawData); } } }
//var API_BASE = '../server/'; // <- this is for if hosted on same localhost. var API_BASE = 'http://davidrs.com/craigit/server/'; var userEmail = ''; var preferredCraigslist ='http://washingtondc.craigslist.org'; var app = { //start app load: function(){ if(localStorage){ // Retrieve Email if found userEmail = localStorage.getItem("email"); if(userEmail && userEmail.length>0){ app.getSearches(userEmail); $('#emailSearch').val(userEmail); } preferredCraigslist = localStorage.getItem("preferredCraigslist"); if(preferredCraigslist){ console.log('preferredCraigslist',preferredCraigslist); $('#baseurl').val(preferredCraigslist); } } this.createRoutes(); }, createRoutes: function(){ var self = this; Finch.route('user/:email', function(res){ self.getSearches(res.email); }); Finch.listen(); }, // Send a search to the server submitSearch: function(newSearch){ newSearch.email = userEmail; $.ajax(API_BASE+'submitSearch.php',{ data:newSearch, success:function(data){ console.log("search response",data); data = JSON.parse(data); if(data.status == "success"){ $('#search-container').hide(); $('#success-message').show(); app.resetForm(); } else{ alert("Error submitting search, "+data); console.warn("Error submitting search, ", data); } //Run getSearches to show latest app.getSearches(userEmail); } }); }, // Print html //TODO add templating engine and use templates printSearchResults: function(data){ $('#search-results').html(''); //TODO group into 3s and add to a row DOM, then append it to search results. for(var key in data){ var html = '<div class="col-md-4 search-listing">'+ '<h3>'+decodeURIComponent(data[key].query.query)+'</h3>'+ '<p>'+ 'Search Radius:'+data[key].filter.distance +' miles'+ (data[key].query.minAsk? '<br />Min: $'+data[key].query.minAsk:'') + (data[key].query.maxAsk? '<br />Max: $'+data[key].query.maxAsk:'') + '</p>'+ //TODO print all results that have been sent. '<p><a class="btn btn-danger" href="#" role="button" data-id="'+data[key].id+'">Delete</a></p>'+ '</div>'; $('#search-results').append(html); } $('#search-results a.btn-danger').click(function(evt){ evt.preventDefault(); var clickedId = $(evt.currentTarget).data('id'); app.deleteSearch(clickedId, evt); }); }, resetForm: function(){ $('#query').val(''); //$('#search-container').hide(); }, // delete the search with this id deleteSearch: function(clickedId, evt){ console.log('About to Delete: ', clickedId); $.ajax(API_BASE+'deleteSearch.php',{ data:{id:clickedId, email:userEmail}, success:function(data){ data = JSON.parse(data); if(data.status == "success"){ $(evt.currentTarget).parents('.search-listing').remove(); } else{ alert('delete failed'); console.error('delete failed:',data); } } }); }, // Gets all searches for a user getSearches: function(userEmail){ if(userEmail != ''){ $('#login-section').hide(); $('.active-user').text(userEmail); $('#logout-section').show(); $('#emailSearch').val(userEmail); } $.ajax(API_BASE+'getSearches.php',{ data:{email:userEmail}, success:function(data){ console.log('getSearches: ',data); data = JSON.parse(data); if(data.length>0){ app.printSearchResults(data); } else{ //TODO prettier info feedback. alert("no listings found for this user."); } } }); } };
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PollList from '../../components/PollList'; import PollCreateModal from '../../components/PollCreateModal/PollCreateModal'; import { fetchPolls, createPoll } from '../../PollActions'; import { Container, Button } from 'semantic-ui-react'; class PollListPage extends Component{ componentDidMount() { this.props.dispatch(fetchPolls()); } submit = (poll) => { this.props.dispatch(createPoll(poll)); } render(){ return ( <Container fluid> <Container textAlign='right'> <PollCreateModal onSubmit={this.submit} /> <Button>My Polls</Button> </Container> <PollList polls={ this.props.polls } /> </Container> ); }; } PollListPage.need = [() => { return fetchPolls(); }]; function mapStateToProps(state){ return { polls : state.polls.data }; } export default connect(mapStateToProps)(PollListPage);
(function (exports) { var canvas, canvas2, ctx, ctx2, gens, objects, tsize, onLoop, tcolor, d, requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }, Game = { init: init, gravity: 0.08, md: 0.1, maxy: 10, maxx: 5, width: 0, height: 0, tsize: 1, tick: 0, generators: function () { return gens; }, top_edge: function (p) { var cy = Game.tsize * Math.floor(p.y/Game.tsize); return p.y*2-cy; }, bottom_edge: function (p) { var cy = Game.tsize * Math.floor(p.y/Game.tsize); if (p.y+p.r >= Game.height) return Game.height-p.r; return cy-p.r+Game.tsize; }, left_edge: function (p) { var cx = Game.tsize * Math.floor(p.x/Game.tsize); return p.x*2-cx; }, right_edge: function (p) { var cx = Game.tsize * Math.floor(p.x/Game.tsize); return p.x*2-cx-Game.tsize; }, size: function (w, h) { var i; Game.width = canvas.width = w; Game.height = canvas.height = h; canvas2.width = w; canvas2.height = h; if (gens) { for (i = 0; i < gens.length; i++) { gens[i].x = canvas.width/2; gens[i].y = canvas.height*0.75; } } } }; function init (w, h, fn) { tcolor = new Color(0, 40, 10); onLoop = fn || function () {}; canvas = document.getElementById('stage'); canvas2 = document.getElementById('stage2'); Game.size(w, h); canvas.focus(); ctx = canvas.getContext('2d'); ctx2 = canvas2.getContext('2d'); objects = []; gens = []; gens.push(new ParticleGenerator({ x: canvas.width/2, y: canvas.height*0.75, intensity: 10, r: 5 })); loop(); } function loop () { var i, j, p, explode, newColor, n = 8, tsize = Game.tsize; Game.tick++; ctx.clearRect(0, 0, canvas.width, canvas.height); if (Game.tick % 4 == 0) { ctx2.clearRect(0, 0, canvas.width, canvas.height); } // update objects for (i = 0; i < objects.length; i++) { p = objects[i]; explode = p.update(); if (!p.alive || p.y >= canvas.height || p.x <= 0 || p.x >= canvas.width) { objects.splice(objects.indexOf(p), 1); } if (explode) { newColor = p.color.rand(); for (j = 0; j < n; j++) { objects.push(new Particle({ x: p.x, y: p.y, dx: 2 * Math.cos(2*Math.PI / n * j), dy: 2 * Math.sin(2*Math.PI / n * j), color: newColor, r: 2 + (Math.random()*4) })); } } if (!p.alive) { p.r = explode ? 16 : 1.5; p.render(ctx2); } } // update generators for (i = 0; i < gens.length; i++) { if (Game.tick % 2 === 0) { gens[i].angle = -(Math.PI/4 + (Math.random() * Math.PI/2)); p = gens[i].update(); if (p !== undefined) { objects.push(p); } } } // render for (i = 0; i < objects.length; i++) { p = objects[i]; p.render(ctx); } input.update(); // update input onLoop(); requestAnimFrame(loop); } exports.Game = Game; }(window));
import React from 'react'; import PureRenderMixin from 'react-addons-pure-render-mixin'; import {FormGroup, ControlLabel, FormControl, Button, Alert} from 'react-bootstrap'; import {isEmail} from '../utils' class ForgotPassword extends React.Component { constructor(props) { super(props); this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this); } changeEmail(event) { this.props.setState({email: event.target.value}); } sendEmail(event) { if (this.valid()) { event.preventDefault(); this.props.forgotPassword(this.props.email); } } valid() { return this.props.email && isEmail(this.props.email); } render() { return ( <div className="col-md-4 col-md-offset-4"> {this.props.emailStatus ? <Alert bsStyle="info"> {this.props.ok ? '' : <i className="fa fa-fw fa-exclamation-circle"/>} {this.props.emailStatus} </Alert> : '' } <form> <FormGroup controlId="email"> <ControlLabel>Email</ControlLabel> <FormControl type="email" value={this.props.email} onChange={this.changeEmail.bind(this)} required/> </FormGroup> <Button type="submit" bsStyle="primary" className="full-width" onClick={this.sendEmail.bind(this)}> Send email </Button> </form> </div> ); } } export default ForgotPassword;
'use strict'; const {check} = require('../util'); const bee = require('../../src/index'); describe('[remove register]', () => { it('normal', () => { let ori = { name: null, age: 12, privacy: { location: 'china', occupation: 'front-end' }, detail: null }; let beeOptions = { privacy: bee.remove() }; check(ori, beeOptions, { name: null, age: 12, detail: null }); }); it('in deep', () => { let ori = { node: { info: { data: { name: 'foo' } } } }; let beeOptions = { node: { info: { data: { name: bee.remove() } } } }; check(ori, beeOptions, { node: { info: { data: {} } } }); }); it('unknown key', () => { let ori = {}; let beeOptions = { unknownKey: bee.remove() }; check(ori, beeOptions, {}); }); it('multi apply', () => { let ori = { name: [] }; let beeOptions = { name: bee.remove().remove().remove() }; check(ori, beeOptions, {}); }); it('chaining call', () => { let ori = { num: 1 }; let beeOptions = { num: bee.remove().remove() }; check(ori, beeOptions, {}); }); });
(function(){ var self = this; //avalon control space var items_ctrl = avalon.define({ $id: 'items_ctrl', data:[], sort: 0, page_start: 0, show_more: false, get_pic_path: function(path){ return upload_img+path; }, get_detail_link : function(e){ window.location.href = base_url+'item/view/'+e; }, get_detail_link_pc : function(e){ return base_url+'item/view_pc/'+e; }, get_content_text: function(e){ return e.substr(0, 45)+'...'; }, get_items_with_pic:function(){ var url = base_url+'Item/get_items_normal_with_pic'; base_remote_data.ajaxjson( url, //url function(data){ if(data.hasOwnProperty('success')){ if(data.success == 1){ // console.log(data); // console.log('获取列表及图片成功!'); for (var i = 0; i < data.data.length; i++) { items_ctrl.data.push(data.data[i]); } //长度大与interval 就加到起始位置 if (data.data.length == page_interval) { items_ctrl.page_start += data.data.length; //show more items_ctrl.show_more = true; } else { items_ctrl.show_more = false; } // console.log('page_start:'+items_ctrl.page_start); } else{ alert(data.message); } } else { alert('返回值错误!'); } }, {'page_start': items_ctrl.page_start}, function() { alert('网络错误!'); }); } }); //Init codes run once items_ctrl.get_items_with_pic(); }).call(define('space_view_items'));
'use strict'; var sinon = require('sinon'); beforeEach(function() { this.sinon = sinon.sandbox.create(); }); afterEach(function() { this.sinon.verifyAndRestore(); });
version https://git-lfs.github.com/spec/v1 oid sha256:c02b17354c602d7b83aa235eb024e27c4e212963dfb323dc96454ed5218ed539 size 1583
/** * Build the CSS Framework Documentation */ import gulp from 'gulp' import sassdoc from 'sassdoc' const sassdocGenerateTask = () => { return gulp .src('src/framework/**/*.scss') .pipe(sassdoc( { dest: 'doc/sassdoc' } )) } gulp.task('sassdoc:generate', sassdocGenerateTask) module.exports = sassdocGenerateTask
export default { templateUrl: "layout/shell/layout.shell.html" };
/* *********************************************************************************** * EventHandlers - Class that each instance of ScrollingTabsControl will instantiate * **********************************************************************************/ function EventHandlers(scrollingTabsControl) { var evh = this; evh.stc = scrollingTabsControl; } // prototype methods (function (p){ p.handleClickOnLeftScrollArrow = function (e) { var evh = this, stc = evh.stc; stc.scrollMovement.incrementScrollLeft(); }; p.handleClickOnRightScrollArrow = function (e) { var evh = this, stc = evh.stc, scrollMovement = stc.scrollMovement; scrollMovement.incrementScrollRight(scrollMovement.getMinPos()); }; p.handleMousedownOnLeftScrollArrow = function (e) { var evh = this, stc = evh.stc; stc.scrollMovement.startScrollLeft(); }; p.handleMousedownOnRightScrollArrow = function (e) { var evh = this, stc = evh.stc; stc.scrollMovement.startScrollRight(); }; p.handleMouseupOnLeftScrollArrow = function (e) { var evh = this, stc = evh.stc; stc.scrollMovement.stopScrollLeft(); }; p.handleMouseupOnRightScrollArrow = function (e) { var evh = this, stc = evh.stc; stc.scrollMovement.stopScrollRight(); }; p.handleWindowResize = function (e) { var evh = this, stc = evh.stc, newWinWidth = stc.$win.width(); if (newWinWidth === stc.winWidth) { return false; // false alarm } stc.winWidth = newWinWidth; stc.elementsHandler.refreshAllElementSizes(); }; }(EventHandlers.prototype));
'use strict'; exports.root = __dirname; exports.name = 'rco_ads'; exports.init = function (N) { require('./lib/autoload.js')(N); };
var mmhome = angular.module('mmhome', [ 'ngRoute']); mmhome .controller('index_controller', function() { }) .config(function($routeProvider, $locationProvider) { var index = { templateUrl: 'tpl/index.html', controller: 'index_controller' }; $routeProvider .when('/', index); $locationProvider.html5Mode(true); });
'use strict'; const jwt = require('koa-jwt'); const {extend} = require('lodash'); const env = process.env.NODE_ENV || 'development'; const {jwtSecret} = require('../config')[env]; const {User} = require('../models'); const regToken = require('../lib/reg-token'); /** * @api {post} /admin/login Авторизация * @apiName AuthLogin * @apiGroup Auth * @apiDescription Админов нельзя регистрировать. * Можно только логиниться с данными указанными в сорцах * (до смены пароля). * * @apiParam {String} login * @apiParam {String} password * * @apiSuccess {String} token jwt, use it in Authorization header * * @apiUse NotAuthorizedError */ exports.login = function*() { let {login, password} = this.request.body; if (!(login && password)) { this.throw(400, 'login and password are required'); } let user = yield User.findOne({ where: { login: login } }); if (!(user && user.authenticate(password))) { this.throw(401, 'Неверные логин или пароль'); } if (user.isBlocked) { this.throw(401, 'Пользователь заблокирован'); } let token = jwt.sign(user.toJSON(), jwtSecret); this.body = extend(user.toJSON(), { token: token }); }; exports.register = function*() { let currentRegToken = yield regToken(); if (this.request.body.regToken !== currentRegToken) { this.throw(401, 'Invalid registration token'); } let user = User.build(this.request.body); try { yield user.save(); } catch(err) { this.throw(400, err.message); } let token = jwt.sign(user.toJSON(), jwtSecret); this.body = extend(user.toJSON(), { token: token }); }; /** * @api {get} /admin/auth/regtoken Токен регистрации * @apiName RegistrationToken * @apiGroup Auth * @apiDescription Отдает токен, который используется * при регистрации юзеров. Генерит новый токен каждый день * * @apiSuccess {String} token Админ будет давать этот токен юзерам для регистрации * * @apiSuccessExample {json} registration token * { * "token": "1234567890abcdef" * } * * @apiUse BadRequestError */ exports.regToken = function*() { let token = yield regToken(); this.body = { token: token }; };
// Fixture for has function // Object literals with attributes to test against var has_attribute_fixture = { "hello": { "world": { "foo bar": { "baz": true } } } }; if (typeof module !== "undefined") { module.exports = has_attribute_fixture; } // End of file
const express=require('express'); const mongoose=require('mongoose'); const Participant=require('../model/participant'); const router=express.Router(); router.route('/') .post(function(req,res){ const participant=new Participant(req.body); participant.save(function(err,participant){ if(err){ res.status(400).json(err); } res.json(participant); }); }); module.exports=router;
var mongoose = require('mongoose'); var name = "candidateElection"; function makeSchema() { var schema = mongoose.Schema({ electionId: { type: mongoose.Schema.Types.ObjectId, required: true }, value: { type: Number, required: true }, votes: [mongoose.model('vote').schema] }); return schema; } function makeModel(db, schema) { return db.model(name, schema); } module.exports = { makeSchema: makeSchema, makeModel: makeModel, name: name }
import Field from './field'; import React, { PropTypes } from 'react'; import Select from 'react-select'; class DropdownField extends React.Component { constructor(props) { super(props); this.state = { selectedItem: typeof props.selectedItem !== 'undefined' ? props.selectedItem : props.clearable ? null : props.options[0].value, }; this.onChange = this.onChange.bind(this); } onChange(value) { if (this.props.onChange) { this.props.onChange(value); } this.setState({ selectedItem: value ? value.value : null }); } componentWillReceiveProps(nextProps) { this.setState({ selectedItem: nextProps.selectedItem }); } render() { return ( <Field fieldName={this.props.fieldName} label={this.props.label} labelPosition={this.props.labelPosition}> <Select className="dropdown" options={this.props.options} name={this.props.name} value={this.state.selectedItem} onChange={this.onChange} searchable={this.props.searchable} clearable={this.props.clearable} placeholder={this.props.searchable ? 'Type to search...' : 'Select...'} multi={false} /> </Field> ); } } DropdownField.propTypes = { selectedItem: PropTypes.string, clearable: PropTypes.bool, options: PropTypes.arrayOf(PropTypes.object), onChange: PropTypes.func, name: PropTypes.string, fieldName: PropTypes.string, label: PropTypes.string, labelPosition: PropTypes.string, searchable: PropTypes.bool, }; DropdownField.defaultProps = { searchable: false, clearable: false, }; export default DropdownField;
'use strict'; // MODULES // var isNumber = require( 'validate.io-number-primitive' ), isnan = require( 'validate.io-nan' ), isArrayLike = require( 'validate.io-array-like' ), isTypedArrayLike = require( 'validate.io-typed-array-like' ), isMatrixLike = require( 'validate.io-matrix-like' ), ctors = require( 'compute-array-constructors' ), matrix = require( 'dstructs-matrix' ), validate = require( './validate.js' ); // FUNCTIONS // var erfc1 = require( './number.js' ), erfc2 = require( './array.js' ), erfc3 = require( './accessor.js' ), erfc4 = require( './deepset.js' ), erfc5 = require( './matrix.js' ), erfc6 = require( './typedarray.js' ); // COMPLEMENTARY ERROR FUNCTION // /** * FUNCTION: erfc( x[, opts] ) * Computes the complementary error function. * * @param {Number|Number[]|Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|Matrix} x - input value * @param {Object} [opts] - function options * @param {Boolean} [opts.copy=true] - boolean indicating if the function should return a new data structure * @param {Function} [opts.accessor] - accessor function for accessing array values * @param {String} [opts.path] - deep get/set key path * @param {String} [opts.sep="."] - deep get/set key path separator * @param {String} [opts.dtype="float64"] - output data type * @returns {Number|Number[]|Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|Matrix} complementary error function value(s) */ function erfc( x, options ) { /* jshint newcap:false */ var opts = {}, ctor, err, out, dt, d; if ( isNumber( x ) || isnan( x ) ) { return erfc1( x ); } if ( arguments.length > 1 ) { err = validate( opts, options ); if ( err ) { throw err; } } if ( isMatrixLike( x ) ) { if ( opts.copy !== false ) { dt = opts.dtype || 'float64'; ctor = ctors( dt ); if ( ctor === null ) { throw new Error( 'erfc()::invalid option. Data type option does not have a corresponding array constructor. Option: `' + dt + '`.' ); } // Create an output matrix: d = new ctor( x.length ); out = matrix( d, x.shape, dt ); } else { out = x; } return erfc5( out, x ); } if ( isTypedArrayLike( x ) ) { if ( opts.copy === false ) { out = x; } else { dt = opts.dtype || 'float64'; ctor = ctors( dt ); if ( ctor === null ) { throw new Error( 'erfc()::invalid option. Data type option does not have a corresponding array constructor. Option: `' + dt + '`.' ); } out = new ctor( x.length ); } return erfc6( out, x ); } if ( isArrayLike( x ) ) { // Handle deepset first... if ( opts.path ) { opts.sep = opts.sep || '.'; return erfc4( x, opts.path, opts.sep ); } // Handle regular and accessor arrays next... if ( opts.copy === false ) { out = x; } else if ( opts.dtype ) { ctor = ctors( opts.dtype ); if ( ctor === null ) { throw new TypeError( 'erfc()::invalid option. Data type option does not have a corresponding array constructor. Option: `' + opts.dtype + '`.' ); } out = new ctor( x.length ); } else { out = new Array( x.length ); } if ( opts.accessor ) { return erfc3( out, x, opts.accessor ); } return erfc2( out, x ); } return NaN; } // end FUNCTION erfc() // EXPORTS // module.exports = erfc;
angular.module('pages', [ 'uiGmapgoogle-maps', 'app.home', 'app.modals', 'app.popups', 'app.customPopup', 'app.picker', 'app.list', 'app.forms', 'app.cards', 'app.map', 'app.foodApp' ]) angular.module('app', ['framework7', 'pages']) .config(function($F7Provider, $F7RouterProvider){ $F7Provider.init({ swipePanel: 'left', materialRipple: false, animateNavBackIcon: true, cache: false }, true); $F7Provider.addView('main', '.view-main', { domCache: true, dynamicNavbar: true, }, true); })
/* * gulp-spellcheck * * Copyright(c) 2014 André König <andre.koenig@posteo.de> * MIT Licensed * */ /** * @author André König <andre.koenig@posteo.de> * */ 'use strict'; var fs = require('fs'); var path = require('path'); var spellcheck = require('../'); var gutil = require('gulp-util'); describe('The "gulp-spellcheck" plugin', function () { var file = new gutil.File({ base: __dirname, cwd: __dirname, path: path.join(__dirname, 'checkable.md'), contents: fs.readFileSync(path.join(__dirname, 'checkable.md')) }); it('should find wrong words', function (done) { var strom = spellcheck(); var checked = ''; strom.on('data', function (chunk) { checked = checked + chunk.contents.toString('utf-8'); }); strom.on('end', function onEnd () { expect(checked.indexOf('suggestions')).not.toBe(-1); done(); }); strom.write(file); strom.end(); }); it('should return an error if the language is unknown', function (done) { var strom = spellcheck({ language: 'unknownLanguage' }); strom.on('error', function (err) { expect(err).toBeDefined(); done(); }); strom.write(file); strom.end(); }); });