code
stringlengths
2
1.05M
(function() { 'use strict'; var bowerFiles = require('bower-files')(); var config = require('./gulp/config'); function listFiles() { var files = [] .concat(bowerFiles.dev().ext('js').files) .concat([ config.sourceDir + 'app/**/*.html', config.sourceDir + 'app/**/*.js', ]); return files; } function listPreprocessors() { var preprocessors = {}; preprocessors[config.sourceDir + 'app/**/*.html'] = ['ng-html2js']; preprocessors[config.sourceDir + 'app/**/!(*.spec|*.mock).js'] = ['coverage']; return preprocessors; } module.exports = function(karmaConfig) { karmaConfig.set({ files: listFiles(), browsers: ['PhantomJS'], frameworks: ['jasmine', 'angular-filesort'], preprocessors: listPreprocessors(), ngHtml2JsPreprocessor: { stripPrefix: config.sourceDir, moduleName: 'templateCache' }, angularFilesort: { whitelist: [ config.sourceDir + 'app/**/!*.html', config.sourceDir + 'app/**/!(*.spec|*.mock).js' ] }, reporters: ['progress', 'coverage', 'html'], coverageReporter: { dir: config.coverageDir, reporters: [ { type: 'html', subdir: 'report-html' }, { type: 'lcov', subdir: 'report-lcov' } ] } }); }; })();
var http = require("http"); var https = require("https"); var url = require("url"); var log = require("./logger"); var headerRE = /(.*):(.*)/ // Runs a single step within a given context exports.run = function(context, step, callback) { if (step.variables) { context.updateVariables(step.variables); } log.debugi("step ", step); var fullURL = context.substituteVariables(step.fullURL || step.url); var opts = url.parse(fullURL); opts.method = step.request || "GET"; if (step.headers) { opts.headers = {}; for(var ix=0; ix<step.headers.length; ix++) { var v = step.headers[ix]; var hdr = headerRE.exec(v); opts.headers[ context.substituteVariables(hdr[1]) ] = context.substituteVariables(hdr[2]); } } // So it can add cookies and the like context.preflight(opts); // Update content length if (step.content && step.content.data) { var toSend = []; var len = 0; for(var ix=0; ix<step.content.data.length; ix++) { var el = step.content.data[ix]; el = context.substituteVariables(el); len += el.length; toSend.push(el); } if (!opts.headers) opts.headers = {}; opts.headers["content-length"] = len; } if (opts.protocol == "https") { var proto = https; } else { var proto = http; } log.debugi("Request options ", opts); var req = proto.request(opts); var result = { timing: { created: Date.now() } , errors: [] }; req.on("response", function(response) { log.debug("response"); result.statusCode = response.statusCode; result.headers = response.headers; result.timing.responseBegins = Date.now(); result.data = []; response.on("data", function(data) { log.debug("response data"); result.data.push(data); }); response.on("error", function(err) { errors.push("response error: "+err); }); response.on("end", function() { log.debug("response end"); result.timing.end = Date.now(); // Finishing processing if (step.xtracts) { context.xtract(step.xtracts, result); } callback(null, result); }); // Set timeout on response??? }); req.on("socket", function(socket) { socket.setMaxListeners(0); socket.on("error", function(e) { console.log("Socket thing "+e); }); }); req.on("error", function(err) { log.warning("request error ", err); result.timing.error = Date.now(); result.errors.push(err); //callback(err); console.trace(); return false; }); req.setTimeout(step.timeout, function() { result.timing.requestTimeout = Date.now(); }); // Send any data if we have that to do if (toSend) { sent = []; for(var ix=0; ix<toSend.length; ix++) { var el = toSend[ix]; sent.push(el); req.write( el ); } result.sent = sent; } req.end(); // Return a canceler return function() { log.debugi("req abort function"); req.setTimeout(0, function() { }); } }
// @flow /** * Copyright (c) 2017, Dirk-Jan Rutten * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ export { serializeTime, serializeTimeString, serializeDate, serializeDateTime, serializeDateTimeString, serializeUnixTimestamp, parseTime, parseDate, parseDateTime } from './formatter' export { validateTime, validateDate, validateDateTime, validateUnixTimestamp, validateJSDate } from './validator'
'use strict' var website = angular.module('website',['ngRoute']); website.config(function($routeProvider, $locationProvider) { $routeProvider.when('/', { templateUrl: '/website/partials/home.html', controller: 'mainCtrl' }) });
/** * The MIT License (MIT) * Copyright (c) 2016 Krypto Fin ry and the FIMK Developers * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ (function () { 'use strict'; var module = angular.module('fim.base'); module.directive('fileSelect', function () { return { restrict: 'A', link: function (scope, element, attrs) { element.on('change', function () { var input = element, numFiles = input.files ? input.files.length : 1, label = input.val().replace(/\\/g, '/').replace(/.*\//, ''); var event; if (document.createEvent) { event = document.createEvent("HTMLEvents"); event.initEvent("fileselect", true, true); } else { event = document.createEventObject(); event.eventType = "fileselect"; } event.eventName = "fileselect"; if (document.createEvent) { element[0].dispatchEvent(event); } else { element[0].fireEvent("on" + event.eventType, event); } // input.trigger('fileselect', [numFiles, label]); }); } }; }); })();
/* let fs = require('fs'); fs.readFile('./files/a.json','utf8',(error1,data1)=>{ console.log(data1); fs.readFile('./files/b.json','utf8',(error2,data2)=>{ console.log(data2); fs.readFile('./files/c.json','utf8',(error3,data3)=>{ console.log(data3); fs.readFile('./files/d.json','utf8',(error4,data4)=>{ console.log(data4); }); }); }); }); */ let fs = require('fs'); let co = require('co'); let readFile = url => { return cb => fs.readFile(url,'utf8',cb); } /* yield 与 yield* 的区别在于:yield 只是返回右值,而 yield* 则将函数委托 (delegate)到另一个生成器( Generator)或可迭代的对象(如字符串、数组和类数组 arguments,以及 ES6 中的 Map、Set 等)。 */ function(cb){ return fs.readFile('./files/a.json','utf8',cb); } co(function*(){ let data1 = yield readFile('./files/a.json'); console.log(data1); let data2 = yield readFile('./files/b.json'); console.log(data2); let data3 = yield readFile('./files/c.json'); console.log(data3); let data4 = yield readFile('./files/d.json'); console.log(data4); }).catch(error => console.log(error) )
const _ = require('lodash'); const Promise = require('bluebird'); const fs = require('fs'); const _path = require('path'); /** * @memberOf FileUtil * @function symlink * * Asynchronous {@link http://man7.org/linux/man-pages/man2/symlink.2.html|symlink(2)}. * * @param {Object} options * @param {String|Buffer} options.target * @param {String|Buffer} options.path * @param {String} [options.type=file] The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on other platforms). * * Note that Windows junction points require the destination path to be absolute. When using 'junction', the target argument will automatically be normalized to absolute path. * * @returns {Promise<undefined>} * @see {@link https://nodejs.org/api/fs.html#fs_fs_symlink_target_path_type_callback} */ var symlink = function (options) { return new Promise(function (resolve, reject) { try { var target = _.get(options, 'target'); var path = _.get(options, 'path'); if (_.isString(target) || _.isBuffer(target)) { target = _path.resolve(process.cwd(), target); } if (_.isString(path) || _.isBuffer(path)) { path = _path.resolve(process.cwd(), path); } var symlinkArgs = [target, path]; var type = _.get(options, 'type'); if (!_.isNil(type)) { symlinkArgs.push(type); } var callback = function (err) { if (!_.isNil(err)) { return reject(err); } return resolve(); }; symlinkArgs.push(callback); return fs.symlink.apply(fs, symlinkArgs); } catch (err) { return reject(err); } }); }; module.exports = symlink;
import React, { PureComponent } from 'react'; import { connect } from 'react-redux'; import isFunction from 'lodash/isFunction'; import noop from 'lodash/noop'; import withTheme from 'hoc/withTheme'; import { actions } from 'modules/modal'; import Button from 'components/Button'; import { propTypes, defaultProps } from './ModalWrapper.statics'; import StyledModal, { ModalActions, ModalBackdrop } from './ModalWrapper.styled'; @withTheme @connect(null, { close: actions.closeModal, }) class ModalWrapper extends PureComponent { static defaultProps = defaultProps; static propTypes = propTypes; // Wrap Action with close event withClose = (action, useReduxCloseAction = false) => () => { const { id, close } = this.props; const modalAction = isFunction(action) ? action : noop; if (useReduxCloseAction) { modalAction(); } else { modalAction(); close(id); } }; getCloseEvent = () => { const { cancelButton, onClose, onCancel, useCloseAction, useCancelAction } = this.props; return cancelButton ? this.withClose(onCancel, useCloseAction) : this.withClose(onClose, useCancelAction); }; handleBackgroundClick = e => { if (e.target === e.currentTarget) { const closeEvent = this.getCloseEvent(); closeEvent(); } }; handleKeyPress = ({ keyCode }) => { if (keyCode === 27) { const closeEvent = this.getCloseEvent(); closeEvent(); } }; getButtonType = (type = '') => ({ alert: type === 'alert', info: type === 'info', success: type === 'success', noAccent: type === 'noAccent', }); componentDidMount() { document.addEventListener('keyup', this.handleKeyPress); } componentWillUnmount() { document.removeEventListener('keyup', this.handleKeyPress); } render() { const { id, buttons, children, collapse, cancelText, closeText, cancelButton, closeButton, footNote, useCloseAction, useCancelAction, locked, theme, title, type, width, valid, onCancel, onClose, transitionEnter, transitionLeave, } = this.props; const modalButtons = []; if (closeButton) { modalButtons.push({ action: onClose, useReduxAction: useCloseAction, text: closeText, type: type || 'info', disabled: !valid, }); } if (cancelButton) { modalButtons.push({ action: onCancel, useReduxAction: useCancelAction, type: 'noAccent', text: cancelText, }); } const modalActions = [...buttons, ...modalButtons]; return ( <ModalBackdrop key={id} onClick={!locked ? this.handleBackgroundClick : noop} theme={theme} transitionEnter={transitionEnter} transitionLeave={transitionLeave} > <StyledModal className="Modal" style={{ width: width ? `${width}px` : '100%' }} type={type} collapse={collapse} theme={theme} transitionEnter={transitionEnter} transitionLeave={transitionLeave} > {title && <div className="Modal__header">{title}</div>} <div className="Modal__content">{children}</div> {modalActions.length > 0 && ( <div className="Modal__footer"> <ModalActions className="Modal__actions" length={modalActions.length}> {modalActions.map(({ action, type, text, useReduxAction, ...props }, i) => ( <Button className="Modal__action" key={i} onClick={this.withClose(action, useReduxAction)} {...this.getButtonType(type)} {...props} > {text} </Button> ))} </ModalActions> </div> )} {footNote && <div className="Modal__footNote">{footNote}</div>} </StyledModal> </ModalBackdrop> ); } } export default ModalWrapper;
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.15-3-16 description: > Array.prototype.lastIndexOf - value of 'length' is a string which is able to be converted into hex number includes: [runTestCase.js] ---*/ function testcase() { var obj = { 2573: 2573, 2574: 0x000A0E, length: "0x000A0E" }; return Array.prototype.lastIndexOf.call(obj, 2573) === 2573 && Array.prototype.lastIndexOf.call(obj, 0x000A0E) === -1; } runTestCase(testcase);
// Generated by CoffeeScript 1.9.3 (function() { 'use strict'; var _containersControllers, _windowEventsHandlerBinded, _windowInViewItems, addWindowInViewItem, bindWindowEvents, checkInView, debounce, getBoundingClientRect, getOffsetFromPercentage, getViewportHeight, offsetIsPercentage, removeWindowInViewItem, trackInViewContainer, triggerInViewCallback, unbindWindowEvents, untrackInViewContainer, windowCheckInView, windowEventsHandler, slice = [].slice; angular.module('angular-inview', []).directive('inView', [ '$parse', function($parse) { return { restrict: 'A', require: '?^inViewContainer', link: function(scope, element, attrs, containerController) { var inViewFunc, item, options, performCheck, ref, ref1; if (!attrs.inView) { return; } inViewFunc = $parse(attrs.inView); item = { element: element, wasInView: false, offset: 0, customDebouncedCheck: null, callback: function($event, $inview, $inviewpart) { if ($event == null) { $event = {}; } return scope.$evalAsync((function(_this) { return function() { $event.inViewTarget = element[0]; return inViewFunc(scope, { '$event': $event, '$inview': $inview, '$inviewpart': $inviewpart }); }; })(this)); } }; if ((attrs.inViewOptions != null) && (options = scope.$eval(attrs.inViewOptions))) { item.offset = options.offset || [options.offsetTop || 0, options.offsetBottom || 0]; if (options.debounce) { item.customDebouncedCheck = debounce((function(event) { return checkInView([item], element[0], event); }), options.debounce); } } performCheck = (ref = (ref1 = item.customDebouncedCheck) != null ? ref1 : containerController != null ? containerController.checkInView : void 0) != null ? ref : windowCheckInView; if (containerController != null) { containerController.addItem(item); } else { addWindowInViewItem(item); } setTimeout(performCheck); return scope.$on('$destroy', function() { if (containerController != null) { containerController.removeItem(item); } return removeWindowInViewItem(item); }); } }; } ]).directive('inViewContainer', function() { return { restrict: 'AC', controller: [ '$element', function($element) { this.items = []; this.addItem = function(item) { return this.items.push(item); }; this.removeItem = function(item) { var i; return this.items = (function() { var j, len, ref, results; ref = this.items; results = []; for (j = 0, len = ref.length; j < len; j++) { i = ref[j]; if (i !== item) { results.push(i); } } return results; }).call(this); }; this.checkInView = (function(_this) { return function(event) { var i, j, len, ref; ref = _this.items; for (j = 0, len = ref.length; j < len; j++) { i = ref[j]; if (i.customDebouncedCheck != null) { i.customDebouncedCheck(); } } return checkInView((function() { var k, len1, ref1, results; ref1 = this.items; results = []; for (k = 0, len1 = ref1.length; k < len1; k++) { i = ref1[k]; if (i.customDebouncedCheck == null) { results.push(i); } } return results; }).call(_this), $element[0], event); }; })(this); return this; } ], link: function(scope, element, attrs, controller) { element.bind('DOMMouseScroll MouseScrollEvent MozMousePixelScroll wheel scroll', controller.checkInView); trackInViewContainer(controller); return scope.$on('$destroy', function() { element.unbind('DOMMouseScroll MouseScrollEvent MozMousePixelScroll wheel scroll', controller.checkInView); return untrackInViewContainer(controller); }); } }; }); _windowInViewItems = []; addWindowInViewItem = function(item) { _windowInViewItems.push(item); return bindWindowEvents(); }; removeWindowInViewItem = function(item) { var i; _windowInViewItems = (function() { var j, len, results; results = []; for (j = 0, len = _windowInViewItems.length; j < len; j++) { i = _windowInViewItems[j]; if (i !== item) { results.push(i); } } return results; })(); return unbindWindowEvents(); }; _containersControllers = []; trackInViewContainer = function(controller) { _containersControllers.push(controller); return bindWindowEvents(); }; untrackInViewContainer = function(container) { var c; _containersControllers = (function() { var j, len, results; results = []; for (j = 0, len = _containersControllers.length; j < len; j++) { c = _containersControllers[j]; if (c !== container) { results.push(c); } } return results; })(); return unbindWindowEvents(); }; _windowEventsHandlerBinded = false; windowEventsHandler = function(event) { var c, j, len; for (j = 0, len = _containersControllers.length; j < len; j++) { c = _containersControllers[j]; c.checkInView(event); } if (_windowInViewItems.length) { return windowCheckInView(event); } }; bindWindowEvents = function() { if (_windowEventsHandlerBinded) { return; } _windowEventsHandlerBinded = true; return angular.element(window).bind('checkInView click ready DOMMouseScroll MouseScrollEvent MozMousePixelScroll wheel scroll resize', windowEventsHandler); }; unbindWindowEvents = function() { if (!_windowEventsHandlerBinded) { return; } if (_windowInViewItems.length || _containersControllers.length) { return; } _windowEventsHandlerBinded = false; return angular.element(window).unbind('checkInView click ready DOMMouseScroll MouseScrollEvent MozMousePixelScroll wheel scroll resize', windowEventsHandler); }; triggerInViewCallback = function(event, item, inview, isTopVisible, isBottomVisible) { var elOffsetTop, inviewpart; if (inview) { elOffsetTop = getBoundingClientRect(item.element[0]).top + window.pageYOffset; inviewpart = (isTopVisible && isBottomVisible && 'neither') || (isTopVisible && 'top') || (isBottomVisible && 'bottom') || 'both'; if (!(item.wasInView && item.wasInView === inviewpart && elOffsetTop === item.lastOffsetTop)) { item.lastOffsetTop = elOffsetTop; item.wasInView = inviewpart; return item.callback(event, true, inviewpart); } } else if (item.wasInView) { item.wasInView = false; return item.callback(event, false); } }; checkInView = function(items, container, event) { var bounds, boundsBottom, boundsTop, element, item, j, k, len, len1, ref, ref1, ref2, ref3, results, viewport; viewport = { top: 0, bottom: getViewportHeight() }; if (container && container !== window) { bounds = getBoundingClientRect(container); if (bounds.top > viewport.bottom || bounds.bottom < viewport.top) { for (j = 0, len = items.length; j < len; j++) { item = items[j]; triggerInViewCallback(event, item, false); } return; } if (bounds.top > viewport.top) { viewport.top = bounds.top; } if (bounds.bottom < viewport.bottom) { viewport.bottom = bounds.bottom; } } results = []; for (k = 0, len1 = items.length; k < len1; k++) { item = items[k]; element = item.element[0]; bounds = getBoundingClientRect(element); boundsTop = bounds.top + (offsetIsPercentage(item.offset) ? getOffsetFromPercentage(bounds, item.offset) : parseInt((ref = (ref1 = item.offset) != null ? ref1[0] : void 0) != null ? ref : item.offset)); boundsBottom = bounds.bottom + (offsetIsPercentage(item.offset) ? getOffsetFromPercentage(bounds, item.offset) : parseInt((ref2 = (ref3 = item.offset) != null ? ref3[1] : void 0) != null ? ref2 : item.offset)); if (boundsTop < viewport.bottom && boundsBottom >= viewport.top) { results.push(triggerInViewCallback(event, item, true, boundsBottom > viewport.bottom, boundsTop < viewport.top)); } else { results.push(triggerInViewCallback(event, item, false)); } } return results; }; offsetIsPercentage = function(offset) { return typeof offset === 'string' && offset.slice(-1) === '%'; }; getOffsetFromPercentage = function(bounds, offsetPercentage) { var percentage; percentage = offsetPercentage.substring(0, offsetPercentage.length - 1); return (bounds.bottom - bounds.top) * (percentage / 100); }; getViewportHeight = function() { var height, mode, ref; height = window.innerHeight; if (height) { return height; } mode = document.compatMode; if (mode || !(typeof $ !== "undefined" && $ !== null ? (ref = $.support) != null ? ref.boxModel : void 0 : void 0)) { height = mode === 'CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight; } return height; }; getBoundingClientRect = function(element) { var el, parent, top; if (element.getBoundingClientRect != null) { return element.getBoundingClientRect(); } top = 0; el = element; while (el) { top += el.offsetTop; el = el.offsetParent; } parent = element.parentElement; while (parent) { if (parent.scrollTop != null) { top -= parent.scrollTop; } parent = parent.parentElement; } return { top: top, bottom: top + element.offsetHeight }; }; debounce = function(f, t) { var timer; timer = null; return function() { var args; args = 1 <= arguments.length ? slice.call(arguments, 0) : []; if (timer != null) { clearTimeout(timer); } return timer = setTimeout((function() { return f.apply(null, args); }), t != null ? t : 100); }; }; windowCheckInView = function(event) { var i, j, len; for (j = 0, len = _windowInViewItems.length; j < len; j++) { i = _windowInViewItems[j]; if (i.customDebouncedCheck != null) { i.customDebouncedCheck(); } } return checkInView((function() { var k, len1, results; results = []; for (k = 0, len1 = _windowInViewItems.length; k < len1; k++) { i = _windowInViewItems[k]; if (i.customDebouncedCheck == null) { results.push(i); } } return results; })(), null, event); }; }).call(this);
/** * Copyright (c) 2011-2014 Felix Gnass * Licensed under the MIT license * http://spin.js.org/ */ ; (function (root, factory) { /* CommonJS */ if (typeof module == 'object' && module.exports) module.exports = factory() /* AMD module */ else if (typeof define == 'function' && define.amd) define(factory) /* Browser global */ else root.Spinner = factory() }(this, function () { "use strict" var prefixes = ['webkit', 'Moz', 'ms', 'O'] /* Vendor prefixes */, animations = {} /* Animation rules keyed by their name */, useCssAnimations /* Whether to use CSS animations or setTimeout */, sheet /* A stylesheet to hold the @keyframe or VML rules. */ /** * Utility function to create elements. If no tag name is given, * a DIV is created. Optionally properties can be passed. */ function createEl(tag, prop) { var el = document.createElement(tag || 'div'), n for (n in prop) el[n] = prop[n] return el } /** * Appends children and returns the parent. */ function ins(parent /* child1, child2, ...*/) { for (var i = 1, n = arguments.length; i < n; i++) { parent.appendChild(arguments[i]) } return parent } /** * Creates an opacity keyframe animation rule and returns its name. * Since most mobile Webkits have timing issues with animation-delay, * we create separate rules for each line/segment. */ function addAnimation(alpha, trail, i, lines) { var name = ['opacity', trail, ~~(alpha * 100), i, lines].join('-'), start = 0.01 + i / lines * 100, z = Math.max(1 - (1 - alpha) / trail * (100 - start), alpha), prefix = useCssAnimations.substring(0, useCssAnimations.indexOf('Animation')).toLowerCase(), pre = prefix && '-' + prefix + '-' || '' if (!animations[name]) { sheet.insertRule( '@' + pre + 'keyframes ' + name + '{' + '0%{opacity:' + z + '}' + start + '%{opacity:' + alpha + '}' + (start + 0.01) + '%{opacity:1}' + (start + trail) % 100 + '%{opacity:' + alpha + '}' + '100%{opacity:' + z + '}' + '}', sheet.cssRules.length) animations[name] = 1 } return name } /** * Tries various vendor prefixes and returns the first supported property. */ function vendor(el, prop) { var s = el.style, pp, i prop = prop.charAt(0).toUpperCase() + prop.slice(1) if (s[prop] !== undefined) return prop for (i = 0; i < prefixes.length; i++) { pp = prefixes[i] + prop if (s[pp] !== undefined) return pp } } /** * Sets multiple style properties at once. */ function css(el, prop) { for (var n in prop) { el.style[vendor(el, n) || n] = prop[n] } return el } /** * Fills in default values. */ function merge(obj) { for (var i = 1; i < arguments.length; i++) { var def = arguments[i] for (var n in def) { if (obj[n] === undefined) obj[n] = def[n] } } return obj } /** * Returns the line color from the given string or array. */ function getColor(color, idx) { return typeof color == 'string' ? color : color[idx % color.length] } // Built-in defaults var defaults = { lines: 12 // The number of lines to draw , length: 7 // The length of each line , width: 5 // The line thickness , radius: 10 // The radius of the inner circle , scale: 1.0 // Scales overall size of the spinner , corners: 1 // Roundness (0..1) , color: '#000' // #rgb or #rrggbb , opacity: 1 / 4 // Opacity of the lines , rotate: 0 // Rotation offset , direction: 1 // 1: clockwise, -1: counterclockwise , speed: 1 // Rounds per second , trail: 100 // Afterglow percentage , fps: 20 // Frames per second when using setTimeout() , zIndex: 2e9 // Use a high z-index by default , className: 'spinner' // CSS class to assign to the element , top: '50%' // center vertically , left: '50%' // center horizontally , shadow: false // Whether to render a shadow , hwaccel: false // Whether to use hardware acceleration (might be buggy) , position: 'absolute' // Element positioning } /** The constructor */ function Spinner(o) { this.opts = merge(o || {}, Spinner.defaults, defaults) } // Global defaults that override the built-ins: Spinner.defaults = {} merge(Spinner.prototype, { /** * Adds the spinner to the given target element. If this instance is already * spinning, it is automatically removed from its previous target b calling * stop() internally. */ spin: function (target) { this.stop() var self = this, o = self.opts, el = self.el = createEl(null, {className: o.className}) css(el, { position: o.position, width: 0, zIndex: o.zIndex, left: o.left, top: o.top }) if (target) { target.insertBefore(el, target.firstChild || null) } el.setAttribute('role', 'progressbar') self.lines(el, self.opts) if (!useCssAnimations) { // No CSS animation support, use setTimeout() instead var i = 0, start = (o.lines - 1) * (1 - o.direction) / 2, alpha, fps = o.fps, f = fps / o.speed, ostep = (1 - o.opacity) / (f * o.trail / 100), astep = f / o.lines ; (function anim() { i++ for (var j = 0; j < o.lines; j++) { alpha = Math.max(1 - (i + (o.lines - j) * astep) % f * ostep, o.opacity) self.opacity(el, j * o.direction + start, alpha, o) } self.timeout = self.el && setTimeout(anim, ~~(1000 / fps)) })() } return self } /** * Stops and removes the Spinner. */, stop: function () { var el = this.el if (el) { clearTimeout(this.timeout) if (el.parentNode) el.parentNode.removeChild(el) this.el = undefined } return this } /** * Internal method that draws the individual lines. Will be overwritten * in VML fallback mode below. */, lines: function (el, o) { var i = 0, start = (o.lines - 1) * (1 - o.direction) / 2, seg function fill(color, shadow) { return css(createEl(), { position: 'absolute', width: o.scale * (o.length + o.width) + 'px', height: o.scale * o.width + 'px', background: color, boxShadow: shadow, transformOrigin: 'left', transform: 'rotate(' + ~~(360 / o.lines * i + o.rotate) + 'deg) translate(' + o.scale * o.radius + 'px' + ',0)', borderRadius: (o.corners * o.scale * o.width >> 1) + 'px' }) } for (; i < o.lines; i++) { seg = css(createEl(), { position: 'absolute', top: 1 + ~(o.scale * o.width / 2) + 'px', transform: o.hwaccel ? 'translate3d(0,0,0)' : '', opacity: o.opacity, animation: useCssAnimations && addAnimation(o.opacity, o.trail, start + i * o.direction, o.lines) + ' ' + 1 / o.speed + 's linear infinite' }) if (o.shadow) ins(seg, css(fill('#000', '0 0 4px #000'), {top: '2px'})) ins(el, ins(seg, fill(getColor(o.color, i), '0 0 1px rgba(0,0,0,.1)'))) } return el } /** * Internal method that adjusts the opacity of a single line. * Will be overwritten in VML fallback mode below. */, opacity: function (el, i, val) { if (i < el.childNodes.length) el.childNodes[i].style.opacity = val } }) function initVML() { /* Utility function to create a VML tag */ function vml(tag, attr) { return createEl('<' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr) } // No CSS transforms but VML support, add a CSS rule for VML elements: sheet.addRule('.spin-vml', 'behavior:url(#default#VML)') Spinner.prototype.lines = function (el, o) { var r = o.scale * (o.length + o.width), s = o.scale * 2 * r function grp() { return css( vml('group', { coordsize: s + ' ' + s, coordorigin: -r + ' ' + -r }), {width: s, height: s} ) } var margin = -(o.width + o.length) * o.scale * 2 + 'px', g = css(grp(), { position: 'absolute', top: margin, left: margin }), i function seg(i, dx, filter) { ins( g, ins( css(grp(), {rotation: 360 / o.lines * i + 'deg', left: ~~dx}), ins( css( vml('roundrect', {arcsize: o.corners}), { width: r, height: o.scale * o.width, left: o.scale * o.radius, top: -o.scale * o.width >> 1, filter: filter } ), vml('fill', { color: getColor(o.color, i), opacity: o.opacity }), vml('stroke', {opacity: 0}) // transparent stroke to fix color bleeding upon opacity change ) ) ) } if (o.shadow) for (i = 1; i <= o.lines; i++) { seg(i, -2, 'progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)') } for (i = 1; i <= o.lines; i++) seg(i) return ins(el, g) } Spinner.prototype.opacity = function (el, i, val, o) { var c = el.firstChild o = o.shadow && o.lines || 0 if (c && i + o < c.childNodes.length) { c = c.childNodes[i + o]; c = c && c.firstChild; c = c && c.firstChild if (c) c.opacity = val } } } if (typeof document !== 'undefined') { sheet = (function () { var el = createEl('style', {type: 'text/css'}) ins(document.getElementsByTagName('head')[0], el) return el.sheet || el.styleSheet }()) var probe = css(createEl('group'), {behavior: 'url(#default#VML)'}) if (!vendor(probe, 'transform') && probe.adj) initVML() else useCssAnimations = vendor(probe, 'animation') } return Spinner }));
var tool = require('../tool'); var mapping = require('../mapping'); var factory = require('../io/factory'); //protobuf映射 function callbackMapping(entity, tag) { switch (tag) { case "GetUserInfoOutput": var userInfo = new RongIMClient.UserInfo(); userInfo.setUserId(entity.userId); userInfo.setUserName(entity.userName); userInfo.setPortraitUri(entity.userPortrait); return userInfo; case "GetQNupTokenOutput": return { deadline: util.int64ToTimestamp(entity.deadline), token: entity.token }; case "GetQNdownloadUrlOutput": return { downloadUrl: entity.downloadUrl }; case "CreateDiscussionOutput": return entity.id; case "ChannelInfoOutput": var disInfo = new RongIMClient.Discussion(); disInfo.setCreatorId(entity.adminUserId); disInfo.setId(entity.channelId); disInfo.setMemberIdList(entity.firstTenUserIds); disInfo.setName(entity.channelName); disInfo.setOpen(RongIMClient.DiscussionInviteStatus.setValue(entity.openStatus)); return disInfo; case "GroupHashOutput": return entity.result; case "QueryBlackListOutput": return entity.userIds; default: return entity; } } function MessageCallback(error) { var timeoutMillis, me = this; this.timeout = null; this.onError = null; if (error && typeof error == "number") { timeoutMillis = error } else { timeoutMillis = 6000; this.onError = error; } this.resumeTimer = function () { if (timeoutMillis > 0 && !this.timeout) { this.timeout = setTimeout(function () { me.readTimeOut(true); }, timeoutMillis) } } } MessageCallback.prototype = { pauseTimer: function () { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null } }, readTimeOut: function (isTimeout) { if (isTimeout && this.onError) { this.onError(RongIMClient.callback.ErrorCode.TIMEOUT) } else { this.pauseTimer() } } }; //发送PublishMessage消息回调类 function PublishCallback(cb, _timeout) { MessageCallback.call(this, _timeout); this.done = cb || function () { }; this.fail = _timeout || function () { }; } tool.inherit(PublishCallback, MessageCallback); PublishCallback.prototype.process = function (_staus, _serverTime, _msg) { this.readTimeOut(); if (_staus == 0) { if (_msg) { //把发送的消息发送状态改为已接收 _msg.setSentStatus(RongIMClient.SentStatus.RECEIVED) } this.done(); } else { this.fail(RongIMClient.SendErrorStatus.setValue(_staus)); } }; PublishCallback.prototype.readTimeOut = function (x) { PublishCallback.super_.prototype.readTimeOut.call(this, x) }; //发送QueryMessage消息回调类 function QueryCallback(cb, _timeout) { MessageCallback.call(this, _timeout); this.done = cb || function () { }; this.fail = _timeout || function () { }; } tool.inherit(QueryCallback, MessageCallback); QueryCallback.prototype.process = function (status, data, serverTime, pbtype) { this.readTimeOut(); if (pbtype && data && status == 0) { try { data = callbackMapping(Modules[pbtype].decode(data), pbtype); } catch (e) { this.fail(RongIMClient.callback.ErrorCode.UNKNOWN_ERROR); return; } if ("GetUserInfoOutput" == pbtype) { //pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列 mapping.userInfoMapping[data.getUserId()] = data; } this.done(data); } else { status > 0 ? this.fail(status) : this.done(status) } }; QueryCallback.prototype.readTimeOut = function (x) { QueryCallback.super_.prototype.readTimeOut.call(this, x) }; //连接回调类 function ConnectAck(cb, _timeout, context) { MessageCallback.call(this, _timeout); this.context = context; this.done = cb || function () { }; this.fail = _timeout || function () { }; } tool.inherit(ConnectAck, MessageCallback); ConnectAck.prototype.process = function (status, userId) { this.readTimeOut(); if (status == 0) { mapping.userId = this.context.userId = userId; if (!RongIMClient.isNotPullMsg) { this.context.syncTime(); } if (mapping.reconnectSet.onSuccess) { mapping.reconnectSet.onSuccess(userId); try { delete mapping.reconnectSet.onSuccess; } catch (e) { } } else { this.done(userId); } factory.getInstance().fire("StatusChanged", 0); factory.getInstance()._doQueue() } else if (status == 6) { var that = this; ConnectAck.redirect(this.context.token, this.context.appId, function () { that.context.clearHeartbeat(); ConnectAck.redirect(); that.context.channel.socket.fire("StatusChanged", 2); }, function () { that.fail(); }, false); } else { if (mapping.reconnectSet.onError) { mapping.reconnectSet.onError(RongIMClient.ConnectErrorStatus.setValue(status)); delete mapping.reconnectSet.onError; } else { this.fail(RongIMClient.ConnectErrorStatus.setValue(status)) } } }; ConnectAck.prototype.readTimeOut = function (x) { ConnectAck.super_.prototype.readTimeOut.call(this, x) }; ConnectAck.redirect = function () { }; module.exports = { MessageCallback: MessageCallback, PublishCallback: PublishCallback, QueryCallback: QueryCallback, ConnectAck: ConnectAck };
// Backbone.Declarative.Views, v4.1.2 // Copyright (c) 2014-2017 Michael Heim, Zeilenwechsel.de // Distributed under MIT license // http://github.com/hashchange/backbone.declarative.views ;( function ( root, factory ) { "use strict"; // UMD for a Backbone plugin. Supports AMD, Node.js, CommonJS and globals. // // - Code lives in the Backbone namespace. // - The module does not export a meaningful value. // - The module does not create a global. var supportsExports = typeof exports === "object" && exports && !exports.nodeType && typeof module === "object" && module && !module.nodeType; // AMD: // - Some AMD build optimizers like r.js check for condition patterns like the AMD check below, so keep it as is. // - Check for `exports` after `define` in case a build optimizer adds an `exports` object. // - The AMD spec requires the dependencies to be an array **literal** of module IDs. Don't use a variable there, // or optimizers may fail. if ( typeof define === "function" && typeof define.amd === "object" && define.amd ) { // AMD module define( [ "exports", "underscore", "backbone" ], factory ); } else if ( supportsExports ) { // Node module, CommonJS module factory( exports, require( "underscore" ), require( "backbone" ) ); } else { // Global (browser or Rhino) factory( {}, _, Backbone ); } }( this, function ( exports, _, Backbone ) { "use strict"; var originalClearCache, // for Marionette only originalConstructor = Backbone.View, templateCache = {}, instanceCacheAliases = [], enforceTemplateLoading = false, isMarionetteInitialized = false, registeredDataAttributes = { primitives: [], json: [] }, rxElDefinitionComment, rxRegisteredDataAttributes = {}, GenericError = createCustomErrorType( "Backbone.DeclarativeViews.Error" ), TemplateError = createCustomErrorType( "Backbone.DeclarativeViews.TemplateError" ), CompilerError = createCustomErrorType( "Backbone.DeclarativeViews.CompilerError" ), CustomizationError = createCustomErrorType( "Backbone.DeclarativeViews.CustomizationError" ), ConfigurationError = createCustomErrorType( "Backbone.DeclarativeViews.ConfigurationError" ), events = _.clone( Backbone.Events ), $ = Backbone.$; // // Core functionality and API // -------------------------- _.extend( Backbone.View.prototype, { tagName: function () { var data = getViewTemplateData( this ) || {}; return data.tagName || "div"; }, className: function () { var data = getViewTemplateData( this ) || {}; return data.className || undefined; }, id: function () { var data = getViewTemplateData( this ) || {}; return data.id || undefined; }, attributes: function () { var data = getViewTemplateData( this ) || {}; return data.attributes || undefined; } } ); Backbone.View = Backbone.View.extend( { constructor: function ( options ) { if ( options && options.template !== undefined ) this.template = options.template; this.declarativeViews = { meta: { viewId: _.uniqueId( "view-" ) }, getCachedTemplate: _.partial( getViewTemplateData, this ), clearCachedTemplate: _.partial( clearViewTemplateCache, this ) }; _.each( instanceCacheAliases, function ( alias ) { this[alias] = this.declarativeViews; }, this ); if ( enforceTemplateLoading ) getViewTemplateData( this, options ); originalConstructor.apply( this, arguments ); } } ); Backbone.DeclarativeViews = { getCachedTemplate: getTemplateData, clearCachedTemplate: clearCachedTemplate, clearCache: clearCache, joinMarionette: joinMarionette, Error: GenericError, TemplateError: TemplateError, CompilerError: CompilerError, CustomizationError: CustomizationError, ConfigurationError: ConfigurationError, plugins: { registerDataAttribute: _registerDataAttribute, getDataAttributes: _getDataAttributes, updateJqueryDataCache: _updateJQueryDataCache, registerCacheAlias: _registerCacheAlias, enforceTemplateLoading: _enforceTemplateLoading, tryCompileTemplate: _tryCompileTemplate, events: events }, defaults: { loadTemplate: loadTemplate }, custom: { /** @type {Function|undefined} */ loadTemplate: undefined, /** @type {Function|undefined} */ compiler: undefined }, version: "4.1.2" }; // // Initialization // -------------- _registerDataAttribute( "tag-name" ); _registerDataAttribute( "class-name" ); _registerDataAttribute( "id" ); _registerDataAttribute( "attributes", { isJSON: true } ); // // Cache management // ---------------- /** * Returns the template data associated with a template property string. Caches it in the process, or retrieves it * from the cache if already available. Returns undefined if there is no cacheable template data. * * When retrieved from the cache, a copy of the cache entry is returned. It protects the cache entry from * modification in case the data is manipulated later on. The protection also extends to the nested `attributes` * hash. The `_pluginData` property, however, must remain writable, and is returned as is. * * The template data is returned as a hash. For a list of properties, see readme. * * @param {string} templateProp template selector, or raw template HTML, identifying the cache entry * @param {Backbone.View} [view] the view which requested the template * @param {Object} [viewOptions] the options passed to the view during instantiation. For availability, * see getViewTemplateData() * @returns {CachedTemplateData|undefined} */ function getTemplateData ( templateProp, view, viewOptions ) { var data; if ( templateProp && _.isString( templateProp ) ) { data = templateCache[ templateProp ]; if ( ! data ) data = _createTemplateCache( templateProp, view, viewOptions ); if ( data.invalid ) data = undefined; if ( data ) data = _copyCacheEntry( data ); } return data; } /** * Returns the template data associated with a given view, provided that the template is set to a non-empty string. * Otherwise, it returns undefined. Manages caching behind the scenes. * * The template data is returned as a hash. For a list of properties, see readme. * * Events * ------ * * The method fires two events: * * - cacheEntry:view:process * * Fires only once per view, on first access to the template from that particular view. Fires whether or not the * template is already in the cache. * * The event handler receives a **copy** of the returned cache data. Modifications of the data are ineffective, * they don't show up anywhere outside of the handler. * * (That is by design. When setting up the el of a view, the cache is accessed several times - once for each * el-related property. The handler would be able to modify the data during the very first access, when the * `attributes` property is requested, but not for `className`, `tagName`, `id`. That behaviour can be confusing * and cause bugs which are difficult to track down. Hence data modification is actively prevented even during * first access, making the behaviour consistent.) * * But there is an exception: the _pluginData property. If the handler needs to change or store data, it can write * to the _pluginData hash. Changes to the hash are persistent. They are stored in the original cache entry and * hence show up in every subsequent cache query for that entry. * * NB: When `el`-related properties from the cache, like tagName or html, need to be manipulated on the fly, it * must be done in a handler for another event: cacheEntry:view:fetch. That handler _is_ allowed to change the * returned data. It also has access to the _pluginData created during the cacheEntry:view:process event. * * - cacheEntry:view:fetch * * Fires every time data is requested from the cache in the context of a querying view. The event fires on first * access as well. On that occasion, it is preceded by the cacheEntry:view:process event. * * The event handler receives the returned cache data and has full access to it. If the handler modifies the data, * the modifications show up in the returned result. * * However, the original cache entry is protected from modification (with the exception of the _pluginData * property, see above), so changes made by the event handler do not alter the values stored in the cache. * * The events fire only if the cache is accessed with getViewTemplateData(), ie when the cache is queried from a * view: during view instantiation, or when called with `view.declarativeViews.getCachedTemplate()`. * * The events do **not** fire when the cache is queried from the global API, even if a view is provided as an * additional argument, as in `Backbone.DeclarativeViews.getCachedTemplate( "#template", view )`. * * @param {Backbone.View} view * @param {Object} [viewOptions] the options passed to the view during instantiation. Only available when * called during view instantiation, and only if the component has been * configured to enforce template loading, with _enforceTemplateLoading() * @returns {CachedTemplateData|undefined} */ function getViewTemplateData ( view, viewOptions ) { var data, meta = view.declarativeViews.meta; if ( ! meta.processed ) { if ( view.template && _.isString( view.template ) ) { meta.originalTemplateProp = view.template; data = getTemplateData( view.template, view, viewOptions ); meta.processed = true; meta.inGlobalCache = true; if ( data ) events.trigger( "cacheEntry:view:process", _copyCacheEntry( data ), meta.originalTemplateProp, view, viewOptions ); } else { data = undefined; meta.processed = true; meta.inGlobalCache = false; } } else { data = meta.inGlobalCache ? getTemplateData( meta.originalTemplateProp, view, viewOptions ) : undefined; } if ( data ) events.trigger( "cacheEntry:view:fetch", data, meta.originalTemplateProp, view, viewOptions ); return data; } /** * Clears the cache as a whole. * * Also clears the Marionette cache (if Marionette is available). * * @param {boolean} [fromMarionette=false] internal flag to prevent circular calls to and from Marionette */ function clearCache ( fromMarionette ) { templateCache = {}; if ( ! fromMarionette && Backbone.Marionette && Backbone.Marionette.TemplateCache ) Backbone.Marionette.TemplateCache.clear(); } /** * Removes one or more cache entries. * * Arguments * --------- * * The strings identifying the cache entries can be passed in as individual arguments (prop1, prop2, ...), or as an * array. Each string must be * * - a template selector * - raw HTML of a template, if that's what the template property held when a view made use of it. * * A template selector must be identical to the one which was used when creating the cache entry, ie the selector * specified in the template property or template option of a view. Mere selector equivalence (e.g. "#template" and * "script#template") won't match the cache. * * Strings not matching a cache entry are ignored, as are non-string arguments. * * Marionette.TemplateCache * ------------------------ * * When templates are cleared here, they are removed from the Marionette template cache as well (if Marionette is * loaded). * * @param {...string|string[]} [templateProp] template selector(s), or raw template HTML, identifying the cache * entry. NB The last argument can also be an internal "fromMarionette" * flag to prevent circular calls to and from Marionette */ function clearCachedTemplate ( templateProp ) { var fromMarionette = false, args = _.toArray( arguments ), lastArg = _.last( args ); // When called from Marionette, or called recursively, the last argument is a "fromMarionette" boolean. Splice // it off before proceeding. if ( args.length && _.isBoolean( lastArg ) ) fromMarionette = args.pop(); // Handle multiple template props passed in as a varargs list, or as an array, with recursive calls for each // template property. if ( args.length > 1 ) { _.each( args, function ( singleProp ) { clearCachedTemplate( singleProp, fromMarionette ); } ); } else if ( _.isArray( templateProp ) || _.isArguments( templateProp ) ) { _.each( templateProp, function ( singleProp ) { clearCachedTemplate( singleProp, fromMarionette ); } ); } else { if ( ! templateProp ) throw new GenericError( "Missing argument: string identifying the template. The string should be a template selector or the raw HTML of a template, as provided to the template property of a view when the cache entry was created" ); // Dealing with a single templateProp argument. // // Delete the corresponding cache entry. Try to clear it from the Marionette cache as well. The // templateProp must be a string - non-string arguments are quietly ignored. if ( _.isString( templateProp ) ) { _clearCachedTemplate( templateProp ); if ( ! fromMarionette && Backbone.Marionette && Backbone.Marionette.TemplateCache ) { try { Backbone.Marionette.TemplateCache.clear( templateProp ); } catch ( err ) {} } } } } /** * Removes the template cache entry associated with a given view, provided that a cache entry exists. * * @param {Backbone.View} view */ function clearViewTemplateCache ( view ) { var meta = view.declarativeViews.meta; if ( meta.processed ) { if ( meta.inGlobalCache ) _clearCachedTemplate( meta.originalTemplateProp ); } else if ( view.template && _.isString( view.template ) ) { _clearCachedTemplate( view.template ); } } /** * Defines the default template loader. Accepts a selector string and returns the template node (usually a <script> * or <template> node) in a jQuery wrapper. * * Is only ever called with a string argument. There is no need to handle other argument types here, or guard * against them. * * Interprets the argument as a selector first and returns the corresponding node if it exists. If not, the argument * is interpreted as a raw HTML/template string and wrapped in a script tag (of type text/x-template). If the raw * template string contains a comment describing the el, the related data attributes are created on the script tag. * * NB Raw template strings are never altered, and not interpreted (apart from looking for the el-related comment). * * @param {string} templateProperty * @returns {jQuery} */ function loadTemplate ( templateProperty ) { var $template; try { $template = $( templateProperty ); // If the template is not in the DOM, treat the template property as a raw template string instead. That // part is handled in `catch`, and should not be guarded against further errors here. To switch to that // process, just throw an error. if ( !$.contains( document.documentElement, $template[0] ) ) throw new Error(); } catch ( err ) { $template = _wrapRawTemplate( templateProperty ); // If the template string cannot be retrieved unaltered even after wrapping it in a script tag, bail out by // throwing a silent error (will be caught, and not propagated further, in _createTemplateCache()). if ( $template.html() !== templateProperty ) throw new Error( "Failed to wrap template string in script tag without altering it" ); } return $template; } /** * Takes a raw HTML/template string and wraps it in a script tag (of type "text/x-template"). In the process, it * detects el-related data attributes which are contained in an HTML comment, and sets them on the script tag. * Returns the script element, as a jQuery object. * * @param {string} templateString * @returns {jQuery} */ function _wrapRawTemplate( templateString ) { var $wrapper = $( "<script />" ) .attr( "type", "text/x-template" ) .text( templateString ), elDataAttributes = _getEmbeddedElAttributes( templateString ); if ( elDataAttributes ) $wrapper.attr( elDataAttributes ); return $wrapper; } /** * Takes a raw HTML/template string and looks for el-related data attributes which are contained in a comment. * Returns the attributes hash, or undefined if no attributes are found. * * The keys in the hash are the data attribute names, ie they include the "data-" prefix. * * @param {string} templateString * @returns {Object|undefined} */ function _getEmbeddedElAttributes ( templateString ) { var elDataAttributes = {}, elDefinitionMatch = rxElDefinitionComment.exec( templateString ), elDefinitionComment = elDefinitionMatch && elDefinitionMatch[0]; if ( elDefinitionComment ) { _.each( rxRegisteredDataAttributes, function ( rxAttributeMatcher, attributeName ) { var match = rxAttributeMatcher.exec( elDefinitionComment ), attributeValue = match && match[2]; if ( attributeValue ) elDataAttributes[attributeName] = attributeValue; } ); } return _.size( elDataAttributes ) ? elDataAttributes : undefined; } /** * Creates a copy of a cache entry and returns it. Protects the original cache entry from modification, except for * the _pluginData property, which remains writable and can be accessed from the copy. * * NB The `attribute` property is cloned and protected, too, if it exists. * * @param {CachedTemplateData} cacheEntry * @returns {CachedTemplateData} */ function _copyCacheEntry ( cacheEntry ) { var copy = _.clone( cacheEntry ); if ( _.isObject( copy.attributes ) ) copy.attributes = _.clone( copy.attributes ); return copy; } /** * Creates a cache entry for a given template property. * * Returns the cached entry if creating it has succeeded. In case of failure, it returns the hash { invalid: true }. * It signals that the template has been processed, but that the returned hash, as well as the cache itself, does * not contain valid data for the template property. * * The creation of a cache entry can fail if the template property is an empty string, or a selector which doesn't * match anything, or a string which jQuery can't process. * * Uses a custom loader if specified, instead of loading the template with jQuery (default). * * Events * ------ * * The method fires the following event: * * - cacheEntry:create * * Fires only once per cache entry, when a valid cache entry is created. That may happen in the context of a view, * or with a global query. * * The event handler receives the original cache entry. If the handler modifies the data, the modifications show * up in the returned result **and** alter the content in the cache. * * If a valid cache entry can't be created (flagged as invalid), the event does NOT fire. * * @param {string} templateProp template selector, or raw template HTML, identifying the cache entry * @param {Backbone.View} [view] the view which requested the template * @param {Object} [viewOptions] the options passed to the view during instantiation. For availability, * see getViewTemplateData() * @returns {CachedTemplateData|Uncacheable} */ function _createTemplateCache( templateProp, view, viewOptions ) { var $template, data, html, customLoader = Backbone.DeclarativeViews.custom.loadTemplate, defaultLoader = Backbone.DeclarativeViews.defaults.loadTemplate, modifiedDefaultLoader = defaultLoader !== loadTemplate, cacheId = templateProp; // Load the template try { $template = customLoader ? customLoader( templateProp, view, viewOptions ) : defaultLoader( templateProp, view, viewOptions ); } catch ( err ) { // Rethrow and exit if the alarm has been raised deliberately, using an error type of Backbone.DeclarativeViews. if( _isDeclarativeViewsErrorType( err ) ) throw err; // Otherwise, continue without having fetched a template. $template = ""; } if ( ( customLoader || modifiedDefaultLoader ) && $template !== "" && ! ( $template instanceof Backbone.$ ) ) { throw new CustomizationError( "Invalid return value. The " + ( customLoader ? "custom" : "default" ) + " loadTemplate function must return a jQuery instance, but it hasn't" ); } // Create cache entry if ( $template.length ) { // Read the el-related data attributes of the template. data = _getDataAttributes( $template ) ; html = $template.html(); templateCache[cacheId] = { html: html, compiled: _tryCompileTemplate( html, $template ), tagName: data.tagName, className: data.className, id: data.id, attributes: data.attributes, // Data store for plugins. Plugins should create their own namespace in the store, with the plugin name // as key. _pluginData: {} }; events.trigger( "cacheEntry:create", templateCache[cacheId], templateProp, view, viewOptions ); } else { templateCache[cacheId] = { invalid: true }; } return templateCache[cacheId]; } /** * Returns the compiled template if a custom compiler is set in Backbone.DeclarativeViews.custom.compiler, or * undefined if no compiler is set. * * The compiler function is passed the inner HTML of the template node as first argument, and the $template node * itself, in a jQuery wrapper, as the second argument. * * The template node argument is always present when the function is invoked by Backbone.Declarative.Views. When * invoked by plugins for individual template string snippets, the $template node might be missing when there is no * node for such a snippet. * * The compiler should return a function which can be called with the template vars as arguments, producing the * final HTML. This is not enforced, though - the compiler can in fact return anything because who knows what hacks * people come up with. * * @param {string} html * @param {jQuery} [$template] * @returns {Function|undefined} */ function _tryCompileTemplate ( html, $template ) { var compiled, customCompiler = Backbone.DeclarativeViews.custom.compiler; if ( customCompiler ) { if ( customCompiler && !_.isFunction( customCompiler ) ) throw new CustomizationError( "Invalid custom template compiler set in Backbone.DeclarativeViews.custom.compiler: compiler is not a function" ); try { compiled = customCompiler( html, $template ); } catch ( err ) { throw new CompilerError( 'An error occurred while compiling the template. The compiler had been passed the HTML string "' + html + ( $template ? '" as the first argument, and the corresponding template node, wrapped in a jQuery object, as the second argument.' : '" as the only argument.' ) + "\nOriginal error thrown by the compiler:\n" + err.message ); } } return compiled; } /** * Removes a cache entry. * * @param {string} templateProp template selector, or raw template HTML, identifying the cache entry */ function _clearCachedTemplate ( templateProp ) { if ( templateCache[ templateProp ] ) delete templateCache[ templateProp ]; } /** * Adds a name to the list of data attributes which are used and managed by Backbone.Declarative.Views. The name * must be passed without the "data-" prefix, but written as in the data attribute (ie "tag-name", not "tagName"). * * When a data attribute is used to store stringified JSON objects, the flag `{ isJSON: true }` must be set in the * options. Primitive data attributes (of type string, number, boolean) don't need a flag. * * The names "html" and "compiled" are illegal because they are reserved. They are already in use in the cache * object, so there could be a conflict further down the line. Also, a name can only be registered once. And, as * said before, it must not be prefixed with "data-". Violations of these rules cause an error to be thrown. * * Registering a data attribute has the following effects: * * - When a registered data attribute is queried by Backbone.Declarative.Views, the attribute is refreshed from the * DOM and updated in the jQuery data cache. Changes to the attribute in the DOM are picked up that way. The * update can also be triggered externally, e.g. by a plugin, with `updateJqueryDataCache()`. * * - A registered data attribute is detected in a raw HTML/template string, provided that it is placed into a * comment. It must be written as it would appear on a script or template tag, ie in dashed form and including the * "data-" prefix, just like the standard `el`-defining attributes. Custom attributes and `el`-defining attributes * must be placed into the same, single comment. * * The registered attribute is then created on the temporary script tag which is wrapped around the template * string, along with the `el`-defining data attributes. But unlike these, the custom attribute does not make it * into the cache (nor does the script tag). * * However, the script tag can be accessed and examined by a custom loader. For that to happen, the custom loader * has to invoke the default loader before processing the result further. Custom attributes can be read this way. * * @param {string} name as in the data attribute (e.g. "tag-name", not "tagName"), and without "data-" prefix * @param {object} [options] * @param {boolean} [options.isJSON=false] */ function _registerDataAttribute ( name, options ) { var existingNames = _getRegisteredDataAttributeNames(), fullName = "data-" + name, type = options && options.isJSON ? "json" : "primitives", names = registeredDataAttributes[type]; if ( name.indexOf( "data-" ) === 0 ) throw new CustomizationError( 'registerDataAttribute(): Illegal attribute name "' + name + '", must be registered without "data-" prefix' ); if ( name === "html" || name === "compiled" ) throw new CustomizationError( 'registerDataAttribute(): Cannot register attribute name "' + name + '" because it is reserved' ); if ( _.contains( existingNames, name ) ) throw new CustomizationError( 'registerDataAttribute(): Cannot register attribute name "' + name + '" because it has already been registered' ); // Add the name to the list of registered data attributes names.push( name ); registeredDataAttributes[type] = _.uniq( names ); // Create amd store a regex matching the attribute and its value in an HTML/template string, for transfer onto a // wrapper node (see _wrapRawTemplate()) rxRegisteredDataAttributes[fullName] = new RegExp( fullName + "\\s*=\\s*(['\"])([\\s\\S]+?)\\1" ); // Update the regular expression which tests an HTML/template string and detects a comment containing registered // attributes. rxElDefinitionComment = _createElDefinitionCommentRx(); } /** * Returns the names of all registered attributes. These names are dashed but don't include the "data-" prefix. * * @returns {string[]} */ function _getRegisteredDataAttributeNames () { return registeredDataAttributes.primitives.concat( registeredDataAttributes.json ); } /** * Returns a regular expression which tests an HTML/template string and detects a comment containing at least one * registered attribute. Stops after the first matching comment is found (no /g flag). * * NB When the default el-related attributes are registered, this is the resulting regex: * /<!--(?:(?!-->)[\s\S])*?data-(?:tag-name|class-name|id|attributes)\s*=\s*(['"])[\s\S]+?\1[\s\S]*?-->/ * * @returns {RegExp} */ function _createElDefinitionCommentRx () { return new RegExp( "<!--(?:(?!-->)[\\s\\S])*?data-(?:" + _getRegisteredDataAttributeNames().join( "|" ) + ")\\s*=\\s*(['\"])[\\s\\S]+?\\1[\\s\\S]*?-->" ); } /** * Returns the data attributes of an element. * * Makes sure that the registered data attributes, which describe a Backbone el, are read from the DOM directly, * circumventing a potentially stale jQuery cache. The jQuery cache is updated in the process (but for these * attributes only). * * With registerDataAttribute(), plugins can register additional data attributes to have them handled the same way. * * See _updateJQueryDataCache() for more about updating the jQuery data cache. * * @param {jQuery} $elem * @returns {Object} */ function _getDataAttributes ( $elem ) { _updateJQueryDataCache( $elem ); return $elem.data(); } /** * Reads registered data attributes of a given element from the DOM, and updates an existing jQuery data cache with * these values. * * If no jQuery data cache exists, it is NOT created by the call. (This function is meant to be used as an efficient, * internal tool.) If you need to make sure the jQuery data cache is current and in sync with the DOM, and also * create it if it doesn't exist, just call _getDataAttributes() instead. * * The function is needed because jQuery keeps its own cache of data attributes, but there is no API to clear or * circumvent that cache. The jQuery functions $.fn.removeData() and $.removeData() don't do that job: despite their * name, they don't actually remove the cached values but set them to undefined. So undefined is returned on next * access - not the actual values in the DOM. * * Here, we force-update the jQuery cache, making sure that changes of the HTML5 data-* attributes in the DOM are * picked up. * * The implementation circumvents the numerous bugs of jQuery.fn.data(), in particular when removing data. The * behaviour and bugs of a .data() call vary by jQuery version. For an overview of that mess, see * http://jsbin.com/venuqo/4/edit?html,js,console * * NB The cache update is limited to the data attributes which have been registered with _registerDataAttribute(). * By default, only attributes which are "owned" by Backbone.Declarative.Views are updated - ie, the ones describing * the `el` of a view. Other HTML5 data-* attributes are not updated in the jQuery cache because it would interfere * with the responsibilities of other code. * * @param {jQuery} $elem * @returns {Object} */ function _updateJQueryDataCache ( $elem ) { var add = {}, remove = []; if ( $.hasData( $elem[0] ) ) { // A jQuery data cache exists. Update it for the el properties (and attribute names registered by a plugin). // Primitive data types. Normally, this will read the "data-tag-name", "data-class-name" and "data-id" // attributes. _.each( registeredDataAttributes.primitives, function ( attributeName ) { var attributeValue = $elem.attr( "data-" + attributeName ); if ( attributeValue === undefined ) { remove.push( attributeName ); } else { add[toCamelCase( attributeName )] = attributeValue; } } ); // Stringified JSON data. Normally, this just deals with "data-attributes". _.each( registeredDataAttributes.json, function ( attributeName ) { var attributeValue = $elem.attr( "data-" + attributeName ); if ( attributeValue === undefined ) { remove.push( attributeName ); } else { try { add[toCamelCase( attributeName )] = $.parseJSON( attributeValue ); } catch ( err ) { remove.push( attributeName ); } } } ); if ( remove.length ) $elem.removeData( remove ); if ( _.size( add ) ) $elem.data( add ); } } /** * Registers an alternative way to access the cache and set up a custom compiler and loader. Intended for use by * plugins. * * A cache alias just adds syntactic sugar for users wanting to manage and access the cache from a plugin namespace. * The registration creates references to `getCachedTemplate`, `clearCachedTemplate`, `clearCache`, and the `custom` * object in the alternative namespace. * * You can also register the name of an alias to use on view instances (optional). A property of that name will be * created on each view. It references the declarativeViews property of the view. * * @param {Object} namespaceObject e.g. Backbone.InlineTemplate * @param {string} [instanceCachePropertyName] the name of the cache property on a view instance, e.g. "inlineTemplate" */ function _registerCacheAlias( namespaceObject, instanceCachePropertyName ) { namespaceObject.getCachedTemplate = Backbone.DeclarativeViews.getCachedTemplate; namespaceObject.clearCachedTemplate = Backbone.DeclarativeViews.clearCachedTemplate; namespaceObject.clearCache = Backbone.DeclarativeViews.clearCache; namespaceObject.custom = Backbone.DeclarativeViews.custom; if ( instanceCachePropertyName ) { instanceCacheAliases.push( instanceCachePropertyName ); instanceCacheAliases = _.unique( instanceCacheAliases ); } } /** * Sets a flag to enforce template loading when a view is instantiated. Intended for use by plugins. * * When all `el` properties (`tagName`, `className`, ...) are overridden by properties set in a view, there normally * is no need to examine the template, and the loader is not called. (It will be called as soon as the data is * needed, ie when the template cache is queried; that is early enough.) * * However, if the loader does not just fetch the template but also transforms the template element, that * transformation would not happen if all `el` properties are overridden. Calling _enforceTemplateLoading() and * setting the flag makes sure that the loader is called, even in that case. * * _enforceTemplateLoading() must also be called if the loader, or a cache creation helper, needs access to the view * options which are passed to the constructor. */ function _enforceTemplateLoading () { enforceTemplateLoading = true; } /** * Checks if an error belongs to the error types of Backbone.DeclarativeViews. * * ATTN Update this check as new error types are added to Backbone.DeclarativeViews. * * @param {Object} error * @returns {boolean} */ function _isDeclarativeViewsErrorType ( error ) { return error instanceof GenericError || error instanceof TemplateError || error instanceof CompilerError || error instanceof CustomizationError || error instanceof ConfigurationError; } // // Marionette integration // ---------------------- function joinMarionette () { if ( Backbone.Marionette && Backbone.Marionette.TemplateCache && !isMarionetteInitialized ) { originalClearCache = Backbone.Marionette.TemplateCache.clear; // Custom implementation of Marionette.TemplateCache.clear() // // When the Marionette cache is cleared, the DeclarativeViews cache is cleared as well. This is not technically // necessary, but makes sense. If there is a reason to invalidate a cached template, it applies to all caches. Backbone.Marionette.TemplateCache.clear = function () { if ( arguments.length ) { Backbone.DeclarativeViews.clearCachedTemplate( arguments, true ); } else { Backbone.DeclarativeViews.clearCache( true ); } originalClearCache.apply( this, arguments ); }; isMarionetteInitialized = true; // Removed: integration of the Marionette and Backbone.Declarative.Views template loading mechanisms // // Integrating the template loaders turned out to be of little or no benefit, and could potentially have caused // problems with other custom loaders. In detail: // // - Integration saved exactly one DOM access per *template*. Given the limited number of templates in a project, // the performance gain had often been too small to even be measurable. // // - During testing with just a single template, the net effect was even negative (!) - integration and the // associated overhead seemed to slow things down. // // - With integration, custom loaders like the one for Marionette/Handlebars had been trickier to use. Load // order suddenly mattered. The code setting up a custom loader had to be run after integrating // Backbone.Declarative.Views with Marionette. Otherwise, the custom loader would haven been overwritten, // breaking the application. // // In a nutshell, loader integration has proven to be more trouble than it is worth. } } // // Generic helpers // --------------- /** * Turns a dashed string into a camelCased one. * * Simple implementation, but good enough for data attributes. * * @param {string} dashed * @returns {string} */ function toCamelCase ( dashed ) { return dashed.replace( /([^-])-([a-z])/g, function ( $0, $1, $2 ) { return $1 + $2.toUpperCase(); } ); } /** * Creates and returns a custom error type. * * See gist at https://gist.github.com/hashchange/4c1ce239570c77e698c1d2df09d0e540 * * @param {string} name of the error type * @returns {Error} */ function createCustomErrorType ( name ) { function CustomError ( message ) { this.message = message; if ( Error.captureStackTrace ) { Error.captureStackTrace( this, this.constructor ); } else { this.stack = ( new Error() ).stack; } } CustomError.prototype = new Error(); CustomError.prototype.name = name; CustomError.prototype.constructor = CustomError; return CustomError; } // Module return value // ------------------- // // A return value may be necessary for AMD to detect that the module is loaded. It ony exists for that reason and is // purely symbolic. Don't use it in client code. The functionality of this module lives in the Backbone namespace. exports.info = "Backbone.Declarative.Views has loaded. Don't use the exported value of the module. Its functionality is available inside the Backbone namespace."; // // Custom types // ------------ // // For easier documentation and type inference. /** * @name CachedTemplateData * @type {Object} * * @property {string} html * @property {Function|undefined} compiled * @property {string|undefined} tagName * @property {string|undefined} className * @property {string|undefined} id * @property {Object|undefined} attributes * @property {Object} _pluginData */ /** * @name Uncacheable * @type {Object} * * @property {boolean} invalid always true */ } ) );
import { $, ensureEventExists } from "../api/jquery.js"; import { TD } from "../api/td.js"; import { ensurePropertyExists } from "../api/utils.js"; function reloadScheduledColumn() { const column = Object.values(TD.controller.columnManager.getAll()).find(column => column.model.state.type === "scheduled"); if (column) { setTimeout(function() { column.reloadTweets(); }, 1000); } } /** * Works around scheduled tweets not showing up sometimes after being sent. */ export default function() { ensurePropertyExists(TD, "controller", "columnManager", "getAll"); ensureEventExists(document, "dataTweetSent"); $(document).on("dataTweetSent", function(e, data) { if ("request" in data && "scheduledDate" in data.request) { reloadScheduledColumn(); } }); };
import gulp from 'gulp'; import path from 'path'; import runSequence from 'run-sequence'; import { spawn } from 'child_process'; const pkg = require('../package.json'); function zip(src, dest) { const current_process = spawn('7z', ['a', '-tzip', dest, src], {cwd: './tmp'}); let is_error = false; return new Promise((resolve, reject) => { current_process.stdout.on('data', function(msg) { console.log(msg.toString()); }); current_process.stderr.on('data', function(msg) { console.error(msg.toString()); is_error = true; }); current_process.on('close', function(code) { if (is_error) return reject(); return resolve(); }); }); } function releaseFile(platform) { return `Championify-${platform}-${pkg.version}.zip`; } gulp.task('zip:osx', function(cb) { const src = `${pkg.name}.app`; const dest = path.join('../releases', releaseFile('OSX')); return zip(src, dest, cb); }); gulp.task('zip:win', function(cb) { const src = pkg.name; const dest = path.join('../releases', releaseFile('WIN')); return zip(src, dest, cb); }); gulp.task('zip:all', function(cb) { return runSequence(['zip:osx', 'zip:win'], cb); });
function getParam(e){e=e.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var n="[\\?&]"+e+"=([^&#]*)",t=new RegExp(n),r=t.exec(window.location.href);return null==r?"":r[1]}function getQueryString(){var e=window.location.search.substring(1),n=e.split("?");return n=n.join(""),n.length>0?n="?"+n:(n=e.split("#!"),n=n.join(""),n.length>0&&(n="#!"+n)),n}function redirectURL(e){var n=getQueryString(),t=getParam("fullsite");screen.width<700&&"true"!=t&&(window.location=e+n)}
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define(["require","exports","../../../../../../core/tsSupport/makeTemplateObjectHelper","../../shaderModules/interfaces"],function(n,e,b,c){Object.defineProperty(e,"__esModule",{value:!0});e.RibbonVertexPosition=function(a,d){a.vertex.uniforms.add("intrinsicWidth","float");d.vvSize?(a.attributes.add("sizeFeatureAttribute","float"),a.vertex.uniforms.add("vvSizeMinSize","vec3"),a.vertex.uniforms.add("vvSizeMaxSize","vec3"),a.vertex.uniforms.add("vvSizeOffset","vec3"),a.vertex.uniforms.add("vvSizeFactor", "vec3"),a.vertex.code.add(c.glsl(f||(f=b(["\n float getSize() {\n return intrinsicWidth * clamp(vvSizeOffset + sizeFeatureAttribute * vvSizeFactor, vvSizeMinSize, vvSizeMaxSize).x;\n }\n "],["\n float getSize() {\n return intrinsicWidth * clamp(vvSizeOffset + sizeFeatureAttribute * vvSizeFactor, vvSizeMinSize, vvSizeMaxSize).x;\n }\n "]))))):(a.attributes.add("size","float"),a.vertex.code.add(c.glsl(g||(g=b(["\n float getSize(){\n return intrinsicWidth * size;\n }\n "], ["\n float getSize(){\n return intrinsicWidth * size;\n }\n "])))));d.vvOpacity?(a.attributes.add("opacityFeatureAttribute","float"),a.vertex.defines.addInt("VV_OPACITY_N",8),a.vertex.code.add(c.glsl(h||(h=b(["\n uniform float vvOpacityValues[VV_OPACITY_N];\n uniform float vvOpacityOpacities[VV_OPACITY_N];\n\n float interpolateOpacity( float value ){\n if (value \x3c\x3d vvOpacityValues[0]) {\n return vvOpacityOpacities[0];\n }\n\n for (int i \x3d 1; i \x3c VV_OPACITY_N; ++i) {\n if (vvOpacityValues[i] \x3e\x3d value) {\n float f \x3d (value - vvOpacityValues[i-1]) / (vvOpacityValues[i] - vvOpacityValues[i-1]);\n return mix(vvOpacityOpacities[i-1], vvOpacityOpacities[i], f);\n }\n }\n\n return vvOpacityOpacities[VV_OPACITY_N - 1];\n }\n\n vec4 applyOpacity( vec4 color ){\n return vec4(color.xyz, interpolateOpacity(opacityFeatureAttribute));\n }\n "], ["\n uniform float vvOpacityValues[VV_OPACITY_N];\n uniform float vvOpacityOpacities[VV_OPACITY_N];\n\n float interpolateOpacity( float value ){\n if (value \x3c\x3d vvOpacityValues[0]) {\n return vvOpacityOpacities[0];\n }\n\n for (int i \x3d 1; i \x3c VV_OPACITY_N; ++i) {\n if (vvOpacityValues[i] \x3e\x3d value) {\n float f \x3d (value - vvOpacityValues[i-1]) / (vvOpacityValues[i] - vvOpacityValues[i-1]);\n return mix(vvOpacityOpacities[i-1], vvOpacityOpacities[i], f);\n }\n }\n\n return vvOpacityOpacities[VV_OPACITY_N - 1];\n }\n\n vec4 applyOpacity( vec4 color ){\n return vec4(color.xyz, interpolateOpacity(opacityFeatureAttribute));\n }\n "]))))): a.vertex.code.add(c.glsl(k||(k=b(["\n vec4 applyOpacity( vec4 color ){\n return color;\n }\n "],["\n vec4 applyOpacity( vec4 color ){\n return color;\n }\n "]))));d.vvColor?(a.attributes.add("colorFeatureAttribute","float"),a.vertex.defines.addInt("VV_COLOR_N",8),a.vertex.code.add(c.glsl(l||(l=b(["\n uniform float vvColorValues[VV_COLOR_N];\n uniform vec4 vvColorColors[VV_COLOR_N];\n\n vec4 interpolateColor( float value ) {\n if (value \x3c\x3d vvColorValues[0]) {\n return vvColorColors[0];\n }\n\n for (int i \x3d 1; i \x3c VV_COLOR_N; ++i) {\n if (vvColorValues[i] \x3e\x3d value) {\n float f \x3d (value - vvColorValues[i-1]) / (vvColorValues[i] - vvColorValues[i-1]);\n return mix(vvColorColors[i-1], vvColorColors[i], f);\n }\n }\n\n return vvColorColors[VV_COLOR_N - 1];\n }\n\n vec4 getColor(){\n return applyOpacity(interpolateColor(colorFeatureAttribute));\n }\n "], ["\n uniform float vvColorValues[VV_COLOR_N];\n uniform vec4 vvColorColors[VV_COLOR_N];\n\n vec4 interpolateColor( float value ) {\n if (value \x3c\x3d vvColorValues[0]) {\n return vvColorColors[0];\n }\n\n for (int i \x3d 1; i \x3c VV_COLOR_N; ++i) {\n if (vvColorValues[i] \x3e\x3d value) {\n float f \x3d (value - vvColorValues[i-1]) / (vvColorValues[i] - vvColorValues[i-1]);\n return mix(vvColorColors[i-1], vvColorColors[i], f);\n }\n }\n\n return vvColorColors[VV_COLOR_N - 1];\n }\n\n vec4 getColor(){\n return applyOpacity(interpolateColor(colorFeatureAttribute));\n }\n "]))))): (a.attributes.add("color","vec4"),a.vertex.code.add(c.glsl(m||(m=b(["\n vec4 getColor(){\n return applyOpacity(color);\n }\n "],["\n vec4 getColor(){\n return applyOpacity(color);\n }\n "])))))};var f,g,h,k,l,m});
import logger from '../../logging'; export default logger.child({module: 'resources', resource: 'account'});
/* eslint-disable max-len, camelcase */ 'use strict'; exports.seed = function(knex) { return knex('tasks').del() .then(() => { return knex('tasks').insert([{ id: 1, column_index: 1, short_description: 'Prepare Day 1 of Angular Curriculum', long_description: 'Focus on getting students with the purpose of ' + 'frontend development in a goal to fully understand the importance ' + 'of planning your UI before implementation.', column_id: 2, is_archived: false, created_at: new Date('2016-10-25 14:26:16 UTC'), updated_at: new Date('2016-10-25 14:26:16 UTC') }, { id: 2, column_index: 1, short_description: 'Prepare Day 2 of Angular Curriculum', long_description: 'Focus on taking students to understand and build ' + 'the initial view based on the UI plan.', column_id: 1, is_archived: false, created_at: new Date('2016-10-25 14:26:16 UTC'), updated_at: new Date('2016-10-25 14:26:16 UTC') }]); }) .then(() => { return knex.raw( "SELECT setval('tasks_id_seq', (SELECT MAX(id) FROM tasks));" ); }); };
var class_property_two = [ [ "SetUp", "class_property_two.html#aa3ab39cf4e6c751cb0788c575bf92ca2", null ], [ "TearDown", "class_property_two.html#aa4ffb2b9dddeba69f0f9baf133f06ef2", null ] ];
var base = require('../base') var ERROR_LEVEL = base.ERROR_LEVEL var Class = base.Class var RuleChecker = base.RuleChecker var helper = require('./helper'); module.exports = global.FEDUseSingleQuotation = new Class(RuleChecker, function() { this.__init__ = function(self) { self.id = 'single-quotation' self.errorLevel = ERROR_LEVEL.WARNING self.errorMsg = 'replace " with \' in "${selector}"' } this.check = function(self, rule, config) { if (self._findDouble(rule.value)) return false return true } this.fix = function(self, rule, config) { if (self._findDouble(rule.value)) rule.fixedValue = rule.fixedValue.replace(/"/g, "'") } this._findDouble = function(self, value) { return value.indexOf('"') != -1 } this.__doc__ = { "summary":"使用单引号", "desc":"CSS的属性取值一律使用单引号<code>'</code>, 不允许使用双引号" } })
define(['app', 'lodash'], function(app, _) { app.factory("mongoStorage", ['$http','$rootScope','$q','$timeout','$filter', function($http,$rootScope,$q,$timeout,$filter) { var clientOrg = 0; // means cbd //============================================================ // //============================================================ function save(schema, doc) { var url = 'https://api.cbd.int/api/v2016/' + schema; var params = {}; if (!doc.meta) doc.meta ={}; if (!doc.meta.clientOrg) doc.meta.clientOrg = clientOrg; if (!doc.clientOrg) doc.clientOrg = clientOrg; if (doc._id) { params.id = doc._id; url = url + '/' + doc._id; return $http.patch(url, doc, params); } else { return $http.post(url, doc, params); } //create } //============================================================ // //============================================================ async function loadDoc(schema, _id) { try{ const { data } = await $http.get(`https://api.cbd.int/api/v2016/${schema}/${_id}`) return _.isEmpty(data)? false : data }catch(e){ console.error('mongo-storage.loadDoc',e.data) } } //============================================================ // //============================================================ function getReservations(start, end, location, type,fields) { var params = {}; params = { q: { 'location.room': location.room, '$and': [{ 'start': { '$gte': { '$date': start } } }, { 'end': { '$lt': { '$date': end } } }], 'meta.status': { $nin: ['archived', 'deleted'] }, }, 'f':fields }; if(type)params.q.type=type; //TODO search if parent and if yes search for parent or children if (type && _.isString(type)) { return getChildrenTypes(type).then(function(typeArr) { params.q.$and.push({ 'type': { '$in': typeArr } }); return $http.get('https://api.cbd.int/api/v2016/reservations', { 'params': params }); }); } else return $http.get('https://api.cbd.int/api/v2016/reservations', { 'params': params }); } // getDocs //============================================================ // //============================================================ function getRecurrences(seriesId) { var params = {}; if(!parent) throw "Error: no parent id passed to getReccurences."; params ={ q: { 'meta.status': { $nin: ['archived', 'deleted'] }, // },s:{'start':1}}; params.q.seriesId=seriesId; return $http.get('https://api.cbd.int/api/v2016/reservations/', { 'params': params }); } // getReccurences //============================================================ // //============================================================ function loadDocs(schema,q, pageNumber,pageLength,count,sort,fields) { var params = {}; if(!sort) sort={'meta.modifiedOn':-1}; if (!schema) throw "Error: failed to indicate schema loadDocs"; params = { q: q, sk: pageNumber, l: pageLength, s:sort,//{'meta':{'modifiedOn':1}}//{'meta.modifiedOn':1}, f:fields }; if(!count) return $http.get('https://api.cbd.int/api/v2016/' + schema, {'params': params}); else return injectCount(schema,params); } //============================================================ // //============================================================ function injectCount(schema,params) { var promises=[]; promises[0]=$http.get('https://api.cbd.int/api/v2016/' + schema, {'params':_.clone(params)}); params.c=1; promises[1]=$http.get('https://api.cbd.int/api/v2016/' + schema, {'params': params}); if(!params.q['meta.status'] || _.isObject(params.q['meta.status'])) _.each(['draft','request','published','canceled','rejected','archived'], function(status) { var tempP = _.cloneDeep(params); tempP.q['meta.status']=status; promises.push($http.get('https://api.cbd.int/api/v2016/' + schema, {'params': tempP})); }); return $q.all(promises).then(function(res){ res[0].count=res[1].data.count; res[0].facits={all:res[1].data.count}; var count=2; if(!params.q['meta.status'] || _.isObject(params.q['meta.status'])) _.each(['draft','request','published','canceled','rejected','archived'], function(status) { res[0].facits[status]=res[count].data.count; count++; }); else res[0].facits[params.q['meta.status']]=res[1].data.count; return res[0]; }); } //============================================================ // //============================================================ function getDocs(schema, status, cache) { if (!cache) cache = false; var params = {}; if (!schema) throw "Error: failed to indicate schema loadOwnerDocs"; if (!status) { params = { q: { 'meta.status': { $nin: ['archived', 'deleted'] } }, }; return $http.get('https://api.cbd.int/api/v2016/' + schema, { 'params': params, 'cache': cache }); } if (!_.isArray(status)) { params = { q: { 'meta.status': status } }; return $http.get('https://api.cbd.int/api/v2016/' + schema, { 'params': params, 'cache': cache }); } else { params = { q: { 'meta.status': { $in: status } } }; return $http.get('https://api.cbd.int/api/v2016/' + schema, { 'params': params, 'cache': cache }); } } // getDocs //============================================================ // //============================================================ function getAllOrgs() { const cache = true const q = { 'meta.status': 'published' } const params = { q } try{ return $http.get('https://api.cbd.int/api/v2016/inde-orgs', { params, cache }); }catch(e){ console.error('mongo-storage.getAllOrgs',e) } } // getDocs var loadOrgsInProgress=null; var allOrgs = []; //============================================================ // //============================================================ async function loadOrgs(force) { if(loadOrgsInProgress) return loadOrgsInProgress; const hasBeenModified = await isModified('inde-orgs') const notInLocalStorage = !localStorage.getItem('allOrgs') const loadFromApi = force || hasBeenModified || notInLocalStorage const cache = true const q = { 'meta.status': 'published' } const params = { q } if(loadFromApi) { try{ const promises = [ countries(), $http.get('https://api.cbd.int/api/v2016/inde-orgs', { params, cache })]// return loadOrgsInProgress = $q.all(promises).then((data) =>{ const orgsAndParties = _.union(data[0], data[1].data); allOrgs = orgsAndParties localStorage.setItem('allOrgs', JSON.stringify(orgsAndParties)); return orgsAndParties; }); }catch(e){ console.error('mongo-storage.loadOrgs', e) } } loadOrgsInProgress = null if(_.isEmpty(allOrgs)) allOrgs = JSON.parse(localStorage.getItem('allOrgs')); return allOrgs; } // loadDocs var countriesData; //============================================================ // //============================================================ function countries() { if (countriesData) return $q(function(resolve) { return resolve(countriesData); }); if (!localStorage.getItem('countries')) return $http.get('https://api.cbd.int/api/v2015/countries', { cache: true }).then(function(o) { var countries = $filter("orderBy")(o.data, "name.en"); _.each(countries, function(c) { c.title = c.name.en; c.identifier = c.code.toLowerCase(); c._id = c.identifier; }); countriesData =countries; localStorage.setItem('countries', JSON.stringify(countries)); return countries; }); else return $q(function(resolve) { return resolve(JSON.parse(localStorage.getItem('countries'))); }); } //======================================================================= // //======================================================================= function deleteDoc(schema, docObj, _id) { if (!docObj.meta) docObj.meta = {}; docObj.meta.status = 'deleted'; return save(schema, docObj, _id); } //============================================================ // //============================================================ function getConferenceRooms(id) { return $http.get('https://api.cbd.int/api/v2016/conferences/' + id + '/rooms', {}); } // getConferenceRooms //============================================================ // //============================================================ function getConferences() { var params = {}; params = { q: { 'meta.status': { $nin: ['archived', 'deleted'] } }, s: { 'start': -1 } }; return $http.get('https://api.cbd.int/api/v2016/conferences', { 'params': params, 'cache': true }); } //============================================================ // //============================================================ function getChildrenTypes(type) { var types = []; types.push(type); var params = { q: { 'parent': type } }; return $http.get('https://api.cbd.int/api/v2016/types', { 'params': params }).then(function(responce) { _.each(responce.data, function(t) { types.push(t._id); }); return types; }); } //loadSideEventTypes //============================================================ // //============================================================ function syncSideEvents(conferenceId) { if (!conferenceId) throw "Error no confrence selected to sync"; return $http.get('https://api.cbd.int/api/v2016/reservations/sync/side-events/' + conferenceId); } var conferences = []; //============================================================ // //============================================================ function loadConferences(force) { var allPromises = []; var numPromises= 1; var modified = true; allPromises[0] = isModified('conferences').then( function(isModified) { modified = (!localStorage.getItem('allConferences') || isModified || force); var params = {}; if (modified) { params = { q: { timezone: { $exists: true }, venueId: { $exists: true } // TMP for compatibility with coference collection; }, s : { StartDate : -1 }, f : {Title:1,MajorEventIDs:1,StartDate:1,EndDate:1,timezone:1,schedule:1,venueId:1,seTiers:1,"conference.streamId":1, code:1} }; numPromises++; allPromises[1]= $http.get('https://api.cbd.int/api/v2016/conferences', { 'params': params }).then(function(res) { var oidArray = []; conferences=res.data; numPromises+=conferences.length; _.each(conferences,function(conf){ oidArray=[]; _.each(conf.MajorEventIDs, function(id) { oidArray.push({ '$oid': id }); }); allPromises.push($http.get("https://api.cbd.int/api/v2016/meetings", { params: { q: { _id: { $in: oidArray } }, // f : {EVT_REG_MTG_CD:1,agenda:1} } }).then(function(m) { conf.meetings = m.data; })); }); }); } else{ if(_.isEmpty(conferences)) conferences=JSON.parse(localStorage.getItem('allConferences')); numPromises++; allPromises.push($q(function(resolve) {resolve(conferences);})); } }); return $q(function(resolve, reject) { var timeOut = setInterval(function() { if ((allPromises.length === 2 && !modified) || (modified && numPromises === allPromises.length && allPromises.length > 2) ) $q.all(allPromises).then(function(res) { clearInterval(timeOut); if(modified) localStorage.setItem('allConferences', JSON.stringify(conferences)); resolve(conferences); }); }, 100); $timeout(function(){ clearInterval(timeOut); reject('Error: getting conferences timed out 5 seconds'); },5000); }); } // loadDocs var types = {}; //============================================================ // //============================================================ function loadTypes(schema) { var params = { q: {'schema':schema,'meta.status':{'$nin':['deleted','archived']}}, f:{parent:1,title:1,color:1} }; return $http.get('https://api.cbd.int/api/v2016/types', { 'params': params }).then(function(res) { types[schema]=res.data; _.each(types[schema], function(type, key) { type.showChildren = true; if (type.parent) { var parentObj = _.find(types[schema], {'_id': type.parent}); if (!parentObj) throw "error ref to parent res type not found."; if (!parentObj.children) parentObj.children = []; parentObj.children.push(type); delete(types[schema][key]); } }); return types[schema]; }); } // loadTypes var isModifiedInProgress = {}; //======================================================================= // //======================================================================= function isModified(schema) { if(!isModifiedInProgress)isModifiedInProgress = {}; if(isModifiedInProgress && isModifiedInProgress[schema]) return isModifiedInProgress[schema]; var isModified = true; var modifiedSchemas = localStorage.getItem('modifiedSchemas'); if (modifiedSchemas) modifiedSchemas = JSON.parse(modifiedSchemas); isModifiedInProgress[schema]= $q(function(resolve, reject) { $http.get('https://api.cbd.int/api/v2016/' + schema + '/last-modified').then(function(lastModified) { if (!lastModified.data) reject('Error: no date returned'); if (!modifiedSchemas || lastModified.data !== modifiedSchemas[schema]) { if (!modifiedSchemas) modifiedSchemas = {}; modifiedSchemas[schema] = lastModified.data; localStorage.setItem('modifiedSchemas', JSON.stringify(modifiedSchemas)); isModifiedInProgress=null; resolve(isModified); } else { isModified = false; isModifiedInProgress=null; resolve(isModified); } }).catch(function(err) { isModifiedInProgress=null; reject(err); }); }); return isModifiedInProgress[schema]; } return { loadTypes:loadTypes, loadConferences:loadConferences, getRecurrences:getRecurrences, getConferences: getConferences, getAllOrgs: getAllOrgs, syncSideEvents: syncSideEvents, deleteDoc: deleteDoc, save: save, getConferenceRooms: getConferenceRooms, getReservations: getReservations, getDocs: getDocs, loadDocs:loadDocs, loadOrgs:loadOrgs, loadDoc:loadDoc }; //return }]); //factory }); //require
var https = require('https'); var url = require('url'); module.exports = function (options) { options = options || {}; var agent = new https.Agent(options); return agent; };
/* eslint-disable jsx-a11y/anchor-is-valid */ import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Paper from '@material-ui/core/Paper'; import Breadcrumbs from '@material-ui/core/Breadcrumbs'; import Typography from '@material-ui/core/Typography'; import Link from '@material-ui/core/Link'; const useStyles = makeStyles(theme => ({ root: { justifyContent: 'center', flexWrap: 'wrap', }, paper: { padding: theme.spacing(1, 2), }, })); function handleClick(event) { event.preventDefault(); alert('You clicked a breadcrumb.'); } export default function CollapsedBreadcrumbs() { const classes = useStyles(); return ( <Paper elevation={0} className={classes.paper}> <Breadcrumbs maxItems={2} aria-label="breadcrumb"> <Link color="inherit" href="#" onClick={handleClick}> Home </Link> <Link color="inherit" href="#" onClick={handleClick}> Catalog </Link> <Link color="inherit" href="#" onClick={handleClick}> Accessories </Link> <Link color="inherit" href="#" onClick={handleClick}> New Collection </Link> <Typography color="textPrimary">Belts</Typography> </Breadcrumbs> </Paper> ); }
/** * This behavior adds a class of 'js' to the element. * * Although simple, this technique is useful when applied to the BODY element in the DOM. * Stylesheets can then target the page if the page has Javascript enabled (as the new class * will be applied), or target a Javascript less environment where the class will not be applied. */ Elemental.JavascriptEnabled = function(el){ el.addClass('js'); };
'use strict'; /* https://github.com/angular/protractor/blob/master/docs/toc.md */ // describe('my app', function() { // // browser.get('index.html'); // // it('should automatically redirect to /view1 when location hash/fragment is empty', function() { // expect(browser.getLocationAbsUrl()).toMatch("/view1"); // }); // // // describe('view1', function() { // // beforeEach(function() { // browser.get('index.html#/view1'); // }); // // // it('should render view1 when user navigates to /view1', function() { // expect(element.all(by.css('[ng-view] p')).first().getText()). // toMatch(/partial for view 1/); // }); // // }); // // // describe('view2', function() { // // beforeEach(function() { // browser.get('index.html#/view2'); // }); // // // it('should render view2 when user navigates to /view2', function() { // expect(element.all(by.css('[ng-view] p')).first().getText()). // toMatch(/partial for view 2/); // }); // // }); // });
const Shader = require('../') const test = require('tape') const GL = require('gl') const gl = GL(256, 256) test('kindred-shader: compiler errors', function (t) { const valid = Shader` attribute vec2 position; void vert() { gl_Position = vec4(position, 1, 1); } void frag() { gl_FragColor = vec4(1); } ` const invalid = Shader` attribute vec2 position; void vert() { unused_reference; gl_Position = vec4(position, 1, 1); } void frag() { gl_FragColor = vec4(1); } ` t.throws(function () { invalid.bind(gl) }, 'invalid shaders throw on binding') t.throws(function () { invalid.bind(gl) }, 'invalid shaders throw every binding') t.doesNotThrow(function () { valid.bind(gl) }, 'valid shaders do not throw on binding') t.equal(valid.compiled, true, 'valid shader considered "compiled"') t.equal(invalid.compiled, false, 'invalid shader not considered "compiled"') try { invalid.bind(gl) } catch (e) { t.ok( e.message.indexOf('1:') !== -1 && e.message.indexOf('2:') !== -1 && e.message.indexOf('3:') !== -1 , 'line numbers included in error output') } t.end() }) test('kindred-shader: invalid context errors', function (t) { const secondary = GL(64, 64) const shader = Shader` attribute vec2 position; void vert() { gl_Position = vec4(position, 1, 1); } void frag() { gl_FragColor = vec4(1); } ` t.throws(function () { shader.bind() }, 'binding without a context causes an error') t.doesNotThrow(function () { shader.bind(gl) }, 'can be attempted again successfully') t.throws(function () { shader.bind(secondary) }, 'errors when handed a fresh context') t.doesNotThrow(function () { shader.dispose() shader.bind(secondary) }, 'can use .dispose() to set a fresh context safely') t.ok(shader.compiled, 'shader.compiled === true') t.end() }) test('kindred-shader: glslify error (without transform)', function (t) { try { Shader` attribute vec2 position; #pragma glslify: square = require('glsl-square-frame') void vert() { gl_Position = vec4(position, 1, 1); } void frag() { gl_FragColor = vec4(1); } ` } catch (e) { t.ok(e.message.indexOf('glslify') !== -1, 'error on using glslify, referring as such') t.end() return } t.fail('Shader did not throw error on creation') })
// Add residence data if (Residences.find().count() === 0) { Residences.insert({ building: 'Sibley', type: 'Residence Hall', beds: 'Single', tenantNames: [], tenants: 0 // use $inc }); Residences.insert({ building: 'Shuniah', type: 'Residence Hall', beds: 'Double', tenantNames: [], tenants: 0 // use $inc }); Residences.insert({ building: 'Bartley', type: 'Townhouse', beds: 'Double', tenantNames: [], tenants: 0 // use $inc }); Residences.insert({ building: 'Chicago', type: 'Apartment', beds: 'Double', tenantNames: [], tenants: 0 // use $inc }); Residences.insert({ building: 'Ripley', type: 'Townhouse', beds: 'Single', tenantNames: [], tenants: 0 // use $inc }); Residences.insert({ building: 'Ridgemont', type: 'Residence Hall', beds: 'Single Basic', tenantNames: [], tenants: 0 // use $inc }); }
var AboutMeEditEntryView = Backbone.View.extend({ events: { "click #save": "saveEntry", "click #delete": "deleteEntry", "click #close-success": "closeSuccess" }, render: function() { $(this.el).html(template.preferencesView.aboutMeEditEntry({title: this.model.get("title"), body:this.model.get("body")})); this.notificationSuccess = $(this.el).find("#notif-success"); return this; }, deleteEntry: function(){ this.model.destroy(); $(this.el).fadeOut(function(){ $(this).remove(); }); }, saveEntry: function(){ var html = $(this.el); var notif = this.notificationSuccess; this.model.save({title: html.find("#title").val(), body: html.find("#body").val()},{ success:function(){ notif.show(); } }); }, closeSuccess: function(){ this.notificationSuccess.hide(); } });
module.exports = function getTaxRate(income) { if (income <= 18200) return 0; if (income <= 37000) return 0.19 - 3458/income; if (income <= 80000) return 0.325 - 8453/income; if (income <= 180000) return 0.37 - 12053/income; return 0.45 - 26453/income; };
module.exports = { favicon: { src: '<%= src %>/favicon.ico', dest: '<%= build %>/favicon.ico' }, bower_components: { files: { '<%= build %>/css/codemirror.css':'bower_components/codemirror/lib/codemirror.css' } }, 'wri-skeleton': { files: { '<%= build %>/css/wri-skeleton.css':'<%= tmp %>/css/wri-skeleton.css', '<%= dist %>/wri-skeleton.css':'<%= tmp %>/css/wri-skeleton.css', '<%= build %>/js/wri-skeleton.min.js':'<%= dist %>/js/wri-skeleton.min.js' } } };
'use strict' const apemandb = require('apemandb') let db = apemandb({ env: require('../env')('database'), models: `${__dirname}/models/*.json`, addons: `${__dirname}/addons/*.addon.js`, seeds: `/seeds/${process.env.NODE_ENV}/*.seed.js` }) // Models are exposed as db.models.<ModelName> (like db.models.User) module.exports = db
angular.module('Atarnia.utils').factory('_uploader', ['$upload', '_apiAdapter', _uploader]); function _uploader($upload, _apiAdapter) { return { setUp: setUpUploader }; function setUpUploader(scope, fileFieldLabel, tokenFieldLabel, progressFieldLabel) { var url = _apiAdapter.getApiUrl() + 'upload/', uploader; scope.$watch(fileFieldLabel, function() { var file = scope[fileFieldLabel] && scope[fileFieldLabel][0]; if (file){ if (uploader) { uploader.abort(); } uploader = $upload.upload({ url: url, method: 'POST', file: file }) .progress(function(evt) { scope[progressFieldLabel] = scope[progressFieldLabel] || {}; scope[progressFieldLabel][fileFieldLabel] = { progress: parseInt(100.0 * evt.loaded / evt.total), loaded: evt.loaded, total: evt.total }; }) .success(function(data, status, headers, config) { scope[tokenFieldLabel] = data.token; delete scope[progressFieldLabel][fileFieldLabel]; }) .error(function(reason){ scope[progressFieldLabel][fileFieldLabel] = { error: reason }; }); } }); } }
// Dependencies var express = require('express'); var path = require('path'); // Args var port = process.argv[2]; var template = process.argv[3]; // App var app = express(); // App settings app.set('views', template || path.join(__dirname, 'templates')); app.set('view engine', 'jade'); // URL app.get('/home', function(request, response){ var tplData = { 'date': new Date().toDateString() } response.render('index', tplData); }); app.listen(port || 8080);
'use strict'; const UserHandler = require('../handlers/user'); const user = new UserHandler(require('../services/user')); const middleware = require('../../../middleware'); module.exports = function (app) { app.route('/users') .post(user.create.bind(user)); app.route('/users/likes') .put(middleware.getClubData, user.editLikes.bind(user)); app.route('/users/dislikes') .put(middleware.getClubData, user.editDisLikes.bind(user)); app.route('users/exists') .get(user.isUserExists.bind(this)); app.route('/users/:user') .get(user.getOne.bind(user)); };
import { StyleSheet } from 'aphrodite'; import * as fonts from '../../style/fonts'; import * as colors from '../../style/colors'; export default StyleSheet.create({ quiz: { marginTop: '3em' }, flower: { marginTop: '1rem', }, img: { maxWidth: '100%', height: 'auto', marginBottom: '20px' }, rsvpButton: { fontSize: fonts.medium }, rsvpButtonText: { fontSize: fonts.smallerer, fontWeight: 200 }, score: { marginBottom: '2em' }, retake: { marginBottom: '2em', fontSize: '2em', }, retakeLink: { textDecoration: 'underline', cursor: 'pointer', color: colors.blue, ':hover': { color: colors.aquaMarine } } });
import { __decorate } from "tslib"; import { customAttribute, inject } from "aurelia-framework"; let AttachFocusAttribute = /** @class */ (() => { let AttachFocusAttribute = class AttachFocusAttribute { constructor(element) { this.element = element; } attached() { if (this.value === '' || (this.value && this.value !== 'false')) { this.element.focus(); } } }; AttachFocusAttribute = __decorate([ inject(Element), customAttribute('ux-attach-focus') ], AttachFocusAttribute); return AttachFocusAttribute; })(); export { AttachFocusAttribute }; //# sourceMappingURL=attach-focus-attribute.js.map
'use strict'; module.exports = function (verificationToken, onSlackEvent) { return function (req, res, next) { if (req.method !== 'POST') return next(); if (!req.body) { res.stausCode = 400; res.end('bad request - no body found'); return; } var body = req.body.payload ? JSON.parse(req.body.payload) : req.body; if (verificationToken && body.token !== verificationToken) { res.statusCode = 403; res.end('could not verify slack token'); return; } if (body.type === 'url_verification') return res.end(body.challenge); if (body.type === 'event_callback') { onSlackEvent(body, function (err) { if (!err) return res.end('ok'); res.statusCode = 400; res.end('please retry'); }); return; } res.statusCode = 400; res.end('bad request - not slack event api'); }; };
"use strict"; var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) { return typeof obj === "undefined" ? "undefined" : _typeof2(obj); } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj); }; !function (t, e) { "object" == (typeof exports === "undefined" ? "undefined" : _typeof(exports)) && "undefined" != typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define(e) : t.VueRouter = e(); }(undefined, function () { "use strict"; function t(t, e) { if (!t) throw new Error("[vue-router] " + e); }function e(t, e) { t || "undefined" != typeof console && console.warn("[vue-router] " + e); }function n(t, n) { switch (typeof n === "undefined" ? "undefined" : _typeof(n)) {case "undefined": return;case "object": return n;case "function": return n(t);case "boolean": return n ? t.params : void 0;default: e(!1, 'props in "' + t.path + '" is a ' + (typeof n === "undefined" ? "undefined" : _typeof(n)) + ", expecting an object, function or boolean.");} }function r(t, n) { if (void 0 === n && (n = {}), t) { var r;try { r = o(t); } catch (t) { e(!1, t.message), r = {}; }for (var i in n) { r[i] = n[i]; }return r; }return n; }function o(t) { var e = {};return (t = t.trim().replace(/^(\?|#|&)/, "")) ? (t.split("&").forEach(function (t) { var n = t.replace(/\+/g, " ").split("="), r = $t(n.shift()), o = n.length > 0 ? $t(n.join("=")) : null;void 0 === e[r] ? e[r] = o : Array.isArray(e[r]) ? e[r].push(o) : e[r] = [e[r], o]; }), e) : e; }function i(t) { var e = t ? Object.keys(t).map(function (e) { var n = t[e];if (void 0 === n) return "";if (null === n) return _t(e);if (Array.isArray(n)) { var r = [];return n.slice().forEach(function (t) { void 0 !== t && (null === t ? r.push(_t(e)) : r.push(_t(e) + "=" + _t(t))); }), r.join("&"); }return _t(e) + "=" + _t(n); }).filter(function (t) { return t.length > 0; }).join("&") : null;return e ? "?" + e : ""; }function a(t, e, n) { var r = { name: e.name || t && t.name, meta: t && t.meta || {}, path: e.path || "/", hash: e.hash || "", query: e.query || {}, params: e.params || {}, fullPath: c(e), matched: t ? u(t) : [] };return n && (r.redirectedFrom = c(n)), Object.freeze(r); }function u(t) { for (var e = []; t;) { e.unshift(t), t = t.parent; }return e; }function c(t) { var e = t.path, n = t.query;void 0 === n && (n = {});var r = t.hash;return void 0 === r && (r = ""), (e || "/") + i(n) + r; }function s(t, e) { return e === St ? t === e : !!e && (t.path && e.path ? t.path.replace(Tt, "") === e.path.replace(Tt, "") && t.hash === e.hash && p(t.query, e.query) : !(!t.name || !e.name) && t.name === e.name && t.hash === e.hash && p(t.query, e.query) && p(t.params, e.params)); }function p(t, e) { void 0 === t && (t = {}), void 0 === e && (e = {});var n = Object.keys(t), r = Object.keys(e);return n.length === r.length && n.every(function (n) { return String(t[n]) === String(e[n]); }); }function f(t, e) { return 0 === t.path.replace(Tt, "/").indexOf(e.path.replace(Tt, "/")) && (!e.hash || t.hash === e.hash) && h(t.query, e.query); }function h(t, e) { for (var n in e) { if (!(n in t)) return !1; }return !0; }function l(t) { if (!(t.metaKey || t.ctrlKey || t.shiftKey || t.defaultPrevented || void 0 !== t.button && 0 !== t.button)) { if (t.target && t.target.getAttribute) { var e = t.target.getAttribute("target");if (/\b_blank\b/i.test(e)) return; }return t.preventDefault && t.preventDefault(), !0; } }function d(t) { if (t) for (var e, n = 0; n < t.length; n++) { if (e = t[n], "a" === e.tag) return e;if (e.children && (e = d(e.children))) return e; } }function y(t) { if (!y.installed) { y.installed = !0, Ot = t, Object.defineProperty(t.prototype, "$router", { get: function get() { return this.$root._router; } }), Object.defineProperty(t.prototype, "$route", { get: function get() { return this.$root._route; } }), t.mixin({ beforeCreate: function beforeCreate() { this.$options.router && (this._router = this.$options.router, this._router.init(this), t.util.defineReactive(this, "_route", this._router.history.current)); } }), t.component("router-view", Et), t.component("router-link", Pt);var e = t.config.optionMergeStrategies;e.beforeRouteEnter = e.beforeRouteLeave = e.created; } }function v(t, e, n) { if ("/" === t.charAt(0)) return t;if ("?" === t.charAt(0) || "#" === t.charAt(0)) return e + t;var r = e.split("/");n && r[r.length - 1] || r.pop();for (var o = t.replace(/^\//, "").split("/"), i = 0; i < o.length; i++) { var a = o[i];"." !== a && (".." === a ? r.pop() : r.push(a)); }return "" !== r[0] && r.unshift(""), r.join("/"); }function m(t) { var e = "", n = "", r = t.indexOf("#");r >= 0 && (e = t.slice(r), t = t.slice(0, r));var o = t.indexOf("?");return o >= 0 && (n = t.slice(o + 1), t = t.slice(0, o)), { path: t, query: n, hash: e }; }function g(t) { return t.replace(/\/\//g, "/"); }function w(t, e, n) { var r = e || Object.create(null), o = n || Object.create(null);return t.forEach(function (t) { b(r, o, t); }), { pathMap: r, nameMap: o }; }function b(n, r, o, i, a) { var u = o.path, c = o.name;t(null != u, '"path" is required in a route configuration.'), t("string" != typeof o.component, 'route config "component" for path: ' + String(u || c) + " cannot be a string id. Use an actual component instead.");var s = { path: x(u, i), components: o.components || { default: o.component }, instances: {}, name: c, parent: i, matchAs: a, redirect: o.redirect, beforeEnter: o.beforeEnter, meta: o.meta || {}, props: null == o.props ? {} : o.components ? o.props : { default: o.props } };if (o.children && (o.name && o.children.some(function (t) { return (/^\/?$/.test(t.path) ); }) && e(!1, "Named Route '" + o.name + "' has a default child route. When navigating to this named route (:to=\"{name: '" + o.name + "'\"), the default child route will not be rendered. Remove the name from this route and use the name of the default child route for named links instead."), o.children.forEach(function (t) { var e = a ? g(a + "/" + t.path) : void 0;b(n, r, t, s, e); })), void 0 !== o.alias) if (Array.isArray(o.alias)) o.alias.forEach(function (t) { var e = { path: t, children: o.children };b(n, r, e, i, s.path); });else { var p = { path: o.alias, children: o.children };b(n, r, p, i, s.path); }n[s.path] || (n[s.path] = s), c && (r[c] ? a || e(!1, 'Duplicate named routes definition: { name: "' + c + '", path: "' + s.path + '" }') : r[c] = s); }function x(t, e) { return t = t.replace(/\/$/, ""), "/" === t[0] ? t : null == e ? t : g(e.path + "/" + t); }function k(t, e) { for (var n, r = [], o = 0, i = 0, a = "", u = e && e.delimiter || "/"; null != (n = Ft.exec(t));) { var c = n[0], s = n[1], p = n.index;if (a += t.slice(i, p), i = p + c.length, s) a += s[1];else { var f = t[i], h = n[2], l = n[3], d = n[4], y = n[5], v = n[6], m = n[7];a && (r.push(a), a = "");var g = null != h && null != f && f !== h, w = "+" === v || "*" === v, b = "?" === v || "*" === v, x = n[2] || u, k = d || y;r.push({ name: l || o++, prefix: h || "", delimiter: x, optional: b, repeat: w, partial: g, asterisk: !!m, pattern: k ? C(k) : m ? ".*" : "[^" + A(x) + "]+?" }); } }return i < t.length && (a += t.substr(i)), a && r.push(a), r; }function R(t, e) { return j(k(t, e)); }function O(t) { return encodeURI(t).replace(/[\/?#]/g, function (t) { return "%" + t.charCodeAt(0).toString(16).toUpperCase(); }); }function E(t) { return encodeURI(t).replace(/[?#]/g, function (t) { return "%" + t.charCodeAt(0).toString(16).toUpperCase(); }); }function j(t) { for (var e = new Array(t.length), n = 0; n < t.length; n++) { "object" == _typeof(t[n]) && (e[n] = new RegExp("^(?:" + t[n].pattern + ")$")); }return function (n, r) { for (var o = "", i = n || {}, a = r || {}, u = a.pretty ? O : encodeURIComponent, c = 0; c < t.length; c++) { var s = t[c];if ("string" != typeof s) { var p, f = i[s.name];if (null == f) { if (s.optional) { s.partial && (o += s.prefix);continue; }throw new TypeError('Expected "' + s.name + '" to be defined'); }if (Mt(f)) { if (!s.repeat) throw new TypeError('Expected "' + s.name + '" to not repeat, but received `' + JSON.stringify(f) + "`");if (0 === f.length) { if (s.optional) continue;throw new TypeError('Expected "' + s.name + '" to not be empty'); }for (var h = 0; h < f.length; h++) { if (p = u(f[h]), !e[c].test(p)) throw new TypeError('Expected all "' + s.name + '" to match "' + s.pattern + '", but received `' + JSON.stringify(p) + "`");o += (0 === h ? s.prefix : s.delimiter) + p; } } else { if (p = s.asterisk ? E(f) : u(f), !e[c].test(p)) throw new TypeError('Expected "' + s.name + '" to match "' + s.pattern + '", but received "' + p + '"');o += s.prefix + p; } } else o += s; }return o; }; }function A(t) { return t.replace(/([.+*?=^!:${}()[\]|\/\\])/g, "\\$1"); }function C(t) { return t.replace(/([=!:$\/()])/g, "\\$1"); }function _(t, e) { return t.keys = e, t; }function $(t) { return t.sensitive ? "" : "i"; }function T(t, e) { var n = t.source.match(/\((?!\?)/g);if (n) for (var r = 0; r < n.length; r++) { e.push({ name: r, prefix: null, delimiter: null, optional: !1, repeat: !1, partial: !1, asterisk: !1, pattern: null }); }return _(t, e); }function S(t, e, n) { for (var r = [], o = 0; o < t.length; o++) { r.push(P(t[o], e, n).source); }var i = new RegExp("(?:" + r.join("|") + ")", $(n));return _(i, e); }function q(t, e, n) { return L(k(t, n), e, n); }function L(t, e, n) { Mt(e) || (n = e || n, e = []), n = n || {};for (var r = n.strict, o = n.end !== !1, i = "", a = 0; a < t.length; a++) { var u = t[a];if ("string" == typeof u) i += A(u);else { var c = A(u.prefix), s = "(?:" + u.pattern + ")";e.push(u), u.repeat && (s += "(?:" + c + s + ")*"), s = u.optional ? u.partial ? c + "(" + s + ")?" : "(?:" + c + "(" + s + "))?" : c + "(" + s + ")", i += s; } }var p = A(n.delimiter || "/"), f = i.slice(-p.length) === p;return r || (i = (f ? i.slice(0, -p.length) : i) + "(?:" + p + "(?=$))?"), i += o ? "$" : r && f ? "" : "(?=" + p + "|$)", _(new RegExp("^" + i, $(n)), e); }function P(t, e, n) { return Mt(e) || (n = e || n, e = []), n = n || {}, t instanceof RegExp ? T(t, e) : Mt(t) ? S(t, e, n) : q(t, e, n); }function U(t) { var e, n, r = Nt[t];return r ? (e = r.keys, n = r.regexp) : (e = [], n = zt(t, e), Nt[t] = { keys: e, regexp: n }), { keys: e, regexp: n }; }function V(t, n, r) { try { var o = Jt[t] || (Jt[t] = zt.compile(t));return o(n || {}, { pretty: !0 }); } catch (t) { return e(!1, "missing param for " + r + ": " + t.message), ""; } }function M(t, n, o) { var i = "string" == typeof t ? { path: t } : t;if (i.name || i._normalized) return i;if (!i.path && i.params && n) { i = z({}, i), i._normalized = !0;var a = z(z({}, n.params), i.params);if (n.name) i.name = n.name, i.params = a;else if (n.matched) { var u = n.matched[n.matched.length - 1].path;i.path = V(u, a, "path " + n.path); } else e(!1, "relative params navigation requires a current route.");return i; }var c = m(i.path || ""), s = n && n.path || "/", p = c.path ? v(c.path, s, o || i.append) : n && n.path || "/", f = r(c.query, i.query), h = i.hash || c.hash;return h && "#" !== h.charAt(0) && (h = "#" + h), { _normalized: !0, path: p, query: f, hash: h }; }function z(t, e) { for (var n in e) { t[n] = e[n]; }return t; }function B(n) { function r(t) { w(t, p, f); }function o(t, n, r) { var o = M(t, n), i = o.name;if (i) { var a = f[i];e(a, "Route with name '" + i + "' does not exist");var u = U(a.path).keys.filter(function (t) { return !t.optional; }).map(function (t) { return t.name; });if ("object" != _typeof(o.params) && (o.params = {}), n && "object" == _typeof(n.params)) for (var s in n.params) { !(s in o.params) && u.indexOf(s) > -1 && (o.params[s] = n.params[s]); }if (a) return o.path = V(a.path, o.params, 'named route "' + i + '"'), c(a, o, r); } else if (o.path) { o.params = {};for (var h in p) { if (H(h, o.params, o.path)) return c(p[h], o, r); } }return c(null, o); }function i(n, r) { var i = n.redirect, u = "function" == typeof i ? i(a(n, r)) : i;if ("string" == typeof u && (u = { path: u }), !u || "object" != (typeof u === "undefined" ? "undefined" : _typeof(u))) return e(!1, "invalid redirect option: " + JSON.stringify(u)), c(null, r);var s = u, p = s.name, h = s.path, l = r.query, d = r.hash, y = r.params;if (l = s.hasOwnProperty("query") ? s.query : l, d = s.hasOwnProperty("hash") ? s.hash : d, y = s.hasOwnProperty("params") ? s.params : y, p) { var v = f[p];return t(v, 'redirect failed: named route "' + p + '" not found.'), o({ _normalized: !0, name: p, query: l, hash: d, params: y }, void 0, r); }if (h) { var m = I(h, n), g = V(m, y, 'redirect route with path "' + m + '"');return o({ _normalized: !0, path: g, query: l, hash: d }, void 0, r); }return e(!1, "invalid redirect option: " + JSON.stringify(u)), c(null, r); }function u(t, e, n) { var r = V(n, e.params, 'aliased route with path "' + n + '"'), i = o({ _normalized: !0, path: r });if (i) { var a = i.matched, u = a[a.length - 1];return e.params = i.params, c(u, e); }return c(null, e); }function c(t, e, n) { return t && t.redirect ? i(t, n || e) : t && t.matchAs ? u(t, e, t.matchAs) : a(t, e, n); }var s = w(n), p = s.pathMap, f = s.nameMap;return { match: o, addRoutes: r }; }function H(t, e, n) { var r = U(t), o = r.regexp, i = r.keys, a = n.match(o);if (!a) return !1;if (!e) return !0;for (var u = 1, c = a.length; u < c; ++u) { var s = i[u - 1], p = "string" == typeof a[u] ? decodeURIComponent(a[u]) : a[u];s && (e[s.name] = p); }return !0; }function I(t, e) { return v(t, e.parent ? e.parent.path : "/", !0); }function D() { window.addEventListener("popstate", function (t) { t.state && t.state.key && Z(t.state.key); }), window.addEventListener("scroll", N); }function F(e, n, r, o) { if (e.app) { var i = e.options.scrollBehavior;i && (t("function" == typeof i, "scrollBehavior must be a function"), e.app.$nextTick(function () { var t = J(), e = i(n, r, o ? t : null);if (e) { var a = "object" == (typeof e === "undefined" ? "undefined" : _typeof(e));if (a && "string" == typeof e.selector) { var u = document.querySelector(e.selector);u ? t = K(u) : W(e) && (t = X(e)); } else a && W(e) && (t = X(e));t && window.scrollTo(t.x, t.y); } })); } }function N() { var t = Q();t && (Kt[t] = { x: window.pageXOffset, y: window.pageYOffset }); }function J() { var t = Q();if (t) return Kt[t]; }function K(t) { var e = document.documentElement.getBoundingClientRect(), n = t.getBoundingClientRect();return { x: n.left - e.left, y: n.top - e.top }; }function W(t) { return Y(t.x) || Y(t.y); }function X(t) { return { x: Y(t.x) ? t.x : window.pageXOffset, y: Y(t.y) ? t.y : window.pageYOffset }; }function Y(t) { return "number" == typeof t; }function G() { return Xt.now().toFixed(3); }function Q() { return Yt; }function Z(t) { Yt = t; }function tt(t, e) { var n = window.history;try { e ? n.replaceState({ key: Yt }, "", t) : (Yt = G(), n.pushState({ key: Yt }, "", t)), N(); } catch (n) { window.location[e ? "replace" : "assign"](t); } }function et(t) { tt(t, !0); }function nt(t, e, n) { var r = function r(o) { o >= t.length ? n() : t[o] ? e(t[o], function () { r(o + 1); }) : r(o + 1); };r(0); }function rt(t) { if (!t) if (Ut) { var e = document.querySelector("base");t = e ? e.getAttribute("href") : "/"; } else t = "/";return "/" !== t.charAt(0) && (t = "/" + t), t.replace(/\/$/, ""); }function ot(t, e) { var n, r = Math.max(t.length, e.length);for (n = 0; n < r && t[n] === e[n]; n++) {}return { updated: e.slice(0, n), activated: e.slice(n), deactivated: t.slice(n) }; }function it(t, e, n, r) { var o = dt(t, function (t, r, o, i) { var a = at(t, e);if (a) return Array.isArray(a) ? a.map(function (t) { return n(t, r, o, i); }) : n(a, r, o, i); });return yt(r ? o.reverse() : o); }function at(t, e) { return "function" != typeof t && (t = Ot.extend(t)), t.options[e]; }function ut(t) { return it(t, "beforeRouteLeave", st, !0); }function ct(t) { return it(t, "beforeRouteUpdate", st); }function st(t, e) { return function () { return t.apply(e, arguments); }; }function pt(t, e, n) { return it(t, "beforeRouteEnter", function (t, r, o, i) { return ft(t, o, i, e, n); }); }function ft(t, e, n, r, o) { return function (i, a, u) { return t(i, a, function (t) { u(t), "function" == typeof t && r.push(function () { ht(t, e.instances, n, o); }); }); }; }function ht(t, e, n, r) { e[n] ? t(e[n]) : r() && setTimeout(function () { ht(t, e, n, r); }, 16); }function lt(t) { return dt(t, function (t, n, r, o) { if ("function" == typeof t && !t.options) return function (n, i, a) { var u = vt(function (t) { r.components[o] = t, a(); }), c = vt(function (t) { e(!1, "Failed to resolve async component " + o + ": " + t), a(!1); }), s = t(u, c);s && "function" == typeof s.then && s.then(u, c); }; }); }function dt(t, e) { return yt(t.map(function (t) { return Object.keys(t.components).map(function (n) { return e(t.components[n], t.instances[n], t, n); }); })); }function yt(t) { return Array.prototype.concat.apply([], t); }function vt(t) { var e = !1;return function () { if (!e) return e = !0, t.apply(this, arguments); }; }function mt(t) { var e = window.location.pathname;return t && 0 === e.indexOf(t) && (e = e.slice(t.length)), (e || "/") + window.location.search + window.location.hash; }function gt(t) { var e = mt(t);if (!/^\/#/.test(e)) return window.location.replace(g(t + "/#" + e)), !0; }function wt() { var t = bt();return "/" === t.charAt(0) || (kt("/" + t), !1); }function bt() { var t = window.location.href, e = t.indexOf("#");return e === -1 ? "" : t.slice(e + 1); }function xt(t) { window.location.hash = t; }function kt(t) { var e = window.location.href.indexOf("#");window.location.replace(window.location.href.slice(0, e >= 0 ? e : 0) + "#" + t); }function Rt(t, e, n) { var r = "hash" === n ? "#" + e : e;return t ? g(t + "/" + r) : r; }var Ot, Et = { name: "router-view", functional: !0, props: { name: { type: String, default: "default" } }, render: function render(t, e) { var r = e.props, o = e.children, i = e.parent, a = e.data;a.routerView = !0;for (var u = r.name, c = i.$route, s = i._routerViewCache || (i._routerViewCache = {}), p = 0, f = !1; i;) { i.$vnode && i.$vnode.data.routerView && p++, i._inactive && (f = !0), i = i.$parent; }if (a.routerViewDepth = p, f) return t(s[u], a, o);var h = c.matched[p];if (!h) return s[u] = null, t();var l = s[u] = h.components[u], d = a.hook || (a.hook = {});return d.init = function (t) { h.instances[u] = t.child; }, d.prepatch = function (t, e) { h.instances[u] = e.child; }, d.destroy = function (t) { h.instances[u] === t.child && (h.instances[u] = void 0); }, a.props = n(c, h.props && h.props[u]), t(l, a, o); } }, jt = /[!'()*]/g, At = function At(t) { return "%" + t.charCodeAt(0).toString(16); }, Ct = /%2C/g, _t = function _t(t) { return encodeURIComponent(t).replace(jt, At).replace(Ct, ","); }, $t = decodeURIComponent, Tt = /\/?$/, St = a(null, { path: "/" }), qt = [String, Object], Lt = [String, Array], Pt = { name: "router-link", props: { to: { type: qt, required: !0 }, tag: { type: String, default: "a" }, exact: Boolean, append: Boolean, replace: Boolean, activeClass: String, event: { type: Lt, default: "click" } }, render: function render(t) { var e = this, n = this.$router, r = this.$route, o = n.resolve(this.to, r, this.append), i = o.location, u = o.route, c = o.href, p = {}, h = this.activeClass || n.options.linkActiveClass || "router-link-active", y = i.path ? a(null, i) : u;p[h] = this.exact ? s(r, y) : f(r, y);var v = function v(t) { l(t) && (e.replace ? n.replace(i) : n.push(i)); }, m = { click: l };Array.isArray(this.event) ? this.event.forEach(function (t) { m[t] = v; }) : m[this.event] = v;var g = { class: p };if ("a" === this.tag) g.on = m, g.attrs = { href: c };else { var w = d(this.$slots.default);if (w) { w.isStatic = !1;var b = Ot.util.extend, x = w.data = b({}, w.data);x.on = m;var k = w.data.attrs = b({}, w.data.attrs);k.href = c; } else g.on = m; }return t(this.tag, g, this.$slots.default); } }, Ut = "undefined" != typeof window, Vt = Array.isArray || function (t) { return "[object Array]" == Object.prototype.toString.call(t); }, Mt = Vt, zt = P, Bt = k, Ht = R, It = j, Dt = L, Ft = new RegExp(["(\\\\.)", "([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))"].join("|"), "g");zt.parse = Bt, zt.compile = Ht, zt.tokensToFunction = It, zt.tokensToRegExp = Dt;var Nt = Object.create(null), Jt = Object.create(null), Kt = Object.create(null), Wt = Ut && function () { var t = window.navigator.userAgent;return (t.indexOf("Android 2.") === -1 && t.indexOf("Android 4.0") === -1 || t.indexOf("Mobile Safari") === -1 || t.indexOf("Chrome") !== -1 || t.indexOf("Windows Phone") !== -1) && window.history && "pushState" in window.history; }(), Xt = Ut && window.performance && window.performance.now ? window.performance : Date, Yt = G(), Gt = function Gt(t, e) { this.router = t, this.base = rt(e), this.current = St, this.pending = null, this.ready = !1, this.readyCbs = []; };Gt.prototype.listen = function (t) { this.cb = t; }, Gt.prototype.onReady = function (t) { this.ready ? t() : this.readyCbs.push(t); }, Gt.prototype.transitionTo = function (t, e, n) { var r = this, o = this.router.match(t, this.current);this.confirmTransition(o, function () { r.updateRoute(o), e && e(o), r.ensureURL(), r.ready || (r.ready = !0, r.readyCbs.forEach(function (t) { t(o); })); }, n); }, Gt.prototype.confirmTransition = function (t, e, n) { var r = this, o = this.current, i = function i() { n && n(); };if (s(t, o) && t.matched.length === o.matched.length) return this.ensureURL(), i();var a = ot(this.current.matched, t.matched), u = a.updated, c = a.deactivated, p = a.activated, f = [].concat(ut(c), this.router.beforeHooks, ct(u), p.map(function (t) { return t.beforeEnter; }), lt(p));this.pending = t;var h = function h(e, n) { return r.pending !== t ? i() : void e(t, o, function (t) { t === !1 ? (r.ensureURL(!0), i()) : "string" == typeof t || "object" == (typeof t === "undefined" ? "undefined" : _typeof(t)) ? ("object" == (typeof t === "undefined" ? "undefined" : _typeof(t)) && t.replace ? r.replace(t) : r.push(t), i()) : n(t); }); };nt(f, h, function () { var n = [], o = function o() { return r.current === t; }, a = pt(p, n, o);nt(a, h, function () { return r.pending !== t ? i() : (r.pending = null, e(t), void (r.router.app && r.router.app.$nextTick(function () { n.forEach(function (t) { return t(); }); }))); }); }); }, Gt.prototype.updateRoute = function (t) { var e = this.current;this.current = t, this.cb && this.cb(t), this.router.afterHooks.forEach(function (n) { n && n(t, e); }); };var Qt = function (t) { function e(e, n) { var r = this;t.call(this, e, n);var o = e.options.scrollBehavior;o && D(), window.addEventListener("popstate", function (t) { r.transitionTo(mt(r.base), function (t) { o && F(e, t, r.current, !0); }); }); }return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.go = function (t) { window.history.go(t); }, e.prototype.push = function (t, e, n) { var r = this;this.transitionTo(t, function (t) { tt(g(r.base + t.fullPath)), F(r.router, t, r.current, !1), e && e(t); }, n); }, e.prototype.replace = function (t, e, n) { var r = this;this.transitionTo(t, function (t) { et(g(r.base + t.fullPath)), F(r.router, t, r.current, !1), e && e(t); }, n); }, e.prototype.ensureURL = function (t) { if (mt(this.base) !== this.current.fullPath) { var e = g(this.base + this.current.fullPath);t ? tt(e) : et(e); } }, e.prototype.getCurrentLocation = function () { return mt(this.base); }, e; }(Gt), Zt = function (t) { function e(e, n, r) { t.call(this, e, n), r && gt(this.base) || wt(); }return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.setupListeners = function () { var t = this;window.addEventListener("hashchange", function () { wt() && t.transitionTo(bt(), function (t) { kt(t.fullPath); }); }); }, e.prototype.push = function (t, e, n) { this.transitionTo(t, function (t) { xt(t.fullPath), e && e(t); }, n); }, e.prototype.replace = function (t, e, n) { this.transitionTo(t, function (t) { kt(t.fullPath), e && e(t); }, n); }, e.prototype.go = function (t) { window.history.go(t); }, e.prototype.ensureURL = function (t) { var e = this.current.fullPath;bt() !== e && (t ? xt(e) : kt(e)); }, e.prototype.getCurrentLocation = function () { return bt(); }, e; }(Gt), te = function (t) { function e(e, n) { t.call(this, e, n), this.stack = [], this.index = -1; }return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.push = function (t, e, n) { var r = this;this.transitionTo(t, function (t) { r.stack = r.stack.slice(0, r.index + 1).concat(t), r.index++, e && e(t); }, n); }, e.prototype.replace = function (t, e, n) { var r = this;this.transitionTo(t, function (t) { r.stack = r.stack.slice(0, r.index).concat(t), e && e(t); }, n); }, e.prototype.go = function (t) { var e = this, n = this.index + t;if (!(n < 0 || n >= this.stack.length)) { var r = this.stack[n];this.confirmTransition(r, function () { e.index = n, e.updateRoute(r); }); } }, e.prototype.getCurrentLocation = function () { var t = this.stack[this.stack.length - 1];return t ? t.fullPath : "/"; }, e.prototype.ensureURL = function () {}, e; }(Gt), ee = function ee(e) { void 0 === e && (e = {}), this.app = null, this.apps = [], this.options = e, this.beforeHooks = [], this.afterHooks = [], this.matcher = B(e.routes || []);var n = e.mode || "hash";switch (this.fallback = "history" === n && !Wt, this.fallback && (n = "hash"), Ut || (n = "abstract"), this.mode = n, n) {case "history": this.history = new Qt(this, e.base);break;case "hash": this.history = new Zt(this, e.base, this.fallback);break;case "abstract": this.history = new te(this, e.base);break;default: t(!1, "invalid mode: " + n);} }, ne = { currentRoute: {} };return ee.prototype.match = function (t, e, n) { return this.matcher.match(t, e, n); }, ne.currentRoute.get = function () { return this.history && this.history.current; }, ee.prototype.init = function (e) { var n = this;if (t(y.installed, "not installed. Make sure to call `Vue.use(VueRouter)` before creating root instance."), this.apps.push(e), !this.app) { this.app = e;var r = this.history;if (r instanceof Qt) r.transitionTo(r.getCurrentLocation());else if (r instanceof Zt) { var o = function o() { r.setupListeners(); };r.transitionTo(r.getCurrentLocation(), o, o); }r.listen(function (t) { n.apps.forEach(function (e) { e._route = t; }); }); } }, ee.prototype.beforeEach = function (t) { this.beforeHooks.push(t); }, ee.prototype.afterEach = function (t) { this.afterHooks.push(t); }, ee.prototype.onReady = function (t) { this.history.onReady(t); }, ee.prototype.push = function (t, e, n) { this.history.push(t, e, n); }, ee.prototype.replace = function (t, e, n) { this.history.replace(t, e, n); }, ee.prototype.go = function (t) { this.history.go(t); }, ee.prototype.back = function () { this.go(-1); }, ee.prototype.forward = function () { this.go(1); }, ee.prototype.getMatchedComponents = function (t) { var e = t ? this.resolve(t).route : this.currentRoute;return e ? [].concat.apply([], e.matched.map(function (t) { return Object.keys(t.components).map(function (e) { return t.components[e]; }); })) : []; }, ee.prototype.resolve = function (t, e, n) { var r = M(t, e || this.history.current, n), o = this.match(r, e), i = o.redirectedFrom || o.fullPath, a = this.history.base, u = Rt(a, i, this.mode);return { location: r, route: o, href: u, normalizedTo: r, resolved: o }; }, ee.prototype.addRoutes = function (t) { this.matcher.addRoutes(t), this.history.current !== St && this.history.transitionTo(this.history.getCurrentLocation()); }, Object.defineProperties(ee.prototype, ne), ee.install = y, ee.version = "2.2.0", Ut && window.Vue && window.Vue.use(ee), ee; }); //# sourceMappingURL=vue-router.min-compiled.js.map //# sourceMappingURL=vue-router.min-compiled-compiled.js.map
/* the root getters */
/** * reply代理 */ var Reply=require('../models').Reply; var EventProxy=require('eventproxy'); var tools=require('../common/tools'); var User=require('./user'); var at=require('../common/at'); /** * 获取一条回复信息 * @param {String} id 回复ID * @param {Function} callback 回调函数 */ exports.getReply=function(id,callback){ Reply.findOne() }; /** * 根据回复ID,获取回复 * Callback: * - err, 数据库异常 * - reply, 回复内容 * @param {String} id 回复ID * @param {Function} callback 回调函数 */ exports.getReplyById=function(id,callback){ if(!id){ return callback(null,null); } Reply.findOne({_id:id},function(err,reply){ if(err){ return callback(err); } if(!reply){ return callback(err,null); } var user_id=reply.user_id; User.getUserById(user_id,function(err,user){ if(err){ return callback(err); } reply.user=user; at.linkUsers(reply.content,function(err,str){ if(err){ return callback(err); } reply.content=str; return callback(err,reply); }); }); }); }; /** * 根据objId,获取回复列表 * Callback: * - err, 数据库异常 * - replies, 回复列表 * @param {String} id objId * @param {Function} callback 回调函数 */ exports.getRepliesByObjectId = function (id, cb) { Reply.find({object_id: id, deleted: false}, '', {sort: 'create_at'}, function (err, replies) { if (err) { return cb(err); } if (replies.length === 0) { return cb(null, []); } var proxy = new EventProxy(); proxy.after('reply_find', replies.length, function () { cb(null, replies); }); for (var j = 0; j < replies.length; j++) { (function (i) { var user_id = replies[i].user_id; User.getUserById(user_id, function (err, user) { if (err) { return cb(err); } replies[i].user = user || { _id: '' }; if (replies[i].content_is_html) { return proxy.emit('reply_find'); } at.linkUsers(replies[i].content, function (err, str) { if (err) { return cb(err); } replies[i].content = str; proxy.emit('reply_find'); }); }); })(j); } }); }; /** * 创建并保存一条回复信息 * @param {String} content 回复内容 * @param {String} objectId 回复对象ID mongoose.Types.ObjectId.toString() * @param {String} userId 回复用户 * @param {String} [replyId] 回复ID,当二级回复时设定该值 * @param {Function} callback 回调函数 */ exports.newAndSave=function(content,objectId,userId,replyId,callback){ if(typeof replyId==='function'){ callback=replyId; replyId=null; } var reply=new Reply(); reply.content=content; reply.object_id=objectId; reply.user_id=userId; if(replyId){ reply.reply_id=replyId; } reply.save(function(err){ callback(err,reply); }); }; /** * 根据objId查询到最新的一条未删除回复 * @param objId 回复对象ID * @param callback 回调函数 */ exports.getLastReplyByObjId=function(objId,callback){ Reply.find({object_id:objId},{},{},callback); // Reply.find({object_id:objId,delete:false},'_id',{sort:{create_at:-1},limit:1},callback); }; /** * 根据用户id获取所有回复 */ exports.getRepliesByUserId=function(userId,opt,callback){ if(callback){ callback=opt; opt=null; } Reply.find({user_id:userId},{},opt,callback); }; /** * 通过userId获取回复总数 */ exports.getCountByUserId=function(userId,callback){ Reply.count({user_id:userId},callback); }
const winston = require("winston"); require("winston-daily-rotate-file"); const beautify = require('js-beautify').js_beautify const embedBuilder = require("./embedBuilder.js"); const util = require("./util.js"); const config = require('./../config.json'); const winstonLogger = new (winston.Logger)({ exitOnError: false, transports: [ new winston.transports.DailyRotateFile({ name: 'info-log', filename: 'logs/info-', datePattern: 'yyyy-MM-dd.log', level: 'info', json: false, prettyPrint: false }), new winston.transports.DailyRotateFile({ name: 'warning-log', filename: 'logs/warning-', datePattern: 'yyyy-MM-dd.log', level: 'warn', json: false, prettyPrint: false }), new winston.transports.DailyRotateFile({ name: 'error-log', filename: 'logs/error-', datePattern: 'yyyy-MM-dd.log', level: 'error', json: false, prettyPrint: false, handleExceptions: true, humanReadableUnhandledException: true }) ] }); const logger = { generic: function (logParams, client, message, log) { if (util.loggable(logParams)) { const level = "info"; if (message) { logger.winstonLogger(level, client, logParams, message, log); logger.embedLogger(logParams, client, level, embedBuilder.message(message, level).embed, log); } else { logger.winstonLogger(level, client, logParams, message, log); logger.embedLogger(logParams, client, level, embedBuilder.empty(level).embed, log); } } }, log: function (logParams, client, data, event, wrapper) { if (util.loggable(logParams)) { const level = "info"; const logMessage = embedBuilder[wrapper](data, level, event); logger.winstonLogger(level, client, logParams, event, data); logger.embedLogger(logParams, client, level, logMessage.embed, logMessage.message); } }, warn: function (logParams, client, data, event, wrapper) { if (util.loggable(logParams)) { const level = "warning"; const logMessage = embedBuilder[wrapper](data, level, event); logger.winstonLogger(level, client, logParams, event, data); logger.embedLogger(logParams, client, level, logMessage.embed, logMessage.message); } }, error: function (logParams, client, data, event, wrapper) { if (util.loggable(logParams)) { const level = "error"; const logMessage = embedBuilder[wrapper](data, level, event); logger.winstonLogger(level, client, logParams, event, data); logger.embedLogger(logParams, client, level, logMessage.embed, logMessage.message); } }, imgError: function (logParams, client, data, error, wrapper, embedImage) { if (util.loggable(logParams)) { const level = "error"; const logMessage = embedBuilder[wrapper](data, level, error, embedImage); logger.winstonLogger(level, client, logParams, error, data, embedImage); logger.embedLogger(logParams, client, level, logMessage.embed, logMessage.message); } }, embedLogger: function (logParams, client, level, embed, message = "") { //TODO message length if (util.loggable({level: level})) { const logChannelId = util.getData("/config/logChannels/default"); if (logChannelId) { const logChannel = client.channels.filter(channel => logChannelId == channel.id).first(); if (logChannel) { logChannel.sendMessage(message, { embed: embed }); } else { console.log("Log channel " + logChannelId + " does not exist"); } } else { console.log("Log channel not configured"); } } const levelLogChannelId = util.getData("/config/logChannels/" + level); if (levelLogChannelId) { const levelLogChannel = client.channels.filter(channel => levelLogChannelId == channel.id).first(); if (levelLogChannel) { levelLogChannel.sendMessage(message, { embed: embed }); } else { console.log("Level log channel " + levelLogChannelId + " does not exist for " + level); } } else { console.log("Level log channel not configured for " + level); } }, winstonLogger: function (level, client, ...logData) { const levels = { "info": "info", "warning": "warn", "error": "error" }; logData = require('util').inspect(logData, { depth: null }); winstonLogger.log(levels[level], util.scrubOutput(client, JSON.stringify(logData, null, 4)).replace(new RegExp("\\\\n", 'g'), "\n")); } }; module.exports = logger;
// for tests need to install mocha: // npm install -g mocha // // then to run a test // // mocha test.js // var assert = require("assert"); require('./index') // the values are arrays of elements. describe('groupby',function(){ it("should sort items into buckets. return an object - put each item of an array into an object property, according to value of a specified field",function(){ var arr=[ {n:1,v:'a'}, {n:2,v:'b'}, {n:3,v:'b'} ]; var result={ a:[ {n:1,v:'a'} ], b:[ {n:2,v:'b'}, {n:3,v:'b'} ] }; assert.deepEqual(groupby(arr,'v'),result); }) }) describe('objeach',function(){ it("should be iterate for each on object's properties",function(){ var obj={aa:2,bb:1,cc:3}; var gotvalues=[],gotkeys=[],gotindexes=[] var indexes=[0,1,2] var keys=["aa","bb","cc"] var values=[2,1,3] objeach(obj,function(v,k,i){gotvalues.push(v);gotkeys.push(k);gotindexes.push(i)}) assert.deepEqual(gotvalues,values); assert.deepEqual(gotkeys,keys); assert.deepEqual(gotindexes,indexes); }) }) describe('objmap',function(){ it("should be return a new object with same names and values updated by map function",function(){ var obj={aa:2,bb:1,cc:3}; var mapped={aa:3,bb:2,cc:4}; var gotvalues=[],gotkeys=[],gotindexes=[] var indexes=[0,1,2] var keys=["aa","bb","cc"] var values=[2,1,3] assert.deepEqual(objmap(obj,function(v,k,i){gotvalues.push(v);gotkeys.push(k);gotindexes.push(i);return v+1}),mapped); assert.deepEqual(gotvalues,values); assert.deepEqual(gotkeys,keys); assert.deepEqual(gotindexes,indexes); }) }) //var obj=objmap(obj, function(value,key,index){ return value.field ; } ) describe('objfilter',function(){ it("should be return a new object with properties filtered by their value",function(){ var obj={aa:2,bb:1,cc:3}; var filtered={aa:2}; var gotvalues=[],gotkeys=[],gotindexes=[] var indexes=[0,1,2] var keys=["aa","bb","cc"] var values=[2,1,3] assert.deepEqual(objfilter(obj,function(v,k,i){gotvalues.push(v);gotkeys.push(k);gotindexes.push(i);return v==2}),filtered); assert.deepEqual(gotvalues,values); assert.deepEqual(gotkeys,keys); assert.deepEqual(gotindexes,indexes); }) }) describe('sortobj',function(){ it("should sort object's keys by their names",function(){ var obj={aa:2,bb:1,cc:3}; var sorted={cc:3,aa:2,bb:1}; assert.deepEqual(sortobj(obj),sorted); }) it("should be able to use optional comparator",function(){ var obj={aa:2,bb:1,cc:3}; var sorted_asc={cc:3,aa:2,bb:1}; function comparator_asc(a,b) {return a==b?0:(a>b?1:-1)}; assert.deepEqual(sortobj(obj,comparator_asc),sorted_asc); }) }) describe('sortobjkey',function(){ it("should sort object's keys by value is desc order",function(){ var obj={aa:{f:2},bb:{f:1},cc:{f:3}}; var sorted={cc:{f:3},aa:{f:2},bb:{f:1}}; assert.deepEqual(sortobjkey(obj,'f'),sorted); }) }) describe('sortkeys',function(){ it("should sort object's keys by their names",function(){ var obj={bb:1,aa:1}; var sorted={aa:1,bb:1}; assert.deepEqual(sortkeys(obj),sorted); }) it("should be able to use optional comparator",function(){ var obj={bb:1,aa:1,cc:1}; var sorteddesc={cc:1,bb:1,aa:1}; function comparator_desc(a,b) {return a==b?0:(a>b?-1:1)}; assert.deepEqual(sortkeys(obj,comparator_desc),sorteddesc); }) }) describe('objtokvarr',function(){ it("should convert object to array of objects of key and value",function(){ var obj={aa:123}; var kva=[ {k:'aa',v:123} ]; assert.deepEqual(objtokvarr(obj),kva); }) it("should be able to use defined names",function(){ var obj={aa:123}; var kva=[ {name:'aa',value:123} ]; assert.deepEqual(objtokvarr(obj,"name","value"),kva); }) }) describe('objtsv',function(){ it("should convert array of objects to tab seperated values string",function(){ var tsv='id\tname\r\n'+ '1\taaa\r\n'+ '2\tbbb'; var objarr=[ {id:1,name:"aaa"}, {id:2,name:"bbb"} ] assert.deepEqual(objtsv(objarr),tsv); }) })
'use strict'; describe('rgiResourcesCtrl', function () { beforeEach(module('app')); var $scope, $location, actualErrorHandler, locationPathBackup, RESOURCES = 'RESOURCES', spies = {}, stubs = {}, initializeController = function(resourceType) { beforeEach(inject( function ($rootScope, $controller, _$location_, rgiHttpResponseProcessorSrvc, rgiResourcesSrvc) { $location = _$location_; locationPathBackup = $location.$$path; $location.$$path = '/' + resourceType; spies.resourcesQuery = sinon.spy(function(criteria, callback, errorHandler) { actualErrorHandler = errorHandler; callback(RESOURCES); }); stubs.resourcesQuery = sinon.stub(rgiResourcesSrvc, 'query', spies.resourcesQuery); stubs.httpResponseProcessorGetDefaultHandler = sinon.stub(rgiHttpResponseProcessorSrvc, 'getDefaultHandler', function(errorMessage) {return errorMessage;}); $scope = $rootScope.$new(); $controller('rgiResourcesCtrl', {$scope: $scope}); } )); }, checkTypeSpecificProperties = function(resourceType, title, errorHandler) { it('sets the resource type', function () { $scope.resource_type.should.be.equal(resourceType); }); it('sets the title', function () { $scope.title.should.be.equal(title); }); it('processes HTTP failures', function () { actualErrorHandler.should.be.equal(errorHandler); }); it('requires resources', function () { spies.resourcesQuery.withArgs({type: resourceType}).called.should.be.equal(true); }); }; describe('FAQ', function() { initializeController('faq'); checkTypeSpecificProperties('faq', 'Frequently Asked Questions', 'Load FAQ data failure'); }); describe('Resources', function() { initializeController('resource'); checkTypeSpecificProperties('resource', 'Other Resources', 'Load resource data failure'); it('sets the resources', function () { $scope.resources.should.be.equal(RESOURCES); }); }); afterEach(function () { Object.keys(stubs).forEach(function(stubName) { stubs[stubName].restore(); }); $location.$$path = locationPathBackup; }); });
/*eslint-env node*/ var fs = require('fs'); module.exports = (function (fileName) { var fileObj = JSON.parse(fs.readFileSync(fileName, 'utf8')) return fileObj.token; });
import React from 'react'; import {State, History} from 'react-router'; import { Menu, Mixins, Styles } from 'material-ui'; import Content from '../../components/layout/Content'; import ContentHeader from '../../components/layout/ContentHeader'; import Tabela from '../../components/Tabela'; class StudentiLista extends React.Component { render() { var menu = []; return ( <Content> <ContentHeader title='Lista Studenata' menu={menu}/> <Tabela/> </Content> ); } } export default StudentiLista;
(function(define, describe) { "use strict"; var dependencies = [ 'bootstrap', 'angular' ]; define(dependencies, function(AppBootstrap, angular) { var appName = 'app'; describe('Network service', function() { beforeEach(module(appName)); var networkService, $httpBackend, appMessagesService, $window, $rootScope, dngUserManagement, $state; beforeEach(function() { $window = { location: { reload: jasmine.createSpy() }, angular: angular }; module(function($provide) { $provide.value('$window', $window); }); AppTestUtils.login(); inject(function(_network_, _$httpBackend_, _appMessagesService_, _$rootScope_, _dngUserManagement_, _$state_) { networkService = _network_; $httpBackend = _$httpBackend_; appMessagesService = _appMessagesService_; $rootScope = _$rootScope_; dngUserManagement = _dngUserManagement_; $state = _$state_; }); }); afterEach(function() { var messages = appMessagesService.getMessages(); for (var i = 0; i < messages.length; i++) { appMessagesService.removeMessage(0); } }); it('works with GET', function() { var success, api = '/api/get'; $httpBackend.whenGET(api).respond(200); networkService.get(api).then(function() { success = true; }); $httpBackend.flush(); expect(success).toBeTruthy(); }); it('works with POST', function() { var success, api = '/api/post'; $httpBackend.whenPOST(api).respond(200); networkService.post(api).then(function() { success = true; }); $httpBackend.flush(); expect(success).toBeTruthy(); }); it('works with PUT', function() { var success, api = '/api/put'; $httpBackend.whenPUT(api).respond(200); networkService.put(api).then(function() { success = true; }); $httpBackend.flush(); expect(success).toBeTruthy(); }); it('works with PATCH', function() { var success = false, api = '/api/patch'; $httpBackend.whenPATCH(api).respond(200); networkService.patch(api).then(function() { success = true; }); $httpBackend.flush(); expect(success).toBeTruthy(); }); it('works with DELETE', function() { var success, api = '/api/delete'; $httpBackend.whenDELETE(api).respond(200); networkService.delete(api).then(function() { success = true; }); $httpBackend.flush(); expect(success).toBeTruthy(); }); it('remote connection fails', function() { var success = false, api = '/api/post'; $httpBackend.whenPOST(api).respond(400, {'errors': ['Error']}); networkService.post(api).then(function() { success = true; }).catch(function() {}); $httpBackend.flush(); expect(success).toBeFalsy(); $httpBackend.whenPUT(api).respond(400, {'errors': ['Error2']}); var failure = false; networkService.put(api).then(function() { }, function() { failure = true; }); $httpBackend.flush(); expect(failure).toBeTruthy(); $httpBackend.whenGET(api).respond(400, 'Error'); failure = false; networkService.get(api).then(function() { }, function() { failure = true; }); $httpBackend.flush(); expect(failure).toBeTruthy(); expect(appMessagesService.getMessages().length).toEqual(3); }); it('should handle detail error message', function() { var success = false, api = '/api/post/test'; $httpBackend.whenPOST(api).respond(400, {'detail': 'Detail error message'}); networkService.post(api).then(function() { success = true; }).catch(function() {}); $httpBackend.flush(); expect(success).toBeFalsy(); var messages = appMessagesService.getMessages(); expect(messages.length).toEqual(1); expect(messages[0].msgBody).toContain('<div>Detail error message</div>'); }); it('should handle multiple error messages', function() { var success = false, api = '/api/post/test'; $httpBackend.whenPOST(api).respond(400, {'errors': ['Error1', 'Error2']}); networkService.post(api).then(function() { success = true; }).catch(function() {}); $httpBackend.flush(); expect(success).toBeFalsy(); var messages = appMessagesService.getMessages(); expect(messages.length).toEqual(1); expect(messages[0].msgBody).toContain('<br/>'); }); it('makes full reload if application code at server has changed', function() { // GIVEN application code has changed at server side var api = '/api/get'; $httpBackend.whenGET(api).respond(418, 'Application code has changed. Please reload.'); // WHEN fetching some data from server networkService.get(api).catch(function() {}); $httpBackend.flush(); // THEN full reload is performed at client side expect($window.location.reload).toHaveBeenCalled(); }); it('redirects to login page on HTTP 401', function() { // GIVEN 401 response code from server var api = '/api/get'; spyOn(dngUserManagement, 'reset').and.callThrough(); spyOn($state, 'go').and.callThrough(); $httpBackend.whenGET(api).respond(401, ''); // WHEN fetching some data from server networkService.get(api).catch(function() {}); $httpBackend.flush(); // THEN user status is reset and user redirected to login page expect(dngUserManagement.reset).toHaveBeenCalled(); expect(dngUserManagement.user.isAuthenticated()).toBeFalsy(); expect($state.go).toHaveBeenCalledWith('auth.login'); }); }); }); })(define, describe);
const Chromy = require('../src') const path = require('path') let chromy = new Chromy() chromy.chain() .goto('file://' + path.join(__dirname, '/pages/index.html')) .evaluate(() => { return document.querySelectorAll('*').length }) .result((r) => console.log(r)) .end() .then(_ => chromy.close())
/** * File to check duration selection and pass selected duration to modules. * Will trigger on event on every duration change. */ "use strict"; var myDur = (function () { var myDur = {}; var startDate, endDate; var EVENT_DURATION_CHANGE = jQuery.Event(myConfig.EVENT_DURATION_CHANGE_NAME); function addDatePicker() { if ($(".date-picker").length > 0) { $("#date-picker-1").datepicker({}); $("#date-picker-2").datepicker({}); $(".date-picker").on("click", function (event) { event.preventDefault(); event.stopImmediatePropagation(); event.stopPropagation(); }) } } function checkAndUpdateDuration(days) { endDate = moment().utc().format(myConfig.API_DATE_FORMAT); startDate = moment().subtract(days, 'days').utc().format(myConfig.API_DATE_FORMAT); EVENT_DURATION_CHANGE.startDate = startDate; EVENT_DURATION_CHANGE.endDate = endDate; jQuery('body').trigger(EVENT_DURATION_CHANGE); } function init() { /** * TODO will consider after 3 months. *addDatePicker(); */ jQuery('.time-selection-controls button[data-days]').on('click', function () { console.log(this); var _button = jQuery(this); _button.siblings().removeClass('btn-primary'); _button.siblings().addClass('btn-outline-primary'); _button.removeClass("btn-outline-primary"); _button.addClass("btn-primary"); checkAndUpdateDuration(_button.data('days')); }); } myDur.init = init; jQuery('body').on(myConfig.EVENT_APPLICATION_LOADED_NAME, function () { if (jQuery('#my-chart,.reporting').length > 0) { init(); } }); return myDur; }());
import Vue from 'vue' import CButton from 'components/c-button' describe('button.vue', () => { let el beforeEach(() => { el = document.createElement('div') document.body.appendChild(el) }) afterEach(() => { document.body.removeChild(el) }) it('should render correct contents', () => { const vm = new Vue({ el, replace: false, template: '<c-button>PLATO</c-button>', components: { CButton } }) expect(vm.$children.length).to.equal(1) const el0 = vm.$children[0].$el expect(el0.textContent).to.equal('PLATO') expect(el0.type).to.equal('button') }) it('type', () => { const vm = new Vue({ el, replace: false, template: '<c-button type="submit">PLATO</c-button>', components: { CButton } }) expect(vm.$children[0].$el.type).to.equal('submit') }) })
'use strict'; import angular from 'angular'; import OnboardingController from './design-onboarding-controller'; var stateConfig = ($stateProvider) => { $stateProvider .state('app.design.onboarding', { url: '/onboarding', controller: OnboardingController, controllerAs: 'onboarding', templateProvider: ($templateCache) => $templateCache.get('design/onboarding/design-onboarding.html') }); }; export default angular.module('app.design.onboarding', []) .config(['$stateProvider', stateConfig]);
/** * editor_plugin_src.js * * Copyright 2010, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.Save', { init : function(ed, url) { var t = this; t.editor = ed; // Register commands ed.addCommand('mceSave', t._save, t); ed.addCommand('mceCancel', t._cancel, t); // Register buttons ed.addButton('save', {title : 'save.save_desc', cmd : 'mceSave'}); ed.addButton('cancel', {title : 'save.cancel_desc', cmd : 'mceCancel'}); ed.onNodeChange.add(t._nodeChange, t); ed.addShortcut('ctrl+s', ed.getLang('save.save_desc'), 'mceSave'); }, getInfo : function() { return { longname : 'Save', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/save', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _nodeChange : function(ed, cm, n) { var ed = this.editor; if (ed.getParam('save_enablewhendirty')) { cm.setDisabled('save', !ed.isDirty()); cm.setDisabled('cancel', !ed.isDirty()); } }, // Private methods _save : function() { var ed = this.editor, formObj, os, i, elementId; formObj = tinymce.DOM.get(ed.id).form || tinymce.DOM.getParent(ed.id, 'form'); if (ed.getParam("save_enablewhendirty") && !ed.isDirty()) return; tinyMCE.triggerSave(); // Use callback instead if (os = ed.getParam("save_onsavecallback")) { if (ed.execCallback('save_onsavecallback', ed)) { ed.startContent = tinymce.trim(ed.getContent({format : 'raw'})); ed.nodeChanged(); } return; } if (formObj) { ed.isNotDirty = true; if (formObj.onsubmit == null || formObj.onsubmit() != false) formObj.submit(); ed.nodeChanged(); } else ed.windowManager.alert("Error: No form element found."); }, _cancel : function() { var ed = this.editor, os, h = tinymce.trim(ed.startContent); // Use callback instead if (os = ed.getParam("save_oncancelcallback")) { ed.execCallback('save_oncancelcallback', ed); return; } ed.setContent(h); ed.undoManager.clear(); ed.nodeChanged(); } }); // Register plugin tinymce.PluginManager.add('save', tinymce.plugins.Save); })();
import get from 'lodash/get' /** * parseConnectionString - Parse a BTCPay Server style connection string. * * @param {string} value Connection string * @param {string} network Network code of config to extract * @returns {{ host, port, macaroon, cert }} Parsed connection string */ const parseConnectionString = (value, network = 'BTC') => { let config = {} try { config = JSON.parse(value) } catch (e) { throw new Error('Invalid connection string') } const allConfigs = get(config, 'configurations', []) const params = allConfigs.find(c => c.type === 'grpc' && c.cryptoCode === network) || {} const { host, port, macaroon, cert } = params if (!host || !port || !macaroon) { throw new Error('Invalid connection string') } return { host, port, macaroon, cert } } export default parseConnectionString
//~ name a481 alert(a481); //~ component a482.js
$(function () { $(".submit-on-checked").change(function (ev) { var that = $(this); if (that.attr("type") == "radio" && !that.is(":checked")) { return; } $("#search-form").submit(); }) })
module.exports = {"ClickerScript":{"normal":"ClickerScript-Regular.ttf","bold":"ClickerScript-Regular.ttf","italics":"ClickerScript-Regular.ttf","bolditalics":"ClickerScript-Regular.ttf"}};
'use strict'; exports.__esModule = true; var _slice = Array.prototype.slice; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _Container2 = require('./Container'); var _Container3 = _interopRequireDefault(_Container2); var ContainerComponent = (function (_Container) { _inherits(ContainerComponent, _Container); function ContainerComponent() { _classCallCheck(this, ContainerComponent); _Container.apply(this, arguments); } ContainerComponent.prototype.componentDidMount = function componentDidMount() { var _Container$prototype$componentDidMount; (_Container$prototype$componentDidMount = _Container.prototype.componentDidMount).call.apply(_Container$prototype$componentDidMount, [this].concat(_slice.call(arguments))); this.context.container.add(this.node); }; return ContainerComponent; })(_Container3['default']); ContainerComponent.contextTypes = { container: _react2['default'].PropTypes.object.isRequired }; exports['default'] = ContainerComponent; module.exports = exports['default'];
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 index = require('./routes/index'); //var users = require('./routes/users'); var pub_scr = require('./routes/dop.pubscr.js'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // 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(express.static(path.join(__dirname, 'dop_dcdp2'))); app.use(express.static(path.join(__dirname, 'template'))); app.use(express.static(path.join(__dirname, 'uploads'))); //app.use('/', index); app.use('/pub_scr', pub_scr); // 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 handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;
var width = document.body.clientWidth; var height = document.body.clientHeight; var canvas = document.getElementById('theCanvas'); var interaction_canvas = document.getElementById('interactionCanvas'); var param_names = { realMin: "Minimum X", realMax: "Maximum X", imagMin: "Minimum Y", imagMax: "Maximum Y", maxIter: "Maximal Iterations", minResolution: "Minimal Resolution", CR: "C (Real part)", CI: "C (Imaginary part)", newtonThresh: "Threshold", newtonContrast: "Constrast" } /* Scaling */ var real_scale = d3.scale.linear() .range([0, width]) .domain([-1.7,1.7]); var imag_scale = d3.scale.linear() .range([0, height]) .domain([-1,1]); d3.selectAll("canvas") .attr("width", width) .attr("height", height); var ctx = canvas.getContext('2d'); jul = fractal(width,height) .context(ctx) .minResolution(21); /* Colors */ var bw = d3.scale.sqrt() .domain([0, jul.__.maxIter]) .range(["white", "black"]) .interpolate(d3.interpolateLab); var mixed = d3.scale.linear() .domain([0, 12, 30, 50, 100, 180, 260, 380, 600, 800, 1200, 1600, 3200]) .range(["moccasin", "#999", "steelblue", "yellow", "brown", "#222", "pink", "purple", "#027", "#260", "orange", "yellow", "blue"]) .interpolate(d3.interpolateHcl); var greenBlack = d3.scale.sqrt() .domain([0, jul.__.maxIter]) .range(["black", "green"]) .interpolate(d3.interpolateLab); var deep = d3.scale.linear() .domain(d3.range(0,jul.__.maxIter,20)) .range(d3.range(0,100).map(function(i) { return d3.hcl(190+120*i, 40+35*Math.round(Math.cos(i/5)), 18+6*(i%10)).toString(); })) .interpolate(d3.interpolateLab); var zoom = d3.behavior.zoom() .x(real_scale) .y(imag_scale) .on("zoom", onzoom) function onzoom() { d3.select("#input-realMin").attr("value", real_scale.domain()[0]); d3.select("#input-imagMin").attr("value", imag_scale.domain()[0]); d3.select("#input-realMax").attr("value", real_scale.domain()[1]); d3.select("#input-imagMax").attr("value", imag_scale.domain()[1]); jul.zoom(real_scale.domain(), imag_scale.domain()); }; function resetZoom() { real_scale.domain([-1.7,1.7]); imag_scale.domain([-1,1]); zoom.scale(1) .translate([0,0]) .x(real_scale) .y(imag_scale); onzoom(); } function changeMethod(method){ real_scale.domain([-1.7,1.7]); imag_scale.domain([-1,1]); zoom.scale(1) .translate([0,0]) .x(real_scale) .y(imag_scale); d3.select("#input-realMin").attr("value", real_scale.domain()[0]); d3.select("#input-imagMin").attr("value", imag_scale.domain()[0]); d3.select("#input-realMax").attr("value", real_scale.domain()[1]); d3.select("#input-imagMax").attr("value", imag_scale.domain()[1]); jul.changeMethod(method, real_scale.domain(), imag_scale.domain()); updateKeys(method); activate(method) } function activate(method){ d3.selectAll(".subchoice").classed("active", false) d3.selectAll(".choice").classed("active", false) d3.select("#"+method.id).classed("active", true) } function updateMethods() { d3.select("#methods").html("") d3.keys(jul._menuItems). forEach(function(menuItem) { var menu = jul._menuItems[menuItem] d3.select("#methods") .append("span") .attr("id", menu.main.id) .attr("class", "choice") .html(menu.name+"<br/>") .on("click", function(){changeMethod(menu.main)}) menu.others.forEach(function(item){ d3.select("#methods") .append("span") .attr("id", item.id) .attr("class", "subchoice") .html(item.name+"<br/>") .on("click", function(){changeMethod(item)}) }) }); } function changeColor(color){ jul.changeColor(color) d3.select("#mixed").classed("active", color==mixed); d3.select("#deep").classed("active", color==deep); d3.select("#bw").classed("active", color==bw); d3.select("#greenBlack").classed("active", color==greenBlack); } // bind inputs to julia parameters function updateKeys(method) { d3.select("#tools").html('') d3.keys(jul.__).filter( function(key){ var specificFilterJ = (method.id == 'j' || method.id=='j3') | ((key != "CR") & (key != "CI")); var specificFilterN = method.id== 'n' | ((key != "newtonThresh") & (key != "newtonContrast")); var generalFilter = (key!= "method"); return specificFilterJ & specificFilterN & generalFilter; }). forEach(function(key) { d3.select("#tools") .append("div") .html(param_names[key] + "<br/>") .append("input") .attr({ id: "input-" + key, type: "text", value: jul[key]() }) .on("keyup", function() { jul[key](this.value); }); }); } jul.color = deep; updateKeys(jul.__.method); updateMethods() activate(jul.__.method) jul.go(); d3.select(interaction_canvas) .call(zoom); window.onresize = function() { width = document.body.clientWidth; height = document.body.clientHeight; real_scale.range([0, width]); imag_scale.range([0, height]); jul.x_extent(width) .y_extent(height); d3.selectAll("canvas") .attr("width", width) .attr("height", height); resetZoom() }
angular.module('utils') .directive('paraPie', function($q, percentsFilter) { return { restrict: 'E', scope: { slices : '=' }, link: function(scope, element, attrs) { var Gui = Class.extend({ init : function() { var self = this; self.width = element.parent().width(); self.piePadding = 100; self.radius = self.width / 2 - self.piePadding; self.slices = null; self.sliceTitleTexts = null; self.selectedSliceTitleText = null; self.sliceInfoText = null; self.percentsText = null; self.colors = null; self.blurredColors = null; self.highlightedSliceIndex = null; self.animationDuration = 1000; }, createSvg : function(root) { var self = this; var width = (self.piePadding + self.radius) * 2; self.svg = d3.select(root) .append("svg") .attr("viewBox", "0 0 " + width + " " + width) .attr("preserveAspectRatio", "xMidYMid meet") .append("g"); self.svg.attr("transform", "translate(" + self.width / 2 + ", " + self.radius + ")"); self.svg.append("g") .attr("class", "slices"); self.svg.append("g") .attr("class", "slice-titles"); self.svg.append("g") .attr("class", "lines"); self.selectedSliceTitleText = self.svg.append("g") .append("text") .attr("text-anchor", "middle") .attr("dy", "-1em"); self.sliceInfoText = self.svg.append("g") .append("text") .attr("text-anchor", "middle"); self.percentsText = self.svg.append("g") .append("text") .attr("text-anchor", "middle") .attr("dy", "1em"); }, _hsl2Rgb : function(h, s, l) { var r, g, b; if (s == 0) { // Achromatic: r = g = b = l; } else { function hue2rgb(p, q, t) { if (t < 0) { t += 1; } if (t > 1) { t -= 1; } if (t < 1/6) { return p + (q - p) * 6 * t; } if (t < 0.5) { return q; } if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; } return p; } var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } return "#" + [r, g, b] .map(function(x) { var res = Math.floor(x * 255).toString(16); if (res.length == 1) { res = "0" + res; } return res; }) .join(""); }, _createValueInterpolation : function(animatedObj, value) { if (value == undefined) { return null; } animatedObj._current = animatedObj._current || value; var interpolate = d3.interpolate(animatedObj._current, value); animatedObj._current = interpolate(1); return interpolate; }, _getPercents : function(d) { return 100 * d.size / this.model.slices.reduce(function(s1, s2) { return s1 + s2.size; }, 0); }, updateSvgData : function() { var self = this; var pie = d3.layout.pie() .sort(null) .value(self._getPercents.bind(self)); var key = function(d) { return d.data.title; }; var arc = d3.svg.arc() .outerRadius(self.radius * 0.9) .innerRadius(self.radius * 0.65); var outerArc = d3.svg.arc() .outerRadius(self.radius * 0.95) .innerRadius(self.radius * 0.95); colors = d3.scale.ordinal() .domain(self.model.slices.map(function(s) { return s.title; })) .range(self.model.slices.map(function(s, i) { return s.color || self._hsl2Rgb(i / self.model.slices.length, 0.9, 0.65); })); blurredColors = d3.scale.ordinal() .domain(colors.domain()) .range(self.model.slices.map(function(s, i) { return s.blurredColor || self._hsl2Rgb(i / self.model.slices.length, 0.9, 0.9); })); function aboveThresholdVisibility(d) { return d.data.size > 0 ? "visible" : "hidden"; } // Pie slices: self.slices = self.svg.select(".slices").selectAll("path.slice") .data(pie(self.model.slices), key); self.slices.enter() .insert("path") .style("fill", function(d) { return colors(d.data.title); }) .attr("cursor", "pointer") .attr("class", "para-pie") .on('mouseover', function(d, i) { self.highlightSlice(i); }) .on('mouseout', function() { self.highlightNothing(); }) .on('click', function(d, i) { self.clickSlice(i); }); self.slices .transition().duration(self.animationDuration) .attrTween("d", function(d) { var interpolate = self._createValueInterpolation(this, d); if (interpolate == null) { return null; } return function(t) { return arc(interpolate(t)); }; }); self.slices.exit() .remove(); // Text labels: self.sliceTitleTexts = self.svg.select(".slice-titles").selectAll("text") .data(pie(self.model.slices), key) .style("visibility", aboveThresholdVisibility); self.sliceTitleTexts.enter() .append("text") .attr("dy", ".35em") .style("visibility", aboveThresholdVisibility) .attr("cursor", "pointer") .text(function(d) { return d.data.title; }) .on('mouseover', function(d, i) { self.highlightSlice(i); }) .on('mouseout', function() { self.highlightNothing(); }) .on('click', function(d, i) { self.clickSlice(i); }); function midAngle(d) { return d.startAngle + (d.endAngle - d.startAngle) / 2; } self.sliceTitleTexts.transition().duration(self.animationDuration) .attrTween("transform", function(d) { var interpolate = self._createValueInterpolation(this, d); if (interpolate == null) { return null; } return function(t) { var d2 = interpolate(t); var pos = outerArc.centroid(d2); pos[0] = self.radius * (midAngle(d2) < Math.PI ? 1 : -1); return "translate(" + pos + ")"; }; }) .styleTween("text-anchor", function(d) { var interpolate = self._createValueInterpolation(this, d); if (interpolate == null) { return null; } return function(t) { var d2 = interpolate(t); return midAngle(d2) < Math.PI ? "start" : "end"; }; }); self.sliceTitleTexts.exit() .remove(); // Slice to text polylines: var polylines = self.svg.select(".lines").selectAll("polyline") .data(pie(self.model.slices), key) .style("visibility", aboveThresholdVisibility); polylines.enter() .append("polyline") .attr("class", "para-pie") .style("visibility", aboveThresholdVisibility); polylines.transition().duration(self.animationDuration) .attrTween("points", function(d) { var interpolate = self._createValueInterpolation(this, d); if (interpolate == null) { return null; } return function(t) { var d2 = interpolate(t); var pos = outerArc.centroid(d2); pos[0] = self.radius * 0.95 * (midAngle(d2) < Math.PI ? 1 : -1); return [arc.centroid(d2), outerArc.centroid(d2), pos]; }; }); polylines.exit() .remove(); // Make sure the GUI's state is retained: if (self.highlightedSliceIndex != null) { self.highlightSlice(self.highlightedSliceIndex, true); } }, highlightSlice : function(sliceIndex, transition) { var self = this; self.slices .style("fill", function(d, i) { return i == sliceIndex ? colors(d.data.title) : blurredColors(d.data.title); }); self.sliceTitleTexts .style("fill", function(d, i) { return i == sliceIndex ? "black" : "lightgray"; }); self.sliceTitleTexts[0][sliceIndex].parentNode.appendChild(self.sliceTitleTexts[0][sliceIndex]) self.selectedSliceTitleText.text(self.model.slices[sliceIndex].title); self.sliceInfoText .transition().duration(transition ? self.animationDuration : 0) .tween("text", function() { var slice = self.model.slices[sliceIndex]; var interpolate = self._createValueInterpolation(this, slice.size); if (interpolate == null) { return null; } return function(t) { $(this).text(slice.textPrefix + Math.round(interpolate(t)) + slice.textSuffix); }; }); self.percentsText .transition().duration(transition ? self.animationDuration : 0) .tween("text", function() { var slice = self.model.slices[sliceIndex]; var interpolate = self._createValueInterpolation(this, self._getPercents(slice)); if (interpolate == null) { return null; } return function(t) { $(this).text(percentsFilter(interpolate(t))); }; }); self.selectedSliceTitleText.style("visibility", "visible"); self.sliceInfoText.style("visibility", "visible"); self.percentsText.style("visibility", "visible"); self.highlightedSliceIndex = sliceIndex; }, highlightNothing : function() { var self = this; if (self.model.slices.selected != null) { self.highlightSlice(self.model.slices.selected); } else { self.slices .style("fill", function(d) { return colors(d.data.title); }); self.sliceTitleTexts .style("fill", "black"); self.selectedSliceTitleText.style("visibility", "hidden"); self.sliceInfoText.style("visibility", "hidden"); self.percentsText.style("visibility", "hidden"); self.highlightedSliceIndex = null; } }, clickSlice : function(sliceIndex) { var self = this; self.model.selectSlice(sliceIndex == self.model.slices.selected ? null : sliceIndex); }, sliceSelected : function(sliceIndex) { var self = this; if (sliceIndex != null) { self.highlightSlice(sliceIndex); } else { self.highlightNothing(); } } }); var Model = Class.extend({ init : function(scope) { var self = this; self._scope = scope; self._scope.slices = self._scope.slices || []; self._scope.slices.selected = self._scope.slices.selected || undefined; // self.slices contains all of the slices in self._scope.slices. // The difference between the two is while the slices order // within self._scope.slices may change, it doesn't change in // self.slices. Moreover, once slices are deleted from // self._scope.slices, they aren't deleted from self.slices - // their size changes to 0. // This "mirroring" is a must, because we want the pie to // have a consistent look (e.g. slices shouldn't change their // position in the pie - even if they did change in // self._scope.slice). self.slices = angular.copy(self._scope.slices); }, createListeners : function() { var self = this; function update() { if ((self._scope.slices || []).length > 0) { // Copy slices to self.slices: self._scope.slices .forEach(function(slice) { var sliceIndex = self.slices.map(function(s) { return s.title; }).indexOf(slice.title); if (sliceIndex < 0) { self.slices.push(slice); } else { self.slices[sliceIndex] = slice; } }); // "Delete" slices which don't exit anymore: self.slices .forEach(function(slice) { var sliceIndex = self._scope.slices.map(function(s) { return s.title; }).indexOf(slice.title); if (sliceIndex < 0) { slice.size = 0; } }); // Translate the selected property: self.slices.selected = self._scope.slices.selected == null ? self._scope.slices.selected : self.slices.indexOf(self._scope.slices[self._scope.slices.selected]); self.gui.updateSvgData(); self.selectSlice(self.slices.selected); } } self._scope.$watchCollection(function() { return self._scope.slices; }, update, true); self._scope.$watch(function() { return self._scope.slices.selected; }, update); }, selectSlice : function(sliceIndex) { var self = this; self.slices.selected = sliceIndex; // Translate the selected property: self._scope.slices.selected = sliceIndex == null ? sliceIndex : self._scope.slices.indexOf(self.slices[sliceIndex]); self.gui.sliceSelected(sliceIndex); } }); var gui = new Gui(); var model = new Model(scope); gui.model = model; model.gui = gui; gui.createSvg(element[0]); model.createListeners(); } }; });
import DynamicLayer from 'esri/layers/ArcGISDynamicMapServiceLayer'; import TiledLayer from 'esri/layers/ArcGISTiledMapServiceLayer'; import ImageLayer from 'esri/layers/ArcGISImageServiceLayer'; import ImageParameters from 'esri/layers/ImageParameters'; import WebTiledLayer from 'esri/layers/WebTiledLayer'; import GraphicsLayer from 'esri/layers/GraphicsLayer'; import FeatureLayer from 'esri/layers/FeatureLayer'; import SimpleRenderer from 'esri/renderers/SimpleRenderer'; import Symbols from 'helpers/Symbols'; import KEYS from 'js/constants'; import {errors} from 'js/config'; /** * Map Function that gets called for each entry in the provided layers config and returns an array of ArcGIS Layers * @param {object} layer - Layer Config object, see the layersConfig object in js/map/config.js for example * @return {Layer} esriLayer - Some sort of esri layer, current types are: * - ArcGISDynamicMapServiceLayer * - ArcGISTiledMapServiceLayer * - ArcGISImageServiceLayer * - FeatureLayer */ export default (layer) => { if ((!layer.url && layer.type !== 'graphic') || !layer.type) { throw new Error(errors.missingLayerConfig); } let esriLayer, options = {}, imageParameters; switch (layer.type) { case 'tiled': options.id = layer.id; options.visible = layer.visible || false; esriLayer = new TiledLayer(layer.url, options); break; case 'webtiled': options.id = layer.id; options.visible = layer.visible || false; esriLayer = new WebTiledLayer(layer.url, options); break; case 'image': options.id = layer.id; options.visible = layer.visible || false; options.opacity = layer.opacity || 1; esriLayer = new ImageLayer(layer.url, options); break; case 'dynamic': // Create some image parameters imageParameters = new ImageParameters(); imageParameters.layerOption = ImageParameters.LAYER_OPTION_SHOW; imageParameters.layerIds = layer.layerIds; imageParameters.format = 'png32'; // Populate the options and then add the layer options.id = layer.id; options.visible = layer.visible || false; options.opacity = layer.opacity || 1.0; options.imageParameters = imageParameters; if (layer.defaultDefinitionExpression) { var layerDefs = []; layer.layerIds.forEach(val => { // ['ACQ_DATE', 1] // "ACQ_DATE > date'" + new window.Kalendae.moment().subtract(1, 'd').format('YYYY-MM-DD') + "'", const date = new Date(); date.setDate(date.getDate() - layer.defaultDefinitionExpression[1]); const dateString = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(); layerDefs[val] = layer.defaultDefinitionExpression[0] + ' > date \'' + dateString + '\''; // layerDefs[val] = layer.defaultDefinitionExpression; }); imageParameters.layerDefinitions = layerDefs; } esriLayer = new DynamicLayer(layer.url, options); break; case 'feature': options.id = layer.id; options.visible = layer.visible || false; options.outFields = layer.outFields || ['*']; esriLayer = new FeatureLayer(layer.url, options); if (layer.id === KEYS.smallGrants) { const pointSymbol = Symbols.getGrantsPointSymbol(); const renderer = new SimpleRenderer(pointSymbol); esriLayer.renderer = renderer; } break; case 'graphic': options.id = layer.id; options.visible = layer.visible || false; esriLayer = new GraphicsLayer(options); break; default: throw new Error(errors.incorrectLayerConfig(layer.type)); } return esriLayer; };
const path = require('path'); module.exports = (config, env) => { const moduleResolve = config.resolve.modules; moduleResolve.push(path.resolve('./src')); return config; }
var _debug = true; var ajaxCalls = new Array(); var resultDisplayed = false; $( document ).ready(function() { $("#searchField").first().focus(); }); $('#advanced_link').click(function() { $('#advanced_link').addClass("hide"); $('#row_advanced_search').removeClass("hide"); }); $('#combo_structure').change(function() { $('#combo_sous_structure').html('<option value="">Chargement...</option>'); $.ajax({ url: 'sous-structure.php', data: {struct: $('#combo_structure').val()} }) .done(function (data) { debug("done sous-structure with data: " + data); var html = '<option value="">Sous-Structure</option>'; data.forEach(function(elt) { html += '<option value="'+ elt.structure.structId +'">'+ elt.structureLibelle +'</option>'; }); $('#combo_sous_structure').html(html); }) .fail(function () { debug("error"); }) .always(function () { debug("complete"); }); search(); }); $('#combo_sous_structure').change(function() { search(); }); $('#searchField').on('input', function (e) { cancelAjaxCalls(); search(); }); function search() { text = $('#searchField').val(); if (text.length > 2 || $('#combo_structure').val() != '') { $("#row_result").html(''); $("#row_result").addClass("loading"); var ajaxCall = $.ajax({ url: 'result.php', data: { name: text, struct: $('#combo_structure').val(), sstruct: $('#combo_sous_structure').val() } }) .done(function (data) { debug("done for: " + text); $("#row_result").removeClass("loading"); $('#row_result').html(data); }) .fail(function () { debug("error"); }) .always(function () { debug("complete"); ajaxCalls.slice(ajaxCalls.indexOf(ajaxCall)); }); ajaxCalls.push(ajaxCall); displayResult(); }else { $("#row_result").html(''); $("#row_result").removeClass('loading'); } } function displayResult() { if (!resultDisplayed) { $('#search').removeClass("vertical-center"); $('#search').addClass("top-search"); $('#column_logo').removeClass("small-12"); $('#column_logo').addClass("small-5"); $('#column_logo').addClass("medium-3"); $('#column_logo').addClass("large-2"); $('#column_search').removeClass("small-12"); $('#column_search').addClass("small-7"); $('#column_search').addClass("medium-9"); $('#column_search').addClass("large-10"); $('#column_logo').html('<a href="' + SITE_URL + '">' + $('#column_logo').html() + '</a>'); resultDisplayed = true; } } function cancelAjaxCalls() { debug("Cancelling all ajax calls..."); debug(ajaxCalls); ajaxCalls.forEach(function (a) { a.abort(); ajaxCalls.slice(ajaxCalls.indexOf(a),1); }); } function debug(msg) { if (_debug) { console.log(msg); } }
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra Modified by Richard Scarrott @richardscarrott */ var Template = require('webpack/lib/Template'); var JsonpMainTemplatePlugin; /** * Patches the `JsonpMainTemplatePlugin` with jsonp error handling logic. * @param {JsonpMainTemplatePlugin} plugin The plugin to be patched. */ function JsonpErrorHandlerPlugin(plugin) { JsonpMainTemplatePlugin = plugin; } module.exports = JsonpErrorHandlerPlugin; /** * Indicates whether the `JsonpMainTemplatePlugin` has been patched. * @type {Boolean} */ JsonpErrorHandlerPlugin.prototype.patched = false; /** * Applies the patch. */ JsonpErrorHandlerPlugin.prototype.apply = function() { if (!this.patched) { this.patchJsonpMainTemplatePlugin(); } }; /** * Patches the `JsonpMainTemplatePlugin` with jsonp error handling logic. */ JsonpErrorHandlerPlugin.prototype.patchJsonpMainTemplatePlugin = function() { JsonpMainTemplatePlugin.prototype.apply = this._apply; JsonpErrorHandlerPlugin.prototype.patched = true; }; /** * Adds the error handling logic by tapping into the main template plugin hooks. * This is mostly taken from 'webpack/lib/JsonpMainTemplatePlugin'. * @param {MainTemplate} mainTemplate The main template. */ JsonpErrorHandlerPlugin.prototype._apply = function(mainTemplate) { mainTemplate.plugin("local-vars", function(source, chunk, hash) { if(chunk.chunks.length > 0) { return this.asString([ source, "", "// object to store loaded and loading chunks", '// "0" means "already loaded"', '// Array means "loading", array contains callbacks', "var installedChunks = {", this.indent( chunk.ids.map(function(id) { return id + ":0" }).join(",\n") ), "};" ]); } return source; }); mainTemplate.plugin("require-ensure", function(_, chunk, hash) { var filename = this.outputOptions.filename || "bundle.js"; var chunkFilename = this.outputOptions.chunkFilename || "[id]." + filename; var chunkMaps = chunk.getChunkMaps(); return this.asString([ "};", // HACK: the requireEnsure signature is defined in the mainTemplate so need to override it here... this.requireFn + ".e = function requireEnsure(chunkId, successCallback, errorCallback) {", this.indent([ "errorCallback = errorCallback || function() {};", "// \"0\" is the signal for \"already loaded\"", "if (installedChunks[chunkId] === 0)", this.indent("return successCallback.call(null, " + this.requireFn + ");"), "", "// an array means \"currently loading\".", "if (installedChunks[chunkId] !== undefined) {", this.indent([ "installedChunks[chunkId].push({", this.indent([ "success: successCallback,", "error: errorCallback" ]), "});", ]), "} else {", this.indent([ "// start chunk loading", "installedChunks[chunkId] = [{", this.indent([ "success: successCallback,", "error: errorCallback" ]), "}];", "loadChunk(chunkId)" ]), "}" ]) ]); }); mainTemplate.plugin("bootstrap", function(source, chunk, hash) { if(chunk.chunks.length > 0) { var jsonpFunction = this.outputOptions.jsonpFunction || Template.toIdentifier("webpackJsonp" + (this.outputOptions.library || "")); var filename = this.outputOptions.filename || "bundle.js"; var chunkFilename = this.outputOptions.chunkFilename || "[id]." + filename; var chunkMaps = chunk.getChunkMaps(); return this.asString([ source, "", "// install a JSONP callback for chunk loading", "var parentJsonpFunction = window[" + JSON.stringify(jsonpFunction) + "];", "window[" + JSON.stringify(jsonpFunction) + "] = function webpackJsonpCallback(chunkIds, moreModules) {", this.indent([ '// add "moreModules" to the modules object,', '// then flag all "chunkIds" as loaded and fire callback', "var moduleId, chunkId, i = 0, callbacks = [];", "for(;i < chunkIds.length; i++) {", this.indent([ "chunkId = chunkIds[i];", "if(installedChunks[chunkId])", this.indent("callbacks.push.apply(callbacks, installedChunks[chunkId]);"), "installedChunks[chunkId] = 0;" ]), "}", "for(moduleId in moreModules) {", this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")), "}", "if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules);", "while(callbacks.length)", this.indent("callbacks.shift().success.call(null, " + this.requireFn + ");"), (this.entryPointInChildren(chunk) ? [ "if(moreModules[0]) {", this.indent([ "installedModules[0] = 0;", "return " + this.requireFn + "(0);" ]), "}" ] : "") ]), "};", "", "// load chunk", "function loadChunk(chunkId) {", this.indent([ "var head = document.getElementsByTagName('head')[0];", "var script = document.createElement('script');", "script.type = 'text/javascript';", "script.charset = 'utf-8';", "script.async = true;", "function onComplete(error) {", this.indent([ "// avoid mem leaks in IE.", "script.onerror = script.onload = script.onreadystatechange = null;", "if (error) {", this.indent([ "var callbacks = installedChunks[chunkId];", "// set chunkId to undefined so subsequent require's try again", "delete installedChunks[chunkId];", "if (callbacks) {", this.indent([ "while(callbacks.length) {", this.indent([ "callbacks.shift().error.call(null, __webpack_require__);", ]), "}" ]), '}', ]), '}', "// success callbacks will be called by webpackJsonpCallback handler" ]), "}", "script.onerror = script.onload = script.onreadystatechange = function() {", this.indent([ "// cover buggy onerror / readystate implementations by checking whether the chunk is actually installed", "onComplete(installedChunks[chunkId] !== 0);" ]), "};", "script.src = " + this.requireFn + ".p + " + this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), { hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"", hashWithLength: function(length) { return "\" + " + this.renderCurrentHashCode(hash, length) + " + \""; }.bind(this), chunk: { id: "\" + chunkId + \"", hash: "\" + " + JSON.stringify(chunkMaps.hash) + "[chunkId] + \"", hashWithLength: function(length) { var shortChunkHashMap = {}; Object.keys(chunkMaps.hash).forEach(function(chunkId) { if(typeof chunkMaps.hash[chunkId] === "string") shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length); }); return "\" + " + JSON.stringify(shortChunkHashMap) + "[chunkId] + \""; }, name: "\" + (" + JSON.stringify(chunkMaps.name) + "[chunkId]||chunkId) + \"" } }) + ";", "head.appendChild(script);" ]), "}" ]); } return source; }); mainTemplate.plugin("hot-bootstrap", function(source, chunk, hash) { var hotUpdateChunkFilename = this.outputOptions.hotUpdateChunkFilename; var hotUpdateMainFilename = this.outputOptions.hotUpdateMainFilename; var hotUpdateFunction = this.outputOptions.hotUpdateFunction || Template.toIdentifier("webpackHotUpdate" + (this.outputOptions.library || "")); var currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), { hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"", hashWithLength: function(length) { return "\" + " + this.renderCurrentHashCode(hash, length) + " + \""; }.bind(this), chunk: { id: "\" + chunkId + \"" } }); var currentHotUpdateMainFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), { hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"", hashWithLength: function(length) { return "\" + " + this.renderCurrentHashCode(hash, length) + " + \""; }.bind(this) }); return source + "\n"+ "var parentHotUpdateCallback = this[" + JSON.stringify(hotUpdateFunction) + "];\n" + "this[" + JSON.stringify(hotUpdateFunction) + "] = " + Template.getFunctionContent(function() { function webpackHotUpdateCallback(chunkId, moreModules) { hotAddUpdateChunk(chunkId, moreModules); if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); } function hotDownloadUpdateChunk(chunkId) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.charset = 'utf-8'; script.src = $require$.p + $hotChunkFilename$; head.appendChild(script); } function hotDownloadManifest(callback) { if(typeof XMLHttpRequest === "undefined") return callback(new Error("No browser support")); try { var request = new XMLHttpRequest(); var requestPath = $require$.p + $hotMainFilename$; request.open("GET", requestPath, true); request.timeout = 10000; request.send(null); } catch(err) { return callback(err); } request.onreadystatechange = function() { if(request.readyState !== 4) return; if(request.status === 0) { // timeout callback(new Error("Manifest request to " + requestPath + " timed out.")); } else if(request.status === 404) { // no update available callback(); } else if(request.status !== 200 && request.status !== 304) { // other failure callback(new Error("Manifest request to " + requestPath + " failed.")); } else { // success try { var update = JSON.parse(request.responseText); } catch(e) { callback(e); return; } callback(null, update); } }; } }) .replace(/\$require\$/g, this.requireFn) .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) .replace(/\$hash\$/g, JSON.stringify(hash)) }); mainTemplate.plugin("hash", function(hash) { hash.update("jsonp"); hash.update("4"); hash.update(this.outputOptions.filename + ""); hash.update(this.outputOptions.chunkFilename + ""); hash.update(this.outputOptions.jsonpFunction + ""); hash.update(this.outputOptions.library + ""); }); };
// api used to check the status of the service and database module.exports = (db) => { var express = require('express'); var router = express.Router(); router.use('/status', function(req, res, next) { console.log('status router.use'); next(); }); router.route('/status') .get(function(req, res) { console.log('GET /status'); res.sendStatus(200); }) .post(function(req, res) { console.log('POST /status'); console.log('body: %j', req.body); res.sendStatus(200); }); router.route('/status/db') .get(function(req, res) { console.log('GET /status/db'); db.query('SELECT 1', function(err, rows) { //db.ping(function(err) { if(err) { res.status(err.status || 500); res.json({message: err.message, error: err }); } else res.sendStatus(200); }); }); return router; };
'use strict'; // 培训信息子集 exports = module.exports = function(mongo, mongoose) { var trainInfoSubset = new mongoose.Schema({ startDate: { type: Date }, // 培训起始时间 content: { type: String }, // 培训内容 lessonHour: { type: Number }, // 课时 notes: { type: String }, // 备注 endDate: { type: Date }, // 培训结束时间 lecturer: { type: String }, // 主讲师 address: { type: String }, // 培训地址 employee: { type: mongoose.Schema.Types.ObjectId, ref: "Employee" }, // 员工ID _remove: { type: Boolean } }); trainInfoSubset.index({ employee: 1 }); trainInfoSubset.index({ _remove: 1 }); mongo.model('TrainInfoSubset', trainInfoSubset); };
'use strict'; const CONSTANTS = require('./../constants'); const resetRoles = (data, message) => { let reply = 'You have no roles to reset ' + message.author.toString(); if (message.member.roles.cache) { var found = false; //reset user roles message.member.roles.cache.forEach( (role) => { if (CONSTANTS.PROTECTED_ROLES.indexOf(role.name) == -1) { if(!found) reply = message.author.toString() + ', I am removing the following roles:'; found = true; reply += ' ' + role.name; message.member.roles.remove(role).catch(console.error); } }); found = false; // reset channel overwritten permissions Object.keys(data.channelsByName).forEach((channelName) => { let channel = data.channelsByName[channelName]; if(channel.name.indexOf('-') > -1) { let foundOverwrite = channel.permissionOverwrites.get(message.author.id); if(foundOverwrite) { if(!found) reply += '\n' + message.author.toString() + ', I am unhiding these neighborhood channels: '; found = true; // do not repeat found message reply += `#${channel.name}`; foundOverwrite.delete(); } } }); } message.channel.send(reply); return reply; }; module.exports = (data) => ( (message) => { return resetRoles(data, message); });
// http://bonesmoses.org/2016/07/15/pg-phriday-a-postgres-persepctive-on-mongodb/ use db var timing = new Array() var currentDate = new Date(); currentDate.setHours(0,0,0,0) var batch = new Array() var start = new Date() for (var i = 1; i <= 1000000; i++) { batch[i] = { _id: i, location: i % 1000, reading: i % 100, readingDate: new Date(currentDate - i * 10000) } } db.sensorLog.insert(batch) // We start at 1 to match the ID of the MySQL query performance data timing[1] = (new Date() - start) / 1000 // 13.638 start = new Date() db.sensorLog.ensureIndex( { readingDate: 1 } ) timing[2] = (new Date() - start) / 1000 // 3.013 var currentDate = new Date() currentDate.setHours(0,0,0,0) start = new Date() db.sensorLog.update({ readingDate: { $gte: new Date(currentDate.getTime() - 8*86400000), $lt: new Date(currentDate.getTime() - 7*86400000) } }, { $inc: { reading: 1 } }, { multi: true } ) timing[3] = (new Date() - start) / 1000 //WriteResult({ "nMatched" : 8640, "nUpserted" : 0, "nModified" : 8640 }) // 77 start = new Date() db.sensorLog.remove({ readingDate: { $gte: new Date(currentDate.getTime() - 9*86400000), $lt: new Date(currentDate.getTime() - 8*86400000) } } ) timing[4] = (new Date() - start) / 1000 // WriteResult({ "nRemoved" : 8640 }) // 154 start = new Date() db.sensorLog.count() timing[5] = (new Date() - start) / 1000 // 4 start = new Date() db.sensorLog.find({ readingDate: { $lt: new Date(currentDate.getTime() - 14*86400000) } } ).sort({readingDate: 1}).skip(20).limit(5) timing[6] = (new Date() - start) / 1000 // 14 timing.shift(); // Remove the 0th position // var output = {}; var v = 1; timing.forEach(function(e) { this.output[this.v++] = e;}); // Produce the series (data frame) q = { "mongo" : output } db.dropDatabase()
import config from '../../config.json'; import gulp from 'gulp'; import yargs from 'yargs' import browserSync from 'browser-sync'; const argv = yargs.argv const browserSyncTask = () => { var browserSyncWatch = [ config.dist.markup + '**/*.{html,php,twig,rss}', config.dist.images.base + '**/*.{jpg,jpeg,webp,gif,png,svg,ico}', config.dist.css + '**/*.css', ]; // Build a condition when Proxy is active var bsProxy, bsServer; const url = argv.url || config.browsersync.proxy; // Condition for Proxy if( config.browsersync.proxy ) { bsProxy = url; bsServer = false; } else { bsProxy = false; bsServer = { baseDir : config.dist.browserSyncDir}; } var browserSyncConfig = { proxy: bsProxy, ghostMode: { clicks: true, forms: true, links: true, scroll: true }, logLevel: 'info', // info, debug, warn, silent watchTask: true, open: config.browsersync.openbrowser, // false if you don't want to automatically open the browser server: bsServer, stream: true, notify: { styles: [ 'padding: 10px 20px;', 'font-family: arial;', 'line-height: 1', 'position: fixed;', 'font-size: 10px;', 'font-weight: bold', 'z-index: 9999;', 'top: inherit', 'border-radius: 0', 'right: 0;', 'bottom: 0;', 'color: #fff;', 'background-color: rgba(0,0,0, .5)', 'text-transform: uppercase' ] } } browserSync.init(browserSyncWatch, browserSyncConfig); } gulp.task('browser-sync', browserSyncTask); module.exports = { browserSyncTask }
import 'styles/styles.css' import React from 'react' import { Field } from 'redux-form' import RenderValidationField from 'components/survey/RenderValidationField' import { required } from 'redux-form-validators' const TextQuestion = ({ fields, input: { name, value }, meta: { error, submitFailed, invalid, touched }, index, isShowcase, isEdit, onEdit, type }) => { if (isEdit) { return ( <div className='question-body'> <Field name={`${name}.question`} type='text' className='form-control' placeholder='Question' component={RenderValidationField} validate={required()} span /> <div className='d-flex justify-content-end'> <button type='button' className='btn btn-success' onClick={() => onEdit(true)} disabled={invalid} > Save </button> <button type='button' className='btn btn-danger' onClick={() => onEdit(false)} > Cancel </button> </div> </div> ) } return ( <div className='question-body'> <Field name={`${name}.answer`} className='form-control' placeholder='Answer' component={RenderValidationField} textarea rows='3' validate={isShowcase && fields.get(index).isRequired ? required() : null} /> </div> ) } export default TextQuestion
var assert = require('assert'); var noDef = ' is not defined'; module.exports = { str: function () { assert(this.editor.gruntfile.toString, 'gruntfile.toString' + noDef); return this.editor.gruntfile.toString(); }, read: function (file) { return require('fs').readFileSync(file, 'utf-8').trim(); }, insertConfig: function (name, body) { assert(this.editor.insertConfig, 'insertConfig' + noDef); return this.editor.insertConfig.bind(this.editor, name, body); }, insertVariable: function (name, value) { assert(this.editor.insertVariable, 'insertVariable' + noDef); return this.editor.insertVariable.bind(this.editor, name, value); }, prependJavaScript: function (code) { assert(this.editor.prependJavaScript, 'prependJavaScript' + noDef); return this.editor.prependJavaScript.bind(this.editor, code); }, appendJavaScript: function (code) { assert(this.editor.appendJavaScript, 'appendJavaScript' + noDef); return this.editor.appendJavaScript.bind(this.editor, code); }, load: function (plugin) { assert(this.editor.loadNpmTasks, 'loadNpmTasks' + noDef); return this.editor.loadNpmTasks.bind(this.editor, plugin); }, registerTask: function (group, desc, tasks, multi) { assert(this.editor.registerTask, 'registerTask' + noDef); return this.editor.registerTask.bind(this.editor, group, desc, tasks, multi); } };
/** * Created by truls on 29.06.17. */ import mongoose from 'mongoose'; const Schema = mongoose.Schema; const socialSchema = new Schema({ facebook: { type: 'String', required: false }, twitter: { type: 'String', required: false }, youtube: { type: 'String', required: false }, provider: { type: 'String', required: true }, }); export default mongoose.model('Social', socialSchema);
/** * Created by roberthilscher on 25.06.15. */ module.exports = (function () { var lodashTemplate = require('lodash.template'), path = require('path'), fs = require('fs'), statuses = { FAILED: 'failed', PASSED: 'passed', UNDEFINED: 'undefined', PENDING: 'pending', SKIPPED: 'skipped' }, templates; /** * Convert html tags to html entites * @param str * @returns {XML|string|*|void} */ function toHtmlEntities(str) { str = str || ''; return str.replace(/./gm, function (s) { return "&#" + s.charCodeAt(0) + ";"; }); } /** * Checks if the step is an empty After step * @param step - object which contains step data * @returns boolean */ function isEmptyAfterStep(step) { return step.keyword.trim() === 'After' && step.name === undefined && step.embeddings === undefined; } /** * Checks if the step is an empty Before step * @param step - object which contains step data * @returns boolean */ function isEmptyBeforeStep(step) { return step.keyword.trim() === 'Before' && step.name === undefined && step.embeddings === undefined; } /** * Checks if the step is an After step containing a screenshot * @param step - object which contains step data * @returns boolean */ function isAfterStepWithScreenshot(step) { return step.keyword.trim() === 'After' && step.embeddings && step.embeddings[0] && step.embeddings[0].mime_type === 'image/png'; } /** * Return html code of step element based on step template * @param step - object which contains step data * @returns string */ function getStep(step) { var template = fs.readFileSync(templates.stepTemplate), compiled = lodashTemplate(template.toString()); return compiled({ status: step.result ? step.result.status : '', errorDetails: step.result ? toHtmlEntities(step.result.error_message) : '', name: step.keyword + (step.name ? step.name : ''), dataTable: step.rows ? step.rows : '' }); } /** * Return html code of step element based on step template * @param step - object which contains step data * @returns string */ function getAfterScreenshotStep(step) { var template = fs.readFileSync(templates.screenshotTemplate), compiled = lodashTemplate(template.toString()); return compiled({ screenshot: step.embeddings && step.embeddings[0] ? step.embeddings[0].data : '' }); } /** * Return html code of scenario element based on scenario template * @param scenario - object which contains step data * @param isPassed = flag which is true when all steps in scenario are passed otherwise is false * @returns string */ function getScenario(scenario, isPassed) { var template = fs.readFileSync(templates.scenarioTemplate), compiled = lodashTemplate(template.toString()); return compiled({ status: isPassed ? statuses.PASSED : statuses.FAILED, name: scenario.keyword + ': ' + scenario.name }); } /** * Return html code of feature element based on feature template * @param feature - object which contains feature data * @returns {*} */ function getFeature(feature, scenariosNumberInFeature, passedScenariosNumberInFeature, stepsNumberInFeature, passedStepsInFeature) { var template = fs.readFileSync(templates.featureTemplate), compiled = lodashTemplate(template.toString()); return compiled({ name: feature.name, scenariosNumberInFeature: scenariosNumberInFeature, passedScenariosNumberInFeature: passedScenariosNumberInFeature, stepsNumberInFeature: stepsNumberInFeature, passedStepsInFeature: passedStepsInFeature }); } /** * Return true when all steps is passed otherwise return false * @param scenariosNumber * @param passedScenarios * @returns {boolean} */ function areTestsPassed(scenariosNumber, passedScenarios) { return (scenariosNumber === passedScenarios); } /** * Return header html code based on header template * @param scenariosNumber * @param passedScenarios * @param stepsNumber * @param passedSteps * @returns {*} */ function getHeader(scenariosNumber, passedScenarios, stepsNumber, passedSteps) { var template = fs.readFileSync(templates.headerTemplate), compiled = lodashTemplate(template.toString()); return compiled({ status: areTestsPassed(scenariosNumber, passedScenarios) ? 'passed' : 'failed', scenariosSummary: scenariosNumber + ' scenarios ' + '( ' + passedScenarios + ' passed)', stepsSummary: stepsNumber + ' steps ' + '( ' + passedSteps + ' passed)' }); } /** * Generate html code which contains all elements needed to generate reports * @param testResults * @returns {string} */ function generateHTML(testResults) { var stepsHtml = '', isPassed = false, passedScenarios = 0, passedSteps = 0, stepsNumber = 0, scenariosNumber = 0, html = '', step; for (var i = 0; i < testResults.length; i++) { var scenariosHtml = '', scenariosNumberInFeature = 0, passedScenariosNumberInFeature = 0, stepsNumberInFeature = 0, passedStepsInFeature = 0; if (testResults[i].elements) { for (var j = 0; j < testResults[i].elements.length; j++) { var element = testResults[i].elements[j]; if (element.type === 'scenario' || element.keyword === 'Scenario') { scenariosNumber++; scenariosNumberInFeature++; stepsHtml = ''; isPassed = true; for (var k = 0; k < testResults[i].elements[j].steps.length; k++) { step = testResults[i].elements[j].steps[k]; if(isEmptyAfterStep(step) || isEmptyBeforeStep(step)) { continue; } if (isAfterStepWithScreenshot(step)) { stepsHtml += getAfterScreenshotStep(step); } else { stepsHtml += getStep(step); stepsNumber++; stepsNumberInFeature++; if (step.result.status !== statuses.PASSED) { isPassed = false; } else if (step.result.status === statuses.PASSED) { passedSteps++; passedStepsInFeature++; } } } if (isPassed) { passedScenarios++; passedScenariosNumberInFeature++; } scenariosHtml += '<div class="scenario-container">' + getScenario(element, isPassed); scenariosHtml += stepsHtml + '</div>'; } } } html += getFeature(testResults[i], scenariosNumberInFeature, passedScenariosNumberInFeature, stepsNumberInFeature, passedStepsInFeature); html += scenariosHtml; } header = getHeader(scenariosNumber, passedScenarios, stepsNumber, passedSteps); return header + html; } /** * Generate report from report template * @param html - concatenated all elements * @returns string which contains html code of report */ function generateReport(html) { var template = fs.readFileSync(templates.reportTemplate), compiled = lodashTemplate(template.toString()); return compiled({ scenarios: html }); } return { generateReport: function (testResults, htmlTemplates) { var html; templates = htmlTemplates; html = generateHTML(testResults); return generateReport(html); } }; }());
/* jshint esversion:6, node: true */ /* * Loblaws Messenger - recipe.js * * Recipe search handler. */ const request = require('request'), net_handler = require('../net_handler.js'); function requestRecipe(sender, query) { console.log("[INFO] " + sender + ": Requested search for recipe with query: \'" + query + "\'"); // Produces URL to make search request with Loblaws let url = 'https://community-food2fork.p.mashape.com/search?key=9a266ac158d1966f7a00f043259f2c5e&q='; url = url.concat(query.trim()); // Array to be sent with request let options = { url: url, headers: { 'X-Mashape-Key': 'RNsZ2tiy2pmshxmPkPRrn6viHrUwp1UZ22BjsnbuPVLyEnTS57', 'Accept': 'application/json' } }; // Send the search request request(options, function callback(error, response, body) { if (!error && response.statusCode == 200) { let results = JSON.parse(body); //console.log(body); console.log("[INFO] " + "Received response from product query with: " + results.count + " results"); if (results.count !== 0) { sendRecipeResults(sender, results.recipes); } else { sendTextMessage(sender, "There are no results for that search."); } } }); delete net_handler.userStates.sender; } /* * Process the returned recipe response, then sends it to the user. * Makes a carouel displaying tile, description, and image. * sender (String): The user to be sent to * recipes (JSON Object): The response of recipes */ function sendRecipeResults(sender, recipes) { let messageData = { "attachment": { "type": "template", "payload": { "template_type": "generic", "elements": loadRecipeElements(recipes) // Load the products into an object that messenger api can handle } } }; if (net_handler.sendFBRequest(sender, messageData)) { console.log("[INFO] " + sender + ": Sent recipe results"); } } /* * Load recipes into an array that can be handled by messenger API. * Makes carousel as long as the number of responses. */ function loadRecipeElements(recipes) { let elements = []; // Create blank array let length = recipes.length > 10 ? 10 : recipes.length; for (let i = 0; i < length; i++) { let element = { "title": recipes[i].title, // Sets title "subtitle": recipes[i].publisher, // Sets description "image_url": recipes[i].image_url, // Sets image "buttons": [ { "type": "postback", "title": "Let's make this!", "payload": "recipeSelected - " + recipes[i].recipe_id },{ "type": "web_url", "title": "More Info", "url": recipes[i].source_url } ] }; elements.push(element); // Add the element to the array } return elements; } /* Sends a text messsage to the user. */ function sendTextMessage(sender, text) { let messageData = { text: text }; if (net_handler.sendFBRequest(sender, messageData)) { console.log("[INFO] " + sender + ": Sent message: \'" + text + "\'"); } } module.exports = { requestRecipe: requestRecipe };
(function() { 'use strict'; angular.module('app.tasks', [ 'app.core', 'app.widgets' ]); })();
var alt = angular.module('alt', ['ngResource', 'ngRoute', 'wu.masonry']); alt .config(function($routeProvider, $locationProvider) { $locationProvider.html5Mode(true); $routeProvider .when('/', { templateUrl: '/pages/index' }) .when('/brand/chapter/products/all', { templateUrl: '/pages/brand-products-all', controller: 'brandCtrl' }) .when('/brand/chapter/products/featured', { templateUrl: '/pages/brand-products-featured' }) .when('/brand/chapter/trace', { templateUrl: '/pages/brand-products-all' }) .when('/brand/chapter/:chapter', { templateUrl: '/pages/brand-chapter' }) .when('/product', { templateUrl: '/pages/product', controller: 'productCtrl' }) .when('/products', { templateUrl: '/pages/products', controller: 'productCtrl' }) .when('/account-mylove', { templateUrl: '/pages/account-mylove', controller: 'productCtrl' }) .when('/search', { templateUrl: '/pages/search', controller: 'searchCtrl' }) .when('/signin', { templateUrl: '/pages/signin' }); });
this["JST"] = this["JST"] || {}; this["JST"]["test/fixtures/it's-a-bad-filename.hbs"] = Handlebars.template({"compiler":[8,">= 4.3.0"],"main":function(container,depth0,helpers,partials,data) { return "Why would you name your file like this?"; },"useData":true});
var should = require('should') var Browser = require('zombie') var Driver = require('zombify') describe("Viewing a hotel room", function() { var driver = new Driver('../Hotelier') , client = null before(function(done) { driver.start(done) }) after(function(done) { driver.stop(done) }) describe('With a single hotel room', function() { before(function(done) { driver.invoke('InMemoryHotel.AddHotelRoom', { id: '200', number: '101', capacity: 3 }, done) }) describe("Viewing the room's page", function(done) { before(function(done) { client = new Browser() client.visit(driver.baseHref + '/Room/Index/200', handleVisit(client, done)) }) it('Should have the hotel room number as the header', function() { client.querySelector('h1').textContent .should.equal('101') }) it('Should state the room\'s capacity', function() { client.querySelector('.capacity').textContent .should.equal('3') }) }) }) }) function handleVisit(client, cb) { return function() { if(client.statusCode !== 200) { var message = client.querySelector('h1').textContent var stacktrace = client.querySelector('tbody pre').textContent console.error(message, stacktrace) } cb() } }
Excel.run(function (ctx) { var chart = ctx.workbook.worksheets.getActiveWorksheet().charts.getItemAt(0); chart.dataLabels.showSeriesName = true; return ctx.sync(); }).catch(function (error) { console.log(error); });
//------------------------------------------------------------------ // // Creates an explosion effect that emits all particles at creation time. // The spec is defined as: // { // center: { x: , y: }, // howMany: // How many particles to emit // } // //------------------------------------------------------------------ Demo.components.ParticleSystem.createEffectExplosion = function(spec) { 'use strict'; let effect = { }; effect.update = function() { for (let particle = 0; particle < spec.howMany; particle += 1) { // // Create a new fire particle let sizeStart = Random.nextGaussian(0.015, 0.005); let sizeEnd = sizeStart * 0.2; Demo.components.ParticleSystem.createParticle({ image: Demo.assets['fire'], alphaStart: 1.0, alphaEnd: 0.2, center: { x: spec.center.x, y: spec.center.y }, sizeStart: sizeStart, sizeEnd: sizeEnd, direction: Random.nextCircleVector(1.0), speed: Random.nextGaussian(0.0003, 0.0001), rateRotation: (2 * Math.PI) / 1000, // Radians per millisecond lifetime: Random.nextGaussian(1500, 250) }); } return false; // One time emit! }; return Demo.components.ParticleSystem.addEffect(effect); };
class Test { constructor() { } pai() { let list = [1, 2, 3, 4]; list.forEach(d => { //console.log(d) }); } getMin() { let getMinIdx = function (list) { let min = Math.min(...list); return list.indexOf(min); }; let list = [1, 4, 6]; let sum = list.reduce((a, b) => a + b); let list2 = [[1, 2, 3], [4, 5], [2, 4, 6]]; let tList = list2.flat(); } } let test = new Test(); test.getMin();
/*jslint browser: true */ // Log.js (c) 2010-2013 Loren West and other contributors // May be freely distributed under the MIT license. // For further details and documentation: // http://lorenwest.github.com/monitor-min (function(root){ // Module loading var Monitor = root.Monitor || require('./Monitor'), // Raw events on the server (for speed), backbone events on the browser (for functionality) EventEmitter = Monitor.commonJS ? require('events').EventEmitter.prototype : Monitor.Backbone.Events, Stat = Monitor.Stat, stat = new Stat('Log'), _ = Monitor._, emittingNow = false; /** * A lightweight component for gathering and emitting application logs * * It's designed with low development and runtime cost in mind, encouraging * usage with minimum concern for overhead. Runtime monitoring can be as chatty * as desired, outputting every log statement of every type, or finely tuned * with regular expressions to monitor specific log statements. * * Log Collector * ------------- * * As a collector, it's a place to send application logs. * * Example for outputting a log in your application: * * var log = require('monitor-min').getLogger('myModule'); * ... * log.info('Credit limit accepted', limit, requestedAmount); * * The above is a request to output an ```info``` log for ```myModule``` named * ```Credit limit accepted```. The log entry includes all additional parameters, * in this case the customer credit limit and the reqeusted amount. * * The full name for this log entry is: ```"info.myModule.Credit limit accepted"``` * The name is important, as monitors can be configured to output logs based * on this name. * * Best practices are to include dynamic parameters in extra arguments * vs. concatenating strings. This reduces logging overhead, especially * for log statements that aren't currently being watched. * * Log Emitter * ----------- * As an emitter, the Log module is a place to capture logging output. * * When listening for log entries, wildcards can be used to register for * particular log types and entries. * * var Log = require('monitor-min').Log; * ... * Log.on('info.myModule.*', myFunction); * * Will call ```myFunction``` when all ```info.myModule.*``` logs are emitted. * * Listeners are invoked with the following arguments: * * - type - The log type (trace, debug, info, warn, error, or fatal) * - module - The logger module name * - name - The log entry name * - args... - Additional arguments passed into the log entry are passed on * as additional args to the event listener. * * Wildcards * --------- * A flexible and user-oriented wildcard pattern is used for monitoring * logs. The pattern is described in the <a href="Stat.html#wildcards">Wildcard secttion of the Stats class</a>. * * Choosing Good Names * ------------------- * It's a good idea to pick a good naming scheme with each dot-delimited segment * having a consistent, well-defined purpose. Volatile segments should be as deep * into the hierarchy (furthest right) as possible. Keeping the names less * volatile makes it easier to turn statistics recording on for all logs. * * @class Log * @constructor */ var Log = Monitor.Log = function(module) { var t = this; t.module = module; }; var proto = Log.prototype; // This is a map of registered event names to compiled regexs, for // quickly testing if a log needs to be emitted. Log.eventRegex = {}; /** * Output a ```trace``` log entry * * @method trace * @param name {String} Log entry name * @param [...] {Any} Subsequent arguments to add to the log */ /** * Output a ```debug``` log entry * * @method debug * @param name {String} Log entry name * @param [...] {Any} Subsequent arguments to add to the log */ /** * Output a ```info``` log entry * * @method info * @param name {String} Log entry name * @param [...] {Any} Subsequent arguments to add to the log */ /** * Output a ```warn``` log entry * * @method warn * @param name {String} Log entry name * @param [...] {Any} Subsequent arguments to add to the log */ /** * Output a ```error``` log entry * * @method error * @param name {String} Log entry name * @param [...] {Any} Subsequent arguments to add to the log */ /** * Output a ```fatal``` log entry * * @method fatal * @param name {String} Log entry name * @param [...] {Any} Subsequent arguments to add to the log */ // Add a method for each log type ['trace','debug','info','warn','error','fatal'].forEach(function(method) { proto[method] = function(name) { Log._emit(method, this.module, name, arguments); }; }); /** * Send the log to all registered listeners * * @private * @static * @method emit * @param type {string} The log type (trace, debug, info, etc) * @param module {String} The log module name * @param name {String} The log entry name * @param args {any[]} Arguments to the log entry */ Log._emit = function(type, module, name, args) { var eventName, fullName = type + '.' + module + '.' + name; // Prevent log recursion. This has the effect of disabling all logging // for log handlers (and their downstream effect), but is necessary to // prevent infinite recursion. If it's desired to log the output of // log handlers, then delay that processing until nextTick. if (emittingNow) { return; } emittingNow = true; // Output a counter stat for this log stat.increment(fullName); // Test the name against all registered events for (eventName in Log._events) { // Get the regex associated with the name (using the Stat package) var regex = Log.eventRegex[eventName]; if (!regex) { regex = Log.eventRegex[eventName] = Stat._buildRegex(eventName); } // Test the long name with the regex, and emit if it matches if (regex.test(fullName)) { // Build the arguments as event name, log type, module, name, [other args...] var allArgs = _.toArray(args), emitFn = Log.emit || Log.trigger; // NodeJS/server=emit, Backbone/browser=trigger allArgs.splice(0, 1, eventName, type, module, name); emitFn.apply(Log, allArgs); } } // Turn off recursion prevention emittingNow = false; }; // Mixin event processing for the Log class _.extend(Log, EventEmitter); // Expose this class from the Monitor module Monitor.setLoggerClass(Log); /** * Output log statements to the console * * This method can be used as a listener to send logs to the console. * * It uses console.error() for error and fatal log types, and console.log() * for all other log types. * * Example: * * var Log = Monitor.Log; * Log.on('*.MyModule.*', Log.console); * * @static * @method consoleLogger * @param type {string} The log type (trace, debug, info, etc) * @param module {String} The log module name * @param name {String} The log entry name * @param args {any...} All original, starting with the short name */ Log.console = function(type, module, name, args) { // Build the string to log, in log4js format var nowStr = JSON.stringify(new Date()).substr(1,22), allArgs = _.toArray(arguments), logStr = nowStr + ' [' + type + '] ' + module + '.' + name + ' '; allArgs.splice(0,3); try { logStr += JSON.stringify(allArgs); } catch(e) { logStr += Monitor.stringify(allArgs); } // Log or error if (type === 'error' || type === 'fatal') { console.error(logStr); } else { console.log(logStr); } }; // Attach the console log listener var pattern = Monitor.Config.MonitorMin.consoleLogListener.pattern; if (pattern) { Log.on(pattern, Log.console); } }(this));
'use strict'; angular.module('ccFilters', []).filter('noTransparent', function() { return function(colors) { var output = []; angular.forEach (colors, function(color) { if (color.color != 'transparent') { output.push(color); } }) return output; }; });
/** * Created by vmalla on 11/20/2014. */ var GhostServer = require('./index');
openRequest.onupgradeneeded = function(e){ database = e.target.result; createObjectStore(database,"profile",false); var ms= createObjectStore(database,"messages",false); ms.createIndex("between",'f'); ms.createIndex("profile",'m.p.u'); createObjectStore(database,"application",true); }; openRequest.onsuccess = function(e){ database = e.target.result; checkSession(); }; openRequest.onerror = function(e){ console.log(e); }; function getStore(objectStore,permission){ var tran = database.transaction([objectStore],permission); var store = tran.objectStore(objectStore); return store; }; function addToStore(item,key,store){ var storeObject = getStore(store,"readwrite"); if(key){ storeObject.put(item,key); } if(!key){ storeObject.put(item); } return storeObject; }; function createObjectStore(database,name,key){ if(database.objectStoreNames.contains(name))return null; if(key){ return database.createObjectStore(name); } if(!key){ return database.createObjectStore(name,{autoIncrement:true}); } return null; };
function middle(e,t){var _=function t(){var n=Array.prototype.slice.call(arguments);return void 0===_._m_ctx&&(_._m_ctx=this),_._m_stack.length===_._m_index?(_._m_index=0,e.apply(_._m_ctx,n)):(n.unshift(t),_._m_stack[_._m_index++].apply(_._m_ctx,n))};return _._m_stack=[],_._m_index=0,_._m_ctx=t,_.use=function(e,t){_._m_stack.push(e.bind(t))},_}function decorator(e,t,_){if(e){var n=_.writable,i=_.enumerable;return{get:function(){var e=middle(_.value,this);return Object.defineProperty(this,t,{value:e,writable:n,enumerable:i}),e}}}}export{decorator};export default middle; //# sourceMappingURL=middle.es.js.map
(function() { 'use strict'; var name = 'ZOBAngels.directive.SecurityDirectives'; var securityDirectives = angular.module(name,[ 'ZOBAngels.service.AccountService' ]); securityDirectives.directive('isAuthenticated',[ 'ngIfDirective', 'ZOBAngels.service.AccountService', function(ngIfDirective,accountService) { var ngIf = ngIfDirective[0]; return { transclude: ngIf.transclude, priority: ngIf.priority - 1, terminal: ngIf.terminal, restrict: ngIf.restrict, link: function(scope, element, attributes) { // find the initial ng-if attribute var initialNgIf = attributes.ngIf, ifEvaluator; // if it exists, evaluates ngIf && ifAuthenticated if (initialNgIf) { ifEvaluator = function () { return scope.$eval(initialNgIf) && accountService.isLoggedIn(); }; } else { ifEvaluator = function () { return accountService.isLoggedIn(); }; } attributes.ngIf = ifEvaluator; ngIf.link.apply(ngIf, arguments); } }; } ]); securityDirectives.directive('isNotAuthenticated',[ 'ngIfDirective', 'ZOBAngels.service.AccountService', function(ngIfDirective,accountService) { var ngIf = ngIfDirective[0]; return { transclude: ngIf.transclude, priority: ngIf.priority - 1, terminal: ngIf.terminal, restrict: ngIf.restrict, link: function(scope, element, attributes) { // find the initial ng-if attribute var initialNgIf = attributes.ngIf, ifEvaluator; // if it exists, evaluates ngIf && ifAuthenticated if (initialNgIf) { ifEvaluator = function () { return scope.$eval(initialNgIf) && !accountService.isLoggedIn(); }; } else { ifEvaluator = function () { return !accountService.isLoggedIn(); }; } attributes.ngIf = ifEvaluator; ngIf.link.apply(ngIf, arguments); } }; } ]); securityDirectives.directive('hasRole',[ 'ngIfDirective', 'ZOBAngels.service.AccountService', function(ngIfDirective,accountService) { var ngIf = ngIfDirective[0]; return { transclude: ngIf.transclude, priority: ngIf.priority - 1, terminal: ngIf.terminal, restrict: ngIf.restrict, link: function(scope, element, attributes) { // find the initial ng-if attribute var initialNgIf = attributes.ngIf, ifEvaluator; // if it exists, evaluates ngIf && ifAuthenticated if (initialNgIf) { ifEvaluator = function () { return scope.$eval(initialNgIf) && accountService.hasRole(attributes.hasRole); }; } else { ifEvaluator = function () { return accountService.hasRole(attributes.hasRole); }; } attributes.ngIf = ifEvaluator; ngIf.link.apply(ngIf, arguments); } }; } ]); securityDirectives.directive('hasAnyRole',[ 'ngIfDirective', 'ZOBAngels.service.AccountService', function(ngIfDirective,accountService) { var ngIf = ngIfDirective[0]; return { transclude: ngIf.transclude, priority: ngIf.priority - 1, terminal: ngIf.terminal, restrict: ngIf.restrict, link: function(scope, element, attributes) { // find the initial ng-if attribute var initialNgIf = attributes.ngIf, ifEvaluator, roles = attributes.hasAnyRole.split(',').map(function(role) { return role.trim(); }), checkRoles = function(roles) { var i,len = roles.length; for (i=0; i<len; i+=1) { if (accountService.hasRole(roles[i])) { return true; } } return false; }; // if it exists, evaluates ngIf && ifAuthenticated if (initialNgIf) { ifEvaluator = function () { var i,len = roles.length; if (scope.$eval(initialNgIf)) { return checkRoles(roles); } return false; }; } else { ifEvaluator = function () { return checkRoles(roles); }; } attributes.ngIf = ifEvaluator; ngIf.link.apply(ngIf, arguments); } }; } ]); securityDirectives.directive('hasAllRoles',[ 'ngIfDirective', 'ZOBAngels.service.AccountService', function(ngIfDirective,accountService) { var ngIf = ngIfDirective[0]; return { transclude: ngIf.transclude, priority: ngIf.priority - 1, terminal: ngIf.terminal, restrict: ngIf.restrict, link: function(scope, element, attributes) { // find the initial ng-if attribute var initialNgIf = attributes.ngIf, ifEvaluator, roles = attributes.hasAllRoles.split(',').map(function(role) { return role.trim(); }), checkRoles = function(roles) { var i,len = roles.length; for (i=0; i<len; i+=1) { if (!accountService.hasRole(roles[i])) { return false; } } return true; }; // if it exists, evaluates ngIf && ifAuthenticated if (initialNgIf) { ifEvaluator = function () { var i,len = roles.length; if (scope.$eval(initialNgIf)) { return checkRoles(roles); } return false; }; } else { ifEvaluator = function () { return checkRoles(roles); }; } attributes.ngIf = ifEvaluator; ngIf.link.apply(ngIf, arguments); } }; } ]); })();
import React, { Component } from 'react' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Header from '../Shared/Header' import Body from './Body' import Footer from './Footer' import injectTapEventPlugin from 'react-tap-event-plugin'; const TheContainer = React.createClass({ render: function () { return ( <div> </div> ) } }); class MainPage extends Component { render(){ return( <MuiThemeProvider> <div> <Header /> <Body className="generic-center borderless"/> <Footer /> </div> </MuiThemeProvider> ) } } export default MainPage
(function() { 'use strict'; document.addEventListener('DOMContentLoaded', function() { var includes = document.querySelectorAll('.includes-link'); for(var i = 0; i < includes.length; i++) { includes[i].addEventListener('click', function(e) { e.preventDefault(); var example_box = this.parentElement.parentElement; example_box.classList.toggle('hide-includes'); }) } }) })();
import Blockly from 'node-blockly/browser'; Blockly.JavaScript['stop_motor'] = function (block) { var motor = Blockly.JavaScript.valueToCode(block, 'MOTOR', Blockly.JavaScript.ORDER_ATOMIC); let actualMotor = eval(motor); return(`bot.motors.${actualMotor.motor}.stop();\n`) };
const bluebird = require('bluebird'); const crypto = bluebird.promisifyAll(require('crypto')); const api_key = process.env.MAILGUN_API_KEY || process.env.MAILGUN_API_SANDBOX_KEY; const domain = process.env.DOMAIN; const mailgun = require('mailgun-js')({apiKey: api_key, domain: domain}); const passport = require('passport'); const User = require('../models/User'); /** * GET /login * Login page. */ exports.getLogin = (req, res) => { if (req.user) { return res.redirect('/'); } res.render('account/login', { title: 'Login' }); }; /** * POST /login * Sign in using email and password. */ exports.postLogin = (req, res, next) => { req.assert('email', 'Email is not valid').isEmail(); req.assert('password', 'Password cannot be blank').notEmpty(); req.sanitize('email').normalizeEmail({ remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/login'); } passport.authenticate('local', (err, user, info) => { if (err) { return next(err); } if (!user) { req.flash('errors', info); return res.redirect('/login'); } req.logIn(user, (err) => { if (err) { return next(err); } req.flash('success', { msg: 'Success! You are logged in.' }); res.redirect(req.session.returnTo || '/'); }); })(req, res, next); }; /** * GET /logout * Log out. */ exports.logout = (req, res) => { req.logout(); res.redirect('/'); }; /** * GET /signup * Signup page. */ exports.getSignup = (req, res) => { if (req.user) { return res.redirect('/'); } res.render('account/signup', { title: 'Create Account' }); }; /** * POST /signup * Create a new local account. */ exports.postSignup = (req, res, next) => { req.assert('email', 'Email is not valid').isEmail(); req.assert('password', 'Password must be at least 4 characters long').len(4); req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password); req.sanitize('email').normalizeEmail({ remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/signup'); } const user = new User({ email: req.body.email, password: req.body.password }); User.findOne({ email: req.body.email }, (err, existingUser) => { if (err) { return next(err); } if (existingUser) { req.flash('errors', { msg: 'Account with that email address already exists.' }); return res.redirect('/signup'); } user.save((err) => { if (err) { return next(err); } req.logIn(user, (err) => { if (err) { return next(err); } }); req.flash('success', { msg: 'Signup Success! Welcome to Furnace1.' }); res.redirect('/'); const emailData = { to: user.email, from: '"Furnace1" <noreply@furnace1.tk>', // sender address subject: 'Welcome to Furnace1', text: `Hello,\n\nWelcome to Furnace1\n` }; mailgun.messages().send(emailData, function (err, body) { if (err) { req.flash('errors', { msg: err.message }); } req.flash('success', { msg: 'Email has been sent successfully!' }); }); }); }); }; /** * GET /account * Profile page. */ exports.getAccount = (req, res) => { res.render('account/profile', { title: 'Account Management' }); }; /** * POST /account/profile * Update profile information. */ exports.postUpdateProfile = (req, res, next) => { req.assert('email', 'Please enter a valid email address.').isEmail(); req.sanitize('email').normalizeEmail({ remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findById(req.user.id, (err, user) => { if (err) { return next(err); } user.email = req.body.email || ''; user.profile.name = req.body.name || ''; user.profile.gender = req.body.gender || ''; user.profile.location = req.body.location || ''; user.profile.website = req.body.website || ''; user.save((err) => { if (err) { if (err.code === 11000) { req.flash('errors', { msg: 'The email address you have entered is already associated with an account.' }); return res.redirect('/account'); } return next(err); } req.flash('success', { msg: 'Profile information has been updated.' }); res.redirect('/account'); }); }); }; /** * POST /account/password * Update current password. */ exports.postUpdatePassword = (req, res, next) => { req.assert('password', 'Password must be at least 4 characters long').len(4); req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/account'); } User.findById(req.user.id, (err, user) => { if (err) { return next(err); } user.password = req.body.password; user.save((err) => { if (err) { return next(err); } req.flash('success', { msg: 'Password has been changed.' }); res.redirect('/account'); }); }); }; /** * POST /account/delete * Delete user account. */ exports.postDeleteAccount = (req, res, next) => { User.remove({ _id: req.user.id }, (err) => { if (err) { return next(err); } req.logout(); req.flash('info', { msg: 'Your account has been deleted.' }); res.redirect('/'); }); }; /** * GET /account/unlink/:provider * Unlink OAuth provider. */ exports.getOauthUnlink = (req, res, next) => { const provider = req.params.provider; User.findById(req.user.id, (err, user) => { if (err) { return next(err); } user[provider] = undefined; user.tokens = user.tokens.filter(token => token.kind !== provider); user.save((err) => { if (err) { return next(err); } req.flash('info', { msg: `${provider} account has been unlinked.` }); res.redirect('/account'); }); }); }; /** * GET /reset/:token * Reset Password page. */ exports.getReset = (req, res, next) => { if (req.isAuthenticated()) { return res.redirect('/'); } User .findOne({ passwordResetToken: req.params.token }) .where('passwordResetExpires').gt(Date.now()) .exec((err, user) => { if (err) { return next(err); } if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('/forgot'); } res.render('account/reset', { title: 'Password Reset' }); }); }; /** * POST /reset/:token * Process the reset password request. */ exports.postReset = (req, res, next) => { req.assert('password', 'Password must be at least 4 characters long.').len(4); req.assert('confirm', 'Passwords must match.').equals(req.body.password); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('back'); } const resetPassword = () => User .findOne({ passwordResetToken: req.params.token }) .where('passwordResetExpires').gt(Date.now()) .then((user) => { if (!user) { req.flash('errors', { msg: 'Password reset token is invalid or has expired.' }); return res.redirect('back'); } user.password = req.body.password; user.passwordResetToken = undefined; user.passwordResetExpires = undefined; return user.save().then(() => new Promise((resolve, reject) => { req.logIn(user, (err) => { if (err) { return reject(err); } resolve(user); }); })); }); const sendResetPasswordEmail = (user) => { if (!user) { return; } const emailData = { to: user.email, from: '"Furnace1" <noreply@furnace1.tk>', // sender address subject: 'Your password has been changed', text: `Hello,\n\nThis is a confirmation that the password for your account ${user.email} has just been changed.\n` }; mailgun.messages().send(emailData, function (err, body) { if (err) { req.flash('errors', { msg: err.message }); return res.redirect('/contact'); } req.flash('success', { msg: 'Email has been sent successfully!' }); }); }; resetPassword() .then(sendResetPasswordEmail) .then(() => { if (!res.finished) res.redirect('/'); }) .catch(err => next(err)); }; /** * GET /forgot * Forgot Password page. */ exports.getForgot = (req, res) => { if (req.isAuthenticated()) { return res.redirect('/'); } res.render('account/forgot', { title: 'Forgot Password' }); }; /** * POST /forgot * Create a random token, then the send user an email with a reset link. */ exports.postForgot = (req, res, next) => { req.assert('email', 'Please enter a valid email address.').isEmail(); req.sanitize('email').normalizeEmail({ remove_dots: false }); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/forgot'); } const createRandomToken = crypto .randomBytesAsync(16) .then(buf => buf.toString('hex')); const setRandomToken = token => User .findOne({ email: req.body.email }) .then((user) => { if (!user) { req.flash('errors', { msg: 'Account with that email address does not exist.' }); } else { user.passwordResetToken = token; user.passwordResetExpires = Date.now() + 3600000; // 1 hour user = user.save(); } return user; }); const sendForgotPasswordEmail = (user) => { if (!user) { return; } const token = user.passwordResetToken; const emailData = { to: user.email, from: '"Furnace1" <noreply@furnace1.tk>', // sender address subject: 'Reset your password on Hackathon Starter', text: `You are receiving this email because you (or someone else) have requested the reset of the password for your account.\n\n Please click on the following link, or paste this into your browser to complete the process:\n\n http://www.furnace1.tk /reset/${token}\n\n If you did not request this, please ignore this email and your password will remain unchanged.\n` }; mailgun.messages().send(emailData, function (err, body) { if (err) { req.flash('errors', { msg: err.message }); } req.flash('success', { msg: 'Email has been sent successfully!' }); }); }; createRandomToken .then(setRandomToken) .then(sendForgotPasswordEmail) .then(() => res.redirect('/forgot')) .catch(next); };
'use strict'; angular.module('projects', ['ui.router']) .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('projects', { url: '/projects', controller: 'ProjectsCtrl' }) .state('projects.project', { url: '/:project', controller: 'ProjectsCtrl' }); }]) .controller('ProjectsCtrl', ['$scope', function($scope) { var self = this; var project1 = { name: 'The Insomniac', placecard: 'cube-18.jpg', date: (new Date(2015, 5)).getTime(), sref: 'The-Insomniac', content: '' }; var project4 = { name: 'TileTraveler', placecard: 'composition-01.jpg', date: (new Date(2013, 11)).getTime(); sref: 'TileTraveler', content: '' }; var project2 = { name: 'GIS Lookup System', placecard: 'photoshoot-09.jpg', date: (new Date(2015, 5)).getTime(), sref: 'GIS', content: '' }; var project3 = { name: 'Protein Cavity Finder', placecard: 'cube-13.jpg', date: (new Date(2015, 4)).getTime(), sref: 'Protein-Cavity-Finder', content: '' }; self.activeProject = ''; self.projectItems = [project1, project2, project3, project4]; self.projectFormData = []; self.newProject = {name: '', placecard: '', month: 1 + (new Date()).getMonth(), year: 1970 + (new Date()).getYear(), sref: '', content: ''}; for (var i = 0; i < self.projectItems.length; i++) { var projectItem = projectItems[i]; self.projectFormData["_"+projectItem.sref] = {}; self.projectFormData["_"+projectItem.sref].name = projectItem.name; self.projectFormData["_"+projectItem.sref].placecard = projectItem.placecard; self.projectFormData["_"+projectItem.sref].date = projectItem.date; self.projectFormData["_"+projectItem.sref].sref = projectItem.sref; self.projectFormData["_"+projectItem.sref].content = projectItem.content; } $scope.$watch('$stateParams.project', function(val) { if (val != null) { var newProject = self.getFromSref(val); self.activeProject = newProject; } }); self.getFromSref = function (sref) { var theProject self.projectItems.filter(function(obj) { return obj.sref === sref; }) return ((theProject[0] === null || theProject[0] === undefined) ? null : theProject[0]); }; self.resetProjectForm = function(sref) { var modelProject = self.getFromSref(name); self.projectFormData["_" + sref].name = modelProject.name; self.projectFormData["_" + sref].placecard = modelProject.placecard; self.projectFormData["_" + sref].date = modelProject.date; self.projectFormData["_" + sref].sref = modelProject.sref; self.projectFormData["_" + sref].content = modelProject.content; } self.updateProject = function(sref) { var projectFields = self.projectFormData["_"+sref]; var updatedProject = {name: projectFields.name, placecard: projectFields.placecard, date: projectFields.date, sref: projectFields.sref, content: projectFields.content}; console.log("Updated: \n", updatedProject); } self.deleteProject = function(date) { var delProject = self.getFromSref(name); if($window.confirm("Delete project '" + delProject.title + "'?")) { console.log("Deleted: \n", delProject); } } self.submitProject = function() { var projectFields = self.projectFormData["_"+sref]; var newProject = {name: projectFields.name, placecard: projectFields.placecard, date: projectFields.date, sref: projectFields.sref, content: projectFields.content}; console.log("Submitting: ", newProject); } }])
var Application = require('./../models/application'); var Student = require('./../models/student'); var Company = require('./../models/company'); var MailController = require('./mailController'); var nodemailer = require("nodemailer"); var objectAssign = require('object-assign'); // Get var getApplication = function(res, criteria, project, option) { criteria = criteria || {}; project = project || {}; option = option || {}; Application.find(criteria, project, option, function(err, applications) { if (err) return res.status(500).send({ success: false, error:err }); res.status(200).send({ success: true, result: applications, meta : { limit : option.limit, skip : option.skip, total : applications.length } }); }); }; var getApplicationByStudent = function(res, item){ getApplication(res, {"student":item}); }; var getApplicationByCompany = function(res, item){ getApplication(res, {"company._id":item}); }; var getApplicationUnreply = function(res, item){ getApplication(res, {"reply":false}); }; var findApplicationById = function(res, item) { getApplication(res, {"_id": item}); }; var getStudentApplyStatus = function(res, item){ Application.find({student:item, apply_date:{$exists:true}},function(err, application) { if (err) return res.status(500).send({ success: false, error:err }); if(!application) return res.status(200).send({ success: true, result: {status : false} }); return res.status(200).send({ success:true, result: { status : true, applications: application } }); }); } var getStudentAcceptStatus = function(res, item){ Application.find({student:item,response:true,reply:{$exists:true}},function(err, application) { if (err) return res.status(500).send({success: false,error: err}); if(application) return res.status(200).send({ success: true, result: { status:true, _id:item } }); return res.status(200).send({ success:true, result:{ status:false, _id:item } }); }); } // Create var createApplication = function(res, item){ Student.findOne({ _id : item.student },{ attachments: 1, contact: 1, name: 1, gpa: 1, sex: 1 }, function(err, studentInfo){ if(err) { return res.status(500).send({ success:false, error:err }); } if(!studentInfo) { return res.status(400).send({ success:false, error: { message: "Student doesn't exist." } }); } var attach =[]; //console.log("attachs: ", studentInfo.attachments, studentInfo.attachments.length>0, studentInfo.attachments.length, typeof attach); if(studentInfo.attachments && studentInfo.attachments.length>0) attach = initialAttachment(studentInfo.attachments, item.attachments); Company.findOne({ _id: item.company._id },{ contact: 1, coordinator: 1, name: 1 }, function(err, companyInfo){ if(err) { return res.status(500).send({ success:false, error:err }); } if(!companyInfo) { return res.status(400).send({ success:false, error: { message: "Company doesn't exist." } }); } var newApplication = new Application(); objectAssign(newApplication, item); newApplication.save(function(err) { if (err) return res.status(500).send({ success:false, error:err }); }); var studentEmail = studentInfo.contact.email; var mailContent = "Student name : " + studentInfo.name.title + studentInfo.name.first + " " + studentInfo.name.last + "\n"; mailContent = mailContent + "ID : " + studentInfo._id + "\n"; mailContent = mailContent + "Email : " + studentEmail + " Tel : " + studentInfo.contact.tel + "\n"; mailContent = mailContent + "GPA : " + studentInfo.gpa + "\n"; mailContent = mailContent + "Sex : " + studentInfo.sex + "\n"; mailContent = mailContent + "Company : " + companyInfo.name.full + "\n"; var mailCompanyOption = { from : { name: 'CoopSys Admin', address: 'nattawut_k@cmu.ac.th' }, to : companyInfo.contact.email + ', "' + companyInfo.contact.name.first + " " + companyInfo.contact.name.last +'"', subject : "CS CMU Cooperative plan's student application", text : mailContent + "\n" + item.mail_text, attachments : attach } var mailStudentOption = { from : { name: 'CoopSys Admin', address: 'nattawut_k@cmu.ac.th' }, to : studentEmail, subject : "You have been apply to " + companyInfo.name.full, text : mailContent } MailController.sendMail(mailCompanyOption); MailController.sendMail(mailStudentOption); res.status(201).send({success: true, message: "Application email has been sent to the Company"}); }) }) } var initialAttachment = function(attachments, needAttachments){ attachments = attachments || []; var result = []; var i = 0; for(var i=0; i<attachments.length; i++){ //console.log("doc"+i+" : " + attachments[i]._id, needAttachments.lastIndexOf(attachments[i]._id)); if(needAttachments.lastIndexOf(attachments[i]._id.toString())>=0){ var newItem= {}; newItem.filename = attachments[i].file_name, newItem.path = "./public/" + attachments[i].file_path.substr(2); newItem.contentType = "application/pdf" result.push(newItem); //console.log(newItem) } } return result; } // Update var updateApplication = function(res, item) { Application.findOne({ _id: item._id }, function(err, doc) { if (err) return res.status(500).send({ success:false, error:err }); if (!doc) { console.log("Not found - not update"); return res.status(400).send({ success:false, result:err }); } // if(item.attachments) // delete item.attachments; objectAssign(doc, item); doc.save(function(err){ if (err) return res.status(500).send({ success:false, error:err }); return res.status(200).send({ success:true }); }); }); }; // Remove var delApplication = function(res, item) { Application.remove({ _id: item }, function(err) { if (err) return res.status(500).send({ success:false, error:err }); return res.status(200).send({ success:true }); }) }; module.exports = { 'getApplication': getApplication, 'getApplicationByStudent': getApplicationByStudent, 'getApplicationByCompany': getApplicationByCompany, 'getApplicationUnreply': getApplicationUnreply, 'findApplicationById': findApplicationById, 'getStudentApplyStatus': getStudentApplyStatus, 'getStudentAcceptStatus': getStudentAcceptStatus, 'createApplication': createApplication, 'updateApplication': updateApplication, 'delApplication': delApplication, };
function toggleSide(node) { $('.sidebar').toggleClass('hidden'); $('.page-main').toggleClass('hidden'); } $(document).ready(function(){ $('.sidebar').css('height',document.body.offsetHeight+"px"); $('.sidebar .scrollpane>ul.nav').slimScroll({ height: '100%' }); if(!window.module)return; var active = $('.sidebar .doc-link[module="'+module+'"][name="'+name+'"]'); active.addClass('active'); //scroll to $('.sidebar .scrollpane ul[name="scrolllist"]').slimScroll({ scrollTo:active.offset().top - 200/*paddingTop*/ +'px' }); }); function openWindow(path){ var code = EDITOR.getValue(); localStorage.setItem("code",code); window.open('window.html',module+"-"+name,'width=800,height=600'); } function runjs(){ var code = EDITOR.getValue(); localStorage.setItem("code",code); //stop all games soya2d.games.forEach(function(game){ game.destroy(); }); new Function(code)(); }
function readURL(input,x) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('.img').eq(x).attr('src', e.target.result); try { resizeImg(); } catch(e) { } }; reader.readAsDataURL(input.files[0]); } }
require('chai').use(require('chai-as-promised')) if (global.__env__) { process.env.CHROMANODE_URL = global.__env__.CHROMANODE_URL } let errors = require('../src').errors process.on('unhandledRejection', (err) => { let msg = (err && err.stack || err).toString() if (err instanceof errors.Network.Chromanode.Fail || err instanceof errors.Network.SubscribeError) { console.error(msg.split('\n')[0]) return } console.log(msg) }) describe('blockchainjs', () => { // network require('./network/network') require('./network/chromanode') // storage require('./storage/interface') require('./storage/indexeddb') require('./storage/localstorage') require('./storage/memory') require('./storage/sqlite') require('./storage/websql') // blockchain require('./blockchain/blockchain') require('./blockchain/naive') require('./blockchain/verified') })
import state from './basket.state' import actions from './basket.actions' import mutations from './basket.mutations' export default { state, actions, mutations }
function compose() { const argz = arguments; return x => [...argz].reduceRight((acc, curr) => curr(acc), x); } const addClass = name => el => { el.classList.add(name); } const S = f => g => x => { const fx = f(x); const gx = g(x); const result = fx(gx); return result; } const K = x => y => { return x; } const addClassOK = name => S(K)(addClass(name)); // x => K(x)(addClass(name)(x)); const getElement = document.getElementById.bind(document); const mess = compose (addClassOK('red'), addClassOK('large'), getElement); const mess2 = el => addClassOK('red')(addClassOK('large')(getElement(el))); const newMess = el => PIPPO().GetElement(el).AddClassOK('large').AddClassOK('red'); function PIPPO() { let _target; const result = { target: () => _target, GetElement: id => { _target = getElement(id); return result; }, AddClassOK: name => { addClassOK(name)(result.target()); return result; }, }; return result; }
import { map } from '@ember/object/computed'; import { isEmpty } from '@ember/utils'; import { observer, get, defineProperty } from '@ember/object'; import Helper from '@ember/component/helper'; export default Helper.extend({ compute([func, array]) { this.set('func', func); this.set('array', array); return this.get('content'); }, changed: observer('content', function() { this.recompute(); }), funcDidChange: observer('func', function() { let func = get(this, 'func'); if ( isEmpty(func) ) { defineProperty(this, 'content', []); return; } defineProperty(this, 'content', map('array', func)); }), });
// chrome.tabs // ----------------- // ref: // - http://chrome.liuyixi.com/tabs.html (function (root, factory) { 'use strict'; if ('function' === typeof define && define.amd) { define([], factory); } else { root.tabs = factory(); } }(window, function () { 'use strict'; var tabs = { /* * * 获取一个标签页对象 * * @method get * @param {Number} tabId 标签页 Id * @returns {Object} 标签页对象 * */ get: function (tabId) { return new Promise(function (resolve) { chrome.tabs.get(tabId, function (tab) { resolve(tab); }); }); }, /* * * 获取该方法被调用时所在的标签页对象,在 background 和 popup 中时返回 undefined * * @method getCurrent * @returns {Object} 标签页对象 * */ getCurrent: function () { return new Promise(function (resolve) { chrome.tabs.getCurrent(function (tab) { resolve(tab); }); }); }, query: function (queryInfo) { return new Promise(function (resolve, reject) { chrome.tabs.query(queryInfo, function (tabs) { var error = chrome.extension.lastError; error ? reject(error) : resolve(tabs); }); }); }, getSelected: function () { return this.query({active: true}); }, getAllInWindow: function (windowId) { return this.query({windowId: windowId}); }, /* * * 向内容页或注入到页面的 iframe 发送消息 * * @method sendMessage * @param {String} tabId 标签 id * @param {Any} message 消息内容 * @returns {Promise} * */ sendMessage: function (tabId, message, options) { return new Promise(function (resolve, reject) { function cb(response) { var error = chrome.extension.lastError; error ? reject(error) : resolve(response); } options ? chrome.tabs.sendMessage(tabId, message, options, cb) : chrome.tabs.sendMessage(tabId, message, cb); }); } }; return Object.freeze(tabs); }));