code
stringlengths
2
1.05M
Lizard.Models.CollageItem = Backbone.AssociatedModel.extend({ defaults: { graph_index: 0, timeseries: [] } });
import React from 'react'; import { ListItem, Radio, Left, Right, Text } from 'native-base'; // Radio button list item with title and note. const RadioWithNote = ({ title, note, selected, onPress }) => <ListItem selected={selected} onPress={onPress} > <Left> <Radio selected={selected} onPress={onPress} /> <Text>{title}</Text> <Right> <Text note>{note}</Text> </Right> </Left> </ListItem>; RadioWithNote.propTypes = { title: React.PropTypes.string.isRequired, note: React.PropTypes.string.isRequired, selected: React.PropTypes.bool.isRequired, onPress: React.PropTypes.func.isRequired, }; export default (RadioWithNote);
/* * GET home page. */ exports.index = function(req, res){ res.render('index'); }; exports.main = function(req, res){ res.render('main'); }; exports.deco = function(req, res){ res.render('deco'); };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var pauseCircleO = exports.pauseCircleO = { "viewBox": "0 0 1536 1792", "children": [{ "name": "path", "attribs": { "d": "M768 128q209 0 385.5 103t279.5 279.5 103 385.5-103 385.5-279.5 279.5-385.5 103-385.5-103-279.5-279.5-103-385.5 103-385.5 279.5-279.5 385.5-103zM768 1440q148 0 273-73t198-198 73-273-73-273-198-198-273-73-273 73-198 198-73 273 73 273 198 198 273 73zM864 1216q-14 0-23-9t-9-23v-576q0-14 9-23t23-9h192q14 0 23 9t9 23v576q0 14-9 23t-23 9h-192zM480 1216q-14 0-23-9t-9-23v-576q0-14 9-23t23-9h192q14 0 23 9t9 23v576q0 14-9 23t-23 9h-192z" } }] };
import styled from 'styled-components'; import Divider from '@material-ui/core/Divider'; const StyledDivider = styled(Divider)` margin-left: 16px !important; `; export default StyledDivider;
import StringUtil from '../StringUtil' import View from '../View' /** * Field view */ export default class FieldView extends View { /** * Constructor */ constructor () { super() this._$message = null this._message = null this._id = StringUtil.uniqueId() this._first = false } /** * Returns wether this field is the first in a row. * @return {boolean} */ isFirst () { return this._first } /** * Sets wether this field is the first in a row. * @param {boolean} * @return {Field} Fluent interface */ setFirst (first) { if (this._first !== first) { this._first = first if (first) { this.getElement().classList.add('field--first') } else { this.getElement().classList.remove('field--first') } } return this } /** * Returns the current message, if any. * @protected * @return {?string} Message or null */ getMessage () { return this._message } /** * Sets the message. * @protected * @param {?string} message * @return {FieldView} Fluent interface */ setMessage (message) { this._message = message return this.update() } /** * Clears the message. * @protected * @return {FieldView} Fluent interface */ clearMessage () { return this.setMessage(null) } /** * Returns field id. * @return {string} */ getId () { return this._id } /** * Renders view. * @protected * @return {HTMLElement} */ render () { return View.createElement('div', { className: 'field' + (this._first ? ' field--first' : '') }, [ this.renderLabel(), this.renderField() ]) } /** * Renders label. * @protected * @return {?HTMLElement} */ renderLabel () { return View.createElement('label', { className: 'field__label', htmlFor: this.getId() }, this.getModel().getLabel()) } /** * Renders field. * @protected * @return {?HTMLElement} */ renderField () { return View.createElement('div', { className: 'field__field' }) } /** * Renders message. * @protected * @return {?HTMLElement} */ renderMessage () { if (this.getMessage() !== null) { return View.createElement('div', { className: 'field__message' }, this.getMessage()) } return null } /** * Triggered after rendering root element. */ didRender () { super.didRender() // Update value initially this.updateValue() } /** * Updates view on model change. * @return {FieldView} Fluent interface */ update () { const $field = this.getElement() // Set width attr $field.dataset.width = this.getModel().getWidth() // Set focus modifier if (this.hasFocus()) { $field.classList.add('field--focus') } else { $field.classList.remove('field--focus') } // Add invalid modifier if (!this.getModel().isValid() || this.getMessage() !== null) { $field.classList.add('field--invalid') } else { $field.classList.remove('field--invalid') } // Remove old message, if any if (this._$message !== null && this._$message.parentNode !== null) { this._$message.parentNode.removeChild(this._$message) } this._$message = null // Create new message, if any this._$message = this.renderMessage() if (this._$message !== null) { this.getElement().appendChild(this._$message) } return this } /** * Triggered when view receives focus. */ didFocus () { this.getElement().classList.add('field--focus') } /** * Triggered when view loses focus. */ didBlur () { this.getElement().classList.remove('field--focus') } /** * Retrieves value from model and updates it in view. * @override * @return {FieldView} Fluent interface */ updateValue () { // Nothing to do return this } }
'use strict'; // ------------------------------------------------------------------------------ // Requirements // ------------------------------------------------------------------------------ var rule = require('../rules/controller-as-route'); var RuleTester = require('eslint').RuleTester; var commonFalsePositives = require('./utils/commonFalsePositives'); // ------------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------------ var eslintTester = new RuleTester(); eslintTester.run('controller-as-route', rule, { valid: [ '$routeProvider.when("/myroute", {controller: "MyController", controllerAs: "vm"})', '$routeProvider.when("/myroute2", {template: "<div></div>"})', '$stateProvider.state("mystate", {controller: "MyController", controllerAs: "vm"})', '$stateProvider.state("mystate2", {controller: "MyController as vm"})', '$stateProvider.state("mystate2", {template: "<div></div>"})', 'something.when("string", {controller: "MyController"})', 'when("string", {controller: "MyController"})', 'state("mystate2", {})', 'var state = "mystate2"', 'something[type][changeType][state](test)', 'var when = "mystate2"', 'something[type][changeType][when](test)' ].concat(commonFalsePositives), invalid: [ {code: '$routeProvider.when("/myroute", {controller: "MyController"})', errors: [{message: 'Route "/myroute" should use controllerAs syntax'}]}, {code: '$routeProvider.when("/myroute", {controller: "MyController", controllerAs: "vm"}).when("/myroute2", {controller: "MyController"})', errors: [{message: 'Route "/myroute2" should use controllerAs syntax'}]}, {code: '$stateProvider.state("mystate", {controller: "MyController"})', errors: [{message: 'State "mystate" should use controllerAs syntax'}]}, {code: '$stateProvider.state("mystate", {controller: "MyController", controllerAs: "vm"}).state("mystate2", {controller: "MyController"})', errors: [{message: 'State "mystate2" should use controllerAs syntax'}]}, {code: '$stateProvider.state({name: "myobjstate", controller: "MyController"})', errors: [{message: 'State "myobjstate" should use controllerAs syntax'}]} ] });
version https://git-lfs.github.com/spec/v1 oid sha256:9ba8c58b9640c65237b1fb95671725637f01a3b9e460a34c39a5d788a5eb1af9 size 1031
var dayRouter = require('express').Router(); var attractionRouter = require('express').Router(); var models = require('../models'); // GET /days dayRouter.get('/', function(req, res, next) { console.log('duuude') // serves up all days as json models.Day.find().sort({number: 1}).populate("hotels restaurants thingsToDo") .exec(function(err, result){ console.log(err) console.log(result) res.json(result) }) }); // POST /days dayRouter.post('/', function(req, res, next) { // creates a new day and serves it as json models.Day.find().count(function(err, numDays){ var newDay = new models.Day( {number: numDays+1} ) newDay.save(function(err, dayObj){ res.json(dayObj) }) }) }); // GET /days/:id // id refers to the day number dayRouter.get('/:id', function(req, res, next) { // serves a particular day as json var id = req.param.id; models.Day.findById(id) .exec(function(err, day) { res.json(day) }); }); // DELETE /days/:id dayRouter.delete('/:id', function(req, res, next) { // deletes a particular day var id = req.param.id; models.Day.remove( {number: id} ) next(); }); dayRouter.use('/:id', attractionRouter); // POST /days/:id/hotel attractionRouter.post('/hotel', function(req, res, next) { // creates a reference to the hotel var id = req.param.id; models.Day.findOneAndUpdate({number: id},function(err, day){ day.hotel = req.body.hotel; day.save(); res.send(); }) }); // DELETE /days/:id/hotel attractionRouter.delete('/hotel', function(req, res, next) { // deletes the reference of the hotel var id = req.param.id; models.Day.findOneAndUpdate({number: id},function(err, day){ day.hotel = undefined; day.save(); res.send(); }) }); // POST /days/:id/restaurants attractionRouter.post('/restaurants', function(req, res, next) { // creates a reference to a restaurant var id = req.param.id; }); // DELETE /days/:dayId/restaurants/:restId attractionRouter.delete('/restaurant/:id', function(req, res, next) { // deletes a reference to a restaurant var id = req.param.id; }); // POST /days/:id/thingsToDo attractionRouter.post('/thingsToDo', function(req, res, next) { // creates a reference to a thing to do var id = req.param.id; }); // DELETE /days/:dayId/thingsToDo/:thingId attractionRouter.delete('/thingsToDo/:id', function(req, res, next) { // deletes a reference to a thing to do var id = req.param.id; }); module.exports = dayRouter;
/** @constructor */ ScalaJS.c.scala_util_Failure$ = (function() { ScalaJS.c.java_lang_Object.call(this) }); ScalaJS.c.scala_util_Failure$.prototype = new ScalaJS.inheritable.java_lang_Object(); ScalaJS.c.scala_util_Failure$.prototype.constructor = ScalaJS.c.scala_util_Failure$; ScalaJS.c.scala_util_Failure$.prototype.toString__T = (function() { return "Failure" }); ScalaJS.c.scala_util_Failure$.prototype.apply__Ljava_lang_Throwable__Lscala_util_Failure = (function(exception) { return new ScalaJS.c.scala_util_Failure().init___Ljava_lang_Throwable(exception) }); ScalaJS.c.scala_util_Failure$.prototype.unapply__Lscala_util_Failure__Lscala_Option = (function(x$0) { if (ScalaJS.anyRefEqEq(x$0, null)) { return ScalaJS.modules.scala_None() } else { return new ScalaJS.c.scala_Some().init___O(x$0.exception__Ljava_lang_Throwable()) } }); ScalaJS.c.scala_util_Failure$.prototype.readResolve__p1__O = (function() { return ScalaJS.modules.scala_util_Failure() }); ScalaJS.c.scala_util_Failure$.prototype.unapply__Lscala_util_Failure__ = (function(x$0) { return this.unapply__Lscala_util_Failure__Lscala_Option(x$0) }); ScalaJS.c.scala_util_Failure$.prototype.apply__Ljava_lang_Throwable__ = (function(exception) { return this.apply__Ljava_lang_Throwable__Lscala_util_Failure(exception) }); /** @constructor */ ScalaJS.inheritable.scala_util_Failure$ = (function() { /*<skip>*/ }); ScalaJS.inheritable.scala_util_Failure$.prototype = ScalaJS.c.scala_util_Failure$.prototype; ScalaJS.is.scala_util_Failure$ = (function(obj) { return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_util_Failure$))) }); ScalaJS.as.scala_util_Failure$ = (function(obj) { if ((ScalaJS.is.scala_util_Failure$(obj) || (obj === null))) { return obj } else { ScalaJS.throwClassCastException(obj, "scala.util.Failure") } }); ScalaJS.isArrayOf.scala_util_Failure$ = (function(obj, depth) { return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_util_Failure$))) }); ScalaJS.asArrayOf.scala_util_Failure$ = (function(obj, depth) { if ((ScalaJS.isArrayOf.scala_util_Failure$(obj, depth) || (obj === null))) { return obj } else { ScalaJS.throwArrayCastException(obj, "Lscala.util.Failure;", depth) } }); ScalaJS.data.scala_util_Failure$ = new ScalaJS.ClassTypeData({ scala_util_Failure$: 0 }, false, "scala.util.Failure$", ScalaJS.data.java_lang_Object, { scala_util_Failure$: 1, scala_Serializable: 1, java_io_Serializable: 1, java_lang_Object: 1 }); ScalaJS.c.scala_util_Failure$.prototype.$classData = ScalaJS.data.scala_util_Failure$; ScalaJS.moduleInstances.scala_util_Failure = undefined; ScalaJS.modules.scala_util_Failure = (function() { if ((!ScalaJS.moduleInstances.scala_util_Failure)) { ScalaJS.moduleInstances.scala_util_Failure = new ScalaJS.c.scala_util_Failure$().init___() }; return ScalaJS.moduleInstances.scala_util_Failure }); //@ sourceMappingURL=Failure$.js.map
'use strict'; angular.module('todoApp', ['todoApp.controller', 'ngAnimate']);
'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var _ = require('lodash'); /* jshint ignore:line */ var util = require('util'); /* jshint ignore:line */ var CredentialListList = require('./sip/credentialList').CredentialListList; var DomainList = require('./sip/domain').DomainList; var IpAccessControlListList = require( './sip/ipAccessControlList').IpAccessControlListList; var SipList; /* jshint ignore:start */ /** * Initialize the SipList * * @constructor Twilio.Api.V2010.AccountContext.SipList * * @param {Twilio.Api.V2010} version - Version of the resource * @param {string} accountSid - * A 34 character string that uniquely identifies this resource. */ /* jshint ignore:end */ SipList = function SipList(version, accountSid) { /* jshint ignore:start */ /** * @function sip * @memberof Twilio.Api.V2010.AccountContext# * * @param {string} sid - sid of instance * * @returns {Twilio.Api.V2010.AccountContext.SipContext} */ /* jshint ignore:end */ function SipListInstance(sid) { return SipListInstance.get(sid); } SipListInstance._version = version; // Path Solution SipListInstance._solution = {accountSid: accountSid}; // Components SipListInstance._domains = undefined; SipListInstance._regions = undefined; SipListInstance._ipAccessControlLists = undefined; SipListInstance._credentialLists = undefined; Object.defineProperty(SipListInstance, 'domains', { get: function domains() { if (!this._domains) { this._domains = new DomainList(this._version, this._solution.accountSid); } return this._domains; } }); Object.defineProperty(SipListInstance, 'ipAccessControlLists', { get: function ipAccessControlLists() { if (!this._ipAccessControlLists) { this._ipAccessControlLists = new IpAccessControlListList(this._version, this._solution.accountSid); } return this._ipAccessControlLists; } }); Object.defineProperty(SipListInstance, 'credentialLists', { get: function credentialLists() { if (!this._credentialLists) { this._credentialLists = new CredentialListList(this._version, this._solution.accountSid); } return this._credentialLists; } }); /* jshint ignore:start */ /** * Provide a user-friendly representation * * @function toJSON * @memberof Twilio.Api.V2010.AccountContext.SipList# * * @returns Object */ /* jshint ignore:end */ SipListInstance.toJSON = function toJSON() { return this._solution; }; SipListInstance[util.inspect.custom] = function inspect(depth, options) { return util.inspect(this.toJSON(), options); }; return SipListInstance; }; module.exports = { SipList: SipList };
game.PlayerBaseEntity = me.Entity.extend({ init : function(x, y, settings) { //same like PlayerEntity above for our constructor function this._super(me.Entity, 'init', [x, y, { image: "tower", width: 100, height:100, spritewidth: "100", spriteheight: "100", getShape: function() { return (new me.Rect(0, 0, 100, 70)).toPolygon(); } }]); this.broken = false; //tower has not been destroyed this.health = game.data.playerBaseHealth; //sets its hp to 10 this.alwaysUpdate = true; //always updates even if its not on screen this.body.onCollision = this.onCollision.bind(this); //if you can colide with turret/tower this.type = "PlayerBase"; //type for other collisions so we can check what we're running into when we're hitting otherstuff this.renderable.addAnimation("idle", [0]); //animation number 0 is our idle animation this.renderable.addAnimation("broken", [1]); //animation number 1 is our broken tower animation this.renderable.setCurrentAnimation("idle"); //sets the current/starting animation to our idle animation stated above }, update:function(delta) { //delta represents time from last update if(this.health<=0) { //if health is less than or equal to 0, then our turret is dead this.broken = true; game.data.win = false; this.renderable.setCurrentAnimation("broken"); //if our tower is dead, then animation turns from "idle" to "broken" } this.body.update(delta); //updates(herpderp) this._super(me.Entity, "update", [delta]); //call super in any update function and pass it as a update function then re return true; }, loseHealth: function(damage) { this.health = this.health - damage; }, onCollision: function() { } });
//------------------------------------------------------------- //for myaccount.html // to add address //------------------------------------------------------------- $(document).ready(function(){ $.post("php/address/get_addr.php", { user_id: $.cookie()['user_id'] }, function (dataa, status){ $.getScript("json/address.json",function (data){ data = JSON.parse(data); $("#defaultaddress").empty(); $("#alladdress").empty(); var content1 = ''; var content2 = '<p>暂未设置</p>'; $.each( data, function (index, addrinfo){ if(addrinfo['default_addr'] == "Y"){ content1 += '<div class="radio"><label><input type="radio" name="optionsRadios" id="optionsRadios' + index + '" value="' + addrinfo['addr_id'] + '" checked="checked"><div> 地址: ' + addrinfo['addr'] + '</div><div> 收件人: ' + addrinfo['reciver'] + '</div><div> 联系方式: ' + addrinfo['reci_phone'] + '</div></label></div>'; content2 = '<p><div> 地址: ' + addrinfo['addr'] + '</div><div> 收件人: ' + addrinfo['reciver'] + '</div><div> 联系方式: ' + addrinfo['reci_phone'] + '</div></p>'; } else { content1 += '<div class="radio"><label><input type="radio" name="optionsRadios" id="optionsRadios' + index + '" value="' + addrinfo['addr_id'] + '"><div> 地址: ' + addrinfo['addr'] + '</div><div> 收件人: ' + addrinfo['reciver'] + '</div><div> 联系方式: ' + addrinfo['reci_phone'] + '</div></label></div>'; } }); content1 += '<button type="button" class="btn btn-primary" id="setdefaultaddr">设置为默认地址</button>'; $("#alladdress").append(content1); $("#defaultaddress").append(content2); // when click the "设置默认地址" button $.getScript("js/address/setDefaultAddr.js"); }); }); });
var SceneConstants = require('../constants/scene-constants'); var AppDispatcher = require('../dispatchers/app-dispatcher'); var ActionTypes = SceneConstants.ActionTypes; var HubRecieveActions = { tryListScenes: function() { AppDispatcher.handleViewAction({ type: ActionTypes.LIST_SCENES_ATTEMPT, }); }, recieveSceneList: function(scenes) { AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVE_SCENE_LIST, scenes: scenes }); }, recieveSceneGraphList: function(sceneGraphs) { AppDispatcher.handleServerAction({ type: ActionTypes.RECEIVE_SCENE_GRAPH_LIST, sceneGraphs: sceneGraphs }); }, recieveScene: function(scene) { AppDispatcher.handleServerAction({ type: ActionTypes.RECIEVE_SCENE, scene: scene }); }, recieveSceneGraph: function(sceneGraph) { AppDispatcher.handleServerAction({ type: ActionTypes.RECEIVE_SCENE_GRAPH, sceneGraph: sceneGraph }); }, recieveLoginResult: function(success, errorMessage) { AppDispatcher.handleServerAction({ type: ActionTypes.HUB_LOGIN_RESULT, result: success, errorMessage: errorMessage }); }, errorMessage: function(message) { AppDispatcher.handleViewAction({ type: ActionTypes.STATUS_MESSAGE, message: message, status: 'danger' }); }, }; module.exports = HubRecieveActions;
const mixin = { mounted() { } } export default mixin
/* eslint no-undef: "off", import/no-extraneous-dependencies: "off" */ const assert = require('chai').assert; const nock = require('nock'); const moltin = require('../../dist/moltin.cjs.js'); const apiUrl = 'https://api.moltin.com'; describe('Moltin authentication', () => { // Instantiate a Moltin client before each test beforeEach(() => { Moltin = moltin.gateway({ client_id: 'XXX', }); }); it('should return an access token', () => { // Intercept the API request nock(apiUrl, { reqHeaders: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) .post('/oauth/access_token', { grant_type: 'implicit', client_id: 'XXX', }) .reply(200, { access_token: 'a550d8cbd4a4627013452359ab69694cd446615a', expires: '999999999999999999999', }); return Moltin.Authenticate() .then((response) => { assert.propertyVal(response, 'access_token', 'a550d8cbd4a4627013452359ab69694cd446615a'); }); }); // TODO: endpoint request should fire authenticate function if `access_token` is null // it('should reauthenticate if access_token is null', () => { // // }); it('should throw an error when no client id is set', () => { // Clear the `client_id` Moltin.config.client_id = ''; assert.throws(() => Moltin.Authenticate(), Error, 'You must have a client_id set'); }); });
var express = require('express'); var router = express.Router(); var multer = require('multer'); var upload = multer({ dest: './public/images' }) var mongo = require('mongodb'); var db = require('monk')('localhost/nodeblog'); router.get('/show/:id', function(req, res, next) { var posts = db.get('accounts'); posts.findById(req.params.id,function(err, post){ res.render('show',{ 'accounts': account }); }); }); router.get('/add', function(req, res, next) { var accounts = db.get('accounts'); accounts.find({},{},function(err, categories){ res.render('accountedit',{ 'title': 'Change account', }); }); }); router.post('/add', upload.single('profilepic'), function(req, res, next) { // Get Form Values var title = req.body.title; var body = req.body.body; var date = new Date(); // Check Image Upload if(req.file){ var profilepic = req.file.filename } else { var profilepic = 'profilepic.jpg'; } // Form Validation req.checkBody('body', 'Body field is required').notEmpty(); // Check Errors var errors = req.validationErrors(); if(errors){ res.render('accountedit',{ "errors": errors }); } else { var posts = db.get('accounts'); posts.insert({ "body": body, "date": date, "profilepic": profilepic }, function(err, post){ if(err){ res.send(err); } else { req.flash('success','profile updated'); res.location('/'); res.redirect('/'); } }); } }); module.exports = router;
/* Live.js - One script closer to Designing in the Browser Written for Handcraft.com by Martin Kool (@mrtnkl). Version 4. Recent change: Made stylesheet and mimetype checks case insensitive. http://livejs.com http://livejs.com/license (MIT) @livejs Include live.js#css to monitor css changes only. Include live.js#js to monitor js changes only. Include live.js#html to monitor html changes only. Mix and match to monitor a preferred combination such as live.js#html,css By default, just include live.js to monitor all css, js and html changes. Live.js can also be loaded as a bookmarklet. It is best to only use it for CSS then, as a page reload due to a change in html or css would not re-include the bookmarklet. To monitor CSS and be notified that it has loaded, include it as: live.js#css,notify */ (function () { var headers = { "Etag": 1, "Last-Modified": 1, "Content-Length": 1, "Content-Type": 1 }, resources = {}, pendingRequests = {}, currentLinkElements = {}, oldLinkElements = {}, interval = 10, loaded = false, active = { "html": 1, "css": 1, "js": 1 }; var Live = { // performs a cycle per interval heartbeat: function () { if (document.body) { // make sure all resources are loaded on first activation if (!loaded) Live.loadresources(); Live.checkForChanges(); } setTimeout(Live.heartbeat, interval); }, // loads all local css and js resources upon first activation loadresources: function () { // helper method to assert if a given url is local function isLocal(url) { var loc = document.location, reg = new RegExp("^\\.|^\/(?!\/)|^[\\w]((?!://).)*$|" + loc.protocol + "//" + loc.host); return url.match(reg); } // gather all resources var scripts = document.getElementsByTagName("script"), links = document.getElementsByTagName("link"), uris = []; // track local js urls for (var i = 0; i < scripts.length; i++) { var script = scripts[i], src = script.getAttribute("src"); if (src && isLocal(src)) uris.push(src); if (src && src.match(/\blive.js#/)) { for (var type in active) active[type] = src.match("[#,|]" + type) != null if (src.match("notify")) alert("Live.js is loaded."); } } if (!active.js) uris = []; if (active.html) uris.push(document.location.href); // track local css urls for (var i = 0; i < links.length && active.css; i++) { var link = links[i], rel = link.getAttribute("rel"), href = link.getAttribute("href", 2); if (href && rel && rel.match(new RegExp("stylesheet", "i")) && isLocal(href)) { uris.push(href); currentLinkElements[href] = link; } } // initialize the resources info for (var i = 0; i < uris.length; i++) { var url = uris[i]; Live.getHead(url, function (url, info) { resources[url] = info; }); } // add rule for morphing between old and new css files var head = document.getElementsByTagName("head")[0], style = document.createElement("style"), rule = "transition: all .3s ease-out;" css = [".livejs-loading * { ", rule, " -webkit-", rule, "-moz-", rule, "-o-", rule, "}"].join(''); style.setAttribute("type", "text/css"); head.appendChild(style); style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css)); // yep loaded = true; }, // check all tracking resources for changes checkForChanges: function () { for (var url in resources) { if (pendingRequests[url]) continue; Live.getHead(url, function (url, newInfo) { var oldInfo = resources[url], hasChanged = false; resources[url] = newInfo; for (var header in oldInfo) { // do verification based on the header type var oldValue = oldInfo[header], newValue = newInfo[header], contentType = newInfo["Content-Type"]; switch (header.toLowerCase()) { case "etag": if (!newValue) break; // fall through to default default: hasChanged = oldValue != newValue; break; } // if changed, act if (hasChanged) { Live.refreshResource(url, contentType); break; } } }); } }, // act upon a changed url of certain content type refreshResource: function (url, type) { switch (type.toLowerCase()) { // css files can be reloaded dynamically by replacing the link element case "text/css": var link = currentLinkElements[url], html = document.body.parentNode, head = link.parentNode, next = link.nextSibling, newLink = document.createElement("link"); html.className = html.className.replace(/\s*livejs\-loading/gi, '') + ' livejs-loading'; newLink.setAttribute("type", "text/css"); newLink.setAttribute("rel", "stylesheet"); newLink.setAttribute("href", url + "?now=" + new Date() * 1); next ? head.insertBefore(newLink, next) : head.appendChild(newLink); currentLinkElements[url] = newLink; oldLinkElements[url] = link; // schedule removal of the old link Live.removeoldLinkElements(); break; // check if an html resource is our current url, then reload case "text/html": if (url != document.location.href) return; // local javascript changes cause a reload as well case "text/javascript": case "application/javascript": case "application/x-javascript": document.location.reload(); } }, // removes the old stylesheet rules only once the new one has finished loading removeoldLinkElements: function () { var pending = 0; for (var url in oldLinkElements) { // if this sheet has any cssRules, delete the old link try { var link = currentLinkElements[url], oldLink = oldLinkElements[url], html = document.body.parentNode, sheet = link.sheet || link.styleSheet, rules = sheet.rules || sheet.cssRules; if (rules.length >= 0) { oldLink.parentNode.removeChild(oldLink); delete oldLinkElements[url]; setTimeout(function () { html.className = html.className.replace(/\s*livejs\-loading/gi, ''); }, 100); } } catch (e) { pending++; } if (pending) setTimeout(Live.removeoldLinkElements, 50); } }, // performs a HEAD request and passes the header info to the given callback getHead: function (url, callback) { pendingRequests[url] = true; var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XmlHttp"); xhr.open("HEAD", url, true); xhr.onreadystatechange = function () { delete pendingRequests[url]; if (xhr.readyState == 4 && xhr.status != 304) { xhr.getAllResponseHeaders(); var info = {}; for (var h in headers) { var value = xhr.getResponseHeader(h); // adjust the simple Etag variant to match on its significant part if (h.toLowerCase() == "etag" && value) value = value.replace(/^W\//, ''); if (h.toLowerCase() == "content-type" && value) value = value.replace(/^(.*?);.*?$/i, "$1"); info[h] = value; } callback(url, info); } } xhr.send(); } }; // start listening if (document.location.protocol != "file:") { if (!window.liveJsLoaded) Live.heartbeat(); window.liveJsLoaded = true; } else if (window.console) console.log("Live.js doesn't support the file protocol. It needs http."); })();
version https://git-lfs.github.com/spec/v1 oid sha256:f82fb377ec906859e125a5293b90ee581949ce98f795e7d82c4c817a4e487292 size 3582
export class NavigationStateSchema{ constructor(state, index){ this.state = state; this.index = index; } validate() { return tv4.validateMultiple(this.state, this.schema); } get schema(){ return { "type" : "object", "properties" : { "links" : { "type" : "array", "minItems" : 1, "items" : { "type" : "object", "properties" : { "href" : { "type" : "string" }, "label" : { "type" : "string" }, "labelHTML" : { "type" : "string" }, "labelTemplateUrl" : { "type" : "string" }, "attributes" : { "type" : "object", "properties" : { "target" : { "type" : "string", "enum" : ["_blank"] } } }, "onClick" : { "type" : "array" } }, "oneOf": [{ "required" : ["href"] }, { "required": ["route"] }], } } }, "required" : ["links"] } } }
// dtm.i = dtm.instr = function () { // var instr = new Instr(); // return instr; // }; // // function Instr() { // function instr() { // return this; // } // // var params = { // dur: 0.1 // }; // // var m = dtm.music().for(params.dur).rep() // .amp(dtm.decay().expc(10)); // // // var uni = dtm.model('unipolar'); // // instr.play = function () { // m.play(); // // return instr; // }; // // instr.stop = function () { // m.stop(); // // return instr; // }; // // function mapArgs(argObject) { // if (argsAreSingleVals(argObject)) { // return argsToArray(argObject); // } else if (argObject.length === 0) { // return null; // } else if (argObject.length === 1) { // return argObject[0]; // } // } // // instr.pitch = function () { // var args = mapArgs(arguments); // // if (args) { // m.note(dtm.model('unipolar')(args).range(60,90).block()); // } // return instr; // }; // // instr.speed = function () { // var args = mapArgs(arguments); // // if (args) { // m.interval(dtm.model('unipolar')(args).range(0.5, 0.05).block()); // } // // return instr; // }; // // instr.__proto__ = Instr.prototype; // return instr; // } // // Instr.prototype = Object.create(Function.prototype); // // dtm.instr.create = function () { // // }; dtm.i = dtm.instr = function () { var instr = new Instr(); return instr; }; function Instr() { var params = { dur: 0.1 }; var instr = dtm.music().for(params.dur).rep() .amp(dtm.decay().expc(10)); // var uni = dtm.model('unipolar'); // instr.play = function () { // instr.play(); // // return instr; // }; // // instr.stop = function () { // instr.stop(); // // return instr; // }; function mapArgs(argObject) { if (argsAreSingleVals(argObject)) { return argsToArray(argObject); } else if (argObject.length === 0) { return null; } else if (argObject.length === 1) { return argObject[0]; } } instr.pitch = function () { var args = mapArgs(arguments); if (args) { instr.note(dtm.model('unipolar')(args).range(60,90).block()); } return instr; }; instr.speed = function () { var args = mapArgs(arguments); if (args) { instr.interval(dtm.model('unipolar')(args).range(0.5, 0.05).block()); } return instr; }; // instr.__proto__ = Instr.prototype; return instr; } Instr.prototype = Object.create(Function.prototype); dtm.instr.create = function () { };
import ListFormRoute from 'ember-flexberry/routes/list-form'; import { Query } from 'ember-flexberry-data'; const { SimplePredicate, StringPredicate, DatePredicate } = Query; export default ListFormRoute.extend({ /** Name of model projection to be used as record's properties limitation. @property modelProjection @type String @default 'FlexberryObjectlistviewCustomFilter' */ modelProjection: 'FlexberryObjectlistviewCustomFilter', /** Name of model to be used as list's records types. @property modelName @type String @default 'ember-flexberry-dummy-application-user' */ modelName: 'ember-flexberry-dummy-suggestion', /** developerUserSettings. { <componentName>: { <settingName>: { colsOrder: [ { propName :<colName>, hide: true|false }, ... ], sorting: [{ propName: <colName>, direction: "asc"|"desc" }, ... ], colsWidths: [ <colName>:<colWidth>, ... ], }, ... }, ... } For default userSetting use empty name (''). <componentName> may contain any of properties: colsOrder, sorting, colsWidth or being empty. @property developerUserSettings @type Object @default {} */ developerUserSettings: { FOLVCustomFilterObjectListView: { } }, predicateForFilter(filter) { if (filter.type === 'string' && filter.condition === 'like') { return new StringPredicate(filter.name).contains(filter.pattern); } if (filter.type === 'string' && filter.condition === 'empty') { return new SimplePredicate(filter.name, 'eq', null); } if (filter.type === 'decimal') { return new SimplePredicate(filter.name, filter.condition, filter.pattern ? Number(filter.pattern) : filter.pattern); } if (filter.type === 'date') { return new DatePredicate(filter.name, filter.condition, filter.pattern, true); } return this._super(...arguments); }, predicateForAttribute(attribute, filter) { switch (attribute.type) { case 'boolean': let yes = ['TRUE', 'True', 'true', 'YES', 'Yes', 'yes', 'ДА', 'Да', 'да', '1', '+']; let no = ['False', 'False', 'false', 'NO', 'No', 'no', 'НЕТ', 'Нет', 'нет', '0', '-']; if (yes.indexOf(filter) > 0) { return new SimplePredicate(attribute.name, 'eq', 'true'); } if (no.indexOf(filter) > 0) { return new SimplePredicate(attribute.name, 'eq', 'false'); } return null; default: return this._super(...arguments); } }, /** This method will be invoked always when load operation completed, regardless of load promise's state (was it fulfilled or rejected). @method onModelLoadingAlways. @param {Object} data Data about completed load operation. */ onModelLoadingAlways(data) { let loadCount = this.get('controller.loadCount') + 1; this.set('controller.loadCount', loadCount); }, });
phantom.onError = function(msg) { stderr.writeLiner(msg); phantom.exit(1); }; var ARGS = require("system").args; var page = require("webpage").create(); var stdout = require("system").stdout; var stderr = require("system").stderr; var threadId = parseInt(ARGS[1], 10); stdout.writeLine("Thread-ID: " + threadId); var pageNo = parseInt(ARGS[2], 10); stdout.writeLine("Page-Nr: " + pageNo); var url = "https://breadfish.de/index.php?thread/&id=" + threadId + "&pageNo=" + pageNo; stdout.writeLine("Post-URL: " + url); var filePath = ARGS[3]; stdout.writeLine("File-Path: " + filePath); var userAgent = ARGS[4]; stdout.writeLine("User-Agent: " + userAgent); var threadWidth = ARGS[5]; stdout.writeLine("Width: " + threadWidth); var imageQuality = ARGS[6]; stdout.writeLine("Quality: " + imageQuality + "%"); page.settings.userAgent = userAgent; page.settings.javascriptEnabled = true; page.viewportSize = { width: threadWidth, height: 1 }; page.onResourceError = function(resourceError) { var id = resourceError.id; var url = resourceError.url; var errorCode = resourceError.errorCode; var errorString = resourceError.errorString; stderr.writeLine("Unable to load resource (#" + id + "URL:" + url + ")"); stderr.writeLine("Error code: " + errorCode + ". Description: " + errorString); }; page.onResourceError = function(resourceError) { var id = resourceError.id; var url = resourceError.url; var errorCode = resourceError.errorCode; var errorString = resourceError.errorString; stderr.writeLine("Unable to load resource (#" + id + "URL:" + url + ")"); stderr.writeLine("Error code: " + errorCode + ". Description: " + errorString); }; page.onResourceReceived = function (response) { var id = response.id; var contentType = response.contentType; var url = response.url; var stage = response.stage; stdout.writeLine("Response (#" + id + ", stage " + stage + "): " + contentType + " " + url); }; page.onResourceRequested = function (requestData, networkRequest) { var id = requestData.id; var method = requestData.method; var url = requestData.url; var match = requestData.url.match(/sponsorads\.de|google-analytics\.com|googlesyndication\.com|doubleclick\.net/g); if (match !== null) { networkRequest.abort(); } else { stdout.writeLine("Request (#" + id + "): " + method + " " + url); } }; page.onResourceTimeout = function (request) { var id = request.id; var method = request.method; var url = request.url; var error = {errorCode: request.errorCode, errorString: request.errorString}; stdout.writeLine("Timeout (#" + id + "): " + method + " " + url + " " + JSON.stringify(error)); }; page.onUrlChanged = function (targetUrl) { stdout.writeLine("New URL: " + targetUrl); }; page.open(url, function () { stdout.writeLine("removing unneccessary elements"); page.evaluate(function () { /* global document */ var removeElement = function removeElement(selector) { Array.prototype.forEach.call(document.querySelectorAll(selector), function (element) { element.parentElement.removeChild(element); }); }; // header //removeElement("#pageHeader"); // breadcrumbs //removeElement(".breadcrumbs"); // footer //removeElement("#pageFooter"); // bg image entfernen //document.body.style.background = "none"; // bg transparent machen //document.querySelector("#main").style.margin = "0"; //document.querySelector("#main").className = ""; // aussenabstand anpassen //document.querySelector("header[data-thread-id]").style.marginTop = "10px"; //document.querySelector("#content").style.padding = "0 10px 10px 10px"; // ads removeElement(".wcfAdLocation"); // gast-benachrichtigungen removeElement(".userNotice"); // vorgeschlagene threads removeElement("#content > .container"); // 1px transparente bar top removeElement("#top"); Array.prototype.forEach.call(document.querySelectorAll(".layoutFluid"), function (element) { element.classList.remove("layoutFluid"); }); }); setTimeout(function () { stdout.writeLine("rendering"); page.render(filePath, {format: "png", quality: imageQuality}); phantom.exit(); }, 1); });
const validator = require("../library/validator"); const User = require("../entities/user"); const maxAge = 1000 * 60 * 60 * 24 * 7; // 1 week (in miliseconds) class AuthController { constructor(authService, userService) { this.authService = authService; this.userService = userService; this.login = this.login.bind(this); this.signup = this.signup.bind(this); this.reset = this.reset.bind(this); } async login(ctx) { const data = {}; if (ctx.method === "POST") { const {email, password} = ctx.request.body; const user = await this.userService.findByEmail(email); let passwordMatches = false; if (user && password) { // Only verify password when we have a password and found a user passwordMatches = await this.authService.verifyPassword(password, user.password); } if (!user || !passwordMatches) { data.email = email; data.errors = ["Incorrect username or password."]; } else { // Set session token ctx.cookies.set("session_user_id", user.id, {signed: true, maxAge}); // Redirect ctx.redirect("/"); } } await ctx.render("auth/login", data); } async signup(ctx) { let data = {}; if (ctx.method === "POST") { const {name, email, password} = ctx.request.body; const errors = validator.validate([ ["name", name, "required"], ["email", email, "required", "email", ["min", 6]], ["password", password, "required", ["min", 8]], ]); // Now check for duplicate emails too const duplicateUser = await this.userService.findByEmail(email); if (duplicateUser) { errors.push("This email is already in use."); } if (errors.length > 0) { data = {name, email, errors}; } else { let user = new User({name, email, password}); // Hash password user.password = await this.authService.hashPassword(user.password); // Create user user = await this.userService.create(user); // Set session token ctx.cookies.set("session_user_id", user.id, {signed: true, maxAge}); // Redirect ctx.redirect("/forms/create"); } } await ctx.render("auth/signup", data); } async reset(ctx) { await ctx.render("auth/reset"); } async signout(ctx) { // Delete auth token ctx.cookies.set("session_user_id", null, {overwrite: true}); ctx.redirect("/"); } } AuthController.dependencies = ["services:auth", "services:user"]; module.exports = AuthController;
(this["webpackJsonp@visa/vds-react"]=this["webpackJsonp@visa/vds-react"]||[]).push([[80],{1592:function(s,a,t){s.exports=t.p+"static/media/illustration-hero-guy-eating-with-man-woman-bg.3d0b3b34.svg"}}]); //# sourceMappingURL=80.e9e02408.chunk.js.map
/** The **Component** class is the base class for all xeogl components. ## Usage * [Component IDs](#component-ids) * [Metadata](#metadata) * [Logging](#logging) * [Destruction](#destruction) * [Creating custom Components](#creating-custom-components) ### Component IDs Every Component has an ID that's unique within the parent {{#crossLink "Scene"}}{{/crossLink}}. xeogl generates the IDs automatically by default, however you can also specify them yourself. In the example below, we're creating a scene comprised of {{#crossLink "Scene"}}{{/crossLink}}, {{#crossLink "Material"}}{{/crossLink}}, {{#crossLink "Geometry"}}{{/crossLink}} and {{#crossLink "Mesh"}}{{/crossLink}} components, while letting xeogl generate its own ID for the {{#crossLink "Geometry"}}{{/crossLink}}: ````javascript // The Scene is a Component too var scene = new xeogl.Scene({ id: "myScene" }); var material = new xeogl.PhongMaterial(scene, { id: "myMaterial" }); var geometry = new xeogl.Geometry(scene, { id: "myGeometry" }); // Let xeogl automatically generate the ID for our Mesh var mesh = new xeogl.Mesh(scene, { material: material, geometry: geometry }); ```` We can then find those components like this: ````javascript // Find the Scene var theScene = xeogl.scenes["myScene"]; // Find the Material var theMaterial = theScene.components["myMaterial"]; // Find all PhongMaterials in the Scene var phongMaterials = theScene.types["xeogl.PhongMaterial"]; // Find our Material within the PhongMaterials var theMaterial = phongMaterials["myMaterial"]; ```` ### Component inheritance TODO All xeogl components are (at least indirect) subclasses of the Component base type. For most components, you can get the name of its class via its {{#crossLink "Component/type:property"}}{{/crossLink}} property: ````javascript var type = theMaterial.type; // "xeogl.PhongMaterial" ```` You can also test if a component implements or extends a given component class, like so: ````javascript // Evaluates true: var isComponent = theMaterial.isType("xeogl.Component"); // Evaluates true: var isMaterial = theMaterial.isType("xeogl.Material"); // Evaluates true: var isPhongMaterial = theMaterial.isType("xeogl.PhongMaterial"); // Evaluates false: var isMetallicMaterial = theMaterial.isType("xeogl.MetallicMaterial"); ```` ### Metadata You can set optional **metadata** on your Components, which can be anything you like. These are intended to help manage your components within your application code or content pipeline. You could use metadata to attach authoring or version information, like this: ````javascript // Scene with authoring metadata var scene = new xeogl.Scene({ id: "myScene", meta: { title: "My bodacious 3D scene", author: "@xeographics", date: "February 30 2018" } }); // Material with descriptive metadata var material = new xeogl.PhongMaterial(scene, { id: "myMaterial", diffuse: [1, 0, 0], meta: { description: "Bright red color with no textures", version: "0.1", foo: "bar" } }); ```` ### Logging Components have methods to log ID-prefixed messages to the JavaScript console: ````javascript material.log("Everything is fine, situation normal."); material.warn("Wait, whats that red light?"); material.error("Aw, snap!"); ```` The logged messages will look like this in the console: ````text [LOG] myMaterial: Everything is fine, situation normal. [WARN] myMaterial: Wait, whats that red light.. [ERROR] myMaterial: Aw, snap! ```` ### Destruction Get notification of destruction directly on the Components: ````javascript material.on("destroyed", function() { this.log("Component was destroyed: " + this.id); }); ```` Or get notification of destruction of any Component within its {{#crossLink "Scene"}}{{/crossLink}}, indiscriminately: ````javascript scene.on("componentDestroyed", function(component) { this.log("Component was destroyed: " + component.id); }); ```` Then destroy a component like this: ````javascript material.destroy(); ```` ### Creating custom Components Subclassing a Component to create a new ````xeogl.ColoredTorus```` type: ````javascript class ColoredTorus extends xeogl.Component{ get type() { return "ColoredTorus"; } constructor(scene=null, cfg) { // Constructor super(scene. cfg); this._torus = new xeogl.Mesh({ geometry: new xeogl.TorusGeometry({radius: 2, tube: .6}), material: new xeogl.MetallicMaterial({ baseColor: [1.0, 0.5, 0.5], roughness: 0.4, metallic: 0.1 }) }); this.color = cfg.color; }, set color(color) { this._torus.material.baseColor = color; } get color() { return this._torus.material.baseColor; } destroy() { super.destroy(); this._torus.geometry.destroy(); this._torus.material.destroy(); this._torus.destroy(); } }; ```` #### Examples * [Custom component definition](../../examples/#extending_component_basic) * [Custom component that fires events](../../examples/#extending_component_changeEvents) * [Custom component that manages child components](../../examples/#extending_component_childCleanup) * [Custom component that schedules asynch tasks](../../examples/#extending_component_update) @class Component @module xeogl @constructor @param [owner] {Component} Owner component. When destroyed, the owner will destroy this component as well. Creates this component within the default {{#crossLink "Scene"}}{{/crossLink}} when omitted. @param [cfg] {*} DepthBuf configuration @param [cfg.id] {String} Optional ID, unique among all components in the parent {{#crossLink "Scene"}}Scene{{/crossLink}}, generated automatically when omitted. @param [cfg.meta] {String:Object} Optional map of user-defined metadata to attach to this Component. */ import {core} from "./core.js"; import {utils} from './utils.js'; import {tasks} from './tasks.js'; import {Map} from "./utils/map.js"; import {componentClasses} from "./componentClasses.js"; const type = "xeogl.Component"; class Component { /** JavaScript class name for this Component. For example: "xeogl.AmbientLight", "xeogl.MetallicMaterial" etc. @property type @type String @final */ get type() { return type; } constructor() { var cfg = {}; var arg1 = arguments[0]; var arg2 = arguments[1]; var owner = null; /** The parent {{#crossLink "Scene"}}{{/crossLink}} that contains this Component. @property scene @type {Scene} @final */ this.scene = null; if (this.type === "xeogl.Scene") { this.scene = this; if (arg1) { cfg = arg1; } } else { if (arg1) { if (arg1.type === "xeogl.Scene") { this.scene = arg1; owner = this.scene; if (arg2) { cfg = arg2; } } else if (arg1 instanceof Component) { this.scene = arg1.scene; owner = arg1; if (arg2) { cfg = arg2; } } else { // Create this component within the default xeogl Scene this.scene = core.getDefaultScene(); owner = this.scene; cfg = arg1; } } else { // Create this component within the default xeogl Scene this.scene = core.getDefaultScene(); owner = this.scene; } this._renderer = this.scene._renderer; } this._dontClear = !!cfg.dontClear; // Prevent Scene#clear from destroying this component this._model = null; this._renderer = this.scene._renderer; /** Arbitrary, user-defined metadata on this component. @property metadata @type Object */ this.meta = cfg.meta || {}; /** Unique ID for this Component within its parent {{#crossLink "Scene"}}Scene{{/crossLink}}. @property id @type String @final */ this.id = cfg.id; // Auto-generated by xeogl.Scene by default /** True as soon as this Component has been destroyed @property destroyed @type Boolean */ this.destroyed = false; this._attached = {}; // Attached components with names. this._attachments = null; // Attached components keyed to IDs - lazy-instantiated this._subIdMap = null; // Subscription subId pool this._subIdEvents = null; // Subscription subIds mapped to event names this._eventSubs = null; // Event names mapped to subscribers this._events = null; // Maps names to events this._eventCallDepth = 0; // Helps us catch stack overflows from recursive events this._adoptees = null; // // Components created with #create - lazy-instantiated if (this !== this.scene) { // Don't add scene to itself this.scene._addComponent(this); // Assigns this component an automatic ID if not yet assigned } this._updateScheduled = false; // True when #_update will be called on next tick this.init(cfg); if (owner) { owner._adopt(this); } } init() { // No-op } _addedToModel(model) { // Called by xeogl.Model.add() this._model = model; } _removedFromModel(model) { // Called by xeogl.Model.remove() this._model = null; } /** The {{#crossLink "Model"}}{{/crossLink}} which contains this Component, if any. Will be null if this Component is not in a Model. @property model @final @type Model */ get model() { return this._model; } /** Tests if this component is of the given type, or is a subclass of the given type. The type may be given as either a string or a component constructor. This method works by walking up the inheritance type chain, which this component provides in property {{#crossLink "Component/superTypes:property"}}{{/crossLink}}, returning true as soon as one of the type strings in the chain matches the given type, of false if none match. #### Examples: ````javascript var myRotate = new xeogl.Rotate({ ... }); myRotate.isType(xeogl.Component); // Returns true for all xeogl components myRotate.isType("xeogl.Component"); // Returns true for all xeogl components myRotate.isType(xeogl.Rotate); // Returns true myRotate.isType(xeogl.Transform); // Returns true myRotate.isType("xeogl.Transform"); // Returns true myRotate.isType(xeogl.Mesh); // Returns false, because xeogl.Rotate does not (even indirectly) extend xeogl.Mesh ```` @method isType @param {String|Function} type Component type to compare with, eg "xeogl.PhongMaterial", or a xeogl component constructor. @returns {Boolean} True if this component is of given type or is subclass of the given type. */ isType(type) { if (!utils.isString(type)) { type = type.type; if (!type) { return false; } } return core.isComponentType(this.type, type); } /** * Fires an event on this component. * * Notifies existing subscribers to the event, optionally retains the event to give to * any subsequent notifications on the event as they are made. * * @method fire * @param {String} event The event type name * @param {Object} value The event parameters * @param {Boolean} [forget=false] When true, does not retain for subsequent subscribers */ fire(event, value, forget) { if (!this._events) { this._events = {}; } if (!this._eventSubs) { this._eventSubs = {}; } if (forget !== true) { this._events[event] = value || true; // Save notification } const subs = this._eventSubs[event]; let sub; if (subs) { // Notify subscriptions for (const subId in subs) { if (subs.hasOwnProperty(subId)) { sub = subs[subId]; this._eventCallDepth++; if (this._eventCallDepth < 300) { sub.callback.call(sub.scope, value); } else { this.error("fire: potential stack overflow from recursive event '" + event + "' - dropping this event"); } this._eventCallDepth--; } } } } /** * Subscribes to an event on this component. * * The callback is be called with this component as scope. * * @method on * @param {String} event The event * @param {Function} callback Called fired on the event * @param {Object} [scope=this] Scope for the callback * @return {String} Handle to the subscription, which may be used to unsubscribe with {@link #off}. */ on(event, callback, scope) { if (!this._events) { this._events = {}; } if (!this._subIdMap) { this._subIdMap = new Map(); // Subscription subId pool } if (!this._subIdEvents) { this._subIdEvents = {}; } if (!this._eventSubs) { this._eventSubs = {}; } let subs = this._eventSubs[event]; if (!subs) { subs = {}; this._eventSubs[event] = subs; } const subId = this._subIdMap.addItem(); // Create unique subId subs[subId] = { callback: callback, scope: scope || this }; this._subIdEvents[subId] = event; const value = this._events[event]; if (value !== undefined) { // A publication exists, notify callback immediately callback.call(scope || this, value); } return subId; } /** * Cancels an event subscription that was previously made with {{#crossLink "Component/on:method"}}Component#on(){{/crossLink}} or * {{#crossLink "Component/once:method"}}Component#once(){{/crossLink}}. * * @method off * @param {String} subId Publication subId */ off(subId) { if (subId === undefined || subId === null) { return; } if (!this._subIdEvents) { return; } const event = this._subIdEvents[subId]; if (event) { delete this._subIdEvents[subId]; const subs = this._eventSubs[event]; if (subs) { delete subs[subId]; } this._subIdMap.removeItem(subId); // Release subId } } /** * Subscribes to the next occurrence of the given event, then un-subscribes as soon as the event is subIdd. * * This is equivalent to calling {{#crossLink "Component/on:method"}}Component#on(){{/crossLink}}, and then calling * {{#crossLink "Component/off:method"}}Component#off(){{/crossLink}} inside the callback function. * * @method once * @param {String} event Data event to listen to * @param {Function(data)} callback Called when fresh data is available at the event * @param {Object} [scope=this] Scope for the callback */ once(event, callback, scope) { const self = this; const subId = this.on(event, function (value) { self.off(subId); callback(value); }, scope); } /** * Returns true if there are any subscribers to the given event on this component. * * @method hasSubs * @param {String} event The event * @return {Boolean} True if there are any subscribers to the given event on this component. */ hasSubs(event) { return (this._eventSubs && !!this._eventSubs[event]); } /** * Logs a console debugging message for this component. * * The console message will have this format: *````[LOG] [<component type> <component id>: <message>````* * * Also fires the message as a {{#crossLink "Scene/log:event"}}{{/crossLink}} event on the * parent {{#crossLink "Scene"}}Scene{{/crossLink}}. * * @method log * @param {String} message The message to log */ log(message) { message = "[LOG]" + this._message(message); window.console.log(message); this.scene.fire("log", message); } _message(message) { return " [" + this.type + " " + utils.inQuotes(this.id) + "]: " + message; } /** * Logs a warning for this component to the JavaScript console. * * The console message will have this format: *````[WARN] [<component type> =<component id>: <message>````* * * Also fires the message as a {{#crossLink "Scene/warn:event"}}{{/crossLink}} event on the * parent {{#crossLink "Scene"}}Scene{{/crossLink}}. * * @method warn * @param {String} message The message to log */ warn(message) { message = "[WARN]" + this._message(message); window.console.warn(message); this.scene.fire("warn", message); } /** * Logs an error for this component to the JavaScript console. * * The console message will have this format: *````[ERROR] [<component type> =<component id>: <message>````* * * Also fires the message as an {{#crossLink "Scene/error:event"}}{{/crossLink}} event on the * parent {{#crossLink "Scene"}}Scene{{/crossLink}}. * * @method error * @param {String} message The message to log */ error(message) { message = "[ERROR]" + this._message(message); window.console.error(message); this.scene.fire("error", message); } /** * Adds a child component to this. * When component not given, attaches the scene's default instance for the given name (if any). * Publishes the new child component on this component, keyed to the given name. * * @param {*} params * @param {String} params.name component name * @param {Component} [params.component] The component * @param {String} [params.type] Optional expected type of base type of the child; when supplied, will * cause an exception if the given child is not the same type or a subtype of this. * @param {Boolean} [params.sceneDefault=false] * @param {Boolean} [params.sceneSingleton=false] * @param {Function} [params.onAttached] Optional callback called when component attached * @param {Function} [params.onAttached.callback] Callback function * @param {Function} [params.onAttached.scope] Optional scope for callback * @param {Function} [params.onDetached] Optional callback called when component is detached * @param {Function} [params.onDetached.callback] Callback function * @param {Function} [params.onDetached.scope] Optional scope for callback * @param {{String:Function}} [params.on] Callbacks to subscribe to properties on component * @param {Boolean} [params.recompiles=true] When true, fires "dirty" events on this component * @private */ _attach(params) { const name = params.name; if (!name) { this.error("Component 'name' expected"); return; } let component = params.component; const sceneDefault = params.sceneDefault; const sceneSingleton = params.sceneSingleton; const type = params.type; const on = params.on; const recompiles = params.recompiles !== false; // True when child given as config object, where parent manages its instantiation and destruction let managingLifecycle = false; if (component) { if (utils.isNumeric(component) || utils.isString(component)) { // Component ID given // Both numeric and string IDs are supported const id = component; component = this.scene.components[id]; if (!component) { // Quote string IDs in errors this.error("Component not found: " + utils.inQuotes(id)); return; } } else if (utils.isObject(component)) { // Component config given const componentCfg = component; const componentType = componentCfg.type || type || "xeogl.Component"; const componentClass = componentClasses[componentType]; if (!componentClass) { this.error("Component type not found: " + componentType); return; } if (type) { if (!core.isComponentType(componentType, type)) { this.error("Expected a " + type + " type or subtype, not a " + componentType); return; } } component = new componentClass(this.scene, componentCfg); managingLifecycle = true; } } if (!component) { if (sceneSingleton === true) { // Using the first instance of the component type we find const instances = this.scene.types[type]; for (const id2 in instances) { if (instances.hasOwnProperty) { component = instances[id2]; break; } } if (!component) { this.error("Scene has no default component for '" + name + "'"); return null; } } else if (sceneDefault === true) { // Using a default scene component component = this.scene[name]; if (!component) { this.error("Scene has no default component for '" + name + "'"); return null; } } } if (component) { if (component.scene.id !== this.scene.id) { this.error("Not in same scene: " + component.type + " " + utils.inQuotes(component.id)); return; } if (type) { if (!component.isType(type)) { this.error("Expected a " + type + " type or subtype: " + component.type + " " + utils.inQuotes(component.id)); return; } } } if (!this._attachments) { this._attachments = {}; } const oldComponent = this._attached[name]; let subs; let i; let len; if (oldComponent) { if (component && oldComponent.id === component.id) { // Reject attempt to reattach same component return; } const oldAttachment = this._attachments[oldComponent.id]; // Unsubscribe from events on old component subs = oldAttachment.subs; for (i = 0, len = subs.length; i < len; i++) { oldComponent.off(subs[i]); } delete this._attached[name]; delete this._attachments[oldComponent.id]; const onDetached = oldAttachment.params.onDetached; if (onDetached) { if (utils.isFunction(onDetached)) { onDetached(oldComponent); } else { onDetached.scope ? onDetached.callback.call(onDetached.scope, oldComponent) : onDetached.callback(oldComponent); } } if (oldAttachment.managingLifecycle) { // Note that we just unsubscribed from all events fired by the child // component, so destroying it won't fire events back at us now. oldComponent.destroy(); } } if (component) { // Set and publish the new component on this component const attachment = { params: params, component: component, subs: [], managingLifecycle: managingLifecycle }; attachment.subs.push( component.on("destroyed", function () { attachment.params.component = null; this._attach(attachment.params); }, this)); if (recompiles) { attachment.subs.push( component.on("dirty", function () { this.fire("dirty", this); }, this)); } this._attached[name] = component; this._attachments[component.id] = attachment; // Bind destruct listener to new component to remove it // from this component when destroyed const onAttached = params.onAttached; if (onAttached) { if (utils.isFunction(onAttached)) { onAttached(component); } else { onAttached.scope ? onAttached.callback.call(onAttached.scope, component) : onAttached.callback(component); } } if (on) { let event; let subIdr; let callback; let scope; for (event in on) { if (on.hasOwnProperty(event)) { subIdr = on[event]; if (utils.isFunction(subIdr)) { callback = subIdr; scope = null; } else { callback = subIdr.callback; scope = subIdr.scope; } if (!callback) { continue; } attachment.subs.push(component.on(event, callback, scope)); } } } } if (recompiles) { this.fire("dirty", this); // FIXME: May trigger spurous mesh recompilations unless able to limit with param? } this.fire(name, component); // Component can be null return component; } _checkComponent(expectedType, component) { if (utils.isObject(component)) { if (component.type) { if (!core.isComponentType(component.type, expectedType)) { this.error("Expected a " + expectedType + " type or subtype: " + component.type + " " + utils.inQuotes(component.id)); return; } } else { component.type = expectedType; } component = new componentClasses[component.type](this.scene, component); } else { if (utils.isID(component)) { // Expensive test const id = component; component = this.scene.components[id]; if (!component) { this.error("Component not found: " + utils.inQuotes(component.id)); return; } } } if (component.scene.id !== this.scene.id) { this.error("Not in same scene: " + component.type + " " + utils.inQuotes(component.id)); return; } if (!component.isType(expectedType)) { this.error("Expected a " + expectedType + " type or subtype: " + component.type + " " + utils.inQuotes(component.id)); return; } return component; } /** * Convenience method for creating a Component within this Component's {{#crossLink "Scene"}}{{/crossLink}}. * * The method is given a component configuration, like so: * * ````javascript * var material = myComponent.create({ * type: "xeogl.PhongMaterial", * diffuse: [1,0,0], * specular: [1,1,0] * }, "myMaterial"); * ```` * * @method create * @param {*} [cfg] Configuration for the component instance. * @returns {*} */ create(cfg) { let type; let claz; if (utils.isObject(cfg)) { type = cfg.type || "xeogl.Component"; claz = componentClasses[type]; } else if (utils.isString(cfg)) { type = cfg; claz = componentClasses[type]; } else { claz = cfg; type = cfg.prototype.type; // TODO: catch unknown component class } if (!claz) { this.error("Component type not found: " + type); return; } if (!core.isComponentType(type, "xeogl.Component")) { this.error("Expected a xeogl.Component type or subtype"); return; } if (cfg && cfg.id && this.components[cfg.id]) { this.error("Component " + utils.inQuotes(cfg.id) + " already exists in Scene - ignoring ID, will randomly-generate instead"); cfg.id = undefined; //return null; } const component = new claz(this, cfg); if (component) { this._adopt(component); } return component; } _adopt(component) { if (!this._adoptees) { this._adoptees = {}; } if (!this._adoptees[component.id]) { this._adoptees[component.id] = component; } component.on("destroyed", function () { delete this._adoptees[component.id]; }, this); } /** * Protected method, called by sub-classes to queue a call to _update(). * @protected * @param {Number} [priority=1] */ _needUpdate(priority) { if (!this._updateScheduled) { this._updateScheduled = true; if (priority === 0) { this._doUpdate(); } else { tasks.scheduleTask(this._doUpdate, this); } } } /** * @private */ _doUpdate() { if (this._updateScheduled) { this._updateScheduled = false; if (this._update) { this._update(); } } } /** * Protected virtual template method, optionally implemented * by sub-classes to perform a scheduled task. * * @protected */ _update() { } /** * Destroys this component. * * Fires a {{#crossLink "Component/destroyed:event"}}{{/crossLink}} event on this Component. * * Automatically disassociates this component from other components, causing them to fall back on any * defaults that this component overrode on them. * * TODO: describe effect with respect to #create * * @method destroy */ destroy() { if (this.destroyed) { return; } // Unsubscribe from child components and destroy then let id; let attachment; let component; let subs; let i; let len; if (this._attachments) { for (id in this._attachments) { if (this._attachments.hasOwnProperty(id)) { attachment = this._attachments[id]; component = attachment.component; subs = attachment.subs; for (i = 0, len = subs.length; i < len; i++) { component.off(subs[i]); } if (attachment.managingLifecycle) { component.destroy(); } } } } // Release components created with #create if (this._adoptees) { const ids = Object.keys(this._adoptees); for (i = 0, len = ids.length; i < len; i++) { component = this._adoptees[ids[i]]; component.destroy(); } } this.scene._removeComponent(this); // Memory leak avoidance this._attached = {}; this._attachments = null; this._subIdMap = null; this._subIdEvents = null; this._eventSubs = null; this._events = null; this._eventCallDepth = 0; this._adoptees = null; this._updateScheduled = false; /** * Fired when this Component is destroyed. * @event destroyed */ this.fire("destroyed", this.destroyed = true); } } componentClasses[type] = Component; export {Component};
'use strict'; describe('Controller: SettingDetailCtrl', function () { // load the controller's module beforeEach(module('amApp')); var createController, $controller, requestHandler, $httpBackend, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($injector) { $controller = $injector.get('$controller'); $httpBackend = $injector.get('$httpBackend'); scope = $injector.get('$rootScope').$new(); createController = function(){ return $controller('SettingDetailCtrl',{ '$scope': scope }) }; })); it('should attach fields to form', function () { createController(); expect(scope.swaggerFormFields).toBeDefined(); }); it('TO DO should test get', function(){ var mockItem = { swagger : '2.0', info : 'swagger info mock' }; requestHandler = $httpBackend.when('GET', 'http://localhost:1337/projectsetting/1') .respond('200', [ mockItem ]); $httpBackend.expectGET('http://localhost:1337/projectsettings/1'); createController(); /* expect(scope.setting.swagger).toBe('2.0');*/ }); it('should test save function', function(){ var mockItem = { swagger : '2.0', info : 'swagger info mock', put : function(){ } }; createController(); scope.setting = mockItem; scope.save(scope.setting); }); });
"use strict"; function messageFromResponse(response) { return `API Error (${response.status}): ${response.statusText}`; } /** * A base error class for API errors * * @extends {Error} */ export default class ShopifyAPIError extends Error { constructor(response) { super(messageFromResponse(response)); this._status = response.status; this._message = messageFromResponse(response); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { Object.defineProperty(this, "stack", { value: (new Error()).stack }); } } /** * The name of the class of this error * * @return {string} */ get name() { return this.constructor.name; } /** * The status code returned from the response * * @return {number} */ get status() { return this._status; } /** * The message for this error (including status code and text) * * @return {string} */ get message() { return this._message; } }
/** * The MIT License (MIT) * * Copyright (c) 2017 GochoMugo <mugo@forfuture.co.ke> * Copyright (c) 2017 Forfuture LLC <we@forfuture.co.ke> */ // built-in modules const assert = require("assert"); // own modules const mau = require("../../.."); const constants = require("../../../lib/constants"); const errors = require("../../../lib/errors"); const FormSet = require("../../../lib/formset"); describe("mau", function() { describe(".constants", function() { it("is exported", function() { assert.strictEqual(constants, mau.constants); }); }); describe(".errors", function() { it("is exported", function() { assert.strictEqual(errors, mau.errors); }); }); describe(".FormSet", function() { it("is exported", function() { assert.strictEqual(FormSet, mau.FormSet); }); }); });
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // A renderer for the ScrollBar control sap.ui.define(function() { "use strict"; /** * @class Control renderer. * @static * @alias sap.ui.core.tmpl.TemplateControlRenderer */ var TemplateControlRenderer = {}; /** * Renders the Template for the given control, using the provided * {@link sap.ui.core.RenderManager}. * * @param {sap.ui.core.RenderManager} * oRM RenderManager that can be used for writing to the * Render-Output-Buffer * @param {sap.ui.core.tmpl.TemplateControl} * oControl Object representation of the template control * that should be rendered */ TemplateControlRenderer.render = function(oRM, oControl) { // check the control being inlined or renders the control data itself var bSkipRootElement = oControl.isInline() || this.hasControlData; // we need to make sure to have a common root tag (therefore we add a DIV) // if we have no common root tag, the re-rendering would not clean up // the old markup properly. if (!bSkipRootElement) { oRM.write("<div"); oRM.writeControlData(oControl); oRM.writeStyles(); oRM.writeClasses(); oRM.write(">"); } // in case of declaring a control the renderTemplate function is part of the // specific renderer implementation - in case of anonymous template controls // the renderer is defined at the control instance var fnRenderer = this.renderTemplate || oControl.getTemplateRenderer(); if (fnRenderer) { fnRenderer.apply(this, arguments); } if (!bSkipRootElement) { oRM.write("</div>"); } }; return TemplateControlRenderer; }, /* bExport= */ true);
import {map, slice} from "./array"; import {linearish} from "./linear"; import number from "./number"; export default function identity() { var domain = [0, 1]; function scale(x) { return +x; } scale.invert = scale; scale.domain = scale.range = function(_) { return arguments.length ? (domain = map.call(_, number), scale) : domain.slice(); }; scale.copy = function() { return identity().domain(domain); }; return linearish(scale); };
/** * REST API * Author: Joshua M. Waggoner * <rabbitfighter@cryptolab.net> * @rabbitfighter81 */ // Imports var express = require('express'); var bodyParser = require('body-parser'); var statusHandler = require("express-mongoose-status"); // Database Schemas var Posts = require('../models/post'); var Comments = require('../models/comment'); // REST allowed methods Posts.methods(['get', 'put', 'post', 'delete']); Comments.methods(['get', 'put', 'post', 'delete']); // Express var api = express(); api.use(bodyParser.urlencoded({ extended: true })); api.use(bodyParser.json()); /****** * GET ******/ // GET all posts api.get("/api/posts", function(req, res) { Posts.find({}, function(err, data) { statusHandler(err, res, data); }) .then(function(data) { console.log('GET ' + data.length + " posts via /api/posts"); }); }); // GET all comments api.get("/api/comments", function(req, res) { Comments.find({}, function(err, data) { statusHandler(err, res, data); }) .then(function(data) { console.log('GET' + data.length + " comments via /api/comments"); }); }); /******* * POST *******/ // POST increment likes api.post("/api/posts/increment_likes", function(req, res) { var code = req.body.postId, index = req.body.i; Posts.findOne({ code: code }, function(err, doc) { if (err) return console.log(err) doc.likes = doc.likes + 1; doc.save(); res.send({ doc: doc, index: index }); }) .then(function(data) { console.log("POST increment likes to " + data.likes + " via /api/posts/increment_likes"); }); }); // POST comment by code api.post("/api/comments/add", function(req, res) { var code = req.body.code, text = req.body.text || '...', user = req.body.user || 'Anonymous'; Comments.findOne({ code: code }, function(err, doc) { if (err) return console.log(err) doc.comments.push({ text: text, user: user }); doc.save(); res.send(doc); }) .then(function(data) { console.log("POST comment " + data.code + " via /api/comments/add"); }); }); /********* * Delete *********/ // DELETE comment by code api.delete("/api/comments/remove", function(req, res) { var postId = req.body.postId, index = req.body.i; Comments.findOne({ code: postId }, function(err, doc) { if (err) return console.log(err); doc.comments.splice(index, 1); doc.save(); res.send({ postId: postId, index: index }); }) .then(function(data) { console.log("DELETE comment from " + data.code + " via /api/comments/remove"); }); }); module.exports = api;
require("should"); module.exports = function (data) { data.should.not.equal(null); data.should.instanceOf(Object); data.should.have.property('code'); data.code.should.be.String(); data.should.have.property('name'); data.code.should.be.String(); data.should.have.property('divisionId'); data.divisionId.should.be.Object(); data.should.have.property('division'); data.division.should.be.Object(); // data.should.have.property('storeId'); // data.storeId.should.be.Object(); // data.should.have.property('store'); // data.store.should.be.Object(); data.should.have.property('description'); data.description.should.be.String(); };
/** * @license Angular v4.2.5 * (c) 2010-2017 Google, Inc. https://angular.io/ * License: MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common')) : typeof define === 'function' && define.amd ? define(['exports', '@angular/core', '@angular/common'], factory) : (factory((global.ng = global.ng || {}, global.ng.common = global.ng.common || {}, global.ng.common.testing = global.ng.common.testing || {}),global.ng.core,global.ng.common)); }(this, (function (exports,_angular_core,_angular_common) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } /** * @license Angular v4.2.5 * (c) 2010-2017 Google, Inc. https://angular.io/ * License: MIT */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A spy for {@link Location} that allows tests to fire simulated location events. * * @experimental */ var SpyLocation = (function () { function SpyLocation() { this.urlChanges = []; this._history = [new LocationState('', '')]; this._historyIndex = 0; /** @internal */ this._subject = new _angular_core.EventEmitter(); /** @internal */ this._baseHref = ''; /** @internal */ this._platformStrategy = null; } SpyLocation.prototype.setInitialPath = function (url) { this._history[this._historyIndex].path = url; }; SpyLocation.prototype.setBaseHref = function (url) { this._baseHref = url; }; SpyLocation.prototype.path = function () { return this._history[this._historyIndex].path; }; SpyLocation.prototype.isCurrentPathEqualTo = function (path, query) { if (query === void 0) { query = ''; } var givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path; var currPath = this.path().endsWith('/') ? this.path().substring(0, this.path().length - 1) : this.path(); return currPath == givenPath + (query.length > 0 ? ('?' + query) : ''); }; SpyLocation.prototype.simulateUrlPop = function (pathname) { this._subject.emit({ 'url': pathname, 'pop': true }); }; SpyLocation.prototype.simulateHashChange = function (pathname) { // Because we don't prevent the native event, the browser will independently update the path this.setInitialPath(pathname); this.urlChanges.push('hash: ' + pathname); this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'hashchange' }); }; SpyLocation.prototype.prepareExternalUrl = function (url) { if (url.length > 0 && !url.startsWith('/')) { url = '/' + url; } return this._baseHref + url; }; SpyLocation.prototype.go = function (path, query) { if (query === void 0) { query = ''; } path = this.prepareExternalUrl(path); if (this._historyIndex > 0) { this._history.splice(this._historyIndex + 1); } this._history.push(new LocationState(path, query)); this._historyIndex = this._history.length - 1; var locationState = this._history[this._historyIndex - 1]; if (locationState.path == path && locationState.query == query) { return; } var url = path + (query.length > 0 ? ('?' + query) : ''); this.urlChanges.push(url); this._subject.emit({ 'url': url, 'pop': false }); }; SpyLocation.prototype.replaceState = function (path, query) { if (query === void 0) { query = ''; } path = this.prepareExternalUrl(path); var history = this._history[this._historyIndex]; if (history.path == path && history.query == query) { return; } history.path = path; history.query = query; var url = path + (query.length > 0 ? ('?' + query) : ''); this.urlChanges.push('replace: ' + url); }; SpyLocation.prototype.forward = function () { if (this._historyIndex < (this._history.length - 1)) { this._historyIndex++; this._subject.emit({ 'url': this.path(), 'pop': true }); } }; SpyLocation.prototype.back = function () { if (this._historyIndex > 0) { this._historyIndex--; this._subject.emit({ 'url': this.path(), 'pop': true }); } }; SpyLocation.prototype.subscribe = function (onNext, onThrow, onReturn) { return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn }); }; SpyLocation.prototype.normalize = function (url) { return null; }; return SpyLocation; }()); SpyLocation.decorators = [ { type: _angular_core.Injectable }, ]; /** @nocollapse */ SpyLocation.ctorParameters = function () { return []; }; var LocationState = (function () { function LocationState(path, query) { this.path = path; this.query = query; } return LocationState; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A mock implementation of {@link LocationStrategy} that allows tests to fire simulated * location events. * * @stable */ var MockLocationStrategy = (function (_super) { __extends(MockLocationStrategy, _super); function MockLocationStrategy() { var _this = _super.call(this) || this; _this.internalBaseHref = '/'; _this.internalPath = '/'; _this.internalTitle = ''; _this.urlChanges = []; /** @internal */ _this._subject = new _angular_core.EventEmitter(); return _this; } MockLocationStrategy.prototype.simulatePopState = function (url) { this.internalPath = url; this._subject.emit(new _MockPopStateEvent(this.path())); }; MockLocationStrategy.prototype.path = function (includeHash) { if (includeHash === void 0) { includeHash = false; } return this.internalPath; }; MockLocationStrategy.prototype.prepareExternalUrl = function (internal) { if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) { return this.internalBaseHref + internal.substring(1); } return this.internalBaseHref + internal; }; MockLocationStrategy.prototype.pushState = function (ctx, title, path, query) { this.internalTitle = title; var url = path + (query.length > 0 ? ('?' + query) : ''); this.internalPath = url; var externalUrl = this.prepareExternalUrl(url); this.urlChanges.push(externalUrl); }; MockLocationStrategy.prototype.replaceState = function (ctx, title, path, query) { this.internalTitle = title; var url = path + (query.length > 0 ? ('?' + query) : ''); this.internalPath = url; var externalUrl = this.prepareExternalUrl(url); this.urlChanges.push('replace: ' + externalUrl); }; MockLocationStrategy.prototype.onPopState = function (fn) { this._subject.subscribe({ next: fn }); }; MockLocationStrategy.prototype.getBaseHref = function () { return this.internalBaseHref; }; MockLocationStrategy.prototype.back = function () { if (this.urlChanges.length > 0) { this.urlChanges.pop(); var nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : ''; this.simulatePopState(nextUrl); } }; MockLocationStrategy.prototype.forward = function () { throw 'not implemented'; }; return MockLocationStrategy; }(_angular_common.LocationStrategy)); MockLocationStrategy.decorators = [ { type: _angular_core.Injectable }, ]; /** @nocollapse */ MockLocationStrategy.ctorParameters = function () { return []; }; var _MockPopStateEvent = (function () { function _MockPopStateEvent(newUrl) { this.newUrl = newUrl; this.pop = true; this.type = 'popstate'; } return _MockPopStateEvent; }()); exports.SpyLocation = SpyLocation; exports.MockLocationStrategy = MockLocationStrategy; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=common-testing.umd.js.map
import React, {Component} from 'react'; import Form from '../ui/Form'; import Input from '../ui/Input'; import FormLabel from '../ui/FormLabel'; import {reduxForm} from 'redux-form'; class FilterBox extends Component { /* eslint react/prop-types: 0 */ render() { const {fields: {text, showArchived}} = this.props; return ( <Form> <Input placeholder = "Search text" className = "p0 m0" fieldDefinition = {text} /> <FormLabel>Show archived</FormLabel><input className = "" type = "checkbox" {...showArchived} /> </Form> ); } } export default reduxForm({ form: 'noteFilter', fields: ['text', 'showArchived'], })(FilterBox);
$(document).ready(function(){ (function() { var canvas = Martin('martin-home-blur', { autorender: false }), rainbow, t = 0, // time starts at 0 hasMousedOver = false, animatingHelper = false; Martin.registerEffect('rainbow', function(t) { this.context.loop(function(x, y, pixel) { // Increase by a maximum of 100, and take in x value // and time as parameters. pixel.r += 100 * Math.sin((x - 4 * t) / 100); pixel.g += 100 * Math.sin((x - 8 * t) / 100); pixel.b += 100 * Math.sin((x - 12 * t) / 100); return pixel; }); }); (function createRainbow() { if ( rainbow ) rainbow.remove(); rainbow = canvas.layer(0).rainbow(t); t++; if ( t === 100 && !hasMousedOver && !animatingHelper ) { animatingHelper = true; animateHelperTo(280); } if ( animatingHelper && hasMousedOver ) { animatingHelper = false; animateHelperTo(360); } canvas.render(); // requestAnimationFrame will wait until the browser is ready to // repaint the canvas. requestAnimationFrame(createRainbow); })(); var circle = canvas.circle({ x: '50%', y: '50%', radius: 80, color: '#fff' }); circle.blur(60); canvas.mousemove(function(e) { hasMousedOver = true; circle.moveTo(e.x, e.y); }); canvas.newLayer(); var text = canvas.text({ font: 'Futura', text: 'THIS IS MARTIN.JS', align: 'center', x: '50%', y: 20, color: '#fff', size: 66 }); var helperText = canvas.text({ font: 'Futura', align: 'center', x: '50%', y: 360, text: '(Hover over or touch the rabbit)', size: 20, color: '#fff' }); function animateHelperTo(target) { var diff; if ( helperText.data.y !== target ) { diff = target - helperText.data.y; diff = diff > 0 ? 1 : -1; requestAnimationFrame(function() { helperText.data.y += diff; animateHelperTo(target); }); } } })(); (function() { var canvas = Martin('martin-autorender', { autorender: false }), t = 0, circles = [], num = 60, text, offText = 'Automatic rendering is off (smooth).', onText = 'Automatic rendering is on (janky).'; function x(i) { return ( (100 * i) / num) + (50 / num) + '%'; } function y(i, t) { var heightOffset = canvas.height() / 4; i *= 0.25; t *= Math.PI / 40; return 0.5 * canvas.height() + heightOffset * Math.sin(i + t); } function toggleText(t) { return (t === onText) ? offText : onText; } canvas.width(500).height(200); canvas.newLayer(); canvas.background('#ccc'); for ( var i = 0; i < num; i++ ) { circles.push(canvas.circle({ radius: Math.round(canvas.width() / ( 2.5 * num )) })); } text = canvas.text({ color: '#fff', text: offText }); (function moveCircles() { circles.forEach(function(circle, i) { circle.moveTo( x(i), y(i, t) ); }); if ( canvas.options.autorender === false ) canvas.render(); t++; requestAnimationFrame(moveCircles); })(); canvas.click(function() { canvas.options.autorender = !canvas.options.autorender; text.data.text = toggleText(text.data.text); canvas.render(); }); })(); Martin('martin-height-200-crop').height(200); Martin('martin-height-200-resize').height(200, true); Martin('martin-height-400-resize').height(400, true); Martin('martin-width-200-crop').width(200); Martin('martin-width-200-resize').width(200, true); Martin('martin-width-500-resize').width(500, true); (function(){ var back = Martin('martin-background'); back.newLayer(); back.background('#f00'); back.opacity(50); })(); line = Martin('martin-line').line({ x: 40, y: 100, endX: '95%', endY: 30, strokeWidth: 10, color: '#fff', cap: 'round' }); Martin('martin-rect').rect({ x: '60%', y: 20, width: '40%', height: 260, color: '#ff0' }); var poly = Martin('martin-polygon'); poly.polygon({ points: [ ['20%', '10%'], ['40%', '40%'], ['20%', '40%'] ], color: '#fff' // white }); poly.polygon({ points: [ [300, 200], [350, 200], [300, 250], [250, 250] ], color: '#00f', // blue fill strokeWidth: 2, stroke: '#000' // black stroke }); Martin('martin-circle').circle({ x: 320, y: 250, radius: 35, color: '#ef3' }); Martin('martin-ellipse').ellipse({ x: 300, y: 250, radiusX: 100, radiusY: 35, color: '#ef3' }); Martin('martin-text').text({ text: 'Hello, world!', x: 140, y: 220, size: 20, color: '#fe0', font: 'Georgia' }); (function() { var canvas = Martin('martin-bump-up'); var circle1 = canvas.circle({ radius: 100, color: '#f00' }); var circle2 = canvas.circle({ x: 100, radius: 100, color: '#00f' }); // circle 1 is now below circle 2 circle1.bumpUp(); })(); (function() { var canvas = Martin('martin-move-to', { autorender: false }); var circle1 = canvas.circle({ radius: 100, x: '50%', y: '50%', color: '#f00' }); var circle2 = canvas.circle({ radius: 60, x: '50%', y: '50%', color: '#fff' }); var t = 0; (function bounce() { t += Math.PI / 180; circle1.moveTo( 0.5 * canvas.width(), 0.5 * canvas.height() + 30 * Math.sin(t) ); circle2.moveTo( 0.5 * canvas.width(), 0.5 * canvas.height() + 30 * Math.sin(t) ); canvas.render(); requestAnimationFrame(bounce); })(); })(); (function() { var canvas = Martin('martin-update'); canvas.background('#eee'); var text = canvas.text({ text: 'Hello, world!' }); text.update('text', 'I am the new text!'); text.update({ color: '#f00', size: 40 }); })(); Martin('martin-saturate').saturate(100); Martin('martin-desaturate').desaturate(80); Martin('martin-lighten').lighten(25); Martin('martin-darken').darken(25); Martin('martin-opacity').opacity(50); Martin('martin-blur').blur(15); Martin('martin-sharpen').sharpen(150); Martin('martin-invert').invert(); (function() { var canvas = Martin('martin-flash', { autorender: false }); var effect = canvas.lighten(0); var increasing = true; (function flash() { var amount = effect.data; if ( increasing && amount < 100 ) { effect.increase(); } else if ( increasing && amount === 100 ) { increasing = false; effect.decrease() // .lighten() and .darken() are the inverses of each other, // and so actually range between -100 and 100 } else if ( !increasing && amount > -100 ) { effect.decrease(); } else { increasing = true; effect.increase(); } canvas.render(); requestAnimationFrame(flash); })(); })(); (function() { var canvas = Martin('martin-effect-remove'); var effect = canvas.lighten(50); canvas.click(function() { effect.remove(); }); })(); (function() { Martin.registerEffect('myNewEffect', function(data) { this.context.loop(function(x, y, pixel) { pixel.r = 100; pixel.g += 5 + data.a; pixel.b -= Math.round(data.b / 2); return pixel; }); }); // After having registered the new effect, call it on the instance of Martin var canvas = Martin('martin-my-new-effect'); canvas.myNewEffect({ a: 100, b: 100 }); })(); (function() { var canvas = Martin('martin-click'); var blurred = false, effect = canvas.blur(0); // don't actually blur, but add an effect canvas.click(function() { if ( !blurred ) { effect.increase(20); blurred = true; } else { effect.decrease(20); blurred = false; } }); })(); (function() { var canvas = Martin('martin-mouseover'); var circle = canvas.circle({ x: Math.random() * canvas.width(), y: Math.random() * canvas.height(), radius: 50, color: '#00f' }); canvas.on('mouseover mouseout', function() { // move the circle to random coordinates on the canvas circle.moveTo( Math.random() * canvas.width(), Math.random() * canvas.height() ); }); })(); (function() { var canvas = Martin('martin-mousedown'); function randomCircle() { // generate a random color and size var hex = '0123456789abcdef'; var radius = Math.random() * 50, r = hex[Math.floor(Math.random() * hex.length)], g = hex[Math.floor(Math.random() * hex.length)], b = hex[Math.floor(Math.random() * hex.length)]; canvas.circle({ radius: radius, color: '#' + r + g + b, x: Math.random() * canvas.width(), y: Math.random() * canvas.height() }); } // fire once for good measure :-) randomCircle(); canvas.on('mousedown mouseup', randomCircle); })(); (function() { var canvas = Martin('martin-mousemove'); var text = canvas.text({ text: 'Follow that mouse!', x: '50%', y: '50%', color: '#fff', size: 24, align: 'center' }); canvas.mousemove(function(e) { text.moveTo(e.x, e.y); }); })(); (function() { Martin.registerElement('star', function(data) { // let data.size be the radius of the star var size = data.size, centerX = data.x, centerY = data.y; var context = this.context; var angles = [54, 126, 198, 270, 342]; angles = angles.map(Martin.degToRad); angles.forEach(function(angle, i) { var next = angles[i + 1] || angle + Martin.degToRad(72), average = 0.5 * (angle + next); context.lineTo(centerX + Math.cos(angle) * size, centerY + Math.sin(angle) * size); context.lineTo(centerX + Math.cos(average) * size / 2.5, centerY + Math.sin(average) * size / 2.5); }); context.lineTo(centerX + Math.cos(angles[0]) * size, centerY + Math.sin(angles[0]) * size); context.closePath(); }); var canvas = Martin('martin-plugins-star'); var star = canvas.star({ color: '#f00', stroke: '#000', strokeWidth: 10, size: 50, x: '50%', y: '50%' }); canvas.mousemove(function(e) { star.moveTo(e.x, e.y); }); })(); });
version https://git-lfs.github.com/spec/v1 oid sha256:e0f34bac8d54a670402d6584230a8be5a2ec3e7a7f0cea998293f85a36cfeb80 size 2116
/** * @file * Control flow for the Kalabox installer. * * Copyright 2013 Kalamuna LLC */ // Dependencies: var flow = require('nue').flow, as = require('nue').as, parallel = require('nue').parallel, installUtils = require('./install-utils'), exec = require('child_process').exec, url = require('url'), fs = require('fs'), box = require('../box'), logger = require('../../logger'), config = require('../../config'), sudoRunner = require('../utils/task-runner/sudo-runner'); // "Constants": var VBOX_VERSION = config.get('VBOX_VERSION'), VBOX_URL = 'http://files.kalamuna.com/virtualbox-macosx-' + VBOX_VERSION + '.dmg', TEMP_DIR = process.env['TMPDIR'], VAGRANT_VERSION = config.get('VAGRANT_VERSION'), VAGRANT_URL = 'http://files.kalamuna.com/vagrant-macosx-' + VAGRANT_VERSION + '.dmg', VAGRANT_PLUGINS = config.get('VAGRANT_PLUGINS'), KALABOX_DIR = config.get('KALABOX_DIR'), KALABOX64_URL = 'http://files.kalamuna.com/kalabox64.box', KALABOX64_FILENAME = 'kalabox64.box', KALASTACK_DIR = config.get('KALASTACK_DIR'), KALASTACK_BASE_URL = config.get('KALASTACK_BASE_URL'), KALASTACK_VERSION = config.kalastack.get('kalastack_version'), KALASTACK_URL = KALASTACK_BASE_URL + 'kalastack-' + KALASTACK_VERSION + '.tar.gz', KALASTACK_FILENAME = 'kalastack.tar.gz', APP_ROOT = config.root; // "Variables": var socket, progressRunning = 0, progressFinal = 1600, progressWeight; // Installer file info: var vboxUrlParsed = url.parse(VBOX_URL); vboxUrlParsed.packageLocation = '/Volumes/VirtualBox/VirtualBox.pkg'; var vagrantUrlParsed = url.parse(VAGRANT_URL); vagrantUrlParsed.packageLocation = '/Volumes/Vagrant/Vagrant.pkg'; // Helper functions: function downloadAndReport(url, destination, callback) { // Download file via the utils. installUtils.downloadFile(url, destination, function(error, percentDone) { if (percentDone < 100) { // Notify client of progress. installProgress = false; if (url.indexOf('dmg') !== -1) { installProgress = true; } sendProgress(percentDone, installProgress); } else { if (error) { installUtils.checkInternet(function(hasInternet) { if (!hasInternet) { error.message = 'No internet'; io.sockets.emit('noInternet'); } callback(error); }); } else { callback(null); } } }); } function sendMessage(message) { io.sockets.emit('installer', { message: message }); } function sendIcon(icon, kalacolor) { io.sockets.emit('installer', { icon: icon, kalacolor: kalacolor }); } function sendProgress(progress, install) { progressBump = progressWeight / 100; if (install) { realPercent = (progressRunning + ((((progress * progressBump) / progressFinal)) * 100) * .90); } else { realPercent = progressRunning + (((progress * progressBump) / progressFinal)) * 100; } io.sockets.emit('installer', { complete: realPercent }); } function decreaseProgressFinal(progress) { progressFinal = progressFinal - progress; } /** * Get permission to install a specific program * * @param string programName Name of the program in text. */ var installPermission = flow('installPermission')( // Activate the permission request modal. function installPermission0(programName, callback) { this.data.programName = programName; this.data.callback = callback; io.sockets.emit('getPermission', { programName: this.data.programName}); socket.on('permissionResponse', this.async(as(0))); }, // If given permission, proceed. Otherwise, gracefully kill install. function installPermission1(permissionResponse) { if (permissionResponse.value !== true) { this.data.permissionGranted = permissionResponse.value; } else { this.data.permissionGranted = true; } this.next(); }, function installPermissionEnd() { if (this.err) { this.data.callback({ message: this.err.message }); this.err = null; } this.data.callback(this.data.permissionGranted); this.next(); } ); /** * Downloads and installs a DMG file. * * @param object fileUrl * URL object from url.parse(). * @param string destination * Directory to store downloaded DMGs, with trailing /. * @param string packageLocation * Location of the installer package in the mounted DMG. * @param string programName * Name of the software being installed. * @param function callback * Callback to invoke on completion. */ var installDMG = flow('installDMG')( // Ask for permission to download. function installDMG0(fileUrl, destination, packageLocation, programName, validVersion, callback) { this.data.fileUrl = fileUrl; this.data.destination = destination; this.data.fileName = fileUrl.pathname.split('/').pop(); this.data.packageLocation = packageLocation; this.data.programName = programName; this.data.validVersion = validVersion; this.data.callback = callback; if (this.data.validVersion === true) { this.next(true); } else { installPermission(programName, this.async(as(0))); } }, // Begin installation process. function installDMG1(permissionGranted) { if (permissionGranted === true) { logger.info('User granted permission to install ' + this.data.programName); var mkdir = 'mkdir -p ' + this.data.destination; var child = exec(mkdir, this.async()); } else { io.sockets.emit('noPermission'); return; } }, // Start downloads. function installDMG2() { // Download DMG. sendMessage('Downloading Stuff...'); sendIcon('fa fa-download', 'kalagreen'); downloadAndReport(this.data.fileUrl.href, this.data.destination, this.async()); }, // Confirm download succeeded. function installDMG3() { fs.exists(this.data.destination + this.data.fileName, this.async(as(0))); }, // Mount disk image. function installDMG4(exists) { if (!exists) { this.endWith({message: 'Software DMG does not exist!'}); return; } logger.info('Successfully downloaded ' + this.data.programName + ' DMG.'); // Make sure a volume isn't already mounted. var mountPoint = this.data.packageLocation.split('/'); mountPoint.pop(); mountPoint = mountPoint.join('/'); this.data.mountPoint = mountPoint; fs.exists(mountPoint, this.async(as(0))); }, function installDMG5(exists) { // If a volume is already mounted, eject it. if (exists) { exec('hdiutil detach ' + this.data.mountPoint, this.async()); } else { this.next(); } }, function installDMG6() { sendMessage('Configuring Things...'); sendIcon('fa fa-cog', 'kalablue'); exec('hdiutil attach ' + this.data.destination + this.data.fileName, this.async()); }, // Execute installer. function installDMG7(stdout, stderr) { logger.info('Successfully mounted ' + this.data.programName + ' DMG.'); sendMessage('Configuring Things...'); sendIcon('fa fa-cog', 'kalablue'); sudoRunner.runCommand('installer', ['-pkg', this.data.packageLocation, '-target', '/'], this.async()); }, // Unmount DMG after installation. function installDMG8(stdout, stderr) { logger.info(this.data.programName + ' installation complete.'); sendMessage('Configuring Things...'); sendIcon('fa fa-cog', 'kalablue'); // Only unmount if volume hasn't been removed already. fs.exists(this.data.mountPoint, this.async(as(0))); }, function installDMG9(exists) { if (exists) { exec('hdiutil detach ' + this.data.mountPoint, this.async()); } else { this.next(); } }, function installDMGEnd(stdout, stderr) { if (this.err) { this.data.callback({message: this.err.message}); this.err = null; } else { logger.info('Successfully ejected ' + this.data.programName + ' DMG.'); this.data.callback(); } this.next(); } ); /** * Route handler that installs Kalabox. */ var install = flow('installKalabox')( // use -k here because if you've previous entered sudo and are under timeout // it will do weird things and you could enter in a wrong password function installResetPassword() { exec('sudo -k', this.async()); }, // Get asking for the user's password out of the way. function installGetPassword() { sudoRunner.runCommand('echo', ['We needs the passwordz...'], this.async()); }, function installCheckFirewall0() { // Make sure firewall settings won't cause us trouble. installUtils.checkFirewall(this.async(as(0))); }, function installCheckFirewall1(firewallOk) { if (firewallOk === null) { logger.warn('Unable to check firewall status.'); } else if (!firewallOk) { // Stop and alert user if firewall will be problematic. logger.warn('Failed firewall check.'); socket.emit('installer.firewallCheckFailed'); return; } this.next(); }, // Check if VBox and Vagrant are installed. parallel('installGetVersions')( function install0() { installUtils.checkVBox(this.async(as(0))); }, function install1() { installUtils.checkVagrant(this.async(as(0))); }, function install2() { installUtils.checkbaseBox(this.async(as(0))); } ), // Check installed results against required versions. function install2(results) { this.data.vboxInstalled = false; this.data.vagrantInstalled = false; this.data.baseboxExists = false; this.data.vboxValidVersion = true; this.data.vagrantValidVersion = true; var vboxVersion = results[0]; var vagrantVersion = results[1]; var baseboxStatus = results[2]; this.data.baseboxExists = baseboxStatus[0]; // Parse and compare VBox version string. if (vboxVersion !== false && typeof vboxVersion[0] === 'string') { vboxVersion = vboxVersion[0].match(/^(\d+\.\d+\.\d+)r\d*\s*$/); if (vboxVersion !== null) { vboxVersion = vboxVersion[1]; logger.info('Existing VirtualBox installation, version ' + vboxVersion); // Make sure VBox version is greater than or equal to required. if (installUtils.compareVersions(vboxVersion, VBOX_VERSION) >= 0) { this.data.vboxInstalled = true; } else { this.data.vboxValidVersion = false; } } } // Parse and compare Vagrant version string. if (vagrantVersion !== false && typeof vagrantVersion[0] === 'string') { vagrantVersion = vagrantVersion[0].match(/(\d+\.\d+\.\d+)/); if (vagrantVersion !== null) { vagrantVersion = vagrantVersion[1]; logger.info('Existing Vagrant installation, version ' + vagrantVersion); // Make sure Vagrant version equals required. if (installUtils.compareVersions(vagrantVersion, VAGRANT_VERSION) === 0) { this.data.vagrantInstalled = true; } else { this.data.vagrantValidVersion = false; } } } this.next(); }, // Download and install VBox. function install3() { // Set the amount this step should contribute to total install progress progressWeight = 300; if (!this.data.vboxInstalled) { logger.info('VirtualBox not installed or wrong version. Installing.'); installDMG(vboxUrlParsed, TEMP_DIR, vboxUrlParsed.packageLocation, 'VirtualBox', this.data.vboxValidVersion, this.async()); } else { // If this step is already done we shouldnt reflect it in the installer decreaseProgressFinal(progressWeight); this.next(); } }, // Download and install Vagrant. function install4() { // Virtual Box not previously installed if (!this.data.vboxInstalled) { // Update the running progress when the intall is complete progressRunning = progressRunning + ((progressWeight / progressFinal) * 100); sendProgress(progressRunning); } // Set the amount this step should contribute to total install progress progressWeight = 100; // Start Vagrant Install if (!this.data.vagrantInstalled) { logger.info('Vagrant not installed or wrong version. Installing.'); installDMG(vagrantUrlParsed, TEMP_DIR, vagrantUrlParsed.packageLocation, 'Vagrant', this.data.vagrantValidVersion, this.async()); } else { // If this step is already done we shouldnt reflect it in the installer decreaseProgressFinal(progressWeight); this.next(); } }, // @todo Verify that VBox and Vagrant were installed successfully. // Create the .kalabox directory in home. function install5() { // Vagrant not previously installed if (!this.data.vagrantInstalled) { // Update the running progress when the intall is complete progressRunning = progressRunning + ((progressWeight / progressFinal) * 100); sendProgress(progressRunning); } // Create Kalabox dir exec('mkdir -p "' + KALABOX_DIR + '"', this.async()); }, // Download Kalabox image. function install6(stdout, stderr) { // Set the amount this step should contribute to total install progress progressWeight = 1000; if (!this.data.baseboxExists) { sendMessage('Downloading Stuff...'); sendIcon('fa fa-download', 'kalagreen'); downloadAndReport(KALABOX64_URL, KALABOX_DIR, this.async()); } else { logger.info('Kalabox image already downloaded.'); decreaseProgressFinal(progressWeight); this.next(); } }, // Verify Kalabox was downloaded. function install7() { fs.exists(KALABOX_DIR + KALABOX64_FILENAME, this.async(as(0))); }, // Download Kalastack archive from GitHub if download made it. function install8(exists) { if (!exists) { this.endWith({message: 'Failed to download Kalabox image.'}); return; } else if (exists && !this.data.baseboxExists) { // Update total progress after box is DLed but only if box wasnt previously DLed progressRunning = progressRunning + ((progressWeight / progressFinal) * 100); } logger.info('Box image downloaded.'); sendMessage('Downloading Stuff...'); sendIcon('fa fa-download', 'kalagreen'); installUtils.downloadKalastack(KALABOX_DIR, KALASTACK_FILENAME, KALASTACK_URL, KALASTACK_DIR, this.async()); }, // Uninstall Vagrant plugins in case we need to recompile function install9() { if (typeof VAGRANT_PLUGINS.length === 'undefined' || VAGRANT_PLUGINS.length < 1) { this.next(); } else { this.asyncEach(1)(VAGRANT_PLUGINS, function(plugin, group) { logger.info('Installing Vagrant plugin ' + plugin.name); exec('vagrant plugin uninstall ' + plugin.name, {cwd: KALASTACK_DIR}, group.async()); }); } }, // Download Vagrant plugins. function install10() { logger.info('Kalastack downloaded'); sendMessage('Kalaboxing...'); sendIcon('icon-kalabox', 'kalaclear'); // Set the amount this step should contribute to total install progress progressWeight = 200; if (typeof VAGRANT_PLUGINS.length === 'undefined' || VAGRANT_PLUGINS.length < 1) { this.next(); } else { this.asyncEach(1)(VAGRANT_PLUGINS, function(plugin, group) { logger.info('Installing Vagrant plugin ' + plugin.name); exec('vagrant plugin install ' + plugin.name + ' --plugin-version ' + plugin.version, {cwd: KALASTACK_DIR}, group.async()); }); } }, // Restart VirtualBox for good measure. function install11() { sudoRunner.runCommand('/Library/StartupItems/VirtualBox/VirtualBox', ['restart'], this.async()); }, // Check to make sure a kalabox isn't already in Vagrant. function install12() { // Increment final "step" to 10% sendProgress(10); exec('vagrant box list', this.async()); }, // Start box build from Kalabox image if necessary. function install13(stdout, stderr) { var response = stdout.toString(); if (/kalabox\s+\(virtualbox\)/.test(response)) { this.next(); } else { logger.info('Adding base box image to Vagrant.'); exec('vagrant box add kalabox "' + KALABOX_DIR + KALABOX64_FILENAME + '"', {cwd: KALASTACK_DIR}, this.async()); } }, // Move the kalastack config file into place. function install14(stdout, stderr) { var reader = fs.createReadStream(fs.realpathSync(APP_ROOT + '/kalastack.json')); reader.on('end', this.async()); reader.pipe(fs.createWriteStream(KALASTACK_DIR + '/config.json')); }, // Run a sudo command to get authentication. function install15() { logger.info('Wrote configuration file.'); // Increment final "step" to 40% sendProgress(40); sudoRunner.runCommand('echo', ['something something something darkside!'], this.async()); }, // Finish box build with "vagrant up". function install16(output) { // Show this step as 70% complete sendProgress(70); logger.info('Executing box spinup.'); installUtils.spinupBox(this.async()); }, // Reinitialize the box module. function install17(stdout, stderr) { // Bump up the progress of this step to 100% sendProgress(100); box.initialize(this.async()); }, function installEnd() { if (this.err) { var userCanceled = (this.err.message.indexOf('User canceled') !== -1); if (this.err.message != 'No internet' && !userCanceled) { logger.error('Error during installation routine: ' + this.err.message); } if (userCanceled) { io.sockets.emit('noPermission'); } this.err = null; this.next(); } else { logger.info('Installation completed successfully.'); io.sockets.emit('installerComplete'); this.next(); } } ); /** * Initializes the controller, binding to events from client and other modules. */ exports.initialize = function() { // Bind handlers for communication events coming from the client. io.sockets.on('connection', function (newSocket) { socket = newSocket; install(); }); };
'use strict'; var Q = require('q'); var queue = []; /** * @constructor */ function Queue() { Object.defineProperty(this, 'length', { get: getLength }); } /** * @returns {number} */ Queue.prototype.push = function() { return queue.push.apply(queue, arguments); }; /** * @returns {T} */ Queue.prototype.pop = function() { return queue.shift.apply(queue, arguments); }; /** * @returns {Array.<T>} */ Queue.prototype.clear = function() { return queue.splice(0, queue.length); }; /** * @returns {Promise} */ Queue.prototype.process = function() { var promise = this.clear().reduce(Q.when, Q.resolve()); queue.push(function() { return promise.catch(function() {}); }); return promise; }; /** * @private * @returns {number} */ function getLength() { return queue.length; } module.exports = new Queue();
import aggregate from "./base/aggregator"; import toNumber from "./base/type-converter"; function min(accumulator, value, converter) { let converted = converter(value); return isNaN(converted) ? false : Math.min(accumulator, converted); } export default function minOf(array, callback) { callback = callback || (item => item); // Let's assume (in a perfect world) that the data type of the first item // is the same throughout the whole array and use the same converter let firstValue = callback.call(array, array[0]); let converter = toNumber(firstValue); return aggregate(array, (accumulator, item, array) => { let value = callback.call(array, item); return min(accumulator, value, converter); }, Infinity); }
(function() { var FormatPhone, _, exports, parser, root; _ = require('lodash'); parser = require('./phone-number-parser'); FormatPhone = { parsePhoneNumber: function(text, countryCode) { if (text.length < 0 || text === '') { return null; } return parser.parseNumber(text, countryCode); }, cleanPhone: function(text) { return parser.cleanPhone(text); } }; root = typeof self === 'object' && self.self === self && self || typeof global === 'object' && global.global === global && global || this; if (typeof exports !== 'undefined' && !exports.nodeType) { exports.FormatPhone = FormatPhone; } if (typeof module !== 'undefined' && !module.nodeType && module.exports) { exports = module.exports = FormatPhone; } root.FormatPhone = FormatPhone; }).call(this);
import React from 'react'; import { View, StyleSheet, Navigator, TouchableOpacity, TouchableHighlight, Text, ScrollView, Modal, CameraRoll, Animated, ActivityIndicator, InteractionManager, TextInput, Dimensions, BackAndroid, Image, RefreshControl, ListView, ToastAndroid, NativeModules, } from 'react-native'; var FilePickerManager = NativeModules.FilePickerManager; import ScrollableTabView, { DefaultTabBar, } from 'react-native-scrollable-tab-view'; import Token from './Token'; import Icon from 'react-native-vector-icons/Ionicons'; import Gonggaob from './Gonggaob'; import Swipeable from 'react-native-swipeable'; import ImageViewer from 'react-native-image-zoom-viewer'; import RNFS from 'react-native-fs'; import OpenFile from 'react-native-doc-viewer'; import panLook from './panLook'; import panainfosb from './panainfosb'; import CheckBox from 'react-native-check-box'; import RNFetchBlob from 'react-native-fetch-blob' var array = []; var dataImpor = []; let aa=[]; var images = []; var folder_str = []; var file_str = []; var folder_strs = []; var file_strs = []; var flog = false; var flogs = false; export default class Newsb extends React.Component { constructor(props) { super(props); this.state = { dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), id: '', widths: new Animated.Value(0), uid:'', datas:[], imgs:[], loaded: false, isLoadMore:false, p:1, infos:'', isReach:false, isRefreshing:false, isNull:false, sx:false, domain:'', currentlyOpenSwipeable: null, status:false, tp:false, bcimg:'', bottoms: new Animated.Value(-110), IDS:'', type:'', statust:'', names:'', downloadUrl:'', add:false, statusk:false, textaera:'', isfalse:true, checks:false, isChecked:false, imagest:true, ischeck:true, file:'', filesd:false, typefy:'', typename:'', uploading:false, }; } componentDidMount() { //这里获取传递过来的参数: name this.setState({domain:data.data.domain}) array = []; aa=[]; this.timer = setTimeout( () => {this.fetchData('' + data.data.domain + ''+this.props.url+'&uid='+data.data.uid+'&folder_id=0&file_type=0&access_token=' + data.data.token + ''); }, 500 ); } _pressButton() { const { navigator } = this.props; if(navigator) { //很熟悉吧,入栈出栈~ 把当前的页面pop掉,这里就返回到了上一个页面了 navigator.pop(); return true; } return false; } componentWillUnmount() { BackAndroid.removeEventListener('hardwareBackPress', this._pressButton); this.timer && clearTimeout(this.timer); } toQueryString(obj) { return obj ? Object.keys(obj).sort().map(function (key) { var val = obj[key]; if (Array.isArray(val)) { return val.sort().map(function (val2) { return encodeURIComponent(key) + '=' + encodeURIComponent(val2); }).join('&'); } return encodeURIComponent(key) + '=' + encodeURIComponent(val); }).join('&') : ''; } fetchData(url) { var that=this; fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/x-www-form-urlencoded', } }) .then(function (response) { return response.json(); }) .then(function (result) { console.log(result) if(result.data != null){ result.data.forEach((Data,i) => { key={i} array.push(Data); if(Data.icon){ folder_strs.push(Data.id); }else{ file_strs.push(Data.id); } }) } if(result.count <= 10){ that.setState({ isReach:true, isLoadMore:false, }) } if(result.data == null){ that.setState({ dataSource: that.state.dataSource.cloneWithRows(['暂无数据']), loaded: true, sx:false, isLoadMore:false, isNull:true, }) }else if(array.length > Number(result.count)+Number(result.folders_count)){ that.setState({ isReach:true, isLoadMore:false, isNull:false, }) }else{ that.setState({ datas:result.data, dataSource: that.state.dataSource.cloneWithRows(array), loaded: true, sx:false, isNull:false, }) } }) .catch((error) => { that.setState({ isRefreshing:false, loaded: true, sx:true, isNull:false, dataSource: that.state.dataSource.cloneWithRows(['加载失败,请下拉刷新']), }) }); } _add(){ this.setState({add:!this.state.add,}) } _adds(){ this.setState({add:false,}) } _Tj(){ this.setState({add:false,isfalse:false,checks:true,}); Animated.timing( this.state.widths, {toValue: 50}, ).start(); } _quxiao(){ folder_str = []; file_str = []; flog = false; flogs = false; this.setState({isfalse:true,checks:false,isChecked:false,ischeck:true,}); this._Refresh(); Animated.timing( this.state.widths, {toValue: 0}, ).start(); } /* 新增文件夹 start */ new_folder(){ this.setState({statusk:true,add:false,}); } _cancerk(){ this.setState({ statusk:false, }) } trim(str){ return str.replace(/(^\s*)|(\s*$)/g, ""); } /* 消除空格 end */ _yesk(){ if(this.trim(this.state.textaera) == ''){ ToastAndroid.show('名称不能为空', ToastAndroid.LONG) return false; }else{ this.addFech('' + data.data.domain + '/index.php?app=Wangpan&m=MobileApi&a=create_folder&name='+this.state.textaera+'&uid='+data.data.uid+'&folder_id=0&access_token=' + data.data.token + '') this.setState({ statusk:false, }) } } addFech(url){ var that = this; fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/x-www-form-urlencoded', } }) .then(function (response) { return response.json(); }) .then(function (result) { ToastAndroid.show('创建成功', ToastAndroid.LONG) that._Refresh(); }) .catch((error) => { ToastAndroid.show('创建失败', ToastAndroid.LONG) }); } /* 新增文件夹 end */ /* 全选 start */ _allselect(){ folder_str = folder_strs; file_str = file_strs; flog = true; flogs = true; this.setState({isChecked:true,ischeck:false,}) this._Refresh(); console.log(folder_str); console.log(file_str); } /* 全选 end */ /* 全不选 start */ _allnoselect(){ folder_str = []; file_str = []; flog = false; flogs = false; this.setState({isChecked:false,ischeck:true,}) this._Refresh(); } /* 全不选 end */ allDeletes(){ this.setState({isfalse:true,checks:false,isChecked:false,ischeck:true,}); Animated.timing( this.state.widths, {toValue: 0}, ).start(); if(folder_str.length>0 && file_str.length>0){ this.deleteFech('' + data.data.domain + '/index.php?app=Wangpan&m=MobileApi&a=delete&uid='+data.data.uid+'&folder_str='+folder_str.join(',')+'&file_str='+file_str.join(',')+'&access_token=' + data.data.token + ''); }else if(folder_str.length == 0 && file_str.length>0){ this.deleteFech('' + data.data.domain + '/index.php?app=Wangpan&m=MobileApi&a=delete&uid='+data.data.uid+'&file_str='+file_str.join(',')+'&access_token=' + data.data.token + ''); }else if(folder_str.length > 0 && file_str.length == 0){ this.deleteFech('' + data.data.domain + '/index.php?app=Wangpan&m=MobileApi&a=delete&uid='+data.data.uid+'&folder_str='+folder_str.join(',')+'&access_token=' + data.data.token + ''); }else if(folder_str.length == 0 && file_str.length == 0){ return false; } } /* 单个文档删除 start */ deleteFech(url){ var that = this; fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/x-www-form-urlencoded', } }) .then(function (response) { return response.json(); }) .then(function (result) { console.log(result); if(result.status == 'success'){ ToastAndroid.show('删除成功', ToastAndroid.LONG) }else{ ToastAndroid.show('删除失败', ToastAndroid.LONG) } folder_str = []; file_str = []; flog = false; flogs = false; that._Refresh(); }) .catch((error) => { ToastAndroid.show('删除失败', ToastAndroid.LONG) }); } deletes(data){ if(this.state.currentlyOpenSwipeable) { this.state.currentlyOpenSwipeable.recenter(); } this.setState({ status:true, IDS:data.id, type:data.type, }) } _Yes(){ if(this.state.type == 'folder'){ this.deleteFech('' + data.data.domain + '/index.php?app=Wangpan&m=MobileApi&a=delete&uid='+data.data.uid+'&folder_str='+this.state.IDS+'&access_token=' + data.data.token + ''); }else{ this.deleteFech('' + data.data.domain + '/index.php?app=Wangpan&m=MobileApi&a=delete&uid='+data.data.uid+'&file_str='+this.state.IDS+'&access_token=' + data.data.token + ''); } this.setState({ status:false, }) } /* 单个文档删除 end */ /* 单个文档下载 start */ /* 单个文档下载 end */ /* 页面滑动时关闭删除按钮 start */ handleScroll(){ if(this.state.currentlyOpenSwipeable) { this.state.currentlyOpenSwipeable.recenter(); } }; /* 页面滑动时关闭删除按钮 end */ _cancer(){ this.setState({ status:false, }) } _cancers(){ this.setState({ statust:false, }) } openfile(){ const options = { title: 'File Picker', chooseFileButtonTitle: 'Choose File...' }; FilePickerManager.showFilePicker(options, (response) => { console.log('Response = ', response); if (response.didCancel) { console.log('User cancelled photo picker'); } else if (response.error) { console.log('ImagePickerManager Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { this.setState({ file: response.uri, filesd:true, typename:response.path, typefy : response.path.split("/")[response.path.split("/").length-1] }); console.log(response) } }); } _uploads(){ var that = this; this.setState({filesd:false,uploading:true,}); var type = this.state.file.split("/")[this.state.file.split("/").length-1]; var types = new Date().getTime()+'.'+type; let formData = new FormData(); var file = {uri: this.state.file, type: 'multipart/form-data', name:type}; formData.append("file",file); fetch('' + data.data.domain + '/index.php?app=Wangpan&m=MobileApi&a=uploadify&uid='+data.data.uid+'&fid=0&access_token=' + data.data.token + '', { method: 'POST', headers: { 'Content-Type': 'multipart/form-data;', }, body:formData, }) .then(function (response) { return response.json(); }) .then(function (result) { ToastAndroid.show('上传成功', ToastAndroid.LONG) that._Refresh(); that.setState({uploading:false,}); }) .catch((error) => { ToastAndroid.show('上传失败', ToastAndroid.LONG) }); } _nouploads(){ this.setState({ file: '', filesd:false, }); } render() { if(!this.state.loaded){ return ( <View style={{flex:1,backgroundColor:'#fff'}}> <View style={styles.card}> <View style={{flex:1,justifyContent:'center'}}> <TouchableOpacity onPress={this._pressButton.bind(this)}> <View style={{justifyContent:'flex-start',flexDirection:'row',alignItems:'center',}}> <Image source={require('./imgs/back.png')} style={{width: 25, height: 25,marginLeft:5,}} /> <Text style={{color:'white',fontSize:16,marginLeft:-5,}} allowFontScaling={false} adjustsFontSizeToFit={false}>返回</Text> </View> </TouchableOpacity> </View> <View style={{flex:1,alignItems:'center',justifyContent:'center'}}> <View style={{justifyContent:'center',flexDirection:'row',alignItems:'center'}}> <Text style={{color:'white',fontSize:18}} allowFontScaling={false} adjustsFontSizeToFit={false}>{this.props.titles}</Text> </View> </View> <View style={{flex:1,justifyContent:'flex-end',alignItems:'center', flexDirection:'row'}}> </View> </View> <View style={{justifyContent: 'center',alignItems: 'center',height:Dimensions.get('window').height-110,width:Dimensions.get('window').width}}> <View style={styles.loading}> <ActivityIndicator color="white"/> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={styles.loadingTitle}>加载中……</Text> </View> </View> </View> ) } return( <View style={{flex:1}}> {this.state.isfalse ? <View style={styles.card}> <View style={{flex:1,justifyContent:'center'}}> <TouchableOpacity onPress={this._pressButton.bind(this)}> <View style={{justifyContent:'flex-start',flexDirection:'row',alignItems:'center',}}> <Image source={require('./imgs/back.png')} style={{width: 25, height: 25,marginLeft:5,}} /> <Text style={{color:'white',fontSize:16,marginLeft:-5,}} allowFontScaling={false} adjustsFontSizeToFit={false}>返回</Text> </View> </TouchableOpacity> </View> <View style={{flex:1,alignItems:'center',justifyContent:'center'}}> <View style={{justifyContent:'center',flexDirection:'row',alignItems:'center'}}> <Text style={{color:'white',fontSize:18}} allowFontScaling={false} adjustsFontSizeToFit={false}>{this.props.titles}</Text> </View> </View> <View style={{flex:1,justifyContent:'flex-end',alignItems:'center', flexDirection:'row'}}> </View> </View> : <View style={styles.card}> <View style={{flex:1,justifyContent:'center'}}> <TouchableOpacity onPress={this._quxiao.bind(this)}> <View style={{justifyContent:'flex-start',flexDirection:'row',alignItems:'center',paddingLeft:15,}}> <Text style={{color:'white',fontSize:16,marginLeft:-5,}} allowFontScaling={false} adjustsFontSizeToFit={false}>取消</Text> </View> </TouchableOpacity> </View> <View style={{flex:1,alignItems:'center',justifyContent:'center'}}> <View style={{justifyContent:'center',flexDirection:'row',alignItems:'center'}}> <Text style={{color:'white',fontSize:18}} allowFontScaling={false} adjustsFontSizeToFit={false}>{this.props.titles}</Text> </View> </View> <View style={{flex:1,justifyContent:'flex-end',alignItems:'center', flexDirection:'row'}}> {this.state.ischeck ? <View style={{paddingRight:5,}}> <CheckBox style={{width:40, alignItems:'center',justifyContent:'center'}} onClick={this._allselect.bind(this)} isChecked={this.state.isChecked} leftTextStyle={{color:'#fff',width:40,fontSize:16}} leftText={'全选'} checkedImage={<Image source={require('./imgs/enabled.png')} style={{width:0,height:0}}/>} unCheckedImage={<Image source={require('./imgs/disabled.png')} style={{width:0,height:0}}/>} /> </View> : <View style={{paddingRight:5,}}> <CheckBox style={{width:50, alignItems:'center',justifyContent:'center'}} onClick={this._allnoselect.bind(this)} isChecked={this.state.isChecked} leftTextStyle={{color:'#fff',width:50,fontSize:16}} leftText={'全不选'} checkedImage={<Image source={require('./imgs/enabled.png')} style={{width:0,height:0}}/>} unCheckedImage={<Image source={require('./imgs/disabled.png')} style={{width:0,height:0}}/>} /> </View>} </View> </View>} <View style={{backgroundColor:'#fff',flex:1}}> <ListView onScroll={this.handleScroll.bind(this)} dataSource={this.state.dataSource} renderRow={this.renderMovie.bind(this)} showsVerticalScrollIndicator={false} removeClippedSubviews = {false} refreshControl={ <RefreshControl refreshing={this.state.isRefreshing} onRefresh={this._onRefresh.bind(this) } colors={['#ff0000', '#00ff00', '#0000ff','#3ad564']} progressBackgroundColor="#ffffff" /> } /> </View> {!this.state.isfalse ? <TouchableHighlight underlayColor='transparent' activeOpacity ={0.9} onPress={this.allDeletes.bind(this)}><View style={{width:Dimensions.get('window').width,height:50,backgroundColor:'#ddd',borderTopWidth:1,borderColor:'#ddd',alignItems:'center',justifyContent:'center'}}> <Text style={{fontSize:18,color:'#ff0a0a'}} allowFontScaling={false} adjustsFontSizeToFit={false}>删除</Text> </View></TouchableHighlight> : null} <Modal visible={this.state.tp} animationType={"fade"} onRequestClose={() => {console.log("Modal has been closed.")}} transparent={true}> <ImageViewer saveToLocalByLongPress={false} onClick={this.closest.bind(this)} imageUrls={images}/> <TouchableOpacity onPress={this.showActionSheet.bind(this)} style={{position:'absolute',bottom:0,right:30}}> <View ><Icon name="ios-list-outline" color="#fff"size={50} /></View> </TouchableOpacity> {this.state.statu ? <Animated.View style={{ padding:10,width:200,backgroundColor:'rgba(23, 22, 22, 0.7)',justifyContent:'flex-start',alignItems:'center',position:'absolute',top:(Dimensions.get('window').height-150)/2,left:(Dimensions.get('window').width-200)/2,}}> <Icon name="ios-checkmark-outline" color="#fff"size={50} /> <Text style={{fontSize:16,color:'#fff',marginTop:20,}} allowFontScaling={false} adjustsFontSizeToFit={false}>{this.state.infos}</Text> </Animated.View> : null} <Animated.View style={{bottom:this.state.bottoms,left:0,width:Dimensions.get('window').width,backgroundColor:'#fff',justifyContent:'center',alignItems:'center',position:'absolute',}}> <TouchableOpacity onPress={this.sures.bind(this)} style={{width:Dimensions.get('window').width,}}> <View style={{borderColor:'#ccc',borderBottomWidth:1,width:Dimensions.get('window').width,justifyContent:'center',alignItems:'center',}}> <Text style={{fontSize:18,paddingTop:15,paddingBottom:15,}} allowFontScaling={false} adjustsFontSizeToFit={false}>保存到手机</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={this.cancels.bind(this)} style={{width:Dimensions.get('window').width,}}> <View style={{width:Dimensions.get('window').width,justifyContent:'center',alignItems:'center',}}> <Text style={{fontSize:18,paddingTop:15,paddingBottom:15,}} allowFontScaling={false} adjustsFontSizeToFit={false}>取消</Text> </View> </TouchableOpacity> </Animated.View> </Modal> {this.state.status ? <View style={{backgroundColor:'rgba(119, 119, 119, 0.51)',position:'absolute',width:(Dimensions.get('window').width),height:(Dimensions.get('window').height),top:0,left:0}}><View style={{position:'absolute',backgroundColor:'#fff',width:260,height:150,top:(Dimensions.get('window').height-230)/2,left:(Dimensions.get('window').width-260)/2,borderRadius:5,overflow:'hidden'}}> <View style={{height:40,alignItems:'center',justifyContent:'center',flexDirection:'row', }}> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:18,color:'#000'}}>删除此文件?</Text> </View> <View style={{flex:1,justifyContent:'center',alignItems:'center',borderBottomWidth:1,borderColor:'#ececec'}}> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:16,}}>该文件将从网盘里彻底删除</Text> </View> <View style={{flexDirection:'row',justifyContent:'space-between',height:50,backgroundColor:'#ececec',borderBottomLeftRadius:5,borderBottomRightRadius:5}}> <TouchableOpacity onPress={this._cancer.bind(this)} style={{flex:1,alignItems:'center',justifyContent:'center',borderBottomLeftRadius:5,backgroundColor:'#fff'}}> <View ><Text allowFontScaling={false} adjustsFontSizeToFit={false}style={{color:'#4385f4',fontSize:16}}>取消</Text></View> </TouchableOpacity> <TouchableOpacity onPress={this._Yes.bind(this)} style={{flex:1, alignItems:'center',justifyContent:'center', borderBottomRightRadius:5,marginLeft:1,backgroundColor:'#fff'}}> <View><Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{color:'#4385f4',fontSize:16}}>确定</Text></View> </TouchableOpacity> </View> </View></View> : null} {this.state.filesd ? <View style={{backgroundColor:'rgba(119, 119, 119, 0.51)',position:'absolute',width:(Dimensions.get('window').width),height:(Dimensions.get('window').height),top:0,left:0}}><View style={{position:'absolute',backgroundColor:'#fff',width:260,height:150,top:(Dimensions.get('window').height-230)/2,left:(Dimensions.get('window').width-260)/2,borderRadius:5,overflow:'hidden'}}> <View style={{height:40,alignItems:'center',justifyContent:'center',flexDirection:'row', }}> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:18,color:'#000'}}>上传此文件?</Text> </View> <View style={{flex:1,justifyContent:'center',alignItems:'center',borderBottomWidth:1,borderColor:'#ececec'}}> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:16,}}>{this.state.typefy}</Text> </View> <View style={{flexDirection:'row',justifyContent:'space-between',height:50,backgroundColor:'#ececec',borderBottomLeftRadius:5,borderBottomRightRadius:5}}> <TouchableOpacity onPress={this._nouploads.bind(this)} style={{flex:1,alignItems:'center',justifyContent:'center',borderBottomLeftRadius:5,backgroundColor:'#fff'}}> <View ><Text allowFontScaling={false} adjustsFontSizeToFit={false}style={{color:'#4385f4',fontSize:16}}>取消</Text></View> </TouchableOpacity> <TouchableOpacity onPress={this._uploads.bind(this)} style={{flex:1, alignItems:'center',justifyContent:'center', borderBottomRightRadius:5,marginLeft:1,backgroundColor:'#fff'}}> <View><Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{color:'#4385f4',fontSize:16}}>上传</Text></View> </TouchableOpacity> </View> </View></View> : null} {this.state.uploading ? <View style={{justifyContent: 'center',alignItems: 'center',height:Dimensions.get('window').height-90,width:Dimensions.get('window').width,position:'absolute',top:0,left:0}}> <View style={styles.loading}> <ActivityIndicator color="white"/> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={styles.loadingTitle}>文件上传中……</Text> </View> </View> : null} {this.state.add ? <TouchableOpacity onPress={this._adds.bind(this)} style={{width:Dimensions.get('window').width,height:Dimensions.get('window').height-45,position:'absolute',top:45,left:0,}}><View style={{width:Dimensions.get('window').width,height:Dimensions.get('window').height-45,backgroundColor:'rgba(61, 61, 62, 0.3)',position:'absolute',top:0,left:0,}}></View></TouchableOpacity> : <View></View>} {this.state.add ? <View style={{position:'absolute',top:40,right:5,flexDirection:'column',width:120,height:100,}}> <View style={{width:120,height:90,backgroundColor:'#fff',borderRadius:5,flexDirection:'column',alignItems:'center',marginTop:10,}}> <TouchableOpacity onPress={this._Tj.bind(this)}> <View style={{borderBottomWidth:1,borderColor:'#ccc',width:120,alignItems:'center',height:45,flexDirection:'row',paddingLeft:10,}}> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{marginLeft:10,fontSize:16,}}>多选</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={this.new_folder.bind(this)}> <View style={{width:120,alignItems:'center',height:45,flexDirection:'row',paddingLeft:10,}}> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{marginLeft:10,fontSize:16,}}>新建文件夹</Text> </View> </TouchableOpacity> </View> <View style={{position:'absolute',top:-8,right:13}}><Icon name="md-arrow-dropup" color="#fff"size={30} /></View> </View> : <View></View>} {this.state.statusk ? <View style={{backgroundColor:'rgba(119, 119, 119, 0.51)',position:'absolute',width:(Dimensions.get('window').width),height:(Dimensions.get('window').height),top:0,left:0}}><View style={{position:'absolute',backgroundColor:'#fff',width:260,height:150,top:(Dimensions.get('window').height-230)/2,left:(Dimensions.get('window').width-260)/2,borderRadius:5,overflow:'hidden'}}> <View style={{height:40,alignItems:'center',justifyContent:'center',flexDirection:'row', }}> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:18,color:'#000'}}>文件夹名称</Text> </View> <View style={{flex:1,justifyContent:'center',alignItems:'center',borderBottomWidth:1,borderColor:'#ececec',}}> <TextInput onChangeText={(textaera) => this.setState({textaera})} numberOfLines={1} multiline = {true} placeholderTextColor={'#999'} style={{ color:'#666',fontSize:14,width:230,borderWidth:1,borderColor:'#ccc',height:35,textAlignVertical:'center',padding: 0,paddingLeft:5,borderRadius:3}} placeholder='文件夹名称' underlineColorAndroid={'transparent'} /> </View> <View style={{flexDirection:'row',justifyContent:'space-between',height:50,backgroundColor:'#ececec',borderBottomLeftRadius:5,borderBottomRightRadius:5}}> <TouchableOpacity onPress={this._cancerk.bind(this)} style={{flex:1,alignItems:'center',justifyContent:'center',borderBottomLeftRadius:5,backgroundColor:'#fff'}}> <View ><Text allowFontScaling={false} adjustsFontSizeToFit={false}style={{color:'#4385f4',fontSize:16}}>取消</Text></View> </TouchableOpacity> <TouchableOpacity onPress={this._yesk.bind(this)} style={{flex:1, alignItems:'center',justifyContent:'center', borderBottomRightRadius:5,marginLeft:1,backgroundColor:'#fff'}}> <View><Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{color:'#4385f4',fontSize:16}}>确定</Text></View> </TouchableOpacity> </View> </View></View> : null} </View> ) } _ggButton(id){ const { navigator } = this.props; if(navigator) { InteractionManager.runAfterInteractions(() => { this.props.navigator.push({ name: 'Gonggaob', component: Gonggaob, params: { id: id, } }) }) } } imgAll(img){ var ims={url:img}; images=[]; images.push(ims) this.setState({tp:true,bcimg:img}) } sures(){ var that=this; const downloadDest = `${RNFS.ExternalStorageDirectoryPath}/DCIM/Camera/${(new Date().getTime())}.jpg`; var files = 'file://' + downloadDest; RNFS.downloadFile({ fromUrl: this.state.bcimg, toFile: downloadDest}).promise.then(res => { CameraRoll.saveToCameraRoll(files); that.setState({ statu:true, infos:'保存成功' }) Animated.timing( this.state.bottoms, {toValue: -110}, ).start(); that.timerx = setTimeout(() => { that.setState({ statu:false, }) },1000) }).catch(err => { that.setState({ statu:true, infos:'保存失败' }) Animated.timing( this.state.bottoms, {toValue: -110}, ).start(); that.timerx = setTimeout(() => { that.setState({ statu:false, }) },1000) }); } closest(){ if(this.state.bottoms._value == 0){ Animated.timing( this.state.bottoms, {toValue: -110}, ).start(); }else{ this.setState({ tp:false, }) } } cancels(){ Animated.timing( this.state.bottoms, {toValue: -110}, ).start(); } showActionSheet() { var that=this; Animated.timing( this.state.bottoms, {toValue: 0}, ).start(); } looks(data){ if(this.state.currentlyOpenSwipeable) { this.state.currentlyOpenSwipeable.recenter(); this.setState({currentlyOpenSwipeable: null}) }else{ var { navigator } = this.props; if(navigator) { InteractionManager.runAfterInteractions(() => { navigator.push({ name: 'panLook', component: panLook, params: { data: data } }) }) } } } files_k(data){ var that = this; if(this.state.currentlyOpenSwipeable) { this.state.currentlyOpenSwipeable.recenter(); this.setState({currentlyOpenSwipeable: null}) }else{ var { navigator } = this.props; if(navigator) { InteractionManager.runAfterInteractions(() => { navigator.push({ name: 'panainfosb', component: panainfosb, params: { dataID: data, urls:that.props.url } }) }) } } } _check(data){ if(!flog){ file_str.push(data.id); flog = true; }else{ for(var i in file_str){ if(file_str[i] == data.id){ file_str.splice(i,1); if(file_str.length == 0){ flog = false; } }else{ if(i == file_str.length-1){ return file_str.push(data.id); } } } } } _checks(data){ if(!flogs){ folder_str.push(data.id); flogs = true; }else{ for(var i in folder_str){ if(folder_str[i] == data.id){ folder_str.splice(i,1); if(folder_str.length == 0){ flogs = false; } }else{ if(i == folder_str.length-1){ return folder_str.push(data.id); } } } } } onOpen(event,gestureState,swipeable){ const {currentlyOpenSwipeable} = this.state; if (currentlyOpenSwipeable && currentlyOpenSwipeable !== swipeable) { currentlyOpenSwipeable.recenter(); } this.setState({currentlyOpenSwipeable: swipeable}); } onClose(){this.setState({currentlyOpenSwipeable: null})} renderMovie(data,sectionID: number, rowID: number) { if(this.state.sx){ return( <View style={{justifyContent:'center',alignItems:'center',height:Dimensions.get('window').height-170,}}> <Icon name="ios-sad-outline" color="#ccc"size={70} /> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:18,}}>{data}</Text> </View> ) } else if(this.state.isNull){ return ( <View style={{justifyContent:'center',alignItems:'center',height:Dimensions.get('window').height-170,}}> <Icon name="ios-folder-outline" color="#ccc"size={70} /> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:18,}}>{data}</Text> </View> ) } else{ if(data.icon){ return ( <View style={{flexDirection:'row'}}> <Animated.View style={{width:this.state.widths,alignItems:'center',justifyContent:'center',overflow:'hidden'}}> <View style={{flex:1,alignItems:'center',justifyContent:'center',}}> <CheckBox style={{width:50, alignItems:'center',justifyContent:'center'}} onClick={this._checks.bind(this,data)} isChecked={this.state.isChecked} leftText={''} checkedImage={<Image source={require('./imgs/enabled.png')} style={{width:30,height:30}}/>} unCheckedImage={<Image source={require('./imgs/disabled.png')} style={{width:30,height:30}}/>} /> </View> </Animated.View> <View style={{width:(Dimensions.get('window').width)}}> <Swipeable rightActionActivationDistance={75} onRightButtonsOpenRelease={this.onOpen.bind(this)} onRightButtonsCloseRelease={this.onClose.bind(this)} > <TouchableHighlight underlayColor='#ddd' onPress={this.files_k.bind(this,data)}> <View style={{alignItems:'center',flexDirection:'row'}}> <View style={{paddingLeft:10}}> <Image source={require('./imgs/folder.png')} style={{width: 36, height: 36,}} /> </View> <View style={{flex:1,flexDirection:'row',borderBottomWidth:1,borderColor:'#ddd',marginLeft:10,paddingTop:10,paddingBottom:10,paddingRight:10,justifyContent:'space-between',alignItems:'center'}}> <View style={{flexDirection:'column',}}> <Text allowFontScaling={false} adjustsFontSizeToFit={false}> {decodeURI(data.name)} </Text> <Text style={{fontSize:12,color:'#aaa'}} allowFontScaling={false} adjustsFontSizeToFit={false}>{data.inputtime} {data.size}</Text> </View> <View style={{alignItems:'center'}}> <Image source={require('./imgs/right.png')} style={{width: 14, height: 14,}} /> </View> </View> </View> </TouchableHighlight> </Swipeable> </View> </View> ) }else if(data.file_extension == 1){ return ( <View style={{flexDirection:'row'}}> <Animated.View style={{width:this.state.widths,alignItems:'center',justifyContent:'center',overflow:'hidden'}}> <View style={{flex:1,alignItems:'center',justifyContent:'center',}}> <CheckBox style={{width:50, alignItems:'center',justifyContent:'center'}} onClick={this._check.bind(this,data)} isChecked={this.state.isChecked} leftText={''} checkedImage={<Image source={require('./imgs/enabled.png')} style={{width:30,height:30}}/>} unCheckedImage={<Image source={require('./imgs/disabled.png')} style={{width:30,height:30}}/>} /> </View> </Animated.View> <View style={{width:(Dimensions.get('window').width)}}> <Swipeable rightButtonWidth={75} onRightButtonsOpenRelease={this.onOpen.bind(this)} onRightButtonsCloseRelease={this.onClose.bind(this)} > <TouchableHighlight underlayColor='#ddd' onPress={this.imgAll.bind(this,this.state.domain.slice(0,-6)+data.preview_url.slice(1))}> <View style={{alignItems:'center',flexDirection:'row'}}> <View style={{paddingLeft:10}}> <Image source={{uri:this.state.domain.slice(0,-6)+data.imgUrl.slice(1)}} style={{width: 36, height: 36,}} /> </View> <View style={{flex:1,flexDirection:'row',borderBottomWidth:1,borderColor:'#ddd',marginLeft:10,paddingTop:10,paddingBottom:10,paddingRight:10,justifyContent:'space-between',alignItems:'center'}}> <View style={{flexDirection:'column',flex:1}}> <Text allowFontScaling={false} adjustsFontSizeToFit={false}> {decodeURI(data.name)} </Text> <Text style={{fontSize:12,color:'#aaa'}} allowFontScaling={false} adjustsFontSizeToFit={false}>{data.inputtime} {data.size}</Text> </View> <View style={{alignItems:'center'}}> <Image source={require('./imgs/right.png')} style={{width: 14, height: 14,}} /> </View> </View> </View> </TouchableHighlight> </Swipeable> </View> </View> ) }else{ return ( <View style={{flexDirection:'row'}}> <Animated.View style={{width:this.state.widths,alignItems:'center',justifyContent:'center',overflow:'hidden'}}> <View style={{flex:1,alignItems:'center',justifyContent:'center',}}> <CheckBox style={{width:50, alignItems:'center',justifyContent:'center'}} onClick={this._check.bind(this,data)} isChecked={this.state.isChecked} leftText={''} checkedImage={<Image source={require('./imgs/enabled.png')} style={{width:30,height:30}}/>} unCheckedImage={<Image source={require('./imgs/disabled.png')} style={{width:30,height:30}}/>} /> </View> </Animated.View> <View style={{width:(Dimensions.get('window').width)}}> <Swipeable rightActionActivationDistance={75} onRightButtonsOpenRelease={this.onOpen.bind(this)} onRightButtonsCloseRelease={this.onClose.bind(this)} > <TouchableHighlight underlayColor='#ddd' onPress={this.looks.bind(this,data)}> <View style={{alignItems:'center',flexDirection:'row'}}> <View style={{paddingLeft:10}}> <Image source={{uri:this.state.domain.slice(0,-6)+data.file_extension_icon.slice(1)}} style={{width: 36, height: 36,}} /> </View> <View style={{flex:1,flexDirection:'row',borderBottomWidth:1,borderColor:'#ddd',marginLeft:10,paddingTop:10,paddingBottom:10,paddingRight:10,justifyContent:'space-between',alignItems:'center'}}> <View style={{flexDirection:'column',flex:1}}> <Text allowFontScaling={false} adjustsFontSizeToFit={false}> {decodeURI(data.name)} </Text> <Text style={{fontSize:12,color:'#aaa'}} allowFontScaling={false} adjustsFontSizeToFit={false}>{data.inputtime} {data.size}</Text> </View> <View style={{alignItems:'center'}}> <Image source={require('./imgs/right.png')} style={{width: 14, height: 14,}} /> </View> </View> </View> </TouchableHighlight> </Swipeable> </View> </View> ) } } } // 下拉刷新 _onRefresh() { this.setState({ isRefreshing:true, p:1, }) var that=this this.fresh(); } _Refresh() { this.setState({ isRefreshing:false, p:1, }) var that=this this.fresh(); } fresh(){ var that=this; fetch('' + data.data.domain + ''+this.props.url+'&uid='+data.data.uid+'&folder_id=0&file_type=0&access_token=' + data.data.token + '&p='+that.state.p, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', } }) .then(function (response) { return response.json(); }) .then(function (result) { folder_strs = []; file_strs = []; array=[]; array.length = 0; if(result.data != null){ result.data.forEach((Data,i) => { key={i} array.push(Data); if(Data.icon){ folder_strs.push(Data.id); }else{ file_strs.push(Data.id); } }) } if(result.count <= 10){ that.setState({ isReach:true, isLoadMore:false, }) } if(result.data == null){ that.setState({ dataSource: that.state.dataSource.cloneWithRows(['暂无数据']), loaded: true, sx:false, isLoadMore:false, isRefreshing:false, isReach:true, isNull:true, }) }else if(array.length > Number(result.count)+Number(result.folders_count)){ that.setState({ isReach:true, isLoadMore:false, isNull:false, }) }else{ that.setState({ imgs: aa, dataSource: that.state.dataSource.cloneWithRows(array), loaded: true, sx:false, isRefreshing:false, isNull:false, }) } console.log(result) }) .catch((error) => { that.setState({ loaded: true, sx:true, isReach:true, isRefreshing:false, dataSource: that.state.dataSource.cloneWithRows(['加载失败,请下拉刷新']), }) }); } } const styles = StyleSheet.create({ tabView: { flex: 1, flexDirection: 'column', backgroundColor:'#fafafa', }, card: { height:45, backgroundColor:'#4385f4', flexDirection:'row' }, loading: { backgroundColor: 'gray', height: 80, width: 100, borderRadius: 10, justifyContent: 'center', alignItems: 'center', }, loadingTitle: { marginTop: 10, fontSize: 14, color: 'white' }, footer: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', height: 40, }, footerTitle: { marginLeft: 10, fontSize: 15, color: 'gray' }, default: { height: 37, borderWidth: 0, borderColor: 'rgba(0,0,0,0.55)', flex: 1, fontSize: 13, }, });
describe('Forced March', function() { integration(function() { describe('when revealed', function() { beforeEach(function() { const deck = this.buildDeck('targaryen', [ 'Forced March (SoD)', 'A Noble Cause', 'Hedge Knight', 'Hedge Knight', 'Hedge Knight' ]); this.player1.selectDeck(deck); this.player2.selectDeck(deck); this.startGame(); this.keepStartingHands(); [this.char1, this.char2, this.char3] = this.player1.filterCardsByName('Hedge Knight'); [this.opponentChar1, this.opponentChar2, this.opponentChar3] = this.player2.filterCardsByName('Hedge Knight'); this.player1.clickCard(this.char1); this.player1.clickCard(this.char2); this.player1.clickCard(this.char3); this.player2.clickCard(this.opponentChar1); this.player2.clickCard(this.opponentChar2); this.completeSetup(); this.player1.selectPlot('Forced March'); this.player2.selectPlot('A Noble Cause'); this.selectFirstPlayer(this.player1); this.player2.clickCard(this.opponentChar1); }); it('requires each opponent to kneel a military character', function() { expect(this.opponentChar1.kneeled).toBe(true); }); it('prompts to re-initiate', function() { expect(this.player1).toHavePrompt('Select card to kneel'); }); describe('when there are no more valid targets to kneel', function() { beforeEach(function() { // Kneel another to initiate again this.player1.clickCard(this.char1); this.player2.clickCard(this.opponentChar2); }); it('does not prompt to re-initiate', function() { expect(this.player1).toHavePrompt('Marshal your cards'); }); }); }); describe('vs cancels', function() { beforeEach(function() { const deck = this.buildDeck('targaryen', [ 'Forced March (SoD)', 'A Noble Cause', 'Outwit', 'Hedge Knight', 'Hedge Knight', 'Hedge Knight', 'Maester Wendamyr' ]); this.player1.selectDeck(deck); this.player2.selectDeck(deck); this.startGame(); this.keepStartingHands(); [this.char1, this.char2, this.char3] = this.player1.filterCardsByName('Hedge Knight'); [this.opponentChar1, this.opponentChar2, this.opponentChar3] = this.player2.filterCardsByName('Hedge Knight'); this.maester = this.player2.findCardByName('Maester Wendamyr'); this.outwit = this.player2.findCardByName('Outwit'); this.player1.clickCard(this.char1); this.player1.clickCard(this.char2); this.player1.clickCard(this.char3); this.player2.clickCard(this.opponentChar1); this.player2.clickCard(this.opponentChar2); this.player2.clickCard(this.maester); this.completeSetup(); this.player1.selectPlot('Forced March'); this.player2.selectPlot('Outwit'); this.selectFirstPlayer(this.player1); this.player2.clickCard(this.opponentChar1); // Pass Outwit for original initiation this.player2.clickPrompt('Pass'); // Kneel another to initiate again this.player1.clickCard(this.char1); // Choose it this.player2.clickCard(this.opponentChar2); }); it('gives another chance to cancel', function() { expect(this.player2).toAllowAbilityTrigger(this.outwit); }); }); }); });
var express = require('express'); var bodyParser = require("body-parser"); var knexConf = require("../../../knexConf"); var knex = require('knex')(knexConf); var joinjs = require("join-js"); var resultMaps = require("../resultMaps/maps"); var Promise = require('bluebird'); var _ = require("lodash"); app = express(); var router = express.Router(); /*** API rest ***/ /*** Recipes/Last ***/ var lastRecipesRest = router.route('/recipes/last'); lastRecipesRest.get(function(req,res){ knex.select().from("recipe").orderBy("rec_updated", "desc").limit(10) .then(function(rows){ res.json(rows); }); }); /*** Recipes ***/ var recipesRest = router.route('/recipes'); recipesRest.get(function(req,res){ knex.select().from("recipe") .then(function(rows){ res.json(rows); }); }); recipesRest.post(function(req,res){ var recipe = req.body; var ingredients = recipe.ingredients; recipe.con_created = (new Date()).toUTCString(); recipe.con_updated = (new Date()).toUTCString(); knex.transaction(function(trx){ knex.insert({id_recipe:recipe.id_recipe, rec_name : recipe.name, rec_chef : recipe.chef , rec_category : recipe.category, rec_preparation : recipe.preparation, rec_name_url : recipe.name_url, rec_score : 0, rec_created: recipe.con_created, rec_updated : recipe.con_created},"id_recipe") .into("recipe") .transacting(trx) .then(function(id_recipe) { var id_recipe = id_recipe[0]; if(_.size(ingredients)>0 || ingredients != undefined){ return Promise.map(ingredients, function(ing) { return knex.insert({id_ingredient : ing.id_ingredient, ing_name : ing.name, ing_amount : ing.amount, ing_id_recipe : id_recipe}) .into("ingredient").transacting(trx); }); } }) .then(trx.commit).then(trx.rollback); }) .then(function(result){ console.log(result); }) .catch(function(error){ console.error(error); }); res.json({ message: 'post recipes' }); }); /*** Recipes/Category:ID ***/ var recipesCategoryRest = router.route('/recipes/category/:category'); recipesCategoryRest.get(function(req,res){ var category = req.params.category; knex.select().from("recipe") // .join("ingredient", // {"recipe.id_recipe" : "ingredient.ing_id_recipe"}) .where({rec_category : category}) .then(function(rows){ res.json(rows); }); }); /*** Recipes:NAME_URL ***/ var recipesIDRest = router.route('/recipes/:name_url'); recipesIDRest.get(function(req,res){ var name_url = req.params.name_url; console.log(name_url); knex.select().from("recipe as r") .leftJoin("ingredient as i","r.id_recipe","i.ing_id_recipe") .where({"r.rec_name_url" : name_url}) .then(function(rows){ var rows = joinjs.map(rows, resultMaps.recipe); res.json(rows); }); }); recipesIDRest.put(function(req,res){ var id = req.params.id; var body = req.body; knex.transaction(function(trx){ knex("recipe").where({id_recipe : id}) .update(body).transacting(trx) .then(trx.commit).then(trx.rollback); }) .then(function(result){ console.log(result); }) .catch(function(error){ console.error(error); }); }); recipesIDRest.delete(function(req,res){ var id = req.params.id; knex.transaction(function(trx){ knex("recipe").where({id_recipe : id}).del() .transacting(trx) .then(trx.commit).then(trx.rollback); }) .then(function(result){ console.log(result); }) .catch(function(error){ console.error(error); }); }); /*** Recipes:ID Comments ***/ var recipesIDCommentsRest = router.route('/recipes/:id_recipe/comments') recipesIDCommentsRest.get(function(req,res){ var id_recipe = req.params.id_recipe; knex.select().from("comment").where({con_id_recipe : id_recipe}) .then(function(rows){ res.json(rows); }); }); recipesIDCommentsRest.post(function(req,res){ var id_recipe = req.params.id_recipe; var comment = req.body; var point = parseInt(comment.con_points); var score = parseInt(comment.scoreRecipe); console.log(comment); knex.transaction(function(trx){ knex.insert({id_comment : comment.id_comment, con_name: comment.con_name, con_description : comment.con_description, con_id_recipe : id_recipe, con_points : comment.con_points}, "con_id_recipe") .into("comment") .transacting(trx) .then(function(id_recipe) { var id_recipe = id_recipe[0]; return knex("recipe").where({id_recipe: id_recipe}).update("rec_score",score + point).transacting(trx); }) .then(trx.commit).then(trx.rollback); }) .then(function(result){ console.log(result); }) .catch(function(error){ console.error(error); }); res.json({ message: 'post comment' }); }); /*** Categories ***/ var categoriesRest = router.route('/categories') categoriesRest.get(function(req,res){ var id = req.params.id; knex.select().from("category") .then(function(rows){ res.json(rows); }) .catch(()=>{ res.json(["pastas","salads","meat","desserts"]); }); }); module.exports = router;
import {handleActions} from 'redux-actions'; const defaultValue = true; function onExpandedLocationChange(_, action) { return action.payload.query.expanded !== 'false'; } export default handleActions({ '@@router/LOCATION_CHANGE': onExpandedLocationChange }, defaultValue);
class ExDate { now() { return Date.now(); } } class TokenBucket { constructor(date, hearing_time, max_token) { this.date = date; var now = date.now(); this.hearing_time = hearing_time; this.b = max_token; this.token = max_token; this.instanciated_at = now; this.last_updated_at = now; } hearing() { var now = this.date.now(); var delta = now - this.last_updated_at; var v = delta % this.hearing_time; var hearing_token = (this.token + v > this.b) ? this.b: this.token + v; this.token = hearing_token; this.last_updated_at = now; } remove_token(n) { this.hearing(); if (0 <= this.token - n) { this.token -= n; return true; } return false; } } var token_bucket = new TokenBucket(new ExDate(), 16, 100); var h1 = document.createElement("h1") document.body.appendChild(h1); var button = document.createElement("button") button.innerText = "hi"; button.addEventListener("click", function(){ token_bucket.remove_token(10); console.log(token_bucket.token); }); document.body.appendChild(button);
/** * Hydro configuration * * @param {Hydro} hydro */ module.exports = function(hydro) { hydro.set({ suite: 'lift-result', timeout: 500, plugins: [ require('hydro-chai'), require('hydro-bdd') ], chai: { chai: require('chai'), plugins: [ require('chai-spies') ], styles: ['should', 'expect'], global: true, stack: true }, globals: {} }) }
// block specific req number export const BLACK_LIST = ['183787BR', '183788BR', '183789BR', '184340BR', '184341BR', '184343BR', '184344BR', '184345BR', '184346BR', '188212BR', '188213BR', '188214BR', '188215BR', '188216BR', '188313BR', '188314BR', '188312BR', '188315BR', '188212BR', '188213BR', '188214BR', '188215BR', '188216BR', '188420BR']; export const GROUP_MAP = { 'IME DEV': 'IME Dev', 'IME Sustaining': 'IME Sus', 'One FS & Data Services': 'Data Management' }; export const EXPECT_OFFER_TREND = { isilon: [0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, 13, 14, 16, 18, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 37, 38, 39], ecs: [0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 12, 14, 16, 19, 22, 24, 26, 29, 30, 30, 31, 31, 32, 32, 33, 34, 35, 35, 36, 37, 38, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 45, 46, 46], overview: [0, 0, 0, 0, 2, 4, 6, 8, 12, 16, 19, 22, 25, 28, 32, 36, 40, 44, 53, 55, 56, 58, 59, 61, 62, 64, 67, 68, 70, 73, 75, 77, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 45, 46, 46] } export const DATE_RANGE = { isilon: { START: new Date('2017/6/25'), END: new Date('2018/1/28') }, ecs: { START: new Date('2017/6/25'), END: new Date('2018/4/29') }, overview: { START: new Date('2017/6/25'), END: new Date('2018/4/29') } }
;(function(){ var shout; module('shout', { setup: function(){ shout = new Shout(); }, teardown: function(){ shout = null; } }); test('single event on', 1, function(){ var test = false; shout.on('foo', function(){ test = true; }); shout.emit('foo'); equal(test, true, 'Should fire single event.'); shout.off('foo'); }); test('single event w/ args', 4, function(){ var test = false; shout.on('foo', function( arg ) { test = arg; }); shout.emit('foo', true); equal(test, true, 'Should pass argument via emit.'); shout.off('foo'); test = false; shout.on('foo', function( arg1, arg2 ){ test = arg1 + arg2; }); shout.emit('foo', 1, 2); equal(test, 3, 'Should pass multiple arguments via emit'); shout.off('foo'); test = false; shout.on('foo', function( arg1, arg2, arg3 ){ test = arg1 + arg2 + arg3; }); shout.emit('foo', 1, 2, 3); equal(test, 6, 'Should pass multiple arguments via emit'); shout.off('foo'); test = false; shout.on('foo', function( arg1, arg2, arg3, arg4 ){ test = arg1 + arg2 + arg3 + arg4; }); shout.emit('foo', 1, 2, 3, 4); equal(test, 10, 'Should pass multiple arguments via emit'); shout.off('foo'); }); test('single event off', 1, function(){ var test = false; shout.on('foo', function(){ test = true; }); shout.off('foo'); equal(test, false, 'Should not fire single event.'); shout.emit('foo'); }); test('bind/unbind multiple events', 3, function(){ var count = 0; shout.on('foo bar', function(){ count++; }); shout.emit('foo'); shout.emit('bar'); equal(count, 2, 'Should fire multiple events.'); shout.off('bar'); shout.emit('foo'); equal(count, 3, 'Should unbind single event.'); shout.off('foo'); shout.emit('foo'); equal(count, 3, 'Should unbind all events.'); }); test('bind/unbind specific handlers', 2, function(){ var count = 0; function inc() { count++; } function incDeux() { count++; } shout.on('foo', inc); shout.on('foo', incDeux); shout.emit('foo'); equal(count, 2, 'Should fire both handlers.'); shout.off('foo', inc); shout.emit('foo'); equal(count, 3, 'Should fire one handler after `off`.'); shout.off('foo'); }); test('emit multiple events w/ args', 1, function(){ var test = 0; shout.on('foo bar', function( arg ){ test += arg; }); shout.emit('foo bar', 1); equal(test, 2, 'Should emit multiple events w/ arguments'); shout.off('foo bar'); }); test('chainability', 3, function(){ equal(shout.on('foo'), shout, '`on` should return instance.'); equal(shout.off('bar'), shout, '`off` should return instance.'); equal(shout.emit('baz'), shout, '`emit` should return instance.'); shout.off('foo'); }); test('verify no leaks from OOP implementation', 1, function(){ var vent = new Shout(), count = 0; shout.on('foo', function(){ count++; }); vent.on('foo', function(){ count++; }); shout.emit('foo'); equal(count, 1, 'Objects should be atomic.'); }); test('ensure constructor is correct', 1, function(){ equal(shout.constructor, Shout, '`shout` instance constructor should be `Shout`.'); }); test('handlers bound with once() should only fire once', 1, function(){ var count = 0; shout.once('foo', function(){ count++; }); shout.emit('foo').emit('foo'); equal(count, 1, 'handler should only fire once'); }); test('handlers bound with once() for multiple events should only fire once', 1, function(){ var count = 0; shout.once('foo bar', function(){ count++; }); shout.emit('foo').emit('bar'); equal(count, 1, 'handler should only fire once'); }); test('handlers bound with once() for multiple events should fire for any event', 1, function(){ var count = 0; shout.once('foo bar baz', function(){ count++; }); shout.emit('baz'); equal(count, 1, 'handler should only fire once'); }); })();
import { REPLY_RECEIVED } from '_utils/promiseMiddleware'; import { SET_PENDING, CLEAR_ALL_PENDING } from './constants'; export default ( state = { pending: [], }, action, ) => { if (action.stage && action.stage !== REPLY_RECEIVED) return state; switch (action.type) { case SET_PENDING: return { ...state, pending: [...state.pending, action.payload.join('|')], }; case CLEAR_ALL_PENDING: return { ...state, pending: [], }; default: return state; } };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var code_1 = require("./code"); exports.States = code_1.States;
/** * @description * <%= controllerName %>.controller * <%= whatIsThisController %> **/ angular.module('<%= controllerName %>.controller', [ 'humpback.controllers' ]) .controller( '<%= ControllerName %>', function <%= ControllerNameLong %> ( $scope ) { });
'use strict'; var ld = require('lodash'); exports.configureEnv = function () { global.ROOT_DIR = '.'; global.APP_NAME = require('../package.json').name; }; exports.deepCopy = function (obj) { return JSON.parse(JSON.stringify(obj)); }; exports.range = function (n) { return ld.map(new Array(n), function (elm, i) { return i; }); };
const arrayPrototype = Array.prototype; if (arrayPrototype.fill == null) { // polyfill based on: // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill Object.defineProperty(arrayPrototype, 'fill', { value(value, start, end) { if (this == null) { throw new TypeError('this is null or not defined'); } const O = Object(this); const len = O.length >>> 0; const relativeStart = start >> 0; const relativeEnd = end === undefined ? len : end >> 0; const final = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); let k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); while (k < final) { O[k] = value; k++; } return O; } }); }
export default function($resource) { "ngInject"; return $resource('/api/v1/goal/:id/', { id: '@_id' }, {}); };
/*! d3-corrplot - v0.0.1 - 2015-03-01 - Jeremy Kahn */ ;(function (global) { // Compiler directive for UglifyJS. See Corrplot.const.js for more info. if (typeof DEBUG === 'undefined') { DEBUG = true; } // Corrplot-GLOBAL CONSTANTS // // These constants are exposed to all Corrplot modules. // GLOBAL is a reference to the global Object. var Fn = Function, GLOBAL = new Fn('return this')(); // Corrplot-GLOBAL METHODS // // The methods here are exposed to all Corrplot modules. Because all of the // source files are wrapped within a closure at build time, they are not // exposed globally in the distributable binaries. /** * A no-op function. Useful for passing around as a default callback. */ function noop() { } /** * Init wrapper for the core module. * @param {Object} The Object that the Corrplot gets attached to in * Corrplot.init.js. If the Corrplot was not loaded with an AMD loader such as * require.js, this is the global Object. */ function initCorrplotCore(context) { // It is recommended to use strict mode to help make mistakes easier to find. 'use strict'; // PRIVATE MODULE CONSTANTS // // An example of a CONSTANT variable; var CORE_CONSTANT = true; // PRIVATE MODULE METHODS // // These do not get attached to a prototype. They are private utility // functions. /** * An example of a private method. Feel free to remove this. * @param {number} aNumber This is a parameter description. * @returns {number} This is a return value description. */ function corePrivateMethod(aNumber) { return aNumber; } /** * This is the constructor for the Corrplot Object. Please rename it to * whatever your Corrplot's name is. Note that the constructor is also being * attached to the context that the Corrplot was loaded in. * @param {Object} opt_config Contains any properties that should be used to * configure this instance of the Corrplot. * @constructor */ var Corrplot = context.Corrplot = function (opt_config) { opt_config = opt_config || {}; // INSTANCE PROPERTY SETUP // // Your Corrplot likely has some instance-specific properties. The value of // these properties can depend on any number of things, such as properties // passed in via opt_config or global state. Whatever the case, the values // should be set in this constructor. // Instance variables that have a leading underscore mean that they should // not be modified outside of the Corrplot. They can be freely modified // internally, however. If an instance variable will likely be accessed // outside of the Corrplot, consider making a public getter function for it. this._readOnlyVar = 'read only'; // Instance variables that do not have an underscore prepended are // considered to be part of the Corrplot's public API. External code may // change the value of these variables freely. this.readAndWrite = 'read and write'; return this; }; // Corrplot PROTOTYPE METHODS // // These methods define the public API. /** * An example of a protoype method. * @return {string} */ Corrplot.prototype.getReadOnlyVar = function () { return this._readOnlyVar; }; /** * This is an example of a chainable method. That means that the return * value of this function is the Corrplot instance itself (`this`). This lets * you do chained method calls like this: * * var myCorrplot = new Corrplot(); * myCorrplot * .chainableMethod() * .chainableMethod(); * * @return {Corrplot} */ Corrplot.prototype.chainableMethod = function () { return this; }; // DEBUG CODE // // With compiler directives, you can wrap code in a conditional check to // ensure that it does not get included in the compiled binaries. This is // useful for exposing certain properties and methods that are needed during // development and testing, but should be private in the compiled binaries. if (DEBUG) { GLOBAL.corePrivateMethod = corePrivateMethod; } } // Your Corrplot may have many modules. How you organize the modules is up to // you, but generally speaking it's best if each module addresses a specific // concern. No module should need to know about the implementation details of // any other module. // Note: You must name this function something unique. If you end up // copy/pasting this file, the last function defined will clobber the previous // one. function initCorrplotChart(context) { 'use strict'; var Corrplot = context.Corrplot; // A Corrplot module can do two things to the Corrplot Object: It can extend // the prototype to add more methods, and it can add static properties. This // is useful if your Corrplot needs helper methods. // PRIVATE MODULE CONSTANTS // var MODULE_CONSTANT = true; // PRIVATE MODULE METHODS // /** * An example of a private method. Feel free to remove this. */ function modulePrivateMethod() { return; } // Corrplot STATIC PROPERTIES // /** * An example of a static Corrplot property. This particular static property * is also an instantiable Object. * @constructor */ Corrplot.CorrplotHelper = function () { return this; }; // Corrplot PROTOTYPE EXTENSIONS // // A module can extend the prototype of the Corrplot Object. /** * An example of a prototype method. * @return {string} */ Corrplot.prototype.alternateGetReadOnlyVar = function () { // Note that a module can access all of the Corrplot instance variables with // the `this` keyword. return this._readOnlyVar; }; d3.chart('corrplot', { initialize: function () { var chart = this; //initialize variables with default values this._loadDefaults(chart); var corrplotBase = this.base .attr('height', this.w + this.margin.top + this.margin.bottom) .attr('width', this.w + this.margin.left + this.margin.right) .style('margin-left', -this.margin.left + 'px') .append('g') .classed('corrplot', true) .attr('transform', 'translate (' + this.margin.left + ',' + this.margin.top + ')'); //var corrplotBackground = corrplotBase.append('rect') // .attr('class', 'background') // .attr('width', this.w) // .attr('height', this.w); this.layer('rows', corrplotBase, { dataBind: function (data) { var chart = this.chart(), matrix = data.matrix, order = data.order; //initialize x domain use order if (order === undefined) { order = d3.range(data.nodes.length); } chart.x.domain(order); //initialize coordinates matrix = matrix.map(function (row, i) { return row.map(function (cell, j) { return {x: j, y: i, z: cell}; }); }); // return a data bound selection for the passed in data. return this.selectAll('.row') .data(matrix); }, insert: function () { var chart = this.chart(); // setup the elements that were just created return this.append('g') .classed('row', true); }, // setup an enter event for the data as it comes in: events: { 'merge': function () { var chart = this.chart(); return this .attr('transform', function (d, i) { return 'translate(0,' + chart.x(i) + ')'; }) .each(row); }, 'exit': function () { this.remove(); } } }); function row(row) { var cells = d3.select(this).selectAll('.cell').data(row); //comes the new ones cells .enter().append('path') .attr('class', 'cell') .on('mouseover', chart._mouseover) .on('mouseout', chart._mouseout); //goes the old cells .exit() .remove(); //everyone needs to readjust their sizes cells .attr('transform', function (d) { var halfWidth = chart.x.rangeBand() / 2; return 'translate(' + (chart.x(d.x) + halfWidth) + ',' + halfWidth + ')'; }) .attr('fill', chart.c) //.attr('width', chart.x.rangeBand()) //.attr('height', chart.x.rangeBand()) .attr('d', function (d) { return chart._shape(d, chart.x.rangeBand()); }); } this.layer('rows-header', corrplotBase.append('g'), { dataBind: function (data) { var chart = this.chart(), nodes = data.nodes; nodes.forEach(function (node, i) { node.index = i; }); return this.selectAll('.row-header') .data(nodes); }, insert: function () { var chart = this.chart(); return this .append('text') .classed('row-header', true); }, events: { 'merge': function () { var chart = this.chart(); return this .attr('transform', function (d, i) { return 'translate(0,' + chart.x(i) + ')'; }) .attr('x', -6) .attr('y', chart.x.rangeBand() / 2) .attr('dy', '.32em') .attr('text-anchor', 'end') .text(function (d) { return d.name; }) }, 'exit': function () { this.remove(); } } }); this.layer('cols-header', corrplotBase.append('g'), { dataBind: function (data) { var chart = this.chart(), nodes = data.nodes; return this.selectAll('.col-header') .data(nodes); }, insert: function () { var chart = this.chart(); return this .append('text') .classed('col-header', true); }, events: { 'merge': function () { var chart = this.chart(); //FIXME: Implement shift in x/y when rotation is not -90 return this .attr('transform', function (d, i) { return 'translate(' + chart.x(i) + ')rotate(' + chart.colRotation + ')'; }) .attr('x', 6) .attr('y', chart.x.rangeBand() / 2) .attr('dy', '.32em') .attr('text-anchor', 'start') .text(function (d) { return d.name; }) }, 'exit': function () { this.remove(); } } }); //this.layer('cols-grid', corrplotBase.append('g'), { // dataBind: function (data) { // var chart = this.chart(), // nodes = data.nodes; // // return this.selectAll('.col-grid') // .data(nodes); // }, // insert: function () { // var chart = this.chart(); // // return this // .append('line') // .classed('col-grid', true); // }, // events: { // 'merge': function () { // var chart = this.chart(); // // return this // .attr('transform', function (d, i) { // return 'translate(' + chart.x(i) + ')rotate(-90)'; // }) // .attr('x1', -chart.w); // }, // // 'exit': function () { // this.remove(); // } // } //}); }, _loadDefaults: function () { this.x = d3.scale.ordinal(); this.width(720); var c = d3.scale.linear() .domain([-1, 0, 1]) .range(['#ef8a62', '#f7f7f7', '#67a9cf']); this.color(function (d) { return c(d.z); }); this.duration(0); this.margin({top: 80, right: 0, bottom: 10, left: 80}); this.rotatecols(-90); this.shape(function (d, width) { return Corrplot.Shape.Square(width); }); //TODO: Implement default tips this.mouseover(function () { }); this.mouseout(function () { }); }, // configures the width/height of the chart. // when called without arguments, returns the // current width/height. width: function (newWidth) { if (arguments.length === 0) { return this.w; } this.w = newWidth; //update x range this.x = this.x.rangeBands([0, newWidth]); //redraw to refelct the size change this.reDraw(); return this; }, // configures the margin of the chart. // when called without arguments, returns the // current margin. margin: function (newMargin) { if (arguments.length === 0) { return this.margin; } this.margin = newMargin; return this; }, // configures the rotation of the column headers. // when called without arguments, returns the // current rotation. rotatecols: function (newRotation) { if (arguments.length === 0) { return this.colRotation; } this.colRotation = newRotation; return this; }, // configures the color scale of the elements in the chart. // when called without arguments, returns the // current color scale. color: function (newColor) { if (arguments.length === 0) { return this.c; } this.c = newColor; return this; }, // configures the animation duration // when called without arguments, returns the // current animation duration. duration: function (newDuration) { if (arguments.length == 0) { return this.d; } this.d = newDuration; return this; }, // configures the animation duration // when called without arguments, returns the // current animation duration. mouseover: function (newMouseover) { if (arguments.length == 0) { return this._mouseover; } this._mouseover = newMouseover; return this; }, // configures the animation duration // when called without arguments, returns the // current animation duration. mouseout: function (newMouseout) { if (arguments.length == 0) { return this._mouseout; } this._mouseout = newMouseout; return this; }, // configures the order of rows/columns in the chart. // when called without arguments, returns the // current order. // when called with arguments after the first time, // rows and columns are shifted with animation order: function (newOrder) { if (arguments.length == 0) { return this.x.domain(); } if (this.x.domain().length === 0) { this.x.domain(newOrder); } else { this.x.domain(newOrder); var x = this.x, width = this.w, duration = this.d, colRotation = this.colRotation, t = this.base.transition().duration(duration); t.selectAll('.row') .delay(function (d, i) { return x(i) / width * duration; }) .attr('transform', function (d, i) { return 'translate(0,' + x(i) + ')'; }) .selectAll('.cell') .delay(function (d) { return x(d.x) / width * duration; }) .attr('transform', function (d) { var halfWidth = x.rangeBand() / 2; return 'translate(' + (x(d.x) + halfWidth) + ',' + halfWidth + ')'; }); t.selectAll('.row-header') .delay(function (d, i) { return x(i) / width * duration; }) .attr('transform', function (d, i) { return 'translate(0,' + x(i) + ')'; }); t.selectAll('.col-header') .delay(function (d, i) { return x(i) / width * duration; }) .attr('transform', function (d, i) { return 'translate(' + x(i) + ')rotate(' + colRotation + ')'; }); } return this; }, shape: function (newShape) { if (arguments.length == 0) { return this._shape; } if (this._shape === undefined) { this._shape = newShape; } else { this._shape = newShape; var x = this.x, duration = this.d, t = this.base.transition().duration(duration); t.selectAll('.cell') .attr('d', function (d) { return newShape(d, x.rangeBand()); }); } return this; }, // draw and save the data for future redraw drawAndSave: function (data) { this._data = data; this.draw(data); return this; }, reDraw: function () { if (this._data) { this.base .attr('height', this.w + this.margin.top + this.margin.bottom) .attr('width', this.w + this.margin.left + this.margin.right); return this.draw(this._data); } return this; } }); if (DEBUG) { // DEBUG CODE // // Each module can have its own debugging section. They all get compiled // out of the binary. } } // Your Corrplot may have many modules. How you organize the modules is up to // you, but generally speaking it's best if each module addresses a specific // concern. No module should need to know about the implementation details of // any other module. // Note: You must name this function something unique. If you end up // copy/pasting this file, the last function defined will clobber the previous // one. function initCorrplotModule (context) { 'use strict'; var Corrplot = context.Corrplot; // A Corrplot module can do two things to the Corrplot Object: It can extend // the prototype to add more methods, and it can add static properties. This // is useful if your Corrplot needs helper methods. // PRIVATE MODULE CONSTANTS // var MODULE_CONSTANT = true; // PRIVATE MODULE METHODS // /** * An example of a private method. Feel free to remove this. */ function modulePrivateMethod () { return; } // Corrplot STATIC PROPERTIES // /** * An example of a static Corrplot property. This particular static property * is also an instantiable Object. * @constructor */ Corrplot.CorrplotHelper = function () { return this; }; // Corrplot PROTOTYPE EXTENSIONS // // A module can extend the prototype of the Corrplot Object. /** * An example of a prototype method. * @return {string} */ Corrplot.prototype.alternateGetReadOnlyVar = function () { // Note that a module can access all of the Corrplot instance variables with // the `this` keyword. return this._readOnlyVar; }; if (DEBUG) { // DEBUG CODE // // Each module can have its own debugging section. They all get compiled // out of the binary. } } /** * Orders are similar to modules, only they do not use the same namespace as * the Core, but defined a sub-namespace of their own. * @param {Object} The Object that the Corrplot gets attached to in * Corrplot.init.js. If the Corrplot was not loaded with an AMD loader such as * require.js, this is the global Object. */ function initCorrplotOrder(context) { 'use strict'; var Corrplot = context.Corrplot; Corrplot.Order = { Original: function (n) { if (Array.isArray(n)) n = n.length; if (typeof (n) === 'object') n = n.nodes.length; return d3.range(n); }, Alphabetical: function (nodes, fn) { if (arguments.length == 1) fn = function (d) { return d; }; return d3.range(nodes.length).sort(function (a, b) { return d3.ascending(fn(nodes[a]), fn(nodes[b])); }); }, AOE: function (matrix) { if (!Array.isArray(matrix)) matrix = matrix.matrix; var eigvec = numeric.eig(matrix).E.x; var alpha = d3.range(matrix.length).map(function (i) { var e1 = eigvec[i][0], e2 = eigvec[i][1]; return Math.atan(e2 / e1) + (e1 > 0 ? 0 : Math.PI); }); return d3.range(matrix.length).sort(function (a, b) { return alpha[a] - alpha[b]; }); }, FPC: function (matrix) { if (!Array.isArray(matrix)) matrix = matrix.matrix; var eigvec = numeric.eig(matrix).E.x; var e1 = eigvec.map(function (d) { return d[0]; }); return d3.range(matrix.length).sort(function (a, b) { return e1[b] - e1[a]; }); } }; } /** * Orders are similar to modules, only they do not use the same namespace as * the Core, but defined a sub-namespace of their own. * @param {Object} The Object that the Corrplot gets attached to in * Corrplot.init.js. If the Corrplot was not loaded with an AMD loader such as * require.js, this is the global Object. */ function initCorrplotShape(context) { 'use strict'; var Corrplot = context.Corrplot; Corrplot.Shape = { Square: function (width) { return 'M -' + width / 2 + ',' + '-' + width / 2 + ' h ' + width + ' v ' + width + ' h -' + width + ' Z'; }, Circle: function (r) { return 'M -' + r + ',0 ' + 'a ' + r + ',' + r + ' 0 1,0 ' + r * 2 + ',0 ' + 'a ' + r + ',' + r + ' 0 1,0 -' + r * 2 + ',0'; }, Ellipse: function (rho, width, segments) { if (arguments.length === 2) segments = 180; var delta = Math.acos(rho), scale = width / 2, line = d3.svg.line() .x(function (d) { return d.x * scale; }) .y(function (d) { return d.y * scale; }); return line(d3.range(0, 180).map(function (i) { var theta = i * Math.PI / 90; return {'x': Math.cos(theta + delta / 2), 'y': Math.cos(theta - delta / 2)} })); } }; if (d3.superformula !== undefined) { Corrplot.Shape = { Square: function (width, segments) { if (arguments.length === 1) segments = 180; return d3.superformula().type('square').size(width * width).segments(segments)(); }, Circle: function (r, segments) { if (arguments.length === 1) segments = 180; return d3.superformula().type('circle').size(r * r * 2).segments(segments)(); }, Ellipse: Corrplot.Shape.Ellipse }; } } /** * Submodules are similar to modules, only they do not use the same namespace as * the Core, but defined a sub-namespace of their own. * @param {Object} The Object that the Corrplot gets attached to in * Corrplot.init.js. If the Corrplot was not loaded with an AMD loader such as * require.js, this is the global Object. */ function initCorrplotSubmodule (context) { 'use strict'; var Corrplot = context.Corrplot; /* * The submodule constructor * @param {Object} opt_config Contains any properties that should be used to * configure this instance of the Corrplot. * @constructor */ var submodule = Corrplot.Submodule = function(opt_config) { // defines a temporary variable, // living only as long as the constructor runs. var constructorVariable = "Constructor Variable"; // set an instance variable // will be available after constructor has run. this.instanceVariable = null; // an optional call to the private method // at the end of the construction process this._privateMethod(constructorVariable); }; // Corrplot PROTOTYPE EXTENSIONS /** * A public method of the submodule * @param {object} a variable to be set to the instance variable * @returns {object} the final value of the instance variable */ submodule.prototype.publicMethod = function(value){ if (value !== undefined) { this._privateMethod(value); } return this.instanceVariable; }; /** * a private instance method * @param {object} a variable to be set to the instance variable * @returns {object} the final value of the instance variable */ submodule.prototype._privateMethod = function(value){ return this.instanceVariable = value; }; } /*global initCorrplotCore initCorrplotModule initCorrplotSubmodule */ var initCorrplot = function (context) { initCorrplotCore(context); initCorrplotShape(context); initCorrplotChart(context); initCorrplotModule(context); initCorrplotSubmodule(context); initCorrplotOrder(context); // Add a similar line as above for each module that you have. If you have a // module named "Awesome Module," it should live in the file // "src/Corrplot.awesome-module.js" with a wrapper function named // "initAwesomeModule". That function should then be invoked here with: // // initAwesomeModule(context); return context.Corrplot; }; if (typeof define === 'function' && define.amd) { // Expose Corrplot as an AMD module if it's loaded with RequireJS or // similar. define(function () { return initCorrplot({}); }); } else { // Load Corrplot normally (creating a Corrplot global) if not using an AMD // loader. initCorrplot(this); } } (this));
const { src, dest, task, series } = require('gulp'); const fs = require('fs'); const del = require('del'); const gulpif = require('gulp-if'); const replace = require('gulp-replace'); const postcss = require('gulp-postcss'); const autoprefixer = require('autoprefixer'); const uglify = require('gulp-uglify'); const cleanCSS = require('gulp-clean-css'); const rename = require('gulp-rename'); const header = require("gulp-header"); const eslint = require('gulp-eslint'); const pack = () => JSON.parse(fs.readFileSync("./package.json", "utf8")); const pkg = pack(); const year = new Date().getFullYear(); const banner = `/*! * round-slider v${pkg.version} * * @website ${pkg.homepage} * @copyright (c) 2015-${year} Soundar * @license MIT */\n\n`; const isJavaScript = file => file.extname === '.js'; const isCSS = file => file.extname === '.css'; function buildFiles(ext) { return src([`src/*.${ext}`]) // replace the variables from the source files .pipe(replace('{VERSION}', pkg.version)) .pipe(replace('{YEAR}', year)) // add the CSS vendor prefixes (Browserslist config will be loaded from '.browserslistrc' file) .pipe(gulpif(isCSS, postcss([autoprefixer()]))) // move the unminified version of source files to dist folder, for development purpose .pipe(dest('dist/')) // do the minification for JS and CSS files .pipe(gulpif(isJavaScript, uglify())) .pipe(gulpif(isCSS, cleanCSS({ level: { 1: { specialComments: 0 }} }))) // rename the minified files with '.min' suffix .pipe(rename({ suffix: '.min' })) // add the banner content, since it should be removed from source files during minification .pipe(header(banner)) // move the minified files also to the dist folder .pipe(dest('dist/')); } task('lint', () => { return src(['src/*.js']) .pipe(eslint()) .pipe(eslint.formatEach('compact', process.stderr)); }); task('deleteFiles', () => del(['dist/*'])); task('build_js', series('lint', () => buildFiles('js'))); task('build_css', series(() => buildFiles('css'))); task('build', series('deleteFiles', 'build_js', 'build_css'));
// Example var ourArray = ["John", 23]; // Only change code below this line. var myArray = [];
import React from 'react'; import styled from 'styled-components'; const LogoContainer = styled.div` `; const StyledLogo = styled.svg` width: 100px; `; const LogoTextContainer = styled.div` display: inline-block; height: 100%; font-size: 30px; margin: 0.02em; vertical-align: middle; `; const SvgLogo = () => ( <StyledLogo x="0px" y="0px" viewBox="0 0 612 792" enable-background="new 0 0 612 792"> <path fill="#6F6F6D" d="M585.576,185.144c-54.506-1.913-98.494,6.694-125.269,25.819c-16.257,28.688-24.862,77.456-23.906,137.7 c54.506,1.912,102.318-0.956,125.269-25.819C583.664,298.938,586.532,245.388,585.576,185.144"/> <path fill="#F4A19A" d="M571.232,221.481c-38.25-0.956-68.85,4.781-87.975,18.169c-11.476,20.081-18.169,54.506-17.213,96.581 c38.25,0.956,71.719-0.956,87.975-18.169C570.276,300.851,572.188,263.557,571.232,221.481"/> <path fill="#6F6F6D" d="M11.826,185.144c54.506-1.913,98.494,6.694,125.269,25.819c16.256,28.688,24.863,77.456,23.906,137.7 c-53.55,1.912-102.318-0.956-125.269-25.819C13.739,298.938,10.87,245.388,11.826,185.144"/> <path fill="#F4A19A" d="M26.17,221.481c38.25-0.956,68.85,4.781,87.975,18.169c11.475,20.081,17.212,54.506,17.212,96.581 c-38.25,0.956-71.719-0.956-87.975-18.169C27.126,300.851,25.214,263.557,26.17,221.481"/> <path fill="#89664C" d="M307.912,442.856c-163.519,0-288.787-67.894-288.787,84.149c0,122.4,161.606,155.869,284.962,155.869 c143.438,0,288.788-33.469,288.788-155.869C592.875,374.962,476.213,442.856,307.912,442.856"/> <path fill="#9B7861" d="M303.131,289.856c-91.8,0-234.281,10.519-234.281,120.487c0,160.65,473.343,160.65,473.343,0 C543.15,300.375,400.669,289.856,303.131,289.856"/> <path fill="#A88673" d="M468.562,249.694c-43.987-98.494-252.45,2.869-216.112-116.663c5.737-18.169,4.781-25.819-8.606-22.95 c-74.587,15.3-129.094,91.8-109.969,155.869C195.075,470.588,528.807,383.569,468.562,249.694"/> <path fill="#FFFFFF" d="M275.4,417.994c0,38.25-30.6,68.85-68.85,68.85s-68.85-30.6-68.85-68.85c0-38.25,30.6-68.851,68.85-68.851 S275.4,379.744,275.4,417.994"/> <circle fill="#231F20" cx="225.675" cy="417.994" r="34.425"/> <path fill="#FFFFFF" d="M474.3,417.994c0,38.25-30.6,68.85-68.85,68.85s-68.851-30.6-68.851-68.85 c0-38.25,30.601-68.851,68.851-68.851C442.744,349.144,474.3,379.744,474.3,417.994"/> <g> <circle fill="#231F20" cx="386.325" cy="417.994" r="34.425"/> <path fill="#231F20" d="M363.375,573.862c0,31.557-25.818,57.375-57.375,57.375c-31.556,0-57.375-25.818-57.375-57.375 c0-31.556,25.819-57.375,57.375-57.375C337.557,516.487,363.375,542.307,363.375,573.862"/> </g> <g> <path fill="#F6C799" d="M205.116,246.334c-34.425-18.169-57.375-56.419-57.375-56.419 c-9.562,100.406,26.775,125.269,47.812,125.269C223.284,316.14,245.278,268.327,205.116,246.334"/> <path fill="#F6C799" d="M406.885,246.334c34.426-18.169,57.375-56.419,57.375-56.419c9.562,100.406-26.775,125.269-47.812,125.269 C388.717,316.14,366.723,268.327,406.885,246.334"/> </g> </StyledLogo>); export default () => (<LogoContainer> <LogoTextContainer></LogoTextContainer> <SvgLogo /> <LogoTextContainer></LogoTextContainer> </LogoContainer>);
var students = [ { first_name: 'Bob', last_name: 'Harrison', gender: 'Male', address: '1197 Thunder Wagon Common, Cataract, RI, 02987-1016, US, (401) 747-0763', mood: "Happy", country: 'Ireland' }, { first_name: 'Mary', last_name: 'Wilson', gender: 'Female', age: 11, address: '3685 Rocky Glade, Showtucket, NU, X1E-9I0, CA, (867) 371-4215', mood: "Sad", country: 'Ireland' }, { first_name: 'Sadiq', last_name: 'Khan', gender: 'Male', age: 12, address: '3235 High Forest, Glen Campbell, MS, 39035-6845, US, (601) 638-8186', mood: "Happy", country: 'Ireland' }, { first_name: 'Jerry', last_name: 'Mane', gender: 'Male', age: 12, address: '2234 Sleepy Pony Mall , Drain, DC, 20078-4243, US, (202) 948-3634', mood: "Happy", country: 'Ireland' } ]; // double the array twice, make more data! students.forEach(function (item) { students.push(cloneObject(item)); }); students.forEach(function (item) { students.push(cloneObject(item)); }); students.forEach(function (item) { students.push(cloneObject(item)); }); function cloneObject(obj) { return JSON.parse(JSON.stringify(obj)); } var columnDefs = [ { field: "first_name", headerName: "First Name", width: 120, editable: true}, {field: "last_name", headerName: "Last Name", width: 120, editable: true}, { field: "gender", width: 100, cellEditor: 'mySimpleCellEditor' }, { field: "age", width: 80, cellEditor: 'mySimpleCellEditor' }, { field: "mood", width: 90, cellEditor: 'mySimpleCellEditor' }, { field: "country", width: 110, cellEditor: 'mySimpleCellEditor' }, { field: "address", width: 502, cellEditor: 'mySimpleCellEditor' } ]; var gridOptions = { columnDefs: columnDefs, defaultColDef: { editable: true, sortable: true, flex: 1, minWidth: 100, filter: true, resizable: true }, rowData: students, components: { mySimpleCellEditor: MySimpleCellEditor } }; var KEY_BACKSPACE = 8; var KEY_F2 = 113; var KEY_DELETE = 46; function MySimpleCellEditor() { } MySimpleCellEditor.prototype.init = function (params) { this.gui = document.createElement('input'); this.gui.type = 'text'; this.gui.classList.add('my-simple-editor'); this.params = params; var startValue; var keyPressBackspaceOrDelete = params.keyPress === KEY_BACKSPACE || params.keyPress === KEY_DELETE; if (keyPressBackspaceOrDelete) { startValue = ''; } else if (params.charPress) { startValue = params.charPress; } else { startValue = params.value; if (params.keyPress !== KEY_F2) { this.highlightAllOnFocus = true; } } if (startValue !== null && startValue !== undefined) { this.gui.value = startValue; } }; MySimpleCellEditor.prototype.getGui = function () { return this.gui; }; MySimpleCellEditor.prototype.getValue = function () { return this.gui.value; }; MySimpleCellEditor.prototype.afterGuiAttached = function () { this.gui.focus(); }; MySimpleCellEditor.prototype.myCustomFunction = function () { return { rowIndex: this.params.rowIndex, colId: this.params.column.getId() }; }; // setup the grid after the page has finished loading document.addEventListener('DOMContentLoaded', function () { var gridDiv = document.querySelector('#myGrid'); new agGrid.Grid(gridDiv, gridOptions); }); setInterval(function () { var instances = gridOptions.api.getCellEditorInstances(); if (instances.length > 0) { var instance = instances[0]; if (instance.myCustomFunction) { var result = instance.myCustomFunction(); console.log('found editing cell: row index = ' + result.rowIndex + ', column = ' + result.colId + '.'); } else { console.log('found editing cell, but method myCustomFunction not found, must be the default editor.'); } } else { console.log('found not editing cell.'); } }, 1000);
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var partials = require('express-partials'); var routes = require('./routes/index'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(partials()); // uncomment after placing your favicon in /public app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // 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: {} }); }); module.exports = app;
const mongoose = require('mongoose'); let Room = require('../models/roomRent'); let PropertyRent = require('../models/propertyRent'); let login = require('../helpers/login'); const checkAuth = (req,res, next) => { let method = req.method; let hasParam = req.path !== '/'; // if (method == "GET") next() if (req.headers.hasOwnProperty('token')){ let decoded = login.getUserDetail(req.headers.token); if (decoded) next(); else res.send({err:'You must login'}) } else res.send({err:'You must login'}) } const getRooms = (req,res) => { console.log("=========== masuk 1"); Room.find({_propertyId : req.params._propertyId}, (err,rooms) => { console.log("=========== masuk 2"); res.send(err ? err : rooms); }) } const getRoom = (req,res) => { Room.findById( req.params._roomId , (err, record)=>{ err ? res.json({ err }) : res.json(record) }) } const addRoom = (req,res) => { let decoded = login.getUserDetail(req.headers.token); let room = new Room({ name: req.body.name, image: req.body.image, descr: req.body.descr, _propertyId: req.params._propertyId, _userId: decoded._id }); room.save((err,newroom) => { if (err) { let err_msg = []; for (let error in err.errors) err_msg.push(err.errors[error].message); res.send({err : err_msg.join(',')}); } else { PropertyRent.update({_id: newroom._propertyId},{$push: {_roomId: newroom._id}}, {new: true, safe: true, upsert: true}).exec((error, result)=> { if(error) res.send(error) else { res.send(newroom) // PropertyRent.findById({_id: newroom._propertyId}, (err, data) => { // if(err){ // console.log(err); // } else { // console.log("==================== newroom ctrl ===================="); // console.log(result); // console.log(data); // } // }) } }) } }) } const editRoom = (req,res) => { let decoded = login.getUserDetail(req.headers.token); Room.findById(req.params._roomId, (err,room) => { if (err) res.send({err: 'Invalid Property'}) else if (room._userId != decoded._id && decoded.role !== 'admin') { res.send({err:'Invalid access'}) } else { if (typeof req.body.name != 'undefined') room.name = req.body.name; if (typeof req.body.image != 'undefined') room.image = req.body.image; if (typeof req.body.descr != 'undefined') room.descr = req.body.descr; room.save((err,edroom)=> { if (err) res.send({ err: err }) else { res.send(edroom) } } ); } }) } const deleteRoom = (req,res) => { let decoded = login.getUserDetail(req.headers.token); Room.findById(req.params._roomId, (err,room) => { if (err) res.send({err: 'Invalid Request'}) else if (room._userId != decoded._id && decoded.role !== 'admin') res.send({err:'Invalid access'}); else { room.remove((err,deleted) => {res.send(err? err : deleted)}) // PropertyRent.update({_id: room._propertyId}, { $pullAll : [{_roomId: room._id}] }).exec((error, result)=> { // if(error) { // res.send(error) // } else { // res.send({msg: "deleted"}) // } // }) } }) } module.exports = { getRooms, getRoom, addRoom, editRoom, deleteRoom, checkAuth }
import fetch from 'focus-core/network/fetch'; import movieUrl from '../config/server/movies'; import omit from 'lodash/object/omit'; export default { loadMovie(id) { console.log(`[MOVIE] call loadMovie(${id}) method`); return fetch(movieUrl.load({urlData: {id}}), {isCORS: true}); }, loadMovieCasting(id) { console.log(`[MOVIE] call loadMovieCasting(${id}) method`); return fetch(movieUrl.casting({urlData: {id}}), {isCORS: true}).then(({actors, camera, directors, producers, writers}) => { return {actors, camera, directors, producers, writers}; }); }, updateMovieCaracteristics(data) { const movieId = data.id; const newData = omit(data, ['id', 'actors', 'camera', 'directors', 'producers', 'writers']); console.log(`[MOVIE] call updateMovieCaracteristics ${movieId} method. data=${JSON.stringify(newData)}`); return fetch(movieUrl.update({urlData: {id: movieId}, data: newData}), {isCORS: true}); }, updateMovieSynopsis(data) { const movieId = data.id; const newData = omit(data, ['id', 'actors', 'camera', 'directors', 'producers', 'writers']); console.log(`[MOVIE] call updateMovieSynopsis method. data=${JSON.stringify(newData)}`); return fetch(movieUrl.update({urlData: {id: movieId}, data: newData}), {isCORS: true}); } }
///import core ///import uicore ///import ui/mask.js ///import ui/button.js (function() { var utils = baidu.editor.utils, domUtils = baidu.editor.dom.domUtils, uiUtils = baidu.editor.ui.uiUtils, Mask = baidu.editor.ui.Mask, UIBase = baidu.editor.ui.UIBase, Button = baidu.editor.ui.Button, Dialog = (baidu.editor.ui.Dialog = function(options) { if (options.name) { var name = options.name; var cssRules = options.cssRules; if (!options.className) { options.className = "edui-for-" + name; } if (cssRules) { options.cssRules = ".edui-for-" + name + " .edui-dialog-content {" + cssRules + "}"; } } this.initOptions( utils.extend( { autoReset: true, draggable: true, onok: function() {}, oncancel: function() {}, onclose: function(t, ok) { return ok ? this.onok() : this.oncancel(); }, //是否控制dialog中的scroll事件, 默认为不阻止 holdScroll: false }, options ) ); this.initDialog(); }); var modalMask; var dragMask; var activeDialog; Dialog.prototype = { draggable: false, uiName: "dialog", initDialog: function() { var me = this, theme = this.editor.options.theme; if (this.cssRules) { this.cssRules = ".edui-" + theme + " " + this.cssRules; utils.cssRule("edui-customize-" + this.name + "-style", this.cssRules); } this.initUIBase(); this.modalMask = modalMask || (modalMask = new Mask({ className: "edui-dialog-modalmask", theme: theme, onclick: function() { activeDialog && activeDialog.close(false); } })); this.dragMask = dragMask || (dragMask = new Mask({ className: "edui-dialog-dragmask", theme: theme })); this.closeButton = new Button({ className: "edui-dialog-closebutton", title: me.closeDialog, theme: theme, onclick: function() { me.close(false); } }); this.fullscreen && this.initResizeEvent(); if (this.buttons) { for (var i = 0; i < this.buttons.length; i++) { if (!(this.buttons[i] instanceof Button)) { this.buttons[i] = new Button( utils.extend( this.buttons[i], { editor: this.editor }, true ) ); } } } }, initResizeEvent: function() { var me = this; domUtils.on(window, "resize", function() { if (me._hidden || me._hidden === undefined) { return; } if (me.__resizeTimer) { window.clearTimeout(me.__resizeTimer); } me.__resizeTimer = window.setTimeout(function() { me.__resizeTimer = null; var dialogWrapNode = me.getDom(), contentNode = me.getDom("content"), wrapRect = UE.ui.uiUtils.getClientRect(dialogWrapNode), contentRect = UE.ui.uiUtils.getClientRect(contentNode), vpRect = uiUtils.getViewportRect(); contentNode.style.width = vpRect.width - wrapRect.width + contentRect.width + "px"; contentNode.style.height = vpRect.height - wrapRect.height + contentRect.height + "px"; dialogWrapNode.style.width = vpRect.width + "px"; dialogWrapNode.style.height = vpRect.height + "px"; me.fireEvent("resize"); }, 100); }); }, fitSize: function() { var popBodyEl = this.getDom("body"); // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) { // uiUtils.removeStyle(popBodyEl, 'width'); // uiUtils.removeStyle(popBodyEl, 'height'); // } var size = this.mesureSize(); popBodyEl.style.width = size.width + "px"; popBodyEl.style.height = size.height + "px"; return size; }, safeSetOffset: function(offset) { var me = this; var el = me.getDom(); var vpRect = uiUtils.getViewportRect(); var rect = uiUtils.getClientRect(el); var left = offset.left; if (left + rect.width > vpRect.right) { left = vpRect.right - rect.width; } var top = offset.top; if (top + rect.height > vpRect.bottom) { top = vpRect.bottom - rect.height; } el.style.left = Math.max(left, 0) + "px"; el.style.top = Math.max(top, 0) + "px"; }, showAtCenter: function() { var vpRect = uiUtils.getViewportRect(); if (!this.fullscreen) { this.getDom().style.display = ""; var popSize = this.fitSize(); var titleHeight = this.getDom("titlebar").offsetHeight | 0; var left = vpRect.width / 2 - popSize.width / 2; var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight; var popEl = this.getDom(); this.safeSetOffset({ left: Math.max(left | 0, 0), top: Math.max(top | 0, 0) }); if (!domUtils.hasClass(popEl, "edui-state-centered")) { popEl.className += " edui-state-centered"; } } else { var dialogWrapNode = this.getDom(), contentNode = this.getDom("content"); dialogWrapNode.style.display = "block"; var wrapRect = UE.ui.uiUtils.getClientRect(dialogWrapNode), contentRect = UE.ui.uiUtils.getClientRect(contentNode); dialogWrapNode.style.left = "-100000px"; contentNode.style.width = vpRect.width - wrapRect.width + contentRect.width + "px"; contentNode.style.height = vpRect.height - wrapRect.height + contentRect.height + "px"; dialogWrapNode.style.width = vpRect.width + "px"; dialogWrapNode.style.height = vpRect.height + "px"; dialogWrapNode.style.left = 0; //保存环境的overflow值 this._originalContext = { html: { overflowX: document.documentElement.style.overflowX, overflowY: document.documentElement.style.overflowY }, body: { overflowX: document.body.style.overflowX, overflowY: document.body.style.overflowY } }; document.documentElement.style.overflowX = "hidden"; document.documentElement.style.overflowY = "hidden"; document.body.style.overflowX = "hidden"; document.body.style.overflowY = "hidden"; } this._show(); }, getContentHtml: function() { var contentHtml = ""; if (typeof this.content == "string") { contentHtml = this.content; } else if (this.iframeUrl) { contentHtml = '<span id="' + this.id + '_contmask" class="dialogcontmask"></span><iframe id="' + this.id + '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="' + this.iframeUrl + '"></iframe>'; } return contentHtml; }, getHtmlTpl: function() { var footHtml = ""; if (this.buttons) { var buff = []; for (var i = 0; i < this.buttons.length; i++) { buff[i] = this.buttons[i].renderHtml(); } footHtml = '<div class="%%-foot">' + '<div id="##_buttons" class="%%-buttons">' + buff.join("") + "</div>" + "</div>"; } return ( '<div id="##" class="%%"><div ' + (!this.fullscreen ? 'class="%%"' : 'class="%%-wrap edui-dialog-fullscreen-flag"') + '><div id="##_body" class="%%-body">' + '<div class="%%-shadow"></div>' + '<div id="##_titlebar" class="%%-titlebar">' + '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' + '<span class="%%-caption">' + (this.title || "") + "</span>" + "</div>" + this.closeButton.renderHtml() + "</div>" + '<div id="##_content" class="%%-content">' + (this.autoReset ? "" : this.getContentHtml()) + "</div>" + footHtml + "</div></div></div>" ); }, postRender: function() { // todo: 保持居中/记住上次关闭位置选项 if (!this.modalMask.getDom()) { this.modalMask.render(); this.modalMask.hide(); } if (!this.dragMask.getDom()) { this.dragMask.render(); this.dragMask.hide(); } var me = this; this.addListener("show", function() { me.modalMask.show(this.getDom().style.zIndex - 2); }); this.addListener("hide", function() { me.modalMask.hide(); }); if (this.buttons) { for (var i = 0; i < this.buttons.length; i++) { this.buttons[i].postRender(); } } domUtils.on(window, "resize", function() { setTimeout(function() { if (!me.isHidden()) { me.safeSetOffset(uiUtils.getClientRect(me.getDom())); } }); }); //hold住scroll事件,防止dialog的滚动影响页面 // if( this.holdScroll ) { // // if( !me.iframeUrl ) { // domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){ // domUtils.preventDefault(e); // } ); // } else { // me.addListener('dialogafterreset', function(){ // window.setTimeout(function(){ // var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow; // // if( browser.ie ) { // // var timer = window.setInterval(function(){ // // if( iframeWindow.document && iframeWindow.document.body ) { // window.clearInterval( timer ); // timer = null; // domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){ // domUtils.preventDefault(e); // } ); // } // // }, 100); // // } else { // domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){ // domUtils.preventDefault(e); // } ); // } // // }, 1); // }); // } // // } this._hide(); }, mesureSize: function() { var body = this.getDom("body"); var width = uiUtils.getClientRect(this.getDom("content")).width; var dialogBodyStyle = body.style; dialogBodyStyle.width = width; return uiUtils.getClientRect(body); }, _onTitlebarMouseDown: function(evt, el) { if (this.draggable) { var rect; var vpRect = uiUtils.getViewportRect(); var me = this; uiUtils.startDrag(evt, { ondragstart: function() { rect = uiUtils.getClientRect(me.getDom()); me.getDom("contmask").style.visibility = "visible"; me.dragMask.show(me.getDom().style.zIndex - 1); }, ondragmove: function(x, y) { var left = rect.left + x; var top = rect.top + y; me.safeSetOffset({ left: left, top: top }); }, ondragstop: function() { me.getDom("contmask").style.visibility = "hidden"; domUtils.removeClasses(me.getDom(), ["edui-state-centered"]); me.dragMask.hide(); } }); } }, reset: function() { this.getDom("content").innerHTML = this.getContentHtml(); this.fireEvent("dialogafterreset"); }, _show: function() { if (this._hidden) { this.getDom().style.display = ""; //要高过编辑器的zindxe this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10); this._hidden = false; this.fireEvent("show"); baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4; } }, isHidden: function() { return this._hidden; }, _hide: function() { if (!this._hidden) { var wrapNode = this.getDom(); wrapNode.style.display = "none"; wrapNode.style.zIndex = ""; wrapNode.style.width = ""; wrapNode.style.height = ""; this._hidden = true; this.fireEvent("hide"); } }, open: function() { if (this.autoReset) { //有可能还没有渲染 try { this.reset(); } catch (e) { this.render(); this.open(); } } this.showAtCenter(); if (this.iframeUrl) { try { this.getDom("iframe").focus(); } catch (ex) {} } activeDialog = this; }, _onCloseButtonClick: function(evt, el) { this.close(false); }, close: function(ok) { if (this.fireEvent("close", ok) !== false) { //还原环境 if (this.fullscreen) { document.documentElement.style.overflowX = this._originalContext.html.overflowX; document.documentElement.style.overflowY = this._originalContext.html.overflowY; document.body.style.overflowX = this._originalContext.body.overflowX; document.body.style.overflowY = this._originalContext.body.overflowY; delete this._originalContext; } this._hide(); //销毁content var content = this.getDom("content"); var iframe = this.getDom("iframe"); if (content && iframe) { var doc = iframe.contentDocument || iframe.contentWindow.document; doc && (doc.body.innerHTML = ""); domUtils.remove(content); } } } }; utils.inherits(Dialog, UIBase); })();
'use strict'; angular.module('animatedBirdsDirective', []) .directive('animatedBirds', function($window) { return { restrict: 'A', compile: function() { return function(scope, lElem) { var tl = new TimelineMax( { repeat: 0, delay: 1, onComplete: function() { lElem.children().remove(); } } ); for (var i = 10 ; i< 100; i++){ var childElement = angular.element('<div class="bird"/>'); lElem.append(childElement); var bezTween = new TweenMax( childElement, 8, { bezier: { type: 'soft', values: [ {x:-30 * Math.random()* 100, y:-30 * Math.random()* 200}, {x:30 + Math.random() * 100, y:Math.random() * 100}, {x:300 + Math.random() * 100, y:30 + Math.random() * 100}, {x:500 + Math.random() * 100, y:320 * Math.random() + 50}, {x:650, y:320 * Math.random() + 50}, {x:900+ Math.random() *100, y: Math.random() * 100}, {x:$window.innerWidth, y:$window.innerHeight /2} ], autoRotate: true }, ease: Linear.easeNone } ); //start bird animation every 0.007 seconds tl.add(bezTween, 0.007*i); } }; } }; });
#!/usr/bin/env node import meow from 'meow'; import emptyTrash from 'empty-trash'; meow(` Usage $ empty-trash `, { importMeta: import.meta, }); emptyTrash();
const socketio = require('socket.io') const data = require('../data/tasks') exports.listen = function (server) { io = socketio.listen(server) io.sockets.on('connection', function (socket) { console.log('Connection created') createTask(socket) displayAllTask(socket) }) const createTask = (socket) => { socket.on('createTask', (task) => { let counter = ++(data.seq) data['tasks'][counter] = { title: task.title, desc: task.description, status: 'new', assgnBy: 'current', assgnTo: task.assignedTo, createdOn: new Date().toISOString(), dueDate: task.dueDate } io.emit('updateTaskList', {task: task, status: 'new'}) }) } const displayAllTask = (socket) => { socket.on('populateAllTask', (data) => { socket.emit('displayAllTask', data) }) } }
/* CalendarController: This controller handles the calendar functionality in the tracks page. The tracks.html file makes use of this calendar controller 1) We have made use of the calendar directive to achieve this. 2) There are 4 important functions of this controller(PrevMonth,NextMonth,DateClicked,Populating the calendar) */ (function () { 'use strict'; function AllTracksPaginationTabCtrl( $rootScope, $scope, $translate, $mdMedia, $mdDialog, TrackService, UserCredentialsService, ecBaseUrl, ecServerBase, FilterStateService) { "ngInject"; $scope.okay_pressed = false; $scope.onload_pagination_tab = false; $scope.Math = window.Math; $scope.filterOrder = FilterStateService.getFilterStateOrder(); console.log($scope.filterOrder); $scope.itemsPerPage = ($scope.screenIsXS ? 5 : 10); $scope.itemsPerPage = (window.innerHeight < 1000 ? 5 : 10); $(window).resize(function () { // $scope.$apply(function () { // if (window.innerHeight < 1000) { // $scope.itemsPerPage = 5; // } else { // $scope.itemsPerPage = 10; // } // var number_monthly_tracks = $scope.currentPaginationTracks.currentSelectedTracks.length; // $scope.currentPaginationTracks.currentMonthTracks = []; // // number pages: // $scope.pagingTab.total = Math.ceil(number_monthly_tracks / $scope.itemsPerPage); // // take the first $scope.itemsPerPage: // for (var i = 0; i < $scope.itemsPerPage && i < number_monthly_tracks; i++) { // $scope.currentPaginationTracks.currentMonthTracks.push($scope.currentPaginationTracks.currentSelectedTracks[i]); // } // $scope.pagingTab.current = 1; // loadPages(); // }); }); $scope.username = UserCredentialsService.getCredentials().username; var params = FilterStateService.getFilterState(); // Filters: $scope.filters = { distance: { name: 'distance', label: $translate.instant('FILTER_DISTANCE'), params: { min: params.distance.min, max: params.distance.max }, inUse: params.distance.inUse }, date: { name: 'date', label: $translate.instant('FILTER_DATE'), params: { min: params.date.min, max: params.date.max }, inUse: params.date.inUse }, duration: { name: 'duration', label: $translate.instant('FILTER_DURATION'), params: { min: params.duration.min, max: params.duration.max }, inUse: params.duration.inUse }, vehicle: { name: 'vehicle', label: $translate.instant('FILTER_VEHICLE'), params: { cars_all: params.vehicle.all, cars_set: params.vehicle.set }, inUse: params.vehicle.inUse }, spatial: { name: 'spatial', label: $translate.instant('FILTER_SPATIAL'), params: { southwest: { lat: params.spatial.southwest.lat, lng: params.spatial.southwest.lng }, northeast: { lat: params.spatial.northeast.lat, lng: params.spatial.northeast.lng }, track_ids: params.spatial.track_ids }, inUse: params.spatial.inUse, layer: 0 } }; $scope.filtered_tracks = 0; $scope.addFilter = function (filter) { // An utility map to replace writing switch cases for each of the filter if (!filter.inUse) { filter.inUse = true; if (filter.name === 'spatial') { filter.inUse = false; $scope.commonDialog(filter); } else { FilterStateService.setFilterInUse(filter.name, true); } $scope.filterOrder.push(filter); FilterStateService.setFilterStateOrder($scope.filterOrder); } console.log($scope.filters); var muh = FilterStateService.getFilterState(); console.log(muh); }; $scope.removeFilter = function (filter) { // delete all scope filters with name of removed filter: var i = $scope.filterOrder.length - 1; while (i >= 0) { if ($scope.filterOrder[i].name === filter.name) { $scope.filterOrder.splice(i, 1); } i--; } var params = FilterStateService.getFilterState(); console.log(params.filterOrder); // delete all state filters with name of removed filter: var i = params.filterOrder.length - 1; while (i >= 0) { if (params.filterOrder[i].name === filter.name) { // before deletion: set values to default: switch (filter.name) { case 'distance': params.distance.inUse = false; params.distance.min = undefined; params.distance.max = undefined; FilterStateService.setDistanceFilterState( false, params.distance.min, params.distance.max ); break; case 'date': console.log("removing date filter."); params.date.inUse = false; params.date.min = undefined; params.date.max = undefined; FilterStateService.setDateFilterState( false, params.date.min, params.date.max ); break; case 'duration': params.duration.inUse = false; params.duration.min = undefined; params.duration.max = undefined; FilterStateService.setDurationFilterState( false, params.duration.min, params.duration.max ); break; case 'vehicle': params.vehicle.inUse = false; params.vehicle.all = []; params.vehicle.set = []; FilterStateService.setVehicleFilterState( false, params.vehicle.all, params.vehicle.set ); break; case 'spatial': params.spatial.inUse = false; params.spatial.southwest.lat = undefined; params.spatial.southwest.lng = undefined; params.spatial.northeast.lat = undefined; params.spatial.northeast.lng = undefined; params.spatial.track_ids = []; FilterStateService.setSpatialFilterState( false, params.spatial.southwest.lat, params.spatial.southwest.lng, params.spatial.northeast.lat, params.spatial.northeast.lng, params.spatial.track_ids ); break; } // finally delete it: params.filterOrder.splice(i, 1); } i--; } console.log($scope.filters); var muh = FilterStateService.getFilterState(); console.log(muh); }; FilterStateService.setFilterStateOrder($scope.filterOrder); $scope.commonDialog = function (filter) { var showObject = {}; var useFullScreen = ($mdMedia('sm') || $mdMedia('xs')) && $scope.customFullscreen; if (filter.name === "spatial") { showObject = { controller: 'SpatialDialogCtrl', templateUrl: 'app/components/tracks/all_tracks_pagination_tab/filter_dialogs/spatial/spatial_filter_dialog.html', parent: angular.element(document.body), scope: $scope.$new(), clickOutsideToClose: false, fullscreen: useFullScreen }; } $mdDialog.show(showObject) .then(function (answer) { $scope.status = 'You said the information was "' + answer + '".'; }, function () { $scope.status = 'You cancelled the dialog.'; }); $scope.$watch(function () { return $mdMedia('xs') || $mdMedia('sm'); }, function (wantsFullScreen) { $scope.customFullscreen = (wantsFullScreen === true); }); }; var originatorEv; $scope.openMenu = function ($mdOpenMenu, ev) { originatorEv = ev; $mdOpenMenu(ev); }; $scope.filtersChanged = function () { // filter GO! var amount_of_user_tracks = $scope.currentPaginationTracks.tracks.length; $scope.amount_of_user_tracks = amount_of_user_tracks; var filterByDistance = $scope.filters.distance.inUse; var filterByDuration = $scope.filters.duration.inUse; var filterByDate = $scope.filters.date.inUse; var filterByVehicle = $scope.filters.vehicle.inUse; var filterBySpatial = $scope.filters.spatial.inUse; $scope.filtered_tracks = 0; // counts tracks, that are filtered into the result. var resultTracks = []; for (var i = 0; i < amount_of_user_tracks; i++) { var currTrack = $scope.currentPaginationTracks.tracks[i]; // filter by distance: if (filterByDistance) { var currDistance = currTrack.length; if ($scope.filters.distance.params.max === undefined) { if (!(currDistance >= $scope.filters.distance.params.min)) { continue; } } else { if (!((currDistance >= $scope.filters.distance.params.min) && (currDistance <= $scope.filters.distance.params.max))) { continue; } } } // filter by date: if (filterByDate) { var currDate = currTrack.begin; if (($scope.filters.date.params.min === undefined) && ($scope.filters.date.params.max !== undefined)) { if (!(currDate <= $scope.filters.date.params.max)) { continue; } } else if (($scope.filters.date.params.max === undefined) && ($scope.filters.date.params.min !== undefined)) { if (!(currDate >= $scope.filters.date.params.min)) { continue; } } else if ((!(currDate <= $scope.filters.date.params.max)) || (!(currDate >= $scope.filters.date.params.min))) { continue; } } // filter by duration: if (filterByDuration) { var seconds_passed = new Date(currTrack.end).getTime() - new Date(currTrack.begin).getTime(); var seconds = seconds_passed / 1000; var currTravelTime = seconds / 60; if (($scope.filters.duration.params.min === undefined) && ($scope.filters.duration.params.max !== undefined)) { if (!(currTravelTime < $scope.filters.duration.params.max)) { continue; } } else if (($scope.filters.duration.params.max === undefined) && ($scope.filters.duration.params.min !== undefined)) { if (!(currTravelTime >= $scope.filters.duration.params.min)) { continue; } } else if ((!(currTravelTime < $scope.filters.duration.params.max)) || (!(currTravelTime >= $scope.filters.duration.params.min))) { continue; } } // filter by vehicle: if (filterByVehicle) { var car = currTrack.car; var manu = currTrack.manufacturer; var carCombo = manu + "-" + car; if (!$scope.containsVehicle($scope.filters.vehicle.params.cars_set, carCombo)) { continue; } } // filter by spatial: if (filterBySpatial) { var currID = currTrack.id; var found = $scope.filters.spatial.params.track_ids.filter(function (id) { return currID === id; })[0]; if (!found) { continue; } } // if all filters passed, add to resultTracks: resultTracks.push(currTrack); $scope.filtered_tracks++; } $scope.currentPaginationTracks.currentSelectedTracks = resultTracks; // calculate pagination: var number_monthly_tracks = $scope.currentPaginationTracks.currentSelectedTracks.length; $scope.currentPaginationTracks.currentMonthTracks = []; // number pages: $scope.pagingTab.total = Math.ceil(number_monthly_tracks / $scope.itemsPerPage); // take the first $scope.itemsPerPage: for (var i = 0; i < $scope.itemsPerPage && i < number_monthly_tracks; i++) { $scope.currentPaginationTracks.currentMonthTracks.push($scope.currentPaginationTracks.currentSelectedTracks[i]); } $scope.pagingTab.current = 1; loadPages(); $rootScope.$broadcast('filter:spatial-filter-changed'); }; $scope.$on('toolbar:language-changed', function (event, args) { // translate filter labels: $translate([ 'FILTER_DISTANCE', 'FILTER_DATE', 'FILTER_DURATION', 'FILTER_VEHICLE', 'FILTER_SPATIAL']).then( function (translations) { $scope.filters.distance.label = translations['FILTER_DISTANCE']; $scope.filters.date.label = translations['FILTER_DATE']; $scope.filters.duration.label = translations['FILTER_DURATION']; $scope.filters.vehicle.label = translations['FILTER_VEHICLE']; $scope.filters.spatial.label = translations['FILTER_SPATIAL']; }); }); // pagination: $scope.currentPaginationTracks = { currentMonthTracks: [], // all tracks currently shown in current pagination page. currentSelectedTracks: [], // all tracks from this month in the current selection. tracks: [] // all tracks }; $scope.currentPageTab = 0; $scope.pagingTab = { total: 5, current: 1, align: 'center start', onPageChanged: loadPages }; function loadPages() { $scope.currentPageTab = $scope.pagingTab.current; // remove the 1-$scope.itemsPerPage tracks from current pagination page: $scope.currentPaginationTracks.currentMonthTracks = []; var number_monthly_tracks = $scope.currentPaginationTracks.currentSelectedTracks.length; // take the 1-$scope.itemsPerPage from page current and push into currentMonthTracks: for (var i = $scope.itemsPerPage * ($scope.currentPageTab - 1); i < $scope.itemsPerPage * ($scope.currentPageTab) && i < number_monthly_tracks; i++) { $scope.currentPaginationTracks.currentMonthTracks.push($scope.currentPaginationTracks.currentSelectedTracks[i]); } } $scope.tracksPagination = []; if (window.innerHeight > 0) { // calculate pagination: var number_monthly_tracks = $scope.currentPaginationTracks.currentSelectedTracks.length; $scope.currentPaginationTracks.currentMonthTracks = []; // number pages: $scope.pagingTab.total = Math.ceil(number_monthly_tracks / $scope.itemsPerPage); // take the first $scope.itemsPerPage: for (var i = 0; i < $scope.itemsPerPage && i < number_monthly_tracks; i++) { $scope.currentPaginationTracks.currentMonthTracks.push($scope.currentPaginationTracks.currentSelectedTracks[i]); } $scope.pagingTab.current = 1; loadPages(); } $scope.containsVehicle = function (array, car) { var indexLooper = array.length; while (indexLooper--) { if (array[indexLooper] === car) { return true; } } return false; }; // tracks holen: TrackService.getUserTracks($scope.username).then( function (data) { // Erstelle eine Tagestabelle var date_count = []; var tracks = data.data.tracks; // mins and max's for card starting values: $scope.date_min = new Date(tracks[0].begin); $scope.date_max = new Date(tracks[0].begin); $scope.distance_min = parseFloat(tracks[0]['length'].toFixed(2)); $scope.distance_max = parseFloat(tracks[0]['length'].toFixed(2)); var seconds_passed = new Date(tracks[0].end).getTime() - new Date(tracks[0].begin).getTime(); var minutes = seconds_passed / 60000; $scope.duration_min = Math.floor(minutes); $scope.duration_max = Math.ceil(minutes); var contains = function (array, obj) { var i = array.length; while (i--) { if (array[i].year === obj.year && array[i].month === obj.month) { return true; } } return false; }; $scope.filtered_tracks = tracks.length; $scope.tracksPagination = []; for (var i = 0; i < tracks.length; i++) { var currTrack = tracks[i]; // get date of track and increase date_count: var datestart = currTrack['begin']; var dateobject = new Date(datestart); var string_date = dateobject.toString(); var array_string_date = string_date.split(" "); var stripped_date = (array_string_date[1] + array_string_date[2] + array_string_date[3]); if (date_count[stripped_date] !== undefined) { date_count[stripped_date]++; } else { date_count[stripped_date] = 1; } // get track begin date: var currDate = new Date(currTrack.begin); // update date_min and date_max: if (currDate < $scope.date_min) { $scope.date_min = new Date(currDate.getTime()); } if (currDate > $scope.date_max) { $scope.date_max = new Date(currDate.getTime()); } // get current Track's month: var month = currDate.getUTCMonth(); //months from 0-11 var year = currDate.getUTCFullYear(); //year var day = currDate.getDate(); // days from 1-31 var month_year = { 'year': year, 'month': month, 'day': day }; /** if (!contains($scope.monthsWithTracksCalendar, month_year)) { $scope.monthsWithTracksCalendar.push(month_year); }*/ var seconds_passed = new Date(currTrack.end).getTime() - new Date(currTrack.begin).getTime(); var seconds = seconds_passed / 1000; // time of travel is in minutes // convert to the right format. of hh:mm:ss; var date_for_seconds = new Date(null); date_for_seconds.setSeconds(seconds); var date_hh_mm_ss = date_for_seconds.toISOString().substr(11, 8); var travelTime = date_hh_mm_ss; var travelStart = new Date(currTrack.begin); var travelEnd = new Date(currTrack.end); var seconds_passed = new Date(currTrack.end).getTime() - new Date(currTrack.begin).getTime(); var minutes = seconds_passed / 60000; // update distance_min and distance_max: if (minutes < $scope.duration_min) { $scope.duration_min = Math.floor(minutes); } if (minutes > $scope.duration_max) { $scope.duration_max = Math.ceil(minutes); } var carType = currTrack.sensor.properties.model; var carManu = currTrack.sensor.properties.manufacturer; var carCombo = carManu + "-" + carType; if (!$scope.containsVehicle($scope.filters.vehicle.params.cars_all, carCombo)) { $scope.filters.vehicle.params.cars_all.push(carCombo); } ; var resultTrack = { year: year, month: month, day: day, car: carType, manufacturer: carManu, id: currTrack.id, url: ecServerBase + '/tracks/' + currTrack.id + "/preview", travelTime: travelTime, begin: travelStart, end: travelEnd, length: 0 }; if (currTrack.length) { var travelDistance = parseFloat(currTrack['length'].toFixed(2)); // update distance_min and distance_max: if (travelDistance < $scope.distance_min) { $scope.distance_min = travelDistance; } if (travelDistance > $scope.distance_max) { $scope.distance_max = travelDistance; } resultTrack.length = travelDistance; } $scope.tracksPagination.push(resultTrack); } $scope.distance_max = Math.ceil($scope.distance_max); $scope.distance_min = Math.floor($scope.distance_min); // get all tracks from current month&year: $scope.currentPaginationTracks = { currentMonthTracks: [], currentSelectedTracks: [], // all tracks from this month in the current selection. tracks: [] }; for (var i = 0; i < $scope.tracksPagination.length; i++) { var currTrack = $scope.tracksPagination[i]; $scope.currentPaginationTracks.tracks.push(currTrack); $scope.currentPaginationTracks.currentSelectedTracks.push(currTrack); } // calculate pagination: var number_monthly_tracks = $scope.currentPaginationTracks.tracks.length; // number pages: $scope.pagingTab.total = Math.ceil(number_monthly_tracks / $scope.itemsPerPage); // take the first $scope.itemsPerPage: for (var i = 0; i < $scope.itemsPerPage && i < number_monthly_tracks; i++) { $scope.currentPaginationTracks.currentMonthTracks.push($scope.currentPaginationTracks.tracks[i]); } $scope.onload_pagination_tab = true; $rootScope.$broadcast('trackspage:pagination_tab-loaded'); if ($scope.filterOrder.length > 0) if ($scope.filters.spatial.inUse && $scope.filterOrder.length > 1) { $scope.filtersChanged(); } else if (!$scope.filters.spatial.inUse) $scope.filtersChanged(); window.dispatchEvent(new Event('resize')); }, function (data) { console.log("error " + data) } ); } ; angular.module('enviroCar.tracks') .controller('AllTracksPaginationTabCtrl', AllTracksPaginationTabCtrl); })();
function a(){return function(c){var d=Array.prototype.slice.call(arguments,1),b="__"+(c.name||Math.random());return function(){if(arguments.callee[b])return arguments.callee[b];arguments.callee[b]=this;c.apply(this,d.length?d:arguments)}}}"function"===typeof define&&define.amd?define(a):"object"===typeof exports?module.exports=a():this.createSingleton=a();
const models = require('../../models'); let Project = models.projects; let User = models.users; let ProjectAssignment = models.project_assignments; module.exports = function(connection, done) { connection.createChannel(function(err, ch) { console.log(err); var ex = process.env.ex; var queue = 'chiepherd.project_assignment.delete'; ch.assertExchange(ex, 'topic'); ch.assertQueue(queue, { exclusive: false }, function(err, q) { ch.bindQueue(q.queue, ex, queue) ch.consume(q.queue, function(msg) { // LOG console.log(" [%s]: %s", msg.fields.routingKey, msg.content.toString()); let json = JSON.parse(msg.content.toString()); ProjectAssignment.find({ where: { uuid: json.uuid } }).then(function (assignment) { assignment.destroy().then(function (removed) { ch.sendToQueue(msg.properties.replyTo, new Buffer.from(JSON.stringify({ status: 'removed' })), { correlationId: msg.properties.correlationId }); connection.createChannel(function(error, channel) { channel.assertExchange(ex, 'topic'); channel.publish(ex, queue + '.reply', new Buffer(msg.content.toString())); }); ch.ack(msg); }).catch(function (error) { console.log(error); ch.sendToQueue(msg.properties.replyTo, new Buffer(error.toString()), { correlationId: msg.properties.correlationId }); ch.ack(msg); }); }).catch(function (error) { console.log(error); ch.sendToQueue(msg.properties.replyTo, new Buffer(error.toString()), { correlationId: msg.properties.correlationId }); ch.ack(msg); }); }, { noAck: false }); }); }); done(); }
// libraries import { combineReducers } from 'redux'; // Reducers import App from './app'; const rootReducer = combineReducers({ App: App }); export default rootReducer;
import requestToQualifiedRelationQuoted from '../query/requestToQualifiedRelationQuoted'; import requestToWhereClause from '../query/requestToWhereClause'; import sql, {raw as rawSql} from '../sqlTemplate'; export default function requestToDeleteStatement(req) { const qualifiedRelationQuoted = rawSql(requestToQualifiedRelationQuoted(req)); const whereClause = requestToWhereClause(req); return sql `DELETE FROM ${qualifiedRelationQuoted} ${whereClause}`; }
var Knex = require('knex') var knexConfig = require('../knexfile')[process.env.NODE_ENV || 'development'] var knex = Knex(knexConfig) module.exports = { getMinions // isOnsite, // isOffsite } //get all minions function getMinions() { return knex('edaRegister') } // //check if onsite // function isOnsite() { // return knex('edaRegister') // .select('name') // .where('onsite', '=', '1') // } // // //check if offsite // function isOffsite() { // return knex('edaRegister') // .select('name') // .where('onsite', '=', "0") // }
'use strict'; /** * Module dependencies. */ var _ = require('lodash'); var walk = require('walk'); var fs = require('fs'); var path = require('path'); var util = require('./util'); var chalk = require('chalk'); var indexer = { // The JSON of the index. _index: undefined, // Last time the index was // pulled from online. _indexLastUpdate: undefined, // Always wait at least an hour since // the last index.json was pulled // before trying again, unless the // update is forced. _updateInterval: 3600000, // When building your docs with gulp, // you sometimes don't want Wat to // be smart and override your index. updateRemotely: true, init: function init(parent) { this.parent = parent; }, /** * Thump, thump... It's alive! * * @param {Object} options * @return {Indexer} * @api public */ start: function start(options) { var self = this; options = options || {}; if (options.clerk) { indexer.clerk = options.clerk; } if (options.updateRemotely !== undefined) { this.updateRemotely = options.updateRemotely; } if (this.updateRemotely === true) { setInterval(this.update, 3600000); setTimeout(function () { self.update(); }, 6000); } return this; }, /** * Assembles the index based on the ./docs * folder. This needs to be called manually, * and is used by Gulp in rebuilding the * the index after doc work. * * @param {Function} callback * @api public */ build: function build(callback) { callback = callback || {}; var index = {}; var walker = walk.walk(path.normalize(__dirname + '/../docs/'), {}); walker.on('file', function (root, fileStats, next) { var parts = String(path.normalize(root)).split('docs/'); if (parts[1] === undefined) { console.log('Invalid path passed into wat.indexer.build: ' + root); next(); return; } if (String(fileStats.name).indexOf('.json') > -1) { next(); return; } var file = parts[1]; var dirs = String(path.normalize(file)).split('/'); dirs.push(fileStats.name); var remainder = _.clone(dirs); function build(idx, arr) { var item = String(arr.shift()); if (item.indexOf('.md') > -1) { var split = item.split('.'); split.pop(); var last = split[split.length - 1]; var special = split.length > 1 && ['install', 'detail'].indexOf(last) > -1; if (special) { split.pop(); } var type = special ? last : 'basic'; var filename = split.join('.'); idx[filename] = idx[filename] || {}; idx[filename]['__' + type] = fileStats.size; } else { idx[item] = idx[item] || {}; } if (arr.length > 0) { idx[item] = build(idx[item], arr); } return idx; } index = build(index, remainder); next(); }); walker.on('errors', function (root, nodeStatsArray) { console.log(root, nodeStatsArray); throw new Error(root); }); walker.on('end', function () { callback(index); }); }, /** * Writes an index JSON to the disk. * * @param {Object} json * @api public */ write: function write(json) { var index = JSON.stringify(json, null, ''); var result = fs.writeFileSync(__dirname + '/../config/index.json', JSON.stringify(json, null, '')); this._index = json; indexer.clerk.config.setLocal('docIndexLastWrite', new Date()); indexer.clerk.config.setLocal('docIndexSize', String(index).length); return result; }, /** * Retrieves the index.json as it * sees fit. * * @return {Object} json * @api public */ index: function index() { if (!this._index) { try { var index = fs.readFileSync(__dirname + '/../config/index.json', { encoding: 'utf-8' }); var json = JSON.parse(index); this._index = json; } catch (e) { this._index = undefined; return undefined; } } return this._index; }, /** * Pulls the index.json from the * main github doc repo. * * @param {function} callback * @api public */ getRemoteIndex: function getRemoteIndex(callback) { var self = this; util.fetchRemote(self.clerk.paths.remoteConfigUrl + 'index.json', function (err, data) { if (!err) { var err2 = false; var json = undefined; try { json = JSON.parse(data); } catch (e) { err2 = true; callback('Error parsing remote index json: ' + data + ', Error: ' + e + ', url: ' + self.clerk.paths.remoteConfigUrl + 'index.json'); } if (!err2) { callback(undefined, json); } } else { callback(err); } }); }, /** * Interval that checks the * config.json online to see if the * index.json has changed. We go through * this hoop as the index.json will eventually * be huge, and that would be really messed up * to have every wat client on earth * pulling that regardless of updates or * not. And github might sue me. * * If { force: true } is passed in as an * option, update regardless of whether or * not we think the index change or if it's * past curfew. * * @param {Object} options * @api public */ update: function update(options, callback) { options = options || {}; callback = callback || function () {}; var self = indexer; var sinceUpdate = undefined; // If we can't read the file, // assume we just download it newly. try { var stats = fs.statSync(path.join(__dirname, '/../config/index.json')); sinceUpdate = Math.floor(new Date() - stats.mtime); } catch (e) {} if (sinceUpdate > self._updateInterval || !sinceUpdate || options.force === true) { self.clerk.config.getRemote(function (err, remote) { if (!err) { var local = self.clerk.config.getLocal(); var localSize = parseFloat(local.docIndexSize || 0); var remoteSize = parseFloat(remote.docIndexSize || -1); if (localSize !== remoteSize || options.force === true) { self.getRemoteIndex(function (err, index) { if (err) { console.log(err); } else { self.write(index); self.clerk.compareDocs(); callback(undefined, 'Successfully updated index.'); } }); } } else if (String(err).indexOf('Not Found') > -1) { var lellow = chalk.yellow('\nWat could not locate the remote config directory and so does not know where to pull docs from.\nRe-installing your instance of Wat through NPM should solve this problem.'); var error = lellow + '\n\nUrl Attempted: ' + self.clerk.paths.remoteConfigUrl + 'config.json'; console.log(error); throw new Error(err); } else if (err.code === 'EAI_AGAIN') { var error = chalk.yellow('\n\nEr, Wat\'s having DNS resolution errors. Are you sure you\'re connected to the internet?'); console.log(error); throw new Error(err); } else if (err.code === 'ETIMEDOUT') { var error = chalk.yellow('\n\nHmm.. Wat had a connection timeout when trying to fetch its index. \nHow\'s that internet connection looking?'); console.log(error); } else { console.log(chalk.yellow('\nWat had an unexpected error while requesting the remote index:\n')); console.log(err); } }); } } }; module.exports = indexer;
// Regular expression that matches all symbols in the Manichaean block as per Unicode v9.0.0: /\uD802[\uDEC0-\uDEFF]/;
let btn = document.getElementById('btn'); let body = document.body; btn.addEventListener('click', ev => { var popup = new Promise((res, rej) => { btn.disabled = true; let div = document.createElement('div'); div.className += ' popup'; div.innerHTML = 'redirecting to telerik academy'; body.appendChild(div); setTimeout(res, 5000) }) popup.then(() => { window.location = 'http://www.telerikacademy.com'; }) })
//////////////////////////////////////////////// /* Provided Code - Please Don't Edit */ //////////////////////////////////////////////// 'use strict'; function getInput() { console.log("Please choose either 'rock', 'paper', or 'scissors'.") return prompt(); } function randomPlay() { var randomNumber = Math.random(); if (randomNumber < 0.33) { return "rock"; } else if (randomNumber < 0.66) { return "paper"; } else { return "scissors"; } } //////////////////////////////////////////////// /* Write Your Code Below */ //////////////////////////////////////////////// function getPlayerMove(move) { // Write an expression that operates on a variable called `move` // If a `move` has a value, your expression should evaluate to that value. // However, if `move` is not specified / is null, your expression should equal `getInput()`. return move || getInput(); } function getComputerMove(move) { // Write an expression that operates on a variable called `move` // If a `move` has a value, your expression should evaluate to that value. // However, if `move` is not specified / is null, your expression should equal `randomPlay()`. return move || randomPlay(); } function getWinner(playerMove,computerMove) { var winner; // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove. // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'. // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'. if (playerMove == “rock”) { switch (computerMove) { case “rock” : winner = ‘tie’; break; case “paper” : winner = ‘computer; break; case “scissors” : winner = ‘player; break; } } else if (playerMove == “paper”) { switch (computerMove) { case “rock” : winner = ‘player’; break; case “paper” : winner = ‘tie’; break; case “scissors” : winner = ‘computer; break; } } else if (playerMove == “scissors”) { switch (computerMove) { case “rock” : winner = ‘computer’; break; case “paper” : winner = ‘player’; break; case “scissors” : winner = ‘tie’; break; } } return winner; } function playToFive() { console.log("Let's play Rock, Paper, Scissors"); var playerWins = 0; var computerWins = 0; var lastWinner; var playerMove; var computerMove; while ((playerWins < 5) && (computerWins < 5)) { playerMove = getPlayerMove(); computerMove = getComputerMove(); console.log(“Computer chose: “ + computerMove); lastWinner = getWinner(playerMove, computerMove); console.log(“Result of Game: “ + lastWinner); if (lastWinner == ‘player’) {++playerWins;} else if (lastWinner == ‘computer’) {++computerWins} } return [playerWins, computerWins]; }
import '../assets/stylesheets/index.css'; import React from 'react'; import BrowserHistory from 'react-router/lib/BrowserHistory'; import HashHistory from 'react-router/lib/HashHistory'; import Root from './Root'; // Use hash location for Github Pages // but switch to HTML5 history locally. const history = process.env.NODE_ENV === 'production' ? new HashHistory() : new BrowserHistory(); React.render(<Root history={history}/>, document.getElementById('app'));
import gulp from 'gulp' import mocha from 'gulp-mocha' import gutil from 'gulp-util' import babel from 'gulp-babel' gulp.task('test', () => { return gulp.src('./test/**/*.js') .pipe(mocha({ compilers: { js: babel } })) .on('error', gutil.log) }) gulp.task('test:watch', () => { gulp.watch(['./test/**/*.js', './src/**/*.js'], ['test']) })
module.exports = { /** Used to map method names to their aliases. */ 'aliasMap': { 'forEach': ['each'], 'forEachRight': ['eachRight'] }, /** Used to map method names to their iteratee ary. */ 'aryIterateeMap': { 'assignWith': 2, 'cloneDeepWith': 1, 'cloneWith': 1, 'countBy': 1, 'dropRightWhile': 1, 'dropWhile': 1, 'every': 1, 'extendWith': 2, 'filter': 1, 'find': 1, 'findIndex': 1, 'findKey': 1, 'findLast': 1, 'findLastIndex': 1, 'findLastKey': 1, 'forEach': 1, 'forEachRight': 1, 'forIn': 1, 'forInRight': 1, 'forOwn': 1, 'forOwnRight': 1, 'groupBy': 1, 'indexBy': 1, 'isEqualWith': 2, 'isMatchWith': 2, 'map': 1, 'mapKeys': 1, 'mapValues': 1, 'maxBy': 1, 'minBy': 1, 'omitBy': 1, 'partition': 1, 'pickBy': 1, 'reduce': 2, 'reduceRight': 2, 'reject': 1, 'remove': 1, 'some': 1, 'sortBy': 1, 'sortByOrder': 1, 'sortedIndexBy': 1, 'sortedLastIndexBy': 1, 'sumBy': 1, 'takeRightWhile': 1, 'takeWhile': 1, 'times': 1, 'transform': 2, 'uniqBy': 1 }, /** Used to map ary to method names. */ 'aryMethodMap': { 1: ( 'attempt,ceil,create,curry,floor,invert,memoize,method,methodOf,restParam,' + 'round,sample,template,trim,trimLeft,trimRight,words,zipObject').split(','), 2: ( 'ary,assign,at,bind,bindKey,cloneDeepWith,cloneWith,countBy,curryN,debounce,' + 'defaults,defaultsDeep,delay,difference,drop,dropRight,dropRightWhile,' + 'dropWhile,endsWith,every,extend,filter,find,find,findIndex,findKey,findLast,' + 'findLastIndex,findLastKey,forEach,forEachRight,forIn,forInRight,forOwn,' + 'forOwnRight,get,groupBy,includes,indexBy,indexOf,intersection,invoke,' + 'isMatch,lastIndexOf,map,mapKeys,mapValues,maxBy,minBy,merge,omit,pad,padLeft,' + 'padRight,parseInt,partition,pick,pull,pullAt,random,range,rearg,reject,' + 'remove,repeat,result,set,some,sortBy,sortByOrder,sortedIndexBy,sortedLastIndexBy,' + 'sortedUniqBy,startsWith,sumBy,take,takeRight,takeRightWhile,takeWhile,throttle,' + 'times,trunc,union,uniqBy,uniqueId,without,wrap,xor,zip').split(','), 3: ( 'assignWith,extendWith,isEqualWith,isMatchWith,omitBy,pickBy,reduce,' + 'reduceRight,slice,transform,zipWith').split(','), 4: ['fill', 'inRange'] }, /** Used to map ary to rearg configs. */ 'aryReargMap': { 2: [1, 0], 3: [2, 0, 1], 4: [3, 2, 0, 1] }, /** Used to map keys to other keys. */ 'keyMap': { 'curryN': 'curry', 'debounceOpt': 'debounce', 'sampleN': 'sample', 'throttleOpt': 'throttle' }, /** Used to track methods that skip `_.rearg`. */ 'skipReargMap': { 'difference': true, 'range': true, 'random': true, 'zipObject': true } };
import { Animal, AnimalState } from "./animal.js"; import { State } from "./states.js"; import { map, scene, BlockSize } from "./global.js"; import { Block } from "./map.js"; import { Message, MessageTypes, SoundMessage } from "./message.js"; import { Global } from "./global.js"; import { Deer, DeerDead } from "./deer.js"; import { Wave } from "./wave.js"; export class Tiger extends Animal { constructor(id, x, y) { super(id, "tiger"); this.energy = Tiger.EnergyDefault; this.detectDistance = Tiger.DetectDistance; this.visualRange.distance = Tiger.VisualDistance; this.visualRange.ang = Tiger.VisualAngle; var pol = new Polygon([new Point(15, 0), new Point(-12.5, -12.5), new Point(-12.5, 12.5)]); pol.fillStyle = "#ffdfa6"; pol.strokeStyle = "rgba(0,0,0,0)"; this.gameObject.graphic = pol; this.gameObject.collider = pol; this.gameObject.mass = 2; this.gameObject.collider.rigidBody = true; //scene.addGameObject(this.gameObject, 1); this.gameObject.moveTo(x, y); } onMessage(message) { } onDisplay() { this.changeState(new TigerWander(this)); } isHungry() { return (this.energy < Tiger.EnergyDefault - 5000000); } isFull() { return (this.energy > Tiger.EnergyDefault); } seekFood() { } /** * * @param {Animal} target */ checkFood(target) { return (target.state instanceof DeerDead && target.energy > 0); } static get DetectDistance() { return 200; } static get VisualDistance() { return 200; } static get VisualAngle() { return Math.PI / 3; } static get MemoryTime() { return 10; } static get MaxChaseTime() { return 10000; } static get EnergyDefault() { return 500000000; } } export class TigerGlobal extends State { update(dt) { } onEnter(previousState) { } onExit(nextState) { } constructor(tiger) { super(tiger); } } export class TigerWander extends State { /** * * @param {Tiger} tiger */ constructor(tiger) { super(tiger); this.animal = tiger; this.maxPower = 40000; this.power = 0; this.maxTurn = 0.1; this.maxForce = 5000; this.visualDistance = Tiger.VisualDistance; this.visualAngle = Tiger.VisualAngle; } update(dt) { if (this.animal.isHungry()) { this.animal.changeState(new TigerForge(this.animal)); return; } if (this.direction) this.animal.moveTo(this.direction, this.power, this.maxForce, this.maxTurn, dt); } AIUpdate() { if (this.disposed) return; // Visual this.animal.clearMemory(); this.animal.visual(this.visualDistance, this.visualAngle); // Guard for (let i = 0; i < this.animal.positionMemory.length; i++) { var memory = this.animal.positionMemory[i]; if (memory.entity instanceof Deer && memory.entity.HP>0) { this.animal.changeState(new TigerForge(this.animal)); return; } else if (this.animal.checkFood(memory.entity)) { this.animal.changeState(new TigerEat(this.animal, memory.entity)); return; } } let state = this; setTimeout(function() { state.AIUpdate.call(state); }, 100); } onEnter(previousState) { this.nextTarget(); this.AIUpdate(); } onExit(nextState) { this.animal = null; } nextTarget() { if (!this.animal) return; if (Math.random() < 0.75) { this.direction = this.animal.randomDirection(); this.power = this.maxPower * Math.random(); } else this.direction = null; var state = this; setTimeout(function () { state.nextTarget.call(state); }, 1000 + 2000 * Math.random()); } } export class TigerForge extends AnimalState { /** * * @param {Tiger} tiger */ constructor(tiger) { super(tiger) this.direction = null; this.visualDistance = Tiger.VisualDistance * 1.5; this.visualAngle = Math.PI * 2 / 3; this.power = 50000; this.maxTurn = 0.1; this.maxForce = 5000; } update(dt) { if (this.direction && this.animal.moveTo(this.direction,this.power,this.maxForce,this.maxTurn,dt)) { this.direction = null; } } AIUpdate() { if (this.disposed) return; // Visual this.animal.clearMemory(); this.animal.visual(this.visualDistance, this.visualAngle); // Guard let chaseList = []; for (let i = 0; i < this.animal.positionMemory.length; i++) { var memory = this.animal.positionMemory[i]; if (memory.entity instanceof Deer) { chaseList[chaseList.length] = memory.entity; } } // Lock target let minDist = Number.MAX_SAFE_INTEGER; let nearestTarget = null; for (let i = 0; i < chaseList.length; i++) { let target = chaseList[i]; let distance = Vector2.minus(target.position, this.animal.position).mod(); if (distance < minDist) { minDist = distance; nearestTarget = target; } } if (nearestTarget) { this.animal.changeState(new TigerAttack(this.animal, nearestTarget)); return; } } nextTarget() { if (!this.disposed) return; this.direction = this.animal.randomDirection(); var state = this; setTimeout(function () { state.nextTarget.call(state); }, 1000 * Math.random()); } onEnter(previousState) { this.AIUpdate(); this.nextTarget(); } } export class TigerAttack extends AnimalState { /** * * @param {Tiger} tiger * @param {Deer} target */ constructor(tiger, target) { super(tiger); this.target = target; this.lostTarget = false; this.direction = null; this.damage = 30; this.power = 100000; this.maxForce = 10000; this.maxTurn = 0.05; this.visualDistance = Tiger.visualDistance * 1.5; this.visualRange = Math.PI; this.startTime = 0; } update(dt) { if (this.direction) { this.animal.moveTo(this.direction, this.animal.powerLimit(this.power, Tiger.EnergyDefault), this.maxForce, this.maxTurn, dt); } // Attack if (this.animal.attack(this.target, this.damage)) { this.animal.gameObject.collider.collide(this.animal.gameObject, this.target.gameObject, dt); var wave = new Wave(Global.RegisterID(), this.animal.position.x, this.animal.position.y, 50, 100); wave.color = new Color(255, 0, 0, 0.1); Global.AddEntity(wave); } } AIUpdate() { if (this.disposed) return true; // Visual this.animal.visual(this.visualDistance, this.visualRange); // Guard this.lostTarget = true; for (let i = 0; i < this.animal.positionMemory.length; i++) { var memory = this.animal.positionMemory[i]; if (memory.entity === this.target && !memory.isExpired(Tiger.MemoryTime)) { this.lostTarget = false; } } if (this.lostTarget) { this.animal.changeState(new TigerWander(this.animal)); return; } // Check alive if (this.target.state instanceof DeerDead) { this.animal.changeState(new TigerEat(this.animal, this.target)); return; } // Chase this.direction = this.animal.chase(this.target); // Give up if (new Date().getTime() - this.startTime > Tiger.MaxChaseTime) { this.animal.changeState(new TigerWander(this.animal)); return; } let state = this; setTimeout(function() { state.AIUpdate.call(state); }, 100); } onEnter(previousState) { this.startTime = new Date().getTime(); this.AIUpdate(); } } export class TigerEat extends AnimalState { /** * * @param {Tiger} tiger * @param {Animal} food */ constructor(tiger, food) { super(tiger); this.food = food; this.visualDistance = Tiger.visualDistance * 0.5; this.visualAngle = Math.PI / 6; this.power = 100000; this.maxForce = 10000; this.maxTurn = 0.15; this.eatSpeed = 10000000; } update(dt) { if (this.animal.gameObject.graphic.isCollideWith(this.food.gameObject.graphic)) { var eat = this.eatSpeed * dt; if (this.food.energy < eat) eat = this.food.energy; this.food.energy -= eat; this.animal.energy += eat / 10; if (this.food.energy <= 0) { this.animal.changeState(new TigerWander(this.animal)); return; } } else this.animal.moveTo(this.food.position, this.power, this.maxForce, this.maxTurn, dt); } AIUpdate() { if (this.disposed) return; // Visual this.animal.visual(this.visualDistance, this.visualAngle); // Guard for (let i = 0; i < this.animal.positionMemory.length; i++) { var memory = this.animal.positionMemory[i]; /* Check danger */ } let state = this; setTimeout(function() { state.AIUpdate.call(state); }, 100); } onEnter() { this.AIUpdate(); } } export class TigerCautious extends State { constructor(tiger) { super(tiger); } } export class TigerInDanger extends State { constructor(tiger) { super(tiger); } }
'use strict'; /** * Module dependencies. */ var config = require('../config'), chalk = require('chalk'), path = require('path'), _ = require('lodash'), mongoose = require('mongoose'); mongoose.Promise = global.Promise; // Load the mongoose models module.exports.loadModels = function() { // Globbing model files config.files.server.models.forEach(function(modelPath) { require(path.resolve(modelPath)); }); }; // Initialize Mongoose module.exports.connect = function(cb) { var _this = this; var db = mongoose.connect(config.mongo.uri, function (err) { // Log Error if (err) { console.error(chalk.red('Could not connect to MongoDB!')); console.log('tried: "%s"\n got: "%s"',config.mongo.uri, err); console.log('Maybe you need to set MONGO_HOST_VAR to one of these:'); _(process.env) .pick(function(v,k) { return k.match( /pass/i ) ? false : k.match( /mongo/i ); }) .toPairs() .forEach(function(p) { console.log(' ',p); }); } else { // Load modules _this.loadModels(); // Call callback FN if (cb) cb(db); } }); }; module.exports.disconnect = function(cb) { mongoose.disconnect(function(err) { console.info(chalk.yellow('Disconnected from MongoDB.')); cb(err); }); };
"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); }; require("bootstrap/dist/css/bootstrap.css"); require("font-awesome/css/font-awesome.css"); require("highlight.js/styles/github.css"); require("../scss/angular-calendar.scss"); require("intl"); require("intl/locale-data/jsonp/en"); var core_1 = require("@angular/core"); var router_1 = require("@angular/router"); var platform_browser_1 = require("@angular/platform-browser"); var hljs = require("highlight.js"); var angular_highlight_js_1 = require("angular-highlight-js"); var demo_app_component_1 = require("./demo-app.component"); var kitchenSink = require("./demo-modules/kitchen-sink"); var asyncEvents = require("./demo-modules/async-events"); var addEventButton = require("./demo-modules/add-event-button"); var optionalEventEndDates = require("./demo-modules/optional-event-end-dates"); var editableDeletableEvents = require("./demo-modules/editable-deletable-events"); var draggableEvents = require("./demo-modules/draggable-events"); var resizableEvents = require("./demo-modules/resizable-events"); var monthViewBadgeTotal = require("./demo-modules/month-view-badge-total"); var recurringEvents = require("./demo-modules/recurring-events"); var customEventClass = require("./demo-modules/custom-event-class"); var clickableEvents = require("./demo-modules/clickable-events"); var dayClick = require("./demo-modules/day-click"); var dayViewStartEnd = require("./demo-modules/day-view-start-end"); var dayViewHourSplit = require("./demo-modules/day-view-hour-split"); var navigatingBetweenViews = require("./demo-modules/navigating-between-views"); var dayModifier = require("./demo-modules/day-modifier"); var i18n = require("./demo-modules/i18n"); var draggableExternalEvents = require("./demo-modules/draggable-external-events"); var allDayEvents = require("./demo-modules/all-day-events"); var customiseDateFormats = require("./demo-modules/customise-date-formats"); var showDatesOnTitles = require("./demo-modules/show-dates-on-titles"); var disableTooltips = require("./demo-modules/disable-tooltips"); var additionalEventProperties = require("./demo-modules/additional-event-properties"); var selectableMonthDay = require("./demo-modules/selectable-month-day"); var minMaxDate = require("./demo-modules/min-max-date"); var DemoAppModule = (function () { function DemoAppModule() { } return DemoAppModule; }()); DemoAppModule = __decorate([ core_1.NgModule({ declarations: [demo_app_component_1.DemoAppComponent], imports: [ platform_browser_1.BrowserModule, angular_highlight_js_1.HighlightJsModule.forRoot(hljs), kitchenSink.DemoModule, addEventButton.DemoModule, asyncEvents.DemoModule, optionalEventEndDates.DemoModule, editableDeletableEvents.DemoModule, draggableEvents.DemoModule, resizableEvents.DemoModule, monthViewBadgeTotal.DemoModule, recurringEvents.DemoModule, customEventClass.DemoModule, clickableEvents.DemoModule, dayClick.DemoModule, dayViewStartEnd.DemoModule, dayViewHourSplit.DemoModule, navigatingBetweenViews.DemoModule, dayModifier.DemoModule, i18n.DemoModule, draggableExternalEvents.DemoModule, allDayEvents.DemoModule, customiseDateFormats.DemoModule, showDatesOnTitles.DemoModule, disableTooltips.DemoModule, additionalEventProperties.DemoModule, selectableMonthDay.DemoModule, minMaxDate.DemoModule, router_1.RouterModule.forRoot([{ path: 'kitchen-sink', component: kitchenSink.DemoComponent, data: { label: 'Kitchen sink' } }, { path: 'add-event-button', component: addEventButton.DemoComponent, data: { label: 'Add event Button in (mouseenter) month day ' } }, { path: 'async-events', component: asyncEvents.DemoComponent, data: { label: 'Async events' } }, { path: 'optional-event-end-dates', component: optionalEventEndDates.DemoComponent, data: { label: 'Optional event end dates' } }, { path: 'editable-deletable-events', component: editableDeletableEvents.DemoComponent, data: { label: 'Editable / deletable events' } }, { path: 'draggable-events', component: draggableEvents.DemoComponent, data: { label: 'Draggable events' } }, { path: 'resizable-events', component: resizableEvents.DemoComponent, data: { label: 'Resizable events' } }, { path: 'month-view-badge-total', component: monthViewBadgeTotal.DemoComponent, data: { label: 'Month view badge total' } }, { path: 'recurring-events', component: recurringEvents.DemoComponent, data: { label: 'Recurring events' } }, { path: 'custom-event-class', component: customEventClass.DemoComponent, data: { label: 'Custom event class' } }, { path: 'clickable-events', component: clickableEvents.DemoComponent, data: { label: 'Clickable events' } }, { path: 'clickable-days', component: dayClick.DemoComponent, data: { label: 'Clickable days' } }, { path: 'day-view-start-end', component: dayViewStartEnd.DemoComponent, data: { label: 'Day view start / end time' } }, { path: 'day-view-hour-split', component: dayViewHourSplit.DemoComponent, data: { label: 'Day view hour split' } }, { path: 'navigating-between-views', component: navigatingBetweenViews.DemoComponent, data: { label: 'Navigating between views' } }, { path: 'day-modifier', component: dayModifier.DemoComponent, data: { label: 'Day modifier' } }, { path: 'i18n', component: i18n.DemoComponent, data: { label: 'Internationalisation' } }, { path: 'draggable-external-events', component: draggableExternalEvents.DemoComponent, data: { label: 'Draggable external events' } }, { path: 'all-day-events', component: allDayEvents.DemoComponent, data: { label: 'All day events' } }, { path: 'customise-date-formats', component: customiseDateFormats.DemoComponent, data: { label: 'Customise date formats' } }, { path: 'show-dates-on-titles', component: showDatesOnTitles.DemoComponent, data: { label: 'Show dates on title' } }, { path: 'disable-tooltips', component: disableTooltips.DemoComponent, data: { label: 'Disable tooltips' } }, { path: 'additional-event-properties', component: additionalEventProperties.DemoComponent, data: { label: 'Additional event properties' } }, { path: 'selectable-month-day', component: selectableMonthDay.DemoComponent, data: { label: 'Selectable month day' } }, { path: 'min-max-date', component: minMaxDate.DemoComponent, data: { label: 'Min max date' } }, { path: '**', redirectTo: 'kitchen-sink' }], { useHash: true }) ], bootstrap: [demo_app_component_1.DemoAppComponent] }), __metadata("design:paramtypes", []) ], DemoAppModule); exports.DemoAppModule = DemoAppModule; //# sourceMappingURL=demo-app.module.js.map
#!/usr/bin/env node let http = require('http'), cp = require('child_process'), qs = require('querystring'), result = ''; http.createServer((req, res) => { if(req.url != '/') { err(res); return; } console.log(req.headers); console.log(''); switch(req.method) { case 'GET': show(res); break; case 'POST': execCmd(req, res); break; default: err(res); break; } }).listen(8080); function err(res) { const msg = 'Not found'; res.statusCode = 404; res.setHeader('Content-Length', msg.length); res.setHeader('Content-Type', 'text/plain'); res.end(msg); } function show(res) { let html = ` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>execute linux command</title> </head> <body> <h1>Input a Linux Command</h1> <form method="post" action="/"> <p><input type="text" name="cmd" /> <input type="submit" value="execute" /></p> </form> <div><pre style="font-family: Consolas;">${result}</pre></div> </body> </html>`; res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); res.setHeader('Content-Length', Buffer.byteLength(html)); res.end(html); } function execCmd(req, res) { let cmd = ''; req.on('data', chunk => cmd += chunk); req.on('end', () => { cmd = qs.parse(cmd).cmd; if(cmd === '') { result = 'Please input linux command'; show(res); } else { console.log(cmd); cp.exec(cmd, (err, stdout, stderr) => { result = (err === null) ? stdout : stderr; show(res); }); } }); }
import {partial} from 'lodash' export function register (method, path, ...middleware) { return (target, key) => { const { routes = [] } = target routes.push({ path, method, middleware, action: key }) target.routes = routes } } export const all = partial(register, 'all') export const get = partial(register, 'get') export const post = partial(register, 'post') export const put = partial(register, 'put') export const patch = partial(register, 'patch') export const del = partial(register, 'delete') export function blueprint (path, ...middleware) { return target => { target.prototype.prefix = path target.prototype.middleware = middleware } } export const prefix = blueprint
import ExtandableError from 'es6-error'; class ActionCreatorError extends ExtandableError { constructor(message, {actionCreator, actionType, data}) { super(message); this.action = { creator: actionCreator , type : actionType}; this.data = data; } } export default ActionCreatorError;
/** * File socket.js * Service class for Socket */ angular.module('services.socket', []); angular.module('services.socket').factory('socketContainer', function(){ var socket = io(); var socketService = {}; socketService.getSocket = function() { return socket; }; return socketService; });
/* jshint devel: true */ /* jshint browser: true */ /* jshint -W097 */ /* global io */ "use strict"; // TODO: Fix shell offset when turret rotated var imageScale = 0.20; var shellRange = 10000; var traverseSpeed = 0.03; var turretSpeed = 0.03; var fireWaitDelay_ms = 2000; var tankUpdateThreshold_ms = 5000; var canvas = document.getElementById("tankCanvas"); var context = canvas.getContext('2d'); var socket = io(); var shells = []; var downKeys = {}; var lastTankUpdate = new Date(); var lastShotTime = new Date(); var bodyImage = new Image(); var turretImage = new Image(); var shellImage = new Image(); var tanks = {}; var dirty = true; var localTank = { id: "" + Math.random(), x: 500, y: 500, bodyRotation: 1.0, turretRotation: 0.0 }; function drawCaptureCircle() { context.beginPath(); context.arc(95, 50, 40, 0, 2 * Math.PI); context.stroke(); } function drawTank(tank) { context.save(); context.scale(imageScale, imageScale); context.translate(tank.x, tank.y); context.rotate(tank.bodyRotation); context.save(); context.translate( -bodyImage.width / 2, -bodyImage.height / 2); context.drawImage(bodyImage, 0, 0); context.restore(); context.translate( 0, -70); context.rotate(tank.turretRotation); context.translate( -turretImage.width / 2, -turretImage.height / 2 - 50); context.drawImage(turretImage, 0, 0); context.restore(); } function drawTanks() { for (var key in tanks) { var tank = tanks[key]; drawTank(tank); } } function drawShell(shell) { context.save(); context.scale(imageScale, imageScale); context.translate(shell.x, shell.y); context.rotate(shell.direction); context.drawImage(shellImage, 0, 0); context.restore(); // context.beginPath(); // context.arc(shell.x * imageScale, shell.y * imageScale, 4, 0, 2 * Math.PI); // context.stroke(); } function drawShells() { for (var shellIndex in shells) { var shell = shells[shellIndex]; drawShell(shell); } } function moveTank(tank, distance) { tank.x = tank.x + distance * Math.cos(tank.bodyRotation - 3.14159265 * 0.5); tank.y = tank.y + distance * Math.sin(tank.bodyRotation - 3.14159265 * 0.5); dirty = true; } function moveShell(shell, distance) { shell.x = shell.x + distance * Math.cos(shell.direction - 3.14159265 * 0.5); shell.y = shell.y + distance * Math.sin(shell.direction - 3.14159265 * 0.5); shell.distance += distance; if (shell.distance > shellRange) return false; return true; } function fire(tank) { var barrelLength = 450; // var x = tank.x + -70 * Math.cos(shell.direction - 3.14159265 * 0.5) + var shell = {x: tank.x, y: tank.y, direction: tank.bodyRotation + tank.turretRotation, distance: 0.0}; moveShell(shell, barrelLength); shells.push(shell); dirty = true; } function incrementShells() { var hadShells = shells.length; var shellsToKeep = []; var shellIndex; for (shellIndex in shells) { var shell = shells[shellIndex]; var keep = moveShell(shell, 100); if (keep) shellsToKeep.push(shell); } shells = shellsToKeep; return hadShells; } function rotateTank(tank, amount) { tank.bodyRotation = tank.bodyRotation + amount; dirty = true; } function rotateTurret(tank, amount) { tank.turretRotation = tank.turretRotation + amount; dirty = true; } function keypress(keyCode) { var tank = localTank; // console.log("keypress event detected: ", key); if (keyCode === 65) { socket.emit('rotateTank', {id: localTank.id, amount: -traverseSpeed}); rotateTank(tank, -traverseSpeed); } else if (keyCode === 68) { socket.emit('rotateTank', {id: localTank.id, amount: traverseSpeed}); rotateTank(tank, traverseSpeed); } else if (keyCode === 87) { socket.emit('moveTank', {id: localTank.id, amount: 10}); moveTank(tank, 10); } else if (keyCode === 83) { socket.emit('moveTank', {id: localTank.id, amount: -10}); moveTank(tank, -10); } else if (keyCode === 37) { socket.emit('rotateTurret', {id: localTank.id, amount: -turretSpeed}); rotateTurret(tank, -turretSpeed); } else if (keyCode === 39) { socket.emit('rotateTurret', {id: localTank.id, amount: turretSpeed}); rotateTurret(tank, turretSpeed); } else if (keyCode === 32) { var now = new Date(); var fireWait_ms = now.getTime() - lastShotTime.getTime(); if (fireWait_ms < fireWaitDelay_ms) return; lastShotTime = now; socket.emit('fire', {id: localTank.id}); fire(tank); } } function keydown(event) { var keyCode = event.keyCode; // console.log("keydown", event, keyCode); downKeys["" + keyCode] = keyCode; keypress(keyCode); drawAll(); } function keyup(event) { var keyCode = event.keyCode; // console.log("keyup", event, keyCode); delete downKeys["" + keyCode]; } function drawAll() { context.clearRect(0 , 0, canvas.width, canvas.height); drawCaptureCircle(); drawTanks(); drawShells(); dirty = false; } function timerTick() { var redrawNeeded = incrementShells(); for (var key in downKeys) { redrawNeeded = true; keypress(downKeys[key]); } if (dirty) redrawNeeded = true; if (redrawNeeded) drawAll(); var now = new Date(); var lastUpdateGap_ms = now.getTime() - lastTankUpdate.getTime(); if (lastUpdateGap_ms > tankUpdateThreshold_ms) { socket.emit('tank', localTank); lastTankUpdate = new Date(); } } function tankForID(id) { // console.log("tankForID", id, tanks[id]); return tanks[id]; } function setup() { tanks[localTank.id] = localTank; bodyImage.src = 'images/hullv1.png'; turretImage.src = 'images/tank1imageturretv2.png'; shellImage.src = 'images/shell.png'; window.onkeydown = keydown; window.onkeyup = keyup; window.setInterval(timerTick, 100); socket.on('rotateTank', function(message) { // console.log("rotateTank", message); var tank = tankForID(message.id); if (tank && message.id !== localTank.id) rotateTank(tank, message.amount); }); socket.on('moveTank', function(message) { // console.log("moveTank", message); var tank = tankForID(message.id); if (tank && message.id !== localTank.id) moveTank(tank, message.amount); }); socket.on('rotateTurret', function(message) { // console.log("rotateTurret", message); var tank = tankForID(message.id); if (tank && message.id !== localTank.id) rotateTurret(tank, message.amount); }); socket.on('fire', function(message) { // console.log("fire", message); var tank = tankForID(message.id); if (tank && message.id !== localTank.id && tanks) fire(tank); }); socket.on('tank', function(message) { // console.log("tank", message); if (message.id !== localTank.id) { tanks[message.id] = message; dirty = true; } }); } setup(); drawAll();
exports.domain = 'http://api.douban.com'; exports.res = [{ route: '/book/:id', method: 'GET', url: '/v2/book/1220562', params: [{ name: 'id', type: 'Number', maxLength: 10, minLength: 6, reg: /^\d{6,10}$/, message: '必须是6-10位的数字' }] }];
var m = require('mithril') var Tabs = require('./tabs') var Sidebar = require('./sidebar') var Footer = require('./footer') var Details = require('./details') var Preferences = require('./preferences') var Loading = require('./loading') var rendererStore = require('../rendererStore'); var config = require('electron').remote.getGlobal('config'); var root = document.body var stateData = rendererStore.getState(); var unsubscribe = rendererStore.subscribe(function() { stateData = rendererStore.getState(); m.redraw(); }); var Main = { view: function() { var overlayEl = undefined, overlayCSS = { height: '0%' }; if (stateData.overlay.type) { overlayCSS.height = '100%'; } if (stateData.overlay.type === 'preferences') { overlayEl = m(Preferences, {stateData: stateData}); } else if (stateData.overlay.type === 'loading') { overlayCSS.transition = 'none'; overlayCSS['background-color'] = '#bb2f2b'; overlayEl = m(Loading, {stateData: stateData}); } else if (stateData.overlay.type === 'details') { overlayEl = m(Details, {stateData: stateData}); } return m(".main", [ m(Sidebar, {stateData: stateData}), m('div.overlay', {style: overlayCSS}, [ overlayEl ]), m(Tabs, {stateData: stateData}) ]) } } m.mount(root, Main)
module.exports = function(params, dynamo) { return dynamo.raw.deleteTable(params).promise().then(function (response) { return response; }); };
var Cachematrix; (function (Cachematrix) { var WeatherApp; (function (WeatherApp) { var ViewModels; (function (ViewModels) { var HomePageVM = (function () { function HomePageVM(data) { var _this = this; this.today = ko.computed({ read: function () { return _this.days[0]; }, deferEvaluation: true }); this.tomorrow = ko.computed({ read: function () { return _this.days[1]; }, deferEvaluation: true }); this.dayAfterTomorrow = ko.computed({ read: function () { return _this.days[2]; }, deferEvaluation: true }); this.currentConditions = new ViewModels.CurrentConditionsVM(data.currentConditions); this.days = _.map(data.days, function (day) { return new ViewModels.DayVM(day); }); } HomePageVM.prototype.init = function () { //Nothing to do here }; return HomePageVM; })(); ViewModels.HomePageVM = HomePageVM; })(ViewModels = WeatherApp.ViewModels || (WeatherApp.ViewModels = {})); })(WeatherApp = Cachematrix.WeatherApp || (Cachematrix.WeatherApp = {})); })(Cachematrix || (Cachematrix = {})); //# sourceMappingURL=HomePageVM.js.map
import 'src/style/index.css'; import 'modules/env'; import ReactDOM from 'react-dom'; import { loadableReady } from '@loadable/component'; import App from './App'; import AppError from 'components/AppError'; const elRoot = document.getElementById('app'); const render = (Component) => { // eslint-disable-next-line no-undef if (__SSR__) { console.log('in SSR mode'); loadableReady(() => { ReactDOM.hydrate( <AppError> <Component /> </AppError>, elRoot, ); }); return; } ReactDOM.render( <AppError> <Component /> </AppError>, elRoot, ); }; render(App); // Webpack Hot Module Replacement API if (module.hot) { module.hot.accept('./App', () => { render(require('./App').default); }); // module.hot.check().then(modules => { // console.log('modules: ', modules); // }); // module.hot.addStatusHandler((status) => { // console.log('status: ', status); // if (status === 'idle') { // // window.location.reload() // } // }) }
import Directive from '../../directive' import { replace, getAttr, isFragment } from '../../util/index' import { compile, compileRoot, transclude } from '../../compiler/index' export default function (Vue) { /** * Update v-ref for component. * * @param {Boolean} remove */ Vue.prototype._updateRef = function (remove) { var ref = this.$options._ref if (ref) { var refs = (this._scope || this._context).$refs if (remove) { if (refs[ref] === this) { refs[ref] = null } } else { refs[ref] = this } } } /** * Transclude, compile and link element. * * If a pre-compiled linker is available, that means the * passed in element will be pre-transcluded and compiled * as well - all we need to do is to call the linker. * * Otherwise we need to call transclude/compile/link here. * * @param {Element} el */ Vue.prototype._compile = function (el) { var options = this.$options // transclude and init element // transclude can potentially replace original // so we need to keep reference; this step also injects // the template and caches the original attributes // on the container node and replacer node. var original = el el = transclude(el, options) this._initElement(el) // handle v-pre on root node (#2026) if (el.nodeType === 1 && getAttr(el, 'v-pre') !== null) { return } // root is always compiled per-instance, because // container attrs and props can be different every time. var contextOptions = this._context && this._context.$options var rootLinker = compileRoot(el, options, contextOptions) // compile and link the rest var contentLinkFn var ctor = this.constructor // component compilation can be cached // as long as it's not using inline-template if (options._linkerCachable) { contentLinkFn = ctor.linker if (!contentLinkFn) { contentLinkFn = ctor.linker = compile(el, options) } } // link phase // make sure to link root with prop scope! var rootUnlinkFn = rootLinker(this, el, this._scope) var contentUnlinkFn = contentLinkFn ? contentLinkFn(this, el) : compile(el, options)(this, el) // register composite unlink function // to be called during instance destruction this._unlinkFn = function () { rootUnlinkFn() // passing destroying: true to avoid searching and // splicing the directives contentUnlinkFn(true) } // finally replace original if (options.replace) { replace(original, el) } this._isCompiled = true this._callHook('compiled') } /** * Initialize instance element. Called in the public * $mount() method. * * @param {Element} el */ Vue.prototype._initElement = function (el) { if (isFragment(el)) { this._isFragment = true this.$el = this._fragmentStart = el.firstChild this._fragmentEnd = el.lastChild // set persisted text anchors to empty if (this._fragmentStart.nodeType === 3) { this._fragmentStart.data = this._fragmentEnd.data = '' } this._fragment = el } else { this.$el = el } this.$el.__vue__ = this this._callHook('beforeCompile') } /** * Create and bind a directive to an element. * * @param {String} name - directive name * @param {Node} node - target node * @param {Object} desc - parsed directive descriptor * @param {Object} def - directive definition object * @param {Vue} [host] - transclusion host component * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - owner fragment */ Vue.prototype._bindDir = function (descriptor, node, host, scope, frag) { this._directives.push( new Directive(descriptor, this, node, host, scope, frag) ) } /** * Teardown an instance, unobserves the data, unbind all the * directives, turn off all the event listeners, etc. * * @param {Boolean} remove - whether to remove the DOM node. * @param {Boolean} deferCleanup - if true, defer cleanup to * be called later */ Vue.prototype._destroy = function (remove, deferCleanup) { if (this._isBeingDestroyed) { if (!deferCleanup) { this._cleanup() } return } var destroyReady var pendingRemoval var self = this // Cleanup should be called either synchronously or asynchronoysly as // callback of this.$remove(), or if remove and deferCleanup are false. // In any case it should be called after all other removing, unbinding and // turning of is done var cleanupIfPossible = function () { if (destroyReady && !pendingRemoval && !deferCleanup) { self._cleanup() } } // remove DOM element if (remove && this.$el) { pendingRemoval = true this.$remove(function () { pendingRemoval = false cleanupIfPossible() }) } this._callHook('beforeDestroy') this._isBeingDestroyed = true var i // remove self from parent. only necessary // if parent is not being destroyed as well. var parent = this.$parent if (parent && !parent._isBeingDestroyed) { parent.$children.$remove(this) // unregister ref (remove: true) this._updateRef(true) } // destroy all children. i = this.$children.length while (i--) { this.$children[i].$destroy() } // teardown props if (this._propsUnlinkFn) { this._propsUnlinkFn() } // teardown all directives. this also tearsdown all // directive-owned watchers. if (this._unlinkFn) { this._unlinkFn() } i = this._watchers.length while (i--) { this._watchers[i].teardown() } // remove reference to self on $el if (this.$el) { this.$el.__vue__ = null } destroyReady = true cleanupIfPossible() } /** * Clean up to ensure garbage collection. * This is called after the leave transition if there * is any. */ Vue.prototype._cleanup = function () { if (this._isDestroyed) { return } // remove self from owner fragment // do it in cleanup so that we can call $destroy with // defer right when a fragment is about to be removed. if (this._frag) { this._frag.children.$remove(this) } // remove reference from data ob // frozen object may not have observer. if (this._data.__ob__) { this._data.__ob__.removeVm(this) } // Clean up references to private properties and other // instances. preserve reference to _data so that proxy // accessors still work. The only potential side effect // here is that mutating the instance after it's destroyed // may affect the state of other components that are still // observing the same object, but that seems to be a // reasonable responsibility for the user rather than // always throwing an error on them. this.$el = this.$parent = this.$root = this.$children = this._watchers = this._context = this._scope = this._directives = null // call the last hook... this._isDestroyed = true this._callHook('destroyed') // turn off all instance listeners. this.$off() } }
import React from 'react'; import PropTypes from 'prop-types'; import BaseView from '../../utils/rnw-compat/BaseView'; const propTypes = { children: PropTypes.node.isRequired, }; const ToastHeader = React.forwardRef((props, ref) => ( <BaseView {...props} ref={ref} essentials={{ className: 'toast-header' }} /> )); ToastHeader.displayName = 'ToastHeader'; ToastHeader.propTypes = propTypes; export default ToastHeader;
let config = { TOTAL_DURATION: 20, // in seconds BASE_FREQ: 35, COL_COUNT: 40, ROW_COUNT: 30, BOARD_WIDTH: 2000, BOARD_HEIGHT: 1500, VISUALIZER_FRAME_RATE: 50, gridlines: false, midify: false, frequencies: false, paletteLabels: false, scales: { aeolian: [0, 2, 3, 5, 7, 8, 10], blues: [0, 3, 5, 6, 7, 10], fourths: [0, 4, 8], ionian: [0, 2, 4, 5, 7, 9, 11], gypsyMinor: [0, 2, 3, 6, 7, 8, 11], pentatonic: [0, 2, 4, 7, 9], pentMinor: [0, 3, 5, 7, 10, 12], yo: [0, 2, 5, 7, 9, 12], // chords majI: [0, 5, 7], minII: [2, 5, 9], minIII: [4, 7, 11], majIV: [5, 9, 12], majV: [2, 7, 11], minVI: [0, 4, 9], minVIIdim: [4, 7, 11], }, } config['PXLS_PER_COL'] = Math.floor(config.BOARD_WIDTH / config.COL_COUNT); config['PXLS_PER_ROW'] = Math.floor(config.BOARD_HEIGHT / config.ROW_COUNT); let makeFactor = function(candidate, product){ let attemptFactor = function(_candidate){ if (product % _candidate === 0) { return _candidate; } else{ return attemptFactor(_candidate + 1); } } return attemptFactor(candidate); } // PXL_COL_CHKPTS is important as it should be the max value for a quadrant, i.e. if markings were found at all checkpoints config['PXL_COL_CHKPTS'] = makeFactor(10, config.PXLS_PER_ROW); config['PXL_ROW_CHKPTS'] = makeFactor(10, config.PXLS_PER_ROW); module.exports = config;
// Load required packages var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); // Define our user schema var UserSchema = new mongoose.Schema({ username: { type: String, unique: true, required: true }, email: { type: String, required: true }, password: { type: String, required: true }, created_at: { type: Number, required: true }, blocked: { type: Boolean, required: true } }); // Execute before each user.save() call UserSchema.pre('save', function(callback) { var user = this; // Break out if the password hasn't changed if (!user.isModified('password')) return callback(); // Password changed so we need to hash it bcrypt.genSalt(5, function(err, salt) { if (err) return callback(err); bcrypt.hash(user.password, salt, null, function(err, hash) { if (err) return callback(err); user.password = hash; callback(); }); }); }); UserSchema.methods.verifyPassword = function(password, cb) { bcrypt.compare(password, this.password, function(err, isMatch) { if (err) return cb(err); cb(null, isMatch); }); }; // Export the Mongoose model module.exports = mongoose.model('User', UserSchema);
version https://git-lfs.github.com/spec/v1 oid sha256:5b951f77463e33578e159bfb3d8f35ef4ec677392ddb23e17eeea74bd0aed9c4 size 13668
Pebble.addEventListener("ready", function(e) { console.log("JavaScript app ready and running!"); //Pebble.showSimpleNotificationOnPebble("JavaScript Event Listener", "is ready"); } ); // Send command to XBMC JSON-RPC API function doPOST(data)//, on_load_function) { var req = new XMLHttpRequest(); // TODO: use webstorage to store configuration such as server name // (http://www.w3.org/TR/webstorage/). req.open('POST','http://192.168.178.106:80/jsonrpc'); req.setRequestHeader("Content-Type", "application/json"); //if (on_load_function) { req.onload = on_load_function; } req.send(data); } function doRealSelect() { //Pebble.showSimpleNotificationOnPebble("appmessage receieved", "Select"); var rpc = {"jsonrpc": "2.0", "method": "Input.Select", "id": "1"}; return doPOST(JSON.stringify(rpc)); } function doPlayPause() { // TODO handle more than one active player? //Pebble.showSimpleNotificationOnPebble("appmessage receieved", "PlayPause"); var rpc = {"jsonrpc": "2.0", "method": "Player.PlayPause", "params": { "playerid": "1" }, "id": "1"}; return doPOST(JSON.stringify(rpc)); } function doSelect() { var rpc = {"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1}; var req = new XMLHttpRequest(); req.open('POST','http://192.168.178.106:80/jsonrpc'); req.setRequestHeader("Content-Type", "application/json"); req.onload = function(e) { if (req.readyState == 4 && req.status == 200) { if(req.status == 200) { var response = JSON.parse(req.responseText); if (response.result.length > 0) { // one (or more) active player(s) return doPlayPause(); } // zero active players return doRealSelect(); } } }; var data = JSON.stringify(rpc); req.send(data); } function doUp() { //Pebble.showSimpleNotificationOnPebble("appmessage receieved", "Up"); var rpc = {"jsonrpc": "2.0", "method": "Input.Up", "id": "1"}; return doPOST(JSON.stringify(rpc)); } function doDown() { //Pebble.showSimpleNotificationOnPebble("appmessage receieved", "Down"); var rpc = {"jsonrpc": "2.0", "method": "Input.Down", "id": "1"}; return doPOST(JSON.stringify(rpc)); } function doContext() { //Pebble.showSimpleNotificationOnPebble("appmessage receieved", "ContextMenu"); var rpc = {"jsonrpc": "2.0", "method": "Input.ContextMenu", "id": "1"}; return doPOST(JSON.stringify(rpc)); } function doLeft() { //Pebble.showSimpleNotificationOnPebble("appmessage receieved", "Left"); var rpc = {"jsonrpc": "2.0", "method": "Input.Left", "id": "1"}; return doPOST(JSON.stringify(rpc)); } function doRight() { //Pebble.showSimpleNotificationOnPebble("appmessage receieved", "Right"); var rpc = {"jsonrpc": "2.0", "method": "Input.Right", "id": "1"}; return doPOST(JSON.stringify(rpc)); } // Set callback for appmessage events Pebble.addEventListener("appmessage", function(e) { //Pebble.showSimpleNotificationOnPebble("appmessage receieved", "AppMessage"); Pebble.sendAppMessage({"OUTPUT_TEXT":JSON.stringify(e)}, function(e) { return; }, function(e) { return; } ); if (e.payload.down) { doDown(); } else if (e.payload.up) { doUp(); } else if (e.payload.select) { doSelect(); } else if (e.payload.context) { doContext(); } else if (e.payload.left) { doLeft(); } else if (e.payload.right) { doRight(); } } ); //Pebble.addEventListener("showConfiguration", // function(e) { // Pebble.openURL("http://bennettp123.com"); // } //); // //Pebble.addEventListener("webviewclosed", // function(e) { // var configuration = JSON.parse(e.response); // console.log("Configuration window returned: ", configuration); // } //);