code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
(function ($) { /** * Toggle the visibility of a fieldset using smooth animations. */ Drupal.toggleFieldset = function (fieldset) { var $toggle = $($(fieldset).find('[data-toggle=collapse]').data('target')); if ($toggle.length) { $toggle.collapse('toggle'); } }; /** * Scroll a given fieldset into view as much as possible. */ Drupal.collapseScrollIntoView = function (node) { var h = document.documentElement.clientHeight || document.body.clientHeight || 0; var offset = document.documentElement.scrollTop || document.body.scrollTop || 0; var posY = $(node).offset().top; var fudge = 55; if (posY + node.offsetHeight + fudge > h + offset) { if (node.offsetHeight > h) { window.scrollTo(0, posY); } else { window.scrollTo(0, posY + node.offsetHeight - h + fudge); } } }; Drupal.behaviors.collapse = { attach: function (context, settings) { $('fieldset.collapsible', context).once('collapse', function () { var $fieldset = $(this); // Expand fieldset if there are errors inside, or if it contains an // element that is targeted by the URI fragment identifier. var anchor = location.hash && location.hash != '#' ? ', ' + location.hash : ''; if ($fieldset.find('.error' + anchor).length) { $fieldset.removeClass('collapsed'); } var summary = $('<span class="summary"></span>'); $fieldset. bind('summaryUpdated', function () { var text = $.trim($fieldset.drupalGetSummary()); summary.html(text ? ' (' + text + ')' : ''); }) .trigger('summaryUpdated'); // Turn the legend into a clickable link, but retain span.fieldset-legend // for CSS positioning. var $legend = $('> legend .fieldset-legend', this); $('<span class="fieldset-legend-prefix element-invisible"></span>') .append($fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide')) .prependTo($legend); $fieldset.find('[data-toggle=collapse]').on('click', function (e) { e.preventDefault(); }); // Bind Bootstrap events with Drupal core events. $fieldset .append(summary) .on('show.bs.collapse', function () { $fieldset .removeClass('collapsed') .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Hide')); }) .on('shown.bs.collapse', function () { $fieldset.trigger({ type: 'collapsed', value: false }); Drupal.collapseScrollIntoView($fieldset.get(0)); }) .on('hide.bs.collapse', function () { $fieldset .addClass('collapsed') .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Show')); }) .on('hidden.bs.collapse', function () { $fieldset.trigger({ type: 'collapsed', value: true }); }); }); } }; })(jQuery);
cooper-webdesign/cooper.dk
webshop/sites/all/themes/bootstrap/js/misc/_collapse.js
JavaScript
gpl-2.0
2,910
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import invariant from 'fbjs/lib/invariant'; var ensurePositiveDelayProps = function ensurePositiveDelayProps(props) { invariant(!(props.delayPressIn < 0 || props.delayPressOut < 0 || props.delayLongPress < 0), 'Touchable components cannot have negative delay properties'); }; export default ensurePositiveDelayProps;
cdnjs/cdnjs
ajax/libs/react-native-web/0.17.7/exports/Touchable/ensurePositiveDelayProps.js
JavaScript
mit
516
/* AngularJS v1.1.2 (c) 2010-2012 Google, Inc. http://angularjs.org License: MIT */ (function(n,j){'use strict';j.module("bootstrap",[]).directive({dropdownToggle:["$document","$location","$window",function(h,e){var d=null,a;return{restrict:"C",link:function(g,b){g.$watch(function(){return e.path()},function(){a&&a()});b.parent().bind("click",function(){a&&a()});b.bind("click",function(i){i.preventDefault();i.stopPropagation();i=!1;d&&(i=d===b,a());i||(b.parent().addClass("open"),d=b,a=function(c){c&&c.preventDefault();c&&c.stopPropagation();h.unbind("click",a);b.parent().removeClass("open"); d=a=null},h.bind("click",a))})}}}],tabbable:function(){return{restrict:"C",compile:function(h){var e=j.element('<ul class="nav nav-tabs"></ul>'),d=j.element('<div class="tab-content"></div>');d.append(h.contents());h.append(e).append(d)},controller:["$scope","$element",function(h,e){var d=e.contents().eq(0),a=e.controller("ngModel")||{},g=[],b;a.$render=function(){var a=this.$viewValue;if(b?b.value!=a:a)if(b&&(b.paneElement.removeClass("active"),b.tabElement.removeClass("active"),b=null),a){for(var c= 0,d=g.length;c<d;c++)if(a==g[c].value){b=g[c];break}b&&(b.paneElement.addClass("active"),b.tabElement.addClass("active"))}};this.addPane=function(e,c){function l(){f.title=c.title;f.value=c.value||c.title;if(!a.$setViewValue&&(!a.$viewValue||f==b))a.$viewValue=f.value;a.$render()}var k=j.element("<li><a href></a></li>"),m=k.find("a"),f={paneElement:e,paneAttrs:c,tabElement:k};g.push(f);c.$observe("value",l)();c.$observe("title",function(){l();m.text(f.title)})();d.append(k);k.bind("click",function(b){b.preventDefault(); b.stopPropagation();a.$setViewValue?h.$apply(function(){a.$setViewValue(f.value);a.$render()}):(a.$viewValue=f.value,a.$render())});return function(){f.tabElement.remove();for(var a=0,b=g.length;a<b;a++)f==g[a]&&g.splice(a,1)}}}]}},tabPane:function(){return{require:"^tabbable",restrict:"C",link:function(h,e,d,a){e.bind("$remove",a.addPane(e,d))}}}})})(window,window.angular);
bonbon197/jsdelivr
files/angularjs/1.1.2/angular-bootstrap.min.js
JavaScript
mit
2,023
/**! * AngularJS file upload/drop directive and service with progress and abort * FileAPI Flash shim for old browsers not supporting FormData * @author Danial <danial.farid@gmail.com> * @version 7.0.5 */ (function () { /** @namespace FileAPI.noContentTimeout */ function patchXHR(fnName, newFn) { window.XMLHttpRequest.prototype[fnName] = newFn(window.XMLHttpRequest.prototype[fnName]); } function redefineProp(xhr, prop, fn) { try { Object.defineProperty(xhr, prop, {get: fn}); } catch (e) {/*ignore*/ } } if (!window.FileAPI) { window.FileAPI = {}; } FileAPI.shouldLoad = (window.XMLHttpRequest && !window.FormData) || FileAPI.forceLoad; if (FileAPI.shouldLoad) { var initializeUploadListener = function (xhr) { if (!xhr.__listeners) { if (!xhr.upload) xhr.upload = {}; xhr.__listeners = []; var origAddEventListener = xhr.upload.addEventListener; xhr.upload.addEventListener = function (t, fn) { xhr.__listeners[t] = fn; if (origAddEventListener) origAddEventListener.apply(this, arguments); }; } }; patchXHR('open', function (orig) { return function (m, url, b) { initializeUploadListener(this); this.__url = url; try { orig.apply(this, [m, url, b]); } catch (e) { if (e.message.indexOf('Access is denied') > -1) { this.__origError = e; orig.apply(this, [m, '_fix_for_ie_crossdomain__', b]); } } }; }); patchXHR('getResponseHeader', function (orig) { return function (h) { return this.__fileApiXHR && this.__fileApiXHR.getResponseHeader ? this.__fileApiXHR.getResponseHeader(h) : (orig == null ? null : orig.apply(this, [h])); }; }); patchXHR('getAllResponseHeaders', function (orig) { return function () { return this.__fileApiXHR && this.__fileApiXHR.getAllResponseHeaders ? this.__fileApiXHR.getAllResponseHeaders() : (orig == null ? null : orig.apply(this)); }; }); patchXHR('abort', function (orig) { return function () { return this.__fileApiXHR && this.__fileApiXHR.abort ? this.__fileApiXHR.abort() : (orig == null ? null : orig.apply(this)); }; }); patchXHR('setRequestHeader', function (orig) { return function (header, value) { if (header === '__setXHR_') { initializeUploadListener(this); var val = value(this); // fix for angular < 1.2.0 if (val instanceof Function) { val(this); } } else { this.__requestHeaders = this.__requestHeaders || {}; this.__requestHeaders[header] = value; orig.apply(this, arguments); } }; }); patchXHR('send', function (orig) { return function () { var xhr = this; if (arguments[0] && arguments[0].__isFileAPIShim) { var formData = arguments[0]; var config = { url: xhr.__url, jsonp: false, //removes the callback form param cache: true, //removes the ?fileapiXXX in the url complete: function (err, fileApiXHR) { xhr.__completed = true; if (!err && xhr.__listeners.load) xhr.__listeners.load({ type: 'load', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true }); if (!err && xhr.__listeners.loadend) xhr.__listeners.loadend({ type: 'loadend', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true }); if (err === 'abort' && xhr.__listeners.abort) xhr.__listeners.abort({ type: 'abort', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true }); if (fileApiXHR.status !== undefined) redefineProp(xhr, 'status', function () { return (fileApiXHR.status === 0 && err && err !== 'abort') ? 500 : fileApiXHR.status; }); if (fileApiXHR.statusText !== undefined) redefineProp(xhr, 'statusText', function () { return fileApiXHR.statusText; }); redefineProp(xhr, 'readyState', function () { return 4; }); if (fileApiXHR.response !== undefined) redefineProp(xhr, 'response', function () { return fileApiXHR.response; }); var resp = fileApiXHR.responseText || (err && fileApiXHR.status === 0 && err !== 'abort' ? err : undefined); redefineProp(xhr, 'responseText', function () { return resp; }); redefineProp(xhr, 'response', function () { return resp; }); if (err) redefineProp(xhr, 'err', function () { return err; }); xhr.__fileApiXHR = fileApiXHR; if (xhr.onreadystatechange) xhr.onreadystatechange(); if (xhr.onload) xhr.onload(); }, progress: function (e) { e.target = xhr; if (xhr.__listeners.progress) xhr.__listeners.progress(e); xhr.__total = e.total; xhr.__loaded = e.loaded; if (e.total === e.loaded) { // fix flash issue that doesn't call complete if there is no response text from the server var _this = this; setTimeout(function () { if (!xhr.__completed) { xhr.getAllResponseHeaders = function () { }; _this.complete(null, {status: 204, statusText: 'No Content'}); } }, FileAPI.noContentTimeout || 10000); } }, headers: xhr.__requestHeaders }; config.data = {}; config.files = {}; for (var i = 0; i < formData.data.length; i++) { var item = formData.data[i]; if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) { config.files[item.key] = item.val; } else { config.data[item.key] = item.val; } } setTimeout(function () { if (!FileAPI.hasFlash) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } xhr.__fileApiXHR = FileAPI.upload(config); }, 1); } else { if (this.__origError) { throw this.__origError; } orig.apply(xhr, arguments); } }; }); window.XMLHttpRequest.__isFileAPIShim = true; window.FormData = FormData = function () { return { append: function (key, val, name) { if (val.__isFileAPIBlobShim) { val = val.data[0]; } this.data.push({ key: key, val: val, name: name }); }, data: [], __isFileAPIShim: true }; }; window.Blob = Blob = function (b) { return { data: b, __isFileAPIBlobShim: true }; }; } })(); (function () { /** @namespace FileAPI.forceLoad */ /** @namespace window.FileAPI.jsUrl */ /** @namespace window.FileAPI.jsPath */ function isInputTypeFile(elem) { return elem[0].tagName.toLowerCase() === 'input' && elem.attr('type') && elem.attr('type').toLowerCase() === 'file'; } function hasFlash() { try { var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash'); if (fo) return true; } catch (e) { if (navigator.mimeTypes['application/x-shockwave-flash'] !== undefined) return true; } return false; } function getOffset(obj) { var left = 0, top = 0; if (window.jQuery) { return jQuery(obj).offset(); } if (obj.offsetParent) { do { left += (obj.offsetLeft - obj.scrollLeft); top += (obj.offsetTop - obj.scrollTop); obj = obj.offsetParent; } while (obj); } return { left: left, top: top }; } if (FileAPI.shouldLoad) { //load FileAPI if (FileAPI.forceLoad) { FileAPI.html5 = false; } if (!FileAPI.upload) { var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src; if (window.FileAPI.jsUrl) { jsUrl = window.FileAPI.jsUrl; } else if (window.FileAPI.jsPath) { basePath = window.FileAPI.jsPath; } else { for (i = 0; i < allScripts.length; i++) { src = allScripts[i].src; index = src.search(/\/ng\-file\-upload[\-a-zA-z0-9\.]*\.js/); if (index > -1) { basePath = src.substring(0, index + 1); break; } } } if (FileAPI.staticPath == null) FileAPI.staticPath = basePath; script.setAttribute('src', jsUrl || basePath + 'FileAPI.min.js'); document.getElementsByTagName('head')[0].appendChild(script); FileAPI.hasFlash = hasFlash(); } FileAPI.ngfFixIE = function (elem, fileElem, changeFn) { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } var fixInputStyle = function () { if (elem.attr('disabled')) { if (fileElem) fileElem.removeClass('js-fileapi-wrapper'); } else { if (!fileElem.attr('__ngf_flash_')) { fileElem.unbind('change'); fileElem.unbind('click'); fileElem.bind('change', function (evt) { fileApiChangeFn.apply(this, [evt]); changeFn.apply(this, [evt]); }); fileElem.attr('__ngf_flash_', 'true'); } fileElem.addClass('js-fileapi-wrapper'); if (!isInputTypeFile(elem)) { fileElem.css('position', 'absolute') .css('top', getOffset(elem[0]).top + 'px').css('left', getOffset(elem[0]).left + 'px') .css('width', elem[0].offsetWidth + 'px').css('height', elem[0].offsetHeight + 'px') .css('filter', 'alpha(opacity=0)').css('display', elem.css('display')) .css('overflow', 'hidden').css('z-index', '900000') .css('visibility', 'visible'); } } }; elem.bind('mouseenter', fixInputStyle); var fileApiChangeFn = function (evt) { var files = FileAPI.getFiles(evt); //just a double check for #233 for (var i = 0; i < files.length; i++) { if (files[i].size === undefined) files[i].size = 0; if (files[i].name === undefined) files[i].name = 'file'; if (files[i].type === undefined) files[i].type = 'undefined'; } if (!evt.target) { evt.target = {}; } evt.target.files = files; // if evt.target.files is not writable use helper field if (evt.target.files !== files) { evt.__files_ = files; } (evt.__files_ || evt.target.files).item = function (i) { return (evt.__files_ || evt.target.files)[i] || null; }; }; }; FileAPI.disableFileInput = function (elem, disable) { if (disable) { elem.removeClass('js-fileapi-wrapper'); } else { elem.addClass('js-fileapi-wrapper'); } }; } })(); if (!window.FileReader) { window.FileReader = function () { var _this = this, loadStarted = false; this.listeners = {}; this.addEventListener = function (type, fn) { _this.listeners[type] = _this.listeners[type] || []; _this.listeners[type].push(fn); }; this.removeEventListener = function (type, fn) { if (_this.listeners[type]) _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1); }; this.dispatchEvent = function (evt) { var list = _this.listeners[evt.type]; if (list) { for (var i = 0; i < list.length; i++) { list[i].call(_this, evt); } } }; this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null; var constructEvent = function (type, evt) { var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error}; if (evt.result != null) e.target.result = evt.result; return e; }; var listener = function (evt) { if (!loadStarted) { loadStarted = true; if (_this.onloadstart) _this.onloadstart(constructEvent('loadstart', evt)); } var e; if (evt.type === 'load') { if (_this.onloadend) _this.onloadend(constructEvent('loadend', evt)); e = constructEvent('load', evt); if (_this.onload) _this.onload(e); _this.dispatchEvent(e); } else if (evt.type === 'progress') { e = constructEvent('progress', evt); if (_this.onprogress) _this.onprogress(e); _this.dispatchEvent(e); } else { e = constructEvent('error', evt); if (_this.onerror) _this.onerror(e); _this.dispatchEvent(e); } }; this.readAsArrayBuffer = function (file) { FileAPI.readAsBinaryString(file, listener); }; this.readAsBinaryString = function (file) { FileAPI.readAsBinaryString(file, listener); }; this.readAsDataURL = function (file) { FileAPI.readAsDataURL(file, listener); }; this.readAsText = function (file) { FileAPI.readAsText(file, listener); }; }; }
froala/cdnjs
ajax/libs/danialfarid-angular-file-upload/7.0.5/ng-file-upload-shim.js
JavaScript
mit
14,014
/*! * @overview Ember Data Model Fragments * @copyright Copyright 2015 Lytics Inc. and contributors * @license Licensed under MIT license * See https://raw.githubusercontent.com/lytics/ember-data.model-fragments/master/LICENSE * @version 0.3.3+8b1fcdd5 */ (function() { "use strict"; var ember$lib$main$$default = Ember; var ember$data$lib$main$$default = DS; var ember$data$lib$serializers$json$api$serializer$$default = DS.JSONAPISerializer; var ember$data$lib$serializers$json$serializer$$default = DS.JSONSerializer; var ember$data$lib$system$model$internal$model$$default = DS.InternalModel; var ember$data$lib$system$model$states$$default = DS.RootState; var ember$data$lib$system$model$$default = DS.Model; var ember$data$lib$system$snapshot$$default = DS.Snapshot; var ember$data$lib$system$store$$default = DS.Store; var ember$data$lib$system$transform$$default = DS.Transform; /** @module ember-data.model-fragments */ var model$fragments$lib$fragments$states$$get = ember$lib$main$$default.get; var model$fragments$lib$fragments$states$$create = Object.create || ember$lib$main$$default.create; var model$fragments$lib$fragments$states$$didSetProperty = ember$data$lib$system$model$states$$default.loaded.saved.didSetProperty; var model$fragments$lib$fragments$states$$propertyWasReset = ember$data$lib$system$model$states$$default.loaded.updated.uncommitted.propertyWasReset; var model$fragments$lib$fragments$states$$dirtySetup = function(internalModel) { var record = internalModel._owner; var key = internalModel._name; // A newly created fragment may not have an owner yet if (record) { model$fragments$lib$fragments$states$$fragmentDidDirty(record, key, internalModel); } }; /** Like `DS.Model` instances, all fragments have a `currentState` property that reflects where they are in the model lifecycle. However, there are much fewer states that a fragment can be in, since the `loading` state doesn't apply, `inFlight` states are no different than the owner record's, and there is no concept of a `deleted` state. This is the simplified hierarchy of valid states for a fragment: ```text * root * empty * loaded * created * saved * updated ``` Note that there are no `uncommitted` sub-states because it's implied by the `created` and `updated` states (since there are no `inFlight` substates). @class FragmentRootState */ var model$fragments$lib$fragments$states$$FragmentRootState = { // Include all `DS.Model` state booleans for consistency isEmpty: false, isLoading: false, isLoaded: false, isDirty: false, isSaving: false, isDeleted: false, isNew: false, isValid: true, didSetProperty: model$fragments$lib$fragments$states$$didSetProperty, propertyWasReset: ember$lib$main$$default.K, becomeDirty: ember$lib$main$$default.K, rolledBack: ember$lib$main$$default.K, empty: { isEmpty: true, loadedData: function(internalModel) { internalModel.transitionTo('loaded.created'); }, pushedData: function(internalModel) { internalModel.transitionTo('loaded.saved'); } }, loaded: { pushedData: function(internalModel) { internalModel.transitionTo('saved'); }, saved: { setup: function(internalModel) { var record = internalModel._owner; var key = internalModel._name; // Abort if fragment is still initializing if (!record._internalModel._fragments[key] || internalModel._isInitializing) { return; } // Reset the property on the owner record if no other siblings // are dirty (or there are no siblings) if (!model$fragments$lib$fragments$states$$get(record, key + '.hasDirtyAttributes')) { model$fragments$lib$fragments$states$$fragmentDidReset(record, key, internalModel); } }, pushedData: ember$lib$main$$default.K, didCommit: ember$lib$main$$default.K, becomeDirty: function(internalModel) { internalModel.transitionTo('updated'); } }, created: { isDirty: true, setup: model$fragments$lib$fragments$states$$dirtySetup, didCommit: function(internalModel) { internalModel.transitionTo('saved'); } }, updated: { isDirty: true, setup: model$fragments$lib$fragments$states$$dirtySetup, propertyWasReset: model$fragments$lib$fragments$states$$propertyWasReset, didCommit: function(internalModel) { internalModel.transitionTo('saved'); }, rolledBack: function(internalModel) { internalModel.transitionTo('saved'); } } } }; function model$fragments$lib$fragments$states$$mixin(original, hash) { for (var prop in hash) { original[prop] = hash[prop]; } return original; } // Wouldn't it be awesome if this was public? function model$fragments$lib$fragments$states$$wireState(object, parent, name) { object = model$fragments$lib$fragments$states$$mixin(parent ? model$fragments$lib$fragments$states$$create(parent) : {}, object); object.parentState = parent; object.stateName = name; for (var prop in object) { if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; } if (typeof object[prop] === 'object') { object[prop] = model$fragments$lib$fragments$states$$wireState(object[prop], object, name + "." + prop); } } return object; } model$fragments$lib$fragments$states$$FragmentRootState = model$fragments$lib$fragments$states$$wireState(model$fragments$lib$fragments$states$$FragmentRootState, null, 'root'); var model$fragments$lib$fragments$states$$default = model$fragments$lib$fragments$states$$FragmentRootState; function model$fragments$lib$fragments$states$$fragmentDidDirty(record, key, fragment) { if (!model$fragments$lib$fragments$states$$get(record, 'isDeleted')) { // Add the fragment as a placeholder in the owner record's // `_attributes` hash to indicate it is dirty record._internalModel._attributes[key] = fragment; record.send('becomeDirty'); } } function model$fragments$lib$fragments$states$$fragmentDidReset(record, key) { // Make sure there's no entry in the owner record's // `_attributes` hash to indicate the fragment is dirty delete record._internalModel._attributes[key]; // Don't reset if the record is new, otherwise it will enter the 'deleted' state // NOTE: This case almost never happens with attributes because their initial value // is always undefined, which is *usually* not what attributes get 'reset' to if (!model$fragments$lib$fragments$states$$get(record, 'isNew')) { record.send('propertyWasReset', key); } } /** @module ember-data.model-fragments */ var model$fragments$lib$fragments$array$stateful$$get = ember$lib$main$$default.get; var model$fragments$lib$fragments$array$stateful$$set = ember$lib$main$$default.set; var model$fragments$lib$fragments$array$stateful$$computed = ember$lib$main$$default.computed; /** A state-aware array that is tied to an attribute of a `DS.Model` instance. @class StatefulArray @namespace DS @extends Ember.ArrayProxy */ var model$fragments$lib$fragments$array$stateful$$StatefulArray = ember$lib$main$$default.ArrayProxy.extend({ /** A reference to the array's owner record. @property owner @type {DS.Model} */ owner: null, /** The array's property name on the owner record. @property name @private @type {String} */ name: null, init: function() { this._super(); this._pendingData = undefined; model$fragments$lib$fragments$array$stateful$$set(this, '_originalState', []); }, content: model$fragments$lib$fragments$array$stateful$$computed(function() { return ember$lib$main$$default.A(); }), /** @method setupData @private @param {Object} data */ setupData: function(data) { // Since replacing the contents of the array can trigger changes to fragment // array properties, this method can get invoked recursively with the same // data, so short circuit here once it's been setup the first time if (this._pendingData === data) { return; } this._pendingData = data; var processedData = this._processData(data); // This data is canonical, so create rollback point model$fragments$lib$fragments$array$stateful$$set(this, '_originalState', processedData); // Completely replace the contents with the new data this.replaceContent(0, model$fragments$lib$fragments$array$stateful$$get(this, 'content.length'), processedData); this._pendingData = undefined; }, /** @method _processData @private @param {Object} data */ _processData: function(data) { // Simply ensure that the data is an actual array return ember$lib$main$$default.makeArray(data); }, /** @method _createSnapshot @private */ _createSnapshot: function() { // Since elements are not models, a snapshot is simply a mapping of raw values return this.toArray(); }, /** @method adapterDidCommit @private */ _adapterDidCommit: function(data) { if (data) { this.setupData(data); } else { // Fragment array has been persisted; use the current state as the original state model$fragments$lib$fragments$array$stateful$$set(this, '_originalState', this.toArray()); } }, /** @method isDirty @deprecated Use `hasDirtyAttributes` instead */ isDirty: model$fragments$lib$fragments$array$stateful$$computed('hasDirtyAttributes', function() { ember$lib$main$$default.deprecate('The `isDirty` method of fragment arrays has been deprecated, please use `hasDirtyAttributes` instead'); return this.get('hasDirtyAttributes'); }), /** If this property is `true` the contents of the array do not match its original state. The array has local changes that have not yet been saved by the adapter. This includes additions, removals, and reordering of elements. Example ```javascript array.toArray(); // [ 'Tom', 'Yehuda' ] array.get('isDirty'); // false array.popObject(); // 'Yehuda' array.get('isDirty'); // true ``` @property hasDirtyAttributes @type {Boolean} @readOnly */ hasDirtyAttributes: model$fragments$lib$fragments$array$stateful$$computed('[]', '_originalState', function() { return ember$lib$main$$default.compare(this.toArray(), model$fragments$lib$fragments$array$stateful$$get(this, '_originalState')) !== 0; }), /** @method rollback @deprecated Use `rollbackAttributes()` instead */ rollback: function() { ember$lib$main$$default.deprecate('Using array.rollback() has been deprecated. Use array.rollbackAttributes() to discard any unsaved changes to fragments in the array.'); this.rollbackAttributes(); }, /** This method reverts local changes of the array's contents to its original state. Example ```javascript array.toArray(); // [ 'Tom', 'Yehuda' ] array.popObject(); // 'Yehuda' array.toArray(); // [ 'Tom' ] array.rollbackAttributes(); array.toArray(); // [ 'Tom', 'Yehuda' ] ``` @method rollbackAttributes */ rollbackAttributes: function() { this.setObjects(model$fragments$lib$fragments$array$stateful$$get(this, '_originalState')); }, /** Method alias for `toArray`. @method serialize @return {Array} */ serialize: function() { return this.toArray(); }, arrayContentDidChange: function() { this._super.apply(this, arguments); var record = model$fragments$lib$fragments$array$stateful$$get(this, 'owner'); var key = model$fragments$lib$fragments$array$stateful$$get(this, 'name'); // Any change to the size of the fragment array means a potential state change if (model$fragments$lib$fragments$array$stateful$$get(this, 'hasDirtyAttributes')) { model$fragments$lib$fragments$states$$fragmentDidDirty(record, key, this); } else { model$fragments$lib$fragments$states$$fragmentDidReset(record, key); } }, toStringExtension: function() { return 'owner(' + model$fragments$lib$fragments$array$stateful$$get(this, 'owner.id') + ')'; } }); var model$fragments$lib$fragments$array$stateful$$default = model$fragments$lib$fragments$array$stateful$$StatefulArray; /** @module ember-data.model-fragments */ var model$fragments$lib$fragments$ext$$keys = Object.keys || Ember.keys; /** @class Store @namespace DS */ ember$data$lib$system$store$$default.reopen({ /** Create a new fragment that does not yet have an owner record. The properties passed to this method are set on the newly created fragment. To create a new instance of the `name` fragment: ```js store.createFragment('name', { first: "Alex", last: "Routé" }); ``` @method createRecord @param {String} type @param {Object} properties a hash of properties to set on the newly created fragment. @return {DS.ModelFragment} fragment */ createFragment: function(modelName, props) { var type = this.modelFor(modelName); Ember.assert("The '" + type + "' model must be a subclass of DS.ModelFragment", model$fragments$lib$fragments$model$$default.detect(type)); var internalModel = new ember$data$lib$system$model$internal$model$$default(type, null, this, this.container); // Re-wire the internal model to use the fragment state machine internalModel.currentState = model$fragments$lib$fragments$states$$default.empty; internalModel._name = null; internalModel._owner = null; internalModel.loadedData(); var fragment = internalModel.getRecord(); if (props) { fragment.setProperties(props); } return fragment; } }); /** @class Model @namespace DS */ ember$data$lib$system$model$$default.reopen({ /** Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. When the model has fragments that have changed, the property value is simply `true`. Example ```javascript App.Mascot = DS.Model.extend({ type: DS.attr('string'), name: DS.hasOneFragment('name') }); App.Name = DS.Model.extend({ first : DS.attr('string'), last : DS.attr('string') }); var person = store.createRecord('person'); person.changedAttributes(); // {} person.get('name').set('first', 'Tomster'); person.set('type', 'Hamster'); person.changedAttributes(); // { name: true, type: [undefined, 'Hamster'] } ``` @method changedAttributes @return {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function() { var diffData = this._super(); var internalModel = model$fragments$lib$fragments$model$$internalModelFor(this); model$fragments$lib$fragments$ext$$keys(internalModel._fragments).forEach(function(name) { // An actual diff of the fragment or fragment array is outside the scope // of this method, so just indicate that there is a change instead if (name in internalModel._attributes) { diffData[name] = true; } }, this); return diffData; }, }); // Replace a method on an object with a new one that calls the original and then // invokes a function with the result function model$fragments$lib$fragments$ext$$decorateMethod(obj, name, fn) { var originalFn = obj[name]; obj[name] = function() { var value = originalFn.apply(this, arguments); return fn.call(this, value, arguments); }; } var model$fragments$lib$fragments$ext$$InternalModelPrototype = ember$data$lib$system$model$internal$model$$default.prototype; /** Override parent method to snapshot fragment attributes before they are passed to the `DS.Model#serialize`. @method _createSnapshot @private */ model$fragments$lib$fragments$ext$$decorateMethod(model$fragments$lib$fragments$ext$$InternalModelPrototype, 'createSnapshot', function createFragmentSnapshot(snapshot) { var attrs = snapshot._attributes; model$fragments$lib$fragments$ext$$keys(attrs).forEach(function(key) { var attr = attrs[key]; // If the attribute has a `_createSnapshot` method, invoke it before the // snapshot gets passed to the serializer if (attr && typeof attr._createSnapshot === 'function') { attrs[key] = attr._createSnapshot(); } }); return snapshot; }); /** If the model `hasDirtyAttributes` this function will discard any unsaved changes, recursively doing the same for all fragment properties. Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollbackAttributes(); record.get('name'); // 'Untitled Document' ``` @method rollbackAttributes */ model$fragments$lib$fragments$ext$$decorateMethod(model$fragments$lib$fragments$ext$$InternalModelPrototype, 'rollbackAttributes', function rollbackFragments() { for (var key in this._fragments) { if (this._fragments[key]) { this._fragments[key].rollbackAttributes(); } } }); /** If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data and notify all fragments of the commit. @method adapterDidCommit */ model$fragments$lib$fragments$ext$$decorateMethod(model$fragments$lib$fragments$ext$$InternalModelPrototype, 'adapterDidCommit', function adapterDidCommit(returnValue, args) { var attributes = (args[0] && args[0].attributes) || {}; var fragment; // Notify fragments that the record was committed for (var key in this._fragments) { if (fragment = this._fragments[key]) { fragment._adapterDidCommit(attributes[key]); } } }); /** @class JSONSerializer @namespace DS */ ember$data$lib$serializers$json$serializer$$default.reopen({ /** Enables fragment properties to have custom transforms based on the fragment type, so that deserialization does not have to happen on the fly @method transformFor @private */ transformFor: function(attributeType) { if (attributeType.indexOf('-mf-') === 0) { return model$fragments$lib$fragments$ext$$getFragmentTransform(this.container, this.store, attributeType); } return this._super.apply(this, arguments); } }); // Retrieve or create a transform for the specific fragment type function model$fragments$lib$fragments$ext$$getFragmentTransform(container, store, attributeType) { var registry = container._registry || container; var containerKey = 'transform:' + attributeType; var match = attributeType.match(/^-mf-(fragment|fragment-array|array)(?:\$([^$]+))?(?:\$(.+))?$/); var transformType = match[1]; var modelName = match[2]; var polymorphicTypeProp = match[3]; if (!registry.has(containerKey)) { var transformClass = container.lookupFactory('transform:' + transformType); registry.register(containerKey, transformClass.extend({ store: store, modelName: modelName, polymorphicTypeProp: polymorphicTypeProp })); } return container.lookup(containerKey); } /** @module ember-data.model-fragments */ var model$fragments$lib$fragments$model$$get = ember$lib$main$$default.get; var model$fragments$lib$fragments$model$$create = Object.create || ember$lib$main$$default.create; var model$fragments$lib$fragments$model$$merge = ember$lib$main$$default.merge; /** The class that all nested object structures, or 'fragments', descend from. Fragments are bound to a single 'owner' record (an instance of `DS.Model`) and cannot change owners once set. They behave like models, but they have no `save` method since their persistence is managed entirely through their owner. Because of this, a fragment's state directly influences its owner's state, e.g. when a record's fragment `hasDirtyAttributes`, its owner `hasDirtyAttributes`. Example: ```javascript App.Person = DS.Model.extend({ name: DS.hasOneFragment('name') }); App.Name = DS.ModelFragment.extend({ first : DS.attr('string'), last : DS.attr('string') }); ``` With JSON response: ```json { "id": "1", "name": { "first": "Robert", "last": "Jackson" } } ``` ```javascript var person = store.getbyid('person', '1'); var name = person.get('name'); person.get('hasDirtyAttributes'); // false name.get('hasDirtyAttributes'); // false name.get('first'); // 'Robert' name.set('first', 'The Animal'); name.get('hasDirtyAttributes'); // true person.get('hasDirtyAttributes'); // true person.rollbackAttributes(); name.get('first'); // 'Robert' person.get('hasDirtyAttributes'); // false person.get('hasDirtyAttributes'); // false ``` @class ModelFragment @namespace DS @extends CoreModel @uses Ember.Comparable @uses Ember.Copyable */ var model$fragments$lib$fragments$model$$ModelFragment = ember$data$lib$system$model$$default.extend(ember$lib$main$$default.Comparable, ember$lib$main$$default.Copyable, { /** Compare two fragments by identity to allow `FragmentArray` to diff arrays. @method compare @param a {DS.ModelFragment} the first fragment to compare @param b {DS.ModelFragment} the second fragment to compare @return {Integer} the result of the comparison */ compare: function(f1, f2) { return f1 === f2 ? 0 : 1; }, /** Create a new fragment that is a copy of the current fragment. Copied fragments do not have the same owner record set, so they may be added to other records safely. @method copy @return {DS.ModelFragment} the newly created fragment */ copy: function() { var data = {}; // TODO: handle copying sub-fragments model$fragments$lib$fragments$model$$merge(data, this._data); model$fragments$lib$fragments$model$$merge(data, this._attributes); return this.store.createFragment(this.constructor.modelName, data); }, /** @method adapterDidCommit */ _adapterDidCommit: function(data) { model$fragments$lib$fragments$model$$internalModelFor(this).setupData({ attributes: data || {} }); }, toStringExtension: function() { return 'owner(' + model$fragments$lib$fragments$model$$get(model$fragments$lib$fragments$model$$internalModelFor(this)._owner, 'id') + ')'; } }); function model$fragments$lib$fragments$model$$getActualFragmentType(declaredType, options, data) { if (!options.polymorphic || !data) { return declaredType; } var typeKey = options.typeKey || 'type'; var actualType = data[typeKey]; return actualType || declaredType; } function model$fragments$lib$fragments$model$$internalModelFor(record) { var internalModel = record._internalModel; // Ensure the internal model has a fragments hash, since we can't override the // constructor function anymore if (!internalModel._fragments) { internalModel._fragments = model$fragments$lib$fragments$model$$create(null); } return internalModel; } function model$fragments$lib$fragments$model$$setFragmentOwner(fragment, record, key) { var internalModel = model$fragments$lib$fragments$model$$internalModelFor(fragment); ember$lib$main$$default.assert("Fragments can only belong to one owner, try copying instead", !internalModel._owner || internalModel._owner === record); internalModel._owner = record; internalModel._name = key; return fragment; } var model$fragments$lib$fragments$model$$default = model$fragments$lib$fragments$model$$ModelFragment; function model$fragments$lib$util$map$$map(obj, callback, thisArg) { return obj.map ? obj.map(callback, thisArg) : model$fragments$lib$util$map$$mapPolyfill.call(obj, callback, thisArg); } var model$fragments$lib$util$map$$default = model$fragments$lib$util$map$$map; // https://github.com/emberjs/ember.js/blob/v1.11.0/packages/ember-metal/lib/array.js function model$fragments$lib$util$map$$mapPolyfill(fun /*, thisp */) { if (this === void 0 || this === null || typeof fun !== "function") { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; var res = new Array(len); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in t) { res[i] = fun.call(thisp, t[i], i, t); } } return res; } /** @module ember-data.model-fragments */ var model$fragments$lib$fragments$array$fragment$$get = ember$lib$main$$default.get; var model$fragments$lib$fragments$array$fragment$$computed = ember$lib$main$$default.computed; /** A state-aware array of fragments that is tied to an attribute of a `DS.Model` instance. `FragmentArray` instances should not be created directly, instead use the `DS.hasManyFragments` attribute. @class FragmentArray @namespace DS @extends StatefulArray */ var model$fragments$lib$fragments$array$fragment$$FragmentArray = model$fragments$lib$fragments$array$stateful$$default.extend({ /** The type of fragments the array contains @property type @private @type {String} */ type: null, options: null, init: function() { this._super(); this._isInitializing = false; }, /** @method _processData @private @param {Object} data */ _processData: function(data) { var record = model$fragments$lib$fragments$array$fragment$$get(this, 'owner'); var store = model$fragments$lib$fragments$array$fragment$$get(record, 'store'); var declaredType = model$fragments$lib$fragments$array$fragment$$get(this, 'type'); var options = model$fragments$lib$fragments$array$fragment$$get(this, 'options'); var key = model$fragments$lib$fragments$array$fragment$$get(this, 'name'); var content = model$fragments$lib$fragments$array$fragment$$get(this, 'content'); // Mark the fragment array as initializing so that state changes are ignored // until after all fragments' data is setup this._isInitializing = true; // Map data to existing fragments and create new ones where necessary var processedData = model$fragments$lib$util$map$$default(ember$lib$main$$default.makeArray(data), function(data, i) { var fragment = content[i]; // Create a new fragment from the data array if needed if (!fragment) { var actualType = model$fragments$lib$fragments$model$$getActualFragmentType(declaredType, options, data); fragment = store.createFragment(actualType); model$fragments$lib$fragments$model$$setFragmentOwner(fragment, record, key); } // Initialize the fragment with the data model$fragments$lib$fragments$model$$internalModelFor(fragment).setupData({ attributes: data }); return fragment; }); this._isInitializing = false; return processedData; }, /** @method _createSnapshot @private */ _createSnapshot: function() { // Snapshot each fragment return this.map(function(fragment) { return fragment._createSnapshot(); }); }, /** @method adapterDidCommit @private */ _adapterDidCommit: function(data) { this._super(data); // If the adapter update did not contain new data, just notify each fragment // so it can transition to a clean state if (!data) { // Notify all records of commit this.forEach(function(fragment) { fragment._adapterDidCommit(); }); } }, /** If this property is `true`, either the contents of the array do not match its original state, or one or more of the fragments in the array are dirty. Example ```javascript array.toArray(); // [ <Fragment:1>, <Fragment:2> ] array.get('hasDirtyAttributes'); // false array.get('firstObject').set('prop', 'newValue'); array.get('hasDirtyAttributes'); // true ``` @property hasDirtyAttributes @type {Boolean} @readOnly */ hasDirtyAttributes: model$fragments$lib$fragments$array$fragment$$computed('@each.hasDirtyAttributes', '_originalState', function() { return this._super() || this.isAny('hasDirtyAttributes'); }), /** This method reverts local changes of the array's contents to its original state, and calls `rollbackAttributes` on each fragment. Example ```javascript array.get('firstObject').get('hasDirtyAttributes'); // true array.get('hasDirtyAttributes'); // true array.rollbackAttributes(); array.get('firstObject').get('hasDirtyAttributes'); // false array.get('hasDirtyAttributes'); // false ``` @method rollbackAttributes */ rollbackAttributes: function() { this._super(); this.invoke('rollbackAttributes'); }, /** Serializing a fragment array returns a new array containing the results of calling `serialize` on each fragment in the array. @method serialize @return {Array} */ serialize: function() { return this.invoke('serialize'); }, replaceContent: function(idx, amt, fragments) { var array = this; var record = model$fragments$lib$fragments$array$fragment$$get(this, 'owner'); var key = model$fragments$lib$fragments$array$fragment$$get(this, 'name'); // Since all array manipulation methods end up using this method, ensure // ensure that fragments are the correct type and have an owner and name if (fragments) { fragments.forEach(function(fragment) { var owner = model$fragments$lib$fragments$model$$internalModelFor(fragment)._owner; ember$lib$main$$default.assert("Fragments can only belong to one owner, try copying instead", !owner || owner === record); ember$lib$main$$default.assert("You can only add '" + model$fragments$lib$fragments$array$fragment$$get(array, 'type') + "' fragments to this property", (function (type) { if (fragment instanceof type) { return true; } else if (ember$lib$main$$default.MODEL_FACTORY_INJECTIONS) { return fragment instanceof type.superclass; } return false; })(model$fragments$lib$fragments$array$fragment$$get(record, 'store').modelFor(model$fragments$lib$fragments$array$fragment$$get(array, 'type')))); if (!owner) { model$fragments$lib$fragments$model$$setFragmentOwner(fragment, record, key); } }); } return model$fragments$lib$fragments$array$fragment$$get(this, 'content').replace(idx, amt, fragments); }, /** Adds an existing fragment to the end of the fragment array. Alias for `addObject`. @method addFragment @param {DS.ModelFragment} fragment @return {DS.ModelFragment} the newly added fragment */ addFragment: function(fragment) { return this.addObject(fragment); }, /** Removes the given fragment from the array. Alias for `removeObject`. @method removeFragment @param {DS.ModelFragment} fragment @return {DS.ModelFragment} the removed fragment */ removeFragment: function(fragment) { return this.removeObject(fragment); }, /** Creates a new fragment of the fragment array's type and adds it to the end of the fragment array @method createFragment @param {DS.ModelFragment} fragment @return {DS.ModelFragment} the newly added fragment */ createFragment: function(props) { var record = model$fragments$lib$fragments$array$fragment$$get(this, 'owner'); var store = model$fragments$lib$fragments$array$fragment$$get(record, 'store'); var type = model$fragments$lib$fragments$array$fragment$$get(this, 'type'); var fragment = store.createFragment(type, props); return this.pushObject(fragment); } }); var model$fragments$lib$fragments$array$fragment$$default = model$fragments$lib$fragments$array$fragment$$FragmentArray; var model$fragments$lib$util$ember$new$computed$$Ember = window.Ember; var model$fragments$lib$util$ember$new$computed$$computed = model$fragments$lib$util$ember$new$computed$$Ember.computed; var model$fragments$lib$util$ember$new$computed$$supportsSetterGetter; try { model$fragments$lib$util$ember$new$computed$$Ember.computed({ set: function() { }, get: function() { } }); model$fragments$lib$util$ember$new$computed$$supportsSetterGetter = true; } catch(e) { model$fragments$lib$util$ember$new$computed$$supportsSetterGetter = false; } var model$fragments$lib$util$ember$new$computed$$default = function() { var polyfillArguments = []; var config = arguments[arguments.length - 1]; if (typeof config === 'function' || model$fragments$lib$util$ember$new$computed$$supportsSetterGetter) { return model$fragments$lib$util$ember$new$computed$$computed.apply(this, arguments); } for (var i = 0, l = arguments.length - 1; i < l; i++) { polyfillArguments.push(arguments[i]); } var func; if (config.set) { func = function(key, value) { if (arguments.length > 1) { return config.set.call(this, key, value); } else { return config.get.call(this, key); } }; } else { func = function(key) { return config.get.call(this, key); }; } polyfillArguments.push(func); return model$fragments$lib$util$ember$new$computed$$computed.apply(this, polyfillArguments); }; /** @module ember-data.model-fragments */ var model$fragments$lib$fragments$attributes$$get = ember$lib$main$$default.get; // Create a unique type string for the combination of fragment property type, // fragment model name, and polymorphic type key function model$fragments$lib$fragments$attributes$$metaTypeFor(type, modelName, options) { var metaType = '-mf-' + type; if (modelName) { metaType += '$' + modelName; } if (options && options.polymorphic) { metaType += '$' + (options.typeKey || 'type'); } return metaType; } /** `DS.hasOneFragment` defines an attribute on a `DS.Model` or `DS.ModelFragment` instance. Much like `DS.belongsTo`, it creates a property that returns a single fragment of the given type. `DS.hasOneFragment` takes an optional hash as a second parameter, currently supported options are: - `defaultValue`: An object literal or a function to be called to set the attribute to a default value if none is supplied. Values are deep copied before being used. Note that default values will be passed through the fragment's serializer when creating the fragment. Example ```javascript App.Person = DS.Model.extend({ name: DS.hasOneFragment('name', { defaultValue: {} }) }); App.Name = DS.ModelFragment.extend({ first : DS.attr('string'), last : DS.attr('string') }); ``` @namespace @method hasOneFragment @for DS @param {String} type the fragment type @param {Object} options a hash of options @return {Attribute} */ function model$fragments$lib$fragments$attributes$$hasOneFragment(declaredModelName, options) { options = options || {}; var metaType = model$fragments$lib$fragments$attributes$$metaTypeFor('fragment', declaredModelName, options); function setupFragment(store, record, key) { var internalModel = model$fragments$lib$fragments$model$$internalModelFor(record); var data = internalModel._data[key] || model$fragments$lib$fragments$attributes$$getDefaultValue(internalModel, options, 'object'); var fragment = internalModel._fragments[key]; var actualTypeName = model$fragments$lib$fragments$model$$getActualFragmentType(declaredModelName, options, data); // Regardless of whether being called as a setter or getter, the fragment // may not be initialized yet, in which case the data will contain a // raw response or a stashed away fragment // If we already have a processed fragment in _data and our current fragmet is // null simply reuse the one from data. We can be in this state after a rollback // for example if (!fragment && model$fragments$lib$fragments$attributes$$isInstanceOfType(store.modelFor(actualTypeName), data)) { fragment = data; // Else initialize the fragment } else if (data && data !== fragment) { fragment || (fragment = model$fragments$lib$fragments$model$$setFragmentOwner(store.createFragment(actualTypeName), record, key)); // Make sure to first cache the fragment before calling setupData, so if setupData causes this CP to be accessed // again we have it cached already internalModel._data[key] = fragment; model$fragments$lib$fragments$model$$internalModelFor(fragment).setupData({ attributes: data }); } else { // Handle the adapter setting the fragment to null fragment = data; } return fragment; } function setFragmentValue(record, key, fragment, value) { ember$lib$main$$default.assert("You can only assign a '" + declaredModelName + "' fragment to this property", value === null || model$fragments$lib$fragments$attributes$$isInstanceOfType(record.store.modelFor(declaredModelName), value)); var internalModel = model$fragments$lib$fragments$model$$internalModelFor(record); fragment = value ? model$fragments$lib$fragments$model$$setFragmentOwner(value, record, key) : null; if (internalModel._data[key] !== fragment) { model$fragments$lib$fragments$states$$fragmentDidDirty(record, key, fragment); } else { model$fragments$lib$fragments$states$$fragmentDidReset(record, key); } return fragment; } return model$fragments$lib$fragments$attributes$$fragmentProperty(metaType, options, setupFragment, setFragmentValue); } // Check whether a fragment is an instance of the given type, respecting model // factory injections function model$fragments$lib$fragments$attributes$$isInstanceOfType(type, fragment) { if (fragment instanceof type) { return true; } else if (ember$lib$main$$default.MODEL_FACTORY_INJECTIONS) { return fragment instanceof type.superclass; } return false; } /** `DS.hasManyFragments` defines an attribute on a `DS.Model` or `DS.ModelFragment` instance. Much like `DS.hasMany`, it creates a property that returns an array of fragments of the given type. The array is aware of its original state and so has a `hasDirtyAttributes` property and a `rollback` method. If a fragment type is not given, values are not converted to fragments, but passed straight through. `DS.hasOneFragment` takes an optional hash as a second parameter, currently supported options are: - `defaultValue`: An array literal or a function to be called to set the attribute to a default value if none is supplied. Values are deep copied before being used. Note that default values will be passed through the fragment's serializer when creating the fragment. Example ```javascript App.Person = DS.Model.extend({ addresses: DS.hasManyFragments('address', { defaultValue: [] }) }); App.Address = DS.ModelFragment.extend({ street : DS.attr('string'), city : DS.attr('string'), region : DS.attr('string'), country : DS.attr('string') }); ``` @namespace @method hasManyFragments @for DS @param {String} type the fragment type (optional) @param {Object} options a hash of options @return {Attribute} */ function model$fragments$lib$fragments$attributes$$hasManyFragments(modelName, options) { options || (options = {}); // If a modelName is not given, it implies an array of primitives if (ember$lib$main$$default.typeOf(modelName) !== 'string') { return model$fragments$lib$fragments$attributes$$arrayProperty(options); } var metaType = model$fragments$lib$fragments$attributes$$metaTypeFor('fragment-array', modelName, options); return model$fragments$lib$fragments$attributes$$fragmentArrayProperty(metaType, options, function createFragmentArray(record, key) { return model$fragments$lib$fragments$array$fragment$$default.create({ type: modelName, options: options, name: key, owner: record }); }); } function model$fragments$lib$fragments$attributes$$arrayProperty(options) { options || (options = {}); var metaType = model$fragments$lib$fragments$attributes$$metaTypeFor('array'); return model$fragments$lib$fragments$attributes$$fragmentArrayProperty(metaType, options, function createStatefulArray(record, key) { return model$fragments$lib$fragments$array$stateful$$default.create({ options: options, name: key, owner: record }); }); } function model$fragments$lib$fragments$attributes$$fragmentProperty(type, options, setupFragment, setFragmentValue) { options = options || {}; var meta = { type: type, isAttribute: true, isFragment: true, options: options }; return model$fragments$lib$util$ember$new$computed$$default({ get: function(key) { var internalModel = model$fragments$lib$fragments$model$$internalModelFor(this); var fragment = setupFragment(this.store, this, key); return internalModel._fragments[key] = fragment; }, set: function(key, value) { var internalModel = model$fragments$lib$fragments$model$$internalModelFor(this); var fragment = setupFragment(this.store, this, key); fragment = setFragmentValue(this, key, fragment, value); return internalModel._fragments[key] = fragment; } }).meta(meta); } function model$fragments$lib$fragments$attributes$$fragmentArrayProperty(metaType, options, createArray) { function setupFragmentArray(store, record, key) { var internalModel = model$fragments$lib$fragments$model$$internalModelFor(record); var data = internalModel._data[key] || model$fragments$lib$fragments$attributes$$getDefaultValue(internalModel, options, 'array'); var fragments = internalModel._fragments[key] || null; // If we already have a processed fragment in _data and our current fragmet is // null simply reuse the one from data. We can be in this state after a rollback // for example if (data instanceof model$fragments$lib$fragments$array$stateful$$default && !fragments) { fragments = data; // Create a fragment array and initialize with data } else if (data && data !== fragments) { fragments || (fragments = createArray(record, key)); internalModel._data[key] = fragments; fragments.setupData(data); } else { // Handle the adapter setting the fragment array to null fragments = data; } return fragments; } function setFragmentValue(record, key, fragments, value) { var internalModel = model$fragments$lib$fragments$model$$internalModelFor(record); if (ember$lib$main$$default.isArray(value)) { fragments || (fragments = createArray(record, key)); fragments.setObjects(value); } else if (value === null) { fragments = null; } else { ember$lib$main$$default.assert("A fragment array property can only be assigned an array or null"); } if (internalModel._data[key] !== fragments || model$fragments$lib$fragments$attributes$$get(fragments, 'hasDirtyAttributes')) { model$fragments$lib$fragments$states$$fragmentDidDirty(record, key, fragments); } else { model$fragments$lib$fragments$states$$fragmentDidReset(record, key); } return fragments; } return model$fragments$lib$fragments$attributes$$fragmentProperty(metaType, options, setupFragmentArray, setFragmentValue); } // Like `DS.belongsTo`, when used within a model fragment is a reference // to the owner record /** `DS.fragmentOwner` defines a read-only attribute on a `DS.ModelFragment` instance. The attribute returns a reference to the fragment's owner record. Example ```javascript App.Person = DS.Model.extend({ name: DS.hasOneFragment('name') }); App.Name = DS.ModelFragment.extend({ first : DS.attr('string'), last : DS.attr('string'), person : DS.fragmentOwner() }); ``` @namespace @method fragmentOwner @for DS @return {Attribute} */ function model$fragments$lib$fragments$attributes$$fragmentOwner() { // TODO: add a warning when this is used on a non-fragment return ember$lib$main$$default.computed(function() { return model$fragments$lib$fragments$model$$internalModelFor(this)._owner; }).readOnly(); } // The default value of a fragment is either an array or an object, // which should automatically get deep copied function model$fragments$lib$fragments$attributes$$getDefaultValue(record, options, type) { var value; if (typeof options.defaultValue === "function") { value = options.defaultValue(); } else if (options.defaultValue) { value = options.defaultValue; } else { return null; } ember$lib$main$$default.assert("The fragment's default value must be an " + type, ember$lib$main$$default.typeOf(value) == type); // Create a deep copy of the resulting value to avoid shared reference errors return ember$lib$main$$default.copy(value, true); } /** @module ember-data.model-fragments */ var model$fragments$lib$fragments$transforms$array$$makeArray = ember$lib$main$$default.makeArray; /** Transform for array-like attributes fragment attribute with no model @class ArrayTransform @namespace DS @extends DS.Transform */ var model$fragments$lib$fragments$transforms$array$$ArrayTransform = ember$data$lib$system$transform$$default.extend({ deserialize: function deserializeArray(data) { return data == null ? null : model$fragments$lib$fragments$transforms$array$$makeArray(data); }, serialize: function serializeArray(array) { return array && array.toArray ? array.toArray() : array; } }); var model$fragments$lib$fragments$transforms$array$$default = model$fragments$lib$fragments$transforms$array$$ArrayTransform; /** @module ember-data.model-fragments */ var model$fragments$lib$fragments$transforms$fragment$$get = ember$lib$main$$default.get; /** Transform for `DS.hasOneFragment` fragment attribute which delegates work to the fragment type's serializer @class FragmentTransform @namespace DS @extends DS.Transform */ var model$fragments$lib$fragments$transforms$fragment$$FragmentTransform = ember$data$lib$system$transform$$default.extend({ store: null, modelName: null, polymorphicTypeProp: null, deserialize: function deserializeFragment(data) { if (data == null) { return null; } return this.deserializeSingle(data); }, serialize: function serializeFragment(snapshot) { if (!snapshot) { return null; } var store = this.store; var serializer = store.serializerFor(snapshot.modelName); return serializer.serialize(snapshot); }, modelNameFor: function modelNameFor(data) { var modelName = model$fragments$lib$fragments$transforms$fragment$$get(this, 'modelName'); var polymorphicTypeProp = model$fragments$lib$fragments$transforms$fragment$$get(this, 'polymorphicTypeProp'); if (data && polymorphicTypeProp && data[polymorphicTypeProp]) { modelName = data[polymorphicTypeProp]; } return modelName; }, deserializeSingle: function deserializeSingle(data) { var store = this.store; var modelName = this.modelNameFor(data); var serializer = store.serializerFor(modelName); ember$lib$main$$default.assert("The `JSONAPISerializer` is not suitable for model fragments, please use `JSONSerializer`", !(serializer instanceof ember$data$lib$serializers$json$api$serializer$$default)); var isNewSerializerAPI = model$fragments$lib$fragments$transforms$fragment$$get(serializer, 'isNewSerializerAPI'); var typeClass = store.modelFor(modelName); var serialized = serializer.normalize(typeClass, data); // The new serializer API returns a full JSON API document, but we only need // the attributes hash if (isNewSerializerAPI) { return model$fragments$lib$fragments$transforms$fragment$$get(serialized, 'data.attributes'); } else { return serialized; } } }); var model$fragments$lib$fragments$transforms$fragment$$default = model$fragments$lib$fragments$transforms$fragment$$FragmentTransform; /** @module ember-data.model-fragments */ /** Transform for `DS.hasManyFragments` fragment attribute which delegates work to the fragment type's serializer @class FragmentArrayTransform @namespace DS @extends DS.Transform */ var model$fragments$lib$fragments$transforms$fragment$array$$FragmentArrayTransform = model$fragments$lib$fragments$transforms$fragment$$default.extend({ deserialize: function deserializeFragmentArray(data) { if (data == null) { return null; } return model$fragments$lib$util$map$$default(data, function(datum) { return this.deserializeSingle(datum); }, this); }, serialize: function serializeFragmentArray(snapshots) { if (!snapshots) { return null; } var store = this.store; return model$fragments$lib$util$map$$default(snapshots, function(snapshot) { var serializer = store.serializerFor(snapshot.modelName); return serializer.serialize(snapshot); }); } }); var model$fragments$lib$fragments$transforms$fragment$array$$default = model$fragments$lib$fragments$transforms$fragment$array$$FragmentArrayTransform; var model$fragments$lib$initializers$$initializers = [ { name: "fragmentTransform", before: "store", initialize: function(container, application) { application.register('transform:fragment', model$fragments$lib$fragments$transforms$fragment$$default); application.register('transform:fragment-array', model$fragments$lib$fragments$transforms$fragment$array$$default); application.register('transform:array', model$fragments$lib$fragments$transforms$array$$default); } } ]; var model$fragments$lib$initializers$$default = model$fragments$lib$initializers$$initializers; function model$fragments$lib$main$$exportMethods(scope) { scope.ModelFragment = model$fragments$lib$fragments$model$$default; scope.FragmentArray = model$fragments$lib$fragments$array$fragment$$default; scope.FragmentTransform = model$fragments$lib$fragments$transforms$fragment$$default; scope.FragmentArrayTransform = model$fragments$lib$fragments$transforms$fragment$array$$default; scope.ArrayTransform = model$fragments$lib$fragments$transforms$array$$default; scope.hasOneFragment = model$fragments$lib$fragments$attributes$$hasOneFragment; scope.hasManyFragments = model$fragments$lib$fragments$attributes$$hasManyFragments; scope.fragmentOwner = model$fragments$lib$fragments$attributes$$fragmentOwner; } /** Ember Data Model Fragments @module ember-data.model-fragments @main ember-data.model-fragments */ var model$fragments$lib$main$$MF = ember$lib$main$$default.Namespace.create({ VERSION: '0.3.3+8b1fcdd5' }); model$fragments$lib$main$$exportMethods(model$fragments$lib$main$$MF); // This will be removed at some point in favor of the `MF` namespace model$fragments$lib$main$$exportMethods(ember$data$lib$main$$default); ember$lib$main$$default.onLoad('Ember.Application', function(Application) { model$fragments$lib$initializers$$default.forEach(Application.initializer, Application); }); if (ember$lib$main$$default.libraries) { ember$lib$main$$default.libraries.register('Model Fragments', model$fragments$lib$main$$MF.VERSION); } var model$fragments$lib$main$$default = model$fragments$lib$main$$MF; }).call(this); //# sourceMappingURL=ember-data.model-fragments.map
jkusa/ember-data.model-fragments
dist/ember-data.model-fragments.js
JavaScript
mit
56,548
'use strict'; var pify = module.exports = function (fn, P, opts) { if (typeof P !== 'function') { opts = P; P = Promise; } opts = opts || {}; if (typeof fn !== 'function') { return P.reject(new TypeError('Expected a function')); } return function () { var that = this; var args = [].slice.call(arguments); return new P(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else if (opts.multiArgs) { resolve([].slice.call(arguments, 1)); } else { resolve(result); } }); fn.apply(that, args); }); }; }; pify.all = function (obj, P, opts) { if (typeof P !== 'function') { opts = P; P = Promise; } opts = opts || {}; var filter = function (key) { if (opts.include) { return opts.include.indexOf(key) !== -1; } if (opts.exclude) { return opts.exclude.indexOf(key) === -1; } return true; }; var ret = (typeof obj === 'function') ? function () { if (opts.excludeMain) { return obj.apply(this, arguments); } return pify(obj, P, opts).apply(this, arguments); } : {}; return Object.keys(obj).reduce(function (ret, key) { var x = obj[key]; ret[key] = (typeof x === 'function') && filter(key) ? pify(x, P, opts) : x; return ret; }, ret); };
zayers/ridgecrest-alumni
wp-content/themes/ridgecrest-alumni/grunt/node_modules/grunt-contrib-cssmin/node_modules/maxmin/node_modules/pretty-bytes/node_modules/meow/node_modules/read-pkg-up/node_modules/read-pkg/node_modules/path-type/node_modules/pify/index.js
JavaScript
gpl-2.0
1,285
/* eslint-disable */ // adapted based on rackt/history (MIT) // Node 0.10+ var execSync = require('child_process').execSync; var fs = require('fs'); // Node 0.10 check if (!execSync) { execSync = require('sync-exec'); } function exec(command) { execSync(command, { stdio: [0, 1, 2] }); } fs.stat('dist', function(error, stat) { // Skip building on Travis if (process.env.TRAVIS) { return; } if (error || !stat.isDirectory()) { // Create a directory to avoid getting stuck // in postinstall loop fs.mkdirSync('dist'); exec('npm install --only=dev'); exec('npm run build'); } });
shikun2014010800/manga
web/console/node_modules/uglifyjs-webpack-plugin/lib/post_install.js
JavaScript
mit
626
/* Copyright (c) 2012, Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var fileset = require('fileset'), path = require('path'), seq = 0; function filesFor(options, callback) { if (!callback && typeof options === 'function') { callback = options; options = null; } options = options || {}; var root = options.root, includes = options.includes, excludes = options.excludes, relative = options.relative, opts; root = root || process.cwd(); includes = includes && Array.isArray(includes) ? includes : [ '**/*.js' ]; excludes = excludes && Array.isArray(excludes) ? excludes : [ '**/node_modules/**' ]; opts = { cwd: root }; seq += 1; opts['x' + seq + new Date().getTime()] = true; //cache buster for minimatch cache bug fileset(includes.join(' '), excludes.join(' '), opts, function (err, files) { if (err) { return callback(err); } if (!relative) { files = files.map(function (file) { return path.resolve(root, file); }); } callback(err, files); }); } function matcherFor(options, callback) { if (!callback && typeof options === 'function') { callback = options; options = null; } options = options || {}; options.relative = false; //force absolute paths filesFor(options, function (err, files) { var fileMap = {}, matchFn; if (err) { return callback(err); } files.forEach(function (file) { fileMap[file] = true; }); matchFn = function (file) { return fileMap[file]; }; matchFn.files = Object.keys(fileMap); return callback(null, matchFn); }); } module.exports = { filesFor: filesFor, matcherFor: matcherFor };
frangucc/gamify
www/sandbox/pals/node_modules/karma-coverage/node_modules/istanbul/lib/util/file-matcher.js
JavaScript
mit
1,860
var argscheck = require('cordova/argscheck'), utils = require('cordova/utils'), exec = require('cordova/exec'), channel = require('cordova/channel'); var Keyboard = function() { }; Keyboard.hideKeyboardAccessoryBar = function(hide) { exec(null, null, "Keyboard", "hideKeyboardAccessoryBar", [hide]); }; Keyboard.close = function() { exec(null, null, "Keyboard", "close", []); }; Keyboard.show = function() { exec(null, null, "Keyboard", "show", []); }; Keyboard.disableScroll = function(disable) { exec(null, null, "Keyboard", "disableScroll", [disable]); }; /* Keyboard.styleDark = function(dark) { exec(null, null, "Keyboard", "styleDark", [dark]); }; */ Keyboard.isVisible = false; channel.onCordovaReady.subscribe(function() { exec(success, null, 'Keyboard', 'init', []); function success(msg) { var action = msg.charAt(0); if ( action === 'S' ) { var keyboardHeight = msg.substr(1); cordova.plugins.Keyboard.isVisible = true; cordova.fireWindowEvent('native.keyboardshow', { 'keyboardHeight': + keyboardHeight }); //deprecated cordova.fireWindowEvent('native.showkeyboard', { 'keyboardHeight': + keyboardHeight }); } else if ( action === 'H' ) { cordova.plugins.Keyboard.isVisible = false; cordova.fireWindowEvent('native.keyboardhide'); //deprecated cordova.fireWindowEvent('native.hidekeyboard'); } } }); module.exports = Keyboard;
porschebest/NOW
www/plugins/ionic-plugin-keyboard/www/android/keyboard.js
JavaScript
mit
1,538
var m1_a1 = 10; var m1_c1 = (function () { function m1_c1() { } return m1_c1; })(); var m1_instance1 = new m1_c1(); function m1_f1() { return m1_instance1; } //# sourceMappingURL=m1.js.map
wangyanxing/TypeScript
tests/baselines/reference/projectOutput/sourcerootUrlSubfolderSpecifyOutputDirectory/node/outdir/simple/ref/m1.js
JavaScript
apache-2.0
214
import * as t from "babel-types"; import * as util from "./util"; // this function converts a shorthand object generator method into a normal // (non-shorthand) object property which is a generator function expression. for // example, this: // // var foo = { // *bar(baz) { return 5; } // } // // should be replaced with: // // var foo = { // bar: function*(baz) { return 5; } // } // // to do this, it clones the parameter array and the body of the object generator // method into a new FunctionExpression. // // this method can be passed any Function AST node path, and it will return // either: // a) the path that was passed in (iff the path did not need to be replaced) or // b) the path of the new FunctionExpression that was created as a replacement // (iff the path did need to be replaced) // // In either case, though, the caller can count on the fact that the return value // is a Function AST node path. // // If this function is called with an AST node path that is not a Function (or with an // argument that isn't an AST node path), it will throw an error. export default function replaceShorthandObjectMethod(path) { if (!path.node || !t.isFunction(path.node)) { throw new Error("replaceShorthandObjectMethod can only be called on Function AST node paths."); } // this function only replaces shorthand object methods (called ObjectMethod // in Babel-speak). if (!t.isObjectMethod(path.node)) { return path; } // this function only replaces generators. if (!path.node.generator) { return path; } const parameters = path.node.params.map(function (param) { return t.cloneDeep(param); }) const functionExpression = t.functionExpression( null, // id parameters, // params t.cloneDeep(path.node.body), // body path.node.generator, path.node.async ); util.replaceWithOrRemove(path, t.objectProperty( t.cloneDeep(path.node.key), // key functionExpression, //value path.node.computed, // computed false // shorthand ) ); // path now refers to the ObjectProperty AST node path, but we want to return a // Function AST node path for the function expression we created. we know that // the FunctionExpression we just created is the value of the ObjectProperty, // so return the "value" path off of this path. return path.get("value"); }
hellokidder/js-studying
微信小程序/wxtest/node_modules/regenerator-transform/src/replaceShorthandObjectMethod.js
JavaScript
mit
2,374
/* Highcharts JS v3.0.4 (2013-08-02) Exporting module (c) 2010-2013 Torstein Hønsi License: www.highcharts.com/license */ (function(e){var y=e.Chart,v=e.addEvent,B=e.removeEvent,m=e.createElement,j=e.discardElement,t=e.css,k=e.merge,r=e.each,p=e.extend,C=Math.max,i=document,z=window,D=e.isTouchDevice,E=e.Renderer.prototype.symbols,s=e.getOptions(),w;p(s.lang,{printChart:"Print chart",downloadPNG:"Download PNG image",downloadJPEG:"Download JPEG image",downloadPDF:"Download PDF document",downloadSVG:"Download SVG vector image",contextButtonTitle:"Chart context menu"});s.navigation={menuStyle:{border:"1px solid #A0A0A0", background:"#FFFFFF",padding:"5px 0"},menuItemStyle:{padding:"0 10px",background:"none",color:"#303030",fontSize:D?"14px":"11px"},menuItemHoverStyle:{background:"#4572A5",color:"#FFFFFF"},buttonOptions:{symbolFill:"#E0E0E0",symbolSize:14,symbolStroke:"#666",symbolStrokeWidth:3,symbolX:12.5,symbolY:10.5,align:"right",buttonSpacing:3,height:22,theme:{fill:"white",stroke:"none"},verticalAlign:"top",width:24}};s.exporting={type:"image/png",url:"http://export.highcharts.com/",buttons:{contextButton:{symbol:"menu", _titleKey:"contextButtonTitle",menuItems:[{textKey:"printChart",onclick:function(){this.print()}},{separator:!0},{textKey:"downloadPNG",onclick:function(){this.exportChart()}},{textKey:"downloadJPEG",onclick:function(){this.exportChart({type:"image/jpeg"})}},{textKey:"downloadPDF",onclick:function(){this.exportChart({type:"application/pdf"})}},{textKey:"downloadSVG",onclick:function(){this.exportChart({type:"image/svg+xml"})}}]}}};e.post=function(a,b){var c,d;d=m("form",{method:"post",action:a,enctype:"multipart/form-data"}, {display:"none"},i.body);for(c in b)m("input",{type:"hidden",name:c,value:b[c]},null,d);d.submit();j(d)};p(y.prototype,{getSVG:function(a){var b=this,c,d,x,g,f=k(b.options,a);if(!i.createElementNS)i.createElementNS=function(a,b){return i.createElement(b)};a=m("div",null,{position:"absolute",top:"-9999em",width:b.chartWidth+"px",height:b.chartHeight+"px"},i.body);d=b.renderTo.style.width;g=b.renderTo.style.height;d=f.exporting.sourceWidth||f.chart.width||/px$/.test(d)&&parseInt(d,10)||600;g=f.exporting.sourceHeight|| f.chart.height||/px$/.test(g)&&parseInt(g,10)||400;p(f.chart,{animation:!1,renderTo:a,forExport:!0,width:d,height:g});f.exporting.enabled=!1;f.series=[];r(b.series,function(a){x=k(a.options,{animation:!1,showCheckbox:!1,visible:a.visible});x.isInternal||f.series.push(x)});c=new e.Chart(f,b.callback);r(["xAxis","yAxis"],function(a){r(b[a],function(b,f){var d=c[a][f],e=b.getExtremes(),g=e.userMin,e=e.userMax;d&&(g!==void 0||e!==void 0)&&d.setExtremes(g,e,!0,!1)})});d=c.container.innerHTML;f=null;c.destroy(); j(a);d=d.replace(/zIndex="[^"]+"/g,"").replace(/isShadow="[^"]+"/g,"").replace(/symbolName="[^"]+"/g,"").replace(/jQuery[0-9]+="[^"]+"/g,"").replace(/url\([^#]+#/g,"url(#").replace(/<svg /,'<svg xmlns:xlink="http://www.w3.org/1999/xlink" ').replace(/ href=/g," xlink:href=").replace(/\n/," ").replace(/<\/svg>.*?$/,"</svg>").replace(/&nbsp;/g," ").replace(/&shy;/g,"­").replace(/<IMG /g,"<image ").replace(/height=([^" ]+)/g,'height="$1"').replace(/width=([^" ]+)/g,'width="$1"').replace(/hc-svg-href="([^"]+)">/g, 'xlink:href="$1"/>').replace(/id=([^" >]+)/g,'id="$1"').replace(/class=([^" >]+)/g,'class="$1"').replace(/ transform /g," ").replace(/:(path|rect)/g,"$1").replace(/style="([^"]+)"/g,function(a){return a.toLowerCase()});return d=d.replace(/(url\(#highcharts-[0-9]+)&quot;/g,"$1").replace(/&quot;/g,"'")},exportChart:function(a,b){var a=a||{},c=this.options.exporting,c=this.getSVG(k({chart:{borderRadius:0}},c.chartOptions,b,{exporting:{sourceWidth:a.sourceWidth||c.sourceWidth,sourceHeight:a.sourceHeight|| c.sourceHeight}})),a=k(this.options.exporting,a);e.post(a.url,{filename:a.filename||"chart",type:a.type,width:a.width||0,scale:a.scale||2,svg:c})},print:function(){var a=this,b=a.container,c=[],d=b.parentNode,e=i.body,g=e.childNodes;if(!a.isPrinting)a.isPrinting=!0,r(g,function(a,b){if(a.nodeType===1)c[b]=a.style.display,a.style.display="none"}),e.appendChild(b),z.focus(),z.print(),setTimeout(function(){d.appendChild(b);r(g,function(a,b){if(a.nodeType===1)a.style.display=c[b]});a.isPrinting=!1},1E3)}, contextMenu:function(a,b,c,d,e,g,f){var h=this,q=h.options.navigation,n=q.menuItemStyle,o=h.chartWidth,i=h.chartHeight,A="cache-"+a,l=h[A],k=C(e,g),u,j,s;if(!l)h[A]=l=m("div",{className:"highcharts-"+a},{position:"absolute",zIndex:1E3,padding:k+"px"},h.container),u=m("div",null,p({MozBoxShadow:"3px 3px 10px #888",WebkitBoxShadow:"3px 3px 10px #888",boxShadow:"3px 3px 10px #888"},q.menuStyle),l),j=function(){t(l,{display:"none"});f&&f.setState(0);h.openMenu=!1},v(l,"mouseleave",function(){s=setTimeout(j, 500)}),v(l,"mouseenter",function(){clearTimeout(s)}),r(b,function(a){if(a){var b=a.separator?m("hr",null,null,u):m("div",{onmouseover:function(){t(this,q.menuItemHoverStyle)},onmouseout:function(){t(this,n)},onclick:function(){j();a.onclick.apply(h,arguments)},innerHTML:a.text||h.options.lang[a.textKey]},p({cursor:"pointer"},n),u);h.exportDivElements.push(b)}}),h.exportDivElements.push(u,l),h.exportMenuWidth=l.offsetWidth,h.exportMenuHeight=l.offsetHeight;a={display:"block"};c+h.exportMenuWidth>o? a.right=o-c-e-k+"px":a.left=c-k+"px";d+g+h.exportMenuHeight>i&&f.alignOptions.verticalAlign!=="top"?a.bottom=i-d-k+"px":a.top=d+g-k+"px";t(l,a);h.openMenu=!0},addButton:function(a){var b=this,c=b.renderer,a=k(b.options.navigation.buttonOptions,a),d=a.onclick,i=a.menuItems,g,f,h={stroke:a.symbolStroke,fill:a.symbolFill},q=a.symbolSize||12;if(!b.btnCount)b.btnCount=0;b.btnCount++;if(!b.exportDivElements)b.exportDivElements=[],b.exportSVGElements=[];if(a.enabled!==!1){var n=a.theme,o=n.states,m=o&&o.hover, o=o&&o.select,j;delete n.states;d?j=function(){d.apply(b,arguments)}:i&&(j=function(){b.contextMenu("contextmenu",i,f.translateX,f.translateY,f.width,f.height,f);f.setState(2)});a.text&&a.symbol?n.paddingLeft=e.pick(n.paddingLeft,25):a.text||p(n,{width:a.width,height:a.height,padding:0});f=c.button(a.text,0,0,j,n,m,o).attr({title:b.options.lang[a._titleKey],"stroke-linecap":"round"});a.symbol&&(g=c.symbol(a.symbol,a.symbolX-q/2,a.symbolY-q/2,q,q).attr(p(h,{"stroke-width":a.symbolStrokeWidth||1,zIndex:1})).add(f)); f.add().align(p(a,{width:f.width,x:e.pick(a.x,w)}),!0,"spacingBox");w+=(f.width+a.buttonSpacing)*(a.align==="right"?-1:1);b.exportSVGElements.push(f,g)}},destroyExport:function(a){var a=a.target,b,c;for(b=0;b<a.exportSVGElements.length;b++)if(c=a.exportSVGElements[b])c.onclick=c.ontouchstart=null,a.exportSVGElements[b]=c.destroy();for(b=0;b<a.exportDivElements.length;b++)c=a.exportDivElements[b],B(c,"mouseleave"),a.exportDivElements[b]=c.onmouseout=c.onmouseover=c.ontouchstart=c.onclick=null,j(c)}}); E.menu=function(a,b,c,d){return["M",a,b+2.5,"L",a+c,b+2.5,"M",a,b+d/2+0.5,"L",a+c,b+d/2+0.5,"M",a,b+d-1.5,"L",a+c,b+d-1.5]};y.prototype.callbacks.push(function(a){var b,c=a.options.exporting,d=c.buttons;w=0;if(c.enabled!==!1){for(b in d)a.addButton(d[b]);v(a,"destroy",a.destroyExport)}})})(Highcharts);
REI-Systems/GovDashboard-Community
webapp/sites/all/libraries/highcharts/js/modules/exporting.js
JavaScript
gpl-3.0
7,095
define(function (require) { var a = require('a'); return { name: 'c', aName: a.name }; });
SesamTV/ChromecastCordovaExample
www/sesamcast/bower_components/requirejs/tests/anon/c.js
JavaScript
mit
119
ace.define('ace/snippets/ada', ['require', 'exports', 'module' ], function(require, exports, module) { exports.snippetText = ""; exports.scope = "ada"; });
KrishnaVamsiKV/Shark
zeppelin/zeppelin-web/vendor/scripts/ace/snippets/ada.js
JavaScript
apache-2.0
159
/*! Copyright (c) 2011 Piotr Rochala (http://rocha.la) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * Version: 1.0.0 * */ (function($) { jQuery.fn.extend({ slimScroll: function(options) { var defaults = { wheelStep : 20, width : 'auto', height : '250px', size : '7px', color: '#000', position : 'right', distance : '1px', start : 'top', opacity : .4, alwaysVisible : false, disableFadeOut: false, railVisible : false, railColor : '#333', railOpacity : '0.2', railClass : 'slimScrollRail', barClass : 'slimScrollBar', wrapperClass : 'slimScrollDiv', allowPageScroll : false, scroll : 0, touchScrollStep : 200 }; var o = $.extend(defaults, options); // do it for every element that matches selector this.each(function(){ var isOverPanel, isOverBar, isDragg, queueHide, touchDif, barHeight, percentScroll, lastScroll, divS = '<div></div>', minBarHeight = 30, releaseScroll = false; // used in event handlers and for better minification var me = $(this); // ensure we are not binding it again if (me.parent().hasClass('slimScrollDiv')) { // start from last bar position var offset = me.scrollTop(); // find bar and rail bar = me.parent().find('.slimScrollBar'); rail = me.parent().find('.slimScrollRail'); // check if we should scroll existing instance if (options) { if ('scrollTo' in options) { // jump to a static point offset = parseInt(o.scrollTo); } else if ('scrollBy' in options) { // jump by value pixels offset += parseInt(o.scrollBy); } // scroll content by the given offset scrollContent(offset, false, true); } return; } // optionally set height to the parent's height o.height = (o.height == 'auto') ? me.parent().innerHeight() : o.height; // wrap content var wrapper = $(divS) .addClass(o.wrapperClass) .css({ position: 'relative', overflow: 'hidden', width: o.width, height: o.height }); // update style for the div me.css({ overflow: 'hidden', width: o.width, height: o.height }); // create scrollbar rail var rail = $(divS) .addClass(o.railClass) .css({ width: o.size, height: '100%', position: 'absolute', top: 0, display: (o.alwaysVisible && o.railVisible) ? 'block' : 'none', 'border-radius': o.size, background: o.railColor, opacity: o.railOpacity, zIndex: 90 }); // create scrollbar var bar = $(divS) .addClass(o.barClass) .css({ background: o.color, width: o.size, position: 'absolute', top: 0, opacity: o.opacity, display: o.alwaysVisible ? 'block' : 'none', 'border-radius' : o.size, BorderRadius: o.size, MozBorderRadius: o.size, WebkitBorderRadius: o.size, zIndex: 99 }); // set position var posCss = (o.position == 'right') ? { right: o.distance } : { left: o.distance }; rail.css(posCss); bar.css(posCss); // wrap it me.wrap(wrapper); // append to parent div me.parent().append(bar); me.parent().append(rail); // make it draggable bar.draggable({ axis: 'y', containment: 'parent', start: function() { isDragg = true; }, stop: function() { isDragg = false; hideBar(); }, drag: function(e) { // scroll content scrollContent(0, $(this).position().top, false); } }); // on rail over rail.hover(function(){ showBar(); }, function(){ hideBar(); }); // on bar over bar.hover(function(){ isOverBar = true; }, function(){ isOverBar = false; }); // show on parent mouseover me.hover(function(){ isOverPanel = true; showBar(); hideBar(); }, function(){ isOverPanel = false; hideBar(); }); // support for mobile me.bind('touchstart', function(e,b){ if (e.originalEvent.touches.length) { // record where touch started touchDif = e.originalEvent.touches[0].pageY; } }); me.bind('touchmove', function(e){ // prevent scrolling the page e.originalEvent.preventDefault(); if (e.originalEvent.touches.length) { // see how far user swiped var diff = (touchDif - e.originalEvent.touches[0].pageY) / o.touchScrollStep; // scroll content scrollContent(diff, true); } }); var _onWheel = function(e) { // use mouse wheel only when mouse is over if (!isOverPanel) { return; } var e = e || window.event; var delta = 0; if (e.wheelDelta) { delta = -e.wheelDelta/120; } if (e.detail) { delta = e.detail / 3; } // scroll content scrollContent(delta, true); // stop window scroll if (e.preventDefault && !releaseScroll) { e.preventDefault(); } if (!releaseScroll) { e.returnValue = false; } } function scrollContent(y, isWheel, isJump) { var delta = y; if (isWheel) { // move bar with mouse wheel delta = parseInt(bar.css('top')) + y * parseInt(o.wheelStep) / 100 * bar.outerHeight(); // move bar, make sure it doesn't go out var maxTop = me.outerHeight() - bar.outerHeight(); delta = Math.min(Math.max(delta, 0), maxTop); // scroll the scrollbar bar.css({ top: delta + 'px' }); } // calculate actual scroll amount percentScroll = parseInt(bar.css('top')) / (me.outerHeight() - bar.outerHeight()); delta = percentScroll * (me[0].scrollHeight - me.outerHeight()); if (isJump) { delta = y; var offsetTop = delta / me[0].scrollHeight * me.outerHeight(); bar.css({ top: offsetTop + 'px' }); } // scroll content me.scrollTop(delta); // ensure bar is visible showBar(); // trigger hide when scroll is stopped hideBar(); } var attachWheel = function() { if (window.addEventListener) { this.addEventListener('DOMMouseScroll', _onWheel, false ); this.addEventListener('mousewheel', _onWheel, false ); } else { document.attachEvent("onmousewheel", _onWheel) } } // attach scroll events attachWheel(); function getBarHeight() { // calculate scrollbar height and make sure it is not too small barHeight = Math.max((me.outerHeight() / me[0].scrollHeight) * me.outerHeight(), minBarHeight); bar.css({ height: barHeight + 'px' }); } // set up initial height getBarHeight(); function showBar() { // recalculate bar height getBarHeight(); clearTimeout(queueHide); // when bar reached top or bottom if (percentScroll == ~~ percentScroll) { //release wheel releaseScroll = o.allowPageScroll; // publish approporiate event if (lastScroll != percentScroll) { var msg = (~~percentScroll == 0) ? 'top' : 'bottom'; me.trigger('slimscroll', msg); } } lastScroll = percentScroll; // show only when required if(barHeight >= me.outerHeight()) { //allow window scroll releaseScroll = true; return; } bar.stop(true,true).fadeIn('fast'); if (o.railVisible) { rail.stop(true,true).fadeIn('fast'); } } function hideBar() { // only hide when options allow it if (!o.alwaysVisible) { queueHide = setTimeout(function(){ if (!(o.disableFadeOut && isOverPanel) && !isOverBar && !isDragg) { bar.fadeOut('slow'); rail.fadeOut('slow'); } }, 1000); } } // check start position if (o.start == 'bottom') { // scroll content to bottom bar.css({ top: me.outerHeight() - bar.outerHeight() }); scrollContent(0, true); } else if (typeof o.start == 'object') { // scroll content scrollContent($(o.start).position().top, null, true); // make sure bar stays hidden if (!o.alwaysVisible) { bar.hide(); } } }); // maintain chainability return this; } }); jQuery.fn.extend({ slimscroll: jQuery.fn.slimScroll }); })(jQuery);
bootcdn/cdnjs
ajax/libs/jQuery-slimScroll/1.0.1/jquery.slimscroll.js
JavaScript
mit
9,965
define([ "../Data" ], function( Data ) { return new Data(); });
yuyang545262477/Resume
项目三jQueryMobile/bower_components/jquery/src/data/var/data_user.js
JavaScript
mit
66
/*! jQuery Once - v2.0.0-alpha.3 - 10/1/2014 - https://github.com/RobLoach/jquery-once * (c) 2014 Rob Loach <robloach@gmail.com> (http://github.com/robloach) * Licensed GPL-2.0, MIT */ !function(a){"use strict";"object"==typeof exports?a(require("jquery")):"function"==typeof define&&define.amd?define(["jquery"],a):a(jQuery)}(function(a){"use strict";var b={},c=0;a.fn.once=function(d,e){"string"!=typeof d&&(d in b||(b[d]=++c),e||(e=d),d=b[d]);var f="jquery-once-"+d,g=this.filter(function(){return a(this).data(f)!==!0}).data(f,!0);return a.isFunction(e)?g.each(e):g},a.fn.removeOnce=function(b,c){var d="jquery-once-"+b,e=this.filter(function(){return a(this).data(d)===!0}).removeData(d);return a.isFunction(c)?e.each(c):e}});
wil93/cdnjs
ajax/libs/jquery-once/2.0.0-alpha.3/jquery.once.min.js
JavaScript
mit
733
//>>built define("dojox/lang/functional/curry",["dijit","dojo","dojox","dojo/require!dojox/lang/functional/lambda"],function(_1,_2,_3){ _2.provide("dojox.lang.functional.curry"); _2.require("dojox.lang.functional.lambda"); (function(){ var df=_3.lang.functional,ap=Array.prototype; var _4=function(_5){ return function(){ var _6=_5.args.concat(ap.slice.call(arguments,0)); if(arguments.length+_5.args.length<_5.arity){ return _4({func:_5.func,arity:_5.arity,args:_6}); } return _5.func.apply(this,_6); }; }; _2.mixin(df,{curry:function(f,_7){ f=df.lambda(f); _7=typeof _7=="number"?_7:f.length; return _4({func:f,arity:_7,args:[]}); },arg:{},partial:function(f){ var a=arguments,l=a.length,_8=new Array(l-1),p=[],i=1,t; f=df.lambda(f); for(;i<l;++i){ t=a[i]; _8[i-1]=t; if(t===df.arg){ p.push(i-1); } } return function(){ var t=ap.slice.call(_8,0),i=0,l=p.length; for(;i<l;++i){ t[p[i]]=arguments[i]; } return f.apply(this,t); }; },mixer:function(f,_9){ f=df.lambda(f); return function(){ var t=new Array(_9.length),i=0,l=_9.length; for(;i<l;++i){ t[i]=arguments[_9[i]]; } return f.apply(this,t); }; },flip:function(f){ f=df.lambda(f); return function(){ var a=arguments,l=a.length-1,t=new Array(l+1),i=0; for(;i<=l;++i){ t[l-i]=a[i]; } return f.apply(this,t); }; }}); })(); });
studentsphere/ApiProxy
wso2am-1.7.0/repository/deployment/server/jaggeryapps/store/site/themes/fancy/templates/utils/dojo-release-1.8.3/dojox/lang/functional/curry.js
JavaScript
apache-2.0
1,279
YUI.add("lang/datatype-date-format_pl-PL",function(a){a.Intl.add("datatype-date-format","pl-PL",{"a":["niedz.","pon.","wt.","śr.","czw.","pt.","sob."],"A":["niedziela","poniedziałek","wtorek","środa","czwartek","piątek","sobota"],"b":["sty","lut","mar","kwi","maj","cze","lip","sie","wrz","paź","lis","gru"],"B":["stycznia","lutego","marca","kwietnia","maja","czerwca","lipca","sierpnia","września","października","listopada","grudnia"],"c":"%a, %d %b %Y %H:%M:%S %Z","p":["AM","PM"],"P":["am","pm"],"x":"%d-%m-%y","X":"%H:%M:%S"});},"@VERSION@");YUI.add("lang/datatype-date_pl-PL",function(a){},"@VERSION@",{use:["lang/datatype-date-format_pl-PL"]});YUI.add("lang/datatype_pl-PL",function(a){},"@VERSION@",{use:["lang/datatype-date_pl-PL"]});
blairvanderhoof/cdnjs
ajax/libs/yui/3.4.0pr2/datatype/lang/datatype_pl-PL.js
JavaScript
mit
750
/** * Test the side menu directive. For more test coverage of the side menu, * see the core Ionic sideMenu controller tests. */ describe('Ionic Angular Slide Box', function() { var el, compile, rootScope, timeout; beforeEach(module('ionic')); beforeEach(inject(function($compile, $rootScope, $timeout) { timeout = $timeout; rootScope = $rootScope; compile = $compile; el = $compile('<ion-slide-box>' + '<ion-slide>' + '<div class="box blue">' + '<h1>BLUE {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '<ion-slide>' + '<div class="box yellow">' + '<h1>YELLOW {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '<ion-slide>' + '<div class="box pink"><h1>PINK {{slideBox.slideIndex}}</h1></div>' + '</ion-slide>' + '</ion-slide-box>')($rootScope); })); it('should register with $ionicSlideBoxDelegate', inject(function($compile, $rootScope, $ionicSlideBoxDelegate) { var deregisterSpy = jasmine.createSpy('deregister'); spyOn($ionicSlideBoxDelegate, '_registerInstance').andCallFake(function() { return deregisterSpy; }); var el = $compile('<ion-slide-box delegate-handle="superHandle">')($rootScope.$new()); $rootScope.$apply(); expect($ionicSlideBoxDelegate._registerInstance) .toHaveBeenCalledWith(el.controller('ionSlideBox').__slider, 'superHandle', jasmine.any(Function)); expect(deregisterSpy).not.toHaveBeenCalled(); el.scope().$destroy(); expect(deregisterSpy).toHaveBeenCalled(); })); }); describe('ionSlideBox with active slide', function() { beforeEach(module('ionic')); it('Should set initial active slide', inject(function($ionicSlideBoxDelegate, $rootScope, $compile) { el = $compile('<ion-slide-box active-slide="2">' + '<ion-slide>' + '<div class="box blue">' + '<h1>BLUE {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '<ion-slide>' + '<div class="box yellow">' + '<h1>YELLOW {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '<ion-slide>' + '<div class="box pink"><h1>PINK {{slideBox.slideIndex}}</h1></div>' + '</ion-slide>' + '</ion-slide-box>')($rootScope.$new()); var scope = el.scope(); scope.$apply(); expect($ionicSlideBoxDelegate.currentIndex()).toBe(2); })); it('Should create and show pager unless told not to', inject(function($rootScope, $compile, $timeout) { el = $compile('<ion-slide-box>' + '<ion-slide>' + '<div class="box blue">' + '<h1>BLUE {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '<ion-slide>' + '<div class="box yellow">' + '<h1>YELLOW {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '</ion-slide-box>')($rootScope.$new()); var scope = el.scope(); scope.$apply(); expect(el.find('.slider-pager').length).toBe(1); expect(el.find('.slider-pager.hide').length).toBe(0); })); it('Should create and show pager unless told not to', inject(function($rootScope, $compile, $timeout) { el = $compile('<ion-slide-box show-pager="false">' + '<ion-slide>' + '<div class="box blue">' + '<h1>BLUE {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '<ion-slide>' + '<div class="box yellow">' + '<h1>YELLOW {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '</ion-slide-box>')($rootScope.$new()); var scope = el.scope(); scope.$apply(); expect(el.find('.slider-pager.hide').length).toBe(1); })); });
brant-hwang/ionic
test/unit/angular/directive/slideBox.unit.js
JavaScript
mit
3,724
// moment.js locale configuration // locale : uzbek (uz) // author : Sardor Muminov : https://github.com/muminoff (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.defineLocale('uz', { months : "январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"), monthsShort : "янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"), weekdays : "Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба".split("_"), weekdaysShort : "Якш_Душ_Сеш_Чор_Пай_Жум_Шан".split("_"), weekdaysMin : "Як_Ду_Се_Чо_Па_Жу_Ша".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "D MMMM YYYY, dddd LT" }, calendar : { sameDay : '[Бугун соат] LT [да]', nextDay : '[Эртага] LT [да]', nextWeek : 'dddd [куни соат] LT [да]', lastDay : '[Кеча соат] LT [да]', lastWeek : '[Утган] dddd [куни соат] LT [да]', sameElse : 'L' }, relativeTime : { future : "Якин %s ичида", past : "Бир неча %s олдин", s : "фурсат", m : "бир дакика", mm : "%d дакика", h : "бир соат", hh : "%d соат", d : "бир кун", dd : "%d кун", M : "бир ой", MM : "%d ой", y : "бир йил", yy : "%d йил" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 4th is the first week of the year. } }); }));
srcclr/open-core
spec/dummy/lib/javascripts/moment_locale/uz.js
JavaScript
gpl-2.0
2,304
"use strict"; var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"]; var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"]; var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"]; exports.__esModule = true; var _binding = require("../binding"); var _binding2 = _interopRequireDefault(_binding); var _babelTypes = require("babel-types"); var t = _interopRequireWildcard(_babelTypes); var renameVisitor = { ReferencedIdentifier: function ReferencedIdentifier(_ref, state) { var node = _ref.node; if (node.name === state.oldName) { node.name = state.newName; } }, Scope: function Scope(path, state) { if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) { path.skip(); } }, "AssignmentExpression|Declaration": function AssignmentExpressionDeclaration(path, state) { var ids = path.getOuterBindingIdentifiers(); for (var _name in ids) { if (_name === state.oldName) ids[_name].name = state.newName; } } }; var Renamer = (function () { function Renamer(binding, oldName, newName) { _classCallCheck(this, Renamer); this.newName = newName; this.oldName = oldName; this.binding = binding; } Renamer.prototype.maybeConvertFromExportDeclaration = function maybeConvertFromExportDeclaration(parentDeclar) { var exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath; if (!exportDeclar) return; // build specifiers that point back to this export declaration var isDefault = exportDeclar.isExportDefaultDeclaration(); if (isDefault && (parentDeclar.isFunctionDeclaration() || parentDeclar.isClassDeclaration()) && !parentDeclar.node.id) { // Ensure that default class and function exports have a name so they have a identifier to // reference from the export specifier list. parentDeclar.node.id = parentDeclar.scope.generateUidIdentifier("default"); } var bindingIdentifiers = parentDeclar.getOuterBindingIdentifiers(); var specifiers = []; for (var _name2 in bindingIdentifiers) { var localName = _name2 === this.oldName ? this.newName : _name2; var exportedName = isDefault ? "default" : _name2; specifiers.push(t.exportSpecifier(t.identifier(localName), t.identifier(exportedName))); } var aliasDeclar = t.exportNamedDeclaration(null, specifiers); // hoist to the top if it's a function if (parentDeclar.isFunctionDeclaration()) { aliasDeclar._blockHoist = 3; } exportDeclar.insertAfter(aliasDeclar); exportDeclar.replaceWith(parentDeclar.node); }; Renamer.prototype.maybeConvertFromClassFunctionDeclaration = function maybeConvertFromClassFunctionDeclaration(path) { return; // TODO // retain the `name` of a class/function declaration if (!path.isFunctionDeclaration() && !path.isClassDeclaration()) return; if (this.binding.kind !== "hoisted") return; path.node.id = t.identifier(this.oldName); path.node._blockHoist = 3; path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(t.identifier(this.newName), t.toExpression(path.node))])); }; Renamer.prototype.maybeConvertFromClassFunctionExpression = function maybeConvertFromClassFunctionExpression(path) { return; // TODO // retain the `name` of a class/function expression if (!path.isFunctionExpression() && !path.isClassExpression()) return; if (this.binding.kind !== "local") return; path.node.id = t.identifier(this.oldName); this.binding.scope.parent.push({ id: t.identifier(this.newName) }); path.replaceWith(t.assignmentExpression("=", t.identifier(this.newName), path.node)); }; Renamer.prototype.rename = function rename(block) { var binding = this.binding; var oldName = this.oldName; var newName = this.newName; var scope = binding.scope; var path = binding.path; var parentDeclar = path.find(function (path) { return path.isDeclaration() || path.isFunctionExpression(); }); if (parentDeclar) { this.maybeConvertFromExportDeclaration(parentDeclar); } scope.traverse(block || scope.block, renameVisitor, this); if (!block) { scope.removeOwnBinding(oldName); scope.bindings[newName] = binding; this.binding.identifier.name = newName; } if (binding.type === "hoisted") { // https://github.com/babel/babel/issues/2435 // todo: hoist and convert function to a let } if (parentDeclar) { this.maybeConvertFromClassFunctionDeclaration(parentDeclar); this.maybeConvertFromClassFunctionExpression(parentDeclar); } }; return Renamer; })(); exports["default"] = Renamer; module.exports = exports["default"];
emineKoc/WiseWit
wisewit_front_end/node_modules/babel-traverse/lib/scope/lib/renamer.js
JavaScript
gpl-3.0
4,874
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v4.1.1 * @link http://www.ag-grid.com/ * @license MIT */
Piicksarn/cdnjs
ajax/libs/ag-grid/4.1.1/lib/rendering/cellRenderers/iCellRenderer.js
JavaScript
mit
181
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; var ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin"); class ExternalsPlugin { constructor(type, externals) { this.type = type; this.externals = externals; } apply(compiler) { compiler.plugin("compile", (params) => { params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(this.type, this.externals)); }); } } module.exports = ExternalsPlugin;
puyanLiu/LPYFramework
前端练习/autoFramework/webpack-test/node_modules/webpack/lib/ExternalsPlugin.js
JavaScript
apache-2.0
527
// Validation errors messages for Parsley // Load this after Parsley Parsley.addMessages('sv', { dateiso: "Ange ett giltigt datum (ÅÅÅÅ-MM-DD)." });
krasnyuk/e-liquid-MS
wwwroot/assets/js/parsleyjs/dist/i18n/sv.extra.js
JavaScript
mit
156
/** * Tag-closer extension for CodeMirror. * * This extension adds an "autoCloseTags" option that can be set to * either true to get the default behavior, or an object to further * configure its behavior. * * These are supported options: * * `whenClosing` (default true) * Whether to autoclose when the '/' of a closing tag is typed. * `whenOpening` (default true) * Whether to autoclose the tag when the final '>' of an opening * tag is typed. * `dontCloseTags` (default is empty tags for HTML, none for XML) * An array of tag names that should not be autoclosed. * `indentTags` (default is block tags for HTML, none for XML) * An array of tag names that should, when opened, cause a * blank line to be added inside the tag, and the blank line and * closing line to be indented. * * See demos/closetag.html for a usage example. */ (function() { CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) { if (val && (old == CodeMirror.Init || !old)) { var map = {name: "autoCloseTags"}; if (typeof val != "object" || val.whenClosing) map["'/'"] = function(cm) { autoCloseTag(cm, '/'); }; if (typeof val != "object" || val.whenOpening) map["'>'"] = function(cm) { autoCloseTag(cm, '>'); }; cm.addKeyMap(map); } else if (!val && (old != CodeMirror.Init && old)) { cm.removeKeyMap("autoCloseTags"); } }); var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]; var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"]; function autoCloseTag(cm, ch) { var pos = cm.getCursor(), tok = cm.getTokenAt(pos); var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state; if (inner.mode.name != "xml") throw CodeMirror.Pass; var opt = cm.getOption("autoCloseTags"), html = inner.mode.configuration == "html"; var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose); var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent); if (ch == ">" && state.tagName) { var tagName = state.tagName; if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch); var lowerTagName = tagName.toLowerCase(); // Don't process the '>' at the end of an end-tag or self-closing tag if (tok.type == "tag" && state.type == "closeTag" || /\/\s*$/.test(tok.string) || dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1) throw CodeMirror.Pass; var doIndent = indentTags && indexOf(indentTags, lowerTagName) > -1; cm.replaceSelection(">" + (doIndent ? "\n\n" : "") + "</" + tagName + ">", doIndent ? {line: pos.line + 1, ch: 0} : {line: pos.line, ch: pos.ch + 1}); if (doIndent) { cm.indentLine(pos.line + 1); cm.indentLine(pos.line + 2); } return; } else if (ch == "/" && tok.type == "tag" && tok.string == "<") { var tagName = state.context && state.context.tagName; if (tagName) cm.replaceSelection("/" + tagName + ">", "end"); return; } throw CodeMirror.Pass; } function indexOf(collection, elt) { if (collection.indexOf) return collection.indexOf(elt); for (var i = 0, e = collection.length; i < e; ++i) if (collection[i] == elt) return i; return -1; } })();
d8ta/CMS_Skiclub
wp-content/plugins/ilightbox/scripts/codemirror/closetag.js
JavaScript
gpl-2.0
3,778
/*! * classie - class helper functions * from bonzo https://github.com/ded/bonzo * * classie.has( elem, 'my-class' ) -> true/false * classie.add( elem, 'my-new-class' ) * classie.remove( elem, 'my-unwanted-class' ) */ /*jshint browser: true, strict: true, undef: true */ ( function( window ) { 'use strict'; // class helper functions from bonzo https://github.com/ded/bonzo function classReg( className ) { return new RegExp("(^|\\s+)" + className + "(\\s+|$)"); } // classList support for class management // altho to be fair, the api sucks because it won't accept multiple classes at once var hasClass, addClass, removeClass; if ( 'classList' in document.documentElement ) { hasClass = function( elem, c ) { return elem.classList.contains( c ); }; addClass = function( elem, c ) { elem.classList.add( c ); }; removeClass = function( elem, c ) { elem.classList.remove( c ); }; } else { hasClass = function( elem, c ) { return classReg( c ).test( elem.className ); }; addClass = function( elem, c ) { if ( !hasClass( elem, c ) ) { elem.className = elem.className + ' ' + c; } }; removeClass = function( elem, c ) { elem.className = elem.className.replace( classReg( c ), ' ' ); }; } window.classie = { // full names hasClass: hasClass, addClass: addClass, removeClass: removeClass, // short names has: hasClass, add: addClass, remove: removeClass }; })( window );
joelpinheiro/joelpinheiro.github.io
itrading/js/classie.js
JavaScript
mit
1,457
var castSlice = require('./_castSlice'), charsEndIndex = require('./_charsEndIndex'), charsStartIndex = require('./_charsStartIndex'), stringToArray = require('./_stringToArray'), toString = require('./toString'); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (!string) { return string; } if (guard || chars === undefined) { return string.replace(reTrim, ''); } if (!(chars += '')) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } module.exports = trim;
lokiiart/upali-mobile
www/frontend/node_modules/browser-sync/node_modules/lodash/trim.js
JavaScript
gpl-3.0
1,388
function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { o.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new Error(sequenceContainsNoElements)); } else { o.onNext(value); o.onCompleted(); } }); }, source); }
alvarpoon/halodome
wp-content/themes/halodome/node_modules/bower/node_modules/insight/node_modules/inquirer/node_modules/rx/src/core/linq/observable/_singleordefault.js
JavaScript
gpl-2.0
657
define({ name: 'prototype' });
SesamTV/ChromecastCordovaExample
www/sesamcast/bower_components/requirejs/tests/hasOwnProperty/prototype.js
JavaScript
mit
34
/** * @license AngularJS v1.3.0-beta.11 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc module * @name ngCookies * @description * * # ngCookies * * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies. * * * <div doc-module-components="ngCookies"></div> * * See {@link ngCookies.$cookies `$cookies`} and * {@link ngCookies.$cookieStore `$cookieStore`} for usage. */ angular.module('ngCookies', ['ng']). /** * @ngdoc service * @name $cookies * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from this object, new * cookies are created/deleted at the end of current $eval. * The object's properties can only be strings. * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * function ExampleController($cookies) { * // Retrieving a cookie * var favoriteCookie = $cookies.myFavorite; * // Setting a cookie * $cookies.myFavorite = 'oatmeal'; * } * ``` */ factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) { var cookies = {}, lastCookies = {}, lastBrowserCookies, runEval = false, copy = angular.copy, isUndefined = angular.isUndefined; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); if (runEval) $rootScope.$apply(); } })(); runEval = true; //at the end of each eval, push cookies //TODO: this should happen before the "delayed" watches fire, because if some cookies are not // strings or browser refuses to store some cookies, we update the model in the push fn. $rootScope.$watch(push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were * stored. */ function push() { var name, value, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, undefined); } } //update all cookies updated in $cookies for(name in cookies) { value = cookies[name]; if (!angular.isString(value)) { value = '' + value; cookies[name] = value; } if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } } //verify what was actually stored if (updated){ updated = false; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } } } }]). /** * @ngdoc service * @name $cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * function ExampleController($cookieStore) { * // Put cookie * $cookieStore.put('myFavorite','oatmeal'); * // Get cookie * var favoriteCookie = $cookieStore.get('myFavorite'); * // Removing a cookie * $cookieStore.remove('myFavorite'); * } * ``` */ factory('$cookieStore', ['$cookies', function($cookies) { return { /** * @ngdoc method * @name $cookieStore#get * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { var value = $cookies[key]; return value ? angular.fromJson(value) : value; }, /** * @ngdoc method * @name $cookieStore#put * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $cookies[key] = angular.toJson(value); }, /** * @ngdoc method * @name $cookieStore#remove * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $cookies[key]; } }; }]); })(window, window.angular);
edugasser/testangular
static/angular/angular-cookies.js
JavaScript
mit
5,627
/* YUI 3.17.1 (build 0eb5a52) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("datasource-xmlschema",function(e,t){var n=function(){n.superclass.constructor.apply(this,arguments)};e.mix(n,{NS:"schema",NAME:"dataSourceXMLSchema",ATTRS:{schema:{}}}),e.extend(n,e.Plugin.Base,{initializer:function(e){this.doBefore("_defDataFn",this._beforeDefDataFn)},_beforeDefDataFn:function(t){var n=this.get("schema"),r=t.details[0],i=e.XML.parse(t.data.responseText)||t.data;return r.response=e.DataSchema.XML.apply.call(this,n,i)||{meta:{},results:i},this.get("host").fire("response",r),new e.Do.Halt("DataSourceXMLSchema plugin halted _defDataFn")}}),e.namespace("Plugin").DataSourceXMLSchema=n},"3.17.1",{requires:["datasource-local","plugin","datatype-xml","dataschema-xml"]});
stevermeister/cdnjs
ajax/libs/yui/3.17.1/datasource-xmlschema/datasource-xmlschema-min.js
JavaScript
mit
843
module.exports = function (args, opts) { if (!opts) opts = {}; var flags = { bools : {}, strings : {}, unknownFn: null }; if (typeof opts['unknown'] === 'function') { flags.unknownFn = opts['unknown']; } if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { flags.allBools = true; } else { [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { flags.bools[key] = true; }); } var aliases = {}; Object.keys(opts.alias || {}).forEach(function (key) { aliases[key] = [].concat(opts.alias[key]); aliases[key].forEach(function (x) { aliases[x] = [key].concat(aliases[key].filter(function (y) { return x !== y; })); }); }); [].concat(opts.string).filter(Boolean).forEach(function (key) { flags.strings[key] = true; if (aliases[key]) { flags.strings[aliases[key]] = true; } }); var defaults = opts['default'] || {}; var argv = { _ : [] }; Object.keys(flags.bools).forEach(function (key) { setArg(key, defaults[key] === undefined ? false : defaults[key]); }); var notFlags = []; if (args.indexOf('--') !== -1) { notFlags = args.slice(args.indexOf('--')+1); args = args.slice(0, args.indexOf('--')); } function argDefined(key, arg) { return (flags.allBools && /^--[^=]+$/.test(arg)) || flags.strings[key] || flags.bools[key] || aliases[key]; } function setArg (key, val, arg) { if (arg && flags.unknownFn && !argDefined(key, arg)) { if (flags.unknownFn(arg) === false) return; } var value = !flags.strings[key] && isNumber(val) ? Number(val) : val ; setKey(argv, key.split('.'), value); (aliases[key] || []).forEach(function (x) { setKey(argv, x.split('.'), value); }); } for (var i = 0; i < args.length; i++) { var arg = args[i]; if (/^--.+=/.test(arg)) { // Using [\s\S] instead of . because js doesn't support the // 'dotall' regex modifier. See: // http://stackoverflow.com/a/1068308/13216 var m = arg.match(/^--([^=]+)=([\s\S]*)$/); setArg(m[1], m[2], arg); } else if (/^--no-.+/.test(arg)) { var key = arg.match(/^--no-(.+)/)[1]; setArg(key, false, arg); } else if (/^--.+/.test(arg)) { var key = arg.match(/^--(.+)/)[1]; var next = args[i + 1]; if (next !== undefined && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !flags.bools[aliases[key]] : true)) { setArg(key, next, arg); i++; } else if (/^(true|false)$/.test(next)) { setArg(key, next === 'true', arg); i++; } else { setArg(key, flags.strings[key] ? '' : true, arg); } } else if (/^-[^-]+/.test(arg)) { var letters = arg.slice(1,-1).split(''); var broken = false; for (var j = 0; j < letters.length; j++) { var next = arg.slice(j+2); if (next === '-') { setArg(letters[j], next, arg) continue; } if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { setArg(letters[j], next, arg); broken = true; break; } if (letters[j+1] && letters[j+1].match(/\W/)) { setArg(letters[j], arg.slice(j+2), arg); broken = true; break; } else { setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); } } var key = arg.slice(-1)[0]; if (!broken && key !== '-') { if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) && !flags.bools[key] && (aliases[key] ? !flags.bools[aliases[key]] : true)) { setArg(key, args[i+1], arg); i++; } else if (args[i+1] && /true|false/.test(args[i+1])) { setArg(key, args[i+1] === 'true', arg); i++; } else { setArg(key, flags.strings[key] ? '' : true, arg); } } } else { if (!flags.unknownFn || flags.unknownFn(arg) !== false) { argv._.push( flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) ); } if (opts.stopEarly) { argv._.push.apply(argv._, args.slice(i + 1)); break; } } } Object.keys(defaults).forEach(function (key) { if (!hasKey(argv, key.split('.'))) { setKey(argv, key.split('.'), defaults[key]); (aliases[key] || []).forEach(function (x) { setKey(argv, x.split('.'), defaults[key]); }); } }); if (opts['--']) { argv['--'] = new Array(); notFlags.forEach(function(key) { argv['--'].push(key); }); } else { notFlags.forEach(function(key) { argv._.push(key); }); } return argv; }; function hasKey (obj, keys) { var o = obj; keys.slice(0,-1).forEach(function (key) { o = (o[key] || {}); }); var key = keys[keys.length - 1]; return key in o; } function setKey (obj, keys, value) { var o = obj; keys.slice(0,-1).forEach(function (key) { if (o[key] === undefined) o[key] = {}; o = o[key]; }); var key = keys[keys.length - 1]; if (o[key] === undefined || typeof o[key] === 'boolean') { o[key] = value; } else if (Array.isArray(o[key])) { o[key].push(value); } else { o[key] = [ o[key], value ]; } } function isNumber (x) { if (typeof x === 'number') return true; if (/^0x[0-9a-f]+$/i.test(x)) return true; return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); }
jtrueblood/pfl-2015
wp-content/themes/tif-child-bootstrap/node_modules/grunt-contrib-imagemin/node_modules/imagemin/node_modules/meow/node_modules/minimist/index.js
JavaScript
gpl-2.0
6,604
"use strict"; import assert from "assert"; import sinon from "sinon"; import testPlease from "../helpers/testPlease"; import { genericDouble } from "../helpers/doubles"; import * as JobsActionCreators from "../../../src/js/actions/JobsActionCreators"; import * as JobItemsActionCreators from "../../../src/js/actions/JobItemsActionCreators"; import * as ProductActionCreators from "../../../src/js/actions/ProductActionCreators"; import * as SharedActionCreators from "../../../src/js/actions/SharedActionCreators"; import * as JobsAPI from "../../../src/js/api/JobsAPI"; const toTest = [ { fn: "startLoading", type: "IS_LOADING", give: [], desc: "no data" }, { fn: "changeItem", type: "CHANGE_SINGLE_JOB_ITEM", give: [{item: "newItem"}], want: {item: "newItem"}, desc: "a new job item" }, { fn: "changeDetails", type: "CHANGE_SINGLE_JOB_DETAILS", give: [{details: "newDetails"}], want: {details: "newDetails"}, desc: "a new job details" }, { fn: "sortBy", type: "SORT_ONE", give: ["doctor"], want: "doctor", desc: "a sort string" }, { fn: "setCurrentY", type: "SET_CURRENT_Y", give: [158], want: 158, desc: "a new y position" }, { fn: "setTableHeight", type: "SET_TABLE_HEIGHT", give: [450], want: 450, desc: "a new table height" } ]; describe("SharedActionCreators", () => { describe(".externalSortBy", () => { let result, sortStub, jSpy, jiSpy, pSpy; before(() => { sortStub = sinon.stub(JobsAPI, "getSortedThings", (r, f, d) => { result = [r, f, d]; }); jSpy = sinon.spy(JobsActionCreators, "sortBy"); jiSpy = sinon.spy(JobItemsActionCreators, "sortBy"); pSpy = sinon.spy(ProductActionCreators, "sortBy"); }); after(() => { [sortStub, jSpy, jiSpy, pSpy].forEach(e => e.restore()); }); it("#calls the relevant sortBy action creator", () => { SharedActionCreators.externalSortBy("jobs", "dawg", false); assert(jSpy.called); assert.deepEqual(jSpy.firstCall.args, ["dawg"]); SharedActionCreators.externalSortBy("items", "caht", true); assert(jSpy.called); assert.deepEqual(jiSpy.firstCall.args, ["caht"]); SharedActionCreators.externalSortBy("products", "forks", false); assert(pSpy.called); assert.deepEqual(pSpy.firstCall.args, ["forks"]); }); it("#calls JobsAPI.getSortedThings with the endpoint," + " sort field and sort direction, defaulting to false", () => { const args1 = ["items", "chickens", false]; const args2 = ["jobs", "frogs", true]; SharedActionCreators.externalSortBy(args1[0], args1[1], args1[2]); assert.deepEqual(result, [args1[0], args1[1], !args1[2]]); SharedActionCreators.externalSortBy(args2[0], args2[1], args2[2]); assert.deepEqual(result, [args2[0], args2[1], !args2[2]]); }); }); describe("API callers", () => { let dubbel; let result = {}; before(() => { dubbel = genericDouble(JobsAPI, result); }); after(() => dubbel()); it(".getSelections calls JobsAPI.getSelections", () => { SharedActionCreators.getSelections(); assert.equal(result.getSelections, "calledWithNoArgs"); }); it(".getAllProducts calls JobsAPI.getAllProducts", () => { SharedActionCreators.getAllProducts(); assert.equal(result.getAllProducts, "calledWithNoArgs"); }); it(".getUserProfile calls JobsAPI.getUserProfile", () => { SharedActionCreators.getUserProfile(); assert.equal(result.getUserProfile, "calledWithNoArgs"); }); it(".saveDetails calls JobsAPI.saveDetails with an id and details", () => { SharedActionCreators.saveDetails(123, "hello hi"); assert.deepEqual(result.saveDetails, [123, "hello hi"]); }); it(".saveItem calls JobsAPI.saveItem with an id and item", () => { SharedActionCreators.saveItem(123, "hello hi"); assert.deepEqual(result.saveItem, [123, "hello hi"]); }); it(".createItem calls JobsAPI.createItem with an id and blueprint", () => { SharedActionCreators.createItem(123, {name: "hello hi"}); assert.deepEqual(result.createSingleJobItem, [123, {name: "hello hi"}]); }); it(".deleteItem calls JobsAPI.deleteItem with any arg and an immutable object", () => { SharedActionCreators.deleteItem(null, { get(thing) { return thing; } }); assert.deepEqual(result.deleteSingleItem, "item_id"); }); }); testPlease(toTest, SharedActionCreators); });
foundersandcoders/chandelier
test/src/actions/__SharedActionCreators.js
JavaScript
isc
4,345
import { t } from '../../core/localizer'; import { uiPane } from '../pane'; import { uiSectionPrivacy } from '../sections/privacy'; export function uiPanePreferences(context) { let preferencesPane = uiPane('preferences', context) .key(t('preferences.key')) .label(t.html('preferences.title')) .description(t.html('preferences.description')) .iconName('fas-user-cog') .sections([ uiSectionPrivacy(context) ]); return preferencesPane; }
openstreetmap/iD
modules/ui/panes/preferences.js
JavaScript
isc
475
import SpvChoicePage from "components/views/GetStartedPage/SpvChoicePage"; import { render } from "test-utils.js"; import { screen } from "@testing-library/react"; import user from "@testing-library/user-event"; import * as sel from "selectors"; import * as da from "actions/DaemonActions"; let mockIsTestNet; let mockToggleSpv; const selectors = sel; const daemonActions = da; beforeEach(() => { mockIsTestNet = selectors.isTestNet = jest.fn(() => false); mockToggleSpv = daemonActions.toggleSpv = jest.fn(() => () => {}); selectors.stakeTransactions = jest.fn(() => []); }); test("render SPV choice page", () => { render(<SpvChoicePage />); expect(screen.getByTestId("getstarted-pagebody").className).not.toMatch( /testnetBody/ ); const spvLabel = screen.getByText(/simple payment verification \(spv\)/i); expect(spvLabel).toBeInTheDocument(); expect(spvLabel.nextSibling.textContent).toMatchInlineSnapshot( '"Select how Decrediton should connect to the Decred network. You can change this in the application settings later. For more in-depth information about SPV and how it works, you can go here"' ); const enableSpvLabel = screen.getByText(/enable spv/i); expect(enableSpvLabel).toBeInTheDocument(); expect(enableSpvLabel.nextSibling.textContent).toMatchInlineSnapshot( "\"SPV will allow your wallets to be restored and used much more quickly. This speed comes at cost, with blocks not being fully verified. It's 'less secure' but very unlikely that there will be any problems.\"" ); user.click(enableSpvLabel); expect(mockToggleSpv).toHaveBeenCalledWith(true); mockToggleSpv.mockClear(); const disableSpvLabel = screen.getByText(/disable spv/i); expect(disableSpvLabel).toBeInTheDocument(); expect(disableSpvLabel.nextSibling.textContent).toMatchInlineSnapshot( '"This will use the regular Decred daemon and fully verify blocks. This will take longer but is fully secure. Any block or mined transaction can be fully trusted."' ); user.click(disableSpvLabel); expect(mockToggleSpv).toHaveBeenCalledWith(false); }); test("render SPV choice page in testnet mode", () => { mockIsTestNet = selectors.isTestNet = jest.fn(() => true); render(<SpvChoicePage />); expect(mockIsTestNet).toHaveBeenCalled(); expect(screen.getByTestId("getstarted-pagebody").className).toMatch( /testnetBody/ ); });
decred/decrediton
test/unit/components/views/GetStaredPage/SpvChoicePage.spec.js
JavaScript
isc
2,383
const webpack = require('webpack'); const path = require('path'); const {debugMode, pkg} = require('./env'); const cwd = process.cwd(); const srcPath = path.join(cwd, pkg.src.js); const distPath = path.join(cwd, pkg.dist.js); // Babel loaders const babelLoaders = (function () { const presets = ['react', 'es2015', 'stage-0']; const plugins = ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties']; const presetsQuery = presets.map(p => `presets[]=${p}`).join(','); const pluginsQuery = plugins.map(p => `plugins[]=${p}`).join(','); const query = [presetsQuery, pluginsQuery].join(','); return [`babel?${query}`]; }()); if (debugMode) { // Only hot load on debug mode babelLoaders.push('webpack-module-hot-accept'); babelLoaders.unshift('react-hot'); } const plugins = (function () { const dedup = new webpack.optimize.DedupePlugin(); const occurenceOrder = new webpack.optimize.OccurenceOrderPlugin(); const noErrors = new webpack.NoErrorsPlugin(); const hotModuleReplacement = new webpack.HotModuleReplacementPlugin(); const uglifyJS = new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, output: { comments: false }, mangle: false, sourcemap: false, }); const define = new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify(debugMode ? 'debug' : 'production'), }, '__PRODUCTION_MODE': JSON.stringify(!debugMode), '__DEBUG_MODE': JSON.stringify(debugMode), '__APP_NAME': JSON.stringify(pkg.name), '__APP_VERSION': JSON.stringify(pkg.version), }); if (debugMode) { return [occurenceOrder, hotModuleReplacement, noErrors]; } return [dedup, occurenceOrder, uglifyJS, define]; }()); const webpackSettings = { debug: debugMode, plugins, entry: { app: [ path.join(srcPath, './app.jsx'), ], }, output: { path: distPath, publicPath: '/js/', filename: '[name].js', }, resolve: { extensions: ['', '.js', '.jsx'], }, module: { loaders: [{ test: /\.jsx$/, exclude: /(?:node_modules|bower_components)/, include: [srcPath], loaders: babelLoaders, }], }, }; // debug mode settings if (debugMode) { webpackSettings.devtool = 'inline-sourcemap'; for (const key in webpackSettings.entry) { if (webpackSettings.entry.hasOwnProperty(key)) { webpackSettings.entry[key].unshift('webpack-hot-middleware/client'); webpackSettings.entry[key].unshift('webpack/hot/dev-server'); } } } module.exports = webpackSettings;
rolldever/react-starter-kit
config/webpack.js
JavaScript
isc
2,584
/* global PropertyFactory, extendPrototype, RenderableElement, BaseElement, FrameElement */ function AudioElement(data, globalData, comp) { this.initFrame(); this.initRenderable(); this.assetData = globalData.getAssetData(data.refId); this.initBaseData(data, globalData, comp); this._isPlaying = false; this._canPlay = false; var assetPath = this.globalData.getAssetsPath(this.assetData); this.audio = this.globalData.audioController.createAudio(assetPath); this._currentTime = 0; this.globalData.audioController.addAudio(this); this.tm = data.tm ? PropertyFactory.getProp(this, data.tm, 0, globalData.frameRate, this) : { _placeholder: true }; } AudioElement.prototype.prepareFrame = function (num) { this.prepareRenderableFrame(num, true); this.prepareProperties(num, true); if (!this.tm._placeholder) { var timeRemapped = this.tm.v; this._currentTime = timeRemapped; } else { this._currentTime = num / this.data.sr; } }; extendPrototype([RenderableElement, BaseElement, FrameElement], AudioElement); AudioElement.prototype.renderFrame = function () { if (this.isInRange && this._canPlay) { if (!this._isPlaying) { this.audio.play(); this.audio.seek(this._currentTime / this.globalData.frameRate); this._isPlaying = true; } else if (!this.audio.playing() || Math.abs(this._currentTime / this.globalData.frameRate - this.audio.seek()) > 0.1 ) { this.audio.seek(this._currentTime / this.globalData.frameRate); } } }; AudioElement.prototype.show = function () { // this.audio.play() }; AudioElement.prototype.hide = function () { this.audio.pause(); this._isPlaying = false; }; AudioElement.prototype.pause = function () { this.audio.pause(); this._isPlaying = false; this._canPlay = false; }; AudioElement.prototype.resume = function () { this._canPlay = true; }; AudioElement.prototype.setRate = function (rateValue) { this.audio.rate(rateValue); }; AudioElement.prototype.volume = function (volumeValue) { this.audio.volume(volumeValue); }; AudioElement.prototype.getBaseElement = function () { return null; }; AudioElement.prototype.destroy = function () { }; AudioElement.prototype.sourceRectAtTime = function () { }; AudioElement.prototype.initExpressions = function () { };
damienmortini/dlib
node_modules/lottie-web/player/js/elements/AudioElement.js
JavaScript
isc
2,390
/* Module handles message posting. */ 'use strict'; const AWS = require('aws-sdk'), Joi = require('joi'), config = require('../environments/config'), dynamodb = new AWS.DynamoDB({ region: 'us-east-1' }); /* Joi validation object */ const postMessageValidate = Joi.object().keys({ UserName: Joi .string() .not('') .default('Anonymous') .description('Name of user who posts the message.'), MessageBody: Joi .string() .not('') .description('The message content.'), Extra: Joi .string() .default('') .description('Any additional info about the message.') }).requiredKeys( 'UserName', 'MessageBody' ); /* params for postMessage */ const postMessageParams = (query) => { let curTime = (new Date()).getTime(); let item = { 'UserName': { S: query.UserName }, 'TimeStamp': { S: curTime.toString() }, 'MessageBody': { S: query.MessageBody } }; if(query.Extra && query.Extra !== ''){ item['Extra'] = { S: query.Extra }; } return { TableName: config.dynamodb, Item: item }; }; /* Handler for postMessage */ const postMessage = (req, resp) => { let query = req.query, params = postMessageParams(query); dynamodb.putItem(params, (err, data) => { if(err){ console.log('ERR: ' + err); resp({Error: err}).code(400); } else { resp({mete: {status: "Success"}, data: data}).code(200); } }); }; module.exports = { postMessageParams, config: { handler: postMessage, description: 'Allow user to post a message.', tags: ['api'], validate: { query: postMessageValidate } } };
luzou0526/msg-proj
lib/postMessage.js
JavaScript
isc
1,863
define(["config"], function(Config) { "use strict"; var width = 100, height = 27, padding = 6; function drawScore(ctx, score, screenWidth) { ctx.beginPath(); ctx.strokeStyle = "#fff"; ctx.lineWidth = 1; ctx.moveTo(screenWidth - 100, 0); ctx.lineTo(screenWidth - 100, height); ctx.lineTo(screenWidth, height); ctx.stroke(); ctx.closePath(); ctx.beginPath(); ctx.fillStyle = Config.text.score.color; ctx.textBaseline = "top"; ctx.font = Config.text.score.font; ctx.fillText("Score: " + score, screenWidth - width + padding, padding); ctx.closePath(); } return drawScore; });
booleangate/snakejs
app/game-objects/draw-helpers/score.js
JavaScript
isc
619
import { connect } from 'react-redux'; import get from 'lodash.get'; import { QuestionView } from '../../components/Questions'; import { openEditQuestionForm, deleteQuestion } from '../../actions'; const mapStateToProps = (state, ownProps) => { const { isAdmin, groups } = state.profile; return { question: get(state.questions.questions, ownProps.id, {}), groups, isAdmin, }; }; const Question = connect(mapStateToProps, { editQuestion: openEditQuestionForm, deleteQuestion, })(QuestionView); export { Question };
klpdotorg/tada-frontend
app/containers/Questions/Question.js
JavaScript
isc
540
'use strict'; const chalk = require('chalk'); function log(type) { if (arguments.length < 2) { return; } const msgs = Array.from(arguments).slice(1); let log = ['[rise]']; switch(type) { case 'error': log.push(chalk.red('ERRO')); break; case 'warn': log.push(chalk.yellow('WARN')); break; case 'info': log.push(chalk.blue('INFO')); break; case 'debug': log.push(chalk.gray('DEBU')); break; } log = log.concat(msgs.map(function(m) { if (m instanceof Error) { return m.stack; } return m; })); log.push("\n"); const msg = log.join(' '); if (process.env.NODE_ENV === 'test') { // Don't log in tests. return; } if (type === 'error') { process.stderr.write(msg); } else { process.stdout.write(msg); } } module.exports = { error(/* msg */) { log.apply(this, ['error'].concat(Array.from(arguments))); }, warn(/* msg */) { log.apply(this, ['warn'].concat(Array.from(arguments))); }, info(/* msg */) { log.apply(this, ['info'].concat(Array.from(arguments))); }, debug(/* msg */) { log.apply(this, ['debug'].concat(Array.from(arguments))); } };
rise-cloud/rise
rise-cli/src/utils/log.js
JavaScript
isc
1,207
// I used to use `util.format()` which was massive, then I switched to // format-util, although when using rollup I discovered that the index.js // just exported `require('util').format`, and then had the below contents // in another file. at any rate all I want is this function: function format(fmt) { fmt = String(fmt); // this is closer to util.format() behavior var re = /(%?)(%([jds]))/g , args = Array.prototype.slice.call(arguments, 1); if(args.length) { if(Array.isArray(args[0])) args = args[0]; fmt = fmt.replace(re, function(match, escaped, ptn, flag) { var arg = args.shift(); switch(flag) { case 's': arg = '' + arg; break; case 'd': arg = Number(arg); break; case 'j': arg = JSON.stringify(arg); break; } if(!escaped) { return arg; } args.unshift(arg); return match; }) } // arguments remain after formatting if(args.length) { fmt += ' ' + args.join(' '); } // update escaped %% values fmt = fmt.replace(/%{2,2}/g, '%'); return '' + fmt; } export default format;
sprjr/react-localize
src/util.format.js
JavaScript
isc
1,165
var plates = [{img:"centralamerica-inset.gif", start: 1900, end: 2020, left: -10, top: 500}, {img:"mexicanrevolution1910.png", start: 1910, end: 1920, top: 190, left: -30}, {img:"zapatista1994.png", start: 1994, end: 1994, top: 190, left: -30}, {img:"fococuba1959.gif", start: 1959, end: 1965, top: 105, left: 650} ];
dbp/latinamerica
plates.js
JavaScript
isc
366
'use strict'; const Async = require('async'); const Boom = require('boom'); const DataRetrievalRouter = require('./DataRetrievalRouter'); const DENY = 0; const PERMIT = 1; const UNDETERMINED = 3; const internals = {}; /** * Evaluate a single Policy of PolicySet * **/ internals.evaluatePolicy = (item, dataRetriever, callback) => { if (!item) { return callback(Boom.badImplementation('RBAC configuration error: null item')); } if (!dataRetriever) { return callback(Boom.badImplementation('RBAC configuration error: null data retriever')); } if (!(dataRetriever instanceof DataRetrievalRouter)) { return callback(Boom.badImplementation('RBAC configuration error: invalid data retriever')); } if (!item.apply) { // Default combinatory algorithm item.apply = 'permit-overrides'; } if (!(item.apply instanceof Function)) { if (!internals.combineAlg[item.apply]) { return callback(Boom.badImplementation('RBAC error: combinatory algorithm does not exist: ' + item.apply)); } item.apply = internals.combineAlg[item.apply]; } internals.evaluateTarget(item.target, dataRetriever, (err, applies) => { if (err) { return callback(err); } if (!applies) { return callback(null, UNDETERMINED); } // Policy set if (item.policies) { return item.apply(item.policies, dataRetriever, internals.evaluatePolicy, callback); } // Policy if (item.rules) { return item.apply(item.rules, dataRetriever, internals.evaluateRule, callback); } // Rule internals.evaluateRule(item, dataRetriever, callback); }); }; const VALID_EFFECTS = ['permit', 'deny']; /** * Evaluate a single rule. * * { * 'target': [...], * 'effect': PERMIT, DENY * } **/ internals.evaluateRule = (rule, dataRetriever, callback) => { if (!rule) { return callback(Boom.badImplementation('RBAC rule is missing')); } if (!rule.effect) { return callback(Boom.badImplementation('RBAC rule effect is missing')); } if (VALID_EFFECTS.indexOf(rule.effect) === -1) { return callback(Boom.badImplementation('RBAC rule effect is invalid. Use one of', VALID_EFFECTS)); } internals.evaluateTarget(rule.target, dataRetriever, (err, applies) => { if (err) { return callback(err); } if (!applies) { return callback(null, UNDETERMINED); } switch (rule.effect) { case 'permit': case PERMIT: return callback(null, PERMIT); case 'deny': case DENY: return callback(null, DENY); default: return callback(Boom.badImplementation('RBAC rule error: invalid effect ' + rule.effect)); } }); }; /** * Evaluate a target * The objects in the target array are matched with OR condition. The keys in an object are matched with AND condition. * * [ * { * 'credentials:username': 'francisco', // AND * 'credentials:group': 'admin' * }, // OR * { * 'credentials:username': 'francisco', // AND * 'credentials:group': 'writer' * } * ] * * This target applies to francisco, if he is in the group admin or writer. * **/ internals.evaluateTarget = (target, dataRetriever, callback) => { if (!target) { // Applies by default, when no target is defined return callback(null, true); } if (target instanceof Array) { if (!target.length) { return callback(Boom.badImplementation('RBAC target error: invalid format. The array in target should have at least one element.')); } } else { // Allow defining a single element in target without using an array target = [target]; } const tasks = []; for (const index in target) { const element = target[index]; tasks.push(internals.evaluateTargetElement(dataRetriever, element)); } Async.parallel(tasks, (err, result) => { if (err) { return callback(err); } // At least one should apply (OR) const applicables = result.filter((value) => value); callback(null, applicables.length > 0); }); }; internals.evaluateTargetElement = (dataRetriever, element) => { return (callback) => { const promises = Object.keys(element).map((key) => internals.evaluateTargetElementKey(dataRetriever, element, key)); Promise.all(promises) .then((results) => { // Should all apply (AND) const nonApplicable = results.filter((value) => !value); callback(null, nonApplicable.length === 0); }) .catch((err) => callback(err)) }; }; /** * If target is defined as: * { field: "credentials:user" } * then this definition should be replaced by * a value from dataRetriever for matching. * * @param dataRetriever * @param definedValue * @returns Promise **/ internals.getTargetValue = (dataRetriever, definedValue) => { if(typeof definedValue === "object") { if (definedValue.field) { return dataRetriever.get(definedValue.field); } } return Promise.resolve(definedValue); }; internals.evaluateTargetElementKey = (dataRetriever, element, key) => { return Promise.all([ internals.getTargetValue(dataRetriever, element[key]), dataRetriever.get(key) ]) .then((results) => { const targetValue = results[0]; const value = results[1]; return internals._targetApplies(targetValue, value); }); }; /** * If target has more than one value, all of them should match **/ internals._targetApplies = (targets, values) => { if (!Array.isArray(targets)) { targets = [targets]; } if (!Array.isArray(values)) { values = [values]; } // Should match all // So: continue looping unless one doesn't for (const index in targets) { const target = targets[index]; const matches = values.filter((value) => { if (target instanceof RegExp) { return target.test(value); } return value === target; }); if (matches.length === 0) { return false; } } // All targets are matched return true; }; /** * Combinator algorithms: * * - permit-overrides - If at least one permit is evaluated, then permit * - deny-overrides - If at least one deny is evaluated, then deny * - only-one-applicable - * - first-applicable - Only evaluate the first applicable rule **/ internals.combineAlg = {}; internals.combineAlg['permit-overrides'] = (items, information, fn, callback) => { if (!items || items.length === 0) { return callback(null, UNDETERMINED); } const tasks = []; for (let i = 0; i < items.length; ++i) { tasks.push(fn.bind(null, items[i], information)); } Async.parallel(tasks, (err, results) => { if (err) { return callback(err); } for (let i = 0; i < results.length; ++i) { if (results[i] === PERMIT) { return callback(null, PERMIT); } } callback(null, DENY); }); }; internals.combineAlg['deny-overrides'] = (items, information, fn, callback) => { if (!items || items.length === 0) { return callback(null, UNDETERMINED); } const tasks = []; for (let i = 0; i < items.length; ++i) { tasks.push(fn.bind(null, items[i], information)); } Async.parallel(tasks, (err, results) => { if (err) { return callback(err); } for (let i = 0; i < results.length; ++i) { if (results[i] === DENY) { return callback(null, DENY); } } callback(null, PERMIT); }); }; exports = module.exports = { evaluatePolicy: internals.evaluatePolicy, evaluateRule: internals.evaluateRule, evaluateTarget: internals.evaluateTarget, DENY: DENY, PERMIT: PERMIT, UNDETERMINED: UNDETERMINED, DataRetrievalRouter: DataRetrievalRouter };
franciscogouveia/rbac-core
lib/index.js
JavaScript
isc
8,340
'use strict'; var lab = require('lab'), describe = lab.describe, it = lab.it, demand = require('must'), bole = require('bole'), fs = require('fs'), LogOutput = require('../lib/output-logfile'), mkdirp = require('mkdirp'), path = require('path'), rimraf = require('rimraf') ; var tmpdir = './tmp'; describe('logfile output', function() { var output; var mockopts = { path: path.join(tmpdir, 'foo.log'), name: 'test-1' }; lab.before(function(done) { mkdirp(tmpdir, done); }); it('demands an options object', function(done) { function shouldThrow() { return new LogOutput(); } shouldThrow.must.throw(/options/); done(); }); it('demands a name object', function(done) { function shouldThrow() { return new LogOutput({ path: '../tmp'}); } shouldThrow.must.throw(/name/); done(); }); it('can be constructed', function(done) { output = new LogOutput(mockopts); output.must.be.an.object(); output.must.be.instanceof(LogOutput); done(); }); it('creates a logger client', function(done) { output.must.have.property('client'); output.client.must.be.truthy(); output.client.must.have.property('info'); output.client.info.must.be.a.function(); done(); }); it('emits to its logfile', function(done) { output.write({ test: 'yes'}, function() { fs.readFile(mockopts.path, function(err, data) { data = data.toString('utf8'); var first = data.split('\n')[0]; var written = JSON.parse(first); written.must.be.an.object(); written.level.must.equal('info'); written.name.must.equal('test-1'); written.test.must.equal('yes'); done(); }); }); }); it('the path option is optional', function(done) { var consoleOut = new LogOutput({ name: 'test-2' }); output.write({ test: 'yes'}, function() { done(); }); }); it('has a useful toString() implementation', function(done) { var str = output.toString(); str.must.equal('[ logfile @ tmp/foo.log ]'); done(); }); lab.after(function(done) { rimraf(tmpdir, done); }); });
mehrdadrafiee/numbat-collector
test/test-03.logfile.js
JavaScript
isc
2,495
import {normalize} from '../lib/themeUtils' const unused = new Set() const freeze = Object.freeze const createAccessors = (object, path = '') => { for (const key of Object.keys(object)) { const value = object[key] const keyPath = path ? `${path}.${key}` : key if (value && typeof value === 'object') { createAccessors(value, keyPath) } else if (typeof value === 'string') { unused.add(keyPath) Object.defineProperty(object, key, { get () { unused.delete(keyPath) return `%${keyPath}${value ? '#' + value : ''}%` } }) } } freeze.call(Object, object) } const theme = {} // normalize() caches the result, so this is just a cache key Object.freeze = obj => obj // Stub out so accessors can be created const normalized = normalize({theme}) createAccessors(normalized) Object.freeze = freeze export default theme export {normalized as normalizedTheme} export function checkThemeUsage (t) { t.deepEqual(unused, new Set(), 'All theme properties should be accessed at least once') }
novemberborn/kathryn
test/_instrumentedTheme.js
JavaScript
isc
1,067
/** * Icon based on ion-ios-paper-outline */ import React, { Component } from 'react'; class Many extends Component { render() { return ( <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="512px" height="512px" viewBox="0 0 512 512" enable-background="new 0 0 512 512"> <g> <path d="M112,64v16v320h16V80h304v337.143c0,8.205-6.652,14.857-14.857,14.857H94.857C86.652,432,80,425.348,80,417.143V128h16v-16 H64v305.143C64,434.157,77.843,448,94.857,448h322.285C434.157,448,448,434.157,448,417.143V64H112z"/> <rect x="160" y="112" width="128" height="16"/> <rect x="160" y="192" width="240" height="16"/> <rect x="160" y="272" width="192" height="16"/> <rect x="160" y="352" width="240" height="16"/> </g> </svg> ) } } export default Many;
ThinkingInReact/ThinkingInReact.xyz
src/common/components/icons/features/Many.js
JavaScript
isc
880
describe('getting elements by class name', function () { var chai = require('chai'), assert = chai.assert; var DomParser = require('../index.js'), parser = new DomParser(); context('Dom', function(){ it('spaces and case', function(){ var html = '<div class="examples">\n' + ' <span>text</span>\n' + ' <div class="example"></div>\n' + ' <span>text</span>\n' + ' <div class=" example"></div>\n' + ' <div class=" example"></div>\n' + ' <span>text</span>\n' + ' <div class="exAmple "></div>\n' + ' <span>text</span>\n' + ' <div class=" asd example ss"></div>\n' + ' <div class=" sd examples"></div>\n' + ' <span>text</span>\n' + ' <div class=" example as">' + ' </div>\n' + '</div>'; var dom = parser.parseFromString(html), elements = dom.getElementsByClassName('example'); assert.equal(elements.length, 5, 'html contains 5 elements with className "example"'); }); it('nested elements', function(){ var html = '<div class="examples">\n' + ' <span>text</span>\n' + ' <div class="example"></div>\n' + ' <span>text</span>\n' + ' <div class=" example"></div>\n' + ' <div class=" example"></div>\n' + ' <span>text</span>\n' + ' <div class="example "></div>\n' + ' <span>text</span>\n' + ' <div class=" asd example ss"></div>\n' + ' <div class=" sd examples"></div>\n' + ' <span>text</span>\n' + ' <div class=" example as nasted">' + ' <div class="examples">\n' + ' <span>text</span>\n' + ' <div class="example"></div>\n' + ' <span>text</span>\n' + ' <div class=" example"></div>\n' + ' <div class=" example"></div>\n' + ' <span>text</span>\n' + ' <div class="example "></div>\n' + ' <span>text</span>\n' + ' <div class=" asd example ss"></div>\n' + ' <div class=" sd examples"></div>\n' + ' <span>text</span>\n' + ' <div class=" example as nasted">' + ' </div>\n' + ' </div>' + ' </div>\n' + '</div>'; var dom = parser.parseFromString(html), elements = dom.getElementsByClassName('example'); assert.equal(elements.length, 12, 'html contains 12 elements with className "example"'); }); }); context('Node', function(){ it('root: spaces and case', function(){ var html = '<div class="examples root">\n' + ' <span>text</span>\n' + ' <div class="example"></div>\n' + ' <span>text</span>\n' + ' <div class=" example"></div>\n' + ' <div class=" example"></div>\n' + ' <span>text</span>\n' + ' <div class="exAmple "></div>\n' + ' <span>text</span>\n' + ' <div class=" asd example ss"></div>\n' + ' <div class=" sd examples"></div>\n' + ' <span>text</span>\n' + ' <div class=" example as">' + ' </div>\n' + '</div>'; var dom = parser.parseFromString(html), root = dom.getElementsByClassName('root')[0], elements = root.getElementsByClassName('example'); assert.equal(elements.length, 5, 'root element contains 5 elements with className "example"'); }); it('nested elements', function(){ var html = '<div class=" root examples">\n' + ' <span>text</span>\n' + ' <div class="example"></div>\n' + ' <span>text</span>\n' + ' <div class=" example"></div>\n' + ' <div class=" example"></div>\n' + ' <span>text</span>\n' + ' <div class="example "></div>\n' + ' <span>text</span>\n' + ' <div class=" asd example ss"></div>\n' + ' <div class=" sd examples"></div>\n' + ' <span>text</span>\n' + ' <div class=" example as nasted">' + ' <div class="examples">\n' + ' <span>text</span>\n' + ' <div class="example"></div>\n' + ' <span>text</span>\n' + ' <div class=" example"></div>\n' + ' <div class=" example"></div>\n' + ' <span>text</span>\n' + ' <div class="example "></div>\n' + ' <span>text</span>\n' + ' <div class=" asd example ss"></div>\n' + ' <div class=" sd examples"></div>\n' + ' <span>text</span>\n' + ' <div class=" example as nasted">' + ' </div>\n' + ' </div>' + ' </div>\n' + '</div>'; var dom = parser.parseFromString(html), root = dom.getElementsByClassName('root')[0], elements = root.getElementsByClassName('example'); assert.equal(elements.length, 12, 'root element contains 12 elements with className "example"'); }); }); });
ershov-konst/dom-parser
test/getElementsByClassName.js
JavaScript
isc
5,085
import { event as d3_event, select as d3_select } from 'd3-selection'; import { svgIcon } from '../svg/icon'; import { t, textDirection } from '../util/locale'; import { tooltip } from '../util/tooltip'; import { geoExtent } from '../geo'; import { modeBrowse } from '../modes/browse'; import { uiDisclosure } from './disclosure'; import { uiSettingsCustomData } from './settings/custom_data'; import { uiTooltipHtml } from './tooltipHtml'; import { uiCmd } from './cmd'; import { utilQsString, utilStringQs } from '../util'; export function uiMapData(context) { var key = t('map_data.key'); var osmDataToggleKey = uiCmd('⌥' + t('area_fill.wireframe.key')); var features = context.features().keys(); var layers = context.layers(); var fills = ['wireframe', 'partial', 'full']; var dateRanges = ['start_date', 'end_date']; var settingsCustomData = uiSettingsCustomData(context) .on('change', customChanged); var _pane = d3_select(null); var _fillSelected = context.storage('area-fill') || 'partial'; var _dataLayerContainer = d3_select(null); var _photoOverlayContainer = d3_select(null); var _fillList = d3_select(null); var _rangeList = d3_select(null); var _featureList = d3_select(null); var _visualDiffList = d3_select(null); var _QAList = d3_select(null); function showsFeature(d) { return context.features().enabled(d); } function autoHiddenFeature(d) { if (d.type === 'kr_error') return context.errors().autoHidden(d); return context.features().autoHidden(d); } function clickFeature(d) { context.features().toggle(d); update(); } function showsQA(d) { var QAKeys = [d]; var QALayers = layers.all().filter(function(obj) { return QAKeys.indexOf(obj.id) !== -1; }); var data = QALayers.filter(function(obj) { return obj.layer.supported(); }); function layerSupported(d) { return d.layer && d.layer.supported(); } function layerEnabled(d) { return layerSupported(d) && d.layer.enabled(); } return layerEnabled(data[0]); } function showsFill(d) { return _fillSelected === d; } function showsDateRanges(d) { return true; } function setFill(d) { fills.forEach(function(opt) { context.surface().classed('fill-' + opt, Boolean(opt === d)); }); _fillSelected = d; context.storage('area-fill', d); if (d !== 'wireframe') { context.storage('area-fill-toggle', d); } update(); } function setDateRanges(d) { // var setValue = parseInt(this.value.replace(/-/g,''),10) var setValue; if (typeof this.value === 'string' && this.value.length > 0){ var val = this.value.replace(/-/g, ''); setValue = parseInt(val, 10); } setValue = isNaN(setValue) ? (d === 'start_date' ? -Infinity : Infinity) : setValue; context.features().dateRange = context.features().dateRange || [-Infinity,Infinity]; context.features().dateRange[d === 'start_date' ? 0 : 1] = setValue; context.features().reset() context.dispatchChange(); update(); } function toggleHighlightEdited() { d3_event.preventDefault(); var surface = context.surface(); surface.classed('highlight-edited', !surface.classed('highlight-edited')); updateVisualDiffList(); context.map().pan([0,0]); // trigger a redraw } function showsLayer(which) { var layer = layers.layer(which); if (layer) { return layer.enabled(); } return false; } function setLayer(which, enabled) { // Don't allow layer changes while drawing - #6584 var mode = context.mode(); if (mode && /^draw/.test(mode.id)) return; var layer = layers.layer(which); if (layer) { layer.enabled(enabled); if (!enabled && (which === 'osm' || which === 'notes')) { context.enter(modeBrowse(context)); } update(); } } function toggleLayer(which) { setLayer(which, !showsLayer(which)); } function drawPhotoItems(selection) { var photoKeys = context.photos().overlayLayerIDs(); var photoLayers = layers.all().filter(function(obj) { return photoKeys.indexOf(obj.id) !== -1; }); var data = photoLayers.filter(function(obj) { return obj.layer.supported(); }); function layerSupported(d) { return d.layer && d.layer.supported(); } function layerEnabled(d) { return layerSupported(d) && d.layer.enabled(); } var ul = selection .selectAll('.layer-list-photos') .data([0]); ul = ul.enter() .append('ul') .attr('class', 'layer-list layer-list-photos') .merge(ul); var li = ul.selectAll('.list-item-photos') .data(data); li.exit() .remove(); var liEnter = li.enter() .append('li') .attr('class', function(d) { var classes = 'list-item-photos list-item-' + d.id; if (d.id === 'mapillary-signs' || d.id === 'mapillary-map-features') { classes += ' indented'; } return classes; }); var labelEnter = liEnter .append('label') .each(function(d) { var titleID; if (d.id === 'mapillary-signs') titleID = 'mapillary.signs.tooltip'; else if (d.id === 'mapillary') titleID = 'mapillary_images.tooltip'; else if (d.id === 'openstreetcam') titleID = 'openstreetcam_images.tooltip'; else titleID = d.id.replace(/-/g, '_') + '.tooltip'; d3_select(this) .call(tooltip() .title(t(titleID)) .placement('top') ); }); labelEnter .append('input') .attr('type', 'checkbox') .on('change', function(d) { toggleLayer(d.id); }); labelEnter .append('span') .text(function(d) { var id = d.id; if (id === 'mapillary-signs') id = 'photo_overlays.traffic_signs'; return t(id.replace(/-/g, '_') + '.title'); }); labelEnter .filter(function(d) { return d.id === 'mapillary-map-features'; }) .append('a') .attr('class', 'request-data-link') .attr('target', '_blank') .attr('tabindex', -1) .call(svgIcon('#iD-icon-out-link', 'inline')) .attr('href', 'https://mapillary.github.io/mapillary_solutions/data-request') .append('span') .text(t('mapillary_map_features.request_data')); // Update li .merge(liEnter) .classed('active', layerEnabled) .selectAll('input') .property('checked', layerEnabled); } function drawPhotoTypeItems(selection) { var data = context.photos().allPhotoTypes(); function typeEnabled(d) { return context.photos().showsPhotoType(d); } var ul = selection .selectAll('.layer-list-photo-types') .data(context.photos().shouldFilterByPhotoType() ? [0] : []); ul.exit() .remove(); ul = ul.enter() .append('ul') .attr('class', 'layer-list layer-list-photo-types') .merge(ul); var li = ul.selectAll('.list-item-photo-types') .data(data); li.exit() .remove(); var liEnter = li.enter() .append('li') .attr('class', function(d) { return 'list-item-photo-types list-item-' + d; }); var labelEnter = liEnter .append('label') .each(function(d) { d3_select(this) .call(tooltip() .title(t('photo_overlays.photo_type.' + d + '.tooltip')) .placement('top') ); }); labelEnter .append('input') .attr('type', 'checkbox') .on('change', function(d) { context.photos().togglePhotoType(d); update(); }); labelEnter .append('span') .text(function(d) { return t('photo_overlays.photo_type.' + d + '.title'); }); // Update li .merge(liEnter) .classed('active', typeEnabled) .selectAll('input') .property('checked', typeEnabled); } function drawOsmItems(selection) { var osmKeys = ['osm', 'notes']; var osmLayers = layers.all().filter(function(obj) { return osmKeys.indexOf(obj.id) !== -1; }); var ul = selection .selectAll('.layer-list-osm') .data([0]); ul = ul.enter() .append('ul') .attr('class', 'layer-list layer-list-osm') .merge(ul); var li = ul.selectAll('.list-item') .data(osmLayers); li.exit() .remove(); var liEnter = li.enter() .append('li') .attr('class', function(d) { return 'list-item list-item-' + d.id; }); var labelEnter = liEnter .append('label') .each(function(d) { if (d.id === 'osm') { d3_select(this) .call(tooltip() .html(true) .title(uiTooltipHtml(t('map_data.layers.' + d.id + '.tooltip'), osmDataToggleKey)) .placement('bottom') ); } else { d3_select(this) .call(tooltip() .title(t('map_data.layers.' + d.id + '.tooltip')) .placement('bottom') ); } }); labelEnter .append('input') .attr('type', 'checkbox') .on('change', function(d) { toggleLayer(d.id); }); labelEnter .append('span') .text(function(d) { return t('map_data.layers.' + d.id + '.title'); }); // Update li .merge(liEnter) .classed('active', function (d) { return d.layer.enabled(); }) .selectAll('input') .property('checked', function (d) { return d.layer.enabled(); }); } function drawQAItems(selection) { var qaKeys = ['keepRight', 'improveOSM']; var qaLayers = layers.all().filter(function(obj) { return qaKeys.indexOf(obj.id) !== -1; }); var ul = selection .selectAll('.layer-list-qa') .data([0]); ul = ul.enter() .append('ul') .attr('class', 'layer-list layer-list-qa') .merge(ul); var li = ul.selectAll('.list-item') .data(qaLayers); li.exit() .remove(); var liEnter = li.enter() .append('li') .attr('class', function(d) { return 'list-item list-item-' + d.id; }); var labelEnter = liEnter .append('label') .each(function(d) { d3_select(this) .call(tooltip() .title(t('map_data.layers.' + d.id + '.tooltip')) .placement('bottom') ); }); labelEnter .append('input') .attr('type', 'checkbox') .on('change', function(d) { toggleLayer(d.id); }); labelEnter .append('span') .text(function(d) { return t('map_data.layers.' + d.id + '.title'); }); // Update li .merge(liEnter) .classed('active', function (d) { return d.layer.enabled(); }) .selectAll('input') .property('checked', function (d) { return d.layer.enabled(); }); } // Beta feature - sample vector layers to support Detroit Mapping Challenge // https://github.com/osmus/detroit-mapping-challenge function drawVectorItems(selection) { var dataLayer = layers.layer('data'); var vtData = [ { name: 'Detroit Neighborhoods/Parks', src: 'neighborhoods-parks', tooltip: 'Neighborhood boundaries and parks as compiled by City of Detroit in concert with community groups.', template: 'https://{switch:a,b,c,d}.tiles.mapbox.com/v4/jonahadkins.cjksmur6x34562qp9iv1u3ksf-54hev,jonahadkins.cjksmqxdx33jj2wp90xd9x2md-4e5y2/{z}/{x}/{y}.vector.pbf?access_token=pk.eyJ1Ijoiam9uYWhhZGtpbnMiLCJhIjoiRlVVVkx3VSJ9.9sdVEK_B_VkEXPjssU5MqA' }, { name: 'Detroit Composite POIs', src: 'composite-poi', tooltip: 'Fire Inspections, Business Licenses, and other public location data collated from the City of Detroit.', template: 'https://{switch:a,b,c,d}.tiles.mapbox.com/v4/jonahadkins.cjksmm6a02sli31myxhsr7zf3-2sw8h/{z}/{x}/{y}.vector.pbf?access_token=pk.eyJ1Ijoiam9uYWhhZGtpbnMiLCJhIjoiRlVVVkx3VSJ9.9sdVEK_B_VkEXPjssU5MqA' }, { name: 'Detroit All-The-Places POIs', src: 'alltheplaces-poi', tooltip: 'Public domain business location data created by web scrapers.', template: 'https://{switch:a,b,c,d}.tiles.mapbox.com/v4/jonahadkins.cjksmswgk340g2vo06p1w9w0j-8fjjc/{z}/{x}/{y}.vector.pbf?access_token=pk.eyJ1Ijoiam9uYWhhZGtpbnMiLCJhIjoiRlVVVkx3VSJ9.9sdVEK_B_VkEXPjssU5MqA' } ]; // Only show this if the map is around Detroit.. var detroit = geoExtent([-83.5, 42.1], [-82.8, 42.5]); var showVectorItems = (context.map().zoom() > 9 && detroit.contains(context.map().center())); var container = selection.selectAll('.vectortile-container') .data(showVectorItems ? [0] : []); container.exit() .remove(); var containerEnter = container.enter() .append('div') .attr('class', 'vectortile-container'); containerEnter .append('h4') .attr('class', 'vectortile-header') .text('Detroit Vector Tiles (Beta)'); containerEnter .append('ul') .attr('class', 'layer-list layer-list-vectortile'); containerEnter .append('div') .attr('class', 'vectortile-footer') .append('a') .attr('target', '_blank') .attr('tabindex', -1) .call(svgIcon('#iD-icon-out-link', 'inline')) .attr('href', 'https://github.com/osmus/detroit-mapping-challenge') .append('span') .text('About these layers'); container = container .merge(containerEnter); var ul = container.selectAll('.layer-list-vectortile'); var li = ul.selectAll('.list-item') .data(vtData); li.exit() .remove(); var liEnter = li.enter() .append('li') .attr('class', function(d) { return 'list-item list-item-' + d.src; }); var labelEnter = liEnter .append('label') .each(function(d) { d3_select(this).call( tooltip().title(d.tooltip).placement('top') ); }); labelEnter .append('input') .attr('type', 'radio') .attr('name', 'vectortile') .on('change', selectVTLayer); labelEnter .append('span') .text(function(d) { return d.name; }); // Update li .merge(liEnter) .classed('active', isVTLayerSelected) .selectAll('input') .property('checked', isVTLayerSelected); function isVTLayerSelected(d) { return dataLayer && dataLayer.template() === d.template; } function selectVTLayer(d) { context.storage('settings-custom-data-url', d.template); if (dataLayer) { dataLayer.template(d.template, d.src); dataLayer.enabled(true); } } } function drawCustomDataItems(selection) { var dataLayer = layers.layer('data'); var hasData = dataLayer && dataLayer.hasData(); var showsData = hasData && dataLayer.enabled(); var ul = selection .selectAll('.layer-list-data') .data(dataLayer ? [0] : []); // Exit ul.exit() .remove(); // Enter var ulEnter = ul.enter() .append('ul') .attr('class', 'layer-list layer-list-data'); var liEnter = ulEnter .append('li') .attr('class', 'list-item-data'); var labelEnter = liEnter .append('label') .call(tooltip() .title(t('map_data.layers.custom.tooltip')) .placement('top') ); labelEnter .append('input') .attr('type', 'checkbox') .on('change', function() { toggleLayer('data'); }); labelEnter .append('span') .text(t('map_data.layers.custom.title')); liEnter .append('button') .call(tooltip() .title(t('settings.custom_data.tooltip')) .placement((textDirection === 'rtl') ? 'right' : 'left') ) .on('click', editCustom) .call(svgIcon('#iD-icon-more')); liEnter .append('button') .call(tooltip() .title(t('map_data.layers.custom.zoom')) .placement((textDirection === 'rtl') ? 'right' : 'left') ) .on('click', function() { d3_event.preventDefault(); d3_event.stopPropagation(); dataLayer.fitZoom(); }) .call(svgIcon('#iD-icon-search')); // Update ul = ul .merge(ulEnter); ul.selectAll('.list-item-data') .classed('active', showsData) .selectAll('label') .classed('deemphasize', !hasData) .selectAll('input') .property('disabled', !hasData) .property('checked', showsData); } function editCustom() { d3_event.preventDefault(); context.container() .call(settingsCustomData); } function customChanged(d) { var dataLayer = layers.layer('data'); if (d && d.url) { dataLayer.url(d.url); } else if (d && d.fileList) { dataLayer.fileList(d.fileList); } } function drawListItems(selection, data, type, name, change, active) { var items = selection.selectAll('li') .data(data); // Exit items.exit() .remove(); // Enter var enter = items.enter() .append('li') .call(tooltip() .html(true) .title(function(d) { var tip = t(name + '.' + d + '.tooltip'); var key = (d === 'wireframe' ? t('area_fill.wireframe.key') : null); if (d === 'highlight_edits') key = t('map_data.highlight_edits.key'); if ((name === 'feature' || name === 'keepRight') && autoHiddenFeature(d)) { var msg = showsLayer('osm') ? t('map_data.autohidden') : t('map_data.osmhidden'); tip += '<div>' + msg + '</div>'; } return uiTooltipHtml(tip, key); }) .placement('top') ); var label = enter .append('label'); label .append('input') .attr('type', type) .attr('name', name) .on('change', change); label .append('span') .text(function(d) { return t(name + '.' + d + '.description'); }); // Update items = items .merge(enter); items .classed('active', active) .selectAll('input') .property('checked', active) .property('indeterminate', function(d) { return ((name === 'feature' || name === 'keepRight') && autoHiddenFeature(d)); }); } function renderDataLayers(selection) { var container = selection.selectAll('.data-layer-container') .data([0]); _dataLayerContainer = container.enter() .append('div') .attr('class', 'data-layer-container') .merge(container); updateDataLayers(); } function renderPhotoOverlays(selection) { var container = selection.selectAll('.photo-overlay-container') .data([0]); _photoOverlayContainer = container.enter() .append('div') .attr('class', 'photo-overlay-container') .merge(container); updatePhotoOverlays(); } function renderStyleOptions(selection) { var container = selection.selectAll('.layer-fill-list') .data([0]); _fillList = container.enter() .append('ul') .attr('class', 'layer-list layer-fill-list') .merge(container); updateFillList(); var container2 = selection.selectAll('.layer-visual-diff-list') .data([0]); _visualDiffList = container2.enter() .append('ul') .attr('class', 'layer-list layer-visual-diff-list') .merge(container2); updateVisualDiffList(); } function renderDateRanges(selection) { var container = selection.selectAll('.layer-date-range') .data([0]); _rangeList = container.enter() .append('ul') .attr('class', 'layer-list layer-date-range') .merge(container); updateDateRanges(); } function renderFeatureList(selection) { var container = selection.selectAll('.layer-feature-list-container') .data([0]); var containerEnter = container.enter() .append('div') .attr('class', 'layer-feature-list-container'); containerEnter .append('ul') .attr('class', 'layer-list layer-feature-list'); var footer = containerEnter .append('div') .attr('class', 'feature-list-links section-footer'); footer .append('a') .attr('class', 'feature-list-link') .attr('href', '#') .text(t('issues.enable_all')) .on('click', function() { context.features().enableAll(); }); footer .append('a') .attr('class', 'feature-list-link') .attr('href', '#') .text(t('issues.disable_all')) .on('click', function() { context.features().disableAll(); }); // Update container = container .merge(containerEnter); _featureList = container.selectAll('.layer-feature-list'); updateFeatureList(); } function updatePhotoOverlays() { _photoOverlayContainer .call(drawPhotoItems) .call(drawPhotoTypeItems); } function updateDataLayers() { _dataLayerContainer .call(drawOsmItems) .call(drawQAItems) .call(drawCustomDataItems) .call(drawVectorItems); // Beta - Detroit mapping challenge } function updateFillList() { _fillList .call(drawListItems, fills, 'radio', 'area_fill', setFill, showsFill); } function updateDateRanges() { _rangeList .call(drawListItems, dateRanges, 'text', 'date_ranges', setDateRanges, showsDateRanges); if (context.features().dateRange){ _rangeList.selectAll('input').each(function(d, i){ d3_select(this).attr("value",context.features().dateRange[i]) }); } } function updateVisualDiffList() { _visualDiffList .call(drawListItems, ['highlight_edits'], 'checkbox', 'visual_diff', toggleHighlightEdited, function() { return context.surface().classed('highlight-edited'); }); } function updateFeatureList() { _featureList .call(drawListItems, features, 'checkbox', 'feature', clickFeature, showsFeature); } function update() { if (!_pane.select('.disclosure-wrap-data_layers').classed('hide')) { updateDataLayers(); } if (!_pane.select('.disclosure-wrap-photo_overlays').classed('hide')) { updatePhotoOverlays(); } if (!_pane.select('.disclosure-wrap-fill_area').classed('hide')) { updateFillList(); } if (!_pane.select('.disclosure-wrap-map_features').classed('hide')) { updateFeatureList(); } _QAList .call(drawListItems, ['keep-right'], 'checkbox', 'QA', function(d) { toggleLayer(d); }, showsQA); if (!window.mocha) { var q = utilStringQs(window.location.hash.substring(1)); const disable_features = (q.disable_features ? q.disable_features.replace(/;/g, ',').split(',') : []); if (context.features().dateRange && disable_features.includes('date_range')){ q.start_date = context.features().dateRange[0]; q.end_date = context.features().dateRange[1]; } window.location.replace('#' + utilQsString(q, true)); } } function toggleWireframe() { if (d3_event) { d3_event.preventDefault(); d3_event.stopPropagation(); } if (_fillSelected === 'wireframe') { _fillSelected = context.storage('area-fill-toggle') || 'partial'; } else { _fillSelected = 'wireframe'; } setFill(_fillSelected); context.map().pan([0,0]); // trigger a redraw } var paneTooltip = tooltip() .placement((textDirection === 'rtl') ? 'right' : 'left') .html(true) .title(uiTooltipHtml(t('map_data.description'), key)); function hidePane() { context.ui().togglePanes(); } uiMapData.togglePane = function() { if (d3_event) d3_event.preventDefault(); paneTooltip.hide(); context.ui().togglePanes(!_pane.classed('shown') ? _pane : undefined); }; uiMapData.renderToggleButton = function(selection) { selection .append('button') .on('click', uiMapData.togglePane) .call(svgIcon('#iD-icon-data', 'light')) .call(paneTooltip); }; uiMapData.renderPane = function(selection) { _pane = selection .append('div') .attr('class', 'fillL map-pane map-data-pane hide') .attr('pane', 'map-data'); var heading = _pane .append('div') .attr('class', 'pane-heading'); heading .append('h2') .text(t('map_data.title')); heading .append('button') .on('click', hidePane) .call(svgIcon('#iD-icon-close')); var content = _pane .append('div') .attr('class', 'pane-content'); // data layers content .append('div') .attr('class', 'map-data-data-layers') .call(uiDisclosure(context, 'data_layers', true) .title(t('map_data.data_layers')) .content(renderDataLayers) ); // photo overlays content .append('div') .attr('class', 'map-data-photo-overlays') .attr('style', 'display:none') .call(uiDisclosure(context, 'photo_overlays', false) .title(t('photo_overlays.title')) .content(renderPhotoOverlays) ); // area fills content .append('div') .attr('class', 'map-data-area-fills') .call(uiDisclosure(context, 'fill_area', false) .title(t('map_data.style_options')) .content(renderStyleOptions) ); // Date Ranges content .append('div') .attr('class', 'map-data-date-ranges') .call(uiDisclosure(context, 'date_ranges', false) .title(t('map_data.date_ranges')) .content(renderDateRanges) ); // feature filters content .append('div') .attr('class', 'map-data-feature-filters') .call(uiDisclosure(context, 'map_features', false) .title(t('map_data.map_features')) .content(renderFeatureList) ); // add listeners context.features() .on('change.map_data-update', update); update(); setFill(_fillSelected); context.keybinding() .on(key, uiMapData.togglePane) .on(t('area_fill.wireframe.key'), toggleWireframe) .on(osmDataToggleKey, function() { d3_event.preventDefault(); d3_event.stopPropagation(); toggleLayer('osm'); }) .on(t('map_data.highlight_edits.key'), toggleHighlightEdited); }; return uiMapData; }
kartta-labs/iD
modules/ui/map_data.js
JavaScript
isc
30,342
// A database of labels define(['util', 'label'], function(Util, Label) { var Labels = function() { this.getURL = '/annotate.database.getlabels'; this.addURL = '/annotate.database.addlabel'; this.saveLabelURL = '/annotate.database.savelabel'; this.removeLabelURL = '/annotate.database.removelabel'; this.database = []; this.databaseByColor = {}; this.databaseByName = {}; this.databaseById = {}; this.labelsLoadedCallback = []; this.labelAddedCallbacks = []; }; Labels.prototype.getById = function(i) { return this.databaseById[i]; } Labels.prototype.getByColor = function(color) { return this.databaseByColor[color]; } Labels.prototype.getByName = function(name) { return this.databaseByName[name]; } Labels.prototype.registerLabelsLoadedCallback = function(callback) { this.labelsLoadedCallback.push( callback ); } Labels.prototype.registerLabelAddedCallback = function(callback) { this.labelAddedCallbacks.push( callback ); } Labels.prototype.load = function() { Util.load_data(this.getURL, this.onLoaded.bind(this) ); } Labels.prototype.onLoaded = function(res) { var compressed = new Uint8Array(res.response); var inflate = new Zlib.Inflate(compressed); var binary = inflate.decompress(); var binaryconverter = new TextDecoder('utf-8'); var decompressed = binaryconverter.decode(binary); var data = JSON.parse( window.atob(decompressed) ); // decode the string this.database = data; var colorKey = ''; var label = null; for(var i=0; i<this.database.length; i++) { label = this.database[i]; colorKey = label.r + '' + label.b + '' + label.g; this.databaseByColor[colorKey] = label; this.databaseById[label.index] = label; this.databaseByName[label.name] = label; } this.trigerLoadedCallback(); } Labels.prototype.add = function(name, r, g, b, imageId) { //Util.load_data(this.getURL, this.onLoaded.bind(this) ); var label = new Label(name, r, g, b); label.index = this.getavailableindex(); var colorKey = label.r + '' + label.b + '' + label.g; this.database.push( label ); this.databaseById[label.index] = label; this.databaseByName[label.name] = label; this.databaseByColor[colorKey] = label; console.log(this.database); //this.triggerLabelAdded(name); this.saveLabel(label); return label; } Labels.prototype.trigerLoadedCallback = function() { for(var i=0; i<this.labelsLoadedCallback.length; i++) { this.labelsLoadedCallback[i](); } } Labels.prototype.triggerLabelAdded = function(name) { for(var i=0; i<this.labelAddedCallbacks.length; i++) { //this.labelAddedCallbacks[i](name); } } Labels.prototype.update = function(name, newname, r, g, b, imageId) { console.log('Labels.prototype.update'); var label = this.databaseByName[name]; if (label == null) { return; } delete this.databaseByName[name]; label.name = newname; label.r = r; label.g = g; label.b = b; console.log(this); this.databaseByName[newname] = label; this.triggerLabelAdded(); //Util.load_data(this.getURL, this.onLoaded.bind(this) ); this.saveLabel(label, imageId); console.log(label); console.log(this); } Labels.prototype.remove = function(name) { console.log('labels.Labels.prototype.remove'); var label = this.databaseByName[name]; if (label == null) { return false; } console.log('ref: ' + label.references); console.log(label); if (label.references != null && label.references.length > 0) return false; var colorKey = label.r + '' + label.b + '' + label.g; delete this.databaseByName[label.name]; delete this.databaseByColor[colorKey]; delete this.databaseById[label.index]; //this.triggerLabelAdded(); this.removeLabel(label.index); this.load(); return true; } Labels.prototype.saveLabel = function(label, imageId) { console.log('labels.Labels.prototype.saveLabel'); console.log(label); input = JSON.stringify(label); Util.send_data(this.saveLabelURL, 'id=' + this.id + ';label='+input); } Labels.prototype.removeLabel = function(labelId) { console.log('labels.Labels.prototype.removeLabel labelId: ' + labelId); Util.send_data(this.removeLabelURL, 'id=' + labelId); } Labels.prototype.getavailableindex = function() { var index = 0; for(var i=0; i<this.database.length; i++) { if (this.database[i].index == index) index++; } console.log(this.database[0]); console.log('available index: ' + index); return index; } return Labels; });
fegonda/icon_demo
code/web/resources/js/modules/labels.js
JavaScript
mit
4,755
(function(){ var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x){ window.requestAnimation = window[vendors[x] + 'RequestAnimationFrame']; window.cancelAnimtionFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimtionFrame']; } if(!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element){ var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function(){ callback(currTime + timeToCall) ;},timeToCall); lastTime = currTime + timeToCall; return id; }; if(!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id){ clearTimeout(id); } })();
fakefish/Must-Jump
common.js
JavaScript
mit
863
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _glob = require('glob'); var _glob2 = _interopRequireDefault(_glob); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var FlowRequireManager = function () { function FlowRequireManager(settings) { _classCallCheck(this, FlowRequireManager); this.settings = settings || {}; this.items = {}; } _createClass(FlowRequireManager, [{ key: 'log', value: function log(level, message) { if (this.settings.logger) { this.settings.logger.log(level, message); } } }, { key: 'getAbsolutePath', value: function getAbsolutePath(relative) { return _path2.default.normalize(_path2.default.join(process.cwd(), relative)); } }, { key: 'addItem', value: function addItem(item) { this.log('info', 'Adding item ' + item.name); this.items[item.name] = item; } }, { key: 'removeItem', value: function removeItem(name) { this.log('info', 'Removing item ' + name); delete this.items[name]; } }, { key: 'getItem', value: function getItem(name) { return this.items[name]; } }, { key: 'addFolder', value: function addFolder(folder, cb) { (0, _glob2.default)(folder + '/' + this.settings.pattern, {}, function (err, files) { if (err) { return cb(err); } for (var i = 0; i < files.length; i++) { var extension = _path2.default.extname(files[i]); var content = void 0; var absolutePath = this.getAbsolutePath(files[i]); if (extension === '.json' || extension === '.js') { content = require(absolutePath); } else { content = _fs2.default.readFileSync(absolutePath, 'utf8'); } if (content) { if (!_lodash2.default.isArray(content)) { var name = content.name; if (_lodash2.default.isFunction(content)) { content = { method: content }; } else if (_lodash2.default.isString(content)) { content = { text: content }; } if (!name) { name = _path2.default.basename(files[i], extension).toLowerCase(); } content.name = name; content = [content]; } for (var j = 0; j < content.length; j++) { this.addItem(content[j]); } } else { this.log('warning', 'Content not found for file ' + files[i]); } } return cb(); }.bind(this)); } }]); return FlowRequireManager; }(); exports.default = FlowRequireManager;
jseijas/flow-bot
lib/require-manager/flow-require-manager.js
JavaScript
mit
3,779
module.exports = function() { 'use strict'; this.title = element(by.model('movie.title')); this.releaseYear = element(by.model('movie.releaseYear')); this.description = element(by.css('div[contenteditable=true]')); this.save = element(by.css('.btn-primary')); this.open = function() { browser.get('/movies/new'); }; this.addMovie = function(title, description, releaseYear) { this.open(); this.title.clear(); this.title.sendKeys(title); if (releaseYear !== undefined) { this.releaseYear.clear(); this.releaseYear.sendKeys(releaseYear); } this.description.clear(); this.description.sendKeys(description); this.save.click(); }; };
agilejs/2014-10-localhorsts
test/client/ui/NewMovie.js
JavaScript
mit
764
/* global process */ /** * Dependencies */ // Third party libraries var debug = require('debug')('wakizashi'); var merge = require('merge-descriptors'); var fs = require('fs'); // Wakizashi libraries var domoweb = require('./domoweb'); var auth = require('./auth'); var dataset = require('./dataset'); var dataflow = require('./dataflow'); /** * Expose `createInstance()` */ exports = module.exports = createInstance; /** * Create a new instance of Wakizashi. Pass in a Domo Developer API Token * * @paran token * @return {Function} * @api public */ function createInstance(instance, token) { // Look for a credentials file if (instance == null || token == null) { try { var credFile = fs.readFileSync(".creds", 'utf8'); var creds = JSON.parse(credFile); token = creds.token; instance = creds.instance; } catch(error) { console.log("Not configured! Create a .creds file in the root folder."); } } // Store globally-accessible settings this.settings = { // Authentication details _authtoken: token, _instance: instance, // The DataSource Type to upload as // This can be overridden per create _type: "Wakizashi" }; // Create empty container function var app = function(){}; // Add in library functions merge(app, domoweb, false); merge(app, auth, false); merge(app, dataset, false); merge(app, dataflow, false); // And away we go! return app; }
woganmay/wakizashi
lib/wakizashi.js
JavaScript
mit
1,425
var casper = require('casper').create(), x = require('casper').selectXPath, config = require('config.json'), fs = require('fs'), moment = require('moment'); casper.start("http://caravantomidnight.com/show-archive/"); var currentMonthUrl = "http://caravantomidnight.com/show-archive-" + moment(casper.cli.get(0)).format("MMMM-YYYY/").toLowerCase(); var basePath = casper.cli.get(1); var episodes = []; var mp3Folder = basePath + 'mp3/'; function downloadEpisode(url, file) { var mp3Filepath = mp3Folder + file; if(!fs.exists(mp3Filepath)) { casper.download(url, mp3Filepath); } } casper.then(function () { casper.fillSelectors('#wma_login_form', { '#user_login': config.username, '#user_pass': config.password }); casper.click('#wp-submit'); }); casper.thenOpen(currentMonthUrl); casper.then(function () { var blocks = casper.getElementsInfo('div.content-column'); var episodeBlocks = casper.getElementsInfo(x('//div[contains(@class,"content-column")]/p[last()]')); if(blocks.length !== episodeBlocks.length) { casper.exit("Oh noes."); } for(var i=0; i < blocks.length; i++) { var episodeDescription = blocks[i].html.split('<p>')[0]; var episodeNumber = /Ep. (\d+) /.exec(episodeDescription)[1]; var mp3RegexMatches = /(http.+\.mp3)\".+>(.+) \(Full MP3\)/.exec(episodeBlocks[i].html); var mp3FileUrl = mp3RegexMatches[1]; episodes.push({ number: episodeNumber, description: episodeDescription, file: 'episode_' + episodeNumber + '.mp3', date: new Date(mp3RegexMatches[2]) }); downloadEpisode(mp3FileUrl, 'episode_' + episodeNumber + '.mp3'); } casper.echo(JSON.stringify(episodes)); }); casper.run();
tetious/CaravanScaper
midnight_caravan_superscraper.js
JavaScript
mit
1,722
/** * Module dependencies. */ var passport = require('passport'); module.exports.loginForm = function(req, res) { res.render('login'); }; module.exports.login = passport.authenticate('local', { successReturnToOrRedirect: '/login/status/success', failureRedirect: '/login/status/failure' }); module.exports.logout = function(req, res) { req.logout(); res.status(200).json('logout success'); } module.exports.loginStatus = function(req, res) { const { status } = req.params; if (status === 'current') { if (req.session.passport) { res.status(230).json('logining'); } else { res.status(403).json('no login'); } } else if (status === 'success'){ res.status(200).json('login success'); } else { res.status(403).json('login failure'); } }
gjSCUT/NodeJsApiServer
server/handlers/site.js
JavaScript
mit
798
// Generated by CoffeeScript 1.9.0 exports.MSGBYPAGE = 30; exports.LIMIT_DESTROY = 200; exports.LIMIT_UPDATE = 30; exports.CONCURRENT_DESTROY = 1; exports.FETCH_AT_ONCE = 1000;
m4dz/cozy-emails
build/server/utils/constants.js
JavaScript
mit
181
(function( $, ko ) { // Namespace for app. window['massroute'] = window.massroute || {}; window.massroute['model'] = window.massroute.model || {}; /** * Overall session model that holds state of the application. * @return {massroute.model.Session} */ var Session = (function() { this.routes = undefined; this.selectedRoute = undefined; this.configurationCache = {}; }); /** * Model representation of a Route from MassDOT. * @return {massroute.model.Route} */ var Route = (function() { this.tag = '' this.title = ''; this.inflate = function( xml ) { this.tag = $(xml).attr( 'tag' ); this.title = $(xml).attr( 'title' ); return this; }; }); /** * Model representation of a stop along a route from MassDOT. * @return {massroute.model.RouteStop} */ var RouteStop = (function() { this.tag = ''; this.title = ''; this.latitude = ''; this.longitude = ''; this.stopId = ''; this.inflate = function( xml ) { this.tag = $(xml).attr( 'tag' ); this.title = $(xml).attr( 'title' ); this.dirTag = $(xml).attr( 'dirTag' ); this.stopId = $(xml).attr( 'stopId' ); return this; }; }); /** * Model representation of a destination along a route from MassDOT. * @return {massroute.model.RouteDestination} */ var RouteDestination = (function() { this.tag = ''; this.name = ''; this.title = ''; this.stops = []; this.inflate = function( xml ) { this.tag = $(xml).attr( 'tag' ); this.name = $(xml).attr( 'name' ); this.title = $(xml).attr( 'title' ); var $stops = this.stops; $(xml).find( 'stop' ).each( function() { var stop = new massroute.model.RouteStop().inflate(this); $stops[$stops.length] = stop; }); return this; }; }); /** * Model representation of a route configuration from MassDOT. * @return {massroute.model.RouteConfiguration} */ var RouteConfiguration = (function() { var _stops = {}, _stopsByDestination = {}; this.route = undefined; this.destinations = []; /** * Adds a stop to the map of stops based on tag properties. * @param {XML} xml The XML representation of a stop. */ function addStop( xml ) { var stop = new massroute.model.RouteStop().inflate( xml ); _stops[stop.tag] = stop; } /** * Adds a destination to the list of destinations. * @param {XML} xml XML representation of a destination. * @param {Array} list The target list to add the destination to. */ function addDestination( xml, list ) { list[list.length] = new massroute.model.RouteDestination().inflate( xml ); } /** * Fills this model based on the XML data. * @param {XML} xml XML representation of a route configuration. * @return {massroute.model.RouteConfiguration} */ this.inflate = function( xml ) { var self = this, routeNode, routeStops, routeDirections; routeNode = $(xml).find( 'route' ); routeStops = $(routeNode).children( 'stop' ); routeDirections = $(routeNode).children( 'direction' ); this.route = new massroute.model.Route().inflate( routeNode ); $.each( routeStops, function( index, value ) { addStop( value ); }); $.each( routeDirections, function( index, value ) { addDestination( value, self.destinations ); }); return this; } /** * Finds stop within map based on supplied value corresponding to the tag property on RouteStop. * @param {String} value The tag property value to look-up. * @return {massroute.model.RouteStop} */ this.findStopByTag = function( value ) { return ( _stops.hasOwnProperty( value ) ? _stops[value] : undefined ); } /** * Finds the destination within the list based on the supplied value corresponding to that tag property on RouteDestination. * @param {String} value The tag property value to look-up. * @return {massroute.model.RouteDestination} */ this.findDestinationByTag = function( value ) { return ko.utils.arrayFirst( this.destinations, function( item ) { item.tag === value; }); } /** * Finds list of stops along destination. * @param {massroute.model.RouteDestination} destination The target destination to find stops along. * @return {Array} */ this.stopsForDestination = function( destination ) { var payload, destinationStops, configurationStops, destinationTag = destination.tag; payload = ( _stopsByDestination.hasOwnProperty( destinationTag ) ? _stopsByDestination[destinationTag] : null ); if( payload === null ) { payload = []; destinationStops = destination.stops; configurationStops = _stops; $.each( destinationStops, function( index, value ) { payload[payload.length] = configurationStops[this.tag]; }); _stopsByDestination[destinationTag] = payload; } return payload; } }); /** * Model representation of a prediction for a stop along a route from MassDOT. * @return {massroute.model.StopPrediction} */ var StopPrediction = (function() { this.seconds = 0; this.minutes = 0; this.epochTime = ''; this.isDeparture = false; this.dirTag = ''; this.affectedByLayover = false; this.delayed = false; this.slowness = 0; this.inflate = function( xml ) { this.seconds = Number($(xml).attr( 'seconds' )); this.minutes = Number($(xml).attr( 'minutes' )); this.epochTime = $(xml).attr( 'epochTime' ); this.isDeparture = ( $(xml).attr( 'isDeparture' ) === 'true' ) ? true : false; this.dirTag = $(xml).attr('dirTag'); this.affectedByLayover = ( $(xml).attr( 'affectedByLayover' ) === 'true' ) ? true : false; this.delayed = ( $(xml).attr( 'delayed' ) === 'true' ) ? true : false; this.slowness = Number($(xml).attr( 'slowness' )); return this; }; }); window.massroute.model.Session = Session; window.massroute.model.Route = Route; window.massroute.model.RouteConfiguration = RouteConfiguration; window.massroute.model.RouteStop = RouteStop; window.massroute.model.RouteDestination = RouteDestination; window.massroute.model.StopPrediction = StopPrediction; })( jQuery, ko );
bustardcelly/massroute-js
massroute-examples/knockout/js/app/model.js
JavaScript
mit
7,318
/** * Copyright (C) 2013 Emay Komarudin * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @author Emay Komarudin * **/ Ext.define('App.store.PO.ssupplier', { extend: 'Ext.data.Store', fields: [ 'id', 'address', "email", "fax", "phone", "name" ], proxy: { type: 'rest', url: getApiUrl() + '/suppliers', reader: { type: 'json', root: 'results', totalProperty: 'total' } } });
emayk/ics
public/frontend/app/store/PO/ssupplier.js
JavaScript
mit
1,014
import nodeResolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; import nodePolyfills from 'rollup-plugin-node-polyfills'; export default [ { input: 'support/demo_template/demo.js', output: { file: 'demo/demo.js', format: 'iife', name: 'demo' }, plugins: [ nodePolyfills(), nodeResolve(), commonjs() ] } ];
nodeca/js-yaml
support/demo_template/rollup.config.js
JavaScript
mit
384
$('section').horizon(); $(".menu-list").find("li").each(function(){ var menuIndex = $(this).index()+1; $(this).click(function(){ $(document).stop().horizon('scrollTo', menuIndex); }) })
dickywong0/teamde
js/inculde/slide.js
JavaScript
mit
201
export { default } from './RubymineOriginal'
fpoumian/react-devicon
src/components/rubymine/original/index.js
JavaScript
mit
45
/** * @file * @copyright 2016 Yahoo Inc. * @license Licensed under {@link https://spdx.org/licenses/BSD-3-Clause-Clear.html BSD-3-Clause-Clear}. * Github.js is freely distributable. */ import axios from 'axios'; import debug from 'debug'; import {Base64} from 'js-base64'; import {polyfill} from 'es6-promise'; const log = debug('github:request'); if (typeof Promise === 'undefined') { polyfill(); } /** * Requestable wraps the logic for making http requests to the API */ class Requestable { /** * Either a username and password or an oauth token for Github * @typedef {Object} Requestable.auth * @prop {string} [username] - the Github username * @prop {string} [password] - the user's password * @prop {token} [token] - an OAuth token */ /** * Initialize the http internals. * @param {Requestable.auth} [auth] - the credentials to authenticate to Github. If auth is * not provided request will be made unauthenticated * @param {string} [apiBase=https://api.github.com] - the base Github API URL */ constructor(auth, apiBase) { this.__apiBase = apiBase || 'https://api.github.com'; this.__auth = { token: auth.token, username: auth.username, password: auth.password }; if (auth.token) { this.__authorizationHeader = 'token ' + auth.token; } else if (auth.username && auth.password) { this.__authorizationHeader = 'Basic ' + Base64.encode(auth.username + ':' + auth.password); } } /** * Compute the URL to use to make a request. * @private * @param {string} path - either a URL relative to the API base or an absolute URL * @return {string} - the URL to use */ __getURL(path) { let url = path; if (path.indexOf('//') === -1) { url = this.__apiBase + path; } let newCacheBuster = 'timestamp=' + new Date().getTime(); return url.replace(/(timestamp=\d+)/, newCacheBuster); } /** * Compute the headers required for an API request. * @private * @param {boolean} raw - if the request should be treated as JSON or as a raw request * @return {Object} - the headers to use in the request */ __getRequestHeaders(raw) { let headers = { 'Accept': raw ? 'application/vnd.github.v3.raw+json' : 'application/vnd.github.v3+json', 'Content-Type': 'application/json;charset=UTF-8' }; if (this.__authorizationHeader) { headers.Authorization = this.__authorizationHeader; } return headers; } /** * Sets the default options for API requests * @protected * @param {Object} [requestOptions={}] - the current options for the request * @return - the options to pass to the request */ _getOptionsWithDefaults(requestOptions = {}) { requestOptions.type = requestOptions.type || 'all'; requestOptions.sort = requestOptions.sort || 'updated'; requestOptions.per_page = requestOptions.per_page || '100'; // jscs:ignore return requestOptions; } /** * if a `Date` is passed to this function it will be converted to an ISO string * @param {*} date - the object to attempt to cooerce into an ISO date string * @return {string} - the ISO representation of `date` or whatever was passed in if it was not a date */ _dateToISO(date) { if (date && (date instanceof Date)) { date = date.toISOString(); } return date; } /** * A function that receives the result of the API request. * @callback Requestable.callback * @param {Requestable.Error} error - the error returned by the API or `null` * @param {(Object|true)} result - the data returned by the API or `true` if the API returns `204 No Content` * @param {Object} request - the raw {@linkcode https://github.com/mzabriskie/axios#response-schema Response} */ /** * Make a request. * @param {string} method - the method for the request (GET, PUT, POST, DELETE) * @param {string} path - the path for the request * @param {*} [data] - the data to send to the server. For HTTP methods that don't have a body the data * will be sent as query parameters * @param {Requestable.callback} [cb] - the callback for the request * @param {boolean} [raw=false] - if the request should be sent as raw. If this is a falsy value then the * request will be made as JSON * @return {Promise} - the Promise for the http request */ _request(method, path, data, cb, raw) { const url = this.__getURL(path); const headers = this.__getRequestHeaders(raw); let queryParams = {}; const shouldUseDataAsParams = data && (typeof data === 'object') && methodHasNoBody(method); if (shouldUseDataAsParams) { queryParams = data; data = undefined; } const config = { url: url, method: method, headers: headers, params: queryParams, data: data, responseType: raw ? 'text' : 'json' }; log(`${config.method} to ${config.url}`); const requestPromise = axios(config).catch(callbackErrorOrThrow(cb, path)); if (cb) { requestPromise.then((response) => { cb(null, response.data || true, response); }); } return requestPromise; } /** * Make a request to an endpoint the returns 204 when true and 404 when false * @param {string} path - the path to request * @param {Object} data - any query parameters for the request * @param {Requestable.callback} cb - the callback that will receive `true` or `false` * @return {Promise} - the promise for the http request */ _request204or404(path, data, cb) { return this._request('GET', path, data) .then(function success(response) { if (cb) { cb(null, true, response); } return true; }, function failure(response) { if (response.status === 404) { if (cb) { cb(null, false, response); } return false; } if (cb) { cb(response); } throw response; }); } /** * Make a request and fetch all the available data. Github will paginate responses so for queries * that might span multiple pages this method is preferred to {@link Requestable#request} * @param {string} path - the path to request * @param {Object} options - the query parameters to include * @param {Requestable.callback} [cb] - the function to receive the data. The returned data will always be an array. * @param {Object[]} results - the partial results. This argument is intended for interal use only. * @return {Promise} - a promise which will resolve when all pages have been fetched * @deprecated This will be folded into {@link Requestable#_request} in the 2.0 release. */ _requestAllPages(path, options, cb, results) { results = results || []; return this._request('GET', path, options) .then((response) => { results.push.apply(results, response.data); const nextUrl = getNextPage(response.headers.link); if (nextUrl) { log(`getting next page: ${nextUrl}`); return this._requestAllPages(nextUrl, options, cb, results); } if (cb) { cb(null, results, response); } response.data = results; return response; }).catch(callbackErrorOrThrow(cb, path)); } } module.exports = Requestable; // ////////////////////////// // // Private helper functions // // ////////////////////////// // class ResponseError extends Error { constructor(path, response) { super(`error making request ${response.config.method} ${response.config.url}`); this.path = path; this.request = response.config; this.response = response; this.status = response.status; } } const METHODS_WITH_NO_BODY = ['GET', 'HEAD', 'DELETE']; function methodHasNoBody(method) { return METHODS_WITH_NO_BODY.indexOf(method) !== -1; } function getNextPage(linksHeader = '') { const links = linksHeader.split(/\s*,\s*/); // splits and strips the urls return links.reduce(function(nextUrl, link) { if (link.search(/rel="next"/) !== -1) { return (link.match(/<(.*)>/) || [])[1]; } return nextUrl; }, undefined); } function callbackErrorOrThrow(cb, path) { return function handler(response) { log(`error making request ${response.config.method} ${response.config.url} ${JSON.stringify(response.data)}`); let error = new ResponseError(path, response); if (cb) { log('going to error callback'); cb(error); } else { log('throwing error'); throw error; } }; }
suamorales/course-registration
node_modules/github-api/lib/Requestable.js
JavaScript
mit
9,079
define(['./module'], function (controllers) { 'use strict'; controllers.controller('msg_ctrl', [function ($scope) {}]); });
wbarahona/NodeChat
public/js/controllers/msg-ctrl.js
JavaScript
mit
131
import buble from 'rollup-plugin-buble'; import resolve from 'rollup-plugin-node-resolve'; import vue from 'rollup-plugin-vue'; export default { entry: 'index.js', dest: 'dist/v-tags.js', format: 'umd', sourceMap: true, useStrict: true, moduleName: 'VTags', plugins: [ vue({ compileTemplate: false }), buble({ objectAssign: 'Vue.util.extend' }), resolve({ jsnext: true, main: true, browser: true }), ] };
75team-biz/v-tags
rollup.config.js
JavaScript
mit
476
/** * App * * Root application file. * Load main controllers here. */ define([ "jquery", "modules/connected-devices/index" ], function( $, ConnectedDevices ) { "use strict"; var retriveData = function(callback) { var connected_devices_request = $.getJSON("data/connected-devices.json", { cache: + new Date() }); $.when(connected_devices_request) .then(function(connected_devices_data) { callback(null, connected_devices_data); }, function() { callback(new Error("An error has occurred requesting init data")); }); }, app = {}, connected_devices; /* * * */ app.init = function() { var $app_el = $(".js-app"); if ($app_el.length < 1) { throw new Error("Placeholder element is not available"); } retriveData(function(err, connected_devices_data) { if (err) { return window.console.error(err); } connected_devices = new ConnectedDevices({ el: $app_el.get(0), data: connected_devices_data }); connected_devices.render(); }); return true; }; /* * * */ app.destroy = function() { connected_devices.destroy(); }; /* * * */ app.update = function() { retriveData(function(err, connected_devices_data) { if (err) { return window.console.error(err); } connected_devices.update({ data: connected_devices_data }); }); }; return app; });
alistairjcbrown/connected-devices-display
js/src/app.js
JavaScript
mit
1,751
// The following will make sure the team_leader does not have access to certain menu items // All menu items have been tested at the administration level describe("Shakeout Menu", () => { // Before running tests - we have to make sure the admin user is logged in before(() => { cy.login('team_leader','Test1234$'); cy.getCookie("sessionid").should("exist"); cy.getCookie("csrftoken").should("exist"); }); //Making sure we still have the sessionid and csrftoken beforeEach(() => { Cypress.Cookies.preserveOnce("sessionid", "csrftoken"); }); //Make sure the administration menu does not exist it("Check no admin menu", () => { //Go to dashboard cy.visit('http://localhost:8000/'); //Make sure the administration drop down does not exist cy.get('#administrationDropdown') .should('not.exist'); }) })
robotichead/NearBeach
cypress/integration/team_leader/shakeout_menu.spec.js
JavaScript
mit
868
import * as R from 'ramda'; import ascent from './ascent'; import descent from './descent'; import lineGap from './lineGap'; /** * Get run height * * @param {Object} run * @return {number} height */ const height = R.either( R.path(['attributes', 'lineHeight']), R.compose(R.sum, R.juxt([ascent, R.o(R.negate, descent), lineGap])), ); export default height;
diegomura/react-pdf
packages/textkit/src/run/height.js
JavaScript
mit
371
'use strict' import assert from 'assert' import {remove} from '..' describe('remove', () => { it('throws a TypeError if the first argument is not an array', () => { const targets = [null, true, function() {}, {}] if (global.Map) targets.push(new Map()) targets.forEach(value => { assert.throws(() => { remove(value, 'foo') }, TypeError) }) }) it('remove the value (once) if target is an array', () => { const target = ['bar', 'bar'] remove(target, 'bar') assert.strictEqual(target.length, 1) }) if (global.Set) { it('removes the value if target is a set', () => { const target = new Set() target.add('foo') remove(target, 'foo') assert(!target.has('foo')) assert.strictEqual(target.size, 0) }) } })
sonnyp/mole
test/remove.js
JavaScript
mit
803
/* jshint strict: true, quotmark: false, es3: true */ /* global $: false, JSZip: false, odtprocessor: false */ var EUCopyright = EUCopyright || {}; EUCopyright.settings = EUCopyright.settings || {}; EUCopyright.settings.defaultToNoOpinion = EUCopyright.settings.defaultToNoOpinion === undefined ? true : EUCopyright.settings.defaultToNoOpinion; (function(){ "use strict"; EUCopyright.parseUrlParams = function (querystr) { var urlParams; querystr = querystr || window.location.search; var match, pl = /\+/g, // Regex for replacing addition symbol with a space search = /([^&=]+)=?([^&]*)/g, decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, query = querystr.substring(1); urlParams = {}; match = search.exec(query); while (match) { urlParams[decode(match[1])] = decode(match[2]); match = search.exec(query); } return urlParams; }; EUCopyright.parseCSV = function( strData, strDelimiter ){ /* This code taken from: http://stackoverflow.com/a/1293163/114462 under CC-By-SA 3.0 */ // This will parse a delimited string into an array of // arrays. The default delimiter is the comma, but this // can be overriden in the second argument. // Check to see if the delimiter is defined. If not, // then default to comma. strDelimiter = (strDelimiter || ","); var strMatchedValue, strMatchedDelimiter; // Create a regular expression to parse the CSV values. var objPattern = new RegExp( ( // Delimiters. "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" + // Quoted fields. "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" + // Standard fields. "([^\"\\" + strDelimiter + "\\r\\n]*))" ), "gi" ); // Create an array to hold our data. Give the array // a default empty first row. var arrData = [[]]; // Create an array to hold our individual pattern // matching groups. var arrMatches = null; // Keep looping over the regular expression matches // until we can no longer find a match. arrMatches = objPattern.exec(strData); while (arrMatches){ // Get the delimiter that was found. strMatchedDelimiter = arrMatches[ 1 ]; // Check to see if the given delimiter has a length // (is not the start of string) and if it matches // field delimiter. If id does not, then we know // that this delimiter is a row delimiter. if ( strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter) ){ // Since we have reached a new row of data, // add an empty row to our data array. arrData.push( [] ); } // Now that we have our delimiter out of the way, // let's check to see which kind of value we // captured (quoted or unquoted). if (arrMatches[ 2 ]){ // We found a quoted value. When we capture // this value, unescape any double quotes. strMatchedValue = arrMatches[ 2 ].replace(/""/g, '"'); } else { // We found a non-quoted value. strMatchedValue = arrMatches[ 3 ]; } // Now that we have our value string, let's add // it to the data array. arrData[arrData.length - 1].push(strMatchedValue); arrMatches = objPattern.exec(strData); } // Return the parsed data. return arrData ; }; EUCopyright.collectData = function() { var data = {}; var question, j, radio; var typesOfRespondents = []; $('*[name="typeofrespondent"]').each(function(i, el){ el = $(el); if ((el.attr('type') !== 'checkbox' && el.attr('type') !== 'radio') || el.prop('checked')){ typesOfRespondents.push(el.val()); } }); for (var i = 0; i < EUCopyright.questions.length; i += 1) { question = EUCopyright.questions[i]; if (question.type === 'multiple_choice' && question.options) { for (j = 0; j < question.options.length; j += 1) { radio = $('#q-' + question.num + '-' + j); if (radio.prop('checked')) { data['q-' + question.num] = j; if (question.options[j].fulltext) { data['q-' + question.num + '-' + j + '-text'] = $('#q-' + question.num + '-' + j + '-text').val(); } } } } else if (question.type == 'open_question') { data['q-' + question.num + '-text'] = $('#q-' + question.num + '-text').val(); } } data.name = $('#name').val(); data.registerid = $('#register-id').val(); data.typeofrespondent = typesOfRespondents; data.typeofrespondentother = $('#typeofrespondent-other-text').val(); return data; }; EUCopyright.compile = function(data, settings){ var addFile = function(zip, zipPath){ var d = $.Deferred(); $.get(EUCopyright.baseurl + '/data/' + zipPath).done(function(parsed, mes, xhr){ zip.file(zipPath, xhr.responseText); d.resolve(); }); return d; }; var constructContents = function(zip, data, settings) { var d = $.Deferred(); $.get(EUCopyright.baseurl + '/data/content.xml').done(function(parsed, mes, xhr){ var text = xhr.responseText; text = odtprocessor.renderText( text, data, EUCopyright.questions, settings ); zip.file('content.xml', text); d.resolve(); }); return d; }; var zip = new JSZip(); var jobs = [ constructContents(zip, data, settings), addFile(zip, 'mimetype'), addFile(zip, 'META-INF/manifest.xml'), addFile(zip, 'meta.xml'), addFile(zip, 'settings.xml'), addFile(zip, 'styles.xml') ]; var d = $.Deferred(); $.when.apply($, jobs).then(function(){ d.resolve(zip); }); return d; }; EUCopyright.answerCache = {}; EUCopyright.applyGuideToAll = function(guide, options){ var question, answer, answers = EUCopyright.answerCache[guide.slug]; for (var i = 0; i < EUCopyright.questions.length; i += 1) { if (answers[EUCopyright.questions[i].num]) { question = EUCopyright.questions[i]; answer = answers[question.num]; EUCopyright.applyGuide(guide, question, answer, options); } } }; EUCopyright.supports_html5_storage = function() { try { return 'localStorage' in window && window.localStorage !== null; } catch (e) { return false; } }; EUCopyright.applyGuide = function(guide, question, answer, options) { options = options || {}; var isAnswered = false; if (options.activeOnly && !$('#q-' + question.num).hasClass('active')) { return; } if (question.type === 'multiple_choice' && question.options) { if (answer.option !== null) { isAnswered = true; $('#q-' + question.num + '-' + answer.option). prop('checked', true). parents('div').addClass('isChecked'); // microsites might need this to hide unrecommended answer options if (question.options && question.options[answer.option].fulltext) { if ($('#q-' + question.num + '-' + answer.option + '-text').val() === '') { $('#q-' + question.num + '-' + answer.option + '-text').val(answer.answer); } } } } else if (question.type == 'open_question') { if (answer.answer) { isAnswered = true; } if ($('#q-' + question.num + '-text').val() === '') { $('#q-' + question.num + '-text').val(answer.answer); } } if (answer.explanation) { isAnswered = true; $('#q-' + question.num + '-customexplanation').slideDown(); $('#q-' + question.num + '-customexplanation-text').html(answer.explanation); if (answer.explanationmore) { $('#q-' + question.num + '-customexplanation').find('.toggle').show(); $('#q-' + question.num + '-customexplanationmore-text').html(answer.explanationmore); } else { $('#q-' + question.num + '-customexplanation').find('.toggle').hide(); $('#q-' + question.num + '-customexplanationmore-text').html('').hide(); } } else { $('#q-' + question.num + '-customexplanation').slideUp(); $('#q-' + question.num + '-customexplanationmore-text').slideUp(); } $('.answer-choices-' + question.num + ' a').removeClass('active'); if (isAnswered) { $('#answer-choice-' + guide.slug + '-' + question.num).addClass('active'); } }; EUCopyright.loadQuestionGuide = function(slug, clb){ if (EUCopyright.answerCache[slug] !== undefined){ if (EUCopyright.answerCache[slug] === 'waiting') { return; } return clb(EUCopyright.answerCache[slug]); } EUCopyright.answerCache[slug] = 'waiting'; $.get(EUCopyright.answers[slug].url, function(text, status, xhr){ var csv = EUCopyright.parseCSV(xhr.responseText); var answers = {}; for (var i = 1; i < csv.length; i += 1) { var row = {}; if (csv[i].length <= 1) { continue; // skip empty line in csv (usually last one) } for (var j = 0; j < csv[0].length; j += 1) { row[csv[0][j]] = csv[i][j]; } var answer = { option: row.Option ? parseInt(row.Option, 10) - 1 : null, answer: row.Answer, explanation: row.Explanation.replace(/\n/g, '<br/>') }; if (row.Explanation_more) { answer.explanationmore = row.Explanation_more.replace(/\n/g, '<br/>'); } answers[parseInt(row.Question, 10)] = answer; } EUCopyright.answerCache[slug] = answers; clb(EUCopyright.answerCache[slug]); }); }; EUCopyright.loadGuide = function(slug, options){ $('.load-question-guide').removeClass('active'); $('.load-question-guide-' + slug).addClass('active'); EUCopyright.loadQuestionGuide(slug, function(){ EUCopyright.applyGuideToAll(EUCopyright.answers[slug], options); }); }; EUCopyright.trackGoal = function(goalId){ if (window._paq !== undefined) { window._paq.push(['trackGoal', goalId]); } }; EUCopyright.createDownload = function(zip){ var filename = 'consultation-document_en.odt'; if (window.URL === undefined || !JSZip.support.blob) { $('#download-link-container').downloadify({ swf: EUCopyright.baseurl + '/js/downloadify.swf', downloadImage: EUCopyright.baseurl + '/img/downloadbutton.png', width: 116, height: 45, filename: filename, data: function(){ return zip.generate(); }, dataType: 'base64', onComplete: function(){ EUCopyright.trackGoal(1); } }); } else { $('#download').attr({ 'href': window.URL.createObjectURL(zip.generate({type: "blob"})), 'download': filename }).removeClass('disabled'); } $('#download-preparing').fadeOut(); }; EUCopyright.showDownloadModal = function(){ var data = EUCopyright.collectData(); EUCopyright.compile(data, EUCopyright.settings).done(EUCopyright.createDownload); $('#download').addClass('disabled'); $('#download-preparing').show(); $('#download-modal').modal(); }; $(function(){ $('.submit-form').removeClass('hide') .click(function(e){ e.preventDefault(); EUCopyright.trackGoal(1); var $c = $('#consultation-form'); var $dm = $('#download-modal'); $dm.find('.final-cases').addClass('hide'); var email = $c.find('*[name=email]').val(); if (email) { EUCopyright.trackGoal(2); $dm.find('.email-sent').removeClass('hide'); $dm.find('.email-sent-to').text(email); } else { $dm.find('.download-only').removeClass('hide'); } $dm.modal(); var action = $c.attr('action'); action = action.split('?')[0]; $c.attr('action', action); $c.submit(); }); $('#download').click(function(){ if (window._paq !== undefined) { window._paq.push(['trackGoal', 1]); } }); $('.load-question-guide').click(function(e){ e.preventDefault(); var params = EUCopyright.parseUrlParams($(this).attr('href')); EUCopyright.loadGuide(params.guide); }); $('.load-question').click(function(e){ e.preventDefault(); var slug = $(this).attr('href').substr(1); var qnum = parseInt($(this).data('question'), 10); EUCopyright.loadQuestionGuide(slug, function(answers){ EUCopyright.applyGuide( EUCopyright.answers[slug], EUCopyright.questions[qnum - 1], answers[qnum] ); }); }); $('.div-toggle').hide(); $('.toggle').show().click(function(e){ e.preventDefault(); if ($(this).hasClass('toggle-hide')) { $(this).hide(); } var div = $($(this).attr('href')); if (div.css('display') === 'block') { div.slideUp(); } else { div.slideDown(); } }); $('.needs-js').removeClass('hide'); if (!EUCopyright.supports_html5_storage()) { $('#localstorage-hint').hide(); } if (EUCopyright.supports_html5_storage()) { $('.delete-localstorage').click(function(e){ e.preventDefault(); var answer = window.confirm('Are you sure?'); if (!answer) { return; } for (var key in localStorage) { delete localStorage[key]; } window.location.reload(); }); } $('.radio-text textarea.save').on('keyup', function(){ var radio = $(this).parent().parent().find('input:not(checked)'); radio.prop('checked', true); if (EUCopyright.supports_html5_storage()) { var name = radio.attr('name'); var value = radio.val(); if (value !== null) { localStorage.setItem(name, value); } } }); $('.sdfootnoteanc').click(function(){ $('#footnote-div').show(); }); $('textarea').autogrow(); if (EUCopyright.supports_html5_storage()) { $('textarea.save').each(function() { var id = $(this).attr('id'); var value = localStorage.getItem(id); $(this).val(value); }); $('input[type=radio].save').each(function() { var name = $(this).attr('name'); var value = localStorage.getItem(name); if (value !== null) { $('input[type=radio]#' + name + '-' + value).prop('checked', true); } }); $('input[type=checkbox].save').each(function() { var name = $(this).attr('id'); var value = localStorage.getItem(name); if (!!value) { $('input[type=checkbox]#' + name).prop('checked', true); } }); $('input[type=text].save, input[type=email].save').each(function() { var id = $(this).attr('id'); var value = localStorage.getItem(id); $(this).val(value); }); $('textarea.save').on('keydown change', function() { var id = $(this).attr('id'); var value = $(this).val(); if (value !== null) { localStorage.setItem(id, value); } }); $('input[type=radio].save').on('click change', function() { var name = $(this).attr('name'); var value = $(this).val(); if (value !== null) { localStorage.setItem(name, value); } }); $('input[type=checkbox].save').on('click change', function() { var name = $(this).attr('id'); var value = $(this).prop('checked'); if (value) { localStorage.setItem(name, value); } else { delete localStorage[name]; } }); $('input[type=text].save, input[type=email].save').on('keydown change', function() { var id = $(this).attr('id'); var value = $(this).val(); if (value !== null) { localStorage.setItem(id, value); } }); } setTimeout(function () { var $sideBar = $('.side-navbar'); $sideBar.affix({ offset: { top: function () { var offsetTop = $sideBar.offset().top; var sideBarMargin = parseInt($sideBar.children(0).css('margin-top'), 10); var navOuterHeight = $('.navbar').height(); this.top = offsetTop - navOuterHeight - sideBarMargin; return this.top; }, bottom: function () { this.bottom = $('.footer-row').outerHeight(true); return this.bottom; } } }); }, 100); var urlParams = EUCopyright.parseUrlParams(); if (urlParams.guide) { EUCopyright.loadGuide(urlParams.guide); } }); /* Mozilla Cooke Reader/Writer https://developer.mozilla.org/en-US/docs/Web/API/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support */ window.docCookies = { getItem: function (sKey) { return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null; }, setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) { if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; } var sExpires = ""; if (vEnd) { switch (vEnd.constructor) { case Number: sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd; break; case String: sExpires = "; expires=" + vEnd; break; case Date: sExpires = "; expires=" + vEnd.toUTCString(); break; } } document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : ""); return true; }, removeItem: function (sKey, sPath, sDomain) { if (!sKey || !this.hasItem(sKey)) { return false; } document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : ""); return true; }, hasItem: function (sKey) { return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }, keys: /* optional method: you can safely remove it! */ function () { var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/); for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); } return aKeys; } }; }());
okfde/eucopyright
js/eucopyright.js
JavaScript
mit
17,935
var gulp = require('gulp'); var Path = require('path'); var compass = require('gulp-compass'); var minifyCss = require('gulp-minify-css'); var del = require('del'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var browserSync = require('browser-sync'); var reload = browserSync.reload; var plumber = require('gulp-plumber'); var replace = require('gulp-replace'); var karma = require('gulp-karma'); var shell = require('gulp-shell'); var zip = require('gulp-zip'); gulp.task('sass', sassCompile); gulp.task('assets', assetCopy); gulp.task('scripts', scriptCompile); gulp.task('flash', flashCompile); gulp.task('clean', clean); gulp.task('packageCopy', packageJsonCopy); gulp.task('devPackageCopy', devPackageCopy); gulp.task('reloader', ['build'], reload); gulp.task('reloadFlash', ['flash'], reload); gulp.task('dev', ['devPackageCopy', 'build', 'flash'], server); gulp.task('test', ['build', 'flash'], test); gulp.task('build', ['sass', 'assets', 'scripts']); gulp.task('nw', ['build', 'flash', 'packageCopy'], packageNodeWebkit); gulp.task('default', ['nw']); var outDir = 'out'; var packageDir = '.'; function sassCompile() { return gulp.src('src/main/scss/style.scss') .pipe(plumber({ errorHandler : function (error) { console.log(error.message); this.emit('end'); } })) .pipe(compass({ project : Path.join(__dirname), css : outDir + '/css', sass : 'src/main/scss', image : 'src/main/img' })) .pipe(minifyCss()) .pipe(gulp.dest(outDir + '/css')); } function scriptCompile() { return browserify('src/main/js/app.js') .bundle() .on('error', function (err) { console.log('error occured:', err); this.emit('end'); }) .pipe(source('app.js')) .pipe(gulp.dest(outDir + '/js')); } function flashCompile() { var flashCompileCommand; if (process.platform === 'darwin') { flashCompileCommand = 'osascript -e \'tell application "Adobe Flash CS6" to open posix file "' + __dirname + '/src/flash/compile.jsfl"\''; } else { flashCompileCommand = 'flash.exe "src\\flash\\compile.jsfl"'; } return gulp.src(['src/flash/compile.jsfl']) .pipe(plumber()) .pipe(shell('echo 1 > src/flash/compile.jsfl.deleteme')) .pipe(shell(flashCompileCommand)) } function assetCopy() { return gulp.src(['src/main/**', '!src/main/js/**', '!src/main/scss', '!src/main/scss/**']) .pipe(gulp.dest(outDir)); } function packageJsonCopy() { return gulp.src(['src/package.json']) .pipe(gulp.dest(outDir)); } function devPackageCopy() { return gulp.src(['src/package.json']) .pipe(replace(/(\s*)"main"(\s*:\s*)"([^"]*)"(\s*,\s*)/, '$1"main"$2"http://localhost:3000/$3"$4"node-remote"$2"http://localhost:3000"$4')) .pipe(gulp.dest(outDir)); } function test() { return gulp.src('src/test/**/*Spec.js') .pipe(karma({ configFile : 'karma.conf.js', action : 'run' })) .on('error', function (err) { throw err; }); } function server() { browserSync({ server : { baseDir : outDir }, open: false }); gulp.watch(['src/main/**', 'src/main/js/**', 'src/main/scss/**/*.scss'], {}, ['reloader']); gulp.watch(['src/flash/**'], {}, ['reloadFlash']); gulp.src('src/test/**/*Spec.js').pipe(karma({ configFile : 'karma.conf.js', action : 'watch' })); } function packageNodeWebkit() { return gulp.src(outDir + '/**') .pipe(zip('xlc_shop.nw')) .pipe(gulp.dest(packageDir)) } function clean(cb) { del([outDir], cb); }
campudus/ff-nw-flash
gulpfile.js
JavaScript
mit
3,571
munit( 'Rule Compression.Hex to Safe Color', function( assert ) { assert.exists( "Table", CSSCompressor.tables[ 'Hex to Safe Color' ] ); testRule( assert, 'Hex to Safe Color', [ { name: 'Basic', actual: '#000080', expected: 'navy' }, { name: 'Basic Uppercase', actual: '#c0c0c0', expected: 'silver' }, { name: 'Unsafe Color', actual: '#f0ffff', expected: undefined }, { name: 'No Conversion', actual: '#f02de5', expected: undefined } ]); });
codenothing/CSSCompressor
test/Rules/test-Hex to Safe Color.js
JavaScript
mit
503
var searchData= [ ['cache',['Cache',['../classCache.html',1,'']]], ['conversation',['Conversation',['../classConversation.html',1,'']]] ];
waitman/red
doc/html/search/classes_63.js
JavaScript
mit
143
'use strict'; function curry (fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { var nextArgs = Array.prototype.slice.call(arguments), allArgs = args.concat(nextArgs); return fn.apply(this, allArgs); }; } function compose () { var args = Array.prototype.slice.call(arguments).reverse(); return function (obj) { return args.reduce(function (result, F) { return F(result); }, obj); }; } module.exports = { identity: function (i) { return i; }, constant: function (k) { return function () { return k; }; }, noop: function () {}, compose: compose, curry: curry };
xue2sheng/mountebank
src/util/combinators.js
JavaScript
mit
661
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the LICENSE file in * the root directory of this source tree. * * @flow */ /** * Get a hash for the provider object. Hashes are unique per-hasher, so if you have two different * hashers, there is no guarantee that they will give the same hash for the same object. * * One use case for this is with lists of React elements. Just create a hasher and use the hash as * a key: * * class MyComponent extends React.Component { * constructor(props) { * super(props); * this._hasher = new Hasher(); * } * render() { * return this.props.items.map(item => ( * <ItemView key={this._hasher.getHash(item)} model={item} /> * )); * } * } */ export default class Hasher<K> { _hashes: WeakMap<K, string>; _objectCount: number; constructor() { this._hashes = new WeakMap(); this._objectCount = 0; } getHash(item: K): string | number { if (item === null) { return 'null'; } const type = typeof item; switch (typeof item) { case 'object': { let hash = this._hashes.get(item); if (hash == null) { hash = `${type}:${this._objectCount}`; this._hashes.set(item, hash); this._objectCount = this._objectCount + 1 === Number.MAX_SAFE_INTEGER ? Number.MIN_SAFE_INTEGER : this._objectCount + 1; } return hash; } case 'undefined': return 'undefined'; case 'string': case 'boolean': return `${type}:${item.toString()}`; case 'number': return item; default: throw new Error('Unhashable object'); } } }
JackPu/atom-weexpack
pkg/commons-node/Hasher.js
JavaScript
mit
1,800
//Categories service used to communicate Categories REST endpoints (function () { 'use strict'; angular .module('categories') .factory('CategoriesService', CategoriesService); CategoriesService.$inject = ['$resource']; function CategoriesService($resource) { return $resource('api/categories/:categoryId', { categoryId: '@_id' }, { update: { method: 'PUT' } }); } })();
megatronv7/pos
modules/categories/client/services/categories.client.service.js
JavaScript
mit
429
'use strict'; var Transform = require('readable-stream').Transform; var inherits = require('inherits'); var deepMatch = require('./lib/deepMatch'); var wrap = require('./lib/wrapMessage'); var jschan = require('jschan'); function noop() {} function Graft() { if (!(this instanceof Graft)) { return new Graft(); } Transform.call(this, { objectMode: true, highWaterMark: 16 }); var that = this; function readFirst() { /*jshint validthis:true */ this.removeListener('readable', readFirst); that._transform(wrap(this.read(), this), null, noop); } this._session = jschan.memorySession(); this._session.on('channel', function(channel) { channel.on('readable', readFirst); }); this._nextChannel = this._session.WriteChannel(); this.on('pipe', function(source) { source.on('ready', that.emit.bind(that, 'ready')); this.on('end', function() { source.end(); }); }); this._patterns = []; } inherits(Graft, Transform); Graft.prototype._transform = function flowing(obj, enc, done) { if (!obj._session && !obj._channel) { // it quacks like a duck, so it's a duck - s/duck/request/g var channel = this._nextChannel; this._nextChannel = this._session.WriteChannel(); channel.write(obj); return done(); } var i; for (i = 0; i < this._patterns.length; i++) { if (this._patterns[i].pattern(obj)) { this._patterns[i].stream.write(obj, done); return; } } this.push(obj); done(); }; Graft.prototype.branch = function(pattern, stream) { if (!pattern) { throw new Error('missing pattern'); } if (!stream) { throw new Error('missing destination'); } this._patterns.push({ pattern: pattern, stream: stream }); return this; }; Graft.prototype.where = function(pattern, stream) { return this.branch(function(req) { return deepMatch(pattern, req); }, stream); }; Graft.prototype.close = function(cb) { function complete() { /*jshint validthis:true */ this._session.close(function(err) { if (err) { return cb(err); } return cb(); }); } if (this._readableState.endEmitted) { complete.call(this); } else { this.on('end', complete); } if (!this._readableState.flowing) { this.resume(); } this.end(); }; Graft.prototype.ReadChannel = function() { return this._nextChannel.ReadChannel(); }; Graft.prototype.WriteChannel = function() { return this._nextChannel.WriteChannel(); }; module.exports = Graft;
GraftJS/graft
graft.js
JavaScript
mit
2,535
'use strict'; // Declare app level module which depends on views, and components var accountModule = angular.module('accountModule', []); var partnerModule = angular.module('partnerModule', []); var dodoModule = angular.module('dodoModule', []); angular.module('myApp', [ 'ngMaterial', 'ngRoute', 'myApp.version', 'accountModule', 'partnerModule', 'dodoModule' ]). config(['$routeProvider', function ($routeProvider) { $routeProvider.otherwise({redirectTo: '/view1'}); }]).factory('storageService', ['$log', '$rootScope', function ($log, $rootScope) { var localStorageMaxCount = 10; var storageService = { save: function (storageName, data) { localStorage[storageName] = JSON.stringify(data); if (localStorage.length > localStorageMaxCount) { $log.warn('local storage count (length) is over 10, this may be a bug, please check it out - Message from StorageService'); } $rootScope.$broadcast(storageName, data); return data; }, load: function (storageName) { var storedData = localStorage[storageName]; if (typeof storedData !== "undefined") { return JSON.parse(storedData); } else { return undefined; } }, clear: function (storageName) { delete localStorage[storageName]; $rootScope.$broadcast(storageName); return undefined; }, swipeAll: function () { localStorage.clear(); return 'localStorage is cleared!'; }, status: function () { $log.info('Current status -> localstorage: ', localStorage); } }; return storageService; }]).config(['$sceProvider', function ($sceProvider) { // Completely disable SCE. For demonstration purposes only! // Do not use in new projects. $sceProvider.enabled(false); }]).run(['storageService', '$location', '$http', function (storageService, $location, $http) { var currentUser = storageService.load('currentUser'); if (typeof currentUser == "undefined") { $location.path('/account/login'); } else { $http.defaults.headers.common["X-Parse-Session-Token"] = currentUser.sessionToken; } }]) .config(function ($mdThemingProvider) { $mdThemingProvider.theme('default') .primaryPalette('pink') .accentPalette('orange'); });
magnusosbeck/rManager
app/app.js
JavaScript
mit
2,567
"use strict"; const root = require('./helpers.js').root const ip = require('ip'); exports.HOST = ip.address(); exports.DEV_PORT = 3000; exports.E2E_PORT = 4201; exports.PROD_PORT = 8088; exports.UNIVERSAL_PORT = process.env.PORT || 8000; exports.SHOW_WEBPACK_BUNDLE_ANALYZER = false; /** * These constants set whether or not you will use proxy for Webpack DevServer * For advanced configuration details, go to: * https://webpack.github.io/docs/webpack-dev-server.html#proxy */ exports.USE_DEV_SERVER_PROXY = false; exports.DEV_SERVER_PROXY_CONFIG = { '**': 'http://localhost:8089' } /** * These constants set the source maps that will be used on build. * For info on source map options, go to: * https://webpack.github.io/docs/configuration.html#devtool */ exports.DEV_SOURCE_MAPS = 'eval'; exports.PROD_SOURCE_MAPS = 'source-map'; /** * Set watch options for Dev Server. For better HMR performance, you can * try setting poll to 1000 or as low as 300 and set aggregateTimeout to as low as 0. * These settings will effect CPU usage, so optimal setting will depend on your dev environment. * https://github.com/webpack/docs/wiki/webpack-dev-middleware#watchoptionsaggregatetimeout */ exports.DEV_SERVER_WATCH_OPTIONS = { poll: undefined, aggregateTimeout: 300, ignored: /node_modules/ } /** * specifies which @ngrx dev tools will be available when you build and load * your app in dev mode. Options are: monitor | logger | both | none */ exports.STORE_DEV_TOOLS = 'monitor' exports.EXCLUDE_SOURCE_MAPS = [ // these packages have problems with their sourcemaps root('node_modules/@angular'), root('node_modules/@nguniversal'), root('node_modules/rxjs') ] exports.MY_COPY_FOLDERS = [ // use this for folders you want to be copied in to Client dist // src/assets and index.html are already copied by default. // format is { from: 'folder_name', to: 'folder_name' } ] exports.MY_POLYFILL_DLLS = [ // list polyfills that you want to be included in your dlls files // this will speed up initial dev server build and incremental builds. // Be sure to run `npm run build:dll` if you make changes to this array. ] exports.MY_VENDOR_DLLS = [ // list vendors that you want to be included in your dlls files // this will speed up initial dev server build and incremental builds. // Be sure to run `npm run build:dll` if you make changes to this array. ] exports.MY_CLIENT_PLUGINS = [ // use this to import your own webpack config Client plugins. ] exports.MY_CLIENT_PRODUCTION_PLUGINS = [ // use this to import your own webpack config plugins for production use. ] exports.MY_CLIENT_RULES = [ // use this to import your own rules for Client webpack config. ] exports.MY_TEST_RULES = [ // use this to import your own rules for Test webpack config. ] exports.MY_TEST_PLUGINS = [ // use this to import your own Test webpack config plugins. ]
sangeet003/ng4-pwa-test
constants.js
JavaScript
mit
2,901
function report(str) { console.log(str); } function vec3(x,y,z) { return new THREE.Vector3(x,y,z); } SCENE = {}; SCENE.getCard = function(boxW, boxH, rotZ) { boxD = 0.1; if (!rotZ) rotZ = 0; //report("getImageCard "+imageUrl); var material = new THREE.MeshLambertMaterial( { color: 0xdddddd, //map: THREE.ImageUtils.loadTexture(imageUrl) //transparent: true }); material.side = THREE.DoubleSide; material.transparency = 0.5; var geometry = new THREE.PlaneGeometry( boxW, boxH ); var obj = new THREE.Mesh( geometry, material ); var card = new THREE.Object3D(); card.add(obj); obj.rotation.z = rotZ; obj.position.y += 0.5*boxH + boxD; obj.position.x += 0.0*boxW; obj.position.z += 0.0*boxD; card.obj = obj; card.material = material; return card; } var scene; SCENE.scene = scene; if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); var container, stats; var camera, renderer; var object, arrow; var useFog = true; var useGround = true; function start() { init(); animate(); } function init() { P = {}; P.v0 = 0.04; P.theta0 = 0; P.xbias = 0; P.lastTrackedTime = 0; P.pauseTime = 5; container = document.createElement( 'div' ); document.body.appendChild( container ); // scene scene = new THREE.Scene(); clearColor = 0xcce0ff; if (useFog) //scene.fog = new THREE.Fog( 0xcce0ff, 500, 10000 ); //NOFOG scene.fog = new THREE.Fog( clearColor, 500, 10000 ); //NOFOG //scene.fog = new THREE.Fog( 0xcce0ff, 500, 50000 ); //NOFOG // camera //camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 10000 ); camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 30000 ); camera.position.y = 50; camera.position.z = 1500; scene.add( camera ); P.camera = camera; // lights var light, materials; scene.add( new THREE.AmbientLight( 0x666666 ) ); var group = new THREE.Scene(); scene.add(group); light = new THREE.DirectionalLight( 0xdfebff, 1.75 ); light.position.set( 50, 200, 100 ); light.position.multiplyScalar( 1.3 ); light.castShadow = true; //light.shadowCameraVisible = true; light.shadowMapWidth = 1024; light.shadowMapHeight = 1024; //var d = 300; var d = 1200; light.shadowCameraLeft = -d; light.shadowCameraRight = d; light.shadowCameraTop = d; light.shadowCameraBottom = -d; light.shadowCameraFar = 1000; light.shadowDarkness = 0.5; scene.add( light ); // ground if (useGround) { var texLoader = new THREE.TextureLoader(); //var groundTexture = texLoader.load( "textures/terrain/grasslight-big.jpg" ); //groundTexture.repeat.set( 25, 25 ); //var groundTexture = texLoader.load( "textures/terrain/dark_grass.png" ); //groundTexture.repeat.set( 15, 15 ); var groundTexture = texLoader.load( "textures/terrain/red_earth.png" ); groundTexture.repeat.set( 15, 15 ); //var groundTexture = texLoader.load( "textures/terrain/BrownLeaves.jpg" ); groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping; //groundTexture.repeat.set( 5, 5 ); groundTexture.anisotropy = 16; var groundMaterial = new THREE.MeshPhongMaterial( { color: 0x664444, specular: 0x111111, map: groundTexture } ); var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 20000, 20000 ), groundMaterial ); mesh.position.y = -250; mesh.rotation.x = - Math.PI / 2; mesh.receiveShadow = true; scene.add( mesh ); } // renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.setClearColor( clearColor ); //NOFOG container.appendChild( renderer.domElement ); renderer.gammaInput = true; renderer.gammaOutput = true; //renderer.shadowMapEnabled = true; renderer.shadowMap.enabled = true; // stats = new Stats(); container.appendChild( stats.domElement ); // window.addEventListener( 'resize', onWindowResize, false ); trackball = 1; if (trackball) { //controls = new THREE.TrackballControls( camera, container ); //controls = new THREE.EditorControls( camera, container ); //controls = new THREE.OrthographicTrackballControls( camera, container ); //controls = new THREE.OrbitControls( camera, container ); controls = new THREE.PVControls( camera, container, scene ); controls.rotateSpeed = 2.0; controls.zoomSpeed = 1.2; controls.panSpeed = 0.8; controls.noZoom = false; controls.noPan = false; controls.staticMoving = true; controls.dynamicDampingFactor = 0.3; controls.keys = [ 65, 83, 68 ]; //controls.addEventListener( 'change', render ); } } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } // function animate() { requestAnimationFrame( animate ); render(); var time = Date.now(); //arrow.setLength( windMag ); //arrow.setDirection( SKIRT.windForce ); var ct = new Date().getTime() / 1000; // Adjust renderer.render( scene, camera ); stats.update(); } function render() { var timer = Date.now() * 0.0002; //sphere.position.copy( ballPosition ); //camera.lookAt( scene.position ); }
WorldViews/Spirals
Kinetics/js/simpleScene.js
JavaScript
mit
5,468
#!/usr/bin/env node var mkdirp = require('yeoman-generator/node_modules/mkdirp') var path = require('path') var fs = require('fs') var win32 = process.platform === 'win32' var homeDir = process.env[ win32? 'USERPROFILE' : 'HOME'] var libPath = path.join(homeDir, '.generator-lego', 'node_modules') var configPath = path.join(homeDir, '.generator-lego', 'config.json') // USERPROFILE 文件夹创建 mkdirp.sync(libPath) fs.writeFileSync(configPath, JSON.stringify({}, null, 4), { encoding: 'utf8' })
sdgdsffdsfff/generator-lego
scripts/post-install.js
JavaScript
mit
501
exports.platform = function () { switch(process.platform){ case 'win32': dep='win'; break; case 'linux': case 'mac': dep=process.platform; } return 'node-' + dep; };
iot-kit/xmpp-service-layer
modules/environment.js
JavaScript
mit
238
/** vim: et:ts=4:sw=4:sts=4 * @license RequireJS 2.1.11 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ //Not using strict: uneven strict support in browsers, #392, and causes //problems with requirejs.exec()/transpiler plugins that may not be strict. /*jslint regexp: true, nomen: true, sloppy: true */ /*global window, navigator, document, importScripts, setTimeout, opera */ var requirejs, require, define; (function (global) { var req, s, head, baseElement, dataMain, src, interactiveScript, currentlyAddingScript, mainScript, subPath, version = '2.1.11', commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, jsSuffixRegExp = /\.js$/, currDirRegExp = /^\.\//, op = Object.prototype, ostring = op.toString, hasOwn = op.hasOwnProperty, ap = Array.prototype, apsp = ap.splice, isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document), isWebWorker = !isBrowser && typeof importScripts !== 'undefined', //PS3 indicates loaded and complete, but need to wait for complete //specifically. Sequence is 'loading', 'loaded', execution, // then 'complete'. The UA check is unfortunate, but not sure how //to feature test w/o causing perf issues. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? /^complete$/ : /^(complete|loaded)$/, defContextName = '_', //Oh the tragedy, detecting opera. See the usage of isOpera for reason. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', contexts = {}, cfg = {}, globalDefQueue = [], useInteractive = false; function isFunction(it) { return ostring.call(it) === '[object Function]'; } function isArray(it) { return ostring.call(it) === '[object Array]'; } /** * Helper function for iterating over an array. If the func returns * a true value, it will break out of the loop. */ function each(ary, func) { if (ary) { var i; for (i = 0; i < ary.length; i += 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } /** * Helper function for iterating over an array backwards. If the func * returns a true value, it will break out of the loop. */ function eachReverse(ary, func) { if (ary) { var i; for (i = ary.length - 1; i > -1; i -= 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } function hasProp(obj, prop) { return hasOwn.call(obj, prop); } function getOwn(obj, prop) { return hasProp(obj, prop) && obj[prop]; } /** * Cycles over properties in an object and calls a function for each * property value. If the function returns a truthy value, then the * iteration is stopped. */ function eachProp(obj, func) { var prop; for (prop in obj) { if (hasProp(obj, prop)) { if (func(obj[prop], prop)) { break; } } } } /** * Simple function to mix in properties from source into target, * but only if target does not already have a property of the same name. */ function mixin(target, source, force, deepStringMixin) { if (source) { eachProp(source, function (value, prop) { if (force || !hasProp(target, prop)) { if (deepStringMixin && typeof value === 'object' && value && !isArray(value) && !isFunction(value) && !(value instanceof RegExp)) { if (!target[prop]) { target[prop] = {}; } mixin(target[prop], value, force, deepStringMixin); } else { target[prop] = value; } } }); } return target; } //Similar to Function.prototype.bind, but the 'this' object is specified //first, since it is easier to read/figure out what 'this' will be. function bind(obj, fn) { return function () { return fn.apply(obj, arguments); }; } function scripts() { return document.getElementsByTagName('script'); } function defaultOnError(err) { throw err; } //Allow getting a global that is expressed in //dot notation, like 'a.b.c'. function getGlobal(value) { if (!value) { return value; } var g = global; each(value.split('.'), function (part) { g = g[part]; }); return g; } /** * Constructs an error with a pointer to an URL with more information. * @param {String} id the error ID that maps to an ID on a web page. * @param {String} message human readable error. * @param {Error} [err] the original error, if there is one. * * @returns {Error} */ function makeError(id, msg, err, requireModules) { var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); e.requireType = id; e.requireModules = requireModules; if (err) { e.originalError = err; } return e; } if (typeof define !== 'undefined') { //If a define is already in play via another AMD loader, //do not overwrite. return; } if (typeof requirejs !== 'undefined') { if (isFunction(requirejs)) { //Do not overwrite and existing requirejs instance. return; } cfg = requirejs; requirejs = undefined; } //Allow for a require config object if (typeof require !== 'undefined' && !isFunction(require)) { //assume it is a config object. cfg = require; require = undefined; } function newContext(contextName) { var inCheckLoaded, Module, context, handlers, checkLoadedTimeoutId, config = { //Defaults. Do not set a default for map //config to speed up normalize(), which //will run faster if there is no default. waitSeconds: 7, baseUrl: './', paths: {}, bundles: {}, pkgs: {}, shim: {}, config: {} }, registry = {}, //registry of just enabled modules, to speed //cycle breaking code when lots of modules //are registered, but not activated. enabledRegistry = {}, undefEvents = {}, defQueue = [], defined = {}, urlFetched = {}, bundlesMap = {}, requireCounter = 1, unnormalizedCounter = 1; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part, length = ary.length; for (i = 0; i < length; i++) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @param {Boolean} applyMap apply the map config to the value. Should * only be done if this normalization is for a dependency ID. * @returns {String} normalized name */ function normalize(name, baseName, applyMap) { var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, foundMap, foundI, foundStarMap, starI, baseParts = baseName && baseName.split('/'), normalizedBaseParts = baseParts, map = config.map, starMap = map && map['*']; //Adjust any relative paths. if (name && name.charAt(0) === '.') { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { //Convert baseName to array, and lop off the last part, //so that . matches that 'directory' and not name of the baseName's //module. For instance, baseName of 'one/two/three', maps to //'one/two/three.js', but we want the directory, 'one/two' for //this normalization. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); name = name.split('/'); lastIndex = name.length - 1; // If wanting node ID compatibility, strip .js from end // of IDs. Have to do this here, and not in nameToUrl // because node allows either .js or non .js to map // to same file. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); } name = normalizedBaseParts.concat(name); trimDots(name); name = name.join('/'); } else if (name.indexOf('./') === 0) { // No baseName, so this is ID is resolved relative // to baseUrl, pull off the leading dot. name = name.substring(2); } } //Apply map config if available. if (applyMap && map && (baseParts || starMap)) { nameParts = name.split('/'); outerLoop: for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join('/'); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = getOwn(map, baseParts.slice(0, j).join('/')); //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = getOwn(mapValue, nameSegment); if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break outerLoop; } } } } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { foundStarMap = getOwn(starMap, nameSegment); starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } // If the name points to a package's name, use // the package main instead. pkgMain = getOwn(config.pkgs, name); return pkgMain ? pkgMain : name; } function removeScript(name) { if (isBrowser) { each(scripts(), function (scriptNode) { if (scriptNode.getAttribute('data-requiremodule') === name && scriptNode.getAttribute('data-requirecontext') === context.contextName) { scriptNode.parentNode.removeChild(scriptNode); return true; } }); } } function hasPathFallback(id) { var pathConfig = getOwn(config.paths, id); if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { //Pop off the first array value, since it failed, and //retry pathConfig.shift(); context.require.undef(id); context.require([id]); return true; } } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } /** * Creates a module mapping that includes plugin prefix, module * name, and path. If parentModuleMap is provided it will * also normalize the name via require.normalize() * * @param {String} name the module name * @param {String} [parentModuleMap] parent module map * for the module name, used to resolve relative names. * @param {Boolean} isNormalized: is the ID already normalized. * This is true if this call is done for a define() module ID. * @param {Boolean} applyMap: apply the map config to the ID. * Should only be true if this map is for a dependency. * * @returns {Object} */ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { var url, pluginModule, suffix, nameParts, prefix = null, parentName = parentModuleMap ? parentModuleMap.name : null, originalName = name, isDefine = true, normalizedName = ''; //If no name, then it means it is a require call, generate an //internal name. if (!name) { isDefine = false; name = '_@r' + (requireCounter += 1); } nameParts = splitPrefix(name); prefix = nameParts[0]; name = nameParts[1]; if (prefix) { prefix = normalize(prefix, parentName, applyMap); pluginModule = getOwn(defined, prefix); } //Account for relative paths if there is a base name. if (name) { if (prefix) { if (pluginModule && pluginModule.normalize) { //Plugin is loaded, use its normalize method. normalizedName = pluginModule.normalize(name, function (name) { return normalize(name, parentName, applyMap); }); } else { normalizedName = normalize(name, parentName, applyMap); } } else { //A regular module. normalizedName = normalize(name, parentName, applyMap); //Normalized name may be a plugin ID due to map config //application in normalize. The map config values must //already be normalized, so do not need to redo that part. nameParts = splitPrefix(normalizedName); prefix = nameParts[0]; normalizedName = nameParts[1]; isNormalized = true; url = context.nameToUrl(normalizedName); } } //If the id is a plugin id that cannot be determined if it needs //normalization, stamp it with a unique ID so two matching relative //ids that may conflict can be separate. suffix = prefix && !pluginModule && !isNormalized ? '_unnormalized' + (unnormalizedCounter += 1) : ''; return { prefix: prefix, name: normalizedName, parentMap: parentModuleMap, unnormalized: !!suffix, url: url, originalName: originalName, isDefine: isDefine, id: (prefix ? prefix + '!' + normalizedName : normalizedName) + suffix }; } function getModule(depMap) { var id = depMap.id, mod = getOwn(registry, id); if (!mod) { mod = registry[id] = new context.Module(depMap); } return mod; } function on(depMap, name, fn) { var id = depMap.id, mod = getOwn(registry, id); if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) { if (name === 'defined') { fn(defined[id]); } } else { mod = getModule(depMap); if (mod.error && name === 'error') { fn(mod.error); } else { mod.on(name, fn); } } } function onError(err, errback) { var ids = err.requireModules, notified = false; if (errback) { errback(err); } else { each(ids, function (id) { var mod = getOwn(registry, id); if (mod) { //Set error on module, so it skips timeout checks. mod.error = err; if (mod.events.error) { notified = true; mod.emit('error', err); } } }); if (!notified) { req.onError(err); } } } /** * Internal method to transfer globalQueue items to this context's * defQueue. */ function takeGlobalQueue() { //Push all the globalDefQueue items into the context's defQueue if (globalDefQueue.length) { //Array splice in the values since the context code has a //local var ref to defQueue, so cannot just reassign the one //on context. apsp.apply(defQueue, [defQueue.length, 0].concat(globalDefQueue)); globalDefQueue = []; } } handlers = { 'require': function (mod) { if (mod.require) { return mod.require; } else { return (mod.require = context.makeRequire(mod.map)); } }, 'exports': function (mod) { mod.usingExports = true; if (mod.map.isDefine) { if (mod.exports) { return (defined[mod.map.id] = mod.exports); } else { return (mod.exports = defined[mod.map.id] = {}); } } }, 'module': function (mod) { if (mod.module) { return mod.module; } else { return (mod.module = { id: mod.map.id, uri: mod.map.url, config: function () { return getOwn(config.config, mod.map.id) || {}; }, exports: mod.exports || (mod.exports = {}) }); } } }; function cleanRegistry(id) { //Clean up machinery used for waiting modules. delete registry[id]; delete enabledRegistry[id]; } function breakCycle(mod, traced, processed) { var id = mod.map.id; if (mod.error) { mod.emit('error', mod.error); } else { traced[id] = true; each(mod.depMaps, function (depMap, i) { var depId = depMap.id, dep = getOwn(registry, depId); //Only force things that have not completed //being defined, so still in the registry, //and only if it has not been matched up //in the module already. if (dep && !mod.depMatched[i] && !processed[depId]) { if (getOwn(traced, depId)) { mod.defineDep(i, defined[depId]); mod.check(); //pass false? } else { breakCycle(dep, traced, processed); } } }); processed[id] = true; } } function checkLoaded() { var err, usingPathFallback, waitInterval = config.waitSeconds * 1000, //It is possible to disable the wait interval by using waitSeconds of 0. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), noLoads = [], reqCalls = [], stillLoading = false, needCycleCheck = true; //Do not bother if this call was a result of a cycle break. if (inCheckLoaded) { return; } inCheckLoaded = true; //Figure out the state of all the modules. eachProp(enabledRegistry, function (mod) { var map = mod.map, modId = map.id; //Skip things that are not enabled or in error state. if (!mod.enabled) { return; } if (!map.isDefine) { reqCalls.push(mod); } if (!mod.error) { //If the module should be executed, and it has not //been inited and time is up, remember it. if (!mod.inited && expired) { if (hasPathFallback(modId)) { usingPathFallback = true; stillLoading = true; } else { noLoads.push(modId); removeScript(modId); } } else if (!mod.inited && mod.fetched && map.isDefine) { stillLoading = true; if (!map.prefix) { //No reason to keep looking for unfinished //loading. If the only stillLoading is a //plugin resource though, keep going, //because it may be that a plugin resource //is waiting on a non-plugin cycle. return (needCycleCheck = false); } } } }); if (expired && noLoads.length) { //If wait time expired, throw error of unloaded modules. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); err.contextName = context.contextName; return onError(err); } //Not expired, check for a cycle. if (needCycleCheck) { each(reqCalls, function (mod) { breakCycle(mod, {}, {}); }); } //If still waiting on loads, and the waiting load is something //other than a plugin resource, or there are still outstanding //scripts, then just try back later. if ((!expired || usingPathFallback) && stillLoading) { //Something is still waiting to load. Wait for it, but only //if a timeout is not already in effect. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { checkLoadedTimeoutId = setTimeout(function () { checkLoadedTimeoutId = 0; checkLoaded(); }, 50); } } inCheckLoaded = false; } Module = function (map) { this.events = getOwn(undefEvents, map.id) || {}; this.map = map; this.shim = getOwn(config.shim, map.id); this.depExports = []; this.depMaps = []; this.depMatched = []; this.pluginMaps = {}; this.depCount = 0; /* this.exports this.factory this.depMaps = [], this.enabled, this.fetched */ }; Module.prototype = { init: function (depMaps, factory, errback, options) { options = options || {}; //Do not do more inits if already done. Can happen if there //are multiple define calls for the same module. That is not //a normal, common case, but it is also not unexpected. if (this.inited) { return; } this.factory = factory; if (errback) { //Register for errors on this module. this.on('error', errback); } else if (this.events.error) { //If no errback already, but there are error listeners //on this module, set up an errback to pass to the deps. errback = bind(this, function (err) { this.emit('error', err); }); } //Do a copy of the dependency array, so that //source inputs are not modified. For example //"shim" deps are passed in here directly, and //doing a direct modification of the depMaps array //would affect that config. this.depMaps = depMaps && depMaps.slice(0); this.errback = errback; //Indicate this module has be initialized this.inited = true; this.ignore = options.ignore; //Could have option to init this module in enabled mode, //or could have been previously marked as enabled. However, //the dependencies are not known until init is called. So //if enabled previously, now trigger dependencies as enabled. if (options.enabled || this.enabled) { //Enable this module and dependencies. //Will call this.check() this.enable(); } else { this.check(); } }, defineDep: function (i, depExports) { //Because of cycles, defined callback for a given //export can be called more than once. if (!this.depMatched[i]) { this.depMatched[i] = true; this.depCount -= 1; this.depExports[i] = depExports; } }, fetch: function () { if (this.fetched) { return; } this.fetched = true; context.startTime = (new Date()).getTime(); var map = this.map; //If the manager is for a plugin managed resource, //ask the plugin to load it now. if (this.shim) { context.makeRequire(this.map, { enableBuildCallback: true })(this.shim.deps || [], bind(this, function () { return map.prefix ? this.callPlugin() : this.load(); })); } else { //Regular dependency. return map.prefix ? this.callPlugin() : this.load(); } }, load: function () { var url = this.map.url; //Regular dependency. if (!urlFetched[url]) { urlFetched[url] = true; context.load(this.map.id, url); } }, /** * Checks if the module is ready to define itself, and if so, * define it. */ check: function () { if (!this.enabled || this.enabling) { return; } var err, cjsModule, id = this.map.id, depExports = this.depExports, exports = this.exports, factory = this.factory; if (!this.inited) { this.fetch(); } else if (this.error) { this.emit('error', this.error); } else if (!this.defining) { //The factory could trigger another require call //that would result in checking this module to //define itself again. If already in the process //of doing that, skip this work. this.defining = true; if (this.depCount < 1 && !this.defined) { if (isFunction(factory)) { //If there is an error listener, favor passing //to that instead of throwing an error. However, //only do it for define()'d modules. require //errbacks should not be called for failures in //their callbacks (#699). However if a global //onError is set, use that. if ((this.events.error && this.map.isDefine) || req.onError !== defaultOnError) { try { exports = context.execCb(id, factory, depExports, exports); } catch (e) { err = e; } } else { exports = context.execCb(id, factory, depExports, exports); } // Favor return value over exports. If node/cjs in play, // then will not have a return value anyway. Favor // module.exports assignment over exports object. if (this.map.isDefine && exports === undefined) { cjsModule = this.module; if (cjsModule) { exports = cjsModule.exports; } else if (this.usingExports) { //exports already set the defined value. exports = this.exports; } } if (err) { err.requireMap = this.map; err.requireModules = this.map.isDefine ? [this.map.id] : null; err.requireType = this.map.isDefine ? 'define' : 'require'; return onError((this.error = err)); } } else { //Just a literal value exports = factory; } this.exports = exports; if (this.map.isDefine && !this.ignore) { defined[id] = exports; if (req.onResourceLoad) { req.onResourceLoad(context, this.map, this.depMaps); } } //Clean up cleanRegistry(id); this.defined = true; } //Finished the define stage. Allow calling check again //to allow define notifications below in the case of a //cycle. this.defining = false; if (this.defined && !this.defineEmitted) { this.defineEmitted = true; this.emit('defined', this.exports); this.defineEmitComplete = true; } } }, callPlugin: function () { var map = this.map, id = map.id, //Map already normalized the prefix. pluginMap = makeModuleMap(map.prefix); //Mark this as a dependency for this plugin, so it //can be traced for cycles. this.depMaps.push(pluginMap); on(pluginMap, 'defined', bind(this, function (plugin) { var load, normalizedMap, normalizedMod, bundleId = getOwn(bundlesMap, this.map.id), name = this.map.name, parentName = this.map.parentMap ? this.map.parentMap.name : null, localRequire = context.makeRequire(map.parentMap, { enableBuildCallback: true }); //If current map is not normalized, wait for that //normalized name to load instead of continuing. if (this.map.unnormalized) { //Normalize the ID if the plugin allows it. if (plugin.normalize) { name = plugin.normalize(name, function (name) { return normalize(name, parentName, true); }) || ''; } //prefix and name should already be normalized, no need //for applying map config again either. normalizedMap = makeModuleMap(map.prefix + '!' + name, this.map.parentMap); on(normalizedMap, 'defined', bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true, ignore: true }); })); normalizedMod = getOwn(registry, normalizedMap.id); if (normalizedMod) { //Mark this as a dependency for this plugin, so it //can be traced for cycles. this.depMaps.push(normalizedMap); if (this.events.error) { normalizedMod.on('error', bind(this, function (err) { this.emit('error', err); })); } normalizedMod.enable(); } return; } //If a paths config, then just load that file instead to //resolve the plugin, as it is built into that paths layer. if (bundleId) { this.map.url = context.nameToUrl(bundleId); this.load(); return; } load = bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true }); }); load.error = bind(this, function (err) { this.inited = true; this.error = err; err.requireModules = [id]; //Remove temp unnormalized modules for this module, //since they will never be resolved otherwise now. eachProp(registry, function (mod) { if (mod.map.id.indexOf(id + '_unnormalized') === 0) { cleanRegistry(mod.map.id); } }); onError(err); }); //Allow plugins to load other code without having to know the //context or how to 'complete' the load. load.fromText = bind(this, function (text, textAlt) { /*jslint evil: true */ var moduleName = map.name, moduleMap = makeModuleMap(moduleName), hasInteractive = useInteractive; //As of 2.1.0, support just passing the text, to reinforce //fromText only being called once per resource. Still //support old style of passing moduleName but discard //that moduleName in favor of the internal ref. if (textAlt) { text = textAlt; } //Turn off interactive script matching for IE for any define //calls in the text, then turn it back on at the end. if (hasInteractive) { useInteractive = false; } //Prime the system by creating a module instance for //it. getModule(moduleMap); //Transfer any config to this other module. if (hasProp(config.config, id)) { config.config[moduleName] = config.config[id]; } try { req.exec(text); } catch (e) { return onError(makeError('fromtexteval', 'fromText eval for ' + id + ' failed: ' + e, e, [id])); } if (hasInteractive) { useInteractive = true; } //Mark this as a dependency for the plugin //resource this.depMaps.push(moduleMap); //Support anonymous modules. context.completeLoad(moduleName); //Bind the value of that module to the value for this //resource ID. localRequire([moduleName], load); }); //Use parentName here since the plugin's name is not reliable, //could be some weird string with no path that actually wants to //reference the parentName's path. plugin.load(map.name, localRequire, load, config); })); context.enable(pluginMap, this); this.pluginMaps[pluginMap.id] = pluginMap; }, enable: function () { enabledRegistry[this.map.id] = this; this.enabled = true; //Set flag mentioning that the module is enabling, //so that immediate calls to the defined callbacks //for dependencies do not trigger inadvertent load //with the depCount still being zero. this.enabling = true; //Enable each dependency each(this.depMaps, bind(this, function (depMap, i) { var id, mod, handler; if (typeof depMap === 'string') { //Dependency needs to be converted to a depMap //and wired up to this module. depMap = makeModuleMap(depMap, (this.map.isDefine ? this.map : this.map.parentMap), false, !this.skipMap); this.depMaps[i] = depMap; handler = getOwn(handlers, depMap.id); if (handler) { this.depExports[i] = handler(this); return; } this.depCount += 1; on(depMap, 'defined', bind(this, function (depExports) { this.defineDep(i, depExports); this.check(); })); if (this.errback) { on(depMap, 'error', bind(this, this.errback)); } } id = depMap.id; mod = registry[id]; //Skip special modules like 'require', 'exports', 'module' //Also, don't call enable if it is already enabled, //important in circular dependency cases. if (!hasProp(handlers, id) && mod && !mod.enabled) { context.enable(depMap, this); } })); //Enable each plugin that is used in //a dependency eachProp(this.pluginMaps, bind(this, function (pluginMap) { var mod = getOwn(registry, pluginMap.id); if (mod && !mod.enabled) { context.enable(pluginMap, this); } })); this.enabling = false; this.check(); }, on: function (name, cb) { var cbs = this.events[name]; if (!cbs) { cbs = this.events[name] = []; } cbs.push(cb); }, emit: function (name, evt) { each(this.events[name], function (cb) { cb(evt); }); if (name === 'error') { //Now that the error handler was triggered, remove //the listeners, since this broken Module instance //can stay around for a while in the registry. delete this.events[name]; } } }; function callGetModule(args) { //Skip modules already defined. if (!hasProp(defined, args[0])) { getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); } } function removeListener(node, func, name, ieName) { //Favor detachEvent because of IE9 //issue, see attachEvent/addEventListener comment elsewhere //in this file. if (node.detachEvent && !isOpera) { //Probably IE. If not it will throw an error, which will be //useful to know. if (ieName) { node.detachEvent(ieName, func); } } else { node.removeEventListener(name, func, false); } } /** * Given an event from a script node, get the requirejs info from it, * and then removes the event listeners on the node. * @param {Event} evt * @returns {Object} */ function getScriptData(evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. var node = evt.currentTarget || evt.srcElement; //Remove the listeners once here. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); removeListener(node, context.onScriptError, 'error'); return { node: node, id: node && node.getAttribute('data-requiremodule') }; } function intakeDefines() { var args; //Any defined modules in the global queue, intake them now. takeGlobalQueue(); //Make sure any remaining defQueue items get properly processed. while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); } else { //args are id, deps, factory. Should be normalized by the //define() function. callGetModule(args); } } } context = { config: config, contextName: contextName, registry: registry, defined: defined, urlFetched: urlFetched, defQueue: defQueue, Module: Module, makeModuleMap: makeModuleMap, nextTick: req.nextTick, onError: onError, /** * Set a configuration for the context. * @param {Object} cfg config object to integrate. */ configure: function (cfg) { //Make sure the baseUrl ends in a slash. if (cfg.baseUrl) { if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { cfg.baseUrl += '/'; } } //Save off the paths since they require special processing, //they are additive. var shim = config.shim, objs = { paths: true, bundles: true, config: true, map: true }; eachProp(cfg, function (value, prop) { if (objs[prop]) { if (!config[prop]) { config[prop] = {}; } mixin(config[prop], value, true, true); } else { config[prop] = value; } }); //Reverse map the bundles if (cfg.bundles) { eachProp(cfg.bundles, function (value, prop) { each(value, function (v) { if (v !== prop) { bundlesMap[v] = prop; } }); }); } //Merge shim if (cfg.shim) { eachProp(cfg.shim, function (value, id) { //Normalize the structure if (isArray(value)) { value = { deps: value }; } if ((value.exports || value.init) && !value.exportsFn) { value.exportsFn = context.makeShimExports(value); } shim[id] = value; }); config.shim = shim; } //Adjust packages if necessary. if (cfg.packages) { each(cfg.packages, function (pkgObj) { var location, name; pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; name = pkgObj.name; location = pkgObj.location; if (location) { config.paths[name] = pkgObj.location; } //Save pointer to main module ID for pkg name. //Remove leading dot in main, so main paths are normalized, //and remove any trailing .js, since different package //envs have different conventions: some use a module name, //some use a file name. config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') .replace(currDirRegExp, '') .replace(jsSuffixRegExp, ''); }); } //If there are any "waiting to execute" modules in the registry, //update the maps for them, since their info, like URLs to load, //may have changed. eachProp(registry, function (mod, id) { //If module already has init called, since it is too //late to modify them, and ignore unnormalized ones //since they are transient. if (!mod.inited && !mod.map.unnormalized) { mod.map = makeModuleMap(id); } }); //If a deps array or a config callback is specified, then call //require with those args. This is useful when require is defined as a //config object before require.js is loaded. if (cfg.deps || cfg.callback) { context.require(cfg.deps || [], cfg.callback); } }, makeShimExports: function (value) { function fn() { var ret; if (value.init) { ret = value.init.apply(global, arguments); } return ret || (value.exports && getGlobal(value.exports)); } return fn; }, makeRequire: function (relMap, options) { options = options || {}; function localRequire(deps, callback, errback) { var id, map, requireMod; if (options.enableBuildCallback && callback && isFunction(callback)) { callback.__requireJsBuild = true; } if (typeof deps === 'string') { if (isFunction(callback)) { //Invalid call return onError(makeError('requireargs', 'Invalid require call'), errback); } //If require|exports|module are requested, get the //value for them from the special handlers. Caveat: //this only works while module is being defined. if (relMap && hasProp(handlers, deps)) { return handlers[deps](registry[relMap.id]); } //Synchronous access to one module. If require.get is //available (as in the Node adapter), prefer that. if (req.get) { return req.get(context, deps, relMap, localRequire); } //Normalize module name, if it contains . or .. map = makeModuleMap(deps, relMap, false, true); id = map.id; if (!hasProp(defined, id)) { return onError(makeError('notloaded', 'Module name "' + id + '" has not been loaded yet for context: ' + contextName + (relMap ? '' : '. Use require([])'))); } return defined[id]; } //Grab defines waiting in the global queue. intakeDefines(); //Mark all the dependencies as needing to be loaded. context.nextTick(function () { //Some defines could have been added since the //require call, collect them. intakeDefines(); requireMod = getModule(makeModuleMap(null, relMap)); //Store if map config should be applied to this require //call for dependencies. requireMod.skipMap = options.skipMap; requireMod.init(deps, callback, errback, { enabled: true }); checkLoaded(); }); return localRequire; } mixin(localRequire, { isBrowser: isBrowser, /** * Converts a module name + .extension into an URL path. * *Requires* the use of a module name. It does not support using * plain URLs like nameToUrl. */ toUrl: function (moduleNamePlusExt) { var ext, index = moduleNamePlusExt.lastIndexOf('.'), segment = moduleNamePlusExt.split('/')[0], isRelative = segment === '.' || segment === '..'; //Have a file extension alias, and it is not the //dots from a relative path. if (index !== -1 && (!isRelative || index > 1)) { ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); moduleNamePlusExt = moduleNamePlusExt.substring(0, index); } return context.nameToUrl(normalize(moduleNamePlusExt, relMap && relMap.id, true), ext, true); }, defined: function (id) { return hasProp(defined, makeModuleMap(id, relMap, false, true).id); }, specified: function (id) { id = makeModuleMap(id, relMap, false, true).id; return hasProp(defined, id) || hasProp(registry, id); } }); //Only allow undef on top level require calls if (!relMap) { localRequire.undef = function (id) { //Bind any waiting define() calls to this context, //fix for #408 takeGlobalQueue(); var map = makeModuleMap(id, relMap, true), mod = getOwn(registry, id); removeScript(id); delete defined[id]; delete urlFetched[map.url]; delete undefEvents[id]; //Clean queued defines too. Go backwards //in array so that the splices do not //mess up the iteration. eachReverse(defQueue, function(args, i) { if(args[0] === id) { defQueue.splice(i, 1); } }); if (mod) { //Hold on to listeners in case the //module will be attempted to be reloaded //using a different config. if (mod.events.defined) { undefEvents[id] = mod.events; } cleanRegistry(id); } }; } return localRequire; }, /** * Called to enable a module if it is still in the registry * awaiting enablement. A second arg, parent, the parent module, * is passed in for context, when this method is overridden by * the optimizer. Not shown here to keep code compact. */ enable: function (depMap) { var mod = getOwn(registry, depMap.id); if (mod) { getModule(depMap).enable(); } }, /** * Internal method used by environment adapters to complete a load event. * A load event could be a script load or just a load pass from a synchronous * load call. * @param {String} moduleName the name of the module to potentially complete. */ completeLoad: function (moduleName) { var found, args, mod, shim = getOwn(config.shim, moduleName) || {}, shExports = shim.exports; takeGlobalQueue(); while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { args[0] = moduleName; //If already found an anonymous module and bound it //to this name, then this is some other anon module //waiting for its completeLoad to fire. if (found) { break; } found = true; } else if (args[0] === moduleName) { //Found matching define call for this script! found = true; } callGetModule(args); } //Do this after the cycle of callGetModule in case the result //of those calls/init calls changes the registry. mod = getOwn(registry, moduleName); if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { if (hasPathFallback(moduleName)) { return; } else { return onError(makeError('nodefine', 'No define call for ' + moduleName, null, [moduleName])); } } else { //A script that does not call define(), so just simulate //the call for it. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); } } checkLoaded(); }, /** * Converts a module name to a file path. Supports cases where * moduleName may actually be just an URL. * Note that it **does not** call normalize on the moduleName, * it is assumed to have already been normalized. This is an * internal API, not a public one. Use toUrl for the public API. */ nameToUrl: function (moduleName, ext, skipExt) { var paths, syms, i, parentModule, url, parentPath, bundleId, pkgMain = getOwn(config.pkgs, moduleName); if (pkgMain) { moduleName = pkgMain; } bundleId = getOwn(bundlesMap, moduleName); if (bundleId) { return context.nameToUrl(bundleId, ext, skipExt); } //If a colon is in the URL, it indicates a protocol is used and it is just //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) //or ends with .js, then assume the user meant to use an url and not a module id. //The slash is important for protocol-less URLs as well as full paths. if (req.jsExtRegExp.test(moduleName)) { //Just a plain path, not module name lookup, so just return it. //Add extension if it is included. This is a bit wonky, only non-.js things pass //an extension, this method probably needs to be reworked. url = moduleName + (ext || ''); } else { //A module that needs to be converted to a path. paths = config.paths; syms = moduleName.split('/'); //For each module name segment, see if there is a path //registered for it. Start with most specific name //and work up from it. for (i = syms.length; i > 0; i -= 1) { parentModule = syms.slice(0, i).join('/'); parentPath = getOwn(paths, parentModule); if (parentPath) { //If an array, it means there are a few choices, //Choose the one that is desired if (isArray(parentPath)) { parentPath = parentPath[0]; } syms.splice(0, i, parentPath); break; } } //Join the path parts together, then figure out if baseUrl is needed. url = syms.join('/'); url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js')); url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; } return config.urlArgs ? url + ((url.indexOf('?') === -1 ? '?' : '&') + config.urlArgs) : url; }, //Delegates to req.load. Broken out as a separate function to //allow overriding in the optimizer. load: function (id, url) { req.load(context, id, url); }, /** * Executes a module callback function. Broken out as a separate function * solely to allow the build system to sequence the files in the built * layer in the right sequence. * * @private */ execCb: function (name, callback, args, exports) { return callback.apply(exports, args); }, /** * callback for script loads, used to check status of loading. * * @param {Event} evt the event from the browser for the script * that was loaded. */ onScriptLoad: function (evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. if (evt.type === 'load' || (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { //Reset interactive script so a script node is not held onto for //to long. interactiveScript = null; //Pull out the name of the module and the context. var data = getScriptData(evt); context.completeLoad(data.id); } }, /** * Callback for script errors. */ onScriptError: function (evt) { var data = getScriptData(evt); if (!hasPathFallback(data.id)) { return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id])); } } }; context.require = context.makeRequire(); return context; } /** * Main entry point. * * If the only argument to require is a string, then the module that * is represented by that string is fetched for the appropriate context. * * If the first argument is an array, then it will be treated as an array * of dependency string names to fetch. An optional function callback can * be specified to execute when all of those dependencies are available. * * Make a local req variable to help Caja compliance (it assumes things * on a require that are not standardized), and to give a short * name for minification/local scope use. */ req = requirejs = function (deps, callback, errback, optional) { //Find the right context, use default var context, config, contextName = defContextName; // Determine if have config object in the call. if (!isArray(deps) && typeof deps !== 'string') { // deps is a config object config = deps; if (isArray(callback)) { // Adjust args if there are dependencies deps = callback; callback = errback; errback = optional; } else { deps = []; } } if (config && config.context) { contextName = config.context; } context = getOwn(contexts, contextName); if (!context) { context = contexts[contextName] = req.s.newContext(contextName); } if (config) { context.configure(config); } return context.require(deps, callback, errback); }; /** * Support require.config() to make it easier to cooperate with other * AMD loaders on globally agreed names. */ req.config = function (config) { return req(config); }; /** * Execute something after the current tick * of the event loop. Override for other envs * that have a better solution than setTimeout. * @param {Function} fn function to execute later. */ req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { setTimeout(fn, 4); } : function (fn) { fn(); }; /** * Export require as a global, but only if it does not already exist. */ if (!require) { require = req; } req.version = version; //Used to filter out dependencies that are already paths. req.jsExtRegExp = /^\/|:|\?|\.js$/; req.isBrowser = isBrowser; s = req.s = { contexts: contexts, newContext: newContext }; //Create default context. req({}); //Exports some context-sensitive methods on global require. each([ 'toUrl', 'undef', 'defined', 'specified' ], function (prop) { //Reference from contexts instead of early binding to default context, //so that during builds, the latest instance of the default context //with its config gets used. req[prop] = function () { var ctx = contexts[defContextName]; return ctx.require[prop].apply(ctx, arguments); }; }); if (isBrowser) { head = s.head = document.getElementsByTagName('head')[0]; //If BASE tag is in play, using appendChild is a problem for IE6. //When that browser dies, this can be removed. Details in this jQuery bug: //http://dev.jquery.com/ticket/2709 baseElement = document.getElementsByTagName('base')[0]; if (baseElement) { head = s.head = baseElement.parentNode; } } /** * Any errors that require explicitly generates will be passed to this * function. Intercept/override it if you want custom error handling. * @param {Error} err the error object. */ req.onError = defaultOnError; /** * Creates the node for the load command. Only used in browser envs. */ req.createNode = function (config, moduleName, url) { var node = config.xhtml ? document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : document.createElement('script'); node.type = config.scriptType || 'text/javascript'; node.charset = 'utf-8'; node.async = true; return node; }; /** * Does the request to load a module for the browser case. * Make this a separate function to allow other environments * to override it. * * @param {Object} context the require context to find state. * @param {String} moduleName the name of the module. * @param {Object} url the URL to the module. */ req.load = function (context, moduleName, url) { var config = (context && context.config) || {}, node; if (isBrowser) { //In the browser so use a script tag node = req.createNode(config, moduleName, url); node.setAttribute('data-requirecontext', context.contextName); node.setAttribute('data-requiremodule', moduleName); //Set up load listener. Test attachEvent first because IE9 has //a subtle issue in its addEventListener and script onload firings //that do not match the behavior of all other browsers with //addEventListener support, which fire the onload event for a //script right after the script execution. See: //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution //UNFORTUNATELY Opera implements attachEvent but does not follow the script //script execution mode. if (node.attachEvent && //Check if node.attachEvent is artificially added by custom script or //natively supported by browser //read https://github.com/jrburke/requirejs/issues/187 //if we can NOT find [native code] then it must NOT natively supported. //in IE8, node.attachEvent does not have toString() //Note the test for "[native code" with no closing brace, see: //https://github.com/jrburke/requirejs/issues/273 !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera) { //Probably IE. IE (at least 6-8) do not fire //script onload right after executing the script, so //we cannot tie the anonymous define call to a name. //However, IE reports the script as being in 'interactive' //readyState at the time of the define call. useInteractive = true; node.attachEvent('onreadystatechange', context.onScriptLoad); //It would be great to add an error handler here to catch //404s in IE9+. However, onreadystatechange will fire before //the error handler, so that does not help. If addEventListener //is used, then IE will fire error before load, but we cannot //use that pathway given the connect.microsoft.com issue //mentioned above about not doing the 'script execute, //then fire the script load event listener before execute //next script' that other browsers do. //Best hope: IE10 fixes the issues, //and then destroys all installs of IE 6-9. //node.attachEvent('onerror', context.onScriptError); } else { node.addEventListener('load', context.onScriptLoad, false); node.addEventListener('error', context.onScriptError, false); } node.src = url; //For some cache cases in IE 6-8, the script executes before the end //of the appendChild execution, so to tie an anonymous define //call to the module name (which is stored on the node), hold on //to a reference to this node, but clear after the DOM insertion. currentlyAddingScript = node; if (baseElement) { head.insertBefore(node, baseElement); } else { head.appendChild(node); } currentlyAddingScript = null; return node; } else if (isWebWorker) { try { //In a web worker, use importScripts. This is not a very //efficient use of importScripts, importScripts will block until //its script is downloaded and evaluated. However, if web workers //are in play, the expectation that a build has been done so that //only one script needs to be loaded anyway. This may need to be //reevaluated if other use cases become common. importScripts(url); //Account for anonymous modules context.completeLoad(moduleName); } catch (e) { context.onError(makeError('importscripts', 'importScripts failed for ' + moduleName + ' at ' + url, e, [moduleName])); } } }; function getInteractiveScript() { if (interactiveScript && interactiveScript.readyState === 'interactive') { return interactiveScript; } eachReverse(scripts(), function (script) { if (script.readyState === 'interactive') { return (interactiveScript = script); } }); return interactiveScript; } //Look for a data-main script attribute, which could also adjust the baseUrl. if (isBrowser && !cfg.skipDataMain) { //Figure out baseUrl. Get it from the script tag with require.js in it. eachReverse(scripts(), function (script) { //Set the 'head' where we can append children by //using the script's parent. if (!head) { head = script.parentNode; } //Look for a data-main attribute to set main script for the page //to load. If it is there, the path to data main becomes the //baseUrl, if it is not already set. dataMain = script.getAttribute('data-main'); if (dataMain) { //Preserve dataMain in case it is a path (i.e. contains '?') mainScript = dataMain; //Set final baseUrl if there is not already an explicit one. if (!cfg.baseUrl) { //Pull off the directory of data-main for use as the //baseUrl. src = mainScript.split('/'); mainScript = src.pop(); subPath = src.length ? src.join('/') + '/' : './'; cfg.baseUrl = subPath; } //Strip off any trailing .js since mainScript is now //like a module name. mainScript = mainScript.replace(jsSuffixRegExp, ''); //If mainScript is still a path, fall back to dataMain if (req.jsExtRegExp.test(mainScript)) { mainScript = dataMain; } //Put the data-main script in the files to load. cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; return true; } }); } /** * The function that handles definitions of modules. Differs from * require() in that a string for the module should be the first argument, * and the function to execute after dependencies are loaded should * return a value to define the module corresponding to the first argument's * name. */ define = function (name, deps, callback) { var node, context; //Allow for anonymous modules if (typeof name !== 'string') { //Adjust args appropriately callback = deps; deps = name; name = null; } //This module may not have dependencies if (!isArray(deps)) { callback = deps; deps = null; } //If no name, and callback is a function, then figure out if it a //CommonJS thing with dependencies. if (!deps && isFunction(callback)) { deps = []; //Remove comments from the callback string, //look for require calls, and pull them into the dependencies, //but only if there are function args. if (callback.length) { callback .toString() .replace(commentRegExp, '') .replace(cjsRequireRegExp, function (match, dep) { deps.push(dep); }); //May be a CommonJS thing even without require calls, but still //could use exports, and module. Avoid doing exports and module //work though if it just needs require. //REQUIRES the function to expect the CommonJS variables in the //order listed below. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); } } //If in IE 6-8 and hit an anonymous define() call, do the interactive //work. if (useInteractive) { node = currentlyAddingScript || getInteractiveScript(); if (node) { if (!name) { name = node.getAttribute('data-requiremodule'); } context = contexts[node.getAttribute('data-requirecontext')]; } } //Always save off evaluating the def call until the script onload handler. //This allows multiple modules to be in a file without prematurely //tracing dependencies, and allows for anonymous module support, //where the module name is not known until the script onload event //occurs. If no context, use the global queue, and get it processed //in the onscript load callback. (context ? context.defQueue : globalDefQueue).push([name, deps, callback]); }; define.amd = { jQuery: true }; /** * Executes the text. Normally just uses eval, but can be modified * to use a better, environment-specific call. Only used for transpiling * loader plugins, not for plain JS modules. * @param {String} text the text to execute/evaluate. */ req.exec = function (text) { /*jslint evil: true */ return eval(text); }; //Set up with config info. req(cfg); }(this));
GooDay0923/chatroom
public/lib/requirejs/require.js
JavaScript
mit
82,275
var add = require('./add'); QUnit.test('add example', function () { // add function returns sum of numbers QUnit.equal(add(2, 3), 5); // it also concatenates strings QUnit.equal(add('foo', 'bar'), 'foobar') });
bahmutov/xplain
examples/markdown/qunit/add-test.js
JavaScript
mit
226
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. * See LICENSE in the project root for license information. */ /** * This sample shows how to: * - Get the current user's metadata * - Get the current user's profile photo * - Attach the photo as a file attachment to an email message * - Upload the photo to the user's root drive * - Get a sharing link for the file and add it to the message * - Send the email */ const express = require('express'); const router = express.Router(); const graphHelper = require('../utils/graphHelper.js'); const emailer = require('../utils/emailer.js'); const passport = require('passport'); // ////const fs = require('fs'); // ////const path = require('path'); // Get the home page. router.get('/', (req, res) => { // check if user is authenticated if (!req.isAuthenticated()) { res.render('login'); } else { renderSendMail(req, res); } }); // Authentication request. router.get('/login', passport.authenticate('azuread-openidconnect', { failureRedirect: '/' }), (req, res) => { res.redirect('/'); }); // Authentication callback. // After we have an access token, get user data and load the sendMail page. router.get('/token', passport.authenticate('azuread-openidconnect', { failureRedirect: '/' }), (req, res) => { graphHelper.getUserData(req.user.accessToken, (err, user) => { if (!err) { req.user.profile.displayName = user.body.displayName; req.user.profile.emails = [{ address: user.body.mail || user.body.userPrincipalName }]; renderSendMail(req, res); } else { renderError(err, res); } }); }); // Load the sendMail page. function renderSendMail(req, res) { res.render('sendMail', { display_name: req.user.profile.displayName, email_address: req.user.profile.emails[0].address }); } // Do prep before building the email message. // The message contains a file attachment and embeds a sharing link to the file in the message body. function prepForEmailMessage(req, callback) { const accessToken = req.user.accessToken; const displayName = req.user.profile.displayName; const destinationEmailAddress = req.body.default_email; // Get the current user's profile photo. graphHelper.getProfilePhoto(accessToken, (errPhoto, profilePhoto) => { // //// TODO: MSA flow with local file (using fs and path?) if (!errPhoto) { // Upload profile photo as file to OneDrive. graphHelper.uploadFile(accessToken, profilePhoto, (errFile, file) => { // Get sharingLink for file. graphHelper.getSharingLink(accessToken, file.id, (errLink, link) => { const mailBody = emailer.generateMailBody( displayName, destinationEmailAddress, link.webUrl, profilePhoto ); callback(null, mailBody); }); }); } else { var fs = require('fs'); var readableStream = fs.createReadStream('public/img/test.jpg'); var picFile; var chunk; readableStream.on('readable', function() { while ((chunk=readableStream.read()) != null) { picFile = chunk; } }); readableStream.on('end', function() { graphHelper.uploadFile(accessToken, picFile, (errFile, file) => { // Get sharingLink for file. graphHelper.getSharingLink(accessToken, file.id, (errLink, link) => { const mailBody = emailer.generateMailBody( displayName, destinationEmailAddress, link.webUrl, picFile ); callback(null, mailBody); }); }); }); } }); } // Send an email. router.post('/sendMail', (req, res) => { const response = res; const templateData = { display_name: req.user.profile.displayName, email_address: req.user.profile.emails[0].address, actual_recipient: req.body.default_email }; prepForEmailMessage(req, (errMailBody, mailBody) => { if (errMailBody) renderError(errMailBody); graphHelper.postSendMail(req.user.accessToken, JSON.stringify(mailBody), (errSendMail) => { if (!errSendMail) { response.render('sendMail', templateData); } else { if (hasAccessTokenExpired(errSendMail)) { errSendMail.message += ' Expired token. Please sign out and sign in again.'; } renderError(errSendMail, response); } }); }); }); router.get('/disconnect', (req, res) => { req.session.destroy(() => { req.logOut(); res.clearCookie('graphNodeCookie'); res.status(200); res.redirect('/'); }); }); // helpers function hasAccessTokenExpired(e) { let expired; if (!e.innerError) { expired = false; } else { expired = e.forbidden && e.message === 'InvalidAuthenticationToken' && e.response.error.message === 'Access token has expired.'; } return expired; } /** * * @param {*} e * @param {*} res */ function renderError(e, res) { e.innerError = (e.response) ? e.response.text : ''; res.render('error', { error: e }); } module.exports = router;
microsoftgraph/nodejs-connect-rest-sample
routes/index.js
JavaScript
mit
5,258
(function($,window){ })(Zepto,window);
picacure/_sandBox
funny/shapeSpot/js/dev/primary.js
JavaScript
mit
39
module.exports = require('./src/angularjs-dependencies-wrapper');
StarterSquad/angularjs-dependencies-wrapper
index.js
JavaScript
mit
65
////////////////////////////////////////////////////////////////////////// // // // This is a generated file. You can view the original // // source in your browser if your browser supports source maps. // // // // If you are using Chrome, open the Developer Tools and click the gear // // icon in its lower right corner. In the General Settings panel, turn // // on 'Enable source maps'. // // // // If you are using Firefox 23, go to `about:config` and set the // // `devtools.debugger.source-maps-enabled` preference to true. // // (The preference should be on by default in Firefox 24; versions // // older than 23 do not support source maps.) // // // ////////////////////////////////////////////////////////////////////////// (function () { /* Imports */ var Meteor = Package.meteor.Meteor; var TAPi18next = Package['tap:i18n'].TAPi18next; var TAPi18n = Package['tap:i18n'].TAPi18n; var Session = Package.session.Session; /* Package-scope variables */ var i18n, setLanguage; (function () { /////////////////////////////////////////////////////////////////////////////// // // // packages/telescope-i18n/i18n.js // // // /////////////////////////////////////////////////////////////////////////////// // // do this better: // 1 setLanguage = function (language) { // 2 // Session.set('i18nReady', false); // 3 // console.log('i18n loading… '+language) // 4 // 5 // moment // 6 Session.set('momentReady', false); // 7 // console.log('moment loading…') // 8 if (language.toLowerCase() === "en") { // 9 Session.set('momentReady', true); // 10 } else { // 11 $.getScript("//cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/lang/" + language.toLowerCase() + ".js", function (result) { moment.locale(language); // 13 Session.set('momentReady', true); // 14 Session.set('momentLocale', language); // 15 // console.log('moment loaded!') // 16 }); // 17 } // 18 // 19 // TAPi18n // 20 Session.set("TAPi18nReady", false); // 21 // console.log('TAPi18n loading…') // 22 TAPi18n.setLanguage(language) // 23 .done(function () { // 24 Session.set("TAPi18nReady", true); // 25 // console.log('TAPi18n loaded!') // 26 }); // 27 // 28 // T9n // 29 T9n.setLanguage(language); // 30 } // 31 // 32 i18n = { // 33 t: function (str, options) { // 34 if (Meteor.isServer) { // 35 return TAPi18n.__(str, options, Settings.get('language', 'en')); // 36 } else { // 37 return TAPi18n.__(str, options); // 38 } // 39 } // 40 }; // 41 // 42 Meteor.startup(function () { // 43 // 44 if (Meteor.isClient) { // 45 // 46 // doesn't quite work yet // 47 // Tracker.autorun(function (c) { // 48 // console.log('momentReady',Session.get('momentReady')) // 49 // console.log('i18nReady',Session.get('i18nReady')) // 50 // var ready = Session.get('momentReady') && Session.get('i18nReady'); // 51 // if (ready) { // 52 // Session.set('i18nReady', true); // 53 // Session.set('locale', language); // 54 // console.log('i18n ready! '+language) // 55 // } // 56 // }); // 57 // 58 setLanguage(Settings.get('language', 'en')); // 59 } // 60 // 61 }); // 62 // 63 /////////////////////////////////////////////////////////////////////////////// }).call(this); /* Exports */ if (typeof Package === 'undefined') Package = {}; Package['telescope-i18n'] = { i18n: i18n, setLanguage: setLanguage }; })();
firstchair/klussenbank
.meteor/local copy/build/programs/web.browser/packages/telescope-i18n.js
JavaScript
mit
7,388
describe('async methods', () => { it('commits multiple valid inserts to the database', done => { const methodUnderTest = async (unitOfWork) => { const insert = { method: 'insert' }; await new unitOfWork.Users(getUserWithEmail('1')).save(null, insert); await new unitOfWork.Users(getUserWithEmail('2')).save(null, insert); await new unitOfWork.Users(getUserWithEmail('3')).save(null, insert); }; new SomeService(methodUnderTest) .runMethodUnderTest() .then(() => bookshelf.Users.count()) .then(count => expect(count).to.equal('3')) .then(() => done(), done); }) });
royriojas/esformatter-jsx
specs/fixtures/bug-44.js
JavaScript
mit
686
'use strict'; var CurrentCourseStore = require('../../../js/stores/CurrentCourseStore'); var CourseActions = require('../../../js/actions/CourseActions'); require('../../../utils/createAuthenticatedSuite')('Store: CurrentCourse', function() { it('should be empty on init', function(done) { (CurrentCourseStore.course === null).should.be.true; // jshint ignore:line done(); }); it('should set course on action', function(done) { var course = { id: 1 }; CourseActions.setCourse(course, function(err) { (err === null).should.be.true; // jshint ignore:line CurrentCourseStore.course.should.be.instanceOf(Object); CurrentCourseStore.course.id.should.equal(1); done(); }); }); it('should load a course on action', function(done) { CourseActions.openCourse(1, function(err) { (err === null).should.be.true; // jshint ignore:line CurrentCourseStore.course.should.be.instanceOf(Object); CurrentCourseStore.course.id.should.equal(1); CurrentCourseStore.course.should.have.property('title'); CurrentCourseStore.course.should.have.property('slug'); CurrentCourseStore.course.should.have.property('description'); done(); }); }); it('should create a new lesson on action', function(done) { var lesson = { title: 'lesson to test creation', description: 'test description', bodyElements: [] }; // Make sure `this.course` is set in store before attempting to access `this.course.id` CourseActions.setCourse({ id: 1 }, function() { CourseActions.createLesson(lesson, function(err, lesson) { console.log('error creating lesson:', err); (err === null).should.be.true; // jshint ignore:line lesson.should.be.instanceOf(Object); lesson.should.have.property('title'); lesson.should.have.property('description'); lesson.should.have.property('bodyElements'); done(); }); }); }); });
jakemmarsh/acadeME
js/__tests__/stores/CurrentCourseStore.spec.js
JavaScript
mit
1,997
export * from './PythonHome'; export * from './PythonNav';
EdwardRees/EdwardRees.github.io
static/programming-tutorials-backup/src/languages/python/index.js
JavaScript
mit
59
const JSONBox = require("../JSONBox"); const rmdir = require("rmdir"); const appRootDir = require("app-root-dir"); const Q = require("q"); const path = require("path"); const async = require("asyncawait/async"); const await = require("asyncawait/await"); const expect = require("chai").expect; const fs = require("fs"); const mkdirp = require("mkdirp"); const sinon = require("sinon"); const uuid = require("uuid"); const assign = require("lodash.assign"); const testDir = "store-test"; const createMockData = async(function() { this.obj = { id: "76ba67b8-7907-11e6-8b77-86f30ca893d3", some: "data", is: "cool" }; this.obj2 = { id: "bc7e5fb6-7907-11e6-8b77-86f30ca893d3", muchas: "gracias" }; await(Q.nfcall(mkdirp ,path.join(appRootDir.get(), testDir))); fs.writeFileSync(path.join(appRootDir.get(), testDir, `${this.obj.id}.json`), JSON.stringify(this.obj), { flag: "w+" }); fs.writeFileSync(path.join(appRootDir.get(), testDir, `${this.obj2.id}.json`), JSON.stringify(this.obj2), { flag: "w+" }); }); describe("JSONBox", function() { before(function() { this.uuid = sinon.stub(uuid, "v4").returns("53ccfe14-7916-11e6-8b77-86f30ca893d3"); }); after(function() { this.uuid.restore(); }) afterEach(function(done) { Q.nfcall(rmdir, path.join(appRootDir.get(), testDir)) .then(() => done()) .catch(() => done()); }); it("Get all entries (callback style)", function(done) { createMockData.call(this) .then(() => { const box = JSONBox.of({ name: testDir }); const expected = [this.obj, this.obj2]; box.all(function(error, data) { if(error) done(error); expect(data).to.eql(expected); done(); }); }); }); it("Get all entries (promise style)", function(done) { createMockData.call(this) .then(() => { const box = JSONBox.of({ name: testDir }); return box.all(); }) .then(data => { expect(data).to.eql([this.obj, this.obj2]); done(); }) .catch(done); }); it("Get a single entry (callback style)", function(done) { createMockData.call(this) .then(() => { const box = JSONBox.of({ name: testDir }); box.get(this.obj.id, function(error, data) { if(error) done(error); expect(data).to.eql(this.obj); done(); }.bind(this)); }); }); it("Get a single entry (promise style)", function(done) { createMockData.call(this) .then(() => { const box = JSONBox.of({ name: testDir }); return box.get(this.obj.id); }) .then(data => { expect(data).to.eql(this.obj); done(); }) .catch(done); }); it("Store an entry (callback style)", function(done) { const box = JSONBox.of({ name: testDir }); const storable = { abc: 123, def: "456" }; box.store(storable, function(error, data) { if(error) done(error); expect(data).to.eql(assign({}, data, { id: "53ccfe14-7916-11e6-8b77-86f30ca893d3" })); done(); }.bind(this)); }); it("Store an entry (promise style)", function(done) { const box = JSONBox.of({ name: testDir }); const storable = { abc: 123, def: "456" }; box.store(storable) .then(data => { expect(data).to.eql(assign({}, data, { id: "53ccfe14-7916-11e6-8b77-86f30ca893d3" })); done(); }) .catch(done); }); it("Store an null entry (callback style), expect Error", function(done) { const box = JSONBox.of({ name: testDir }); box.store(null, function(error, data) { if(error) done(); else done(new Error("Expected to throw an Error!")); }); }); it("Store an null entry (promise style), expect Error", function(done) { const box = JSONBox.of({ name: testDir }); box.store(null) .then(data => done(new Error("Expected to throw an Error!"))) .catch(() => done()); }); it("Deletes an entry (callback style)", function(done) { createMockData.call(this) .then(() => { const box = JSONBox.of({ name: testDir }); box.delete(this.obj, function(error) { if(error) done(error); done(); }.bind(this)); }); }); it("Deletes an entry (promise style)", function(done) { createMockData.call(this) .then(() => { const box = JSONBox.of({ name: testDir }); box.delete(this.obj.id) .then(() => done()) .catch(done); }); }); });
nikonovd/jsonbox
lib/__tests__/JSONBoxTest.js
JavaScript
mit
5,677
const SafeHarborModules = require('./SafeHarborModules'); const SafeHarborInverters = require('./SafeHarborInverters'); module.exports = () => { SafeHarborModules(); SafeHarborInverters(); }
kennethchatfield/rule-evaluator
test/AppliedRule/Filters/SafeHarborFilters/testAll.js
JavaScript
mit
201
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('tallytextApp')); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
willynilly/tallytext
test/spec/controllers/main.js
JavaScript
mit
508
'use strict' const React = require('react'); import {Sidebar} from 'react-semantify'; const UISidebar = React.createClass({ render : function() { return ( <Sidebar className="ui top sidebar menu push scale down" init={true}> <a className="item"> Our company </a> <a className="item"> Dashboard </a> <a className="item"> My recipes </a> <a href="/logout" className="item right floated"> Logout </a> </Sidebar> ) } }); module.exports = UISidebar;
douglaswissett/burntFood
public/js/components/sidebar.js
JavaScript
mit
574
const express = require('express'); const app = express(); const port = 8080; app.get('/', (req, res) => { res.send('Hello World\n'); }); app.listen(port, () => { console.log(`application is listening on port ${port}...`); });
JaeGyu/PythonEx_1
web/app1/app.js
JavaScript
mit
238
/*! Backstretch - v2.0.4 - 2013-06-19 * http://srobbin.com/jquery-plugins/backstretch/ * Copyright (c) 2013 Scott Robbin; Licensed MIT */ (function (a, d, p) { a.fn.backstretch = function (c, b) { (c === p || 0 === c.length) && a.error("No images were supplied for Backstretch"); 0 === a(d).scrollTop() && d.scrollTo(0, 0); return this.each(function () { var d = a(this), g = d.data("backstretch"); if (g) { if ("string" == typeof c && "function" == typeof g[c]) { g[c](b); return } b = a.extend(g.options, b); g.destroy(!0) } g = new q(this, c, b); d.data("backstretch", g) }) }; a.backstretch = function (c, b) { return a("body").backstretch(c, b).data("backstretch") }; a.expr[":"].backstretch = function (c) { return a(c).data("backstretch") !== p }; a.fn.backstretch.defaults = {centeredX: !0, centeredY: !0, duration: 5E3, fade: 0}; var r = {left: 0, top: 0, overflow: "hidden", margin: 0, padding: 0, height: "100%", width: "100%", zIndex: -999999}, s = {position: "absolute", display: "none", margin: 0, padding: 0, border: "none", width: "auto", height: "auto", maxHeight: "none", maxWidth: "none", zIndex: -999999}, q = function (c, b, e) { this.options = a.extend({}, a.fn.backstretch.defaults, e || {}); this.images = a.isArray(b) ? b : [b]; a.each(this.images, function () { a("<img />")[0].src = this }); this.isBody = c === document.body; this.$container = a(c); this.$root = this.isBody ? l ? a(d) : a(document) : this.$container; c = this.$container.children(".backstretch").first(); this.$wrap = c.length ? c : a('<div class="backstretch"></div>').css(r).appendTo(this.$container); this.isBody || (c = this.$container.css("position"), b = this.$container.css("zIndex"), this.$container.css({position: "static" === c ? "relative" : c, zIndex: "auto" === b ? 0 : b, background: "none"}), this.$wrap.css({zIndex: -999998})); this.$wrap.css({position: this.isBody && l ? "fixed" : "absolute"}); this.index = 0; this.show(this.index); a(d).on("resize.backstretch", a.proxy(this.resize, this)).on("orientationchange.backstretch", a.proxy(function () { this.isBody && 0 === d.pageYOffset && (d.scrollTo(0, 1), this.resize()) }, this)) }; q.prototype = {resize: function () { try { var a = {left: 0, top: 0}, b = this.isBody ? this.$root.width() : this.$root.innerWidth(), e = b, g = this.isBody ? d.innerHeight ? d.innerHeight : this.$root.height() : this.$root.innerHeight(), j = e / this.$img.data("ratio"), f; j >= g ? (f = (j - g) / 2, this.options.centeredY && (a.top = "-" + f + "px")) : (j = g, e = j * this.$img.data("ratio"), f = (e - b) / 2, this.options.centeredX && (a.left = "-" + f + "px")); this.$wrap.css({width: b, height: g}).find("img:not(.deleteable)").css({width: e, height: j}).css(a) } catch (h) { } return this }, show: function (c) { if (!(Math.abs(c) > this.images.length - 1)) { var b = this, e = b.$wrap.find("img").addClass("deleteable"), d = {relatedTarget: b.$container[0]}; b.$container.trigger(a.Event("backstretch.before", d), [b, c]); this.index = c; clearInterval(b.interval); b.$img = a("<img />").css(s).bind("load",function (f) { var h = this.width || a(f.target).width(); f = this.height || a(f.target).height(); a(this).data("ratio", h / f); a(this).fadeIn(b.options.speed || b.options.fade, function () { e.remove(); b.paused || b.cycle(); a(["after", "show"]).each(function () { b.$container.trigger(a.Event("backstretch." + this, d), [b, c]) }) }); b.resize() }).appendTo(b.$wrap); b.$img.attr("src", b.images[c]); return b } }, next: function () { return this.show(this.index < this.images.length - 1 ? this.index + 1 : 0) }, prev: function () { return this.show(0 === this.index ? this.images.length - 1 : this.index - 1) }, pause: function () { this.paused = !0; return this }, resume: function () { this.paused = !1; this.next(); return this }, cycle: function () { 1 < this.images.length && (clearInterval(this.interval), this.interval = setInterval(a.proxy(function () { this.paused || this.next() }, this), this.options.duration)); return this }, destroy: function (c) { a(d).off("resize.backstretch orientationchange.backstretch"); clearInterval(this.interval); c || this.$wrap.remove(); this.$container.removeData("backstretch") }}; var l, f = navigator.userAgent, m = navigator.platform, e = f.match(/AppleWebKit\/([0-9]+)/), e = !!e && e[1], h = f.match(/Fennec\/([0-9]+)/), h = !!h && h[1], n = f.match(/Opera Mobi\/([0-9]+)/), t = !!n && n[1], k = f.match(/MSIE ([0-9]+)/), k = !!k && k[1]; l = !((-1 < m.indexOf("iPhone") || -1 < m.indexOf("iPad") || -1 < m.indexOf("iPod")) && e && 534 > e || d.operamini && "[object OperaMini]" === {}.toString.call(d.operamini) || n && 7458 > t || -1 < f.indexOf("Android") && e && 533 > e || h && 6 > h || "palmGetResource"in d && e && 534 > e || -1 < f.indexOf("MeeGo") && -1 < f.indexOf("NokiaBrowser/8.5.0") || k && 6 >= k) })(jQuery, window);
karlgroves/webcomponents-csun15
custom/js/jquery.backstretch.min.js
JavaScript
mit
5,794
'use strict'; var request = require('request') var uuid = require('node-uuid') var env = require('./env') var World = function World(callback) { var self = this this.collection = null this.lastResponse = null this.doc1 = null this.doc2 = null this.generateCollectionId = function() { this.collection = uuid.v1() } this.generateDocumentId = function() { // MongoDB either accepts a 12 byte string or 24 hex characters this.doc1 = uuid.v1().replace(/-/gi, '').substring(0,24) } this.get = function(path, callback) { var uri = this.uri(path) request.get(uri, function(error, response) { if (error) { return callback.fail(new Error('Error on GET request to ' + uri + ': ' + error.message)) } self.lastResponse = response callback() }) } this.post = function(path, requestBody, callback) { var uri = this.uri(path) request({url: uri, body: requestBody, method: 'POST'}, function(error, response) { if (error) { return callback(new Error('Error on POST request to ' + uri + ': ' + error.message)) } self.lastResponse = response callback(null, self.lastResponse.headers.location) }) } this.put = function(path, requestBody, callback) { var uri = this.uri(path) request({url: uri, body: requestBody, method: 'PUT'}, function(error, response) { if (error) { return callback(new Error('Error on PUT request to ' + uri + ': ' + error.message)) } self.lastResponse = response callback(null, self.lastResponse.headers.locations) }) } this.delete = function(path, callback) { var uri = this.uri(path) request({url: uri, method: 'DELETE'}, function(error, response) { if (error) { return callback(new Error('Error on DELETE request to ' + uri + ': ' + error.message)) } self.lastResponse = response callback() }) } this.options = function(path, callback) { var uri = this.uri(path) request({'uri': uri, method: 'OPTIONS'}, function(error, response) { if (error) { return callback.fail(new Error('Error on OPTIONS request to ' + uri + ': ' + error.message)) } self.lastResponse = response callback() }) } this.rootPath = function() { return '/' } this.rootUri = function() { return this.uri(this.rootPath()) } this.collectionPath = function(collection) { return '/' + collection } this.collectionUri = function(collection) { return this.uri(this.collectionPath(collection)) } this.documentPath = function(collection, document) { return this.collectionPath(collection) + '/' + document } this.documentUri = function(collection, document) { return this.uri(this.documentPath(collection, document)) } this.uri = function(path) { return env.BASE_URL + path } callback() } exports.World = World
basti1302/storra
features/support/world.js
JavaScript
mit
3,003
var gulp = require('gulp'); gulp.task('default', function() { console.log("Currently there are no available tasks. There will be!"); }); /** * Builds the client files into a jar and moves it to the 'build/client' folder. */ /* gulp.task('build-client', function() { return gulp.src('.') .pipe() // Build source/client/bin and data/client into a JAR. .pipe(gulp.dest('build/client')); }); */ /** * Builds the server files into a jar and moves it to the 'build/client' folder. */ /* gulp.task('build-server', function() { return gulp.src('.') .pipe() // Build source/server/bin and data/server into a JAR. .pipe(gulp.dest('build/server')); }); */
Jarinus/osrs-private-server
gulpfile.js
JavaScript
mit
662