code
stringlengths
2
1.05M
export function deferredFactoryResolveSpy(resolve_value) { let resolve_fn; const resolve_spy = sinon.spy(v => resolve_fn(v)); const promise = new Promise(resolve => { resolve_fn = sinon.spy(resolve); }); const factory_spy = sinon.spy(() => { setImmediate(resolve_spy, resolve_value); return promise; }); return [factory_spy, resolve_spy]; }
'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var di_1 = require('angular2/di'); var collection_1 = require('angular2/src/core/facade/collection'); var lang_1 = require('angular2/src/core/facade/lang'); var modelModule = require('./model'); /** * Creates a form object from a user-specified configuration. * * # Example * * ``` * import {Component, View, bootstrap} from 'angular2/angular2'; * import {FormBuilder, Validators, FORM_DIRECTIVES, ControlGroup} from 'angular2/forms'; * * @Component({ * selector: 'login-comp', * viewBindings: [ * FormBuilder * ] * }) * @View({ * template: ` * <form [control-group]="loginForm"> * Login <input control="login"> * * <div control-group="passwordRetry"> * Password <input type="password" control="password"> * Confirm password <input type="password" control="passwordConfirmation"> * </div> * </form> * `, * directives: [ * FORM_DIRECTIVES * ] * }) * class LoginComp { * loginForm: ControlGroup; * * constructor(builder: FormBuilder) { * this.loginForm = builder.group({ * login: ["", Validators.required], * * passwordRetry: builder.group({ * password: ["", Validators.required], * passwordConfirmation: ["", Validators.required] * }) * }); * } * } * * bootstrap(LoginComp) * ``` * * This example creates a {@link ControlGroup} that consists of a `login` {@link Control}, and a * nested * {@link ControlGroup} that defines a `password` and a `passwordConfirmation` {@link Control}: * * ``` * var loginForm = builder.group({ * login: ["", Validators.required], * * passwordRetry: builder.group({ * password: ["", Validators.required], * passwordConfirmation: ["", Validators.required] * }) * }); * * ``` */ var FormBuilder = (function () { function FormBuilder() { } FormBuilder.prototype.group = function (controlsConfig, extra) { if (extra === void 0) { extra = null; } var controls = this._reduceControls(controlsConfig); var optionals = lang_1.isPresent(extra) ? collection_1.StringMapWrapper.get(extra, "optionals") : null; var validator = lang_1.isPresent(extra) ? collection_1.StringMapWrapper.get(extra, "validator") : null; if (lang_1.isPresent(validator)) { return new modelModule.ControlGroup(controls, optionals, validator); } else { return new modelModule.ControlGroup(controls, optionals); } }; FormBuilder.prototype.control = function (value, validator) { if (validator === void 0) { validator = null; } if (lang_1.isPresent(validator)) { return new modelModule.Control(value, validator); } else { return new modelModule.Control(value); } }; FormBuilder.prototype.array = function (controlsConfig, validator) { var _this = this; if (validator === void 0) { validator = null; } var controls = collection_1.ListWrapper.map(controlsConfig, function (c) { return _this._createControl(c); }); if (lang_1.isPresent(validator)) { return new modelModule.ControlArray(controls, validator); } else { return new modelModule.ControlArray(controls); } }; FormBuilder.prototype._reduceControls = function (controlsConfig) { var _this = this; var controls = {}; collection_1.StringMapWrapper.forEach(controlsConfig, function (controlConfig, controlName) { controls[controlName] = _this._createControl(controlConfig); }); return controls; }; FormBuilder.prototype._createControl = function (controlConfig) { if (controlConfig instanceof modelModule.Control || controlConfig instanceof modelModule.ControlGroup || controlConfig instanceof modelModule.ControlArray) { return controlConfig; } else if (lang_1.isArray(controlConfig)) { var value = controlConfig[0]; var validator = controlConfig.length > 1 ? controlConfig[1] : null; return this.control(value, validator); } else { return this.control(controlConfig); } }; FormBuilder = __decorate([ di_1.Injectable(), __metadata('design:paramtypes', []) ], FormBuilder); return FormBuilder; })(); exports.FormBuilder = FormBuilder; //# sourceMappingURL=form_builder.js.map
'use strict'; var csp = require('../../dist/index'); csp.longStackSupport = true; var a = function() { return csp.go(function*() { throw new Error("Oops!"); }); }; var b = function() { return csp.go(function*() { return yield csp.go(function*() { return yield a(); }); }); }; var c = function() { return csp.go(function*() { return yield b(); }); }; csp.top(c());
/** @module ember @submodule ember-views */ import jQuery from "ember-views/system/jquery"; import Ember from "ember-metal/core"; import o_create from 'ember-metal/platform/create'; import { normalizeProperty } from "dom-helper/prop"; import { canSetNameOnInputs } from "ember-views/system/platform"; // The HTML spec allows for "omitted start tags". These tags are optional // when their intended child is the first thing in the parent tag. For // example, this is a tbody start tag: // // <table> // <tbody> // <tr> // // The tbody may be omitted, and the browser will accept and render: // // <table> // <tr> // // However, the omitted start tag will still be added to the DOM. Here // we test the string and context to see if the browser is about to // perform this cleanup, but with a special allowance for disregarding // <script tags. This disregarding of <script being the first child item // may bend the official spec a bit, and is only needed for Handlebars // templates. // // http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags // describes which tags are omittable. The spec for tbody and colgroup // explains this behavior: // // http://www.whatwg.org/specs/web-apps/current-work/multipage/tables.html#the-tbody-element // http://www.whatwg.org/specs/web-apps/current-work/multipage/tables.html#the-colgroup-element // var omittedStartTagChildren; var omittedStartTagChildTest = /(?:<script)*.*?<([\w:]+)/i; function detectOmittedStartTag(dom, string, contextualElement) { omittedStartTagChildren = omittedStartTagChildren || { tr: dom.createElement('tbody'), col: dom.createElement('colgroup') }; // Omitted start tags are only inside table tags. if (contextualElement.tagName === 'TABLE') { var omittedStartTagChildMatch = omittedStartTagChildTest.exec(string); if (omittedStartTagChildMatch) { // It is already asserted that the contextual element is a table // and not the proper start tag. Just look up the start tag. return omittedStartTagChildren[omittedStartTagChildMatch[1].toLowerCase()]; } } } function ClassSet() { this.seen = o_create(null); this.list = []; } ClassSet.prototype = { add(string) { if (this.seen[string] === true) { return; } this.seen[string] = true; this.list.push(string); } }; var BAD_TAG_NAME_TEST_REGEXP = /[^a-zA-Z0-9\-]/; var BAD_TAG_NAME_REPLACE_REGEXP = /[^a-zA-Z0-9\-]/g; function stripTagName(tagName) { if (!tagName) { return tagName; } if (!BAD_TAG_NAME_TEST_REGEXP.test(tagName)) { return tagName; } return tagName.replace(BAD_TAG_NAME_REPLACE_REGEXP, ''); } var BAD_CHARS_REGEXP = /&(?!\w+;)|[<>"'`]/g; var POSSIBLE_CHARS_REGEXP = /[&<>"'`]/; function escapeAttribute(value) { // Stolen shamelessly from Handlebars var escape = { "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" }; var escapeChar = function(chr) { return escape[chr] || "&amp;"; }; var string = value.toString(); if (!POSSIBLE_CHARS_REGEXP.test(string)) { return string; } return string.replace(BAD_CHARS_REGEXP, escapeChar); } export function renderComponentWithBuffer(component, contextualElement, dom) { var buffer = []; component.render(buffer); var element = dom.parseHTML(buffer.join(''), contextualElement); return element; } /** `Ember.RenderBuffer` gathers information regarding the view and generates the final representation. `Ember.RenderBuffer` will generate HTML which can be pushed to the DOM. ```javascript var buffer = new Ember.RenderBuffer('div', contextualElement); ``` @method renderBuffer @namespace Ember */ var RenderBuffer = function(domHelper) { this.buffer = null; this.childViews = []; this.attrNodes = []; Ember.assert("RenderBuffer requires a DOM helper to be passed to its constructor.", !!domHelper); this.dom = domHelper; }; RenderBuffer.prototype = { reset(tagName, contextualElement) { this.tagName = tagName; this.buffer = null; this._element = null; this._outerContextualElement = contextualElement; this.elementClasses = null; this.elementId = null; this.elementAttributes = null; this.elementProperties = null; this.elementTag = null; this.elementStyle = null; this.childViews.length = 0; this.attrNodes.length = 0; }, // The root view's element _element: null, // The root view's contextualElement _outerContextualElement: null, /** An internal set used to de-dupe class names when `addClass()` is used. After each call to `addClass()`, the `classes` property will be updated. @private @property elementClasses @type Array @default null */ elementClasses: null, /** Array of class names which will be applied in the class attribute. You can use `setClasses()` to set this property directly. If you use `addClass()`, it will be maintained for you. @property classes @type Array @default null */ classes: null, /** The id in of the element, to be applied in the id attribute. You should not set this property yourself, rather, you should use the `id()` method of `Ember.RenderBuffer`. @property elementId @type String @default null */ elementId: null, /** A hash keyed on the name of the attribute and whose value will be applied to that attribute. For example, if you wanted to apply a `data-view="Foo.bar"` property to an element, you would set the elementAttributes hash to `{'data-view':'Foo.bar'}`. You should not maintain this hash yourself, rather, you should use the `attr()` method of `Ember.RenderBuffer`. @property elementAttributes @type Hash @default {} */ elementAttributes: null, /** A hash keyed on the name of the properties and whose value will be applied to that property. For example, if you wanted to apply a `checked=true` property to an element, you would set the elementProperties hash to `{'checked':true}`. You should not maintain this hash yourself, rather, you should use the `prop()` method of `Ember.RenderBuffer`. @property elementProperties @type Hash @default {} */ elementProperties: null, /** The tagname of the element an instance of `Ember.RenderBuffer` represents. Usually, this gets set as the first parameter to `Ember.RenderBuffer`. For example, if you wanted to create a `p` tag, then you would call ```javascript Ember.RenderBuffer('p', contextualElement) ``` @property elementTag @type String @default null */ elementTag: null, /** A hash keyed on the name of the style attribute and whose value will be applied to that attribute. For example, if you wanted to apply a `background-color:black;` style to an element, you would set the elementStyle hash to `{'background-color':'black'}`. You should not maintain this hash yourself, rather, you should use the `style()` method of `Ember.RenderBuffer`. @property elementStyle @type Hash @default {} */ elementStyle: null, pushChildView(view) { var index = this.childViews.length; this.childViews[index] = view; this.push("<script id='morph-"+index+"' type='text/x-placeholder'>\x3C/script>"); }, pushAttrNode(node) { var index = this.attrNodes.length; this.attrNodes[index] = node; }, hydrateMorphs(contextualElement) { var childViews = this.childViews; var el = this._element; for (var i=0,l=childViews.length; i<l; i++) { var childView = childViews[i]; var ref = el.querySelector('#morph-'+i); Ember.assert('An error occurred while setting up template bindings. Please check ' + (((childView && childView.parentView && childView._parentView._debugTemplateName ? '"' + childView._parentView._debugTemplateName + '" template ' : '')) ) + 'for invalid markup or bindings within HTML comments.', ref); var parent = ref.parentNode; childView._morph = this.dom.insertMorphBefore( parent, ref, parent.nodeType === 1 ? parent : contextualElement ); parent.removeChild(ref); } }, /** Adds a string of HTML to the `RenderBuffer`. @method push @param {String} string HTML to push into the buffer @chainable */ push(content) { if (typeof content === 'string') { if (this.buffer === null) { this.buffer = ''; } Ember.assert("A string cannot be pushed into the buffer after a fragment", !this.buffer.nodeType); this.buffer += content; } else { Ember.assert("A fragment cannot be pushed into a buffer that contains content", !this.buffer); this.buffer = content; } return this; }, /** Adds a class to the buffer, which will be rendered to the class attribute. @method addClass @param {String} className Class name to add to the buffer @chainable */ addClass(className) { // lazily create elementClasses this.elementClasses = (this.elementClasses || new ClassSet()); this.elementClasses.add(className); this.classes = this.elementClasses.list; return this; }, setClasses(classNames) { this.elementClasses = null; var len = classNames.length; var i; for (i = 0; i < len; i++) { this.addClass(classNames[i]); } }, /** Sets the elementID to be used for the element. @method id @param {String} id @chainable */ id(id) { this.elementId = id; return this; }, // duck type attribute functionality like jQuery so a render buffer // can be used like a jQuery object in attribute binding scenarios. /** Adds an attribute which will be rendered to the element. @method attr @param {String} name The name of the attribute @param {String} value The value to add to the attribute @chainable @return {Ember.RenderBuffer|String} this or the current attribute value */ attr(name, value) { var attributes = this.elementAttributes = (this.elementAttributes || {}); if (arguments.length === 1) { return attributes[name]; } else { attributes[name] = value; } return this; }, /** Remove an attribute from the list of attributes to render. @method removeAttr @param {String} name The name of the attribute @chainable */ removeAttr(name) { var attributes = this.elementAttributes; if (attributes) { delete attributes[name]; } return this; }, /** Adds a property which will be rendered to the element. @method prop @param {String} name The name of the property @param {String} value The value to add to the property @chainable @return {Ember.RenderBuffer|String} this or the current property value */ prop(name, value) { var properties = this.elementProperties = (this.elementProperties || {}); if (arguments.length === 1) { return properties[name]; } else { properties[name] = value; } return this; }, /** Remove an property from the list of properties to render. @method removeProp @param {String} name The name of the property @chainable */ removeProp(name) { var properties = this.elementProperties; if (properties) { delete properties[name]; } return this; }, /** Adds a style to the style attribute which will be rendered to the element. @method style @param {String} name Name of the style @param {String} value @chainable */ style(name, value) { this.elementStyle = (this.elementStyle || {}); this.elementStyle[name] = value; return this; }, generateElement() { var tagName = this.tagName; var id = this.elementId; var classes = this.classes; var attrs = this.elementAttributes; var props = this.elementProperties; var style = this.elementStyle; var styleBuffer = ''; var attr, prop, tagString; if (!canSetNameOnInputs && attrs && attrs.name) { // IE allows passing a tag to createElement. See note on `canSetNameOnInputs` above as well. tagString = '<'+stripTagName(tagName)+' name="'+escapeAttribute(attrs.name)+'">'; } else { tagString = tagName; } var element = this.dom.createElement(tagString, this.outerContextualElement()); if (id) { this.dom.setAttribute(element, 'id', id); this.elementId = null; } if (classes) { this.dom.setAttribute(element, 'class', classes.join(' ')); this.classes = null; this.elementClasses = null; } if (style) { for (prop in style) { styleBuffer += (prop + ':' + style[prop] + ';'); } this.dom.setAttribute(element, 'style', styleBuffer); this.elementStyle = null; } if (attrs) { for (attr in attrs) { this.dom.setAttribute(element, attr, attrs[attr]); } this.elementAttributes = null; } if (props) { for (prop in props) { var normalizedCase = normalizeProperty(element, prop.toLowerCase()) || prop; this.dom.setPropertyStrict(element, normalizedCase, props[prop]); } this.elementProperties = null; } return this._element = element; }, /** @method element @return {DOMElement} The element corresponding to the generated HTML of this buffer */ element() { if (this._element && this.attrNodes.length > 0) { var i, l, attrMorph, attrNode; for (i=0, l=this.attrNodes.length; i<l; i++) { attrNode = this.attrNodes[i]; attrMorph = this.dom.createAttrMorph(this._element, attrNode.attrName); attrNode._morph = attrMorph; } } var content = this.innerContent(); // No content means a text node buffer, with the content // in _element. Ember._BoundView is an example. if (content === null) { return this._element; } var contextualElement = this.innerContextualElement(content); this.dom.detectNamespace(contextualElement); if (!this._element) { this._element = this.dom.createDocumentFragment(); } if (content.nodeType) { this._element.appendChild(content); } else { var frag = this.dom.parseHTML(content, contextualElement); this._element.appendChild(frag); } // This should only happen with legacy string buffers if (this.childViews.length > 0) { this.hydrateMorphs(contextualElement); } return this._element; }, /** Generates the HTML content for this buffer. @method string @return {String} The generated HTML */ string() { if (this._element) { // Firefox versions < 11 do not have support for element.outerHTML. var thisElement = this.element(); var outerHTML = thisElement.outerHTML; if (typeof outerHTML === 'undefined') { return jQuery('<div/>').append(thisElement).html(); } return outerHTML; } else { return this.innerString(); } }, outerContextualElement() { if (this._outerContextualElement === undefined) { Ember.deprecate("The render buffer expects an outer contextualElement to exist." + " This ensures DOM that requires context is correctly generated (tr, SVG tags)." + " Defaulting to document.body, but this will be removed in the future"); this.outerContextualElement = document.body; } return this._outerContextualElement; }, innerContextualElement(html) { var innerContextualElement; if (this._element && this._element.nodeType === 1) { innerContextualElement = this._element; } else { innerContextualElement = this.outerContextualElement(); } var omittedStartTag; if (html) { omittedStartTag = detectOmittedStartTag(this.dom, html, innerContextualElement); } return omittedStartTag || innerContextualElement; }, innerString() { var content = this.innerContent(); if (content && !content.nodeType) { return content; } }, innerContent() { return this.buffer; } }; export default RenderBuffer;
version https://git-lfs.github.com/spec/v1 oid sha256:2fc29dbedc7376eafdb0844aef43145ddc25d5f50e95271a957e887582688621 size 206304
var _ = require('lodash'), Promise = require('bluebird'), storage = require('../../../storage/index'), replaceImage, ImageImporter, preProcessPosts, preProcessTags, preProcessUsers; replaceImage = function (markdown, image) { // Normalizes to include a trailing slash if there was one var regex = new RegExp('(/)?' + image.originalPath, 'gm'); return markdown.replace(regex, image.newPath); }; preProcessPosts = function (data, image) { _.each(data.posts, function (post) { post.markdown = replaceImage(post.markdown, image); if (post.html) { post.html = replaceImage(post.html, image); } if (post.image) { post.image = replaceImage(post.image, image); } }); }; preProcessTags = function (data, image) { _.each(data.tags, function (tag) { if (tag.image) { tag.image = replaceImage(tag.image, image); } }); }; preProcessUsers = function (data, image) { _.each(data.users, function (user) { if (user.cover) { user.cover = replaceImage(user.cover, image); } if (user.image) { user.image = replaceImage(user.image, image); } }); }; ImageImporter = { type: 'images', preProcess: function (importData) { if (importData.images && importData.data) { _.each(importData.images, function (image) { preProcessPosts(importData.data.data, image); preProcessTags(importData.data.data, image); preProcessUsers(importData.data.data, image); }); } importData.preProcessedByImage = true; return importData; }, doImport: function (imageData) { var store = storage.getStorage(); return Promise.map(imageData, function (image) { return store.save(image, image.targetDir).then(function (result) { return {originalPath: image.originalPath, newPath: image.newPath, stored: result}; }); }); } }; module.exports = ImageImporter;
'use strict'; module.exports = function (req, res) { res.statusCode = 200; res.setHeader('X-Frame-Options', 'SAMEORIGIN'); res.setHeader('X-Xss-Protection', '1; mode=block'); res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.setHeader('Etag', '"7d6d90aec27891b906d0ee6dfc9af4f3"'); res.setHeader('Cache-Control', 'max-age=0, private, must-revalidate'); res.setHeader('X-Request-Id', '7fbe6044-0ea6-4384-abc6-5c0db31566b1'); res.setHeader('X-Runtime', '0.026813'); res.setHeader('Vary', 'Origin'); res.setHeader('Date', 'Wed, 23 Mar 2016 00:31:47 GMT'); res.setHeader('Connection', 'close'); res.write(new Buffer(JSON.stringify({ "message": "Refresh in progress for 3 bills", "status": "200" }))); res.end(); return __filename; };
import 'styles/main.css'; import ColourBar from 'components/ColourBar'; import Favico from 'components/Favico'; import Navigation from 'components/Navigation'; import { ColourProvider } from 'context/colour'; import Head from 'next/head'; import Script from 'next/script'; // eslint-disable-next-line react/prop-types export default function App({ Component, pageProps }) { return ( <> <Head> <link key="favico" rel="icon" sizes="any" href="/favicon.ico" /> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" /> <meta name="msapplication-TileColor" content="#da532c" /> <meta name="theme-color" content="#ffffff" /> <link rel="manifest" href="/site.webmanifest" /> </Head> {process.env.NODE_ENV === 'production' && ( <> <Script strategy="afterInteractive" src="https://www.googletagmanager.com/gtag/js?id=UA-44359005-1" /> <Script strategy="afterInteractive" dangerouslySetInnerHTML={{ __html: ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-44359005-1'); `, }} /> </> )} <ColourProvider> <Favico /> <ColourBar /> <Navigation /> <Component {...pageProps} /> </ColourProvider> </> ); }
import cn from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import Listbox from 'react-widgets/lib/Listbox'; import BaseVirtualList from 'react-list'; import ListOption from 'react-widgets/lib/ListOption'; import ListOptionGroup from 'react-widgets/lib/ListOptionGroup'; import { groupBySortedKeys } from 'react-widgets/lib/util/_'; import * as CustomPropTypes from 'react-widgets/lib/util/PropTypes'; export const virtualListPropTypes = { itemSizeEstimator: PropTypes.func, itemSizeGetter: PropTypes.func, pageSize: PropTypes.number, threshold: PropTypes.number, type: PropTypes.oneOf(['simple', 'variable', 'uniform']), useStaticSize: PropTypes.bool, useTranslate3d: PropTypes.bool, hasNextPage: PropTypes.bool, onRequestItems: PropTypes.func, loadingComponent: CustomPropTypes.elementType, } class VirtualList extends React.Component { static propTypes = { ...virtualListPropTypes, data: PropTypes.array, dataState: PropTypes.object, onSelect: PropTypes.func, onMove: PropTypes.func, activeId: PropTypes.string, optionComponent: CustomPropTypes.elementType, renderItem: PropTypes.func.isRequired, renderGroup: PropTypes.func, focusedItem: PropTypes.any, selectedItem: PropTypes.any, isDisabled: PropTypes.func.isRequired, textAccessor: PropTypes.func.isRequired, disabled: CustomPropTypes.disabled.acceptsArray, groupBy: CustomPropTypes.accessor, messages: PropTypes.shape({ emptyList: CustomPropTypes.message, }) } static defaultProps = { optionComponent: ListOption, type: 'variable', hasNextPage: false, } static getVirtualListProps({ type, itemSizeGetter, itemSizeEstimator, pageSize = 20, threshold = 300, useStaticSize, useTranslate3d, onRequestItems, hasNextPage, loadingComponent, ...props }) { return { props, listProps: { onRequestItems, hasNextPage, loadingComponent, type, itemSizeGetter, itemSizeEstimator, pageSize, threshold, useStaticSize, useTranslate3d, }, } } static getDataState(data, { groupBy }, lastState) { let initial = { flatData: data } lastState = lastState || initial; if ( lastState.data !== data || lastState.groupBy !== groupBy ) { if (!groupBy) return initial; let keys = []; let groups = groupBySortedKeys(groupBy, data, keys); let sequentialData = [] let flatData = [] keys.forEach(group => { let items = groups[group] let groupItem = { __isGroup: true, group }; sequentialData = [...sequentialData, ...items] flatData = [...flatData, groupItem, ...items] }, []); return { groups, groupBy, flatData, sequentialData, sortedKeys: keys, }; } return lastState; } componentDidMount() { this.move() } componentDidUpdate(prevProps) { if ( prevProps.focusedItem !== this.props.focusedItem || prevProps.selectedItem !== this.props.selectedItem ) this.move() } renderItems = (items, ref) => { let { className, messages } = this.props; return ( <Listbox ref={ref} className={className} style={{ overflow: 'visible', maxHeight: 'none' }} emptyListMessage={messages.emptyList(this.props)} > {items} </Listbox> ) } renderItem = (index, key) => { let { activeId , focusedItem , selectedItem , onSelect , dataState , renderItem , isDisabled , pageSize , hasNextPage , onRequestItems , searchTerm , loadingComponent: LoadingComponent , optionComponent: OptionComponent } = this.props let item = dataState.flatData[index]; let len = dataState.flatData.length; if (hasNextPage === true && index >= len) { if (onRequestItems) onRequestItems({ pageSize, searchTerm, limit: len + pageSize, currentIndex: index, }); return ( <li key={key} className="rw-list-empty rw-list-option-loading"> {LoadingComponent ? ( <LoadingComponent key={key} index={index} pageSize={pageSize} /> ) : ( 'Loading items…' )} </li> ) } if (item && item.__isGroup) return this.renderGroupHeader(item.group) let isFocused = focusedItem === item; return ( <OptionComponent key={key} activeId={activeId} dataItem={item} focused={isFocused} disabled={isDisabled(item)} selected={selectedItem === item} onSelect={onSelect} > {renderItem({ item, index })} </OptionComponent> ) } render() { let { type , itemSizeGetter , itemSizeEstimator , pageSize , threshold , useStaticSize , useTranslate3d = true , dataState , itemHeight , focusedItem , selectedItem , onSelect , hasNextPage , searchTerm , disabled } = this.props let length = dataState.flatData.length; if (hasNextPage === true) length += 1; return ( <div className={cn( 'rw-virtual-list-wrapper', type === 'uniform' && 'rw-virtual-list-fixed' )} > <BaseVirtualList ref='scrollable' type={type} length={length} pageSize={pageSize} threshold={threshold} useStaticSize={useStaticSize} useTranslate3d={useTranslate3d} itemRenderer={this.renderItem} itemsRenderer={this.renderItems} itemSizeGetter={itemSizeGetter} itemSizeEstimator={itemSizeEstimator} // these are all to break the list's SCU dataState={dataState} focusedItem={focusedItem} selectedItem={selectedItem} searchTerm={searchTerm} onSelect={onSelect} disabled={disabled} itemHeight={itemHeight} /> </div> ) } renderGroupHeader(group, style) { var renderGroup = this.props.renderGroup return ( <ListOptionGroup style={style}> {renderGroup({ group })} </ListOptionGroup> ) } move() { let { dataState, focusedItem } = this.props; let scrollable = this.refs.scrollable let idx = dataState.flatData.indexOf(focusedItem); if (idx === -1) return scrollable.scrollAround(idx); } } export default VirtualList;
{ if (error) throw error; var stratify = d3_hierarchy.stratify().parentId(function(d) { var i = d.id.lastIndexOf("."); return i >= 0 ? d.id.slice(0, i) : null; }); var pack = d3_hierarchy.pack().size([960, 960]); var data = d3_dsv.csvParse(inputText), expected = JSON.parse(expectedText), actual = pack( stratify(data) .sum(function(d) { return d.value; }) .sort(function(a, b) { return b.value - a.value || a.data.id.localeCompare(b.data.id); }) ); (function visit(node) { node.name = node.data.id.slice(node.data.id.lastIndexOf(".") + 1); node.x = round(node.x); node.y = round(node.y); node.r = round(node.r); delete node.id; delete node.parent; delete node.data; delete node.depth; delete node.height; if (node.children) node.children.forEach(visit); })(actual); (function visit(node) { node.x = round(node.x); node.y = round(node.y); node.r = round(node.r); if (node.children) node.children.forEach(visit); })(expected); test.deepEqual(actual, expected); test.end(); }
version https://git-lfs.github.com/spec/v1 oid sha256:44d22c376185a41b923a54a5deb87a173bd8952051f41408eb5b9381368dc463 size 4700
/* * grunt-jenkins-build-number * https://github.com/Ideame/grunt-jenkins-build-number * * Copyright (c) 2013 Ideame */ module.exports = function (grunt) { var util = require('util'); grunt.registerMultiTask("jenkinsBuildNumber", "Retrieves the latest build number/state from Jenkins.", function () { var http = require('http'); var done = this.async(); var options = this.options({ state: 'lastBuild', path: '' }); var url = { host: options.hostname, port: options.port || 80, path: util.format('%s/job/%s/%s/buildNumber', options.path, options.projectName, options.state) }; if (options.username && options.password) { url.auth = util.format('%s:%s', options.username, options.password); } http.get(url, function (res) { if (res.statusCode !== 200) { return done(new Error('Could not get latest successful build version, statusCode:' + res.statusCode)); } grunt.verbose.writeln('GET %s:%s%s', url.host, url.port, url.path); var body = ''; res.on('data', function (chunk) { body += chunk; }); res.on('end', function () { grunt.verbose.writeln('%s is: %s', options.state, body); grunt.config.set(options.state, body); done(); }); }).on('error', function (err) { done(err); }); }); };
import React, {Component, PropTypes} from 'react'; import ArcGauge from './ArcGauge'; export default class Gauge extends Component { static propTypes = { label: PropTypes.string.isRequired, value: PropTypes.number.isRequired, units: PropTypes.string, topLabel: PropTypes.bool }; static style = { container: { position: 'relative', minWidth: 100, maxWidth: 200, minHeight: 100, border: '1px solid black', borderRadius: 4, boxShadow: '2px 2px 3px #383838', padding: '5px 5px', margin: 0, backgroundColor: '#484848', color: '#eee', textAlign: 'center', lineHeight: 1, fontFamily: 'sans-serif' }, value: { fontSize: '3em', margin: 0, overflow: 'hidden' }, units: { textAlign: 'right', marginTop: -5 }, label: { fontSize: '1.75em', width: '100%', maxWidth: 200, textAlign: 'center', marginTop: 15 }, button: { position: 'absolute', bottom: 5, right: 5, cursor: 'pointer' } }; constructor(props) { super(props); this.state = {reverse: false, width: 212}; } componentDidMount() { this.setState({width: React.findDOMNode(this).offsetWidth}); } componentWillReceiveProps(nextProps) { let history = this.state.history || new Array(100).fill(0); if(history.length > 100) history.shift(); history.push(nextProps.value); this.setState({ history: history, width: React.findDOMNode(this).offsetWidth }); } handleClick() { if(this.state && this.state.reverse) { this.setState({reverse: false}); } else { this.setState({reverse: true}); } } renderObverse() { return ( <div> <ArcGauge value={this.props.value} width={this.state.width-12} strokeWidth={20} /> <div style={Gauge.style.label}>{this.props.label}</div> </div> ); } renderReverse() { return <h1>Reverse</h1>; } render() { const {reverse} = this.state; const {style} = Gauge; return ( <div style={style.container}> {!reverse && this.renderObverse()} {reverse && this.renderReverse()} <span style={style.button} onClick={()=>this.handleClick()}> <i className='fa fa-cog'></i> </span> </div> ); } }
module.exports = function(config){ config.set({ basePath : './', files : [ 'web/static/bower_components/angular/angular.min.js', 'web/static/compiled/scripts/**/*.js', 'test/**/*.js' ], autoWatch : true, frameworks: ['jasmine'], browsers : ['Chrome'], plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
import 'core-js/stable'; import chai from 'chai'; import chaiAsPromised from 'chai-as-promised'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; process.on('unhandledRejection', (err) => { /* eslint no-console: 0 */ console.error(err, err.stack); }); chai.should(); chai.use(chaiAsPromised); chai.use(sinonChai); global.sinon = sinon; global.chaiAsPromised = chaiAsPromised; global.expect = chai.expect; global.AssertionError = chai.AssertionError; global.Assertion = chai.Assertion; global.assert = chai.assert;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.messages = exports.ruleName = undefined; exports.default = function (actual) { return function (root, result) { var validOptions = (0, _utils.validateOptions)(result, ruleName, { actual: actual }); if (!validOptions) { return; } root.walkRules(function (rule) { if (!(0, _utils.isStandardRule)(rule)) { return; } var selector = rule.selector; if (!(0, _utils.isStandardSelector)(selector)) { return; } (0, _postcssSelectorParser2.default)(function (selectorAST) { selectorAST.walkCombinators(function (combinator) { (0, _utils.report)({ message: messages.rejected, node: rule, index: combinator.sourceIndex, ruleName: ruleName, result: result }); }); }).process(selector); }); }; }; var _postcssSelectorParser = require("postcss-selector-parser"); var _postcssSelectorParser2 = _interopRequireDefault(_postcssSelectorParser); var _utils = require("../../utils"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ruleName = exports.ruleName = "selector-no-combinator"; var messages = exports.messages = (0, _utils.ruleMessages)(ruleName, { rejected: "Unexpected combinator" });
require(["gitbook", "jquery"], function (gitbook, $) { var matcher = /\/\/jsfiddle.net\/.+/; var defaults = { type: 'script', tabs: ['js', 'html', 'css', 'result'], theme: 'light' }; var localConfig = { jsfiddle: {} }; var extractConfigFromURL = function (href) { var match = /(#)(.+)$/ig.exec(href); if (match && match[2]) { return match[2].split('&').reduce(function (params, param) { var splitParam = param.split('='); if (splitParam[0] === 'tabs') { splitParam[1] = splitParam[1].split(','); } params[splitParam[0]] = splitParam[1]; return params; }, {}); } return {}; }; var generateAdditionalParams = function (config) { var params = '/'; if (config.theme) { params += config.theme + '/'; } var colors = Object.keys(config).reduce(function (colors, key) { if (['href', 'type', 'theme', 'tabs', 'width', 'height'].indexOf(key) !== -1) { return colors; } colors += key + '=' + config[key] + '&'; return colors; }, ''); colors = colors.replace(/&$/, ''); if (colors) { return params + '?' + colors; } return params; }; var generateUrl = function (config) { var additionalParam = generateAdditionalParams(config); var type = config.type == 'frame' ? 'embedded' : 'embed'; return config.href + type + '/' + config.tabs.join(',') + additionalParam; }; var creator = { script: function (config) { var script = document.createElement('script'); script.src = generateUrl(config); script.async = true; return script; }, frame: function (config) { return $([ '<iframe', ' width=', '"' + (config.width ? config.width : '100%') + '"', ' height=', '"' + (config.height ? config.height : '300') + '"', ' src="' + generateUrl(config) + '"', ' allowfullscreen="allowfullscreen" frameborder="0"', '>', '</iframe>' ].join(''))[0]; } }; var createEmbedNode = function (href, config) { var normalURL = href.replace(/#.+$/, ''); var configFromUrl = extractConfigFromURL(href); var mergedConfig = $.extend({href: normalURL}, config, configFromUrl); return creator[mergedConfig.type](mergedConfig); }; function embedAllLink(config) { localConfig.jsfiddle = $.extend(localConfig.jsfiddle || {}, config.jsfiddle); $(".book-body a").each(function (index, link) { if (link.href && matcher.test(link.href)) { link.parentNode.insertBefore(createEmbedNode(link.href, localConfig.jsfiddle), link.nextSibling); link.parentNode.removeChild(link); } }); } gitbook.events.bind("start", function (e, config) { localConfig.jsfiddle = $.extend({}, defaults); matcher = /(http|https):\/\/jsfiddle.net\/.+/; embedAllLink(config); }); gitbook.events.bind("page.change", function () { if (matcher) { embedAllLink(localConfig); } }); });
import React from 'react'; import ReactDOM from 'react-dom'; import { createStore} from 'redux'; import { Provider } from 'react-redux'; import App from './components/App.jsx'; import Reducers from './reducers/index'; const store = createStore(Reducers); ReactDOM.render(( <Provider store={store}> <App /> </Provider> ), document.getElementById('root'));
(function(){ angular.module('myApp', ['ngMessages','ngResource','ccLogoFilter']); })();
const CUSTOM_LOG_LOAD = 'crm/log/CUSTOM_LOG_LOAD'; const CUSTOM_LOG_SUCCESS = 'crm/log/CUSTOM_LOG_SUCCESS'; const CUSTOM_LOG_FAIL = 'crm/log/CUSTOM_LOG_FAIL'; const initial = { }; export default function reducer(state = initial, action = {}) { switch (action.type) { case CUSTOM_LOG_LOAD: return { ...state, isFetchingCustomLog: true }; case CUSTOM_LOG_SUCCESS: return { ...state, isFetchingCustomLog: false, customLog: action.result.data }; case CUSTOM_LOG_FAIL: return { ...state, isFetchingCustomLog: false, customLogLoadError: action.error }; default: return state; } } // 操作日志 export function getCustomLog(tenantId) { return { types: [CUSTOM_LOG_LOAD, CUSTOM_LOG_SUCCESS, CUSTOM_LOG_FAIL], promise: client => client.post('/customer/detail_queryTenantOperLogList.action', {data: {tenantId}}) }; }
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.8/esri/copyright.txt for details. //>>built define({widgetLabel:"Druk\u0101t",title:"Nosaukums",fileName:"Faila nosaukums",titlePlaceHolder:"Faila virsraksts",fileNamePlaceHolder:"Faila nosaukums",formatDefaultOption:"Atlas\u012bt form\u0101tu",fileFormatTitle:"Faila form\u0101ts:",layoutTitle:"Lapas iestat\u012bjumi",layoutDefaultOption:"Atlas\u012bt lapas iestat\u012bjumus",scale:"Iestat\u012bt m\u0113rogu",scaleLabel:"m\u0113rogs",reset:"atiestat\u012bt",author:"Autors",copyright:"Autorties\u012bbas",legend:"Iek\u013caut apz\u012bm\u0113jumus", lock:"aizsl\u0113gt",swap:"p\u0101rnese",panelToggle:"Pane\u013ca p\u0101rsl\u0113g\u0161ana",advancedOptions:"Papildu izv\u0113lnes",width:"Platums",height:"Augstums",dpi:"DPI",attribution:"Iek\u013caut attiecin\u0101jumu",layoutTab:"Izk\u0101rtojums",mapOnlyTab:"Tikai karte",untitled:"bez nosaukuma",pending:"Eksport\u0113\u0161ana",ready:"Atv\u0113rt \u0161o",linkReady:"Atveriet jaun\u0101 log\u0101.",error:"Izv\u0113lieties \u0161o vien\u012bbu, lai to no\u0146emtu.",sceneViewError:"Skat\u0101 SceneView druk\u0101\u0161ana netiek atbalst\u012bta.", serviceError:"\u0160\u0137iet, ka ir radusies k\u013c\u016bda.","export":"Eksport\u0113t",exportDescription:"Eksport\u0113\u0161ana. Eksport\u0113tie faili tiks r\u0101d\u012bti zem\u0101k.",exportText:"Eksport\u0113tie faili",exportHint:"Eksport\u0113tie faili tiks r\u0101d\u012bti \u0161eit.","a3-landscape":"\u0137_A3 Landscape_____\u016b","a3-portrait":"\u0137_A3 Portrait____\u016b","a4-landscape":"\u0137_A4 Landscape_____\u016b","a4-portrait":"\u0137_A4 Portrait____\u016b","letter-ansi-a-landscape":"\u0137_Letter ANSI A Landscape________\u016b", "letter-ansi-a-portrait":"\u0137_Letter ANSI A Portrait________\u016b","tabloid-ansi-b-landscape":"\u0137_Tabloid ANSI B Landscape________\u016b","tabloid-ansi-b-portrait":"\u0137_Tabloid ANSI B Portrait________\u016b"});
import {HttpClient} from '../scripts/aurelia-http-client.js'; export class App { constructor() { console.log('constructing app...'); this.heading = "Voz da gente"; this.phrase = ''; this.userPhrase = ''; this.foundWords = ''; this.listOfForvoObjs = []; this.langList = []; this.selectedLang = 'pt'; // Set default lang in dropdown. this.filterableCountries = []; this.userImages = null; this.isFetchRecordingsEnabled = true; // Enable/disable buttons if the external api's are config'd correctly. this.isExternalServiceEnabled('forvo') .then(data => { this.isForvoEnabled = JSON.parse(data.response).isEnabled; }); this.isGoogleVisionEnabled = false; this.getLangList(); } /* * Return set of countries from a list of forvoObjs */ getCountryListFromForvoObj(forvoObjs, currentListOfCountries) { // Find the forvo objects that have properties, which are the only ones // we could get countries from. var forvoObjsWithCountries = forvoObjs.filter(function(forvoObjToFilter) { return forvoObjToFilter.props && (forvoObjToFilter.props.length > 0); }); // Collect the countries from the forvo objects. var returnList = forvoObjsWithCountries.map( function (forvoObj) { return forvoObj.props; }).reduce(function(a, b) { return a.concat(b); }, []).map( function(forvoProp) { return forvoProp.country; }); // Sort the return list, making it easy to use in the drop down. returnList.sort( function (country1, country2) { return country1.localeCompare(country2); }); // Set ensures we only have 1 of each country. return new Set([...returnList, ...currentListOfCountries]); } /* * Make a request to parse the entered phrase for the selected language. */ getForvos() { if (this.phrase && this.selectedLang) { let client = new HttpClient(); client.get('http://localhost:3000/voz/api/phrase?phrase=' + encodeURI(this.phrase) + '&lang=' + this.selectedLang + '&isFetchRecordingsEnabled=' + this.isFetchRecordingsEnabled) .then(data => { this.listOfForvoObjs = JSON.parse(data.response); // Let the user filter by the countries found for the words returned. this.filterableCountries = this.getCountryListFromForvoObj(this.listOfForvoObjs, this.filterableCountries); }); this.userPhrase = this.phrase; this.phrase = ''; } } /* * The list of languages a user can use to process their language. */ getLangList() { let client = new HttpClient(); client.get('http://localhost:3000/voz/api/langs') .then(data => { this.langList = JSON.parse(data.response).langs; this.langList.sort( function (lang1, lang2) { return lang1.langName.localeCompare(lang2.langName); }); }); } /* * Get the properties for a single word. */ getPropsForWord(forvoObj) { var word = forvoObj.word; if (word && this.selectedLang) { let client = new HttpClient(); client.get('http://localhost:3000/voz/api/word?word=' + encodeURI(word) + '&lang=' + this.selectedLang) .then(data => { var forvoObjectResponse = JSON.parse(data.response)[0]; forvoObj.props = forvoObjectResponse.props; // Let the user filter by the countries found for the words returned. this.filterableCountries = this.getCountryListFromForvoObj(this.listOfForvoObjs, this.filterableCountries); }); } } /* * Let the user get a sample phrase for a quick demo of what the app will do. */ getSamplePhrase() { let client = new HttpClient(); client.get('http://localhost:3000/voz/api/samplePhrase') .then(data => { this.phrase = JSON.parse(data.response).phrase; this.selectedLang = JSON.parse(data.response).lang; }); } /* * Let user upload image to process its text into something we can hit Forvo with. */ getTextFromImage() { if (this.userImages) { // Possible solution to this problem // http://stackoverflow.com/questions/34495796/javascript-promises-with-filereader this.makeFileRequest('http://localhost:3000/voz/api/imageText', this.userImages[0]) .then( (result) => { console.log("returned a result!!!"); this.phrase = result;}, (error) => { console.log("nooooo everything's broken and the sky's falliiiiiing!!1!!"); }); } } /* * Check if features provided by external services are enabled. */ isExternalServiceEnabled(serviceToCheck) { let client = new HttpClient(); return client.get('http://localhost:3000/voz/api/external/' + serviceToCheck + '/isEnabled'); } /* * Helper functions for app. */ /* * Send a single file to the specified url. */ makeFileRequest(url, fileToUpload) { var arrayBufferToBase64Func = this.arrayBufferToBase64; return new Promise((resolve, reject) => { var imgArrBuff; var fileReader = new FileReader(); let client = new HttpClient(); fileReader.onload = function () { // Read in file imgArrBuff = fileReader.result; // Convert to base64 string for Google Vision. var base64String = arrayBufferToBase64Func(imgArrBuff); // Request to get text from image. client.post(url, {'userImage' : base64String}) .then(data => { var phrase = JSON.parse(data.response).text; console.log('phrase is...'); console.log(phrase.substring(0,100)); resolve(phrase); }).catch(function() { console.log("Messed up in the file upload... :( "); reject("Messed up in the file upload... :( "); }); }; fileReader.readAsArrayBuffer(fileToUpload); }); } /* * Encode an array buffer as base 64 string. * http://stackoverflow.com/questions/9267899/arraybuffer-to-base64-encoded-string */ arrayBufferToBase64( buffer ) { var binary = ''; var bytes = new Uint8Array( buffer ); var len = bytes.byteLength; for (var i = 0; i < len; i++) { binary += String.fromCharCode( bytes[ i ] ); } return window.btoa( binary ); } }
function cargar_Perfil() { $.post( base_url + "Controllerperfil/cargar_Perfil", {}, function(ruta, datos) { $("#content").hide(); $("#content").html(ruta, datos); $("#content").show('slow'); } ); //cargar contenido pagina var accion = "Datos"; var modulo = "Perfil"; var icono = "glyphicon glyphicon-refresh"; cargar_contenidoPaginaXusuario(modulo,accion,icono); }
(function() { 'use strict'; // the `highest` controller the app angular.module('magicsquares').controller('Navigation', ['$scope', '$state', '$ionicSideMenuDelegate', '$ionicHistory', function($scope, $state,$ionicSideMenuDelegate, $ionicHistory) { console.log('hi from Navigation!'); // wasn't able to use the history so using a `hard-coded` reference this.goBack = function() { $state.go('tabs.game'); }; // navigate to the game this.goGame = function() { $state.go('game'); }; }]); }());
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var weather_variable_fullmoon = exports.weather_variable_fullmoon = { "viewBox": "0 0 64 64", "children": [{ "name": "path", "attribs": { "fill": "none", "stroke": "#000000", "stroke-width": "2", "stroke-miterlimit": "10", "d": "M56,50c4.19,0,7-2.81,7-7c0-4.189-2.81-9-7-9\r\n\tc0-10.475-9.525-18-20-18c-9.271,0-17.348,6.211-19,15c0,0-1.232,0-2,0c-5.238,0-9,4.762-9,10s3.762,9,9,9H56z" }, "children": [] }, { "name": "path", "attribs": { "fill": "none", "stroke": "#000000", "stroke-width": "2", "stroke-miterlimit": "10", "d": "M7.004,37.959c-1.59-1.017-2.943-2.37-3.961-3.96\r\n\tC1.75,31.979,1,29.577,1,27c0-7.18,5.82-13,13-13c4.604,0,8.646,2.392,10.957,6.001" }, "children": [] }] };
var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); var crypto = require('crypto'); var userSchema = new mongoose.Schema({ email: { type: String, unique: true, lowercase: true }, name: { type: String, default: '' }, playing: { type: Boolean, default: false }, password: String, tokens: Array, profile: { gender: { type: String, default: '' }, location: { type: String, default: '' }, website: { type: String, default: '' }, picture: { type: String, default: '' } }, resetPasswordToken: String, resetPasswordExpires: Date }); /** * Hash the password for security. * "Pre" is a Mongoose middleware that executes before each user.save() call. */ userSchema.pre('save', function (next) { var user = this; if (!user.isModified('password')) return next(); bcrypt.genSalt(5, function (err, salt) { if (err) return next(err); bcrypt.hash(user.password, salt, null, function (err, hash) { if (err) return next(err); user.password = hash; next(); }); }); }); /** * Validate user's password. * Used by Passport-Local Strategy for password validation. */ userSchema.methods.comparePassword = function (candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function (err, isMatch) { if (err) return cb(err); cb(null, isMatch); }); }; /** * Get URL to a user's gravatar. * Used in Navbar and Account Management page. */ userSchema.methods.gravatar = function (size) { if (!size) size = 200; if (!this.email) { return 'https://gravatar.com/avatar/?s=' + size + '&d=retro'; } var md5 = crypto.createHash('md5').update(this.email).digest('hex'); return 'https://gravatar.com/avatar/' + md5 + '?s=' + size + '&d=retro'; }; module.exports = mongoose.model('User', userSchema);
var gulp = require('gulp'), ejs = require('gulp-ejs'), concat = require('gulp-concat'), jsdoc = require('gulp-jsdoc'), jsdoc2md = require('jsdoc-to-markdown'), fs = require('fs'), path = require('path'), clean = require('del'), pkgInfo = require('./package.json'), CLOBBER = []; gulp.task('clobber', function (done) { clean(CLOBBER, done); }); gulp.task('api.md', function () { return jsdoc2md. render('lib/**/*.js'). pipe(fs.createWriteStream('API.md')); }); CLOBBER.push('API.md'); gulp.task('readme.md', function () { var dir = 'src/tmpl'; return gulp. src([ 'HEADER.ejs', 'SUMMARY.ejs', 'INSTALLATION.ejs', 'DOCUMENTATION.ejs', 'DEPENDENCIES.ejs', 'ISSUES.ejs', 'LICENSE.ejs' ].map(function (file) { return path.join(dir, file); })). pipe(ejs({ pkg: pkgInfo, license: fs.readFileSync('LICENSE', 'utf8'), links: { apiDoc: 'API.md' } })). pipe(concat('README.md')). pipe(gulp.dest('./')); }); CLOBBER.push('README.md'); gulp.task('docs', ['readme.md'], function () { return gulp. src(['./lib/**/*.js', 'README.md']). pipe(jsdoc( path.join('docs', pkgInfo.version), { path: 'ink-docstrap', systemName: pkgInfo.fullname, footer: '', copyright: 'Copyright © 2014 Jerry Hamlet', navType: 'vertical', theme: 'spacelab', linenums: true, collapseSymbols: true, inverseNav: true, outputSourceFiles: true, outputSourcePath: true, highlightTutorialCode: true, syntaxTheme: 'dark' }, { licenses: [ fs.readFileSync('./LICENSE', 'utf8') ], version: pkgInfo.version }, { recurse: true, lenient: true, 'private': true } )); }); CLOBBER.push('docs/**/*'); CLOBBER.push('docs'); gulp.task('default', ['readme.md', 'api.md', 'docs']);
module.exports = { conditions: [''], name: 'BitwiseXORExpression_In', rules: [ 'BitwiseANDExpression_In', 'BitwiseXORExpression_In ^ BitwiseANDExpression_In', ], handlers: [ '$$ = $1;', '$$ = new (require(\'./ast/BitwiseExpression\').BitwiseXORExpressionNode)($2, $1, $3, { loc: this._$, yy })', ], subRules: [ require('./BitwiseANDExpression_In'), ], };
module.exports = { 'v-tabs': { events: [ { name: 'change', value: 'number', }, ], }, }
/** * @typedef {import('unist').Node} Node */ import fs from 'node:fs' import path from 'node:path' import test from 'tape' import {unified} from 'unified' import retextEnglish from 'retext-english' import {emojiModifier} from 'nlcst-emoji-modifier' import {emoticonModifier} from 'nlcst-emoticon-modifier' import {removePosition} from 'unist-util-remove-position' import {affixEmoticonModifier} from '../index.js' /** @type {Node} */ const lollipop = JSON.parse( String(fs.readFileSync(path.join('test', 'fixtures', 'lollipop.json'))) ) /** @type {Node} */ const smile = JSON.parse( String(fs.readFileSync(path.join('test', 'fixtures', 'smile.json'))) ) test('affixEmoticonModifier()', (t) => { t.throws( () => { // @ts-expect-error runtime. affixEmoticonModifier({}) }, /Missing children in `parent`/, 'should throw when not given a parent' ) t.deepEqual( process('Lol! :lollipop: That’s cool.'), lollipop, 'should merge at sentence-start (1)' ) t.deepEqual( process('Lol! :lollipop: That’s cool.', true), removePosition(lollipop, true), 'should merge at sentence-start (1, positionless)' ) t.deepEqual( process('Lol! :) That’s cool.'), smile, 'should merge at sentence-start (2)' ) t.deepEqual( process('Lol! :) That’s cool.', true), removePosition(smile, true), 'should merge at sentence-start (2, positionless)' ) t.end() }) /** * Shortcut to access the CST. * * @param {string} fixture * @param {boolean} [positionless=false] */ function process(fixture, positionless) { const processor = unified().use(retextEnglish).use(plugin).freeze() if (positionless && processor.Parser) { // Fine. // type-coverage:ignore-next-line processor.Parser.prototype.position = false } return processor.runSync(processor.parse(fixture)) } /** * Add modifier to processor. * * @type {import('unified').Plugin<[]>} */ function plugin() { if (this.Parser) { // Fine. // type-coverage:ignore-next-line this.Parser.prototype.useFirst('tokenizeSentence', emojiModifier) // Fine. // type-coverage:ignore-next-line this.Parser.prototype.useFirst('tokenizeSentence', emoticonModifier) // Fine. // type-coverage:ignore-next-line this.Parser.prototype.useFirst('tokenizeParagraph', affixEmoticonModifier) } }
// This file is generated automatically by `scripts/build/fp.js`. Please, don't change it. import fn from '../../subMilliseconds/index.js' import convertToFP from '../_lib/convertToFP/index.js' var subMillisecondsWithOptions = convertToFP(fn, 3) export default subMillisecondsWithOptions
var should = require("should"); var ConcatSource = require("../lib/ConcatSource"); var RawSource = require("../lib/RawSource"); var OriginalSource = require("../lib/OriginalSource"); describe("ConcatSource", function() { it("should concat two sources", function() { var source = new ConcatSource( new RawSource("Hello World\n"), new OriginalSource("console.log('test');\nconsole.log('test2');\n", "console.js") ); source.add(new OriginalSource("Hello2\n", "hello.md")); var expectedMap1 = { version: 3, file: "x", mappings: ";AAAA;AACA;ACDA;", sources: [ "console.js", "hello.md" ], sourcesContent: [ "console.log('test');\nconsole.log('test2');\n", "Hello2\n" ] }; var expectedSource = [ "Hello World", "console.log('test');", "console.log('test2');", "Hello2", "" ].join("\n"); source.size().should.be.eql(62); source.source().should.be.eql(expectedSource); source.map({ columns: false }).should.be.eql(expectedMap1); source.sourceAndMap({ columns: false }).should.be.eql({ source: expectedSource, map: expectedMap1 }); var expectedMap2 = { version: 3, file: "x", mappings: ";AAAA;AACA;ACDA", names: [], sources: [ "console.js", "hello.md" ], sourcesContent: [ "console.log('test');\nconsole.log('test2');\n", "Hello2\n" ] }; source.map().should.be.eql(expectedMap2); source.sourceAndMap().should.be.eql({ source: expectedSource, map: expectedMap2 }); }); });
/* global exports */ "use strict"; // module Leaflet.Map exports.createMap = function(i) { return function(o) { return function() { return L.map(i,o); } } }
const fs = require('fs'); console.log('시작'); let data = fs.readFileSync('./readme2.txt'); console.log('1번 ', data.toString()); data = fs.readFileSync('./readme2.txt'); console.log('2번 ', data.toString()); data = fs.readFileSync('./readme2.txt'); console.log('3번 ', data.toString()); console.log("끝");
console.clear() console.log('Hola Mundo desde la Consola :)') var nombre = 'Jonathan' console.log('Hola Mundo desde la Consola :) te saluda %s', nombre) var anio = 2016 console.log('Hola Mundo desde la Consola :) te saluda %s, que tengas un excelente año %d', nombre, anio) console.error('Error Configurado por el usuario') var cursos = document.querySelector('.course-list') console.log(cursos) console.dir(cursos) console.clear() console.log(window) console.dir(window) console.clear() console.log(Date()) console.dir(Date()) console.clear() console.group('Cursos Bextlán') console.log('Node.js') console.log('jQuery') console.log('WordPress') console.log('Responsive Design') console.log('Diseño y Programación Web') console.groupEnd() console.groupCollapsed('Tutoriales Bextlán') console.log('JavaScript') console.log('HTML5') console.log('PHP') console.log('AS3') console.log('Vlog de MirCha') console.groupEnd() console.clear() var bextlan = { "Cursos":['Node.js','jQuery','WordPress','Responsive Design','Diseño y Programacion Web'], "Tutoriales":['JavaScript','HTML5','PHP','AS3','Vlog de MirCha'] } console.table(bextlan) function Cursos(nombre, url, tipo){ this.nombre = nombre this.url = url this.tipo = tipo } var node = new Cursos('Node.js', 'http://bextlan.com/cursos/nodejs','curso') var js = new Cursos('JavaScript', 'http://bextlan.com/tutoriales/javascript','tutorial') console.table(node) console.table(js) console.clear() console.time('Cuanto tiempo tarda mi código') var arreglo = new Array(1000000) for(var i = arreglo.length - 1; i >= 0; i--) { arreglo[i] = new Object() } console.timeEnd('Cuanto tiempo tarda mi código')
(function() { 'use strict'; angular.module('user', [ 'ngStorage' ]) .config(function($authProvider) { $authProvider.google({ clientId: '' }); $authProvider.facebook({ clientId: '' }); $authProvider.github({ clientId: '' }); $authProvider.twitter({ clientId: '' }); }); })();
/** * @license * v1.3.8 * MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE) * Copyright (c) 2019 Microsoft * docs: https://pnp.github.io/pnpjs/ * source: https://github.com/pnp/pnpjs * bugs: https://github.com/pnp/pnpjs/issues */ import { RuntimeConfig, dateAdd, PnPClientStorage, isFunc, hOP, extend, combine, mergeOptions, objectDefinedNotNull, isArray, getGUID } from '@pnp/common'; import { Logger } from '@pnp/logging'; var CachingOptions = /** @class */ (function () { function CachingOptions(key) { this.key = key; this.expiration = dateAdd(new Date(), "second", RuntimeConfig.defaultCachingTimeoutSeconds); this.storeName = RuntimeConfig.defaultCachingStore; } Object.defineProperty(CachingOptions.prototype, "store", { get: function () { if (this.storeName === "local") { return CachingOptions.storage.local; } else { return CachingOptions.storage.session; } }, enumerable: true, configurable: true }); CachingOptions.storage = new PnPClientStorage(); return CachingOptions; }()); var CachingParserWrapper = /** @class */ (function () { function CachingParserWrapper(parser, cacheOptions) { this.parser = parser; this.cacheOptions = cacheOptions; } CachingParserWrapper.prototype.parse = function (response) { var _this = this; return this.parser.parse(response).then(function (r) { return _this.cacheData(r); }); }; CachingParserWrapper.prototype.cacheData = function (data) { if (this.cacheOptions.store !== null) { this.cacheOptions.store.put(this.cacheOptions.key, data, this.cacheOptions.expiration); } return data; }; return CachingParserWrapper; }()); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } var HttpRequestError = /** @class */ (function (_super) { __extends(HttpRequestError, _super); function HttpRequestError(message, response, status, statusText) { if (status === void 0) { status = response.status; } if (statusText === void 0) { statusText = response.statusText; } var _this = _super.call(this, message) || this; _this.response = response; _this.status = status; _this.statusText = statusText; _this.isHttpRequestError = true; return _this; } HttpRequestError.init = function (r) { return r.clone().text().then(function (t) { return new HttpRequestError("Error making HttpClient request in queryable [" + r.status + "] " + r.statusText + " ::> " + t, r.clone()); }); }; return HttpRequestError; }(Error)); var ODataParserBase = /** @class */ (function () { function ODataParserBase() { this.rawJson = {}; } ODataParserBase.prototype.parse = function (r) { var _this = this; return new Promise(function (resolve, reject) { if (_this.handleError(r, reject)) { _this.parseImpl(r, resolve, reject); } }); }; ODataParserBase.prototype.parseImpl = function (r, resolve, reject) { var _this = this; if ((r.headers.has("Content-Length") && parseFloat(r.headers.get("Content-Length")) === 0) || r.status === 204) { resolve({}); } else { // patch to handle cases of 200 response with no or whitespace only bodies (#487 & #545) r.text() .then(function (txt) { return txt.replace(/\s/ig, "").length > 0 ? JSON.parse(txt) : {}; }) .then(function (json) { return resolve(_this.parseODataJSON(json)); }) .catch(function (e) { return reject(e); }); } }; /** * Handles a response with ok === false by parsing the body and creating a ProcessHttpClientResponseException * which is passed to the reject delegate. This method returns true if there is no error, otherwise false * * @param r Current response object * @param reject reject delegate for the surrounding promise */ ODataParserBase.prototype.handleError = function (r, reject) { if (!r.ok) { HttpRequestError.init(r).then(reject); } return r.ok; }; /** * Normalizes the json response by removing the various nested levels * * @param json json object to parse */ ODataParserBase.prototype.parseODataJSON = function (json) { this.rawJson = json; var result = json; if (hOP(json, "d")) { if (hOP(json.d, "results")) { result = json.d.results; } else { result = json.d; } } else if (hOP(json, "value")) { result = json.value; } return result; }; return ODataParserBase; }()); var ODataDefaultParser = /** @class */ (function (_super) { __extends(ODataDefaultParser, _super); function ODataDefaultParser() { return _super !== null && _super.apply(this, arguments) || this; } return ODataDefaultParser; }(ODataParserBase)); var TextParser = /** @class */ (function (_super) { __extends(TextParser, _super); function TextParser() { return _super !== null && _super.apply(this, arguments) || this; } TextParser.prototype.parseImpl = function (r, resolve) { r.text().then(resolve); }; return TextParser; }(ODataParserBase)); var BlobParser = /** @class */ (function (_super) { __extends(BlobParser, _super); function BlobParser() { return _super !== null && _super.apply(this, arguments) || this; } BlobParser.prototype.parseImpl = function (r, resolve) { r.blob().then(resolve); }; return BlobParser; }(ODataParserBase)); var JSONParser = /** @class */ (function (_super) { __extends(JSONParser, _super); function JSONParser() { return _super !== null && _super.apply(this, arguments) || this; } JSONParser.prototype.parseImpl = function (r, resolve) { r.json().then(resolve); }; return JSONParser; }(ODataParserBase)); var BufferParser = /** @class */ (function (_super) { __extends(BufferParser, _super); function BufferParser() { return _super !== null && _super.apply(this, arguments) || this; } BufferParser.prototype.parseImpl = function (r, resolve) { if (isFunc(r.arrayBuffer)) { r.arrayBuffer().then(resolve); } else { r.buffer().then(resolve); } }; return BufferParser; }(ODataParserBase)); var LambdaParser = /** @class */ (function (_super) { __extends(LambdaParser, _super); function LambdaParser(parser) { var _this = _super.call(this) || this; _this.parser = parser; return _this; } LambdaParser.prototype.parseImpl = function (r, resolve) { this.parser(r).then(resolve); }; return LambdaParser; }(ODataParserBase)); /** * Resolves the context's result value * * @param context The current context */ function returnResult(context) { Logger.log({ data: Logger.activeLogLevel === 0 /* Verbose */ ? context.result : {}, level: 1 /* Info */, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Returning result from pipeline. Set logging to verbose to see data.", }); return Promise.resolve(context.result); } /** * Sets the result on the context */ function setResult(context, value) { return new Promise(function (resolve) { context.result = value; context.hasResult = true; resolve(context); }); } /** * Invokes the next method in the provided context's pipeline * * @param c The current request context */ function next(c) { if (c.pipeline.length > 0) { return c.pipeline.shift()(c); } else { return Promise.resolve(c); } } /** * Executes the current request context's pipeline * * @param context Current context */ function pipe(context) { if (context.pipeline.length < 1) { Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Request pipeline contains no methods!", 2 /* Warning */); } var promise = next(context).then(function (ctx) { return returnResult(ctx); }).catch(function (e) { Logger.error(e); throw e; }); if (context.isBatched) { // this will block the batch's execute method from returning until the child requets have been resolved context.batch.addResolveBatchDependency(promise); } return promise; } /** * decorator factory applied to methods in the pipeline to control behavior */ function requestPipelineMethod(alwaysRun) { if (alwaysRun === void 0) { alwaysRun = false; } return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } // if we have a result already in the pipeline, pass it along and don't call the tagged method if (!alwaysRun && args.length > 0 && hOP(args[0], "hasResult") && args[0].hasResult) { Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Skipping request pipeline method " + propertyKey + ", existing result in pipeline.", 0 /* Verbose */); return Promise.resolve(args[0]); } // apply the tagged method Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Calling request pipeline method " + propertyKey + ".", 0 /* Verbose */); // then chain the next method in the context's pipeline - allows for dynamic pipeline return method.apply(target, args).then(function (ctx) { return next(ctx); }); }; }; } /** * Contains the methods used within the request pipeline */ var PipelineMethods = /** @class */ (function () { function PipelineMethods() { } /** * Logs the start of the request */ PipelineMethods.logStart = function (context) { return new Promise(function (resolve) { Logger.log({ data: Logger.activeLogLevel === 1 /* Info */ ? {} : context, level: 1 /* Info */, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Beginning " + context.verb + " request (" + context.requestAbsoluteUrl + ")", }); resolve(context); }); }; /** * Handles caching of the request */ PipelineMethods.caching = function (context) { return new Promise(function (resolve) { // handle caching, if applicable if (context.isCached) { Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Caching is enabled for request, checking cache...", 1 /* Info */); var cacheOptions = new CachingOptions(context.requestAbsoluteUrl.toLowerCase()); if (context.cachingOptions !== undefined) { cacheOptions = extend(cacheOptions, context.cachingOptions); } // we may not have a valid store if (cacheOptions.store !== null) { // check if we have the data in cache and if so resolve the promise and return var data = cacheOptions.store.get(cacheOptions.key); if (data !== null) { // ensure we clear any held batch dependency we are resolving from the cache Logger.log({ data: Logger.activeLogLevel === 1 /* Info */ ? {} : data, level: 1 /* Info */, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Value returned from cache.", }); if (isFunc(context.batchDependency)) { context.batchDependency(); } // handle the case where a parser needs to take special actions with a cached result if (hOP(context.parser, "hydrate")) { data = context.parser.hydrate(data); } return setResult(context, data).then(function (ctx) { return resolve(ctx); }); } } Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Value not found in cache.", 1 /* Info */); // if we don't then wrap the supplied parser in the caching parser wrapper // and send things on their way context.parser = new CachingParserWrapper(context.parser, cacheOptions); } return resolve(context); }); }; /** * Sends the request */ PipelineMethods.send = function (context) { return new Promise(function (resolve, reject) { // send or batch the request if (context.isBatched) { // we are in a batch, so add to batch, remove dependency, and resolve with the batch's promise var p = context.batch.add(context.requestAbsoluteUrl, context.verb, context.options, context.parser, context.requestId); // we release the dependency here to ensure the batch does not execute until the request is added to the batch if (isFunc(context.batchDependency)) { context.batchDependency(); } Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Batching request in batch " + context.batch.batchId + ".", 1 /* Info */); // we set the result as the promise which will be resolved by the batch's execution resolve(setResult(context, p)); } else { Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Sending request.", 1 /* Info */); // we are not part of a batch, so proceed as normal var client = context.clientFactory(); var opts = extend(context.options || {}, { method: context.verb }); client.fetch(context.requestAbsoluteUrl, opts) .then(function (response) { return context.parser.parse(response); }) .then(function (result) { return setResult(context, result); }) .then(function (ctx) { return resolve(ctx); }) .catch(function (e) { return reject(e); }); } }); }; /** * Logs the end of the request */ PipelineMethods.logEnd = function (context) { return new Promise(function (resolve) { if (context.isBatched) { Logger.log({ data: Logger.activeLogLevel === 1 /* Info */ ? {} : context, level: 1 /* Info */, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") " + context.verb + " request will complete in batch " + context.batch.batchId + ".", }); } else { Logger.log({ data: Logger.activeLogLevel === 1 /* Info */ ? {} : context, level: 1 /* Info */, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Completing " + context.verb + " request.", }); } resolve(context); }); }; __decorate([ requestPipelineMethod(true) ], PipelineMethods, "logStart", null); __decorate([ requestPipelineMethod() ], PipelineMethods, "caching", null); __decorate([ requestPipelineMethod() ], PipelineMethods, "send", null); __decorate([ requestPipelineMethod(true) ], PipelineMethods, "logEnd", null); return PipelineMethods; }()); function getDefaultPipeline() { return [ PipelineMethods.logStart, PipelineMethods.caching, PipelineMethods.send, PipelineMethods.logEnd, ].slice(0); } var Queryable = /** @class */ (function () { function Queryable() { this._query = new Map(); this._options = {}; this._url = ""; this._parentUrl = ""; this._useCaching = false; this._cachingOptions = null; this._cloneParentWasCaching = false; this._cloneParentCacheOptions = null; this._requestPipeline = null; } /** * Gets the currentl url * */ Queryable.prototype.toUrl = function () { return this._url; }; /** * Directly concatonates the supplied string to the current url, not normalizing "/" chars * * @param pathPart The string to concatonate to the url */ Queryable.prototype.concat = function (pathPart) { this._url += pathPart; return this; }; Object.defineProperty(Queryable.prototype, "query", { /** * Provides access to the query builder for this url * */ get: function () { return this._query; }, enumerable: true, configurable: true }); /** * Sets custom options for current object and all derived objects accessible via chaining * * @param options custom options */ Queryable.prototype.configure = function (options) { mergeOptions(this._options, options); return this; }; /** * Configures this instance from the configure options of the supplied instance * * @param o Instance from which options should be taken */ Queryable.prototype.configureFrom = function (o) { mergeOptions(this._options, o._options); return this; }; /** * Enables caching for this request * * @param options Defines the options used when caching this request */ Queryable.prototype.usingCaching = function (options) { if (!RuntimeConfig.globalCacheDisable) { this._useCaching = true; if (options !== undefined) { this._cachingOptions = options; } } return this; }; /** * Allows you to set a request specific processing pipeline * * @param pipeline The set of methods, in order, to execute a given request */ Queryable.prototype.withPipeline = function (pipeline) { this._requestPipeline = pipeline.slice(0); return this; }; Queryable.prototype.getCore = function (parser, options) { if (parser === void 0) { parser = new JSONParser(); } if (options === void 0) { options = {}; } // Fix for #304 - when we clone objects we in some cases then execute a get request // in these cases the caching settings were getting dropped from the request // this tracks if the object from which this was cloned was caching and applies that to an immediate get request // does not affect objects cloned from this as we are using different fields to track the settings so it won't // be triggered if (this._cloneParentWasCaching) { this.usingCaching(this._cloneParentCacheOptions); } return this.reqImpl("GET", options, parser); }; Queryable.prototype.postCore = function (options, parser) { if (options === void 0) { options = {}; } if (parser === void 0) { parser = new JSONParser(); } return this.reqImpl("POST", options, parser); }; Queryable.prototype.patchCore = function (options, parser) { if (options === void 0) { options = {}; } if (parser === void 0) { parser = new JSONParser(); } return this.reqImpl("PATCH", options, parser); }; Queryable.prototype.deleteCore = function (options, parser) { if (options === void 0) { options = {}; } if (parser === void 0) { parser = new JSONParser(); } return this.reqImpl("DELETE", options, parser); }; Queryable.prototype.putCore = function (options, parser) { if (options === void 0) { options = {}; } if (parser === void 0) { parser = new JSONParser(); } return this.reqImpl("PUT", options, parser); }; Queryable.prototype.reqImpl = function (method, options, parser) { var _this = this; if (options === void 0) { options = {}; } return this.getRequestPipeline(method, options, parser) .then(function (pipeline) { return _this.toRequestContext(method, options, parser, pipeline); }) .then(function (context) { return pipe(context); }); }; /** * Appends the given string and normalizes "/" chars * * @param pathPart The string to append */ Queryable.prototype.append = function (pathPart) { this._url = combine(this._url, pathPart); }; Object.defineProperty(Queryable.prototype, "parentUrl", { /** * Gets the parent url used when creating this instance * */ get: function () { return this._parentUrl; }, enumerable: true, configurable: true }); /** * Extends this queryable from the provided parent * * @param parent Parent queryable from which we will derive a base url * @param path Additional path */ Queryable.prototype.extend = function (parent, path) { this._parentUrl = parent._url; this._url = combine(this._parentUrl, path || ""); this.configureFrom(parent); }; /** * Configures a cloned object from this instance * * @param clone */ Queryable.prototype._clone = function (clone, _0) { clone.configureFrom(this); if (this._useCaching) { clone._cloneParentWasCaching = true; clone._cloneParentCacheOptions = this._cachingOptions; } return clone; }; /** * Handles getting the request pipeline to run for a given request */ // @ts-ignore // justified because we want to show that all these arguments are passed to the method so folks inheriting and potentially overriding // clearly see how the method is invoked inside the class Queryable.prototype.getRequestPipeline = function (method, options, parser) { var _this = this; if (options === void 0) { options = {}; } return new Promise(function (resolve) { if (objectDefinedNotNull(_this._requestPipeline) && isArray(_this._requestPipeline)) { resolve(_this._requestPipeline); } else { resolve(getDefaultPipeline()); } }); }; return Queryable; }()); var ODataQueryable = /** @class */ (function (_super) { __extends(ODataQueryable, _super); function ODataQueryable() { var _this = _super.call(this) || this; _this._batch = null; _this._batchDependency = null; return _this; } /** * Adds this query to the supplied batch * * @example * ``` * * let b = pnp.sp.createBatch(); * pnp.sp.web.inBatch(b).get().then(...); * b.execute().then(...) * ``` */ ODataQueryable.prototype.inBatch = function (batch) { if (this.batch !== null) { throw Error("This query is already part of a batch."); } if (objectDefinedNotNull(batch)) { this._batch = batch; } return this; }; /** * Gets the currentl url * */ ODataQueryable.prototype.toUrl = function () { return this._url; }; /** * Executes the currently built request * * @param parser Allows you to specify a parser to handle the result * @param getOptions The options used for this request */ ODataQueryable.prototype.get = function (parser, options) { if (parser === void 0) { parser = new ODataDefaultParser(); } if (options === void 0) { options = {}; } return this.getCore(parser, options); }; ODataQueryable.prototype.getCore = function (parser, options) { if (parser === void 0) { parser = new ODataDefaultParser(); } if (options === void 0) { options = {}; } return _super.prototype.getCore.call(this, parser, options); }; ODataQueryable.prototype.postCore = function (options, parser) { if (options === void 0) { options = {}; } if (parser === void 0) { parser = new ODataDefaultParser(); } return _super.prototype.postCore.call(this, options, parser); }; ODataQueryable.prototype.patchCore = function (options, parser) { if (options === void 0) { options = {}; } if (parser === void 0) { parser = new ODataDefaultParser(); } return _super.prototype.patchCore.call(this, options, parser); }; ODataQueryable.prototype.deleteCore = function (options, parser) { if (options === void 0) { options = {}; } if (parser === void 0) { parser = new ODataDefaultParser(); } return _super.prototype.deleteCore.call(this, options, parser); }; ODataQueryable.prototype.putCore = function (options, parser) { if (options === void 0) { options = {}; } if (parser === void 0) { parser = new ODataDefaultParser(); } return _super.prototype.putCore.call(this, options, parser); }; ODataQueryable.prototype.reqImpl = function (method, options, parser) { if (options === void 0) { options = {}; } if (this.hasBatch) { this._batchDependency = this.addBatchDependency(); } return _super.prototype.reqImpl.call(this, method, options, parser); }; /** * Blocks a batch call from occuring, MUST be cleared by calling the returned function */ ODataQueryable.prototype.addBatchDependency = function () { if (this._batch !== null) { return this._batch.addDependency(); } return function () { return null; }; }; Object.defineProperty(ODataQueryable.prototype, "hasBatch", { /** * Indicates if the current query has a batch associated * */ get: function () { return objectDefinedNotNull(this._batch); }, enumerable: true, configurable: true }); Object.defineProperty(ODataQueryable.prototype, "batch", { /** * The batch currently associated with this query or null * */ get: function () { return this.hasBatch ? this._batch : null; }, enumerable: true, configurable: true }); /** * Configures a cloned object from this instance * * @param clone */ ODataQueryable.prototype._clone = function (clone, cloneSettings) { clone = _super.prototype._clone.call(this, clone, cloneSettings); if (cloneSettings.includeBatch) { clone = clone.inBatch(this._batch); } return clone; }; return ODataQueryable; }(Queryable)); var ODataBatch = /** @class */ (function () { function ODataBatch(_batchId) { if (_batchId === void 0) { _batchId = getGUID(); } this._batchId = _batchId; this._reqs = []; this._deps = []; this._rDeps = []; } Object.defineProperty(ODataBatch.prototype, "batchId", { get: function () { return this._batchId; }, enumerable: true, configurable: true }); Object.defineProperty(ODataBatch.prototype, "requests", { /** * The requests contained in this batch */ get: function () { return this._reqs; }, enumerable: true, configurable: true }); /** * * @param url Request url * @param method Request method (GET, POST, etc) * @param options Any request options * @param parser The parser used to handle the eventual return from the query * @param id An identifier used to track a request within a batch */ ODataBatch.prototype.add = function (url, method, options, parser, id) { var info = { id: id, method: method.toUpperCase(), options: options, parser: parser, reject: null, resolve: null, url: url, }; var p = new Promise(function (resolve, reject) { info.resolve = resolve; info.reject = reject; }); this._reqs.push(info); return p; }; /** * Adds a dependency insuring that some set of actions will occur before a batch is processed. * MUST be cleared using the returned resolve delegate to allow batches to run */ ODataBatch.prototype.addDependency = function () { var resolver = function () { return void (0); }; this._deps.push(new Promise(function (resolve) { resolver = resolve; })); return resolver; }; /** * The batch's execute method will not resolve util any promises added here resolve * * @param p The dependent promise */ ODataBatch.prototype.addResolveBatchDependency = function (p) { this._rDeps.push(p); }; /** * Execute the current batch and resolve the associated promises * * @returns A promise which will be resolved once all of the batch's child promises have resolved */ ODataBatch.prototype.execute = function () { var _this = this; // we need to check the dependencies twice due to how different engines handle things. // We can get a second set of promises added during the first set resolving return Promise.all(this._deps) .then(function () { return Promise.all(_this._deps); }) .then(function () { return _this.executeImpl(); }) .then(function () { return Promise.all(_this._rDeps); }) .then(function () { return void (0); }); }; return ODataBatch; }()); export { CachingOptions, CachingParserWrapper, HttpRequestError, ODataParserBase, ODataDefaultParser, TextParser, BlobParser, JSONParser, BufferParser, LambdaParser, setResult, pipe, requestPipelineMethod, PipelineMethods, getDefaultPipeline, Queryable, ODataQueryable, ODataBatch }; //# sourceMappingURL=odata.es5.js.map
{ var config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false }; config.startShouldSetResponder.captured.child = { order: 2, returnVal: false }; config.startShouldSetResponder.bubbled.child = { order: 3, returnVal: true }; config.responderGrant.child = { order: 4 }; config.responderStart.child = { order: 5 }; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child) ); config = oneEventLoopTestConfig(three); config.moveShouldSetResponder.captured.grandParent = { order: 0, returnVal: false }; config.moveShouldSetResponder.captured.parent = { order: 1, returnVal: false }; config.moveShouldSetResponder.bubbled.parent = { order: 2, returnVal: true }; config.responderGrant.parent = { order: 3 }; config.responderTerminationRequest.child = { order: 4, returnVal: false }; config.responderReject.parent = { order: 5 }; config.responderMove.child = { order: 6 }; var touchConfig = moveConfig(three.child, [three.child], [0]); run(config, three, touchConfig); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child) ); config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false }; config.startShouldSetResponder.bubbled.parent = { order: 2, returnVal: true }; config.responderGrant.parent = { order: 3 }; config.responderTerminationRequest.child = { order: 4, returnVal: false }; config.responderReject.parent = { order: 5 }; config.responderStart.child = { order: 6 }; touchConfig = startConfig(three.child, [three.child, three.child], [1]); run(config, three, touchConfig); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child) ); }
'use strict'; configApp.factory("AboutPageService", function($http) { return { save : function(sendData) { var urlConfig = [baseUrl, 'admin','about_page_save'].join('/'); return $http({ method: 'POST', url: urlConfig, data: $.param({ data : sendData}), headers: {'Content-Type': 'application/x-www-form-urlencoded'} }); }, user : function(sendData) { var urlConfig = [baseUrl, 'admin','lang'].join('/'); return $http({ method: 'POST', url: urlConfig, data: $.param({ lang : sendData}), headers: {'Content-Type': 'application/x-www-form-urlencoded'} }); }, getAboutPage : function() { var urlConfig = [baseUrl, 'admin','get_about_page'].join('/'); return $http({ method: 'POST', url: urlConfig, data: $.param({ }), headers: {'Content-Type': 'application/x-www-form-urlencoded'} }); }, server : function() { var urlConfig = [baseUrl, 'server'].join('/'); return $http.get(urlConfig); } } }); configControllers.controller('AboutPageController', ['$scope', '$rootScope','$routeParams', '$location','$http', '$state', 'AboutPageService', '$route', function($scope, $rootScope, $routeParams, $location, $http, $state, AboutPageService, $route) { document.title = 'AdminLTE '; checkLogin(); AboutPageService.getAboutPage().success(function(res){ if(res) { $scope.page_name = res.page_name; $scope.about_page = res.page_content; $scope.text_menu_dashboard = langArray.text_menu_dashboard; $scope.text_menu_settings_title = langArray.text_menu_settings_title; $scope.text_menu_about = langArray.text_menu_about; $scope.text_title = langArray.text_title; $scope.text_content = langArray.text_content; $scope.btn_save = langArray.btn_save; $scope.message_update_success = langArray.message_update_success; } }); $scope.btnAboutSave = function() { if($scope.about_page !== undefined && $scope.page_name != undefined ) { var data = { "page_name" : $scope.page_name, "about_page" : $scope.about_page }; AboutPageService.save(data).success(function(res){ if(res == "TRUE") { $scope.message_success = $scope.message_update_success; } }); } } }]);
import Reflux from 'reflux'; module.exports = Reflux.createActions([ 'login', 'logout', 'setUserName' ]);
'use strict'; var assParser = require('..'); var test = require('tape'); var fs = require('fs'); var sample = function (encoding) { return fs.readFileSync(__dirname + '/sample.ass', { encoding: encoding }); }; var subtitleWithComments = require('./sample.json'); var subtitleWithoutComments = subtitleWithComments.map(function (section) { return { section: section.section, body: section.body.filter(function (descriptor) { return descriptor.type != 'comment'; }) }; }); test('ass-parser', function (t) { t.deepEqual(assParser(sample('utf8')), subtitleWithoutComments, 'without comments'); t.deepEqual(assParser(sample('utf8'), { comments: true }), subtitleWithComments, 'with comments'); t.deepEqual(assParser(sample(null)), subtitleWithoutComments, 'without comments (buffer)'); t.end(); });
(function() { // // object: the camera or other 3D object to attach to (THREE.Object3D) // size: the size of each page cube (Number) // distance: the distance from the object to create pages (THREE.Vector3) // options: the `add` and `remove` callbacks to (Object) var Paging = function( object, size, distance, options ) { options || ( options = {} ); this.object = object; this.distance = distance; this.size = size; this.halfsize = size / 2; this.position = null; this.add = ( options.add ) || function() {}; this.remove = ( options.remove ) || function() {}; this.pages = []; // page boxes currently in distance from object // this._size = new THREE.Vector3( size, size, size ); this._boxes = []; this._vs = []; this._pagesmap = {}; this.look = new THREE.Vector3(); this.look.x = Math.ceil( distance.x / size ); this.look.y = Math.ceil( distance.y / size ); this.look.z = Math.ceil( distance.z / size ); }; // Paging.prototype = Object.create( Object.prototype ); // Paging.prototype.boxes = function() { // start with the current page var position = this.object.position, xpage = Math.floor( ( position.x + this.halfsize ) / this.size ), ypage = Math.floor( ( position.y + this.halfsize ) / this.size ), zpage = Math.floor( ( position.z + this.halfsize ) / this.size ); // build the center vectors of the pages var boxes = [], i = 0; for ( var x = -this.look.x ; x <= this.look.x ; x += 1 ) { for ( var y = -this.look.y ; y <= this.look.y ; y += 1 ) { for ( var z = -this.look.z ; z <= this.look.z ; z += 1 ) { var xcenter = this.size * ( xpage + x ), ycenter = this.size * ( ypage + y ), zcenter = this.size * ( zpage + z ), center = new THREE.Vector3( xcenter, ycenter, zcenter ), hash = [ center.x, center.y, center.z ].join( "," ), box = new THREE.Box3(); box.setFromCenterAndSize( center, this._size ); box._distance = center.distanceTo( position ); box._center = center; box._hash = hash; boxes.push( box ); i += 1; } } } // sort the centers by distance to add the first pages first boxes.sort( function( a, b ) { if ( a._distance == b._distance ) return 0; else return ( a._distance < b._distance ) ? -1 : 1; } ); // return boxes; }; // Paging.prototype.update = function() { // don't update if the position wasn't changed var position = this.object.position; if ( this.position ) { var d = new THREE.Vector3().subVectors( position, this.position ); if ( Math.abs( d.x ) < this.halfsize && Math.abs( d.y ) < this.halfsize && Math.abs( d.z ) < this.halfsize ) { return; } } // get the camera boxes var boxes = this.boxes(); // boxes to add var _pagesmap = {}; for ( var b = 0 ; b < boxes.length ; b += 1 ) { if ( !this._pagesmap[ boxes[ b ]._hash ] ) { this.add( boxes[ b ] ); } _pagesmap[ boxes[ b ]._hash ] = boxes[ b ]; } // boxes to remove for ( var hash in this._pagesmap ) { if ( !_pagesmap[ hash ] ) { this.remove( this._pagesmap[ hash ] ); } } this._pagesmap = _pagesmap; this.pages = boxes; this.position || ( this.position = new THREE.Vector3() ); this.position.copy( position ); }; // window.Paging = Paging; }());
// This is our bootstrap file responsible for configuring Require.js and loading dependencies. require.config({ paths: { jquery: 'libs/jquery/jquery', underscore: 'libs/underscore/underscore', handlebars: 'libs/handlebars/handlebars', backbone: 'libs/backbone/backbone', viewcache: 'libs/backbone.viewcache/backbone.viewcache', bootstrap: 'libs/bootstrap/bootstrap', three: 'libs/three/three', gsvpano: 'libs/gsvpano/gsvpano', hyperlapse: 'libs/hyperlapse/hyperlapse' }, shim: { 'bootstrap': { deps: ['jquery'], exports: 'Bootstrap' }, 'three': { deps: [], exports: 'THREE' }, 'gsvpano': { deps: [], exports: 'GSVPANO' }, 'hyperlapse': { deps: ['three', 'gsvpano'], exports: 'Hyperlapse' } } }); require([ 'app', ], function(App) { console.log('start: initialize App'); App.initialize(); console.log('end: initialize App'); });
namespace('Demo'); Demo.CollectionView = Backbone.View.extend({ render: function() { this.$el.html("Ready to search..."); return this; }, showResults: function(tasksJson){ var _this = this; this.$el.empty(); _.each(tasksJson, function(task) { _this.$el.append(task.member_name); }); }, searchCriteriaCleared: function(){ this.$el.empty(); }, showNoResults: function(){ this.$el.html("Sorry, but there are no more tasks"); }, showError: function(response, statusCode) { this.$el.html("There was an error: " + response.responseText + " " + statusCode); } });
(function() { 'use strict'; angular .module('app.project') .controller('EditController', EditController); /** @ngInject */ function EditController($scope, $rootScope, $mdDialog, selectedProject, projectService) { $scope.select_project_original = selectedProject; $scope.select_project = angular.copy($scope.select_project_original); $scope.states = ['Offering', 'Buyiny','Aftersale']; $scope.addAttenStatus = false; $scope.scopeOfWorkStatus = false; $scope.customerDetailInfo = $scope.select_project.CustomerInfo.CustomerDetailInfo; $scope.scopeOfWorkInfo = $scope.select_project.ScopeInfo; var vm = this; vm.closeDialog = closeDialog; vm.formWizard = {}; // form project vm.formWizard2 = {}; // form attention vm.formWizard3 = {}; // form scope of work function closeDialog() { $mdDialog.hide(); $scope.select_project = $scope.select_project_original; } $scope.addAttention = function() { if ($scope.addAttenStatus == false) { $scope.addAttenStatus = true; } else { $scope.addAttenStatus = false; } } $scope.attention = function() { $scope.addAttenStatus = false; var remove = $scope.customerDetailInfo.indexOf(vm.formWizard2); if (remove > -1) { $scope.customerDetailInfo.splice(remove, 1); } var project_id = $scope.select_project.ProjectID; var customer_id = $scope.customerDetailInfo.length + 1; vm.formWizard2.CustomerID = customer_id; vm.formWizard2.CompanyID = "1-" + project_id; vm.formWizard2.CustomerStateValue = ""; $scope.customerDetailInfo.push(vm.formWizard2); vm.formWizard2 = {}; } $scope.removeAttention = function() { var remove = $scope.customerDetailInfo.indexOf(vm.formWizard2); if (remove > -1) { $scope.customerDetailInfo.splice(remove, 1); } vm.formWizard2 = {}; } $scope.addScopeOfWork = function() { if ($scope.scopeOfWorkStatus == false) { $scope.scopeOfWorkStatus = true; } else { $scope.scopeOfWorkStatus = false; } } $scope.removeScope = function() { var remove = $scope.scopeOfWorkInfo.indexOf(vm.formWizard3); if (remove > -1) { $scope.scopeOfWorkInfo.splice(remove, 1); } vm.formWizard3 = {}; } $scope.scopeOfWork = function() { $scope.scopeOfWorkStatus = false; var remove = $scope.scopeOfWorkInfo.indexOf(vm.formWizard3); if (remove > -1) { $scope.scopeOfWorkInfo.splice(remove, 1); } var project_id = $scope.select_project.ProjectID; vm.formWizard3.ProjectID = project_id; $scope.scopeOfWorkInfo.push(vm.formWizard3); vm.formWizard3 = {}; } $scope.sendEditProject = function() { console.log($scope.select_project); projectService.putProject($scope.select_project).then(function(response) { console.log('edit project success.'); selectedProject.ProjectDuration = $scope.select_project.ProjectDuration; closeDialog(); $rootScope.chart_progress(); }, function(err) { console.log('edit project fail : ' + JSON.stringify(err)); }) } $scope.changeCustomerDetail = function(atten) { $scope.addAttenStatus = true; vm.formWizard2 = atten; } $scope.changeScope = function(atten) { $scope.scopeOfWorkStatus = true; vm.formWizard3 = atten; } } })();
var NAVTREEINDEX0 = { "annotated.html":[1,0], "api_8h.html":[2,0,0], "api_8h.html#a2997e5a364a7ef0b05d6b4913cd23a6f":[2,0,0,0], "api_8h_source.html":[2,0,0], "binary__symmetric__channel_8h.html":[2,0,1], "binary__symmetric__channel_8h_source.html":[2,0,1], "binary__symmetric__channel__impl_8h.html":[2,0,2], "binary__symmetric__channel__impl_8h_source.html":[2,0,2], "classes.html":[1,1], "classgr_1_1channelcoding_1_1binary__symmetric__channel.html":[1,0,0,0,0], "classgr_1_1channelcoding_1_1binary__symmetric__channel.html#a209dc58e4a09b27e2281f6b18a7e2923":[1,0,0,0,0,1], "classgr_1_1channelcoding_1_1binary__symmetric__channel.html#ace482d1a88ac377b94cb054b4a1882d2":[1,0,0,0,0,0], "classgr_1_1channelcoding_1_1binary__symmetric__channel__impl.html":[1,0,0,0,1], "classgr_1_1channelcoding_1_1binary__symmetric__channel__impl.html#a1d6b227f6045d3017685ec454808e634":[1,0,0,0,1,0], "classgr_1_1channelcoding_1_1binary__symmetric__channel__impl.html#a36a484cc93e0f2210845c7e6fc8685c0":[1,0,0,0,1,1], "classgr_1_1channelcoding_1_1binary__symmetric__channel__impl.html#a56c652d9df7430dbd6e002f7d813f9ae":[1,0,0,0,1,3], "classgr_1_1channelcoding_1_1binary__symmetric__channel__impl.html#a90a1a4410e63f5e45a2bccb3299adeb2":[1,0,0,0,1,4], "classgr_1_1channelcoding_1_1binary__symmetric__channel__impl.html#aeb8232e0fdeeb575728ddda60e78d64f":[1,0,0,0,1,2], "files.html":[2,0], "functions.html":[1,3,0], "functions_func.html":[1,3,1], "functions_type.html":[1,3,2], "globals.html":[2,1,0], "globals_defs.html":[2,1,1], "group__block.html":[0,0], "hierarchy.html":[1,2], "index.html":[], "modules.html":[0], "namespacegr.html":[1,0,0], "namespacegr_1_1channelcoding.html":[1,0,0,0], "pages.html":[] };
(function(window, undefined){ 'use strict'; var imgs = [], els = []; function imageViwer(el){ var basePath = el.getAttribute('data-base-path') || 'images/', images = el.getAttribute('data-images').split(','), delay = el.getAttribute('data-delay') || 500, bp = '', index; function addStylesToEl(el, elStyles){ var st = el.style; elStyles.forEach(function(style){ st[style[0]] = style[1]; }); } function fadeIn(){ var opacity = 0, tid; el.setAttribute('src', images[index]); tid = setInterval(function(){ opacity += 0.01; addStylesToEl(el, [['opacity', opacity]]); if(opacity >= 1){ clearInterval(tid); pause(el); } }, 10); } function pause(){ setTimeout(function(){ fadeOut(el); }, delay); } function fadeOut(){ var opacity = 1, tid; tid = setInterval(function(){ opacity -= 0.01; addStylesToEl(el, [['opacity', opacity]]); if(opacity <= 0){ clearInterval(tid); index += 1; index = index > images.length - 1 ? 0 : index; fadeIn(el); } }, 10); } bp = basePath[basePath.length - 1]; bp = bp === '/' ? basePath : basePath + '/'; //Add basepath to each image images = images.map(function(i){ var img = i.trim(); return bp + img; }) ; //Show the 1st image index = 0; el.setAttribute('src', images[index]); //... and pause setTimeout(function(){ pause(); }, 1); } //Get all images elements imgs = document.getElementsByTagName('img'); imgs = [].slice.call(imgs, 0); //Filter for intended image viewers els = imgs.filter(function(img){ return !!img.getAttribute('data-image-viewer'); }); //Turn them into image viewers els.forEach(function(img){ imageViwer(img); }); }(window));
(function (Random) { describe("integer distribution", function () { [-Math.pow(2, 53) - 2, -Infinity, NaN, Infinity].forEach(function (min) { it("throws a RangeError if min = " + min, function () { expect(function () { Random.integer(min, 0); }).toThrow(new RangeError("Expected min to be at least " + (-0x20000000000000))); }); }); [Math.pow(2, 53) + 2, -Infinity, NaN, Infinity].forEach(function (max) { it("throws a RangeError if max = " + max, function () { expect(function () { Random.integer(0, max); }).toThrow(new RangeError("Expected max to be at most " + 0x20000000000000)); }); }); var engine; beforeEach(function () { engine = Random.engines.mt19937().autoSeed(); }); function cmp(alpha, bravo) { return alpha === bravo ? 0 : alpha < bravo ? -1 : 1; } function sorted(array, comparer) { return array.slice().sort(comparer || cmp); } var primeCache = [2, 3]; function primeGenerator() { var index = 0; return function () { var len = primeCache.length; if (index < len) { var result = primeCache[index]; ++index; return result; } else { var current = primeCache[len - 1] + 2; for (;; current += 2) { var prime = true; for (var i = 0; i < len; ++i) { if (current % primeCache[i] === 0) { prime = false; break; } } if (prime) { primeCache.push(current); ++index; return current; } } } }; } function calculatePrimeFactors(value) { var sqrt = Math.sqrt(value); var result = []; var nextPrime = primeGenerator(); while (true) { var prime = nextPrime(); if (prime > Math.sqrt(value)) { break; } while (value % prime === 0) { result.push(prime); value /= prime; } } if (value > 1) { result.push(value); } return result; } var fullScaleFactors = [5, 13, 37, 109, 246241, 279073]; function calculatePrimeFactorsOfRange(min, max) { if (max - min < 0x20000000000000) { return calculatePrimeFactors(max - min + 1); } else if (min === -0x20000000000000 && max === 0x20000000000000) { return fullScaleFactors.slice(); } var extra = 0x20000000000000; var rangeMinusExtra = (max - extra) - min + 1; var nextPrime = primeGenerator(); while (true) { var prime = nextPrime(); if (rangeMinusExtra % prime === 0) { return [prime].concat(calculatePrimeFactors(Math.round(rangeMinusExtra / prime + extra / prime))); } } throw new Error("Can't calclate prime factors of range [" + min + ", " + max + "]"); } function distinct(values) { var result = []; for (var i = 0, len = values.length; i < len; ++i) { var value = values[i]; if (result.indexOf(value) === -1) { result.push(value); } } return result; } function returnValue(value) { return function () { return value; }; } function toCallback(callback) { return typeof callback === "function" ? callback : returnValue(callback); } function times(count, callback) { callback = toCallback(callback); var result = []; for (var i = 0; i < count; ++i) { result.push(callback(i)); } return result; } function verifyBucket(bucket, iterationCount) { var pdf = 1 / bucket.length; var dividend = Math.sqrt(iterationCount * pdf); for (var i = 0, len = bucket.length; i < len; ++i) { var d = Math.abs(bucket[i] - iterationCount * pdf); var s = d / dividend; if (d > 1) { expect(s).not.toBeGreaterThan(5); } } } function divmod(divisor, dividend) { var mod = divisor % dividend; if (mod < 0) { mod += dividend; return [Math.floor((divisor - mod) / dividend), mod]; } else { return [Math.floor(divisor / dividend), mod]; } } function testUniformDistribution(min, max, iterationCount) { var range = max - min + 1; var factors = calculatePrimeFactorsOfRange(min, max); if (factors.length === 1) { it("is uniformly distributed within [" + min + ", " + max + "] given " + iterationCount + " iterations", function () { var distribution = Random.integer(min, max); var bucket = []; var i; for (i = 0; i < range; ++i) { bucket.push(0); } for (i = 0; i < iterationCount; ++i) { var r = distribution(engine); expect(r).not.toBeLessThan(min); expect(r).not.toBeGreaterThan(max); ++bucket[r - min]; } verifyBucket(bucket, iterationCount); }); } else { it("is uniformly distributed within [" + min + ", " + max + "] modulo factors {" + factors.join(", ") + "} given " + iterationCount + " iterations", function () { var distribution = Random.integer(min, max); var buckets = times(factors.length, function (i) { return times(factors[i], 0); }); function addToBuckets(value) { for (var i = 0, len = factors.length; i < len; ++i) { var factor = factors[i]; var result = divmod(value, factor); ++buckets[i][result[1]]; value = result[0]; } } for (var i = 0; i < iterationCount; ++i) { var r = distribution(engine); expect(r).not.toBeLessThan(min); expect(r).not.toBeGreaterThan(max); addToBuckets(r); } buckets.forEach(function (bucket) { verifyBucket(bucket, iterationCount); }); }); } } // same min and max testUniformDistribution(1, 1, 10); // fits perfectly into int32 testUniformDistribution(0, 0xffffffff, 1000); testUniformDistribution(1, 0x100000000, 1000); // easily maskable, since range is 2^x testUniformDistribution(0, 15, 1000); testUniformDistribution(0, 255, 1000); // within int32 testUniformDistribution(0, 2, 1000); testUniformDistribution(3, 7, 1000); testUniformDistribution(1, 20, 1000); testUniformDistribution(1, 2, 1000); testUniformDistribution(1, 2 * 3, 1000); testUniformDistribution(1, 2 * 3 * 5, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7 * 11, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7 * 11 * 13, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7 * 11 * 13 * 17, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23, 1000); // lower part of range is evenly int32, high part is easily-maskable. testUniformDistribution(1, 0x200000000, 1000); testUniformDistribution(1, 0x10000000000000, 1000); // fits perfectly into uint53 testUniformDistribution(1, 0x20000000000000, 1000); // within uint53-1 testUniformDistribution(1, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31 * 37, 1000); testUniformDistribution(1, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31 * 37 * 41, 1000); testUniformDistribution(1, 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31 * 37 * 41 * 43, 1000); testUniformDistribution(1, 0x300000000, 1000); // fits perfectly into int53 testUniformDistribution(-0x1fffffffffffff, 0x20000000000000, 1000); testUniformDistribution(-0x20000000000000, 0x1fffffffffffff, 1000); // within int53-1 testUniformDistribution(-0x1fffffffffffff, 0xe7ab3bddafc0e, 1000); testUniformDistribution(-0xe7ab3bddafc0d, 0x20000000000000, 1000); it("returns int32 if " + -0x80000000 + " and " + 0x7fffffff + " are passed in", function () { var expected = Random.int32; var actual = Random.integer(-0x80000000, 0x7fffffff); expect(actual).toBe(expected); }); it("returns uint32 if 0 and " + 0xffffffff + " are passed in", function () { var expected = Random.uint32; var actual = Random.integer(0, 0xffffffff); expect(actual).toBe(expected); }); it("returns uint53 if 0 and " + 0x1fffffffffffff + " are passed in", function () { var expected = Random.uint53; var actual = Random.integer(0, 0x1fffffffffffff); expect(actual).toBe(expected); }); it("returns uint53Full if 0 and " + 0x20000000000000 + " are passed in", function () { var expected = Random.uint53Full; var actual = Random.integer(0, 0x20000000000000); expect(actual).toBe(expected); }); it("returns int53 if " + (-0x20000000000000) + " and " + 0x1fffffffffffff + " are passed in", function () { var expected = Random.int53; var actual = Random.integer(-0x20000000000000, 0x1fffffffffffff); expect(actual).toBe(expected); }); it("returns int53Full if " + (-0x20000000000000) + " and " + 0x20000000000000 + " are passed in", function () { var expected = Random.int53Full; var actual = Random.integer(-0x20000000000000, 0x20000000000000); expect(actual).toBe(expected); }); function testFullScale(min, max, distribution) { it("is uniformly distributed within [" + min + ", " + max + "]", function () { var iterationCount = 1000; var factors = calculatePrimeFactorsOfRange(min + 1, max); var buckets = times(factors.length, function (i) { return times(factors[i], 0); }); function addToBuckets(value) { for (var i = 0, len = factors.length; i < len; ++i) { var factor = factors[i]; var result = divmod(value, factor); ++buckets[i][result[1]]; value = result[0]; } } for (var i = 0; i < iterationCount; ++i) { var r = 0; do { r = distribution(engine); } while (r === min); expect(r).not.toBeLessThan(min); expect(r).not.toBeGreaterThan(max); addToBuckets(r); } buckets.forEach(function (bucket) { verifyBucket(bucket, iterationCount); }); }); } testFullScale(-0x20000000000000, 0x20000000000000, Random.int53Full); testFullScale(0, 0x20000000000000, Random.uint53Full); function makeEngine(input) { var index = 0; return function () { if (index >= input.length) { return 0; } else { return input[index++] | 0; } }; } it("can generate " + 0x20000000000000 + " given a distribution of [" + (-0x20000000000000) + ", " + 0x20000000000000 + "]", function () { var distribution = Random.int53Full; var engine = makeEngine([0x400000, 0]); var actual = distribution(engine); expect(actual).toBe(0x20000000000000); }); it("can generate " + 0x20000000000000 + " given a distribution of [0, " + 0x20000000000000 + "]", function () { var distribution = Random.uint53Full; var engine = makeEngine([0x200000, 0]); var actual = distribution(engine); expect(actual).toBe(0x20000000000000); }); }); }(typeof module !== "undefined" ? require("../lib/random") : Random));
import Ember from 'ember'; import jsonSchemaSchema from 'ember-cli-json-schema-validator/schemas/json-schema'; var JsonSchemaValidatorService = Ember.Service.extend({ // Validates the argument is a valid JSON schema and returns errors, if any. // If valid, a falsey value is returned. validate (schemaObj) { var validator = window.jjv(); validator.addSchema('schema', jsonSchemaSchema); return validator.validate('schema', schemaObj); } }); export default JsonSchemaValidatorService;
'use strict'; /* Directives */ angular.module('myApp.directives', []). directive('appVersion', ['version', function(version) { return function(scope, elm, attrs) { elm.text(version); }; }]) .directive('chart', function() { return { restrict: 'A', link: function($scope, $elm, $attr) { // Create the data table var data = new google.visualization.DataTable(); data.addColumn('string', 'Country'); data.addColumn('number', 'Value'); data.addColumn({ type:'string', role:'tooltip' }); // Set chart options var options = {}; options['backgroundColor']= '#96CBD7';//78cabf var colorAxis = { minValue: 0, maxValue: 5, colors: ['#438094','#FF9933','#0066FF','#438094','#438094'] }; options['colorAxis']= colorAxis; options['datalessRegionColor']= 'silver'; options['height']= 600; options['width']= 800; options['legend']= 'none';//hide the colorAxis set to 'none' var tooltip = { textStyle: { color: '#008080' }, showColorCode: false }; options['tooltip']= tooltip; // Instantiate and draw our chart, passing in some options var chart = new google.visualization.GeoChart($elm[0]); chart.draw(data, options); $scope.delCountry = function(index,name){ console.log("delcountry: "+index+" "+name); $scope.beenTo.splice(index, 1); var code = ''; angular.forEach($scope.countries, function(country){ for(var i = 0; i < $scope.countries.length; i++){ if(country.name==name) { console.log(country.name+" "+country['alpha-2']); code = country['alpha-2']; break; } } }); if(code.length!=0){ var foundRows = data.getFilteredRows([{ column: 0, value: code }]); } if(foundRows.length!=0){ for (var i = 0, maxrows = foundRows.length; i < maxrows; i++) { console.log("del found row: should always be 1: "+foundRows.length+"row deled: "+foundRows[i]); data.removeRow(foundRows[i]); chart.draw(data,options); } } }; $scope.updateMap = function(code,name) { var foundExisiting = data.getFilteredRows([{ column: 0, value: code }]); console.log("update foundExisiting.length: "+foundExisiting.length); if(foundExisiting.length==0){ var r = Math.round(Math.random()*1000); data.addRows([[{ v:code, f:name },r,'Traveled']]); chart.draw(data, options); console.log("row added: "+code+" "+ name); } var flag=0; angular.forEach($scope.beenTo, function(item){ for(var i = 0; i < $scope.beenTo.length; i++){ if(item.search(name) >= 0) { flag++; } } }); if(flag==0){ $scope.beenTo.push(name); } }; } } }) .directive('focusin', function factory() { return { restrict: 'E', replace: true, template: '<div>A:{{control}}</div>', scope: { control: '=' }, link : function (scope, element, attrs) { scope.control.takenTablets = 0; scope.control.takeTablet = function() { scope.control.takenTablets += 1; } } }; }) .directive('myCurrentTime', function($interval, dateFilter) { function link(scope, element, attrs) { var format, timeoutId; function updateTime() { element.text(dateFilter(new Date(), format)); } scope.$watch(attrs.myCurrentTime, function(value) { format = value; updateTime(); }); element.on('$destroy', function() { $interval.cancel(timeoutId); }); // start the UI update process; save the timeoutId for canceling timeoutId = $interval(function() { updateTime(); // update DOM }, 1000); } return { link: link }; });
'use strict' var assert = require('assert') var s = require('stream') var Promise = require('promise') var b = require('../') describe('barrage(stream) mixin', function () { it('returns `stream` with a mixin', function () { var r = new s.Readable() var w = new s.Writable() var t = new s.Transform() assert(b(r) === r) assert(b(w) === w) assert(b(t) === t) }) }) function streamType(name, type) { describe('barrage.' + name, function () { var i = new b[name]() it('is an instance of stream.' + name, function () { assert(i instanceof s[name]) }) it('is not the same as stream.' + name, function () { assert(b[name] != s[name]) }) it('is a ' + type + ' barrage', function () { if (type === 'readable' || type === 'writable') { assert(typeof i.syphon === 'function') assert(typeof i.buffer === 'function') assert(typeof i.wait === 'function') } else { throw new Error('unrecognized type') } }) }) } streamType('Readable', 'readable') streamType('Writable', 'writable') streamType('Duplex', 'readable') streamType('Transform', 'readable') streamType('PassThrough', 'readable') describe('barrage extensions', function () { describe('BarrageStream#syphon', function () { it('pipes data', function (done) { var source = new b.Readable() source._read = function () { this.push('foo') this.push('bar') this.push(null) } var dest = new b.PassThrough() source.syphon(dest) var data = [] dest .on('error', done) .on('data', function (chunk) { data.push(chunk) }) .on('end', function () { assert.equal('foobar', data.join('')) done() }) }) it('pipes errors', function (done) { var singleton = {} var source = new b.Readable() source._read = function () { } var dest = new b.PassThrough() source.syphon(dest) dest.on('error', function(err) { assert.equal(singleton, err) done() }) source.emit('error', singleton) }) }) describe('BarrageStream#wait', function () { it('waits for `finish` or `end` events and catches `error` events', function (done) { var source = new b.Readable() source._read = function () { this.push('foo') this.push('bar') this.push(null) } source.wait(function (err, data) { if (err) return done(err) assert.equal(undefined, data) var sourceB = new b.Readable() sourceB._read = function () { } var singleton = {} sourceB.wait(function (err) { assert.equal(singleton, err) done() }) sourceB.emit('error', singleton) }) }) }) describe('BarrageStream#buffer', function () { it('buffers the content of a Readable stream and catches `error` events', function (done) { var source = new b.Readable({objectMode: true}) source._read = function () { this.push('foo') this.push('bar') this.push(null) } source.buffer(function (err, data) { if (err) return done(err) assert.deepEqual(['foo', 'bar'], data) var sourceB = new b.Readable({objectMode: false}) sourceB._read = function () { this.push('foo') this.push('bar') this.push(null) } sourceB.buffer('buffer', function (err, data) { if (err) return done(err) assert(Buffer.isBuffer(data)) assert.equal('foobar', data.toString()) var sourceC = new b.Readable({objectMode: false}) sourceC._read = function () { this.push('foo') this.push('bar') this.push(null) } sourceC.buffer('utf8', function (err, data) { if (err) return done(err) assert(typeof data === 'string') assert.equal('foobar', data) var sourceD = new b.Readable() sourceD._read = function () { } var singleton = {} sourceD.buffer(function (err) { assert.equal(singleton, err) done() }) sourceD.emit('error', singleton) }) }) }) }) }) describe('BarrageStream#map', function () { it('maps each element onto a new element', function (done) { var source = new b.Readable({objectMode: true}) source._read = function () { this.push(1) this.push(2) this.push(3) this.push(null) } var data = [] source.map(function (x) { return x * x }) .on('error', done) .on('data', function (chunk) { data.push(chunk) }) .on('end', function () { assert.deepEqual(data, [1, 4, 9]) done() }) }) it('can be used asynchronously', function (done) { var source = new b.Readable({objectMode: true}) source._read = function () { this.push(1) this.push(2) this.push(3) this.push(null) } var data = [] source.map(function (x, callback) { setImmediate(function () { callback(null, x * x) }) }) .on('error', done) .on('data', function (chunk) { data.push(chunk) }) .on('end', function () { assert.deepEqual(data, [1, 4, 9]) done() }) }) it('can be used with a promise', function (done) { var source = new b.Readable({objectMode: true}) source._read = function () { this.push(1) this.push(2) this.push(3) this.push(null) } var data = [] source.map(function (x) { return Promise.from(x * x) }) .on('error', done) .on('data', function (chunk) { data.push(chunk) }) .on('end', function () { assert.deepEqual(data, [1, 4, 9]) done() }) }) it('can be used in parallel', function (done) { var source = new b.Readable({objectMode: true}) source._read = function () { this.push(1) this.push(2) this.push(3) this.push(null) } var data = [] var running = 0 source.map(function (x, callback) { running++ if (x === 1) { setTimeout(function () { running-- callback(null, x * x) }, 100) } if (x === 2) { assert(running === 2) setTimeout(function () { running-- callback(null, x * x) }, 50) } if (x === 3) { assert(running <= 2) setTimeout(function () { running-- callback(null, x * x) }, 0) } }, {parallel: 2}) .on('error', done) .on('data', function (chunk) { data.push(chunk) }) .on('end', function () { assert.deepEqual(data, [1, 4, 9]) done() }) }) }) describe('BarrageStream#filter', function () { it('filters each element', function (done) { var source = new b.Readable({objectMode: true}) source._read = function () { this.push(1) this.push(2) this.push(3) this.push(null) } var data = [] source.filter(function (x) { return x > 1 }) .on('error', done) .on('data', function (chunk) { data.push(chunk) }) .on('end', function () { assert.deepEqual(data, [2, 3]) done() }) }) it('can be used asynchronously', function (done) { var source = new b.Readable({objectMode: true}) source._read = function () { this.push(1) this.push(2) this.push(3) this.push(null) } var data = [] source.filter(function (x, callback) { setImmediate(function () { callback(null, x > 1) }) }) .on('error', done) .on('data', function (chunk) { data.push(chunk) }) .on('end', function () { assert.deepEqual(data, [2, 3]) done() }) }) it('can be used with a promise', function (done) { var source = new b.Readable({objectMode: true}) source._read = function () { this.push(1) this.push(2) this.push(3) this.push(null) } var data = [] source.filter(function (x) { return Promise.from(x > 1) }) .on('error', done) .on('data', function (chunk) { data.push(chunk) }) .on('end', function () { assert.deepEqual(data, [2, 3]) done() }) }) it('can be used in parallel', function (done) { var source = new b.Readable({objectMode: true}) source._read = function () { this.push(1) this.push(2) this.push(3) this.push(null) } var data = [] var running = 0 source.filter(function (x, callback) { running++ if (x === 1) { setTimeout(function () { running-- callback(null, false) }, 100) } if (x === 2) { assert(running === 2) setTimeout(function () { running-- callback(null, true) }, 50) } if (x === 3) { assert(running <= 2) setTimeout(function () { running-- callback(null, true) }, 0) } }, {parallel: 2}) .on('error', done) .on('data', function (chunk) { data.push(chunk) }) .on('end', function () { assert.deepEqual(data, [2, 3]) done() }) }) }) describe('BarrageStream#bufferTransform', function () { it('transforms as a buffer', function (done) { var source = new b.Readable({objectMode: true}) source._read = function () { this.push(1) this.push(2) this.push(3) this.push(null) } var data = [] source.bufferTransform(function (x) { return x.reverse() }) .on('error', done) .on('data', function (chunk) { data.push(chunk) }) .on('end', function () { assert.deepEqual(data, [[3, 2, 1]]) done() }) }) it('supports an encoding option', function (done) { var source = new b.Readable({objectMode: true}) source._read = function () { this.push('h') this.push('e') this.push('l') this.push('l') this.push('o') this.push(null) } var data = [] source.bufferTransform(function (x) { return x + ' world' }, 'utf8') .on('error', done) .on('data', function (chunk) { data.push(chunk.toString('utf8')) }) .on('end', function () { assert.deepEqual(data, ['hello world']) done() }) }) }) })
/* * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. * * 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. * */ /*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50, regexp: true */ /*global define, describe, it, xit, expect, beforeEach, afterEach, waitsFor, runs, $, brackets, waitsForDone, spyOn, jasmine */ /*unittests: ExtensionManager*/ define(function (require, exports, module) { "use strict"; require("thirdparty/jquery.mockjax.js"); var ExtensionManager = require("extensibility/ExtensionManager"), ExtensionManagerView = require("extensibility/ExtensionManagerView").ExtensionManagerView, ExtensionManagerViewModel = require("extensibility/ExtensionManagerViewModel"), ExtensionManagerDialog = require("extensibility/ExtensionManagerDialog"), InstallExtensionDialog = require("extensibility/InstallExtensionDialog"), Package = require("extensibility/Package"), ExtensionLoader = require("utils/ExtensionLoader"), NativeFileSystem = require("file/NativeFileSystem").NativeFileSystem, NativeFileError = require("file/NativeFileError"), SpecRunnerUtils = require("spec/SpecRunnerUtils"), CollectionUtils = require("utils/CollectionUtils"), NativeApp = require("utils/NativeApp"), Dialogs = require("widgets/Dialogs"), CommandManager = require("command/CommandManager"), Commands = require("command/Commands"), Strings = require("strings"), mockRegistryText = require("text!spec/ExtensionManager-test-files/mockRegistry.json"), mockRegistryForSearch = require("text!spec/ExtensionManager-test-files/mockRegistryForSearch.json"), mockExtensionList = require("text!spec/ExtensionManager-test-files/mockExtensionList.json"), mockRegistry; describe("ExtensionManager", function () { var mockId, mockSettings, origRegistryURL, origExtensionUrl, removedPath; beforeEach(function () { // Use fake URLs for the registry (useful if the registry isn't actually currently // configured). origRegistryURL = brackets.config.extension_registry; origExtensionUrl = brackets.config.extension_url; brackets.config.extension_registry = "http://fake-registry.com/registry.json"; brackets.config.extension_url = "http://fake-repository.com/{0}/{0}-{1}.zip"; // Return a canned registry when requested. Individual tests can override this // at any point before the request is actually made. mockRegistry = JSON.parse(mockRegistryText); mockSettings = { url: brackets.config.extension_registry, dataType: "json", contentType: "application/json", response: function () { this.responseText = mockRegistry; } }; spyOn(mockSettings, "response").andCallThrough(); mockId = $.mockjax(mockSettings); // Set a fake path for user extensions. var mockPath = SpecRunnerUtils.getTestPath("/spec/ExtensionManager-test-files"); spyOn(ExtensionLoader, "getUserExtensionPath").andCallFake(function () { return mockPath + "/user"; }); // Fake package removal. removedPath = null; spyOn(Package, "remove").andCallFake(function (path) { removedPath = path; return new $.Deferred().resolve().promise(); }); }); afterEach(function () { $.mockjaxClear(mockId); ExtensionManager._reset(); $(ExtensionManager).off(".unit-test"); brackets.config.extension_registry = origRegistryURL; brackets.config.extension_url = origExtensionUrl; }); function mockLoadExtensions(names, fail) { var numStatusChanges = 0; runs(function () { $(ExtensionManager).on("statusChange.mock-load", function () { numStatusChanges++; }); var mockPath = SpecRunnerUtils.getTestPath("/spec/ExtensionManager-test-files"); names = names || ["default/mock-extension-1", "dev/mock-extension-2", "user/mock-legacy-extension"]; names.forEach(function (name) { $(ExtensionLoader).triggerHandler(fail ? "loadFailed" : "load", mockPath + "/" + name); }); }); // Make sure the ExtensionManager has finished reading all the package.jsons before continuing. waitsFor(function () { return numStatusChanges === names.length; }, "ExtensionManager status changes"); runs(function () { $(ExtensionManager).off(".mock-load"); }); } describe("ExtensionManager", function () { it("should download the extension list from the registry", function () { var registry; runs(function () { waitsForDone(ExtensionManager.downloadRegistry(), "fetching registry"); }); runs(function () { expect(mockSettings.response).toHaveBeenCalled(); Object.keys(ExtensionManager.extensions).forEach(function (id) { expect(ExtensionManager.extensions[id].registryInfo).toEqual(mockRegistry[id]); }); }); }); it("should trigger a registryUpdate event when updating the extension list from the registry", function () { var registry, registryUpdateSpy; runs(function () { registryUpdateSpy = jasmine.createSpy(); $(ExtensionManager).on("registryUpdate", registryUpdateSpy); waitsForDone(ExtensionManager.downloadRegistry(), "fetching registry"); }); mockLoadExtensions(); runs(function () { expect(registryUpdateSpy).toHaveBeenCalled(); }); }); it("should fail if it can't access the registry", function () { var gotDone = false, gotFail = false; runs(function () { $.mockjaxClear(mockId); mockId = $.mockjax({ url: brackets.config.extension_registry, isTimeout: true }); ExtensionManager.downloadRegistry() .done(function () { gotDone = true; }) .fail(function () { gotFail = true; }); }); waitsFor(function () { return gotDone || gotFail; }, "mock failure"); runs(function () { expect(gotFail).toBe(true); expect(gotDone).toBe(false); }); }); it("should fail if registry content is malformed", function () { var gotDone = false, gotFail = false; runs(function () { mockRegistry = "{malformed json"; ExtensionManager.downloadRegistry() .done(function () { gotDone = true; }) .fail(function () { gotFail = true; }); }); waitsFor(function () { return gotDone || gotFail; }, "bad mock data"); runs(function () { expect(gotFail).toBe(true); expect(gotDone).toBe(false); }); }); it("should correctly list which extensions are installed", function () { runs(function () { waitsForDone(ExtensionManager.downloadRegistry(), "loading registry"); }); mockLoadExtensions(); runs(function () { Object.keys(mockRegistry).forEach(function (extId) { if (extId === "mock-extension-1" || extId === "mock-extension-2") { expect(ExtensionManager.extensions[extId].installInfo.status).toEqual(ExtensionManager.ENABLED); } else { expect(ExtensionManager.extensions[extId].installInfo).toBeUndefined(); } }); }); }); it("should list an extension that is installed but failed to load", function () { runs(function () { waitsForDone(ExtensionManager.downloadRegistry(), "loading registry"); }); mockLoadExtensions(["user/mock-extension-3"], true); runs(function () { expect(ExtensionManager.extensions["mock-extension-3"].installInfo.status).toEqual(ExtensionManager.START_FAILED); }); }); it("should set the title for a legacy extension based on its folder name", function () { mockLoadExtensions(); runs(function () { var mockPath = SpecRunnerUtils.getTestPath("/spec/ExtensionManager-test-files"); expect(ExtensionManager.extensions["mock-legacy-extension"].installInfo.metadata.title).toEqual("mock-legacy-extension"); }); }); it("should determine the location type for installed extensions", function () { mockLoadExtensions(); runs(function () { expect(ExtensionManager.extensions["mock-extension-1"].installInfo.locationType).toEqual(ExtensionManager.LOCATION_DEFAULT); expect(ExtensionManager.extensions["mock-extension-2"].installInfo.locationType).toEqual(ExtensionManager.LOCATION_DEV); var mockPath = SpecRunnerUtils.getTestPath("/spec/ExtensionManager-test-files"); expect(ExtensionManager.extensions["mock-legacy-extension"].installInfo.locationType).toEqual(ExtensionManager.LOCATION_USER); }); }); it("should raise a statusChange event when an extension is loaded", function () { var spy = jasmine.createSpy(); runs(function () { $(ExtensionManager).on("statusChange.unit-test", spy); mockLoadExtensions(["default/mock-extension-1"]); }); runs(function () { expect(spy).toHaveBeenCalledWith(jasmine.any(Object), "mock-extension-1"); }); }); it("should raise a statusChange event when a legacy extension is loaded, with its path as the id", function () { var spy = jasmine.createSpy(); runs(function () { $(ExtensionManager).on("statusChange.unit-test", spy); mockLoadExtensions(["user/mock-legacy-extension"]); }); runs(function () { var mockPath = SpecRunnerUtils.getTestPath("/spec/ExtensionManager-test-files"); expect(spy).toHaveBeenCalledWith(jasmine.any(Object), "mock-legacy-extension"); }); }); it("should remove an extension and raise a statusChange event", function () { var spy = jasmine.createSpy(); runs(function () { mockLoadExtensions(["user/mock-extension-3"]); }); runs(function () { $(ExtensionManager).on("statusChange.unit-test", spy); waitsForDone(ExtensionManager.remove("mock-extension-3")); }); runs(function () { var mockPath = SpecRunnerUtils.getTestPath("/spec/ExtensionManager-test-files"); expect(removedPath).toBe(mockPath + "/user/mock-extension-3"); expect(spy).toHaveBeenCalledWith(jasmine.any(Object), "mock-extension-3"); expect(ExtensionManager.extensions["mock-extension-3"].installInfo).toBeFalsy(); }); }); it("should fail when trying to remove an extension that's not installed", function () { var finished = false; runs(function () { ExtensionManager.remove("mock-extension-3") .done(function () { finished = true; expect("tried to remove a nonexistent extension").toBe(false); }) .fail(function () { finished = true; }); }); waitsFor(function () { return finished; }, "finish removal"); }); it("should calculate compatibility info correctly", function () { function fakeEntry(version) { return { metadata: { engines: { brackets: version } } }; } expect(ExtensionManager.getCompatibilityInfo(fakeEntry(null), "1.0.0")) .toEqual({isCompatible: true}); expect(ExtensionManager.getCompatibilityInfo(fakeEntry(">0.5.0"), "0.6.0")) .toEqual({isCompatible: true}); expect(ExtensionManager.getCompatibilityInfo(fakeEntry(">0.6.0"), "0.6.0")) .toEqual({isCompatible: false, requiresNewer: true}); expect(ExtensionManager.getCompatibilityInfo(fakeEntry(">0.7.0"), "0.6.0")) .toEqual({isCompatible: false, requiresNewer: true}); expect(ExtensionManager.getCompatibilityInfo(fakeEntry("<0.5.0"), "0.4.0")) .toEqual({isCompatible: true}); expect(ExtensionManager.getCompatibilityInfo(fakeEntry("<0.4.0"), "0.4.0")) .toEqual({isCompatible: false, requiresNewer: false}); expect(ExtensionManager.getCompatibilityInfo(fakeEntry("<0.3.0"), "0.4.0")) .toEqual({isCompatible: false, requiresNewer: false}); expect(ExtensionManager.getCompatibilityInfo(fakeEntry("~1.2"), "1.2.0")) .toEqual({isCompatible: true}); expect(ExtensionManager.getCompatibilityInfo(fakeEntry("~1.2"), "1.2.1")) .toEqual({isCompatible: true}); expect(ExtensionManager.getCompatibilityInfo(fakeEntry("~1.2"), "1.3.0")) .toEqual({isCompatible: false, requiresNewer: false}); expect(ExtensionManager.getCompatibilityInfo(fakeEntry("~1.2"), "1.3.1")) .toEqual({isCompatible: false, requiresNewer: false}); expect(ExtensionManager.getCompatibilityInfo(fakeEntry("~1.2"), "1.1.0")) .toEqual({isCompatible: false, requiresNewer: true}); }); it("should return the correct download URL for an extension", function () { expect(ExtensionManager.getExtensionURL("my-cool-extension", "1.2.3")) .toBe("http://fake-repository.com/my-cool-extension/my-cool-extension-1.2.3.zip"); }); }); describe("ExtensionManagerView Model", function () { describe("when initialized from registry", function () { var model; beforeEach(function () { runs(function () { mockRegistry = JSON.parse(mockRegistryForSearch); model = new ExtensionManagerViewModel.RegistryViewModel(); waitsForDone(model.initialize(), "model initialization"); }); runs(function () { // Mock load some extensions, so we can make sure they don't show up in the filtered model in this case. mockLoadExtensions(); }); }); afterEach(function () { model.dispose(); model = null; }); it("should initialize itself from the extension list", function () { expect(model.extensions).toEqual(ExtensionManager.extensions); }); it("should start with the full set sorted in reverse publish date order", function () { expect(model.filterSet).toEqual(["item-5", "item-6", "item-2", "find-uniq1-in-name", "item-4", "item-3"]); }); it("should search case-insensitively for a keyword in the metadata for a given list of registry ids", function () { model.filter("uniq1"); expect(model.filterSet).toEqual(["find-uniq1-in-name"]); model.filter("uniq2"); expect(model.filterSet).toEqual(["item-2"]); model.filter("uniq3"); expect(model.filterSet).toEqual(["item-3"]); model.filter("uniq4"); expect(model.filterSet).toEqual(["item-4"]); model.filter("uniq5"); expect(model.filterSet).toEqual(["item-5"]); model.filter("uniq6"); expect(model.filterSet).toEqual(["item-6"]); model.filter("uniqin1and5"); expect(model.filterSet).toEqual(["item-5", "find-uniq1-in-name"]); // sorted in reverse publish date order }); it("should return correct results when subsequent queries are longer versions of previous queries", function () { model.filter("uniqin1and5"); model.filter("uniqin1and5-2"); expect(model.filterSet).toEqual(["item-5"]); }); it("should go back to the full sorted set when cleared", function () { model.filter("uniq1"); model.filter(""); expect(model.filterSet).toEqual(["item-5", "item-6", "item-2", "find-uniq1-in-name", "item-4", "item-3"]); }); it("should trigger filter event when filter changes", function () { var gotEvent = false; $(model).on("filter", function () { gotEvent = true; }); model.filter("uniq1"); expect(gotEvent).toBe(true); }); }); describe("when initialized from local extension list", function () { var model, origExtensions; beforeEach(function () { runs(function () { origExtensions = ExtensionManager.extensions; ExtensionManager._setExtensions(JSON.parse(mockExtensionList)); model = new ExtensionManagerViewModel.InstalledViewModel(); waitsForDone(model.initialize()); }); }); afterEach(function () { model.dispose(); model = null; ExtensionManager._setExtensions(origExtensions); }); it("should initialize itself from the extension list", function () { expect(model.extensions).toEqual(ExtensionManager.extensions); }); it("should only contain dev and user extensions, sorted case-insensitively on the extension title or name (or last segment of path name for legacy extensions)", function () { expect(model.filterSet).toEqual(["registered-extension", "dev-extension", "/path/to/extensions/user/legacy-extension", "unregistered-extension", "Z-capital-extension"]); }); it("should include a newly-installed extension", function () { mockLoadExtensions(["user/install-later-extension"]); runs(function () { expect(model.filterSet.indexOf("install-later-extension")).toBe(2); }); }); it("should raise an event when an extension is installed", function () { var calledId; runs(function () { $(model).on("change", function (e, id) { calledId = id; }); }); mockLoadExtensions(["user/install-later-extension"]); runs(function () { expect(calledId).toBe("install-later-extension"); }); }); it("should not include a removed extension", function () { runs(function () { waitsForDone(ExtensionManager.remove("registered-extension")); }); runs(function () { expect(model.filterSet.indexOf("registered-extension")).toBe(-1); }); }); it("should raise an event when an extension is removed", function () { var calledId; runs(function () { $(model).on("change", function (e, id) { calledId = id; }); waitsForDone(ExtensionManager.remove("registered-extension")); }); runs(function () { expect(calledId).toBe("registered-extension"); }); }); it("should mark an extension for removal and raise an event without actually removing it", function () { var id = "registered-extension", calledId; runs(function () { $(model).on("change", function (e, id) { calledId = id; }); ExtensionManager.markForRemoval(id, true); expect(calledId).toBe(id); expect(ExtensionManager.isMarkedForRemoval(id)).toBe(true); expect(model.filterSet.indexOf(id)).not.toBe(-1); expect(ExtensionManager.hasExtensionsToRemove()).toBe(true); }); }); it("should unmark an extension previously marked for removal and raise an event", function () { var id = "registered-extension", calledId; runs(function () { ExtensionManager.markForRemoval(id, true); $(model).on("change", function (e, id) { calledId = id; }); ExtensionManager.markForRemoval(id, false); expect(calledId).toBe(id); expect(ExtensionManager.isMarkedForRemoval(id)).toBe(false); expect(ExtensionManager.hasExtensionsToRemove()).toBe(false); }); }); it("should remove extensions previously marked for removal", function () { var removedIds = {}, removedPaths = {}; runs(function () { ExtensionManager.markForRemoval("registered-extension", true); ExtensionManager.markForRemoval("Z-capital-extension", false); $(model).on("change", function (e, id) { removedIds[id] = true; removedPaths[removedPath] = true; }); waitsForDone(ExtensionManager.removeMarkedExtensions()); }); runs(function () { // Test a removed extension, an extension that was unmarked for removal, and an extension that was never marked. expect(removedIds["registered-extension"]).toBe(true); expect(removedPaths["/path/to/extensions/user/registered-extension"]).toBe(true); expect(removedIds["Z-capital-extension"]).toBeUndefined(); expect(removedPaths["/path/to/extensions/user/Z-capital-extension"]).toBeUndefined(); expect(removedIds["unregistered-extension"]).toBeUndefined(); expect(removedPaths["/path/to/extensions/user/unregistered-extension"]).toBeUndefined(); }); }); it("should mark an extension for update and raise an event", function () { var id = "registered-extension", calledId; runs(function () { $(model).on("change", function (e, id) { calledId = id; }); ExtensionManager.updateFromDownload({ localPath: "/path/to/downloaded/file.zip", name: id, installationStatus: "NEEDS_UPDATE" }); expect(calledId).toBe(id); expect(ExtensionManager.isMarkedForUpdate(id)).toBe(true); expect(ExtensionManager.hasExtensionsToUpdate()).toBe(true); }); }); it("should unmark an extension for update, deleting the package and raising an event", function () { var id = "registered-extension", filename = "/path/to/downloaded/file.zip", calledId; runs(function () { $(model).on("change", function (e, id) { calledId = id; }); ExtensionManager.updateFromDownload({ localPath: filename, name: id, installationStatus: "NEEDS_UPDATE" }); calledId = null; spyOn(brackets.fs, "unlink"); ExtensionManager.removeUpdate(id); expect(calledId).toBe(id); expect(brackets.fs.unlink).toHaveBeenCalledWith(filename, jasmine.any(Function)); expect(ExtensionManager.isMarkedForUpdate()).toBe(false); }); }); it("should change an extension marked for removal to update raise an event", function () { var id = "registered-extension", calledId; runs(function () { $(model).on("change", function (e, id) { calledId = id; }); ExtensionManager.markForRemoval(id, true); expect(calledId).toBe(id); calledId = null; ExtensionManager.updateFromDownload({ localPath: "/path/to/downloaded/file.zip", name: id, installationStatus: "NEEDS_UPDATE" }); expect(calledId).toBe(id); expect(ExtensionManager.isMarkedForRemoval()).toBe(false); expect(ExtensionManager.hasExtensionsToRemove()).toBe(false); expect(ExtensionManager.isMarkedForUpdate(id)).toBe(true); expect(ExtensionManager.hasExtensionsToUpdate()).toBe(true); }); }); it("should update extensions marked for update", function () { var id = "registered-extension", filename = "/path/to/downloaded/file.zip"; runs(function () { ExtensionManager.updateFromDownload({ localPath: filename, name: id, installationStatus: "NEEDS_UPDATE" }); expect(ExtensionManager.isMarkedForUpdate()).toBe(false); spyOn(brackets.fs, "unlink"); var d = $.Deferred(); spyOn(Package, "installUpdate").andReturn(d.promise()); d.resolve(); waitsForDone(ExtensionManager.updateExtensions()); }); runs(function () { expect(brackets.fs.unlink).not.toHaveBeenCalled(); expect(Package.installUpdate).toHaveBeenCalledWith(filename, id); }); }); it("should recognize when an update is available", function () { var id = "registered-extension"; runs(function () { console.log(model.extensions[id]); expect(model._getEntry(id).updateAvailable).toBe(true); }); }); }); }); describe("ExtensionManagerView", function () { var testWindow, view, model, fakeLoadDeferred, modelDisposed; // Sets up the view using the normal (mock) ExtensionManager data. function setupViewWithMockData(ModelClass) { runs(function () { view = new ExtensionManagerView(); model = new ModelClass(); modelDisposed = false; waitsForDone(view.initialize(model), "view initializing"); }); runs(function () { spyOn(view.model, "dispose").andCallThrough(); }); } beforeEach(function () { this.addMatchers({ toHaveText: function (expected) { var notText = this.isNot ? " not" : ""; this.message = function () { return "Expected view" + notText + " to contain text " + expected; }; return SpecRunnerUtils.findDOMText(this.actual.$el, expected); }, toHaveLink: function (expected) { var notText = this.isNot ? " not" : ""; this.message = function () { return "Expected view" + notText + " to contain link " + expected; }; return SpecRunnerUtils.findDOMText(this.actual.$el, expected, true); } }); spyOn(InstallExtensionDialog, "installUsingDialog").andCallFake(function (url) { var id = url.match(/fake-repository\.com\/([^\/]+)/)[1]; mockLoadExtensions(["user/" + id]); }); }); afterEach(function () { view = null; if (model) { model.dispose(); } }); describe("when showing registry entries", function () { it("should populate itself with registry entries and display their fields when created", function () { setupViewWithMockData(ExtensionManagerViewModel.RegistryViewModel); runs(function () { CollectionUtils.forEach(mockRegistry, function (item) { // Should show the title if specified, otherwise the bare name. if (item.metadata.title) { expect(view).toHaveText(item.metadata.title); } else { expect(view).toHaveText(item.metadata.name); } // Simple fields [item.metadata.version, item.metadata.author && item.metadata.author.name, item.metadata.description] .forEach(function (value) { if (value) { expect(view).toHaveText(value); } }); if (item.metadata.homepage) { expect(view).toHaveLink(item.metadata.homepage); } // Array-valued fields [item.metadata.keywords, item.metadata.categories].forEach(function (arr) { if (arr) { arr.forEach(function (value) { expect(view).toHaveText(value); }); } }); // Owner--should show the parts, but might format them separately item.owner.split(":").forEach(function (part) { expect(view).toHaveText(part); }); }); }); }); it("should display owner even for installed items", function () { ExtensionManager._setExtensions(JSON.parse(mockExtensionList)); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { console.log(view); CollectionUtils.forEach(JSON.parse(mockExtensionList), function (item) { if (item.installInfo && item.registryInfo) { // Owner--should show the parts, but might format them separately item.registryInfo.owner.split(":").forEach(function (part) { expect(view).toHaveText(part); }); } }); }); }); it("should show an install button for each item", function () { setupViewWithMockData(ExtensionManagerViewModel.RegistryViewModel); runs(function () { CollectionUtils.forEach(mockRegistry, function (item) { var $button = $("button.install[data-extension-id=" + item.metadata.name + "]", view.$el); expect($button.length).toBe(1); }); }); }); it("should show disabled install buttons for items that are already installed", function () { mockLoadExtensions(["user/mock-extension-3", "user/mock-extension-4"]); setupViewWithMockData(ExtensionManagerViewModel.RegistryViewModel); runs(function () { CollectionUtils.forEach(mockRegistry, function (item) { var $button = $("button.install[data-extension-id=" + item.metadata.name + "]", view.$el); if (item.metadata.name === "mock-extension-3" || item.metadata.name === "mock-extension-4") { expect($button.prop("disabled")).toBeTruthy(); } else { expect($button.prop("disabled")).toBeFalsy(); } }); }); }); it("should show an update button for items that have an update available", function () { var id = "registered-extension"; ExtensionManager._setExtensions(JSON.parse(mockExtensionList)); setupViewWithMockData(ExtensionManagerViewModel.RegistryViewModel); runs(function () { var $button = $("button.update[data-extension-id=" + id + "]", view.$el); expect($button.length).toBe(1); expect($button.prop("disabled")).toBeFalsy(); }); }); it("should show disabled install buttons for items that have incompatible versions", function () { runs(function () { mockRegistry = { "incompatible-extension": { "metadata": { "name": "incompatible-extension", "title": "Incompatible Extension", "version": "1.0.0", "engines": { "brackets": "<0.1" } }, "owner": "github:someuser", "versions": [ { "version": "1.0.0", "published": "2013-04-10T18:28:20.530Z", "brackets": "<0.1" } ] } }; setupViewWithMockData(ExtensionManagerViewModel.RegistryViewModel); }); runs(function () { var $button = $("button.install[data-extension-id=incompatible-extension]", view.$el); expect($button.prop("disabled")).toBeTruthy(); }); }); it("should bring up the install dialog and install an item when install button is clicked", function () { runs(function () { setupViewWithMockData(ExtensionManagerViewModel.RegistryViewModel); }); runs(function () { var $button = $("button.install[data-extension-id=mock-extension-3]", view.$el); expect($button.length).toBe(1); $button.click(); expect(InstallExtensionDialog.installUsingDialog) .toHaveBeenCalledWith("http://fake-repository.com/mock-extension-3/mock-extension-3-1.0.0.zip"); }); }); it("should disable the install button for an item immediately after installing it", function () { var $button; runs(function () { setupViewWithMockData(ExtensionManagerViewModel.RegistryViewModel); }); runs(function () { $button = $("button.install[data-extension-id=mock-extension-3]", view.$el); $button.click(); }); runs(function () { // Have to get the button again since the view may have created a new button when re-rendering. $button = $("button.install[data-extension-id=mock-extension-3]", view.$el); expect($button.prop("disabled")).toBeTruthy(); }); }); it("should open links in the native browser instead of in Brackets", function () { runs(function () { mockRegistry = { "basic-valid-extension": { "metadata": { "name": "basic-valid-extension", "title": "Basic Valid Extension", "version": "1.0.0" }, "owner": "github:someuser", "versions": [ { "version": "1.0.0", "published": "2013-04-10T18:28:20.530Z" } ] } }; setupViewWithMockData(ExtensionManagerViewModel.RegistryViewModel); }); runs(function () { var origHref = window.location.href; spyOn(NativeApp, "openURLInDefaultBrowser"); $("a", view.$el).first().click(); expect(NativeApp.openURLInDefaultBrowser).toHaveBeenCalledWith("https://github.com/someuser"); expect(window.location.href).toBe(origHref); }); }); }); describe("when showing installed extensions", function () { it("should show the 'no extensions' message when there are no extensions installed", function () { setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { expect($(".empty-message", view.$el).css("display")).not.toBe("none"); expect($(".empty-message", view.$el).html()).toEqual(Strings.NO_EXTENSIONS); expect($("table", view.$el).css("display")).toBe("none"); }); }); it("should show the 'no extensions' message when there are extensions installed but none match the search query", function () { mockLoadExtensions(["user/mock-extension-3", "user/mock-extension-4", "user/mock-legacy-extension"]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { view.filter("DON'T_FIND_ME_IN_THE_EXTENSION_LIST"); expect($(".empty-message", view.$el).css("display")).not.toBe("none"); expect($(".empty-message", view.$el).html()).toEqual(Strings.NO_EXTENSION_MATCHES); expect($("table", view.$el).css("display")).toBe("none"); }); }); it("should show only items that are already installed and have a remove button for each", function () { mockLoadExtensions(["user/mock-extension-3", "user/mock-extension-4", "user/mock-legacy-extension"]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { expect($(".empty-message", view.$el).css("display")).toBe("none"); expect($("table", view.$el).css("display")).not.toBe("none"); CollectionUtils.forEach(mockRegistry, function (item) { var $button = $("button.remove[data-extension-id=" + item.metadata.name + "]", view.$el); if (item.metadata.name === "mock-extension-3" || item.metadata.name === "mock-extension-4" || item.metadata.name === "mock-legacy-extension") { expect(view).toHaveText(item.metadata.name); expect($button.length).toBe(1); } else { expect(view).not.toHaveText(item.metadata.name); expect($button.length).toBe(0); } }); }); }); it("should show a newly installed extension", function () { setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { expect(view).not.toHaveText("mock-extension-3"); mockLoadExtensions(["user/mock-extension-3"]); }); runs(function () { expect(view).toHaveText("mock-extension-3"); }); }); it("should not show extensions in the default folder", function () { mockLoadExtensions(["default/mock-extension-1"]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { expect(view).not.toHaveText("mock-extension-1"); }); }); it("should show extensions that failed to load with a 'remove' link", function () { mockLoadExtensions(["user/mock-extension-3"], true); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { expect(view).toHaveText("mock-extension-3"); var $removeLink = $("a.remove[data-extension-id=mock-extension-3]", view.$el); expect($removeLink.length).toBe(1); expect($removeLink.prop("disabled")).toBeFalsy(); $removeLink.click(); expect(ExtensionManager.isMarkedForRemoval("mock-extension-3")).toBe(true); var $undoLink = $("a.undo-remove[data-extension-id=mock-extension-3]", view.$el); expect($undoLink.length).toBe(1); $removeLink = $("a.remove[data-extension-id=mock-extension-3]", view.$el); expect($removeLink.length).toBe(0); }); }); it("should not have a 'remove' link for extensions in the dev folder that failed to load", function () { mockLoadExtensions(["dev/mock-failed-in-dev-folder"], true); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { expect(view).toHaveText("mock-failed-in-dev-folder"); var $removeLink = $("a.remove[data-extension-id=mock-failed-in-dev-folder]", view.$el); expect($removeLink.length).toBe(0); }); }); it("should disable the Remove button for extensions in the dev folder", function () { mockLoadExtensions(["dev/mock-extension-2"]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { var $button = $("button.remove[data-extension-id=mock-extension-2]", view.$el); expect($button.length).toBe(1); expect($button.prop("disabled")).toBeTruthy(); }); }); it("should mark the given extension for removal, hide the remove button, and show an undo link", function () { mockLoadExtensions(["user/mock-extension-3"]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { var $button = $("button.remove[data-extension-id=mock-extension-3]", view.$el); $button.click(); expect(ExtensionManager.isMarkedForRemoval("mock-extension-3")).toBe(true); var $undoLink = $("a.undo-remove[data-extension-id=mock-extension-3]", view.$el); expect($undoLink.length).toBe(1); $button = $("button.remove[data-extension-id=mock-extension-3]", view.$el); expect($button.length).toBe(0); }); }); it("should undo marking an extension for removal", function () { mockLoadExtensions(["user/mock-extension-3"]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { var $button = $("button.remove[data-extension-id=mock-extension-3]", view.$el); $button.click(); var $undoLink = $("a.undo-remove[data-extension-id=mock-extension-3]", view.$el); $undoLink.click(); expect(ExtensionManager.isMarkedForRemoval("mock-extension-3")).toBe(false); $button = $("button.remove[data-extension-id=mock-extension-3]", view.$el); expect($button.length).toBe(1); }); }); it("should mark a legacy extension for removal", function () { var id = "mock-legacy-extension"; mockLoadExtensions(["user/" + id]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { var mockPath = SpecRunnerUtils.getTestPath("/spec/ExtensionManager-test-files/user/" + id), $button = $("button.remove[data-extension-id='" + id + "']", view.$el); $button.click(); expect(ExtensionManager.isMarkedForRemoval(id)).toBe(true); }); }); it("should no longer show a fully removed extension", function () { mockLoadExtensions(["user/mock-extension-3", "user/mock-extension-4", "user/mock-legacy-extension"]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { expect(view).toHaveText("mock-extension-3"); waitsForDone(ExtensionManager.remove("mock-extension-3")); }); runs(function () { expect(view).not.toHaveText("mock-extension-3"); }); }); it("should mark the given extension for update, hide the remove button, and show an undo link", function () { var id = "mock-extension-3"; mockLoadExtensions(["user/" + id]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { ExtensionManager.updateFromDownload({ name: id, installationStatus: "NEEDS_UPDATE" }); expect(ExtensionManager.isMarkedForUpdate(id)).toBe(true); var $undoLink = $("a.undo-update[data-extension-id=" + id + "]", view.$el); expect($undoLink.length).toBe(1); var $button = $("button.remove[data-extension-id=" + id + "]", view.$el); expect($button.length).toBe(0); }); }); it("should undo marking an extension for update", function () { var id = "mock-extension-3", filename = "/path/to/downloaded/file.zip"; mockLoadExtensions(["user/" + id]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { ExtensionManager.updateFromDownload({ name: id, installationStatus: "NEEDS_UPDATE", localPath: filename }); spyOn(brackets.fs, "unlink"); var $undoLink = $("a.undo-update[data-extension-id=" + id + "]", view.$el); $undoLink.click(); expect(ExtensionManager.isMarkedForUpdate(id)).toBe(false); expect(brackets.fs.unlink).toHaveBeenCalledWith(filename, jasmine.any(Function)); var $button = $("button.remove[data-extension-id=" + id + "]", view.$el); expect($button.length).toBe(1); }); }); }); describe("ExtensionManagerDialog", function () { var dialogClassShown, dialogDeferred, didQuit; describe("_performChanges", function () { beforeEach(function () { // Mock popping up dialogs dialogClassShown = null; dialogDeferred = new $.Deferred(); spyOn(Dialogs, "showModalDialog").andCallFake(function (dlgClass, title, message) { dialogClassShown = dlgClass; // The test will resolve the promise. return dialogDeferred.promise(); }); // Mock quitting the app so we don't actually quit :) didQuit = false; spyOn(CommandManager, "execute").andCallFake(function (id) { if (id === Commands.FILE_QUIT) { didQuit = true; } else { CommandManager.execute.apply(this, arguments); } }); }); afterEach(function () { ExtensionManager._reset(); }); it("should not show a removal confirmation dialog if no extensions were removed", function () { mockLoadExtensions(["user/mock-extension-3"]); runs(function () { ExtensionManagerDialog._performChanges(); expect(dialogClassShown).toBeFalsy(); }); }); it("should not show a removal confirmation dialog if an extension was marked for removal and then unmarked", function () { mockLoadExtensions(["user/mock-extension-3"]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { var $button = $("button.remove[data-extension-id=mock-extension-3]", view.$el); $button.click(); var $undoLink = $("a.undo-remove[data-extension-id=mock-extension-3]", view.$el); $undoLink.click(); ExtensionManagerDialog._performChanges(); expect(dialogClassShown).toBeFalsy(); }); }); it("should show a removal confirmation dialog if an extension was removed", function () { mockLoadExtensions(["user/mock-extension-3"]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { var $button = $("button.remove[data-extension-id=mock-extension-3]", view.$el); $button.click(); }); runs(function () { // Don't expect the model to be disposed until after the dialog is dismissed. ExtensionManagerDialog._performChanges(); expect(dialogClassShown).toBe("change-marked-extensions"); dialogDeferred.resolve("cancel"); }); }); it("should remove extensions and quit if the user hits Remove and Quit on the removal confirmation dialog", function () { mockLoadExtensions(["user/mock-extension-3"]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { var $button = $("button.remove[data-extension-id=mock-extension-3]", view.$el); $button.click(); }); runs(function () { // Don't expect the model to be disposed until after the dialog is dismissed. ExtensionManagerDialog._performChanges(); dialogDeferred.resolve("ok"); }); waitsFor(function () { return didQuit; }, "mock quit"); runs(function () { var mockPath = SpecRunnerUtils.getTestPath("/spec/ExtensionManager-test-files"); expect(removedPath).toBe(mockPath + "/user/mock-extension-3"); expect(didQuit).toBe(true); }); }); it("should not remove extensions or quit if the user hits Cancel on the removal confirmation dialog", function () { mockLoadExtensions(["user/mock-extension-3"]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { var $button = $("button.remove[data-extension-id=mock-extension-3]", view.$el); $button.click(); }); runs(function () { // Don't expect the model to be disposed until after the dialog is dismissed. ExtensionManagerDialog._performChanges(); dialogDeferred.resolve("cancel"); expect(removedPath).toBeFalsy(); expect(ExtensionManager.isMarkedForRemoval("mock-extension-3")).toBe(false); expect(didQuit).toBe(false); }); }); it("should update extensions and quit if the user hits Update and Quit on the removal confirmation dialog", function () { var id = "mock-extension-3", filename = "/path/to/downloaded/mock-extension-3.zip"; mockLoadExtensions(["user/" + id]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); var installDeferred = $.Deferred(); spyOn(Package, "installUpdate").andReturn(installDeferred.promise()); runs(function () { ExtensionManager.updateFromDownload({ installationStatus: Package.InstallationStatuses.NEEDS_UPDATE, localPath: filename, name: id }); // Don't expect the model to be disposed until after the dialog is dismissed. ExtensionManagerDialog._performChanges(); dialogDeferred.resolve("ok"); installDeferred.resolve({ installationStatus: "INSTALLED" }); }); waitsFor(function () { return didQuit; }, "mock quit"); runs(function () { expect(Package.installUpdate).toHaveBeenCalledWith(filename, id); expect(didQuit).toBe(true); }); }); it("should not update extensions or quit if the user hits Cancel on the confirmation dialog", function () { var id = "mock-extension-3", filename = "/path/to/downloaded/file.zip"; mockLoadExtensions(["user/" + id]); setupViewWithMockData(ExtensionManagerViewModel.InstalledViewModel); runs(function () { ExtensionManager.updateFromDownload({ name: id, localPath: filename, installationStatus: Package.InstallationStatuses.NEEDS_UPDATE }); expect(ExtensionManager.isMarkedForUpdate(id)).toBe(true); spyOn(brackets.fs, "unlink"); // Don't expect the model to be disposed until after the dialog is dismissed. ExtensionManagerDialog._performChanges(); dialogDeferred.resolve("cancel"); expect(removedPath).toBeFalsy(); expect(ExtensionManager.isMarkedForUpdate("mock-extension-3")).toBe(false); expect(didQuit).toBe(false); expect(brackets.fs.unlink).toHaveBeenCalledWith(filename, jasmine.any(Function)); }); }); }); describe("initialization", function () { var dialog, $dlg, originalRegistry; // Sets up a view without actually loading any data--just for testing how we // respond to the notifications. beforeEach(function () { runs(function () { fakeLoadDeferred = new $.Deferred(); spyOn(ExtensionManager, "downloadRegistry").andCallFake(function () { return fakeLoadDeferred.promise(); }); }); }); afterEach(function () { runs(function () { dialog.close(); waitsForDone(dialog.getPromise(), "ExtensionManagerDialog.close"); }); runs(function () { brackets.config.extension_registry = originalRegistry; dialog = null; $dlg = null; }); }); function openDialog() { // this command is synchronous CommandManager.execute(Commands.FILE_EXTENSION_MANAGER) .done(function (dialogResult) { dialog = dialogResult; $dlg = dialog.getElement(); }); } function setRegistryURL(url) { originalRegistry = brackets.config.extension_registry; brackets.config.extension_registry = url; } it("should show the spinner before the registry appears successfully and hide it after", function () { runs(function () { openDialog(); expect($(".spinner", $dlg).length).toBe(1); fakeLoadDeferred.resolve(); expect($(".spinner", $dlg).length).toBe(0); }); }); it("should show an error and remove the spinner if there is an error fetching the registry", function () { runs(function () { openDialog(); fakeLoadDeferred.reject(); expect($(".spinner", $dlg).length).toBe(0); expect($("#registry .empty-message").text()).toBe(Strings.EXTENSION_MANAGER_ERROR_LOAD); }); }); it("should hide the registry tab when no URL is specified", function () { runs(function () { setRegistryURL(null); openDialog(); fakeLoadDeferred.resolve(); expect($(".registry", $dlg).length).toBe(0); }); }); it("should show the registry tab when a URL is specified", function () { runs(function () { setRegistryURL("not null"); openDialog(); fakeLoadDeferred.resolve(); expect($(".registry", $dlg).length).toBe(1); }); }); }); }); }); }); });
import React from 'react'; export default class Wait extends React.Component { render() { return ( <div> <h1>最近十个有新回复的请求</h1> <hr className="colorgraph" /> </div> ) } }
import { AttrAssembler } from './AttrAssembler' import { ChildNodeAssembler } from './ChildNodeAssembler' import { NodeAssembler } from './NodeAssembler' const { prototype : { map } } = Array const { MutationObserver, Node } = window const { ATTRIBUTE_NODE, DOCUMENT_FRAGMENT_NODE } = Node const { getNodeOf } = NodeAssembler const { flatten } = ChildNodeAssembler const CHILDREN_PROPERTY_NAME = 'children' const TYPE_FUNCTION = 'function' const TYPE_STRING = 'string' const key = Symbol() /** * @see https://www.w3.org/TR/dom/#interface-parentnode * @abstract */ export class ParentNodeAssembler extends ChildNodeAssembler { /** * Append child nodes to the node * @param {string|Node|ChildNodeAssembler|array|*} childNodes */ append(...childNodes) { const node = this.node flatten(childNodes).forEach(child => { if(child instanceof ChildNodeAssembler || child instanceof AttrAssembler) { const parentNode = child.node.parentNode if(parentNode && parentNode.nodeType === DOCUMENT_FRAGMENT_NODE) { node.append(parentNode) } else child.parentNode = node } else node.append(child) }) } /** * @param {ChildNodeAssembler|Node|*} object * @returns {boolean} */ contains(object) { return this.node.contains(getNodeOf(object)) } /** * @param {class|string|*} subject - ElementAssembler or AttrAssembler subclass or selector * @param {function} [subject.getAttrOf] * @param {function} [subject.getInstanceOf] * @param {function|string} [filter] * @returns {ElementAssembler|AttrAssembler|*|null} */ find(subject, filter) { const isString = typeof subject === TYPE_STRING if(typeof filter === TYPE_FUNCTION) { const instances = this.findAll(subject, filter) return instances[0] || null } let selector = isString? subject : subject.selector if(typeof filter === TYPE_STRING) { selector += filter } const node = this.node.querySelector(selector) if(node) { if(typeof subject.getAttrOf === TYPE_FUNCTION) { return subject.getAttrOf(node) } else { const assembler = isString? this.constructor.getAssemblerOf(node) : subject return assembler.getInstanceOf(node) } } return null } /** * @param {class|string|*} subject - ElementAssembler or AttrAssembler subclass or selector * @param {function} [subject.getAttrOf] * @param {function} [subject.getInstanceOf] * @param {function|string} [filter] * @returns {array.ElementAssembler|array.AttrAssembler|*} */ findAll(subject, filter) { const isString = typeof subject === TYPE_STRING let selector = isString? subject : subject.selector if(typeof filter === TYPE_STRING) { selector += filter } const nodeList = this.node.querySelectorAll(selector) const results = map.call(nodeList, node => { if(typeof subject.getAttrOf === TYPE_FUNCTION) { return subject.getAttrOf(node) } else { const assembler = isString? this.constructor.getAssemblerOf(node) : subject return assembler.getInstanceOf(node) } }) return typeof filter === TYPE_FUNCTION? results.filter(filter) : results } /** * Prepend child nodes to the node * @param {string|Node|ChildNodeAssembler|array|*} childNodes */ prepend(...childNodes) { this.node.prepend(...flatten(childNodes).map(child => { const node = getNodeOf(child) || child return node.nodeType === ATTRIBUTE_NODE? node.ownerElement : node })) } /** * @param {class|string} type * @param {function} callback * @param {{attributeOldValue,subtree}|{}|boolean|EventTargetAssembler|*} [options] */ on(type, callback, options) { if(typeof type === TYPE_FUNCTION && 'localName' in type) { const { context = this, subtree } = options = getOptions(options) const name = type.localName const storage = context[key] || (context[key] = { true : {}, false : {} }) const handlers = storage[Boolean(subtree)] const map = handlers[name] || (handlers[name] = new Map) if(!map.has(callback)) { const observer = new MutationObserver(records => { records.forEach(record => callback.call(context, record)) }) map.set(callback, observer) options.attributeFilter = [name] delete options.context observer.observe(this.node, options) } } else super.on(type, callback, options) } /** * @param {class|string} type * @param {function} callback * @param {{}|boolean|EventTargetAssembler|*} [options] */ un(type, callback, options) { if(typeof type === TYPE_FUNCTION && 'localName' in type) { const { context = this, subtree } = getOptions(options) const storage = context[key] const map = storage && storage[Boolean(subtree)][type.localName] const observer = map && map.get(callback) if(observer) { observer.takeRecords().forEach(record => callback.call(context, record)) observer.disconnect() map.delete(callback) } } else super.un(type, callback, options) } /** * Get an array of child nodes * @returns {*} {array} */ get childNodes() { return map.call(this.node.childNodes, node => this.getInstanceOf(node)) } /** * Append children to the element * @param {*} children */ set children(children) { if(this.node.hasChildNodes()) { Array.from(this.node.childNodes).forEach(child => child.remove()) } this.append(children) } /** * Get all children of the element as an array * @returns {ElementAssembler[]} */ get children() { return map.call(this.node.children, node => this.getInstanceOf(node)) } /** * @param {ChildNodeAssembler|ChildNode|*} firstChild */ set firstChild(firstChild) { this.prepend(firstChild) } /** * @returns {ChildNodeAssembler|*|null} */ get firstChild() { return this.getInstanceOf(this.node.firstChild) } /** * @returns {ElementAssembler|*|null} */ get firstElementChild() { return this.getInstanceOf(this.node.firstElementChild) } /** * @param {ChildNodeAssembler|ChildNode|*} lastChild */ set lastChild(lastChild) { this.append(lastChild) } /** * @returns {ChildNodeAssembler|*|null} */ get lastChild() { return this.getInstanceOf(this.node.lastChild) } /** * @returns {ChildNodeAssembler|*|null} */ get lastElementChild() { return this.getInstanceOf(this.node.lastElementChild) } /** * Set a text content of the node * @param {string} textContent */ set textContent(textContent) { this.node.textContent = textContent } /** * Get a text content of the node * @returns {string} */ get textContent() { return this.node.textContent } /** * @returns {string} * @override */ static get valuePropertyName() { return CHILDREN_PROPERTY_NAME } } /** * @param {{context,attributeOldValue,subtree}|ParentNodeAssembler|*} [options] * @param {ParentNodeAssembler|*} [options.context] * @param {boolean} [options.attributeOldValue] * @param {boolean} [options.subtree] * @returns {{context,attributeOldValue,subtree}} */ function getOptions(options) { const result = {} if(options) { if(options instanceof NodeAssembler) { result.context = options } else { result.context = options.context result.attributeOldValue = options.attributeOldValue || false result.subtree = options.subtree || false } } return result } ParentNodeAssembler.register()
/*global xAPS */ /** * The xAPS module for the Search page. * * Doesn't really do that much magical. * * Only thing that could make it hard to read is the references to $this.settings * It makes it easier to change settings without the need to skim the code. * * This module is initialized runtime and depends on a supplied url for the "add new parameter" on advanced mode. * * TEMPLATES * /WebContent/templates/search/ // Contains the index.ftl file and some other files that is included in index.ftl. * * @author Jarl Andre Hubenthal */ xAPS.createModule("search",function($this,$super,$){ /** * The configuration. */ $this.settings = { submit : { onchange : ".submitonchange" }, loading: { selector : "#loading_message", message : "Loading ..." }, addparameter: { input: "#addparameter", template: "#parametertemplate", url: null // REQUIRED, only supplied in advanced mode }, enable: { selector: ".enableOrDisable" } }; /** * The constructor. */ $this._initForm = function() { $($this.settings.defaultFormId).submit(function(){ $this.loading(); }); $($this.settings.submit.onchange).change(function(){ $super.submitForm(); }); var enableDisableCheckboxFunction = function(){ var isEnabled = $(this).data("enabled"); if(isEnabled){ if($(this).val()==""){ $(this).data("enabled",false); var radio = $(this).closest("tr").find("td input:checkbox[value='true']"); radio.attr("checked",false); } }else{ if($(this).val()!=""){ $(this).data("enabled",true); var radio = $(this).closest("tr").find("td input:checkbox[value='true']"); radio.attr("checked",true); } } }; $($this.settings.enable.selector).keyup(enableDisableCheckboxFunction); if($this.settings.addparameter.url){ $($this.settings.addparameter.input).autocomplete({ source: $this.settings.addparameter.url, minLength: 1, select: function(event,ui){ var selectedParameter = ui.item.value; var processed = $.jqote($this.settings.addparameter.template, {param: selectedParameter}); processed = $(processed); var tr = $($this.settings.addparameter.input).closest("tr"); tr.before(processed); ui.item.value = ""; processed.find("input:text").keyup(enableDisableCheckboxFunction); } }); } }; /** * Places the loading message in the loading selector. */ $this.loading = function() { $($this.settings.loading.selector).html($this.settings.loading.message); }; });
'use strict'; const crypto = require('crypto'); const rrange = 4294967296; /** * Return an integer, pseudo-random number in the range [0, 2^32). */ const nextInt = function() { return crypto.randomBytes(4).readUInt32BE(0); }; /** * Return a floating-point, pseudo-random number in the range [0, 1). */ const rand = function() { return nextInt() / rrange; }; /** * Return an integer, pseudo-random number in the range [0, max). */ exports.randInt = function(max) { return Math.floor(rand() * max); };
describe('Playlist Saver', function() { var scope, httpBackend, mockData, rootScope, iscope, UserPlaylists, ApiPlaylists, $q, PlaylistSaverSettings; var youtubeVideosMock = {}; var html = [ '<playlist-saver on-save="onSave()" on-cancel="onCancel()" tracks="playlist"></playlist-saver>' ]; function fakePromise () { var defer = $q.defer(); // defer.resolve(); // because there's a scope.apply in the controller // scope.$digest(); return defer; }; beforeEach(function(){ module('playlist.saver'); module('htmlTemplates'); module(function ($provide) { $provide.value('YoutubeApi', {}); }); inject(function($compile, $controller, $rootScope, $httpBackend, _UserPlaylists_, _ApiPlaylists_, _$q_, _PlaylistSaverSettings_){ rootScope = $rootScope; UserPlaylists = _UserPlaylists_; ApiPlaylists = _ApiPlaylists_; $q = _$q_; PlaylistSaverSettings = _PlaylistSaverSettings_; // spyOn(YoutubeSearch, 'search').and.returnValue(true); httpBackend = $httpBackend; scope = $rootScope.$new(); scope.onSave = angular.noop; scope.onCanel = angular.noop; scope.playlist = []; youtubeVideosMock = window.mocks['youtube.videos.mock']; element = angular.element(html.join('')); $compile(element)(scope); scope.$digest(); iscope = element.isolateScope(); }); }); describe('Playlist Saver Directive', function() { it('should render the playlist saver template', function() { expect(element.hasClass('playlist-saver')).toBeTruthy(); }); it('should display an input to enter the name of the playlist', function() { expect(element.find('input')).toBeTruthy(); }); it('should get a playlist array as an attribute', function() { expect(iscope.vm.tracks).toEqual(scope.playlist); }); it('should indicate the total number of videos to be added to the playlist', function() { var totalVideos = scope.playlist.length; scope.playlist.push(youtubeVideosMock.items[0]); scope.playlist.push(youtubeVideosMock.items[1]); scope.$digest(); expect(element.find('.title').text()).toContain('2'); }); it('should show animated icon on save button after click', function(done) { spyOn(PlaylistSaverSettings, 'save').and.callFake(function () { var defer = $q.defer(); defer.resolve(); scope.$digest(); return defer.promise; }); iscope.vm.save(); expect(element.find('.btn-save .fa').hasClass('ng-hide')).toBeFalsy(); done(); }); // PlaylistSaverSettings Service it('should reset the playlist saver settings meta data after save', function(done) { // mock ApiPlaylists.insert -> return promise var defer1 = $q.defer(); var defer2 = $q.defer(); spyOn(ApiPlaylists, 'insert').and.callFake(function () { // defer1.resolve(); return defer1.promise; }); // mock UserPlaylists.addToPlaylist -> return promise spyOn(UserPlaylists, 'addToPlaylist').and.callFake(function () { // defer2 = $q.defer(); return defer2.promise; }); // check playlist{} has been cleaned // so => PlaylistSaverSettings.save().then -> should reset playlist var tracks = youtubeVideosMock.items.slice(0,1); PlaylistSaverSettings.save(tracks); setTimeout(function () { defer1.resolve({ result: 1}); defer2.resolve({ result: 1}); // run digest cycle to apply promises scope.$digest(); expect(ApiPlaylists.insert).toHaveBeenCalled(); expect(UserPlaylists.addToPlaylist).toHaveBeenCalled(); var playlist = PlaylistSaverSettings.playlist; expect(PlaylistSaverSettings.playlist.id).toBe(''); expect(PlaylistSaverSettings.playlist.title).toBe(''); expect(PlaylistSaverSettings.playlist.description).toBe(''); done(); }, 0); }); }); });
'use strict'; angular.module('wanderlustApp') .factory('getUser', function($http){ return{ getData: function(userId, callback){ return $http({ method: 'GET', url: '/api/user/'+userId }).success(function(data){ callback(data); }); } }; }) .controller('UserCtrl', function ($scope, User, Auth, getUser, $stateParams) { var calculatePercentage = function(earned, total){ return total !==0 ? Math.round((earned/total) * 100): 0; }; //get user data from server getUser.getData($stateParams.userId, function(data){ console.log(data); $scope.user = data; $scope.user.percentComplete = calculatePercentage($scope.user.profile.xp, $scope.user.xpneeded); }); });
/** * Exports functions to observe an object for changes. Does not follow the now defunct Object.observe API. * * @module Grue/core/Observe * @author Noah Feldman <nfeldman@nsfdev.com> * @copyright 2012-2016 */ /** * @fileOverview * * This is an experiment to see if there is a reasonably efficient way to create a simple observable object from a * plain javascript object. Given an object, it returns an observable that acts as a proxy for that object. Getting * and setting properties on the returned observable will pass through to the same properties of the observed, provided * those properties existed at the time #observe was first called. One or more subscribers is notified each time one of * these properties changes. If the property is a function, subscribers are notified that the function has been called * and the arguments with which it was called. Properties of Object properties are subscribed to automatically, as are * properties of Array properties. Individual array values are not converted to observables, meaning changes to an * object within an array of objects will not cause subscribers to array changes to be notified. * * For selectively observing a small subset of properties on an object, it may be more convenient to use * Grue/core/Eventing/EventEmitter#before or Grue/core/Eventing/EventEmitter#after * * TODO Benchmark this vs something like dirty checking. */ var randStr = require('./randStr'), GrueSymbol = require('./GrueSymbol'), grueId = GrueSymbol.for('grue_id'), obsId = GrueSymbol.for('obs_id'), obsTarget = GrueSymbol.for('obs_target'), obsList = GrueSymbol.for('obs_list'), obsOwner = GrueSymbol.for('obs_owner'), each = require('./each'), eachInRange = require('./eachInRange'), copy = require('./copy'), mix = require('./mix'), hasOwn = Function.prototype.call.bind({}.hasOwnProperty), toStr = Function.prototype.call.bind({}.toString), arrayProps = Object.getOwnPropertyNames(Array.prototype).filter(function (name) {return name != 'constructor'}), proxyArrayProto = Object.create(null), regisitry = Object.create(null); // set up the prototype for all array proxy objects each(arrayProps, function (prop) { if (typeof [][prop] == 'function') { this[prop] = function () { var prev = this[obsTarget].slice(0), args = [], prevLength = prev.length, ret, currLength; for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); ret = [][prop].apply(this[obsTarget], arguments); currLength = this[obsTarget].length; updateArrayProxy(this); notify(this[obsList], prop, 'call', { type: 'arrayMethod', name: prop, prev: prev, args: args, curr: this[obsTarget].slice(0) }); prevLength != currLength && notify(this[obsList], 'length', 'change', { type: 'literalProperty', name: 'length', prev: prevLength, curr: currLength }); return ret; }; } else { Object.defineProperty(this, prop, { get: function () { return this[obsTarget][prop]; }, set: function (value) { var prev = this[obsTarget][prop]; this[obsTarget][prop] = value; notify(this[obsList], prop, 'change', { type: 'literalProperty', name: prop, prev: prev, curr: value }); } }); } }, proxyArrayProto); // The tricky part of this is dealing with arrays. function updateArrayProxy (proxy) { eachInRange(0, proxy.length, function (i) { Object.defineProperty(proxy, i, { get: function () { return proxy[obsTarget][i]; }, set: function (curr) { var prev = proxy[obsTarget][i]; proxy[obsTarget][i] = prev; notify(proxy[obsList], i, 'change', { index: i, prev: prev, curr: curr, type: 'arrayValue' }); }, configurable: true }); }); } /** * Observe changes in an object. Returns a "proxy" object, setting existing properties on * it will cause the property on the underlying object to be set. #observe may be applied * to the object returned by an initial call to #observe in order to observe properties * added after the first call. * * @param {Object} object The object to observe. * @param {Function} [callback] A fnction called whenever any property changes. * @return {Object} A proxy object with the same properties as the original and an addition "observe" method. * Calling proxy.observe([property,] callback) adds the callback to the collection of functions * called whenever either the specified property or, if no property is supplied, any property of * the observable is changed or invoked, in the case of function properties. */ exports.getObservable = function (object, callback) { return observe(object, callback); }; /** * Observe changes in an object. Returns a "proxy" object, setting existing properties on * it will cause the property on the underlying object to be set. #observe may be applied * to the object returned by an initial call to #observe in order to observe properties * added after the first call. * * @param {Object} object The object to observe. * @param {string} [property] A specific property of the object, if used, a callback must be provided * @param {Function} [callback] Function called whenever a property changes, * if no property name is provided, will be called * when any property changes. * @return {Object} A proxy object. * @private */ function observe (object, property, callback) { if (typeof object != 'object') throw new TypeError('observe cannot be applied to type ' + toStr(object).slice(8, -1) + '.'); if (Object.isFrozen && Object.isFrozen(object)) throw new Error('Cannot observe changes in frozen objects.'); var id = object[grueId] || object[obsId] || (Object.defineProperty(object, obsId, { value: randStr(8, 'ob'), writable: true, configurable: true }), object[obsId]), observed = regisitry[id] || (regisitry[id] = Object.create(null)), observers = observed.observers || (observed.observers = Object.create(null)), original = observed.original || (observed.original = object), proxy; if (observed.proxy) { proxy = observed.proxy; } else { proxy = (Array.isArray(object) && (observed.proxy = Object.create(proxyArrayProto, (function () { var properties = {observe: {value: obFn}}; properties[grueId in object ? grueId : obsId] = {value: id}; properties[obsList] = {value: observers}; properties[obsTarget] = {value: object}; return properties; }()))) || (observed.proxy = (object[grueId] || object[obsId]) ? Object.create(object, {observe: {value: obFn}}) : Object.create(object, (function() { var properties = {observe: {value: obFn}}; properties[grueId in object ? grueId : obsId] = {value: id}; return properties; }())))); if (Array.isArray(object)) updateArrayProxy(proxy); } if (!callback && typeof property == 'function') { callback = property; property = null; if (!observers.__grue_all) observers.__grue_all = []; observers.__grue_all.push(callback); if (!Array.isArray(original)) { each(original, function (v, k) { defineObservedProperty.call(proxy, k, original, observers); }); } } else if (typeof property == 'string') { defineObservedProperty.call(proxy, property, original, observers); !observers[property] && (observers[property] = []); observers[property].push(callback); } return proxy; }; /** * Returns an object that had been observed and attempts to cleanup. * @param {Object} object A proxy object returned by `observe` * @return {Object} The original object that was being observed. */ exports.unobserve = function (object) { var id = object[grueId] || object[obsId], original = id && regisitry[id] && regisitry[id].original; if (!original) { console.warn('trying to unobserve object that was not under observation.'); return object; } // Before we delete the proxy, copy any properties found in it that do not exist in the original. mix({deep: true, source: regisitry[id].proxy, target: original, skipNonEnumerable: true}); each(regisitry[id].observers, function (value, key) { delete regisitry[id].observers[key]; }); setImmediate(function () {delete regisitry[id]}); return original; }; /** @private */ function defineObservedProperty (prop, original, observers) { if (hasOwn(this, prop)) return; var id, observed, observeProp; if (typeof original[prop] == 'object') { // JS collections id = original[grueId] || original[obsId]; observed = regisitry[id]; if (Array.isArray(original[prop])) { observeProp = function () { observed[prop] = observe(original[prop], function (name, detail) { var msg = copy(detail); msg.name = prop + (detail.name ? '.' + detail.name : '[' + detail.index + ']'); notify(observers, prop, name, msg); }); }; observeProp(); Object.defineProperty(this, prop, { get: function () { return observed[prop]; }, set: function (value) { var prev = original[prop]; original[prop] = value; observeProp(); notify(observers, prop, 'change', { type: 'arrayProperty', name: prop, prev: prev, curr: value }); }, configurable: true }); } else { observeProp = function () { observed[prop] = observe(original[prop], function (name, detail) { var event = prop + '.' + detail.name, msg = { type: 'objectProperty', name: event, prev: detail.prev, curr: detail.curr }; notify(observers, prop, 'change', msg); notify(observers, event, 'change', msg, true); }); } observeProp(); Object.defineProperty(this, prop, { get: function () { return observed[prop]; }, set: function (value) { var prev = original[prop]; original[prop] = value; observeProp(); notify(observers, prop, 'change', { type: 'objectProperty', name: prop, prev: prev, curr: value }); }, configurable: true }); } } else if (typeof original[prop] == 'function') { // shrug this[prop] = function () { var args = []; for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); original[prop].apply(original, arguments); notify(observers, prop, 'call', { type: 'functionProperty', name: prop, args: args }); }; } else { // literal values Object.defineProperty(this, prop, { get: function () { return original[prop]; }, set: function (value) { var prev = original[prop]; original[prop] = value; notify(observers, prop, 'change', { type: 'literalProperty', name: prop, prev: prev, curr: value }); } }); } } /** @private */ function notify (observers, property, eventName, eventDetail, onlyDirectListeners) { if (!(observers[property] && observers[property].length || observers.__grue_all && observers.__grue_all.length)) return; for (var i = 0, l = observers[property] && observers[property].length || 0; i < l; i++) observers[property][i](eventName, eventDetail); if (!onlyDirectListeners && observers.__grue_all && observers.__grue_all.length) for (var i = 0, l = observers.__grue_all.length; i < l; i++) observers.__grue_all[i](eventName, eventDetail); } // -- helper -- generic method applied by the proxy objects the observe // function creates. /** @private */ function obFn (property, callback) { observe(this, property, callback); return this; }
var adapter = require("builder-docs-archetype-dev/spec-setup").adapter; var expect = require("chai").expect; var routes = require("../../../static-routes"); var validateRelative = function (abs) { // check if link belongs to our app if (abs.indexOf(global.TEST_FUNC_BASE_URL) === 0) { // strip base url out var rel = abs.substr(global.TEST_FUNC_BASE_URL.length); // strip query/hash out rel = rel.split(/[?#]/)[0]; // throw a helpful error if it's not in static-routes if (routes.indexOf(rel) < 0) { throw new Error(rel + " not a valid relative link"); } } }; describe("About", function () { it("should render a page with proper title", function () { return adapter.client .url("/about/") .getTitle().then(function (title) { expect(title).to.eq("Spectacle | About"); }); }); }); describe("Docs", function () { it("should render a page with proper title", function () { return adapter.client .url("/docs/") .getTitle().then(function (title) { expect(title).to.eq("Spectacle | Documentation"); }); }); // Render every static route routes.forEach(function (r) { describe("Route " + r, function () { it("should render with no broken links", function () { return adapter.client .url(r) .elements("#content").then(function (res) { expect(res.value.length).to.eq(1); // Not a 404 }) // find every link .getAttribute("a[href]", "href").then(function (urls) { urls.forEach(validateRelative); }); }); }); }); });
var TankGame = TankGame || {}; TankGame.Howtoplay = function(){}; var gameFieldX = (window.innerWidth-(61*15))/2; var gameFieldY = (window.innerHeight-(61*10))/2; var instrStyle = {font: "16px Arial", fill: "#ffffff"}; TankGame.Howtoplay.prototype = { create: function() { var instructionText = "There are two players in this game. The task is to destroy the enemy's base and \nsave your own base from destruction. \n\nFirst, you have to chose where your unit (soldier, tank, ninja...) will go. It will be\nplaced wherever the yellow-glowing border is. Player 1 can change its position \nusing W and S keys and Player 2 shall use Arrow up (⬆️) and Arrow down (⬇️).\nThen you can choose what will you place there. You can do that by pressing \nthe corresponding number key. Player 1 uses standart number keys (above the letters) \nand Player 2 uses numpad number keys (on the right of the letters). You can \nsee which number corresponds to which unit by looking at the little cards \nnext to the battleground. There you can also see the price."; var textSprite = this.game.add.text(window.innerWidth/2,window.innerHeight/2,instructionText,instrStyle); textSprite.anchor.setTo(0.5); backbtn = this.game.add.button(centerX, centerY+200, 'back_btn', function(){ this.state.start('Menu'); }, this); backbtn.height = 30; backbtn.width = 100; backbtn.anchor.setTo(0.5); backbtn.onInputOver.add(function(){ backbtn.loadTexture('back_btn_hover'); }, this); backbtn.onInputOut.add(function(){ backbtn.loadTexture('back_btn'); }, this); this.cat = this.game.add.sprite(0,gameFieldY+(61*10)-30,'gunman_walk'); var walk =this.cat.animations.add('walk'); this.cat.animations.play('walk',8,true); this.cat2 = this.game.add.sprite(50,gameFieldY+(61*10)-30,'gunman_walk_blue'); var walk2 =this.cat2.animations.add('walk2'); this.cat2.animations.play('walk2',7,true); game_logo = this.game.add.sprite(window.innerWidth/2,10,'game_logo_moving'); game_logo.anchor.setTo(0.5,0); var move = game_logo.animations.add('move'); game_logo.animations.play('move',20,true); }, update: function() { if(this.cat.position.x<window.innerWidth)this.cat.position.x+=1.8; else this.cat.position.x = -15; if(this.cat2.position.x<window.innerWidth)this.cat2.position.x+=2; else this.cat2.position.x = -15; }, };
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var messages_1 = require("./messages"); var kendo_angular_l10n_1 = require("@progress/kendo-angular-l10n"); /** * Custom component messages override default component messages. */ var CustomMessagesComponent = (function (_super) { __extends(CustomMessagesComponent, _super); function CustomMessagesComponent(service) { var _this = _super.call(this) || this; _this.service = service; return _this; } Object.defineProperty(CustomMessagesComponent.prototype, "override", { get: function () { return true; }, enumerable: true, configurable: true }); return CustomMessagesComponent; }(messages_1.Messages)); CustomMessagesComponent.decorators = [ { type: core_1.Component, args: [{ providers: [ { provide: messages_1.Messages, useExisting: core_1.forwardRef(function () { return CustomMessagesComponent; }) // tslint:disable-line:no-forward-ref } ], selector: 'kendo-upload-messages', template: "" },] }, ]; /** @nocollapse */ CustomMessagesComponent.ctorParameters = function () { return [ { type: kendo_angular_l10n_1.LocalizationService, }, ]; }; exports.CustomMessagesComponent = CustomMessagesComponent;
import React from 'react' import { withReflex } from '../../src' const script = ` !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?"http":"https";if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document, "script", "twitter-wjs"); ` const TweetButton = ({ text, url, via, ...props }) => ( <div {...props}> <div style={{ height: 20 }}> <a href='https://twitter.com/share' className='twitter-share-button' data-text={text} data-url={url} data-via={via} children='Tweet' /> <script dangerouslySetInnerHTML={{ __html: script }} /> </div> </div> ) TweetButton.defaultProps = { text: '', url: 'http://jxnblk.com/reflexbox', via: 'jxnblk' } export default withReflex()(TweetButton)
/* * Kendo UI Web v2012.2.710 (http://kendoui.com) * Copyright 2012 Telerik AD. All rights reserved. * * Kendo UI Web commercial licenses may be obtained at http://kendoui.com/web-license * If you do not own a commercial license, this file shall be governed by the * GNU General Public License (GPL) version 3. * For GPL requirements, please review: http://www.gnu.org/copyleft/gpl.html */ (function($, undefined) { var kendo = window.kendo, ui = kendo.ui, Widget = ui.Widget, extend = $.extend, isFunction = $.isFunction, isPlainObject = $.isPlainObject, inArray = $.inArray, ERRORTEMPLATE = '<div class="k-widget k-tooltip k-tooltip-validation" style="margin:0.5em"><span class="k-icon k-warning"> </span>' + '${message}<div class="k-callout k-callout-n"></div></div>', CHANGE = "change"; var specialRules = ["url", "email", "number", "date", "boolean"]; function fieldType(field) { field = field != null ? field : ""; return field.type || $.type(field) || "string"; } function convertToValueBinding(container) { container.find(":input:not(:button, [" + kendo.attr("role") + "=upload], [" + kendo.attr("skip") + "]), select").each(function() { var bindAttr = kendo.attr("bind"), binding = this.getAttribute(bindAttr) || "", bindingName = this.type === "checkbox" ? "checked:" : "value:", fieldName = this.name; if (binding.indexOf(bindingName) === -1 && fieldName) { binding += (binding.length ? "," : "") + bindingName + fieldName; $(this).attr(bindAttr, binding); } }); } function createAttributes(options) { var field = (options.model.fields || options.model)[options.field], type = fieldType(field), validation = field ? field.validation : {}, ruleName, DATATYPE = kendo.attr("type"), BINDING = kendo.attr("bind"), rule, attr = { name: options.field }; for (ruleName in validation) { rule = validation[ruleName]; if (inArray(ruleName, specialRules) >= 0) { attr[DATATYPE] = ruleName; } else if (!isFunction(rule)) { attr[ruleName] = isPlainObject(rule) ? rule.value || ruleName : rule; } attr[kendo.attr(ruleName + "-msg")] = rule.message; } if (inArray(type, specialRules) >= 0) { attr[DATATYPE] = type; } attr[BINDING] = (type === "boolean" ? "checked:" : "value:") + options.field; return attr; } function convertItems(items) { var idx, length, item, value, text, result; if (items && items.length) { result = []; for (idx = 0, length = items.length; idx < length; idx++) { item = items[idx]; text = item.text || item.value || item; value = item.value == null ? (item.text || item) : item.value; result[idx] = { text: text, value: value }; } } return result; } var editors = { "number": function(container, options) { var attr = createAttributes(options); $('<input type="text"/>').attr(attr).appendTo(container).kendoNumericTextBox({ format: options.format }); $('<span ' + kendo.attr("for") + '="' + options.field + '" class="k-invalid-msg"/>').hide().appendTo(container); }, "date": function(container, options) { var attr = createAttributes(options); attr[kendo.attr("format")] = options.format; $('<input type="text"/>').attr(attr).appendTo(container).kendoDatePicker({ format: options.format }); $('<span ' + kendo.attr("for") + '="' + options.field + '" class="k-invalid-msg"/>').hide().appendTo(container); }, "string": function(container, options) { var attr = createAttributes(options); $('<input type="text" class="k-input k-textbox"/>').attr(attr).appendTo(container); }, "boolean": function(container, options) { var attr = createAttributes(options); $('<input type="checkbox" />').attr(attr).appendTo(container); }, "values": function(container, options) { var attr = createAttributes(options); $('<select ' + kendo.attr("text-field") + '="text"' + kendo.attr("value-field") + '="value"' + kendo.attr("source") + "=\'" + kendo.stringify(convertItems(options.values)) + "\'" + kendo.attr("role") + '="dropdownlist"/>') .attr(attr).appendTo(container); $('<span ' + kendo.attr("for") + '="' + options.field + '" class="k-invalid-msg"/>').hide().appendTo(container); } }; var Editable = Widget.extend({ init: function(element, options) { var that = this; Widget.fn.init.call(that, element, options); that._validateProxy = $.proxy(that._validate, that); that.refresh(); }, events: [CHANGE], options: { name: "Editable", editors: editors, clearContainer: true, errorTemplate: ERRORTEMPLATE }, editor: function(field, modelField) { var that = this, editors = that.options.editors, isObject = isPlainObject(field), fieldName = isObject ? field.field : field, model = that.options.model || {}, isValuesEditor = isObject && field.values, type = isValuesEditor ? "values" : fieldType(modelField), isCustomEditor = isObject && field.editor, editor = isCustomEditor ? field.editor : editors[type], container = that.element.find("[data-container-for=" + fieldName + "]"); editor = editor ? editor : editors["string"]; if (isCustomEditor && typeof field.editor === "string") { editor = function(container) { container.append(field.editor); }; } container = container.length ? container : that.element; editor(container, extend(true, {}, isObject ? field : { field: fieldName }, { model: model })); }, _validate: function(e) { var that = this, isBoolean = typeof e.value === "boolean", input, preventChangeTrigger = that._validationEventInProgress, values = {}; values[e.field] = e.value; input = $(':input[' + kendo.attr("bind") + '="' + (isBoolean ? 'checked:' : 'value:') + e.field + '"]', that.element); try { that._validationEventInProgress = true; if (!that.validatable.validateInput(input) || (!preventChangeTrigger && that.trigger(CHANGE, { values: values }))) { e.preventDefault(); } } finally { that._validationEventInProgress = false; } }, end: function() { return this.validatable.validate(); }, destroy: function() { this.options.model.unbind("set", this._validateProxy); kendo.unbind(this.element); this.element.removeData("kendoValidator") .removeData("kendoEditable"); }, refresh: function() { var that = this, idx, length, fields = that.options.fields || [], container = that.options.clearContainer ? that.element.empty() : that.element, model = that.options.model || {}, rules = {}; if (!$.isArray(fields)) { fields = [fields]; } for (idx = 0, length = fields.length; idx < length; idx++) { var field = fields[idx], isObject = isPlainObject(field), fieldName = isObject ? field.field : field, modelField = (model.fields || model)[fieldName], validation = modelField ? (modelField.validation || {}) : {}; for (var rule in validation) { if (isFunction(validation[rule])) { rules[rule] = validation[rule]; } } that.editor(field, modelField); } convertToValueBinding(container); kendo.bind(container, that.options.model); that.options.model.bind("set", that._validateProxy); that.validatable = container.kendoValidator({ validateOnBlur: false, errorTemplate: that.options.errorTemplate || undefined, rules: rules }).data("kendoValidator"); container.find(":input:visible:first").focus(); } }); ui.plugin(Editable); })(jQuery); ;
define([], function(){ return function (path,speed,trans) { var length = path.getTotalLength(); trans = typeof trans !== 'undefined' && trans !== '' ? trans : speed; path.style.transition = path.style.WebkitTransition = 'none'; path.style.strokeDasharray = length + ' ' + length; path.style.strokeDashoffset = length; path.getBoundingClientRect(); path.style.transition = path.style.WebkitTransition = 'stroke-dashoffset '+speed+' ease-in, fill '+trans+', stroke '+trans; path.style.strokeDashoffset = '0'; setTimeout(function(){ path.classList.add('done'); },speed); }; });
/*jslint nomen: true*/ /*global Backbone,_,$,L,waze */ /*jslint browser: true*/ if (typeof waze === "undefined") { var waze = {}; } waze.map = (function () { 'use strict'; var Notification, NotificationList, MapModel, NotificationView, NotificationListView, NotificationListCounterView, MapView, DebugView, M; // I'll use this to keep track of notifications that were expanded. // this is necessary because the notification list in re-rendered upon map refresh , so // if a notification was expanded it would collapse it. var expandedNotifications = {}; /*** MODELS ***/ Notification = Backbone.Model.extend(); // Overiding Backbone's reset method, because by default it doesnt fire remove events for the removed models NotificationList = Backbone.Collection.extend({ reset: function (models, options) { var i, l; models = models || []; options = options || {}; for (i = 0, l = this.models.length; i < l; i = i + 1) { this._removeReference(this.models[i]); this.models[i].trigger('remove', this.models[i], this); // This is the line I needed to add } this._reset(); this.add(models, _.extend({silent: true}, options)); if (!options.silent) { this.trigger('reset', this, options); } return this; } }); MapModel = Backbone.Model.extend(); /*** Views ***/ NotificationView = Backbone.View.extend({ tagName: 'li', template: _.template($('#notificationTemplate').html()), // using underscore micro templating engine events: { 'click .title button' : 'toggleNotification', 'click button.edit' : 'launchPopup' }, /* Sets the form fields on the popup accrding to the notification */ modelToForm: function ($form, notification) { $form.find('.lon').data('lon', notification.get('lon')); $form.find('.lon').text(parseFloat(notification.escape('lon')).toFixed(4)); $form.find('.lat').data('lat', notification.get('lat')); $form.find('.lat').text(parseFloat(notification.escape('lat')).toFixed(4)); $form.find('.description').val(notification.escape('description')); $form.find('.title').val(notification.escape('title')); $form.find('.vote-up').text(notification.get('votes_up')); }, /* ... and the other way around */ formToModel: function ($form, notification) { notification.set('lon', $form.find('.lon').data('lon')); notification.set('lat', $form.find('.lat').data('lat')); notification.set('description', $form.find('.description').val()); notification.set('title', $form.find('.title').val()); }, initialize: function () { this.listenTo(this.model, 'destroy', this.destroyNotification); this.listenTo(this.model, 'change', this.render); this.listenTo(this.model, 'remove', this.remove); }, render: function () { var params = this.model.toJSON(); params.lat = params.lat.toFixed(4); params.lon = params.lon.toFixed(4); this.$el.html(this.template(params)); // this notificatio was expanded before the maps refresh, so we'll re-display it. if (expandedNotifications[this.model.id] === true) { this.$el.find('.more-details').removeClass('hidden'); } return this; }, remove: function () { // This fixes a problem where the notification is removed for unsaved notification, if the popup causes the map to refresh // when it chnages the bounds if (!this.model.isNew()) { this.$el.remove(); M.removeLayer(this.marker); } }, toggleNotification : function () { this.$('.more-details').toggleClass('hidden'); this.$('.title button').toggleClass('expanded'); if (!this.$('.more-details').hasClass('hidden')) { expandedNotifications[this.model.id] = true; // notification was expanded } else { delete expandedNotifications[this.model.id]; // notification was collapsed, we'll delete it } }, // This will handle placing the marker on the map renderMarker : function () { var that = this, notification = this.model, options = { riseOnHover : true }; // Create a new marker and add it to the map. Bind a popup to be opened when a user clicks on the marker. this.marker = L.marker([notification.get('lat'), notification.get('lon')], options); this.marker.addTo(M); // Here we'll use a template from the html that's under this.marker.bindPopup($('#notificationPopupTemplate').html(), { keepInView : true }); // This will handle the behavior when the popup opens on the map this.marker.on('popupopen', function (event) { M.popupOpen = true; var $form = $('form.notification-popup'); that.modelToForm($form, notification); $form.submit(function (event) { event.preventDefault(); that.formToModel($form, notification); notification.save({}, { url : '/notifications' + (notification.isNew() ? '' : '/' + notification.get('id')), success : function () { $form.addClass('success'); setTimeout(function () { // we'll display a success message and close the popup that.marker.closePopup(); M.popupOpen = false; }, 1000); }, error : function () { $form.addClass('error'); } }); }); that.registerUpVote($form); //here we'll registert the bevior when cliking the 'vote up' button // we can't use notification.save - see the doc $form.find('button.delete').click(function (event) { event.preventDefault(); notification.destroy({ url : '/notifications/' + notification.get('id'), success : function () { M.popupOpen = false; } }); }); }); if (this.model.isNew()) { // if this is a new notification, we'll open the popup right away this.marker.openPopup(); } }, // This will execute when the user clicks the edit button in the notification list launchPopup: function () { var notification = this.model, that = this; // We'll use bpopup to show a simple modal $('div.popup').bPopup({ onOpen : function () { var $form = $('form.notification-edit-popup'); that.modelToForm($form, notification); //We unserialize the model to the form // user clicks save $form.submit(function (event) { event.preventDefault(); that.formToModel($form, notification); // when user submits, serialize the form input to the model and save it notification.save({}, { url : '/notifications' + (notification.isNew() ? '' : '/' + notification.get('id')), success : function () { $form.addClass('success'); setTimeout(function () { $('div.popup').bPopup().close(); }, 1000); }, error : function () { $form.addClass('error'); } }); }); that.registerUpVote($form); //here we'll registert the bevior when cliking the 'vote up' button // we can't use notification.save - see the doc // we need to stop the event - otherwise the form will submit $form.find('.closebutton').click(function (event) { event.preventDefault(); event.stopPropagation(); }); // user clicks delete $form.find('button.delete').click(function (event) { event.preventDefault(); notification.destroy({ url : '/notifications/' + notification.get('id'), success : function () { $('div.popup').bPopup().close(); } }); }); $form.find("input[type=text]").first().focus(); }, //parameter to bpopup. Clicking on elements with this class name will close it. closeClass : 'close' }); }, registerUpVote : function ($form) { var notification = this.model; $form.find('.vote-up').click(function (event) { event.preventDefault(); event.stopPropagation(); $.ajax({ url : '/notifications/' + notification.get('id') + '/upvote.json', type: 'PUT', cache: false, success : function () { var votes_up = notification.get('votes_up'); votes_up = votes_up + 1; $('button.vote-up').text(votes_up); // while it's true that we can't use notification.save to save the notification to the server, // we can at least set the votes_property to trigger change event for element that are listening notification.set('votes_up', votes_up); } }); }); }, destroyNotification : function () { this.$el.remove(); M.removeLayer(this.marker); // this removes the marker from the map delete expandedNotifications[this.model.id]; } }); NotificationListView = Backbone.View.extend({ el: $('ul.notification-list'), initialize: function () { this.listenTo(this.collection, 'add', this.addOne); this.listenTo(this.collection, 'reset', this.addAll); }, addOne: function (notification) { var index = this.collection.indexOf(notification), view = new NotificationView({ model: notification}); view.renderMarker(); //index is the index of the element that was added. We need to add it in the correct place in the list. if (index === 0) { // it's going to be the first one... this.$el.append(view.render().el); } else { // if note, we'll get the element at index index - 1 and add it after. index = index - 1; this.$el.find(">li:eq(" + index + ")").after(view.render().el); } }, addAll: function () { this.collection.each(this.addOne, this); } }); NotificationListCounterView = Backbone.View.extend({ el: $('div.notification-list-counter span.notifications-displayed'), initialize: function () { this.listenTo(this.collection, 'all', this.updateCounter); }, updateCounter : function () { var size = this.collection.size(); this.$el.text(size); updateAllNotificationsCount(size); } }); MapView = Backbone.View.extend({ initialize: function () { var that = this, bounds; // This is where the notification is actually created. Note that in this point it isn't save yet. M.on('click', function (e) { var notification = new Notification({lon : e.latlng.lng, lat : e.latlng.lat, title : 'untitled', description : '', votes_up : 0}); that.collection.add(notification); }); M.on('viewreset moveend', function () { // when the map moves , the markers will redrow. So we'll block this from happening when a dialog is open // there is minor issue here, as some notification might not be seen immediatley. if (!M.popupOpen) { that.refreshBounds(); } }); // this will fire when the user enters the center manually in the debug form this.listenTo(this.model, 'change:center', this.panMap); }, panMap: function () { M.panTo(this.model.get('center')); }, refreshBounds : function () { this.model.set(getBounds()); } }); DebugView = Backbone.View.extend({ el: $('#debugInfo'), initialize: function () { this.listenTo(this.model, 'change', this.update); }, update : function (model) { var that = this; _.each(['west', 'east', 'north', 'south'], function (el) { that.$("." + el).text(model.get(el).toFixed(4)); }); }, events: { 'click button' : 'centerButtonClicked' }, centerButtonClicked: function () { this.model.set('center', [this.$("#lat").val(), this.$("#lon").val()]); } }); // This s where everything starts... function _init() { var notifications, counterView, debugView, mapModel, mapView, app; // fetch notification list from server // parameter reset is a boolean function fetch(reset) { notifications.fetch({reset: reset, url: ["notifications?west=", mapModel.get('west'), "&east=", mapModel.get('east'), "&north=", mapModel.get('north'), "&south=", mapModel.get('south')].join("")}); } notifications = new NotificationList(); notifications.comparator = function (first, second) { // This suppose to find which of the 2 points is closer to the center var s = Math.sqrt, center = getBounds().center, centerLat = center.lat, centerLon = center.lng, firstLat = first.get('lat'), firstLon = first.get('lon'), secondLat = second.get('lat'), secondLon = second.get('lon'), firstDisance, secondDistance, p; // p is just a function that takes a number return its power of 2 // just to make code more readable p = (function () { return function (x) { return Math.pow(x, 2); }; }()); firstDisance = s(p(firstLat - centerLat) + p(firstLon - centerLon)); secondDistance = s(p(secondLat - centerLat) + p(secondLon - centerLon)); if (firstDisance < secondDistance) { return -1; } if (firstDisance > secondDistance) { return 1; } return 0; }; mapModel = new MapModel(getBounds()); //setting the initial state of the map model mapModel.on("change", function () { // if the map moves, we'll re-fetch the notification list fetch(true); }); mapView = new MapView({ collection : notifications, model : mapModel}); app = new NotificationListView({ collection : notifications}); counterView = new NotificationListCounterView({ collection : notifications}); debugView = new DebugView({ model : mapModel }); fetch(true); // Get the initial list // Polling logic setInterval(function () { if (!M.popupOpen) { // we don't want to redraw the map when there is an open popup on the map - it will close it fetch(true); updateAllNotificationsCount(notifications.size()); /// ... and getting the counter of all notifications } }, 20000); // Setting the inital state of the debug line _.each(['west', 'east', 'north', 'south'], function (el) { $("#debugInfo ." + el).text(mapModel.get(el).toFixed(4)); }); } /**** Some private methods **********/ function getBounds() { var bounds = M.getBounds(), coordinates = { west : bounds.getWest(), east : bounds.getEast(), north : bounds.getNorth(), south : bounds.getSouth(), center : bounds.getCenter() }; return coordinates; } function updateAllNotificationsCount(size) { $.ajax({ url: '/count', cache: false, success: function (data) { $('span.all-notifications').text(data.count); if (size >= data.count) { $('div.notification-list-counter').addClass('hidden'); $('div.showing-all').removeClass('hidden'); } else { $('div.notification-list-counter').removeClass('hidden'); $('div.showing-all').addClass('hidden'); } }, dataType: 'json' }); } function initMap() { M = L.map('map').setView([51.505, -0.09], 13); //London! L.tileLayer('http://{s}.tile.cloudmade.com/d1954fa5c5934eecbd0f07c6f7d2d339/997/256/{z}/{x}/{y}.png', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>', maxZoom: 18 }).addTo(M); } return { init : function () { initMap(); _init(); } }; }()); $(waze.map.init);
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['2977',"Tlece.Recruitment.Services.Company Namespace","topic_0000000000000A83.html"],['2978',"CompanyService Class","topic_0000000000000A84.html"],['2991',"Methods","topic_0000000000000A84_methods--.html"],['3051',"PersonRemoveBadges Method","topic_0000000000000ADE.html"]];
/* * jQuery ibanner * */ if (typeof Object.create !== "function") { Object.create = function (obj) { function F() {} F.prototype = obj; return new F(); }; } (function ($, window, document) { var Carousel = { init : function (options, el) { var base = this; base.$elem = $(el); base.options = $.extend({}, $.fn.ibanner.options, base.$elem.data(), options); base.userOptions = options; base.loadContent(); }, loadContent : function () { var base = this, url; function getData(data) { var i, content = ""; if (typeof base.options.jsonSuccess === "function") { base.options.jsonSuccess.apply(this, [data]); } else { for (i in data.owl) { if (data.owl.hasOwnProperty(i)) { content += data.owl[i].item; } } base.$elem.html(content); } base.logIn(); } if (typeof base.options.beforeInit === "function") { base.options.beforeInit.apply(this, [base.$elem]); } if (typeof base.options.jsonPath === "string") { url = base.options.jsonPath; $.getJSON(url, getData); } else { base.logIn(); } }, logIn : function () { var base = this; base.$elem.data("owl-originalStyles", base.$elem.attr("style")); base.$elem.data("owl-originalClasses", base.$elem.attr("class")); base.$elem.css({opacity: 0}); base.orignalItems = base.options.items; base.checkBrowser(); base.wrapperWidth = 0; base.checkVisible = null; base.setVars(); }, setVars : function () { var base = this; if (base.$elem.children().length === 0) {return false; } base.baseClass(); base.eventTypes(); base.$userItems = base.$elem.children(); base.itemsAmount = base.$userItems.length; base.wrapItems(); base.$owlItems = base.$elem.find(".owl-item"); base.$owlWrapper = base.$elem.find(".owl-wrapper"); base.playDirection = "next"; base.prevItem = 0; base.prevArr = [0]; base.currentItem = 0; base.customEvents(); base.onStartup(); }, onStartup : function () { var base = this; base.updateItems(); base.calculateAll(); base.buildControls(); base.updateControls(); base.response(); base.moveEvents(); base.stopOnHover(); base.owlStatus(); if (base.options.transitionStyle !== false) { base.transitionTypes(base.options.transitionStyle); } if (base.options.autoPlay === true) { base.options.autoPlay = 5000; } base.play(); base.$elem.find(".owl-wrapper").css("display", "block"); if (!base.$elem.is(":visible")) { base.watchVisibility(); } else { base.$elem.css("opacity", 1); } base.onstartup = false; base.eachMoveUpdate(); if (typeof base.options.afterInit === "function") { base.options.afterInit.apply(this, [base.$elem]); } }, eachMoveUpdate : function () { var base = this; if (base.options.lazyLoad === true) { base.lazyLoad(); } if (base.options.autoHeight === true) { base.autoHeight(); } base.onVisibleItems(); if (typeof base.options.afterAction === "function") { base.options.afterAction.apply(this, [base.$elem]); } }, updateVars : function () { var base = this; if (typeof base.options.beforeUpdate === "function") { base.options.beforeUpdate.apply(this, [base.$elem]); } base.watchVisibility(); base.updateItems(); base.calculateAll(); base.updatePosition(); base.updateControls(); base.eachMoveUpdate(); if (typeof base.options.afterUpdate === "function") { base.options.afterUpdate.apply(this, [base.$elem]); } }, reload : function () { var base = this; window.setTimeout(function () { base.updateVars(); }, 0); }, watchVisibility : function () { var base = this; if (base.$elem.is(":visible") === false) { base.$elem.css({opacity: 0}); window.clearInterval(base.autoPlayInterval); window.clearInterval(base.checkVisible); } else { return false; } base.checkVisible = window.setInterval(function () { if (base.$elem.is(":visible")) { base.reload(); base.$elem.animate({opacity: 1}, 200); window.clearInterval(base.checkVisible); } }, 500); }, wrapItems : function () { var base = this; base.$userItems.wrapAll("<div class=\"owl-wrapper\">").wrap("<div class=\"owl-item\"></div>"); base.$elem.find(".owl-wrapper").wrap("<div class=\"owl-wrapper-outer\">"); base.wrapperOuter = base.$elem.find(".owl-wrapper-outer"); base.$elem.css("display", "block"); }, baseClass : function () { var base = this, hasBaseClass = base.$elem.hasClass(base.options.baseClass), hasThemeClass = base.$elem.hasClass(base.options.theme); if (!hasBaseClass) { base.$elem.addClass(base.options.baseClass); } if (!hasThemeClass) { base.$elem.addClass(base.options.theme); } }, updateItems : function () { var base = this, width, i; if (base.options.responsive === false) { return false; } if (base.options.singleItem === true) { base.options.items = base.orignalItems = 1; base.options.itemsCustom = false; base.options.itemsDesktop = false; base.options.itemsDesktopSmall = false; base.options.itemsTablet = false; base.options.itemsTabletSmall = false; base.options.itemsMobile = false; return false; } width = $(base.options.responsiveBaseWidth).width(); if (width > (base.options.itemsDesktop[0] || base.orignalItems)) { base.options.items = base.orignalItems; } if (base.options.itemsCustom !== false) { //Reorder array by screen size base.options.itemsCustom.sort(function (a, b) {return a[0] - b[0]; }); for (i = 0; i < base.options.itemsCustom.length; i += 1) { if (base.options.itemsCustom[i][0] <= width) { base.options.items = base.options.itemsCustom[i][1]; } } } else { if (width <= base.options.itemsDesktop[0] && base.options.itemsDesktop !== false) { base.options.items = base.options.itemsDesktop[1]; } if (width <= base.options.itemsDesktopSmall[0] && base.options.itemsDesktopSmall !== false) { base.options.items = base.options.itemsDesktopSmall[1]; } if (width <= base.options.itemsTablet[0] && base.options.itemsTablet !== false) { base.options.items = base.options.itemsTablet[1]; } if (width <= base.options.itemsTabletSmall[0] && base.options.itemsTabletSmall !== false) { base.options.items = base.options.itemsTabletSmall[1]; } if (width <= base.options.itemsMobile[0] && base.options.itemsMobile !== false) { base.options.items = base.options.itemsMobile[1]; } } //if number of items is less than declared if (base.options.items > base.itemsAmount && base.options.itemsScaleUp === true) { base.options.items = base.itemsAmount; } }, response : function () { var base = this, smallDelay, lastWindowWidth; if (base.options.responsive !== true) { return false; } lastWindowWidth = $(window).width(); base.resizer = function () { if ($(window).width() !== lastWindowWidth) { if (base.options.autoPlay !== false) { window.clearInterval(base.autoPlayInterval); } window.clearTimeout(smallDelay); smallDelay = window.setTimeout(function () { lastWindowWidth = $(window).width(); base.updateVars(); }, base.options.responsiveRefreshRate); } }; $(window).resize(base.resizer); }, updatePosition : function () { var base = this; base.jumpTo(base.currentItem); if (base.options.autoPlay !== false) { base.checkAp(); } }, appendItemsSizes : function () { var base = this, roundPages = 0, lastItem = base.itemsAmount - base.options.items; base.$owlItems.each(function (index) { var $this = $(this); $this .css({"width": base.itemWidth}) .data("owl-item", Number(index)); if (index % base.options.items === 0 || index === lastItem) { if (!(index > lastItem)) { roundPages += 1; } } $this.data("owl-roundPages", roundPages); }); }, appendWrapperSizes : function () { var base = this, width = base.$owlItems.length * base.itemWidth; base.$owlWrapper.css({ "width": width * 2, "left": 0 }); base.appendItemsSizes(); }, calculateAll : function () { var base = this; base.calculateWidth(); base.appendWrapperSizes(); base.loops(); base.max(); }, calculateWidth : function () { var base = this; base.itemWidth = Math.round(base.$elem.width() / base.options.items); }, max : function () { var base = this, maximum = ((base.itemsAmount * base.itemWidth) - base.options.items * base.itemWidth) * -1; if (base.options.items > base.itemsAmount) { base.maximumItem = 0; maximum = 0; base.maximumPixels = 0; } else { base.maximumItem = base.itemsAmount - base.options.items; base.maximumPixels = maximum; } return maximum; }, min : function () { return 0; }, loops : function () { var base = this, prev = 0, elWidth = 0, i, item, roundPageNum; base.positionsInArray = [0]; base.pagesInArray = []; for (i = 0; i < base.itemsAmount; i += 1) { elWidth += base.itemWidth; base.positionsInArray.push(-elWidth); if (base.options.scrollPerPage === true) { item = $(base.$owlItems[i]); roundPageNum = item.data("owl-roundPages"); if (roundPageNum !== prev) { base.pagesInArray[prev] = base.positionsInArray[i]; prev = roundPageNum; } } } }, buildControls : function () { var base = this; if (base.options.navigation === true || base.options.pagination === true) { base.owlControls = $("<div class=\"owl-controls\"/>").toggleClass("clickable", !base.browser.isTouch).appendTo(base.$elem); } if (base.options.pagination === true) { base.buildPagination(); } if (base.options.navigation === true) { base.buildButtons(); } }, buildButtons : function () { var base = this, buttonsWrapper = $("<div class=\"owl-buttons\"/>"); base.owlControls.append(buttonsWrapper); base.buttonPrev = $("<div/>", { "class" : "owl-prev", "html" : base.options.navigationText[0] || "" }); base.buttonNext = $("<div/>", { "class" : "owl-next", "html" : base.options.navigationText[1] || "" }); buttonsWrapper .append(base.buttonPrev) .append(base.buttonNext); buttonsWrapper.on("touchstart.owlControls mousedown.owlControls", "div[class^=\"owl\"]", function (event) { event.preventDefault(); }); buttonsWrapper.on("touchend.owlControls mouseup.owlControls", "div[class^=\"owl\"]", function (event) { event.preventDefault(); if ($(this).hasClass("owl-next")) { base.next(); } else { base.prev(); } }); }, buildPagination : function () { var base = this; base.paginationWrapper = $("<div class=\"owl-pagination\"/>"); base.owlControls.append(base.paginationWrapper); base.paginationWrapper.on("touchend.owlControls mouseup.owlControls", ".owl-page", function (event) { event.preventDefault(); if (Number($(this).data("owl-page")) !== base.currentItem) { base.goTo(Number($(this).data("owl-page")), true); } }); }, updatePagination : function () { var base = this, counter, lastPage, lastItem, i, paginationButton, paginationButtonInner; if (base.options.pagination === false) { return false; } base.paginationWrapper.html(""); counter = 0; lastPage = base.itemsAmount - base.itemsAmount % base.options.items; for (i = 0; i < base.itemsAmount; i += 1) { if (i % base.options.items === 0) { counter += 1; if (lastPage === i) { lastItem = base.itemsAmount - base.options.items; } paginationButton = $("<div/>", { "class" : "owl-page" }); paginationButtonInner = $("<span></span>", { "text": base.options.paginationNumbers === true ? counter : "", "class": base.options.paginationNumbers === true ? "owl-numbers" : "" }); paginationButton.append(paginationButtonInner); paginationButton.data("owl-page", lastPage === i ? lastItem : i); paginationButton.data("owl-roundPages", counter); base.paginationWrapper.append(paginationButton); } } base.checkPagination(); }, checkPagination : function () { var base = this; if (base.options.pagination === false) { return false; } base.paginationWrapper.find(".owl-page").each(function () { if ($(this).data("owl-roundPages") === $(base.$owlItems[base.currentItem]).data("owl-roundPages")) { base.paginationWrapper .find(".owl-page") .removeClass("active"); $(this).addClass("active"); } }); }, checkNavigation : function () { var base = this; if (base.options.navigation === false) { return false; } if (base.options.rewindNav === false) { if (base.currentItem === 0 && base.maximumItem === 0) { base.buttonPrev.addClass("disabled"); base.buttonNext.addClass("disabled"); } else if (base.currentItem === 0 && base.maximumItem !== 0) { base.buttonPrev.addClass("disabled"); base.buttonNext.removeClass("disabled"); } else if (base.currentItem === base.maximumItem) { base.buttonPrev.removeClass("disabled"); base.buttonNext.addClass("disabled"); } else if (base.currentItem !== 0 && base.currentItem !== base.maximumItem) { base.buttonPrev.removeClass("disabled"); base.buttonNext.removeClass("disabled"); } } }, updateControls : function () { var base = this; base.updatePagination(); base.checkNavigation(); if (base.owlControls) { if (base.options.items >= base.itemsAmount) { base.owlControls.hide(); } else { base.owlControls.show(); } } }, destroyControls : function () { var base = this; if (base.owlControls) { base.owlControls.remove(); } }, next : function (speed) { var base = this; if (base.isTransition) { return false; } base.currentItem += base.options.scrollPerPage === true ? base.options.items : 1; if (base.currentItem > base.maximumItem + (base.options.scrollPerPage === true ? (base.options.items - 1) : 0)) { if (base.options.rewindNav === true) { base.currentItem = 0; speed = "rewind"; } else { base.currentItem = base.maximumItem; return false; } } base.goTo(base.currentItem, speed); }, prev : function (speed) { var base = this; if (base.isTransition) { return false; } if (base.options.scrollPerPage === true && base.currentItem > 0 && base.currentItem < base.options.items) { base.currentItem = 0; } else { base.currentItem -= base.options.scrollPerPage === true ? base.options.items : 1; } if (base.currentItem < 0) { if (base.options.rewindNav === true) { base.currentItem = base.maximumItem; speed = "rewind"; } else { base.currentItem = 0; return false; } } base.goTo(base.currentItem, speed); }, goTo : function (position, speed, drag) { var base = this, goToPixel; if (base.isTransition) { return false; } if (typeof base.options.beforeMove === "function") { base.options.beforeMove.apply(this, [base.$elem]); } if (position >= base.maximumItem) { position = base.maximumItem; } else if (position <= 0) { position = 0; } base.currentItem = base.owl.currentItem = position; if (base.options.transitionStyle !== false && drag !== "drag" && base.options.items === 1 && base.browser.support3d === true) { base.swapSpeed(0); if (base.browser.support3d === true) { base.transition3d(base.positionsInArray[position]); } else { base.css2slide(base.positionsInArray[position], 1); } base.afterGo(); base.singleItemTransition(); return false; } goToPixel = base.positionsInArray[position]; if (base.browser.support3d === true) { base.isCss3Finish = false; if (speed === true) { base.swapSpeed("paginationSpeed"); window.setTimeout(function () { base.isCss3Finish = true; }, base.options.paginationSpeed); } else if (speed === "rewind") { base.swapSpeed(base.options.rewindSpeed); window.setTimeout(function () { base.isCss3Finish = true; }, base.options.rewindSpeed); } else { base.swapSpeed("slideSpeed"); window.setTimeout(function () { base.isCss3Finish = true; }, base.options.slideSpeed); } base.transition3d(goToPixel); } else { if (speed === true) { base.css2slide(goToPixel, base.options.paginationSpeed); } else if (speed === "rewind") { base.css2slide(goToPixel, base.options.rewindSpeed); } else { base.css2slide(goToPixel, base.options.slideSpeed); } } base.afterGo(); }, jumpTo : function (position) { var base = this; if (typeof base.options.beforeMove === "function") { base.options.beforeMove.apply(this, [base.$elem]); } if (position >= base.maximumItem || position === -1) { position = base.maximumItem; } else if (position <= 0) { position = 0; } base.swapSpeed(0); if (base.browser.support3d === true) { base.transition3d(base.positionsInArray[position]); } else { base.css2slide(base.positionsInArray[position], 1); } base.currentItem = base.owl.currentItem = position; base.afterGo(); }, afterGo : function () { var base = this; base.prevArr.push(base.currentItem); base.prevItem = base.owl.prevItem = base.prevArr[base.prevArr.length - 2]; base.prevArr.shift(0); if (base.prevItem !== base.currentItem) { base.checkPagination(); base.checkNavigation(); base.eachMoveUpdate(); if (base.options.autoPlay !== false) { base.checkAp(); } } if (typeof base.options.afterMove === "function" && base.prevItem !== base.currentItem) { base.options.afterMove.apply(this, [base.$elem]); } }, stop : function () { var base = this; base.apStatus = "stop"; window.clearInterval(base.autoPlayInterval); }, checkAp : function () { var base = this; if (base.apStatus !== "stop") { base.play(); } }, play : function () { var base = this; base.apStatus = "play"; if (base.options.autoPlay === false) { return false; } window.clearInterval(base.autoPlayInterval); base.autoPlayInterval = window.setInterval(function () { base.next(true); }, base.options.autoPlay); }, swapSpeed : function (action) { var base = this; if (action === "slideSpeed") { base.$owlWrapper.css(base.addCssSpeed(base.options.slideSpeed)); } else if (action === "paginationSpeed") { base.$owlWrapper.css(base.addCssSpeed(base.options.paginationSpeed)); } else if (typeof action !== "string") { base.$owlWrapper.css(base.addCssSpeed(action)); } }, addCssSpeed : function (speed) { return { "-webkit-transition": "all " + speed + "ms ease", "-moz-transition": "all " + speed + "ms ease", "-o-transition": "all " + speed + "ms ease", "transition": "all " + speed + "ms ease" }; }, removeTransition : function () { return { "-webkit-transition": "", "-moz-transition": "", "-o-transition": "", "transition": "" }; }, doTranslate : function (pixels) { return { "-webkit-transform": "translate3d(" + pixels + "px, 0px, 0px)", "-moz-transform": "translate3d(" + pixels + "px, 0px, 0px)", "-o-transform": "translate3d(" + pixels + "px, 0px, 0px)", "-ms-transform": "translate3d(" + pixels + "px, 0px, 0px)", "transform": "translate3d(" + pixels + "px, 0px,0px)" }; }, transition3d : function (value) { var base = this; base.$owlWrapper.css(base.doTranslate(value)); }, css2move : function (value) { var base = this; base.$owlWrapper.css({"left" : value}); }, css2slide : function (value, speed) { var base = this; base.isCssFinish = false; base.$owlWrapper.stop(true, true).animate({ "left" : value }, { duration : speed || base.options.slideSpeed, complete : function () { base.isCssFinish = true; } }); }, checkBrowser : function () { var base = this, translate3D = "translate3d(0px, 0px, 0px)", tempElem = document.createElement("div"), regex, asSupport, support3d, isTouch; tempElem.style.cssText = " -moz-transform:" + translate3D + "; -ms-transform:" + translate3D + "; -o-transform:" + translate3D + "; -webkit-transform:" + translate3D + "; transform:" + translate3D; regex = /translate3d\(0px, 0px, 0px\)/g; asSupport = tempElem.style.cssText.match(regex); support3d = (asSupport !== null && asSupport.length === 1); isTouch = "ontouchstart" in window || window.navigator.msMaxTouchPoints; base.browser = { "support3d" : support3d, "isTouch" : isTouch }; }, moveEvents : function () { var base = this; if (base.options.mouseDrag !== false || base.options.touchDrag !== false) { base.gestures(); base.disabledEvents(); } }, eventTypes : function () { var base = this, types = ["s", "e", "x"]; base.ev_types = {}; if (base.options.mouseDrag === true && base.options.touchDrag === true) { types = [ "touchstart.owl mousedown.owl", "touchmove.owl mousemove.owl", "touchend.owl touchcancel.owl mouseup.owl" ]; } else if (base.options.mouseDrag === false && base.options.touchDrag === true) { types = [ "touchstart.owl", "touchmove.owl", "touchend.owl touchcancel.owl" ]; } else if (base.options.mouseDrag === true && base.options.touchDrag === false) { types = [ "mousedown.owl", "mousemove.owl", "mouseup.owl" ]; } base.ev_types.start = types[0]; base.ev_types.move = types[1]; base.ev_types.end = types[2]; }, disabledEvents : function () { var base = this; base.$elem.on("dragstart.owl", function (event) { event.preventDefault(); }); base.$elem.on("mousedown.disableTextSelect", function (e) { return $(e.target).is('input, textarea, select, option'); }); }, gestures : function () { /*jslint unparam: true*/ var base = this, locals = { offsetX : 0, offsetY : 0, baseElWidth : 0, relativePos : 0, position: null, minSwipe : null, maxSwipe: null, sliding : null, dargging: null, targetElement : null }; base.isCssFinish = true; function getTouches(event) { if (event.touches !== undefined) { return { x : event.touches[0].pageX, y : event.touches[0].pageY }; } if (event.touches === undefined) { if (event.pageX !== undefined) { return { x : event.pageX, y : event.pageY }; } if (event.pageX === undefined) { return { x : event.clientX, y : event.clientY }; } } } function swapEvents(type) { if (type === "on") { $(document).on(base.ev_types.move, dragMove); $(document).on(base.ev_types.end, dragEnd); } else if (type === "off") { $(document).off(base.ev_types.move); $(document).off(base.ev_types.end); } } function dragStart(event) { var ev = event.originalEvent || event || window.event, position; if (ev.which === 3) { return false; } if (base.itemsAmount <= base.options.items) { return; } if (base.isCssFinish === false && !base.options.dragBeforeAnimFinish) { return false; } if (base.isCss3Finish === false && !base.options.dragBeforeAnimFinish) { return false; } if (base.options.autoPlay !== false) { window.clearInterval(base.autoPlayInterval); } if (base.browser.isTouch !== true && !base.$owlWrapper.hasClass("grabbing")) { base.$owlWrapper.addClass("grabbing"); } base.newPosX = 0; base.newRelativeX = 0; $(this).css(base.removeTransition()); position = $(this).position(); locals.relativePos = position.left; locals.offsetX = getTouches(ev).x - position.left; locals.offsetY = getTouches(ev).y - position.top; swapEvents("on"); locals.sliding = false; locals.targetElement = ev.target || ev.srcElement; } function dragMove(event) { var ev = event.originalEvent || event || window.event, minSwipe, maxSwipe; base.newPosX = getTouches(ev).x - locals.offsetX; base.newPosY = getTouches(ev).y - locals.offsetY; base.newRelativeX = base.newPosX - locals.relativePos; if (typeof base.options.startDragging === "function" && locals.dragging !== true && base.newRelativeX !== 0) { locals.dragging = true; base.options.startDragging.apply(base, [base.$elem]); } if ((base.newRelativeX > 8 || base.newRelativeX < -8) && (base.browser.isTouch === true)) { if (ev.preventDefault !== undefined) { ev.preventDefault(); } else { ev.returnValue = false; } locals.sliding = true; } if ((base.newPosY > 10 || base.newPosY < -10) && locals.sliding === false) { $(document).off("touchmove.owl"); } minSwipe = function () { return base.newRelativeX / 5; }; maxSwipe = function () { return base.maximumPixels + base.newRelativeX / 5; }; base.newPosX = Math.max(Math.min(base.newPosX, minSwipe()), maxSwipe()); if (base.browser.support3d === true) { base.transition3d(base.newPosX); } else { base.css2move(base.newPosX); } } function dragEnd(event) { var ev = event.originalEvent || event || window.event, newPosition, handlers, owlStopEvent; ev.target = ev.target || ev.srcElement; locals.dragging = false; if (base.browser.isTouch !== true) { base.$owlWrapper.removeClass("grabbing"); } if (base.newRelativeX < 0) { base.dragDirection = base.owl.dragDirection = "left"; } else { base.dragDirection = base.owl.dragDirection = "right"; } if (base.newRelativeX !== 0) { newPosition = base.getNewPosition(); base.goTo(newPosition, false, "drag"); if (locals.targetElement === ev.target && base.browser.isTouch !== true) { $(ev.target).on("click.disable", function (ev) { ev.stopImmediatePropagation(); ev.stopPropagation(); ev.preventDefault(); $(ev.target).off("click.disable"); }); handlers = $._data(ev.target, "events").click; owlStopEvent = handlers.pop(); handlers.splice(0, 0, owlStopEvent); } } swapEvents("off"); } base.$elem.on(base.ev_types.start, ".owl-wrapper", dragStart); }, getNewPosition : function () { var base = this, newPosition = base.closestItem(); if (newPosition > base.maximumItem) { base.currentItem = base.maximumItem; newPosition = base.maximumItem; } else if (base.newPosX >= 0) { newPosition = 0; base.currentItem = 0; } return newPosition; }, closestItem : function () { var base = this, array = base.options.scrollPerPage === true ? base.pagesInArray : base.positionsInArray, goal = base.newPosX, closest = null; $.each(array, function (i, v) { if (goal - (base.itemWidth / 20) > array[i + 1] && goal - (base.itemWidth / 20) < v && base.moveDirection() === "left") { closest = v; if (base.options.scrollPerPage === true) { base.currentItem = $.inArray(closest, base.positionsInArray); } else { base.currentItem = i; } } else if (goal + (base.itemWidth / 20) < v && goal + (base.itemWidth / 20) > (array[i + 1] || array[i] - base.itemWidth) && base.moveDirection() === "right") { if (base.options.scrollPerPage === true) { closest = array[i + 1] || array[array.length - 1]; base.currentItem = $.inArray(closest, base.positionsInArray); } else { closest = array[i + 1]; base.currentItem = i + 1; } } }); return base.currentItem; }, moveDirection : function () { var base = this, direction; if (base.newRelativeX < 0) { direction = "right"; base.playDirection = "next"; } else { direction = "left"; base.playDirection = "prev"; } return direction; }, customEvents : function () { /*jslint unparam: true*/ var base = this; base.$elem.on("owl.next", function () { base.next(); }); base.$elem.on("owl.prev", function () { base.prev(); }); base.$elem.on("owl.play", function (event, speed) { base.options.autoPlay = speed; base.play(); base.hoverStatus = "play"; }); base.$elem.on("owl.stop", function () { base.stop(); base.hoverStatus = "stop"; }); base.$elem.on("owl.goTo", function (event, item) { base.goTo(item); }); base.$elem.on("owl.jumpTo", function (event, item) { base.jumpTo(item); }); }, stopOnHover : function () { var base = this; if (base.options.stopOnHover === true && base.browser.isTouch !== true && base.options.autoPlay !== false) { base.$elem.on("mouseover", function () { base.stop(); }); base.$elem.on("mouseout", function () { if (base.hoverStatus !== "stop") { base.play(); } }); } }, lazyLoad : function () { var base = this, i, $item, itemNumber, $lazyImg, follow; if (base.options.lazyLoad === false) { return false; } for (i = 0; i < base.itemsAmount; i += 1) { $item = $(base.$owlItems[i]); if ($item.data("owl-loaded") === "loaded") { continue; } itemNumber = $item.data("owl-item"); $lazyImg = $item.find(".lazyOwl"); if (typeof $lazyImg.data("src") !== "string") { $item.data("owl-loaded", "loaded"); continue; } if ($item.data("owl-loaded") === undefined) { $lazyImg.hide(); $item.addClass("loading").data("owl-loaded", "checked"); } if (base.options.lazyFollow === true) { follow = itemNumber >= base.currentItem; } else { follow = true; } if (follow && itemNumber < base.currentItem + base.options.items && $lazyImg.length) { base.lazyPreload($item, $lazyImg); } } }, lazyPreload : function ($item, $lazyImg) { var base = this, iterations = 0, isBackgroundImg; if ($lazyImg.prop("tagName") === "DIV") { $lazyImg.css("background-image", "url(" + $lazyImg.data("src") + ")"); isBackgroundImg = true; } else { $lazyImg[0].src = $lazyImg.data("src"); } function showImage() { $item.data("owl-loaded", "loaded").removeClass("loading"); $lazyImg.removeAttr("data-src"); if (base.options.lazyEffect === "fade") { $lazyImg.fadeIn(400); } else { $lazyImg.show(); } if (typeof base.options.afterLazyLoad === "function") { base.options.afterLazyLoad.apply(this, [base.$elem]); } } function checkLazyImage() { iterations += 1; if (base.completeImg($lazyImg.get(0)) || isBackgroundImg === true) { showImage(); } else if (iterations <= 100) {//if image loads in less than 10 seconds window.setTimeout(checkLazyImage, 100); } else { showImage(); } } checkLazyImage(); }, autoHeight : function () { var base = this, $currentimg = $(base.$owlItems[base.currentItem]).find("img"), iterations; function addHeight() { var $currentItem = $(base.$owlItems[base.currentItem]).height(); base.wrapperOuter.css("height", $currentItem + "px"); if (!base.wrapperOuter.hasClass("autoHeight")) { window.setTimeout(function () { base.wrapperOuter.addClass("autoHeight"); }, 0); } } function checkImage() { iterations += 1; if (base.completeImg($currentimg.get(0))) { addHeight(); } else if (iterations <= 100) { //if image loads in less than 10 seconds window.setTimeout(checkImage, 100); } else { base.wrapperOuter.css("height", ""); //Else remove height attribute } } if ($currentimg.get(0) !== undefined) { iterations = 0; checkImage(); } else { addHeight(); } }, completeImg : function (img) { var naturalWidthType; if (!img.complete) { return false; } naturalWidthType = typeof img.naturalWidth; if (naturalWidthType !== "undefined" && img.naturalWidth === 0) { return false; } return true; }, onVisibleItems : function () { var base = this, i; if (base.options.addClassActive === true) { base.$owlItems.removeClass("active"); } base.visibleItems = []; for (i = base.currentItem; i < base.currentItem + base.options.items; i += 1) { base.visibleItems.push(i); if (base.options.addClassActive === true) { $(base.$owlItems[i]).addClass("active"); } } base.owl.visibleItems = base.visibleItems; }, transitionTypes : function (className) { var base = this; //Currently available: "fade", "backSlide", "goDown", "fadeUp" base.outClass = "owl-" + className + "-out"; base.inClass = "owl-" + className + "-in"; }, singleItemTransition : function () { var base = this, outClass = base.outClass, inClass = base.inClass, $currentItem = base.$owlItems.eq(base.currentItem), $prevItem = base.$owlItems.eq(base.prevItem), prevPos = Math.abs(base.positionsInArray[base.currentItem]) + base.positionsInArray[base.prevItem], origin = Math.abs(base.positionsInArray[base.currentItem]) + base.itemWidth / 2, animEnd = 'webkitAnimationEnd oAnimationEnd MSAnimationEnd animationend'; base.isTransition = true; base.$owlWrapper .addClass('owl-origin') .css({ "-webkit-transform-origin" : origin + "px", "-moz-perspective-origin" : origin + "px", "perspective-origin" : origin + "px" }); function transStyles(prevPos) { return { "position" : "relative", "left" : prevPos + "px" }; } $prevItem .css(transStyles(prevPos, 10)) .addClass(outClass) .on(animEnd, function () { base.endPrev = true; $prevItem.off(animEnd); base.clearTransStyle($prevItem, outClass); }); $currentItem .addClass(inClass) .on(animEnd, function () { base.endCurrent = true; $currentItem.off(animEnd); base.clearTransStyle($currentItem, inClass); }); }, clearTransStyle : function (item, classToRemove) { var base = this; item.css({ "position" : "", "left" : "" }).removeClass(classToRemove); if (base.endPrev && base.endCurrent) { base.$owlWrapper.removeClass('owl-origin'); base.endPrev = false; base.endCurrent = false; base.isTransition = false; } }, owlStatus : function () { var base = this; base.owl = { "userOptions" : base.userOptions, "baseElement" : base.$elem, "userItems" : base.$userItems, "owlItems" : base.$owlItems, "currentItem" : base.currentItem, "prevItem" : base.prevItem, "visibleItems" : base.visibleItems, "isTouch" : base.browser.isTouch, "browser" : base.browser, "dragDirection" : base.dragDirection }; }, clearEvents : function () { var base = this; base.$elem.off(".owl owl mousedown.disableTextSelect"); $(document).off(".owl owl"); $(window).off("resize", base.resizer); }, unWrap : function () { var base = this; if (base.$elem.children().length !== 0) { base.$owlWrapper.unwrap(); base.$userItems.unwrap().unwrap(); if (base.owlControls) { base.owlControls.remove(); } } base.clearEvents(); base.$elem .attr("style", base.$elem.data("owl-originalStyles") || "") .attr("class", base.$elem.data("owl-originalClasses")); }, destroy : function () { var base = this; base.stop(); window.clearInterval(base.checkVisible); base.unWrap(); base.$elem.removeData(); }, reinit : function (newOptions) { var base = this, options = $.extend({}, base.userOptions, newOptions); base.unWrap(); base.init(options, base.$elem); }, addItem : function (htmlString, targetPosition) { var base = this, position; if (!htmlString) {return false; } if (base.$elem.children().length === 0) { base.$elem.append(htmlString); base.setVars(); return false; } base.unWrap(); if (targetPosition === undefined || targetPosition === -1) { position = -1; } else { position = targetPosition; } if (position >= base.$userItems.length || position === -1) { base.$userItems.eq(-1).after(htmlString); } else { base.$userItems.eq(position).before(htmlString); } base.setVars(); }, removeItem : function (targetPosition) { var base = this, position; if (base.$elem.children().length === 0) { return false; } if (targetPosition === undefined || targetPosition === -1) { position = -1; } else { position = targetPosition; } base.unWrap(); base.$userItems.eq(position).remove(); base.setVars(); } }; $.fn.ibanner = function (options) { return this.each(function () { if ($(this).data("owl-init") === true) { return false; } $(this).data("owl-init", true); var carousel = Object.create(Carousel); carousel.init(options, this); $.data(this, "ibanner", carousel); }); }; $.fn.ibanner.options = { items : 5, itemsCustom : false, itemsDesktop : [1199, 4], itemsDesktopSmall : [979, 3], itemsTablet : [768, 2], itemsTabletSmall : false, itemsMobile : [479, 1], singleItem : false, itemsScaleUp : false, slideSpeed : 200, paginationSpeed : 800, rewindSpeed : 1000, autoPlay : false, stopOnHover : false, navigation : false, navigationText : ["prev", "next"], rewindNav : true, scrollPerPage : false, pagination : true, paginationNumbers : false, responsive : true, responsiveRefreshRate : 200, responsiveBaseWidth : window, baseClass : "owl-carousel", theme : "owl-theme", lazyLoad : false, lazyFollow : true, lazyEffect : "fade", autoHeight : false, jsonPath : false, jsonSuccess : false, dragBeforeAnimFinish : true, mouseDrag : true, touchDrag : true, addClassActive : false, transitionStyle : false, beforeUpdate : false, afterUpdate : false, beforeInit : false, afterInit : false, beforeMove : false, afterMove : false, afterAction : false, startDragging : false, afterLazyLoad: false }; }(jQuery, window, document));
'use strict'; const rp = require('request-promise'); const {host} = require('./constants'); const createUserAndLogin = (user) => { return rp.post({ uri: `${host}/auth/login`, json: true, body: user }).then(result => result.token).catch(err => { console.log(err.statusCode); if (err.statusCode === 400) { return rp.post({ uri: `${host}/users`, json: true, body: user }).then(() => { return createUserAndLogin(user); }); } }); }; module.exports.createUserAndLogin = createUserAndLogin;
(function (JGS, $, undefined) { "use strict"; /** This class provides javascript handling specific to the example7 page. Most importantly, it provides the dygraphs setup and handling, including the handling of mouse-down/up events on the dygraphs range control element. @class Demo7Page @constructor */ JGS.Demo7Page = function (pageCfg) { this.$graphCont = pageCfg.$graphCont; this.$rangeBtnsCont = pageCfg.$rangeBtnsCont; this.graphDataProvider = new JGS.GraphDataProvider(); this.graphDataProvider.newGraphDataCallbacks.add($.proxy(this._onNewGraphData, this)); this.isRangeSelectorActive = false; }; /** * Starts everything by requesting initial data load. For example's purposes, initial date extents are hardcoded. * * @method */ JGS.Demo7Page.prototype.init = function () { this.showSpinner(true); this._setupRangeButtons(); // Default range dates var rangeEndMom = moment().utc(); rangeEndMom.startOf('hour'); rangeEndMom.add(1, 'hour'); var rangeStartMom = moment.utc(rangeEndMom).add(-6, 'month'); this.$rangeBtnsCont.find("button[name='range-btn-6m']").addClass('active'); // Default detail dates var detailEndMom = moment(rangeEndMom); detailEndMom.add(-30, 'day'); var detailStartMom = moment(detailEndMom); detailStartMom.add(-120, 'day'); this.graphDataProvider.loadData("Series-A", rangeStartMom.toDate(), rangeEndMom.toDate(), detailStartMom.toDate(), detailEndMom.toDate(), this.$graphCont.width()); }; JGS.Demo7Page.prototype._setupRangeButtons = function () { var self = this; this.$rangeBtnsCont.children().on('click', function (evt) { evt.preventDefault(); var rangeType = evt.target.name.toString().replace("range-btn-", ""); self.$rangeBtnsCont.children().removeClass('active'); $(this).addClass('active'); var rangeEndMom; rangeEndMom = moment().utc(); rangeEndMom.minutes(0).seconds(0); rangeEndMom.add(1, 'hour'); //console.log("rangeType", rangeType); var rangeStartMom; if (rangeType == "1d") { rangeStartMom = moment.utc(rangeEndMom).add(-1, 'day'); } else if (rangeType == "1w") { rangeStartMom = moment.utc(rangeEndMom).add(-1, 'week'); } else if (rangeType == "1m") { rangeStartMom = moment.utc(rangeEndMom).add(-1, 'month'); } else if (rangeType == "6m") { rangeStartMom = moment.utc(rangeEndMom).add(-6, 'month'); } else if (rangeType == "1y") { rangeStartMom = moment.utc(rangeEndMom).add(-1, 'year'); } else if (rangeType == "5y") { rangeStartMom = moment.utc(rangeEndMom).add(-5, 'year'); } else if (rangeType == "ytd") { rangeStartMom = moment().startOf('year').utc(); } //For demo purposes, when range is reset, auto reset detail view to same extents as range var detailStartMom = rangeStartMom.clone(); var detailEndMom = rangeEndMom.clone(); self.showSpinner(true); self.graphDataProvider.loadData("Series-A", rangeStartMom.toDate(), rangeEndMom.toDate(), detailStartMom.toDate(), detailEndMom.toDate(), self.$graphCont.width()); }); }; /** * Internal method to add mouse down listener to dygraphs range selector. Coded so that it can be called * multiple times without concern. Although not necessary for simple example (like example1), this becomes necessary * for more advanced examples when the graph must be recreated, not just updated. * * @method _setupRangeMouseHandling * @private */ JGS.Demo7Page.prototype._setupRangeMouseHandling = function () { var self = this; // Element used for tracking mouse up events this.$mouseUpEventEl = $(window); if ($.support.cssFloat == false) { //IE<=8, doesn't support mouse events on window this.$mouseUpEventEl = $(document.body); } //Minor Hack...not sure how else to hook-in to dygraphs range selector events without modifying source. This is //where minor modification to dygraphs (range selector plugin) might make for a cleaner approach. //We only want to install a mouse up handler if mouse down interaction is started on the range control var $rangeEl = this.$graphCont.find('.dygraph-rangesel-fgcanvas, .dygraph-rangesel-zoomhandle'); //Uninstall existing handler if already installed $rangeEl.off("mousedown.jgs touchstart.jgs"); //Install new mouse down handler $rangeEl.on("mousedown.jgs touchstart.jgs", function (evt) { //Track that mouse is down on range selector self.isRangeSelectorActive = true; // Setup mouse up handler to initiate new data load self.$mouseUpEventEl.off("mouseup.jgs touchend.jgs"); //cancel any existing $(self.$mouseUpEventEl).on('mouseup.jgs touchend.jgs', function (evt) { self.$mouseUpEventEl.off("mouseup.jgs touchend.jgs"); //Mouse no longer down on range selector self.isRangeSelectorActive = false; //Get the new detail window extents var graphAxisX = self.graph.xAxisRange(); self.detailStartDateTm = new Date(graphAxisX[0]); self.detailEndDateTm = new Date(graphAxisX[1]); // Load new detail data self._loadNewDetailData(); }); }); }; /** * Internal method that provides a hook in to Dygraphs default pan interaction handling. This is a bit of hack * and relies on Dygraphs' internals. Without this, pan interactions (holding SHIFT and dragging graph) do not result * in detail data being loaded. * * This method works by replacing the global Dygraph.Interaction.endPan method. The replacement method * is global to all instances of this class, and so it can not rely on "self" scope. To support muliple graphs * with their own pan interactions, we keep a circular reference to this object instance on the dygraphs instance * itself when creating it. This allows us to look up the correct page object instance when the endPan callback is * triggered. We use a global JGS.Demo7Page.isGlobalPanInteractionHandlerInstalled flag to make sure we only install * the global handler once. * * @method _setupPanInteractionHandling * @private */ JGS.Demo7Page.prototype._setupPanInteractionHandling = function () { if (JGS.Demo7Page.isGlobalPanInteractionHandlerInstalled) return; else JGS.Demo7Page.isGlobalPanInteractionHandlerInstalled = true; //Save original endPan function var origEndPan = Dygraph.Interaction.endPan; //Replace built-in handling with our own function Dygraph.Interaction.endPan = function (event, g, context) { var myInstance = g.demoPageInstance; //Call the original to let it do it's magic origEndPan(event, g, context); //Extract new start/end from the x-axis //Note that this _might_ not work as is in IE8. If not, might require a setTimeout hack that executes these //next few lines after a few ms delay. Have not tested with IE8 yet. var axisX = g.xAxisRange(); myInstance.detailStartDateTm = new Date(axisX[0]); myInstance.detailEndDateTm = new Date(axisX[1]); //Trigger new detail load myInstance._loadNewDetailData(); }; Dygraph.endPan = Dygraph.Interaction.endPan; //see dygraph-interaction-model.js }; /** * Initiates detail data load request using last known zoom extents * * @method _loadNewDetailData * @private */ JGS.Demo7Page.prototype._loadNewDetailData = function () { this.showSpinner(true); this.graphDataProvider.loadData("Series-A", null, null, this.detailStartDateTm, this.detailEndDateTm, this.$graphCont.width()); }; /** * Callback handler when new graph data is available to be drawn * * @param graphData * @method _onNewGraphData * @private */ JGS.Demo7Page.prototype._onNewGraphData = function (graphData) { this.drawDygraph(graphData); this.$rangeBtnsCont.css('visibility', 'visible'); this.showSpinner(false); }; /** * Main method for creating or updating dygraph control * * @param graphData * @method drawDygraph */ JGS.Demo7Page.prototype.drawDygraph = function (graphData) { var dyData = graphData.dyData; var detailStartDateTm = graphData.detailStartDateTm; var detailEndDateTm = graphData.detailEndDateTm; // This will be needed later when supporting dynamic show/hide of multiple series var recreateDygraph = false; // To keep example1 simple, we just hard code the labels with one series var labels = ["time", "Series-A"]; var useAutoRange = true; // normally configurable var expectMinMax = true; // normally configurable, but for demo easier to hardcode that min/max always available //Create the axes for dygraphs var axes = {}; if (useAutoRange) { axes.y = {valueRange: null}; } else { axes.y = {valueRange: [0, 2100]}; } //Create new graph instance if (!this.graph || recreateDygraph) { var graphCfg = { axes: axes, labels: labels, customBars: expectMinMax, showRangeSelector: true, interactionModel: Dygraph.Interaction.defaultModel, //clickCallback: $.proxy(this._onDyClickCallback, this), connectSeparatedPoints: true, dateWindow: [detailStartDateTm.getTime(), detailEndDateTm.getTime()], drawCallback: $.proxy(this._onDyDrawCallback, this), zoomCallback: $.proxy(this._onDyZoomCallback, this), digitsAfterDecimal: 2, labelsDivWidth: "275" }; this.graph = new Dygraph(this.$graphCont.get(0), dyData, graphCfg); this._setupRangeMouseHandling(); this._setupPanInteractionHandling(); //Store this object instance on the graph itself so we can later reference it for endPan callback handling this.graph.demoPageInstance = this; } //Update existing graph instance else { var graphCfg = { axes: axes, labels: labels, file: dyData, dateWindow: [detailStartDateTm.getTime(), detailEndDateTm.getTime()] }; this.graph.updateOptions(graphCfg); } // Load annotations for the current graph data var annotations = this.getAnnotations(graphData); this.graph.setAnnotations(annotations); }; JGS.Demo7Page.prototype.getAnnotations = function (graphData) { var annotations = []; var lastDataDateTm = graphData.dyData[graphData.dyData.length - 1][0]; var workingMom = moment(lastDataDateTm); var $activeRangeBtn = this.$rangeBtnsCont.find("button.active"); var rangeType = ""; if ($activeRangeBtn) { rangeType = $activeRangeBtn.attr('name').replace("range-btn-", ""); } var workingMomDeltaType = "month"; if (rangeType == "1d") { workingMom.startOf('hour'); workingMomDeltaType = "hour"; } else { workingMom.startOf('month'); } for (var i = 0; i < (12 * 5); i++) { //var x = graphData.dyData[graphData.dyData.length-1 - i*2][0]; var xDate = this._findNearestX(graphData.dyData, workingMom.toDate().getTime()); if (!xDate) { workingMom.add(-1, workingMomDeltaType); continue; } var shortTxt, txt; if (rangeType == "1d") { shortTxt = workingMom.format("HH"); txt = workingMom.format("HH:mm"); } else { shortTxt = workingMom.format("MM"); txt = workingMom.format("MMMM"); } var ann = { series: "Series-A", x: xDate.getTime(), width: 20, height: 20, shortText: shortTxt, text: txt } annotations.push(ann); workingMom.add(-1, workingMomDeltaType); } return annotations; }; JGS.Demo7Page.prototype._findNearestX = function (dyData, epochMs) { // Binary search would be more for (var i = dyData.length - 1; i >= 0; i--) { if (dyData[i][0].getTime() <= epochMs) { return dyData[i][0]; } } return null; }; JGS.Demo7Page.prototype._onDyDrawCallback = function (dygraph, is_initial) { // console.log("_onDyDrawCallback"); // // //IE8 does not have new dates at time of callback, so use timer hack // if ($.support.cssFloat == false) { //IE<=8 // setTimeout(function (evt) { // var axisX = dygraph.xAxisRange(); // var axisXStartDateTm = new Date(axisX[0]); // var axisXEndDateTm = new Date(axisX[1]); // // this.detailStartDateTm = axisXStartDateTm; // this.detailEndDateTm = axisXEndDateTm; // }, 250); // return; // } // // var axisX = dygraph.xAxisRange(); // var axisXStartDateTm = new Date(axisX[0]); // var axisXEndDateTm = new Date(axisX[1]); // // this.detailStartDateTm = axisXStartDateTm; // this.detailEndDateTm = axisXEndDateTm; }; /** * Dygraphs zoom callback handler * * @method _onDyZoomCallback * @private */ JGS.Demo7Page.prototype._onDyZoomCallback = function (minDate, maxDate, yRanges) { //console.log("_onDyZoomCallback"); if (this.graph == null) return; this.detailStartDateTm = new Date(minDate); this.detailEndDateTm = new Date(maxDate); //When zoom reset via double-click, there is no mouse-up event in chrome (maybe a bug?), //so we initiate data load directly if (this.graph.isZoomed('x') === false) { this.$mouseUpEventEl.off("mouseup.jgs touchend.jgs"); //Cancel current event handler if any this._loadNewDetailData(); return; } //Check if need to do IE8 workaround if ($.support.cssFloat == false) { //IE<=8 // ie8 calls drawCallback with new dates before zoom. This example currently does not implement the // drawCallback, so this example might not work in IE8 currently. This next line _might_ solve, but will // result in duplicate loading when drawCallback is added back in. this._loadNewDetailData(); return; } //The zoom callback is called when zooming via mouse drag on graph area, as well as when //dragging the range selector bars. We only want to initiate dataload when mouse-drag zooming. The mouse //up handler takes care of loading data when dragging range selector bars. var doDataLoad = !this.isRangeSelectorActive; if (doDataLoad === true) this._loadNewDetailData(); }; /** * Helper method for showing/hiding spin indicator. Uses spin.js, but this method could just as easily * use a simple "data is loading..." div. * * @method showSpinner */ JGS.Demo7Page.prototype.showSpinner = function (show) { if (show === true) { var target = this.$graphCont.get(0); if (this.spinner == null) { var opts = { lines: 13, // The number of lines to draw length: 7, // The length of each line width: 6, // The line thickness radius: 10, // The radius of the inner circle corners: 1, // Corner roundness (0..1) rotate: 0, // The rotation offset color: '#000', // #rgb or #rrggbb speed: 1, // Rounds per second trail: 60, // Afterglow percentage shadow: false, // Whether to render a shadow hwaccel: false, // Whether to use hardware acceleration className: 'spinner', // The CSS class to assign to the spinner zIndex: 2e9 // The z-index (defaults to 2000000000) }; this.spinner = new Spinner(opts); this.spinner.spin(target); this.spinnerIsSpinning = true; } else { if (this.spinnerIsSpinning === false) { //else already spinning this.spinner.spin(target); this.spinnerIsSpinning = true; } } } else if (this.spinner != null && show === false) { this.spinner.stop(); this.spinnerIsSpinning = false; } }; }(window.JGS = window.JGS || {}, jQuery));
'use strict' /* global describe, it */ const assert = require('assert') describe('ShopProduct Model', () => { it('should exist', () => { assert(global.app.api.models['ShopProduct']) }) })
$(document).ready(function () { var regex = /^(?=(?:.*?[A-Z]){1})(?=(?:.*?[0-9]){1})(?=(?:.*?[a-z]){1})*$/; $('form').submit(function (e) { e.preventDefault(); if ($('#Senha').val() !== $('#RepetirSenha').val()) { alert("Senhas não condizem!"); return false; } else if ($('#Senha').val() < 8) { alert("Senha deve ter pelo menos 8 caracteres!"); return false; } else if ($(!regex.exec('#Senha').val())) { alert("Mínimo 1 minúsculo, 1 maiúsculo e 1 número!"); return false; } else { return true; } }); });
const path = require('path'); const rand = require('crypto-random-string'); const os = require('os'); const fs = require('fs'); const escapeUnsafe = require('./helpers/escapeUnsafe'); module.exports = function SitemapStream() { const tmpPath = path.join(os.tmpdir(), `sitemap_${rand(10)}`); const stream = fs.createWriteStream(tmpPath); stream.write('<?xml version="1.0" encoding="utf-8" standalone="yes" ?>'); stream.write( '\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' ); const getPath = () => tmpPath; const write = (url, currentDateTime, changeFreq, priority) => { const escapedUrl = escapeUnsafe(url); stream.write('\n <url>\n'); stream.write(` <loc>${escapedUrl}</loc>\n`); if (currentDateTime) { stream.write(` <lastmod>${currentDateTime}</lastmod>\n`); } if (changeFreq) { stream.write(` <changefreq>${changeFreq}</changefreq>\n`); } if (priority) { stream.write(` <priority>${priority}</priority>\n`); } stream.write(' </url>'); }; const end = () => { stream.write('\n</urlset>'); stream.end(); }; return { getPath, write, end, }; };
'use strict'; /** * @ngdoc function * @module ng * @name angular.injector * @function * * @description * Creates an injector function that can be used for retrieving services as well as for * dependency injection (see {@link guide/di dependency injection}). * * @param {Array.<string|Function>} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. * @returns {function()} Injector function. See {@link auto.$injector $injector}. * * @example * Typical usage * ```js * // create an injector * var $injector = angular.injector(['ng']); * * // use the injector to kick off your application * // use the type inference to auto inject arguments, or use implicit injection * $injector.invoke(function($rootScope, $compile, $document){ * $compile($document)($rootScope); * $rootScope.$digest(); * }); * ``` * * Sometimes you want to get access to the injector of a currently running Angular app * from outside Angular. Perhaps, you want to inject and compile some markup after the * application has been bootstrapped. You can do this using extra `injector()` added * to JQuery/jqLite elements. See {@link angular.element}. * * *This is fairly rare but could be the case if a third party library is injecting the * markup.* * * In the following example a new block of HTML containing a `ng-controller` * directive is added to the end of the document body by JQuery. We then compile and link * it into the current AngularJS scope. * * ```js * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>'); * $(document.body).append($div); * * angular.element(document).injector().invoke(function($compile) { * var scope = angular.element($div).scope(); * $compile($div)(scope); * }); * ``` */ /** * @ngdoc module * @name auto * @description * * Implicit module which gets automatically added to each {@link auto.$injector $injector}. */ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var $injectorMinErr = minErr('$injector'); function annotate(fn) { var $inject, fnText, argDecl, last; if (typeof fn == 'function') { if (!($inject = fn.$inject)) { $inject = []; if (fn.length) { fnText = fn.toString().replace(STRIP_COMMENTS, ''); argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, underscore, name){ $inject.push(name); }); }); } fn.$inject = $inject; } } else if (isArray(fn)) { last = fn.length - 1; assertArgFn(fn[last], 'fn'); $inject = fn.slice(0, last); } else { assertArgFn(fn, 'fn', true); } return $inject; } /////////////////////////////////////// /** * @ngdoc service * @name $injector * @function * * @description * * `$injector` is used to retrieve object instances as defined by * {@link auto.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * * ```js * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); * expect($injector.invoke(function($injector){ * return $injector; * }).toBe($injector); * ``` * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following are all valid ways of annotating function with injection arguments and are equivalent. * * ```js * // inferred (only works if code not minified/obfuscated) * $injector.invoke(function(serviceA){}); * * // annotated * function explicit(serviceA) {}; * explicit.$inject = ['serviceA']; * $injector.invoke(explicit); * * // inline * $injector.invoke(['serviceA', function(serviceA){}]); * ``` * * ## Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with * minification, and obfuscation tools since these tools change the argument names. * * ## `$inject` Annotation * By adding a `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. */ /** * @ngdoc method * @name $injector#get * * @description * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. * @return {*} The instance. */ /** * @ngdoc method * @name $injector#invoke * * @description * Invoke the method and supply the method arguments from the `$injector`. * * @param {!function} fn The function to invoke. Function parameters are injected according to the * {@link guide/di $inject Annotation} rules. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. * @returns {*} the value returned by the invoked `fn` function. */ /** * @ngdoc method * @name $injector#has * * @description * Allows the user to query if the particular service exist. * * @param {string} Name of the service to query. * @returns {boolean} returns true if injector has given service. */ /** * @ngdoc method * @name $injector#instantiate * @description * Create a new instance of JS type. The method takes a constructor function invokes the new * operator and supplies all of the arguments to the constructor function as specified by the * constructor annotation. * * @param {function} Type Annotated constructor function. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. * @returns {Object} new instance of `Type`. */ /** * @ngdoc method * @name $injector#annotate * * @description * Returns an array of service names which the function is requesting for injection. This API is * used by the injector to determine which services need to be injected into the function when the * function is invoked. There are three ways in which the function can be annotated with the needed * dependencies. * * # Argument names * * The simplest form is to extract the dependencies from the arguments of the function. This is done * by converting the function into a string using `toString()` method and extracting the argument * names. * ```js * // Given * function MyController($scope, $route) { * // ... * } * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * * This method does not work with code minification / obfuscation. For this reason the following * annotation strategies are supported. * * # The `$inject` property * * If a function has an `$inject` property and its value is an array of strings, then the strings * represent names of services to be injected into the function. * ```js * // Given * var MyController = function(obfuscatedScope, obfuscatedRoute) { * // ... * } * // Define function dependencies * MyController['$inject'] = ['$scope', '$route']; * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * * # The array notation * * It is often desirable to inline Injected functions and that's when setting the `$inject` property * is very inconvenient. In these situations using the array notation to specify the dependencies in * a way that survives minification is a better choice: * * ```js * // We wish to write this (not minification / obfuscation safe) * injector.invoke(function($compile, $rootScope) { * // ... * }); * * // We are forced to write break inlining * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { * // ... * }; * tmpFn.$inject = ['$compile', '$rootScope']; * injector.invoke(tmpFn); * * // To better support inline function the inline annotation is supported * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { * // ... * }]); * * // Therefore * expect(injector.annotate( * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) * ).toEqual(['$compile', '$rootScope']); * ``` * * @param {function|Array.<string|Function>} fn Function for which dependent service names need to * be retrieved as described above. * * @returns {Array.<string>} The names of the services which the function requires. */ /** * @ngdoc object * @name $provide * * @description * * The {@link auto.$provide $provide} service has a number of methods for registering components * with the {@link auto.$injector $injector}. Many of these functions are also exposed on * {@link angular.Module}. * * An Angular **service** is a singleton object created by a **service factory**. These **service * factories** are functions which, in turn, are created by a **service provider**. * The **service providers** are constructor functions. When instantiated they must contain a * property called `$get`, which holds the **service factory** function. * * When you request a service, the {@link auto.$injector $injector} is responsible for finding the * correct **service provider**, instantiating it and then calling its `$get` **service factory** * function to get the instance of the **service**. * * Often services have no configuration options and there is no need to add methods to the service * provider. The provider will be no more than a constructor function with a `$get` property. For * these cases the {@link auto.$provide $provide} service has additional helper methods to register * services without specifying a provider. * * * {@link auto.$provide#methods_provider provider(provider)} - registers a **service provider** with the * {@link auto.$injector $injector} * * {@link auto.$provide#methods_constant constant(obj)} - registers a value/object that can be accessed by * providers and services. * * {@link auto.$provide#methods_value value(obj)} - registers a value/object that can only be accessed by * services, not providers. * * {@link auto.$provide#methods_factory factory(fn)} - registers a service **factory function**, `fn`, * that will be wrapped in a **service provider** object, whose `$get` property will contain the * given factory function. * * {@link auto.$provide#methods_service service(class)} - registers a **constructor function**, `class` that * that will be wrapped in a **service provider** object, whose `$get` property will instantiate * a new object using the given constructor function. * * See the individual methods for more information and examples. */ /** * @ngdoc method * @name $provide#provider * @description * * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions * are constructor functions, whose instances are responsible for "providing" a factory for a * service. * * Service provider names start with the name of the service they provide followed by `Provider`. * For example, the {@link ng.$log $log} service has a provider called * {@link ng.$logProvider $logProvider}. * * Service provider objects can have additional methods which allow configuration of the provider * and its service. Importantly, you can configure what kind of service is created by the `$get` * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a * method {@link ng.$logProvider#debugEnabled debugEnabled} * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the * console or not. * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance * @example * * The following example shows how to create a simple event tracking service and register it using * {@link auto.$provide#methods_provider $provide.provider()}. * * ```js * // Define the eventTracker provider * function EventTrackerProvider() { * var trackingUrl = '/track'; * * // A provider method for configuring where the tracked events should been saved * this.setTrackingUrl = function(url) { * trackingUrl = url; * }; * * // The service factory function * this.$get = ['$http', function($http) { * var trackedEvents = {}; * return { * // Call this to track an event * event: function(event) { * var count = trackedEvents[event] || 0; * count += 1; * trackedEvents[event] = count; * return count; * }, * // Call this to save the tracked events to the trackingUrl * save: function() { * $http.post(trackingUrl, trackedEvents); * } * }; * }]; * } * * describe('eventTracker', function() { * var postSpy; * * beforeEach(module(function($provide) { * // Register the eventTracker provider * $provide.provider('eventTracker', EventTrackerProvider); * })); * * beforeEach(module(function(eventTrackerProvider) { * // Configure eventTracker provider * eventTrackerProvider.setTrackingUrl('/custom-track'); * })); * * it('tracks events', inject(function(eventTracker) { * expect(eventTracker.event('login')).toEqual(1); * expect(eventTracker.event('login')).toEqual(2); * })); * * it('saves to the tracking url', inject(function(eventTracker, $http) { * postSpy = spyOn($http, 'post'); * eventTracker.event('login'); * eventTracker.save(); * expect(postSpy).toHaveBeenCalled(); * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); * })); * }); * ``` */ /** * @ngdoc method * @name $provide#factory * @description * * Register a **service factory**, which will be called to return the service instance. * This is short for registering a service where its provider consists of only a `$get` property, * which is the given service factory function. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to * configure your service in a provider. * * @param {string} name The name of the instance. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand * for `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance * * @example * Here is an example of registering a service * ```js * $provide.factory('ping', ['$http', function($http) { * return function ping() { * return $http.send('/ping'); * }; * }]); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { * ping(); * }]); * ``` */ /** * @ngdoc method * @name $provide#service * @description * * Register a **service constructor**, which will be invoked with `new` to create the service * instance. * This is short for registering a service where its provider's `$get` property is the service * constructor function that will be used to instantiate the service instance. * * You should use {@link auto.$provide#methods_service $provide.service(class)} if you define your service * as a type/class. * * @param {string} name The name of the instance. * @param {Function} constructor A class (constructor function) that will be instantiated. * @returns {Object} registered provider instance * * @example * Here is an example of registering a service using * {@link auto.$provide#methods_service $provide.service(class)}. * ```js * var Ping = function($http) { * this.$http = $http; * }; * * Ping.$inject = ['$http']; * * Ping.prototype.send = function() { * return this.$http.get('/ping'); * }; * $provide.service('ping', Ping); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { * ping.send(); * }]); * ``` */ /** * @ngdoc method * @name $provide#value * @description * * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a * number, an array, an object or a function. This is short for registering a service where its * provider's `$get` property is a factory function that takes no arguments and returns the **value * service**. * * Value services are similar to constant services, except that they cannot be injected into a * module configuration function (see {@link angular.Module#config}) but they can be overridden by * an Angular * {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance * * @example * Here are some examples of creating value services. * ```js * $provide.value('ADMIN_USER', 'admin'); * * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); * * $provide.value('halfOf', function(value) { * return value / 2; * }); * ``` */ /** * @ngdoc method * @name $provide#constant * @description * * Register a **constant service**, such as a string, a number, an array, an object or a function, * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be * injected into a module configuration function (see {@link angular.Module#config}) and it cannot * be overridden by an Angular {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance * * @example * Here a some examples of creating constants: * ```js * $provide.constant('SHARD_HEIGHT', 306); * * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); * * $provide.constant('double', function(value) { * return value * 2; * }); * ``` */ /** * @ngdoc method * @name $provide#decorator * @description * * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator * intercepts the creation of a service, allowing it to override or modify the behaviour of the * service. The object returned by the decorator may be the original service, or a new service * object which replaces or wraps and delegates to the original service. * * @param {string} name The name of the service to decorate. * @param {function()} decorator This function will be invoked when the service needs to be * instantiated and should return the decorated service instance. The function is called using * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. * Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. * * @example * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting * calls to {@link ng.$log#error $log.warn()}. * ```js * $provide.decorator('$log', ['$delegate', function($delegate) { * $delegate.warn = $delegate.error; * return $delegate; * }]); * ``` */ function createInjector(modulesToLoad) { var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap(), providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, providerInjector = (providerCache.$injector = createInternalInjector(providerCache, function() { throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); })), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(servicename) { var provider = providerInjector.get(servicename + providerSuffix); return instanceInjector.invoke(provider.$get, provider); })); forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector; //////////////////////////////////// // $provider //////////////////////////////////// function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } }; } function provider(name, provider_) { assertNotHasOwnProperty(name, 'service'); if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); } return providerCache[name + providerSuffix] = provider_; } function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); } function value(name, val) { return factory(name, valueFn(val)); } function constant(name, value) { assertNotHasOwnProperty(name, 'constant'); providerCache[name] = value; instanceCache[name] = value; } function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); }; } //////////////////////////////////// // Module Loading //////////////////////////////////// function loadModules(modulesToLoad){ var runBlocks = [], moduleFn, invokeQueue, i, ii; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); try { if (isString(module)) { moduleFn = angularModule(module); runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { var invokeArgs = invokeQueue[i], provider = providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } } else if (isFunction(module)) { runBlocks.push(providerInjector.invoke(module)); } else if (isArray(module)) { runBlocks.push(providerInjector.invoke(module)); } else { assertArgFn(module, 'module'); } } catch (e) { if (isArray(module)) { module = module[module.length - 1]; } if (e.message && e.stack && e.stack.indexOf(e.message) == -1) { // Safari & FF's stack traces don't contain error.message content // unlike those of Chrome and IE // So if stack doesn't contain message, we create a new string that contains both. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. /* jshint -W022 */ e = e.message + '\n' + e.stack; } throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", module, e.stack || e.message || e); } }); return runBlocks; } //////////////////////////////////// // internal Injector //////////////////////////////////// function createInternalInjector(cache, factory) { function getService(serviceName) { if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName); } catch (err) { if (cache[serviceName] === INSTANTIATING) { delete cache[serviceName]; } throw err; } finally { path.shift(); } } } function invoke(fn, self, locals){ var args = [], $inject = annotate(fn), length, i, key; for(i = 0, length = $inject.length; i < length; i++) { key = $inject[i]; if (typeof key !== 'string') { throw $injectorMinErr('itkn', 'Incorrect injection token! Expected service name as string, got {0}', key); } args.push( locals && locals.hasOwnProperty(key) ? locals[key] : getService(key) ); } if (!fn.$inject) { // this means that we must be an array. fn = fn[length]; } // http://jsperf.com/angularjs-invoke-apply-vs-switch // #5388 return fn.apply(self, args); } function instantiate(Type, locals) { var Constructor = function() {}, instance, returnedValue; // Check if Type is annotated and use just the given function at n-1 as parameter // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; instance = new Constructor(); returnedValue = invoke(Type, instance, locals); return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance; } return { invoke: invoke, instantiate: instantiate, get: getService, annotate: annotate, has: function(name) { return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); } }; } }
'use strict'; ((rb, window, $) => { rb.cardGrids = rb.cardGrids || {}; const CSS = window.CSS; if (CSS && (CSS.supports('display', 'grid') || CSS.supports('display', '-ms-grid'))) { const document = window.document; const resizeGridItem = (item) => { const grid = $(item).closest('.card-grid')[0]; const rowHeight = parseInt($(grid).css('grid-auto-rows'), 10); const rowGap = parseInt($(grid).css('grid-row-gap'), 10); const itemPadding = parseInt($(item).css('paddingTop'), 10) + parseInt($(item).css('paddingBottom'), 10); const itemContentHeight = item.firstElementChild.getBoundingClientRect().height; const itemContentMargin = parseInt($(item.firstElementChild).css('marginTop'), 10) + parseInt($(item.firstElementChild).css('marginBottom'), 10); const rowSpan = Math.ceil( (itemContentHeight + itemContentMargin + itemPadding + rowGap) / (rowHeight + rowGap) ); item.style.gridRowEnd = `span ${rowSpan}`; }; const resizeAllGridItems = (gridSelector) => { const grids = document.querySelectorAll(gridSelector); grids.forEach((grid) => { const items = grid.querySelectorAll('.card-grid_item'); items.forEach((item) => { rb.cardGrids.resizeGridItem(item); }); }); }; const warnAboutGridSupport = () => { console.warn('Browser doesn\'t support CSS grid.'); }; rb.cardGrids.resizeGridItem = resizeGridItem || warnAboutGridSupport; rb.cardGrids.resizeAllGridItems = resizeAllGridItems || warnAboutGridSupport; rb.onDocumentReady(() => rb.cardGrids.resizeAllGridItems('.card-grid')); // Set rAF-throttled resize listener to call resizeAllGridItems. window.addEventListener('rb.optimizedResize', () => { rb.cardGrids.resizeAllGridItems('.card-grid'); }); } })(window.rb, window, jQuery);
/* * The MIT License * Copyright (c) 2014-2016 Nick Guletskii * * 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. */ import { has as _has } from "lodash"; const controller = /* @ngInject*/ ($scope, $stateParams, $q, $http, $translate, members, membersCount, GroupService, UserService) => { $scope.page = $stateParams.page; $scope.groupId = $stateParams.groupId; $scope.members = members; $scope.membersCount = membersCount; $scope.user = {}; function updateUsers() { GroupService .getMembersPage($stateParams.groupId, $stateParams.page) .then( (newMembers) => { $scope.members = newMembers; }); } $scope.userOptionProvider = (filterText) => { const deferred = $q.defer(); $http.get("/api/userCompletion", { params: { term: filterText } }) .then((response) => { deferred.resolve(response.data); }, () => { deferred.reject(); throw new Error("Principal completion failed."); }); return deferred.promise; }; class ButtonStatus { get isSuccess() { return this.lastAdded && ( (this.lastAdded === $scope.user.user) || (this.lastAdded === $scope.user.user.username) ); } get buttonMessage() { if (this.isSuccess) { return "groups.groupView.addUserButton.success"; } return "groups.groupView.addUserButton"; } } $scope.buttonStatus = new ButtonStatus(); $scope.addUser = (form) => { const deferred = $q.defer(); const username = form.user.username || form.user; UserService.addUserToGroup($stateParams.groupId, username) .then((data) => { const errorMapping = { "USER_ALREADY_IN_GROUP": "groups.groupView.addUser.userAlreadyInGroup", "NO_SUCH_USER": "groups.groupView.addUser.noSuchUser" }; if (_has(errorMapping, data)) { $translate([errorMapping[data]]) .then(map => { deferred.reject({ user: map[errorMapping[data]] }); }); } else { $scope.buttonStatus.data = { username }; $scope.buttonStatus.lastAdded = username; deferred.resolve(); updateUsers(); } }); return deferred.promise; }; $scope.removeUser = (user) => { UserService.removeUserFromGroup($stateParams.groupId, user.id) .then(updateUsers); }; }; export default { "name": "groupView", "url": "/groups/{groupId:[0-9]+}/", "templateUrl": "/partials/groups/group.html", controller, "params": { "page": "1" }, "resolve": { "members": /* @ngInject*/ (GroupService, $stateParams) => GroupService.getMembersPage($stateParams.groupId, $stateParams.page), "membersCount": /* @ngInject*/ (GroupService, $stateParams) => GroupService.countMembers($stateParams.groupId) }, "data": { canAccess: /* @ngInject*/ (PromiseUtils, SecurityService, $refStateParams) => PromiseUtils.and( SecurityService.hasPermission("list_groups"), SecurityService.hasGroupPermission($refStateParams.groupId, "view_members") ) } };
var q = require('q'); var qfs = require('q-io/fs'); var mkdirp = require('mkdirp'); var origExec = require('child_process').exec; var exec = function(cmd, cb) { console.log('Running ' + cmd); return origExec(cmd, cb); } function mkdir(dir) { var d = q.defer(); mkdirp(dir, function(err) { if (err) { d.reject(err); } d.resolve(); }); return d.promise; } function writeFile(path, contents) { var pathDir = path.match(/.*\//)[0]; return mkdir(pathDir).then(function() { return qfs.write(path, contents); }); } function readFile(path, encoding) { return qfs.exists(path).then(function(theFileExists) { if (theFileExists) { return qfs.read(path); } else { return q(null); } }); } function execDart2JS(dir, mainDart, checkedMode) { var d = q.defer(); var checked = checkedMode !== false ? '--checked ' : ''; exec( 'cd ' + dir + ' && ' + 'dart2js ' + checked + mainDart + ' -o ' + mainDart + '.js', function (err, stdout, stderr) { if (err) { console.log('error: ' + err); } console.log(stdout); console.log(stderr); d.resolve(dir + mainDart + '.js'); }); return d.promise; } function execDartVersion() { var d = q.defer(); exec('dart --version', function (err, _, stderr) { console.log('Dart version:', stderr); if (err) { d.reject(err); return; } d.resolve(stderr); }); return d.promise; } function execZip(parentDir, dirName) { var d = q.defer(); console.log('cd ' + parentDir + ' && zip -rq ' + dirName + '.zip ' + dirName); exec( 'cd ' + parentDir + ' && zip -rq ' + dirName + '.zip ' + dirName, function (err, stdout, stderr) { if (err) { console.log('error: ' + err); } console.log(stdout); console.log(stderr); d.resolve(parentDir + dirName + '.zip'); }); return d.promise; } module.exports = { writeFile: writeFile, readFile: readFile, execDart2JS: execDart2JS, execZip: execZip, execDartVersion: execDartVersion };
const debug = require('@tryghost/debug')('web:api:v2:content:app'); const boolParser = require('express-query-boolean'); const bodyParser = require('body-parser'); const express = require('../../../../../shared/express'); const shared = require('../../../shared'); const routes = require('./routes'); module.exports = function setupApiApp() { debug('Content API v2 setup start'); const apiApp = express('v2 content'); // API middleware // @NOTE: req.body is undefined if we don't use this parser, this can trouble if components rely on req.body being present apiApp.use(bodyParser.json({limit: '1mb'})); // Query parsing apiApp.use(boolParser()); // API shouldn't be cached apiApp.use(shared.middleware.cacheControl('private')); // Routing apiApp.use(routes()); // API error handling apiApp.use(shared.middleware.errorHandler.resourceNotFound); apiApp.use(shared.middleware.errorHandler.handleJSONResponse); debug('Content API v2 setup end'); return apiApp; };
/* eslint-disable import/prefer-default-export, camelcase */ export { unstable_Box } from './Box';
/******************************************************************************* * @route NodeJS Sandbox * @author Jaroslaw Predki *******************************************************************************/ var express = require( 'express' ); var router = express.Router(); //------------------------------------------------------------------------------ // @route GET / //------------------------------------------------------------------------------ router.get( '/', function( req, res, next ) { // render the page res.render( 'sandbox/sandbox-info', { title: 'Information', subtitle: 'Frameworks, Libraries, SDK\'s & API\'s' }); }); module.exports = router; /******************************************************************************* *******************************************************************************/
const { avatar_upload, login_cellphone } = require('../server') const fs = require('fs') const path = require('path') async function main() { const result = await login_cellphone({ phone: '手机号', password: '密码', }) const filePath = './test.jpg' await avatar_upload({ imgFile: { name: path.basename(filePath), data: fs.readFileSync(filePath), }, imgSize: 1012, //图片尺寸,需要正方形图片 cookie: result.body.cookie, }) } main()
/** * Datatable Service will ensure the coherence column between the back side and the view * @author: Kihansi */ //TODO failed, find the way to be able to create a generator //create generator function Generator(attributes) { this.columns = _.clone(attributes); this.dtProjection = () => { return {select: Object.keys(this.columns)}; }; this.dtHeaderHtml = () => { let attributeHeader = ''; for(let columnHtml of Object.values(this.columns)) { attributeHeader += '<th>' + columnHtml + '</th>'; } return '<thead><tr>' + attributeHeader + '</tr> </thead>'; }; this.dtColumnsJs = () => { let js = '['; for(let column of Object.keys(this.columns)) { js += '{ "data" : "' + column +'" },'; } return js.replace(/.$/, ']'); //replace the last ',' by ] }; } module.exports = { /** * How to use: * -- In controller: * DatatablesService.generateDatatable({ * 'column1': 'My column 1', * 'column2': 'My column 2', * }, (dtgenerator) => { * if(!dtgenerator) { * // error some where * return; * } * * MyModel.find({'field':'value'}, generator.dtProjection()).exec((err, records) => { * //... * * return res.view('...', { * ..., * dtgenerator: dtgenerator * }); * }) * } * * -- In view: * <html> * .... * <table id='datatable ...> * <theader><%= datagenerator.dtHeaderHtml() %></theader> * </table> * ... * <script> * $('#datatable').Datatables({ * ajax: { * ... * }, * columns: <%= datagenerator.dtColumnsJs() %> * }); * </script> * </html> */ /** * Generate an object that will generate the html and the queries from an array of string * @param attributes: Object {'attribute': 'Name in html'} * @param callback: function(datatable) * @returns Object datatables */ getGenerator: function(attributes, callback) { // asset if(!attributes || _.isEmpty(attributes)) { sails.log.error('[DatatablesService.generateDatatable] attribute is not defined, given parameter: '); sails.log.error(attributes); return callback(false); } return Generator(attributes); } };
// Generated by CoffeeScript 1.10.0 var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Hyle.FileLayerInstance = (function(superClass) { extend(FileLayerInstance, superClass); function FileLayerInstance(data) { this.file = {}; FileLayerInstance.__super__.constructor.apply(this, arguments); this.setDefaults({ label: 5 }); this.initiate(data); this; } FileLayerInstance.prototype.render = function() { this.file = hyle.parser.fileItemsCollection.getFileOrImport(this.data.file); return FileLayerInstance.__super__.render.call(this, this.data.AVCompItemTarget.layers.add(this.file)); }; return FileLayerInstance; })(Hyle.LayerInstance);
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'showblocks', 'sq', { toolbar: 'Shfaq Blloqet' });
$(document).ready(function (e) { if ($("form[data-parsley-validate]").length > 0) { $("form[data-parsley-validate]").parsley(); } if ($('.datepicker').length > 0) { $('.datepicker').datepicker({ clearBtn: true, format: "yyyy-mm-dd" }); } if ($('.selectpicker').length > 0) { $('.selectpicker').selectpicker(); } if ($('.summernote').length > 0) { $('.summernote').summernote({ minHeight: 100 }); } if ($("[id$='-manage-table']").length > 0) { $.each($("[id$='-manage-table']"), function (index, table) { var tableIndex = camelize(table.id); window[tableIndex] = $(table).DataTable({ dom: '<"col-sm-4"l><"col-sm-4"B><"col-sm-4"f><"col-sm-6"i><"col-sm-6"p>rTt', serverSide: true, ajax: { url: $(table).data("render-url"), type: 'POST' }, buttons: [ 'copy', 'csv', 'excel', 'pdf', 'print' ], fnDrawCallback: function (oSettings) { $(table).find('.dropdown-toggle').dropdown(); } }); $(document).on("click", "#" + table.id + " .change-status", function (e) { e.preventDefault(); var id = $(this).data("id"); var status = $(this).data("status"); var statusKey = $(table).data("status-key"); var inputOptions = []; var statuses = $(table).data("statuses"); statuses.forEach(function (stat, index) { inputOptions.push({ text: stat.name, value: stat[statusKey] }); }); bootbox.prompt({ title: "Please select the status", inputType: 'select', value: status, inputOptions: inputOptions, callback: function (output) { if (output && output != status) { var data = new FormData(); data.append('id', id); data.append('status', output); $.ajax({ url: $(table).data("status-action"), data: data, contentType: false, processData: false, type: $(table).data("status-method"), success: function (response) { var result = JSON.parse(response); if (result.success) { window[tableIndex].draw(); } $.notify(result.message, { type: result.type || "error", allow_dismiss: true, showProgressbar: false, placement: { from: "bottom", align: "right" } }); } }); } } }); $('.bootbox-prompt select').selectpicker(); }); }); } }); function camelize(str) { return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function (match, index) { if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces return index === 0 ? match.toLowerCase() : match.toUpperCase(); }).replace(/-/g, ''); } $(document).on("submit", "form[data-parsley-validate]", function (e) { e.preventDefault(); var l = Ladda.create($(this).find('button[type=submit]')[0]); l.start(); var data = new FormData($(this)[0]); $.ajax({ url: $(this).attr("action"), data: data, contentType: false, processData: false, type: $(this).attr("method"), success: function (response) { try { var result = JSON.parse(response); if (result.success) { window.location.href = result.url; } else { $.notify(result.message, { type: result.type || "error", allow_dismiss: true, showProgressbar: false, placement: { from: "bottom", align: "right" } }); } } catch (exception) { $.notify("You are logged out of the portal!<br>Please use a new tab to login and try again.", { type: "warning", allow_dismiss: true, showProgressbar: false, placement: { from: "bottom", align: "right" } }); } }, complete: function () { l.stop(); } }); }); $(document).on("click", "#logout", function (e) { e.preventDefault(); $.ajax({ url: $(this).data("action"), contentType: false, processData: false, type: $(this).data("method"), success: function (response) { var result = JSON.parse(response); if (result.success) { window.location.href = result.url; } } }); });
/** * @package Regular Labs Library * @version 17.2.15002 * * @author Peter van Westen <info@regularlabs.com> * @link http://www.regularlabs.com * @copyright Copyright © 2017 Regular Labs All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ /** * BASED ON: * jQuery MiniColors: A tiny color picker built on jQuery * Copyright Cory LaViska for A Beautiful Site, LLC. (http://www.abeautifulsite.net/) * Dual-licensed under the MIT and GPL Version 2 licenses * */ if (jQuery) (function($) { $(document).ready(function() { $('.rl_color').minicolors(); }); // Yay, MiniColors! $.minicolors = { // Default settings defaultSettings: { animationSpeed : 100, animationEasing: 'swing', change : null, changeDelay : 0, control : 'hue', defaultValue : '', hide : null, hideSpeed : 100, inline : false, letterCase : 'lowercase', opacity : false, position : 'default', show : null, showSpeed : 100, swatchPosition : 'left', textfield : true, theme : 'default' } }; // Public methods $.extend($.fn, { minicolors: function(method, data) { switch (method) { // Destroy the control case 'destroy': $(this).each(function() { destroy($(this)); }); return $(this); // Get/set opacity case 'opacity': if (data === undefined) { // Getter return $(this).attr('data-opacity'); } else { // Setter $(this).each(function() { refresh($(this).attr('data-opacity', data)); }); return $(this); } // Get an RGB(A) object based on the current color/opacity case 'rgbObject': return rgbObject($(this), method === 'rgbaObject'); // Get an RGB(A) string based on the current color/opacity case 'rgbString': case 'rgbaString': return rgbString($(this), method === 'rgbaString'); // Get/set settings on the fly case 'settings': if (data === undefined) { return $(this).data('minicolors-settings'); } else { // Setter $(this).each(function() { var settings = $(this).data('minicolors-settings') || {}; destroy($(this)); $(this).minicolors($.extend(true, settings, data)); }); return $(this); } // Get/set the hex color value case 'value': if (data === undefined) { // Getter return $(this).val(); } else { // Setter $(this).each(function() { refresh($(this).val(data)); }); return $(this); } // Initializes the control case 'create': default: if (method !== 'create') data = method; $(this).each(function() { init($(this), data); }); return $(this); } } }); // Initialize input elements function init(input, settings) { var minicolors = $('<span class="minicolors" />'), defaultSettings = $.minicolors.defaultSettings; // Do nothing if already initialized if (input.data('minicolors-initialized')) return; // Handle settings settings = $.extend(true, {}, defaultSettings, settings); // The wrapper minicolors .addClass('minicolors-theme-' + settings.theme) .addClass('minicolors-swatch-position-' + settings.swatchPosition) .toggleClass('minicolors-swatch-left', settings.swatchPosition === 'left') .toggleClass('minicolors-with-opacity', settings.opacity); // Custom positioning if (settings.position !== undefined) { $.each(settings.position.split(' '), function() { minicolors.addClass('minicolors-position-' + this); }); } // The input input .addClass('minicolors-input') .data('minicolors-initialized', true) .data('minicolors-settings', settings) .prop('size', 7) .prop('maxlength', 7) .wrap(minicolors) .after( '<span class="minicolors-panel minicolors-slider-' + settings.control + '">' + '<span class="minicolors-slider">' + '<span class="minicolors-picker"></span>' + '</span>' + '<span class="minicolors-opacity-slider">' + '<span class="minicolors-picker"></span>' + '</span>' + '<span class="minicolors-grid">' + '<span class="minicolors-grid-inner"></span>' + '<span class="minicolors-picker"><span></span></span>' + '</span>' + '</span>' ); // Prevent text selection in IE input.parent().find('.minicolors-panel').on('selectstart', function() { return false; }).end(); // Detect swatch position if (settings.swatchPosition === 'left') { // Left input.before('<span class="minicolors-swatch"><span></span></span>'); } else { // Right input.after('<span class="minicolors-swatch"><span></span></span>'); } // Disable textfield if (!settings.textfield) input.addClass('minicolors-hidden'); // Inline controls if (settings.inline) input.parent().addClass('minicolors-inline'); updateFromInput(input); } // Returns the input back to its original state function destroy(input) { var minicolors = input.parent(); // Revert the input element input .removeData('minicolors-initialized') .removeData('minicolors-settings') .removeProp('size') .removeProp('maxlength') .removeClass('minicolors-input'); // Remove the wrap and destroy whatever remains minicolors.before(input).remove(); } // Refresh the specified control function refresh(input) { updateFromInput(input); } // Shows the specified dropdown panel function show(input) { var minicolors = input.parent(), panel = minicolors.find('.minicolors-panel'), settings = input.data('minicolors-settings'); // Do nothing if uninitialized, disabled, or already open if (!input.data('minicolors-initialized') || input.prop('disabled') || minicolors.hasClass('minicolors-focus')) return; hide(); minicolors.addClass('minicolors-focus'); panel .stop(true, true) .fadeIn(settings.showSpeed, function() { if (settings.show) settings.show.call(input); }); } // Hides all dropdown panels function hide() { $('.minicolors-input').each(function() { var input = $(this), settings = input.data('minicolors-settings'), minicolors = input.parent(); // Don't hide inline controls if (settings.inline) return; minicolors.find('.minicolors-panel').fadeOut(settings.hideSpeed, function() { if (minicolors.hasClass('minicolors-focus')) { if (settings.hide) settings.hide.call(input); } minicolors.removeClass('minicolors-focus'); }); }); } // Moves the selected picker function move(target, event, animate) { var input = target.parents('.minicolors').find('.minicolors-input'), settings = input.data('minicolors-settings'), picker = target.find('[class$=-picker]'), offsetX = target.offset().left, offsetY = target.offset().top, x = Math.round(event.pageX - offsetX), y = Math.round(event.pageY - offsetY), duration = animate ? settings.animationSpeed : 0, wx, wy, r, phi; // Touch support if (event.originalEvent.changedTouches) { x = event.originalEvent.changedTouches[0].pageX - offsetX; y = event.originalEvent.changedTouches[0].pageY - offsetY; } // Constrain picker to its container if (x < 0) x = 0; if (y < 0) y = 0; if (x > target.width()) x = target.width(); if (y > target.height()) y = target.height(); // Constrain color wheel values to the wheel if (target.parent().is('.minicolors-slider-wheel') && picker.parent().is('.minicolors-grid')) { wx = 75 - x; wy = 75 - y; r = Math.sqrt(wx * wx + wy * wy); phi = Math.atan2(wy, wx); if (phi < 0) phi += Math.PI * 2; if (r > 75) { r = 75; x = 75 - (75 * Math.cos(phi)); y = 75 - (75 * Math.sin(phi)); } x = Math.round(x); y = Math.round(y); } // Move the picker if (target.is('.minicolors-grid')) { picker .stop(true) .animate({ top : y + 'px', left: x + 'px' }, duration, settings.animationEasing, function() { updateFromControl(input); }); } else { picker .stop(true) .animate({ top: y + 'px' }, duration, settings.animationEasing, function() { updateFromControl(input); }); } } // Sets the input based on the color picker values function updateFromControl(input) { function getCoords(picker, container) { var left, top; if (!picker.length || !container) return null; left = picker.offset().left; top = picker.offset().top; return { x: left - container.offset().left + (picker.outerWidth() / 2), y: top - container.offset().top + (picker.outerHeight() / 2) }; } var hue, saturation, brightness, opacity, rgb, hex, x, y, r, phi, // Helpful references minicolors = input.parent(), settings = input.data('minicolors-settings'), panel = minicolors.find('.minicolors-panel'), swatch = minicolors.find('.minicolors-swatch'), // Panel objects grid = minicolors.find('.minicolors-grid'), slider = minicolors.find('.minicolors-slider'), opacitySlider = minicolors.find('.minicolors-opacity-slider'), // Picker objects gridPicker = grid.find('[class$=-picker]'), sliderPicker = slider.find('[class$=-picker]'), opacityPicker = opacitySlider.find('[class$=-picker]'), // Picker positions gridPos = getCoords(gridPicker, grid), sliderPos = getCoords(sliderPicker, slider), opacityPos = getCoords(opacityPicker, opacitySlider); // Determine HSB values switch (settings.control) { case 'wheel': // Calculate hue, saturation, and brightness x = (grid.width() / 2) - gridPos.x; y = (grid.height() / 2) - gridPos.y; r = Math.sqrt(x * x + y * y); phi = Math.atan2(y, x); if (phi < 0) phi += Math.PI * 2; if (r > 75) { r = 75; gridPos.x = 69 - (75 * Math.cos(phi)); gridPos.y = 69 - (75 * Math.sin(phi)); } saturation = keepWithin(r / 0.75, 0, 100); hue = keepWithin(phi * 180 / Math.PI, 0, 360); brightness = keepWithin(100 - Math.floor(sliderPos.y * (100 / slider.height())), 0, 100); hex = hsb2hex({ h: hue, s: saturation, b: brightness }); // Update UI slider.css('backgroundColor', hsb2hex({h: hue, s: saturation, b: 100})); break; case 'saturation': // Calculate hue, saturation, and brightness hue = keepWithin(parseInt(gridPos.x * (360 / grid.width())), 0, 360); saturation = keepWithin(100 - Math.floor(sliderPos.y * (100 / slider.height())), 0, 100); brightness = keepWithin(100 - Math.floor(gridPos.y * (100 / grid.height())), 0, 100); hex = hsb2hex({ h: hue, s: saturation, b: brightness }); // Update UI slider.css('backgroundColor', hsb2hex({h: hue, s: 100, b: brightness})); minicolors.find('.minicolors-grid-inner').css('opacity', saturation / 100); break; case 'brightness': // Calculate hue, saturation, and brightness hue = keepWithin(parseInt(gridPos.x * (360 / grid.width())), 0, 360); saturation = keepWithin(100 - Math.floor(gridPos.y * (100 / grid.height())), 0, 100); brightness = keepWithin(100 - Math.floor(sliderPos.y * (100 / slider.height())), 0, 100); hex = hsb2hex({ h: hue, s: saturation, b: brightness }); // Update UI slider.css('backgroundColor', hsb2hex({h: hue, s: saturation, b: 100})); minicolors.find('.minicolors-grid-inner').css('opacity', 1 - (brightness / 100)); break; default: // Calculate hue, saturation, and brightness hue = keepWithin(360 - parseInt(sliderPos.y * (360 / slider.height())), 0, 360); saturation = keepWithin(Math.floor(gridPos.x * (100 / grid.width())), 0, 100); brightness = keepWithin(100 - Math.floor(gridPos.y * (100 / grid.height())), 0, 100); hex = hsb2hex({ h: hue, s: saturation, b: brightness }); // Update UI grid.css('backgroundColor', hsb2hex({h: hue, s: 100, b: 100})); break; } // Determine opacity if (settings.opacity) { opacity = parseFloat(1 - (opacityPos.y / opacitySlider.height())).toFixed(2); } else { opacity = 1; } // Adjust case input.val(convertCase(hex, settings.letterCase)); if (settings.opacity) input.attr('data-opacity', opacity); // Set swatch color swatch.find('SPAN').css({ backgroundColor: hex, opacity : opacity }); // Handle change event if (hex + opacity !== input.data('minicolors-lastChange')) { // Remember last-changed value input.data('minicolors-lastChange', hex + opacity); // Fire change event if (settings.change) { if (settings.changeDelay) { // Call after a delay clearTimeout(input.data('minicolors-changeTimeout')); input.data('minicolors-changeTimeout', setTimeout(function() { settings.change.call(input, hex, opacity); }, settings.changeDelay)); } else { // Call immediately settings.change.call(input, hex, opacity); } } } } // Sets the color picker values from the input function updateFromInput(input, preserveInputValue) { var hex, hsb, opacity, x, y, r, phi, // Helpful references minicolors = input.parent(), settings = input.data('minicolors-settings'), swatch = minicolors.find('.minicolors-swatch'), // Panel objects grid = minicolors.find('.minicolors-grid'), slider = minicolors.find('.minicolors-slider'), opacitySlider = minicolors.find('.minicolors-opacity-slider'), // Picker objects gridPicker = grid.find('[class$=-picker]'), sliderPicker = slider.find('[class$=-picker]'), opacityPicker = opacitySlider.find('[class$=-picker]'); // Determine hex/HSB values hex = convertCase(parseHex(input.val(), true), settings.letterCase); if (!hex) hex = convertCase(parseHex(settings.defaultValue, true)); hsb = hex2hsb(hex); // Update input value if (!preserveInputValue) input.val(hex); // Determine opacity value if (settings.opacity) { opacity = input.attr('data-opacity') === '' ? 1 : keepWithin(parseFloat(input.attr('data-opacity')).toFixed(2), 0, 1); input.attr('data-opacity', opacity); swatch.find('SPAN').css('opacity', opacity); // Set opacity picker position y = keepWithin(opacitySlider.height() - (opacitySlider.height() * opacity), 0, opacitySlider.height()); opacityPicker.css('top', y + 'px'); } // Update swatch swatch.find('SPAN').css('backgroundColor', hex); // Determine picker locations switch (settings.control) { case 'wheel': // Set grid position r = keepWithin(Math.ceil(hsb.s * 0.75), 0, grid.height() / 2); phi = hsb.h * Math.PI / 180; x = keepWithin(75 - Math.cos(phi) * r, 0, grid.width()); y = keepWithin(75 - Math.sin(phi) * r, 0, grid.height()); gridPicker.css({ top : y + 'px', left: x + 'px' }); // Set slider position y = 150 - (hsb.b / (100 / grid.height())); if (hex === '') y = 0; sliderPicker.css('top', y + 'px'); // Update panel color slider.css('backgroundColor', hsb2hex({h: hsb.h, s: hsb.s, b: 100})); break; case 'saturation': // Set grid position x = keepWithin((5 * hsb.h) / 12, 0, 150); y = keepWithin(grid.height() - Math.ceil(hsb.b / (100 / grid.height())), 0, grid.height()); gridPicker.css({ top : y + 'px', left: x + 'px' }); // Set slider position y = keepWithin(slider.height() - (hsb.s * (slider.height() / 100)), 0, slider.height()); sliderPicker.css('top', y + 'px'); // Update UI slider.css('backgroundColor', hsb2hex({h: hsb.h, s: 100, b: hsb.b})); minicolors.find('.minicolors-grid-inner').css('opacity', hsb.s / 100); break; case 'brightness': // Set grid position x = keepWithin((5 * hsb.h) / 12, 0, 150); y = keepWithin(grid.height() - Math.ceil(hsb.s / (100 / grid.height())), 0, grid.height()); gridPicker.css({ top : y + 'px', left: x + 'px' }); // Set slider position y = keepWithin(slider.height() - (hsb.b * (slider.height() / 100)), 0, slider.height()); sliderPicker.css('top', y + 'px'); // Update UI slider.css('backgroundColor', hsb2hex({h: hsb.h, s: hsb.s, b: 100})); minicolors.find('.minicolors-grid-inner').css('opacity', 1 - (hsb.b / 100)); break; default: // Set grid position x = keepWithin(Math.ceil(hsb.s / (100 / grid.width())), 0, grid.width()); y = keepWithin(grid.height() - Math.ceil(hsb.b / (100 / grid.height())), 0, grid.height()); gridPicker.css({ top : y + 'px', left: x + 'px' }); // Set slider position y = keepWithin(slider.height() - (hsb.h / (360 / slider.height())), 0, slider.height()); sliderPicker.css('top', y + 'px'); // Update panel color grid.css('backgroundColor', hsb2hex({h: hsb.h, s: 100, b: 100})); break; } } // Generates an RGB(A) object based on the input's value function rgbObject(input) { var hex = parseHex($(input).val(), true), rgb = hex2rgb(hex), opacity = $(input).attr('data-opacity'); if (!rgb) return null; if (opacity !== undefined) $.extend(rgb, {a: parseFloat(opacity)}); return rgb; } // Genearates an RGB(A) string based on the input's value function rgbString(input, alpha) { var hex = parseHex($(input).val(), true), rgb = hex2rgb(hex), opacity = $(input).attr('data-opacity'); if (!rgb) return null; if (opacity === undefined) opacity = 1; if (alpha) { return 'rgba(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ', ' + parseFloat(opacity) + ')'; } else { return 'rgb(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ')'; } } // Converts to the letter case specified in settings function convertCase(string, letterCase) { return letterCase === 'uppercase' ? string.toUpperCase() : string.toLowerCase(); } // Parses a string and returns a valid hex string when possible function parseHex(string, expand) { string = string.replace(/[^A-F0-9]/ig, ''); if (string.length !== 3 && string.length !== 6) return ''; if (string.length === 3 && expand) { string = string[0] + string[0] + string[1] + string[1] + string[2] + string[2]; } return '#' + string; } // Keeps value within min and max function keepWithin(value, min, max) { if (value < min) value = min; if (value > max) value = max; return value; } // Converts an HSB object to an RGB object function hsb2rgb(hsb) { var rgb = {}; var h = Math.round(hsb.h); var s = Math.round(hsb.s * 255 / 100); var v = Math.round(hsb.b * 255 / 100); if (s === 0) { rgb.r = rgb.g = rgb.b = v; } else { var t1 = v; var t2 = (255 - s) * v / 255; var t3 = (t1 - t2) * (h % 60) / 60; if (h === 360) h = 0; if (h < 60) { rgb.r = t1; rgb.b = t2; rgb.g = t2 + t3; } else if (h < 120) { rgb.g = t1; rgb.b = t2; rgb.r = t1 - t3; } else if (h < 180) { rgb.g = t1; rgb.r = t2; rgb.b = t2 + t3; } else if (h < 240) { rgb.b = t1; rgb.r = t2; rgb.g = t1 - t3; } else if (h < 300) { rgb.b = t1; rgb.g = t2; rgb.r = t2 + t3; } else if (h < 360) { rgb.r = t1; rgb.g = t2; rgb.b = t1 - t3; } else { rgb.r = 0; rgb.g = 0; rgb.b = 0; } } return { r: Math.round(rgb.r), g: Math.round(rgb.g), b: Math.round(rgb.b) }; } // Converts an RGB object to a hex string function rgb2hex(rgb) { var hex = [ rgb.r.toString(16), rgb.g.toString(16), rgb.b.toString(16) ]; $.each(hex, function(nr, val) { if (val.length === 1) hex[nr] = '0' + val; }); return '#' + hex.join(''); } // Converts an HSB object to a hex string function hsb2hex(hsb) { return rgb2hex(hsb2rgb(hsb)); } // Converts a hex string to an HSB object function hex2hsb(hex) { var hsb = rgb2hsb(hex2rgb(hex)); if (hsb.s === 0) hsb.h = 360; return hsb; } // Converts an RGB object to an HSB object function rgb2hsb(rgb) { var hsb = {h: 0, s: 0, b: 0}; var min = Math.min(rgb.r, rgb.g, rgb.b); var max = Math.max(rgb.r, rgb.g, rgb.b); var delta = max - min; hsb.b = max; hsb.s = max !== 0 ? 255 * delta / max : 0; if (hsb.s !== 0) { if (rgb.r === max) { hsb.h = (rgb.g - rgb.b) / delta; } else if (rgb.g === max) { hsb.h = 2 + (rgb.b - rgb.r) / delta; } else { hsb.h = 4 + (rgb.r - rgb.g) / delta; } } else { hsb.h = -1; } hsb.h *= 60; if (hsb.h < 0) { hsb.h += 360; } hsb.s *= 100 / 255; hsb.b *= 100 / 255; return hsb; } // Converts a hex string to an RGB object function hex2rgb(hex) { hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16); return { r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF) }; } // Handle events $(document) // Hide on clicks outside of the control .on('mousedown.minicolors touchstart.minicolors', function(event) { if (!$(event.target).parents().add(event.target).hasClass('minicolors')) { hide(); } }) // Start moving .on('mousedown.minicolors touchstart.minicolors', '.minicolors-grid, .minicolors-slider, .minicolors-opacity-slider', function(event) { var target = $(this); event.preventDefault(); $(document).data('minicolors-target', target); move(target, event, true); }) // Move pickers .on('mousemove.minicolors touchmove.minicolors', function(event) { var target = $(document).data('minicolors-target'); if (target) move(target, event); }) // Stop moving .on('mouseup.minicolors touchend.minicolors', function() { $(this).removeData('minicolors-target'); }) // Toggle panel when swatch is clicked .on('mousedown.minicolors touchstart.minicolors', '.minicolors-swatch', function() { var input = $(this).parent().find('.minicolors-input'), minicolors = input.parent(); if (minicolors.hasClass('minicolors-focus')) { hide(input); } else { show(input); } }) // Show on focus .on('focus.minicolors', '.minicolors-input', function() { var input = $(this); if (!input.data('minicolors-initialized')) return; show(input); }) // Fix hex and hide on blur .on('blur.minicolors', '.minicolors-input', function() { var input = $(this), settings = input.data('minicolors-settings'); if (!input.data('minicolors-initialized')) return; // Parse Hex input.val(parseHex(input.val(), true)); // Is it blank? if (input.val() === '') input.val(parseHex(settings.defaultValue, true)); // Adjust case input.val(convertCase(input.val(), settings.letterCase)); hide(input); }) // Handle keypresses .on('keydown.minicolors', '.minicolors-input', function(event) { var input = $(this); if (!input.data('minicolors-initialized')) return; switch (event.keyCode) { case 9: // tab hide(); break; case 27: // esc hide(); input.blur(); break; } }) // Update on keyup .on('keyup.minicolors', '.minicolors-input', function() { var input = $(this); if (!input.data('minicolors-initialized')) return; updateFromInput(input, true); }) // Update on paste .on('paste.minicolors', '.minicolors-input', function() { var input = $(this); if (!input.data('minicolors-initialized')) return; setTimeout(function() { updateFromInput(input, true); }, 1); }); })(jQuery);
steal('a', 'b', function (__a, __b) { var a = __a, b = __b; exports.action = function () { console.log(`hello world`); }; });
// [Working example](/serviceworker-cookbook/json-cache/). var CACHE_NAME = 'dependencies-cache'; self.addEventListener('install', function(event) { // Perform the install step: // * Load a JSON file from server // * Parse as JSON // * Add files to the cache list // Message to simply show the lifecycle flow console.log('[install] Kicking off service worker registration!'); event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { // With the cache opened, load a JSON file containing an array of files to be cached return fetch('files-to-cache.json').then(function(response) { // Once the contents are loaded, convert the raw text to a JavaScript object return response.json(); }).then(function(files) { // Use cache.addAll just as you would a hardcoded array of items console.log('[install] Adding files from JSON file: ', files); return cache.addAll(files); }); }) .then(function() { // Message to simply show the lifecycle flow console.log( '[install] All required resources have been cached;', 'the Service Worker was successfully installed!' ); // Force activation return self.skipWaiting(); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return the response from the cached version if (response) { console.log( '[fetch] Returning from Service Worker cache: ', event.request.url ); return response; } // Not in cache - return the result from the live server // `fetch` is essentially a "fallback" console.log('[fetch] Returning from server: ', event.request.url); return fetch(event.request); } ) ); }); self.addEventListener('activate', function(event) { // Message to simply show the lifecycle flow console.log('[activate] Activating service worker!'); // Claim the service work for this client, forcing `controllerchange` event console.log('[activate] Claiming this service worker!'); event.waitUntil(self.clients.claim()); });
// Generated by CoffeeScript 2.1.1 (function() { // out: ../lib/index.js, sourcemap: true /* * @overview Contains the entry point for the right click context menu * @module tara-right-click-menu */ var TARA_CONFIG_DBS, app, join, remote, rimraf; ({app, remote} = require("electron")); ({join} = require("path")); rimraf = require("rimraf"); ({TARA_CONFIG_DBS} = require("tara-core/lib/constants.js")); if (typeof app === "undefined") { app = remote.app; } module.exports.main = function(tara) { tara.logger.debug("Loaded tara-right-click-menu."); return app.on("window-all-closed", function() { tara.logger.debug("Removing context menu dbs..."); // Rm old stuff return rimraf.sync(TARA_CONFIG_DBS); }); }; }).call(this); //# sourceMappingURL=index.js.map
/** * @since 2017-03-17 11:33:56 * @author vivaxy */ import EventEmitter from 'https://unpkg.com/event-based-framework/class/event-emitter.js'; import canvas from './canvas.js'; import Bird from './bird.js'; import Input from './input.js'; import Background from './background.js'; import StickManager from './stick-manager.js'; export default class GameManager extends EventEmitter { constructor() { super(); this.background = new Background(); this.bird = new Bird(); this.input = new Input(); this.sticks = new StickManager(); this.input.on('touch', () => { this.bird.moveUp(); }); } paint() { canvas.clear(); this.background.move(); this.background.paint(); this.sticks.move(); this.sticks.paint(); this.bird.move(); this.bird.paint(); } checkGameOver() { const isCollided = this.sticks.getSticks().some((stick) => { return stick.isCollidedWidthBird(this.bird.isCollidedWithRect.bind(this.bird)); }); const isOutOfScreen = this.bird.isOutOfScreen(); return isCollided || isOutOfScreen; } loop() { this.paint(); if (this.checkGameOver()) { this.emit('game-over'); return this; } requestAnimationFrame(() => { this.loop(); }); return this; } start() { this.loop(); } }
var http = require("http").createServer(handler) // tu je pomemben argument "handler", ki je kasneje uporabljen -> "function handler (req, res); v tej vrstici kreiramo server! (http predstavlja napo aplikacijo - app) , io = require("socket.io").listen(http) , fs = require("fs"); function handler (req, res) { // handler za "response"; ta handler "handla" le datoteko index.html fs.readFile(__dirname + "/pwmbutton_09.html", function (err, data) { if (err) { res.writeHead(500, {'Content-Type': 'text/plain'}); return res.end("Napaka pri nalaganju datoteke pwmbutton_01.html"); } res.writeHead(200); res.end(data); }); } http.listen(8080); // določimo na katerih vratih bomo poslušali | vrata 80 sicer uporablja LAMP | lahko določimo na "router-ju" (http je glavna spremenljivka, t.j. aplikacija oz. app) var firmata = require("firmata"); console.log("Zagon sistema"); // na konzolo zapišemo sporočilo (v terminal) var board = new firmata.Board("/dev/ttyACM0",function(){ console.log("Priključitev na Arduino"); console.log("Firmware: " + board.firmware.name + "-" + board.firmware.version.major + "." + board.firmware.version.minor); // izpišemo verzijo Firmware console.log("Omogočimo pine"); board.pinMode(13, board.MODES.OUTPUT); board.pinMode(12, board.MODES.INPUT); board.pinMode(3, board.MODES.OUTPUT); board.pinMode(5, board.MODES.PWM); board.pinMode(6, board.MODES.PWM); board.pinMode(9, board.MODES.PWM); board.pinMode(10, board.MODES.PWM); }); var leftCount = 0; var rightCount = 0; var timesArray = new Array(); var timePrevious = Date.now(); function countValuesAndChopArray (timesArray, timeValue) { // function counts the values in the timesArray that are less or equal to timeValue and chops them out // function returns chopped array and number of occurences // timesArray must be defined as global variable not to lose time in between counter = 0; for (i = 0; i < timesArray.length; i++) { if (timesArray[i] <= timeValue) { counter++; } else {break;} } timesArray.splice(0, counter); // remove the values from 0, n=counter values return counter; // function returns the number of occurences of times leess or equal to timeValue } io.sockets.on("connection", function(socket) { // od oklepaja ( dalje imamo argument funkcije on -> ob 'connection' se prenese argument t.j. funkcija(socket) // ko nekdo pokliče IP preko "browser-ja" ("browser" pošlje nekaj node.js-u) se vzpostavi povezava = "connection" oz. // je to povezava = "connection" oz. to smatramo kot "connection" // v tem primeru torej želi client nekaj poslati (ko nekdo z browserjem dostopi na naš ip in port) // ko imamo povezavo moramo torej izvesti funkcijo: function (socket) // pri tem so argument podatki "socket-a" t.j. argument = socket // ustvari se socket_id socket.emit("sporociloKlientu", Date.now()); // izvedemo funkcijo = "hello" na klientu, z argumentom, t.j. podatki="Strežnik povezan." socket.on("ukazArduinu", function(data) { // ko je socket ON in je posredovan preko connection-a: ukazArduinu (t.j. ukaz: išči funkcijo ukazArduinu) if (data.stevilkaUkaza == "1") { // če je številka ukaza, ki smo jo dobili iz klienta enaka 1 board.digitalWrite(13, board.HIGH); // na pinu 13 zapišemo vrednost HIGH board.analogWrite(6, 150); // tretji argument je lahko tudi callback - za funkcijo, ki jo kličemo po izvedbi console.log("ana6=" + "150"); //board.analogWrite(6, pwmValue2); // tretji argument je lahko tudi callback - za funkcijo, ki jo kličemo po izvedbi socket.emit("sporociloKlientu", "LED prižgana."); // izvedemo to funkcijo = "sporociloKlientu" na klientu, z argumentom, t.j. podatki="LED prižgana." } else if (data.stevilkaUkaza == "0") { // če je številka ukaza, ki smo jo dobili iz klienta enaka 0 board.digitalWrite(3, board.LOW); // na pinu 13 zapišemo vrednost LOW //board.analogWrite(6, 0); // tretji argument je lahko tudi callback - za funkcijo, ki jo kličemo po izvedbi socket.emit("sporociloKlientu", "LED ugasnjena."); // izvedemo to funkcijo = "sporociloKlientu" na klientu, z argumentom, t.j. podatki="LED ugasnjena." } else if (data.stevilkaUkaza == "2") { // če je številka ukaza, ki smo jo dobili iz klienta enaka 0 if (data.valuePWM != 0) { // če PWM vrednost ni 0 vklopimo rele board.digitalWrite(3, board.HIGH); // na pinu 3 zapišemo vrednost HIGH board.digitalWrite(13, board.HIGH); // na pinu 3 zapišemo vrednost HIGH } else { // če je PWM vrednost enaka 0 izklopimo rele board.digitalWrite(3, board.LOW); // na pinu 3 zapišemo vrednost LOW } board.analogWrite(data.pinNo, data.valuePWM); // tretji argument je lahko tudi callback - za funkcijo, ki jo kličemo po izvedbi console.log("pinNO=" + data.pinNo + " | " + "valuePWM = " + data.valuePWM); socket.emit("sporociloKlientu", "PWM Custom."); // izvedemo to funkcijo = "sporociloKlientu" na klientu, z argumentom, t.j. podatki="LED ugasnjena." } else if (data.stevilkaUkaza == "3") { // če je številka ukaza, ki smo jo dobili iz klienta enaka 0 if (data.valuePWM != 0) { // če PWM vrednost ni 0 vklopimo rele board.digitalWrite(3, board.HIGH); // na pinu 3 zapišemo vrednost HIGH } else { // če je PWM vrednost enaka 0 izklopimo rele board.digitalWrite(3, board.LOW); // na pinu 3 zapišemo vrednost LOW board.digitalWrite(13, board.LOW); // na pinu 3 zapišemo vrednost LOW } board.analogWrite(data.pinNo, data.valuePWM); // tretji argument je lahko tudi callback - za funkcijo, ki jo kličemo po izvedbi console.log("pinNO=" + data.pinNo + " | " + "valuePWM = " + data.valuePWM); socket.emit("sporociloKlientu", "PWM Custom."); // izvedemo to funkcijo = "sporociloKlientu" na klientu, z argumentom, t.j. podatki="LED ugasnjena." } }); /* function test() { //console.log("hello"); setInterval(function() { // Do something every 100ms //pinCallback will be called when data arrives from server board.digitalRead(12,pinCallback); }, 100); } function pinCallback(value) { socket.emit("klientBeri", value); } test(); */ // digital read LEFT: {"stevilkaUkaza": stevilkaUkaza, "pinNo": pinNo, "valuePWM": valuePWM} //setInterval(function() { //var now; //var then = Date.now(); board.digitalRead(12, function(value) { // funkcija se aktivira le, kadar se spremeni stanje; sicer bi bilo 1M čitanj na sekundo timesArray.push(Date.now()); socket.emit("klientBeri", {"vrednost": value, "cas": timesArray[timesArray.length - 1]}); }); //},1); //analog read RIGHT: board.analogRead(2, function(value) { socket.emit("klientBeri2", value); }); function loop() { timerObject = setTimeout(loop, 500); timeNext = Date.now(); numberOfCounts = countValuesAndChopArray(timesArray, timeNext); // number of counts up to current time within last second timeInterval = timeNext - timePrevious; timePrevious = timeNext; frequency = numberOfCounts/(timeInterval/1000); socket.emit("odcitanaFrekvenca", {"stevilo": numberOfCounts, "frekvenca": frequency}); } loop(); });
import { mutations as comicBookMutations } from './comicBook' export const Mutation = ` type Mutation { ${comicBookMutations} } `
import isBrowser from 'is-in-browser'; //Grab variables from process.env or window export const { APP_WEB_BASE_PATH, API_HOST, ALLOW_REDUX_DEV_TOOLS, GOOGLE_BOOKS_API } = isBrowser ? window.__APP_ENV_VARS__ : process.env;
'use strict'; module.exports = profile; profile.Profile = Profile; var event_emitter = require('events').EventEmitter; var node_util = require('util'); var node_path = require('path'); var fs = require('fs-sync'); var trait = require('trait'); var ini = require('ini'); function profile(options) { return new Profile(options); } var DEFAULT_PROFILE = 'default'; var RESERVED_PROFILE_NAME = ['profiles', 'current_profile', DEFAULT_PROFILE]; // normalize path, convert '~' to the absolute pathname of the current user profile.resolveHomePath = function(path) { if (path.indexOf('~') === 0) { var USER_HOME = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME']; path = path.replace(/^~/, USER_HOME); } return path; }; // Force to touching a file, if the file is not exists // If there's already a dir named `path`, the former dir will be copied as a backup before being deleted profile.touchFile = function(path) { if (!fs.isFile(path)) { if (fs.isDir(path)) { fs.copy(path, path + '-bak-' + Date.now(), { force: true }); fs.remove(path); } // create empty file fs.write(path, ''); } }; var CODEC = { json: { parse: function (string) { return JSON.parse(string); }, stringify: function (object) { return JSON.stringify(object, null, 2); } }, ini: { parse: function (string) { return ini.parse(string); }, stringify: function (object) { var obj = {}; var key; // #13 // `ini` will save undefined value into the config file // so clean the object before saving. for (key in object) { if (object[key] !== undefined) { obj[key] = object[key]; } } return ini.stringify(obj); } } }; profile.CODEC = CODEC; // Constructor of Profile has no fault-tolerance, make sure you pass the right parameters // @param {Object} options // - path: {node_path} path to save the profiles function Profile(options) { this.path = node_path.resolve(profile.resolveHomePath(options.path)); this.schema = options.schema; this.context = options.context || null; this.raw_data = {}; this.codec = this._get_codec(options.codec); this.options = options; } node_util.inherits(Profile, event_emitter); mix(Profile.prototype, { _get_codec: function (codec) { if (!codec) { return profile.CODEC.json; } if (Object(codec) === codec) { return codec; } if (typeof codec !== 'string') { var error = new Error('Invalid options.codec "' + codec + '".'); error.code = 'INVALID_OPTION_CODEC'; error.data = { codec: codec, error: e }; throw error; } return profile.CODEC[codec] || profile.CODEC.json; }, // save the current configurations _save_data: function(data) { var content = this.codec.stringify(data); fs.write(this.profile_file, content); }, _read_data: function() { var conf = this.profile_file; var content; try { content = fs.read(conf).trim(); } catch(e) { var error = new Error('Error reading config file "' + conf + '".'); error.code = 'ERROR_READ_CONFIG'; error.data = { file: conf, error: e }; throw error; } if (!content) { return {}; } var data; try { data = this.codec.parse(content); } catch (e) { var error = new Error('Error parsing config file "' + conf + '".'); error.code = 'ERROR_PARSE_CONFIG'; error.data = { file: conf, error: e }; throw error; } return data; }, init: function() { this._prepare(); this._prepareProfile(this.options.profile); }, // get all profile names // @return {Array.<string>} all: function() { return this.attr.get('profiles'); }, // get the current profile name // @return {string|null} current: function() { return this.attr.get('current'); }, // get the current profile directory which contains a variety of files currentDir: function() { return this.profile_dir || null; }, getPath: function () { return this.path; }, getConfigFile: function () { return this.profile_file; }, exists: function(name) { return !!~this.all().indexOf(name); }, // switchTo: function(name, callback) { var current = this.current(); var err = null; if (current === name) { err = '"' + name + '" is already the current profile.'; } else if (!this.exists(name)) { err = 'Profile "' + name + '" not found.' } else { this.attr.set('current', name); this._initProfile(name); } var data = { err: err, former: current, current: err ? current : name }; this.emit('switch', data); callback && callback(err, data); }, add: function(name, callback) { return this._add(name, false, callback); }, // Add a new profile. // Adding a profile will not do nothing about initialization _add: function(name, force, callback) { var err = null; var profiles = this.all(); if (~profiles.indexOf(name)) { err = 'Profile "' + name + '" already exists.'; } else if (!force && ~RESERVED_PROFILE_NAME.indexOf(name)) { err = 'Profile name "' + name + '" is reserved by `multi-profile`'; } else if (/^_/.test(name)) { err = 'Profile name "' + name + '" should not begin with `_`'; } else { profiles.push(name); this.attr.set('profiles', profiles); } var data = { err: err, name: name }; this.emit('add', data); callback && callback(err, data); }, // @param get: function(key) { if (arguments.length === 0) { return this._getAllOption(); } else { return this._getOption(key); } }, set: function(key, value) { if (Object(key) === key) { return this.profile.set(key); } else { return this.profile.set(key, value); } }, reset: function(name) { this.profile.reset(name); }, // not allow to add options // addOption: function (key, attr) { // return this.profile.add(key, attr); // }, _getAllOption: function() { return this.profile.get(); }, _getOption: function(key) { return this.profile.get(key); }, // @param {string} name profile name // @param {} del: function(name, remove_data, callback) { var profiles = this.all(); var current = this.current(); var index = profiles.indexOf(name); var err = null; if (current === name) { err = 'You could not delete current profile.'; } else if (!~index) { err = 'Profile "' + name + '" not found.'; } else { profiles.splice(index, 1); this.attr.set('profiles', profiles); if (remove_data) { fs.remove(node_path.join(this.path, name)); } } var data = { err: err, name: name }; this.emit('delete', data); callback && callback(err, data); }, save: function(data) { var data = arguments.length === 0 ? this.getWritable() : data; this.raw_data = data; this._save_data(data); }, // @returns {Array} // get the list of writable property names writable: function() { return this.profile.writable(); }, enumerable: function() { return this.profile.enumerable(); }, getWritable: function() { return this._getFromList(this.writable()); }, getEnumerable: function() { return this._getFromList(this.enumerable()); }, _getFromList: function(list) { var data = {}; list.forEach(function(key) { data[key] = this._getOption(key); }, this); return data; }, // prepare environment _prepare: function() { // the attributes for multi-profile itself this.attr = trait({ path: { value: this.path, type: { readOnly: true, setup: function(value) { if (!fs.isDir(value)) { fs.mkdir(value); } var profiles = this.profiles_file = node_path.join(value, 'profiles'); var current = this.current_file = node_path.join(value, 'current_profile'); profile.touchFile(profiles); profile.touchFile(current); } } }, // get or set the names of profiles profiles: { type: { getter: function() { return fs.read(this.profiles_file).split(/[\r\n]+/).filter(Boolean); }, setter: function(profiles) { fs.write(this.profiles_file, profiles.join('\n')); return profiles; } } }, // get or set the name of the current profile current: { type: { getter: function() { return fs.read(this.current_file).trim() || null; }, setter: function(v) { fs.write(this.current_file, v); return v; } } } }, { host: this }); }, // Initialize the current profile, // and create necessary files and dirs if not exists. // Initialize properties of current profile _initProfile: function(name) { this.profile = trait(Object.create(this.schema), { context: this.context }); var profile_dir = this.profile_dir = node_path.join(this.path, name); if (!fs.isDir(profile_dir)) { fs.mkdir(profile_dir); } var profile_file = this.profile_file = node_path.join(profile_dir, 'config'); if (!fs.isFile(profile_file)) { fs.write(profile_file, ''); } else { this.reload(); } }, // Prepare profile _prepareProfile: function(name) { var current = name || this.current(); // Make sure there is always a 'default' profile if (!~this.all().indexOf(DEFAULT_PROFILE)) { this._add(DEFAULT_PROFILE, true); } if (current) { this._initProfile(current); } else { // Use 'default' profile by default this.switchTo(DEFAULT_PROFILE); } }, // Reload properties reload: function() { var raw = this._read_data(); this.raw_data = raw; this.profile.set(raw); }, hasConfig: function (key) { return key in this.raw_data; } }); function mix(receiver, supplier, override) { var key; if (arguments.length === 2) { override = true; } for (key in supplier) { if (override || !(key in receiver)) { receiver[key] = supplier[key] } } return receiver; }
var lcdboot_8c = [ [ "LCD_DATA", "lcdboot_8c.html#a6951f4c8fe91af3b5d606cd933970c86", null ], [ "LCD_Boot_Init", "lcdboot_8c.html#a9d26519d0eec10bbcc82be0769e320f1", null ], [ "LCD_Command", "lcdboot_8c.html#ac5e48d9c8ff163af96d51d34d8ccf0b0", null ], [ "LCD_Data", "lcdboot_8c.html#a231fadbfce2c5e498ffc85b7b5627f01", null ], [ "LCD_LowLevelInit", "lcdboot_8c.html#a99160c47c7fafb994440d74a54cb8dbf", null ], [ "LCD_PutChar", "lcdboot_8c.html#a7ca5f0083378ba636c416acf2a8c60e7", null ], [ "font8x16", "lcdboot_8c.html#a6a6db444488a026e6faf6bafd9db0a24", null ] ];
import enterFullscreen from '../utils/enterFullscreen'; import exitFullscreen from '../utils/exitFullscreen'; export default function (isOn) { let self = this; if (isOn) { enterFullscreen(self.wrapper[0]); } else { exitFullscreen(); } };
#!/usr/bin/env node import { readFile } from 'fs/promises'; import minimist from 'minimist'; import createPullRequest from '../lib/create-github-pr.js'; import fixtureJsonStringify from '../lib/fixture-json-stringify.js'; import importJson from '../lib/import-json.js'; import { checkFixture } from '../tests/fixture-valid.js'; /** @typedef {import('../lib/types.js').FixtureCreateResult} FixtureCreateResult */ const cliArguments = minimist(process.argv.slice(2), { string: [`p`, `a`], boolean: `c`, alias: { a: `author-name`, p: `plugin`, c: `create-pull-request`, }, }); await checkCliArguments(); const filename = cliArguments._[0]; try { const buffer = await readFile(filename); const plugin = await import(`../plugins/${cliArguments.plugin}/import.js`); const { manufacturers, fixtures, warnings } = await plugin.importFixtures(buffer, filename, cliArguments[`author-name`]); /** @type {FixtureCreateResult} */ const result = { manufacturers, fixtures, warnings, errors: {}, }; for (const key of Object.keys(result.fixtures)) { const [manufacturerKey, fixtureKey] = key.split(`/`); const checkResult = await checkFixture(manufacturerKey, fixtureKey, result.fixtures[key]); result.warnings[key] = result.warnings[key].concat(checkResult.warnings); result.errors[key] = checkResult.errors; } if (cliArguments[`create-pull-request`]) { try { const pullRequestUrl = await createPullRequest(result); console.log(`URL: ${pullRequestUrl}`); } catch (error) { console.log(fixtureJsonStringify(result)); console.error(`Error creating pull request: ${error.message}`); } } else { console.log(fixtureJsonStringify(result)); } } catch (error) { console.error(`Error parsing '${filename}':`); console.error(error); process.exit(1); } /** * Checks the command line interface arguments parsed by minimist. */ async function checkCliArguments() { const plugins = await importJson(`../plugins/plugins.json`, import.meta.url); if (cliArguments._.length !== 1 || !plugins.importPlugins.includes(cliArguments.plugin) || !cliArguments[`author-name`]) { const importPlugins = plugins.importPlugins.join(`, `); console.error(`Usage: ${process.argv[1]} -p <plugin> -a <author name> [--create-pull-request] <filename>\n\navailable plugins: ${importPlugins}`); process.exit(1); } }
import{B as t}from"./index-fe8be053.js";const e="orient",n="vertical",i="horizontal";export default class extends t{constructor(t,e=""){super(t);const n=e.split(/\s+/g);this.aria=!n.includes("no-aria"),this.dynamic=n.includes("dynamic"),this.orient=n.includes("v")?"v":"h",this.dynamic&&t.addEventListener("focusin",(()=>{const e=getComputedStyle(t);this.set(e.flexFlow.includes("column")||"v"===e.getPropertyValue("--orient")?"v":"h")}),{passive:!0})}set(t){const{host:e}=this;if(null==t){const n=e.nuGetAttr("orient",!0);t=null!=n?n:"h"}const n="v"===t?"vertical":"horizontal";e.nuSetAria("orientation",n),e.nuSetContext("orientation",n),this.orient=n}connected(){this.set()}changed(t){"orient"===t&&this.set()}}export{i as HORIZONTAL,e as ORIENT_ATTR,n as VERTICAL};
Polymer({ is: 'moi-actions-row' });
'use strict'; var _chalk = require('chalk'); var _chalk2 = _interopRequireDefault(_chalk); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var error = _chalk2.default.red, warn = _chalk2.default.yellow, step = _chalk2.default.green, start = _chalk2.default.grey, info = _chalk2.default.blue; // import colors from 'colors/safe'; console.logPrototype = console.log; console.errorPrototype = console.error; console.warnPrototype = console.warn; var dateTime = function dateTime() { var currentdate = new Date(); var datetime = '[' + currentdate.getDate() + "/" + (currentdate.getMonth() + 1) + "/" + currentdate.getFullYear() + " @ " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds() + ']'; return datetime; }; console.log = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var date = [dateTime()]; date = date.concat(args); if (console) { console.logPrototype.apply(console, date); } }; console.error = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } var date = [error(dateTime())]; date = date.concat(args); if (console) { console.errorPrototype.apply(console, date); } }; console.warn = function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } var date = [warn(dateTime())]; date = date.concat(args); if (console) { console.warnPrototype.apply(console, date); } }; console.info = function () { for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } var date = [info(dateTime())]; date = date.concat(args); if (console) { console.logPrototype.apply(console, date); } }; console.start = function () { for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } var date = [start(dateTime())]; date = date.concat(args); if (console) { console.logPrototype.apply(console, date); } }; console.step = function () { for (var _len6 = arguments.length, args = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } var date = [step(dateTime())]; date = date.concat(args); if (console) { console.logPrototype.apply(console, date); } };