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
/* * @version $Id: Uploader.js 10876 2013-05-30 06:23:01Z btowles $ * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2014 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ ((function(){if(!this.Uploader){this.Uploader={}; }this.Uploader=new Class({Implements:[Options,Events],options:{url:""},initialize:function(b,a){this.options.url=RokGallerySettings.url;this.setOptions(a); this.type=UploaderSupport.check();if(!this.type){return;}if(this.type=="Flash"){var c=RokGallerySettings.session;this.setOptions({url:this.options.url+"&"+RokGallerySettings.token+"=1&"+c.name+"="+c.id}); }this.element=document.id(b)||document.getElement("element");this.bounds={click:this.load.bind(this)};this.job=new Job({url:RokGallery.url,onError:function(d){this.instance.setJobText(d); }.bind(this),onBeforeCreate:function(){this.instance.setJobText("Creating Job...");}.bind(this),onCreate:function(d,e){this.instance.job=e;this.instance.setJobText("Uploading..."); this.instance.start();}.bind(this),onBeforeReady:function(){this.instance.setJobText("Waiting for the Job to be ready.");}.bind(this),onReady:function(d,f){this.instance.setJobText("Job is in ready state mode."); window.Popup.popup.getElement(".loading").setStyle("display","none");var e=new Element("canvas",{width:18,height:18,"class":"job-canvas"});e.inject(this.instance.jobsInfo,"before"); this.instance.canvasWrapper=new Element("div.job-canvas-wrapper").wraps(e);this.job.progress=new Progress(e);this.job.process();}.bind(this),onBeforeProcess:function(){this.instance.setJobText("Processing the uploaded files."); }.bind(this),onProcess:function(d){window.Popup.setPopup({buttons:{cancel:{label:"background"}}});window.Popup.popup.getElement(".button:last-child").setStyle("display","block"); if(RokGallery.uploader.type=="Flash"){window.Popup.popup.getElement(".button.cancel").setStyles({display:"block",position:"relative",visibility:"visible","float":"right"}); }this.timer=this.job.status.periodical(1000,this.job);this.job.status();}.bind(this),onBeforeStatus:function(){if(this.request.isRunning()){this.request.cancel(); }},onStatus:function(d){this.job.progress.set(d.payload.percent);this.instance.setJobText(d.payload.percent+"% - "+d.payload.status);if(d.payload.percent=="100"){clearTimeout(this.timer); this.job.complete();}return this.job;}.bind(this),onComplete:function(e){clearTimeout(this.timer);this.job.request.cancel();window.Popup.setPopup({type:"success",buttons:{cancel:{label:"close"}}}); window.Popup.popup.getElement(".button:last-child").setStyle("display","block");if(RokGallery.uploader.type=="Flash"){window.Popup.popup.getElement(".button.cancel").setStyles({display:"block",position:"relative",visibility:"visible","float":"right"}); }var d=this.type=="HTML5"?this.instance.files.length:this.instance.fileList.length;this.instance.jobsInfo.dispose();this.instance.canvasWrapper.dispose(); window.Popup.popup.getElement(".loading").setStyle("display","none");RokGallery.loadMore.refresh(d);}.bind(this)});this.attach();},attach:function(){this.element.addEvents(this.bounds); },detach:function(){this.element.removeEvents(this.bounds);},load:function(a){if(a){a.stop();}this.popup();this.instance=new Uploader[this.type]("files-status","files-list",this.options); if(this.type=="HTML5"){window.Popup.popup.addEvents({dragover:function(){var b=this.form.getElement(".drop-info"),c=b.set("morph",{link:"cancel"});b.addClass("drag-over"); }.bind(this.instance),dragleave:function(){this.form.getElement(".drop-info").removeClass("drag-over");}.bind(this.instance),drop:function(){this.form.getElement(".drop-info").removeClass("drag-over"); }.bind(this.instance)});}},popup:function(){var b=window.Popup,d;d=this.type=="Flash"?"<p>Click the Browse button and select the images you want to upload.</p><p>Once you are ready to upload, click the Upload button and keep track of the progress bars</p>":'<div class="drop-info">Drag &amp; Drop Files Here</div>'; b.setPopup({type:"",title:"Files Upload",message:'<form action="'+this.options.url+'" method="post" enctype="multipart/form-data" id="files-form"><div id="files-empty-desc">'+d+'</div><div id="files-status"><div class="total-progress"><canvas class="overall-progress" height="25" width="25"></canvas><div id="files-success"></div></div><div class="overall-title"></div><div class="current-text"></div></div><div id="files-list"></div></form>',buttons:{ok:{show:true,label:"upload"},cancel:{show:true,label:"close"}},"continue":function(){}}); var c=b.statusBar.getElement("div.button.browse.custom");if(!c){c=new Element("div#files-browse.button.browse.custom",{text:"browse"}).inject(b.statusBar.getElement(".clr"),"before"); }var a=b.topBar.getElement("div.counter");if(!a){a=new Element("div.counter",{html:"<span>0</span> files"}).inject(b.topBar.getElement(".icon"),"after"); }a.set("tween",{duration:200,transition:"quad:in:out",link:"chain"});b.counter=a;b.popup.addEvent("close:once",function(){var e=document.id("files-clear"); a.dispose();document.id("files-browse").dispose();document.getElements("#popup .job-canvas-wrapper, #popup .job-info").dispose();if(e){e.dispose();}}.bind(this)); b.open();},onBeforeUnload:function(a){var b=b||window.event,a=a||"You are about to leave this page and any unsaved changed will be lost. Are you sure you want to continue?"; if(b){b.returnValue=a;}return a;},attachUnload:function(a){window.onbeforeunload=this.onBeforeUnload.pass(a);},detachUnload:function(){window.onbeforeunload=function(){}; }});window.addEvent("domready",function(){UploaderSupport.load(RokGallerySettings.application);});Object.append(this.Uploader,{STATUS_QUEUED:0,STATUS_RUNNING:1,STATUS_ERROR:2,STATUS_COMPLETE:3,STATUS_STOPPED:4,log:function(){if(window.console&&console.info){console.info.apply(console,arguments); }},unitLabels:{b:[{min:1,unit:"B"},{min:1024,unit:"KB"},{min:1048576,unit:"MB"},{min:1073741824,unit:"GB"}],s:[{min:1,unit:"s"},{min:60,unit:"m"},{min:3600,unit:"h"},{min:86400,unit:"d"}]},formatUnit:function(a,h,b){var f=Uploader.unitLabels[(h=="bps")?"b":h]; var c=(h=="bps")?"/s":"";var e,d=f.length,j;if(a<1){return"0 "+f[0].unit+c;}if(h=="s"){var g=[];for(e=d-1;e>=0;e--){j=Math.floor(a/f[e].min);if(j){g.push(j+" "+f[e].unit); a-=j*f[e].min;if(!a){break;}}}return(b===false)?g:g.join(b||", ");}for(e=d-1;e>=0;e--){j=f[e].min;if(a>=j){break;}}return(a/j).toFixed(2)+" "+f[e].unit+c; }});})());
JamesBurnside/uobtennis
administrator/components/com_rokgallery/assets/application/joomla/2.5/Uploader.js
JavaScript
gpl-2.0
6,471
/** * @copyright 2010-2015, The Titon Project * @license http://opensource.org/licenses/BSD-3-Clause * @link http://titon.io */ define([ 'jquery', './toolkit' ], function($, Toolkit) { // Empty class to extend from var Class = Toolkit.Class = function() {}; // Flag to determine if a constructor is initializing var constructing = false; /** * Very basic method for allowing functions to inherit functionality through the prototype. * * @param {Object} properties * @param {Object} options * @returns {Function} */ Class.extend = function(properties, options) { constructing = true; var prototype = new this(); constructing = false; // Inherit the prototype and merge properties $.extend(prototype, properties); // Fetch the constructor function before setting the prototype var constructor = prototype.constructor; // Class interface function Class() { // Exit constructing if being applied as prototype if (constructing) { return; } // Reset (clone) the array and object properties else they will be referenced between instances for (var key in this) { var value = this[key], type = $.type(value); if (type === 'array') { this[key] = value.slice(0); // Clone array } else if (type === 'object') { this[key] = $.extend(true, {}, value); // Clone object } } // Set the UID and increase global count this.uid = Class.count += 1; // Generate the CSS class name and attribute/event name based off the plugin name var name = this.name; if (name) { this.cssClass = name.replace(/[A-Z]/g, function(match) { return ('-' + match.charAt(0).toLowerCase()); }).slice(1); // Generate an attribute and event key name based off the plugin name this.keyName = name.charAt(0).toLowerCase() + name.slice(1); } // Trigger constructor if (constructor) { constructor.apply(this, arguments); } } // Inherit the prototype Class.prototype = prototype; Class.prototype.constructor = constructor || Class; // Inherit and set default options Class.options = $.extend(true, {}, this.options || {}, options || {}); // Inherit the extend method Class.extend = this.extend; // Count of total instances Class.count = 0; return Class; }; return Class; });
localymine/multisite
wp-content/themes/kodomo/html/toolkit-3.0/js/class.js
JavaScript
gpl-2.0
2,561
/* YUI 3.7.1 (build 5627) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('charts', function (Y, NAME) { /** * The Chart class is the basic application used to create a chart. * * @module charts * @class Chart * @constructor */ function Chart(cfg) { if(cfg.type != "pie") { return new Y.CartesianChart(cfg); } else { return new Y.PieChart(cfg); } } Y.Chart = Chart; }, '3.7.1', {"requires": ["charts-base"]});
medbenhenda/migration-ez5
ezpublish_legacy/extension/ezjscore/design/standard/lib/yui/3.7.1/build/charts/charts.js
JavaScript
gpl-2.0
533
YUI.add('moodle-mod_quiz-dragdrop', function (Y, NAME) { /** * Drag and Drop for Quiz sections and slots. * * @module moodle-mod-quiz-dragdrop */ var CSS = { ACTIONAREA: '.actions', ACTIVITY: 'activity', ACTIVITYINSTANCE: 'activityinstance', CONTENT: 'content', COURSECONTENT: 'mod-quiz-edit-content', EDITINGMOVE: 'editing_move', ICONCLASS: 'iconsmall', JUMPMENU: 'jumpmenu', LEFT: 'left', LIGHTBOX: 'lightbox', MOVEDOWN: 'movedown', MOVEUP: 'moveup', PAGE : 'page', PAGECONTENT: 'page-content', RIGHT: 'right', SECTION: 'section', SECTIONADDMENUS: 'section_add_menus', SECTIONHANDLE: 'section-handle', SLOTS: 'slots', SUMMARY: 'summary', SECTIONDRAGGABLE: 'sectiondraggable' }, // The CSS selectors we use. SELECTOR = { PAGE: 'li.page', SLOT: 'li.slot' }; /** * Section drag and drop. * * @class M.mod_quiz.dragdrop.section * @constructor * @extends M.core.dragdrop */ var DRAGSECTION = function() { DRAGSECTION.superclass.constructor.apply(this, arguments); }; Y.extend(DRAGSECTION, M.core.dragdrop, { sectionlistselector: null, initializer: function() { // Set group for parent class this.groups = [ CSS.SECTIONDRAGGABLE ]; this.samenodeclass = M.mod_quiz.edit.get_sectionwrapperclass(); this.parentnodeclass = M.mod_quiz.edit.get_containerclass(); // Check if we are in single section mode if (Y.Node.one('.' + CSS.JUMPMENU)) { return false; } // Initialise sections dragging this.sectionlistselector = M.mod_quiz.edit.get_section_wrapper(Y); if (this.sectionlistselector) { this.sectionlistselector = '.' + CSS.COURSECONTENT + ' ' + this.sectionlistselector; this.setup_for_section(this.sectionlistselector); // Make each li element in the lists of sections draggable var del = new Y.DD.Delegate({ container: '.' + CSS.COURSECONTENT, nodes: '.' + CSS.SECTIONDRAGGABLE, target: true, handles: ['.' + CSS.LEFT], dragConfig: {groups: this.groups} }); del.dd.plug(Y.Plugin.DDProxy, { // Don't move the node at the end of the drag moveOnEnd: false }); del.dd.plug(Y.Plugin.DDConstrained, { // Keep it inside the .mod-quiz-edit-content constrain: '#' + CSS.PAGECONTENT, stickY: true }); del.dd.plug(Y.Plugin.DDWinScroll); } }, /** * Apply dragdrop features to the specified selector or node that refers to section(s) * * @method setup_for_section * @param {String} baseselector The CSS selector or node to limit scope to */ setup_for_section: function(baseselector) { Y.Node.all(baseselector).each(function(sectionnode) { // Determine the section ID var sectionid = Y.Moodle.core_course.util.section.getId(sectionnode); // We skip the top section as it is not draggable if (sectionid > 0) { // Remove move icons var movedown = sectionnode.one('.' + CSS.RIGHT + ' a.' + CSS.MOVEDOWN); var moveup = sectionnode.one('.' + CSS.RIGHT + ' a.' + CSS.MOVEUP); // Add dragger icon var title = M.util.get_string('movesection', 'moodle', sectionid); var cssleft = sectionnode.one('.' + CSS.LEFT); if ((movedown || moveup) && cssleft) { cssleft.setStyle('cursor', 'move'); cssleft.appendChild(this.get_drag_handle(title, CSS.SECTIONHANDLE, 'icon', true)); if (moveup) { moveup.remove(); } if (movedown) { movedown.remove(); } // This section can be moved - add the class to indicate this to Y.DD. sectionnode.addClass(CSS.SECTIONDRAGGABLE); } } }, this); }, /* * Drag-dropping related functions */ drag_start: function(e) { // Get our drag object var drag = e.target; // Creat a dummy structure of the outer elemnents for clean styles application var containernode = Y.Node.create('<' + M.mod_quiz.edit.get_containernode() + '></' + M.mod_quiz.edit.get_containernode() + '>'); containernode.addClass(M.mod_quiz.edit.get_containerclass()); var sectionnode = Y.Node.create('<' + M.mod_quiz.edit.get_sectionwrappernode() + '></' + M.mod_quiz.edit.get_sectionwrappernode() + '>'); sectionnode.addClass( M.mod_quiz.edit.get_sectionwrapperclass()); sectionnode.setStyle('margin', 0); sectionnode.setContent(drag.get('node').get('innerHTML')); containernode.appendChild(sectionnode); drag.get('dragNode').setContent(containernode); drag.get('dragNode').addClass(CSS.COURSECONTENT); }, drag_dropmiss: function(e) { // Missed the target, but we assume the user intended to drop it // on the last last ghost node location, e.drag and e.drop should be // prepared by global_drag_dropmiss parent so simulate drop_hit(e). this.drop_hit(e); }, get_section_index: function(node) { var sectionlistselector = '.' + CSS.COURSECONTENT + ' ' + M.mod_quiz.edit.get_section_selector(Y), sectionList = Y.all(sectionlistselector), nodeIndex = sectionList.indexOf(node), zeroIndex = sectionList.indexOf(Y.one('#section-0')); return (nodeIndex - zeroIndex); }, drop_hit: function(e) { var drag = e.drag; // Get references to our nodes and their IDs. var dragnode = drag.get('node'), dragnodeid = Y.Moodle.core_course.util.section.getId(dragnode), loopstart = dragnodeid, dropnodeindex = this.get_section_index(dragnode), loopend = dropnodeindex; if (dragnodeid === dropnodeindex) { return; } if (loopstart > loopend) { // If we're going up, we need to swap the loop order // because loops can't go backwards. loopstart = dropnodeindex; loopend = dragnodeid; } // Get the list of nodes. drag.get('dragNode').removeClass(CSS.COURSECONTENT); var sectionlist = Y.Node.all(this.sectionlistselector); // Add a lightbox if it's not there. var lightbox = M.util.add_lightbox(Y, dragnode); // Handle any variables which we must pass via AJAX. var params = {}, pageparams = this.get('config').pageparams, varname; for (varname in pageparams) { if (!pageparams.hasOwnProperty(varname)) { continue; } params[varname] = pageparams[varname]; } // Prepare request parameters params.sesskey = M.cfg.sesskey; params.courseid = this.get('courseid'); params.quizid = this.get('quizid'); params['class'] = 'section'; params.field = 'move'; params.id = dragnodeid; params.value = dropnodeindex; // Perform the AJAX request. var uri = M.cfg.wwwroot + this.get('ajaxurl'); Y.io(uri, { method: 'POST', data: params, on: { start: function() { lightbox.show(); }, success: function(tid, response) { // Update section titles, we can't simply swap them as // they might have custom title try { var responsetext = Y.JSON.parse(response.responseText); if (responsetext.error) { new M.core.ajaxException(responsetext); } M.mod_quiz.edit.process_sections(Y, sectionlist, responsetext, loopstart, loopend); } catch (e) {} // Update all of the section IDs - first unset them, then set them // to avoid duplicates in the DOM. var index; // Classic bubble sort algorithm is applied to the section // nodes between original drag node location and the new one. var swapped = false; do { swapped = false; for (index = loopstart; index <= loopend; index++) { if (Y.Moodle.core_course.util.section.getId(sectionlist.item(index - 1)) > Y.Moodle.core_course.util.section.getId(sectionlist.item(index))) { // Swap section id. var sectionid = sectionlist.item(index - 1).get('id'); sectionlist.item(index - 1).set('id', sectionlist.item(index).get('id')); sectionlist.item(index).set('id', sectionid); // See what format needs to swap. M.mod_quiz.edit.swap_sections(Y, index - 1, index); // Update flag. swapped = true; } } loopend = loopend - 1; } while (swapped); window.setTimeout(function() { lightbox.hide(); }, 250); }, failure: function(tid, response) { this.ajax_failure(response); lightbox.hide(); } }, context:this }); } }, { NAME: 'mod_quiz-dragdrop-section', ATTRS: { courseid: { value: null }, quizid: { value: null }, ajaxurl: { value: 0 }, config: { value: 0 } } }); M.mod_quiz = M.mod_quiz || {}; M.mod_quiz.init_section_dragdrop = function(params) { new DRAGSECTION(params); }; /** * Resource drag and drop. * * @class M.course.dragdrop.resource * @constructor * @extends M.core.dragdrop */ var DRAGRESOURCE = function() { DRAGRESOURCE.superclass.constructor.apply(this, arguments); }; Y.extend(DRAGRESOURCE, M.core.dragdrop, { initializer: function() { // Set group for parent class this.groups = ['resource']; this.samenodeclass = CSS.ACTIVITY; this.parentnodeclass = CSS.SECTION; //this.resourcedraghandle = this.get_drag_handle(M.util.get_string('movecoursemodule', 'moodle'), CSS.EDITINGMOVE, CSS.ICONCLASS, true); this.resourcedraghandle = this.get_drag_handle(M.str.moodle.move, CSS.EDITINGMOVE, CSS.ICONCLASS, true); this.samenodelabel = { identifier: 'dragtoafter', component: 'quiz' }; this.parentnodelabel = { identifier: 'dragtostart', component: 'quiz' }; // Go through all sections var sectionlistselector = M.mod_quiz.edit.get_section_selector(Y); if (sectionlistselector) { sectionlistselector = '.' + CSS.COURSECONTENT + ' ' + sectionlistselector; this.setup_for_section(sectionlistselector); // Initialise drag & drop for all resources/activities var nodeselector = sectionlistselector.slice(CSS.COURSECONTENT.length + 2) + ' li.' + CSS.ACTIVITY; var del = new Y.DD.Delegate({ container: '.' + CSS.COURSECONTENT, nodes: nodeselector, target: true, handles: ['.' + CSS.EDITINGMOVE], dragConfig: {groups: this.groups} }); del.dd.plug(Y.Plugin.DDProxy, { // Don't move the node at the end of the drag moveOnEnd: false, cloneNode: true }); del.dd.plug(Y.Plugin.DDConstrained, { // Keep it inside the .mod-quiz-edit-content constrain: '#' + CSS.SLOTS }); del.dd.plug(Y.Plugin.DDWinScroll); M.mod_quiz.quizbase.register_module(this); M.mod_quiz.dragres = this; } }, /** * Apply dragdrop features to the specified selector or node that refers to section(s) * * @method setup_for_section * @param {String} baseselector The CSS selector or node to limit scope to */ setup_for_section: function(baseselector) { Y.Node.all(baseselector).each(function(sectionnode) { var resources = sectionnode.one('.' + CSS.CONTENT + ' ul.' + CSS.SECTION); // See if resources ul exists, if not create one. if (!resources) { resources = Y.Node.create('<ul></ul>'); resources.addClass(CSS.SECTION); sectionnode.one('.' + CSS.CONTENT + ' div.' + CSS.SUMMARY).insert(resources, 'after'); } resources.setAttribute('data-draggroups', this.groups.join(' ')); // Define empty ul as droptarget, so that item could be moved to empty list new Y.DD.Drop({ node: resources, groups: this.groups, padding: '20 0 20 0' }); // Initialise each resource/activity in this section this.setup_for_resource('#' + sectionnode.get('id') + ' li.' + CSS.ACTIVITY); }, this); }, /** * Apply dragdrop features to the specified selector or node that refers to resource(s) * * @method setup_for_resource * @param {String} baseselector The CSS selector or node to limit scope to */ setup_for_resource: function(baseselector) { Y.Node.all(baseselector).each(function(resourcesnode) { // Replace move icons var move = resourcesnode.one('a.' + CSS.EDITINGMOVE); if (move) { move.replace(this.resourcedraghandle.cloneNode(true)); } }, this); }, drag_start: function(e) { // Get our drag object var drag = e.target; drag.get('dragNode').setContent(drag.get('node').get('innerHTML')); drag.get('dragNode').all('img.iconsmall').setStyle('vertical-align', 'baseline'); }, drag_dropmiss: function(e) { // Missed the target, but we assume the user intended to drop it // on the last ghost node location, e.drag and e.drop should be // prepared by global_drag_dropmiss parent so simulate drop_hit(e). this.drop_hit(e); }, drop_hit: function(e) { var drag = e.drag; // Get a reference to our drag node var dragnode = drag.get('node'); var dropnode = e.drop.get('node'); // Add spinner if it not there var actionarea = dragnode.one(CSS.ACTIONAREA); var spinner = M.util.add_spinner(Y, actionarea); var params = {}; // Handle any variables which we must pass back through to var pageparams = this.get('config').pageparams; var varname; for (varname in pageparams) { params[varname] = pageparams[varname]; } // Prepare request parameters params.sesskey = M.cfg.sesskey; params.courseid = this.get('courseid'); params.quizid = this.get('quizid'); params['class'] = 'resource'; params.field = 'move'; params.id = Number(Y.Moodle.mod_quiz.util.slot.getId(dragnode)); params.sectionId = Y.Moodle.core_course.util.section.getId(dropnode.ancestor(M.mod_quiz.edit.get_section_wrapper(Y), true)); var previousslot = dragnode.previous(SELECTOR.SLOT); if (previousslot) { params.previousid = Number(Y.Moodle.mod_quiz.util.slot.getId(previousslot)); } var previouspage = dragnode.previous(SELECTOR.PAGE); if (previouspage) { params.page = Number(Y.Moodle.mod_quiz.util.page.getId(previouspage)); } // Do AJAX request var uri = M.cfg.wwwroot + this.get('ajaxurl'); Y.io(uri, { method: 'POST', data: params, on: { start: function() { this.lock_drag_handle(drag, CSS.EDITINGMOVE); spinner.show(); }, success: function(tid, response) { var responsetext = Y.JSON.parse(response.responseText); var params = {element: dragnode, visible: responsetext.visible}; M.mod_quiz.quizbase.invoke_function('set_visibility_resource_ui', params); Y.Moodle.mod_quiz.util.slot.reorder_slots(); this.unlock_drag_handle(drag, CSS.EDITINGMOVE); window.setTimeout(function() { spinner.hide(); }, 250); window.location.reload(true); }, failure: function(tid, response) { this.ajax_failure(response); this.unlock_drag_handle(drag, CSS.SECTIONHANDLE); spinner.hide(); window.location.reload(true); } }, context:this }); }, global_drop_over: function(e) { //Overriding parent method so we can stop the slots being dragged before the first page node. // Check that drop object belong to correct group. if (!e.drop || !e.drop.inGroup(this.groups)) { return; } // Get a reference to our drag and drop nodes. var drag = e.drag.get('node'), drop = e.drop.get('node'); // Save last drop target for the case of missed target processing. this.lastdroptarget = e.drop; // Are we dropping within the same parent node? if (drop.hasClass(this.samenodeclass)) { var where; if (this.goingup) { where = "before"; } else { where = "after"; } drop.insert(drag, where); } else if ((drop.hasClass(this.parentnodeclass) || drop.test('[data-droptarget="1"]')) && !drop.contains(drag)) { // We are dropping on parent node and it is empty if (this.goingup) { drop.append(drag); } else { drop.prepend(drag); } } this.drop_over(e); } }, { NAME: 'mod_quiz-dragdrop-resource', ATTRS: { courseid: { value: null }, quizid: { value: null }, ajaxurl: { value: 0 }, config: { value: 0 } } }); M.mod_quiz = M.mod_quiz || {}; M.mod_quiz.init_resource_dragdrop = function(params) { new DRAGRESOURCE(params); }; }, '@VERSION@', { "requires": [ "base", "node", "io", "dom", "dd", "dd-scroll", "moodle-core-dragdrop", "moodle-core-notification", "moodle-mod_quiz-quizbase", "moodle-mod_quiz-util", "moodle-course-util" ] });
Microsoft/moodle
mod/quiz/yui/build/moodle-mod_quiz-dragdrop/moodle-mod_quiz-dragdrop.js
JavaScript
gpl-3.0
19,635
var searchData= [ ['query',['query',['../classcoda_1_1db_1_1query.html',1,'coda::db']]] ];
ryjen/db
html/search/classes_8.js
JavaScript
gpl-3.0
93
if(!dojo._hasResource["dojox.collections.Stack"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dojox.collections.Stack"] = true; dojo.provide("dojox.collections.Stack"); dojo.require("dojox.collections._base"); dojox.collections.Stack=function(/* array? */arr){ // summary // returns an object of type dojox.collections.Stack var q=[]; if (arr) q=q.concat(arr); this.count=q.length; this.clear=function(){ // summary // Clear the internal array and reset the count q=[]; this.count=q.length; }; this.clone=function(){ // summary // Create and return a clone of this Stack return new dojox.collections.Stack(q); }; this.contains=function(/* object */o){ // summary // check to see if the stack contains object o for (var i=0; i<q.length; i++){ if (q[i] == o){ return true; // bool } } return false; // bool }; this.copyTo=function(/* array */ arr, /* int */ i){ // summary // copy the stack into array arr at index i arr.splice(i,0,q); }; this.forEach=function(/* function */ fn, /* object? */ scope){ // summary // functional iterator, following the mozilla spec. dojo.forEach(q, fn, scope); }; this.getIterator=function(){ // summary // get an iterator for this collection return new dojox.collections.Iterator(q); // dojox.collections.Iterator }; this.peek=function(){ // summary // Return the next item without altering the stack itself. return q[(q.length-1)]; // object }; this.pop=function(){ // summary // pop and return the next item on the stack var r=q.pop(); this.count=q.length; return r; // object }; this.push=function(/* object */ o){ // summary // Push object o onto the stack this.count=q.push(o); }; this.toArray=function(){ // summary // create and return an array based on the internal collection return [].concat(q); // array }; } }
235/gwt-odb-ui
src/net/pleso/odbui/public/js/dojo-release-1.0.2/dojox/collections/Stack.js
JavaScript
agpl-3.0
1,921
// Generated on 2014-04-25 using generator-angular 0.8.0 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Define the configuration for all the tasks grunt.initConfig({ // Project settings yeoman: { // configurable paths app: require('./bower.json').appPath || 'app', dist: 'dist' }, // Watches files for changes and runs tasks based on the changed files watch: { bower: { files: ['bower.json'], tasks: ['bowerInstall'] }, js: { files: ['<%= yeoman.app %>/scripts/{,*/}*.js'], tasks: ['newer:jshint:all'], options: { livereload: true } }, jsTest: { files: ['test/spec/{,*/}*.js'], tasks: ['newer:jshint:test', 'karma'] }, compass: { files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'], tasks: ['compass:server', 'autoprefixer'] }, gruntfile: { files: ['Gruntfile.js'], tasks: ['ngconstant:development'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ '<%= yeoman.app %>/{,*/}*.html', '.tmp/styles/{,*/}*.css', '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}' ] } }, // The actual grunt server settings connect: { options: { port: 9000, // Change this to '0.0.0.0' to access the server from outside. hostname: 'localhost', livereload: 35729 }, livereload: { options: { open: true, base: [ '.tmp', '<%= yeoman.app %>' ] } }, test: { options: { port: 9001, base: [ '.tmp', 'test', '<%= yeoman.app %>' ] } }, dist: { options: { base: '<%= yeoman.dist %>' } } }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: [ 'Gruntfile.js', '<%= yeoman.app %>/scripts/{,*/}*.js' ], test: { options: { jshintrc: 'test/.jshintrc' }, src: ['test/spec/{,*/}*.js'] } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= yeoman.dist %>/*', '!<%= yeoman.dist %>/.git*' ] }] }, server: '.tmp' }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['last 1 version'] }, dist: { files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] } }, // Automatically inject Bower components into the app bowerInstall: { app: { src: ['<%= yeoman.app %>/index.html'], ignorePath: '<%= yeoman.app %>/' }, sass: { src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'], ignorePath: '<%= yeoman.app %>/bower_components/' } }, // Compiles Sass to CSS and generates necessary files if requested compass: { options: { sassDir: '<%= yeoman.app %>/styles', cssDir: '.tmp/styles', generatedImagesDir: '.tmp/images/generated', imagesDir: '<%= yeoman.app %>/images', javascriptsDir: '<%= yeoman.app %>/scripts', fontsDir: '<%= yeoman.app %>/styles/fonts', importPath: '<%= yeoman.app %>/bower_components', httpImagesPath: '/images', httpGeneratedImagesPath: '/images/generated', httpFontsPath: '/styles/fonts', relativeAssets: false, assetCacheBuster: false, raw: 'Sass::Script::Number.precision = 10\n' }, dist: { options: { generatedImagesDir: '<%= yeoman.dist %>/images/generated' } }, server: { options: { debugInfo: true } } }, ngconstant: { options: { name: 'config', dest: '<%= yeoman.app %>/scripts/config.js' }, //targets development: { constants: { AppURLs: grunt.file.readJSON('app/config/dev-config.json') } }, production: { constants: { AppURLs: grunt.file.readJSON('app/config/prod-config.json') } } }, // Renames files for browser caching purposes rev: { dist: { files: { src: [ '<%= yeoman.dist %>/scripts/{,*/}*.js', '<%= yeoman.dist %>/styles/{,*/}*.css', '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}' ] } } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { html: '<%= yeoman.app %>/index.html', options: { dest: '<%= yeoman.dist %>', flow: { html: { steps: { js: ['concat', 'uglifyjs'], css: ['cssmin'] }, post: {} } } } }, // Performs rewrites based on rev and the useminPrepare configuration usemin: { html: ['<%= yeoman.dist %>/{,*/}*.html'], css: ['<%= yeoman.dist %>/styles/{,*/}*.css'], options: { dirs: ['<%= yeoman.dist %>'], basedir: '<%= yeoman.dist %>', assetsDirs: [ '<%= yeoman.dist %>', '<%= yeoman.dist %>/images' ] } }, // The following *-min tasks produce minified files in the dist folder cssmin: { }, imagemin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{app/images}*.{png,jpg,jpeg,gif}', dest: '<%= yeoman.dist %>/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{app/images}*.svg', dest: '<%= yeoman.dist %>/images' }] } }, htmlmin: { dist: { options: { collapseWhitespace: true, collapseBooleanAttributes: true, removeCommentsFromCDATA: true, removeOptionalTags: true }, files: [{ expand: true, cwd: '<%= yeoman.dist %>', src: ['*.html', 'views/{,*/}*.html'], dest: '<%= yeoman.dist %>' }] } }, // ngmin tries to make the code safe for minification automatically by // using the Angular long form for dependency injection. It doesn't work on // things like resolve or inject so those have to be done manually. ngmin: { dist: { files: [{ expand: true, cwd: '.tmp/concat/scripts', src: '*.js', dest: '.tmp/concat/scripts' }] } }, // Replace Google CDN references cdnify: { dist: { html: ['<%= yeoman.dist %>/*.html'] } }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', '*.html', 'views/{,*/}*.html', 'images/*.{webp,png,jpg,jpeg,gif}', 'styles/fonts/*' ] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/images', src: ['generated/*'] }] }, styles: { expand: true, cwd: '<%= yeoman.app %>/styles', dest: '.tmp/styles/', src: '{,*/}*.css' } }, //Text replace to replace bower paths to local paths replace: { bower_css: { src: ['<%= yeoman.dist %>/styles/*.css'], // includes files in dir overwrite: true, replacements: [ { from: '/bower_components/bootstrap/dist/fonts/', to: 'fonts/' }, { from: [ '/bower_components/bootstrap-sass-official/vendor/assets/fonts/bootstrap', '/bower_components/bootstrap-sass-official/assets/fonts/bootstrap/' ], to: 'fonts/' } ] } }, // Run some tasks in parallel to speed up the build process concurrent: { server: [ 'compass:server' ], test: [ 'compass' ], dist: [ 'compass:dist', 'imagemin', 'svgmin' ] }, // By default, your `index.html`'s <!-- Usemin block --> will take care of // minification. These next options are pre-configured if you do not wish // to use the Usemin blocks. // cssmin: { // dist: { // files: { // '<%= yeoman.dist %>/styles/main.css': [ // '.tmp/styles/{,*/}*.css', // '<%= yeoman.app %>/styles/{,*/}*.css' // ] // } // } // }, uglify: { options: { mangle: false } // dist: { // files: { // '<%= yeoman.dist %>/scripts/scripts.js': [ // '<%= yeoman.dist %>/scripts/scripts.js' // ] // } // } }, // concat: { // dist: {} // }, // Test settings karma: { unit: { configFile: 'karma.conf.js', singleRun: true } } }); grunt.loadNpmTasks('grunt-text-replace'); grunt.registerTask('serve', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'bowerInstall', 'concurrent:server', 'autoprefixer', 'connect:livereload', 'watch' ]); }); grunt.registerTask('test', [ 'clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'karma' ]); grunt.registerTask('build', [ 'clean:dist', 'bowerInstall', 'ngconstant:production', 'useminPrepare', 'concurrent:dist', 'autoprefixer', 'concat', 'ngmin', 'imagemin', 'copy:dist', 'cdnify', 'cssmin', 'concat', 'uglify', 'rev', 'usemin', 'htmlmin', 'replace' ]); grunt.registerTask('server', [ 'update-config-dev', 'serve:app' ]); grunt.registerTask('server-dist', [ 'serve:dist' ]); grunt.registerTask('update-config-dev', [ 'ngconstant:development' ]); grunt.registerTask('update-config-prod', [ 'ngconstant:production' ]); grunt.registerTask('default', [ 'newer:jshint', 'test', 'build' ]); };
gabriel-laet/somafm-webplayer
Gruntfile.js
JavaScript
apache-2.0
14,477
import readFile from 'itk/readFile' import curry from 'curry' const outputFileInformation = curry(function outputFileInformation (outputTextArea, event) { outputTextArea.textContent = 'Loading...' const dataTransfer = event.dataTransfer const files = event.target.files || dataTransfer.files const viewerElement = document.getElementById('viewer') !!viewerElement && itkVtkViewer.createViewerFromFiles(viewerElement, files) return readFile(null, files[0]) .then(function ({ image, mesh, polyData, webWorker }) { webWorker.terminate() const imageOrMeshOrPolyData = image || mesh || polyData function replacer (key, value) { if (!!value && value.byteLength !== undefined) { return String(value.slice(0, 6)) + '...' } return value } outputTextArea.textContent = JSON.stringify(imageOrMeshOrPolyData, replacer, 4) }) }) export { outputFileInformation }
InsightSoftwareConsortium/ITKBridgeJavaScript
examples/Webpack/src/index.js
JavaScript
apache-2.0
939
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Query display // ============= var GLYPHICON_DEFAULT = {color: '#1edcff'}; var GLYPHICON_HIGHLIGHT = {color: '#999999'}; var STATE_COLOR_MAP = { QUEUED: '#1b8f72', RUNNING: '#19874e', PLANNING: '#674f98', FINISHED: '#1a4629', BLOCKED: '#61003b', USER_ERROR: '#9a7d66', USER_CANCELED: '#858959', INSUFFICIENT_RESOURCES: '#7f5b72', EXTERNAL_ERROR: '#ca7640', UNKNOWN_ERROR: '#943524' }; function getQueryStateColor(query) { switch (query.state) { case "QUEUED": return STATE_COLOR_MAP.QUEUED; case "PLANNING": return STATE_COLOR_MAP.PLANNING; case "STARTING": case "FINISHING": case "RUNNING": if (query.queryStats && query.queryStats.fullyBlocked) { return STATE_COLOR_MAP.BLOCKED; } return STATE_COLOR_MAP.RUNNING; case "FAILED": switch (query.errorType) { case "USER_ERROR": if (query.errorCode.name === 'USER_CANCELED') { return STATE_COLOR_MAP.USER_CANCELED; } return STATE_COLOR_MAP.USER_ERROR; case "EXTERNAL": return STATE_COLOR_MAP.EXTERNAL_ERROR; case "INSUFFICIENT_RESOURCES": return STATE_COLOR_MAP.INSUFFICIENT_RESOURCES; default: return STATE_COLOR_MAP.UNKNOWN_ERROR; } case "FINISHED": return STATE_COLOR_MAP.FINISHED; default: return STATE_COLOR_MAP.QUEUED; } } function getStageStateColor(stage) { switch (stage.state) { case "PLANNED": return STATE_COLOR_MAP.QUEUED; case "SCHEDULING": case "SCHEDULING_SPLITS": case "SCHEDULED": return STATE_COLOR_MAP.PLANNING; case "RUNNING": if (stage.stageStats && stage.stageStats.fullyBlocked) { return STATE_COLOR_MAP.BLOCKED; } return STATE_COLOR_MAP.RUNNING; case "FINISHED": return STATE_COLOR_MAP.FINISHED; case "CANCELED": case "ABORTED": case "FAILED": return STATE_COLOR_MAP.UNKNOWN_ERROR; default: return "#b5b5b5" } } // This relies on the fact that BasicQueryInfo and QueryInfo have all the fields // necessary to compute this string, and that these fields are consistently named. function getHumanReadableState(query) { if (query.state == "RUNNING") { let title = "RUNNING"; if (query.scheduled && query.queryStats.totalDrivers > 0 && query.queryStats.runningDrivers >= 0) { if (query.queryStats.fullyBlocked) { title = "BLOCKED"; if (query.queryStats.blockedReasons && query.queryStats.blockedReasons.length > 0) { title += " (" + query.queryStats.blockedReasons.join(", ") + ")"; } } if (query.memoryPool === "reserved") { title += " (RESERVED)" } return title; } } if (query.state == "FAILED") { switch (query.errorType) { case "USER_ERROR": if (query.errorCode.name === "USER_CANCELED") { return "USER CANCELED"; } return "USER ERROR"; case "INTERNAL_ERROR": return "INTERNAL ERROR"; case "INSUFFICIENT_RESOURCES": return "INSUFFICIENT RESOURCES"; case "EXTERNAL": return "EXTERNAL ERROR"; } } return query.state; } function isProgressMeaningful(query) { return query.scheduled && query.state == "RUNNING" && query.queryStats.totalDrivers > 0 && query.queryStats.completedDrivers > 0; } function getProgressBarPercentage(query) { if (isProgressMeaningful(query)) { return Math.round((query.queryStats.completedDrivers * 100.0) / query.queryStats.totalDrivers); } // progress bars should appear 'full' when query progress is not meaningful return 100; } function getProgressBarTitle(query) { if (isProgressMeaningful(query)) { return getHumanReadableState(query) + " (" + getProgressBarPercentage(query) + "%)" } return getHumanReadableState(query) } function isQueryComplete(query) { return ["FINISHED", "FAILED", "CANCELED"].indexOf(query.state) > -1; } // Sparkline-related functions // =========================== // display at most 5 minutes worth of data on the sparklines var MAX_HISTORY = 60 * 5; // alpha param of exponentially weighted moving average. picked arbitrarily - lower values means more smoothness var MOVING_AVERAGE_ALPHA = 0.2; function addToHistory (value, valuesArray) { if (valuesArray.length == 0) { return valuesArray.concat([value]); } return valuesArray.concat([value]).slice(Math.max(valuesArray.length - MAX_HISTORY, 0)); } function addExponentiallyWeightedToHistory (value, valuesArray) { if (valuesArray.length == 0) { return valuesArray.concat([value]); } var movingAverage = (value * MOVING_AVERAGE_ALPHA) + (valuesArray[valuesArray.length - 1] * (1 - MOVING_AVERAGE_ALPHA)); if (value < 1) { movingAverage = 0; } return valuesArray.concat([movingAverage]).slice(Math.max(valuesArray.length - MAX_HISTORY, 0)); } // DagreD3 Graph-related functions // =============================== function initializeGraph() { return new dagreD3.graphlib.Graph({compound: true}) .setGraph({rankdir: 'BT'}) .setDefaultEdgeLabel(function () { return {}; }); } function initializeSvg(selector) { const svg = d3.select(selector); svg.append("g"); return svg; } function computeSources(nodeInfo) { let sources = []; let remoteSources = []; // TODO: put remoteSources in node-specific section switch (nodeInfo['@type']) { case 'output': case 'explainAnalyze': case 'project': case 'filter': case 'aggregation': case 'sort': case 'markDistinct': case 'window': case 'rowNumber': case 'topnRowNumber': case 'limit': case 'distinctlimit': case 'topn': case 'sample': case 'tablewriter': case 'delete': case 'metadatadelete': case 'tablecommit': case 'groupid': case 'unnest': case 'scalar': sources = [nodeInfo.source]; break; case 'join': sources = [nodeInfo.left, nodeInfo.right]; break; case 'semijoin': sources = [nodeInfo.source, nodeInfo.filteringSource]; break; case 'indexjoin': sources = [nodeInfo.probeSource, nodeInfo.filterSource]; break; case 'union': case 'exchange': sources = nodeInfo.sources; break; case 'remoteSource': remoteSources = nodeInfo.sourceFragmentIds; break; case 'tablescan': case 'values': case 'indexsource': break; default: console.log("NOTE: Unhandled PlanNode: " + nodeInfo['@type']); } return [sources, remoteSources]; } // Utility functions // ================= function truncateString(inputString, length) { if (inputString && inputString.length > length) { return inputString.substring(0, length) + "..."; } return inputString; } function getStageId(stageId) { return stageId.slice(stageId.indexOf('.') + 1, stageId.length) } function getTaskIdSuffix(taskId) { return taskId.slice(taskId.indexOf('.') + 1, taskId.length) } function getTaskIdInStage(taskId) { return Number.parseInt(getTaskIdSuffix(getTaskIdSuffix(taskId))); } function formatState(state, fullyBlocked) { if (fullyBlocked && state == "RUNNING") { return "BLOCKED"; } else { return state; } } function getHostname(url) { var hostname = new URL(url).hostname; if ((hostname.charAt(0) == '[') && (hostname.charAt(hostname.length - 1) == ']')) { hostname = hostname.substr(1, hostname.length - 2); } return hostname; } function getPort(url) { return new URL(url).port; } function getHostAndPort(url) { var url = new URL(url); return url.hostname + ":" + url.port; } function computeRate(count, ms) { if (ms == 0) { return 0; } return (count / ms) * 1000.0; } function precisionRound(n) { if (n < 10) { return n.toFixed(2); } if (n < 100) { return n.toFixed(1); } return Math.round(n); } function formatDuration(duration) { var unit = "ms"; if (duration > 1000) { duration /= 1000; unit = "s"; } if (unit == "s" && duration > 60) { duration /= 60; unit = "m"; } if (unit == "m" && duration > 60) { duration /= 60; unit = "h"; } if (unit == "h" && duration > 24) { duration /= 24; unit = "d"; } if (unit == "d" && duration > 7) { duration /= 7; unit = "w"; } return precisionRound(duration) + unit; } function formatCount(count) { var unit = ""; if (count > 1000) { count /= 1000; unit = "K"; } if (count > 1000) { count /= 1000; unit = "M"; } if (count > 1000) { count /= 1000; unit = "B"; } if (count > 1000) { count /= 1000; unit = "T"; } if (count > 1000) { count /= 1000; unit = "Q"; } return precisionRound(count) + unit; } function formatDataSizeBytes(size) { return formatDataSizeMinUnit(size, ""); } function formatDataSize(size) { return formatDataSizeMinUnit(size, "B"); } function formatDataSizeMinUnit(size, minUnit) { var unit = minUnit; if (size == 0) { return "0" + unit; } if (size >= 1024) { size /= 1024; unit = "K" + minUnit; } if (size >= 1024) { size /= 1024; unit = "M" + minUnit; } if (size >= 1024) { size /= 1024; unit = "G" + minUnit; } if (size >= 1024) { size /= 1024; unit = "T" + minUnit; } if (size >= 1024) { size /= 1024; unit = "P" + minUnit; } return precisionRound(size) + unit; } function parseDataSize(value) { var DATA_SIZE_PATTERN = /^\s*(\d+(?:\.\d+)?)\s*([a-zA-Z]+)\s*$/ var match = DATA_SIZE_PATTERN.exec(value); if (match == null) { return null; } var number = parseFloat(match[1]); switch (match[2]) { case "B": return number; case "kB": return number * Math.pow(2, 10); case "MB": return number * Math.pow(2, 20); case "GB": return number * Math.pow(2, 30); case "TB": return number * Math.pow(2, 40); case "PB": return number * Math.pow(2, 50); default: return null; } } function parseDuration(value) { var DURATION_PATTERN = /^\s*(\d+(?:\.\d+)?)\s*([a-zA-Z]+)\s*$/ var match = DURATION_PATTERN.exec(value); if (match == null) { return null; } var number = parseFloat(match[1]); switch (match[2]) { case "ns": return number / 1000000.0; case "us": return number / 1000.0; case "ms": return number; case "s": return number * 1000; case "m": return number * 1000 * 60; case "h": return number * 1000 * 60 * 60; case "d": return number * 1000 * 60 * 60 * 24; default: return null; } } function formatStackTrace(info) { return doFormatStackTrace(info, [], "", ""); } function doFormatStackTrace(info, parentStack, prefix, linePrefix) { var s = linePrefix + prefix + failureInfoToString(info) + "\n"; if (info.stack != null) { var sharedStackFrames = 0; if (parentStack != null) { sharedStackFrames = countSharedStackFrames(info.stack, parentStack); } for (var i = 0; i < info.stack.length - sharedStackFrames; i++) { s += linePrefix + "\tat " + info.stack[i] + "\n"; } if (sharedStackFrames !== 0) { s += linePrefix + "\t... " + sharedStackFrames + " more" + "\n"; } } if (info.suppressed != null) { for (var i = 0; i < info.suppressed.length; i++) { s += doFormatStackTrace(info.suppressed[i], info.stack, "Suppressed: ", linePrefix + "\t"); } } if (info.cause != null) { s += doFormatStackTrace(info.cause, info.stack, "Caused by: ", linePrefix); } return s; } function countSharedStackFrames(stack, parentStack) { var n = 0; var minStackLength = Math.min(stack.length, parentStack.length); while (n < minStackLength && stack[stack.length - 1 - n] === parentStack[parentStack.length - 1 - n]) { n++; } return n; } function failureInfoToString(t) { return (t.message != null) ? (t.type + ": " + t.message) : t.type; } function formatShortTime(date) { var hours = (date.getHours() % 12) || 12; var minutes = (date.getMinutes() < 10 ? "0" : "") + date.getMinutes(); return hours + ":" + minutes + (date.getHours() >= 12 ? "pm" : "am"); } function formatShortDateTime(date) { var year = date.getFullYear(); var month = "" + (date.getMonth() + 1); var dayOfMonth = "" + date.getDate(); return year + "-" + (month[1] ? month : "0" + month[0]) + "-" + (dayOfMonth[1] ? dayOfMonth: "0" + dayOfMonth[0]) + " " + formatShortTime(date); } function removeQueryId(id) { var pos = id.indexOf('.'); if (pos != -1) { return id.substring(pos + 1); } return id; }
Jimexist/presto
presto-main/src/main/resources/webapp/assets/utils.js
JavaScript
apache-2.0
14,579
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { ADSENSE_AMP_AUTO_ADS_RESPONSIVE_EXPERIMENT_NAME, AdSenseAmpAutoAdsResponsiveBranches, } from '../../../../ads/google/adsense-amp-auto-ads-responsive'; import {Services} from '../../../../src/services'; import { forceExperimentBranch, toggleExperiment, } from '../../../../src/experiments'; import {getAdNetworkConfig} from '../ad-network-config'; describes.realWin('ad-network-config', { amp: { canonicalUrl: 'https://foo.bar/baz', runtimeOn: true, ampdoc: 'single', }, }, env => { let ampAutoAdsElem; let document; beforeEach(() => { document = env.win.document; ampAutoAdsElem = document.createElement('amp-auto-ads'); env.win.document.body.appendChild(ampAutoAdsElem); }); afterEach(() => { env.win.document.body.removeChild(ampAutoAdsElem); }); describe('AdSense', () => { const AD_CLIENT = 'ca-pub-1234'; beforeEach(() => { ampAutoAdsElem.setAttribute('data-ad-client', AD_CLIENT); }); it('should generate the config fetch URL', () => { const adNetwork = getAdNetworkConfig('adsense', ampAutoAdsElem); expect(adNetwork.getConfigUrl()).to.equal( '//pagead2.googlesyndication.com/getconfig/ama?client=' + AD_CLIENT + '&plah=foo.bar&ama_t=amp&' + 'url=https%3A%2F%2Ffoo.bar%2Fbaz'); }); it('should report responsive-enabled when responsive experiment not on', () => { toggleExperiment( env.win, ADSENSE_AMP_AUTO_ADS_RESPONSIVE_EXPERIMENT_NAME, false); const adNetwork = getAdNetworkConfig('adsense', ampAutoAdsElem); expect(adNetwork.isResponsiveEnabled(env.win)).to.equal(true); }); it('should report responsive-enabled when responsive experiment on and ' + 'control branch picked', () => { forceExperimentBranch(env.win, ADSENSE_AMP_AUTO_ADS_RESPONSIVE_EXPERIMENT_NAME, AdSenseAmpAutoAdsResponsiveBranches.CONTROL); const adNetwork = getAdNetworkConfig('adsense', ampAutoAdsElem); expect(adNetwork.isResponsiveEnabled(env.win)).to.equal(true); }); it('should report responsive-disabled when responsive experiment on ' + 'and experiment branch picked', () => { forceExperimentBranch(env.win, ADSENSE_AMP_AUTO_ADS_RESPONSIVE_EXPERIMENT_NAME, AdSenseAmpAutoAdsResponsiveBranches.EXPERIMENT); const adNetwork = getAdNetworkConfig('adsense', ampAutoAdsElem); expect(adNetwork.isResponsiveEnabled(env.win)).to.equal(false); }); // TODO(bradfrizzell, #12476): Make this test work with sinon 4.0. it.skip('should truncate the URL if it\'s too long', () => { const adNetwork = getAdNetworkConfig('adsense', ampAutoAdsElem); const canonicalUrl = 'http://foo.bar/' + 'a'.repeat(4050) + 'shouldnt_be_included'; const docInfo = Services.documentInfoForDoc(ampAutoAdsElem); sandbox.stub(docInfo, 'canonicalUrl').callsFake(canonicalUrl); const url = adNetwork.getConfigUrl(); expect(url).to.contain('ama_t=amp'); expect(url).to.contain('url=http%3A%2F%2Ffoo.bar'); expect(url).not.to.contain('shouldnt_be_included'); }); it('should generate the attributes', () => { const adNetwork = getAdNetworkConfig('adsense', ampAutoAdsElem); expect(adNetwork.getAttributes()).to.deep.equal({ 'type': 'adsense', 'data-ad-client': 'ca-pub-1234', }); }); it('should get the default ad constraints', () => { const viewportMock = sandbox.mock(Services.viewportForDoc(env.win.document)); viewportMock.expects('getSize').returns( {width: 320, height: 500}).atLeast(1); const adNetwork = getAdNetworkConfig('adsense', ampAutoAdsElem); expect(adNetwork.getDefaultAdConstraints()).to.deep.equal({ initialMinSpacing: 500, subsequentMinSpacing: [ {adCount: 3, spacing: 1000}, {adCount: 6, spacing: 1500}, ], maxAdCount: 8, }); }); }); describe('Doubleclick', () => { const AD_LEGACY_CLIENT = 'ca-pub-1234'; const TARGETING_JSON = {'Categories': 'A'}; const EXPERIMENT_SETTINGS = {'width': 300, 'height': 250}; const AD_SLOT = '1234/example.com/SLOT_1'; beforeEach(() => { ampAutoAdsElem.setAttribute('data-ad-legacy-client', AD_LEGACY_CLIENT); ampAutoAdsElem.setAttribute('data-experiment', JSON.stringify(EXPERIMENT_SETTINGS)); ampAutoAdsElem.setAttribute('data-json', JSON.stringify(TARGETING_JSON)); ampAutoAdsElem.setAttribute('data-slot', AD_SLOT); }); it('should report enabled always', () => { const adNetwork = getAdNetworkConfig('doubleclick', ampAutoAdsElem); expect(adNetwork.isEnabled(env.win)).to.equal(true); }); it('should generate the config fetch URL', () => { const adNetwork = getAdNetworkConfig('doubleclick', ampAutoAdsElem); expect(adNetwork.getConfigUrl()).to.equal( '//pagead2.googlesyndication.com/getconfig/ama?client=' + AD_LEGACY_CLIENT + '&plah=foo.bar&ama_t=amp&' + 'url=https%3A%2F%2Ffoo.bar%2Fbaz'); }); // TODO(bradfrizzell, #12476): Make this test work with sinon 4.0. it.skip('should truncate the URL if it\'s too long', () => { const adNetwork = getAdNetworkConfig('doubleclick', ampAutoAdsElem); const canonicalUrl = 'http://foo.bar/' + 'a'.repeat(4050) + 'shouldnt_be_included'; const docInfo = Services.documentInfoForDoc(ampAutoAdsElem); sandbox.stub(docInfo, 'canonicalUrl').callsFake(canonicalUrl); const url = adNetwork.getConfigUrl(); expect(url).to.contain('ama_t=amp'); expect(url).to.contain('url=http%3A%2F%2Ffoo.bar'); expect(url).not.to.contain('shouldnt_be_included'); }); it('should generate the attributes', () => { const adNetwork = getAdNetworkConfig('doubleclick', ampAutoAdsElem); expect(adNetwork.getAttributes()).to.deep.equal({ 'type': 'doubleclick', 'json': JSON.stringify(TARGETING_JSON), 'data-slot': AD_SLOT, }); }); it('should get the default ad constraints', () => { const viewportMock = sandbox.mock(Services.viewportForDoc(env.win.document)); viewportMock.expects('getSize').returns( {width: 320, height: 500}).atLeast(1); const adNetwork = getAdNetworkConfig('doubleclick', ampAutoAdsElem); expect(adNetwork.getDefaultAdConstraints()).to.deep.equal({ initialMinSpacing: 500, subsequentMinSpacing: [ {adCount: 3, spacing: 1000}, {adCount: 6, spacing: 1500}, ], maxAdCount: 8, }); }); it('should not be responsive-enabled', () => { const adNetwork = getAdNetworkConfig('doubleclick', ampAutoAdsElem); expect(adNetwork.isResponsiveEnabled(env.win)).to.be.false; }); }); it('should return null for unknown type', () => { expect(getAdNetworkConfig('unknowntype', ampAutoAdsElem)).to.be.null; }); });
techhtml/amphtml
extensions/amp-auto-ads/0.1/test/test-ad-network-config.js
JavaScript
apache-2.0
7,709
import Ember from 'ember'; const { Component, computed } = Ember; export default Component.extend({ tagName : 'footer', classNames : ['ui', 'inverted', 'vertical', 'footer', 'segment'], currentLocale: computed(function() { return this.get('l10n').getLocale(); }), actions: { switchLanguage(locale) { this.get('l10n').switchLanguage(locale); } } });
sumedh123/open-event-frontend
app/components/footer-main.js
JavaScript
apache-2.0
386
/// <reference path="../../src/Dexie.js" /> /// <reference path="../../addons/Dexie.Observable/Dexie.Observable.js" /> /// <reference path="https://code.jquery.com/jquery-2.1.1.js" /> function DBMonitor(searchBox, tbody) { var searchValue = searchBox.val(); var databases = []; reload(); searchBox.change(updateSearch); window.addEventListener('storage', function (event) { if (event.key === "Dexie.DatabaseNames") { reload(); } }); reload(); function reload() { databases.forEach(function (db) { db.close(); }); Dexie.getDatabaseNames(function (names) { for (var i = 0; i < names.length; ++i) { var db = new Dexie(names[i]); db. } }); } }
cesarmarinhorj/Dexie.js
samples/db-monitor/db-monitor.js
JavaScript
apache-2.0
811
function __processArg(obj, key) { var arg = null; if (obj) { arg = obj[key] || null; delete obj[key]; } return arg; } function Controller() { require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "index"; this.args = arguments[0] || {}; if (arguments[0]) { { __processArg(arguments[0], "__parentSymbol"); } { __processArg(arguments[0], "$model"); } { __processArg(arguments[0], "__itemTemplate"); } } var $ = this; var exports = {}; $.__views.index = Ti.UI.createWindow({ backgroundColor: "#fff", fullscreen: false, exitOnClose: true, id: "index" }); $.__views.index && $.addTopLevelView($.__views.index); $.__views.appVersion = Ti.UI.createLabel({ id: "appVersion", textAlign: "centerAlign", text: Ti.App.getVersion() + "test", height: Ti.UI.SIZE, top: 50 }); $.__views.index.add($.__views.appVersion); $.__views.appVersion = Ti.UI.createLabel({ id: "appVersion", textAlign: "centerAlign", text: "test" + Ti.App.getVersion(), height: Ti.UI.SIZE, top: 100 }); $.__views.index.add($.__views.appVersion); exports.destroy = function() {}; _.extend($, $.__views); $.index.open(); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;
brentonhouse/brentonhouse.alloy
test/apps/testing/ALOY-1516/_generated/windows/alloy/controllers/index.js
JavaScript
apache-2.0
1,575
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _ionicIonic = require('ionic/ionic'); var _angular2Angular2 = require('angular2/angular2'); var _helpers = require('../../helpers'); var __decorate = undefined && undefined.__decorate || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function (o, d) { return d && d(o) || o; }, target); case 3: return decorators.reduceRight(function (o, d) { return (d && d(target, key), void 0); }, void 0); case 4: return decorators.reduceRight(function (o, d) { return d && d(target, key, o) || o; }, desc); } }; var __metadata = undefined && undefined.__metadata || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var BasicPage = function BasicPage() { _classCallCheck(this, BasicPage); }; exports.BasicPage = BasicPage; exports.BasicPage = BasicPage = __decorate([(0, _ionicIonic.Page)({ templateUrl: 'slides/basic/template.html', directives: [(0, _angular2Angular2.forwardRef)(function () { return _helpers.AndroidAttribute; })] }), __metadata('design:paramtypes', [])], BasicPage);
philmerrell/ionic-site
docs/v2/dist/demos/component-docs/slides/basic/pages.js
JavaScript
apache-2.0
1,673
/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var obj = {}; var array = ['Apple', 'Banana', "zero", 0, obj, 'Apple']; var index = array.at(0); assert(index === 'Apple'); assert(array[index] === undefined); assert(array.at(array.length) === undefined); assert(array.at(array.length+1) === undefined); assert(array.at(array.length-1) === 'Apple'); assert(array.at("1") === 'Banana'); assert(array.at(-1) === 'Apple'); assert(array.at("-1") === 'Apple'); assert(array.at("-20") === undefined); /* 7 */ var obj = {} obj.length = 1; Object.defineProperty(obj, '0', { 'get' : function () {throw new ReferenceError ("foo"); } }); obj.at = Array.prototype.at; try { obj.at(0); assert(false); } catch(e) { assert(e.message === "foo"); assert(e instanceof ReferenceError); } try { Array.prototype.at.call(undefined) assert (false); } catch(e) { assert(e instanceof TypeError); }
zherczeg/jerryscript
tests/jerry/es.next/array-prototype-at.js
JavaScript
apache-2.0
1,476
import Resource from '@rancher/ember-api-store/models/resource'; import { get, computed } from '@ember/object'; import { reference } from '@rancher/ember-api-store/utils/denormalize'; export default Resource.extend({ project: reference('projectId'), projectName: computed('project.displayName', function() { return get(this, 'project.displayName'); }), clusterName: computed('project.cluster.displayName', function() { return get(this, 'project.cluster.displayName'); }), clusterId: computed('projectId', function() { let { projectId } = this; return projectId.split(':')[0]; }), appLink: computed('projectId', 'appId', function() { const { projectId } = this; if (projectId) { return `${ projectId.split(':')[1] }:${ this.appId }`; } return null; }), });
westlywright/ui
app/models/target.js
JavaScript
apache-2.0
821
/** * Copyright 2019 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {CSS} from '../../../build/amp-truncate-text-0.1.css'; import {Services} from '../../../src/services'; import {CSS as ShadowCSS} from '../../../build/amp-truncate-text-shadow-0.1.css'; import { closestAncestorElementBySelector, iterateCursor, } from '../../../src/dom'; import {createShadowRoot} from './shadow-utils'; import {dev, userAssert} from '../../../src/log'; import {htmlFor} from '../../../src/static-template'; import {isExperimentOn} from '../../../src/experiments'; import {toArray} from '../../../src/types'; import {truncateText} from './truncate-text'; /** * TODO(sparhami) List of stuff to do / consider: * - Delay truncateing for things outside of the viewport * - Only truncate a few things in a single pass, and defer others * - If estimation + mutation takes too long, fall back to gradient * or perhaps nothing and position absolute the button on top of * text * * Maybe let the developer specify the gradient * - If we had some rough bucket of performance, maybe just fallback * immediately to gradient / hard cut off. * - Custom fonts can cause truncation to end up being wrong * when they load * * Can we just wait to layout if we know a font is loading? * Since all fonts are statically declared in AMP, this is just a * one time thing */ export class AmpTruncateText extends AMP.BaseElement { /** * Sets up the actions supported by this element. * @private */ setupActions_() { this.registerAction('expand', () => this.expand_()); this.registerAction('collapse', () => this.collapse_()); } /** @param {!AmpElement} element */ constructor(element) { super(element); /** @private {?Element} */ this.content_ = null; /** @private {?Element} */ this.collapsedSlot_ = null; /** @private {?Element} */ this.expandedSlot_ = null; /** @private {?Element} */ this.persistentSlot_ = null; /** @private {boolean} */ this.useShadow_ = false; /** @private {!MutationObserver} */ this.mutationObserver_ = new this.win.MutationObserver(() => { this.truncate_(); }); } /** @override */ buildCallback() { userAssert( isExperimentOn(this.win, 'amp-truncate-text'), 'The amp-truncate-text experiment must be enabled to use this ' + 'component.' ); this.useShadow_ = !!this.element.attachShadow && isExperimentOn(this.win, 'amp-truncate-text-shadow'); if (this.useShadow_) { this.buildShadow_(); } else { this.build_(); } this.setupActions_(); this.collapsedSlot_.addEventListener('click', event => { this.maybeExpand_(event); }); this.expandedSlot_.addEventListener('click', event => { this.maybeCollapse_(event); }); } /** * Builds the component when not using Shadow DOM. */ build_() { const html = htmlFor(this.element); this.content_ = html` <div class="i-amphtml-truncate-content"> <span class="i-amphtml-default-slot"></span> <span class="i-amphtml-truncate-collapsed-slot" name="collapsed"></span> <span class="i-amphtml-truncate-expanded-slot" name="expanded"></span> <span class="i-amphtml-truncate-persistent-slot" name="persistent" ></span> </div> `; const defaultSlot = this.content_.querySelector('.i-amphtml-default-slot'); this.collapsedSlot_ = this.content_.querySelector( '.i-amphtml-truncate-collapsed-slot' ); this.expandedSlot_ = this.content_.querySelector( '.i-amphtml-truncate-expanded-slot' ); this.persistentSlot_ = this.content_.querySelector( '.i-amphtml-truncate-persistent-slot' ); iterateCursor(this.element.querySelectorAll('[slot="collapsed"]'), el => { this.collapsedSlot_.appendChild(el); }); iterateCursor(this.element.querySelectorAll('[slot="expanded"]'), el => { this.expandedSlot_.appendChild(el); }); iterateCursor(this.element.querySelectorAll('[slot="persistent"]'), el => { this.persistentSlot_.appendChild(el); }); this.getRealChildNodes().forEach(node => { defaultSlot.appendChild(node); }); this.element.appendChild(this.content_); } /** * Builds the component when using Shadow DOM. */ buildShadow_() { const html = htmlFor(this.element); const sr = createShadowRoot( this.element, ShadowCSS, html` <div class="content"> <slot></slot> <slot class="collapsed-slot" name="collapsed"></slot> <slot class="expanded-slot" name="expanded"></slot> <slot class="persistent-slot" name="persistent"></slot> </div> ` ); this.content_ = null; this.collapsedSlot_ = sr.querySelector('.collapsed-slot'); this.expandedSlot_ = sr.querySelector('.expanded-slot'); this.persistentSlot_ = sr.querySelector('.persistent-slot'); } /** @override */ layoutCallback() { return this.mutateElement(() => { this.truncate_(); }); } /** @override */ firstAttachedCallback() { this.mutationObserver_.observe(this.element, { attributes: true, characterData: true, childList: true, subtree: true, }); } /** @override */ isRelayoutNeeded() { return true; } /** @override */ isLayoutSupported() { return true; } /** * @return {!Array<!Node>} The nodes to show when overflowing. */ getNodesForOverflow_() { if (this.useShadow_) { return toArray( this.element.querySelectorAll('[slot="persistent"], [slot="collapsed"]') ); } return toArray( this.element.querySelectorAll( '.i-amphtml-truncate-persistent-slot, .i-amphtml-truncate-collapsed-slot' ) ); } /** * Truncates the content of the element. * @private */ truncate_() { const container = dev().assertElement( this.useShadow_ ? this.element : this.content_ ); const overflowNodes = this.getNodesForOverflow_(); truncateText({ container, overflowNodes, }); // Take the records to clear them out. This prevents mutations from // the truncation from invoking the observer's callback. this.mutationObserver_.takeRecords(); } /** * Expands the component, unless the event came from an element that is * actionable. * @param {!Event} event */ maybeExpand_(event) { this.maybeToggle_(event, true); } /** * Collapses the component, unless the event came from an element that is * actionable. * @param {!Event} event */ maybeCollapse_(event) { this.maybeToggle_(event, false); } /** * Expand/collapses the component unless the element already has an * associated action or will navigate. * @param {!Event} event * @param {boolean} expand Whether to expand or collapse. */ maybeToggle_(event, expand) { const target = dev().assertElement(event.target); const actionService = Services.actionServiceForDoc(this.element); // If we have a tap action on any ancestor, then skip expansion. if (actionService.hasAction(target, 'tap')) { return; } // If we have an ancestor anchor (either for the slotted element, or // wrapping the whole amp-truncate-text). skip expansion. if (closestAncestorElementBySelector(target, 'a[href]')) { return; } if (expand) { this.expand_(); } else { this.collapse_(); } } /** * Expands the component by removing any height restriction via CSS. */ expand_() { this.element.setAttribute('i-amphtml-truncate-expanded', ''); } /** * Collapses the component by undoing the effects of `expand_()`. */ collapse_() { this.element.removeAttribute('i-amphtml-truncate-expanded'); } } AMP.extension('amp-truncate-text', '0.1', AMP => { AMP.registerElement('amp-truncate-text', AmpTruncateText, CSS); });
dotandads/amphtml
extensions/amp-truncate-text/0.1/amp-truncate-text.js
JavaScript
apache-2.0
8,602
/** * * @authors Your Name ([email protected]) * @date 2015-09-17 10:22:59 * @version $Id$ */ (function(i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function() { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', '#path/js/analytics.js', 'ga'); ga('create', 'UA-4625583-2', 'webapplayers.com'); ga('send', 'pageview');
freiby/flex
server/nirvana-plugins/nirvana-inspinia-style/src/main/webapp/js/embeddedjs2.js
JavaScript
apache-2.0
606
/* * //****************************************************************** * // * // Copyright 2017 Samsung Electronics All Rights Reserved. * // * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= * // * // Licensed under the Apache License, Version 2.0 (the "License"); * // you may not use this file except in compliance with the License. * // You may obtain a copy of the License at * // * // http://www.apache.org/licenses/LICENSE-2.0 * // * // Unless required by applicable law or agreed to in writing, software * // distributed under the License is distributed on an "AS IS" BASIS, * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * // See the License for the specific language governing permissions and * // limitations under the License. * // * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */ var EventEmitter = require('events').EventEmitter; var WS = require('websocket').w3cwebsocket; var convertBlob = require('blob-to-buffer'); var HashMap = require('hashmap'); var coapTokenMap = new HashMap(); var localStorage = window.localStorage; if (typeof localStorage === "undefined" || localStorage === null) { var LocalStorage = require('node-localstorage').LocalStorage; localStorage = new LocalStorage('./client'); } const coap = require('./components/CoapWebsocketCodec').coap; const parse = require('./components/CoapWebsocketCodec').parse; const path = require('./components/CoapWebsocketCodec').path; const CONNECTED = 'connected'; const DISCONNECTED = 'disconnected'; const SIGNUP = 'signup'; const SIGNIN = 'signin'; const SIGNOUT = 'signout'; const ERROR = 'error'; var Client = new function() { var ws; this.event = new EventEmitter(); // coap websocket client initialize. this.init = function(address) { console.log('client init: ' + address); /* TODO websocket secured */ var serverURL = "ws://" + address + "/.well-known/coap"; this.ws = new WS(serverURL, 'coap'); this.ws.onopen = function() { console.debug('Connected to server ' + address); Client.event.emit(CONNECTED); }; this.ws.onclose = function() { console.debug('Disconnected from server ' + address); Client.event.emit(DISCONNECTED); }; this.ws.onerror = function() { console.error('Error occurs'); Client.event.emit(ERROR, 'Error occurs while websocket connection'); Client.event.emit(DISCONNECTED); }; // response callback. this.ws.onmessage = function(event) { console.debug('Message received -'); convertBlob(event.data, function (err, buffer) { if (err) throw err; var packet = parse(buffer); console.debug(packet); console.debug(packet.getPayloadObject); var func = coapTokenMap.get(packet.getToken.toString()); func(packet); if(packet.getSequenceNumber === -1){ coapTokenMap.remove(packet.getToken.toString()); } }); }; } // coap websocket client close. this.close = function() { console.log('client close'); this.ws.close(); Client.event.emit(DISCONNECTED); } // send sign-up request. this.onSignUp = function(packet) { if(packet.getCode === 68) { Client.event.emit(SIGNUP, packet.getPayloadObject.uid, packet.getPayloadObject.accesstoken); } else { Client.event.emit(ERROR, "SignUp Failed" + packet.getCode); } } this.signUp = function(di, provider, authcode) { console.log('client signUp'); var payload = { di: di, authprovider: provider, authcode: authcode, devicetype: "device" }; this.ws.send(this.doRequest("POST", path.ACCOUNT_FULL_URI, null, payload, this.onSignUp)); } // send sign-in request. this.onSignIn = function(packet) { if(packet.getCode === 68) { Client.event.emit(SIGNIN); } else { Client.event.emit(ERROR, "SignIn Failed" + packet.getCode); } } this.signIn = function(di, uid, accesstoken) { console.log('client signIn'); var payload = { di: di, uid: uid, accesstoken: accesstoken, login: true }; this.ws.send(this.doRequest("POST", path.ACCOUNT_SESSION_FULL_URI, null, payload, this.onSignIn)); } // send sign-out request. this.onSignOut = function(packet) { if(packet.getCode === 68) { Client.event.emit(SIGNOUT); } else { Client.event.emit(ERROR, "SignOut Failed" + packet.getCode); } } this.signOut = function(di, accesstoken) { console.log('client signOut'); var payload = { di: di, accesstoken: accesstoken, login: false }; this.ws.send(this.doRequest("POST", path.ACCOUNT_SESSION_FULL_URI, null, payload, this.onSignOut)); } // send resource discovery request. this.discoverResource = function(queries, response) { console.log('client discoverResource ' + queries); this.ws.send(this.doRequest("GET", path.WELL_KNOWN_FULL_URI, queries, null, response)); } // send control message. this.sendMessage = function(uri, method, payload, queries, response) { console.log('client sendMessage'); this.ws.send(this.doRequest(method, uri, queries, payload, response)); } this.doRequest = function(method, uri, query, payload, response) { var newCoaptoken = require('crypto').randomBytes(8); coapTokenMap.set(newCoaptoken.toString(), response); return coap.createTokenRequest(newCoaptoken, method, uri, query, payload); } // erase data in local storage this.removeClientData = function(keyArray) { for (var i = 0; i < keyArray.length; i++) { localStorage.removeItem(keyArray[i]); } }; this.writeClientData = function(keyValArray) { for (var i = 0; i < keyValArray.length; i++) { localStorage.setItem(keyValArray[i][0], keyValArray[i][1]); } }; this.readClientData = function(key) { return localStorage.getItem(key); }; this.getResourceList = function(discoveryPayload) { if (discoveryPayload === null) { return []; } var resourceList = []; console.debug("Discovered devices: " + discoveryPayload.length); for (var i = 0; i < discoveryPayload.length; i++) { for (var j = 0; j < discoveryPayload[i].links.length; j++) { console.debug("[" + i + "] " + discoveryPayload[i].links[j].href); resourceList.push({ n: discoveryPayload[i].n, di: discoveryPayload[i].di, uri: discoveryPayload[i].links[j].href, rts: this.buildArrayString(discoveryPayload[i].links[j].rt), ifs: this.buildArrayString(discoveryPayload[i].links[j].if) }); } } return resourceList; } this.buildArrayString = function(array) { var result = ''; var seperates = ', '; for (var i = 0; i < array.length; i++) { // last data if (i === array.length -1) seperates = ''; result += array[i] + seperates; } return result; } }(); module.exports = Client;
JunhwanPark/TizenRT
external/iotivity/iotivity_1.3-rel/cloud/dashboard/src/Client.js
JavaScript
apache-2.0
7,702
'use strict'; var _ansiStyles = _interopRequireDefault(require('ansi-styles')); var _collections = require('./collections'); var _AsymmetricMatcher = _interopRequireDefault( require('./plugins/AsymmetricMatcher') ); var _ConvertAnsi = _interopRequireDefault(require('./plugins/ConvertAnsi')); var _DOMCollection = _interopRequireDefault(require('./plugins/DOMCollection')); var _DOMElement = _interopRequireDefault(require('./plugins/DOMElement')); var _Immutable = _interopRequireDefault(require('./plugins/Immutable')); var _ReactElement = _interopRequireDefault(require('./plugins/ReactElement')); var _ReactTestComponent = _interopRequireDefault( require('./plugins/ReactTestComponent') ); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol; const toString = Object.prototype.toString; const toISOString = Date.prototype.toISOString; const errorToString = Error.prototype.toString; const regExpToString = RegExp.prototype.toString; const symbolToString = Symbol.prototype.toString; /** * Explicitly comparing typeof constructor to function avoids undefined as name * when mock identity-obj-proxy returns the key as the value for any key. */ const getConstructorName = val => (typeof val.constructor === 'function' && val.constructor.name) || 'Object'; /* global window */ /** Is val is equal to global window object? Works even if it does not exist :) */ const isWindow = val => typeof window !== 'undefined' && val === window; const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; const NEWLINE_REGEXP = /\n/gi; class PrettyFormatPluginError extends Error { constructor(message, stack) { super(message); this.stack = stack; this.name = this.constructor.name; } } function isToStringedArrayType(toStringed) { return ( toStringed === '[object Array]' || toStringed === '[object ArrayBuffer]' || toStringed === '[object DataView]' || toStringed === '[object Float32Array]' || toStringed === '[object Float64Array]' || toStringed === '[object Int8Array]' || toStringed === '[object Int16Array]' || toStringed === '[object Int32Array]' || toStringed === '[object Uint8Array]' || toStringed === '[object Uint8ClampedArray]' || toStringed === '[object Uint16Array]' || toStringed === '[object Uint32Array]' ); } function printNumber(val) { return Object.is(val, -0) ? '-0' : String(val); } function printBigInt(val) { return String(`${val}n`); } function printFunction(val, printFunctionName) { if (!printFunctionName) { return '[Function]'; } return '[Function ' + (val.name || 'anonymous') + ']'; } function printSymbol(val) { return symbolToString.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)'); } function printError(val) { return '[' + errorToString.call(val) + ']'; } /** * The first port of call for printing an object, handles most of the * data-types in JS. */ function printBasicValue(val, printFunctionName, escapeRegex, escapeString) { if (val === true || val === false) { return '' + val; } if (val === undefined) { return 'undefined'; } if (val === null) { return 'null'; } const typeOf = typeof val; if (typeOf === 'number') { return printNumber(val); } if (typeOf === 'bigint') { return printBigInt(val); } if (typeOf === 'string') { if (escapeString) { return '"' + val.replace(/"|\\/g, '\\$&') + '"'; } return '"' + val + '"'; } if (typeOf === 'function') { return printFunction(val, printFunctionName); } if (typeOf === 'symbol') { return printSymbol(val); } const toStringed = toString.call(val); if (toStringed === '[object WeakMap]') { return 'WeakMap {}'; } if (toStringed === '[object WeakSet]') { return 'WeakSet {}'; } if ( toStringed === '[object Function]' || toStringed === '[object GeneratorFunction]' ) { return printFunction(val, printFunctionName); } if (toStringed === '[object Symbol]') { return printSymbol(val); } if (toStringed === '[object Date]') { return isNaN(+val) ? 'Date { NaN }' : toISOString.call(val); } if (toStringed === '[object Error]') { return printError(val); } if (toStringed === '[object RegExp]') { if (escapeRegex) { // https://github.com/benjamingr/RegExp.escape/blob/master/polyfill.js return regExpToString.call(val).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'); } return regExpToString.call(val); } if (val instanceof Error) { return printError(val); } return null; } /** * Handles more complex objects ( such as objects with circular references. * maps and sets etc ) */ function printComplexValue( val, config, indentation, depth, refs, hasCalledToJSON ) { if (refs.indexOf(val) !== -1) { return '[Circular]'; } refs = refs.slice(); refs.push(val); const hitMaxDepth = ++depth > config.maxDepth; const min = config.min; if ( config.callToJSON && !hitMaxDepth && val.toJSON && typeof val.toJSON === 'function' && !hasCalledToJSON ) { return printer(val.toJSON(), config, indentation, depth, refs, true); } const toStringed = toString.call(val); if (toStringed === '[object Arguments]') { return hitMaxDepth ? '[Arguments]' : (min ? '' : 'Arguments ') + '[' + (0, _collections.printListItems)( val, config, indentation, depth, refs, printer ) + ']'; } if (isToStringedArrayType(toStringed)) { return hitMaxDepth ? '[' + val.constructor.name + ']' : (min ? '' : val.constructor.name + ' ') + '[' + (0, _collections.printListItems)( val, config, indentation, depth, refs, printer ) + ']'; } if (toStringed === '[object Map]') { return hitMaxDepth ? '[Map]' : 'Map {' + (0, _collections.printIteratorEntries)( val.entries(), config, indentation, depth, refs, printer, ' => ' ) + '}'; } if (toStringed === '[object Set]') { return hitMaxDepth ? '[Set]' : 'Set {' + (0, _collections.printIteratorValues)( val.values(), config, indentation, depth, refs, printer ) + '}'; } // Avoid failure to serialize global window object in jsdom test environment. // For example, not even relevant if window is prop of React element. return hitMaxDepth || isWindow(val) ? '[' + getConstructorName(val) + ']' : (min ? '' : getConstructorName(val) + ' ') + '{' + (0, _collections.printObjectProperties)( val, config, indentation, depth, refs, printer ) + '}'; } function isNewPlugin(plugin) { return plugin.serialize != null; } function printPlugin(plugin, val, config, indentation, depth, refs) { let printed; try { printed = isNewPlugin(plugin) ? plugin.serialize(val, config, indentation, depth, refs, printer) : plugin.print( val, valChild => printer(valChild, config, indentation, depth, refs), str => { const indentationNext = indentation + config.indent; return ( indentationNext + str.replace(NEWLINE_REGEXP, '\n' + indentationNext) ); }, { edgeSpacing: config.spacingOuter, min: config.min, spacing: config.spacingInner }, config.colors ); } catch (error) { throw new PrettyFormatPluginError(error.message, error.stack); } if (typeof printed !== 'string') { throw new Error( `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".` ); } return printed; } function findPlugin(plugins, val) { for (let p = 0; p < plugins.length; p++) { try { if (plugins[p].test(val)) { return plugins[p]; } } catch (error) { throw new PrettyFormatPluginError(error.message, error.stack); } } return null; } function printer(val, config, indentation, depth, refs, hasCalledToJSON) { const plugin = findPlugin(config.plugins, val); if (plugin !== null) { return printPlugin(plugin, val, config, indentation, depth, refs); } const basicResult = printBasicValue( val, config.printFunctionName, config.escapeRegex, config.escapeString ); if (basicResult !== null) { return basicResult; } return printComplexValue( val, config, indentation, depth, refs, hasCalledToJSON ); } const DEFAULT_THEME = { comment: 'gray', content: 'reset', prop: 'yellow', tag: 'cyan', value: 'green' }; const DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME); const DEFAULT_OPTIONS = { callToJSON: true, escapeRegex: false, escapeString: true, highlight: false, indent: 2, maxDepth: Infinity, min: false, plugins: [], printFunctionName: true, theme: DEFAULT_THEME }; function validateOptions(options) { Object.keys(options).forEach(key => { if (!DEFAULT_OPTIONS.hasOwnProperty(key)) { throw new Error(`pretty-format: Unknown option "${key}".`); } }); if (options.min && options.indent !== undefined && options.indent !== 0) { throw new Error( 'pretty-format: Options "min" and "indent" cannot be used together.' ); } if (options.theme !== undefined) { if (options.theme === null) { throw new Error(`pretty-format: Option "theme" must not be null.`); } if (typeof options.theme !== 'object') { throw new Error( `pretty-format: Option "theme" must be of type "object" but instead received "${typeof options.theme}".` ); } } } const getColorsHighlight = options => DEFAULT_THEME_KEYS.reduce((colors, key) => { const value = options.theme && options.theme[key] !== undefined ? options.theme[key] : DEFAULT_THEME[key]; const color = value && _ansiStyles.default[value]; if ( color && typeof color.close === 'string' && typeof color.open === 'string' ) { colors[key] = color; } else { throw new Error( `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.` ); } return colors; }, Object.create(null)); const getColorsEmpty = () => DEFAULT_THEME_KEYS.reduce((colors, key) => { colors[key] = { close: '', open: '' }; return colors; }, Object.create(null)); const getPrintFunctionName = options => options && options.printFunctionName !== undefined ? options.printFunctionName : DEFAULT_OPTIONS.printFunctionName; const getEscapeRegex = options => options && options.escapeRegex !== undefined ? options.escapeRegex : DEFAULT_OPTIONS.escapeRegex; const getEscapeString = options => options && options.escapeString !== undefined ? options.escapeString : DEFAULT_OPTIONS.escapeString; const getConfig = options => ({ callToJSON: options && options.callToJSON !== undefined ? options.callToJSON : DEFAULT_OPTIONS.callToJSON, colors: options && options.highlight ? getColorsHighlight(options) : getColorsEmpty(), escapeRegex: getEscapeRegex(options), escapeString: getEscapeString(options), indent: options && options.min ? '' : createIndent( options && options.indent !== undefined ? options.indent : DEFAULT_OPTIONS.indent ), maxDepth: options && options.maxDepth !== undefined ? options.maxDepth : DEFAULT_OPTIONS.maxDepth, min: options && options.min !== undefined ? options.min : DEFAULT_OPTIONS.min, plugins: options && options.plugins !== undefined ? options.plugins : DEFAULT_OPTIONS.plugins, printFunctionName: getPrintFunctionName(options), spacingInner: options && options.min ? ' ' : '\n', spacingOuter: options && options.min ? '' : '\n' }); function createIndent(indent) { return new Array(indent + 1).join(' '); } /** * Returns a presentation string of your `val` object * @param val any potential JavaScript object * @param options Custom settings */ function prettyFormat(val, options) { if (options) { validateOptions(options); if (options.plugins) { const plugin = findPlugin(options.plugins, val); if (plugin !== null) { return printPlugin(plugin, val, getConfig(options), '', 0, []); } } } const basicResult = printBasicValue( val, getPrintFunctionName(options), getEscapeRegex(options), getEscapeString(options) ); if (basicResult !== null) { return basicResult; } return printComplexValue(val, getConfig(options), '', 0, []); } prettyFormat.plugins = { AsymmetricMatcher: _AsymmetricMatcher.default, ConvertAnsi: _ConvertAnsi.default, DOMCollection: _DOMCollection.default, DOMElement: _DOMElement.default, Immutable: _Immutable.default, ReactElement: _ReactElement.default, ReactTestComponent: _ReactTestComponent.default }; /* eslint-disable-next-line no-redeclare */ module.exports = prettyFormat;
GoogleCloudPlatform/prometheus-engine
third_party/prometheus_ui/base/web/ui/react-app/node_modules/pretty-format/build/index.js
JavaScript
apache-2.0
13,582
/** * this model contains information about the organization for * the current user and the users who are inside the organizacion. * * Attributes: * * - users: collection with user instances whithin the organization (see cdb.admin.Organization.Users * * */ cdb.admin.Organization = cdb.core.Model.extend({ url: '/api/v1/org/', initialize: function(attrs, opts) { this.owner = new cdb.admin.User(this.get('owner')); this.users = new cdb.admin.Organization.Users( null, { organizationId: this.id, currentUserId: opts && opts.currentUserId } ); this.display_email = ((typeof attrs) != 'undefined' && attrs != null && (typeof attrs.admin_email) != 'undefined') && attrs.admin_email != null && (attrs.admin_email == '' ? this.owner.email : attrs.admin_email); this.users.reset(this.get('users')); // make sure all the users have a reference to this organization var self = this; this.users.each(function (u) { u.organization = self; }); }, fetch: function() { throw new Error("organization should not be fetch, should be static"); }, containsUser: function(user) { return !!this.users.find(function(u) { return u.id === user.id; }) }, viewUrl: function() { return new cdb.common.OrganizationUrl({ base_url: this.get('base_url') }) } }); // helper to manage organization users cdb.admin.Organization.Users = Backbone.Collection.extend({ model: cdb.admin.User, params: { per_page: 50, page: 1, order: 'username', q: '' }, url: function() { if (!this.organizationId) { throw new Error('Organization id is needed for fetching organization users'); } var u = '/api/v1/organization/' + this.organizationId + '/users'; u += "?" + this._createUrlParameters(); return u; }, initialize: function(users, opts) { this.elder('initialize'); this.organizationId = opts.organizationId; this.currentUserId = opts.currentUserId; // Let's add abort behaviour this.sync = Backbone.syncAbort; }, comparator: function(mdl) { return mdl.get('username'); }, _createUrlParameters: function() { return _.compact(_(this.params).map( function(v, k) { return k + "=" + encodeURIComponent(v) } )).join('&'); }, parse: function(r) { var self = this; var users = _.map(r.users, function(user) { if (user.id !== self.currentUserId) { return user; } else { r.total_user_entries--; r.total_entries--; } }); this.total_user_entries = r.total_user_entries; this.total_entries = r.total_entries; return _.compact(users); }, fetch: function(opts) { this.trigger('loading'); this.elder('fetch'); }, // Helper functions setParameters: function(data) { var self = this; _.each(data, function(val, key) { self.params[key] = val; }); return this; }, getParameter: function(key) { return this.params[key] }, getTotalUsers: function() { return this.total_user_entries }, getSearch: function() { return this.getParameter('q') } });
future-analytics/cartodb
lib/assets/javascripts/cartodb/models/organization.js
JavaScript
bsd-3-clause
3,194
var test = require("test"); try { require("a"); require("A"); test.assert(false, "should fail to require alternate spelling"); } catch (error) { } test.print("DONE", "info");
kriskowal/mr
test/case-sensitive/program.js
JavaScript
bsd-3-clause
187
var cdb = require('cartodb.js-v3'); var _ = require('underscore-cdb-v3'); /** * Model for an individual WMS/WMTS layer. */ module.exports = cdb.core.Model.extend({ defaults: { state: 'idle', //, saving, saveDone, saveFail layer: undefined // set after saveDone }, canSave: function(baseLayers) { return !_.any(baseLayers.custom(), function(customLayer) { return customLayer.get('name') === this.get('title'); }, this); }, save: function() { this.set('state', 'saving'); this._shouldBeProxied() ? this._createProxiedLayer() : this._newTileLayer(); }, _shouldBeProxied: function() { if (this.get('type') === 'wmts') { var supportedMatrixSets = cdb.admin.WMSService.supportedMatrixSets(this.get('matrix_sets') || []); return supportedMatrixSets.length > 0; } return true; }, _createProxiedLayer: function() { var self = this; var w = new cdb.admin.WMSService({ wms_url: this.url(), title: this.get('title'), name: this.get('name'), layer: this.get('name'), srs: this.get('srs'), bounding_boxes: this.get('llbbox'), type: this.get('type'), // wms/wmts matrix_sets: this.get('matrix_sets') }); // Event tracking "WMS layer selected" cdb.god.trigger('metrics', 'select_wms', { email: window.user_data.email }); var self = this; w.save({}, { success: function(m) { var tileLayer; try { tileLayer = m.newTileLayer(); } catch(e) { } if (tileLayer) { self._setNewTileLayer(tileLayer); } else { self.set('state', 'saveFail'); } }, error: function() { self.set('state', 'saveFail'); } }); return w; }, _setNewTileLayer: function(tileLayer) { this.set({ state: 'saveDone', tileLayer: tileLayer }); }, _newTileLayer: function() { var tileLayer = cdb.admin.TileLayer.byCustomURL(this._xyzURLTemplate(), false); tileLayer.set({ name: this.get('title') || this.get('name'), attribution: this.get('attribution'), bounding_boxes: this.get('llbbox') }); this._setNewTileLayer(tileLayer); return tileLayer; }, _xyzURLTemplate: function() { var urlTemplate = this.get('url_template') || ''; // Convert the proxy template variables to XYZ format, http://foo.com/bar/%%(z)s/%%(x)s/%%(y)s.png" return urlTemplate.replace(/%%\((\w)\)s/g, '{$1}'); } });
codeandtheory/cartodb
lib/assets/javascripts/cartodb/common/dialogs/add_custom_basemap/wms/layer_model.js
JavaScript
bsd-3-clause
2,510
'use strict'; angular.module('copayApp.controllers').controller('walletHomeController', function($scope, $rootScope, $timeout, $filter, $modal, $log, notification, txStatus, isCordova, profileService, lodash, configService, rateService, storageService, bitcore, isChromeApp, gettext, gettextCatalog, nodeWebkit, addressService, feeService, bwsError, utilService) { var self = this; $rootScope.hideMenuBar = false; $rootScope.wpInputFocused = false; $scope.currentSpendUnconfirmed = configService.getSync().wallet.spendUnconfirmed; // INIT var config = configService.getSync().wallet.settings; this.unitToSatoshi = config.unitToSatoshi; this.satToUnit = 1 / this.unitToSatoshi; this.unitName = config.unitName; this.alternativeIsoCode = config.alternativeIsoCode; this.alternativeName = config.alternativeName; this.alternativeAmount = 0; this.unitDecimals = config.unitDecimals; this.isCordova = isCordova; this.addresses = []; this.isMobile = isMobile.any(); this.isWindowsPhoneApp = isMobile.Windows() && isCordova; this.blockUx = false; this.isRateAvailable = false; this.showScanner = false; this.isMobile = isMobile.any(); this.addr = {}; var disableScannerListener = $rootScope.$on('dataScanned', function(event, data) { self.setForm(data); $rootScope.$emit('Local/SetTab', 'send'); var form = $scope.sendForm; if (form.address.$invalid) { self.resetForm(); self.error = gettext('Could not recognize a valid Bitcoin QR Code'); } }); var disablePaymentUriListener = $rootScope.$on('paymentUri', function(event, uri) { $timeout(function() { $rootScope.$emit('Local/SetTab', 'send'); self.setForm(uri); }, 100); }); var disableAddrListener = $rootScope.$on('Local/NeedNewAddress', function() { self.setAddress(true); }); var disableFocusListener = $rootScope.$on('Local/NewFocusedWallet', function() { self.addr = {}; self.resetForm(); }); var disableResumeListener = $rootScope.$on('Local/Resume', function() { // This is needed then the apps go to sleep self.bindTouchDown(); }); var disableTabListener = $rootScope.$on('Local/TabChanged', function(e, tab) { // This will slow down switch, do not add things here! switch (tab) { case 'receive': // just to be sure we have an address self.setAddress(); break; case 'send': self.resetError(); }; }); var disableOngoingProcessListener = $rootScope.$on('Addon/OngoingProcess', function(e, name) { self.setOngoingProcess(name); }); $scope.$on('$destroy', function() { disableAddrListener(); disableScannerListener(); disablePaymentUriListener(); disableTabListener(); disableFocusListener(); disableResumeListener(); disableOngoingProcessListener(); $rootScope.hideMenuBar = false; }); rateService.whenAvailable(function() { self.isRateAvailable = true; $rootScope.$digest(); }); var accept_msg = gettextCatalog.getString('Accept'); var cancel_msg = gettextCatalog.getString('Cancel'); var confirm_msg = gettextCatalog.getString('Confirm'); $scope.openCopayersModal = function(copayers, copayerId) { var fc = profileService.focusedClient; var ModalInstanceCtrl = function($scope, $modalInstance) { $scope.copayers = copayers; $scope.copayerId = copayerId; $scope.color = fc.backgroundColor; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }; var modalInstance = $modal.open({ templateUrl: 'views/modals/copayers.html', windowClass: 'full animated slideInUp', controller: ModalInstanceCtrl, }); modalInstance.result.finally(function() { var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass('slideOutDown'); }); }; $scope.openWalletsModal = function(wallets) { var ModalInstanceCtrl = function($scope, $modalInstance) { $scope.wallets = wallets; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; $scope.selectWallet = function(walletId, walletName) { $scope.gettingAddress = true; $scope.selectedWalletName = walletName; $timeout(function() { $scope.$apply(); }); addressService.getAddress(walletId, false, function(err, addr) { $scope.gettingAddress = false; if (err) { self.error = err; $modalInstance.dismiss('cancel'); return; } $modalInstance.close(addr); }); }; }; var modalInstance = $modal.open({ templateUrl: 'views/modals/wallets.html', windowClass: 'full animated slideInUp', controller: ModalInstanceCtrl, }); modalInstance.result.finally(function() { var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass('slideOutDown'); }); modalInstance.result.then(function(addr) { if (addr) { self.setForm(addr); } }); }; this.openTxpModal = function(tx, copayers) { var fc = profileService.focusedClient; var refreshUntilItChanges = false; var currentSpendUnconfirmed = $scope.currentSpendUnconfirmed; var ModalInstanceCtrl = function($scope, $modalInstance) { $scope.error = null; $scope.tx = tx; $scope.copayers = copayers $scope.copayerId = fc.credentials.copayerId; $scope.canSign = fc.canSign(); $scope.loading = null; $scope.color = fc.backgroundColor; refreshUntilItChanges = false; $scope.currentSpendUnconfirmed = currentSpendUnconfirmed; $scope.getShortNetworkName = function() { return fc.credentials.networkName.substring(0, 4); }; lodash.each(['TxProposalRejectedBy', 'TxProposalAcceptedBy', 'transactionProposalRemoved', 'TxProposalRemoved', 'NewOutgoingTx'], function(eventName) { $rootScope.$on(eventName, function() { fc.getTx($scope.tx.id, function(err, tx) { if (err) { if (err.code && err.code == 'BADREQUEST' && (eventName == 'transactionProposalRemoved' || eventName == 'TxProposalRemoved')) { $scope.tx.removed = true; $scope.tx.canBeRemoved = false; $scope.tx.pendingForUs = false; $scope.$apply(); return; } return; } var action = lodash.find(tx.actions, { copayerId: fc.credentials.copayerId }); $scope.tx = utilService.processTx(tx); if (!action && tx.status == 'pending') $scope.tx.pendingForUs = true; $scope.updateCopayerList(); $scope.$apply(); }); }); }); $scope.updateCopayerList = function() { lodash.map($scope.copayers, function(cp) { lodash.each($scope.tx.actions, function(ac) { if (cp.id == ac.copayerId) { cp.action = ac.type; } }); }); }; $scope.sign = function(txp) { var fc = profileService.focusedClient; if (!fc.canSign()) return; if (fc.isPrivKeyEncrypted()) { profileService.unlockFC(function(err) { if (err) { $scope.error = bwsError.msg(err); return; } return $scope.sign(txp); }); return; }; self.setOngoingProcess(gettext('Signing payment')); $scope.loading = true; $scope.error = null; $timeout(function() { fc.signTxProposal(txp, function(err, txpsi) { profileService.lockFC(); self.setOngoingProcess(); if (err) { $scope.loading = false; $scope.error = bwsError.msg(err, gettextCatalog.getString('Could not accept payment')); $scope.$digest(); } else { //if txp has required signatures then broadcast it var txpHasRequiredSignatures = txpsi.status == 'accepted'; if (txpHasRequiredSignatures) { self.setOngoingProcess(gettext('Broadcasting transaction')); $scope.loading = true; fc.broadcastTxProposal(txpsi, function(err, txpsb, memo) { self.setOngoingProcess(); $scope.loading = false; if (err) { $scope.error = bwsError.msg(err, gettextCatalog.getString('Could not broadcast payment')); $scope.$digest(); } else { $log.debug('Transaction signed and broadcasted') if (memo) $log.info(memo); refreshUntilItChanges = true; $modalInstance.close(txpsb); } }); } else { $scope.loading = false; $modalInstance.close(txpsi); } } }); }, 100); }; $scope.reject = function(txp) { self.setOngoingProcess(gettext('Rejecting payment')); $scope.loading = true; $scope.error = null; $timeout(function() { fc.rejectTxProposal(txp, null, function(err, txpr) { self.setOngoingProcess(); $scope.loading = false; if (err) { $scope.error = bwsError.msg(err, gettextCatalog.getString('Could not reject payment')); $scope.$digest(); } else { $modalInstance.close(txpr); } }); }, 100); }; $scope.remove = function(txp) { self.setOngoingProcess(gettext('Deleting payment')); $scope.loading = true; $scope.error = null; $timeout(function() { fc.removeTxProposal(txp, function(err, txpb) { self.setOngoingProcess(); $scope.loading = false; // Hacky: request tries to parse an empty response if (err && !(err.message && err.message.match(/Unexpected/))) { $scope.error = bwsError.msg(err, gettextCatalog.getString('Could not delete payment proposal')); $scope.$digest(); return; } $modalInstance.close(); }); }, 100); }; $scope.broadcast = function(txp) { self.setOngoingProcess(gettext('Broadcasting Payment')); $scope.loading = true; $scope.error = null; $timeout(function() { fc.broadcastTxProposal(txp, function(err, txpb, memo) { self.setOngoingProcess(); $scope.loading = false; if (err) { $scope.error = bwsError.msg(err, gettextCatalog.getString('Could not broadcast payment')); $scope.$digest(); } else { if (memo) $log.info(memo); refreshUntilItChanges = true; $modalInstance.close(txpb); } }); }, 100); }; $scope.copyAddress = function(addr) { if (!addr) return; self.copyAddress(addr); }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }; var modalInstance = $modal.open({ templateUrl: 'views/modals/txp-details.html', windowClass: 'full animated slideInRight', controller: ModalInstanceCtrl, }); modalInstance.result.finally(function() { var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass('slideOutRight'); }); modalInstance.result.then(function(txp) { self.setOngoingProcess(); if (txp) { txStatus.notify(txp, function() { $scope.$emit('Local/TxProposalAction', refreshUntilItChanges); }); } else { $timeout(function() { $scope.$emit('Local/TxProposalAction', refreshUntilItChanges); }, 100); } }); }; this.setAddress = function(forceNew) { self.addrError = null; var fc = profileService.focusedClient; if (!fc) return; // Address already set? if (!forceNew && self.addr[fc.credentials.walletId]) { return; } self.generatingAddress = true; $timeout(function() { addressService.getAddress(fc.credentials.walletId, forceNew, function(err, addr) { self.generatingAddress = false; if (err) { self.addrError = err; } else { if (addr) self.addr[fc.credentials.walletId] = addr; } $scope.$digest(); }); }); }; this.copyAddress = function(addr) { if (isCordova) { window.cordova.plugins.clipboard.copy(addr); window.plugins.toast.showShortCenter(gettextCatalog.getString('Copied to clipboard')); } else if (nodeWebkit.isDefined()) { nodeWebkit.writeToClipboard(addr); } }; this.shareAddress = function(addr) { if (isCordova) { if (isMobile.Android() || isMobile.Windows()) { window.ignoreMobilePause = true; } window.plugins.socialsharing.share('bitcoin:' + addr, null, null, null); } }; this.openCustomizedAmountModal = function(addr) { var self = this; var fc = profileService.focusedClient; var ModalInstanceCtrl = function($scope, $modalInstance) { $scope.addr = addr; $scope.color = fc.backgroundColor; $scope.unitName = self.unitName; $scope.alternativeAmount = self.alternativeAmount; $scope.alternativeName = self.alternativeName; $scope.alternativeIsoCode = self.alternativeIsoCode; $scope.isRateAvailable = self.isRateAvailable; $scope.unitToSatoshi = self.unitToSatoshi; $scope.unitDecimals = self.unitDecimals; var satToUnit = 1 / self.unitToSatoshi; $scope.showAlternative = false; Object.defineProperty($scope, "_customAlternative", { get: function() { return $scope.customAlternative; }, set: function(newValue) { $scope.customAlternative = newValue; if (typeof(newValue) === 'number' && $scope.isRateAvailable) { $scope.customAmount = parseFloat((rateService.fromFiat(newValue, $scope.alternativeIsoCode) * satToUnit).toFixed($scope.unitDecimals), 10); } else { $scope.customAmount = null; } }, enumerable: true, configurable: true }); Object.defineProperty($scope, "_customAmount", { get: function() { return $scope.customAmount; }, set: function(newValue) { $scope.customAmount = newValue; if (typeof(newValue) === 'number' && $scope.isRateAvailable) { $scope.customAlternative = parseFloat((rateService.toFiat(newValue * $scope.unitToSatoshi, $scope.alternativeIsoCode)).toFixed(2), 10); } else { $scope.customAlternative = null; } $scope.alternativeAmount = $scope.customAlternative; }, enumerable: true, configurable: true }); $scope.submitForm = function(form) { var satToBtc = 1 / 100000000; var amount = form.amount.$modelValue; var amountSat = parseInt((amount * $scope.unitToSatoshi).toFixed(0)); $timeout(function() { $scope.customizedAmountUnit = amount + ' ' + $scope.unitName; $scope.customizedAlternativeUnit = $filter('noFractionNumber')(form.alternative.$modelValue, 2) + ' ' + $scope.alternativeIsoCode; if ($scope.unitName == 'bits') { amount = (amountSat * satToBtc).toFixed(8); } $scope.customizedAmountBtc = amount; }, 1); }; $scope.toggleAlternative = function() { $scope.showAlternative = !$scope.showAlternative; }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }; var modalInstance = $modal.open({ templateUrl: 'views/modals/customized-amount.html', windowClass: 'full animated slideInUp', controller: ModalInstanceCtrl, }); modalInstance.result.finally(function() { var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass('slideOutDown'); }); }; // Send var unwatchSpendUnconfirmed = $scope.$watch('currentSpendUnconfirmed', function(newVal, oldVal) { if (newVal == oldVal) return; $scope.currentSpendUnconfirmed = newVal; }); $scope.$on('$destroy', function() { unwatchSpendUnconfirmed(); }); this.canShowAlternative = function() { return $scope.showAlternative; }; this.showAlternative = function() { $scope.showAlternative = true; }; this.hideAlternative = function() { $scope.showAlternative = false; }; this.resetError = function() { this.error = this.success = null; }; this.bindTouchDown = function(tries) { var self = this; tries = tries || 0; if (tries > 5) return; var e = document.getElementById('menu-walletHome'); if (!e) return $timeout(function() { self.bindTouchDown(++tries); }, 500); // on touchdown elements $log.debug('Binding touchstart elements...'); ['hamburger', 'menu-walletHome', 'menu-send', 'menu-receive', 'menu-history'].forEach(function(id) { var e = document.getElementById(id); if (e) e.addEventListener('touchstart', function() { try { event.preventDefault(); } catch (e) {}; angular.element(e).triggerHandler('click'); }, true); }); } this.hideMenuBar = lodash.debounce(function(hide) { if (hide) { $rootScope.hideMenuBar = true; this.bindTouchDown(); } else { $rootScope.hideMenuBar = false; } $rootScope.$digest(); }, 100); this.formFocus = function(what) { if (isCordova && !this.isWindowsPhoneApp) { this.hideMenuBar(what); } if (!this.isWindowsPhoneApp) return if (!what) { this.hideAddress = false; this.hideAmount = false; } else { if (what == 'amount') { this.hideAddress = true; } else if (what == 'msg') { this.hideAddress = true; this.hideAmount = true; } } $timeout(function() { $rootScope.$digest(); }, 1); }; this.setSendFormInputs = function() { var unitToSat = this.unitToSatoshi; var satToUnit = 1 / unitToSat; /** * Setting the two related amounts as properties prevents an infinite * recursion for watches while preserving the original angular updates * */ Object.defineProperty($scope, "_alternative", { get: function() { return $scope.__alternative; }, set: function(newValue) { $scope.__alternative = newValue; if (typeof(newValue) === 'number' && self.isRateAvailable) { $scope._amount = parseFloat((rateService.fromFiat(newValue, self.alternativeIsoCode) * satToUnit).toFixed(self.unitDecimals), 10); } else { $scope.__amount = null; } }, enumerable: true, configurable: true }); Object.defineProperty($scope, "_amount", { get: function() { return $scope.__amount; }, set: function(newValue) { $scope.__amount = newValue; if (typeof(newValue) === 'number' && self.isRateAvailable) { $scope.__alternative = parseFloat((rateService.toFiat(newValue * self.unitToSatoshi, self.alternativeIsoCode)).toFixed(2), 10); } else { $scope.__alternative = null; } self.alternativeAmount = $scope.__alternative; self.resetError(); }, enumerable: true, configurable: true }); Object.defineProperty($scope, "_address", { get: function() { return $scope.__address; }, set: function(newValue) { $scope.__address = self.onAddressChange(newValue); }, enumerable: true, configurable: true }); }; this.setSendError = function(err) { var fc = profileService.focusedClient; var prefix = fc.credentials.m > 1 ? gettextCatalog.getString('Could not create payment proposal') : gettextCatalog.getString('Could not send payment'); this.error = bwsError.msg(err, prefix); $timeout(function() { $scope.$digest(); }, 1); }; this.setOngoingProcess = function(name) { var self = this; self.blockUx = !!name; if (isCordova) { if (name) { window.plugins.spinnerDialog.hide(); window.plugins.spinnerDialog.show(null, name + '...', true); } else { window.plugins.spinnerDialog.hide(); } } else { self.onGoingProcess = name; $timeout(function() { $rootScope.$apply(); }); }; }; this.setFee = function(level) { this.currentSendFeeLevel = level; }; this.submitForm = function() { var fc = profileService.focusedClient; var unitToSat = this.unitToSatoshi; if (isCordova && this.isWindowsPhoneApp) { this.hideAddress = false; this.hideAmount = false; } var form = $scope.sendForm; if (form.$invalid) { this.error = gettext('Unable to send transaction proposal'); return; } if (fc.isPrivKeyEncrypted()) { profileService.unlockFC(function(err) { if (err) return self.setSendError(err); return self.submitForm(); }); return; }; self.setOngoingProcess(gettext('Creating transaction')); $timeout(function() { var comment = form.comment.$modelValue; var paypro = self._paypro; var address, amount; address = form.address.$modelValue; amount = parseInt((form.amount.$modelValue * unitToSat).toFixed(0)); var getFee = function(cb) { if (form.feePerKb) { cb(null, form.feePerKb); } else { feeService.getCurrentFeeValue(self.currentSendFeeLevel, cb); } }; getFee(function(err, feePerKb) { if (err) $log.debug(err); fc.sendTxProposal({ toAddress: address, amount: amount, message: comment, payProUrl: paypro ? paypro.url : null, feePerKb: feePerKb, excludeUnconfirmedUtxos: $scope.currentSpendUnconfirmed ? false : true }, function(err, txp) { if (err) { self.setOngoingProcess(); profileService.lockFC(); return self.setSendError(err); } if (!fc.canSign()) { $log.info('No signing proposal: No private key') self.setOngoingProcess(); self.resetForm(); txStatus.notify(txp, function() { return $scope.$emit('Local/TxProposalAction'); }); return; } self.signAndBroadcast(txp, function(err) { self.setOngoingProcess(); profileService.lockFC(); self.resetForm(); if (err) { self.error = err.message ? err.message : gettext('The payment was created but could not be completed. Please try again from home screen'); $scope.$emit('Local/TxProposalAction'); $timeout(function() { $scope.$digest(); }, 1); } }); }); }); }, 100); }; this.signAndBroadcast = function(txp, cb) { var fc = profileService.focusedClient; self.setOngoingProcess(gettext('Signing transaction')); fc.signTxProposal(txp, function(err, signedTx) { profileService.lockFC(); self.setOngoingProcess(); if (err) { err.message = bwsError.msg(err, gettextCatalog.getString('The payment was created but could not be signed. Please try again from home screen')); return cb(err); } if (signedTx.status == 'accepted') { self.setOngoingProcess(gettext('Broadcasting transaction')); fc.broadcastTxProposal(signedTx, function(err, btx, memo) { self.setOngoingProcess(); if (err) { err.message = bwsError.msg(err, gettextCatalog.getString('The payment was signed but could not be broadcasted. Please try again from home screen')); return cb(err); } if (memo) $log.info(memo); txStatus.notify(btx, function() { $scope.$emit('Local/TxProposalAction', true); return cb(); }); }); } else { self.setOngoingProcess(); txStatus.notify(signedTx, function() { $scope.$emit('Local/TxProposalAction'); return cb(); }); } }); }; this.setForm = function(to, amount, comment, feeRate) { var form = $scope.sendForm; if (to) { form.address.$setViewValue(to); form.address.$isValid = true; form.address.$render(); this.lockAddress = true; } if (amount) { form.amount.$setViewValue("" + amount); form.amount.$isValid = true; form.amount.$render(); this.lockAmount = true; } if (comment) { form.comment.$setViewValue(comment); form.comment.$isValid = true; form.comment.$render(); } if (feeRate) { form.feeRate = feeRate; } }; this.resetForm = function() { this.resetError(); this._paypro = null; this.lockAddress = false; this.lockAmount = false; this.currentSendFeeLevel = null; this.hideAdvSend = true; $scope.currentSpendUnconfirmed = configService.getSync().wallet.spendUnconfirmed; this._amount = this._address = null; var form = $scope.sendForm; if (form && form.feeRate) { form.feeRate = null; } if (form && form.amount) { form.amount.$pristine = true; form.amount.$setViewValue(''); form.amount.$render(); form.comment.$setViewValue(''); form.comment.$render(); form.$setPristine(); if (form.address) { form.address.$pristine = true; form.address.$setViewValue(''); form.address.$render(); } } $timeout(function() { $rootScope.$digest(); }, 1); }; this.openPPModal = function(paypro) { var ModalInstanceCtrl = function($scope, $modalInstance) { var fc = profileService.focusedClient; var satToUnit = 1 / self.unitToSatoshi; $scope.paypro = paypro; $scope.alternative = self.alternativeAmount; $scope.alternativeIsoCode = self.alternativeIsoCode; $scope.isRateAvailable = self.isRateAvailable; $scope.unitTotal = (paypro.amount * satToUnit).toFixed(self.unitDecimals); $scope.unitName = self.unitName; $scope.color = fc.backgroundColor; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }; var modalInstance = $modal.open({ templateUrl: 'views/modals/paypro.html', windowClass: 'full animated slideInUp', controller: ModalInstanceCtrl, }); modalInstance.result.finally(function() { var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass('slideOutDown'); }); }; this.setFromPayPro = function(uri) { var fc = profileService.focusedClient; if (isChromeApp) { this.error = gettext('Payment Protocol not supported on Chrome App'); return; } var satToUnit = 1 / this.unitToSatoshi; var self = this; /// Get information of payment if using Payment Protocol self.setOngoingProcess(gettext('Fetching Payment Information')); $log.debug('Fetch PayPro Request...', uri); $timeout(function() { fc.fetchPayPro({ payProUrl: uri, }, function(err, paypro) { self.setOngoingProcess(); if (err) { $log.warn(err); self.resetForm(); var msg = err.toString(); if (msg.match('HTTP')) { msg = gettext('Could not fetch payment information'); } self.error = msg; } else { self._paypro = paypro; self.setForm(paypro.toAddress, (paypro.amount * satToUnit).toFixed(self.unitDecimals), paypro.memo); } }); }, 1); }; this.setFromUri = function(uri) { function sanitizeUri(uri) { // Fixes when a region uses comma to separate decimals var regex = /[\?\&]amount=(\d+([\,\.]\d+)?)/i; var match = regex.exec(uri); if (!match || match.length === 0) { return uri; } var value = match[0].replace(',', '.'); var newUri = uri.replace(regex, value); return newUri; }; var satToUnit = 1 / this.unitToSatoshi; uri = sanitizeUri(uri); if (!bitcore.URI.isValid(uri)) { return uri; } var parsed = new bitcore.URI(uri); var addr = parsed.address.toString(); var message = parsed.message; if (parsed.r) return this.setFromPayPro(parsed.r); var amount = parsed.amount ? (parsed.amount.toFixed(0) * satToUnit).toFixed(this.unitDecimals) : 0; this.setForm(addr, amount, message); return addr; }; this.onAddressChange = function(value) { this.resetError(); if (!value) return ''; if (this._paypro) return value; if (value.indexOf('bitcoin:') === 0) { return this.setFromUri(value); } else if (/^https?:\/\//.test(value)) { return this.setFromPayPro(value); } else { return value; } }; // History function strip(number) { return (parseFloat(number.toPrecision(12))); } this.getUnitName = function() { return this.unitName; }; this.getAlternativeIsoCode = function() { return this.alternativeIsoCode; }; this.openTxModal = function(btx) { var self = this; var fc = profileService.focusedClient; var ModalInstanceCtrl = function($scope, $modalInstance) { $scope.btx = btx; $scope.settings = config; $scope.color = fc.backgroundColor; $scope.copayerId = fc.credentials.copayerId; $scope.isShared = fc.credentials.n > 1; $scope.getAmount = function(amount) { return self.getAmount(amount); }; $scope.getUnitName = function() { return self.getUnitName(); }; $scope.getShortNetworkName = function() { var n = fc.credentials.network; return n.substring(0, 4); }; $scope.copyAddress = function(addr) { if (!addr) return; self.copyAddress(addr); }; $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; }; var modalInstance = $modal.open({ templateUrl: 'views/modals/tx-details.html', windowClass: 'full animated slideInRight', controller: ModalInstanceCtrl, }); modalInstance.result.finally(function() { var m = angular.element(document.getElementsByClassName('reveal-modal')); m.addClass('slideOutRight'); }); }; this.hasAction = function(actions, action) { return actions.hasOwnProperty('create'); }; this._doSendAll = function(amount, feeRate) { this.setForm(null, amount, null, feeRate); }; this.confirmDialog = function(msg, cb) { if (isCordova) { navigator.notification.confirm( msg, function(buttonIndex) { if (buttonIndex == 1) { $timeout(function() { return cb(true); }, 1); } else { return cb(false); } }, confirm_msg, [accept_msg, cancel_msg] ); } else if (isChromeApp) { // No feedback, alert/confirm not supported. return cb(true); } else { return cb(confirm(msg)); } }; this.sendAll = function(amount, feeStr, feeRate) { var self = this; var msg = gettextCatalog.getString("{{fee}} will be discounted for bitcoin networking fees", { fee: feeStr }); this.confirmDialog(msg, function(confirmed) { if (confirmed) self._doSendAll(amount, feeRate); }); }; /* Start setup */ this.bindTouchDown(); this.setAddress(); this.setSendFormInputs(); });
FuzzyHobbit/copay
src/js/controllers/walletHome.js
JavaScript
mit
32,485
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = { // Options.jsx items_per_page: '/ 쪽', jump_to: '이동하기', page: '', // Pagination.jsx prev_page: '이전 페이지', next_page: '다음 페이지', prev_5: '이전 5 페이지', next_5: '다음 5 페이지', prev_3: '이전 3 페이지', next_3: '다음 3 페이지' }; module.exports = exports['default'];
prodigalyijun/demo-by-antd
node_modules/rc-pagination/lib/locale/ko_KR.js
JavaScript
mit
439
var path = require('path'); var webpack = require('webpack'); var prodCfg = require('./webpack.prod.config'); Object.assign = require('object-assign'); module.exports = Object.assign(prodCfg, { entry: [ 'webpack-dev-server/client?http://localhost:8080/', 'webpack/hot/only-dev-server', './client' ], module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'] } ] }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], devtool: 'inline-source-map', devServer: { hot: true, proxy: { '*': 'http://localhost:' + (process.env.PORT || 3000) } } });
kirbyk/isomorphic-redux
webpack.config.js
JavaScript
mit
729
// check rdns against forward // NOTICE: the functionality of this plugin is duplicated by the // FCrDNS plugin. Consider using it instead. This plugin // may be deprecated in the future. // // To achieve the same results using FCrDNS (in addition to // the additional features), set [reject] no_rdns=true in // connect.fcrdns.ini. // // The FCrDNS plugin uses the white/blacklist functionality in the // access plugin. var dns = require('dns'); // _dns_error handles err from node.dns callbacks. It will always call next() // with a DENYDISCONNECT for this plugin. function _dns_error(connection, next, err, host, plugin, nxdomain, dnserror) { switch (err.code) { case dns.NXDOMAIN: connection.loginfo(plugin, 'could not find a address for ' + host + '. Disconnecting.'); next(DENYDISCONNECT, 'Sorry we could not find address for ' + host + '. ' + nxdomain); break; default: connection.loginfo(plugin, 'encountered an error when looking up ' + host + '. Disconnecting.'); next(DENYDISCONNECT, 'Sorry we encountered an error when ' + 'looking up ' + host + '. ' + dnserror); break; } } function _in_whitelist(connection, plugin, address) { var domain = address.toLowerCase(); var host_list = plugin.config.get('lookup_rdns.strict.whitelist', 'list'); var host_list_regex = plugin.config.get('lookup_rdns.strict.whitelist_regex', 'list'); connection.logdebug(plugin, "Checking if " + address + " is in the " + "lookup_rdns.strict.whitelist files"); var i; for (i in host_list) { connection.logdebug(plugin, "checking " + domain + " against " + host_list[i]); if (host_list[i].toLowerCase() === domain) { connection.logdebug(plugin, "Allowing " + domain); return 1; } } if (host_list_regex.length) { var regex = new RegExp ('^(?:' + host_list_regex.join('|') + ')$', 'i'); connection.logdebug(plugin, "checking " + domain + " against " + regex.source); if (domain.match(regex)) { connection.logdebug(plugin, "Allowing " + domain); return 1; } } return 0; } exports.hook_lookup_rdns = function (next, connection) { var plugin = this; var total_checks = 0; var called_next = 0; var timeout_id = 0; var config = this.config.get('lookup_rdns.strict.ini'); var rdns = ''; var fwd_nxdomain = config.forward && (config.forward['nxdomain'] || ''); var fwd_dnserror = config.forward && (config.forward['dnserror'] || ''); var rev_nxdomain = config.reverse && (config.reverse['nxdomain'] || ''); var rev_dnserror = config.reverse && (config.reverse['dnserror'] || ''); var nomatch = config.general && (config.general['nomatch'] || ''); var timeout = config.general && (config.general['timeout'] || 60); var timeout_msg = config.general && (config.general['timeout_msg'] || ''); if (_in_whitelist(connection, plugin, connection.remote_ip)) { called_next++; return next(OK, connection.remote_ip); } timeout_id = setTimeout(function () { if (!called_next) { connection.loginfo(plugin, 'timed out when looking up ' + connection.remote_ip + '. Disconnecting.'); called_next++; next(DENYDISCONNECT, '[' + connection.remote_ip + '] ' + timeout_msg); } }, timeout * 1000); dns.reverse(connection.remote_ip, function (err, domains) { if (err) { if (!called_next) { called_next++; clearTimeout(timeout_id); connection.auth_results("iprev=permerror"); _dns_error(connection, next, err, connection.remote_ip, plugin, rev_nxdomain, rev_dnserror); } } else { // Anything this strange needs documentation. Since we are // checking M (A) addresses for N (PTR) records, we need to // keep track of our total progress. That way, at the end, // we know to send an error of nothing has been found. Also, // on err, this helps us figure out if we still have more to check. total_checks = domains.length; // Check whitelist before we start doing a bunch more DNS queries. for(var i = 0; i < domains.length; i++) { if (_in_whitelist(connection, plugin, domains[i])) { called_next++; clearTimeout(timeout_id); return next(OK, domains[i]); } } // Now we should make sure that the reverse response matches // the forward address. Almost no one will have more than one // PTR record for a domain, however, DNS protocol does not // restrict one from having multiple PTR records for the same // address. So here we are, dealing with that case. domains.forEach(function (rdns) { dns.resolve4(rdns, function (err, addresses) { total_checks--; if (err) { if (!called_next && !total_checks) { called_next++; clearTimeout(timeout_id); connection.auth_results("iprev=fail"); _dns_error(connection, next, err, rdns, plugin, fwd_nxdomain, fwd_dnserror); } } else { for (var i = 0; i < addresses.length ; i++) { if (addresses[i] === connection.remote_ip) { // We found a match, call next() and return if (!called_next) { called_next++; clearTimeout(timeout_id); connection.auth_results("iprev=pass"); return next(OK, rdns); } } } if (!called_next && !total_checks) { called_next++; clearTimeout(timeout_id); next(DENYDISCONNECT, rdns + ' [' + connection.remote_ip + '] ' + nomatch); } } }); }); } }); };
danucalovj/Haraka
plugins/lookup_rdns.strict.js
JavaScript
mit
6,842
'use strict'; /** * Module for all communication with LB */ define((require) => { const Util = require('util/util'); const BaseScrobbler = require('scrobbler/base-scrobbler'); const ServiceCallResult = require('object/service-call-result'); const listenBrainzTokenPage = 'https://listenbrainz.org/profile/'; const apiUrl = 'https://api.listenbrainz.org/1/submit-listens'; class ListenBrainz extends BaseScrobbler { /** @override */ async getAuthUrl() { const data = await this.storage.get(); data.isAuthStarted = true; delete data.sessionID; delete data.sessionName; await this.storage.set(data); return 'https://listenbrainz.org/login/musicbrainz?next=%2Fprofile%2F'; } /** @override */ getBaseProfileUrl() { return 'https://listenbrainz.org/user/'; } /** @override */ getId() { return 'listenbrainz'; } /** @override */ getLabel() { return 'ListenBrainz'; } /** @override */ async getProfileUrl() { if (this.userToken) { return null; } return super.getProfileUrl(); } /** @override */ getStatusUrl() { if (this.userToken) { return null; } return 'https://listenbrainz.org/current-status'; } /** @override */ getStorageName() { return 'ListenBrainz'; } /** @override */ getUsedDefinedProperties() { return ['userApiUrl', 'userToken']; } /** @override */ async signOut() { if (this.userApiUrl || this.userToken) { await this.applyUserProperties({ userApiUrl: null, userToken: null, }); } await super.signOut(); } /** @override */ async getSession() { if (this.userToken) { return { sessionID: this.userToken }; } const data = await this.storage.get(); if (data.isAuthStarted) { let session = {}; try { session = await this.requestSession(); } catch (err) { this.debugLog('Failed to get session', 'warn'); await this.signOut(); throw ServiceCallResult.ERROR_AUTH; } data.sessionID = session.sessionID; data.sessionName = session.sessionName; delete data.isAuthStarted; await this.storage.set(data); return session; } else if (!data.sessionID) { throw ServiceCallResult.ERROR_AUTH; } return { sessionID: data.sessionID, sessionName: data.sessionName, }; } /** @override */ async isReadyForGrantAccess() { if (this.userToken) { return false; } const data = await this.storage.get(); return data.isAuthStarted; } /** @override */ async sendNowPlaying(song) { const { sessionID } = await this.getSession(); const trackMeta = this.makeTrackMetadata(song); const params = { listen_type: 'playing_now', payload: [ { track_metadata: trackMeta, }, ], }; return this.sendRequest(params, sessionID); } /** @override */ async scrobble(song) { const { sessionID } = await this.getSession(); const params = { listen_type: 'single', payload: [ { listened_at: song.metadata.startTimestamp, track_metadata: this.makeTrackMetadata(song), }, ], }; return this.sendRequest(params, sessionID); } /** Private methods. */ async sendRequest(params, sessionID) { const requestInfo = { method: 'POST', headers: { Authorization: `Token ${sessionID}`, 'Content-Type': 'application/json; charset=UTF-8', }, body: JSON.stringify(params), }; const promise = fetch(this.userApiUrl || apiUrl, requestInfo); const timeout = BaseScrobbler.REQUEST_TIMEOUT; let result = null; let response = null; try { response = await Util.timeoutPromise(timeout, promise); result = await response.json(); } catch (e) { this.debugLog('Error while sending request', 'error'); throw ServiceCallResult.ERROR_OTHER; } switch (response.status) { case 400: this.debugLog('Invalid JSON sent', 'error'); throw ServiceCallResult.ERROR_AUTH; case 401: this.debugLog('Invalid Authorization sent', 'error'); throw ServiceCallResult.ERROR_AUTH; } this.debugLog(JSON.stringify(result, null, 2)); return this.processResult(result); } async requestSession() { const authUrls = [listenBrainzTokenPage, this.authUrl]; let session = null; for (const url of authUrls) { try { session = await this.fetchSession(url); } catch (e) { this.debugLog('request session timeout', 'warn'); continue; } if (session) { break; } } if (session) { const safeId = Util.hideObjectValue(session.sessionID); this.debugLog(`Session ID: ${safeId}`); return session; } throw ServiceCallResult.ERROR_AUTH; } async fetchSession(url) { this.debugLog(`Use ${url}`); // NOTE: Use 'same-origin' credentials to fix login on Firefox ESR 60. const promise = fetch(url, { method: 'GET', credentials: 'same-origin', }); const timeout = BaseScrobbler.REQUEST_TIMEOUT; const response = await Util.timeoutPromise(timeout, promise); if (response.ok) { const parser = new DOMParser(); const rawHtml = await response.text(); const doc = parser.parseFromString(rawHtml, 'text/html'); let sessionName = null; let sessionID = null; const sessionNameEl = doc.querySelector('.page-title'); const sessionIdEl = doc.querySelector('#auth-token'); if (sessionNameEl) { sessionName = sessionNameEl.textContent; } if (sessionIdEl) { sessionID = sessionIdEl.getAttribute('value'); } if (sessionID && sessionName) { return { sessionID, sessionName }; } } return null; } processResult(result) { if (result.status !== 'ok') { return ServiceCallResult.ERROR_OTHER; } return ServiceCallResult.RESULT_OK; } makeTrackMetadata(song) { const trackMeta = { artist_name: song.getArtist(), track_name: song.getTrack(), additional_info: {}, }; if (song.getAlbum()) { trackMeta.release_name = song.getAlbum(); } if (song.getOriginUrl()) { trackMeta.additional_info.origin_url = song.getOriginUrl(); } if (song.getAlbumArtist()) { trackMeta.additional_info.release_artist_name = song.getAlbumArtist(); } return trackMeta; } } return ListenBrainz; });
galeksandrp/web-scrobbler
src/core/background/scrobbler/listenbrainz-scrobbler.js
JavaScript
mit
6,314
/* MIT License http://www.opensource.org/licenses/mit-license.php */ "use strict"; const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); /** @typedef {import("../MainTemplate")} MainTemplate */ class StartupEntrypointRuntimeModule extends RuntimeModule { constructor(asyncChunkLoading) { super("startup entrypoint"); this.asyncChunkLoading = asyncChunkLoading; } /** * @returns {string} runtime code */ generate() { const { compilation } = this; const { runtimeTemplate } = compilation; return `${ RuntimeGlobals.startupEntrypoint } = ${runtimeTemplate.basicFunction( "chunkIds, moduleId", this.asyncChunkLoading ? `return Promise.all(chunkIds.map(${ RuntimeGlobals.ensureChunk }, __webpack_require__)).then(${runtimeTemplate.returningFunction( "__webpack_require__(moduleId)" )})` : [ `chunkIds.map(${RuntimeGlobals.ensureChunk}, __webpack_require__)`, "return __webpack_require__(moduleId)" ] )}`; } } module.exports = StartupEntrypointRuntimeModule;
arvenil/resume
node_modules/webpack/lib/runtime/StartupEntrypointRuntimeModule.js
JavaScript
mit
1,092
module.exports=/[\u2FF2\u2FF3]/
marclundgren/mithril-fidm-app
node_modules/gulp-jscs/node_modules/jscs/node_modules/unicode-6.3.0/properties/IDS_Trinary_Operator/regex.js
JavaScript
mit
31
steal("can/view/stache/mustache_core.js", "can/view/parser",function(mustacheCore, parser){ return function(source){ var template = mustacheCore.cleanLineEndings(source); var imports = [], inImport = false, inFrom = false; var keepToken = function(){ return inImport ? false : true; }; var intermediate = parser(template, { start: function( tagName, unary ){ if(tagName === "can-import") { inImport = true; } return keepToken(); }, end: function( tagName, unary ){ if(tagName === "can-import") { inImport = false; return false; } return keepToken(); }, attrStart: function( attrName ){ if(attrName === "from") { inFrom = true; } return keepToken(); }, attrEnd: function( attrName ){ if(attrName === "from") { inFrom = false; } return keepToken(); }, attrValue: function( value ){ if(inFrom && inImport) { imports.push(value); } return keepToken(); }, chars: keepToken, comment: keepToken, special: keepToken, done: keepToken }, true); return {intermediate: intermediate, imports: imports}; }; });
beno/canjs
view/stache/intermediate_and_imports.js
JavaScript
mit
1,176
var gulp = require('gulp'); var browserSync = require('browser-sync'); var paths = require('../paths'); // this task utilizes the browsersync plugin // to create a dev server instance // at http://localhost:9000 gulp.task('e2e-serve', ['e2e-build'], function(done) { browserSync({ open: false, port: 9000, server: { baseDir: ["."], middleware: function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); next(); } } }, done); });
Mordred/aurelia-compiler
build/tasks/e2e-serve.js
JavaScript
mit
504
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- function write(v) { WScript.Echo(v + ""); } function foo() {} write(undefined >= undefined); write(undefined >= null); write(undefined >= true); write(undefined >= false); write(undefined >= Boolean(true)); write(undefined >= Boolean(false)); write(undefined >= new Boolean(true)); write(undefined >= new Boolean(false)); write(undefined >= NaN); write(undefined >= +0); write(undefined >= -0); write(undefined >= 0); write(undefined >= 0.0); write(undefined >= -0.0); write(undefined >= +0.0); write(undefined >= 1); write(undefined >= 10); write(undefined >= 10.0); write(undefined >= 10.1); write(undefined >= -1); write(undefined >= -10); write(undefined >= -10.0); write(undefined >= -10.1); write(undefined >= Number.MAX_VALUE); write(undefined >= Number.MIN_VALUE); write(undefined >= Number.NaN); write(undefined >= Number.POSITIVE_INFINITY); write(undefined >= Number.NEGATIVE_INFINITY); write(undefined >= new Number(NaN)); write(undefined >= new Number(+0)); write(undefined >= new Number(-0)); write(undefined >= new Number(0)); write(undefined >= new Number(0.0)); write(undefined >= new Number(-0.0)); write(undefined >= new Number(+0.0)); write(undefined >= new Number(1)); write(undefined >= new Number(10)); write(undefined >= new Number(10.0)); write(undefined >= new Number(10.1)); write(undefined >= new Number(-1)); write(undefined >= new Number(-10)); write(undefined >= new Number(-10.0)); write(undefined >= new Number(-10.1)); write(undefined >= new Number(Number.MAX_VALUE)); write(undefined >= new Number(Number.MIN_VALUE)); write(undefined >= new Number(Number.NaN)); write(undefined >= new Number(Number.POSITIVE_INFINITY)); write(undefined >= new Number(Number.NEGATIVE_INFINITY)); write(undefined >= ''); write(undefined >= 0xa); write(undefined >= 04); write(undefined >= 'hello'); write(undefined >= 'hel' + 'lo'); write(undefined >= String('')); write(undefined >= String('hello')); write(undefined >= String('h' + 'ello')); write(undefined >= new String('')); write(undefined >= new String('hello')); write(undefined >= new String('he' + 'llo')); write(undefined >= new Object()); write(undefined >= new Object()); write(undefined >= [1, 2, 3]); write(undefined >= [1 ,2 , 3]); write(undefined >= new Array(3)); write(undefined >= Array(3)); write(undefined >= new Array(1 ,2 ,3)); write(undefined >= Array(1)); write(undefined >= foo); write(null >= undefined); write(null >= null); write(null >= true); write(null >= false); write(null >= Boolean(true)); write(null >= Boolean(false)); write(null >= new Boolean(true)); write(null >= new Boolean(false)); write(null >= NaN); write(null >= +0); write(null >= -0); write(null >= 0); write(null >= 0.0); write(null >= -0.0); write(null >= +0.0); write(null >= 1); write(null >= 10); write(null >= 10.0); write(null >= 10.1); write(null >= -1); write(null >= -10); write(null >= -10.0); write(null >= -10.1); write(null >= Number.MAX_VALUE); write(null >= Number.MIN_VALUE); write(null >= Number.NaN); write(null >= Number.POSITIVE_INFINITY); write(null >= Number.NEGATIVE_INFINITY); write(null >= new Number(NaN)); write(null >= new Number(+0)); write(null >= new Number(-0)); write(null >= new Number(0)); write(null >= new Number(0.0)); write(null >= new Number(-0.0)); write(null >= new Number(+0.0)); write(null >= new Number(1)); write(null >= new Number(10)); write(null >= new Number(10.0)); write(null >= new Number(10.1)); write(null >= new Number(-1)); write(null >= new Number(-10)); write(null >= new Number(-10.0)); write(null >= new Number(-10.1)); write(null >= new Number(Number.MAX_VALUE)); write(null >= new Number(Number.MIN_VALUE)); write(null >= new Number(Number.NaN)); write(null >= new Number(Number.POSITIVE_INFINITY)); write(null >= new Number(Number.NEGATIVE_INFINITY)); write(null >= ''); write(null >= 0xa); write(null >= 04); write(null >= 'hello'); write(null >= 'hel' + 'lo'); write(null >= String('')); write(null >= String('hello')); write(null >= String('h' + 'ello')); write(null >= new String('')); write(null >= new String('hello')); write(null >= new String('he' + 'llo')); write(null >= new Object()); write(null >= new Object()); write(null >= [1, 2, 3]); write(null >= [1 ,2 , 3]); write(null >= new Array(3)); write(null >= Array(3)); write(null >= new Array(1 ,2 ,3)); write(null >= Array(1)); write(null >= foo); write(true >= undefined); write(true >= null); write(true >= true); write(true >= false); write(true >= Boolean(true)); write(true >= Boolean(false)); write(true >= new Boolean(true)); write(true >= new Boolean(false)); write(true >= NaN); write(true >= +0); write(true >= -0); write(true >= 0); write(true >= 0.0); write(true >= -0.0); write(true >= +0.0); write(true >= 1); write(true >= 10); write(true >= 10.0); write(true >= 10.1); write(true >= -1); write(true >= -10); write(true >= -10.0); write(true >= -10.1); write(true >= Number.MAX_VALUE); write(true >= Number.MIN_VALUE); write(true >= Number.NaN); write(true >= Number.POSITIVE_INFINITY); write(true >= Number.NEGATIVE_INFINITY); write(true >= new Number(NaN)); write(true >= new Number(+0)); write(true >= new Number(-0)); write(true >= new Number(0)); write(true >= new Number(0.0)); write(true >= new Number(-0.0)); write(true >= new Number(+0.0)); write(true >= new Number(1)); write(true >= new Number(10)); write(true >= new Number(10.0)); write(true >= new Number(10.1)); write(true >= new Number(-1)); write(true >= new Number(-10)); write(true >= new Number(-10.0)); write(true >= new Number(-10.1)); write(true >= new Number(Number.MAX_VALUE)); write(true >= new Number(Number.MIN_VALUE)); write(true >= new Number(Number.NaN)); write(true >= new Number(Number.POSITIVE_INFINITY)); write(true >= new Number(Number.NEGATIVE_INFINITY)); write(true >= ''); write(true >= 0xa); write(true >= 04); write(true >= 'hello'); write(true >= 'hel' + 'lo'); write(true >= String('')); write(true >= String('hello')); write(true >= String('h' + 'ello')); write(true >= new String('')); write(true >= new String('hello')); write(true >= new String('he' + 'llo')); write(true >= new Object()); write(true >= new Object()); write(true >= [1, 2, 3]); write(true >= [1 ,2 , 3]); write(true >= new Array(3)); write(true >= Array(3)); write(true >= new Array(1 ,2 ,3)); write(true >= Array(1)); write(true >= foo); write(false >= undefined); write(false >= null); write(false >= true); write(false >= false); write(false >= Boolean(true)); write(false >= Boolean(false)); write(false >= new Boolean(true)); write(false >= new Boolean(false)); write(false >= NaN); write(false >= +0); write(false >= -0); write(false >= 0); write(false >= 0.0); write(false >= -0.0); write(false >= +0.0); write(false >= 1); write(false >= 10); write(false >= 10.0); write(false >= 10.1); write(false >= -1); write(false >= -10); write(false >= -10.0); write(false >= -10.1); write(false >= Number.MAX_VALUE); write(false >= Number.MIN_VALUE); write(false >= Number.NaN); write(false >= Number.POSITIVE_INFINITY); write(false >= Number.NEGATIVE_INFINITY); write(false >= new Number(NaN)); write(false >= new Number(+0)); write(false >= new Number(-0)); write(false >= new Number(0)); write(false >= new Number(0.0)); write(false >= new Number(-0.0)); write(false >= new Number(+0.0)); write(false >= new Number(1)); write(false >= new Number(10)); write(false >= new Number(10.0)); write(false >= new Number(10.1)); write(false >= new Number(-1)); write(false >= new Number(-10)); write(false >= new Number(-10.0)); write(false >= new Number(-10.1)); write(false >= new Number(Number.MAX_VALUE)); write(false >= new Number(Number.MIN_VALUE)); write(false >= new Number(Number.NaN)); write(false >= new Number(Number.POSITIVE_INFINITY)); write(false >= new Number(Number.NEGATIVE_INFINITY)); write(false >= ''); write(false >= 0xa); write(false >= 04); write(false >= 'hello'); write(false >= 'hel' + 'lo'); write(false >= String('')); write(false >= String('hello')); write(false >= String('h' + 'ello')); write(false >= new String('')); write(false >= new String('hello')); write(false >= new String('he' + 'llo')); write(false >= new Object()); write(false >= new Object()); write(false >= [1, 2, 3]); write(false >= [1 ,2 , 3]); write(false >= new Array(3)); write(false >= Array(3)); write(false >= new Array(1 ,2 ,3)); write(false >= Array(1)); write(false >= foo); write(Boolean(true) >= undefined); write(Boolean(true) >= null); write(Boolean(true) >= true); write(Boolean(true) >= false); write(Boolean(true) >= Boolean(true)); write(Boolean(true) >= Boolean(false)); write(Boolean(true) >= new Boolean(true)); write(Boolean(true) >= new Boolean(false)); write(Boolean(true) >= NaN); write(Boolean(true) >= +0); write(Boolean(true) >= -0); write(Boolean(true) >= 0); write(Boolean(true) >= 0.0); write(Boolean(true) >= -0.0); write(Boolean(true) >= +0.0); write(Boolean(true) >= 1); write(Boolean(true) >= 10); write(Boolean(true) >= 10.0); write(Boolean(true) >= 10.1); write(Boolean(true) >= -1); write(Boolean(true) >= -10); write(Boolean(true) >= -10.0); write(Boolean(true) >= -10.1); write(Boolean(true) >= Number.MAX_VALUE); write(Boolean(true) >= Number.MIN_VALUE); write(Boolean(true) >= Number.NaN); write(Boolean(true) >= Number.POSITIVE_INFINITY); write(Boolean(true) >= Number.NEGATIVE_INFINITY); write(Boolean(true) >= new Number(NaN)); write(Boolean(true) >= new Number(+0)); write(Boolean(true) >= new Number(-0)); write(Boolean(true) >= new Number(0)); write(Boolean(true) >= new Number(0.0)); write(Boolean(true) >= new Number(-0.0)); write(Boolean(true) >= new Number(+0.0)); write(Boolean(true) >= new Number(1)); write(Boolean(true) >= new Number(10)); write(Boolean(true) >= new Number(10.0)); write(Boolean(true) >= new Number(10.1)); write(Boolean(true) >= new Number(-1)); write(Boolean(true) >= new Number(-10)); write(Boolean(true) >= new Number(-10.0)); write(Boolean(true) >= new Number(-10.1)); write(Boolean(true) >= new Number(Number.MAX_VALUE)); write(Boolean(true) >= new Number(Number.MIN_VALUE)); write(Boolean(true) >= new Number(Number.NaN)); write(Boolean(true) >= new Number(Number.POSITIVE_INFINITY)); write(Boolean(true) >= new Number(Number.NEGATIVE_INFINITY)); write(Boolean(true) >= ''); write(Boolean(true) >= 0xa); write(Boolean(true) >= 04); write(Boolean(true) >= 'hello'); write(Boolean(true) >= 'hel' + 'lo'); write(Boolean(true) >= String('')); write(Boolean(true) >= String('hello')); write(Boolean(true) >= String('h' + 'ello')); write(Boolean(true) >= new String('')); write(Boolean(true) >= new String('hello')); write(Boolean(true) >= new String('he' + 'llo')); write(Boolean(true) >= new Object()); write(Boolean(true) >= new Object()); write(Boolean(true) >= [1, 2, 3]); write(Boolean(true) >= [1 ,2 , 3]); write(Boolean(true) >= new Array(3)); write(Boolean(true) >= Array(3)); write(Boolean(true) >= new Array(1 ,2 ,3)); write(Boolean(true) >= Array(1)); write(Boolean(true) >= foo); write(Boolean(false) >= undefined); write(Boolean(false) >= null); write(Boolean(false) >= true); write(Boolean(false) >= false); write(Boolean(false) >= Boolean(true)); write(Boolean(false) >= Boolean(false)); write(Boolean(false) >= new Boolean(true)); write(Boolean(false) >= new Boolean(false)); write(Boolean(false) >= NaN); write(Boolean(false) >= +0); write(Boolean(false) >= -0); write(Boolean(false) >= 0); write(Boolean(false) >= 0.0); write(Boolean(false) >= -0.0); write(Boolean(false) >= +0.0); write(Boolean(false) >= 1); write(Boolean(false) >= 10); write(Boolean(false) >= 10.0); write(Boolean(false) >= 10.1); write(Boolean(false) >= -1); write(Boolean(false) >= -10); write(Boolean(false) >= -10.0); write(Boolean(false) >= -10.1); write(Boolean(false) >= Number.MAX_VALUE); write(Boolean(false) >= Number.MIN_VALUE); write(Boolean(false) >= Number.NaN); write(Boolean(false) >= Number.POSITIVE_INFINITY); write(Boolean(false) >= Number.NEGATIVE_INFINITY); write(Boolean(false) >= new Number(NaN)); write(Boolean(false) >= new Number(+0)); write(Boolean(false) >= new Number(-0)); write(Boolean(false) >= new Number(0)); write(Boolean(false) >= new Number(0.0)); write(Boolean(false) >= new Number(-0.0)); write(Boolean(false) >= new Number(+0.0)); write(Boolean(false) >= new Number(1)); write(Boolean(false) >= new Number(10)); write(Boolean(false) >= new Number(10.0)); write(Boolean(false) >= new Number(10.1)); write(Boolean(false) >= new Number(-1)); write(Boolean(false) >= new Number(-10)); write(Boolean(false) >= new Number(-10.0)); write(Boolean(false) >= new Number(-10.1)); write(Boolean(false) >= new Number(Number.MAX_VALUE)); write(Boolean(false) >= new Number(Number.MIN_VALUE)); write(Boolean(false) >= new Number(Number.NaN)); write(Boolean(false) >= new Number(Number.POSITIVE_INFINITY)); write(Boolean(false) >= new Number(Number.NEGATIVE_INFINITY)); write(Boolean(false) >= ''); write(Boolean(false) >= 0xa); write(Boolean(false) >= 04); write(Boolean(false) >= 'hello'); write(Boolean(false) >= 'hel' + 'lo'); write(Boolean(false) >= String('')); write(Boolean(false) >= String('hello')); write(Boolean(false) >= String('h' + 'ello')); write(Boolean(false) >= new String('')); write(Boolean(false) >= new String('hello')); write(Boolean(false) >= new String('he' + 'llo')); write(Boolean(false) >= new Object()); write(Boolean(false) >= new Object()); write(Boolean(false) >= [1, 2, 3]); write(Boolean(false) >= [1 ,2 , 3]); write(Boolean(false) >= new Array(3)); write(Boolean(false) >= Array(3)); write(Boolean(false) >= new Array(1 ,2 ,3)); write(Boolean(false) >= Array(1)); write(Boolean(false) >= foo); write(new Boolean(true) >= undefined); write(new Boolean(true) >= null); write(new Boolean(true) >= true); write(new Boolean(true) >= false); write(new Boolean(true) >= Boolean(true)); write(new Boolean(true) >= Boolean(false)); write(new Boolean(true) >= new Boolean(true)); write(new Boolean(true) >= new Boolean(false)); write(new Boolean(true) >= NaN); write(new Boolean(true) >= +0); write(new Boolean(true) >= -0); write(new Boolean(true) >= 0); write(new Boolean(true) >= 0.0); write(new Boolean(true) >= -0.0); write(new Boolean(true) >= +0.0); write(new Boolean(true) >= 1); write(new Boolean(true) >= 10); write(new Boolean(true) >= 10.0); write(new Boolean(true) >= 10.1); write(new Boolean(true) >= -1); write(new Boolean(true) >= -10); write(new Boolean(true) >= -10.0); write(new Boolean(true) >= -10.1); write(new Boolean(true) >= Number.MAX_VALUE); write(new Boolean(true) >= Number.MIN_VALUE); write(new Boolean(true) >= Number.NaN); write(new Boolean(true) >= Number.POSITIVE_INFINITY); write(new Boolean(true) >= Number.NEGATIVE_INFINITY); write(new Boolean(true) >= new Number(NaN)); write(new Boolean(true) >= new Number(+0)); write(new Boolean(true) >= new Number(-0)); write(new Boolean(true) >= new Number(0)); write(new Boolean(true) >= new Number(0.0)); write(new Boolean(true) >= new Number(-0.0)); write(new Boolean(true) >= new Number(+0.0)); write(new Boolean(true) >= new Number(1)); write(new Boolean(true) >= new Number(10)); write(new Boolean(true) >= new Number(10.0)); write(new Boolean(true) >= new Number(10.1)); write(new Boolean(true) >= new Number(-1)); write(new Boolean(true) >= new Number(-10)); write(new Boolean(true) >= new Number(-10.0)); write(new Boolean(true) >= new Number(-10.1)); write(new Boolean(true) >= new Number(Number.MAX_VALUE)); write(new Boolean(true) >= new Number(Number.MIN_VALUE)); write(new Boolean(true) >= new Number(Number.NaN)); write(new Boolean(true) >= new Number(Number.POSITIVE_INFINITY)); write(new Boolean(true) >= new Number(Number.NEGATIVE_INFINITY)); write(new Boolean(true) >= ''); write(new Boolean(true) >= 0xa); write(new Boolean(true) >= 04); write(new Boolean(true) >= 'hello'); write(new Boolean(true) >= 'hel' + 'lo'); write(new Boolean(true) >= String('')); write(new Boolean(true) >= String('hello')); write(new Boolean(true) >= String('h' + 'ello')); write(new Boolean(true) >= new String('')); write(new Boolean(true) >= new String('hello')); write(new Boolean(true) >= new String('he' + 'llo')); write(new Boolean(true) >= new Object()); write(new Boolean(true) >= new Object()); write(new Boolean(true) >= [1, 2, 3]); write(new Boolean(true) >= [1 ,2 , 3]); write(new Boolean(true) >= new Array(3)); write(new Boolean(true) >= Array(3)); write(new Boolean(true) >= new Array(1 ,2 ,3)); write(new Boolean(true) >= Array(1)); write(new Boolean(true) >= foo); write(new Boolean(false) >= undefined); write(new Boolean(false) >= null); write(new Boolean(false) >= true); write(new Boolean(false) >= false); write(new Boolean(false) >= Boolean(true)); write(new Boolean(false) >= Boolean(false)); write(new Boolean(false) >= new Boolean(true)); write(new Boolean(false) >= new Boolean(false)); write(new Boolean(false) >= NaN); write(new Boolean(false) >= +0); write(new Boolean(false) >= -0); write(new Boolean(false) >= 0); write(new Boolean(false) >= 0.0); write(new Boolean(false) >= -0.0); write(new Boolean(false) >= +0.0); write(new Boolean(false) >= 1); write(new Boolean(false) >= 10); write(new Boolean(false) >= 10.0); write(new Boolean(false) >= 10.1); write(new Boolean(false) >= -1); write(new Boolean(false) >= -10); write(new Boolean(false) >= -10.0); write(new Boolean(false) >= -10.1); write(new Boolean(false) >= Number.MAX_VALUE); write(new Boolean(false) >= Number.MIN_VALUE); write(new Boolean(false) >= Number.NaN); write(new Boolean(false) >= Number.POSITIVE_INFINITY); write(new Boolean(false) >= Number.NEGATIVE_INFINITY); write(new Boolean(false) >= new Number(NaN)); write(new Boolean(false) >= new Number(+0)); write(new Boolean(false) >= new Number(-0)); write(new Boolean(false) >= new Number(0)); write(new Boolean(false) >= new Number(0.0)); write(new Boolean(false) >= new Number(-0.0)); write(new Boolean(false) >= new Number(+0.0)); write(new Boolean(false) >= new Number(1)); write(new Boolean(false) >= new Number(10)); write(new Boolean(false) >= new Number(10.0)); write(new Boolean(false) >= new Number(10.1)); write(new Boolean(false) >= new Number(-1)); write(new Boolean(false) >= new Number(-10)); write(new Boolean(false) >= new Number(-10.0)); write(new Boolean(false) >= new Number(-10.1)); write(new Boolean(false) >= new Number(Number.MAX_VALUE)); write(new Boolean(false) >= new Number(Number.MIN_VALUE)); write(new Boolean(false) >= new Number(Number.NaN)); write(new Boolean(false) >= new Number(Number.POSITIVE_INFINITY)); write(new Boolean(false) >= new Number(Number.NEGATIVE_INFINITY)); write(new Boolean(false) >= ''); write(new Boolean(false) >= 0xa); write(new Boolean(false) >= 04); write(new Boolean(false) >= 'hello'); write(new Boolean(false) >= 'hel' + 'lo'); write(new Boolean(false) >= String('')); write(new Boolean(false) >= String('hello')); write(new Boolean(false) >= String('h' + 'ello')); write(new Boolean(false) >= new String('')); write(new Boolean(false) >= new String('hello')); write(new Boolean(false) >= new String('he' + 'llo')); write(new Boolean(false) >= new Object()); write(new Boolean(false) >= new Object()); write(new Boolean(false) >= [1, 2, 3]); write(new Boolean(false) >= [1 ,2 , 3]); write(new Boolean(false) >= new Array(3)); write(new Boolean(false) >= Array(3)); write(new Boolean(false) >= new Array(1 ,2 ,3)); write(new Boolean(false) >= Array(1)); write(new Boolean(false) >= foo); write(NaN >= undefined); write(NaN >= null); write(NaN >= true); write(NaN >= false); write(NaN >= Boolean(true)); write(NaN >= Boolean(false)); write(NaN >= new Boolean(true)); write(NaN >= new Boolean(false)); write(NaN >= NaN); write(NaN >= +0); write(NaN >= -0); write(NaN >= 0); write(NaN >= 0.0); write(NaN >= -0.0); write(NaN >= +0.0); write(NaN >= 1); write(NaN >= 10); write(NaN >= 10.0); write(NaN >= 10.1); write(NaN >= -1); write(NaN >= -10); write(NaN >= -10.0); write(NaN >= -10.1); write(NaN >= Number.MAX_VALUE); write(NaN >= Number.MIN_VALUE); write(NaN >= Number.NaN); write(NaN >= Number.POSITIVE_INFINITY); write(NaN >= Number.NEGATIVE_INFINITY); write(NaN >= new Number(NaN)); write(NaN >= new Number(+0)); write(NaN >= new Number(-0)); write(NaN >= new Number(0)); write(NaN >= new Number(0.0)); write(NaN >= new Number(-0.0)); write(NaN >= new Number(+0.0)); write(NaN >= new Number(1)); write(NaN >= new Number(10)); write(NaN >= new Number(10.0)); write(NaN >= new Number(10.1)); write(NaN >= new Number(-1)); write(NaN >= new Number(-10)); write(NaN >= new Number(-10.0)); write(NaN >= new Number(-10.1)); write(NaN >= new Number(Number.MAX_VALUE)); write(NaN >= new Number(Number.MIN_VALUE)); write(NaN >= new Number(Number.NaN)); write(NaN >= new Number(Number.POSITIVE_INFINITY)); write(NaN >= new Number(Number.NEGATIVE_INFINITY)); write(NaN >= ''); write(NaN >= 0xa); write(NaN >= 04); write(NaN >= 'hello'); write(NaN >= 'hel' + 'lo'); write(NaN >= String('')); write(NaN >= String('hello')); write(NaN >= String('h' + 'ello')); write(NaN >= new String('')); write(NaN >= new String('hello')); write(NaN >= new String('he' + 'llo')); write(NaN >= new Object()); write(NaN >= new Object()); write(NaN >= [1, 2, 3]); write(NaN >= [1 ,2 , 3]); write(NaN >= new Array(3)); write(NaN >= Array(3)); write(NaN >= new Array(1 ,2 ,3)); write(NaN >= Array(1)); write(NaN >= foo); write(+0 >= undefined); write(+0 >= null); write(+0 >= true); write(+0 >= false); write(+0 >= Boolean(true)); write(+0 >= Boolean(false)); write(+0 >= new Boolean(true)); write(+0 >= new Boolean(false)); write(+0 >= NaN); write(+0 >= +0); write(+0 >= -0); write(+0 >= 0); write(+0 >= 0.0); write(+0 >= -0.0); write(+0 >= +0.0); write(+0 >= 1); write(+0 >= 10); write(+0 >= 10.0); write(+0 >= 10.1); write(+0 >= -1); write(+0 >= -10); write(+0 >= -10.0); write(+0 >= -10.1); write(+0 >= Number.MAX_VALUE); write(+0 >= Number.MIN_VALUE); write(+0 >= Number.NaN); write(+0 >= Number.POSITIVE_INFINITY); write(+0 >= Number.NEGATIVE_INFINITY); write(+0 >= new Number(NaN)); write(+0 >= new Number(+0)); write(+0 >= new Number(-0)); write(+0 >= new Number(0)); write(+0 >= new Number(0.0)); write(+0 >= new Number(-0.0)); write(+0 >= new Number(+0.0)); write(+0 >= new Number(1)); write(+0 >= new Number(10)); write(+0 >= new Number(10.0)); write(+0 >= new Number(10.1)); write(+0 >= new Number(-1)); write(+0 >= new Number(-10)); write(+0 >= new Number(-10.0)); write(+0 >= new Number(-10.1)); write(+0 >= new Number(Number.MAX_VALUE)); write(+0 >= new Number(Number.MIN_VALUE)); write(+0 >= new Number(Number.NaN)); write(+0 >= new Number(Number.POSITIVE_INFINITY)); write(+0 >= new Number(Number.NEGATIVE_INFINITY)); write(+0 >= ''); write(+0 >= 0xa); write(+0 >= 04); write(+0 >= 'hello'); write(+0 >= 'hel' + 'lo'); write(+0 >= String('')); write(+0 >= String('hello')); write(+0 >= String('h' + 'ello')); write(+0 >= new String('')); write(+0 >= new String('hello')); write(+0 >= new String('he' + 'llo')); write(+0 >= new Object()); write(+0 >= new Object()); write(+0 >= [1, 2, 3]); write(+0 >= [1 ,2 , 3]); write(+0 >= new Array(3)); write(+0 >= Array(3)); write(+0 >= new Array(1 ,2 ,3)); write(+0 >= Array(1)); write(+0 >= foo); write(-0 >= undefined); write(-0 >= null); write(-0 >= true); write(-0 >= false); write(-0 >= Boolean(true)); write(-0 >= Boolean(false)); write(-0 >= new Boolean(true)); write(-0 >= new Boolean(false)); write(-0 >= NaN); write(-0 >= +0); write(-0 >= -0); write(-0 >= 0); write(-0 >= 0.0); write(-0 >= -0.0); write(-0 >= +0.0); write(-0 >= 1); write(-0 >= 10); write(-0 >= 10.0); write(-0 >= 10.1); write(-0 >= -1); write(-0 >= -10); write(-0 >= -10.0); write(-0 >= -10.1); write(-0 >= Number.MAX_VALUE); write(-0 >= Number.MIN_VALUE); write(-0 >= Number.NaN); write(-0 >= Number.POSITIVE_INFINITY); write(-0 >= Number.NEGATIVE_INFINITY); write(-0 >= new Number(NaN)); write(-0 >= new Number(+0)); write(-0 >= new Number(-0)); write(-0 >= new Number(0)); write(-0 >= new Number(0.0)); write(-0 >= new Number(-0.0)); write(-0 >= new Number(+0.0)); write(-0 >= new Number(1)); write(-0 >= new Number(10)); write(-0 >= new Number(10.0)); write(-0 >= new Number(10.1)); write(-0 >= new Number(-1)); write(-0 >= new Number(-10)); write(-0 >= new Number(-10.0)); write(-0 >= new Number(-10.1)); write(-0 >= new Number(Number.MAX_VALUE)); write(-0 >= new Number(Number.MIN_VALUE)); write(-0 >= new Number(Number.NaN)); write(-0 >= new Number(Number.POSITIVE_INFINITY)); write(-0 >= new Number(Number.NEGATIVE_INFINITY)); write(-0 >= ''); write(-0 >= 0xa); write(-0 >= 04); write(-0 >= 'hello'); write(-0 >= 'hel' + 'lo'); write(-0 >= String('')); write(-0 >= String('hello')); write(-0 >= String('h' + 'ello')); write(-0 >= new String('')); write(-0 >= new String('hello')); write(-0 >= new String('he' + 'llo')); write(-0 >= new Object()); write(-0 >= new Object()); write(-0 >= [1, 2, 3]); write(-0 >= [1 ,2 , 3]); write(-0 >= new Array(3)); write(-0 >= Array(3)); write(-0 >= new Array(1 ,2 ,3)); write(-0 >= Array(1)); write(-0 >= foo); write(0 >= undefined); write(0 >= null); write(0 >= true); write(0 >= false); write(0 >= Boolean(true)); write(0 >= Boolean(false)); write(0 >= new Boolean(true)); write(0 >= new Boolean(false)); write(0 >= NaN); write(0 >= +0); write(0 >= -0); write(0 >= 0); write(0 >= 0.0); write(0 >= -0.0); write(0 >= +0.0); write(0 >= 1); write(0 >= 10); write(0 >= 10.0); write(0 >= 10.1); write(0 >= -1); write(0 >= -10); write(0 >= -10.0); write(0 >= -10.1); write(0 >= Number.MAX_VALUE); write(0 >= Number.MIN_VALUE); write(0 >= Number.NaN); write(0 >= Number.POSITIVE_INFINITY); write(0 >= Number.NEGATIVE_INFINITY); write(0 >= new Number(NaN)); write(0 >= new Number(+0)); write(0 >= new Number(-0)); write(0 >= new Number(0)); write(0 >= new Number(0.0)); write(0 >= new Number(-0.0)); write(0 >= new Number(+0.0)); write(0 >= new Number(1)); write(0 >= new Number(10)); write(0 >= new Number(10.0)); write(0 >= new Number(10.1)); write(0 >= new Number(-1)); write(0 >= new Number(-10)); write(0 >= new Number(-10.0)); write(0 >= new Number(-10.1)); write(0 >= new Number(Number.MAX_VALUE)); write(0 >= new Number(Number.MIN_VALUE)); write(0 >= new Number(Number.NaN)); write(0 >= new Number(Number.POSITIVE_INFINITY)); write(0 >= new Number(Number.NEGATIVE_INFINITY)); write(0 >= ''); write(0 >= 0xa); write(0 >= 04); write(0 >= 'hello'); write(0 >= 'hel' + 'lo'); write(0 >= String('')); write(0 >= String('hello')); write(0 >= String('h' + 'ello')); write(0 >= new String('')); write(0 >= new String('hello')); write(0 >= new String('he' + 'llo')); write(0 >= new Object()); write(0 >= new Object()); write(0 >= [1, 2, 3]); write(0 >= [1 ,2 , 3]); write(0 >= new Array(3)); write(0 >= Array(3)); write(0 >= new Array(1 ,2 ,3)); write(0 >= Array(1)); write(0 >= foo); write(0.0 >= undefined); write(0.0 >= null); write(0.0 >= true); write(0.0 >= false); write(0.0 >= Boolean(true)); write(0.0 >= Boolean(false)); write(0.0 >= new Boolean(true)); write(0.0 >= new Boolean(false)); write(0.0 >= NaN); write(0.0 >= +0); write(0.0 >= -0); write(0.0 >= 0); write(0.0 >= 0.0); write(0.0 >= -0.0); write(0.0 >= +0.0); write(0.0 >= 1); write(0.0 >= 10); write(0.0 >= 10.0); write(0.0 >= 10.1); write(0.0 >= -1); write(0.0 >= -10); write(0.0 >= -10.0); write(0.0 >= -10.1); write(0.0 >= Number.MAX_VALUE); write(0.0 >= Number.MIN_VALUE); write(0.0 >= Number.NaN); write(0.0 >= Number.POSITIVE_INFINITY); write(0.0 >= Number.NEGATIVE_INFINITY); write(0.0 >= new Number(NaN)); write(0.0 >= new Number(+0)); write(0.0 >= new Number(-0)); write(0.0 >= new Number(0)); write(0.0 >= new Number(0.0)); write(0.0 >= new Number(-0.0)); write(0.0 >= new Number(+0.0)); write(0.0 >= new Number(1)); write(0.0 >= new Number(10)); write(0.0 >= new Number(10.0)); write(0.0 >= new Number(10.1)); write(0.0 >= new Number(-1)); write(0.0 >= new Number(-10)); write(0.0 >= new Number(-10.0)); write(0.0 >= new Number(-10.1)); write(0.0 >= new Number(Number.MAX_VALUE)); write(0.0 >= new Number(Number.MIN_VALUE)); write(0.0 >= new Number(Number.NaN)); write(0.0 >= new Number(Number.POSITIVE_INFINITY)); write(0.0 >= new Number(Number.NEGATIVE_INFINITY)); write(0.0 >= ''); write(0.0 >= 0xa); write(0.0 >= 04); write(0.0 >= 'hello'); write(0.0 >= 'hel' + 'lo'); write(0.0 >= String('')); write(0.0 >= String('hello')); write(0.0 >= String('h' + 'ello')); write(0.0 >= new String('')); write(0.0 >= new String('hello')); write(0.0 >= new String('he' + 'llo')); write(0.0 >= new Object()); write(0.0 >= new Object()); write(0.0 >= [1, 2, 3]); write(0.0 >= [1 ,2 , 3]); write(0.0 >= new Array(3)); write(0.0 >= Array(3)); write(0.0 >= new Array(1 ,2 ,3)); write(0.0 >= Array(1)); write(0.0 >= foo); write(-0.0 >= undefined); write(-0.0 >= null); write(-0.0 >= true); write(-0.0 >= false); write(-0.0 >= Boolean(true)); write(-0.0 >= Boolean(false)); write(-0.0 >= new Boolean(true)); write(-0.0 >= new Boolean(false)); write(-0.0 >= NaN); write(-0.0 >= +0); write(-0.0 >= -0); write(-0.0 >= 0); write(-0.0 >= 0.0); write(-0.0 >= -0.0); write(-0.0 >= +0.0); write(-0.0 >= 1); write(-0.0 >= 10); write(-0.0 >= 10.0); write(-0.0 >= 10.1); write(-0.0 >= -1); write(-0.0 >= -10); write(-0.0 >= -10.0); write(-0.0 >= -10.1); write(-0.0 >= Number.MAX_VALUE); write(-0.0 >= Number.MIN_VALUE); write(-0.0 >= Number.NaN); write(-0.0 >= Number.POSITIVE_INFINITY); write(-0.0 >= Number.NEGATIVE_INFINITY); write(-0.0 >= new Number(NaN)); write(-0.0 >= new Number(+0)); write(-0.0 >= new Number(-0)); write(-0.0 >= new Number(0)); write(-0.0 >= new Number(0.0)); write(-0.0 >= new Number(-0.0)); write(-0.0 >= new Number(+0.0)); write(-0.0 >= new Number(1)); write(-0.0 >= new Number(10)); write(-0.0 >= new Number(10.0)); write(-0.0 >= new Number(10.1)); write(-0.0 >= new Number(-1)); write(-0.0 >= new Number(-10)); write(-0.0 >= new Number(-10.0)); write(-0.0 >= new Number(-10.1)); write(-0.0 >= new Number(Number.MAX_VALUE)); write(-0.0 >= new Number(Number.MIN_VALUE)); write(-0.0 >= new Number(Number.NaN)); write(-0.0 >= new Number(Number.POSITIVE_INFINITY)); write(-0.0 >= new Number(Number.NEGATIVE_INFINITY)); write(-0.0 >= ''); write(-0.0 >= 0xa); write(-0.0 >= 04); write(-0.0 >= 'hello'); write(-0.0 >= 'hel' + 'lo'); write(-0.0 >= String('')); write(-0.0 >= String('hello')); write(-0.0 >= String('h' + 'ello')); write(-0.0 >= new String('')); write(-0.0 >= new String('hello')); write(-0.0 >= new String('he' + 'llo')); write(-0.0 >= new Object()); write(-0.0 >= new Object()); write(-0.0 >= [1, 2, 3]); write(-0.0 >= [1 ,2 , 3]); write(-0.0 >= new Array(3)); write(-0.0 >= Array(3)); write(-0.0 >= new Array(1 ,2 ,3)); write(-0.0 >= Array(1)); write(-0.0 >= foo); write(+0.0 >= undefined); write(+0.0 >= null); write(+0.0 >= true); write(+0.0 >= false); write(+0.0 >= Boolean(true)); write(+0.0 >= Boolean(false)); write(+0.0 >= new Boolean(true)); write(+0.0 >= new Boolean(false)); write(+0.0 >= NaN); write(+0.0 >= +0); write(+0.0 >= -0); write(+0.0 >= 0); write(+0.0 >= 0.0); write(+0.0 >= -0.0); write(+0.0 >= +0.0); write(+0.0 >= 1); write(+0.0 >= 10); write(+0.0 >= 10.0); write(+0.0 >= 10.1); write(+0.0 >= -1); write(+0.0 >= -10); write(+0.0 >= -10.0); write(+0.0 >= -10.1); write(+0.0 >= Number.MAX_VALUE); write(+0.0 >= Number.MIN_VALUE); write(+0.0 >= Number.NaN); write(+0.0 >= Number.POSITIVE_INFINITY); write(+0.0 >= Number.NEGATIVE_INFINITY); write(+0.0 >= new Number(NaN)); write(+0.0 >= new Number(+0)); write(+0.0 >= new Number(-0)); write(+0.0 >= new Number(0)); write(+0.0 >= new Number(0.0)); write(+0.0 >= new Number(-0.0)); write(+0.0 >= new Number(+0.0)); write(+0.0 >= new Number(1)); write(+0.0 >= new Number(10)); write(+0.0 >= new Number(10.0)); write(+0.0 >= new Number(10.1)); write(+0.0 >= new Number(-1)); write(+0.0 >= new Number(-10)); write(+0.0 >= new Number(-10.0)); write(+0.0 >= new Number(-10.1)); write(+0.0 >= new Number(Number.MAX_VALUE)); write(+0.0 >= new Number(Number.MIN_VALUE)); write(+0.0 >= new Number(Number.NaN)); write(+0.0 >= new Number(Number.POSITIVE_INFINITY)); write(+0.0 >= new Number(Number.NEGATIVE_INFINITY));
arunetm/ChakraCore_0114
test/Generated/ge.js
JavaScript
mit
33,355
(function() { 'use strict'; /** * @name config * @description config block */ function config($stateProvider) { $stateProvider .state('root.home', { url: '/', views: { '@': { templateUrl: 'src/app/home/home.tpl.html', controller: 'HomeCtrl as home', } } }); } /** * @name HomeCtrl * @description Controller */ function HomeCtrl() { var vm = this; } angular.module('home', []) .config(config) .controller('HomeCtrl', HomeCtrl); })();
lealivran/Moonie
client/src/app/home/home.js
JavaScript
mit
568
// Flags: --expose-internals 'use strict'; require('../common'); const assert = require('assert'); const { sleep } = require('internal/util'); // Make sure we test 0ms timers, since they would had always wanted to run on // the current tick, and greater than 0ms timers, for scenarios where the // outer timer takes longer to complete than the delay of the nested timer. // Since the process of recreating this is identical regardless of the timer // delay, these scenarios are in one test. const scenarios = [0, 100]; scenarios.forEach(function(delay) { let nestedCalled = false; setTimeout(function A() { // Create the nested timer with the same delay as the outer timer so that it // gets added to the current list of timers being processed by // listOnTimeout. setTimeout(function B() { nestedCalled = true; }, delay); // Busy loop for the same timeout used for the nested timer to ensure that // we are in fact expiring the nested timer. sleep(delay); // The purpose of running this assert in nextTick is to make sure it runs // after A but before the next iteration of the libuv event loop. process.nextTick(function() { assert.ok(!nestedCalled); }); // Ensure that the nested callback is indeed called prior to process exit. process.on('exit', function onExit() { assert.ok(nestedCalled); }); }, delay); });
enclose-io/compiler
lts/test/parallel/test-timers-nested.js
JavaScript
mit
1,406
module.exports = require('./lib/test.js');
milesj/boost
packages/log/test.js
JavaScript
mit
43
/**************************************************************************** Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ var UIWidgetAddNodeEditorTest = UIBaseLayer.extend({ ctor: function () { this._super(); var root = this._parseUIFile("ccs-res/cocosui/UIEditorTest/UIWidgetAddNode/widget_add_node.json"); this._mainNode.addChild(root); var back_label =ccui.helper.seekWidgetByName(root, "back"); back_label.addTouchEventListener(this.backEvent,this); var sprite = new cc.Sprite("ccs-res/cocosui/ccicon.png"); sprite.x = 240; sprite.y = 160; root.addNode(sprite,9999); } });
dios-game/dios-cocos
src/oslibs/cocos/cocos-src/tests/js-tests/src/CocoStudioTest/GUITest/UINodeContainerTest/UINodeContainerTest.js
JavaScript
mit
1,893
/* Tabulator v4.0.4 (c) Oliver Folkerd */ !function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):"undefined"!=typeof module&&module.exports?module.exports=t(require("jquery")):t(jQuery)}(function(t,e){t.widget("ui.tabulator",{_create:function(){this.table=new Tabulator(this.element[0],this.options);for(var t in Tabulator.prototype)"function"==typeof Tabulator.prototype[t]&&"_"!==t.charAt(0)&&(this[t]=this.table[t].bind(this.table))},_setOption:function(t,e){console.error("Tabulator jQuery wrapper does not support setting options after the table has been instantiated")},_destroy:function(t,e){this.table.destroy()}})});
sufuf3/cdnjs
ajax/libs/tabulator/4.0.4/js/jquery_wrapper.min.js
JavaScript
mit
655
/*jslint node: true */ "use strict"; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), bower: { install: { options: { install: true, copy: false, targetDir: './libs', cleanTargetDir: true } } }, jshint: { all: ['Gruntfile.js', 'app/*.js', 'app/**/*.js'] }, karma: { options: { configFile: 'config/karma.conf.js' }, unit: { singleRun: true, }, continuous: { singleRun: false, autoWatch: true } }, clean: { temp: { src: ['tmp'] } }, uglify: { dist: { files: { 'dist/app.js': ['dist/app.js'] }, options: { mangle: false } } }, concat: { options: { separator: ';' }, dist: { src: ['app/js/*.js'], dest: 'dist/js/app.js' } }, watch: { dev: { files: ['Gruntfile.js', 'app/js/*.js', '*.html', 'app/templates/*.html'], tasks: ['jshint', 'karma:unit', 'concat:dist', 'clean:temp'], options: { atBegin: true } }, min: { files: ['Gruntfile.js', 'app/*.js', '*.html'], tasks: ['jshint', 'karma:unit', 'concat', 'clean:temp', 'uglify:dist' ], options: { atBegin: true } } }, compress: { dist: { options: { archive: 'dist/<%= pkg.name %>-<%= pkg.version %>.zip' }, files: [{ src: ['index.html'], dest: '/' }, { src: ['dist/**'], dest: 'dist/' }, { src: ['assets/**'], dest: 'assets/' }, { src: ['libs/**'], dest: 'libs/' }] } }, connect: { server: { options: { hostname: 'localhost', port: 8080 } } }, exec: { initnpm: { cmd: 'npm install', }, initbower: { cmd: 'bower install', }, status: { cmd: 'git status' }, add: { cmd: 'git add --all' }, commit: { cmd: 'git commit -m" Version<%= pkg.version %>"' }, push: { cmd: 'git push origin master' } }, bump: { options: { files: ['package.json'], updateConfigs: [], commit: true, commitMessage: 'Release v%VERSION%', commitFiles: ['-a'], createTag: true, tagName: 'v%VERSION%', tagMessage: 'Version %VERSION%', push: true, pushTo: 'origin', gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d', globalReplace: false, prereleaseName: false, regExp: false } }, }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-contrib-compress'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-html2js'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-bower-task'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-exec'); grunt.loadNpmTasks('grunt-bump'); grunt.registerTask('default', ['exec:initnpm', 'exec:initbower']); grunt.registerTask('git', ['exec:status', 'exec:add', 'exec:commit', 'exec:push']); grunt.registerTask('dev', ['bower', 'connect:server', 'watch:dev']); grunt.registerTask('test', ['bower', 'jshint', 'karma:continuous']); grunt.registerTask('minified', ['bower', 'connect:server', 'watch:min']); grunt.registerTask('package', ['bower', 'jshint', 'karma:unit', 'concat:dist', 'uglify:dist', 'clean:temp', 'compress:dist']); };
Fountaintechies/distance-calculator
Gruntfile.js
JavaScript
mit
3,923
var doc = require('./doc'); var dev = require('./dev'); var build = require('./build'); module.exports = { transformAPIModel:doc.transformAPIModel, updateOwnDependenciesFromLocalRepositories:dev.updateOwnDependenciesFromLocalRepositories, buildDevEnv:dev.buildDevEnv, extractImports:build.extractImports, createImportBlock:build.createImportBlock, sortFiles:build.sortFiles };
damianof/tools
src/index.js
JavaScript
mit
390
var exec = require('child_process').exec, fs = require('fs'), path = require('path'), EventEmitter = require('events').EventEmitter; var temp = require('temp'), tasks = require('./tasks'), Q = require('q'); // Map of extensions to tasks var extensions = { gif: 'GIF', jpg: 'JPEG', jpeg: 'JPEG', png: 'PNG' }; var Job = module.exports = function (settings) { var self = this; this.queue = []; this.report = { fileCount: 0, scanned: {}, size: { start: 0, end: 0 }, time: { start: null, end: null } }; this.settings = settings; this.settings.inputs.forEach(function (input) { var files = self.scan(input, 0); files.forEach(function (file) { self.add(file); }); }); }; // Job extends EventEmitter Job.prototype = new EventEmitter; Job.prototype.add = function (filename) { var self = this; // Try to find a task for the current file. If nothing is found, no task is executed var task = tasks[extensions[path.extname(filename).substr(1)]]; if (task) { this.queue.push(function () { return self.compress(filename, task); }); return ++this.report.fileCount; } else { return false; } }; Job.prototype.compress = function (filename, task) { var deferred = Q.defer(), self = this; temp.open('PULVERIZR', function (err, info) { var scratchSpace = info.path; // Copy the old file to a temporary spot exec('cp "' + filename + '" ' + scratchSpace, function (error, stdout, stderr) { task.call(this, { original: filename, filename: scratchSpace, settings: self.settings, deferred: deferred, job: self }).then(function (newStats) { var oldStats = fs.statSync(filename); self.report.size.start += oldStats.size; self.report.size.end += newStats.size; self.emit('compression', { filename: filename, oldSize: oldStats.size, newSize: newStats.size }); // If optimizations were made and this isn't a dry run, copy the new file over if (!self.settings.dryRun && newStats.size < oldStats.size) { fs.renameSync(scratchSpace, filename); } else { // Remove the temporary file fs.unlinkSync(scratchSpace); } }); }); }); return deferred.promise; }; Job.prototype.run = function () { var self = this, result = Q.resolve(); this.emit('start', {}); this.report.time.start = Date.parse(new Date()); // run the queue this.queue.forEach(function (f) { result = result.then(f); }); result.then(function () { var r = self.report; r.time.end = Date.parse(new Date()); self.emit('finish', r); }); }; Job.prototype.scan = function (filename, depth) { var self = this, files = []; (function walk (filename, depth) { var stats = fs.statSync(filename); if (stats.isFile()) { files.push(filename); } else if ((self.settings.recursive || depth === 0) && !self.report.scanned[filename] && stats.isDirectory()) { depth++; fs.readdirSync(filename).forEach(function (_filename) { // Scans the directory, and strips off a trailing slash if it exists walk.call(this, (filename.replace(/(\/)$/g, '') + '/' + _filename), depth); }); } }(filename, 0)); return files; };
vdhwouter/GameNation
src/main/resources/static/node_modules/pulverizr/lib/job.js
JavaScript
mit
3,488
/*jshint node:true */ var fs = require( 'fs' ), config = JSON.parse( fs.readFileSync( __dirname + '/../.jscsrc' ) ); delete config.jsDoc; module.exports = exports = config;
paladox/mediawiki-extensions-MobileFrontend
tests/.jscsrc.js
JavaScript
gpl-2.0
176
var FormSamples = function () { return { //main function to initiate the module init: function () { // use select2 dropdown instead of chosen as select2 works fine with bootstrap on responsive layouts. $('.select2_category').select2({ placeholder: "Select an option", allowClear: true }); $('.select2_sample1').select2({ placeholder: "Select a State", allowClear: true }); $(".select2_sample2").select2({ allowClear: true, minimumInputLength: 1, query: function (query) { var data = { results: [] }, i, j, s; for (i = 1; i < 5; i++) { s = ""; for (j = 0; j < i; j++) { s = s + query.term; } data.results.push({ id: query.term + i, text: s }); } query.callback(data); } }); $(".select2_sample3").select2({ tags: ["red", "green", "blue", "yellow", "pink"] }); } }; }();
kuldeep89/160515
wp-content/themes/ppmlayout/assets/scripts/form-samples.js
JavaScript
gpl-2.0
1,379
module.exports={A:{A:{"2":"H G F C A B SB"},B:{"1":"q W I","2":"D"},C:{"1":"0 1 2 k l m n o p u v w t y r g","2":"3 QB E K H G F C A B D q OB NB","33":"W I L M N O P Q R S T U V s X Y Z a b c d e f J h i j"},D:{"1":"0 1 2 6 9 J h i j k l m n o p u v w t y r g CB RB AB","2":"E K H G F C A B D q W I","33":"R S T U V s X Y Z a b c d e f","66":"L M N O P Q"},E:{"1":"HB IB","2":"7 E K H G F C A BB DB EB FB GB"},F:{"1":"T U V s X Y Z a b c d e f J h i j k l m n o p","2":"4 5 C B D JB KB LB MB PB z","33":"I L M N O P Q R S"},G:{"1":"aB","2":"7 8 F x TB UB VB WB XB YB ZB"},H:{"2":"bB"},I:{"2":"3 E g cB dB eB fB x gB hB"},J:{"2":"G A"},K:{"2":"4 5 A B D J z"},L:{"2":"6"},M:{"2":"r"},N:{"2":"A B"},O:{"2":"iB"},P:{"2":"E"},Q:{"2":"jB"},R:{"2":"kB"}},B:4,C:"PointerLock API"};
nicholaslgoodman/peoples-weather-map
node_modules/caniuse-lite/data/features/pointerlock.js
JavaScript
gpl-2.0
775
/* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ 'use strict'; var spi = require('../Adapter/impl/SPI.js'), dbt_module = require('../Adapter/impl/common/DBTableHandler.js'), DBTableHandler = dbt_module.DBTableHandler, unified_debug = require('../Adapter/api/unified_debug.js'), udebug = unified_debug.getLogger('jscrund_dbspi.js'); function implementation() { }; implementation.prototype = { dbServiceProvider : null, dbConnPool : null, dbSession : null, inBatchMode : false, operations : null }; implementation.prototype.getDefaultProperties = function(adapter) { this.dbServiceProvider = spi.getDBServiceProvider(adapter); return this.dbServiceProvider.getDefaultConnectionProperties(); }; implementation.prototype.close = function(callback) { var impl = this; impl.dbSession.close(function() { impl.dbConnPool.close(callback); }); }; implementation.prototype.initialize = function(options, callback) { udebug.log("initialize"); var impl = this; var mappings = options.annotations; var nmappings = mappings.length; function getMapping(n) { function gotMapping(err, tableMetadata) { udebug.log("gotMapping", n); nmappings--; var dbt = new DBTableHandler(tableMetadata, mappings[n].prototype.mynode.mapping, mappings[n]); udebug.log("Got DBTableHandler", dbt); mappings[n].dbt = dbt; if(nmappings == 0) { callback(null); /* All done */ } } impl.dbConnPool.getTableMetadata(options.properties.database, mappings[n].prototype.mynode.mapping.table, impl.dbSession, gotMapping); } function onDbSession(err, dbSession) { var n; if(err) { callback(err, null); } else { impl.dbSession = dbSession; if(mappings.length) { for(n = 0 ; n < mappings.length ; n++) { getMapping(n); } } else { callback(null); } } } function onConnect(err, dbConnectionPool) { impl.dbConnPool = dbConnectionPool; if(err) { callback(err, null); } else { dbConnectionPool.getDBSession(1, onDbSession); } } impl.dbServiceProvider.connect(options.properties, onConnect); }; implementation.prototype.execOneOperation = function(op, tx, callback, row) { if(this.inBatchMode) { this.operations.push(op); } else { tx.execute([op], function(err) { if(err) console.log("TX EXECUTE ERR:", err, row); }); } }; implementation.prototype.persist = function(parameters, callback) { udebug.log_detail('persist object:', parameters.object); var dbt = parameters.object.constructor.dbt; var tx = this.dbSession.getTransactionHandler(); var op = this.dbSession.buildInsertOperation(dbt, parameters.object, tx, callback); this.execOneOperation(op, tx, callback, parameters.object); }; implementation.prototype.find = function(parameters, callback) { udebug.log_detail('find key:', parameters.key); var dbt = parameters.object.constructor.dbt; var tx = this.dbSession.getTransactionHandler(); var index = dbt.getIndexHandler(parameters.key, true); var op = this.dbSession.buildReadOperation(index, parameters.key, tx, callback); this.execOneOperation(op, tx, callback); }; implementation.prototype.remove = function(parameters, callback) { udebug.log_detail('remove key:', parameters.key); var dbt = parameters.object.constructor.dbt; var tx = this.dbSession.getTransactionHandler(); var index = dbt.getIndexHandler(parameters.key, true); var op = this.dbSession.buildDeleteOperation(index, parameters.key, tx, callback); this.execOneOperation(op, tx, callback); }; implementation.prototype.createBatch = function(callback) { udebug.log_detail('createBatch'); this.operations = []; this.inBatchMode = true; callback(null); }; implementation.prototype.executeBatch = function(callback) { udebug.log_detail('executeBatch'); this.inBatchMode = false; this.dbSession.getTransactionHandler().execute(this.operations, callback); }; implementation.prototype.begin = function(callback) { udebug.log_detail('begin'); this.dbSession.begin(); callback(null); }; implementation.prototype.commit = function(callback) { udebug.log_detail('commit'); this.dbSession.commit(callback); }; exports.implementation = implementation;
greenlion/mysql-server
storage/ndb/nodejs/perftest/jscrund_dbspi.js
JavaScript
gpl-2.0
5,523
//This file is automatically rebuilt by the Cesium build process. /*global define*/ define(function() { "use strict"; return "attribute vec4 position3DAndHeight;\n\ attribute vec3 textureCoordAndEncodedNormals;\n\ \n\ uniform vec3 u_center3D;\n\ uniform mat4 u_modifiedModelView;\n\ uniform vec4 u_tileRectangle;\n\ \n\ // Uniforms for 2D Mercator projection\n\ uniform vec2 u_southAndNorthLatitude;\n\ uniform vec2 u_southMercatorYAndOneOverHeight;\n\ \n\ varying vec3 v_positionMC;\n\ varying vec3 v_positionEC;\n\ \n\ varying vec2 v_textureCoordinates;\n\ varying vec3 v_normalMC;\n\ varying vec3 v_normalEC;\n\ \n\ #ifdef FOG\n\ varying float v_distance;\n\ varying vec3 v_mieColor;\n\ varying vec3 v_rayleighColor;\n\ #endif\n\ \n\ // These functions are generated at runtime.\n\ vec4 getPosition(vec3 position3DWC);\n\ float get2DYPositionFraction();\n\ \n\ vec4 getPosition3DMode(vec3 position3DWC)\n\ {\n\ return czm_projection * (u_modifiedModelView * vec4(position3DAndHeight.xyz, 1.0));\n\ }\n\ \n\ float get2DMercatorYPositionFraction()\n\ {\n\ // The width of a tile at level 11, in radians and assuming a single root tile, is\n\ // 2.0 * czm_pi / pow(2.0, 11.0)\n\ // We want to just linearly interpolate the 2D position from the texture coordinates\n\ // when we're at this level or higher. The constant below is the expression\n\ // above evaluated and then rounded up at the 4th significant digit.\n\ const float maxTileWidth = 0.003068;\n\ float positionFraction = textureCoordAndEncodedNormals.y;\n\ float southLatitude = u_southAndNorthLatitude.x;\n\ float northLatitude = u_southAndNorthLatitude.y;\n\ if (northLatitude - southLatitude > maxTileWidth)\n\ {\n\ float southMercatorY = u_southMercatorYAndOneOverHeight.x;\n\ float oneOverMercatorHeight = u_southMercatorYAndOneOverHeight.y;\n\ \n\ float currentLatitude = mix(southLatitude, northLatitude, textureCoordAndEncodedNormals.y);\n\ currentLatitude = clamp(currentLatitude, -czm_webMercatorMaxLatitude, czm_webMercatorMaxLatitude);\n\ positionFraction = czm_latitudeToWebMercatorFraction(currentLatitude, southMercatorY, oneOverMercatorHeight);\n\ } \n\ return positionFraction;\n\ }\n\ \n\ float get2DGeographicYPositionFraction()\n\ {\n\ return textureCoordAndEncodedNormals.y;\n\ }\n\ \n\ vec4 getPositionPlanarEarth(vec3 position3DWC, float height2D)\n\ {\n\ float yPositionFraction = get2DYPositionFraction();\n\ vec4 rtcPosition2D = vec4(height2D, mix(u_tileRectangle.st, u_tileRectangle.pq, vec2(textureCoordAndEncodedNormals.x, yPositionFraction)), 1.0); \n\ return czm_projection * (u_modifiedModelView * rtcPosition2D);\n\ }\n\ \n\ vec4 getPosition2DMode(vec3 position3DWC)\n\ {\n\ return getPositionPlanarEarth(position3DWC, 0.0);\n\ }\n\ \n\ vec4 getPositionColumbusViewMode(vec3 position3DWC)\n\ {\n\ return getPositionPlanarEarth(position3DWC, position3DAndHeight.w);\n\ }\n\ \n\ vec4 getPositionMorphingMode(vec3 position3DWC)\n\ {\n\ // We do not do RTC while morphing, so there is potential for jitter.\n\ // This is unlikely to be noticeable, though.\n\ float yPositionFraction = get2DYPositionFraction();\n\ vec4 position2DWC = vec4(0.0, mix(u_tileRectangle.st, u_tileRectangle.pq, vec2(textureCoordAndEncodedNormals.x, yPositionFraction)), 1.0);\n\ vec4 morphPosition = czm_columbusViewMorph(position2DWC, vec4(position3DWC, 1.0), czm_morphTime);\n\ return czm_modelViewProjection * morphPosition;\n\ }\n\ \n\ void main() \n\ {\n\ vec3 position3DWC = position3DAndHeight.xyz + u_center3D;\n\ \n\ gl_Position = getPosition(position3DWC);\n\ \n\ #if defined(ENABLE_VERTEX_LIGHTING)\n\ v_positionEC = (czm_modelView3D * vec4(position3DWC, 1.0)).xyz;\n\ v_positionMC = position3DWC; // position in model coordinates\n\ float encodedNormal = textureCoordAndEncodedNormals.z;\n\ v_normalMC = czm_octDecode(encodedNormal);\n\ v_normalEC = czm_normal3D * v_normalMC;\n\ #elif defined(SHOW_REFLECTIVE_OCEAN) || defined(ENABLE_DAYNIGHT_SHADING)\n\ v_positionEC = (czm_modelView3D * vec4(position3DWC, 1.0)).xyz;\n\ v_positionMC = position3DWC; // position in model coordinates\n\ #endif\n\ \n\ v_textureCoordinates = textureCoordAndEncodedNormals.xy;\n\ \n\ #ifdef FOG\n\ AtmosphereColor atmosColor = computeGroundAtmosphereFromSpace(position3DWC);\n\ v_mieColor = atmosColor.mie;\n\ v_rayleighColor = atmosColor.rayleigh;\n\ v_distance = length((czm_modelView3D * vec4(position3DWC, 1.0)).xyz);\n\ #endif\n\ }"; });
nupic-community/nostradamIQ
nostradamIQ-landingpage/webapp/lib/cesium/1.16/Source/Shaders/GlobeVS.js
JavaScript
gpl-3.0
4,687
"use strict"; const whatwgEncoding = require("whatwg-encoding"); const parseContentType = require("content-type-parser"); const querystring = require("querystring"); const DOMException = require("domexception"); const EventTargetImpl = require("../events/EventTarget-impl").implementation; const ProgressEvent = require("../generated/ProgressEvent"); const { setupForSimpleEventAccessors } = require("../helpers/create-event-accessor"); const READY_STATES = Object.freeze({ EMPTY: 0, LOADING: 1, DONE: 2 }); const events = ["loadstart", "progress", "load", "abort", "error", "loadend"]; class FileReaderImpl extends EventTargetImpl { constructor(args, privateData) { super([], privateData); this.error = null; this.readyState = READY_STATES.EMPTY; this.result = null; this._ownerDocument = privateData.window.document; this._terminated = false; } readAsArrayBuffer(file) { this._readFile(file, "buffer"); } readAsDataURL(file) { this._readFile(file, "dataURL"); } readAsText(file, encoding) { this._readFile(file, "text", whatwgEncoding.labelToName(encoding) || "UTF-8"); } abort() { if (this.readyState === READY_STATES.EMPTY || this.readyState === READY_STATES.DONE) { this.result = null; return; } if (this.readyState === READY_STATES.LOADING) { this.readyState = READY_STATES.DONE; this.result = null; } this._terminated = true; this._fireProgressEvent("abort"); this._fireProgressEvent("loadend"); } _fireProgressEvent(name, props) { const event = ProgressEvent.createImpl([name, Object.assign({ bubbles: false, cancelable: false }, props)], {}); this.dispatchEvent(event); } _readFile(file, format, encoding) { if (this.readyState === READY_STATES.LOADING) { throw new DOMException("The object is in an invalid state.", "InvalidStateError"); } this.readyState = READY_STATES.LOADING; setImmediate(() => { if (this._terminated) { this._terminated = false; return; } this._fireProgressEvent("loadstart"); let data = file._buffer; if (!data) { data = Buffer.alloc(0); } this._fireProgressEvent("progress", { lengthComputable: !isNaN(file.size), total: file.size, loaded: data.length }); setImmediate(() => { if (this._terminated) { this._terminated = false; return; } switch (format) { default: case "buffer": { this.result = (new Uint8Array(data)).buffer; break; } case "dataURL": { let dataUrl = "data:"; const contentType = parseContentType(file.type); if (contentType && contentType.isText()) { const fallbackEncoding = whatwgEncoding.getBOMEncoding(data) || whatwgEncoding.labelToName(contentType.get("charset")) || "UTF-8"; const decoded = whatwgEncoding.decode(data, fallbackEncoding); contentType.set("charset", encoding); dataUrl += contentType.toString(); dataUrl += ","; dataUrl += querystring.escape(decoded); } else { if (contentType) { dataUrl += contentType.toString(); } dataUrl += ";base64,"; dataUrl += data.toString("base64"); } this.result = dataUrl; break; } case "text": { this.result = whatwgEncoding.decode(data, encoding); break; } } this.readyState = READY_STATES.DONE; this._fireProgressEvent("load"); this._fireProgressEvent("loadend"); }); }); } } setupForSimpleEventAccessors(FileReaderImpl.prototype, events); exports.implementation = FileReaderImpl;
FreezeWarp/freeze-messenger
stress/node_modules/jsdom/lib/jsdom/living/file-api/FileReader-impl.js
JavaScript
gpl-3.0
3,919
/* * eyeos - The Open Source Cloud's Web Desktop * Version 2.0 * Copyright (C) 2007 - 2010 eyeos Team * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation. * * 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * version 3 along with this program in the file "LICENSE". If not, see * <http://www.gnu.org/licenses/agpl-3.0.txt>. * * See www.eyeos.org for more details. All requests should be sent to [email protected] * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * eyeos" logo and retain the original copyright notice. If the display of the * logo is not reasonably feasible for technical reasons, the Appropriate Legal Notices * must display the words "Powered by eyeos" and retain the original copyright notice. */ /** * eyeos.ui.toolbar.LabelHeader - Styling... * Extending a eyeos.ui.toolbar.ImageHeader, to implement the eyeos * look and feel behaviour. * The two labels will be top-bottom aligned as default, but it can be changed * using the {@see this#order}. */ qx.Class.define('eyeos.ui.toolbar.LabelHeader', { extend : eyeos.ui.toolbar.ImageHeader, construct : function(leftLabel, rightLabel) { arguments.callee.base.call(this, null, null); this.setLeftLabel(leftLabel); this.setRightLabel(rightLabel); this._setEyeosStyle(); }, properties: { /** * the widget's left label. */ leftLabel: { init: null }, /** * the widget's right label. */ rightLabel: { init: null } }, members: { /** * Apply the eyeos look and feel. */ _setEyeosStyle: function() { this.getChildrenContainer().setLayout(new qx.ui.layout.VBox()); this.setDecorator(null); this.removeAll(); var leftButton = new qx.ui.toolbar.Button(tr(this.getLeftLabel())); leftButton.addListener('execute', function() { this.setMode(false); }, this); this.add(leftButton); var rightButton = new qx.ui.toolbar.Button(tr(this.getRightLabel())); rightButton.addListener('execute', function() { this.setMode(true); }, this); this.add(rightButton); this.addListener('changeOrder', function() { switch (this.getOrder()) { case 'left-right': this.getChildrenContainer().setLayout(new qx.ui.layout.HBox()); case 'top-bottom': this.getChildrenContainer().setLayout(new qx.ui.layout.VBox()); } }, this); } } });
cloudspaces/eyeos-u1db
eyeos/extern/js/eyeos.ui.toolbar.LabelHeader.js
JavaScript
agpl-3.0
3,141
/* YUI 3.11.0 (build d549e5c) Copyright 2013 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('matrix', function (Y, NAME) { /** * Matrix utilities. * * @class MatrixUtil * @module matrix **/ var MatrixUtil = { /** * Used as value for the _rounding method. * * @property _rounder * @private */ _rounder: 100000, /** * Rounds values * * @method _round * @private */ _round: function(val) { val = Math.round(val * MatrixUtil._rounder) / MatrixUtil._rounder; return val; }, /** * Converts a radian value to a degree. * * @method rad2deg * @param {Number} rad Radian value to be converted. * @return Number */ rad2deg: function(rad) { var deg = rad * (180 / Math.PI); return deg; }, /** * Converts a degree value to a radian. * * @method deg2rad * @param {Number} deg Degree value to be converted to radian. * @return Number */ deg2rad: function(deg) { var rad = deg * (Math.PI / 180); return rad; }, /** * Converts an angle to a radian * * @method angle2rad * @param {Objecxt} val Value to be converted to radian. * @return Number */ angle2rad: function(val) { if (typeof val === 'string' && val.indexOf('rad') > -1) { val = parseFloat(val); } else { // default to deg val = MatrixUtil.deg2rad(parseFloat(val)); } return val; }, /** * Converts a transform object to an array of column vectors. * * / \ * | matrix[0][0] matrix[1][0] matrix[2][0] | * | matrix[0][1] matrix[1][1] matrix[2][1] | * | matrix[0][2] matrix[1][2] matrix[2][2] | * \ / * * @method getnxn * @return Array */ convertTransformToArray: function(matrix) { var matrixArray = [ [matrix.a, matrix.c, matrix.dx], [matrix.b, matrix.d, matrix.dy], [0, 0, 1] ]; return matrixArray; }, /** * Returns the determinant of a given matrix. * * / \ * | matrix[0][0] matrix[1][0] matrix[2][0] | * | matrix[0][1] matrix[1][1] matrix[2][1] | * | matrix[0][2] matrix[1][2] matrix[2][2] | * | matrix[0][3] matrix[1][3] matrix[2][3] | * \ / * * @method getDeterminant * @param {Array} matrix An nxn matrix represented an array of vector (column) arrays. Each vector array has index for each row. * @return Number */ getDeterminant: function(matrix) { var determinant = 0, len = matrix.length, i = 0, multiplier; if(len == 2) { return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; } for(; i < len; ++i) { multiplier = matrix[i][0]; if(i % 2 === 0 || i === 0) { determinant += multiplier * MatrixUtil.getDeterminant(MatrixUtil.getMinors(matrix, i, 0)); } else { determinant -= multiplier * MatrixUtil.getDeterminant(MatrixUtil.getMinors(matrix, i, 0)); } } return determinant; }, /** * Returns the inverse of a matrix * * @method inverse * @param Array matrix An array representing an nxn matrix * @return Array * * / \ * | matrix[0][0] matrix[1][0] matrix[2][0] | * | matrix[0][1] matrix[1][1] matrix[2][1] | * | matrix[0][2] matrix[1][2] matrix[2][2] | * | matrix[0][3] matrix[1][3] matrix[2][3] | * \ / */ inverse: function(matrix) { var determinant = 0, len = matrix.length, i = 0, j, inverse, adjunct = [], //vector representing 2x2 matrix minor = []; if(len === 2) { determinant = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; inverse = [ [matrix[1][1] * determinant, -matrix[1][0] * determinant], [-matrix[0][1] * determinant, matrix[0][0] * determinant] ]; } else { determinant = MatrixUtil.getDeterminant(matrix); for(; i < len; ++i) { adjunct[i] = []; for(j = 0; j < len; ++j) { minor = MatrixUtil.getMinors(matrix, j, i); adjunct[i][j] = MatrixUtil.getDeterminant(minor); if((i + j) % 2 !== 0 && (i + j) !== 0) { adjunct[i][j] *= -1; } } } inverse = MatrixUtil.scalarMultiply(adjunct, 1/determinant); } return inverse; }, /** * Multiplies a matrix by a numeric value. * * @method scalarMultiply * @param {Array} matrix The matrix to be altered. * @param {Number} multiplier The number to multiply against the matrix. * @return Array */ scalarMultiply: function(matrix, multiplier) { var i = 0, j, len = matrix.length; for(; i < len; ++i) { for(j = 0; j < len; ++j) { matrix[i][j] = MatrixUtil._round(matrix[i][j] * multiplier); } } return matrix; }, /** * Returns the transpose for an nxn matrix. * * @method transpose * @param matrix An nxn matrix represented by an array of vector arrays. * @return Array */ transpose: function(matrix) { var len = matrix.length, i = 0, j = 0, transpose = []; for(; i < len; ++i) { transpose[i] = []; for(j = 0; j < len; ++j) { transpose[i].push(matrix[j][i]); } } return transpose; }, /** * Returns a matrix of minors based on a matrix, column index and row index. * * @method getMinors * @param {Array} matrix The matrix from which to extract the matrix of minors. * @param {Number} columnIndex A zero-based index representing the specified column to exclude. * @param {Number} rowIndex A zero-based index represeenting the specified row to exclude. * @return Array */ getMinors: function(matrix, columnIndex, rowIndex) { var minors = [], len = matrix.length, i = 0, j, column; for(; i < len; ++i) { if(i !== columnIndex) { column = []; for(j = 0; j < len; ++j) { if(j !== rowIndex) { column.push(matrix[i][j]); } } minors.push(column); } } return minors; }, /** * Returns the sign of value * * @method sign * @param {Number} val value to be interpreted * @return Number */ sign: function(val) { return val === 0 ? 1 : val/Math.abs(val); }, /** * Multiplies a vector and a matrix * * @method vectorMatrixProduct * @param {Array} vector Array representing a column vector * @param {Array} matrix Array representing an nxn matrix * @return Array */ vectorMatrixProduct: function(vector, matrix) { var i, j, len = vector.length, product = [], rowProduct; for(i = 0; i < len; ++i) { rowProduct = 0; for(j = 0; j < len; ++j) { rowProduct += vector[i] * matrix[i][j]; } product[i] = rowProduct; } return product; }, /** * Breaks up a 2d transform matrix into a series of transform operations. * * @method decompose * @param {Array} 3x3 matrix array * @return Array */ decompose: function(matrix) { var a = parseFloat(matrix[0][0]), b = parseFloat(matrix[1][0]), c = parseFloat(matrix[0][1]), d = parseFloat(matrix[1][1]), dx = parseFloat(matrix[0][2]), dy = parseFloat(matrix[1][2]), rotate, sx, sy, shear; if((a * d - b * c) === 0) { return false; } //get length of vector(ab) sx = MatrixUtil._round(Math.sqrt(a * a + b * b)); //normalize components of vector(ab) a /= sx; b /= sx; shear = MatrixUtil._round(a * c + b * d); c -= a * shear; d -= b * shear; //get length of vector(cd) sy = MatrixUtil._round(Math.sqrt(c * c + d * d)); //normalize components of vector(cd) c /= sy; d /= sy; shear /=sy; shear = MatrixUtil._round(MatrixUtil.rad2deg(Math.atan(shear))); rotate = MatrixUtil._round(MatrixUtil.rad2deg(Math.atan2(matrix[1][0], matrix[0][0]))); return [ ["translate", dx, dy], ["rotate", rotate], ["skewX", shear], ["scale", sx, sy] ]; }, /** * Parses a transform string and returns an array of transform arrays. * * @method getTransformArray * @param {String} val A transform string * @return Array */ getTransformArray: function(transform) { var re = /\s*([a-z]*)\(([\w,\.,\-,\s]*)\)/gi, transforms = [], args, m, decomp, methods = MatrixUtil.transformMethods; while ((m = re.exec(transform))) { if (methods.hasOwnProperty(m[1])) { args = m[2].split(','); args.unshift(m[1]); transforms.push(args); } else if(m[1] == "matrix") { args = m[2].split(','); decomp = MatrixUtil.decompose([ [args[0], args[2], args[4]], [args[1], args[3], args[5]], [0, 0, 1] ]); transforms.push(decomp[0]); transforms.push(decomp[1]); transforms.push(decomp[2]); transforms.push(decomp[3]); } } return transforms; }, /** * Returns an array of transform arrays representing transform functions and arguments. * * @method getTransformFunctionArray * @return Array */ getTransformFunctionArray: function(transform) { var list; switch(transform) { case "skew" : list = [transform, 0, 0]; break; case "scale" : list = [transform, 1, 1]; break; case "scaleX" : list = [transform, 1]; break; case "scaleY" : list = [transform, 1]; break; case "translate" : list = [transform, 0, 0]; break; default : list = [transform, 0]; break; } return list; }, /** * Compares to arrays or transform functions to ensure both contain the same functions in the same * order. * * @method compareTransformSequence * @param {Array} list1 Array to compare * @param {Array} list2 Array to compare * @return Boolean */ compareTransformSequence: function(list1, list2) { var i = 0, len = list1.length, len2 = list2.length, isEqual = len === len2; if(isEqual) { for(; i < len; ++i) { if(list1[i][0] != list2[i][0]) { isEqual = false; break; } } } return isEqual; }, /** * Mapping of possible transform method names. * * @property transformMethods * @type Object */ transformMethods: { rotate: "rotate", skew: "skew", skewX: "skewX", skewY: "skewY", translate: "translate", translateX: "translateX", translateY: "tranlsateY", scale: "scale", scaleX: "scaleX", scaleY: "scaleY" } }; Y.MatrixUtil = MatrixUtil; /** * Matrix is a class that allows for the manipulation of a transform matrix. * This class is a work in progress. * * @class Matrix * @constructor * @module matrix */ var Matrix = function(config) { this.init(config); }; Matrix.prototype = { /** * Used as value for the _rounding method. * * @property _rounder * @private */ _rounder: 100000, /** * Updates the matrix. * * @method multiple * @param {Number} a * @param {Number} b * @param {Number} c * @param {Number} d * @param {Number} dx * @param {Number} dy */ multiply: function(a, b, c, d, dx, dy) { var matrix = this, matrix_a = matrix.a * a + matrix.c * b, matrix_b = matrix.b * a + matrix.d * b, matrix_c = matrix.a * c + matrix.c * d, matrix_d = matrix.b * c + matrix.d * d, matrix_dx = matrix.a * dx + matrix.c * dy + matrix.dx, matrix_dy = matrix.b * dx + matrix.d * dy + matrix.dy; matrix.a = this._round(matrix_a); matrix.b = this._round(matrix_b); matrix.c = this._round(matrix_c); matrix.d = this._round(matrix_d); matrix.dx = this._round(matrix_dx); matrix.dy = this._round(matrix_dy); return this; }, /** * Parses a string and updates the matrix. * * @method applyCSSText * @param {String} val A css transform string */ applyCSSText: function(val) { var re = /\s*([a-z]*)\(([\w,\.,\-,\s]*)\)/gi, args, m; val = val.replace(/matrix/g, "multiply"); while ((m = re.exec(val))) { if (typeof this[m[1]] === 'function') { args = m[2].split(','); this[m[1]].apply(this, args); } } }, /** * Parses a string and returns an array of transform arrays. * * @method getTransformArray * @param {String} val A css transform string * @return Array */ getTransformArray: function(val) { var re = /\s*([a-z]*)\(([\w,\.,\-,\s]*)\)/gi, transforms = [], args, m; val = val.replace(/matrix/g, "multiply"); while ((m = re.exec(val))) { if (typeof this[m[1]] === 'function') { args = m[2].split(','); args.unshift(m[1]); transforms.push(args); } } return transforms; }, /** * Default values for the matrix * * @property _defaults * @private */ _defaults: { a: 1, b: 0, c: 0, d: 1, dx: 0, dy: 0 }, /** * Rounds values * * @method _round * @private */ _round: function(val) { val = Math.round(val * this._rounder) / this._rounder; return val; }, /** * Initializes a matrix. * * @method init * @param {Object} config Specified key value pairs for matrix properties. If a property is not explicitly defined in the config argument, * the default value will be used. */ init: function(config) { var defaults = this._defaults, prop; config = config || {}; for (prop in defaults) { if(defaults.hasOwnProperty(prop)) { this[prop] = (prop in config) ? config[prop] : defaults[prop]; } } this._config = config; }, /** * Applies a scale transform * * @method scale * @param {Number} val */ scale: function(x, y) { this.multiply(x, 0, 0, y, 0, 0); return this; }, /** * Applies a skew transformation. * * @method skew * @param {Number} x The value to skew on the x-axis. * @param {Number} y The value to skew on the y-axis. */ skew: function(x, y) { x = x || 0; y = y || 0; if (x !== undefined) { // null or undef x = Math.tan(this.angle2rad(x)); } if (y !== undefined) { // null or undef y = Math.tan(this.angle2rad(y)); } this.multiply(1, y, x, 1, 0, 0); return this; }, /** * Applies a skew to the x-coordinate * * @method skewX * @param {Number} x x-coordinate */ skewX: function(x) { this.skew(x); return this; }, /** * Applies a skew to the y-coordinate * * @method skewY * @param {Number} y y-coordinate */ skewY: function(y) { this.skew(null, y); return this; }, /** * Returns a string of text that can be used to populate a the css transform property of an element. * * @method toCSSText * @return String */ toCSSText: function() { var matrix = this, text = 'matrix(' + matrix.a + ',' + matrix.b + ',' + matrix.c + ',' + matrix.d + ',' + matrix.dx + ',' + matrix.dy + ')'; return text; }, /** * Returns a string that can be used to populate the css filter property of an element. * * @method toFilterText * @return String */ toFilterText: function() { var matrix = this, text = 'progid:DXImageTransform.Microsoft.Matrix('; text += 'M11=' + matrix.a + ',' + 'M21=' + matrix.b + ',' + 'M12=' + matrix.c + ',' + 'M22=' + matrix.d + ',' + 'sizingMethod="auto expand")'; text += ''; return text; }, /** * Converts a radian value to a degree. * * @method rad2deg * @param {Number} rad Radian value to be converted. * @return Number */ rad2deg: function(rad) { var deg = rad * (180 / Math.PI); return deg; }, /** * Converts a degree value to a radian. * * @method deg2rad * @param {Number} deg Degree value to be converted to radian. * @return Number */ deg2rad: function(deg) { var rad = deg * (Math.PI / 180); return rad; }, angle2rad: function(val) { if (typeof val === 'string' && val.indexOf('rad') > -1) { val = parseFloat(val); } else { // default to deg val = this.deg2rad(parseFloat(val)); } return val; }, /** * Applies a rotate transform. * * @method rotate * @param {Number} deg The degree of the rotation. */ rotate: function(deg, x, y) { var rad = this.angle2rad(deg), sin = Math.sin(rad), cos = Math.cos(rad); this.multiply(cos, sin, 0 - sin, cos, 0, 0); return this; }, /** * Applies translate transformation. * * @method translate * @param {Number} x The value to transate on the x-axis. * @param {Number} y The value to translate on the y-axis. */ translate: function(x, y) { x = parseFloat(x) || 0; y = parseFloat(y) || 0; this.multiply(1, 0, 0, 1, x, y); return this; }, /** * Applies a translate to the x-coordinate * * @method translateX * @param {Number} x x-coordinate */ translateX: function(x) { this.translate(x); return this; }, /** * Applies a translate to the y-coordinate * * @method translateY * @param {Number} y y-coordinate */ translateY: function(y) { this.translate(null, y); return this; }, /** * Returns an identity matrix. * * @method identity * @return Object */ identity: function() { var config = this._config, defaults = this._defaults, prop; for (prop in config) { if (prop in defaults) { this[prop] = defaults[prop]; } } return this; }, /** * Returns a 3x3 Matrix array * * / \ * | matrix[0][0] matrix[1][0] matrix[2][0] | * | matrix[0][1] matrix[1][1] matrix[2][1] | * | matrix[0][2] matrix[1][2] matrix[2][2] | * \ / * * @method getMatrixArray * @return Array */ getMatrixArray: function() { var matrix = this, matrixArray = [ [matrix.a, matrix.c, matrix.dx], [matrix.b, matrix.d, matrix.dy], [0, 0, 1] ]; return matrixArray; }, /** * Returns the left, top, right and bottom coordinates for a transformed * item. * * @method getContentRect * @param {Number} width The width of the item. * @param {Number} height The height of the item. * @param {Number} x The x-coordinate of the item. * @param {Number} y The y-coordinate of the item. * @return Object */ getContentRect: function(width, height, x, y) { var left = !isNaN(x) ? x : 0, top = !isNaN(y) ? y : 0, right = left + width, bottom = top + height, matrix = this, a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, dx = matrix.dx, dy = matrix.dy, x1 = (a * left + c * top + dx), y1 = (b * left + d * top + dy), //[x2, y2] x2 = (a * right + c * top + dx), y2 = (b * right + d * top + dy), //[x3, y3] x3 = (a * left + c * bottom + dx), y3 = (b * left + d * bottom + dy), //[x4, y4] x4 = (a * right + c * bottom + dx), y4 = (b * right + d * bottom + dy); return { left: Math.min(x3, Math.min(x1, Math.min(x2, x4))), right: Math.max(x3, Math.max(x1, Math.max(x2, x4))), top: Math.min(y2, Math.min(y4, Math.min(y3, y1))), bottom: Math.max(y2, Math.max(y4, Math.max(y3, y1))) }; }, /** * Returns the determinant of the matrix. * * @method getDeterminant * @return Number */ getDeterminant: function() { return Y.MatrixUtil.getDeterminant(this.getMatrixArray()); }, /** * Returns the inverse (in array form) of the matrix. * * @method inverse * @return Array */ inverse: function() { return Y.MatrixUtil.inverse(this.getMatrixArray()); }, /** * Returns the transpose of the matrix * * @method transpose * @return Array */ transpose: function() { return Y.MatrixUtil.transpose(this.getMatrixArray()); }, /** * Returns an array of transform commands that represent the matrix. * * @method decompose * @return Array */ decompose: function() { return Y.MatrixUtil.decompose(this.getMatrixArray()); } }; Y.Matrix = Matrix; }, '3.11.0', {"requires": ["yui-base"]});
devmix/openjst
server/commons/war/src/main/webapp/ui/lib/yui/build/matrix/matrix.js
JavaScript
agpl-3.0
26,090
/* * Globalize Culture ja-JP * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to be fixed in the generator */ ample.locale.addCultureInfo("ja-JP", "default", { name: "ja-JP", englishName: "Japanese (Japan)", nativeName: "日本語 (日本)", language: "ja", numberFormat: { "NaN": "NaN (非数値)", negativeInfinity: "-∞", positiveInfinity: "+∞", percent: { pattern: ["-n%","n%"] }, currency: { pattern: ["-$n","$n"], decimals: 0, symbol: "¥" } }, calendars: { standard: { days: { names: ["日曜日","月曜日","火曜日","水曜日","木曜日","金曜日","土曜日"], namesAbbr: ["日","月","火","水","木","金","土"], namesShort: ["日","月","火","水","木","金","土"] }, months: { names: ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月",""], namesAbbr: ["1","2","3","4","5","6","7","8","9","10","11","12",""] }, AM: ["午前","午前","午前"], PM: ["午後","午後","午後"], eras: [{"name":"西暦","start":null,"offset":0}], patterns: { d: "yyyy/MM/dd", D: "yyyy'年'M'月'd'日'", t: "H:mm", T: "H:mm:ss", f: "yyyy'年'M'月'd'日' H:mm", F: "yyyy'年'M'月'd'日' H:mm:ss", M: "M'月'd'日'", Y: "yyyy'年'M'月'" } }, Japanese: { name: "Japanese", days: { names: ["日曜日","月曜日","火曜日","水曜日","木曜日","金曜日","土曜日"], namesAbbr: ["日","月","火","水","木","金","土"], namesShort: ["日","月","火","水","木","金","土"] }, months: { names: ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月",""], namesAbbr: ["1","2","3","4","5","6","7","8","9","10","11","12",""] }, AM: ["午前","午前","午前"], PM: ["午後","午後","午後"], eras: [{"name":"平成","start":null,"offset":1867},{"name":"昭和","start":-1812153600000,"offset":1911},{"name":"大正","start":-1357603200000,"offset":1925},{"name":"明治","start":60022080000,"offset":1988}], twoDigitYearMax: 99, patterns: { d: "gg y/M/d", D: "gg y'年'M'月'd'日'", t: "H:mm", T: "H:mm:ss", f: "gg y'年'M'月'd'日' H:mm", F: "gg y'年'M'月'd'日' H:mm:ss", M: "M'月'd'日'", Y: "gg y'年'M'月'" } } } });
zonebuilder/zonebuilder.github.io
jul/ample-sdk/ample/cultures/ja-JP.js
JavaScript
lgpl-3.0
2,657
var DOCUMENTATION_OPTIONS = { URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), VERSION: '5.3.4', LANGUAGE: 'None', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' };
tst-eclamar/earthenterprise
docs/geedocs/5.3.4/static/documentation_options.js
JavaScript
apache-2.0
275
sap.ui.define(['sap/ui/core/mvc/Controller'], function(Controller) { "use strict"; var MBController = Controller.extend("sap.m.sample.MenuButton.MB", { onDefaultAction: function() { sap.m.MessageToast.show("Default action triggered"); }, onDefaultActionAccept: function() { sap.m.MessageToast.show("Accepted"); }, onMenuAction: function(oEvent) { var oItem = oEvent.getParameter("item"), sItemPath = ""; while (oItem instanceof sap.m.MenuItem) { sItemPath = oItem.getText() + " > " + sItemPath; oItem = oItem.getParent(); } sItemPath = sItemPath.substr(0, sItemPath.lastIndexOf(" > ")); sap.m.MessageToast.show("Action triggered on item: " + sItemPath); } }); return MBController; });
openui5/packaged-sap.m
test-resources/sap/m/demokit/sample/MenuButton/MB.controller.js
JavaScript
apache-2.0
760
var VERB_NEW = 1; var VERB_CHANGED = 2; var VERB_CURRENT = 3; var VERB_NEW_CLASS = "verb-new"; var VERB_CHANGED_CLASS = "verb-changed"; var VERB_CURRENT_CLASS = "verb-current"; var EDITED_CLASS = "edited"; var NOT_STARTED_TRANSLATION = 0; var VALID_TRANSLATION = 1; var INVALID_TRANSLATION = 2; function getVerbClassName(verb) { switch (verb) { case VERB_NEW: // new source value added, no mapping to target exists return VERB_NEW_CLASS; case VERB_CHANGED: // source value changed, mapping to target likely invalid return VERB_CHANGED_CLASS; case VERB_CURRENT: // source value is mapped to valid target value return VERB_CURRENT_CLASS; default: return ""; } } /** * Iterate over the items of the InputEx form. * * @param env The cb_global object * @param action A function which is passed the sections and items of the form */ function iterateFormItems(env, action) { $.each(env.form.inputsNames.sections.subFields, function(i, section) { $.each(section.inputsNames.data.subFields, function(j, item) { action(section, item); }) }); } function getSectionByName(env, name){ var section = null; $.each(env.form.inputsNames.sections.subFields, function(i, s){ if (s.inputsNames.name.getValue() == name) { section = s; return false; } }); return section; } function markAsEdited(item) { item.changed.setValue(true); $(item.changed.el).closest("fieldset") .removeClass().addClass(EDITED_CLASS); } function insertValidateButton() { var button = new Y.inputEx.widget.Button({ type: "submit-link", value: "Validate", className: "inputEx-Button inputEx-Button-Submit-Link gcb-pull-left", onClick: onClickValidate }); button.render($("div.inputEx-Form-buttonBar")[0]); // Button rendering will append the button at the end of the div, so we // move it to the second position after it's been created. $("div.inputEx-Form-buttonBar > a:first-child").after(button.el); cb_global.form.buttons.splice(1, 0, button); } function onClickValidate() { disableAllControlButtons(cb_global.form); var request = { key: cb_global.save_args.key, xsrf_token: cb_global.xsrf_token, payload: JSON.stringify(cb_global.form.getValue()), validate: true } Y.io(cb_global.save_url, { method: "PUT", data: {"request": JSON.stringify(request)}, on: { complete: onValidateComplete } }); return false; } function onValidateComplete(transactionId, response, args) { enableAllControlButtons(cb_global.form); if (response.status != 200) { cbShowMsg("Server error, please try again."); return; } response = parseJson(response.responseText); if (response.status != 200) { cbShowMsg(response.message); } var payload = JSON.parse(response.payload || "{}"); for (var name in payload) { if (payload.hasOwnProperty(name)) { var section = getSectionByName(cb_global, name); addValidationFeedbackTo(section.divEl.firstChild, payload[name]); } } } function addValidationFeedbackTo(fieldsetEl, feedback) { $("div.validation-feedback", fieldsetEl).remove(); var feedbackDiv = $("<div/>").addClass("validation-feedback"); if (feedback.status == VALID_TRANSLATION) { feedbackDiv.addClass("valid"); } else { feedbackDiv.addClass("invalid"); } feedbackDiv.append($("<div/>").addClass("icon")); feedbackDiv.append($("<div/>").addClass("errm").text(feedback.errm)); $(fieldsetEl).append(feedbackDiv); } function markValidationFeedbackStale(sectionField) { $("div.validation-feedback", sectionField.divEl) .removeClass() .addClass("validation-feedback stale"); } $(function() { iterateFormItems(cb_global, function(sectionField, itemField) { var verb = itemField.inputsNames.verb.getValue(); $(itemField.divEl.firstChild).addClass(getVerbClassName(verb)); }); $(".disabled textarea").prop("disabled", true); // Insert the status indicators into the DOM $(".translation-item fieldset fieldset") .append($("<div class=\"status\"></div>")); // Set up the accept buttons to appear when there is changed content iterateFormItems(cb_global, function(sectionField, itemField) { var button = $("<button class=\"accept inputEx-Button\">Accept</button>"); button.click(function() { markAsEdited(itemField.inputsNames); return false; }); $(itemField.divEl.firstChild).append(button); }); $(".translation-console > fieldset > div:last-child").before($( "<div class=\"translation-header\">" + " <div>Source (<span class=\"source-locale\"></span>)</div>" + " <div>Translation (<span class=\"target-locale\"></span>)</div>" + "</div>")); var formValue = cb_global.form.getValue(); $(".translation-header .source-locale").text(formValue['source_locale']); $(".translation-header .target-locale").text(formValue['target_locale']); iterateFormItems(cb_global, function(sectionField, itemField) { $(itemField.inputsNames.target_value.el).on("input change", function() { // Listen on "change" for older browser support markAsEdited(itemField.inputsNames); markValidationFeedbackStale(sectionField); }); }); cb_global.onSaveComplete = function() { iterateFormItems(cb_global, function(sectionField, itemField) { var item = itemField.inputsNames; if (item.changed.getValue()) { item.verb.setValue(VERB_CURRENT); $(item.changed.el).closest('fieldset') .removeClass().addClass(VERB_CURRENT_CLASS); } item.changed.setValue(false); }); cb_global.lastSavedFormValue = cb_global.form.getValue(); }; insertValidateButton(); });
UniMOOC/AAClassroom
modules/i18n_dashboard/templates/translation_console.js
JavaScript
apache-2.0
5,738
/* YUI 3.6.0 (build 5521) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('exec-command', function(Y) { /** * Plugin for the frame module to handle execCommands for Editor * @class Plugin.ExecCommand * @extends Base * @constructor * @module editor * @submodule exec-command */ var ExecCommand = function() { ExecCommand.superclass.constructor.apply(this, arguments); }; Y.extend(ExecCommand, Y.Base, { /** * An internal reference to the keyCode of the last key that was pressed. * @private * @property _lastKey */ _lastKey: null, /** * An internal reference to the instance of the frame plugged into. * @private * @property _inst */ _inst: null, /** * Execute a command on the frame's document. * @method command * @param {String} action The action to perform (bold, italic, fontname) * @param {String} value The optional value (helvetica) * @return {Node/NodeList} Should return the Node/Nodelist affected */ command: function(action, value) { var fn = ExecCommand.COMMANDS[action]; Y.log('execCommand(' + action + '): "' + value + '"', 'info', 'exec-command'); if (fn) { Y.log('OVERIDE execCommand(' + action + '): "' + value + '"', 'info', 'exec-command'); return fn.call(this, action, value); } else { return this._command(action, value); } }, /** * The private version of execCommand that doesn't filter for overrides. * @private * @method _command * @param {String} action The action to perform (bold, italic, fontname) * @param {String} value The optional value (helvetica) */ _command: function(action, value) { var inst = this.getInstance(); try { try { inst.config.doc.execCommand('styleWithCSS', null, 1); } catch (e1) { try { inst.config.doc.execCommand('useCSS', null, 0); } catch (e2) { } } Y.log('Using default browser execCommand(' + action + '): "' + value + '"', 'info', 'exec-command'); inst.config.doc.execCommand(action, null, value); } catch (e) { Y.log(e.message, 'warn', 'exec-command'); } }, /** * Get's the instance of YUI bound to the parent frame * @method getInstance * @return {YUI} The YUI instance bound to the parent frame */ getInstance: function() { if (!this._inst) { this._inst = this.get('host').getInstance(); } return this._inst; }, initializer: function() { Y.mix(this.get('host'), { execCommand: function(action, value) { return this.exec.command(action, value); }, _execCommand: function(action, value) { return this.exec._command(action, value); } }); this.get('host').on('dom:keypress', Y.bind(function(e) { this._lastKey = e.keyCode; }, this)); }, _wrapContent: function(str, override) { var useP = (this.getInstance().host.editorPara && !override ? true : false); if (useP) { str = '<p>' + str + '</p>'; } else { str = str + '<br>'; } return str; } }, { /** * execCommand * @property NAME * @static */ NAME: 'execCommand', /** * exec * @property NS * @static */ NS: 'exec', ATTRS: { host: { value: false } }, /** * Static object literal of execCommand overrides * @property COMMANDS * @static */ COMMANDS: { /** * Wraps the content with a new element of type (tag) * @method COMMANDS.wrap * @static * @param {String} cmd The command executed: wrap * @param {String} tag The tag to wrap the selection with * @return {NodeList} NodeList of the items touched by this command. */ wrap: function(cmd, tag) { var inst = this.getInstance(); return (new inst.EditorSelection()).wrapContent(tag); }, /** * Inserts the provided HTML at the cursor, should be a single element. * @method COMMANDS.inserthtml * @static * @param {String} cmd The command executed: inserthtml * @param {String} html The html to insert * @return {Node} Node instance of the item touched by this command. */ inserthtml: function(cmd, html) { var inst = this.getInstance(); if (inst.EditorSelection.hasCursor() || Y.UA.ie) { return (new inst.EditorSelection()).insertContent(html); } else { this._command('inserthtml', html); } }, /** * Inserts the provided HTML at the cursor, and focuses the cursor afterwards. * @method COMMANDS.insertandfocus * @static * @param {String} cmd The command executed: insertandfocus * @param {String} html The html to insert * @return {Node} Node instance of the item touched by this command. */ insertandfocus: function(cmd, html) { var inst = this.getInstance(), out, sel; if (inst.EditorSelection.hasCursor()) { html += inst.EditorSelection.CURSOR; out = this.command('inserthtml', html); sel = new inst.EditorSelection(); sel.focusCursor(true, true); } else { this.command('inserthtml', html); } return out; }, /** * Inserts a BR at the current cursor position * @method COMMANDS.insertbr * @static * @param {String} cmd The command executed: insertbr */ insertbr: function(cmd) { var inst = this.getInstance(), sel = new inst.EditorSelection(), html = '<var>|</var>', last = null, q = (Y.UA.webkit) ? 'span.Apple-style-span,var' : 'var'; if (sel._selection.pasteHTML) { sel._selection.pasteHTML(html); } else { this._command('inserthtml', html); } var insert = function(n) { var c = inst.Node.create('<br>'); n.insert(c, 'before'); return c; }; inst.all(q).each(function(n) { var g = true; if (Y.UA.webkit) { g = false; if (n.get('innerHTML') === '|') { g = true; } } if (g) { last = insert(n); if ((!last.previous() || !last.previous().test('br')) && Y.UA.gecko) { var s = last.cloneNode(); last.insert(s, 'after'); last = s; } n.remove(); } }); if (Y.UA.webkit && last) { insert(last); sel.selectNode(last); } }, /** * Inserts an image at the cursor position * @method COMMANDS.insertimage * @static * @param {String} cmd The command executed: insertimage * @param {String} img The url of the image to be inserted * @return {Node} Node instance of the item touched by this command. */ insertimage: function(cmd, img) { return this.command('inserthtml', '<img src="' + img + '">'); }, /** * Add a class to all of the elements in the selection * @method COMMANDS.addclass * @static * @param {String} cmd The command executed: addclass * @param {String} cls The className to add * @return {NodeList} NodeList of the items touched by this command. */ addclass: function(cmd, cls) { var inst = this.getInstance(); return (new inst.EditorSelection()).getSelected().addClass(cls); }, /** * Remove a class from all of the elements in the selection * @method COMMANDS.removeclass * @static * @param {String} cmd The command executed: removeclass * @param {String} cls The className to remove * @return {NodeList} NodeList of the items touched by this command. */ removeclass: function(cmd, cls) { var inst = this.getInstance(); return (new inst.EditorSelection()).getSelected().removeClass(cls); }, /** * Adds a forecolor to the current selection, or creates a new element and applies it * @method COMMANDS.forecolor * @static * @param {String} cmd The command executed: forecolor * @param {String} val The color value to apply * @return {NodeList} NodeList of the items touched by this command. */ forecolor: function(cmd, val) { var inst = this.getInstance(), sel = new inst.EditorSelection(), n; if (!Y.UA.ie) { this._command('useCSS', false); } if (inst.EditorSelection.hasCursor()) { if (sel.isCollapsed) { if (sel.anchorNode && (sel.anchorNode.get('innerHTML') === '&nbsp;')) { sel.anchorNode.setStyle('color', val); n = sel.anchorNode; } else { n = this.command('inserthtml', '<span style="color: ' + val + '">' + inst.EditorSelection.CURSOR + '</span>'); sel.focusCursor(true, true); } return n; } else { return this._command(cmd, val); } } else { this._command(cmd, val); } }, /** * Adds a background color to the current selection, or creates a new element and applies it * @method COMMANDS.backcolor * @static * @param {String} cmd The command executed: backcolor * @param {String} val The color value to apply * @return {NodeList} NodeList of the items touched by this command. */ backcolor: function(cmd, val) { var inst = this.getInstance(), sel = new inst.EditorSelection(), n; if (Y.UA.gecko || Y.UA.opera) { cmd = 'hilitecolor'; } if (!Y.UA.ie) { this._command('useCSS', false); } if (inst.EditorSelection.hasCursor()) { if (sel.isCollapsed) { if (sel.anchorNode && (sel.anchorNode.get('innerHTML') === '&nbsp;')) { sel.anchorNode.setStyle('backgroundColor', val); n = sel.anchorNode; } else { n = this.command('inserthtml', '<span style="background-color: ' + val + '">' + inst.EditorSelection.CURSOR + '</span>'); sel.focusCursor(true, true); } return n; } else { return this._command(cmd, val); } } else { this._command(cmd, val); } }, /** * Sugar method, calles backcolor * @method COMMANDS.hilitecolor * @static * @param {String} cmd The command executed: backcolor * @param {String} val The color value to apply * @return {NodeList} NodeList of the items touched by this command. */ hilitecolor: function() { return ExecCommand.COMMANDS.backcolor.apply(this, arguments); }, /** * Adds a font name to the current selection, or creates a new element and applies it * @method COMMANDS.fontname2 * @deprecated * @static * @param {String} cmd The command executed: fontname * @param {String} val The font name to apply * @return {NodeList} NodeList of the items touched by this command. */ fontname2: function(cmd, val) { this._command('fontname', val); var inst = this.getInstance(), sel = new inst.EditorSelection(); if (sel.isCollapsed && (this._lastKey != 32)) { if (sel.anchorNode.test('font')) { sel.anchorNode.set('face', val); } } }, /** * Adds a fontsize to the current selection, or creates a new element and applies it * @method COMMANDS.fontsize2 * @deprecated * @static * @param {String} cmd The command executed: fontsize * @param {String} val The font size to apply * @return {NodeList} NodeList of the items touched by this command. */ fontsize2: function(cmd, val) { this._command('fontsize', val); var inst = this.getInstance(), sel = new inst.EditorSelection(); if (sel.isCollapsed && sel.anchorNode && (this._lastKey != 32)) { if (Y.UA.webkit) { if (sel.anchorNode.getStyle('lineHeight')) { sel.anchorNode.setStyle('lineHeight', ''); } } if (sel.anchorNode.test('font')) { sel.anchorNode.set('size', val); } else if (Y.UA.gecko) { var p = sel.anchorNode.ancestor(inst.EditorSelection.DEFAULT_BLOCK_TAG); if (p) { p.setStyle('fontSize', ''); } } } }, /** * Overload for COMMANDS.list * @method COMMANDS.insertorderedlist * @static * @param {String} cmd The command executed: list, ul */ insertunorderedlist: function(cmd) { this.command('list', 'ul'); }, /** * Overload for COMMANDS.list * @method COMMANDS.insertunorderedlist * @static * @param {String} cmd The command executed: list, ol */ insertorderedlist: function(cmd) { this.command('list', 'ol'); }, /** * Noramlizes lists creation/destruction for IE. All others pass through to native calls * @method COMMANDS.list * @static * @param {String} cmd The command executed: list (not used) * @param {String} tag The tag to deal with */ list: function(cmd, tag) { var inst = this.getInstance(), html, self = this, /* The yui3- class name below is not a skinnable class, it's a utility class used internally by editor and stripped when completed, calling getClassName on this is a waste of resources. */ DIR = 'dir', cls = 'yui3-touched', dir, range, div, elm, n, str, s, par, list, lis, useP = (inst.host.editorPara ? true : false), sel = new inst.EditorSelection(); cmd = 'insert' + ((tag === 'ul') ? 'un' : '') + 'orderedlist'; if (Y.UA.ie && !sel.isCollapsed) { range = sel._selection; html = range.htmlText; div = inst.Node.create(html) || inst.one('body'); if (div.test('li') || div.one('li')) { this._command(cmd, null); return; } if (div.test(tag)) { elm = range.item ? range.item(0) : range.parentElement(); n = inst.one(elm); lis = n.all('li'); str = '<div>'; lis.each(function(l) { str = self._wrapContent(l.get('innerHTML')); }); str += '</div>'; s = inst.Node.create(str); if (n.get('parentNode').test('div')) { n = n.get('parentNode'); } if (n && n.hasAttribute(DIR)) { if (useP) { s.all('p').setAttribute(DIR, n.getAttribute(DIR)); } else { s.setAttribute(DIR, n.getAttribute(DIR)); } } if (useP) { n.replace(s.get('innerHTML')); } else { n.replace(s); } if (range.moveToElementText) { range.moveToElementText(s._node); } range.select(); } else { par = Y.one(range.parentElement()); if (!par.test(inst.EditorSelection.BLOCKS)) { par = par.ancestor(inst.EditorSelection.BLOCKS); } if (par) { if (par.hasAttribute(DIR)) { dir = par.getAttribute(DIR); } } if (html.indexOf('<br>') > -1) { html = html.split(/<br>/i); } else { var tmp = inst.Node.create(html), ps = tmp ? tmp.all('p') : null; if (ps && ps.size()) { html = []; ps.each(function(n) { html.push(n.get('innerHTML')); }); } else { html = [html]; } } list = '<' + tag + ' id="ie-list">'; Y.each(html, function(v) { var a = inst.Node.create(v); if (a && a.test('p')) { if (a.hasAttribute(DIR)) { dir = a.getAttribute(DIR); } v = a.get('innerHTML'); } list += '<li>' + v + '</li>'; }); list += '</' + tag + '>'; range.pasteHTML(list); elm = inst.config.doc.getElementById('ie-list'); elm.id = ''; if (dir) { elm.setAttribute(DIR, dir); } if (range.moveToElementText) { range.moveToElementText(elm); } range.select(); } } else if (Y.UA.ie) { par = inst.one(sel._selection.parentElement()); if (par.test('p')) { if (par && par.hasAttribute(DIR)) { dir = par.getAttribute(DIR); } html = Y.EditorSelection.getText(par); if (html === '') { var sdir = ''; if (dir) { sdir = ' dir="' + dir + '"'; } list = inst.Node.create(Y.Lang.sub('<{tag}{dir}><li></li></{tag}>', { tag: tag, dir: sdir })); par.replace(list); sel.selectNode(list.one('li')); } else { this._command(cmd, null); } } else { this._command(cmd, null); } } else { inst.all(tag).addClass(cls); if (sel.anchorNode.test(inst.EditorSelection.BLOCKS)) { par = sel.anchorNode; } else { par = sel.anchorNode.ancestor(inst.EditorSelection.BLOCKS); } if (!par) { //No parent, find the first block under the anchorNode par = sel.anchorNode.one(inst.EditorSelection.BLOCKS); } if (par && par.hasAttribute(DIR)) { dir = par.getAttribute(DIR); } if (par && par.test(tag)) { var hasPParent = par.ancestor('p'); html = inst.Node.create('<div/>'); elm = par.all('li'); elm.each(function(h) { html.append(self._wrapContent(h.get('innerHTML'), hasPParent)); }); if (dir) { if (useP) { html.all('p').setAttribute(DIR, dir); } else { html.setAttribute(DIR, dir); } } if (useP) { html = inst.Node.create(html.get('innerHTML')); } var fc = html.get('firstChild'); par.replace(html); sel.selectNode(fc); } else { this._command(cmd, null); } list = inst.all(tag); if (dir) { if (list.size()) { //Changed to a List list.each(function(n) { if (!n.hasClass(cls)) { n.setAttribute(DIR, dir); } }); } } list.removeClass(cls); } }, /** * Noramlizes alignment for Webkit Browsers * @method COMMANDS.justify * @static * @param {String} cmd The command executed: justify (not used) * @param {String} val The actual command from the justify{center,all,left,right} stubs */ justify: function(cmd, val) { if (Y.UA.webkit) { var inst = this.getInstance(), sel = new inst.EditorSelection(), aNode = sel.anchorNode; var bgColor = aNode.getStyle('backgroundColor'); this._command(val); sel = new inst.EditorSelection(); if (sel.anchorNode.test('div')) { var html = '<span>' + sel.anchorNode.get('innerHTML') + '</span>'; sel.anchorNode.set('innerHTML', html); sel.anchorNode.one('span').setStyle('backgroundColor', bgColor); sel.selectNode(sel.anchorNode.one('span')); } } else { this._command(val); } }, /** * Override method for COMMANDS.justify * @method COMMANDS.justifycenter * @static */ justifycenter: function(cmd) { this.command('justify', 'justifycenter'); }, /** * Override method for COMMANDS.justify * @method COMMANDS.justifyleft * @static */ justifyleft: function(cmd) { this.command('justify', 'justifyleft'); }, /** * Override method for COMMANDS.justify * @method COMMANDS.justifyright * @static */ justifyright: function(cmd) { this.command('justify', 'justifyright'); }, /** * Override method for COMMANDS.justify * @method COMMANDS.justifyfull * @static */ justifyfull: function(cmd) { this.command('justify', 'justifyfull'); } } }); /** * This method is meant to normalize IE's in ability to exec the proper command on elements with CSS styling. * @method fixIETags * @protected * @param {String} cmd The command to execute * @param {String} tag The tag to create * @param {String} rule The rule that we are looking for. */ var fixIETags = function(cmd, tag, rule) { var inst = this.getInstance(), doc = inst.config.doc, sel = doc.selection.createRange(), o = doc.queryCommandValue(cmd), html, reg, m, p, d, s, c; if (o) { html = sel.htmlText; reg = new RegExp(rule, 'g'); m = html.match(reg); if (m) { html = html.replace(rule + ';', '').replace(rule, ''); sel.pasteHTML('<var id="yui-ie-bs">'); p = doc.getElementById('yui-ie-bs'); d = doc.createElement('div'); s = doc.createElement(tag); d.innerHTML = html; if (p.parentNode !== inst.config.doc.body) { p = p.parentNode; } c = d.childNodes; p.parentNode.replaceChild(s, p); Y.each(c, function(f) { s.appendChild(f); }); sel.collapse(); if (sel.moveToElementText) { sel.moveToElementText(s); } sel.select(); } } this._command(cmd); }; if (Y.UA.ie) { ExecCommand.COMMANDS.bold = function() { fixIETags.call(this, 'bold', 'b', 'FONT-WEIGHT: bold'); }; ExecCommand.COMMANDS.italic = function() { fixIETags.call(this, 'italic', 'i', 'FONT-STYLE: italic'); }; ExecCommand.COMMANDS.underline = function() { fixIETags.call(this, 'underline', 'u', 'TEXT-DECORATION: underline'); }; } Y.namespace('Plugin'); Y.Plugin.ExecCommand = ExecCommand; }, '3.6.0' ,{skinnable:false, requires:['frame']});
bretkikehara/wattdepot-visualization
src/main/webapp/yui/3.6.0/build/exec-command/exec-command-debug.js
JavaScript
bsd-3-clause
31,671
/* * Copyright 2016 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* global PaymentRequest:false */ /** * Launches the PaymentRequest UI that offers free shipping in California and * $5.00 shipping in US. Does not allow shipping outside of US. * * Legacy entry-point until basic-card is disabled */ function buy() { // eslint-disable-line no-unused-vars buyWithMethods( [{supportedMethods: 'basic-card', data: {supportedNetworks: ['visa']}}]); } /** * Launches the PaymentRequest UI that offers free shipping in California and * $5.00 shipping in US. Does not allow shipping outside of US. * * @param {String} methodData - An array of payment method objects. */ function buyWithMethods(methodData) { // eslint-disable-line no-unused-vars try { var details = { total: {label: 'Total', amount: {currency: 'USD', value: '5.00'}}, displayItems: [ { label: 'Pending shipping price', amount: {currency: 'USD', value: '0.00'}, pending: true, }, {label: 'Subtotal', amount: {currency: 'USD', value: '5.00'}}, ], }; var request = new PaymentRequest( methodData, details, {requestShipping: true}); request.addEventListener('shippingaddresschange', function(evt) { evt.updateWith(new Promise(function(resolve) { resolve(updateDetails(details, request.shippingAddress)); })); }); request.show() .then(function(resp) { resp.complete('success') .then(function() { print(JSON.stringify(resp, undefined, 2)); }) .catch(function(error) { print(error); }); }) .catch(function(error) { print(error); }); } catch (error) { print(error.message); } } /** * Updates the shopping cart with the appropriate shipping prices according to * the shipping address. * @param {object} details - The shopping cart. * @param {ShippingAddress} addr - The shipping address. * @return {object} The updated shopping cart. */ function updateDetails(details, addr) { if (addr.country === 'US') { var shippingOption = { id: '', label: '', amount: {currency: 'USD', value: '0.00'}, selected: true, }; if (addr.region === 'CA') { shippingOption.id = 'californiaShippingOption'; shippingOption.label = 'Free shipping in California'; details.total.amount.value = '5.00'; } else { shippingOption.id = 'usShippingOption'; shippingOption.label = 'Standard shipping in US'; shippingOption.amount.value = '5.00'; details.total.amount.value = '10.00'; } details.displayItems.splice(0, 1, shippingOption); details.shippingOptions = [shippingOption]; } else { details.shippingOptions = []; details.error = 'We do not ship to this address'; details.shippingAddressErrors = { addressLine: 'ADDRESS LINE ERROR', city: 'CITY ERROR', }; } return details; }
chromium/chromium
components/test/data/payments/dynamic_shipping.js
JavaScript
bsd-3-clause
3,140
// (function (root) { "use strict"; if (!root.lux) root.lux = {}; // If a file assign http as protocol (https does not work with PhantomJS) var protocol = root.location ? (root.location.protocol === 'file:' ? 'http:' : '') : '', end = '.js', ostring = Object.prototype.toString, lux = root.lux; function isArray(it) { return ostring.call(it) === '[object Array]'; } function minify () { if (root.lux.context) return lux.context.MINIFIED_MEDIA; } function baseUrl () { if (root.lux.context) return lux.context.MEDIA_URL; } function extend (o1, o2) { if (o2) { for (var key in o2) { if (o2.hasOwnProperty(key)) o1[key] = o2[key]; } } return o1; } function defaultPaths () { return { "angular": "//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular", "angular-animate": "//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-animate", "angular-mocks": "//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-mocks.js", "angular-sanitize": "//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-sanitize", "angular-touch": "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-touch", "angular-strap": "//cdnjs.cloudflare.com/ajax/libs/angular-strap/2.2.1/angular-strap", "angular-strap-tpl": "//cdnjs.cloudflare.com/ajax/libs/angular-strap/2.2.4/angular-strap.tpl", "angular-ui-router": "//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.14/angular-ui-router", "angular-pusher": "//cdn.jsdelivr.net/angular.pusher/latest/pusher-angular.min.js", "async": "//cdnjs.cloudflare.com/ajax/libs/requirejs-async/0.1.1/async.js", "pusher": "//js.pusher.com/2.2/pusher", "codemirror": "//cdnjs.cloudflare.com/ajax/libs/codemirror/3.21.0/codemirror", "codemirror-markdown": "//cdnjs.cloudflare.com/ajax/libs/codemirror/3.21.0/mode/markdown/markdown", "codemirror-javascript": "//cdnjs.cloudflare.com/ajax/libs/codemirror/3.21.0/mode/javascript/javascript", "codemirror-xml": "//cdnjs.cloudflare.com/ajax/libs/codemirror/3.21.0/mode/xml/xml", "codemirror-css": "//cdnjs.cloudflare.com/ajax/libs/codemirror/3.21.0/mode/css/css", "codemirror-htmlmixed": "//cdnjs.cloudflare.com/ajax/libs/codemirror/3.21.0/mode/htmlmixed/htmlmixed", "crossfilter": "//cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.11/crossfilter", "d3": "//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3", "google-analytics": "//www.google-analytics.com/analytics.js", "gridster": "//cdnjs.cloudflare.com/ajax/libs/jquery.gridster/0.5.6/jquery.gridster", "holder": "//cdnjs.cloudflare.com/ajax/libs/holder/2.3.1/holder", "highlight": "//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js", "katex": "//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min.js", "leaflet": "//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.js", "lodash": "//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash", "marked": "//cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked", "mathjax": "//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML", "moment": "//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment", "restangular": "//cdnjs.cloudflare.com/ajax/libs/restangular/1.4.0/restangular", "sockjs": "//cdnjs.cloudflare.com/ajax/libs/sockjs-client/0.3.4/sockjs.min.js", "stats": "//cdnjs.cloudflare.com/ajax/libs/stats.js/r11/Stats", "topojson": "//cdnjs.cloudflare.com/ajax/libs/topojson/1.6.19/topojson" }; } // Default shims function defaultShim () { return { angular: { exports: "angular" }, "angular-strap-tpl": { deps: ["angular", "angular-strap"] }, "google-analytics": { exports: root.GoogleAnalyticsObject || "ga" }, highlight: { exports: "hljs" }, lux: { deps: ["angular"] }, "ui-bootstrap": { deps: ["angular"] }, "codemirror": { exports: "CodeMirror" }, "codemirror-markdown": { deps: ["codemirror"] }, "codemirror-xml": { deps: ["codemirror"] }, "codemirror-javascript": { deps: ["codemirror"] }, "codemirror-css": { deps: ["codemirror"] }, "codemirror-htmlmixed": { deps: ["codemirror", "codemirror-xml", "codemirror-javascript", "codemirror-css"], }, restangular: { deps: ["angular"] }, crossfilter: { exports: "crossfilter" }, trianglify: { deps: ["d3"], exports: "Trianglify" }, mathjax: { exports: "MathJax" } }; } function newPaths (cfg) { var all = {}, min = minify() ? '.min' : '', prefix = root.local_require_prefix, paths = extend(defaultPaths(), cfg.paths); for(var name in paths) { if(paths.hasOwnProperty(name)) { var path = paths[name]; if (prefix && path.substring(0, prefix.length) === prefix) path = path.substring(prefix.length); if (!cfg.shim[name]) { // Add angular dependency if (name.substring(0, 8) === "angular-") cfg.shim[name] = { deps: ["angular"] }; else if (name.substring(0, 3) === "d3-") cfg.shim[name] = { deps: ["d3"] }; } if (typeof(path) !== 'string') { // Don't maanipulate it, live it as it is path = path.url; } else { var params = path.split('?'); if (params.length === 2) { path = params[0]; params = params[1]; } else params = ''; if (path.substring(path.length-3) !== end) path += min; if (params) { if (path.substring(path.length-3) !== end) path += end; path += '?' + params; } // Add protocol if (path.substring(0, 2) === '//' && protocol) path = protocol + path; if (path.substring(path.length-3) === end) path = path.substring(0, path.length-3); } all[name] = path; } } return all; } // require.config override lux.config = function (cfg) { if(!cfg.baseUrl) { var url = baseUrl(); if (url !== undefined) cfg.baseUrl = url; } cfg.shim = extend(defaultShim(), cfg.shim); cfg.paths = newPaths(cfg); require.config(cfg); }; }(this)); lux.config({}); require(['angular'], function (angular) { angular.module('twitter-example', ['templates-tweets']) .directive('twitter', ['$rootScope', '$log', function (root, log) { function connectSock(scope, url) { if (!root.websockets) root.websockets = {}; var hnd = root.websockets[url]; if (!hnd) root.websockets[url] = hnd = createSocket(url); return hnd; } function createSocket (url) { var sock = new WebSocket(url), listeners = []; sock.onopen = function() { log.info('New connection with ' + url); }; sock.onmessage = function (e) { var msg = angular.fromJson(e.data); msg.timestamp = +msg.timestamp; msg.url = 'https://twitter.com/' + msg.user.screen_name + '/status/' + msg.id_str; angular.forEach(listeners, function (listener) { listener(sock, msg); }); }; return { sock: sock, listeners: listeners }; } // Closure which handle incoming messages fro the server function tweetArrived (scope) { return function (sock, msg) { scope.messages.push(msg); scope.$apply(); }; } return { restrict: 'AE', templateUrl: 'tweets/templates/tweets.tpl.html', link: function (scope, element, attrs) { var options = attrs.twitter; if (options) options = angular.fromJson(options); scope.messages = []; if (options && options.url) { var hnd = connectSock(scope, options.url); hnd.listeners.push(tweetArrived(scope)); } else log.error('Twitter directive improperly configured, no url found'); } }; }]); angular.module('templates-tweets', ['tweets/templates/tweets.tpl.html']); angular.module("tweets/templates/tweets.tpl.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("tweets/templates/tweets.tpl.html", "<div class=\"media\" ng-repeat=\"msg in messages | orderBy: ['-timestamp']\">\n" + " <div class=\"media-left\">\n" + " <a ng-href=\"{{ msg.url }}\">\n" + " <img class=\"media-object\" ng-src=\"{{msg.user.profile_image_url_https}}\"\n" + " alt=\"{{msg.user.name}}\" class=\"img-thumbnail\">\n" + " </a>\n" + " </div>\n" + " <div class=\"media-body\">\n" + " <p class='list-group-item-text message'>{{msg.text}}</p>\n" + " </div>\n" + "</div>\n" + ""); }]); // // Angular bootstrap angular.bootstrap(document, ['twitter-example']); });
dejlek/pulsar
examples/tweets/assets/tweets.js
JavaScript
bsd-3-clause
10,267
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. const {session, contextGroup, Protocol} = InspectorTest.start('Tests Runtime.RemoteObject.'); function evaluate(options) { InspectorTest.log(`'${options.expression}', ` + `returnByValue: ${options.returnByValue || false}, ` + `generatePreview: ${options.generatePreview || false}`); return Protocol.Runtime.evaluate(options); } InspectorTest.runAsyncTestSuite([ async function testNull() { InspectorTest.logMessage((await evaluate({ expression: 'null' })).result); InspectorTest.logMessage((await evaluate({ expression: 'null', returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'null', generatePreview: true })).result); }, async function testBoolean() { InspectorTest.logMessage((await evaluate({ expression: 'true' })).result); InspectorTest.logMessage((await evaluate({ expression: 'false' })).result); InspectorTest.logMessage((await evaluate({ expression: 'true', returnByValue: true, })).result); InspectorTest.logMessage((await evaluate({ expression: 'true', generatePreview: true, })).result); }, async function testNumber() { InspectorTest.logMessage((await evaluate({ expression: '0 / {}' })).result); InspectorTest.logMessage((await evaluate({ expression: '-0' })).result); InspectorTest.logMessage((await evaluate({ expression: '0' })).result); InspectorTest.logMessage((await evaluate({ expression: '1/0' })).result); InspectorTest.logMessage((await evaluate({ expression: '-1/0' })).result); InspectorTest.logMessage((await evaluate({ expression: '2.3456' })).result); InspectorTest.logMessage((await evaluate({ expression: '2.3456', returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: '1/0', returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: '({a: 1/0})', returnByValue: true })).result); }, async function testUndefined() { InspectorTest.logMessage((await evaluate({ expression: 'undefined' })).result); InspectorTest.logMessage((await evaluate({ expression: 'undefined', returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: '({a : undefined})', returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: '([1, undefined])', returnByValue: true })).result); }, async function testString() { InspectorTest.logMessage((await evaluate({ expression: '\'Hello!\'' })).result); InspectorTest.logMessage((await evaluate({ expression: '\'Hello!\'', returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: '\'Hello!\'', generatePreview: true })).result); }, async function testSymbol() { InspectorTest.logMessage((await evaluate({ expression: 'Symbol()', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'Symbol(42)', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: `Symbol('abc')`, generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: `Symbol('abc')`, returnByValue: true }))); }, async function testReturnByValue() { InspectorTest.log('Empty object'); InspectorTest.logMessage((await evaluate({ expression: '({})', returnByValue: true })).result); InspectorTest.log('Object with properties'); InspectorTest.logMessage((await evaluate({ expression: '({a:1, b:2})', returnByValue: true })).result); InspectorTest.log('Object with cycle'); InspectorTest.logMessage((await evaluate({ expression: 'a = {};a.a = a; a', returnByValue: true })).error); InspectorTest.log('Function () => 42'); InspectorTest.logMessage((await evaluate({ expression: '() => 42', returnByValue: true })).result); InspectorTest.log('Symbol(42)'); InspectorTest.logMessage((await evaluate({ expression: 'Symbol(42)', returnByValue: true })).error); InspectorTest.log('Error object'); InspectorTest.logMessage((await evaluate({ expression: 'new Error()', returnByValue: true })).result); }, async function testFunction() { InspectorTest.logMessage((await evaluate({ expression: '(() => 42)' })).result); InspectorTest.logMessage((await evaluate({ expression: '(function() { return 42 })' })).result); InspectorTest.logMessage((await evaluate({ expression: '(function name() { return 42 })' })).result); InspectorTest.logMessage((await evaluate({ expression: '(async function asyncName() { return 42 })' })).result); InspectorTest.logMessage((await evaluate({ expression: '(async () => 42)' })).result); InspectorTest.logMessage((await evaluate({ expression: '(function (a) { return a; }).bind(null, 42)' })).result); InspectorTest.logMessage((await evaluate({ expression: 'a = (function() { return 42 }); a.b = 2; a', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: '(function() { return 42 })', returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'a = (function() { return 42 }); a.b = 2; a', returnByValue: true })).result); }, async function testBigInt() { InspectorTest.logMessage((await evaluate({ expression: '1n' })).result); InspectorTest.logMessage((await evaluate({ expression: '-5n' })).result); InspectorTest.logMessage((await evaluate({ expression: '1234567890123456789012345678901234567890n' })).result); InspectorTest.logMessage((await evaluate({ expression: '-5n', returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: '-5n', generatePreview: true })).result); }, async function testRegExp() { InspectorTest.logMessage((await evaluate({ expression: '/\w+/g' })).result); InspectorTest.logMessage((await evaluate({ expression: '/\w+/i' })).result); InspectorTest.logMessage((await evaluate({ expression: '/\w+/m' })).result); InspectorTest.logMessage((await evaluate({ expression: '/\w+/s' })).result); InspectorTest.logMessage((await evaluate({ expression: '/\w+/u' })).result); InspectorTest.logMessage((await evaluate({ expression: '/\w+/y' })).result); InspectorTest.logMessage((await evaluate({ expression: '/\w+/gimsuy' })).result); InspectorTest.logMessage((await evaluate({ expression: `new RegExp('\\w+', 'g')`, })).result); InspectorTest.logMessage((await evaluate({ expression: `var re = new RegExp('\\w+', 'g'); re.prop = 32; re`, generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: `var re = new RegExp('\\w+', 'g'); re.prop = 32; re`, returnByValue: true })).result); }, async function testDate() { let result = (await evaluate({ expression: `new Date('May 18, 1991 03:24:00')`, generatePreview: true })).result; if (result.result.description === new Date('May 18, 1991 03:24:00') + '') result.result.description = '<expected description>'; if (result.result.preview.description === new Date('May 18, 1991 03:24:00') + '') result.result.preview.description = '<expected description>'; InspectorTest.logMessage(result); result = (await evaluate({ expression: `new Date(2018, 9, 31)`, generatePreview: true })).result; if (result.result.description === new Date(2018, 9, 31) + '') result.result.description = '<expected description>'; if (result.result.preview.description === new Date(2018, 9, 31) + '') result.result.preview.description = '<expected description>'; InspectorTest.logMessage(result); result = (await evaluate({ expression: `a = new Date(2018, 9, 31); a.b = 2; a`, generatePreview: true })).result; if (result.result.description === new Date(2018, 9, 31) + '') result.result.description = '<expected description>'; if (result.result.preview.description === new Date(2018, 9, 31) + '') result.result.preview.description = '<expected description>'; InspectorTest.logMessage(result); }, async function testMap() { InspectorTest.logMessage((await evaluate({ expression: 'new Map()', generatePreview: true, })).result); InspectorTest.logMessage((await evaluate({ expression: 'new Map([[1,2]])', generatePreview: true, })).result); InspectorTest.logMessage((await evaluate({ expression: 'a = new Map(); a.set(a, a); a', generatePreview: true, })).result); InspectorTest.logMessage((await evaluate({ expression: `new Map([['a','b']])` })).result); InspectorTest.logMessage((await evaluate({ expression: `({ a: new Map([['a','b']]) })`, generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: `m = new Map([['a', {b: 2}]]) m.d = 42; m`, generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: `m = new Map([['a', {b: 2}]]) m.d = 42; m`, returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: `new Map([['a', {b: 2}]]).values()` })).result); InspectorTest.logMessage((await evaluate({ expression: `new Map([['a', {b: 2}]]).values()`, generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: `it = new Map([['a', {b: 2}]]).values(); it.next(); it`, generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: `new Map([['a', {b: 2}]]).values()`, returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: `new Map([['a', {b: 2}]]).entries()` })).result); InspectorTest.logMessage((await evaluate({ expression: `new Map([['a', {b: 2}]]).entries()`, generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: `it = new Map([['a', {b: 2}]]).entries(); it.next(); it`, generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: `new Map([['a', {b: 2}]]).entries()`, returnByValue: true })).result); }, async function testSet() { InspectorTest.logMessage((await evaluate({ expression: 'new Set([1])', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'new Set([1])', returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'new Set([1,2,3,4,5,6,7])', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'new Set([1,2,3]).values()', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'it = new Set([1,2,3]).values(); it.next(); it', generatePreview: true })).result); }, async function testWeakMap() { InspectorTest.logMessage((await evaluate({ expression: 'new WeakMap()', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'new WeakMap([[this, 1]])', generatePreview: true })).result); }, async function testWeakSet() { InspectorTest.logMessage((await evaluate({ expression: 'new WeakSet()', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'new WeakSet([this])', generatePreview: true })).result); }, async function testGenerator() { InspectorTest.logMessage((await evaluate({ expression: 'g = (function*(){ yield 42; })(); g.a = 2; g', generatePreview: true })).result); }, async function testError() { InspectorTest.logMessage((await evaluate({ expression: 'new Error()' })).result); InspectorTest.logMessage((await evaluate({ expression: `new Error('abc')` })).result); InspectorTest.logMessage((await evaluate({ expression: `new Error('at\\nat')` })).result); InspectorTest.logMessage((await evaluate({ expression: `new Error('preview')`, returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: `new Error('preview')`, generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: `({a: new Error('preview')})`, generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: `a = new Error('preview and a'); a.a = 123; a`, generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: `a = new Error('preview and a'); a.a = 123; a`, returnByValue: true })).result); }, async function testCustomError() { InspectorTest.logMessage((await evaluate({ expression: `class CustomError extends Error {}; a = new CustomError(); delete a.stack; a` })).result); }, async function testCustomErrorWithMessage() { InspectorTest.logMessage((await evaluate( { expression: `class CustomMsgError extends Error {}; a = new CustomMsgError(); delete a.stack; a.message = 'foobar'; a` })).result); }, async function testProxy() { InspectorTest.logMessage((await evaluate({ expression: 'new Proxy({}, {})' })).result); InspectorTest.logMessage((await evaluate({ expression: 'new Proxy(new Error(), {})' })).result); InspectorTest.logMessage((await evaluate({ expression: 'new Proxy({c: 3}, {d: 4})', returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'new Proxy({a: 1}, {b: 2})', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: '({e: new Proxy({a: 1}, {b: 2})})', generatePreview: true })).result); }, async function testPromise() { InspectorTest.logMessage((await evaluate({ expression: 'Promise.resolve(42)' })).result); InspectorTest.logMessage((await evaluate({ expression: 'Promise.reject(42)' })).result); InspectorTest.logMessage((await evaluate({ expression: '(async function(){})()' })).result); InspectorTest.logMessage((await evaluate({ expression: `Promise.resolve('a'.repeat(101))`, generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'Promise.reject(42)', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'new Promise(resolve => this.resolve = resolve)', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'a = Promise.resolve(42); a.b = 2; a', returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: '({a: Promise.resolve(42)})', generatePreview: true })).result); }, async function testTypedArray() { InspectorTest.logMessage((await evaluate({ expression: 'a = new Uint8Array(2); a.b = 2; a', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'new Int32Array(101)', generatePreview: true })).result); }, async function testArrayBuffer() { InspectorTest.logMessage((await evaluate({ expression: 'new Uint8Array().buffer', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'new Int32Array(100).buffer', generatePreview: true })).result); }, async function testDataView() { InspectorTest.logMessage((await evaluate({ expression: 'new DataView(new ArrayBuffer(16))', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'new DataView(new ArrayBuffer(16), 12, 4)', generatePreview: true })).result); }, async function testArray() { InspectorTest.logMessage((await evaluate({ expression: '[]' })).result); InspectorTest.logMessage((await evaluate({ expression: '[1,2,3]' })).result); }, async function testArrayLike() { InspectorTest.logMessage((await evaluate({ expression: '({length: 5, splice: () => []})' })).result); InspectorTest.logMessage((await evaluate({ expression: `new (class Foo{constructor() { this.length = 5; this.splice = () => []; }})` })).result); InspectorTest.logMessage((await evaluate({ expression: '({length: -5, splice: () => []})' })).result); }, async function testOtherObjects() { InspectorTest.logMessage((await evaluate({ expression: '({a: 1, b:2})' })).result); InspectorTest.logMessage((await evaluate({ expression: '({a: 1, b:2})', returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: '({a: 1, b:2})', generatePreview: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'new (function Foo() { this.a = 5; })' })).result); InspectorTest.logMessage((await evaluate({ expression: 'new (function Foo() { this.a = [1,2,3]; })', returnByValue: true })).result); InspectorTest.logMessage((await evaluate({ expression: 'new (class Bar {})' })).result); InspectorTest.logMessage((await evaluate({ expression: 'inspector.createObjectWithAccessor(\'title\', true)', generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: 'inspector.createObjectWithAccessor(\'title\', false)', generatePreview: true }))); // TODO(kozyatinskiy): fix this one. InspectorTest.logMessage((await evaluate({ expression: 'inspector.createObjectWithAccessor(\'title\', true)', returnByValue: true }))); InspectorTest.logMessage((await evaluate({ expression: '({get a() { return 42; }})', generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: '({set a(v) {}})', generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: '({a: () => 42})', generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: '({a: null})', generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: '({a: true})', generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: '({a1: -Infinity, a2: +Infinity, a3: -0, a4: NaN, a5: 1.23})', generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: '({a1: 1234567890123456789012345678901234567890n})', generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: '({a1: Symbol(42)})', generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: '({a1: /abc/i})', generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: '({a1: () => 42, a2: async () => 42})', generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: '({a1: ({}), a2: new (class Bar{})})', generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: `({a1: 'a'.repeat(100), a2: 'a'.repeat(101)})`, generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: `({a1: 1, a2: 2, a3: 3, a4:4, a5:5, a6: 6})`, generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: `([1,2,3])`, generatePreview: true }))); }, async function testArray2() { InspectorTest.logMessage((await evaluate({ expression: `([1,2,3])` }))); InspectorTest.logMessage((await evaluate({ expression: `([1,2,3])`, returnByValue: true }))); InspectorTest.logMessage((await evaluate({ expression: `([1,2,3])`, generatePreview: true }))); InspectorTest.logMessage((await evaluate({ expression: `({a: [1,2,3]})`, generatePreview: true }))); } ]);
youtube/cobalt
third_party/v8/test/inspector/runtime/remote-object.js
JavaScript
bsd-3-clause
21,188
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.9.5.11_A2_T1; * @section: 15.9.5.11; * @assertion: The "length" property of the "getUTCFullYear" is 0; * @description: The "length" property of the "getUTCFullYear" is 0; */ if(Date.prototype.getUTCFullYear.hasOwnProperty("length") !== true){ $ERROR('#1: The getUTCFullYear has a "length" property'); } if(Date.prototype.getUTCFullYear.length !== 0){ $ERROR('#2: The "length" property of the getUTCFullYear is 0'); }
seraum/nectarjs
tests/ES3/Conformance/15_Native_ECMA_Script_Objects/15.9_Date_Objects/15.9.5_Properties_of_the_Date_Prototype_Object/15.9.5.11_Date.prototype.getUTCFullYear/S15.9.5.11_A2_T1.js
JavaScript
mit
579
define('lodash/object/get', ['exports', 'lodash/internal/baseGet', 'lodash/internal/toPath'], function (exports, _lodashInternalBaseGet, _lodashInternalToPath) { 'use strict'; /** * Gets the property value at `path` of `object`. If the resolved value is * `undefined` the `defaultValue` is used in its place. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : (0, _lodashInternalBaseGet['default'])(object, (0, _lodashInternalToPath['default'])(path), path + ''); return result === undefined ? defaultValue : result; } exports['default'] = get; });
hoka-plus/p-01-web
tmp/babel-output_path-hOv4KMmE.tmp/lodash/object/get.js
JavaScript
mit
1,164
var env = process.env.ISUCON_ENV || "local" module.exports = require("./../config/" + env);
isucon/isucon3
final/webapp/nodejs/config.js
JavaScript
mit
92
var originalLookup, App, originalModelInjections; module("Ember.Application Dependency Injection – toString",{ setup: function() { originalModelInjections = Ember.MODEL_FACTORY_INJECTIONS; Ember.MODEL_FACTORY_INJECTIONS = true; originalLookup = Ember.lookup; Ember.run(function(){ App = Ember.Application.create(); Ember.lookup = { App: App }; }); App.Post = Ember.Object.extend(); }, teardown: function() { Ember.lookup = originalLookup; Ember.run(App, 'destroy'); Ember.MODEL_FACTORY_INJECTIONS = originalModelInjections; } }); test("factories", function() { var PostFactory = App.__container__.lookupFactory('model:post'); equal(PostFactory.toString(), 'App.Post', 'expecting the model to be post'); }); test("instances", function() { var post = App.__container__.lookup('model:post'); var guid = Ember.guidFor(post); equal(post.toString(), '<App.Post:' + guid + '>', 'expecting the model to be post'); }); test("with a custom resolver", function() { Ember.run(App,'destroy'); Ember.run(function(){ App = Ember.Application.create({ Resolver: Ember.DefaultResolver.extend({ makeToString: function(factory, fullName) { return fullName; } }) }); }); App.__container__.register('model:peter', Ember.Object.extend()); var peter = App.__container__.lookup('model:peter'); var guid = Ember.guidFor(peter); equal(peter.toString(), '<model:peter:' + guid + '>', 'expecting the supermodel to be peter'); });
ssured/ember.js
packages/ember-application/tests/system/dependency_injection/to_string_test.js
JavaScript
mit
1,557
module.exports=[5024,5025,5026,5027,5028,5029,5030,5031,5032,5033,5034,5035,5036,5037,5038,5039,5040,5041,5042,5043,5044,5045,5046,5047,5048,5049,5050,5051,5052,5053,5054,5055,5056,5057,5058,5059,5060,5061,5062,5063,5064,5065,5066,5067,5068,5069,5070,5071,5072,5073,5074,5075,5076,5077,5078,5079,5080,5081,5082,5083,5084,5085,5086,5087,5088,5089,5090,5091,5092,5093,5094,5095,5096,5097,5098,5099,5100,5101,5102,5103,5104,5105,5106,5107,5108,5109,5110,5111,5112,5113,5114,5115,5116,5117,5118,5119]
marclundgren/mithril-fidm-app
node_modules/gulp-jscs/node_modules/jscs/node_modules/unicode-6.3.0/blocks/Cherokee/code-points.js
JavaScript
mit
496
import React, { cloneElement } from 'react'; import classNames from 'classnames'; import ValidComponentChildren from './utils/ValidComponentChildren'; class ListGroup extends React.Component { render() { let items = ValidComponentChildren.map( this.props.children, (item, index) => cloneElement(item, { key: item.key ? item.key : index }) ); let shouldRenderDiv = false; if (!this.props.children) { shouldRenderDiv = true; } else { React.Children.forEach(this.props.children, (child) => { if (this.isAnchorOrButton(child.props)) { shouldRenderDiv = true; } }); } if (shouldRenderDiv) { return this.renderDiv(items); } else { return this.renderUL(items); } } isAnchorOrButton(props) { return (props.href || props.onClick); } renderUL(items) { let listItems = ValidComponentChildren.map(items, (item) => cloneElement(item, { listItem: true }) ); return ( <ul {...this.props} className={classNames(this.props.className, 'list-group')}> {listItems} </ul> ); } renderDiv(items) { return ( <div {...this.props} className={classNames(this.props.className, 'list-group')}> {items} </div> ); } } ListGroup.propTypes = { className: React.PropTypes.string, id: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]) }; export default ListGroup;
jontewks/react-bootstrap
src/ListGroup.js
JavaScript
mit
1,507
import get from 'ember-metal/property_get'; import { SuiteModuleBuilder } from 'ember-runtime/tests/suites/suite'; const suite = SuiteModuleBuilder.create(); suite.module('removeObject'); suite.test('should return receiver', function() { let before = this.newFixture(3); let obj = this.newObject(before); equal(obj.removeObject(before[1]), obj, 'should return receiver'); }); suite.test('[A,B,C].removeObject(B) => [A,C] + notify', function() { let before = this.newFixture(3); let after = [before[0], before[2]]; let obj = this.newObject(before); let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject'); obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */ obj.removeObject(before[1]); deepEqual(this.toArray(obj), after, 'post item results'); equal(get(obj, 'length'), after.length, 'length'); if (observer.isEnabled) { equal(observer.timesCalled('[]'), 1, 'should have notified [] once'); equal(observer.timesCalled('@each'), 0, 'should not have notified @each once'); equal(observer.timesCalled('length'), 1, 'should have notified length once'); equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once'); equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once'); } }); suite.test('[A,B,C].removeObject(D) => [A,B,C]', function() { let before = this.newFixture(3); let after = before; let item = this.newFixture(1)[0]; let obj = this.newObject(before); let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject'); obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */ obj.removeObject(item); // note: item not in set deepEqual(this.toArray(obj), after, 'post item results'); equal(get(obj, 'length'), after.length, 'length'); if (observer.isEnabled) { equal(observer.validate('[]'), false, 'should NOT have notified []'); equal(observer.validate('@each'), false, 'should NOT have notified @each'); equal(observer.validate('length'), false, 'should NOT have notified length'); equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once'); equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once'); } }); export default suite;
bmac/ember.js
packages/ember-runtime/tests/suites/mutable_array/removeObject.js
JavaScript
mit
2,369
/** * Module dependencies. */ var express = require('express'); /** * Initialize middleware. */ module.exports = function() { this.use(express.urlencoded()); this.use(express.json()); this.use(this.router); this.use(express.errorHandler()); }
bosgood/electrolyte-examples
express/etc/init/02_middleware.js
JavaScript
mit
262
// Generated by CoffeeScript 1.3.3 (function() { var Path, createApiTree, extensions, fs, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, __hasProp = {}.hasOwnProperty; fs = require('fs'); Path = require('path'); extensions = function() { var k, v, _ref, _results; if (typeof require !== "undefined" && require !== null ? require.extensions : void 0) { _ref = require.extensions; _results = []; for (k in _ref) { v = _ref[k]; if (k !== '.json') { _results.push(k); } } return _results; } else { return ['.coffee']; } }; exports.createApiTree = createApiTree = function(directory, options) { var child, item, k, key, name, names, node, tree, v, _i, _len; if (options == null) { options = {}; } options.loadItem || (options.loadItem = require); options.nameToKey || (options.nameToKey = function(name) { return name.split('.')[0].replace(/_*\W+_*/g, '_'); }); options.readdirSync || (options.readdirSync = function(path) { return fs.readdirSync(path); }); options.isDirectory || (options.isDirectory = function(path) { return fs.lstatSync(path).isDirectory(); }); options.filter || (options.filter = function(name, names) { var ext, _ref; ext = Path.extname(name); return ext === '.js' || (__indexOf.call(extensions(), ext) >= 0 && !(_ref = Path.basename(name, ext).concat('.js'), __indexOf.call(names, _ref) >= 0)); }); tree = {}; names = options.readdirSync(directory); for (_i = 0, _len = names.length; _i < _len; _i++) { name = names[_i]; if (name.match(/^[._#]|[#~]$/)) { continue; } child = Path.join(directory, name); key = options.nameToKey(name); item = options.isDirectory(child) ? createApiTree(child, options) : options.filter(name, names) ? options.loadItem(child) : void 0; if (item && Object.keys(item).length) { node = (tree[key] || (tree[key] = {})); for (k in item) { if (!__hasProp.call(item, k)) continue; v = item[k]; if (node[k] != null) { throw new Error("API tree name conflict for '" + k + "' in " + child); } node[k] = v; } } } return tree; }; }).call(this);
rybon/Remocial
node_modules/ss-angular/node_modules/apitree/lib/apitree.js
JavaScript
mit
2,451
define({main:{"de-AT":{identity:{version:{_number:"$Revision: 11914 $",_cldrVersion:"29"},language:"de",territory:"AT"},dates:{timeZoneNames:{hourFormat:"+HH:mm;-HH:mm",gmtFormat:"GMT{0}",gmtZeroFormat:"GMT",regionFormat:"{0} Zeit","regionFormat-type-daylight":"{0} Sommerzeit","regionFormat-type-standard":"{0} Normalzeit",fallbackFormat:"{1} ({0})",zone:{America:{Anchorage:{exemplarCity:"Anchorage"},Bogota:{exemplarCity:"Bogotá"},Buenos_Aires:{exemplarCity:"Buenos Aires"},Caracas:{exemplarCity:"Caracas"}, Chicago:{exemplarCity:"Chicago"},Chihuahua:{exemplarCity:"Chihuahua"},Costa_Rica:{exemplarCity:"Costa Rica"},Denver:{exemplarCity:"Denver"},Edmonton:{exemplarCity:"Edmonton"},El_Salvador:{exemplarCity:"El Salvador"},Godthab:{exemplarCity:"Nuuk"},Guatemala:{exemplarCity:"Guatemala"},Guayaquil:{exemplarCity:"Guayaquil"},Halifax:{exemplarCity:"Halifax"},Indianapolis:{exemplarCity:"Indianapolis"},Lima:{exemplarCity:"Lima"},Los_Angeles:{exemplarCity:"Los Angeles"},Managua:{exemplarCity:"Managua"},Mazatlan:{exemplarCity:"Mazatlan"}, Mexico_City:{exemplarCity:"Mexiko-Stadt"},New_York:{exemplarCity:"New York"},Noronha:{exemplarCity:"Noronha"},Panama:{exemplarCity:"Panama"},Phoenix:{exemplarCity:"Phoenix"},Puerto_Rico:{exemplarCity:"Puerto Rico"},Regina:{exemplarCity:"Regina"},Santiago:{exemplarCity:"Santiago"},Sao_Paulo:{exemplarCity:"São Paulo"},St_Johns:{exemplarCity:"St. John’s"},Tijuana:{exemplarCity:"Tijuana"},Toronto:{exemplarCity:"Toronto"},Vancouver:{exemplarCity:"Vancouver"},Winnipeg:{exemplarCity:"Winnipeg"}},Atlantic:{Azores:{exemplarCity:"Azoren"}, Cape_Verde:{exemplarCity:"Kap Verde"},Reykjavik:{exemplarCity:"Reyk­ja­vík"}},Europe:{Amsterdam:{exemplarCity:"Amsterdam"},Athens:{exemplarCity:"Athen"},Belgrade:{exemplarCity:"Belgrad"},Berlin:{exemplarCity:"Berlin"},Brussels:{exemplarCity:"Brüssel"},Bucharest:{exemplarCity:"Bukarest"},Budapest:{exemplarCity:"Budapest"},Copenhagen:{exemplarCity:"Kopenhagen"},Dublin:{exemplarCity:"Dublin"},Helsinki:{exemplarCity:"Helsinki"},Istanbul:{exemplarCity:"Istanbul"},Kiev:{exemplarCity:"Kiew"},Lisbon:{exemplarCity:"Lissabon"}, London:{exemplarCity:"London"},Luxembourg:{exemplarCity:"Luxemburg"},Madrid:{exemplarCity:"Madrid"},Moscow:{exemplarCity:"Moskau"},Oslo:{exemplarCity:"Oslo"},Paris:{exemplarCity:"Paris"},Prague:{exemplarCity:"Prag"},Riga:{exemplarCity:"Riga"},Rome:{exemplarCity:"Rom"},Sofia:{exemplarCity:"Sofia"},Stockholm:{exemplarCity:"Stockholm"},Tallinn:{exemplarCity:"Tallinn"},Tirane:{exemplarCity:"Tirana"},Vienna:{exemplarCity:"Wien"},Vilnius:{exemplarCity:"Vilnius"},Warsaw:{exemplarCity:"Warschau"},Zurich:{exemplarCity:"Zürich"}}, Africa:{Algiers:{exemplarCity:"Algier"},Cairo:{exemplarCity:"Kairo"},Casablanca:{exemplarCity:"Casablanca"},Djibouti:{exemplarCity:"Dschibuti"},Harare:{exemplarCity:"Harare"},Johannesburg:{exemplarCity:"Johannesburg"},Khartoum:{exemplarCity:"Khartum"},Lagos:{exemplarCity:"Lagos"},Mogadishu:{exemplarCity:"Mogadischu"},Nairobi:{exemplarCity:"Nairobi"},Nouakchott:{exemplarCity:"Nouakchott"},Tripoli:{exemplarCity:"Tripolis"},Tunis:{exemplarCity:"Tunis"}},Asia:{Aden:{exemplarCity:"Aden"},Almaty:{exemplarCity:"Almaty"}, Amman:{exemplarCity:"Amman"},Baghdad:{exemplarCity:"Bagdad"},Bahrain:{exemplarCity:"Bahrain"},Baku:{exemplarCity:"Baku"},Bangkok:{exemplarCity:"Bangkok"},Beirut:{exemplarCity:"Beirut"},Calcutta:{exemplarCity:"Kalkutta"},Colombo:{exemplarCity:"Colombo"},Damascus:{exemplarCity:"Damaskus"},Dhaka:{exemplarCity:"Dhaka"},Dubai:{exemplarCity:"Dubai"},Hong_Kong:{exemplarCity:"Hongkong"},Irkutsk:{exemplarCity:"Irkutsk"},Jakarta:{exemplarCity:"Jakarta"},Jerusalem:{exemplarCity:"Jerusalem"},Kabul:{exemplarCity:"Kabul"}, Kamchatka:{exemplarCity:"Kamtschatka"},Karachi:{exemplarCity:"Karatschi"},Krasnoyarsk:{exemplarCity:"Krasnojarsk"},Kuala_Lumpur:{exemplarCity:"Kuala Lumpur"},Kuwait:{exemplarCity:"Kuwait"},Magadan:{exemplarCity:"Magadan"},Manila:{exemplarCity:"Manila"},Muscat:{exemplarCity:"Maskat"},Nicosia:{exemplarCity:"Nikosia"},Novosibirsk:{exemplarCity:"Nowosibirsk"},Qatar:{exemplarCity:"Katar"},Rangoon:{exemplarCity:"Rangun"},Riyadh:{exemplarCity:"Riad"},Saigon:{exemplarCity:"Ho-Chi-Minh-Stadt"},Seoul:{exemplarCity:"Seoul"}, Shanghai:{exemplarCity:"Shanghai"},Singapore:{exemplarCity:"Singapur"},Taipei:{exemplarCity:"Taipeh"},Tashkent:{exemplarCity:"Taschkent"},Tehran:{exemplarCity:"Teheran"},Tokyo:{exemplarCity:"Tokio"},Vladivostok:{exemplarCity:"Wladiwostok"},Yakutsk:{exemplarCity:"Jakutsk"},Yekaterinburg:{exemplarCity:"Jekaterinburg"}},Australia:{Adelaide:{exemplarCity:"Adelaide"},Brisbane:{exemplarCity:"Brisbane"},Darwin:{exemplarCity:"Darwin"},Hobart:{exemplarCity:"Hobart"},Perth:{exemplarCity:"Perth"},Sydney:{exemplarCity:"Sydney"}}, Pacific:{Auckland:{exemplarCity:"Auckland"},Fiji:{exemplarCity:"Fidschi"},Guam:{exemplarCity:"Guam"},Honolulu:{exemplarCity:"Honolulu"},Midway:{exemplarCity:"Midway"},Pago_Pago:{exemplarCity:"Pago Pago"},Tongatapu:{exemplarCity:"Tongatapu"}}},metazone:{Afghanistan:{"long":{standard:"Afghanistan-Zeit"}},Africa_Central:{"long":{standard:"Zentralafrikanische Zeit"}},Africa_Eastern:{"long":{standard:"Ostafrikanische Zeit"}},Africa_Southern:{"long":{standard:"Südafrikanische Zeit"}},Africa_Western:{"long":{generic:"Westafrikanische Zeit", standard:"Westafrikanische Normalzeit",daylight:"Westafrikanische Sommerzeit"}},Alaska:{"long":{generic:"Alaska-Zeit",standard:"Alaska-Normalzeit",daylight:"Alaska-Sommerzeit"}},Almaty:{"long":{generic:"Almaty-Zeit",standard:"Almaty-Normalzeit",daylight:"Almaty-Sommerzeit"}},America_Central:{"long":{generic:"Nordamerikanische Inlandzeit",standard:"Nordamerikanische Inland-Normalzeit",daylight:"Nordamerikanische Inland-Sommerzeit"}},America_Eastern:{"long":{generic:"Nordamerikanische Ostküstenzeit", standard:"Nordamerikanische Ostküsten-Normalzeit",daylight:"Nordamerikanische Ostküsten-Sommerzeit"}},America_Mountain:{"long":{generic:"Rocky-Mountain-Zeit",standard:"Rocky Mountain-Normalzeit",daylight:"Rocky-Mountain-Sommerzeit"}},America_Pacific:{"long":{generic:"Nordamerikanische Westküstenzeit",standard:"Nordamerikanische Westküsten-Normalzeit",daylight:"Nordamerikanische Westküsten-Sommerzeit"}},Arabian:{"long":{generic:"Arabische Zeit",standard:"Arabische Normalzeit",daylight:"Arabische Sommerzeit"}}, Argentina:{"long":{generic:"Argentinische Zeit",standard:"Argentinische Normalzeit",daylight:"Argentinische Sommerzeit"}},Atlantic:{"long":{generic:"Atlantik-Zeit",standard:"Atlantik-Normalzeit",daylight:"Atlantik-Sommerzeit"}},Australia_Central:{"long":{generic:"Zentralaustralische Zeit",standard:"Zentralaustralische Normalzeit",daylight:"Zentralaustralische Sommerzeit"}},Australia_Eastern:{"long":{generic:"Ostaustralische Zeit",standard:"Ostaustralische Normalzeit",daylight:"Ostaustralische Sommerzeit"}}, Australia_Western:{"long":{generic:"Westaustralische Zeit",standard:"Westaustralische Normalzeit",daylight:"Westaustralische Sommerzeit"}},Azerbaijan:{"long":{generic:"Aserbaidschanische Zeit",standard:"Aserbeidschanische Normalzeit",daylight:"Aserbaidschanische Sommerzeit"}},Azores:{"long":{generic:"Azoren-Zeit",standard:"Azoren-Normalzeit",daylight:"Azoren-Sommerzeit"}},Bangladesh:{"long":{generic:"Bangladesch-Zeit",standard:"Bangladesch-Normalzeit",daylight:"Bangladesch-Sommerzeit"}},Brasilia:{"long":{generic:"Brasília-Zeit", standard:"Brasília-Normalzeit",daylight:"Brasília-Sommerzeit"}},Cape_Verde:{"long":{generic:"Kap-Verde-Zeit",standard:"Kap-Verde-Normalzeit",daylight:"Kap-Verde-Sommerzeit"}},Chamorro:{"long":{standard:"Chamorro-Zeit"}},Chile:{"long":{generic:"Chilenische Zeit",standard:"Chilenische Normalzeit",daylight:"Chilenische Sommerzeit"}},China:{"long":{generic:"Chinesische Zeit",standard:"Chinesische Normalzeit",daylight:"Chinesische Sommerzeit"}},Colombia:{"long":{generic:"Kolumbianische Zeit",standard:"Kolumbianische Normalzeit", daylight:"Kolumbianische Sommerzeit"}},Ecuador:{"long":{standard:"Ecuadorianische Zeit"}},Europe_Central:{"long":{generic:"Mitteleuropäische Zeit",standard:"Mitteleuropäische Normalzeit",daylight:"Mitteleuropäische Sommerzeit"},"short":{generic:"MEZ",standard:"MEZ",daylight:"MESZ"}},Europe_Eastern:{"long":{generic:"Osteuropäische Zeit",standard:"Osteuropäische Normalzeit",daylight:"Osteuropäische Sommerzeit"},"short":{generic:"OEZ",standard:"OEZ",daylight:"OESZ"}},Europe_Western:{"long":{generic:"Westeuropäische Zeit", standard:"Westeuropäische Normalzeit",daylight:"Westeuropäische Sommerzeit"},"short":{generic:"WEZ",standard:"WEZ",daylight:"WESZ"}},Fiji:{"long":{generic:"Fidschi-Zeit",standard:"Fidschi-Normalzeit",daylight:"Fidschi-Sommerzeit"}},GMT:{"long":{standard:"Mittlere Greenwich-Zeit"}},Greenland_Western:{"long":{generic:"Westgrönland-Zeit",standard:"Westgrönland-Normalzeit",daylight:"Westgrönland-Sommerzeit"}},Guam:{"long":{standard:"Guam-Zeit"}},Gulf:{"long":{standard:"Golf-Zeit"}},Hawaii_Aleutian:{"long":{generic:"Hawaii-Aleuten-Zeit", standard:"Hawaii-Aleuten-Normalzeit",daylight:"Hawaii-Aleuten-Sommerzeit"}},Hong_Kong:{"long":{generic:"Hongkong-Zeit",standard:"Hongkong-Normalzeit",daylight:"Hongkong-Sommerzeit"}},India:{"long":{standard:"Indische Zeit"}},Indochina:{"long":{standard:"Indochina-Zeit"}},Indonesia_Western:{"long":{standard:"Westindonesische Zeit"}},Iran:{"long":{generic:"Iranische Zeit",standard:"Iranische Normalzeit",daylight:"Iranische Sommerzeit"}},Irkutsk:{"long":{generic:"Irkutsk-Zeit",standard:"Irkutsk-Normalzeit", daylight:"Irkutsk-Sommerzeit"}},Israel:{"long":{generic:"Israelische Zeit",standard:"Israelische Normalzeit",daylight:"Israelische Sommerzeit"}},Japan:{"long":{generic:"Japanische Zeit",standard:"Japanische Normalzeit",daylight:"Japanische Sommerzeit"}},Kamchatka:{"long":{generic:"Kamtschatka-Zeit",standard:"Kamtschatka-Normalzeit",daylight:"Kamtschatka-Sommerzeit"}},Kazakhstan_Eastern:{"long":{standard:"Ostkasachische Zeit"}},Korea:{"long":{generic:"Koreanische Zeit",standard:"Koreanische Normalzeit", daylight:"Koreanische Sommerzeit"}},Krasnoyarsk:{"long":{generic:"Krasnojarsk-Zeit",standard:"Krasnojarsk-Normalzeit",daylight:"Krasnojarsk-Sommerzeit"}},Lanka:{"long":{standard:"Sri-Lanka-Zeit"}},Magadan:{"long":{generic:"Magadan-Zeit",standard:"Magadan-Normalzeit",daylight:"Magadan-Sommerzeit"}},Malaysia:{"long":{standard:"Malaysische Zeit"}},Moscow:{"long":{generic:"Moskauer Zeit",standard:"Moskauer Normalzeit",daylight:"Moskauer Sommerzeit"}},Myanmar:{"long":{standard:"Myanmar-Zeit"}},New_Zealand:{"long":{generic:"Neuseeland-Zeit", standard:"Neuseeland-Normalzeit",daylight:"Neuseeland-Sommerzeit"}},Newfoundland:{"long":{generic:"Neufundland-Zeit",standard:"Neufundland-Normalzeit",daylight:"Neufundland-Sommerzeit"}},Noronha:{"long":{generic:"Fernando de Noronha-Zeit",standard:"Fernando de Noronha-Normalzeit",daylight:"Fernando de Noronha-Sommerzeit"}},Novosibirsk:{"long":{generic:"Nowosibirsk-Zeit",standard:"Nowosibirsk-Normalzeit",daylight:"Nowosibirsk-Sommerzeit"}},Pakistan:{"long":{generic:"Pakistanische Zeit",standard:"Pakistanische Normalzeit", daylight:"Pakistanische Sommerzeit"}},Peru:{"long":{generic:"Peruanische Zeit",standard:"Peruanische Normalzeit",daylight:"Peruanische Sommerzeit"}},Philippines:{"long":{generic:"Philippinische Zeit",standard:"Philippinische Normalzeit",daylight:"Philippinische Sommerzeit"}},Samoa:{"long":{generic:"Samoa-Zeit",standard:"Samoa-Normalzeit",daylight:"Samoa-Sommerzeit"}},Singapore:{"long":{standard:"Singapur-Zeit"}},Taipei:{"long":{generic:"Taipeh-Zeit",standard:"Taipeh-Normalzeit",daylight:"Taipeh-Sommerzeit"}}, Tonga:{"long":{generic:"Tonganische Zeit",standard:"Tonganische Normalzeit",daylight:"Tonganische Sommerzeit"}},Uzbekistan:{"long":{generic:"Usbekistan-Zeit",standard:"Usbekistan-Normalzeit",daylight:"Usbekistan-Sommerzeit"}},Venezuela:{"long":{standard:"Venezuela-Zeit"}},Vladivostok:{"long":{generic:"Wladiwostok-Zeit",standard:"Wladiwostok-Normalzeit",daylight:"Wladiwostok-Sommerzeit"}},Yakutsk:{"long":{generic:"Jakutsk-Zeit",standard:"Jakutsk-Normalzeit",daylight:"Jakutsk-Sommerzeit"}},Yekaterinburg:{"long":{generic:"Jekaterinburg-Zeit", standard:"Jekaterinburg-Normalzeit",daylight:"Jekaterinburg-Sommerzeit"}}}}}}}});
crmouli/crmouli.github.io
js/libs/oj/v3.0.0/resources/nls/de-AT/timezoneData.js
JavaScript
mit
12,171
YUI.add('gallery-plugin-node-io', function(Y) { /** * Node IO provides a simple interface to load text into a node * * @class NodeIo * @extends Base * @version 1.1.0 */ var YL = Y.Lang; Y.Plugin.NodeIo = Y.Base.create('node-io', Y.Base, [], { /////// P U B L I C ////// /** * Set up ioHandler and bind events * @since 1.1.0 * @method initializer */ initializer : function(){ this.publish('success', {defaultFn: this._defSuccessFn }); this.after('uriChange', this._afterUriChange); this._ioHandlers = { complete: Y.bind(this._handleResponse, this, 'complete'), success: Y.bind(this._handleResponse, this, 'success'), failure: Y.bind(this._handleResponse, this, 'failure'), end: Y.bind(this._handleResponse, this, 'end') }; }, /** * Set uri and start io * @since 1.0.0 * @method load * @chainable * @return {NodeIo} A reference to this object */ load : function(uri) { var config = this.get('ioConfig'); if(!uri) { uri = this.get('uri'); }else{ this.set('uri', uri); } config.on = this._ioHandlers; this._io = Y.io(uri, config); return this; }, /** * Sugar method to refresh the content * Not recommended if placement is not `replace` * @since 1.0.0 * @method refresh * @chainable * @return {NodeIo} A reference to this object */ refresh : function(){ return this.load(); }, /** * Stops any current io * @since 1.0.0 * @method abort * @chainable * @return {NodeIo} A reference to this object */ abort : function() { this._stopIO(); return this; }, ////// P R O T E C T E D ////// /** * Local storage of the internal Y.io * @since 1.0.0 * @protected */ _io: null, /** * Object used to set the on of the _io * @since 1.1.0 * @protected */ _ioHandlers: null, /** * Aborts any current io * @since 1.0.0 * @method _stopIO * @protected */ _stopIO : function() { if(this._io) { this._io.abort(); this._io = null; } }, /** * Single interface for io responses * @since 1.1.0 * @method _handleResponse * @protected */ _handleResponse : function (type, id, o) { this.fire(type, {id: id, response: o}); this._io = null; }, /** * Default onSuccess method for io * Inserts response text into the host by placement * @since 1.1.0 * @method _defSuccessFn * @protected */ _defSuccessFn : function(e) { this.get('host').insert(e.response.responseText, this.get('placement')); }, /** * Aborts any io when the uri is changed * @since 1.1.0 * @method _afterUriChange * @protected */ _afterUriChange : function() { this._stopIO(); } }, { NS : 'io', ATTRS : { /** * Stores host node * @since 1.0.0 * @attribute host * @type Y.Plugin.Host */ host : { writeOnce : true }, /** * Allows for advanced io configuration * @since 1.0.0 * @attribute ioConfig * @type object * @default {} */ ioConfig : { value : {}, validator : YL.isObject }, /** * Placement of responseText * @since 1.0.0 * @attribute placement * @type string * @defautl replace */ placement : { value : 'replace', validator : function(val) { return (/replace|(?:ap|pre)pend/).test(val); } }, /** * Specifies the URI for the io * @since 1.0.0 * @attribute uri * @type string */ uri : { validator : YL.isString } } }); }, 'gallery-2010.09.08-19-45' ,{requires:['plugin','node-base','node-pluginhost','io-base','base-build']});
inikoo/fact
libs/yui/yui3-gallery/build/gallery-plugin-node-io/gallery-plugin-node-io.js
JavaScript
mit
4,086
var validate, $i; var {{ schema | capitalize }}Validator = function(di) { $i = di; validate = $i.validate; return {}; }; module.exports = exports = {{ schema | capitalize }}Validator;
marcelomf/graojs
skeletons/bundle/Validator.js
JavaScript
mit
190
Tinytest.add('options cacheLimit - exceed', function(test) { var sm = new SubsManager({cacheLimit: 2}); sm._addSub(['posts']); sm._addSub(['comments']); sm._addSub(['singlePoint', 'one']); sm._applyCacheLimit(); test.equal(sm._cacheList.length, 2); var subsIds = sm._cacheList.map(function(sub) { return sub.args[0]; }); test.equal(subsIds, ['comments', 'singlePoint']); sm.clear(); }); Tinytest.add('options cacheLimit - not-exceed', function(test) { var sm = new SubsManager({cacheLimit: 10}); sm._addSub(['posts']); sm._addSub(['comments']); sm._addSub(['singlePoint', 'one']); sm._applyCacheLimit(); test.equal(sm._cacheList.length, 3); var subsIds = sm._cacheList.map(function(sub) { return sub.args[0]; }); test.equal(subsIds, ['posts', 'comments', 'singlePoint']); sm.clear(); }); Tinytest.addAsync('options expireIn - expired', function(test, done) { // expireIn 100 millis var sm = new SubsManager({cacheLimit: 20, expireIn: 1/60/10}); sm._addSub(['posts']); sm._addSub(['comments']); test.equal(sm._cacheList.length, 2); Meteor.call('wait', 200, function() { sm._applyExpirations(); test.equal(sm._cacheList.length, 0); sm.clear(); done(); }); }); Tinytest.addAsync('options expireIn - not expired', function(test, done) { // expireIn 2 minutes var sm = new SubsManager({cacheLimit: 20, expireIn: 2}); sm._addSub(['posts']); sm._addSub(['comments']); test.equal(sm._cacheList.length, 2); Meteor.call('wait', 200, function() { sm._applyExpirations(); test.equal(sm._cacheList.length, 2); sm.clear(); done(); }); });
parkerkimbell/subs-manager
tests/options.js
JavaScript
mit
1,642
module.exports={title:"KeePassXC",slug:"keepassxc",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>KeePassXC</title><path d="'+this.path+'"/></svg>'},path:"M12 0C5.378 0 0 5.378 0 12c0 6.623 5.378 12 12 12 6.623 0 12-5.377 12-12 0-6.622-5.377-12-12-12zm0 .791a11.203 11.203 0 0 1 11.209 11.21A11.202 11.202 0 0 1 12 23.208 11.203 11.203 0 0 1 .791 12 11.203 11.203 0 0 1 12.001.791zm0 1.871a9.356 9.356 0 0 0-1.705.162A1.746 1.746 0 0 0 12 4.95a1.746 1.746 0 0 0 1.706-2.126A9.342 9.342 0 0 0 12 2.662zM7.2 4a9.338 9.338 0 0 0-4.54 8 9.338 9.338 0 0 0 18.677 0 9.338 9.338 0 0 0-4.54-7.998 4.888 4.888 0 0 1-2.701 5.365l-.12 2.066 1.482 1.483-1.483 1.482.989.989-.989.988.12 1.857L12 20.328l-2.096-2.096V9.367A4.89 4.89 0 0 1 7.2 4zm3.4 6.543v6.99h.7v-6.99z",source:"https://github.com/keepassxreboot/keepassxc/",hex:"6CAC4D",guidelines:void 0,license:void 0};
cdnjs/cdnjs
ajax/libs/simple-icons/5.24.0/keepassxc.min.js
JavaScript
mit
907
Ext.define('Ext.chart.theme.Default', { extend: 'Ext.chart.theme.Base', singleton: true, alias: [ 'chart.theme.default', 'chart.theme.Base' ] });
ybbkd2/publicweb
web/ext/packages/sencha-charts/src/chart/theme/Default.js
JavaScript
gpl-2.0
177
(function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; define(function(require) { var AnimationProperty, StampingEffectProperty; AnimationProperty = require('../base/module'); return StampingEffectProperty = (function(superClass) { extend(StampingEffectProperty, superClass); function StampingEffectProperty() { StampingEffectProperty.__super__.constructor.call(this, { id: 'stamping', name: 'Stamping' }); } return StampingEffectProperty; })(AnimationProperty); }); }).call(this); //# sourceMappingURL=../../../../../maps/modules/datasketch/animation/properties/stamping/module.js.map
CalCoRE/DataSketch
DataSketchServerUpload/DataSketchWeb/DataSketch.Web/obj/Release/Package/PackageTmp/DataSketchApp3/cslib/modules/datasketch/animation/properties/stamping/module.js
JavaScript
gpl-2.0
954
/*! * Aloha Editor * Author & Copyright (c) 2010 Gentics Software GmbH * [email protected] * Licensed unter the terms of http://www.aloha-editor.com/license.html */ /** * @name block.editor * @namespace Block attribute editors */ define(['aloha/jquery', 'aloha/observable'], function(jQuery, Observable) { /** * @name block.editor.AbstractEditor * @class An abstract editor */ var AbstractEditor = Class.extend(Observable, /** @lends block.editor.AbstractEditor */ { schema: null, /** * @constructor */ _constructor: function(schema) { this.schema = schema; }, /** * Template method to render the editor elements * @return {jQuery} */ render: function() { // Implement in subclass! }, /** * Template method to get the editor values */ getValue: function() { // Implement in subclass! }, /** * We do not throw any change event here, as we need to break the loop "Block" -> "Editor" -> "Block" * * @param {String} value */ setValue: function(value) { // Implement in subclass! }, /** * Destroy the editor elements and unbind events */ destroy: function() { // Implement in subclass! }, /** * On deactivating, we still need to trigger a change event if the value has been modified. * * @private */ _deactivate: function() { this.trigger('change', this.getValue()); this.destroy(); } }); /** * @name block.editor.AbstractFormElementEditor * @class An abstract form editor with label * @extends block.editor.AbstractEditor */ var AbstractFormElementEditor = AbstractEditor.extend( /** @lends block.editor.AbstractFormElementEditor */ { /** * Input element HTML definition * @type String * * @private */ formInputElementDefinition: null, /** * @type jQuery */ _$formInputElement: null, /** * Render the label and form element * @return {jQuery} */ render: function() { var $wrapper = jQuery('<div class="aloha-block-editor" />'); var guid = GENTICS.Utils.guid(); $wrapper.append(this.renderLabel().attr('id', guid)); $wrapper.append(this.renderFormElement().attr('id', guid)); return $wrapper; }, /** * Render the label for the editor * @return {jQuery} */ renderLabel: function() { var element = jQuery('<label />'); element.html(this.schema.label); return element; }, /** * Render the form input element * @return {jQuery} */ renderFormElement: function() { var that = this; this._$formInputElement = jQuery(this.formInputElementDefinition); this._$formInputElement.change(function() { that.trigger('change', that.getValue()); }); return this._$formInputElement; }, /** * @return {String} */ getValue: function() { return this._$formInputElement.val(); }, /** * We do not throw any change event here, as we need to break the loop "Block" -> "Editor" -> "Block" */ setValue: function(value) { this._$formInputElement.val(value); }, /** * Cleanup and remove the input element */ destroy: function() { this._$formInputElement.remove(); } }); /** * @name block.editor.StringEditor * @class An editor for string input * @extends block.editor.AbstractFormElementEditor */ var StringEditor = AbstractFormElementEditor.extend( /** @lends block.editor.StringEditor */ { formInputElementDefinition: '<input type="text" />' }); /** * @name block.editor.NumberEditor * @class An editor for numbers * @extends block.editor.AbstractFormElementEditor */ var NumberEditor = AbstractFormElementEditor.extend( /** @lends block.editor.NumberEditor */ { // TODO Range should be an option formInputElementDefinition: '<input type="range" />' }); /** * @name block.editor.UrlEditor * @class An editor for URLs * @extends block.editor.AbstractFormElementEditor */ var UrlEditor = AbstractFormElementEditor.extend( /** @lends block.editor.UrlEditor */ { formInputElementDefinition: '<input type="url" />' }); /** * @name block.editor.EmailEditor * @class An editor for email addresses * @extends block.editor.AbstractFormElementEditor */ var EmailEditor = AbstractFormElementEditor.extend( /** @lends block.editor.EmailEditor */ { formInputElementDefinition: '<input type="email" />' }); return { AbstractEditor: AbstractEditor, AbstractFormElementEditor: AbstractFormElementEditor, StringEditor: StringEditor, NumberEditor: NumberEditor, UrlEditor: UrlEditor, EmailEditor: EmailEditor } });
berkmancenter/spectacle
web/js/lib/plugins/common/block/lib/editor.js
JavaScript
gpl-2.0
4,571
define([ 'angular' , './instance-controller' , './instance-directive' , '../../glyph/glyph' ], function( angular , Controller , directive , glyphModule ) { "use strict"; return angular.module('mtk.instance', [glyphModule.name]) .controller('InstanceController', Controller) .directive('mtkInstance', directive) ; });
jeroenbreen/metapolator
app/lib/ui/metapolator/instance-panel/instance/instance.js
JavaScript
gpl-3.0
378
if (Date.first_day_of_week == 1) { Date.weekdays = $w("L Ma Me J V S D"); } else { Date.weekdays = $w("D L Ma Me J V S"); } Date.months = $w('Janvier Février Mars Avril Mai Juin Juillet Août Septembre Octobre Novembre Décembre'); _translations = { "OK": "OK", "Now": "Maintenant", "Today": "Aujourd'hui", "Clear": "Claire" };
wesbillman/projects
public/javascripts/calendar_date_select/locale/fr.js
JavaScript
agpl-3.0
349
var classCqrs_1_1Tests_1_1Cache_1_1When__saving__aggregate = [ [ "Setup", "classCqrs_1_1Tests_1_1Cache_1_1When__saving__aggregate_ae3cdfe47b998fc0e76ffc9c9b125c441.html#ae3cdfe47b998fc0e76ffc9c9b125c441", null ], [ "Should_get_same_aggregate_on_get", "classCqrs_1_1Tests_1_1Cache_1_1When__saving__aggregate_a7b8f4858d610b1db41b395516b1dc72b.html#a7b8f4858d610b1db41b395516b1dc72b", null ], [ "Should_not_cache_empty_id", "classCqrs_1_1Tests_1_1Cache_1_1When__saving__aggregate_ae5d0ee92c05898125cc5046fbea0a654.html#ae5d0ee92c05898125cc5046fbea0a654", null ], [ "Should_save_to_repository", "classCqrs_1_1Tests_1_1Cache_1_1When__saving__aggregate_affc34709b78fecd91d555de42344d2ed.html#affc34709b78fecd91d555de42344d2ed", null ] ];
Chinchilla-Software-Com/CQRS
wiki/docs/2.2/html/classCqrs_1_1Tests_1_1Cache_1_1When__saving__aggregate.js
JavaScript
lgpl-2.1
747
// 不再赘述 var path = require('path') // 加载 confi.index.js var config = require('../config') // 使用一些小工具 var utils = require('./utils') // 加载 webpack var webpack = require('webpack') // 加载 webpack 配置合并工具 var merge = require('webpack-merge') // 加载 webpack.base.conf.js var baseWebpackConfig = require('./webpack.base.conf') // 一个 webpack 扩展,可以提取一些代码并且将它们和文件分离开 // 如果我们想将 webpack 打包成一个文件 css js 分离开,那我们需要这个插件 var ExtractTextPlugin = require('extract-text-webpack-plugin') // 一个可以插入 html 并且创建新的 .html 文件的插件 var HtmlWebpackPlugin = require('html-webpack-plugin') var env = config.build.env // 合并 webpack.base.conf.js var webpackConfig = merge(baseWebpackConfig, { // 使用的 loader module: { loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) }, // 是否使用 #source-map 开发工具,更多信息可以查看 DDFE 往期文章 devtool: config.build.productionSourceMap ? '#source-map' : false, output: { // 编译输出目录 path: config.build.assetsRoot, // 编译输出文件名 // 我们可以在 hash 后加 :6 决定使用几位 hash 值 filename: utils.assetsPath('js/[name].[chunkhash].js'), // 没有指定输出名的文件输出的文件名 chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') }, vue: { // 编译 .vue 文件时使用的 loader loaders: utils.cssLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) }, // 使用的插件 plugins: [ // http://vuejs.github.io/vue-loader/en/workflow/production.html // definePlugin 接收字符串插入到代码当中, 所以你需要的话可以写上 JS 的字符串 new webpack.DefinePlugin({ 'process.env': env }), // 压缩 js (同样可以压缩 css) new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new webpack.optimize.OccurrenceOrderPlugin(), // 将 css 文件分离出来 new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')), // 输入输出的 .html 文件 new HtmlWebpackPlugin({ filename: config.build.index, template: 'index.html', // 是否注入 html inject: true, // 压缩的方式 minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true // more options: // https://github.com/kangax/html-minifier#options-quick-reference }, // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }), // 没有指定输出文件名的文件输出的静态文件名 new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module, count) { // any required modules inside node_modules are extracted to vendor return ( module.resource && /\.js$/.test(module.resource) && module.resource.indexOf( path.join(__dirname, '../node_modules') ) === 0 ) } }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', chunks: ['vendor'] }) ] }) // 开启 gzip 的情况下使用下方的配置 if (config.build.productionGzip) { // 加载 compression-webpack-plugin 插件 var CompressionWebpackPlugin = require('compression-webpack-plugin') // 向webpackconfig.plugins中加入下方的插件 webpackConfig.plugins.push( // 使用 compression-webpack-plugin 插件进行压缩 new CompressionWebpackPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: new RegExp( '\\.(' + config.build.productionGzipExtensions.join('|') + ')$' ), threshold: 10240, minRatio: 0.8 }) ) } module.exports = webpackConfig
huang303513/WebBasicCommonDemos
vue-cli2.0的webpack配置分析/lessproject/build/webpack.prod.conf.js
JavaScript
apache-2.0
4,179
//>>built define("dojox/lang/async/event",["dijit","dojo","dojox"],function(k,b,h){b.provide("dojox.lang.async.event");(function(){var g=h.lang.async.event;g.from=function(e,f){return function(){var a,c=function(){a&&(b.disconnect(a),a=null)},d=new b.Deferred(c);a=b.connect(e,f,function(a){c();d.callback(a)});return d}};g.failOn=function(e,f){return function(){var a,c=function(){a&&(b.disconnect(a),a=null)},d=new b.Deferred(c);a=b.connect(e,f,function(a){c();d.errback(Error(a))});return d}}})()});
aconyteds/Esri-Ozone-Map-Widget
vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/dojox/lang/async/event.js
JavaScript
apache-2.0
502
var assert = require('assert'); var util = require('util'); var events = require('events'); var utils = require('../../lib/utils'); var helper = require('../test-helper'); var InetAddress = require('../../lib/types').InetAddress; describe('InetAddress', function () { describe('constructor', function () { it('should validate the Buffer length', function () { assert.throws(function () { new InetAddress(new Buffer(10)); }); assert.throws(function () { new InetAddress(null); }); assert.throws(function () { new InetAddress(); }); assert.doesNotThrow(function () { new InetAddress(new Buffer(16)); }); assert.doesNotThrow(function () { new InetAddress(new Buffer(4)); }); }); }); describe('#toString()', function () { it('should convert IPv6 to string representation', function () { var val = new InetAddress(new Buffer('aabb0000eeff00112233445566778899', 'hex')); assert.strictEqual(val.version, 6); assert.strictEqual(val.toString(), 'aabb::eeff:11:2233:4455:6677:8899'); val = new InetAddress(new Buffer('aabbccddeeff00112233445566778899', 'hex')); assert.strictEqual(val.toString(), 'aabb:ccdd:eeff:11:2233:4455:6677:8899'); val = new InetAddress(new Buffer('aabb0000000000112233445566778899', 'hex')); assert.strictEqual(val.toString(), 'aabb::11:2233:4455:6677:8899'); val = new InetAddress(new Buffer('aabb0001000100112233445500000000', 'hex')); assert.strictEqual(val.toString(), 'aabb:1:1:11:2233:4455::'); val = new InetAddress(new Buffer('00000000000100112233445500aa00bb', 'hex')); assert.strictEqual(val.toString(), '::1:11:2233:4455:aa:bb'); val = new InetAddress(new Buffer('000000000000000022330000000000bb', 'hex')); assert.strictEqual(val.toString(), '::2233:0:0:bb'); val = new InetAddress(new Buffer('00000000000000000000000000000001', 'hex')); assert.strictEqual(val.toString(), '::1'); }); it('should convert IPv4 to string representation', function () { var val = new InetAddress(new Buffer([127, 0, 0, 1])); assert.strictEqual(val.version, 4); assert.strictEqual(val.toString(), '127.0.0.1'); val = new InetAddress(new Buffer([198, 168, 1, 1])); assert.strictEqual(val.toString(), '198.168.1.1'); val = new InetAddress(new Buffer([10, 12, 254, 32])); assert.strictEqual(val.toString(), '10.12.254.32'); }); }); describe('#equals()', function () { it('should return true when the bytes are the same', function () { var hex1 = 'aabb0000eeff00112233445566778899'; var hex2 = 'ffff0000eeff00112233445566778899'; var buf1 = new Buffer(hex1, 'hex'); var val1 = new InetAddress(buf1); var val2 = new InetAddress(new Buffer(hex2, 'hex')); assert.ok(val1.equals(new InetAddress(buf1))); assert.ok(val1.equals(new InetAddress(new Buffer(hex1, 'hex')))); assert.ok(!val1.equals(val2)); }); }); describe('fromString()', function () { it('should parse IPv6 string representation', function () { [ 'aabb::eeff:11:2233:4455:6677:8899', 'aabb:1:eeff:11:2233:4455:6677:8899', 'aabb:1:eeff:11:2233:4455:6677:8899', '::1:11:2233:4455:aa:bb', '::2233:0:0:bb', '::1234', '10fa::1' ].forEach(function (item) { var val = InetAddress.fromString(item, 'hex'); helper.assertInstanceOf(val, InetAddress); assert.strictEqual(val.toString(), item); }); }); it('should parse IPv4 string representation', function () { var val = InetAddress.fromString('127.0.0.1'); helper.assertInstanceOf(val, InetAddress); assert.strictEqual(val.toString(), '127.0.0.1'); val = InetAddress.fromString('198.168.1.1'); helper.assertInstanceOf(val, InetAddress); assert.strictEqual(val.toString(), '198.168.1.1'); val = InetAddress.fromString('10.11.12.13'); helper.assertInstanceOf(val, InetAddress); assert.strictEqual(val.toString(), '10.11.12.13'); }); it('should throw when can not parse to 4 or 16 bytes', function () { assert.throws(function () { InetAddress.fromString('127.0.0.1.10'); }, Error); }); }); });
thiagoveras/nodejs-driver
test/unit/inet-address-tests.js
JavaScript
apache-2.0
4,324
var V; function F() { } ; var C = (function () { function C() { } C.prototype.pF = function () { }; C.prototype.rF = function () { }; C.prototype.pgF = function () { }; C.prototype.psF = function (param) { }; C.prototype.rgF = function () { }; C.prototype.rsF = function (param) { }; C.tF = function tF() { }; C.tsF = function tsF(param) { }; C.tgF = function tgF() { }; return C; })(); ; ; var M; (function (M) { var V; function F() { } ; var C = (function () { function C() { } C.prototype.pF = function () { }; C.prototype.rF = function () { }; C.prototype.pgF = function () { }; C.prototype.psF = function (param) { }; C.prototype.rgF = function () { }; C.prototype.rsF = function (param) { }; C.tF = function tF() { }; C.tsF = function tsF(param) { }; C.tgF = function tgF() { }; return C; })(); ; ; var M; (function (M) { var V; function F() { } ; var C = (function () { function C() { } return C; })(); ; ; ; M.eV; function eF() { } M.eF = eF; ; var eC = (function () { function eC() { } return eC; })(); M.eC = eC; ; ; ; ; ; })(M || (M = {})); M.eV; function eF() { } M.eF = eF; ; var eC = (function () { function eC() { } eC.prototype.pF = function () { }; eC.prototype.rF = function () { }; eC.prototype.pgF = function () { }; eC.prototype.psF = function (param) { }; eC.prototype.rgF = function () { }; eC.prototype.rsF = function (param) { }; eC.tF = function tF() { }; eC.tsF = function tsF(param) { }; eC.tgF = function tgF() { }; return eC; })(); M.eC = eC; ; ; (function (eM) { var V; function F() { } ; var C = (function () { function C() { } return C; })(); ; ; ; eM.eV; function eF() { } eM.eF = eF; ; var eC = (function () { function eC() { } return eC; })(); eM.eC = eC; ; ; ; ; ; })(M.eM || (M.eM = {})); var eM = M.eM; ; })(M || (M = {})); exports.eV; function eF() { } exports.eF = eF; ; var eC = (function () { function eC() { } eC.prototype.pF = function () { }; eC.prototype.rF = function () { }; eC.prototype.pgF = function () { }; eC.prototype.psF = function (param) { }; eC.prototype.rgF = function () { }; eC.prototype.rsF = function (param) { }; eC.tF = function tF() { }; eC.tsF = function tsF(param) { }; eC.tgF = function tgF() { }; return eC; })(); exports.eC = eC; ; ; (function (eM) { var V; function F() { } ; var C = (function () { function C() { } C.prototype.pF = function () { }; C.prototype.rF = function () { }; C.prototype.pgF = function () { }; C.prototype.psF = function (param) { }; C.prototype.rgF = function () { }; C.prototype.rsF = function (param) { }; C.tF = function tF() { }; C.tsF = function tsF(param) { }; C.tgF = function tgF() { }; return C; })(); ; ; var M; (function (M) { var V; function F() { } ; var C = (function () { function C() { } return C; })(); ; ; ; M.eV; function eF() { } M.eF = eF; ; var eC = (function () { function eC() { } return eC; })(); M.eC = eC; ; ; ; ; ; })(M || (M = {})); eM.eV; function eF() { } eM.eF = eF; ; var eC = (function () { function eC() { } eC.prototype.pF = function () { }; eC.prototype.rF = function () { }; eC.prototype.pgF = function () { }; eC.prototype.psF = function (param) { }; eC.prototype.rgF = function () { }; eC.prototype.rsF = function (param) { }; eC.tF = function tF() { }; eC.tsF = function tsF(param) { }; eC.tgF = function tgF() { }; return eC; })(); eM.eC = eC; ; ; (function (eM) { var V; function F() { } ; var C = (function () { function C() { } return C; })(); ; ; ; eM.eV; function eF() { } eM.eF = eF; ; var eC = (function () { function eC() { } return eC; })(); eM.eC = eC; ; ; ; ; ; })(eM.eM || (eM.eM = {})); var eM = eM.eM; ; })(exports.eM || (exports.eM = {})); var eM = exports.eM; ;
vcsjones/typescript
tests/baselines/reference/giant.commonjs.js
JavaScript
apache-2.0
5,825
/** * @license * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ foam.CLASS({ package: 'foam.graphics', name: 'StereoCView', extends: 'foam.graphics.CView', methods: [ function paintChildren(x) { this.children.sort(function(o1, o2) { return o2.z - o1.z; }); for ( var i = 0 ; i < this.children.length ; i++ ) { var c = this.children[i]; c.x += 20; c.paint(x); } x.translate(500, 0); for ( var i = 0 ; i < this.children.length ; i++ ) { var c = this.children[i]; c.x -= 20; c.paint(x); } } ] });
jacksonic/vjlofvhjfgm
src/foam/graphics/StereoCView.js
JavaScript
apache-2.0
1,166
var path = require('path'); var assign = require('object-assign'); var forEachBail = require('enhanced-resolve/lib/forEachBail'); var basename = require('enhanced-resolve/lib/getPaths').basename; module.exports = function (modulesToResolveToEs5) { return { apply: doApply.bind(this, modulesToResolveToEs5) }; }; function doApply(modulesToResolveToEs5, resolver) { // file type taken from: https://github.com/webpack/enhanced-resolve/blob/v4.0.0/test/plugins.js var target = resolver.ensureHook("undescribed-raw-file"); //console.log(resolver.hooks); resolver.getHook("resolve") .tapAsync("ViewerResolvePlugin", (request, resolveContext, callback) => { for(var package of modulesToResolveToEs5){ if(request.request.indexOf(package+"/") == 0){ const newRequest = Object.assign({}, request, { request: package, }); return resolver.doResolve(target, newRequest, "viewer resolved", resolveContext, callback); } } return callback(); }); }
BabylonJS/Babylon.js
Tools/WebpackPlugins/viewerResolve.js
JavaScript
apache-2.0
1,075
// This file was procedurally generated from the following sources: // - src/dstr-binding-for-await/ary-ptrn-rest-ary-rest.case // - src/dstr-binding-for-await/default/for-await-of-async-gen-const.template /*--- description: Rest element containing a rest element (for-await-of statement) esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation features: [destructuring-binding, async-iteration] flags: [generated, async] info: | IterationStatement : for await ( ForDeclaration of AssignmentExpression ) Statement [...] 2. Return ? ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, lexicalBinding, labelSet, async). 13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation [...] 4. Let destructuring be IsDestructuring of lhs. [...] 6. Repeat [...] j. If destructuring is false, then [...] k. Else i. If lhsKind is assignment, then [...] ii. Else if lhsKind is varBinding, then [...] iii. Else, 1. Assert: lhsKind is lexicalBinding. 2. Assert: lhs is a ForDeclaration. 3. Let status be the result of performing BindingInitialization for lhs passing nextValue and iterationEnv as arguments. [...] 13.3.3.6 Runtime Semantics: IteratorBindingInitialization BindingRestElement : ... BindingPattern 1. Let A be ArrayCreate(0). [...] 3. Repeat [...] b. If iteratorRecord.[[done]] is true, then i. Return the result of performing BindingInitialization of BindingPattern with A and environment as the arguments. [...] ---*/ var values = [1, 2, 3]; var iterCount = 0; async function *fn() { for await (const [...[...x]] of [values]) { assert(Array.isArray(x)); assert.sameValue(x.length, 3); assert.sameValue(x[0], 1); assert.sameValue(x[1], 2); assert.sameValue(x[2], 3); assert.notSameValue(x, values); iterCount += 1; } } fn().next() .then(() => assert.sameValue(iterCount, 1, 'iteration occurred as expected'), $DONE) .then($DONE, $DONE);
sebastienros/jint
Jint.Tests.Test262/test/language/statements/for-await-of/async-gen-dstr-const-ary-ptrn-rest-ary-rest.js
JavaScript
bsd-2-clause
2,180
/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @extends {WebInspector.Widget} * @param {!Array.<!WebInspector.DataGrid.ColumnDescriptor>} columnsArray * @param {function(!WebInspector.DataGridNode, string, string, string)=} editCallback * @param {function(!WebInspector.DataGridNode)=} deleteCallback * @param {function()=} refreshCallback * @param {function(!WebInspector.ContextMenu, !WebInspector.DataGridNode)=} contextMenuCallback */ WebInspector.DataGrid = function(columnsArray, editCallback, deleteCallback, refreshCallback, contextMenuCallback) { WebInspector.Widget.call(this); this.registerRequiredCSS("ui_lazy/dataGrid.css"); this.element.className = "data-grid"; // Override this.element.tabIndex = 0; this.element.addEventListener("keydown", this._keyDown.bind(this), false); var headerContainer = createElementWithClass("div", "header-container"); /** @type {!Element} */ this._headerTable = headerContainer.createChild("table", "header"); /** @type {!Object.<string, !Element>} */ this._headerTableHeaders = {}; /** @type {!Element} */ this._scrollContainer = createElementWithClass("div", "data-container"); /** @type {!Element} */ this._dataTable = this._scrollContainer.createChild("table", "data"); this._dataTable.addEventListener("mousedown", this._mouseDownInDataTable.bind(this)); this._dataTable.addEventListener("click", this._clickInDataTable.bind(this), true); this._dataTable.addEventListener("contextmenu", this._contextMenuInDataTable.bind(this), true); // FIXME: Add a createCallback which is different from editCallback and has different // behavior when creating a new node. if (editCallback) this._dataTable.addEventListener("dblclick", this._ondblclick.bind(this), false); /** @type {function(!WebInspector.DataGridNode, string, string, string)|undefined} */ this._editCallback = editCallback; /** @type {function(!WebInspector.DataGridNode)|undefined} */ this._deleteCallback = deleteCallback; /** @type {function()|undefined} */ this._refreshCallback = refreshCallback; /** @type {function(!WebInspector.ContextMenu, !WebInspector.DataGridNode)|undefined} */ this._contextMenuCallback = contextMenuCallback; this.element.appendChild(headerContainer); this.element.appendChild(this._scrollContainer); /** @type {!Element} */ this._headerRow = createElement("tr"); /** @type {!Element} */ this._headerTableColumnGroup = createElement("colgroup"); /** @type {!Element} */ this._dataTableColumnGroup = createElement("colgroup"); /** @type {!Element} */ this._topFillerRow = createElementWithClass("tr", "revealed"); /** @type {!Element} */ this._bottomFillerRow = createElementWithClass("tr", "revealed"); this.setVerticalPadding(0, 0); /** @type {!Array.<!WebInspector.DataGrid.ColumnDescriptor>} */ this._columnsArray = columnsArray; /** @type {!Array.<!WebInspector.DataGrid.ColumnDescriptor>} */ this._visibleColumnsArray = columnsArray; /** @type {!Object.<string, !WebInspector.DataGrid.ColumnDescriptor>} */ this._columns = {}; /** @type {?string} */ this._cellClass = null; for (var i = 0; i < columnsArray.length; ++i) { var column = columnsArray[i]; var columnIdentifier = column.identifier = column.id || i; this._columns[columnIdentifier] = column; if (column.disclosure) this.disclosureColumnIdentifier = columnIdentifier; var cell = createElement("th"); cell.className = columnIdentifier + "-column"; cell.columnIdentifier = columnIdentifier; this._headerTableHeaders[columnIdentifier] = cell; var div = createElement("div"); if (column.titleDOMFragment) div.appendChild(column.titleDOMFragment); else div.textContent = column.title; cell.appendChild(div); if (column.sort) { cell.classList.add(column.sort); this._sortColumnCell = cell; } if (column.sortable) { cell.addEventListener("click", this._clickInHeaderCell.bind(this), false); cell.classList.add("sortable"); cell.createChild("div", "sort-order-icon-container").createChild("div", "sort-order-icon"); } } this._headerTable.appendChild(this._headerTableColumnGroup); this.headerTableBody.appendChild(this._headerRow); this._dataTable.appendChild(this._dataTableColumnGroup); this.dataTableBody.appendChild(this._topFillerRow); this.dataTableBody.appendChild(this._bottomFillerRow); this._refreshHeader(); /** @type {boolean} */ this._editing = false; /** @type {?WebInspector.DataGridNode} */ this.selectedNode = null; /** @type {boolean} */ this.expandNodesWhenArrowing = false; this.setRootNode(new WebInspector.DataGridNode()); /** @type {number} */ this.indentWidth = 15; /** @type {!Array.<!Element|{__index: number, __position: number}>} */ this._resizers = []; /** @type {boolean} */ this._columnWidthsInitialized = false; /** @type {number} */ this._cornerWidth = WebInspector.DataGrid.CornerWidth; /** @type {!WebInspector.DataGrid.ResizeMethod} */ this._resizeMethod = WebInspector.DataGrid.ResizeMethod.Nearest; } // Keep in sync with .data-grid col.corner style rule. WebInspector.DataGrid.CornerWidth = 14; /** @typedef {!{id: ?string, editable: boolean, longText: ?boolean, sort: !WebInspector.DataGrid.Order, sortable: boolean, align: !WebInspector.DataGrid.Align}} */ WebInspector.DataGrid.ColumnDescriptor; WebInspector.DataGrid.Events = { SelectedNode: "SelectedNode", DeselectedNode: "DeselectedNode", SortingChanged: "SortingChanged", ColumnsResized: "ColumnsResized" } /** @enum {string} */ WebInspector.DataGrid.Order = { Ascending: "sort-ascending", Descending: "sort-descending" } /** @enum {string} */ WebInspector.DataGrid.Align = { Center: "center", Right: "right" } WebInspector.DataGrid.prototype = { /** * @param {string} cellClass */ setCellClass: function(cellClass) { this._cellClass = cellClass; }, _refreshHeader: function() { this._headerTableColumnGroup.removeChildren(); this._dataTableColumnGroup.removeChildren(); this._headerRow.removeChildren(); this._topFillerRow.removeChildren(); this._bottomFillerRow.removeChildren(); for (var i = 0; i < this._visibleColumnsArray.length; ++i) { var column = this._visibleColumnsArray[i]; var columnIdentifier = column.identifier; var headerColumn = this._headerTableColumnGroup.createChild("col"); var dataColumn = this._dataTableColumnGroup.createChild("col"); if (column.width) { headerColumn.style.width = column.width; dataColumn.style.width = column.width; } this._headerRow.appendChild(this._headerTableHeaders[columnIdentifier]); this._topFillerRow.createChild("td", "top-filler-td"); this._bottomFillerRow.createChild("td", "bottom-filler-td").columnIdentifier_ = columnIdentifier; } this._headerRow.createChild("th", "corner"); this._topFillerRow.createChild("td", "corner").classList.add("top-filler-td"); this._bottomFillerRow.createChild("td", "corner").classList.add("bottom-filler-td"); this._headerTableColumnGroup.createChild("col", "corner"); this._dataTableColumnGroup.createChild("col", "corner"); }, /** * @param {number} top * @param {number} bottom * @protected */ setVerticalPadding: function(top, bottom) { this._topFillerRow.style.height = top + "px"; if (top || bottom) this._bottomFillerRow.style.height = bottom + "px"; else this._bottomFillerRow.style.height = "auto"; }, /** * @param {!WebInspector.DataGridNode} rootNode * @protected */ setRootNode: function(rootNode) { if (this._rootNode) { this._rootNode.removeChildren(); this._rootNode.dataGrid = null; this._rootNode._isRoot = false; } /** @type {!WebInspector.DataGridNode} */ this._rootNode = rootNode; rootNode._isRoot = true; rootNode.hasChildren = false; rootNode._expanded = true; rootNode._revealed = true; rootNode.dataGrid = this; }, /** * @return {!WebInspector.DataGridNode} */ rootNode: function() { return this._rootNode; }, _ondblclick: function(event) { if (this._editing || this._editingNode) return; var columnIdentifier = this.columnIdentifierFromNode(event.target); if (!columnIdentifier || !this._columns[columnIdentifier].editable) return; this._startEditing(event.target); }, /** * @param {!WebInspector.DataGridNode} node * @param {number} cellIndex */ _startEditingColumnOfDataGridNode: function(node, cellIndex) { this._editing = true; /** @type {?WebInspector.DataGridNode} */ this._editingNode = node; this._editingNode.select(); var element = this._editingNode._element.children[cellIndex]; WebInspector.InplaceEditor.startEditing(element, this._startEditingConfig(element)); element.getComponentSelection().setBaseAndExtent(element, 0, element, 1); }, _startEditing: function(target) { var element = target.enclosingNodeOrSelfWithNodeName("td"); if (!element) return; this._editingNode = this.dataGridNodeFromNode(target); if (!this._editingNode) { if (!this.creationNode) return; this._editingNode = this.creationNode; } // Force editing the 1st column when editing the creation node if (this._editingNode.isCreationNode) return this._startEditingColumnOfDataGridNode(this._editingNode, this._nextEditableColumn(-1)); this._editing = true; WebInspector.InplaceEditor.startEditing(element, this._startEditingConfig(element)); element.getComponentSelection().setBaseAndExtent(element, 0, element, 1); }, renderInline: function() { this.element.classList.add("inline"); this._cornerWidth = 0; this.updateWidths(); }, _startEditingConfig: function(element) { return new WebInspector.InplaceEditor.Config(this._editingCommitted.bind(this), this._editingCancelled.bind(this), element.textContent); }, _editingCommitted: function(element, newText, oldText, context, moveDirection) { var columnIdentifier = this.columnIdentifierFromNode(element); if (!columnIdentifier) { this._editingCancelled(element); return; } var column = this._columns[columnIdentifier]; var cellIndex = this._visibleColumnsArray.indexOf(column); var textBeforeEditing = this._editingNode.data[columnIdentifier]; var currentEditingNode = this._editingNode; /** * @param {boolean} wasChange * @this {WebInspector.DataGrid} */ function moveToNextIfNeeded(wasChange) { if (!moveDirection) return; if (moveDirection === "forward") { var firstEditableColumn = this._nextEditableColumn(-1); if (currentEditingNode.isCreationNode && cellIndex === firstEditableColumn && !wasChange) return; var nextEditableColumn = this._nextEditableColumn(cellIndex); if (nextEditableColumn !== -1) return this._startEditingColumnOfDataGridNode(currentEditingNode, nextEditableColumn); var nextDataGridNode = currentEditingNode.traverseNextNode(true, null, true); if (nextDataGridNode) return this._startEditingColumnOfDataGridNode(nextDataGridNode, firstEditableColumn); if (currentEditingNode.isCreationNode && wasChange) { this.addCreationNode(false); return this._startEditingColumnOfDataGridNode(this.creationNode, firstEditableColumn); } return; } if (moveDirection === "backward") { var prevEditableColumn = this._nextEditableColumn(cellIndex, true); if (prevEditableColumn !== -1) return this._startEditingColumnOfDataGridNode(currentEditingNode, prevEditableColumn); var lastEditableColumn = this._nextEditableColumn(this._visibleColumnsArray.length, true); var nextDataGridNode = currentEditingNode.traversePreviousNode(true, true); if (nextDataGridNode) return this._startEditingColumnOfDataGridNode(nextDataGridNode, lastEditableColumn); return; } } if (textBeforeEditing == newText) { this._editingCancelled(element); moveToNextIfNeeded.call(this, false); return; } // Update the text in the datagrid that we typed this._editingNode.data[columnIdentifier] = newText; // Make the callback - expects an editing node (table row), the column number that is being edited, // the text that used to be there, and the new text. this._editCallback(this._editingNode, columnIdentifier, textBeforeEditing, newText); if (this._editingNode.isCreationNode) this.addCreationNode(false); this._editingCancelled(element); moveToNextIfNeeded.call(this, true); }, _editingCancelled: function(element) { this._editing = false; this._editingNode = null; }, /** * @param {number} cellIndex * @param {boolean=} moveBackward * @return {number} */ _nextEditableColumn: function(cellIndex, moveBackward) { var increment = moveBackward ? -1 : 1; var columns = this._visibleColumnsArray; for (var i = cellIndex + increment; (i >= 0) && (i < columns.length); i += increment) { if (columns[i].editable) return i; } return -1; }, /** * @return {?string} */ sortColumnIdentifier: function() { if (!this._sortColumnCell) return null; return this._sortColumnCell.columnIdentifier; }, /** * @return {?string} */ sortOrder: function() { if (!this._sortColumnCell || this._sortColumnCell.classList.contains(WebInspector.DataGrid.Order.Ascending)) return WebInspector.DataGrid.Order.Ascending; if (this._sortColumnCell.classList.contains(WebInspector.DataGrid.Order.Descending)) return WebInspector.DataGrid.Order.Descending; return null; }, /** * @return {boolean} */ isSortOrderAscending: function() { return !this._sortColumnCell || this._sortColumnCell.classList.contains(WebInspector.DataGrid.Order.Ascending); }, get headerTableBody() { if ("_headerTableBody" in this) return this._headerTableBody; this._headerTableBody = this._headerTable.getElementsByTagName("tbody")[0]; if (!this._headerTableBody) { this._headerTableBody = this.element.ownerDocument.createElement("tbody"); this._headerTable.insertBefore(this._headerTableBody, this._headerTable.tFoot); } return this._headerTableBody; }, get dataTableBody() { if ("_dataTableBody" in this) return this._dataTableBody; this._dataTableBody = this._dataTable.getElementsByTagName("tbody")[0]; if (!this._dataTableBody) { this._dataTableBody = this.element.ownerDocument.createElement("tbody"); this._dataTable.insertBefore(this._dataTableBody, this._dataTable.tFoot); } return this._dataTableBody; }, /** * @param {!Array.<number>} widths * @param {number} minPercent * @param {number=} maxPercent * @return {!Array.<number>} */ _autoSizeWidths: function(widths, minPercent, maxPercent) { if (minPercent) minPercent = Math.min(minPercent, Math.floor(100 / widths.length)); var totalWidth = 0; for (var i = 0; i < widths.length; ++i) totalWidth += widths[i]; var totalPercentWidth = 0; for (var i = 0; i < widths.length; ++i) { var width = Math.round(100 * widths[i] / totalWidth); if (minPercent && width < minPercent) width = minPercent; else if (maxPercent && width > maxPercent) width = maxPercent; totalPercentWidth += width; widths[i] = width; } var recoupPercent = totalPercentWidth - 100; while (minPercent && recoupPercent > 0) { for (var i = 0; i < widths.length; ++i) { if (widths[i] > minPercent) { --widths[i]; --recoupPercent; if (!recoupPercent) break; } } } while (maxPercent && recoupPercent < 0) { for (var i = 0; i < widths.length; ++i) { if (widths[i] < maxPercent) { ++widths[i]; ++recoupPercent; if (!recoupPercent) break; } } } return widths; }, /** * @param {number} minPercent * @param {number=} maxPercent * @param {number=} maxDescentLevel */ autoSizeColumns: function(minPercent, maxPercent, maxDescentLevel) { var widths = []; for (var i = 0; i < this._columnsArray.length; ++i) widths.push((this._columnsArray[i].title || "").length); maxDescentLevel = maxDescentLevel || 0; var children = this._enumerateChildren(this._rootNode, [], maxDescentLevel + 1); for (var i = 0; i < children.length; ++i) { var node = children[i]; for (var j = 0; j < this._columnsArray.length; ++j) { var text = node.data[this._columnsArray[j].identifier] || ""; if (text.length > widths[j]) widths[j] = text.length; } } widths = this._autoSizeWidths(widths, minPercent, maxPercent); for (var i = 0; i < this._columnsArray.length; ++i) this._columnsArray[i].weight = widths[i]; this._columnWidthsInitialized = false; this.updateWidths(); }, _enumerateChildren: function(rootNode, result, maxLevel) { if (!rootNode._isRoot) result.push(rootNode); if (!maxLevel) return; for (var i = 0; i < rootNode.children.length; ++i) this._enumerateChildren(rootNode.children[i], result, maxLevel - 1); return result; }, onResize: function() { this.updateWidths(); }, // Updates the widths of the table, including the positions of the column // resizers. // // IMPORTANT: This function MUST be called once after the element of the // DataGrid is attached to its parent element and every subsequent time the // width of the parent element is changed in order to make it possible to // resize the columns. // // If this function is not called after the DataGrid is attached to its // parent element, then the DataGrid's columns will not be resizable. updateWidths: function() { var headerTableColumns = this._headerTableColumnGroup.children; // Use container size to avoid changes of table width caused by change of column widths. var tableWidth = this.element.offsetWidth - this._cornerWidth; var numColumns = headerTableColumns.length - 1; // Do not process corner column. // Do not attempt to use offsetes if we're not attached to the document tree yet. if (!this._columnWidthsInitialized && this.element.offsetWidth) { // Give all the columns initial widths now so that during a resize, // when the two columns that get resized get a percent value for // their widths, all the other columns already have percent values // for their widths. for (var i = 0; i < numColumns; i++) { var columnWidth = this.headerTableBody.rows[0].cells[i].offsetWidth; var column = this._visibleColumnsArray[i]; if (!column.weight) column.weight = 100 * columnWidth / tableWidth; } this._columnWidthsInitialized = true; } this._applyColumnWeights(); }, /** * @param {string} name */ setName: function(name) { this._columnWeightsSetting = WebInspector.settings.createSetting("dataGrid-" + name + "-columnWeights", {}); this._loadColumnWeights(); }, _loadColumnWeights: function() { if (!this._columnWeightsSetting) return; var weights = this._columnWeightsSetting.get(); for (var i = 0; i < this._columnsArray.length; ++i) { var column = this._columnsArray[i]; var weight = weights[column.identifier]; if (weight) column.weight = weight; } this._applyColumnWeights(); }, _saveColumnWeights: function() { if (!this._columnWeightsSetting) return; var weights = {}; for (var i = 0; i < this._columnsArray.length; ++i) { var column = this._columnsArray[i]; weights[column.identifier] = column.weight; } this._columnWeightsSetting.set(weights); }, wasShown: function() { this._loadColumnWeights(); }, _applyColumnWeights: function() { var tableWidth = this.element.offsetWidth - this._cornerWidth; if (tableWidth <= 0) return; var sumOfWeights = 0.0; for (var i = 0; i < this._visibleColumnsArray.length; ++i) sumOfWeights += this._visibleColumnsArray[i].weight; var sum = 0; var lastOffset = 0; for (var i = 0; i < this._visibleColumnsArray.length; ++i) { sum += this._visibleColumnsArray[i].weight; var offset = (sum * tableWidth / sumOfWeights) | 0; var width = (offset - lastOffset) + "px"; this._headerTableColumnGroup.children[i].style.width = width; this._dataTableColumnGroup.children[i].style.width = width; lastOffset = offset; } this._positionResizers(); this.dispatchEventToListeners(WebInspector.DataGrid.Events.ColumnsResized); }, /** * @param {!Object.<string, boolean>} columnsVisibility */ setColumnsVisiblity: function(columnsVisibility) { this._visibleColumnsArray = []; for (var i = 0; i < this._columnsArray.length; ++i) { var column = this._columnsArray[i]; if (columnsVisibility[column.identifier]) this._visibleColumnsArray.push(column); } this._refreshHeader(); this._applyColumnWeights(); var nodes = this._enumerateChildren(this.rootNode(), [], -1); for (var i = 0; i < nodes.length; ++i) nodes[i].refresh(); }, get scrollContainer() { return this._scrollContainer; }, _positionResizers: function() { var headerTableColumns = this._headerTableColumnGroup.children; var numColumns = headerTableColumns.length - 1; // Do not process corner column. var left = []; var resizers = this._resizers; while (resizers.length > numColumns - 1) resizers.pop().remove(); for (var i = 0; i < numColumns - 1; i++) { // Get the width of the cell in the first (and only) row of the // header table in order to determine the width of the column, since // it is not possible to query a column for its width. left[i] = (left[i-1] || 0) + this.headerTableBody.rows[0].cells[i].offsetWidth; } // Make n - 1 resizers for n columns. for (var i = 0; i < numColumns - 1; i++) { var resizer = resizers[i]; if (!resizer) { // This is the first call to updateWidth, so the resizers need // to be created. resizer = createElement("div"); resizer.__index = i; resizer.classList.add("data-grid-resizer"); // This resizer is associated with the column to its right. WebInspector.installDragHandle(resizer, this._startResizerDragging.bind(this), this._resizerDragging.bind(this), this._endResizerDragging.bind(this), "col-resize"); this.element.appendChild(resizer); resizers.push(resizer); } if (resizer.__position !== left[i]) { resizer.__position = left[i]; resizer.style.left = left[i] + "px"; } } }, addCreationNode: function(hasChildren) { if (this.creationNode) this.creationNode.makeNormal(); var emptyData = {}; for (var column in this._columns) emptyData[column] = null; this.creationNode = new WebInspector.CreationDataGridNode(emptyData, hasChildren); this.rootNode().appendChild(this.creationNode); }, _keyDown: function(event) { if (!this.selectedNode || event.shiftKey || event.metaKey || event.ctrlKey || this._editing) return; var handled = false; var nextSelectedNode; if (event.keyIdentifier === "Up" && !event.altKey) { nextSelectedNode = this.selectedNode.traversePreviousNode(true); while (nextSelectedNode && !nextSelectedNode.selectable) nextSelectedNode = nextSelectedNode.traversePreviousNode(true); handled = nextSelectedNode ? true : false; } else if (event.keyIdentifier === "Down" && !event.altKey) { nextSelectedNode = this.selectedNode.traverseNextNode(true); while (nextSelectedNode && !nextSelectedNode.selectable) nextSelectedNode = nextSelectedNode.traverseNextNode(true); handled = nextSelectedNode ? true : false; } else if (event.keyIdentifier === "Left") { if (this.selectedNode.expanded) { if (event.altKey) this.selectedNode.collapseRecursively(); else this.selectedNode.collapse(); handled = true; } else if (this.selectedNode.parent && !this.selectedNode.parent._isRoot) { handled = true; if (this.selectedNode.parent.selectable) { nextSelectedNode = this.selectedNode.parent; handled = nextSelectedNode ? true : false; } else if (this.selectedNode.parent) this.selectedNode.parent.collapse(); } } else if (event.keyIdentifier === "Right") { if (!this.selectedNode.revealed) { this.selectedNode.reveal(); handled = true; } else if (this.selectedNode.hasChildren) { handled = true; if (this.selectedNode.expanded) { nextSelectedNode = this.selectedNode.children[0]; handled = nextSelectedNode ? true : false; } else { if (event.altKey) this.selectedNode.expandRecursively(); else this.selectedNode.expand(); } } } else if (event.keyCode === 8 || event.keyCode === 46) { if (this._deleteCallback) { handled = true; this._deleteCallback(this.selectedNode); this.changeNodeAfterDeletion(); } } else if (isEnterKey(event)) { if (this._editCallback) { handled = true; this._startEditing(this.selectedNode._element.children[this._nextEditableColumn(-1)]); } } if (nextSelectedNode) { nextSelectedNode.reveal(); nextSelectedNode.select(); } if (handled) event.consume(true); }, changeNodeAfterDeletion: function() { var nextSelectedNode = this.selectedNode.traverseNextNode(true); while (nextSelectedNode && !nextSelectedNode.selectable) nextSelectedNode = nextSelectedNode.traverseNextNode(true); if (!nextSelectedNode || nextSelectedNode.isCreationNode) { nextSelectedNode = this.selectedNode.traversePreviousNode(true); while (nextSelectedNode && !nextSelectedNode.selectable) nextSelectedNode = nextSelectedNode.traversePreviousNode(true); } if (nextSelectedNode) { nextSelectedNode.reveal(); nextSelectedNode.select(); } }, /** * @param {!Node} target * @return {?WebInspector.DataGridNode} */ dataGridNodeFromNode: function(target) { var rowElement = target.enclosingNodeOrSelfWithNodeName("tr"); return rowElement && rowElement._dataGridNode; }, /** * @param {!Node} target * @return {?string} */ columnIdentifierFromNode: function(target) { var cellElement = target.enclosingNodeOrSelfWithNodeName("td"); return cellElement && cellElement.columnIdentifier_; }, _clickInHeaderCell: function(event) { var cell = event.target.enclosingNodeOrSelfWithNodeName("th"); if (!cell || (cell.columnIdentifier === undefined) || !cell.classList.contains("sortable")) return; var sortOrder = WebInspector.DataGrid.Order.Ascending; if ((cell === this._sortColumnCell) && this.isSortOrderAscending()) sortOrder = WebInspector.DataGrid.Order.Descending; if (this._sortColumnCell) this._sortColumnCell.classList.remove(WebInspector.DataGrid.Order.Ascending, WebInspector.DataGrid.Order.Descending); this._sortColumnCell = cell; cell.classList.add(sortOrder); this.dispatchEventToListeners(WebInspector.DataGrid.Events.SortingChanged); }, /** * @param {string} columnIdentifier * @param {!WebInspector.DataGrid.Order} sortOrder */ markColumnAsSortedBy: function(columnIdentifier, sortOrder) { if (this._sortColumnCell) this._sortColumnCell.classList.remove(WebInspector.DataGrid.Order.Ascending, WebInspector.DataGrid.Order.Descending); this._sortColumnCell = this._headerTableHeaders[columnIdentifier]; this._sortColumnCell.classList.add(sortOrder); }, /** * @param {string} columnIdentifier * @return {!Element} */ headerTableHeader: function(columnIdentifier) { return this._headerTableHeaders[columnIdentifier]; }, _mouseDownInDataTable: function(event) { var gridNode = this.dataGridNodeFromNode(event.target); if (!gridNode || !gridNode.selectable) return; if (gridNode.isEventWithinDisclosureTriangle(event)) return; if (event.metaKey) { if (gridNode.selected) gridNode.deselect(); else gridNode.select(); } else gridNode.select(); }, _contextMenuInDataTable: function(event) { var contextMenu = new WebInspector.ContextMenu(event); var gridNode = this.dataGridNodeFromNode(event.target); if (this._refreshCallback && (!gridNode || gridNode !== this.creationNode)) contextMenu.appendItem(WebInspector.UIString("Refresh"), this._refreshCallback.bind(this)); if (gridNode && gridNode.selectable && !gridNode.isEventWithinDisclosureTriangle(event)) { if (this._editCallback) { if (gridNode === this.creationNode) contextMenu.appendItem(WebInspector.UIString.capitalize("Add ^new"), this._startEditing.bind(this, event.target)); else { var columnIdentifier = this.columnIdentifierFromNode(event.target); if (columnIdentifier && this._columns[columnIdentifier].editable) contextMenu.appendItem(WebInspector.UIString("Edit \"%s\"", this._columns[columnIdentifier].title), this._startEditing.bind(this, event.target)); } } if (this._deleteCallback && gridNode !== this.creationNode) contextMenu.appendItem(WebInspector.UIString.capitalize("Delete"), this._deleteCallback.bind(this, gridNode)); if (this._contextMenuCallback) this._contextMenuCallback(contextMenu, gridNode); } contextMenu.show(); }, _clickInDataTable: function(event) { var gridNode = this.dataGridNodeFromNode(event.target); if (!gridNode || !gridNode.hasChildren) return; if (!gridNode.isEventWithinDisclosureTriangle(event)) return; if (gridNode.expanded) { if (event.altKey) gridNode.collapseRecursively(); else gridNode.collapse(); } else { if (event.altKey) gridNode.expandRecursively(); else gridNode.expand(); } }, /** * @param {!WebInspector.DataGrid.ResizeMethod} method */ setResizeMethod: function(method) { this._resizeMethod = method; }, /** * @return {boolean} */ _startResizerDragging: function(event) { this._currentResizer = event.target; return true; }, _resizerDragging: function(event) { var resizer = this._currentResizer; if (!resizer) return; // Constrain the dragpoint to be within the containing div of the // datagrid. var dragPoint = event.clientX - this.element.totalOffsetLeft(); var firstRowCells = this.headerTableBody.rows[0].cells; var leftEdgeOfPreviousColumn = 0; // Constrain the dragpoint to be within the space made up by the // column directly to the left and the column directly to the right. var leftCellIndex = resizer.__index; var rightCellIndex = leftCellIndex + 1; for (var i = 0; i < leftCellIndex; i++) leftEdgeOfPreviousColumn += firstRowCells[i].offsetWidth; // Differences for other resize methods if (this._resizeMethod === WebInspector.DataGrid.ResizeMethod.Last) { rightCellIndex = this._resizers.length; } else if (this._resizeMethod === WebInspector.DataGrid.ResizeMethod.First) { leftEdgeOfPreviousColumn += firstRowCells[leftCellIndex].offsetWidth - firstRowCells[0].offsetWidth; leftCellIndex = 0; } var rightEdgeOfNextColumn = leftEdgeOfPreviousColumn + firstRowCells[leftCellIndex].offsetWidth + firstRowCells[rightCellIndex].offsetWidth; // Give each column some padding so that they don't disappear. var leftMinimum = leftEdgeOfPreviousColumn + this.ColumnResizePadding; var rightMaximum = rightEdgeOfNextColumn - this.ColumnResizePadding; if (leftMinimum > rightMaximum) return; dragPoint = Number.constrain(dragPoint, leftMinimum, rightMaximum); var position = (dragPoint - this.CenterResizerOverBorderAdjustment); resizer.__position = position; resizer.style.left = position + "px"; var pxLeftColumn = (dragPoint - leftEdgeOfPreviousColumn) + "px"; this._headerTableColumnGroup.children[leftCellIndex].style.width = pxLeftColumn; this._dataTableColumnGroup.children[leftCellIndex].style.width = pxLeftColumn; var pxRightColumn = (rightEdgeOfNextColumn - dragPoint) + "px"; this._headerTableColumnGroup.children[rightCellIndex].style.width = pxRightColumn; this._dataTableColumnGroup.children[rightCellIndex].style.width = pxRightColumn; var leftColumn = this._visibleColumnsArray[leftCellIndex]; var rightColumn = this._visibleColumnsArray[rightCellIndex]; if (leftColumn.weight || rightColumn.weight) { var sumOfWeights = leftColumn.weight + rightColumn.weight; var delta = rightEdgeOfNextColumn - leftEdgeOfPreviousColumn; leftColumn.weight = (dragPoint - leftEdgeOfPreviousColumn) * sumOfWeights / delta; rightColumn.weight = (rightEdgeOfNextColumn - dragPoint) * sumOfWeights / delta; } this._positionResizers(); event.preventDefault(); this.dispatchEventToListeners(WebInspector.DataGrid.Events.ColumnsResized); }, /** * @param {string} columnId * @return {number} */ columnOffset: function(columnId) { if (!this.element.offsetWidth) return 0; for (var i = 1; i < this._visibleColumnsArray.length; ++i) { if (columnId === this._visibleColumnsArray[i].identifier) { if (this._resizers[i - 1]) return this._resizers[i - 1].__position; } } return 0; }, _endResizerDragging: function(event) { this._currentResizer = null; this._saveColumnWeights(); this.dispatchEventToListeners(WebInspector.DataGrid.Events.ColumnsResized); }, ColumnResizePadding: 24, CenterResizerOverBorderAdjustment: 3, __proto__: WebInspector.Widget.prototype } /** @enum {string} */ WebInspector.DataGrid.ResizeMethod = { Nearest: "nearest", First: "first", Last: "last" } /** * @constructor * @extends {WebInspector.Object} * @param {?Object.<string, *>=} data * @param {boolean=} hasChildren */ WebInspector.DataGridNode = function(data, hasChildren) { /** @type {?Element} */ this._element = null; /** @type {boolean} */ this._expanded = false; /** @type {boolean} */ this._selected = false; /** @type {number|undefined} */ this._depth; /** @type {boolean|undefined} */ this._revealed; /** @type {boolean} */ this._attached = false; /** @type {?{parent: !WebInspector.DataGridNode, index: number}} */ this._savedPosition = null; /** @type {boolean} */ this._shouldRefreshChildren = true; /** @type {!Object.<string, *>} */ this._data = data || {}; /** @type {boolean} */ this.hasChildren = hasChildren || false; /** @type {!Array.<!WebInspector.DataGridNode>} */ this.children = []; /** @type {?WebInspector.DataGrid} */ this.dataGrid = null; /** @type {?WebInspector.DataGridNode} */ this.parent = null; /** @type {?WebInspector.DataGridNode} */ this.previousSibling = null; /** @type {?WebInspector.DataGridNode} */ this.nextSibling = null; /** @type {number} */ this.disclosureToggleWidth = 10; } WebInspector.DataGridNode.prototype = { /** @type {boolean} */ selectable: true, /** @type {boolean} */ _isRoot: false, /** * @return {!Element} */ element: function() { if (!this._element) { this.createElement(); this.createCells(); } return /** @type {!Element} */ (this._element); }, /** * @protected */ createElement: function() { this._element = createElement("tr"); this._element._dataGridNode = this; if (this.hasChildren) this._element.classList.add("parent"); if (this.expanded) this._element.classList.add("expanded"); if (this.selected) this._element.classList.add("selected"); if (this.revealed) this._element.classList.add("revealed"); }, /** * @protected */ createCells: function() { this._element.removeChildren(); var columnsArray = this.dataGrid._visibleColumnsArray; for (var i = 0; i < columnsArray.length; ++i) this._element.appendChild(this.createCell(columnsArray[i].identifier)); this._element.appendChild(this._createTDWithClass("corner")); }, get data() { return this._data; }, set data(x) { this._data = x || {}; this.refresh(); }, get revealed() { if (this._revealed !== undefined) return this._revealed; var currentAncestor = this.parent; while (currentAncestor && !currentAncestor._isRoot) { if (!currentAncestor.expanded) { this._revealed = false; return false; } currentAncestor = currentAncestor.parent; } this._revealed = true; return true; }, set hasChildren(x) { if (this._hasChildren === x) return; this._hasChildren = x; if (!this._element) return; this._element.classList.toggle("parent", this._hasChildren); this._element.classList.toggle("expanded", this._hasChildren && this.expanded); }, get hasChildren() { return this._hasChildren; }, set revealed(x) { if (this._revealed === x) return; this._revealed = x; if (this._element) this._element.classList.toggle("revealed", this._revealed); for (var i = 0; i < this.children.length; ++i) this.children[i].revealed = x && this.expanded; }, /** * @return {number} */ get depth() { if (this._depth !== undefined) return this._depth; if (this.parent && !this.parent._isRoot) this._depth = this.parent.depth + 1; else this._depth = 0; return this._depth; }, get leftPadding() { return this.depth * this.dataGrid.indentWidth; }, get shouldRefreshChildren() { return this._shouldRefreshChildren; }, set shouldRefreshChildren(x) { this._shouldRefreshChildren = x; if (x && this.expanded) this.expand(); }, get selected() { return this._selected; }, set selected(x) { if (x) this.select(); else this.deselect(); }, get expanded() { return this._expanded; }, /** * @param {boolean} x */ set expanded(x) { if (x) this.expand(); else this.collapse(); }, refresh: function() { if (!this.dataGrid) this._element = null; if (!this._element) return; this.createCells(); }, /** * @param {string} className * @return {!Element} */ _createTDWithClass: function(className) { var cell = createElementWithClass("td", className); var cellClass = this.dataGrid._cellClass; if (cellClass) cell.classList.add(cellClass); return cell; }, /** * @param {string} columnIdentifier * @return {!Element} */ createTD: function(columnIdentifier) { var cell = this._createTDWithClass(columnIdentifier + "-column"); cell.columnIdentifier_ = columnIdentifier; var alignment = this.dataGrid._columns[columnIdentifier].align; if (alignment) cell.classList.add(alignment); if (columnIdentifier === this.dataGrid.disclosureColumnIdentifier) { cell.classList.add("disclosure"); if (this.leftPadding) cell.style.setProperty("padding-left", this.leftPadding + "px"); } return cell; }, /** * @param {string} columnIdentifier * @return {!Element} */ createCell: function(columnIdentifier) { var cell = this.createTD(columnIdentifier); var data = this.data[columnIdentifier]; if (data instanceof Node) { cell.appendChild(data); } else { cell.textContent = data; if (this.dataGrid._columns[columnIdentifier].longText) cell.title = data; } return cell; }, /** * @return {number} */ nodeSelfHeight: function() { return 16; }, /** * @param {!WebInspector.DataGridNode} child */ appendChild: function(child) { this.insertChild(child, this.children.length); }, /** * @param {!WebInspector.DataGridNode} child * @param {number} index */ insertChild: function(child, index) { if (!child) throw("insertChild: Node can't be undefined or null."); if (child.parent === this) throw("insertChild: Node is already a child of this node."); child.remove(); this.children.splice(index, 0, child); this.hasChildren = true; child.parent = this; child.dataGrid = this.dataGrid; child.recalculateSiblings(index); child._depth = undefined; child._revealed = undefined; child._attached = false; child._shouldRefreshChildren = true; var current = child.children[0]; while (current) { current.dataGrid = this.dataGrid; current._depth = undefined; current._revealed = undefined; current._attached = false; current._shouldRefreshChildren = true; current = current.traverseNextNode(false, child, true); } if (this.expanded) child._attach(); if (!this.revealed) child.revealed = false; }, remove: function() { if (this.parent) this.parent.removeChild(this); }, /** * @param {!WebInspector.DataGridNode} child */ removeChild: function(child) { if (!child) throw("removeChild: Node can't be undefined or null."); if (child.parent !== this) throw("removeChild: Node is not a child of this node."); child.deselect(); child._detach(); this.children.remove(child, true); if (child.previousSibling) child.previousSibling.nextSibling = child.nextSibling; if (child.nextSibling) child.nextSibling.previousSibling = child.previousSibling; child.dataGrid = null; child.parent = null; child.nextSibling = null; child.previousSibling = null; if (this.children.length <= 0) this.hasChildren = false; }, removeChildren: function() { for (var i = 0; i < this.children.length; ++i) { var child = this.children[i]; child.deselect(); child._detach(); child.dataGrid = null; child.parent = null; child.nextSibling = null; child.previousSibling = null; } this.children = []; this.hasChildren = false; }, /** * @param {number} myIndex */ recalculateSiblings: function(myIndex) { if (!this.parent) return; var previousChild = this.parent.children[myIndex - 1] || null; if (previousChild) previousChild.nextSibling = this; this.previousSibling = previousChild; var nextChild = this.parent.children[myIndex + 1] || null; if (nextChild) nextChild.previousSibling = this; this.nextSibling = nextChild; }, collapse: function() { if (this._isRoot) return; if (this._element) this._element.classList.remove("expanded"); this._expanded = false; for (var i = 0; i < this.children.length; ++i) this.children[i].revealed = false; }, collapseRecursively: function() { var item = this; while (item) { if (item.expanded) item.collapse(); item = item.traverseNextNode(false, this, true); } }, populate: function() { }, expand: function() { if (!this.hasChildren || this.expanded) return; if (this._isRoot) return; if (this.revealed && !this._shouldRefreshChildren) for (var i = 0; i < this.children.length; ++i) this.children[i].revealed = true; if (this._shouldRefreshChildren) { for (var i = 0; i < this.children.length; ++i) this.children[i]._detach(); this.populate(); if (this._attached) { for (var i = 0; i < this.children.length; ++i) { var child = this.children[i]; if (this.revealed) child.revealed = true; child._attach(); } } this._shouldRefreshChildren = false; } if (this._element) this._element.classList.add("expanded"); this._expanded = true; }, expandRecursively: function() { var item = this; while (item) { item.expand(); item = item.traverseNextNode(false, this); } }, reveal: function() { if (this._isRoot) return; var currentAncestor = this.parent; while (currentAncestor && !currentAncestor._isRoot) { if (!currentAncestor.expanded) currentAncestor.expand(); currentAncestor = currentAncestor.parent; } this.element().scrollIntoViewIfNeeded(false); }, /** * @param {boolean=} supressSelectedEvent */ select: function(supressSelectedEvent) { if (!this.dataGrid || !this.selectable || this.selected) return; if (this.dataGrid.selectedNode) this.dataGrid.selectedNode.deselect(); this._selected = true; this.dataGrid.selectedNode = this; if (this._element) this._element.classList.add("selected"); if (!supressSelectedEvent) this.dataGrid.dispatchEventToListeners(WebInspector.DataGrid.Events.SelectedNode); }, revealAndSelect: function() { if (this._isRoot) return; this.reveal(); this.select(); }, /** * @param {boolean=} supressDeselectedEvent */ deselect: function(supressDeselectedEvent) { if (!this.dataGrid || this.dataGrid.selectedNode !== this || !this.selected) return; this._selected = false; this.dataGrid.selectedNode = null; if (this._element) this._element.classList.remove("selected"); if (!supressDeselectedEvent) this.dataGrid.dispatchEventToListeners(WebInspector.DataGrid.Events.DeselectedNode); }, /** * @param {boolean} skipHidden * @param {?WebInspector.DataGridNode=} stayWithin * @param {boolean=} dontPopulate * @param {!Object=} info * @return {?WebInspector.DataGridNode} */ traverseNextNode: function(skipHidden, stayWithin, dontPopulate, info) { if (!dontPopulate && this.hasChildren) this.populate(); if (info) info.depthChange = 0; var node = (!skipHidden || this.revealed) ? this.children[0] : null; if (node && (!skipHidden || this.expanded)) { if (info) info.depthChange = 1; return node; } if (this === stayWithin) return null; node = (!skipHidden || this.revealed) ? this.nextSibling : null; if (node) return node; node = this; while (node && !node._isRoot && !((!skipHidden || node.revealed) ? node.nextSibling : null) && node.parent !== stayWithin) { if (info) info.depthChange -= 1; node = node.parent; } if (!node) return null; return (!skipHidden || node.revealed) ? node.nextSibling : null; }, /** * @param {boolean} skipHidden * @param {boolean=} dontPopulate * @return {?WebInspector.DataGridNode} */ traversePreviousNode: function(skipHidden, dontPopulate) { var node = (!skipHidden || this.revealed) ? this.previousSibling : null; if (!dontPopulate && node && node.hasChildren) node.populate(); while (node && ((!skipHidden || (node.revealed && node.expanded)) ? node.children[node.children.length - 1] : null)) { if (!dontPopulate && node.hasChildren) node.populate(); node = ((!skipHidden || (node.revealed && node.expanded)) ? node.children[node.children.length - 1] : null); } if (node) return node; if (!this.parent || this.parent._isRoot) return null; return this.parent; }, /** * @return {boolean} */ isEventWithinDisclosureTriangle: function(event) { if (!this.hasChildren) return false; var cell = event.target.enclosingNodeOrSelfWithNodeName("td"); if (!cell || !cell.classList.contains("disclosure")) return false; var left = cell.totalOffsetLeft() + this.leftPadding; return event.pageX >= left && event.pageX <= left + this.disclosureToggleWidth; }, _attach: function() { if (!this.dataGrid || this._attached) return; this._attached = true; var previousNode = this.traversePreviousNode(true, true); var previousElement = previousNode ? previousNode.element() : this.dataGrid._topFillerRow; this.dataGrid.dataTableBody.insertBefore(this.element(), previousElement.nextSibling); if (this.expanded) for (var i = 0; i < this.children.length; ++i) this.children[i]._attach(); }, _detach: function() { if (!this._attached) return; this._attached = false; if (this._element) this._element.remove(); for (var i = 0; i < this.children.length; ++i) this.children[i]._detach(); this.wasDetached(); }, wasDetached: function() { }, savePosition: function() { if (this._savedPosition) return; if (!this.parent) throw("savePosition: Node must have a parent."); this._savedPosition = { parent: this.parent, index: this.parent.children.indexOf(this) }; }, restorePosition: function() { if (!this._savedPosition) return; if (this.parent !== this._savedPosition.parent) this._savedPosition.parent.insertChild(this, this._savedPosition.index); this._savedPosition = null; }, __proto__: WebInspector.Object.prototype } /** * @constructor * @extends {WebInspector.DataGridNode} */ WebInspector.CreationDataGridNode = function(data, hasChildren) { WebInspector.DataGridNode.call(this, data, hasChildren); /** @type {boolean} */ this.isCreationNode = true; } WebInspector.CreationDataGridNode.prototype = { makeNormal: function() { this.isCreationNode = false; }, __proto__: WebInspector.DataGridNode.prototype }
guorendong/iridium-browser-ubuntu
third_party/WebKit/Source/devtools/front_end/ui_lazy/DataGrid.js
JavaScript
bsd-3-clause
57,639
module.exports = { test: { options: { port: 8000, keepalive: true, hostname: 'localhost', livereload: 35728, open: 'http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/test.html' } }, dev: { options: { port: 9000, livereload: 35729, hostname: 'localhost', open: 'http://<%= connect.dev.options.hostname %>:<%= connect.dev.options.port %>/preview/' } }, };
TBAPI-0KA/vizabi
grunt/config/connect.js
JavaScript
bsd-3-clause
536
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; var CSSCore = require('CSSCore'); var React; var ReactDOM; var ReactCSSTransitionGroup; // Most of the real functionality is covered in other unit tests, this just // makes sure we're wired up correctly. describe('ReactCSSTransitionGroup', function() { var container; beforeEach(function() { require('mock-modules').dumpCache(); React = require('React'); ReactDOM = require('ReactDOM'); ReactCSSTransitionGroup = require('ReactCSSTransitionGroup'); container = document.createElement('div'); spyOn(console, 'error'); }); it('should warn if timeouts aren\'t specified', function() { ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo" transitionEnter={false} transitionLeave={true} > <span key="one" id="one" /> </ReactCSSTransitionGroup>, container ); // Warning about the missing transitionLeaveTimeout prop expect(console.error.argsForCall.length).toBe(1); }); it('should not warn if timeouts is zero', function() { ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo" transitionEnter={false} transitionLeave={true} transitionLeaveTimeout={0} > <span key="one" id="one" /> </ReactCSSTransitionGroup>, container ); expect(console.error.argsForCall.length).toBe(0); }); it('should clean-up silently after the timeout elapses', function() { var a = ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo" transitionEnter={false} transitionLeaveTimeout={200} > <span key="one" id="one" /> </ReactCSSTransitionGroup>, container ); expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1); setTimeout.mock.calls.length = 0; ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo" transitionEnter={false} transitionLeaveTimeout={200} > <span key="two" id="two" /> </ReactCSSTransitionGroup>, container ); expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2); expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('two'); expect(ReactDOM.findDOMNode(a).childNodes[1].id).toBe('one'); // For some reason jst is adding extra setTimeout()s and grunt test isn't, // so we need to do this disgusting hack. for (var i = 0; i < setTimeout.mock.calls.length; i++) { if (setTimeout.mock.calls[i][1] === 200) { setTimeout.mock.calls[i][0](); break; } } // No warnings expect(console.error.argsForCall.length).toBe(0); // The leaving child has been removed expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1); expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('two'); }); it('should keep both sets of DOM nodes around', function() { var a = ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo"> <span key="one" id="one" /> </ReactCSSTransitionGroup>, container ); expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1); ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo"> <span key="two" id="two" /> </ReactCSSTransitionGroup>, container ); expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2); expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('two'); expect(ReactDOM.findDOMNode(a).childNodes[1].id).toBe('one'); }); it('should switch transitionLeave from false to true', function() { var a = ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo" transitionEnter={false} transitionLeave={false}> <span key="one" id="one" /> </ReactCSSTransitionGroup>, container ); expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1); ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo" transitionEnter={false} transitionLeave={false}> <span key="two" id="two" /> </ReactCSSTransitionGroup>, container ); expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1); ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo" transitionEnter={false} transitionLeave={true}> <span key="three" id="three" /> </ReactCSSTransitionGroup>, container ); expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2); expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('three'); expect(ReactDOM.findDOMNode(a).childNodes[1].id).toBe('two'); }); it('should work with no children', function() { ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo" />, container ); }); it('should work with a null child', function() { ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo"> {[null]} </ReactCSSTransitionGroup>, container ); }); it('should transition from one to null', function() { var a = ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo"> <span key="one" id="one" /> </ReactCSSTransitionGroup>, container ); expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1); ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo"> {null} </ReactCSSTransitionGroup>, container ); // (Here, we expect the original child to stick around but test that no // exception is thrown) expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1); expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('one'); }); it('should transition from false to one', function() { var a = ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo"> {false} </ReactCSSTransitionGroup>, container ); expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(0); ReactDOM.render( <ReactCSSTransitionGroup transitionName="yolo"> <span key="one" id="one" /> </ReactCSSTransitionGroup>, container ); expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1); expect(ReactDOM.findDOMNode(a).childNodes[0].id).toBe('one'); }); it('should use transition-type specific names when they\'re provided', function() { var customTransitionNames = { enter: 'custom-entering', leave: 'custom-leaving', }; var a = ReactDOM.render( <ReactCSSTransitionGroup transitionName={customTransitionNames} transitionEnterTimeout={1} transitionLeaveTimeout={1} > <span key="one" id="one" /> </ReactCSSTransitionGroup>, container ); expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(1); // Add an element ReactDOM.render( <ReactCSSTransitionGroup transitionName={customTransitionNames} transitionEnterTimeout={1} transitionLeaveTimeout={1} > <span key="one" id="one" /> <span key="two" id="two" /> </ReactCSSTransitionGroup>, container ); expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2); var enteringNode = ReactDOM.findDOMNode(a).childNodes[1]; expect(CSSCore.hasClass(enteringNode, 'custom-entering')).toBe(true); // Remove an element ReactDOM.render( <ReactCSSTransitionGroup transitionName={customTransitionNames} transitionEnterTimeout={1} transitionLeaveTimeout={1} > <span key="two" id="two" /> </ReactCSSTransitionGroup>, container ); expect(ReactDOM.findDOMNode(a).childNodes.length).toBe(2); var leavingNode = ReactDOM.findDOMNode(a).childNodes[0]; expect(CSSCore.hasClass(leavingNode, 'custom-leaving')).toBe(true); }); });
camsong/react
src/addons/transitions/__tests__/ReactCSSTransitionGroup-test.js
JavaScript
bsd-3-clause
8,182
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticWheelEvent */ 'use strict'; var SyntheticMouseEvent = require('SyntheticMouseEvent'); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function(event) { return ( 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0 ); }, deltaY: function(event) { return ( 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0 ); }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null, }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent;
zeke/react
src/renderers/dom/client/syntheticEvents/SyntheticWheelEvent.js
JavaScript
bsd-3-clause
2,006
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const SelectTypeExamples = () => ( <ExampleSection title='Usage'> <ComponentExample title='Select' description='Default Select.' examplePath='addons/Select/Types/SelectExample' /> </ExampleSection> ) export default SelectTypeExamples
aabustamante/Semantic-UI-React
docs/app/Examples/addons/Select/Types/index.js
JavaScript
mit
450
(function () { 'use strict'; /** * @ngdoc overview * @name ui.grid.edit * @description * * # ui.grid.edit * * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div> * * This module provides cell editing capability to ui.grid. The goal was to emulate keying data in a spreadsheet via * a keyboard. * <br/> * <br/> * To really get the full spreadsheet-like data entry, the ui.grid.cellNav module should be used. This will allow the * user to key data and then tab, arrow, or enter to the cells beside or below. * * <div doc-module-components="ui.grid.edit"></div> */ var module = angular.module('ui.grid.edit', ['ui.grid']); /** * @ngdoc object * @name ui.grid.edit.constant:uiGridEditConstants * * @description constants available in edit module */ module.constant('uiGridEditConstants', { EDITABLE_CELL_TEMPLATE: /EDITABLE_CELL_TEMPLATE/g, //must be lowercase because template bulder converts to lower EDITABLE_CELL_DIRECTIVE: /editable_cell_directive/g, events: { BEGIN_CELL_EDIT: 'uiGridEventBeginCellEdit', END_CELL_EDIT: 'uiGridEventEndCellEdit', CANCEL_CELL_EDIT: 'uiGridEventCancelCellEdit' } }); /** * @ngdoc service * @name ui.grid.edit.service:uiGridEditService * * @description Services for editing features */ module.service('uiGridEditService', ['$q', 'uiGridConstants', 'gridUtil', function ($q, uiGridConstants, gridUtil) { var service = { initializeGrid: function (grid) { service.defaultGridOptions(grid.options); grid.registerColumnBuilder(service.editColumnBuilder); grid.edit = {}; /** * @ngdoc object * @name ui.grid.edit.api:PublicApi * * @description Public Api for edit feature */ var publicApi = { events: { edit: { /** * @ngdoc event * @name afterCellEdit * @eventOf ui.grid.edit.api:PublicApi * @description raised when cell editing is complete * <pre> * gridApi.edit.on.afterCellEdit(scope,function(rowEntity, colDef){}) * </pre> * @param {object} rowEntity the options.data element that was edited * @param {object} colDef the column that was edited * @param {object} newValue new value * @param {object} oldValue old value */ afterCellEdit: function (rowEntity, colDef, newValue, oldValue) { }, /** * @ngdoc event * @name beginCellEdit * @eventOf ui.grid.edit.api:PublicApi * @description raised when cell editing starts on a cell * <pre> * gridApi.edit.on.beginCellEdit(scope,function(rowEntity, colDef){}) * </pre> * @param {object} rowEntity the options.data element that was edited * @param {object} colDef the column that was edited * @param {object} triggerEvent the event that triggered the edit. Useful to prevent losing keystrokes on some * complex editors */ beginCellEdit: function (rowEntity, colDef, triggerEvent) { }, /** * @ngdoc event * @name cancelCellEdit * @eventOf ui.grid.edit.api:PublicApi * @description raised when cell editing is cancelled on a cell * <pre> * gridApi.edit.on.cancelCellEdit(scope,function(rowEntity, colDef){}) * </pre> * @param {object} rowEntity the options.data element that was edited * @param {object} colDef the column that was edited */ cancelCellEdit: function (rowEntity, colDef) { } } }, methods: { edit: { } } }; grid.api.registerEventsFromObject(publicApi.events); //grid.api.registerMethodsFromObject(publicApi.methods); }, defaultGridOptions: function (gridOptions) { /** * @ngdoc object * @name ui.grid.edit.api:GridOptions * * @description Options for configuring the edit feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc object * @name enableCellEdit * @propertyOf ui.grid.edit.api:GridOptions * @description If defined, sets the default value for the editable flag on each individual colDefs * if their individual enableCellEdit configuration is not defined. Defaults to undefined. */ /** * @ngdoc object * @name cellEditableCondition * @propertyOf ui.grid.edit.api:GridOptions * @description If specified, either a value or function to be used by all columns before editing. * If falsy, then editing of cell is not allowed. * @example * <pre> * function($scope){ * //use $scope.row.entity and $scope.col.colDef to determine if editing is allowed * return true; * } * </pre> */ gridOptions.cellEditableCondition = gridOptions.cellEditableCondition === undefined ? true : gridOptions.cellEditableCondition; /** * @ngdoc object * @name editableCellTemplate * @propertyOf ui.grid.edit.api:GridOptions * @description If specified, cellTemplate to use as the editor for all columns. * <br/> defaults to 'ui-grid/cellTextEditor' */ /** * @ngdoc object * @name enableCellEditOnFocus * @propertyOf ui.grid.edit.api:GridOptions * @description If true, then editor is invoked as soon as cell receives focus. Default false. * <br/>_requires cellNav feature and the edit feature to be enabled_ */ //enableCellEditOnFocus can only be used if cellnav module is used gridOptions.enableCellEditOnFocus = gridOptions.enableCellEditOnFocus === undefined ? false : gridOptions.enableCellEditOnFocus; }, /** * @ngdoc service * @name editColumnBuilder * @methodOf ui.grid.edit.service:uiGridEditService * @description columnBuilder function that adds edit properties to grid column * @returns {promise} promise that will load any needed templates when resolved */ editColumnBuilder: function (colDef, col, gridOptions) { var promises = []; /** * @ngdoc object * @name ui.grid.edit.api:ColumnDef * * @description Column Definition for edit feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs} */ /** * @ngdoc object * @name enableCellEdit * @propertyOf ui.grid.edit.api:ColumnDef * @description enable editing on column */ colDef.enableCellEdit = colDef.enableCellEdit === undefined ? (gridOptions.enableCellEdit === undefined ? (colDef.type !== 'object') : gridOptions.enableCellEdit) : colDef.enableCellEdit; /** * @ngdoc object * @name cellEditableCondition * @propertyOf ui.grid.edit.api:ColumnDef * @description If specified, either a value or function evaluated before editing cell. If falsy, then editing of cell is not allowed. * @example * <pre> * function($scope){ * //use $scope.row.entity and $scope.col.colDef to determine if editing is allowed * return true; * } * </pre> */ colDef.cellEditableCondition = colDef.cellEditableCondition === undefined ? gridOptions.cellEditableCondition : colDef.cellEditableCondition; /** * @ngdoc object * @name editableCellTemplate * @propertyOf ui.grid.edit.api:ColumnDef * @description cell template to be used when editing this column. Can be Url or text template * <br/>Defaults to gridOptions.editableCellTemplate */ if (colDef.enableCellEdit) { colDef.editableCellTemplate = colDef.editableCellTemplate || gridOptions.editableCellTemplate || 'ui-grid/cellEditor'; promises.push(gridUtil.getTemplate(colDef.editableCellTemplate) .then( function (template) { col.editableCellTemplate = template; }, function (res) { // Todo handle response error here? throw new Error("Couldn't fetch/use colDef.editableCellTemplate '" + colDef.editableCellTemplate + "'"); })); } /** * @ngdoc object * @name enableCellEditOnFocus * @propertyOf ui.grid.edit.api:ColumnDef * @requires ui.grid.cellNav * @description If true, then editor is invoked as soon as cell receives focus. Default false. * <br>_requires both the cellNav feature and the edit feature to be enabled_ */ //enableCellEditOnFocus can only be used if cellnav module is used colDef.enableCellEditOnFocus = colDef.enableCellEditOnFocus === undefined ? gridOptions.enableCellEditOnFocus : colDef.enableCellEditOnFocus; /** * @ngdoc string * @name editModelField * @propertyOf ui.grid.edit.api:ColumnDef * @description a bindable string value that is used when binding to edit controls instead of colDef.field * <br/> example: You have a complex property on and object like state:{abbrev:'MS',name:'Mississippi'}. The * grid should display state.name in the cell and sort/filter based on the state.name property but the editor * requires the full state object. * <br/>colDef.field = 'state.name' * <br/>colDef.editModelField = 'state' */ //colDef.editModelField return $q.all(promises); }, /** * @ngdoc service * @name isStartEditKey * @methodOf ui.grid.edit.service:uiGridEditService * @description Determines if a keypress should start editing. Decorate this service to override with your * own key events. See service decorator in angular docs. * @param {Event} evt keydown event * @returns {boolean} true if an edit should start */ isStartEditKey: function (evt) { if (evt.metaKey || evt.keyCode === uiGridConstants.keymap.ESC || evt.keyCode === uiGridConstants.keymap.SHIFT || evt.keyCode === uiGridConstants.keymap.CTRL || evt.keyCode === uiGridConstants.keymap.ALT || evt.keyCode === uiGridConstants.keymap.WIN || evt.keyCode === uiGridConstants.keymap.CAPSLOCK || evt.keyCode === uiGridConstants.keymap.LEFT || (evt.keyCode === uiGridConstants.keymap.TAB && evt.shiftKey) || evt.keyCode === uiGridConstants.keymap.RIGHT || evt.keyCode === uiGridConstants.keymap.TAB || evt.keyCode === uiGridConstants.keymap.UP || (evt.keyCode === uiGridConstants.keymap.ENTER && evt.shiftKey) || evt.keyCode === uiGridConstants.keymap.DOWN || evt.keyCode === uiGridConstants.keymap.ENTER) { return false; } return true; } }; return service; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridEdit * @element div * @restrict A * * @description Adds editing features to the ui-grid directive. * * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.edit']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Bob', title: 'CEO' }, { name: 'Frank', title: 'Lowly Developer' } ]; $scope.columnDefs = [ {name: 'name', enableCellEdit: true}, {name: 'title', enableCellEdit: true} ]; }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-edit></div> </div> </file> </example> */ module.directive('uiGridEdit', ['gridUtil', 'uiGridEditService', function (gridUtil, uiGridEditService) { return { replace: true, priority: 0, require: '^uiGrid', scope: false, compile: function () { return { pre: function ($scope, $elm, $attrs, uiGridCtrl) { uiGridEditService.initializeGrid(uiGridCtrl.grid); }, post: function ($scope, $elm, $attrs, uiGridCtrl) { } }; } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridRenderContainer * @element div * @restrict A * * @description Adds keydown listeners to renderContainer element so we can capture when to begin edits * */ module.directive('uiGridViewport', [ 'uiGridEditConstants', function ( uiGridEditConstants) { return { replace: true, priority: -99998, //run before cellNav require: ['^uiGrid', '^uiGridRenderContainer'], scope: false, compile: function () { return { post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; // Skip attaching if edit and cellNav is not enabled if (!uiGridCtrl.grid.api.edit || !uiGridCtrl.grid.api.cellNav) { return; } var containerId = controllers[1].containerId; //no need to process for other containers if (containerId !== 'body') { return; } //refocus on the grid $scope.$on(uiGridEditConstants.events.CANCEL_CELL_EDIT, function () { uiGridCtrl.focus(); }); $scope.$on(uiGridEditConstants.events.END_CELL_EDIT, function () { uiGridCtrl.focus(); }); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridCell * @element div * @restrict A * * @description Stacks on top of ui.grid.uiGridCell to provide in-line editing capabilities to the cell * Editing Actions. * * Binds edit start events to the uiGridCell element. When the events fire, the gridCell element is appended * with the columnDef.editableCellTemplate element ('cellEditor.html' by default). * * The editableCellTemplate should respond to uiGridEditConstants.events.BEGIN\_CELL\_EDIT angular event * and do the initial steps needed to edit the cell (setfocus on input element, etc). * * When the editableCellTemplate recognizes that the editing is ended (blur event, Enter key, etc.) * it should emit the uiGridEditConstants.events.END\_CELL\_EDIT event. * * If editableCellTemplate recognizes that the editing has been cancelled (esc key) * it should emit the uiGridEditConstants.events.CANCEL\_CELL\_EDIT event. The original value * will be set back on the model by the uiGridCell directive. * * Events that invoke editing: * - dblclick * - F2 keydown (when using cell selection) * * Events that end editing: * - Dependent on the specific editableCellTemplate * - Standards should be blur and enter keydown * * Events that cancel editing: * - Dependent on the specific editableCellTemplate * - Standards should be Esc keydown * * Grid Events that end editing: * - uiGridConstants.events.GRID_SCROLL * */ /** * @ngdoc object * @name ui.grid.edit.api:GridRow * * @description GridRow options for edit feature, these are available to be * set internally only, by other features */ /** * @ngdoc object * @name enableCellEdit * @propertyOf ui.grid.edit.api:GridRow * @description enable editing on row, grouping for example might disable editing on group header rows */ module.directive('uiGridCell', ['$compile', '$injector', '$timeout', 'uiGridConstants', 'uiGridEditConstants', 'gridUtil', '$parse', 'uiGridEditService', '$rootScope', function ($compile, $injector, $timeout, uiGridConstants, uiGridEditConstants, gridUtil, $parse, uiGridEditService, $rootScope) { var touchstartTimeout = 500; if ($injector.has('uiGridCellNavService')) { var uiGridCellNavService = $injector.get('uiGridCellNavService'); } return { priority: -100, // run after default uiGridCell directive restrict: 'A', scope: false, require: '?^uiGrid', link: function ($scope, $elm, $attrs, uiGridCtrl) { var html; var origCellValue; var inEdit = false; var cellModel; var cancelTouchstartTimeout; var editCellScope; if (!$scope.col.colDef.enableCellEdit) { return; } var cellNavNavigateDereg = function() {}; var viewPortKeyDownDereg = function() {}; var setEditable = function() { if ($scope.col.colDef.enableCellEdit && $scope.row.enableCellEdit !== false) { if (!$scope.beginEditEventsWired) { //prevent multiple attachments registerBeginEditEvents(); } } else { if ($scope.beginEditEventsWired) { cancelBeginEditEvents(); } } }; setEditable(); var rowWatchDereg = $scope.$watch('row', function (n, o) { if (n !== o) { setEditable(); } }); $scope.$on( '$destroy', rowWatchDereg ); function registerBeginEditEvents() { $elm.on('dblclick', beginEdit); // Add touchstart handling. If the users starts a touch and it doesn't end after X milliseconds, then start the edit $elm.on('touchstart', touchStart); if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { viewPortKeyDownDereg = uiGridCtrl.grid.api.cellNav.on.viewPortKeyDown($scope, function (evt, rowCol) { if (rowCol === null) { return; } if (rowCol.row === $scope.row && rowCol.col === $scope.col && !$scope.col.colDef.enableCellEditOnFocus) { //important to do this before scrollToIfNecessary beginEditKeyDown(evt); } }); cellNavNavigateDereg = uiGridCtrl.grid.api.cellNav.on.navigate($scope, function (newRowCol, oldRowCol) { if ($scope.col.colDef.enableCellEditOnFocus) { // Don't begin edit if the cell hasn't changed if ((!oldRowCol || newRowCol.row !== oldRowCol.row || newRowCol.col !== oldRowCol.col) && newRowCol.row === $scope.row && newRowCol.col === $scope.col) { $timeout(function () { beginEdit(); }); } } }); } $scope.beginEditEventsWired = true; } function touchStart(event) { // jQuery masks events if (typeof(event.originalEvent) !== 'undefined' && event.originalEvent !== undefined) { event = event.originalEvent; } // Bind touchend handler $elm.on('touchend', touchEnd); // Start a timeout cancelTouchstartTimeout = $timeout(function() { }, touchstartTimeout); // Timeout's done! Start the edit cancelTouchstartTimeout.then(function () { // Use setTimeout to start the edit because beginEdit expects to be outside of $digest setTimeout(beginEdit, 0); // Undbind the touchend handler, we don't need it anymore $elm.off('touchend', touchEnd); }); } // Cancel any touchstart timeout function touchEnd(event) { $timeout.cancel(cancelTouchstartTimeout); $elm.off('touchend', touchEnd); } function cancelBeginEditEvents() { $elm.off('dblclick', beginEdit); $elm.off('keydown', beginEditKeyDown); $elm.off('touchstart', touchStart); cellNavNavigateDereg(); viewPortKeyDownDereg(); $scope.beginEditEventsWired = false; } function beginEditKeyDown(evt) { if (uiGridEditService.isStartEditKey(evt)) { beginEdit(evt); } } function shouldEdit(col, row) { return !row.isSaving && ( angular.isFunction(col.colDef.cellEditableCondition) ? col.colDef.cellEditableCondition($scope) : col.colDef.cellEditableCondition ); } function beginEdit(triggerEvent) { //we need to scroll the cell into focus before invoking the editor $scope.grid.api.core.scrollToIfNecessary($scope.row, $scope.col) .then(function () { beginEditAfterScroll(triggerEvent); }); } /** * @ngdoc property * @name editDropdownOptionsArray * @propertyOf ui.grid.edit.api:ColumnDef * @description an array of values in the format * [ {id: xxx, value: xxx} ], which is populated * into the edit dropdown * */ /** * @ngdoc property * @name editDropdownIdLabel * @propertyOf ui.grid.edit.api:ColumnDef * @description the label for the "id" field * in the editDropdownOptionsArray. Defaults * to 'id' * @example * <pre> * $scope.gridOptions = { * columnDefs: [ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor', * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}], * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' } * ], * </pre> * */ /** * @ngdoc property * @name editDropdownRowEntityOptionsArrayPath * @propertyOf ui.grid.edit.api:ColumnDef * @description a path to a property on row.entity containing an * array of values in the format * [ {id: xxx, value: xxx} ], which will be used to populate * the edit dropdown. This can be used when the dropdown values are dependent on * the backing row entity. * If this property is set then editDropdownOptionsArray will be ignored. * @example * <pre> * $scope.gridOptions = { * columnDefs: [ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor', * editDropdownRowEntityOptionsArrayPath: 'foo.bars[0].baz', * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' } * ], * </pre> * */ /** * @ngdoc property * @name editDropdownValueLabel * @propertyOf ui.grid.edit.api:ColumnDef * @description the label for the "value" field * in the editDropdownOptionsArray. Defaults * to 'value' * @example * <pre> * $scope.gridOptions = { * columnDefs: [ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor', * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}], * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' } * ], * </pre> * */ /** * @ngdoc property * @name editDropdownFilter * @propertyOf ui.grid.edit.api:ColumnDef * @description A filter that you would like to apply to the values in the options list * of the dropdown. For example if you were using angular-translate you might set this * to `'translate'` * @example * <pre> * $scope.gridOptions = { * columnDefs: [ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor', * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}], * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status', editDropdownFilter: 'translate' } * ], * </pre> * */ function beginEditAfterScroll(triggerEvent) { // If we are already editing, then just skip this so we don't try editing twice... if (inEdit) { return; } if (!shouldEdit($scope.col, $scope.row)) { return; } cellModel = $parse($scope.row.getQualifiedColField($scope.col)); //get original value from the cell origCellValue = cellModel($scope); html = $scope.col.editableCellTemplate; if ($scope.col.colDef.editModelField) { html = html.replace(uiGridConstants.MODEL_COL_FIELD, gridUtil.preEval('row.entity.' + $scope.col.colDef.editModelField)); } else { html = html.replace(uiGridConstants.MODEL_COL_FIELD, $scope.row.getQualifiedColField($scope.col)); } html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)'); var optionFilter = $scope.col.colDef.editDropdownFilter ? '|' + $scope.col.colDef.editDropdownFilter : ''; html = html.replace(uiGridConstants.CUSTOM_FILTERS, optionFilter); var inputType = 'text'; switch ($scope.col.colDef.type){ case 'boolean': inputType = 'checkbox'; break; case 'number': inputType = 'number'; break; case 'date': inputType = 'date'; break; } html = html.replace('INPUT_TYPE', inputType); var editDropdownRowEntityOptionsArrayPath = $scope.col.colDef.editDropdownRowEntityOptionsArrayPath; if (editDropdownRowEntityOptionsArrayPath) { $scope.editDropdownOptionsArray = resolveObjectFromPath($scope.row.entity, editDropdownRowEntityOptionsArrayPath); } else { $scope.editDropdownOptionsArray = $scope.col.colDef.editDropdownOptionsArray; } $scope.editDropdownIdLabel = $scope.col.colDef.editDropdownIdLabel ? $scope.col.colDef.editDropdownIdLabel : 'id'; $scope.editDropdownValueLabel = $scope.col.colDef.editDropdownValueLabel ? $scope.col.colDef.editDropdownValueLabel : 'value'; var cellElement; var createEditor = function(){ inEdit = true; cancelBeginEditEvents(); var cellElement = angular.element(html); $elm.append(cellElement); editCellScope = $scope.$new(); $compile(cellElement)(editCellScope); var gridCellContentsEl = angular.element($elm.children()[0]); gridCellContentsEl.addClass('ui-grid-cell-contents-hidden'); }; if (!$rootScope.$$phase) { $scope.$apply(createEditor); } else { createEditor(); } //stop editing when grid is scrolled var deregOnGridScroll = $scope.col.grid.api.core.on.scrollBegin($scope, function () { if ($scope.grid.disableScrolling) { return; } endEdit(); $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue); deregOnGridScroll(); deregOnEndCellEdit(); deregOnCancelCellEdit(); }); //end editing var deregOnEndCellEdit = $scope.$on(uiGridEditConstants.events.END_CELL_EDIT, function () { endEdit(); $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue); deregOnEndCellEdit(); deregOnGridScroll(); deregOnCancelCellEdit(); }); //cancel editing var deregOnCancelCellEdit = $scope.$on(uiGridEditConstants.events.CANCEL_CELL_EDIT, function () { cancelEdit(); deregOnCancelCellEdit(); deregOnGridScroll(); deregOnEndCellEdit(); }); $scope.$broadcast(uiGridEditConstants.events.BEGIN_CELL_EDIT, triggerEvent); $timeout(function () { //execute in a timeout to give any complex editor templates a cycle to completely render $scope.grid.api.edit.raise.beginCellEdit($scope.row.entity, $scope.col.colDef, triggerEvent); }); } function endEdit() { $scope.grid.disableScrolling = false; if (!inEdit) { return; } //sometimes the events can't keep up with the keyboard and grid focus is lost, so always focus //back to grid here. The focus call needs to be before the $destroy and removal of the control, //otherwise ng-model-options of UpdateOn: 'blur' will not work. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { uiGridCtrl.focus(); } var gridCellContentsEl = angular.element($elm.children()[0]); //remove edit element editCellScope.$destroy(); angular.element($elm.children()[1]).remove(); gridCellContentsEl.removeClass('ui-grid-cell-contents-hidden'); inEdit = false; registerBeginEditEvents(); $scope.grid.api.core.notifyDataChange( uiGridConstants.dataChange.EDIT ); } function cancelEdit() { $scope.grid.disableScrolling = false; if (!inEdit) { return; } cellModel.assign($scope, origCellValue); $scope.$apply(); $scope.grid.api.edit.raise.cancelCellEdit($scope.row.entity, $scope.col.colDef); endEdit(); } // resolves a string path against the given object // shamelessly borrowed from // http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key function resolveObjectFromPath(object, path) { path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties path = path.replace(/^\./, ''); // strip a leading dot var a = path.split('.'); while (a.length) { var n = a.shift(); if (n in object) { object = object[n]; } else { return; } } return object; } } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridEditor * @element div * @restrict A * * @description input editor directive for editable fields. * Provides EndEdit and CancelEdit events * * Events that end editing: * blur and enter keydown * * Events that cancel editing: * - Esc keydown * */ module.directive('uiGridEditor', ['gridUtil', 'uiGridConstants', 'uiGridEditConstants','$timeout', 'uiGridEditService', function (gridUtil, uiGridConstants, uiGridEditConstants, $timeout, uiGridEditService) { return { scope: true, require: ['?^uiGrid', '?^uiGridRenderContainer', 'ngModel'], compile: function () { return { pre: function ($scope, $elm, $attrs) { }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl, renderContainerCtrl, ngModel; if (controllers[0]) { uiGridCtrl = controllers[0]; } if (controllers[1]) { renderContainerCtrl = controllers[1]; } if (controllers[2]) { ngModel = controllers[2]; } //set focus at start of edit $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function (evt,triggerEvent) { $timeout(function () { $elm[0].focus(); //only select text if it is not being replaced below in the cellNav viewPortKeyPress if ($scope.col.colDef.enableCellEditOnFocus || !(uiGridCtrl && uiGridCtrl.grid.api.cellNav)) { $elm[0].select(); } else { //some browsers (Chrome) stupidly, imo, support the w3 standard that number, email, ... //fields should not allow setSelectionRange. We ignore the error for those browsers //https://www.w3.org/Bugs/Public/show_bug.cgi?id=24796 try { $elm[0].setSelectionRange($elm[0].value.length, $elm[0].value.length); } catch (ex) { //ignore } } }); //set the keystroke that started the edit event //we must do this because the BeginEdit is done in a different event loop than the intitial //keydown event //fire this event for the keypress that is received if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { var viewPortKeyDownUnregister = uiGridCtrl.grid.api.cellNav.on.viewPortKeyPress($scope, function (evt, rowCol) { if (uiGridEditService.isStartEditKey(evt)) { ngModel.$setViewValue(String.fromCharCode(evt.keyCode), evt); ngModel.$render(); } viewPortKeyDownUnregister(); }); } $elm.on('blur', function (evt) { $scope.stopEdit(evt); }); }); $scope.deepEdit = false; $scope.stopEdit = function (evt) { if ($scope.inputForm && !$scope.inputForm.$valid) { evt.stopPropagation(); $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT); } else { $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT); } $scope.deepEdit = false; }; $elm.on('click', function (evt) { if ($elm[0].type !== 'checkbox') { $scope.deepEdit = true; $timeout(function () { $scope.grid.disableScrolling = true; }); } }); $elm.on('keydown', function (evt) { switch (evt.keyCode) { case uiGridConstants.keymap.ESC: evt.stopPropagation(); $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT); break; } if ($scope.deepEdit && (evt.keyCode === uiGridConstants.keymap.LEFT || evt.keyCode === uiGridConstants.keymap.RIGHT || evt.keyCode === uiGridConstants.keymap.UP || evt.keyCode === uiGridConstants.keymap.DOWN)) { evt.stopPropagation(); } // Pass the keydown event off to the cellNav service, if it exists else if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId; if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) { $scope.stopEdit(evt); } } else { //handle enter and tab for editing not using cellNav switch (evt.keyCode) { case uiGridConstants.keymap.ENTER: // Enter (Leave Field) case uiGridConstants.keymap.TAB: evt.stopPropagation(); evt.preventDefault(); $scope.stopEdit(evt); break; } } return true; }); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:input * @element input * @restrict E * * @description directive to provide binding between input[date] value and ng-model for angular 1.2 * It is similar to input[date] directive of angular 1.3 * * Supported date format for input is 'yyyy-MM-dd' * The directive will set the $valid property of input element and the enclosing form to false if * model is invalid date or value of input is entered wrong. * */ module.directive('uiGridEditor', ['$filter', function ($filter) { function parseDateString(dateString) { if (typeof(dateString) === 'undefined' || dateString === '') { return null; } var parts = dateString.split('-'); if (parts.length !== 3) { return null; } var year = parseInt(parts[0], 10); var month = parseInt(parts[1], 10); var day = parseInt(parts[2], 10); if (month < 1 || year < 1 || day < 1) { return null; } return new Date(year, (month - 1), day); } return { priority: -100, // run after default uiGridEditor directive require: '?ngModel', link: function (scope, element, attrs, ngModel) { if (angular.version.minor === 2 && attrs.type && attrs.type === 'date' && ngModel) { ngModel.$formatters.push(function (modelValue) { ngModel.$setValidity(null,(!modelValue || !isNaN(modelValue.getTime()))); return $filter('date')(modelValue, 'yyyy-MM-dd'); }); ngModel.$parsers.push(function (viewValue) { if (viewValue && viewValue.length > 0) { var dateValue = parseDateString(viewValue); ngModel.$setValidity(null, (dateValue && !isNaN(dateValue.getTime()))); return dateValue; } else { ngModel.$setValidity(null, true); return null; } }); } } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridEditDropdown * @element div * @restrict A * * @description dropdown editor for editable fields. * Provides EndEdit and CancelEdit events * * Events that end editing: * blur and enter keydown, and any left/right nav * * Events that cancel editing: * - Esc keydown * */ module.directive('uiGridEditDropdown', ['uiGridConstants', 'uiGridEditConstants', function (uiGridConstants, uiGridEditConstants) { return { require: ['?^uiGrid', '?^uiGridRenderContainer'], scope: true, compile: function () { return { pre: function ($scope, $elm, $attrs) { }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl = controllers[0]; var renderContainerCtrl = controllers[1]; //set focus at start of edit $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () { $elm[0].focus(); $elm[0].style.width = ($elm[0].parentElement.offsetWidth - 1) + 'px'; $elm.on('blur', function (evt) { $scope.stopEdit(evt); }); }); $scope.stopEdit = function (evt) { // no need to validate a dropdown - invalid values shouldn't be // available in the list $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT); }; $elm.on('keydown', function (evt) { switch (evt.keyCode) { case uiGridConstants.keymap.ESC: evt.stopPropagation(); $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT); break; } if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) { evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId; if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) { $scope.stopEdit(evt); } } else { //handle enter and tab for editing not using cellNav switch (evt.keyCode) { case uiGridConstants.keymap.ENTER: // Enter (Leave Field) case uiGridConstants.keymap.TAB: evt.stopPropagation(); evt.preventDefault(); $scope.stopEdit(evt); break; } } return true; }); } }; } }; }]); /** * @ngdoc directive * @name ui.grid.edit.directive:uiGridEditFileChooser * @element div * @restrict A * * @description input editor directive for editable fields. * Provides EndEdit and CancelEdit events * * Events that end editing: * blur and enter keydown * * Events that cancel editing: * - Esc keydown * */ module.directive('uiGridEditFileChooser', ['gridUtil', 'uiGridConstants', 'uiGridEditConstants','$timeout', function (gridUtil, uiGridConstants, uiGridEditConstants, $timeout) { return { scope: true, require: ['?^uiGrid', '?^uiGridRenderContainer'], compile: function () { return { pre: function ($scope, $elm, $attrs) { }, post: function ($scope, $elm, $attrs, controllers) { var uiGridCtrl, renderContainerCtrl; if (controllers[0]) { uiGridCtrl = controllers[0]; } if (controllers[1]) { renderContainerCtrl = controllers[1]; } var grid = uiGridCtrl.grid; var handleFileSelect = function( event ){ var target = event.srcElement || event.target; if (target && target.files && target.files.length > 0) { /** * @ngdoc property * @name editFileChooserCallback * @propertyOf ui.grid.edit.api:ColumnDef * @description A function that should be called when any files have been chosen * by the user. You should use this to process the files appropriately for your * application. * * It passes the gridCol, the gridRow (from which you can get gridRow.entity), * and the files. The files are in the format as returned from the file chooser, * an array of files, with each having useful information such as: * - `files[0].lastModifiedDate` * - `files[0].name` * - `files[0].size` (appears to be in bytes) * - `files[0].type` (MIME type by the looks) * * Typically you would do something with these files - most commonly you would * use the filename or read the file itself in. The example function does both. * * @example * <pre> * editFileChooserCallBack: function(gridRow, gridCol, files ){ * // ignore all but the first file, it can only choose one anyway * // set the filename into this column * gridRow.entity.filename = file[0].name; * * // read the file and set it into a hidden column, which we may do stuff with later * var setFile = function(fileContent){ * gridRow.entity.file = fileContent.currentTarget.result; * }; * var reader = new FileReader(); * reader.onload = setFile; * reader.readAsText( files[0] ); * } * </pre> */ if ( typeof($scope.col.colDef.editFileChooserCallback) === 'function' ) { $scope.col.colDef.editFileChooserCallback($scope.row, $scope.col, target.files); } else { gridUtil.logError('You need to set colDef.editFileChooserCallback to use the file chooser'); } target.form.reset(); $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT); } else { $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT); } }; $elm[0].addEventListener('change', handleFileSelect, false); // TODO: why the false on the end? Google $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () { $elm[0].focus(); $elm[0].select(); $elm.on('blur', function (evt) { $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT); }); }); } }; } }; }]); })();
Lincoln-xzc/angular-ui-grid
src/features/edit/js/gridEdit.js
JavaScript
mit
48,612
/////////////////////////////////////////////////////////////////////////// // Copyright © 2014 - 2016 Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/_base/array', 'dojo/_base/html', 'dojo/topic', 'dojo/Deferred', 'dojo/on', './utils', './WidgetManager', './shared/AppVersionManager', './ConfigLoader', './tokenUtils', './dijit/LoadingIndicator', 'esri/config', 'esri/tasks/GeometryService' ], function (declare, lang, array, html, topic, Deferred, on, jimuUtils, WidgetManager, AppVersionManager, ConfigLoader, tokenUtils, LoadingIndicator, esriConfig, GeometryService) { var instance = null, clazz; clazz = declare(null, { urlParams: null, appConfig: null, configFile: null, _configLoaded: false, portalSelf: null, constructor: function (urlParams) { this.urlParams = urlParams || {}; this.listenBuilderEvents(); this.versionManager = new AppVersionManager(); this.widgetManager = WidgetManager.getInstance(); this.configLoader = ConfigLoader.getInstance(this.urlParams, { versionManager: this.versionManager }); if(this.urlParams.mode === 'config' && window.parent.setConfigViewerTopic && lang.isFunction(window.parent.setConfigViewerTopic)){ window.parent.setConfigViewerTopic(topic); } if(this.urlParams.mode === 'preview' && window.parent.setPreviewViewerTopic && lang.isFunction(window.parent.setPreviewViewerTopic)){ window.parent.setPreviewViewerTopic(topic); } if (!jimuUtils.isMobileUa()) { //mobile devices do NOT listen to the 'resize' event //avoid to virtual-keyboard appears and then app switches between "Mobile Mode" and "Desktop Mode" on(window, 'resize', lang.hitch(this, this._onWindowResize)); } on(window, "orientationchange", lang.hitch(this, this._onOrientationChange)); }, listenBuilderEvents: function(){ //whatever(app, map, widget, widgetPoolChanged) config changed, publish this event. //*when app changed, the id is "app", the data is app's properties, like title, subtitle. //*when map changed, the id is "map", the data is itemId //*when widget that is in preloadwidget/widgetpool changed, the id is widget's id, // the data is widget's setting //*when anything in the widget pool changed, the id is "widgetPool", the data is // widgets and groups topic.subscribe('builder/widgetChanged', lang.hitch(this, this._onWidgetChanged)); topic.subscribe('builder/groupChanged', lang.hitch(this, this._onGroupChanged)); topic.subscribe('builder/widgetPoolChanged', lang.hitch(this, this._onWidgetPoolChanged)); topic.subscribe('builder/openAtStartChange', lang.hitch(this, this._onOpenAtStartChanged)); topic.subscribe('builder/mapChanged', lang.hitch(this, this._onMapChanged)); topic.subscribe('builder/mapOptionsChanged', lang.hitch(this, this._onMapOptionsChanged)); topic.subscribe('builder/appAttributeChanged', lang.hitch(this, this._onAppAttributeChanged)); //actionTriggered event is proccessed by layout manager. // topic.subscribe('builder/actionTriggered', lang.hitch(this, this._onConfigChanged)); topic.subscribe('builder/setAppConfig', lang.hitch(this, this._onAppConfigSet)); topic.subscribe('builder/themeChanged', lang.hitch(this, this._onThemeChanged)); topic.subscribe('builder/layoutChanged', lang.hitch(this, this._onLayoutChanged)); topic.subscribe('builder/styleChanged', lang.hitch(this, this._onStyleChanged)); topic.subscribe('builder/syncExtent', lang.hitch(this, this._onSyncExtent)); topic.subscribe('builder/loadingPageChanged', lang.hitch(this, this._onLoadingPageChanged)); topic.subscribe('builder/templateConfigChanged', lang.hitch(this, this._onTemplateConfigChanged)); topic.subscribe('builder/appProxyForMapChanged', lang.hitch(this, this._onAppProxyForMapChanged)); topic.subscribe('builder/appProxyForUrlChanged', lang.hitch(this, this._onAppProxyForUrlChanged)); }, loadConfig: function(){ if(this.urlParams.mode === 'preview' || this.urlParams.mode === 'config'){ //in preview/config mode, the config is set by the builder. return; } var loading = new LoadingIndicator(); loading.placeAt(window.jimuConfig.layoutId); return this.configLoader.loadConfig().then(lang.hitch(this, function(appConfig){ this.portalSelf = this.configLoader.portalSelf; this.appConfig = this._addDefaultValues(appConfig); window.appInfo.isRunInMobile = jimuUtils.inMobileSize(); console.timeEnd('Load Config'); var _ac = this.getAppConfig(); loading.destroy(); topic.publish("appConfigLoaded", _ac); return _ac; }), lang.hitch(this, function(err){ loading.destroy(); console.error(err); if(err && err.message && typeof err.message === 'string'){ this._showErrorMessage(err.message); } })); }, _showErrorMessage: function(msg){ html.create('div', { 'class': 'app-error', innerHTML: msg }, document.body); }, getAppConfig: function () { var c; if(window.appInfo.isRunInMobile){ // console.log('Switch to mobile mode.'); c = lang.clone(this._getMobileConfig(this.appConfig)); c._originConfig = lang.clone(this.appConfig); }else{ // console.log('Switch to desktop mode.'); c = lang.clone(this.appConfig); } c.getConfigElementById = function(id){ return jimuUtils.getConfigElementById(this, id); }; c.getConfigElementsByName = function(name){ return jimuUtils.getConfigElementsByName(this, name); }; c.getCleanConfig = function(isForAGOLTemplate){ if(this._originConfig){ return getCleanConfig(this._originConfig, isForAGOLTemplate); }else{ return getCleanConfig(this, isForAGOLTemplate); } }; c.visitElement = function(cb){ jimuUtils.visitElement(this, cb); }; return c; }, _onOrientationChange: function() { if (this.appConfig) { topic.publish("appConfigChanged", this.getAppConfig(), 'layoutChange'); } }, _onWindowResize: function () { var runInMobile = jimuUtils.inMobileSize(); if(window.appInfo.isRunInMobile === runInMobile){ return; } window.appInfo.isRunInMobile = runInMobile; if(this.appConfig){ topic.publish("appConfigChanged", this.getAppConfig(), 'layoutChange'); } }, _getMobileConfig: function(appConfig) { return jimuUtils.mixinAppConfigPosition(appConfig, appConfig.mobileLayout); }, _onWidgetChanged: function(_newJson){ // transfer obj to another iframe may cause problems on IE8 var newJson = jimuUtils.reCreateObject(_newJson); var oldJson = jimuUtils.getConfigElementById(this.appConfig, _newJson.id); //for placeholder, add off panel if(newJson.inPanel === false && !oldJson.uri){ newJson.closeable = true; } //for now, we can add/update property only for(var p in newJson){ oldJson[p] = newJson[p]; } delete oldJson.isDefaultConfig; this.configLoader.addNeedValues(this.appConfig); this._addDefaultValues(this.appConfig); topic.publish('appConfigChanged', this.getAppConfig(), 'widgetChange', newJson); }, _onGroupChanged: function(_newJson){ // transfer obj to another iframe may cause problems on IE8 var newJson = jimuUtils.reCreateObject(_newJson); var oldJson = jimuUtils.getConfigElementById(this.appConfig, _newJson.id); //for now, we can add/update property only for(var p in newJson){ oldJson[p] = newJson[p]; } this.configLoader.addNeedValues(this.appConfig); this._addDefaultValues(this.appConfig); topic.publish('appConfigChanged', this.getAppConfig(), 'groupChange', newJson); }, _onWidgetPoolChanged: function(_newJson){ // transfer obj to another iframe may cause problems on IE8 var newJson = jimuUtils.reCreateObject(_newJson); var controllerWidgets = this.widgetManager.getControllerWidgets(); if(controllerWidgets.length === 1){ this.appConfig.widgetPool.widgets = newJson.widgets; this.appConfig.widgetPool.groups = newJson.groups; }else{ var controllerJson = jimuUtils.getConfigElementById(this.appConfig, newJson.controllerId); //remove old jsons from pool array.forEach(controllerJson.controlledWidgets, function(widgetId){ this._removeWidgetOrGroupFromPoolById(this.appConfig, widgetId); }, this); array.forEach(controllerJson.controlledGroups, function(groupId){ this._removeWidgetOrGroupFromPoolById(this.appConfig, groupId); }, this); //add new jsons into pool if(typeof this.appConfig.widgetPool.widgets === 'undefined'){ this.appConfig.widgetPool.widgets = newJson.widgets; }else{ this.appConfig.widgetPool.widgets = this.appConfig.widgetPool.widgets.concat(newJson.widgets); } if(typeof this.appConfig.widgetPool.groups === 'undefined'){ this.appConfig.widgetPool.groups = newJson.groups; }else{ this.appConfig.widgetPool.groups = this.appConfig.widgetPool.groups.concat(newJson.groups); } //add this line because we need id below this.configLoader.addNeedValues(this.appConfig); //update controller setting controllerJson.controlledWidgets = array.map(newJson.widgets, function(widgetJson){ return widgetJson.id; }); controllerJson.controlledGroups = array.map(newJson.groups, function(groupJson){ return groupJson.id; }); } this.configLoader.addNeedValues(this.appConfig); this.configLoader.loadAndUpgradeAllWidgetsConfig(this.appConfig).then(lang.hitch(this, function(appConfig){ this.appConfig = appConfig; this._addDefaultValues(this.appConfig); topic.publish('appConfigChanged', this.getAppConfig(), 'widgetPoolChange', newJson); })); }, _removeWidgetOrGroupFromPoolById: function(appConfig, id){ array.some(appConfig.widgetPool.widgets, function(widget, i){ if(widget.id === id){ appConfig.widgetPool.widgets.splice(i, 1); return true; } }); array.some(appConfig.widgetPool.groups, function(group, i){ if(group.id === id){ appConfig.widgetPool.groups.splice(i, 1); return true; } }); }, _onOpenAtStartChanged: function(_newJson) { // transfer obj to another iframe may cause problems on IE8 var newJson = jimuUtils.reCreateObject(_newJson); //TODO we support only one controller for now, so we don't do much here var appConfig = this.appConfig; if (_newJson.isOnScreen) { var onScreenWidgets = appConfig.widgetOnScreen && appConfig.widgetOnScreen.widgets; if (onScreenWidgets && onScreenWidgets.length > 0) { array.forEach(onScreenWidgets, lang.hitch(this, function(w) { if (w.id === _newJson.id) { w.openAtStart = !w.openAtStart; } else { delete w.openAtStart; } })); } } else { var pool = appConfig.widgetPool; if (pool && pool.groups && pool.groups.length > 0) { array.forEach(pool.groups, lang.hitch(this, function(g) { if (g.id === _newJson.id) { g.openAtStart = !g.openAtStart; } else { delete g.openAtStart; } })); } if (pool && pool.widgets && pool.widgets.length > 0) { array.forEach(pool.widgets, lang.hitch(this, function(w) { if (w.id === _newJson.id) { w.openAtStart = !w.openAtStart; } else { delete w.openAtStart; } })); } } topic.publish('appConfigChanged', this.getAppConfig(), 'openAtStartChange', newJson); }, _onAppAttributeChanged: function(_newJson){ // transfer obj to another iframe may cause problems on IE8 var newJson = jimuUtils.reCreateObject(_newJson); lang.mixin(this.appConfig, newJson); this.configLoader.processProxy(this.appConfig); this.configLoader.addNeedValues(this.appConfig); this._addDefaultValues(this.appConfig); topic.publish('appConfigChanged', this.getAppConfig(), 'attributeChange', newJson); }, _onLoadingPageChanged: function(_newJson){ // transfer obj to another iframe may cause problems on IE8 var newJson = jimuUtils.reCreateObject(_newJson); var oldConfig; if('backgroundColor' in newJson){ this.appConfig.loadingPage.backgroundColor = newJson.backgroundColor; }else if('backgroundImage' in newJson){ oldConfig = this.appConfig.loadingPage.backgroundImage || {}; this.appConfig.loadingPage.backgroundImage = lang.mixin(oldConfig, newJson.backgroundImage); }else if('loadingGif' in newJson){ oldConfig = this.appConfig.loadingPage.loadingGif || {}; this.appConfig.loadingPage.loadingGif = lang.mixin(oldConfig, newJson.loadingGif); } this.configLoader.addNeedValues(this.appConfig); this._addDefaultValues(this.appConfig); topic.publish('appConfigChanged', this.getAppConfig(), 'loadingPageChange', newJson); }, /** * _newJson pattern: * { * mapItemId: itemId, * proxyItems: [{ * sourceUrl: string; * title: string; * premium: boolean; * consumeCredits: boolean; * useProxy: boolean; * proxyUrl?: string; * proxyId?: string; * }] * } */ _onAppProxyForMapChanged: function(_newJson) { var newJson = jimuUtils.reCreateObject(_newJson); if (!('appProxy' in this.appConfig.map)) { // Set appProxy if there is no such property this.appConfig.map.appProxy = newJson; } else if (this.appConfig.map.appProxy.mapItemId !== newJson.mapItemId) { // Replace the app proxy if map changed. this.appConfig.map.appProxy = newJson; } else { // Update proxy items array.forEach(newJson.proxyItems, lang.hitch(this, function(item) { array.some(this.appConfig.map.appProxy.proxyItems, function(configItem) { if (configItem.sourceUrl === item.sourceUrl) { configItem.useProxy = item.useProxy; configItem.proxyUrl = item.proxyUrl || ''; configItem.proxyId = item.proxyId || ''; return true; } }); })); } topic.publish('appConfigChanged', this.getAppConfig(), 'appProxyChange', newJson); }, /** * _newJson pattern is array of: * { * sourceUrl: string, * proxyUrl?: string, * proxyId?: string, * useProxy: boolean, * title: string, * premium: boolean, * consumeCredits: boolean * } */ _onAppProxyForUrlChanged: function(_newJson) { var newJson = jimuUtils.reCreateObject(_newJson); this.appConfig.appProxies = newJson; topic.publish('appConfigChanged', this.getAppConfig(), 'appProxyChange', newJson); }, _onTemplateConfigChanged: function(_newJson){ var newJson = jimuUtils.reCreateObject(_newJson); this.appConfig.templateConfig = newJson; this.configLoader.addNeedValues(this.appConfig); this._addDefaultValues(this.appConfig); topic.publish('appConfigChanged', this.getAppConfig(), 'templateConfigChange', newJson); }, _onMapChanged: function(_newJson){ // transfer obj to another iframe may cause problems on IE8 var newJson = jimuUtils.reCreateObject(_newJson); //remove the options that are relative to map's display when map is changed. if(this.appConfig.map.mapOptions){ jimuUtils.deleteMapOptions(this.appConfig.map.mapOptions); } lang.mixin(this.appConfig.map, newJson); this.configLoader.addNeedValues(this.appConfig); this.configLoader.loadAndUpgradeAllWidgetsConfig(this.appConfig).then(lang.hitch(this, function(appConfig){ this.appConfig = appConfig; this._addDefaultValues(this.appConfig); topic.publish('appConfigChanged', this.getAppConfig(), 'mapChange', newJson); })); }, _onMapOptionsChanged: function(_newJson){ // transfer obj to another iframe may cause problems on IE8 var newJson = jimuUtils.reCreateObject(_newJson); if(!this.appConfig.map.mapOptions){ this.appConfig.map.mapOptions = {}; } lang.mixin(this.appConfig.map.mapOptions, newJson); topic.publish('appConfigChanged', this.getAppConfig(), 'mapOptionsChange', newJson); }, _onThemeChanged: function(theme){ this._getAppConfigFromTheme(theme).then(lang.hitch(this, function(config){ this.appConfig = config; topic.publish('appConfigChanged', this.getAppConfig(), 'themeChange', theme.getName()); })); }, _onLayoutChanged: function(layout){ //summary: // * Layout contains widget/group position, panel uri. // * For default layout, use the same format with app config to define it. // * For other layouts, we support 2 ways: // * Use array, one by one // * Use object, key is widget uri, or ph_<index>(placeholder), or g_<index>(group) this.appConfig = jimuUtils.mixinAppConfigPosition(this.appConfig, layout.layoutConfig); this._addDefaultPanelAndPosition(this.appConfig); topic.publish('appConfigChanged', this.getAppConfig(), 'layoutChange', layout.name); }, _onStyleChanged: function(style){ this.appConfig.theme.styles = this._genStyles(this.appConfig.theme.styles, style.name); if (style.isCustom) { this.appConfig.theme.customStyles = { mainBackgroundColor: style.styleColor }; } else { delete this.appConfig.theme.customStyles; } topic.publish('appConfigChanged', this.getAppConfig(), 'styleChange', style.name); }, _onSyncExtent: function(map){ topic.publish('syncExtent', map); }, _genStyles: function(allStyle, currentStyle){ var styles = []; styles.push(currentStyle); array.forEach(allStyle, function(_style){ if(styles.indexOf(_style) < 0){ styles.push(_style); } }); return styles; }, /************************************** Keep the following same between themes: 1. map config excluding map's position 2. widget pool config excluding pool panel config ***************************************/ _getAppConfigFromTheme: function(theme){ var def = new Deferred(); var config, styles = []; var currentConfig = this.getAppConfig().getCleanConfig(); currentConfig.mode = this.urlParams.mode; //because we don't allow user config panel for group, //and group's panel should be different between differrent theme //so, we delete group panel array.forEach(currentConfig.widgetPool.groups, function(group){ delete group.panel; }, this); //theme has already appConfig object, use it but keep something if(theme.appConfig){ config = lang.clone(theme.appConfig); config.map = currentConfig.map; config.map.position = theme.appConfig.map.position; this._copyPoolToThemePool(currentConfig, config); config.links = currentConfig.links; config.title = currentConfig.title; config.subtitle = currentConfig.subtitle; config.logo = currentConfig.logo; }else{ //use layout and style to create a new appConfig, which may contain some place holders var layout = theme.getCurrentLayout(); var style = theme.getCurrentStyle(); config = lang.clone(currentConfig); var layoutConfig = lang.clone(layout.layoutConfig); //use onscreen config.widgetOnScreen = layoutConfig.widgetOnScreen; //add flag if(layoutConfig.widgetPool){ array.forEach(layoutConfig.widgetPool.widgets, function(w){ w.isPreconfiguredInTheme = true; }); array.forEach(layoutConfig.widgetPool.groups, function(g){ g.isPreconfiguredInTheme = true; }); } //copy pool this._copyPoolToThemePool(currentConfig, layoutConfig); config.widgetPool = layoutConfig.widgetPool; if(layoutConfig.map && layoutConfig.map.position){ config.map.position = layoutConfig.map.position; } config.mobileLayout = layoutConfig.mobileLayout; //put all styles into the style array, and the current style is the first element styles = this._genStyles(array.map(theme.getStyles(), function(style){ return style.name; }), style.name); config.theme = { name: theme.getName(), styles: styles, version: theme.getVersion() }; } this.configLoader.addNeedValues(config); this.configLoader.loadWidgetsManifest(config).then(lang.hitch(this, function(config){ return this.configLoader.loadAndUpgradeAllWidgetsConfig(config); })).then(lang.hitch(this, function(){ this._addDefaultValues(config); def.resolve(config); })); return def; }, _copyPoolToThemePool: function(currentAppConfig, themeAppConfig){ var cpool = currentAppConfig.widgetPool; if(!themeAppConfig.widgetPool){ themeAppConfig.widgetPool = {}; } var tpool = themeAppConfig.widgetPool; //widgets/groups defined in theme var themePoolWidgets = array.filter(tpool.widgets, function(tw){ if(tw.isPreconfiguredInTheme){ return true; } //widgets that exists in the theme only(added by user, not pre-configured) if(!array.some(cpool.widgets, function(cw){ return cw.name === tw.name; })){ return true; } }); var themePoolGroups = array.filter(tpool.groups, function(g){ return g.isPreconfiguredInTheme; }); //widgets/groups are shared var currentPoolWidgets = array.filter(cpool.widgets, function(w){ return !w.isPreconfiguredInTheme; }); var currentPoolGroups = array.filter(cpool.groups, function(g){ return !g.isPreconfiguredInTheme; }); currentPoolWidgets = this._getPoolWidgetsWithoutDuplicated(currentPoolWidgets, themeAppConfig.widgetOnScreen.widgets || []); tpool.widgets = currentPoolWidgets.concat(themePoolWidgets); tpool.groups = currentPoolGroups.concat(themePoolGroups); }, _getPoolWidgetsWithoutDuplicated: function(currentPoolWidgets, themeOnScreeWidgets){ var ret = lang.clone(currentPoolWidgets); var currentAppConfig = this.getAppConfig(); //we don't care groups and theme pool, because all in-panel widgets are not singleton for(var i = currentPoolWidgets.length - 1; i >= 0; i --){ for(var j = themeOnScreeWidgets.length - 1; j >= 0; j --){ if(!themeOnScreeWidgets[j].uri){ continue; } var wname = themeOnScreeWidgets[j].name; if(!wname){ wname = jimuUtils.getWidgetNameFromUri(themeOnScreeWidgets[j].uri); } var wid = currentPoolWidgets[i].id; var wjson = currentAppConfig.getConfigElementById(wid); if(currentPoolWidgets[i] && currentPoolWidgets[i].name === wname && wjson.supportMultiInstance === false){ console.log('Widget', currentPoolWidgets[i].name, 'is not copied to new theme because this widget exists in new theme.'); ret.splice(i, 1); } } } return ret; }, _onAppConfigSet: function(c){ //summary: // this method may be called by builder or UT c = jimuUtils.reCreateObject(c); window.appInfo.isRunInMobile = jimuUtils.inMobileSize(); this.configLoader.processProxy(c); this.configLoader.addNeedValues(c); this.configLoader.loadAndUpgradeAllWidgetsConfig(c).then(lang.hitch(this, function(c){ this._addDefaultValues(c); tokenUtils.setPortalUrl(c.portalUrl); window.portalUrl = c.portalUrl; if(this.appConfig){ //remove the options that are relative to map's display when map is changed. jimuUtils.deleteMapOptions(c.map.mapOptions); this.appConfig = c; topic.publish('appConfigChanged', this.getAppConfig(), 'resetConfig', c); }else{ this.appConfig = c; topic.publish("appConfigLoaded", this.getAppConfig()); } })); }, /********************************************** * Add default values ************************************************/ _addDefaultValues: function(config) { this._addDefaultPortalUrl(config); this._addDefaultGeometryService(config); this._addDefaultStyle(config); this._addDefaultMap(config); this._addDefaultVisible(config); //preload widgets if(typeof config.widgetOnScreen === 'undefined'){ config.widgetOnScreen = {}; } if(typeof config.widgetPool === 'undefined'){ config.widgetPool = {}; } this._addDefaultPanelAndPosition(config); this._addDefaultOfWidgetGroup(config); //if the first widget or first group doesn't have index property, we add it if(config.widgetPool.widgets && config.widgetPool.widgets.length > 0 && config.widgetPool.widgets[0].index === undefined || config.widgetPool.groups && config.widgetPool.groups.length > 0 && config.widgetPool.groups[0].index === undefined){ this._addIndexForWidgetPool(config); } return config; }, _addDefaultPortalUrl: function(config){ if(typeof config.portalUrl === 'undefined'){ config.portalUrl = 'http://www.arcgis.com/'; } if(config.portalUrl && config.portalUrl.substr(config.portalUrl.length - 1) !== '/'){ config.portalUrl += '/'; } }, _addDefaultGeometryService: function(appConfig){ var geoServiceUrl = appConfig && appConfig.geometryService; var validGeoServiceUrl = geoServiceUrl && typeof geoServiceUrl === 'string' && lang.trim(geoServiceUrl); if(validGeoServiceUrl){ geoServiceUrl = lang.trim(geoServiceUrl); } else{ //TODO this.portalSelf is null if app is loaded in builder. //but we can ensure appConfig.geometryService is not null if app is created by builder, //so this line will not be executed. geoServiceUrl = this.portalSelf.helperServices.geometry.url; } appConfig.geometryService = geoServiceUrl; esriConfig.defaults.geometryService = new GeometryService(appConfig.geometryService); }, _addDefaultStyle: function(config){ if(config.theme){ if(!config.theme.styles || config.theme.styles.length === 0){ config.theme.styles = ['default']; } } }, _addDefaultMap: function(config){ config.map.id = 'map'; if(typeof config.map['3D'] === 'undefined' && typeof config.map['2D'] === 'undefined'){ config.map['2D'] = true; } if(typeof config.map.position === 'undefined'){ config.map.position = { left: 0, right: 0, top: 0, bottom: 0 }; } if(typeof config.map.portalUrl === 'undefined'){ config.map.portalUrl = config.portalUrl; } }, _addDefaultVisible: function(config){ jimuUtils.visitElement(config, function(e){ if(e.visible === undefined){ e.visible = true; } }); }, _addDefaultPanelAndPosition: function(config){ this._addOnScreenDefaultPanelAndPosition(config); this._addPoolDefaultPanelAndPosition(config); }, _addOnScreenDefaultPanelAndPosition: function(config){ var i, j, screenSectionConfig = config.widgetOnScreen; if(!screenSectionConfig){ return; } var panelDefaultPositionR = screenSectionConfig.panel && screenSectionConfig.panel.positionRelativeTo? screenSectionConfig.panel.positionRelativeTo: 'map'; if(typeof screenSectionConfig.panel === 'undefined' || typeof screenSectionConfig.panel.uri === 'undefined'){ screenSectionConfig.panel = { uri: 'jimu/OnScreenWidgetPanel', //positionRelativeTo: 'map', position: { //move positionRelativeTo to position.relativeTo relativeTo: panelDefaultPositionR } }; }else if(typeof screenSectionConfig.panel.position === 'undefined'){ screenSectionConfig.panel.position = {relativeTo: panelDefaultPositionR}; }else if(typeof screenSectionConfig.panel.position.relativeTo === 'undefined'){ screenSectionConfig.panel.position.relativeTo = panelDefaultPositionR; } if(screenSectionConfig.widgets){ for(i = 0; i < screenSectionConfig.widgets.length; i++){ if(!screenSectionConfig.widgets[i].position){ screenSectionConfig.widgets[i].position = {}; } if(!screenSectionConfig.widgets[i].position.relativeTo){ screenSectionConfig.widgets[i].position.relativeTo = screenSectionConfig.widgets[i] && screenSectionConfig.widgets[i].positionRelativeTo? screenSectionConfig.widgets[i].positionRelativeTo: 'map'; } if(screenSectionConfig.widgets[i].inPanel === true && !screenSectionConfig.widgets[i].panel){ screenSectionConfig.widgets[i].panel = lang.clone(screenSectionConfig.panel); screenSectionConfig.widgets[i].panel.position = screenSectionConfig.widgets[i].position; screenSectionConfig.widgets[i].panel.position.relativeTo = screenSectionConfig.widgets[i].position.relativeTo; } } } if(screenSectionConfig.groups){ for(i = 0; i < screenSectionConfig.groups.length; i++){ if(!screenSectionConfig.groups[i].panel){ screenSectionConfig.groups[i].panel = screenSectionConfig.panel; } if(screenSectionConfig.groups[i].panel && !screenSectionConfig.groups[i].panel.position){ screenSectionConfig.groups[i].panel.position = {}; } if(!screenSectionConfig.groups[i].panel.position.relativeTo){ screenSectionConfig.groups[i].panel.position.relativeTo = screenSectionConfig.groups[i].panel.positionRelativeTo? screenSectionConfig.groups[i].panel.positionRelativeTo:'map'; } if(!screenSectionConfig.groups[i].widgets){ screenSectionConfig.groups[i].widgets = []; } for(j = 0; j < screenSectionConfig.groups[i].widgets.length; j++){ screenSectionConfig.groups[i].widgets[j].panel = screenSectionConfig.groups[i].panel; } } } }, _addPoolDefaultPanelAndPosition: function(config){ var i, j, poolSectionConfig = config.widgetPool; if(!poolSectionConfig){ return; } var panelDefaultPositionR = poolSectionConfig.panel && poolSectionConfig.panel.positionRelativeTo? poolSectionConfig.panel.positionRelativeTo: 'map'; if(typeof poolSectionConfig.panel === 'undefined' || typeof poolSectionConfig.panel.uri === 'undefined'){ poolSectionConfig.panel = { uri: 'jimu/OnScreenWidgetPanel', position: { relativeTo: panelDefaultPositionR } }; }else if(typeof poolSectionConfig.panel.position === 'undefined'){ poolSectionConfig.panel.position = {relativeTo: panelDefaultPositionR}; }else if(typeof poolSectionConfig.panel.position.relativeTo === 'undefined'){ poolSectionConfig.panel.position.relativeTo = panelDefaultPositionR; } if(poolSectionConfig.groups){ for(i = 0; i < poolSectionConfig.groups.length; i++){ if(!poolSectionConfig.groups[i].panel){ poolSectionConfig.groups[i].panel = poolSectionConfig.panel; }else if(!poolSectionConfig.groups[i].panel.position.relativeTo){ poolSectionConfig.groups[i].panel.position.relativeTo = poolSectionConfig.groups[i].panel.positionRelativeTo? poolSectionConfig.groups[i].panel.positionRelativeTo: 'map'; } if(!poolSectionConfig.groups[i].widgets){ poolSectionConfig.groups[i].widgets = []; } for(j = 0; j < poolSectionConfig.groups[i].widgets.length; j++){ poolSectionConfig.groups[i].widgets[j].panel = poolSectionConfig.groups[i].panel; } } } if(poolSectionConfig.widgets){ for(i = 0; i < poolSectionConfig.widgets.length; i++){ if(poolSectionConfig.widgets[i].inPanel === false){ var defaultWidgetPositionR = poolSectionConfig.widgets[i].positionRelativeTo? poolSectionConfig.widgets[i].positionRelativeTo: 'map'; if(!poolSectionConfig.widgets[i].position){ poolSectionConfig.widgets[i].position = { relativeTo: defaultWidgetPositionR }; }else if(!poolSectionConfig.widgets[i].position.relativeTo){ poolSectionConfig.widgets[i].position.relativeTo = defaultWidgetPositionR; } }else if(!poolSectionConfig.widgets[i].panel){ poolSectionConfig.widgets[i].panel = config.widgetPool.panel; } } } }, _addDefaultOfWidgetGroup: function(config){ //group/widget labe, icon jimuUtils.visitElement(config, lang.hitch(this, function(e, info){ e.isOnScreen = info.isOnScreen; if(e.widgets){ //it's group e.gid = e.id; if(e.widgets.length === 1){ if(!e.label){ e.label = e.widgets[0].label? e.widgets[0].label: 'Group'; } if(!e.icon){ if(e.widgets[0].uri){ e.icon = this._getDefaultIconFromUri(e.widgets[0].uri); }else{ e.icon = 'jimu.js/images/group_icon.png'; } } }else{ e.icon = e.icon? e.icon: 'jimu.js/images/group_icon.png'; e.label = e.label? e.label: 'Group_' + info.index; } }else{ e.gid = info.groupId; } })); }, _getDefaultIconFromUri: function(uri){ var segs = uri.split('/'); segs.pop(); return segs.join('/') + '/images/icon.png?wab_dv=' + window.deployVersion; }, _addIndexForWidgetPool: function(config){ //be default, widgets are in front var index = 0, i, j; if(config.widgetPool.widgets){ for(i = 0; i < config.widgetPool.widgets.length; i++){ config.widgetPool.widgets[i].index = index; index ++; } } if(config.widgetPool.groups){ for(i = 0; i < config.widgetPool.groups.length; i++){ config.widgetPool.groups[i].index = index; index ++; for(j = 0; j < config.widgetPool.groups[i].widgets.length; j++){ config.widgetPool.groups[i].widgets[j].index = j; } } } } }); clazz.getInstance = function (urlParams) { if(instance === null) { instance = new clazz(urlParams); }else{ if(urlParams){ instance.urlParams = urlParams; if(instance.configLoader){ instance.configLoader.urlParams = urlParams; } } } window.getAppConfig = lang.hitch(instance, instance.getAppConfig); return instance; }; function getCleanConfig(config, isForAGOLTemplate){ //delete the properties that framework add var newConfig = lang.clone(config); var properties = jimuUtils.widgetProperties; if(typeof isForAGOLTemplate === 'undefined'){ isForAGOLTemplate = false; } delete newConfig.mode; jimuUtils.visitElement(newConfig, function(e, info){ if(e.widgets){ delete e.isOnScreen; delete e.gid; if(e.icon === 'jimu.js/images/group_icon.png'){ delete e.icon; } delete e.openType; if(info.isOnScreen){ if(e.panel && jimuUtils.isEqual(e.panel, newConfig.widgetOnScreen.panel)){ delete e.panel; } } return; } if(e.icon && e.icon === e.folderUrl + 'images/icon.png?wab_dv=' + window.deployVersion){ delete e.icon; } delete e.panel; delete e.folderUrl; delete e.amdFolder; delete e.thumbnail; delete e.configFile; delete e.gid; delete e.isOnScreen; delete e.isRemote; properties.forEach(function(p){ delete e[p]; }); if(!isForAGOLTemplate){ if(e.visible){ delete e.visible; } if(e.manifest && e.label === e.manifest.label){ delete e.label; } if(e.isDefaultConfig){ delete e.config; delete e.isDefaultConfig; } }else{ if(typeof e.openAtStart === 'undefined'){ e.openAtStart = false; } } delete e.manifest; }); delete newConfig.rawAppConfig; //the _ssl property is added by esriRequest delete newConfig._ssl; //delete all of the methods delete newConfig.getConfigElementById; delete newConfig.getConfigElementsByName; delete newConfig.processNoUriWidgets; delete newConfig.addElementId; delete newConfig.getCleanConfig; delete newConfig.visitElement; delete newConfig.agolConfig; delete newConfig._itemData; delete newConfig.oldWabVersion; return newConfig; } return clazz; });
cmccullough2/cmv-wab-widgets
wab/2.3/jimu.js/ConfigManager.js
JavaScript
mit
39,282
'use strict'; var fs = require('fs'); var path = require('path'); var walk = require('pug-walk'); module.exports = load; function load(ast, options) { load.validateOptions(options); // clone the ast ast = JSON.parse(JSON.stringify(ast)); return walk(ast, function (node) { if (node.str === undefined) { if (node.type === 'Include' || node.type === 'Extends') { var file = node.file; if (file.type !== 'FileReference') { throw new Error('Expected file.type to be "FileReference"'); } var path, str; try { path = load.resolve(file.path, file.filename, options); file.fullPath = path; str = load.read(path, options); } catch (ex) { ex.message += '\n at ' + node.filename + ' line ' + node.line; throw ex; } file.str = str; if (node.type === 'Extends' || (!node.filter && /\.jade$/.test(path))) { file.ast = load.string(str, path, options); } } } }); } load.string = function loadString(str, filename, options) { load.validateOptions(options); var tokens = options.lex(str, filename); var ast = options.parse(tokens, filename); return load(ast, options); }; load.file = function loadFile(filename, options) { load.validateOptions(options); var str = load.read(filename, options); return load.string(str, filename, options); } load.resolve = function resolve(filename, source, options) { if (options && options.resolve) return options.resolve(filename, source, options); filename = filename.trim(); source = source.trim(); if (filename[0] !== '/' && !source) throw new Error('the "filename" option is required to use includes and extends with "relative" paths'); if (filename[0] === '/' && !options.basedir) throw new Error('the "basedir" option is required to use includes and extends with "absolute" paths'); filename = path.join(filename[0] === '/' ? options.basedir : path.dirname(source), filename); if (path.basename(filename).indexOf('.') === -1) filename += '.jade'; return filename; }; load.read = function read(filename, options) { if (options && options.read) return options.read(filename, options); return fs.readFileSync(filename, 'utf8'); }; load.validateOptions = function validateOptions(options) { if (typeof options.lex !== 'function') { throw new TypeError('options.lex must be a function'); } if (typeof options.parse !== 'function') { throw new TypeError('options.parse must be a function'); } if (options.resolve && typeof options.resolve !== 'function') { throw new TypeError('options.resolve must be a function'); } if (options.read && typeof options.read !== 'function') { throw new TypeError('options.read must be a function'); } };
ajredovan/.tour
tour_v1/node_modules/pug-loader/index.js
JavaScript
mit
2,820
/*globals Handlebars */ require("ember-handlebars/ext"); /** @module ember @submodule ember-handlebars */ /** @private Find templates stored in the head tag as script tags and make them available to `Ember.CoreView` in the global `Ember.TEMPLATES` object. This will be run as as jQuery DOM-ready callback. Script tags with `text/x-handlebars` will be compiled with Ember's Handlebars and are suitable for use as a view's template. Those with type `text/x-raw-handlebars` will be compiled with regular Handlebars and are suitable for use in views' computed properties. @method bootstrap @for Ember.Handlebars @static @param ctx */ Ember.Handlebars.bootstrap = function(ctx) { var selectors = 'script[type="text/x-handlebars"], script[type="text/x-raw-handlebars"]'; Ember.$(selectors, ctx) .each(function() { // Get a reference to the script tag var script = Ember.$(this); var compile = (script.attr('type') === 'text/x-raw-handlebars') ? Ember.$.proxy(Handlebars.compile, Handlebars) : Ember.$.proxy(Ember.Handlebars.compile, Ember.Handlebars), // Get the name of the script, used by Ember.View's templateName property. // First look for data-template-name attribute, then fall back to its // id if no name is found. templateName = script.attr('data-template-name') || script.attr('id') || 'application', template = compile(script.html()); // For templates which have a name, we save them and then remove them from the DOM Ember.TEMPLATES[templateName] = template; // Remove script tag from DOM script.remove(); }); }; function bootstrap() { Ember.Handlebars.bootstrap( Ember.$(document) ); } /* We tie this to application.load to ensure that we've at least attempted to bootstrap at the point that the application is loaded. We also tie this to document ready since we're guaranteed that all the inline templates are present at this point. There's no harm to running this twice, since we remove the templates from the DOM after processing. */ Ember.onLoad('application', bootstrap);
chancancode/ember.js
packages/ember-handlebars/lib/loader.js
JavaScript
mit
2,142
var vows = require('vows'); var assert = require('assert'); var suite = vows.describe('jStat.distribution'); require('../env.js'); suite.addBatch({ 'normal pdf': { 'topic': function() { return jStat; }, //Checked against R's dnorm(x, mean, sd) 'check pdf calculation': function(jStat) { var tol = 0.000001; assert.epsilon(tol, jStat.normal.pdf(0, 0, 1.0), 0.3989423); assert.epsilon(tol, jStat.normal.pdf(5, 10, 3.0), 0.03315905); assert.epsilon(tol, jStat.normal.pdf(-1, 1, 0.5), 0.00026766); }, //Checked against R's qnorm(p, mean, sd) 'check inv calculation': function(jStat) { var tol = 0.000001; assert.epsilon(tol, jStat.normal.inv(0.3989423, 0, 1.0), -0.2560858); assert.epsilon(tol, jStat.normal.inv(0.05, 10, 3.0), 5.065439); assert.epsilon(tol, jStat.normal.inv(0.65, -2, .5), -1.80734); } } }); suite.export(module);
akrawitz/jstat
test/distribution/normal-test.js
JavaScript
mit
923
module.exports={A:{A:{"2":"J UB","2340":"C G E B A"},B:{"2":"D Y g H L"},C:{"2":"SB y QB","545":"0 1 3 4 5 F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s x z u t PB"},D:{"2":"F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b c d e f K h i j","1025":"0 1 3 4 5 8 k l m n o p q r s x z u t EB BB TB CB"},E:{"1":"B A JB KB","2":"9 F I DB FB","164":"J","4644":"C G E GB HB IB"},F:{"2":"6 7 E A H L M N O P Q R S T U V W LB MB NB OB","545":"D RB w","1025":"X v Z a b c d e f K h i j k l m n o p q r s"},G:{"1":"A bB cB","2":"2 9 AB","4260":"VB WB","4644":"G XB YB ZB aB"},H:{"2":"dB"},I:{"2":"2 y F eB fB gB hB iB jB","1025":"t"},J:{"2":"C","4260":"B"},K:{"2":"6 7 B A","545":"D w","1025":"K"},L:{"1025":"8"},M:{"545":"u"},N:{"2340":"B A"},O:{"4260":"kB"},P:{"1025":"F I"},Q:{"2":"lB"},R:{"1025":"mB"}},B:7,C:"Crisp edges/pixelated images"};
secatoriuris/vista-theme
themes/vista/node_modules/caniuse-lite/data/features/css-crisp-edges.js
JavaScript
gpl-2.0
890
import Ember from 'ember'; export default Ember.Controller.extend({ applicationController: Ember.inject.controller('application'), stats: Ember.computed.reads('applicationController'), config: Ember.computed.reads('applicationController.config'), cachedLogin: Ember.computed('login', { get() { return this.get('login') || Ember.$.cookie('login'); }, set(key, value) { Ember.$.cookie('login', value); this.set('model.login', value); return value; } }) });
boehla/open-ethereum-pool
www/app/controllers/index.js
JavaScript
gpl-3.0
506
[{ Name: 'Weather Underground Widget', Author: 'Generoso Martello', Version: '2013-03-31', GroupName: '', IconImage: 'pages/control/widgets/homegenie/generic/images/wu_logo.png', StatusText: '', Description: '', RenderView: function (cuid, module) { var container = $(cuid); var widget = container.find('[data-ui-field=widget]'); // if (!this.Initialized) { this.Initialized = true; // settings button widget.find('[data-ui-field=settings]').on('click', function () { HG.WebApp.ProgramEdit._CurrentProgram.Domain = module.Domain; HG.WebApp.ProgramEdit._CurrentProgram.Address = module.Address; HG.WebApp.ProgramsList.UpdateOptionsPopup(); }); } // var display_location = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.DisplayLocation').Value; var serviceapi = HG.WebApp.Utility.GetModulePropertyByName(module, 'ConfigureOptions.ApiKey').Value; if (serviceapi == '' || serviceapi == '?') { widget.find('[data-ui-field=name]').html('Not configured.'); widget.find('[data-ui-field=sunrise_value]').html(sunrise); // widget.find('[data-ui-field=settings]').qtip({ content: { title: HG.WebApp.Locales.GetLocaleString('control_widget_notconfigured_title'), text: HG.WebApp.Locales.GetLocaleString('control_widget_notconfigured_text'), button: HG.WebApp.Locales.GetLocaleString('control_widget_notconfigured_button') }, show: { event: false, ready: true, delay: 1000 }, events: { hide: function () { $(this).qtip('destroy'); } }, hide: { event: false, inactive: 3000 }, style: { classes: 'qtip-red qtip-shadow qtip-rounded qtip-bootstrap' }, position: { my: 'top center', at: 'bottom center' } }); } else if (display_location == '') { widget.find('[data-ui-field=name]').html('Waiting for data...'); widget.find('[data-ui-field=last_updated_value]').html('Not updated!'); } else { widget.find('[data-ui-field=name]').html(display_location); // var sunrise = HG.WebApp.Utility.GetModulePropertyByName(module, 'Astronomy.Sunrise').Value; widget.find('[data-ui-field=sunrise_value]').html(sunrise); // var sunset = HG.WebApp.Utility.GetModulePropertyByName(module, 'Astronomy.Sunset').Value; widget.find('[data-ui-field=sunset_value]').html(sunset); // var iconurl = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.IconUrl').Value; widget.find('[data-ui-field=icon]').attr('src', iconurl); // var icontext = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Description').Value; widget.find('[data-ui-field=description]').html(icontext); // var last_updated = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.LastUpdated').Value; widget.find('[data-ui-field=last_updated_value]').html(last_updated); // var display_celsius = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.DisplayCelsius').Value; if (display_celsius == 'TRUE') { var temperaturec = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.TemperatureC').Value; widget.find('[data-ui-field=temperature_value]').html(temperaturec + '&#8451;'); } else { var temperaturef = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.TemperatureF').Value; widget.find('[data-ui-field=temperature_value]').html(temperaturef + '&#8457;'); } // // Forecast data for (var f = 1; f <= 3; f++) { var fIconUrl = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.IconUrl').Value; widget.find('[data-ui-field=forecast_' + f + '_icon]').attr('src', fIconUrl); var fDescription = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.Description').Value; widget.find('[data-ui-field=forecast_' + f + '_desc]').html(fDescription); if (display_celsius == 'TRUE') { var temperatureMinC = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.TemperatureC.Low').Value; var temperatureMaxC = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.TemperatureC.High').Value; widget.find('[data-ui-field=forecast_' + f + '_tmin]').html(temperatureMinC + '&#8451;'); widget.find('[data-ui-field=forecast_' + f + '_tmax]').html(temperatureMaxC + '&#8451;'); } else { var temperatureMinF = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.TemperatureF.Low').Value; var temperatureMaxF = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.TemperatureF.High').Value; widget.find('[data-ui-field=forecast_' + f + '_tmin]').html(temperatureMinF + '&#8457;'); widget.find('[data-ui-field=forecast_' + f + '_tmax]').html(temperatureMaxF + '&#8457;'); } var displayDate = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.Weekday').Value.substr(0, 3) + ', '; displayDate += HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.Day').Value + ' '; displayDate += HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.Month').Value; widget.find('[data-ui-field=forecast_' + f + '_date]').html(displayDate); } } } }]
AdnanSattar/HomeGenie
BaseFiles/Common/html/pages/control/widgets/weather/wunderground/conditions.js
JavaScript
gpl-3.0
6,270
/*! * jQuery Password Strength plugin for Twitter Bootstrap * Version: 3.0.4 * * Copyright (c) 2008-2013 Tane Piper * Copyright (c) 2013 Alejandro Blanco * Dual licensed under the MIT and GPL licenses. */ (function (jQuery) { // Source: src/i18n.js var i18n = {}; (function (i18n, i18next) { 'use strict'; i18n.fallback = { "wordMinLength": "Your password is too short", "wordMaxLength": "Your password is too long", "wordInvalidChar": "Your password contains an invalid character", "wordNotEmail": "Do not use your email as your password", "wordSimilarToUsername": "Your password cannot contain your username", "wordTwoCharacterClasses": "Use different character classes", "wordRepetitions": "Too many repetitions", "wordSequences": "Your password contains sequences", "errorList": "Errors:", "veryWeak": "Very Weak", "weak": "Weak", "normal": "Normal", "medium": "Medium", "strong": "Strong", "veryStrong": "Very Strong" }; i18n.t = function (key) { var result = ''; // Try to use i18next.com if (i18next) { result = i18next.t(key); } else { // Fallback to english result = i18n.fallback[key]; } return result === key ? '' : result; }; }(i18n, window.i18next)); // Source: src/rules.js var rulesEngine = {}; try { if (!jQuery && module && module.exports) { var jQuery = require("jquery"), jsdom = require("jsdom").jsdom; jQuery = jQuery(jsdom().defaultView); } } catch (ignore) {} (function ($, rulesEngine) { "use strict"; var validation = {}; rulesEngine.forbiddenSequences = [ "0123456789", "abcdefghijklmnopqrstuvwxyz", "qwertyuiop", "asdfghjkl", "zxcvbnm", "!@#$%^&*()_+" ]; validation.wordNotEmail = function (options, word, score) { if (word.match(/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i)) { return score; } return 0; }; validation.wordMinLength = function (options, word, score) { var wordlen = word.length, lenScore = Math.pow(wordlen, options.rules.raisePower); if (wordlen < options.common.minChar) { lenScore = (lenScore + score); } return lenScore; }; validation.wordMaxLength = function (options, word, score) { var wordlen = word.length, lenScore = Math.pow(wordlen, options.rules.raisePower); if (wordlen > options.common.maxChar) { return score; } return lenScore; }; validation.wordInvalidChar = function (options, word, score) { if (options.common.invalidCharsRegExp.test(word)) { return score; } return 0; }; validation.wordMinLengthStaticScore = function (options, word, score) { return word.length < options.common.minChar ? 0 : score; }; validation.wordMaxLengthStaticScore = function (options, word, score) { return word.length > options.common.maxChar ? 0 : score; }; validation.wordSimilarToUsername = function (options, word, score) { var username = $(options.common.usernameField).val(); if (username && word.toLowerCase().match(username.replace(/[\-\[\]\/\{\}\(\)\*\+\=\?\:\.\\\^\$\|\!\,]/g, "\\$&").toLowerCase())) { return score; } return 0; }; validation.wordTwoCharacterClasses = function (options, word, score) { if (word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) || (word.match(/([a-zA-Z])/) && word.match(/([0-9])/)) || (word.match(/(.[!,@,#,$,%,\^,&,*,?,_,~])/) && word.match(/[a-zA-Z0-9_]/))) { return score; } return 0; }; validation.wordRepetitions = function (options, word, score) { if (word.match(/(.)\1\1/)) { return score; } return 0; }; validation.wordSequences = function (options, word, score) { var found = false, j; if (word.length > 2) { $.each(rulesEngine.forbiddenSequences, function (idx, seq) { if (found) { return; } var sequences = [seq, seq.split('').reverse().join('')]; $.each(sequences, function (idx, sequence) { for (j = 0; j < (word.length - 2); j += 1) { // iterate the word trough a sliding window of size 3: if (sequence.indexOf(word.toLowerCase().substring(j, j + 3)) > -1) { found = true; } } }); }); if (found) { return score; } } return 0; }; validation.wordLowercase = function (options, word, score) { return word.match(/[a-z]/) && score; }; validation.wordUppercase = function (options, word, score) { return word.match(/[A-Z]/) && score; }; validation.wordOneNumber = function (options, word, score) { return word.match(/\d+/) && score; }; validation.wordThreeNumbers = function (options, word, score) { return word.match(/(.*[0-9].*[0-9].*[0-9])/) && score; }; validation.wordOneSpecialChar = function (options, word, score) { return word.match(/[!,@,#,$,%,\^,&,*,?,_,~]/) && score; }; validation.wordTwoSpecialChar = function (options, word, score) { return word.match(/(.*[!,@,#,$,%,\^,&,*,?,_,~].*[!,@,#,$,%,\^,&,*,?,_,~])/) && score; }; validation.wordUpperLowerCombo = function (options, word, score) { return word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) && score; }; validation.wordLetterNumberCombo = function (options, word, score) { return word.match(/([a-zA-Z])/) && word.match(/([0-9])/) && score; }; validation.wordLetterNumberCharCombo = function (options, word, score) { return word.match(/([a-zA-Z0-9].*[!,@,#,$,%,\^,&,*,?,_,~])|([!,@,#,$,%,\^,&,*,?,_,~].*[a-zA-Z0-9])/) && score; }; validation.wordIsACommonPassword = function (options, word, score) { if ($.inArray(word, options.rules.commonPasswords) >= 0) { return score; } return 0; }; rulesEngine.validation = validation; rulesEngine.executeRules = function (options, word) { var totalScore = 0; $.each(options.rules.activated, function (rule, active) { if (active) { var score = options.rules.scores[rule], funct = rulesEngine.validation[rule], result, errorMessage; if (!$.isFunction(funct)) { funct = options.rules.extra[rule]; } if ($.isFunction(funct)) { result = funct(options, word, score); if (result) { totalScore += result; } if (result < 0 || (!$.isNumeric(result) && !result)) { errorMessage = options.ui.spanError(options, rule); if (errorMessage.length > 0) { options.instances.errors.push(errorMessage); } } } } }); return totalScore; }; }(jQuery, rulesEngine)); try { if (module && module.exports) { module.exports = rulesEngine; } } catch (ignore) {} // Source: src/options.js var defaultOptions = {}; defaultOptions.common = {}; defaultOptions.common.minChar = 6; defaultOptions.common.maxChar = 20; defaultOptions.common.usernameField = "#username"; defaultOptions.common.invalidCharsRegExp = new RegExp(/[\s,'"]/); defaultOptions.common.userInputs = [ // Selectors for input fields with user input ]; defaultOptions.common.onLoad = undefined; defaultOptions.common.onKeyUp = undefined; defaultOptions.common.onScore = undefined; defaultOptions.common.zxcvbn = false; defaultOptions.common.zxcvbnTerms = [ // List of disrecommended words ]; defaultOptions.common.events = ["keyup", "change", "paste"]; defaultOptions.common.debug = false; defaultOptions.rules = {}; defaultOptions.rules.extra = {}; defaultOptions.rules.scores = { wordNotEmail: -100, wordMinLength: -50, wordMaxLength: -50, wordInvalidChar: -100, wordSimilarToUsername: -100, wordSequences: -20, wordTwoCharacterClasses: 2, wordRepetitions: -25, wordLowercase: 1, wordUppercase: 3, wordOneNumber: 3, wordThreeNumbers: 5, wordOneSpecialChar: 3, wordTwoSpecialChar: 5, wordUpperLowerCombo: 2, wordLetterNumberCombo: 2, wordLetterNumberCharCombo: 2, wordIsACommonPassword: -100 }; defaultOptions.rules.activated = { wordNotEmail: true, wordMinLength: true, wordMaxLength: false, wordInvalidChar: false, wordSimilarToUsername: true, wordSequences: true, wordTwoCharacterClasses: true, wordRepetitions: true, wordLowercase: true, wordUppercase: true, wordOneNumber: true, wordThreeNumbers: true, wordOneSpecialChar: true, wordTwoSpecialChar: true, wordUpperLowerCombo: true, wordLetterNumberCombo: true, wordLetterNumberCharCombo: true, wordIsACommonPassword: true }; defaultOptions.rules.raisePower = 1.4; // List taken from https://github.com/danielmiessler/SecLists (MIT License) defaultOptions.rules.commonPasswords = [ '123456', 'password', '12345678', 'qwerty', '123456789', '12345', '1234', '111111', '1234567', 'dragon', '123123', 'baseball', 'abc123', 'football', 'monkey', 'letmein', '696969', 'shadow', 'master', '666666', 'qwertyuiop', '123321', 'mustang', '1234567890', 'michael', '654321', 'pussy', 'superman', '1qaz2wsx', '7777777', 'fuckyou', '121212', '000000', 'qazwsx', '123qwe', 'killer', 'trustno1', 'jordan', 'jennifer', 'zxcvbnm', 'asdfgh', 'hunter', 'buster', 'soccer', 'harley', 'batman', 'andrew', 'tigger', 'sunshine', 'iloveyou', 'fuckme', '2000', 'charlie', 'robert', 'thomas', 'hockey', 'ranger', 'daniel', 'starwars', 'klaster', '112233', 'george', 'asshole', 'computer', 'michelle', 'jessica', 'pepper', '1111', 'zxcvbn', '555555', '11111111', '131313', 'freedom', '777777', 'pass', 'fuck', 'maggie', '159753', 'aaaaaa', 'ginger', 'princess', 'joshua', 'cheese', 'amanda', 'summer', 'love', 'ashley', '6969', 'nicole', 'chelsea', 'biteme', 'matthew', 'access', 'yankees', '987654321', 'dallas', 'austin', 'thunder', 'taylor', 'matrix' ]; defaultOptions.ui = {}; defaultOptions.ui.bootstrap2 = false; defaultOptions.ui.bootstrap3 = false; defaultOptions.ui.colorClasses = [ "danger", "danger", "danger", "warning", "warning", "success" ]; defaultOptions.ui.showProgressBar = true; defaultOptions.ui.progressBarEmptyPercentage = 1; defaultOptions.ui.progressBarMinWidth = 1; defaultOptions.ui.progressBarMinPercentage = 1; defaultOptions.ui.progressExtraCssClasses = ''; defaultOptions.ui.progressBarExtraCssClasses = ''; defaultOptions.ui.showPopover = false; defaultOptions.ui.popoverPlacement = "bottom"; defaultOptions.ui.showStatus = false; defaultOptions.ui.spanError = function (options, key) { "use strict"; var text = options.i18n.t(key); if (!text) { return ''; } return '<span style="color: #d52929">' + text + '</span>'; }; defaultOptions.ui.popoverError = function (options) { "use strict"; var errors = options.instances.errors, errorsTitle = options.i18n.t("errorList"), message = "<div>" + errorsTitle + "<ul class='error-list' style='margin-bottom: 0;'>"; jQuery.each(errors, function (idx, err) { message += "<li>" + err + "</li>"; }); message += "</ul></div>"; return message; }; defaultOptions.ui.showVerdicts = true; defaultOptions.ui.showVerdictsInsideProgressBar = false; defaultOptions.ui.useVerdictCssClass = false; defaultOptions.ui.showErrors = false; defaultOptions.ui.showScore = false; defaultOptions.ui.container = undefined; defaultOptions.ui.viewports = { progress: undefined, verdict: undefined, errors: undefined, score: undefined }; defaultOptions.ui.scores = [0, 14, 26, 38, 50]; defaultOptions.i18n = {}; defaultOptions.i18n.t = i18n.t; // Source: src/ui.js var ui = {}; (function ($, ui) { "use strict"; var statusClasses = ["error", "warning", "success"], verdictKeys = [ "veryWeak", "weak", "normal", "medium", "strong", "veryStrong" ]; ui.getContainer = function (options, $el) { var $container; $container = $(options.ui.container); if (!($container && $container.length === 1)) { $container = $el.parent(); } return $container; }; ui.findElement = function ($container, viewport, cssSelector) { if (viewport) { return $container.find(viewport).find(cssSelector); } return $container.find(cssSelector); }; ui.getUIElements = function (options, $el) { var $container, result; if (options.instances.viewports) { return options.instances.viewports; } $container = ui.getContainer(options, $el); result = {}; result.$progressbar = ui.findElement($container, options.ui.viewports.progress, "div.progress"); if (options.ui.showVerdictsInsideProgressBar) { result.$verdict = result.$progressbar.find("span.password-verdict"); } if (!options.ui.showPopover) { if (!options.ui.showVerdictsInsideProgressBar) { result.$verdict = ui.findElement($container, options.ui.viewports.verdict, "span.password-verdict"); } result.$errors = ui.findElement($container, options.ui.viewports.errors, "ul.error-list"); } result.$score = ui.findElement($container, options.ui.viewports.score, "span.password-score"); options.instances.viewports = result; return result; }; ui.initProgressBar = function (options, $el) { var $container = ui.getContainer(options, $el), progressbar = "<div class='progress "; if (options.ui.bootstrap2) { // Boostrap 2 progressbar += options.ui.progressBarExtraCssClasses + "'><div class='"; } else { // Bootstrap 3 & 4 progressbar += options.ui.progressExtraCssClasses + "'><div class='" + options.ui.progressBarExtraCssClasses + " progress-"; } progressbar += "bar'>"; if (options.ui.showVerdictsInsideProgressBar) { progressbar += "<span class='password-verdict'></span>"; } progressbar += "</div></div>"; if (options.ui.viewports.progress) { $container.find(options.ui.viewports.progress).append(progressbar); } else { $(progressbar).insertAfter($el); } }; ui.initHelper = function (options, $el, html, viewport) { var $container = ui.getContainer(options, $el); if (viewport) { $container.find(viewport).append(html); } else { $(html).insertAfter($el); } }; ui.initVerdict = function (options, $el) { ui.initHelper(options, $el, "<span class='password-verdict'></span>", options.ui.viewports.verdict); }; ui.initErrorList = function (options, $el) { ui.initHelper(options, $el, "<ul class='error-list'></ul>", options.ui.viewports.errors); }; ui.initScore = function (options, $el) { ui.initHelper(options, $el, "<span class='password-score'></span>", options.ui.viewports.score); }; ui.initPopover = function (options, $el) { try { $el.popover("destroy"); } catch (error) { // Bootstrap 4.2.X onwards $el.popover("dispose"); } $el.popover({ html: true, placement: options.ui.popoverPlacement, trigger: "manual", content: " " }); }; ui.initUI = function (options, $el) { if (options.ui.showPopover) { ui.initPopover(options, $el); } else { if (options.ui.showErrors) { ui.initErrorList(options, $el); } if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar) { ui.initVerdict(options, $el); } } if (options.ui.showProgressBar) { ui.initProgressBar(options, $el); } if (options.ui.showScore) { ui.initScore(options, $el); } }; ui.updateProgressBar = function (options, $el, cssClass, percentage) { var $progressbar = ui.getUIElements(options, $el).$progressbar, $bar = $progressbar.find(".progress-bar"), cssPrefix = "progress-"; if (options.ui.bootstrap2) { $bar = $progressbar.find(".bar"); cssPrefix = ""; } $.each(options.ui.colorClasses, function (idx, value) { if (options.ui.bootstrap2 || options.ui.bootstrap3) { $bar.removeClass(cssPrefix + "bar-" + value); } else { $bar.removeClass("bg-" + value); } }); if (options.ui.bootstrap2 || options.ui.bootstrap3) { $bar.addClass(cssPrefix + "bar-" + options.ui.colorClasses[cssClass]); } else { $bar.addClass("bg-" + options.ui.colorClasses[cssClass]); } if (percentage > 0) { $bar.css("min-width", options.ui.progressBarMinWidth + 'px'); } else { $bar.css("min-width", ''); } $bar.css("width", percentage + '%'); }; ui.updateVerdict = function (options, $el, cssClass, text) { var $verdict = ui.getUIElements(options, $el).$verdict; $verdict.removeClass(options.ui.colorClasses.join(' ')); if (cssClass > -1) { $verdict.addClass(options.ui.colorClasses[cssClass]); } if (options.ui.showVerdictsInsideProgressBar) { $verdict.css('white-space', 'nowrap'); } $verdict.html(text); }; ui.updateErrors = function (options, $el, remove) { var $errors = ui.getUIElements(options, $el).$errors, html = ""; if (!remove) { $.each(options.instances.errors, function (idx, err) { html += "<li>" + err + "</li>"; }); } $errors.html(html); }; ui.updateScore = function (options, $el, score, remove) { var $score = ui.getUIElements(options, $el).$score, html = ""; if (!remove) { html = score.toFixed(2); } $score.html(html); }; ui.updatePopover = function (options, $el, verdictText, remove) { var popover = $el.data("bs.popover"), html = "", hide = true; if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar && verdictText.length > 0) { html = "<h5><span class='password-verdict'>" + verdictText + "</span></h5>"; hide = false; } if (options.ui.showErrors) { if (options.instances.errors.length > 0) { hide = false; } html += options.ui.popoverError(options); } if (hide || remove) { $el.popover("hide"); return; } if (options.ui.bootstrap2) { popover = $el.data("popover"); } if (popover.$arrow && popover.$arrow.parents("body").length > 0) { $el.find("+ .popover .popover-content").html(html); } else { // It's hidden if (options.ui.bootstrap2 || options.ui.bootstrap3) { popover.options.content = html; } else { popover.config.content = html; } $el.popover("show"); } }; ui.updateFieldStatus = function (options, $el, cssClass, remove) { var $target = $el; if (options.ui.bootstrap2) { $target = $el.parents(".control-group").first(); } else if (options.ui.bootstrap3) { $target = $el.parents(".form-group").first(); } $.each(statusClasses, function (idx, css) { if (options.ui.bootstrap3) { css = "has-" + css; } else if (!options.ui.bootstrap2) { // BS4 if (css === "error") { css = "danger"; } css = "border-" + css; } $target.removeClass(css); }); if (remove) { return; } cssClass = statusClasses[Math.floor(cssClass / 2)]; if (options.ui.bootstrap3) { cssClass = "has-" + cssClass; } else if (!options.ui.bootstrap2) { // BS4 if (cssClass === "error") { cssClass = "danger"; } cssClass = "border-" + cssClass; } $target.addClass(cssClass); }; ui.percentage = function (options, score, maximun) { var result = Math.floor(100 * score / maximun), min = options.ui.progressBarMinPercentage; result = result <= min ? min : result; result = result > 100 ? 100 : result; return result; }; ui.getVerdictAndCssClass = function (options, score) { var level, verdict; if (score === undefined) { return ['', 0]; } if (score <= options.ui.scores[0]) { level = 0; } else if (score < options.ui.scores[1]) { level = 1; } else if (score < options.ui.scores[2]) { level = 2; } else if (score < options.ui.scores[3]) { level = 3; } else if (score < options.ui.scores[4]) { level = 4; } else { level = 5; } verdict = verdictKeys[level]; return [options.i18n.t(verdict), level]; }; ui.updateUI = function (options, $el, score) { var cssClass, barPercentage, verdictText, verdictCssClass; cssClass = ui.getVerdictAndCssClass(options, score); verdictText = score === 0 ? '' : cssClass[0]; cssClass = cssClass[1]; verdictCssClass = options.ui.useVerdictCssClass ? cssClass : -1; if (options.ui.showProgressBar) { if (score === undefined) { barPercentage = options.ui.progressBarEmptyPercentage; } else { barPercentage = ui.percentage(options, score, options.ui.scores[4]); } ui.updateProgressBar(options, $el, cssClass, barPercentage); if (options.ui.showVerdictsInsideProgressBar) { ui.updateVerdict(options, $el, verdictCssClass, verdictText); } } if (options.ui.showStatus) { ui.updateFieldStatus(options, $el, cssClass, score === undefined); } if (options.ui.showPopover) { ui.updatePopover(options, $el, verdictText, score === undefined); } else { if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar) { ui.updateVerdict(options, $el, verdictCssClass, verdictText); } if (options.ui.showErrors) { ui.updateErrors(options, $el, score === undefined); } } if (options.ui.showScore) { ui.updateScore(options, $el, score, score === undefined); } }; }(jQuery, ui)); // Source: src/methods.js var methods = {}; (function ($, methods) { "use strict"; var onKeyUp, onPaste, applyToAll; onKeyUp = function (event) { var $el = $(event.target), options = $el.data("pwstrength-bootstrap"), word = $el.val(), userInputs, verdictText, verdictLevel, score; if (options === undefined) { return; } options.instances.errors = []; if (word.length === 0) { score = undefined; } else { if (options.common.zxcvbn) { userInputs = []; $.each(options.common.userInputs.concat([options.common.usernameField]), function (idx, selector) { var value = $(selector).val(); if (value) { userInputs.push(value); } }); userInputs = userInputs.concat(options.common.zxcvbnTerms); score = zxcvbn(word, userInputs).guesses; score = Math.log(score) * Math.LOG2E; } else { score = rulesEngine.executeRules(options, word); } if ($.isFunction(options.common.onScore)) { score = options.common.onScore(options, word, score); } } ui.updateUI(options, $el, score); verdictText = ui.getVerdictAndCssClass(options, score); verdictLevel = verdictText[1]; verdictText = verdictText[0]; if (options.common.debug) { console.log(score + ' - ' + verdictText); } if ($.isFunction(options.common.onKeyUp)) { options.common.onKeyUp(event, { score: score, verdictText: verdictText, verdictLevel: verdictLevel }); } }; onPaste = function (event) { // This handler is necessary because the paste event fires before the // content is actually in the input, so we cannot read its value right // away. Therefore, the timeouts. var $el = $(event.target), word = $el.val(), tries = 0, callback; callback = function () { var newWord = $el.val(); if (newWord !== word) { onKeyUp(event); } else if (tries < 3) { tries += 1; setTimeout(callback, 100); } }; setTimeout(callback, 100); }; methods.init = function (settings) { this.each(function (idx, el) { // Make it deep extend (first param) so it extends also the // rules and other inside objects var clonedDefaults = $.extend(true, {}, defaultOptions), localOptions = $.extend(true, clonedDefaults, settings), $el = $(el); localOptions.instances = {}; $el.data("pwstrength-bootstrap", localOptions); $.each(localOptions.common.events, function (idx, eventName) { var handler = eventName === "paste" ? onPaste : onKeyUp; $el.on(eventName, handler); }); ui.initUI(localOptions, $el); $el.trigger("keyup"); if ($.isFunction(localOptions.common.onLoad)) { localOptions.common.onLoad(); } }); return this; }; methods.destroy = function () { this.each(function (idx, el) { var $el = $(el), options = $el.data("pwstrength-bootstrap"), elements = ui.getUIElements(options, $el); elements.$progressbar.remove(); elements.$verdict.remove(); elements.$errors.remove(); $el.removeData("pwstrength-bootstrap"); }); }; methods.forceUpdate = function () { this.each(function (idx, el) { var event = { target: el }; onKeyUp(event); }); }; methods.addRule = function (name, method, score, active) { this.each(function (idx, el) { var options = $(el).data("pwstrength-bootstrap"); options.rules.activated[name] = active; options.rules.scores[name] = score; options.rules.extra[name] = method; }); }; applyToAll = function (rule, prop, value) { this.each(function (idx, el) { $(el).data("pwstrength-bootstrap").rules[prop][rule] = value; }); }; methods.changeScore = function (rule, score) { applyToAll.call(this, rule, "scores", score); }; methods.ruleActive = function (rule, active) { applyToAll.call(this, rule, "activated", active); }; methods.ruleIsMet = function (rule) { var rulesMetCnt = 0; if (rule === "wordMinLength") { rule = "wordMinLengthStaticScore"; } else if (rule === "wordMaxLength") { rule = "wordMaxLengthStaticScore"; } this.each(function (idx, el) { var options = $(el).data("pwstrength-bootstrap"), ruleFunction = rulesEngine.validation[rule], result; if (!$.isFunction(ruleFunction)) { ruleFunction = options.rules.extra[rule]; } if ($.isFunction(ruleFunction)) { result = ruleFunction(options, $(el).val(), 1); if ($.isNumeric(result)) { rulesMetCnt += result; } } }); return (rulesMetCnt === this.length); }; $.fn.pwstrength = function (method) { var result; if (methods[method]) { result = methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === "object" || !method) { result = methods.init.apply(this, arguments); } else { $.error("Method " + method + " does not exist on jQuery.pwstrength-bootstrap"); } return result; }; }(jQuery, methods)); }(jQuery));
tejoesperanto/pasportaservo
pasportaservo/static/pwstrength/js/pwstrength-bootstrap.js
JavaScript
agpl-3.0
30,423
/* * bootstrap-table - v1.2.4 - 2014-10-08 * https://github.com/wenzhixin/bootstrap-table * Copyright (c) 2014 zhixin wen * Licensed MIT License */ !function(a){"use strict";a.extend(a.fn.bootstrapTable.defaults,{formatLoadingMessage:function(){return"Cargando, espere por favor..."},formatRecordsPerPage:function(a){return a+" registros por página"},formatShowingRows:function(a,b,c){return"Mostrando "+a+" a "+b+" de "+c+" filas"},formatSearch:function(){return"Buscar"},formatNoMatches:function(){return"No se encontraron registros"}})}(jQuery);
bakasajoshua/web-lims-old
assets/bower_components/bootstrap-table/dist/locale/bootstrap-table-es_AR.min.js
JavaScript
lgpl-3.0
549
//// [tests/cases/conformance/types/import/importTypeGenericTypes.ts] //// //// [foo.ts] interface Point<T> { x: number; y: number; data: T; } export = Point; //// [foo2.ts] namespace Bar { export interface I<T> { a: string; b: number; data: T; } } export namespace Baz { export interface J<T> { a: number; b: string; data: T; } } class Bar<T> { item: Bar.I<T>; constructor(input: Baz.J<T>) {} } export { Bar } //// [usage.ts] export const x: import("./foo")<{x: number}> = { x: 0, y: 0, data: {x: 12} }; export let y: import("./foo2").Bar.I<{x: number}> = { a: "", b: 0, data: {x: 12} }; export class Bar2<T> { item: {a: string, b: number, c: object, data: T}; constructor(input?: any) {} } export let shim: typeof import("./foo2") = { Bar: Bar2 }; //// [foo.js] "use strict"; exports.__esModule = true; //// [foo2.js] "use strict"; exports.__esModule = true; exports.Bar = void 0; var Bar = /** @class */ (function () { function Bar(input) { } return Bar; }()); exports.Bar = Bar; //// [usage.js] "use strict"; exports.__esModule = true; exports.shim = exports.Bar2 = exports.y = exports.x = void 0; exports.x = { x: 0, y: 0, data: { x: 12 } }; exports.y = { a: "", b: 0, data: { x: 12 } }; var Bar2 = /** @class */ (function () { function Bar2(input) { } return Bar2; }()); exports.Bar2 = Bar2; exports.shim = { Bar: Bar2 }; //// [foo.d.ts] interface Point<T> { x: number; y: number; data: T; } export = Point; //// [foo2.d.ts] declare namespace Bar { interface I<T> { a: string; b: number; data: T; } } export declare namespace Baz { interface J<T> { a: number; b: string; data: T; } } declare class Bar<T> { item: Bar.I<T>; constructor(input: Baz.J<T>); } export { Bar }; //// [usage.d.ts] export declare const x: import("./foo")<{ x: number; }>; export declare let y: import("./foo2").Bar.I<{ x: number; }>; export declare class Bar2<T> { item: { a: string; b: number; c: object; data: T; }; constructor(input?: any); } export declare let shim: typeof import("./foo2");
Microsoft/TypeScript
tests/baselines/reference/importTypeGenericTypes.js
JavaScript
apache-2.0
2,330