code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (global){ var Model = require("model-js"); var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null); function MyComponent(){ var my = new Model(); my.el = document.createElement("h1"); my.count = 0; my.when("count", function (count){ d3.select(my.el).text(count); }); setInterval(function (){ my.count++; }, 1000); return my; } var myComponent = new MyComponent(); document.getElementById("container").appendChild(myComponent.el); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"model-js":2}],2:[function(require,module,exports){ // ModelJS v0.2.1 // // https://github.com/curran/model // // Last updated by Curran Kelleher March 2015 // // Includes contributions from // // * github.com/mathiasrw // * github.com/bollwyvl // * github.com/adle29 // * github.com/Hypercubed // // The module is defined inside an immediately invoked function // so it does not pullute the global namespace. (function(){ // Returns a debounced version of the given function. // See http://underscorejs.org/#debounce function debounce(callback){ var queued = false; return function () { if(!queued){ queued = true; setTimeout(function () { queued = false; callback(); }, 0); } }; } // Returns true if all elements of the given array are defined, false otherwise. function allAreDefined(arr){ return !arr.some(function (d) { return typeof d === 'undefined' || d === null; }); } // The constructor function, accepting default values. function Model(defaults){ // Make sure "new" is always used, // so we can use "instanceof" to check if something is a Model. if (!(this instanceof Model)) { return new Model(defaults); } // `model` is the public API object returned from invoking `new Model()`. var model = this, // The internal stored values for tracked properties. { property -> value } values = {}, // The callback functions for each tracked property. { property -> [callback] } listeners = {}, // The set of tracked properties. { property -> true } trackedProperties = {}; // The functional reactive "when" operator. // // * `properties` An array of property names (can also be a single property string). // * `callback` A callback function that is called: // * with property values as arguments, ordered corresponding to the properties array, // * only if all specified properties have values, // * once for initialization, // * whenever one or more specified properties change, // * on the next tick of the JavaScript event loop after properties change, // * only once as a result of one or more synchronous changes to dependency properties. function when(properties, callback, thisArg){ // Make sure the default `this` becomes // the object you called `.on` on. thisArg = thisArg || this; // Handle either an array or a single string. properties = (properties instanceof Array) ? properties : [properties]; // This function will trigger the callback to be invoked. var listener = debounce(function (){ var args = properties.map(function(property){ return values[property]; }); if(allAreDefined(args)){ callback.apply(thisArg, args); } }); // Trigger the callback once for initialization. listener(); // Trigger the callback whenever specified properties change. properties.forEach(function(property){ on(property, listener); }); // Return this function so it can be removed later with `model.cancel(listener)`. return listener; } // Adds a change listener for a given property with Backbone-like behavior. // Similar to http://backbonejs.org/#Events-on function on(property, callback, thisArg){ thisArg = thisArg || this; getListeners(property).push(callback); track(property, thisArg); } // Gets or creates the array of listener functions for a given property. function getListeners(property){ return listeners[property] || (listeners[property] = []); } // Tracks a property if it is not already tracked. function track(property, thisArg){ if(!(property in trackedProperties)){ trackedProperties[property] = true; values[property] = model[property]; Object.defineProperty(model, property, { get: function () { return values[property]; }, set: function(newValue) { var oldValue = values[property]; values[property] = newValue; getListeners(property).forEach(function(callback){ callback.call(thisArg, newValue, oldValue); }); } }); } } // Cancels a listener returned by a call to `model.when(...)`. function cancel(listener){ for(var property in listeners){ off(property, listener); } } // Removes a change listener added using `on`. function off(property, callback){ listeners[property] = listeners[property].filter(function (listener) { return listener !== callback; }); } // Sets all of the given values on the model. // `newValues` is an object { property -> value }. function set(newValues){ for(var property in newValues){ model[property] = newValues[property]; } } // Transfer defaults passed into the constructor to the model. set(defaults); // Public API. model.when = when; model.cancel = cancel; model.on = on; model.off = off; model.set = set; } // Model.None is A representation for an optional Model property that is not specified. // Model property values of null or undefined are not propagated through // to when() listeners. If you want the when() listener to be invoked, but // some of the properties may or may not be defined, you can use Model.None. // This way, the when() listener is invoked even when the value is Model.None. // This allows the "when" approach to support optional properties. // // For example usage, see this scatter plot example with optional size and color fields: // http://bl.ocks.org/curran/9e04ccfebeb84bcdc76c // // Inspired by Scala's Option type. // See http://alvinalexander.com/scala/using-scala-option-some-none-idiom-function-java-null Model.None = "__NONE__"; // Support AMD (RequireJS), CommonJS (Node), and browser globals. // Inspired by https://github.com/umdjs/umd if (typeof define === "function" && define.amd) { define([], function () { return Model; }); } else if (typeof exports === "object") { module.exports = Model; } else { this.Model = Model; } })(); },{}]},{},[1]);
ralic/screencasts
introToChiasm/examples/code/snapshot05/main-build.js
JavaScript
mit
7,522
// flow-typed signature: a9e6b6a42d99c07ac6fbcc497ee3edaf // flow-typed version: <<STUB>>/postcss-loader_v^1.1.1/flow_v0.36.0 /** * This is an autogenerated libdef stub for: * * 'postcss-loader' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'postcss-loader' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'postcss-loader/error' { declare module.exports: any; } // Filename aliases declare module 'postcss-loader/error.js' { declare module.exports: $Exports<'postcss-loader/error'>; } declare module 'postcss-loader/index' { declare module.exports: $Exports<'postcss-loader'>; } declare module 'postcss-loader/index.js' { declare module.exports: $Exports<'postcss-loader'>; }
aleksei0807/react-components-boilerplate
flow-typed/npm/postcss-loader_vx.x.x.js
JavaScript
mit
1,054
/** * @class * @extends {Subclass.Property.Type.Collection.Collection} */ Subclass.Property.Type.Collection.ObjectCollection.ObjectCollection = (function() { /** * @inheritDoc */ function ObjectCollection() { ObjectCollection.$parent.apply(this, arguments); } ObjectCollection.$parent = Subclass.Property.Type.Collection.Collection; /** * @inheritDoc * * @param {string} key * @param {*} value * @param {boolean} normalize */ ObjectCollection.prototype.add = function(key, value, normalize) { var result; if (!key || typeof key != 'string') { Subclass.Error.create('InvalidArgument') .argument('the key of object collection item', false) .expected('a string') .received(key) .apply() ; } if (arguments.length < 2) { Subclass.Error.create( 'Method Subclass.Property.Type.Collection.ObjectCollection.ObjectCollection#add ' + 'requires at least two arguments.' ); } if ((result = ObjectCollection.$parent.prototype.add.apply(this, arguments)) === false) { return false; } if (normalize !== false) { this.normalize(key); } return result; }; /** * @inheritDoc */ ObjectCollection.prototype.addItems = function(items) { this._validateItems(items); for (var key in items) { if (items.hasOwnProperty(key)) { this.add(key, items[key], false); } } this.normalizeItems(); }; /** * @inheritDoc * * @param {string} key * @param {*} value * @param {boolean} normalize */ ObjectCollection.prototype.set = function(key, value, normalize) { if (ObjectCollection.$parent.prototype.set.apply(this, arguments) === false) { return false; } if (normalize !== false) { this.normalize(key); } return this._items.get(key); }; /** * @inheritDoc */ ObjectCollection.prototype.setItems = function(items) { this._validateItems(items); for (var key in items) { if (items.hasOwnProperty(key)) { this.set(key, items[key], false); } } this.normalizeItems(); }; /** * Normalizes collection elements */ ObjectCollection.prototype.normalizeItems = function() { var $this = this; this.forEach(function(itemValue, itemKey) { $this.normalize(itemKey); }); }; /** * Normalizes specified collection item * * @param itemName * @returns {*} */ ObjectCollection.prototype.normalize = function(itemName) { var itemData = this._items.get(itemName).getData(); if ( this._property.getDefinition().getProto().type != 'map' || !itemData.extends ) { return itemData; } if (!this.isset(itemData.extends)) { Subclass.Error.create( 'Trying to extend object collection element "' + itemName + '" ' + 'by non existent another collection element with key "' + itemData.extends + '".' ); } var parentItem = Subclass.Tools.copy(this.normalize(itemData.extends)); delete itemData.extends; function prepareItemData(itemProperty, itemData) { if (itemProperty.getType() == 'map') { var children = itemProperty.getChildren(); for (var childName in children) { if (!children.hasOwnProperty(childName)) { continue; } if (!children[childName].isDefaultValue()) { prepareItemData(children[childName], itemData[childName]); } else { delete itemData[childName]; } } } } for (var propName in itemData) { if (!itemData.hasOwnProperty(propName)) { continue; } var itemChild = this._items.get(itemName).getChild(propName); if (itemChild.isDefaultValue()) { delete itemData[propName]; } else { prepareItemData(itemChild, itemData[propName]); } } itemData = Subclass.Tools.extendDeep(parentItem, itemData); this.set(itemName, itemData); return itemData; }; /** * Returns all collection items keys * * @returns {string[]} */ ObjectCollection.prototype.keys = function() { return Object.keys(this._items.getItems()); }; /** * Sorts out all collection items using passed callback function * * @param {Function} callback * Function that will perform each collection item */ ObjectCollection.prototype.forEach = function(callback) { if (this._property.getDefinition().getProto().type != 'map') { return ObjectCollection.$parent.prototype.forEach.apply(this, arguments); } if (arguments.length == 2 && typeof arguments[1] == 'function') { callback = arguments[1]; } if (typeof callback != 'function') { Subclass.Error.create('InvalidArgument') .argument('the callback', false) .received(callback) .expected('a function') .apply() ; } var items = this._items.getItems(); var priorities = []; var $this = this; for (var itemName in items) { if (items.hasOwnProperty(itemName)) { var itemProperty = items[itemName]; priorities.push(itemProperty.getValue().priority); } } priorities = priorities.sort(function(a, b) { a = parseInt(a); b = parseInt(b); if (a > b) return -1; if (a < b) return 1; return 0; }); for (var i = 0; i < priorities.length; i++) { for (itemName in items) { if (!items.hasOwnProperty(itemName)) { continue; } itemProperty = items[itemName]; var itemValue = itemProperty.getValue(); if (itemValue.priority == priorities[i]) { if (callback.call($this, itemValue, itemName) === false) { return false; } } } } }; /** * @inheritDoc */ ObjectCollection.prototype.getData = function() { var collectionItems = {}; var $this = this; this.forEach(function(itemValue, itemName) { collectionItems[itemName] = $this._items.get(itemName).getData(); }); return collectionItems; }; return ObjectCollection; })();
msdoom2011/subclass-property
src/Type/Collection/ObjectCollection/ObjectCollection.js
JavaScript
mit
7,218
/** # progress-bar(百分比進度條)[component] ## 更新訊息 原始來源: 無 最後編輯者: Hank Kuo 最後修改日期: 2013/10/30 更新資訊: 時間 | 版本 | 說明 | 編輯人 ---------- | ---- | --------------------- | ---- 2013.10.30 | 1.0 | 建立元件 | Hank Kuo ## 相依套件與檔案 #### 相依第三方套件 vendor/bootsrap/ 版本:v3(flatty樣板版本) #### 相依元件 #### 相依外部檔案與目錄 ## 相依後端I/O ## 參數說明與使用教學 #### controller: 參數範例: ``` progressbarData: function() { return { width: 300, height: 20, persentage: 50, type: 'success' } }.property(); ``` 使用範例: ``` // 改變進度條百分比 this.set('progressbarData.persentage', 30); ``` #### template: ``` {{progress-bar options=progressbarData}} ``` @class progress-bar @since 1.0 */ /** ###### 進度條寬度 @property width @type Integer @default 260 @optional **/ /** ###### 進度條寬度 @property height @type Integer @default 10 @optional **/ /** ###### 進度條類型 選項: 1. 'info'(藍) 2. 'success'(綠) 3. 'warning'(黃) 4. 'danger'(紅) @property type @type String @default 'info' @optional **/ /** ###### 進度條百分比 @property persentage @type Integer @default 0 @optional **/ var ProgressBarComponent = Ember.Component.extend({ //tagName: 'div', //classNames: ['progress'], /* classNameBindings: ['progressStriped', 'active', 'progress-info', 'progress-success', 'progress-warning', 'progress-danger'], // 設定哪些class要連動控制 progressStripedBindings: ['progressStriped'], // 連接外面傳進來給component的參數progressStriped activeBindings: ['active'], progressInfoBindings: ['progress-info'], progressSuccessBindings: ['progress-success'], progressWaringBindings: ['progress-waring'], progressDangerBindings: ['progress-danger'], */ classNames: ['component-progress-bar'], persentageWidth: function() { return 'width: ' + this.get('options').persentage + '%'; }.property('this.options.persentage'), // 設定綁定this.persentage, 這樣外面傳入參數改變就會動態改變數值 progressbarStyle: function() { if (!this.get('options')) { throw new Error('component(progressbar): 無progressbar資料'); } var typeSelector = function(type) { var outputType = 'progress-bar-info'; switch (type) { case 'success': outputType = 'progress-bar-success'; break; case 'warning': outputType = 'progress-bar-warning'; break; case 'danger': outputType = 'progress-bar-danger'; break; } return outputType; }; var output = 'progress-bar ' + typeSelector(this.get('options').type); /* if (this.get('options').striped) { output += ' progress-striped'; } if (this.get('options').animated) { output += ' active'; } */ return output; }.property(), didInsertElement: function() { var options = { width: this.get('options').width || 260, height: this.get('options').height || 10, //persentage: this.get('options').persentage || 0 }; var self = '#' + $(this.get('element')).attr('id'); // 設定寬度 $(self + ' .progress').css('width', options.width); // 設定高度 $(self + ' .progress').css('height', options.height); } }); export default ProgressBarComponent;
hank7444/ember1.81_pratice
tmp/javascript/app/components/progress-bar.js
JavaScript
mit
3,888
/* * jQuery UI Virtual Keyboard Autocomplete v1.4 for Keyboard v1.8+ only * * By Rob Garrison (aka Mottie & Fudgey) * Licensed under the MIT License * * Use this extension with the Virtual Keyboard to get * the jQuery UI Autocomplete widget to work seamlessly * * Requires: * jQuery * jQuery UI & css * Keyboard plugin : https://github.com/Mottie/Keyboard * * Setup: * $('.ui-keyboard-input') * .keyboard(options) * .autocomplete(options) * .addAutoComplete(); * * // or if targeting a specific keyboard * $('#keyboard1') * .keyboard(options) // keyboard plugin * .autocomplete(options) // jQuery UI autocomplete * .addAutoComplete(); // this keyboard extension * */ /*jshint browser:true, jquery:true, unused:false */ (function($){ "use strict"; $.fn.addAutocomplete = function(){ return this.each(function(){ // make sure a keyboard is attached var base = $(this).data('keyboard'); if (!base) { return; } // jQuery UI versions 1.9+ are different base.autocomplete_new_version = parseFloat($.ui.version) >= 1.9; // Setup base.autocomplete_init = function(txt, delay, accept){ // visible event is fired before this extension is initialized, so check! if (base.options.alwaysOpen && base.isVisible()) { base.autocomplete_setup(); } base.$el .bind('visible.keyboard',function(){ base.autocomplete_setup(); }) .bind('change.keyboard',function(){ if (base.hasAutocomplete && base.isVisible()) { base.$el .val(base.$preview.val()) .trigger('keydown.autocomplete'); } }) .bind('hidden.keyboard', function(e){ base.$el.autocomplete('close'); }) .bind('autocompleteopen', function(e, ui) { if (base.hasAutocomplete){ // reposition autocomplete window next to the keyboard base.$el.data('autocomplete').menu.element.position({ of : base.$keyboard, my : 'right top', at : 'left top', collision: 'flip' }); } }) .bind('autocompleteselect', function(e,ui){ var v = ui.item.value; if (base.hasAutocomplete && v !== ''){ base.$preview .val( v ) .focus(); // see issue #95 - thanks banku! base.lastCaret = { start: v.length, end: v.length }; } }); }; // set up after keyboard is visible base.autocomplete_setup = function(){ // look for autocomplete base.$autocomplete = base.$el.data('autocomplete'); base.hasAutocomplete = (typeof(base.$autocomplete) === 'undefined') ? false : (base.$autocomplete.options.disabled) ? false : true; // only bind to keydown once if (base.hasAutocomplete && !base.autocomplete_bind) { base.$preview.bind('keydown',function(e){ // send keys to the autocomplete widget (arrow, pageup/down, etc) return base.autocomplete_input(e); }); base.$allKeys.bind('mouseup mousedown mouseleave touchstart touchend touchcancel',function(e){ base.autocomplete_input(e); }); base.autocomplete_bind = true; } }; // Navigate and select inside autocomplete popup base.autocomplete_input = function(event){ // copied from jquery ui autocomplete code to include autocomplete navigation // there might be a better workaround var t, keyCode = $.ui.keyCode; switch( event.keyCode ) { case keyCode.PAGE_UP: base.$autocomplete._move( "previousPage", event ); event.preventDefault(); // stop page from moving up break; case keyCode.PAGE_DOWN: base.$autocomplete._move( "nextPage", event ); event.preventDefault(); // stop page from moving down break; case keyCode.UP: base.$autocomplete._move( "previous", event ); // prevent moving cursor to beginning of text field in some browsers event.preventDefault(); break; case keyCode.DOWN: base.$autocomplete._move( "next", event ); // prevent moving cursor to end of text field in some browsers event.preventDefault(); break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: t = base.$autocomplete.menu.element.find('#ui-active-menuitem,.ui-state-focus').text() || ''; if (t !== '') { base.$preview.val(t); } if (base.autocomplete_new_version) { base.$autocomplete.menu.select( event ); } break; default: // keypress is triggered before the input value is changed clearTimeout( base.$autocomplete.searching ); base.$autocomplete.searching = setTimeout(function() { // only search if the value has changed if ( base.$autocomplete.term !== base.$autocomplete.element.val() ) { base.$autocomplete.selectedItem = null; base.$autocomplete.search( null, event ); } }, base.$autocomplete.options.delay ); break; } }; base.origEscClose = base.escClose; // replace original function with this one base.escClose = function(e){ // prevent selecting an item in autocomplete from closing keyboard if ( base.hasAutocomplete && (e.target.id === 'ui-active-menuitem' || $(e.target).hasClass('ui-state-focus')) ) { return; } base.origEscClose(e); }; base.autocomplete_init(); }); }; })(jQuery);
ilam/hci
lab2/js/jquery.keyboard.extension-autocomplete.js
JavaScript
mit
5,131
'use strict' const _ = require('lodash') const express = require('express') const resolver = require('deep-equal-resolver')() module.exports = _.memoize((state) => { const router = new express.Router() const mw = require('./middleware')(state) router.param('id', (req, res, next, id) => { if (id === 'me') return next('route') next() }) router.route('/') .get(mw.formatQuery, mw.find) .post(mw.create) router.route('/:id') .get(mw.findById) .put(mw.update) .patch(mw.update) .delete(mw.remove) return router }, resolver)
thebitmill/midwest-membership-services
users/router.js
JavaScript
mit
574
$(document).ready(function() { objRegistration = new Registration(); objRegistration.init(); }); function Registration() { this.intWindowHeight = $(window).height(); this.init = function() { if($('[data-toggle="popover"]').length){ $('[data-toggle="popover"]').popover({ html : true }); } if($('#frmIsbn').length){ $('#frmIsbn #isbn_code').on('keyup', function(e) {if(e.which == 13) {objRegistration.checkBook('frmIsbn');}}); } }; /* 해당 기능 보류 this.animateBtn = function(ele){ //animate top 58 var eTop = ele.offset().top; console.log('eTop'+eTop); var intEleWindowPosition = eTop - $(window).scrollTop(); console.log('intEleWindowPosition'+intEleWindowPosition); console.log('objRegistration.intWindowHeight/2'+objRegistration.intWindowHeight/2); var windowBottom = $(window).scrollTop() + $(window).height(); var submitBtnBottom = $('.submit_btn').offset().top+$('.submit_btn').outerHeight();; console.log('winbot :'+windowBottom); console.log('submitbottom : '+submitBtnBottom); if( (objRegistration.intWindowHeight/2 <= intEleWindowPosition) ){ //animate next question div to window center var nextETop = ele.next().offset().top; var intEleScrollerTop = nextETop - objRegistration.intWindowHeight/2; if( (windowBottom<submitBtnBottom) ){ $('html, body').animate({scrollTop:intEleScrollerTop}, 200); }else{ $('html, body').animate({scrollTop: (submitBtnBottom-$(window).height()) }, 200); } } }; */ this.setBook = function(strFrm){ $.ajax({ url : '/_connector/yellow.501.php', data : { 'viewID' : "SOMR_SET_BOOK", 'title' : $.trim($('#'+strFrm+' #title').val()), 'pub_name' : $.trim($('#'+strFrm+' #pub_name').val()), 'isbn_code' : $.trim($('#'+strFrm+' #isbn_code').val()), 'category_seq' : $('#'+strFrm+' #category_seq').val() }, type : 'POST', dataType : 'json', beforeSend: function() { if(!objRegistration.userFrmChk(strFrm)){ return false; } }, success : function(jsonResult) { if(jsonResult.boolResult){ halert('등록이 완료 되었습니다.'); // location.href="/smart_omr/exercise_book/registration_detail.php?bs="+jsonResult.str_book_seq; location.href="/smart_omr/exercise_book/detail.php?bs="+jsonResult.str_book_seq; }else{ switch(jsonResult.err_code){ case(1): halert(jsonResult.err_msg); break; default: halert("ISBN 코드번호를 확인하세요"); $('#'+strFrm+' ._d_btn_chk_isbn').css('display','block'); $('#'+strFrm+' ._d_btn_reg_isbn').css('display','none'); $('#'+strFrm+' ._d_btn_reg_isbn').unbind( "click" ); $('#'+strFrm+' ._d_cover_img').attr('src','/smart_omr/_images/default_cover.png'); break; } } } }); }; this.checkBook = function(strFrm){ $.ajax({ url : '/_connector/yellow.501.php', data : { 'viewID' : "SOMR_CHECK_BOOK", 'isbn_code' : $.trim($('#'+strFrm+' #isbn_code').val()) }, type : 'POST', dataType : 'json', beforeSend: function() { if(!objRegistration.userFrmChk(strFrm)){ return false; } }, success : function(jsonResult) { if(jsonResult.boolResult){ $('#'+strFrm+' ._d_btn_reg_isbn').css('display','block'); $('#'+strFrm+' ._d_btn_reg_isbn').on('click',function(){objRegistration.setBook(strFrm);}); $('#'+strFrm+' ._d_btn_chk_isbn').css('display','none'); $('#'+strFrm+' #isbn_code').attr('disabled',true); if(jsonResult.cover_url == "/smart_omr/_images/no_cover.png"){ $('#'+strFrm+' #no_cover_img').css('display','block'); }else{ $('#'+strFrm+' #no_cover_img').css('display','none'); } $('#'+strFrm+' ._d_cover_img').attr('src',jsonResult.cover_url); $('#'+strFrm+' ._d_book_info').css('display','block'); $('#'+strFrm+' ._d_book_info #book_title').html(jsonResult.title); $('#'+strFrm+' ._d_book_info #book_publisher').html(jsonResult.pub_name); }else{ halert(jsonResult.err_msg); } } }); }; this.saveTest = function(){ var options = { url : '/_connector/yellow.501.php', data : { 'viewID' : 'SOMR_SAVE_TEST' }, dataType : 'json', resetForm : false, type : 'post', // 'get' or 'post', override for form's 'method' // attribute beforeSubmit : function() { if(!objRegistration.userFrmChk('frmTest')){ return false; } }, success : function(jsonResult) { if (jsonResult.boolResult) { $('body').append('<form id="frmRegDetail"></form>'); $('#frmRegDetail').append('<input type="hidden" name="test_seq" value="'+jsonResult.test_seq+'">'); $('#frmRegDetail').append('<input type="hidden" name="book_seq" value="'+jsonResult.book_seq+'">'); $('#frmRegDetail').attr('method','post'); $('#frmRegDetail').attr('action','/smart_omr/exercise_book/registration_detail_activation.php'); $('#frmRegDetail').submit(); }else{ if(typeof jsonResult.error_msg!='undefined' && jsonResult.error_msg!=''){ halert(jsonResult.error_msg); }else{ halert("테스트 저장 오류!"); } } } }; $('#frmTest').ajaxSubmit(options); }; this.saveTestQuestionWithAnswer = function(){ var options = { url : '/_connector/yellow.501.php', data : { 'viewID' : 'SOMR_SAVE_TEST_QUESTION_WITH_ANSWER' }, dataType : 'json', resetForm : false, type : 'post', // 'get' or 'post', override for form's 'method' // attribute beforeSubmit : function() { return (true); }, success : function(jsonResult) { if (jsonResult.boolResult) { $(location).attr('href','/smart_omr/exercise_book/detail.php?bs='+jsonResult.str_book_seq); }else{ halert("테스트 저장 오류!"); } } }; $('#frmQuestion').ajaxSubmit(options); }; this.submitQuestionAnswer = function(){ var options = { url : '/_connector/yellow.501.php', data : { 'viewID' : 'SOMR_SUBMIT_QUESTION_ANSWER' }, dataType : 'json', resetForm : true, type : 'post', // 'get' or 'post', override for form's 'method' // attribute beforeSubmit : function() { if(!$('.ans_correct .btn-default.active').length){return confirm('한문제도 선택되지 않앗습니다. 그대로 제출하시겠습니까?');} }, success : function(jsonResult) { if (jsonResult.boolResult) { halert('답안이 전송되었습니다.'); location.href="/smart_omr/exercise_book/test_result.php?t="+jsonResult.str_test_seq; }else{ halert("테스트 저장 오류!"); } } }; $('#frmUserAnswer').ajaxSubmit(options); }; this.insertSingleQuestion = function(intQuestionSeq){ if(hconfirm('해당 문제 밑에 문제를 추가 하시겠습니까?')){ return false; } //get last question seq intQuestionSeq = intQuestionSeq?intQuestionSeq:$('.question_div').eq(($('.question_div').length)-1).attr('data-question-seq'); //get first order_number for reset order number var firstOrderNumber = $('.order_number').eq(0).val(); console.log('question::'+intQuestionSeq); console.log('order::'+firstOrderNumber); console.log('order_number:::'+$('#question_'+intQuestionSeq+' #order_number_'+intQuestionSeq).val()); var sendData = { 'viewID':'INSERT_SINGLE_QUESTION', 'test_seq':$('#frmQuestion #test_seq').val(), 'order_number':$('#question_'+intQuestionSeq+' #order_number_'+intQuestionSeq).val(), 'question_score':$('#question_'+intQuestionSeq+' #question_score_'+intQuestionSeq).val(), 'question_type':$('#question_'+intQuestionSeq+' #question_type_'+intQuestionSeq).val() } $.ajax({ url : '/_connector/yellow.501.php', data : sendData, type : 'POST', dataType : 'json', success : function(jsonResult) { if(jsonResult.boolResult){ console.log("return questionseq : "+jsonResult.question_seq); objRegistration.appendSingleQuestion(sendData.test_seq,intQuestionSeq,jsonResult.question_seq,function(){ objRegistration.autoSetOrderNumber(jsonResult.question_seq,jsonResult.order_number,firstOrderNumber); $('#question_'+jsonResult.question_seq).effect( "highlight",{},2000 ); /* $('.question_score').unbind('keyup'); $('.question_score').keyup(function(){objRegistration.updateQuestionTotalInfo();}); $('.order_number').unbind('keyup'); $('.order_number').keyup(function(){ var intStartIndex = $('.order_number').index($(this)); for(i=intStartIndex;i<$('.order_number').length;i++){ if(i==intStartIndex){ var intOrderNo = eval($('.order_number').eq(i).val()) + 1; }else{ $('.order_number').eq(i).val(intOrderNo++); } } }); */ }); } } }); }; this.appendSingleQuestion = function(intTestsSeq,intBaseQuestionSeq,intAppendQuestionSeq,callBack){ $.ajax({ url : '/smart_omr/exercise_book/single_question_element.php', data : { 'test_seq':intTestsSeq, 'question_seq':intAppendQuestionSeq }, type : 'POST', success : function(resultHtml) { $('#question_'+intBaseQuestionSeq).after(resultHtml); //objRegistration.changeAnswerSelector($('#question_'+intAppendQuestionSeq+' #question_type_'+intAppendQuestionSeq)); //objRegistration.updateQuestionTotalInfo(); callBack.call(); } }); }; this.autoSetOrderNumber = function(intQuestionSeq,intMarkNumber,firstOrderNumber){ var intOrderNumber = firstOrderNumber?firstOrderNumber-1:0; $('#frmQuestion .question_div .order_number').each(function(index){ intOrderNumber ++; $(this).val(intOrderNumber); console.log('order:'+index); $('.order_number_sub').eq(index).html(intOrderNumber); }); }; this.deleteSingleQuestion = function(intQuestionSeq){ if(hconfirm('해당 문제 삭제 하시겠습니까?')){ return false; } //get first order_number for reset order number var firstOrderNumber = $('.order_number').eq(0).val(); var sendData = { 'viewID':'DELETE_SINGLE_QUESTION', 'test_seq':$('#frmQuestion #test_seq').val(), 'question_seq':intQuestionSeq } $.ajax({ url : '/_connector/yellow.501.php', data : sendData, type : 'POST', dataType : 'json', success : function(jsonResult) { if(jsonResult.boolResult){ $('#question_'+intQuestionSeq).remove(); //objRegistration.updateQuestionTotalInfo(); objRegistration.autoSetOrderNumber(); objRegistration.autoSetOrderNumber(null,null,firstOrderNumber); } } }); }; this.updateQuestionTotalInfo = function(){ var intQuestionCount = $('.question_seq').length; var intTestTotalScore = Number($('#test_total_score').val()); var intQuestionTotalScore = 0; $('.question_score').each(function(){ intQuestionTotalScore = intQuestionTotalScore + Number($(this).val()); }); $('#question_total_info #test_total_question').html(intQuestionCount); if(intQuestionTotalScore > intTestTotalScore){ $('#question_total_info #test_total_score').val(intQuestionTotalScore); //$('#test_over_score').html(intQuestionTotalScore-intTestTotalScore); }else{ $('#question_total_info #test_total_score').val(intQuestionTotalScore); //$('#test_over_score').html(0); } }; this.userFrmChk = function(strFrmId){ var boolReturn = true; $("#"+strFrmId+" ._d_chk_input").each(function(){ if( (typeof($(this).val())=="undefined" || $.trim($(this).val())=="") && $(this).is(":visible") ){ alert($(this).attr('placeholder')+"은(는) 필수 항목입니다."); $(this).focus(); return boolReturn = false; } if($(this).hasClass('_d_chk_input_email'))boolReturn=objValid.isValidEmailAddress($.trim($(this).val())); if($(this).hasClass('_d_chk_input_number'))boolReturn=objValid.isValidNumber($.trim($(this).val())); if($(this).hasClass('_d_chk_input_password'))boolReturn=objValid.isValidPassword($.trim($(this).val())); if($(this).hasClass('_d_chk_input_bizid'))boolReturn=objValid.isValidBizID($.trim($(this).val())); if(!boolReturn){ alert($(this).attr('placeholder_cs')); $(this).focus(); return boolReturn = false; } }); return(boolReturn); }; }
Mangongso/MamaOMR
View/smart_omr/_js/registration.js
JavaScript
mit
12,564
Template.locationBar.onRendered(function() { GoogleMaps.load({ v: '3', key: 'AIzaSyCc7dxUtKyvEVFk3o-nqvJptwvNxE5WDJo', libraries: 'places' }); Tracker.autorun( function(computation) { useCurrentLocation(computation); }); this.autorun(function () { if (GoogleMaps.loaded()) { try{ var userLocation = document.getElementById('location'); var autocomplete = new google.maps.places.Autocomplete(userLocation); google.maps.event.addListener(autocomplete, 'place_changed', function() { var place = autocomplete.getPlace(); var geometry = { "type": "Point", "coordinates": [place.geometry.location.lng(), place.geometry.location.lat()] }; Session.set('location', geometry); $('.use-current-location ').show() }); } catch(Error) { //todo throwError } } }); }); Template.locationBar.events( { 'click .use-current-location' : function(e) { useCurrentLocation(); } }) useCurrentLocation = function(computation) { if(Geolocation) { var ETSY_LAT = 40.702637; var ETSY_LNG = -73.989406; var currLocation = Geolocation.currentLocation(); var geometry = {"type": "Point"}; if(currLocation) { geometry.coordinates = [currLocation.coords.longitude, currLocation.coords.latitude]; if(computation) { computation.stop(); } useCurrentLocationMessaging(); } else { geometry.coordinates = [ETSY_LNG, ETSY_LAT]; } Session.set('location', geometry); } } var useCurrentLocationMessaging = function() { $('.use-current-location').hide() $("#location").attr("placeholder", "Using current location..."); $("#location").val(""); }
yala/eatsy
client/includes/locationBar.js
JavaScript
mit
2,093
import {Component} from '@angular/core'; export default class IconComponent { static get annotations() { return [ new Component({ template: require('./icon.html') }) ]; } constructor(){ } } IconComponent.parameters = [];
korosakikun/atlantis-ui
docs/src/app/icon/icon.component.js
JavaScript
mit
261
var Texture = require('../../../src/goo/renderer/Texture'); var CustomMatchers = require('../../../test/unit/CustomMatchers'); describe('Texture', function () { beforeEach(function () { jasmine.addMatchers(CustomMatchers); }); describe('create', function () { function testTypesAndFormats(data, defaultType, defaultFormat) { var settings = {}; var texture = new Texture(data, settings, 1, 1); expect(texture.image).not.toBeNull(); expect(texture.type).toEqual(defaultType); expect(texture.format).toEqual(defaultFormat); settings = { type: 'TestType', format: 'TestFormat' }; texture = new Texture(data, settings, 1, 1); expect(texture.type).toEqual('TestType'); expect(texture.format).toEqual('TestFormat'); } it('can create without parameters', function () { var texture = new Texture(); expect(texture.image).toBeNull(); }); it('can create with Uint8Array for various types/formats', function () { testTypesAndFormats(new Uint8Array(1), 'UnsignedByte', 'RGBA'); }); it('can create with Uint16Array for various types/formats', function () { testTypesAndFormats(new Uint16Array(1), 'UnsignedShort565', 'RGB'); }); it('can create with Float32Array for various types/formats', function () { testTypesAndFormats(new Float32Array(1), 'Float', 'RGBA'); }); }); describe('clone', function () { var exclusionList = ['image', '_originalImage', 'needsUpdate', 'loadImage']; it('can clone a texture holding no image', function () { var original = new Texture(); var clone = original.clone(); expect(clone).toBeCloned({ value: original, excluded: exclusionList }); }); it('can clone a texture holding a typed array', function () { var original = new Texture(new Uint8Array([11, 22, 33, 44]), {}, 1, 1); var clone = original.clone(); expect(clone).toBeCloned({ value: original, excluded: exclusionList }); }); it('can clone a texture holding an html element', function () { var images = [new Image()]; var original = new Texture(images[0]); var clone = original.clone(); expect(clone).toBeCloned({ value: original, excluded: exclusionList }); }); it('can clone a texture holding an 6 html elements', function () { var images = [new Image(), new Image(), new Image(), new Image(), new Image(), new Image()]; var original = new Texture(images); var clone = original.clone(); expect(clone).toBeCloned({ value: original, excluded: exclusionList }); }); }); });
GooTechnologies/goojs
test/unit/renderer/Texture-test.js
JavaScript
mit
2,504
/*global define,require */ /*jslint white:true,browser:true*/ define([ 'jquery', 'bluebird', 'kbwidget', 'base/js/namespace', 'util/timeFormat', 'narrativeConfig', 'kbase/js/widgets/narrative_core/objectCellHeader', 'api/upa' ], function ( $, Promise, KBWidget, Jupyter, TimeFormat, Config, ObjectCellHeader, UpaApi ) { 'use strict'; return KBWidget({ name: 'kbaseNarrativeOutputCell', version: '1.0.0', options: { widget: 'kbaseDefaultNarrativeOutput', data: '{}', cellId: null, type: 'error', title: 'Output', time: '', showMenu: true, lazyRender: true // used in init() }, isRendered: false, OUTPUT_ERROR_WIDGET: 'kbaseNarrativeError', headerShown: false, initMetadata: function () { var baseMeta = { kbase: { dataCell: {} } }; if (!this.cell) { return baseMeta; } else { var metadata = this.cell.metadata; if (!metadata || !metadata.kbase) { metadata = baseMeta; this.cell.metadata = metadata; } if (!metadata.kbase.dataCell) { metadata.kbase.dataCell = {}; } return metadata; } }, init: function (options) { // handle where options.widget == null. options.widget = options.widget || this.options.widget; // handle where options.widget == 'null' string. I know. It happens. options.widget = options.widget === 'null' ? this.options.widget : options.widget; this._super(options); this.upaApi = new UpaApi(); this.data = this.options.data; this.options.type = this.options.type.toLowerCase(); if (this.options.cellId) { this.cell = Jupyter.narrative.getCellByKbaseId(this.options.cellId); if (!this.cell) { var cellElem = $('#' + this.options.cellId).parents('.cell').data(); if (cellElem) { this.cell = cellElem.cell; } } if (this.cell) { this.cell.element.trigger('hideCodeArea.cell'); } } this.metadata = this.initMetadata(); if (this.cell) { this.handleUpas(); } /* * This sets up "lazy" rendering. * Cells that are not visible are not rendered initially. * To render them when they scroll into view, a handler is * added to the container that will check their visibility on * every scroll event. * XXX: Not sure whether "on every scroll event" is going to be * too heavy-weight a check once there are 100+ elements to worry about. */ if (Config.get('features').lazyWidgetRender) { var $nbContainer = $('#notebook-container'); this.visibleSettings = { container: $nbContainer, threshold: 100 }; this.lazyRender({data: this}); // try to render at first view if (!this.isRendered) { // Not initially rendered, so add handler to re-check after scroll events // $nbContainer.scroll(this, this.lazyRender); this.visibleSettings.container.scroll(this, this.lazyRender); } } /* For testing/comparison, do eager-rendering instead */ else { this.render(); } return this; }, /** * handle upas here! Needs to do the following: * - check cell metadata. if no field present for upas, drop them in. if present, use * them instead. * - might need to double check key names. maybe a silly user repurposed/re-ran the * cell? Should try to get the Python stack to reset the metadata in that case. * Not sure if that's possible. * - have cell header widget control which version of objects are seen. * - should auto-serialize on change * - should re-render widget as appropriate * - Finally, all widgets should take upas as inputs. Enforce that here. * - All widgets should have an 'upas' input that handles the mapping. Part of spec? * - Need to start writing widget spec / standard. Share with Jim & Erik & Steve/Shane * * useLocal - forces the serialization to use only the locally defined upas * in this.upas, NOT the ones in the cell metadata. */ handleUpas: function(useLocal) { // if useLocal, then drop the current values in this.upas into the metadata. // otherwise, if there's existing upas in metadata, supplant this.upas with those. if (!this.metadata.kbase.dataCell.upas) { // bail out silently if we don't have any upas, AND there's non in the cell meta. // This likely means that we're dealing with a non-updated Narrative. if (!this.options.upas) { return; } this.metadata.kbase.dataCell.upas = this.upaApi.serializeAll(this.options.upas); } else if (!useLocal && this.metadata.kbase.dataCell.upas) { this.options.upas = this.upaApi.deserializeAll(this.metadata.kbase.dataCell.upas); } else { this.metadata.kbase.dataCell.upas = this.upaApi.serializeAll(this.options.upas); } }, // Possibly render lazily not-yet-rendered cell lazyRender: function (event) { var self = event.data; if (self.isRendered) { // Note: We could also see if a cell that is rendered, is now // no longer visible, and somehow free its resources. return; } // see if it is visible before trying to render if (!self.inViewport(self.$elem, self.visibleSettings)) { return; } return self.render(); }, /** * Tests the current UPAs by testing to see if the user has permission to see them all. * If they don't, then we shouldn't even bother to try showing the viewer, and instead * show a permissions error instead. */ testUpas: function() { return {}; }, render: function () { // set up the widget line // todo find cell and trigger icon setting. var methodName = this.options.title ? this.options.title : 'Unknown App'; var title = methodName; var upaTest = this.testUpas(); if (upaTest.error) { this.renderError(upaTest.error); } if (this.cell) { var meta = this.cell.metadata; if (!meta.kbase) { meta.kbase = {}; } if (!meta.kbase.attributes) { meta.kbase.attributes = {}; } /* This is a bit of a hack - if the cell's metadata already has a title, * then don't change it. It was likely set by the creating App cell. * BUT this means that if someone manually executes the cell again to show * a different output, it still won't change, and might be weird. * * I suspect that will be a very rare case, and this solves an existing * problem with App cells, so here it is. */ if (!meta.kbase.attributes.title) { meta.kbase.attributes.title = title; } this.cell.metadata = meta; } this.$timestamp = $('<span>') .addClass('pull-right kb-func-timestamp'); if (this.options.time) { this.$timestamp.append($('<span>') .append(TimeFormat.readableTimestamp(this.options.time))); this.$elem.closest('.cell').find('.button_container').trigger('set-timestamp.toolbar', this.options.time); } if (this.isRendered) { // update the header this.headerWidget.updateUpas(this.options.upas); } else { if (this.$body) { this.$body.remove(); } var $headController = $('<div>').hide(); this.headerWidget = new ObjectCellHeader($headController, { upas: this.options.upas, versionCallback: this.displayVersionChange.bind(this), }); var $headerBtn = $('<button>') .addClass('btn btn-default kb-data-obj') .attr('type', 'button') .text('Details...') .click(function() { if (this.headerShown) { $headController.hide(); this.headerShown = false; } else { $headController.show(); this.headerShown = true; } }.bind(this)); this.$body = $('<div class="kb-cell-output-content">') .append($headController) .append($headerBtn); this.$elem.append(this.$body); } return this.renderBody() .then(function() { this.isRendered = true; }.bind(this)); }, renderBody: function() { var self = this; return new Promise(function(resolve) { var widget = self.options.widget, widgetData = self.options.data; if (widget === 'kbaseDefaultNarrativeOutput') { widgetData = { data: self.options.data }; } widgetData.upas = self.options.upas; require([widget], function (W) { if (self.$widgetBody) { self.$widgetBody.remove(); } self.$widgetBody = $('<div>'); self.$body.append(self.$widgetBody); self.$outWidget = new W(self.$widgetBody, widgetData); resolve(); }, // TODO: No, should reject the promise, or handle here and resolve, // otherwise on error the promise will dangle. function (err) { return self.renderError(err); } ); }); }, displayVersionChange: function(upaId, newVersion) { /* Modify upa. * Serialize. * re-render all the things. */ var newUpa = this.upaApi.changeUpaVersion(this.options.upas[upaId], newVersion); this.options.upas[upaId] = newUpa; this.handleUpas(true); this.render(); }, renderError: function(err) { // KBError('Output::' + this.options.title, 'failed to render output widget: "' + this.options.widget + '"'); this.options.title = 'App Error'; this.options.data = { error: { msg: 'An error occurred while showing your output:', method_name: 'kbaseNarrativeOutputCell.renderCell', type: 'Output', severity: '', traceback: err.stack } }; this.options.widget = this.OUTPUT_ERROR_WIDGET; return this.render(); }, getState: function () { var state = null; if (this.$outWidget && this.$outWidget.getState) { state = this.$outWidget.getState(); } return state; }, loadState: function (state) { if (state) { if (state.time) { this.$timestamp.html(TimeFormat.readableTimestamp(state.time)); } if (this.$outWidget && this.$outWidget.loadState) { this.$outWidget.loadState(state); } } }, /* ------------------------------------------------------- * Code modified from: * Lazy Load - jQuery plugin for lazy loading images * Copyright (c) 2007-2015 Mika Tuupola * Licensed under the MIT license * Project home: http://www.appelsiini.net/projects/lazyload */ inViewport: function (element, settings) { if (!element || !settings) { return true; } var fold = settings.container.offset().top + settings.container.height(), elementTop = $(element).offset().top - settings.threshold; return elementTop <= fold; // test if it is "above the fold" } /* End of Lazy Load code. * ------------------------------------------------------- */ }); });
briehl/narrative
kbase-extension/static/kbase/js/widgets/narrative_core/kbaseNarrativeOutputCell.js
JavaScript
mit
13,850
describe('gravatar directive', function() { var elm, eleHash; var scope; // load the localization code beforeEach(module('angularjs-gravatardirective')); beforeEach(inject(function($rootScope, $compile) { // we might move this tpl into an html file as well... elm = angular.element( '<gravatar-image data-gravatar-email="email" data-gravatar-size="120" data-gravatar-rating="pg" data-gravatar-default="identicon" data-gravatar-css-class="btn btn-large" ></gravatar-image>' ); elmHash = angular.element( '<gravatar-image data-gravatar-hash="hashedEmail" data-gravatar-size="120" data-gravatar-rating="pg" data-gravatar-default="identicon" data-gravatar-css-class="btn btn-large"></gravatar-image>' ); scope = $rootScope; scope.email = 'jlavin@jimlavin.net'; scope.hashedEmail = '7a5b7242f9370beb1eda421a109d9f77'; $compile(elm)(scope); $compile(elmHash)(scope); scope.$digest(); })); // scope it('should add image tag to the element', function() { var image = elm.html(); expect(image).toContain('<img'); }); it('should add md5 of the email address to the image tag', function() { var image = elm.html(); expect(image).toContain('80b03752791145a3fdd027b154d7b42b'); }); it('should add size parameter of 120 pixels to the image tag', function() { var image = elm.html(); expect(image).toContain('s=120'); }); it('should add a rating parameter of PG to the image tag', function() { var image = elm.html(); expect(image).toContain('r=pg'); }); it('should add a default image parameter of identicon to the image tag', function() { var image = elm.html(); expect(image).toContain('d=identicon'); }); it( 'should add a parse the data-cc-class attribute and assign it to the class attribute', function() { var cssClass = elm.html(); expect(cssClass).toContain('class="btn btn-large"'); }); // hash it('should add image tag to the element', function() { var image = elmHash.html(); expect(image).toContain('<img'); }); it('should add md5 of the email address to the image tag', function() { var image = elmHash.html(); expect(image).toContain('7a5b7242f9370beb1eda421a109d9f77'); }); it('should add size parameter of 120 pixels to the image tag', function() { var image = elmHash.html(); expect(image).toContain('s=120'); }); it('should add a rating parameter of PG to the image tag', function() { var image = elmHash.html(); expect(image).toContain('r=pg'); }); it('should add a default image parameter of identicon to the image tag', function() { var image = elmHash.html(); expect(image).toContain('d=identicon'); }); it( 'should add a parse the data-cc-class attribute and assign it to the class attribute', function() { var cssClass = elmHash.html(); expect(cssClass).toContain('class="btn btn-large"'); }); });
lavinjj/angularjs-gravatardirective
test/unit/angularjs-gravatardirective/directives/gravatar-directive-test.js
JavaScript
mit
2,870
const mime = require('mime-types') const path = require('path') const url = require('url') const paths = require('../../config/paths.config.js') const templatingConf = require('../../config/templating.config') const renderPage = require('./renderPage') const sh = require('kool-shell')() .use(require('kool-shell/plugins/log')) let pages // gracefulError display error both on the browser and the console, // to avoid breaking the auto-reload of browser-sync function gracefulError (res, err) { res.setHeader('Content-Type', 'text/html; charset=utf-8') res.end( `<html><head></head><body>` + `<p style="white-space:pre-wrap;word-wrap:break-word;` + `font-family:monospace;font-size:18px;color:red">${err}</p></body></html>` ) sh.error(err) } function getPageFromRoute (route) { for (let i = 0; i < pages.length; i++) { if (pages[i].output === route) return pages[i] } return false } function processTemplate (page, middleware) { renderPage(page, !!templatingConf.autoPartials) .then(rendered => { const contentType = mime.contentType(path.extname(page.output)) middleware.res.setHeader('Content-Type', contentType) middleware.res.end(rendered) }) .catch(err => gracefulError(middleware.res, err)) } function templateMiddleware (req, res, next) { delete require.cache[require.resolve(path.join(paths.src, 'pages'))] pages = require(path.join(paths.src, 'pages')) // parse url - append index.html to / if needed let fileUrl = url.parse(req.url).pathname if (fileUrl.slice(-1) === '/') fileUrl += 'index.html' fileUrl = fileUrl.slice(1) let page = getPageFromRoute(fileUrl) // if the current requested url match an existing route if (page) { processTemplate(page, {req, res, next}) // it's not for this middleware, skip this request } else { next() } } module.exports = templateMiddleware
brocessing/brocessing.github.io
scripts/utils/templateMiddleware.js
JavaScript
mit
1,891
"use strict"; function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _defaults(subClass, superClass); } var Prefixer = require('./prefixer'); var OldValue = require('./old-value'); var utils = require('./utils'); var vendor = require('postcss').vendor; var Value = /*#__PURE__*/ function (_Prefixer) { _inheritsLoose(Value, _Prefixer); function Value() { return _Prefixer.apply(this, arguments) || this; } /** * Clone decl for each prefixed values */ Value.save = function save(prefixes, decl) { var _this = this; var prop = decl.prop; var result = []; var _loop = function _loop(prefix) { var value = decl._autoprefixerValues[prefix]; if (value === decl.value) { return "continue"; } var item = void 0; var propPrefix = vendor.prefix(prop); if (propPrefix === '-pie-') { return "continue"; } if (propPrefix === prefix) { item = decl.value = value; result.push(item); return "continue"; } var prefixed = prefixes.prefixed(prop, prefix); var rule = decl.parent; if (!rule.every(function (i) { return i.prop !== prefixed; })) { result.push(item); return "continue"; } var trimmed = value.replace(/\s+/, ' '); var already = rule.some(function (i) { return i.prop === decl.prop && i.value.replace(/\s+/, ' ') === trimmed; }); if (already) { result.push(item); return "continue"; } var cloned = _this.clone(decl, { value: value }); item = decl.parent.insertBefore(decl, cloned); result.push(item); }; for (var prefix in decl._autoprefixerValues) { var _ret = _loop(prefix); if (_ret === "continue") continue; } return result; }; /** * Is declaration need to be prefixed */ var _proto = Value.prototype; _proto.check = function check(decl) { var value = decl.value; if (value.indexOf(this.name) === -1) { return false; } return !!value.match(this.regexp()); }; /** * Lazy regexp loading */ _proto.regexp = function regexp() { return this.regexpCache || (this.regexpCache = utils.regexp(this.name)); }; /** * Add prefix to values in string */ _proto.replace = function replace(string, prefix) { return string.replace(this.regexp(), "$1" + prefix + "$2"); }; /** * Get value with comments if it was not changed */ _proto.value = function value(decl) { if (decl.raws.value && decl.raws.value.value === decl.value) { return decl.raws.value.raw; } else { return decl.value; } }; /** * Save values with next prefixed token */ _proto.add = function add(decl, prefix) { if (!decl._autoprefixerValues) { decl._autoprefixerValues = {}; } var value = decl._autoprefixerValues[prefix] || this.value(decl); var before; do { before = value; value = this.replace(value, prefix); if (value === false) return; } while (value !== before); decl._autoprefixerValues[prefix] = value; }; /** * Return function to fast find prefixed value */ _proto.old = function old(prefix) { return new OldValue(this.name, prefix + this.name); }; return Value; }(Prefixer); module.exports = Value;
stephaniejn/stephaniejn.github.io
node_modules/autoprefixer/lib/value.js
JavaScript
mit
3,829
import { Injector, bind } from "angular2/di"; import { Reflector, reflector } from 'angular2/src/core/reflection/reflection'; import { Parser, Lexer, ChangeDetection, DynamicChangeDetection, JitChangeDetection, PreGeneratedChangeDetection } from 'angular2/src/core/change_detection/change_detection'; import { DEFAULT_PIPES } from 'angular2/pipes'; import { EventManager, DomEventsPlugin } from 'angular2/src/core/render/dom/events/event_manager'; import { Compiler, CompilerCache } from 'angular2/src/core/compiler/compiler'; import { BrowserDomAdapter } from 'angular2/src/core/dom/browser_adapter'; import { KeyEventsPlugin } from 'angular2/src/core/render/dom/events/key_events'; import { HammerGesturesPlugin } from 'angular2/src/core/render/dom/events/hammer_gestures'; import { AppViewPool, APP_VIEW_POOL_CAPACITY } from 'angular2/src/core/compiler/view_pool'; import { Renderer, RenderCompiler } from 'angular2/src/core/render/api'; import { AppRootUrl } from 'angular2/src/core/services/app_root_url'; import { DomRenderer, DOCUMENT, DefaultDomCompiler, APP_ID_RANDOM_BINDING, MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE, TemplateCloner } from 'angular2/src/core/render/render'; import { ElementSchemaRegistry } from 'angular2/src/core/render/dom/schema/element_schema_registry'; import { DomElementSchemaRegistry } from 'angular2/src/core/render/dom/schema/dom_element_schema_registry'; import { SharedStylesHost, DomSharedStylesHost } from 'angular2/src/core/render/dom/view/shared_styles_host'; import { DOM } from 'angular2/src/core/dom/dom_adapter'; import { NgZone } from 'angular2/src/core/zone/ng_zone'; import { AppViewManager } from 'angular2/src/core/compiler/view_manager'; import { AppViewManagerUtils } from 'angular2/src/core/compiler/view_manager_utils'; import { AppViewListener } from 'angular2/src/core/compiler/view_listener'; import { ProtoViewFactory } from 'angular2/src/core/compiler/proto_view_factory'; import { ViewResolver } from 'angular2/src/core/compiler/view_resolver'; import { ViewLoader } from 'angular2/src/core/render/dom/compiler/view_loader'; import { DirectiveResolver } from 'angular2/src/core/compiler/directive_resolver'; import { ExceptionHandler } from 'angular2/src/core/exception_handler'; import { ComponentUrlMapper } from 'angular2/src/core/compiler/component_url_mapper'; import { StyleInliner } from 'angular2/src/core/render/dom/compiler/style_inliner'; import { DynamicComponentLoader } from 'angular2/src/core/compiler/dynamic_component_loader'; import { StyleUrlResolver } from 'angular2/src/core/render/dom/compiler/style_url_resolver'; import { UrlResolver } from 'angular2/src/core/services/url_resolver'; import { Testability } from 'angular2/src/core/testability/testability'; import { XHR } from 'angular2/src/core/render/xhr'; import { XHRImpl } from 'angular2/src/core/render/xhr_impl'; import { Serializer } from 'angular2/src/web_workers/shared/serializer'; import { ON_WEB_WORKER } from 'angular2/src/web_workers/shared/api'; import { RenderProtoViewRefStore } from 'angular2/src/web_workers/shared/render_proto_view_ref_store'; import { RenderViewWithFragmentsStore } from 'angular2/src/web_workers/shared/render_view_with_fragments_store'; import { AnchorBasedAppRootUrl } from 'angular2/src/core/services/anchor_based_app_root_url'; import { WebWorkerApplication } from 'angular2/src/web_workers/ui/impl'; import { MessageBus } from 'angular2/src/web_workers/shared/message_bus'; import { MessageBasedRenderCompiler } from 'angular2/src/web_workers/ui/render_compiler'; import { MessageBasedRenderer } from 'angular2/src/web_workers/ui/renderer'; import { MessageBasedXHRImpl } from 'angular2/src/web_workers/ui/xhr_impl'; import { WebWorkerSetup } from 'angular2/src/web_workers/ui/setup'; import { ServiceMessageBrokerFactory } from 'angular2/src/web_workers/shared/service_message_broker'; import { ClientMessageBrokerFactory } from 'angular2/src/web_workers/shared/client_message_broker'; var _rootInjector; // Contains everything that is safe to share between applications. var _rootBindings = [bind(Reflector).toValue(reflector)]; // TODO: This code is nearly identitcal to core/application. There should be a way to only write it // once function _injectorBindings() { var bestChangeDetection = new DynamicChangeDetection(); if (PreGeneratedChangeDetection.isSupported()) { bestChangeDetection = new PreGeneratedChangeDetection(); } else if (JitChangeDetection.isSupported()) { bestChangeDetection = new JitChangeDetection(); } return [ bind(DOCUMENT) .toValue(DOM.defaultDoc()), bind(EventManager) .toFactory((ngZone) => { var plugins = [new HammerGesturesPlugin(), new KeyEventsPlugin(), new DomEventsPlugin()]; return new EventManager(plugins, ngZone); }, [NgZone]), DomRenderer, bind(Renderer).toAlias(DomRenderer), APP_ID_RANDOM_BINDING, TemplateCloner, bind(MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE).toValue(20), DefaultDomCompiler, bind(RenderCompiler).toAlias(DefaultDomCompiler), DomSharedStylesHost, bind(SharedStylesHost).toAlias(DomSharedStylesHost), Serializer, bind(ON_WEB_WORKER).toValue(false), bind(ElementSchemaRegistry).toValue(new DomElementSchemaRegistry()), RenderViewWithFragmentsStore, RenderProtoViewRefStore, ProtoViewFactory, AppViewPool, bind(APP_VIEW_POOL_CAPACITY).toValue(10000), AppViewManager, AppViewManagerUtils, AppViewListener, Compiler, CompilerCache, ViewResolver, DEFAULT_PIPES, bind(ChangeDetection).toValue(bestChangeDetection), ViewLoader, DirectiveResolver, Parser, Lexer, bind(ExceptionHandler).toFactory(() => new ExceptionHandler(DOM), []), bind(XHR).toValue(new XHRImpl()), ComponentUrlMapper, UrlResolver, StyleUrlResolver, StyleInliner, DynamicComponentLoader, Testability, AnchorBasedAppRootUrl, bind(AppRootUrl).toAlias(AnchorBasedAppRootUrl), WebWorkerApplication, WebWorkerSetup, MessageBasedRenderCompiler, MessageBasedXHRImpl, MessageBasedRenderer, ServiceMessageBrokerFactory, ClientMessageBrokerFactory ]; } export function createInjector(zone, bus) { BrowserDomAdapter.makeCurrent(); _rootBindings.push(bind(NgZone).toValue(zone)); _rootBindings.push(bind(MessageBus).toValue(bus)); var injector = Injector.resolveAndCreate(_rootBindings); return injector.resolveAndCreateChild(_injectorBindings()); } //# sourceMappingURL=di_bindings.js.map
rehnen/potato
node_modules/angular2/es6/prod/src/web_workers/ui/di_bindings.js
JavaScript
mit
6,900
require('should'); require('should-http'); var NODE = true; var uri = 'http://localhost:5000'; if (typeof window !== 'undefined') { NODE = false; uri = '//' + window.location.host; } else { process.env.ZUUL_PORT = 5000; require('./server'); } exports.NODE = NODE; exports.uri = uri;
craigspaeth/superagent
test/support/setup.js
JavaScript
mit
293
module.exports = function () { return { action: 'start', frameworks: [], files: [], client: [], yamlPreprocessor: {}, coffeePreprocessor: {}, preprocessors: {}, coverageReporter: {}, exclude: [], reporters: [], proxies: {}, plugins: [ 'karma-*' ] }; };
carlosmarte/workflow-amd-karma
lib/templates/karma.js
JavaScript
mit
377
import { expect } from 'chai'; import sinon from 'sinon'; import { createStore } from 'redux'; import CallHistory from './index'; import getCallHistoryReducer from './getCallHistoryReducer'; import actionTypes from './actionTypes'; describe('CallHistory Unit Test', () => { let callHistory; let store; beforeEach(() => { callHistory = sinon.createStubInstance(CallHistory); store = createStore(getCallHistoryReducer(actionTypes)); callHistory._store = store; callHistory._prefixedActionTypes = actionTypes; [ '_onStateChange', '_shouldInit', '_shouldReset', '_shouldTriggerContactMatch', '_shouldTriggerActivityMatch', '_getEndedCalls', '_shouldRemoveEndedCalls', '_processCallHistory', '_initModuleStatus', '_resetModuleStatus', '_addEndedCalls', '_removeEndedCalls', ].forEach((key) => { callHistory[key].restore(); }); }); describe('_onStateChange', () => { it('_initModuleStatus should be called once when _shouldInit is true', () => { sinon.stub(callHistory, '_shouldInit').callsFake(() => true); sinon.stub(callHistory, '_shouldReset').callsFake(() => false); sinon.stub(callHistory, 'ready', { get: () => false }); sinon.stub(callHistory, '_initModuleStatus'); sinon.stub(callHistory, '_resetModuleStatus'); sinon.stub(callHistory, '_processCallHistory'); callHistory._onStateChange(); sinon.assert.calledOnce(callHistory._initModuleStatus); sinon.assert.notCalled(callHistory._resetModuleStatus); sinon.assert.notCalled(callHistory._processCallHistory); }); it('_resetModuleStatus should be called once when _shouldReset is true', () => { sinon.stub(callHistory, '_shouldInit').callsFake(() => false); sinon.stub(callHistory, '_shouldReset').callsFake(() => true); sinon.stub(callHistory, 'ready', { get: () => false }); sinon.stub(callHistory, '_initModuleStatus'); sinon.stub(callHistory, '_resetModuleStatus'); sinon.stub(callHistory, '_processCallHistory'); callHistory._onStateChange(); sinon.assert.notCalled(callHistory._initModuleStatus); sinon.assert.calledOnce(callHistory._resetModuleStatus); sinon.assert.notCalled(callHistory._processCallHistory); }); it('_processCallHistory should be called once when ready is true', () => { sinon.stub(callHistory, '_shouldInit').callsFake(() => false); sinon.stub(callHistory, '_shouldReset').callsFake(() => false); sinon.stub(callHistory, 'ready', { get: () => true }); sinon.stub(callHistory, '_initModuleStatus'); sinon.stub(callHistory, '_resetModuleStatus'); sinon.stub(callHistory, '_processCallHistory'); callHistory._onStateChange(); sinon.assert.notCalled(callHistory._initModuleStatus); sinon.assert.notCalled(callHistory._resetModuleStatus); sinon.assert.calledOnce(callHistory._processCallHistory); }); it('_initModuleStatus, _resetModuleStatus and _processCallHistory should Not be called', () => { sinon.stub(callHistory, '_shouldInit').callsFake(() => false); sinon.stub(callHistory, '_shouldReset').callsFake(() => false); sinon.stub(callHistory, 'ready', { get: () => false }); sinon.stub(callHistory, '_initModuleStatus'); sinon.stub(callHistory, '_resetModuleStatus'); sinon.stub(callHistory, '_processCallHistory'); callHistory._onStateChange(); sinon.assert.notCalled(callHistory._initModuleStatus); sinon.assert.notCalled(callHistory._resetModuleStatus); sinon.assert.notCalled(callHistory._processCallHistory); }); }); describe('_shouldInit', () => { const options = [true, false]; const optionsWithUndefined = [true, false, undefined]; options.forEach((isModulePending) => { options.forEach((isCallLogReady) => { options.forEach((isAccountInfoReady) => { optionsWithUndefined.forEach((isCallMonitorReady) => { optionsWithUndefined.forEach((isContactMatcherReady) => { optionsWithUndefined.forEach((isActivityMatcherReady) => { const result = ( isModulePending && isCallLogReady && isAccountInfoReady && (isCallMonitorReady !== undefined ? isCallMonitorReady : true) && (isContactMatcherReady !== undefined ? isContactMatcherReady : true) && (isActivityMatcherReady !== undefined ? isActivityMatcherReady : true) ); it(`should return ${result} when isModulePending === ${isModulePending} isCallLogReady === ${isCallLogReady}, isAccountInfoReady === ${isAccountInfoReady}, isCallMonitorReady === ${isCallMonitorReady}, isContactMatcherReady === ${isContactMatcherReady}, isActivityMatcherReady === ${isActivityMatcherReady} `, () => { callHistory._callLog = { ready: isCallLogReady }; callHistory._accountInfo = { ready: isAccountInfoReady }; sinon.stub(callHistory, 'pending', { get: () => isModulePending, }); if (isCallMonitorReady !== undefined) { callHistory._callMonitor = { ready: isCallMonitorReady }; } if (isContactMatcherReady !== undefined) { callHistory._contactMatcher = { ready: isContactMatcherReady }; } if (isActivityMatcherReady !== undefined) { callHistory._activityMatcher = { ready: isActivityMatcherReady }; } expect(callHistory._shouldInit()).to.equals(result); }); }); }); }); }); }); }); }); describe('_shouldReset', () => { const options = [true, false]; const optionsWithUndefined = [true, false, undefined]; options.forEach((isModuleReady) => { options.forEach((isCallLogReady) => { options.forEach((isAccountInfoReady) => { optionsWithUndefined.forEach((isCallMonitorReady) => { optionsWithUndefined.forEach((isContactMatcherReady) => { optionsWithUndefined.forEach((isActivityMatcherReady) => { const result = ( ( !isCallLogReady || !isAccountInfoReady || (isCallMonitorReady === undefined ? undefined : !isCallMonitorReady) || (isContactMatcherReady === undefined ? undefined : !isContactMatcherReady) || (isActivityMatcherReady === undefined ? undefined : !isActivityMatcherReady) ) && isModuleReady ); it(`should return ${result} when isModuleReady === ${isModuleReady} isCallLogReady === ${isCallLogReady}, isAccountInfoReady === ${isAccountInfoReady}, isCallMonitorReady === ${isCallMonitorReady}, isContactMatcherReady === ${isContactMatcherReady}, isActivityMatcherReady === ${isActivityMatcherReady} `, () => { callHistory._callLog = { ready: isCallLogReady }; callHistory._accountInfo = { ready: isAccountInfoReady }; sinon.stub(callHistory, 'ready', { get: () => isModuleReady, }); if (isCallMonitorReady !== undefined) { callHistory._callMonitor = { ready: isCallMonitorReady }; } if (isContactMatcherReady !== undefined) { callHistory._contactMatcher = { ready: isContactMatcherReady }; } if (isActivityMatcherReady !== undefined) { callHistory._activityMatcher = { ready: isActivityMatcherReady }; } expect(callHistory._shouldReset()).to.equals(result); }); }); }); }); }); }); }); }); describe('_shouldTriggerContactMatch', () => { it(`Should return true when _lastProcessedNumbers not equals to uniqueNumbers and contactMatcher is ready`, () => { callHistory._lastProcessedNumbers = 'foo'; callHistory._contactMatcher = { ready: true }; expect(callHistory._shouldTriggerContactMatch('bar')).to.equal(true); }); it(`Should return false when _lastProcessedNumbers not equals to uniqueNumbers and contactMatcher is undefined`, () => { callHistory._lastProcessedNumbers = 'foo'; callHistory._contactMatcher = undefined; expect(callHistory._shouldTriggerContactMatch('bar')).to.equal(false); }); it(`Should return false when _lastProcessedNumbers not equals to uniqueNumbers and contactMatcher is ready`, () => { callHistory._lastProcessedNumbers = 'foo'; callHistory._contactMatcher = { ready: false }; expect(callHistory._shouldTriggerContactMatch('bar')).to.equal(false); }); it(`Should return false when _lastProcessedNumbers equals to uniqueNumbers and contactMatcher is ready`, () => { callHistory._lastProcessedNumbers = 'foo'; callHistory._contactMatcher = { ready: true }; expect(callHistory._shouldTriggerContactMatch('foo')).to.equal(false); }); it(`Should return false when _lastProcessedNumbers equals to uniqueNumbers and contactMatcher is undefined`, () => { callHistory._lastProcessedNumbers = 'foo'; callHistory._contactMatcher = undefined; expect(callHistory._shouldTriggerContactMatch('foo')).to.equal(false); }); it(`Should return false when _lastProcessedNumbers equals to uniqueNumbers and contactMatcher is ready`, () => { callHistory._lastProcessedNumbers = 'foo'; callHistory._contactMatcher = { ready: false }; expect(callHistory._shouldTriggerContactMatch('foo')).to.equal(false); }); }); describe('_shouldTriggerActivityMatch', () => { beforeEach(() => { callHistory._lastProcessedIds = 'foo'; }); it(`Should return true when _lastProcessedIds not equals to sessionIds and activityMatcher is ready`, () => { callHistory._activityMatcher = { ready: true }; expect(callHistory._shouldTriggerActivityMatch('bar')).to.equal(true); }); it(`Should return false when _lastProcessedIds not equals to sessionIds and activityMatcher is undefined`, () => { callHistory._activityMatcher = undefined; expect(callHistory._shouldTriggerActivityMatch('bar')).to.equal(false); }); it(`Should return false when _lastProcessedIds not equals to sessionIds and activityMatcher is ready`, () => { callHistory._activityMatcher = { ready: false }; expect(callHistory._shouldTriggerActivityMatch('bar')).to.equal(false); }); it(`Should return false when _lastProcessedIds not equals to sessionIds and activityMatcher is ready`, () => { callHistory._activityMatcher = { ready: true }; expect(callHistory._shouldTriggerActivityMatch('foo')).to.equal(false); }); it(`Should return false when _lastProcessedIds not equals to sessionIds and activityMatcher is undefined`, () => { callHistory._activityMatcher = undefined; expect(callHistory._shouldTriggerActivityMatch('foo')).to.equal(false); }); it(`Should return false when _lastProcessedIds not equals to sessionIds and activityMatcher is ready`, () => { callHistory._activityMatcher = { ready: false }; expect(callHistory._shouldTriggerActivityMatch('foo')).to.equal(false); }); }); describe('_getEndedCalls', () => { let monitorCalls; beforeEach(() => { monitorCalls = { calls: [{ sessionId: 'foo' }] }; }); it(`Should return endedCalls when _lastProcessedMonitorCalls is not equal to monitorCalls `, () => { callHistory._callMonitor = monitorCalls; callHistory._callLog = { calls: [], }; callHistory._lastProcessedMonitorCalls = [{ sessionId: 'bar' }, { sessionId: 'foo' }]; expect(callHistory._getEndedCalls()).to.deep.equal([{ sessionId: 'bar' }]); }); it('Should return [] when sessionId already exist', () => { callHistory._callMonitor = { calls: [{ sessionId: 'bar' }, { sessionId: 'foo' }] }; callHistory._callLog = { calls: [], }; callHistory._lastProcessedMonitorCalls = [{ sessionId: 'bar' }]; expect(callHistory._getEndedCalls()).to.deep.equal([]); }); it('Should return null when _lastProcessedMonitorCalls is equal to monitorCalls', () => { callHistory._callMonitor = monitorCalls; callHistory._callLog = { calls: [], }; callHistory._lastProcessedMonitorCalls = monitorCalls.calls; expect(callHistory._getEndedCalls()).to.be.a('null'); }); it('Should return null when _callMonitor is undefined', () => { callHistory._callMonitor = undefined; callHistory._callLog = { calls: [], }; callHistory._lastProcessedMonitorCalls = [{ sessionId: 'foo' }]; expect(callHistory._getEndedCalls()).to.be.a('null'); }); }); describe('_shouldRemoveEndedCalls', () => { let currentCalls; beforeEach(() => { currentCalls = { calls: [{ sessionId: 'foo' }] }; }); it(`Should return endedCalls which should be removed when _lastProcessedCalls is not equal to currentCalls `, () => { callHistory._callLog = currentCalls; callHistory._lastProcessedCalls = [{ sessionId: 'bar' }, { sessionId: 'foo' }]; const recentlyEndedCalls = currentCalls.calls; sinon.stub(callHistory, 'recentlyEndedCalls', { get: () => recentlyEndedCalls }); expect(callHistory._shouldRemoveEndedCalls()).to.deep.equal([{ sessionId: 'foo' }]); }); it('Should return [] when _lastProcessedCalls is not equal to currentCalls and sessionId is not existed', () => { callHistory._callLog = currentCalls; callHistory._lastProcessedCalls = [{ sessionId: 'bar' }]; const recentlyEndedCalls = [{ sessionId: 'koo' }]; sinon.stub(callHistory, 'recentlyEndedCalls', { get: () => recentlyEndedCalls }); expect(callHistory._shouldRemoveEndedCalls()).to.deep.equal([]); }); it('Should return null when _lastProcessedCalls is equal to currentCalls', () => { callHistory._callLog = currentCalls; callHistory._lastProcessedCalls = currentCalls.calls; const recentlyEndedCalls = [{ sessionId: 'koo' }]; sinon.stub(callHistory, 'recentlyEndedCalls', { get: () => recentlyEndedCalls }); expect(callHistory._shouldRemoveEndedCalls()).to.be.a('null'); }); }); describe('_processCallHistory', () => { beforeEach(() => { sinon.stub(callHistory, 'uniqueNumbers', { get: () => 'foo' }); sinon.stub(callHistory, 'sessionIds', { get: () => 'foo' }); }); it('_contactMatcher.triggerMatch should be called once when _shouldTriggerContactMatch is true', () => { sinon.stub(callHistory, '_shouldTriggerContactMatch').callsFake(() => true); sinon.stub(callHistory, '_shouldTriggerActivityMatch').callsFake(() => false); sinon.stub(callHistory, '_getEndedCalls').callsFake(() => null); sinon.stub(callHistory, '_shouldRemoveEndedCalls').callsFake(() => null); callHistory._contactMatcher = { triggerMatch: sinon.stub().callsFake(() => {}) }; sinon.stub(callHistory, '_contactMatcher'); callHistory._processCallHistory(); sinon.assert.calledOnce(callHistory._contactMatcher.triggerMatch); }); it('_contactMatcher.triggerMatch should not be called when _shouldTriggerContactMatch is false', () => { sinon.stub(callHistory, '_shouldTriggerContactMatch').callsFake(() => false); sinon.stub(callHistory, '_shouldTriggerActivityMatch').callsFake(() => false); sinon.stub(callHistory, '_getEndedCalls').callsFake(() => null); sinon.stub(callHistory, '_shouldRemoveEndedCalls').callsFake(() => null); callHistory._contactMatcher = { triggerMatch: sinon.stub().callsFake(() => {}) }; sinon.stub(callHistory, '_contactMatcher'); callHistory._processCallHistory(); sinon.assert.notCalled(callHistory._contactMatcher.triggerMatch); }); it('_activityMatcher.triggerMatch should be called once when _shouldTriggerActivityMatch is true', () => { sinon.stub(callHistory, '_shouldTriggerContactMatch').callsFake(() => false); sinon.stub(callHistory, '_shouldTriggerActivityMatch').callsFake(() => true); sinon.stub(callHistory, '_getEndedCalls').callsFake(() => null); sinon.stub(callHistory, '_shouldRemoveEndedCalls').callsFake(() => null); callHistory._activityMatcher = { triggerMatch: sinon.stub().callsFake(() => {}) }; sinon.stub(callHistory, '_activityMatcher'); callHistory._processCallHistory(); sinon.assert.calledOnce(callHistory._activityMatcher.triggerMatch); }); it('_activityMatcher.triggerMatch should not be called when _shouldTriggerActivityMatch is false', () => { sinon.stub(callHistory, '_shouldTriggerContactMatch').callsFake(() => false); sinon.stub(callHistory, '_shouldTriggerActivityMatch').callsFake(() => false); sinon.stub(callHistory, '_getEndedCalls').callsFake(() => null); sinon.stub(callHistory, '_shouldRemoveEndedCalls').callsFake(() => null); callHistory._activityMatcher = { triggerMatch: sinon.stub().callsFake(() => {}) }; sinon.stub(callHistory, '_activityMatcher'); callHistory._processCallHistory(); sinon.assert.notCalled(callHistory._activityMatcher.triggerMatch); }); it('_addEndedCalls should be called when _getEndedCalls is return an array contains values', () => { sinon.stub(callHistory, '_shouldTriggerContactMatch').callsFake(() => false); sinon.stub(callHistory, '_shouldTriggerActivityMatch').callsFake(() => false); sinon.stub(callHistory, '_getEndedCalls').callsFake(() => [{ sessionId: 'foo' }]); sinon.stub(callHistory, '_shouldRemoveEndedCalls').callsFake(() => null); sinon.stub(callHistory, '_addEndedCalls'); callHistory._processCallHistory(); sinon.assert.calledOnce(callHistory._addEndedCalls); }); it('_addEndedCalls should not be called when _getEndedCalls is return an empty array', () => { sinon.stub(callHistory, '_shouldTriggerContactMatch').callsFake(() => false); sinon.stub(callHistory, '_shouldTriggerActivityMatch').callsFake(() => false); sinon.stub(callHistory, '_getEndedCalls').callsFake(() => []); sinon.stub(callHistory, '_shouldRemoveEndedCalls').callsFake(() => null); sinon.stub(callHistory, '_addEndedCalls'); callHistory._processCallHistory(); sinon.assert.notCalled(callHistory._addEndedCalls); }); it('_addEndedCalls should not be called when _getEndedCalls is return null', () => { sinon.stub(callHistory, '_shouldTriggerContactMatch').callsFake(() => false); sinon.stub(callHistory, '_shouldTriggerActivityMatch').callsFake(() => false); sinon.stub(callHistory, '_getEndedCalls').callsFake(() => null); sinon.stub(callHistory, '_shouldRemoveEndedCalls').callsFake(() => null); sinon.stub(callHistory, '_addEndedCalls'); callHistory._processCallHistory(); sinon.assert.notCalled(callHistory._addEndedCalls); }); it('_removeEndedCalls should be called when _shouldRemoveEndedCalls is return an array contains values', () => { sinon.stub(callHistory, '_shouldTriggerContactMatch').callsFake(() => false); sinon.stub(callHistory, '_shouldTriggerActivityMatch').callsFake(() => false); sinon.stub(callHistory, '_getEndedCalls').callsFake(() => null); sinon.stub(callHistory, '_shouldRemoveEndedCalls').callsFake(() => [{ sessionId: 'foo' }]); sinon.stub(callHistory, '_removeEndedCalls'); callHistory._processCallHistory(); sinon.assert.calledOnce(callHistory._removeEndedCalls); }); it('_removeEndedCalls should not be called when _shouldRemoveEndedCalls is return an empty array', () => { sinon.stub(callHistory, '_shouldTriggerContactMatch').callsFake(() => false); sinon.stub(callHistory, '_shouldTriggerActivityMatch').callsFake(() => false); sinon.stub(callHistory, '_getEndedCalls').callsFake(() => null); sinon.stub(callHistory, '_shouldRemoveEndedCalls').callsFake(() => []); sinon.stub(callHistory, '_removeEndedCalls'); callHistory._processCallHistory(); sinon.assert.notCalled(callHistory._removeEndedCalls); }); it('_removeEndedCalls should not be called when _shouldRemoveEndedCalls is return null', () => { sinon.stub(callHistory, '_shouldTriggerContactMatch').callsFake(() => false); sinon.stub(callHistory, '_shouldTriggerActivityMatch').callsFake(() => false); sinon.stub(callHistory, '_getEndedCalls').callsFake(() => null); sinon.stub(callHistory, '_shouldRemoveEndedCalls').callsFake(() => null); sinon.stub(callHistory, '_removeEndedCalls'); callHistory._processCallHistory(); sinon.assert.notCalled(callHistory._removeEndedCalls); }); }); });
ringcentral/ringcentral-js-integration-commons
src/modules/CallHistory/index.test.js
JavaScript
mit
22,381
module.exports.config = { files: { javascripts: { joinTo: { "js/app.js": /^app/, "js/vendor.js": /^(?!app)/ }, order: { before: [ "bower_components/jquery/dist/jquery.js", "bower_components/underscore/underscore.js", "bower_components/bluebird/js/browser/bluebird.js", "bower_components/react/react.js" ] } }, stylesheets: { joinTo: "css/app.css" }, templates: { joinTo: "js/app.js" } }, plugins: { react: { autoIncludeCommentBlock: true, harmony: true, transformOptions : { sourceMap : true } }, reactTags: { verbose: true } }, server: { path: 'app.js', port: 3333, run: true } };
chubas/instaband
brunch-config.js
JavaScript
mit
794
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M8.12 9.29 12 13.17l3.88-3.88c.39-.39 1.02-.39 1.41 0 .39.39.39 1.02 0 1.41l-4.59 4.59c-.39.39-1.02.39-1.41 0L6.7 10.7a.9959.9959 0 0 1 0-1.41c.39-.38 1.03-.39 1.42 0z" }), 'KeyboardArrowDownRounded'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/KeyboardArrowDownRounded.js
JavaScript
mit
647
function AnnotationComponent(o) { this.text = ""; this.notes = []; this._screen_pos = vec3.create(); this._selected = null; this.configure(o); } AnnotationComponent.editor_color = [0.33,0.874,0.56,0.9]; AnnotationComponent.onShowMainAnnotation = function (node) { if(typeof(AnnotationModule) != "undefined") AnnotationModule.editAnnotation(node); } AnnotationComponent.onShowPointAnnotation = function (node, note) { var comp = node.getComponent( AnnotationComponent ); if(!comp) return; //in editor... if(typeof(AnnotationModule) != "undefined") { AnnotationModule.showDialog( note.text, { item: note, on_close: inner_update_note.bind(note), on_delete: function(info) { comp.removeAnnotation(info.item); LS.GlobalScene.refresh(); }, on_focus: function(info) { AnnotationModule.focusInAnnotation(info.item); comp._selected = info.item; }}); } function inner_update_note(text) { this.text = text; } } AnnotationComponent.prototype.addAnnotation = function(item) { this._selected = null; this.notes.push(item); } AnnotationComponent.prototype.getAnnotation = function(index) { return this.nodes[ index ]; } AnnotationComponent.prototype.removeAnnotation = function(item) { this._selected = null; var pos = this.notes.indexOf(item); if(pos != -1) this.notes.splice(pos,1); } AnnotationComponent.prototype.setStartTransform = function() { this.start_position = this.getObjectCenter(); } AnnotationComponent.prototype.getObjectCenter = function() { var center = vec3.create(); var mesh = this._root.getMesh(); if(mesh && mesh.bounding ) vec3.copy( center, BBox.getCenter(mesh.bounding) ); var pos = this._root.transform.transformPointGlobal(center, vec3.create()); return pos; } AnnotationComponent.prototype.serialize = function() { var o = { text: this.text, notes: [], start_position: this.start_position }; for(var i in this.notes) { var note = this.notes[i]; for(var j in note) { if(note[j].constructor == Float32Array) Array.prototype.slice.call( note[j] ); } o.notes.push(note); } return o; } AnnotationComponent.prototype.onAddedToNode = function(node) { LEvent.bind(node,"mousedown",this.onMouse.bind(this),this); } AnnotationComponent.prototype.onRemovedFromNode = function(node) { } AnnotationComponent.prototype.onMouse = function(type, e) { if(e.eventType == "mousedown") { var node = this._root; this._screen_pos[2] = 0; var dist = vec3.dist( this._screen_pos, [e.canvasx, gl.canvas.height - e.canvasy, 0] ); if(dist < 30) { var that = this; AnnotationComponent.onShowMainAnnotation(this._root); } for(var i in this.notes) { var note = this.notes[i]; dist = vec2.dist( note._end_screen, [e.mousex, gl.canvas.height - e.mousey] ); if(dist < 30) { this._selected = note; AnnotationComponent.onShowPointAnnotation(this._root, note); return true; } } } } LS.registerComponent(AnnotationComponent);
TheKnarf/litescene.js
src/components/annotations.js
JavaScript
mit
3,119
module.exports = { debug: false, makeAndCancelOffers: true, apiServer: false, apiPort: 8080, loopDelayInMinutes: 5, exchanges: { 'bitfinex': { msDelayBetweenAPICalls: 2000, credentials: { key: process.env.BITFINEX_KEY || 'BITFINEX-KEY-HERE', secret: process.env.BITFINEX_SECRET || 'BITFINEX-SECRET-HERE' }, duration: { minimum: 2, maximum: 30, lowThreshold: 20, highThreshold: 30 }, currencies: { usd: { active: true, minimumRate: 1.0, maximumRate: 28.0, minimumSizeUSD: 50, maximumSizeUSD: 500, rateCreationStrategy: { name: 'percentDepth', lendbookPositioningPercentage: 10 }, rateUpdateStrategy: { name: 'lowerRateWithTime', lowerAfterMinutes: 30, lowerByPercent: 5 } }, eth: { active: true, minimumRate: 0.1, minimumSizeUSD: 50, maximumSizeUSD: 500, rateCreationStrategy: { name: 'percentDepth', lendbookPositioningPercentage: 10 }, rateUpdateStrategy: { name: 'lowerRateWithTime', lowerAfterMinutes: 30, lowerByPercent: 5 } }, etc: { active: true, minimumRate: 0.1, minimumSizeUSD: 50, maximumSizeUSD: 500, rateCreationStrategy: { name: 'percentDepth', lendbookPositioningPercentage: 15 }, rateUpdateStrategy: { name: 'lowerRateWithTime', lowerAfterMinutes: 30, lowerByPercent: 5 } }, bfx: { active: false, minimumRate: 0.1, minimumSizeUSD: 50, maximumSizeUSD: 500, rateCreationStrategy: { name: 'percentDepth', lendbookPositioningPercentage: 15 }, rateUpdateStrategy: { name: 'lowerRateWithTime', lowerAfterMinutes: 30, lowerByPercent: 5 } }, btc: { active: true, minimumRate: 0.1, minimumSizeUSD: 50, maximumSizeUSD: 500, rateCreationStrategy: { name: 'percentDepth', lendbookPositioningPercentage: 15 }, rateUpdateStrategy: { name: 'lowerRateWithTime', lowerAfterMinutes: 30, lowerByPercent: 5 } } } }, poloniex: { msDelayBetweenAPICalls: 100, credentials: { key: process.env.POLONIEX_KEY || 'POLONIEX-KEY-HERE', secret: process.env.POLONIEX_SECRET || 'POLONIEX-SECRET-HERE' }, duration: { minimum: 2, maximum: 60, lowThreshold: 20, highThreshold: 30 }, currencies: { btc: { active: true, minimumRate: 0.1, minimumSizeUSD: 5, maximumSizeUSD: 500, rateCreationStrategy: { name: 'percentDepth', lendbookPositioningPercentage: 10 }, rateUpdateStrategy: { name: 'lowerRateWithTime', lowerAfterMinutes: 30, lowerByPercent: 5 } }, eth: { active: true, minimumRate: 0.1, minimumSizeUSD: 5, maximumSizeUSD: 500, rateCreationStrategy: { name: 'percentDepth', lendbookPositioningPercentage: 10 }, rateUpdateStrategy: { name: 'lowerRateWithTime', lowerAfterMinutes: 30, lowerByPercent: 5 } }, str: { active: true, minimumRate: 0.1, minimumSizeUSD: 50, maximumSizeUSD: 500, rateCreationStrategy: { name: 'percentDepth', lendbookPositioningPercentage: 15 }, rateUpdateStrategy: { name: 'lowerRateWithTime', lowerAfterMinutes: 30, lowerByPercent: 5 } }, clam: { active: false, minimumRate: 0.1, minimumSizeUSD: 5, maximumSizeUSD: 500, rateCreationStrategy: { name: 'percentDepth', lendbookPositioningPercentage: 1 }, rateUpdateStrategy: { name: 'lowerRateWithTime', lowerAfterMinutes: 30, lowerByPercent: 5 } }, xmr: { active: true, minimumRate: 0.1, minimumSizeUSD: 5, maximumSizeUSD: 100, rateCreationStrategy: { name: 'percentDepth', lendbookPositioningPercentage: 1 }, rateUpdateStrategy: { name: 'lowerRateWithTime', lowerAfterMinutes: 30, lowerByPercent: 5 } } } } } };
mdyring/loan-manager
config/index-example.js
JavaScript
mit
4,086
describe('Mirri Maz Duur', function() { integration(function() { beforeEach(function() { const deck1 = this.buildDeck('targaryen', [ 'Marching Orders', 'Mirri Maz Duur', 'The Hound', 'Targaryen Loyalist' ]); const deck2 = this.buildDeck('targaryen', [ 'Marching Orders', 'Targaryen Loyalist' ]); this.player1.selectDeck(deck1); this.player2.selectDeck(deck2); this.startGame(); this.keepStartingHands(); this.mirri = this.player1.findCardByName('Mirri Maz Duur', 'hand'); this.hound = this.player1.findCardByName('The Hound', 'hand'); this.character = this.player2.findCardByName('Targaryen Loyalist'); this.player1.clickCard(this.mirri); this.player2.clickCard(this.character); this.completeSetup(); this.player1.selectPlot('Marching Orders'); this.player2.selectPlot('Marching Orders'); this.selectFirstPlayer(this.player1); this.player1.clickCard(this.hound); this.completeMarshalPhase(); }); describe('when claim is applied while Mirri attacks alone', function() { beforeEach(function() { this.player1.clickPrompt('Power'); this.player1.clickCard(this.mirri); this.player1.clickPrompt('Done'); this.skipActionWindow(); this.player2.clickPrompt('Done'); this.skipActionWindow(); this.player1.clickPrompt('Apply Claim'); }); it('should allow a character to be killed', function() { this.player1.clickPrompt('Mirri Maz Duur'); this.player1.clickCard(this.character); expect(this.character.location).toBe('dead pile'); }); }); describe('when a card leaves play after the challenge is won', function() { beforeEach(function() { this.player1.clickPrompt('Power'); this.player1.clickCard(this.mirri); this.player1.clickCard(this.hound); this.player1.clickPrompt('Done'); this.skipActionWindow(); this.player2.clickPrompt('Done'); this.skipActionWindow(); // Choose not to discard a card so the Hound returns to hand this.player1.clickPrompt('No'); this.player1.clickPrompt('Apply Claim'); }); it('should consider Mirri to be attacking alone', function() { expect(this.player1).toHavePromptButton('Mirri Maz Duur'); }); }); }); });
cryogen/gameteki
test/server/cards/characters/02/02093-mirrimazduur.spec.js
JavaScript
mit
2,826
version https://git-lfs.github.com/spec/v1 oid sha256:1ea2ba706f446b9a0042307053f5d0b5ba45818b20bacf661ae6a3272d88b665 size 93
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.18.0/selector/selector.js
JavaScript
mit
127
// Comment model var mongoose = require('mongoose'); var ObjectId = mongoose.Schema.Types.ObjectId; var createdDate = require('../plugins/createdDate'); var schema = mongoose.Schema({ text: { type: String, trim: true, validate: validateText } , post: { type: ObjectId, index: true } , author: String }) function validateText (str) { return str.length < 250; } // in production we disable auto index creation // schema.set('autoIndex', false); // add created date property schema.plugin(createdDate); module.exports = mongoose.model('Comment', schema);
gollodev/M101JS
chapter7/introduction_to_week_7/lesson7_examples/models/comment.js
JavaScript
mit
569
var Poll = { reset: function (roomId) { Poll[roomId] = { question: undefined, optionList: [], options: {}, display: '', topOption: '' }; }, splint: function (target) { var parts = target.split(','); var len = parts.length; while (len--) { parts[len] = parts[len].trim(); } return parts; } }; for (var id in Rooms.rooms) { if (Rooms.rooms[id].type === 'chat' && !Poll[id]) { Poll[id] = {}; Poll.reset(id); } } exports.commands = { poll: function (target, room, user) { if (!this.can('poll', null, room)) return false; if (!Poll[room.id]) Poll.reset(room.id); if (Poll[room.id].question) return this.sendReply("There is currently a poll going on already."); if (!this.canTalk()) return; var options = Poll.splint(target); if (options.length < 3) return this.parse('/help poll'); var question = options.shift(); options = options.join(',').toLowerCase().split(','); Poll[room.id].question = question; Poll[room.id].optionList = options; var pollOptions = ''; var start = 0; while (start < Poll[room.id].optionList.length) { pollOptions += '<button name="send" value="/vote ' + Tools.escapeHTML(Poll[room.id].optionList[start]) + '">' + Tools.escapeHTML(Poll[room.id].optionList[start]) + '</button>&nbsp;'; start++; } Poll[room.id].display = '<h2>' + Tools.escapeHTML(Poll[room.id].question) + '&nbsp;&nbsp;<font size="1" color="#AAAAAA">/vote OPTION</font><br><font size="1" color="#AAAAAA">Poll started by <em>' + user.name + '</em></font><br><hr>&nbsp;&nbsp;&nbsp;&nbsp;' + pollOptions; room.add('|raw|<div class="infobox">' + Poll[room.id].display + '</div>'); }, pollhelp: ["/poll [question], [option 1], [option 2]... - Create a poll where users can vote on an option."], endpoll: function (target, room, user) { if (!this.can('poll', null, room)) return false; if (!Poll[room.id]) Poll.reset(room.id); if (!Poll[room.id].question) return this.sendReply("There is no poll to end in this room."); var votes = Object.keys(Poll[room.id].options).length; if (votes === 0) { Poll.reset(room.id); return room.add('|raw|<h3>The poll was canceled because of lack of voters.</h3>'); } var options = {}; for (var l in Poll[room.id].optionList) { options[Poll[room.id].optionList[l]] = 0; } for (var o in Poll[room.id].options) { options[Poll[room.id].options[o]]++; } var data = []; for (var i in options) { data.push([i, options[i]]); } data.sort(function (a, b) { return a[1] - b[1]; }); var results = ''; var len = data.length; var topOption = data[len - 1][0]; while (len--) { if (data[len][1] > 0) { results += '&bull; ' + data[len][0] + ' - ' + Math.floor(data[len][1] / votes * 100) + '% (' + data[len][1] + ')<br>'; } } room.add('|raw|<div class="infobox"><h2>Results to "' + Poll[room.id].question + '"</h2><font size="1" color="#AAAAAA"><strong>Poll ended by <em>' + user.name + '</em></font><br><hr>' + results + '</strong></div>'); Poll.reset(room.id); Poll[room.id].topOption = topOption; }, elimtour: 'etour', etour: function (target, room, user) { if (!target) return this.sendReply("Please provide a format."); if ((this.can('tournamentsmoderation', null, room)) || (this.can('voicetourmoderation'))) { this.parse('/tour new ' + target + ', elimination'); } }, roundrobintour: 'rtour', rtour: function (target, room, user) { if (!target) return this.sendReply("Please provide a format."); if ((this.can('tournamentsmoderation', null, room)) || (this.can('voicetourmoderation'))) { this.parse('/tour new ' + target + ', roundrobin'); } }, dtour: 'doutour', doubletour: 'doutour', doutour: function (target, room, user) { if (!target) return this.sendReply("Please provide a format."); if ((this.can('tournamentsmoderation', null, room)) || (this.can('voicetourmoderation'))) { this.parse('/tour new ' + target + ', elimination, 99, 2'); } }, ttour: 'tritour', tripletour: 'tritour', tritour: function (target, room, user) { if (!target) return this.sendReply("Please provide a format."); if ((this.can('tournamentsmoderation', null, room)) || (this.can('voicetourmoderation'))) { this.parse('/tour new ' + target + ', elimination, 99, 3'); } }, pollr: 'pollremind', pollremind: function (target, room, user) { if (!Poll[room.id]) Poll.reset(room.id); if (!Poll[room.id].question) return this.sendReply("There is no poll currently going on in this room."); if (!this.canBroadcast()) return; this.sendReplyBox(Poll[room.id].display); }, tournamentpoll: 'tourpoll', tourneypoll: 'tourpoll', tourpoll: function (target, room, user) { if (!this.can('poll', null, room)) return false; this.parse("/poll Tournament format?," + "OU, Ubers, UU, RU, NU, PU, LC, VGC, Monotype, [Gen 4] OU, Random, 1v1 Random, Uber Random, High Tier Random, Low Tier Random, LC Random, Monotype Random, Generational Random, Color Random, Inverse Random, Community Random, Orb Random, Hoenn Random, Hoenn Weather Random, Super Smash Bros. Random, Winter Wonderland, Super Staff Bros., Metronome 3v3 Random, Doubles Random, Triples Random, Battle Factory, Hackmons Cup, [Seasonal] Random, [Gen 2] Random, [Gen 1] Random"); }, teampoll: function (target, room, user) { if (!this.can('poll', null, room)) return false; this.parse("/poll Tournament format?," + "OU, Ubers, UU, RU, NU, PU, LC, VGC, Monotype, [Gen 4] OU"); }, randbatpoll: 'randompoll', randbatspoll: 'randompoll', randpoll: 'randompoll', randompoll: function (target, room, user) { if (!this.can('poll', null, room)) return false; this.parse("/poll Tournament format?," + "Random, 1v1 Random, Uber Random, High Tier Random, Low Tier Random, LC Random, Monotype Random, Generational Random, Color Random, Inverse Random, Community Random, Orb Random, Hoenn Random, Hoenn Weather Random, Super Smash Bros. Random, Winter Wonderland, Super Staff Bros., Metronome 3v3 Random, Doubles Random, Triples Random, Battle Factory, Hackmons Cup, [Seasonal] Random, [Gen 2] Random, [Gen 1] Random"); }, vote: function (target, room, user) { if (!Poll[room.id]) Poll.reset(room.id); if (!Poll[room.id].question) return this.sendReply("There is no poll currently going on in this room."); if (!target) return this.parse('/help vote'); if (Poll[room.id].optionList.indexOf(target.toLowerCase()) === -1) return this.sendReply("'" + target + "' is not an option for the current poll."); var ips = JSON.stringify(user.ips); Poll[room.id].options[ips] = target.toLowerCase(); return this.sendReply("You are now voting for " + target + "."); }, votehelp: ["/vote [option] - Vote for an option in the poll."], votes: function (target, room, user) { if (!this.canBroadcast()) return; if (!Poll[room.id]) Poll.reset(room.id); if (!Poll[room.id].question) return this.sendReply("There is no poll currently going on in this room."); this.sendReply("NUMBER OF VOTES: " + Object.keys(Poll[room.id].options).length); } };
yashagl/yash-showdown
chat-plugins/poll.js
JavaScript
mit
7,034
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M19.5 3.5 18 2l-1.5 1.5L15 2l-1.5 1.5L12 2l-1.5 1.5L9 2 7.5 3.5 6 2v14H3v3c0 1.66 1.34 3 3 3h12c1.66 0 3-1.34 3-3V2l-1.5 1.5zM15 20H6c-.55 0-1-.45-1-1v-1h10v2zm4-1c0 .55-.45 1-1 1s-1-.45-1-1v-3H8V5h11v14z" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M9 7h6v2H9zm7 0h2v2h-2zm-7 3h6v2H9zm7 0h2v2h-2z" }, "1")], 'ReceiptLongOutlined'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/ReceiptLongOutlined.js
JavaScript
mit
793
/** * Created by Jeroen on 17/08/16. */ import { Meteor } from 'meteor/meteor' import { FollowData } from '/imports/api/follow_data/collection' if(Meteor.isServer){ Meteor.methods({ Follow(toFollow){ var protagonist = FollowData.findOne({uID: Meteor.userId()}) var subject = FollowData.findOne({uID: toFollow}) FollowData.update({_id: subject._id}, {$addToSet: {followers: Meteor.userId()}}) FollowData.update({_id: protagonist._id}, {$addToSet: {following: toFollow}}) }, Unfollow(toUnfollow){ var protagonist = FollowData.findOne({uID: Meteor.userId()}) var subject = FollowData.findOne({uID: toUnfollow}) FollowData.update({_id: subject._id}, {$pull: {followers: Meteor.userId()}}) FollowData.update({_id: protagonist._id}, {$pull : {following: toUnfollow}}); } }) }
JeroenBe/SnapTwit
imports/api/follow_data/methods.js
JavaScript
mit
913
import { assert } from 'chai' import { clientRect } from 'chirashi' window.describe('chirashi#clientRect', () => { window.it('should be a function', () => { assert.isFunction(clientRect) }) window.it('should return element\'s position on screen', () => { let poulp = document.createElement('div') poulp.classList.add('poulp') document.body.appendChild(poulp) Object.assign(document.body.style, { margin: 0, padding: 0, position: 'relative' }) Object.assign(document.documentElement.style, { margin: 0, padding: 0 }) Object.assign(poulp.style, { display: 'block', position: 'fixed', top: '200px', left: '240px', width: '100px', height: '100px', background: 'red' }) const boundingClientRect = clientRect(poulp) assert.equal(boundingClientRect.top, 200, 'should return correct top position') assert.equal(boundingClientRect.left, 240, 'should return correct left position') assert.equal(boundingClientRect.width, 100, 'should return correct width') assert.equal(boundingClientRect.height, 100, 'should return correct height') assert.isFalse(clientRect(null), 'should return false if element isn\'t valid') document.body.removeChild(poulp) }) })
chirashijs/chirashi
test/styles/clientRect.js
JavaScript
mit
1,298
/* * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, evil:true */ /*global window, document:true, CollectionUtils:true */ window.setTimeout(function () { "use strict"; var deps = { "Mustache": window.Mustache, "jQuery": window.$, "RequireJS": window.require }; var key, missingDeps = []; for (key in deps) { if (deps.hasOwnProperty(key) && !deps[key]) { missingDeps.push(key); } } if (missingDeps.length === 0) { return; } document.write("<h1>Missing libraries</h1>"); document.write("<p>Oops! One or more required libraries could not be found.</p>"); document.write("<ul>"); missingDeps.forEach(function (key) { document.write("<li>" + key + "</li>"); }); document.write("</ul>"); document.write("<p>If you're running from a local copy of the Brackets source, please make sure submodules are updated by running:</p>"); document.write("<pre>git submodule update --init</pre>"); document.write("<p>If you're still having problems, please contact us via one of the channels mentioned at the bottom of the <a target=\"blank\" href=\"../README.md\">README</a>.</p>"); document.write("<p><a href=\"#\" onclick=\"window.location.reload()\">Reload Brackets</a></p>"); }, 1000);
ab7/brackets
src/dependencies.js
JavaScript
mit
2,489
// @flow import * as result from 'orio-result' import { AsIterator, ToString } from 'orio-traits' import type { Producer } from 'orio-types' @ToString @AsIterator export default class Map<T, U> implements Producer<U> { /*:: @@iterator: () => Iterator<U> */ fn: T => U producer: Producer<T> constructor(producer: Producer<T>, fn: T => U) { this.fn = fn this.producer = producer } drop(): void { this.producer.drop() } next(): IteratorResult<U, void> { const next = this.producer.next() if (next.done) { return next } return result.next(this.fn(next.value)) } }
zacharygolba/iter.js
packages/orio-iter/src/adapter/map.js
JavaScript
mit
619
var countries = [ {name: 'Åland Islands', code: 'AX'}, {name: 'Afghanistan', code: 'AF'}, {name: 'Albania', code: 'AL'}, {name: 'Algeria', code: 'DZ'}, {name: 'American Samoa', code: 'AS'}, {name: 'Andorra', code: 'AD'}, {name: 'Angola', code: 'AO'}, {name: 'Anguilla', code: 'AI'}, {name: 'Antarctica', code: 'AQ'}, {name: 'Antigua and Barbuda', code: 'AG'}, {name: 'Argentina', code: 'AR'}, {name: 'Armenia', code: 'AM'}, {name: 'Aruba', code: 'AW'}, {name: 'Australia', code: 'AU'}, {name: 'Austria', code: 'AT'}, {name: 'Azerbaijan', code: 'AZ'}, {name: 'Bahamas', code: 'BS'}, {name: 'Bahrain', code: 'BH'}, {name: 'Bangladesh', code: 'BD'}, {name: 'Barbados', code: 'BB'}, {name: 'Belarus', code: 'BY'}, {name: 'Belgium', code: 'BE'}, {name: 'Belize', code: 'BZ'}, {name: 'Benin', code: 'BJ'}, {name: 'Bermuda', code: 'BM'}, {name: 'Bhutan', code: 'BT'}, {name: 'Bolivia', code: 'BO'}, {name: 'Bosnia and Herzegovina', code: 'BA'}, {name: 'Botswana', code: 'BW'}, {name: 'Bouvet Island', code: 'BV'}, {name: 'Brazil', code: 'BR'}, {name: 'British Indian Ocean Territory', code: 'IO'}, {name: 'Brunei Darussalam', code: 'BN'}, {name: 'Bulgaria', code: 'BG'}, {name: 'Burkina Faso', code: 'BF'}, {name: 'Burundi', code: 'BI'}, {name: 'Cambodia', code: 'KH'}, {name: 'Cameroon', code: 'CM'}, {name: 'Canada', code: 'CA'}, {name: 'Cape Verde', code: 'CV'}, {name: 'Cayman Islands', code: 'KY'}, {name: 'Central African Republic', code: 'CF'}, {name: 'Chad', code: 'TD'}, {name: 'Chile', code: 'CL'}, {name: 'China', code: 'CN'}, {name: 'Christmas Island', code: 'CX'}, {name: 'Cocos (Keeling) Islands', code: 'CC'}, {name: 'Colombia', code: 'CO'}, {name: 'Comoros', code: 'KM'}, {name: 'Congo', code: 'CG'}, {name: 'Congo, The Democratic Republic of the', code: 'CD'}, {name: 'Cook Islands', code: 'CK'}, {name: 'Costa Rica', code: 'CR'}, {name: 'Cote D\'Ivoire', code: 'CI'}, {name: 'Croatia', code: 'HR'}, {name: 'Cuba', code: 'CU'}, {name: 'Cyprus', code: 'CY'}, {name: 'Czech Republic', code: 'CZ'}, {name: 'Denmark', code: 'DK'}, {name: 'Djibouti', code: 'DJ'}, {name: 'Dominica', code: 'DM'}, {name: 'Dominican Republic', code: 'DO'}, {name: 'Ecuador', code: 'EC'}, {name: 'Egypt', code: 'EG'}, {name: 'El Salvador', code: 'SV'}, {name: 'Equatorial Guinea', code: 'GQ'}, {name: 'Eritrea', code: 'ER'}, {name: 'Estonia', code: 'EE'}, {name: 'Ethiopia', code: 'ET'}, {name: 'Falkland Islands (Malvinas)', code: 'FK'}, {name: 'Faroe Islands', code: 'FO'}, {name: 'Fiji', code: 'FJ'}, {name: 'Finland', code: 'FI'}, {name: 'France', code: 'FR'}, {name: 'French Guiana', code: 'GF'}, {name: 'French Polynesia', code: 'PF'}, {name: 'French Southern Territories', code: 'TF'}, {name: 'Gabon', code: 'GA'}, {name: 'Gambia', code: 'GM'}, {name: 'Georgia', code: 'GE'}, {name: 'Germany', code: 'DE'}, {name: 'Ghana', code: 'GH'}, {name: 'Gibraltar', code: 'GI'}, {name: 'Greece', code: 'GR'}, {name: 'Greenland', code: 'GL'}, {name: 'Grenada', code: 'GD'}, {name: 'Guadeloupe', code: 'GP'}, {name: 'Guam', code: 'GU'}, {name: 'Guatemala', code: 'GT'}, {name: 'Guernsey', code: 'GG'}, {name: 'Guinea', code: 'GN'}, {name: 'Guinea-Bissau', code: 'GW'}, {name: 'Guyana', code: 'GY'}, {name: 'Haiti', code: 'HT'}, {name: 'Heard Island and Mcdonald Islands', code: 'HM'}, {name: 'Holy See (Vatican City State)', code: 'VA'}, {name: 'Honduras', code: 'HN'}, {name: 'Hong Kong', code: 'HK'}, {name: 'Hungary', code: 'HU'}, {name: 'Iceland', code: 'IS'}, {name: 'India', code: 'IN'}, {name: 'Indonesia', code: 'ID'}, {name: 'Iran, Islamic Republic Of', code: 'IR'}, {name: 'Iraq', code: 'IQ'}, {name: 'Ireland', code: 'IE'}, {name: 'Isle of Man', code: 'IM'}, {name: 'Israel', code: 'IL'}, {name: 'Italy', code: 'IT'}, {name: 'Jamaica', code: 'JM'}, {name: 'Japan', code: 'JP'}, {name: 'Jersey', code: 'JE'}, {name: 'Jordan', code: 'JO'}, {name: 'Kazakhstan', code: 'KZ'}, {name: 'Kenya', code: 'KE'}, {name: 'Kiribati', code: 'KI'}, {name: 'Korea, Democratic People\'S Republic of', code: 'KP'}, {name: 'Korea, Republic of', code: 'KR'}, {name: 'Kuwait', code: 'KW'}, {name: 'Kyrgyzstan', code: 'KG'}, {name: 'Lao People\'S Democratic Republic', code: 'LA'}, {name: 'Latvia', code: 'LV'}, {name: 'Lebanon', code: 'LB'}, {name: 'Lesotho', code: 'LS'}, {name: 'Liberia', code: 'LR'}, {name: 'Libyan Arab Jamahiriya', code: 'LY'}, {name: 'Liechtenstein', code: 'LI'}, {name: 'Lithuania', code: 'LT'}, {name: 'Luxembourg', code: 'LU'}, {name: 'Macao', code: 'MO'}, {name: 'Macedonia, The Former Yugoslav Republic of', code: 'MK'}, {name: 'Madagascar', code: 'MG'}, {name: 'Malawi', code: 'MW'}, {name: 'Malaysia', code: 'MY'}, {name: 'Maldives', code: 'MV'}, {name: 'Mali', code: 'ML'}, {name: 'Malta', code: 'MT'}, {name: 'Marshall Islands', code: 'MH'}, {name: 'Martinique', code: 'MQ'}, {name: 'Mauritania', code: 'MR'}, {name: 'Mauritius', code: 'MU'}, {name: 'Mayotte', code: 'YT'}, {name: 'Mexico', code: 'MX'}, {name: 'Micronesia, Federated States of', code: 'FM'}, {name: 'Moldova, Republic of', code: 'MD'}, {name: 'Monaco', code: 'MC'}, {name: 'Mongolia', code: 'MN'}, {name: 'Montserrat', code: 'MS'}, {name: 'Morocco', code: 'MA'}, {name: 'Mozambique', code: 'MZ'}, {name: 'Myanmar', code: 'MM'}, {name: 'Namibia', code: 'NA'}, {name: 'Nauru', code: 'NR'}, {name: 'Nepal', code: 'NP'}, {name: 'Netherlands', code: 'NL'}, {name: 'Netherlands Antilles', code: 'AN'}, {name: 'New Caledonia', code: 'NC'}, {name: 'New Zealand', code: 'NZ'}, {name: 'Nicaragua', code: 'NI'}, {name: 'Niger', code: 'NE'}, {name: 'Nigeria', code: 'NG'}, {name: 'Niue', code: 'NU'}, {name: 'Norfolk Island', code: 'NF'}, {name: 'Northern Mariana Islands', code: 'MP'}, {name: 'Norway', code: 'NO'}, {name: 'Oman', code: 'OM'}, {name: 'Pakistan', code: 'PK'}, {name: 'Palau', code: 'PW'}, {name: 'Palestinian Territory, Occupied', code: 'PS'}, {name: 'Panama', code: 'PA'}, {name: 'Papua New Guinea', code: 'PG'}, {name: 'Paraguay', code: 'PY'}, {name: 'Peru', code: 'PE'}, {name: 'Philippines', code: 'PH'}, {name: 'Pitcairn', code: 'PN'}, {name: 'Poland', code: 'PL'}, {name: 'Portugal', code: 'PT'}, {name: 'Puerto Rico', code: 'PR'}, {name: 'Qatar', code: 'QA'}, {name: 'Reunion', code: 'RE'}, {name: 'Romania', code: 'RO'}, {name: 'Russian Federation', code: 'RU'}, {name: 'RWANDA', code: 'RW'}, {name: 'Saint Helena', code: 'SH'}, {name: 'Saint Kitts and Nevis', code: 'KN'}, {name: 'Saint Lucia', code: 'LC'}, {name: 'Saint Pierre and Miquelon', code: 'PM'}, {name: 'Saint Vincent and the Grenadines', code: 'VC'}, {name: 'Samoa', code: 'WS'}, {name: 'San Marino', code: 'SM'}, {name: 'Sao Tome and Principe', code: 'ST'}, {name: 'Saudi Arabia', code: 'SA'}, {name: 'Senegal', code: 'SN'}, {name: 'Serbia and Montenegro', code: 'CS'}, {name: 'Seychelles', code: 'SC'}, {name: 'Sierra Leone', code: 'SL'}, {name: 'Singapore', code: 'SG'}, {name: 'Slovakia', code: 'SK'}, {name: 'Slovenia', code: 'SI'}, {name: 'Solomon Islands', code: 'SB'}, {name: 'Somalia', code: 'SO'}, {name: 'South Africa', code: 'ZA'}, {name: 'South Georgia and the South Sandwich Islands', code: 'GS'}, {name: 'Spain', code: 'ES'}, {name: 'Sri Lanka', code: 'LK'}, {name: 'Sudan', code: 'SD'}, {name: 'Suriname', code: 'SR'}, {name: 'Svalbard and Jan Mayen', code: 'SJ'}, {name: 'Swaziland', code: 'SZ'}, {name: 'Sweden', code: 'SE'}, {name: 'Switzerland', code: 'CH'}, {name: 'Syrian Arab Republic', code: 'SY'}, {name: 'Taiwan, Province of China', code: 'TW'}, {name: 'Tajikistan', code: 'TJ'}, {name: 'Tanzania, United Republic of', code: 'TZ'}, {name: 'Thailand', code: 'TH'}, {name: 'Timor-Leste', code: 'TL'}, {name: 'Togo', code: 'TG'}, {name: 'Tokelau', code: 'TK'}, {name: 'Tonga', code: 'TO'}, {name: 'Trinidad and Tobago', code: 'TT'}, {name: 'Tunisia', code: 'TN'}, {name: 'Turkey', code: 'TR'}, {name: 'Turkmenistan', code: 'TM'}, {name: 'Turks and Caicos Islands', code: 'TC'}, {name: 'Tuvalu', code: 'TV'}, {name: 'Uganda', code: 'UG'}, {name: 'Ukraine', code: 'UA'}, {name: 'United Arab Emirates', code: 'AE'}, {name: 'United Kingdom', code: 'GB'}, {name: 'United States', code: 'US'}, {name: 'United States Minor Outlying Islands', code: 'UM'}, {name: 'Uruguay', code: 'UY'}, {name: 'Uzbekistan', code: 'UZ'}, {name: 'Vanuatu', code: 'VU'}, {name: 'Venezuela', code: 'VE'}, {name: 'Viet Nam', code: 'VN'}, {name: 'Virgin Islands, British', code: 'VG'}, {name: 'Virgin Islands, U.S.', code: 'VI'}, {name: 'Wallis and Futuna', code: 'WF'}, {name: 'Western Sahara', code: 'EH'}, {name: 'Yemen', code: 'YE'}, {name: 'Zambia', code: 'ZM'}, {name: 'Zimbabwe', code: 'ZW'} ]; (function () { 'use strict'; function _hasClass(el, cls) { if (!el) return; if (el.classList) return el.classList.contains(cls); else return new RegExp('(^| )' + cls + '( |$)', 'gi').test(el.className); } function _addClass(el, cls) { if (el.classList) { var arr = cls.split(' '); for (var i in arr) el.classList.add(arr[i]); } else el.className += ' ' + cls; } function _removeClass(el, cls) { if (el.classList) { var arr = cls.split(' '); for (var i in arr) el.classList.remove(arr[i]); } else el.className = el.className.replace(new RegExp('(^|\\b)' + cls.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); } var throttle = function (e, name, obj) { obj = obj || window; var running = false; var func = function () { if (running) return; running = true; requestAnimationFrame(function () { obj.dispatchEvent(new CustomEvent(name)); running = false; }); }; obj.addEventListener(e, func); }; throttle("scroll", "optimizedScroll"); this.stickyHeader = function(el,cls){ var rect = el.getBoundingClientRect(); var i = parseInt(document.body.style.paddingTop,10) || 0; window.addEventListener("optimizedScroll", function () { if (document.body.scrollTop > rect.top) { if (_hasClass(el, cls)) return; document.body.style.paddingTop = i + el.scrollHeight + 'px'; _addClass(el, cls); } else { if (!_hasClass(el, cls)) return; _removeClass(el, cls); document.body.style.paddingTop = 'inherit'; } }); }; }).call(this); (function () { 'use strict'; document.addEventListener('DOMContentLoaded', function () { var demo1 = document.querySelector('#demo1'); var html = ''; for(var c in countries) { var country = countries[c]; html += '<option>'+ country.name + '</option>'; } demo1.innerHTML = html; var combo = ComboBox('#demo1'); combo.onWillAdd = function(value) { return value != 'test'; }; combo.onDidAdd = function(value) { console.log('added "'+value+'"'); }; combo.onWillRemove = function(value) { return value != 'stuck'; }; combo.onDidRemove = function(value) { console.log('removed "'+value+'"'); }; combo.onRenderValue = function(value) { return '<div class="combobox-value">' + value + '</div>'; }; combo.onRenderOption = function(value) { return '<div class="combobox-option">' + value + '</div>'; }; /*stickyHeader(document.getElementById('nav'),'nav-fixed');*/ /*var combo2 = ComboBox('#demo2'); combo2.focus();*/ }); }).call(this);
tomasgreen/combobox
src/example/js/core.js
JavaScript
mit
11,570
Clazz.declarePackage ("J.adapter.readers.quantum"); Clazz.load (["J.adapter.readers.quantum.MOReader"], "J.adapter.readers.quantum.GenNBOReader", ["java.lang.Boolean", "$.Exception", "$.Float", "java.util.Hashtable", "JU.AU", "$.Lst", "$.PT", "$.Rdr", "$.SB", "J.api.JmolAdapter", "JU.Logger"], function () { c$ = Clazz.decorateAsClass (function () { this.isOutputFile = false; this.moType = ""; this.nOrbitals0 = 0; Clazz.instantialize (this, arguments); }, J.adapter.readers.quantum, "GenNBOReader", J.adapter.readers.quantum.MOReader); Clazz.defineMethod (c$, "initializeReader", function () { var line1 = this.rd ().trim (); this.rd (); this.isOutputFile = (this.line.indexOf ("***") >= 0); var isOK; if (this.isOutputFile) { isOK = this.readFile31 (); Clazz.superCall (this, J.adapter.readers.quantum.GenNBOReader, "initializeReader", []); this.moData.put ("isNormalized", Boolean.TRUE); } else if (this.line.indexOf ("s in the AO basis:") >= 0) { this.moType = this.line.substring (1, this.line.indexOf ("s")); this.asc.setCollectionName (line1 + ": " + this.moType + "s"); isOK = this.readFile31 (); } else { this.moType = "AO"; this.asc.setCollectionName (line1 + ": " + this.moType + "s"); isOK = this.readData31 (line1, this.line); }if (!isOK) JU.Logger.error ("Unimplemented shell type -- no orbitals avaliable: " + this.line); if (this.isOutputFile) return; if (isOK) { this.readMOs (); }this.continuing = false; }); Clazz.defineMethod (c$, "readMOs", function () { this.nOrbitals0 = this.orbitals.size (); this.readFile46 (); this.readOrbitalData (!this.moType.equals ("AO")); this.setMOData (false); this.moData.put ("isNormalized", Boolean.TRUE); }); Clazz.overrideMethod (c$, "checkLine", function () { if (this.line.indexOf ("SECOND ORDER PERTURBATION THEORY ANALYSIS") >= 0 && !this.orbitalsRead) { this.moType = "NBO"; var data = this.getFileData (".37"); if (data == null) { this.moType = "PNBO"; data = this.getFileData (".36"); if (data == null) return true; }var readerSave = this.reader; this.reader = JU.Rdr.getBR (data); this.rd (); this.rd (); this.readMOs (); this.reader = readerSave; this.orbitalsRead = false; return true; }return this.checkNboLine (); }); Clazz.defineMethod (c$, "getFileData", function (ext) { var fileName = this.htParams.get ("fullPathName"); var pt = fileName.lastIndexOf ("."); if (pt < 0) pt = fileName.length; fileName = fileName.substring (0, pt) + ext; var data = this.vwr.getFileAsString3 (fileName, false, null); if (data.length == 0 || data.indexOf ("java.io.FileNotFound") >= 0) throw new Exception (" supplemental file " + fileName + " was not found"); return data; }, "~S"); Clazz.defineMethod (c$, "readFile31", function () { var data = this.getFileData (".31"); var readerSave = this.reader; this.reader = JU.Rdr.getBR (data); if (!this.readData31 (null, null)) return false; this.reader = readerSave; return true; }); Clazz.defineMethod (c$, "readFile46", function () { var data = this.getFileData (".46"); var readerSave = this.reader; this.reader = JU.Rdr.getBR (data); this.readData46 (); this.reader = readerSave; }); Clazz.defineMethod (c$, "readData31", function (line1, line2) { if (line1 == null) line1 = this.rd (); if (line2 == null) line2 = this.rd (); this.rd (); var tokens = J.adapter.smarter.AtomSetCollectionReader.getTokensStr (this.rd ()); var ac = this.parseIntStr (tokens[0]); this.shellCount = this.parseIntStr (tokens[1]); this.gaussianCount = this.parseIntStr (tokens[2]); this.rd (); this.asc.newAtomSet (); this.asc.setAtomSetName (this.moType + "s: " + line1.trim ()); for (var i = 0; i < ac; i++) { tokens = J.adapter.smarter.AtomSetCollectionReader.getTokensStr (this.rd ()); var z = this.parseIntStr (tokens[0]); if (z < 0) continue; var atom = this.asc.addNewAtom (); atom.elementNumber = z; this.setAtomCoordTokens (atom, tokens, 1); } this.shells = new JU.Lst (); this.gaussians = JU.AU.newFloat2 (this.gaussianCount); for (var i = 0; i < this.gaussianCount; i++) this.gaussians[i] = Clazz.newFloatArray (6, 0); this.rd (); this.nOrbitals = 0; for (var i = 0; i < this.shellCount; i++) { tokens = J.adapter.smarter.AtomSetCollectionReader.getTokensStr (this.rd ()); var slater = Clazz.newIntArray (4, 0); slater[0] = this.parseIntStr (tokens[0]) - 1; var n = this.parseIntStr (tokens[1]); this.nOrbitals += n; this.line = this.rd ().trim (); switch (n) { case 1: slater[1] = J.api.JmolAdapter.SHELL_S; break; case 3: if (!this.getDFMap (this.line, J.api.JmolAdapter.SHELL_P, J.adapter.readers.quantum.GenNBOReader.$P_LIST, 3)) return false; slater[1] = J.api.JmolAdapter.SHELL_P; break; case 4: if (!this.getDFMap (this.line, J.api.JmolAdapter.SHELL_SP, J.adapter.readers.quantum.GenNBOReader.SP_LIST, 1)) return false; slater[1] = J.api.JmolAdapter.SHELL_SP; break; case 5: if (!this.getDFMap (this.line, J.api.JmolAdapter.SHELL_D_SPHERICAL, J.adapter.readers.quantum.GenNBOReader.$DS_LIST, 3)) return false; slater[1] = J.api.JmolAdapter.SHELL_D_SPHERICAL; break; case 6: if (!this.getDFMap (this.line, J.api.JmolAdapter.SHELL_D_CARTESIAN, J.adapter.readers.quantum.GenNBOReader.$DC_LIST, 3)) return false; slater[1] = J.api.JmolAdapter.SHELL_D_CARTESIAN; break; case 7: if (!this.getDFMap (this.line, J.api.JmolAdapter.SHELL_F_SPHERICAL, J.adapter.readers.quantum.GenNBOReader.$FS_LIST, 3)) return false; slater[1] = J.api.JmolAdapter.SHELL_F_SPHERICAL; break; case 10: if (!this.getDFMap (this.line, J.api.JmolAdapter.SHELL_F_CARTESIAN, J.adapter.readers.quantum.GenNBOReader.$FC_LIST, 3)) return false; slater[1] = J.api.JmolAdapter.SHELL_F_CARTESIAN; break; } slater[2] = this.parseIntStr (tokens[2]) - 1; slater[3] = this.parseIntStr (tokens[3]); this.shells.addLast (slater); } for (var j = 0; j < 5; j++) { this.rd (); var temp = this.fillFloatArray (null, 0, Clazz.newFloatArray (this.gaussianCount, 0)); for (var i = 0; i < this.gaussianCount; i++) { this.gaussians[i][j] = temp[i]; if (j > 1) this.gaussians[i][5] += temp[i]; } } for (var i = 0; i < this.gaussianCount; i++) { if (this.gaussians[i][1] == 0) this.gaussians[i][1] = this.gaussians[i][5]; } if (JU.Logger.debugging) { JU.Logger.debug (this.shells.size () + " slater shells read"); JU.Logger.debug (this.gaussians.length + " gaussian primitives read"); }return true; }, "~S,~S"); Clazz.defineMethod (c$, "readData46", function () { var tokens = J.adapter.smarter.AtomSetCollectionReader.getTokensStr (this.rd ()); var ipt = 1; if (tokens[1].equals ("ALPHA")) { ipt = 2; if (this.haveNboOrbitals) { tokens = J.adapter.smarter.AtomSetCollectionReader.getTokensStr (this.discardLinesUntilContains ("BETA")); this.alphaBeta = "beta"; } else { this.alphaBeta = "alpha"; this.haveNboOrbitals = true; }}if (this.parseIntStr (tokens[ipt]) != this.nOrbitals) { JU.Logger.error ("file 46 number of orbitals does not match nOrbitals: " + this.nOrbitals); return false; }var ntype = null; if (this.moType.equals ("AO")) ntype = "AO"; else if (this.moType.indexOf ("NHO") >= 0) ntype = "NHO"; else if (this.moType.indexOf ("NBO") >= 0) ntype = "NBO"; else if (this.moType.indexOf ("NAO") >= 0) ntype = "NAO"; else if (this.moType.indexOf ("MO") >= 0) ntype = "MO"; if (ntype == null) { JU.Logger.error ("uninterpretable type " + this.moType); return false; }if (!ntype.equals ("AO")) this.discardLinesUntilContains (ntype.equals ("MO") ? "NBO" : ntype); var sb = new JU.SB (); while (this.rd () != null && this.line.indexOf ("O ") < 0 && this.line.indexOf ("ALPHA") < 0 && this.line.indexOf ("BETA") < 0) sb.append (this.line); sb.appendC (' '); var data = sb.toString (); var n = data.length - 1; sb = new JU.SB (); for (var i = 0; i < n; i++) { var c = data.charAt (i); switch (c) { case '(': case '-': if (data.charAt (i + 1) == ' ') i++; break; case ' ': if (JU.PT.isDigit (data.charAt (i + 1)) || data.charAt (i + 1) == '(') continue; break; } sb.appendC (c); } JU.Logger.info (sb.toString ()); tokens = J.adapter.smarter.AtomSetCollectionReader.getTokensStr (sb.toString ()); for (var i = 0; i < tokens.length; i++) { var mo = new java.util.Hashtable (); this.setMO (mo); } if (ntype.equals ("MO")) return true; for (var i = 0; i < tokens.length; i++) { var mo = this.orbitals.get (i + this.nOrbitals0); var type = tokens[i]; mo.put ("type", this.moType + " " + type); mo.put ("occupancy", Float.$valueOf (type.indexOf ("*") >= 0 ? 0 : 2)); } return true; }); Clazz.defineMethod (c$, "readOrbitalData", function (isMO) { var nAOs = this.nOrbitals; this.nOrbitals = this.orbitals.size (); this.line = null; for (var i = this.nOrbitals0; i < this.nOrbitals; i++) { var mo = this.orbitals.get (i); var coefs = Clazz.newFloatArray (nAOs, 0); mo.put ("coefficients", coefs); if (isMO) { if (this.line == null) { while (this.rd () != null && Float.isNaN (this.parseFloatStr (this.line))) { } } else { this.line = null; }this.fillFloatArray (this.line, 0, coefs); this.line = null; } else { coefs[i] = 1; }} if (this.moType.equals ("NBO")) { var occupancies = Clazz.newFloatArray (this.nOrbitals - this.nOrbitals0, 0); this.fillFloatArray (null, 0, occupancies); for (var i = this.nOrbitals0; i < this.nOrbitals; i++) { var mo = this.orbitals.get (i); mo.put ("occupancy", Float.$valueOf (Clazz.floatToInt (occupancies[i - this.nOrbitals0] + 0.2))); } }}, "~B"); Clazz.defineStatics (c$, "$P_LIST", "101 102 103", "SP_LIST", "1 101 102 103", "$DS_LIST", "255 252 253 254 251", "$DC_LIST", "201 204 206 202 203 205", "$FS_LIST", "351 352 353 354 355 356 357", "$FC_LIST", "301 307 310 304 302 303 306 309 308 305"); });
mausdin/MOFsite
jsmol/j2s/J/adapter/readers/quantum/GenNBOReader.js
JavaScript
mit
9,838
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * Creates a new Pixel Perfect Handler function. * * Access via `InputPlugin.makePixelPerfect` rather than calling it directly. * * @function Phaser.Input.CreatePixelPerfectHandler * @since 3.10.0 * * @param {Phaser.Textures.TextureManager} textureManager - A reference to the Texture Manager. * @param {integer} alphaTolerance - The alpha level that the pixel should be above to be included as a successful interaction. * * @return {function} The new Pixel Perfect Handler function. */ var CreatePixelPerfectHandler = function (textureManager, alphaTolerance) { return function (hitArea, x, y, gameObject) { var alpha = textureManager.getPixelAlpha(x, y, gameObject.texture.key, gameObject.frame.name); return (alpha && alpha >= alphaTolerance); }; }; module.exports = CreatePixelPerfectHandler;
TukekeSoft/phaser
src/input/CreatePixelPerfectHandler.js
JavaScript
mit
1,018
var Twit = require('twit'); // read config file, containing twitter oauth data and various other preferences var config = require("./config").read("application"); if (JSON.stringify(config.twitter.auth).indexOf("...") > 0) { console.log("Please add your Twitter API authorization tokens to `application.config`"); process.exit(1); }; exports.fetch = function(callback) { // NOTE: take care when changing the search_interval variable // the rate limit in Search API v1.1 is 180 requests / 15 minutes, meaning 1 request every 5 seconds setInterval(function() { fetchTweets(callback); }, config.twitter.search_interval * 1000); fetchTweets(callback); }; function fetchTweets(callback) { var T = new Twit({ consumer_key : config.twitter.auth.consumer_key, consumer_secret : config.twitter.auth.consumer_secret, access_token : config.twitter.auth.access_token, access_token_secret : config.twitter.auth.access_token_secret }); var stream = T.stream('statuses/filter', { track: config.twitter.search_terms, langauge:'en' }); stream.on('tweet', function (tweet) { // console.log(tweet.text) callback({ id: tweet.id_str, text: tweet.text, author: tweet.user.name, username: tweet.user.screen_name, }); }); }
StuartFeldt/longest-poem-in-the-world
engine/twitter.js
JavaScript
mit
1,247
// * ———————————————————————————————————————————————————————— * // // * ab tester // * handles a/b testing // * ———————————————————————————————————————————————————————— * // const ab_tester = function () {} // * vendor dependencies const _ = require('lodash') // * enduro dependencies const page_queue_generator = require(enduro.enduro_path + '/libs/page_rendering/page_queue_generator') // * ———————————————————————————————————————————————————————— * // // * get ab list // * generates list of ab testing races // * // * list looks like this: // * { // * index: [ // * { // * page: 'index' // * }, { // * page: 'index@ab' // * }, { // * page: 'index@bb' // * } // * ], // * test: [ // * { // * page: 'test' // * }, { // * page: 'test@bigbutton' // * } // * ] // * } // * // * @return {object} - array of testing races // * ———————————————————————————————————————————————————————— * // ab_tester.prototype.get_ab_list = function () { return page_queue_generator.get_all_pages() .then((pages) => { // gets page list pages = pages.map((page) => { return page_queue_generator.get_page_url_from_full_path(page).split('@') }) // groups by page pages = _.groupBy(pages, (page) => { return page[0] }) // removes first item for (p in pages) { pages[p].shift() pages[p].map((page) => { page.shift() }) if (!pages[p].length) { delete pages[p] continue } pages[p].unshift([]) // add urls and paths pages[p] = pages[p].map((page) => { const file = page.length ? p + '@' + page : p return { page: file } }) } return pages }) } ab_tester.prototype.get_ab_tested_filepath = function (url, req, res) { const self = this // removes slash from the front page_name = url[0] == '/' ? url.substring(1) : url return new Promise(function (resolve, reject) { self.generate_global_ab_list_if_nonexistent() .then(() => { // return if page does not have an ab_tests if (!(page_name in global.ab_test_scenarios)) { return resolve(url) } const ab_scenario = global.ab_test_scenarios[page_name] let picked_variation // check if user has cookie for this url if (req.cookies['enduro_ab_' + url]) { picked_variation = req.cookies['enduro_ab_' + url] } else { picked_variation = ab_scenario[Math.floor(Math.random() * ab_scenario.length)] res.cookie('enduro_ab_' + url, picked_variation, { maxAge: 900000, httpOnly: true }) } if (picked_variation.page == 'index') { resolve('/index') } else { resolve('/' + picked_variation.page + '/index') } }) }) } ab_tester.prototype.generate_global_ab_list_if_nonexistent = function () { const self = this return new Promise(function (resolve, reject) { if (typeof global.ab_test_scenarios === 'undefined') { self.generate_global_ab_list() .then(() => { resolve() }) } else { resolve() } }) } ab_tester.prototype.generate_global_ab_list = function () { const self = this return self.get_ab_list() .then((ab_list) => { global.ab_test_scenarios = ab_list }) } module.exports = new ab_tester()
Gottwik/Enduro
libs/ab_testing/ab_tester.js
JavaScript
mit
3,644
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M18.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 10v4c0 .55.45 1 1 1h3l3.29 3.29c.63.63 1.71.18 1.71-.71V6.41c0-.89-1.08-1.34-1.71-.71L9 9H6c-.55 0-1 .45-1 1z" /> , 'VolumeDownRounded');
lgollut/material-ui
packages/material-ui-icons/src/VolumeDownRounded.js
JavaScript
mit
333
module.exports = [ [ "a00.js", "b00.js", "c00.js", "d00.js", "e00.js", "f00.js", "g00.js", "h00.js", "i00.js", "j00.js", "k00.js", "l00.js", "m00.js", "n00.js", "o00.js", "p00.js", "q00.js", "r00.js", "s00.js", "t00.js", "u00.js", "v00.js", "w00.js", "x00.js", "y00.js", "z00.js", "a01.js", "b01.js", "c01.js", "d01.js", "e01.js", "f01.js", "g01.js", "h01.js", "i01.js", "j01.js", "k01.js", "l01.js", "m01.js", "n01.js", "o01.js", "p01.js", "q01.js", "r01.js", "s01.js", "t01.js", "u01.js", "v01.js", "w01.js", "x01.js", "y01.js", "z01.js", "a02.js", "b02.js", "c02.js", "d02.js", "e02.js", "f02.js", "g02.js", "h02.js", "i02.js", "j02.js", "k02.js", "l02.js", "m02.js", "n02.js", "o02.js", "p02.js", "q02.js", "r02.js", "s02.js", "t02.js", "u02.js", "v02.js", "w02.js", "x02.js", "y02.js", "z02.js", "a03.js", "b03.js", "c03.js", "d03.js", "e03.js", "f03.js", "g03.js", "h03.js", "i03.js", "j03.js", "k03.js", "l03.js", "m03.js", "n03.js", "o03.js", "p03.js", "q03.js", "r03.js", "s03.js", "t03.js", "u03.js", "v03.js", "w03.js", "x03.js", "y03.js", "z03.js", "a04.js", "b04.js", "c04.js", "d04.js", "e04.js", "f04.js", "g04.js", "h04.js", "i04.js", "j04.js", "k04.js", "l04.js", "m04.js", "n04.js", "o04.js", "p04.js", "q04.js", "r04.js", "s04.js", "t04.js", "u04.js", "v04.js", "w04.js", "x04.js", "y04.js", "z04.js", "a05.js", "b05.js", "c05.js", "d05.js", "e05.js", "f05.js", "g05.js", "h05.js", "i05.js", "j05.js", "k05.js", "l05.js", "m05.js", "n05.js", "o05.js", "p05.js", "q05.js", "r05.js", "s05.js", "t05.js", "u05.js", "v05.js", "w05.js", "x05.js", "y05.js", "z05.js", "a06.js", "b06.js", "c06.js", "d06.js", "e06.js", "f06.js", "g06.js", "h06.js", "i06.js", "j06.js", "k06.js", "l06.js", "m06.js", "n06.js", "o06.js", "p06.js", "q06.js", "r06.js", "s06.js", "t06.js", "u06.js", "v06.js", "w06.js", "x06.js", "y06.js", "z06.js", "a07.js", "b07.js", "c07.js", "d07.js", "e07.js", "f07.js", "g07.js", "h07.js", "i07.js", "j07.js", "k07.js", "l07.js", "m07.js", "n07.js", "o07.js", "p07.js", "q07.js", "r07.js", "s07.js", "t07.js", "u07.js", "v07.js", "w07.js", "x07.js", "y07.js", "z07.js", "a08.js", "b08.js", "c08.js", "d08.js", "e08.js", "f08.js", "g08.js", "h08.js", "i08.js", "j08.js", "k08.js", "l08.js", "m08.js", "n08.js", "o08.js", "p08.js", "q08.js", "r08.js", "s08.js", "t08.js", "u08.js", "v08.js", "w08.js", "x08.js", "y08.js", "z08.js", "a09.js", "b09.js", "c09.js", "d09.js", "e09.js", "f09.js", "g09.js", "h09.js", "i09.js", "j09.js", "k09.js", "l09.js", "m09.js", "n09.js", "o09.js", "p09.js", "q09.js", "r09.js", "s09.js", "t09.js", "u09.js", "v09.js", "w09.js", "x09.js", "y09.js", "z09.js", "a10.js", "b10.js", "c10.js", "d10.js", "e10.js", "f10.js", "g10.js", "h10.js", "i10.js", "j10.js", "k10.js", "l10.js", "m10.js", "n10.js", "o10.js", "p10.js", "q10.js", "r10.js", "s10.js", "t10.js", "u10.js", "v10.js", "w10.js", "x10.js", "y10.js", "z10.js", "a00.md", "b00.md", "c00.md", "d00.md", "e00.md", "f00.md", "g00.md", "h00.md", "i00.md", "j00.md", "k00.md", "l00.md", "m00.md", "n00.md", "o00.md", "p00.md", "q00.md", "r00.md", "s00.md", "t00.md", "u00.md", "v00.md", "w00.md", "x00.md", "y00.md", "z00.md", "a01.md", "b01.md", "c01.md", "d01.md", "e01.md", "f01.md", "g01.md", "h01.md", "i01.md", "j01.md", "k01.md", "l01.md", "m01.md", "n01.md", "o01.md", "p01.md", "q01.md", "r01.md", "s01.md", "t01.md", "u01.md", "v01.md", "w01.md", "x01.md", "y01.md", "z01.md", "a02.md", "b02.md", "c02.md", "d02.md", "e02.md", "f02.md", "g02.md", "h02.md", "i02.md", "j02.md", "k02.md", "l02.md", "m02.md", "n02.md", "o02.md", "p02.md", "q02.md", "r02.md", "s02.md", "t02.md", "u02.md", "v02.md", "w02.md", "x02.md", "y02.md", "z02.md", "a03.md", "b03.md", "c03.md", "d03.md", "e03.md", "f03.md", "g03.md", "h03.md", "i03.md", "j03.md", "k03.md", "l03.md", "m03.md", "n03.md", "o03.md", "p03.md", "q03.md", "r03.md", "s03.md", "t03.md", "u03.md", "v03.md", "w03.md", "x03.md", "y03.md", "z03.md", "a04.md", "b04.md", "c04.md", "d04.md", "e04.md", "f04.md", "g04.md", "h04.md", "i04.md", "j04.md", "k04.md", "l04.md", "m04.md", "n04.md", "o04.md", "p04.md", "q04.md", "r04.md", "s04.md", "t04.md", "u04.md", "v04.md", "w04.md", "x04.md", "y04.md", "z04.md", "a05.md", "b05.md", "c05.md", "d05.md", "e05.md", "f05.md", "g05.md", "h05.md", "i05.md", "j05.md", "k05.md", "l05.md", "m05.md", "n05.md", "o05.md", "p05.md", "q05.md", "r05.md", "s05.md", "t05.md", "u05.md", "v05.md", "w05.md", "x05.md", "y05.md", "z05.md", "a06.md", "b06.md", "c06.md", "d06.md", "e06.md", "f06.md", "g06.md", "h06.md", "i06.md", "j06.md", "k06.md", "l06.md", "m06.md", "n06.md", "o06.md", "p06.md", "q06.md", "r06.md", "s06.md", "t06.md", "u06.md", "v06.md", "w06.md", "x06.md", "y06.md", "z06.md", "a07.md", "b07.md", "c07.md", "d07.md", "e07.md", "f07.md", "g07.md", "h07.md", "i07.md", "j07.md", "k07.md", "l07.md", "m07.md", "n07.md", "o07.md", "p07.md", "q07.md", "r07.md", "s07.md", "t07.md", "u07.md", "v07.md", "w07.md", "x07.md", "y07.md", "z07.md", "a08.md", "b08.md", "c08.md", "d08.md", "e08.md", "f08.md", "g08.md", "h08.md", "i08.md", "j08.md", "k08.md", "l08.md", "m08.md", "n08.md", "o08.md", "p08.md", "q08.md", "r08.md", "s08.md", "t08.md", "u08.md", "v08.md", "w08.md", "x08.md", "y08.md", "z08.md", "a09.md", "b09.md", "c09.md", "d09.md", "e09.md", "f09.md", "g09.md", "h09.md", "i09.md", "j09.md", "k09.md", "l09.md", "m09.md", "n09.md", "o09.md", "p09.md", "q09.md", "r09.md", "s09.md", "t09.md", "u09.md", "v09.md", "w09.md", "x09.md", "y09.md", "z09.md", "a10.md", "b10.md", "c10.md", "d10.md", "e10.md", "f10.md", "g10.md", "h10.md", "i10.md", "j10.md", "k10.md", "l10.md", "m10.md", "n10.md", "o10.md", "p10.md", "q10.md", "r10.md", "s10.md", "t10.md", "u10.md", "v10.md", "w10.md", "x10.md", "y10.md", "z10.md", "a00.txt", "b00.txt", "c00.txt", "d00.txt", "e00.txt", "f00.txt", "g00.txt", "h00.txt", "i00.txt", "j00.txt", "k00.txt", "l00.txt", "m00.txt", "n00.txt", "o00.txt", "p00.txt", "q00.txt", "r00.txt", "s00.txt", "t00.txt", "u00.txt", "v00.txt", "w00.txt", "x00.txt", "y00.txt", "z00.txt", "a01.txt", "b01.txt", "c01.txt", "d01.txt", "e01.txt", "f01.txt", "g01.txt", "h01.txt", "i01.txt", "j01.txt", "k01.txt", "l01.txt", "m01.txt", "n01.txt", "o01.txt", "p01.txt", "q01.txt", "r01.txt", "s01.txt", "t01.txt", "u01.txt", "v01.txt", "w01.txt", "x01.txt", "y01.txt", "z01.txt", "a02.txt", "b02.txt", "c02.txt", "d02.txt", "e02.txt", "f02.txt", "g02.txt", "h02.txt", "i02.txt", "j02.txt", "k02.txt", "l02.txt", "m02.txt", "n02.txt", "o02.txt", "p02.txt", "q02.txt", "r02.txt", "s02.txt", "t02.txt", "u02.txt", "v02.txt", "w02.txt", "x02.txt", "y02.txt", "z02.txt", "a03.txt", "b03.txt", "c03.txt", "d03.txt", "e03.txt", "f03.txt", "g03.txt", "h03.txt", "i03.txt", "j03.txt", "k03.txt", "l03.txt", "m03.txt", "n03.txt", "o03.txt", "p03.txt", "q03.txt", "r03.txt", "s03.txt", "t03.txt", "u03.txt", "v03.txt", "w03.txt", "x03.txt", "y03.txt", "z03.txt", "a04.txt", "b04.txt", "c04.txt", "d04.txt", "e04.txt", "f04.txt", "g04.txt", "h04.txt", "i04.txt", "j04.txt", "k04.txt", "l04.txt", "m04.txt", "n04.txt", "o04.txt", "p04.txt", "q04.txt", "r04.txt", "s04.txt", "t04.txt", "u04.txt", "v04.txt", "w04.txt", "x04.txt", "y04.txt", "z04.txt", "a05.txt", "b05.txt", "c05.txt", "d05.txt", "e05.txt", "f05.txt", "g05.txt", "h05.txt", "i05.txt", "j05.txt", "k05.txt", "l05.txt", "m05.txt", "n05.txt", "o05.txt", "p05.txt", "q05.txt", "r05.txt", "s05.txt", "t05.txt", "u05.txt", "v05.txt", "w05.txt", "x05.txt", "y05.txt", "z05.txt", "a06.txt", "b06.txt", "c06.txt", "d06.txt", "e06.txt", "f06.txt", "g06.txt", "h06.txt", "i06.txt", "j06.txt", "k06.txt", "l06.txt", "m06.txt", "n06.txt", "o06.txt", "p06.txt", "q06.txt", "r06.txt", "s06.txt", "t06.txt", "u06.txt", "v06.txt", "w06.txt", "x06.txt", "y06.txt", "z06.txt", "a07.txt", "b07.txt", "c07.txt", "d07.txt", "e07.txt", "f07.txt", "g07.txt", "h07.txt", "i07.txt", "j07.txt", "k07.txt", "l07.txt", "m07.txt", "n07.txt", "o07.txt", "p07.txt", "q07.txt", "r07.txt", "s07.txt", "t07.txt", "u07.txt", "v07.txt", "w07.txt", "x07.txt", "y07.txt", "z07.txt", "a08.txt", "b08.txt", "c08.txt", "d08.txt", "e08.txt", "f08.txt", "g08.txt", "h08.txt", "i08.txt", "j08.txt", "k08.txt", "l08.txt", "m08.txt", "n08.txt", "o08.txt", "p08.txt", "q08.txt", "r08.txt", "s08.txt", "t08.txt", "u08.txt", "v08.txt", "w08.txt", "x08.txt", "y08.txt", "z08.txt", "a09.txt", "b09.txt", "c09.txt", "d09.txt", "e09.txt", "f09.txt", "g09.txt", "h09.txt", "i09.txt", "j09.txt", "k09.txt", "l09.txt", "m09.txt", "n09.txt", "o09.txt", "p09.txt", "q09.txt", "r09.txt", "s09.txt", "t09.txt", "u09.txt", "v09.txt", "w09.txt", "x09.txt", "y09.txt", "z09.txt", "a10.txt", "b10.txt", "c10.txt", "d10.txt", "e10.txt", "f10.txt", "g10.txt", "h10.txt", "i10.txt", "j10.txt", "k10.txt", "l10.txt", "m10.txt", "n10.txt", "o10.txt", "p10.txt", "q10.txt", "r10.txt", "s10.txt", "t10.txt", "u10.txt", "v10.txt", "w10.txt", "x10.txt", "y10.txt", "z10.txt" ], "{k10,a01}.*" ];
masakura/micromatch
benchmark/fixtures/basename-braces.js
JavaScript
mit
12,343
import React from 'react' import Icon from 'react-icon-base' const IoIosStar = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m35 16.2l-10.9 7.6 4.2 12.5-10.8-7.8-10.8 7.8 4.2-12.5-10.9-7.6h13.4l4.1-12.4 4.1 12.4h13.4z"/></g> </Icon> ) export default IoIosStar
bengimbel/Solstice-React-Contacts-Project
node_modules/react-icons/io/ios-star.js
JavaScript
mit
294
import notBase from '../notBase'; import notPath from '../notPath'; import notCommon from '../common'; import notRecord from '../record'; import notComponent from '../template/notComponent'; const OPT_DEFAULT_DETAILS_PREFIX = 'details_', OPT_DEFAULT_ROLE_NAME = 'default', OPT_DEFAULT_DETAILS_TITLE = 'Details default title', OPT_DEFAULT_FIELD_DEFINITION = {}, OPT_DEFAULT_FIELD_DEFINITION_SOURCES_PRIORITY_LIST = ['options', 'manifest', 'app']; class notDetails extends notBase { constructor(input) { super(input); if (!this.getOptions('prefix')) { this.setOptions('prefix', OPT_DEFAULT_DETAILS_PREFIX); } this.setWorking('components', []); if (!this.getData().isRecord) { this.setData(new notRecord({}, this.getData())); } this.render(); return this; } getManifest() { return this.getData().getManifest(); } getActionData() { let manifest = this.getManifest(); if (manifest && manifest.actions) { return manifest.actions.hasOwnProperty(this.getOptions('action')) ? manifest.actions[this.getOptions('action')] : null; } else { return null; } } getFieldsList() { let actionData = this.getActionData(), list = [], role = this.getOptions('role', OPT_DEFAULT_ROLE_NAME); if (actionData) { if (actionData.fields) { if (actionData.fields.hasOwnProperty(role)) { list = actionData.fields[role]; } } } return list; } render() { this.renderWrapper(); } getPartTemplateName(formPart) { return this.getOptions('prefix') + formPart; } renderWrapper() { if (this.getWorking('wrapper')) { this.getWorking('wrapper').update(); } else { let input = { data: this.getWrapperData(), template: { name: this.getPartTemplateName('wrapper') }, options: { helpers: this.getOptions('helpers'), targetEl: this.getOptions('targetEl'), targetQuery: this.getOptions('targetQuery'), id: this.getOptions('id') }, events: [ [ ['afterRender', 'afterUpdate'], this.renderComponents.bind(this) ] ] }; let wrapper = new notComponent(input); this.setWorking('wrapper', wrapper); } } getWrapperData() { let actionData = this.getActionData(); return { title: actionData.title ? actionData.title : OPT_DEFAULT_DETAILS_TITLE }; } renderComponents() { if (this.getWorking('components') && this.getWorking('components').length) { for (let t = 0; t < this.getWorking('components').length; t++) { this.getWorking('components')[t].component.update(); } } else { for (let t = 0; t < this.getFieldsList().length; t++) { let fieldName = this.getFieldsList()[t]; this.addFieldComponent(fieldName); } } } clearFieldsComponents() { let comps = this.getWorking('components'); while (comps.length > 0) { comps[0].component.destroy(); comps.splice(0, 1); } } getFieldsLibs() { let result = { options: {}, manifest: {}, app: {}, }; if (this.getOptions('fields')) { result.options = this.getOptions('fields'); } if (notCommon.getApp() && notCommon.getApp().getOptions('fields')) { result.app = notCommon.getApp().getOptions('fields'); } if (this.getData().isRecord && this.getData().getManifest()) { result.manifest = this.getData().getManifest().fields; } return result; } getFieldsDefinition(fieldName) { let def = OPT_DEFAULT_FIELD_DEFINITION, fieldsLibs = this.getFieldsLibs(); for (let t of OPT_DEFAULT_FIELD_DEFINITION_SOURCES_PRIORITY_LIST) { if (fieldsLibs.hasOwnProperty(t) && fieldsLibs[t].hasOwnProperty(fieldName)) { return fieldsLibs[t][fieldName]; } } return def; } addFieldComponent(fieldName) { let fieldType = this.getFieldsDefinition(fieldName), rec = null; if (fieldType.component) { rec = this.castCustom(fieldName, fieldType); } else { rec = this.castCommon(fieldName, fieldType); } this.getWorking('components').push(rec); } castCustom(fieldName, fieldType) { let CustomComponent = notCommon.get('components')[fieldType.component]; let rec = { field: { name: fieldName, title: fieldType.label || fieldType.placeholder, type: fieldType.type, label: fieldType.label, array: fieldType.array, default: fieldType.default, placeholder: fieldType.placeholder, options: this.getOptions(notPath.join('helpers', 'libs', fieldName)) } }; let helpers = notCommon.extend({ isChecked: (params) => { return params.item.value === this.getData(fieldName); }, field: rec.field, data: this.getData() }, this.getOptions('helpers')); rec.component = new CustomComponent({ data: this.getData(), options: { helpers, targetEl: this.getTargetElement(fieldType.target), renderAnd: 'placeLast' } }); return rec; } castCommon(fieldName, fieldType) { let rec = { field: { name: fieldName, title: fieldType.label || fieldType.placeholder, type: fieldType.type, label: fieldType.label, array: fieldType.array, default: fieldType.default, placeholder: fieldType.placeholder, options: this.getOptions(notPath.join('helpers', 'libs', fieldName)) } }; let helpers = notCommon.extend({ isChecked: (params) => { return params.item.value === this.getData(fieldName); }, field: rec.field, data: this.getData() }, this.getOptions('helpers')); rec.component = new notComponent({ data: this.getData(), template: { name: this.getPartTemplateName(fieldType.type) }, options: { helpers, targetEl: this.getTargetElement(fieldType.target), renderAnd: 'placeLast' } }); return rec; } getTargetElement(target = 'body') { if (!target) { target = 'body'; } let res = this.getOptions('targetEl').querySelector('[role="' + target + '"]'); if (!res && target !== 'body') { target = 'body'; res = this.getOptions('targetEl').querySelector('[role="' + target + '"]'); } if (!res && target == 'body') { return this.getOptions('targetEl'); } else { return res; } } /* Data management */ updateField(fieldName) { for (let t = 0; t < this.getWorking('components').length; t++) { if (this.getWorking('components')[t].field.name === fieldName) { this.getWorking('components')[t].component.update(); } } } update() { for (let t = 0; t < this.getWorking('components').length; t++) { this.getWorking('components')[t].component.update(); } } } export default notDetails;
interrupter/not-framework
src/components/notDetails.js
JavaScript
mit
6,472
/** * Copyright [2012] [free-topo copyright npc] * * 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. */ /** * ViewPort Component * @author zouxuejun, buhe */ FT.ViewPort = function(config){ FT.ViewPort.baseConstructor.call(this,config); if(typeof FT.ViewPort._initialized == "undefined"){ FT.ViewPort.prototype.getViewComponent = function(){ return this.viewComponent; }; FT.ViewPort.prototype.setViewComponent = function(viewComponent){ this.viewComponent = viewComponent; this.children[0] = viewComponent; if(viewComponent!=null){ this.viewComponent.setParent(this); this.viewComponent.moveToViewRect(this.computeViewRect(new GF.Point(0, 0))); } }; FT.ViewPort.prototype.computeViewRect = function(location){ var x = location.x > 0?location.x:0; var y = location.y > 0?location.y:0; var viewArea = this.getGraphic().getViewArea(); return new GF.Rectangle(x, y, viewArea.width, viewArea.height); }; FT.ViewPort.prototype.moveToViewRect = function(viewRect){ this.viewComponent.moveToViewRect(viewRect); this.paint(); }; FT.ViewPort.prototype.canMoveViewRect = function(viewRect){ var realRect = getRealSize(); if(viewRect.getLocation().x < 0 || viewRect.getLocation().y < 0){ return false; } if(viewRect.getLocation().x > realRect.width || viewRect.getLocation().y > realRect.height){ return false; } return true; }; FT.ViewPort.prototype.getRealSize = function(){ return this.viewComponent.getSize(); }; FT.ViewPort.prototype.paint = function(){ this.viewportUI.draw(); }; FT.ViewPort._initialized = true; } this.scale = 1.0; this.parent = null; this.parentEmId = config.parentEmId; this.viewportUI = new FT.ViewportUI(this); }; FT.extend(FT.ViewPort,FT.Component); FT.ViewportUI = function(viewport){ this.viewport = viewport; var self = this; // this.viewport.getGraphic().on('onmousedown' ,function(e){ // // var point = new GF.Point(event.offsetX, event.offsetY); // if(!self.isPointAtController(point)){ // return; // } // var component = self.viewport.getViewComponent(); // var rect = component.getViewRect(); // var newRect = new GF.Rectangle(rect.x,rect.y + 100,rect.width,rect.height); // component.moveToViewRect(newRect); // self.draw(); // }); this.viewport.on("mouseup", function(e){ var point = new GF.Point(event.offsetX, event.offsetY); if(!self.isPointAtController(point)){ return; } //TODO - not yet implemented,for test,move 100 when click. var component = self.viewport.getViewComponent(); var rect = component.getViewRect(); var newRect = new GF.Rectangle(rect.x,rect.y + 100,rect.width,rect.height); component.moveToViewRect(newRect); self.draw(); }); this.controllerPosition = new GF.Point(40, 40); this.controllerRadius = 30; this.controllerRect = new GF.Rectangle(this.controllerPosition.x - this.controllerRadius, this.controllerPosition.y - this.controllerRadius, this.controllerRadius * 2, this.controllerRadius * 2); if(typeof FT.ViewportUI._initialized == "undefined"){ FT.ViewportUI.prototype.draw = function(){ this.viewport.getViewComponent().paint(); this.drawController(); }; FT.ViewportUI.prototype.drawController = function(){ var style = "#00FFFF"; //TODO draw view controller here var x = this.controllerPosition.x;// point.x of cycle center var y = this.controllerPosition.y;// point.y of cycle center this.viewport.getGraphic().drawArc(x, y, this.controllerRadius, style, 'event'); this.viewport.getGraphic().drawRect(this.controllerRect, style, 'event'); }; FT.ViewportUI.prototype.isPointAtController = function(point){ if( (point.x > this.controllerRect.x && point.x < this.controllerRect.width) && (point.y > this.controllerRect.y && point.y < this.controllerRect.height)){ return true; } return false; }; FT.ViewportUI._initialized = true; } };
buhe/free-topo
src/topo-viewport.js
JavaScript
mit
4,565
(function() { "use strict"; /*\ |*| |*| :: cookies.js :: |*| |*| A complete cookies reader/writer framework with full unicode support. |*| |*| Revision #1 - September 4, 2014 |*| |*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie |*| https://developer.mozilla.org/User:fusionchess |*| |*| This framework is released under the GNU Public License, version 3 or later. |*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| |*| Syntaxes: |*| |*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]]) |*| * docCookies.getItem(name) |*| * docCookies.removeItem(name[, path[, domain]]) |*| * docCookies.hasItem(name) |*| * docCookies.keys() |*| \*/ var docCookies = { getItem: function (sKey) { if (!sKey) { return null; } return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null; }, setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) { if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; } var sExpires = ""; if (vEnd) { switch (vEnd.constructor) { case Number: sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd; break; case String: sExpires = "; expires=" + vEnd; break; case Date: sExpires = "; expires=" + vEnd.toUTCString(); break; } } document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : ""); return true; }, removeItem: function (sKey, sPath, sDomain) { if (!this.hasItem(sKey)) { return false; } document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : ""); return true; }, hasItem: function (sKey) { if (!sKey) { return false; } return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }, keys: function () { var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/); for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); } return aKeys; } }; /*-------------------------------------------------------------------------------------------------- File Extensions to ACE Editor Languages --------------------------------------------------------------------------------------------------*/ var langs = { as: "actionscript", txt: "asciidoc", s: "assembly_x86", S: "assembly_x86", asm: "assembly_x86", cpp: "c_cpp", hpp: "c_cpp", cx: "c_cpp", hx: "c_cpp", c: "c_cpp", h: "c_cpp", clj: "clojure", cljs: "clojure", edn: "clojure", coffee: "coffee", cs: "csharp", css: "css", dart: "dart", d: "d", erl: "erlang", hrl: "erlang", go: "golang", hs: "haskell", lhs: "haskell", html: "html", htm: "html", java: "java", js: "javascript", json: "json", jsp: "jsp", jl: "julia", tex: "latex", less: "less", lisp: "lisp", lsp: "lisp", l: "lisp", cl: "lisp", fasl: "lisp", lua: "lua", mk: "makefile", md: "markdown", m: "matlab", ml: "ocaml", pl: "perl", pm: "perl", t: "perl", pod: "perl", php: "php", ps: "powershell", py: "python", rb: "ruby", rs: "rust", rlib: "rust", sass: "sass", scss: "sass", scala: "scala", scm: "scheme", ss: "scheme", sh: "sh", bash: "sh", sql: "sql", vb: "vbscript", xml: "xml", yaml: "yaml", yml: "yaml", }; /*-------------------------------------------------------------------------------------------------- List of ACE Editor Themes --------------------------------------------------------------------------------------------------*/ var themes = { ambiance : "Ambiance", chaos : "Chaos", chrome : "Chrome", clouds : "Clouds", clouds_midnight : "Clouds/Midnight", cobalt : "Cobalt", crimson_editor : "Crimson", dawn : "Dawn", dreamweaver : "Dreamweaver", eclipse : "Eclipse", github : "Github", idle_fingers : "Idle Fingers", katzenmilch : "Katzenmilch", kuroir : "Kurior", merbivore : "Merbivore", merbivore_soft : "Merbivore Soft", mono_industrial : "Mono Industrial", monokai : "Monokai", pastel_on_dark : "Pastel on Dark", solarized_dark : "Solarized Dark", solarized_light : "Solarized Light", terminal : "Terminal", textmate : "Textmate", tomorrow : "Tomorrow", tomorrow_night_blue : "Tomorrow Night Blue", tomorrow_night_bright : "Tomorrow Night Bright", tomorrow_night_eighties : "Tomorrow Night Eighties", tomorrow_night : "Tomorrow Night", twilight : "Twilight", vibrant_ink : "Vibrant Ink", xcode : "XCode" }; /*-------------------------------------------------------------------------------------------------- List of ACE Editor Key Mappings --------------------------------------------------------------------------------------------------*/ var keymaps = { none : "Standard", vim : "Vim", emacs : "Emacs" }; /*-------------------------------------------------------------------------------------------------- Global Variables --------------------------------------------------------------------------------------------------*/ var ace_editor = null; var leaps_client = null; var username = "anon"; var users = {}; var theme = "dawn"; var binding = "none"; var useTabs = true; var wrapLines = true; /*-------------------------------------------------------------------------------------------------- ACE Editor Configuration --------------------------------------------------------------------------------------------------*/ var configure_ace_editor = function() { if ( ace_editor === null ) { return; } ace_editor.setTheme("ace/theme/" + theme); var map = ""; if ( binding !== "none" ) { map = "ace/keyboard/" + binding; } ace_editor.setKeyboardHandler(map); ace_editor.getSession().setUseSoftTabs(!useTabs); ace_editor.getSession().setUseWrapMode(wrapLines); }; /*-------------------------------------------------------------------------------------------------- Leaps Editor User Cursor Helpers --------------------------------------------------------------------------------------------------*/ var HSVtoRGB = function(h, s, v) { var r, g, b, i, f, p, q, t; if (h && s === undefined && v === undefined) { s = h.s, v = h.v, h = h.h; } i = Math.floor(h * 6); f = h * 6 - i; p = v * (1 - s); q = v * (1 - f * s); t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } return { r: Math.floor(r * 255), g: Math.floor(g * 255), b: Math.floor(b * 255) }; }; var hash = function(str) { var hash = 0, i, chr, len; if ('string' !== typeof str || str.length === 0) { return hash; } for (i = 0, len = str.length; i < len; i++) { chr = str.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var user_id_to_color = function(user_id) { var id_hash = hash(user_id); if ( id_hash < 0 ) { id_hash = id_hash * -1; } var hue = ( id_hash % 10000 ) / 10000; var rgb = HSVtoRGB(hue, 1, 0.8); return "rgba(" + rgb.r + ", " + rgb.g + ", " + rgb.b + ", 1)"; }; var oob_elements = []; var ACE_cursor_clear_handler = function() { for ( var i = 0, l = oob_elements.length; i < l; i++ ) { document.body.removeChild(oob_elements[i]); } oob_elements = []; }; var ACE_cursor_handler = function(user_id, lineHeight, top, left, row, column) { var colorStyle = user_id_to_color(user_id); // Needs IE9 var editor_bounds = ace_editor.container.getBoundingClientRect(); var editor_width = ace_editor.getSession().getScreenWidth(); var editor_height = ace_editor.getSession().getScreenLength(); var user_tag = user_id; if ( 'string' === typeof users[user_id] ) { user_tag = users[user_id]; } var triangle_height = 20; var triangle_opacity = 0.5; var ball_width = 8; var height = lineHeight; var extra_height = 6; var width = 2; var tag_height = 30; var create_ptr_ele = function() { var top_ptr_ele = document.createElement('div'); top_ptr_ele.style.opacity = 0.7 + ''; top_ptr_ele.style.position = 'absolute'; top_ptr_ele.style.width = '0'; top_ptr_ele.style.height = '0'; top_ptr_ele.style.zIndex = '99'; return top_ptr_ele; }; if ( top < 0 ) { var top_ptr_ele = create_ptr_ele(); top_ptr_ele.style.top = editor_bounds.top + 'px'; top_ptr_ele.style.left = (editor_bounds.left + triangle_height) + 'px'; top_ptr_ele.style.borderBottom = triangle_height + 'px solid ' + colorStyle; top_ptr_ele.style.borderLeft = (triangle_height/2) + 'px solid transparent'; top_ptr_ele.style.borderRight = (triangle_height/2) + 'px solid transparent'; document.body.appendChild(top_ptr_ele); oob_elements.push(top_ptr_ele); } else if ( top > editor_bounds.height ) { var bottom_ptr_ele = create_ptr_ele(); bottom_ptr_ele.style.top = (editor_bounds.top + editor_bounds.height - triangle_height) + 'px'; bottom_ptr_ele.style.left = (editor_bounds.left + triangle_height) + 'px'; bottom_ptr_ele.style.borderTop = triangle_height + 'px solid ' + colorStyle; bottom_ptr_ele.style.borderLeft = (triangle_height/2) + 'px solid transparent'; bottom_ptr_ele.style.borderRight = (triangle_height/2) + 'px solid transparent'; document.body.appendChild(bottom_ptr_ele); oob_elements.push(bottom_ptr_ele); } var left_ptr_obj = ''; if ( left > editor_bounds.width ) { left_ptr_obj = '<div style="' + 'position: absolute; ' + 'width: 0; height: 0; z-index: 99; ' + 'top: ' + top + 'px; ' + 'left: 0; border-top: ' + (triangle_height/2) + 'px solid transparent; ' + 'border-left: ' + (triangle_height/3) + 'px solid ' + colorStyle + '; ' + 'border-bottom: ' + (triangle_height/2) + 'px solid transparent; ' + 'opacity: 0.7; ' + '"></div>'; } var tag_obj = '<div style="background-color: ' + colorStyle + '; opacity: 0.5; z-index: 99; position: absolute; top: ' + (top - tag_height) + 'px; padding: 2px; left: ' + (left + ball_width) + 'px; color: #f0f0f0;">' + user_tag + '</div>'; return left_ptr_obj + tag_obj + '<div style="position: absolute; top: ' + (top - extra_height) + 'px; left: ' + left + 'px; color: ' + colorStyle + '; height: ' + (height + extra_height) + 'px; border-left: ' + width + 'px solid ' + colorStyle + '; ">' + '<div style="position: relative; height: ' + ball_width + 'px; width: ' + ball_width + 'px; border-radius: ' + (ball_width/2) + 'px; top: -' + (ball_width) + 'px; left: -' + (ball_width/2 + width/2) + 'px; background-color: ' + colorStyle + '"></div>' + '</div>'; }; /*-------------------------------------------------------------------------------------------------- Leaps Editor Bootstrapping --------------------------------------------------------------------------------------------------*/ var join_new_document = function(document_id) { if ( leaps_client !== null ) { leaps_client.close(); leaps_client = null; } if ( ace_editor !== null ) { var oldDiv = ace_editor.container; var newDiv = oldDiv.cloneNode(false); ace_editor.destroy(); ace_editor = null; oldDiv.parentNode.replaceChild(newDiv, oldDiv); } users = {}; refresh_users_list(); ace_editor = ace.edit("editor"); configure_ace_editor(); var filetype = "asciidoc"; try { var ext = document_id.substr(document_id.lastIndexOf(".") + 1); if ( typeof langs[ext] === 'string' ) { filetype = langs[ext]; } } catch (e) {} ace_editor.getSession().setMode("ace/mode/" + filetype); leaps_client = new leap_client(); leaps_client.bind_ace_editor(ace_editor); leaps_client.on("error", function(err) { if ( leaps_client !== null ) { console.error(err); system_message("Connection to document closed, document is now READ ONLY", "red"); leaps_client.close(); leaps_client = null; } }); leaps_client.on("disconnect", function(err) { if ( leaps_client !== null ) { system_message(document_id + " closed", "red"); } }); leaps_client.on("connect", function() { leaps_client.join_document(document_id); }); leaps_client.on("document", function() { system_message("Opened document " + document_id, "blue"); }); leaps_client.on("user", function(user_update) { var refresh_user_list = false; var metadata = user_update.message; if ( 'string' === typeof metadata ) { var data = JSON.parse(metadata); if ( 'string' === typeof data.text ) { chat_message(user_update.user_id, data.username, data.text); } if ( 'string' === typeof data.username ) { refresh_user_list = refresh_user_list || !users.hasOwnProperty(user_update.user_id) || users[user_update.user_id] !== data.username; users[user_update.user_id] = data.username; } } if ( typeof user_update.active === 'boolean' && !user_update.active ) { refresh_user_list = true; delete users[user_update.user_id] } if ( refresh_user_list ) { refresh_users_list(); } }); leaps_client.ACE_set_cursor_handler(ACE_cursor_handler, ACE_cursor_clear_handler); var protocol = window.location.protocol === "http:" ? "ws:" : "wss:"; leaps_client.connect(protocol + "//" + window.location.host + "/socket"); }; /*-------------------------------------------------------------------------------------------------- File Path Acquire and Listing --------------------------------------------------------------------------------------------------*/ var fileItemClass = "file-path"; var get_selected_li = function() { var li_eles = document.getElementsByTagName('li'); for ( var i = 0, l = li_eles.length; i < l; i++ ) { if ( li_eles[i].className === fileItemClass + ' selected' ) { return li_eles[i]; } } return null; }; var create_path_click = function(ele, id) { return function() { if ( ele.className === fileItemClass + ' selected' ) { // Nothing } else { var current_ele = get_selected_li(); if ( current_ele !== null ) { current_ele.className = fileItemClass; } ele.className = fileItemClass + ' selected'; window.location.hash = "path:" + id; join_new_document(id); } }; }; var draw_path_object = function(path_object, parent, selected_id) { if ( "object" === typeof path_object ) { for ( var prop in path_object ) { if ( path_object.hasOwnProperty(prop) ) { var li = document.createElement("li"); var text = document.createTextNode(prop); if ( "object" === typeof path_object[prop] ) { var span = document.createElement("span"); var list = document.createElement("ul"); list.className = "narrow-list"; span.className = "directory-name"; span.appendChild(text); li.appendChild(span); li.appendChild(list); draw_path_object(path_object[prop], list, selected_id); parent.appendChild(li); } else if ( "string" === typeof path_object[prop] ) { li.id = path_object[prop]; li.onclick = create_path_click(li, li.id); if ( selected_id === li.id ) { li.className = fileItemClass + ' selected'; } else { li.className = fileItemClass; } li.appendChild(text); parent.appendChild(li); } else { console.error("path object wrong type", typeof path_object[prop]); } } } } }; var show_paths = function(paths_list) { var i = 0, l = 0, j = 0, k = 0; if ( typeof paths_list !== 'object' ) { console.error("paths list wrong type", typeof paths_list); return; } var paths_hierarchy = {}; for ( i = 0, l = paths_list.length; i < l; i++ ) { var split_path = paths_list[i].split('/'); var ptr = paths_hierarchy; for ( j = 0, k = split_path.length - 1; j < k; j++ ) { if ( 'object' !== typeof ptr[split_path[j]] ) { ptr[split_path[j]] = {}; } ptr = ptr[split_path[j]]; } ptr[split_path[split_path.length - 1]] = paths_list[i]; } var selected_path = ""; var selected_ele = get_selected_li(); if ( selected_ele !== null ) { selected_path = selected_ele.id; } var paths_ele = document.getElementById("file-list"); paths_ele.innerHTML = ""; draw_path_object(paths_hierarchy, paths_ele, selected_path); }; var AJAX_REQUEST = function(path, onsuccess, onerror, data) { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if ( xmlhttp.readyState == 4 ) { // DONE if ( xmlhttp.status == 200 ) { onsuccess(xmlhttp.responseText); } else { onerror(xmlhttp.status, xmlhttp.responseText); } } }; if ( 'undefined' !== typeof data ) { xmlhttp.open("POST", path, true); xmlhttp.setRequestHeader("Content-Type","text/plain"); xmlhttp.send(data); } else { xmlhttp.open("GET", path, true); xmlhttp.send(); } }; var get_paths = function() { AJAX_REQUEST("/files", function(data) { try { var paths_list = JSON.parse(data); show_paths(paths_list.paths); } catch (e) { console.error("paths parse error", e); } }, function(code, message) { console.error("get_paths error", code, message); }); }; /*-------------------------------------------------------------------------------------------------- Kick Button Helpers --------------------------------------------------------------------------------------------------*/ var create_kick_btn = function(user_id) { if ( window.location.hostname !== "localhost" && window.location.hostname !== "127.0.0.1" ) { return null; } var kick_btn = document.createElement("button"); kick_btn.onclick = function() { if ( null === leaps_client ) { return; } AJAX_REQUEST( "http://localhost:8002/admin/kick_user", function(data) {}, function(code, message) { console.error("kick error", code, message); }, JSON.stringify({ doc_id: leaps_client._document_id, user_id: user_id })); }; kick_btn.className = "small-kick-button red"; kick_btn.innerHTML = "x"; kick_btn.title = "Kick user"; return kick_btn; }; /*-------------------------------------------------------------------------------------------------- Chat UI Helpers --------------------------------------------------------------------------------------------------*/ // Use to alert users when new messages appear var flash_chat_window = function() { var info_window = document.getElementById("info-window"); info_window.style.boxShadow = "0px 0px 0px 5px #4E81B4"; setTimeout(function() { info_window.style.boxShadow = "0px 0px 0px 0px #4E81B4"; }, 300); }; var chat_message = function(user_id, username, message) { var container = document.getElementById("info-window"); var messages = document.getElementById("info-messages"); var div = document.createElement("div"); var ts_span = document.createElement('span'); var name_span = document.createElement('span'); var text_span = document.createElement('span'); if ( 'string' === typeof user_id ) { name_span.style.backgroundColor = user_id_to_color(user_id); name_span.style.color = "#f0f0f0"; } div.className = "white"; name_span.style.fontWeight = "700"; name_span.style.paddingLeft = "4px"; name_span.style.paddingRight = "4px"; var date_txt = document.createTextNode((new Date()).toTimeString().substr(0, 8) + " "); var user_txt = document.createTextNode(username); var msg_txt = document.createTextNode(" " + message); ts_span.appendChild(date_txt); div.appendChild(ts_span); name_span.appendChild(user_txt); div.appendChild(name_span); text_span.appendChild(msg_txt); div.appendChild(text_span); messages.appendChild(div); container.scrollTop = container.scrollHeight; flash_chat_window(); }; var system_message = function(text, style) { var container = document.getElementById("info-window"); var messages = document.getElementById("info-messages"); var div = document.createElement("div"); if ( typeof style === 'string' ) { div.className = style; } var textNode = document.createTextNode((new Date()).toTimeString().substr(0, 8) + " " + text); div.appendChild(textNode); messages.appendChild(div); container.scrollTop = container.scrollHeight; flash_chat_window(); }; /*-------------------------------------------------------------------------------------------------- Users List UI Helpers --------------------------------------------------------------------------------------------------*/ var refresh_users_list = function() { var styles = ["ash","light-grey"]; var style_index = 0; var users_element = document.getElementById("users-list"); users_element.innerHTML = ""; var self_element = document.createElement("div"); // var self_text_ele = document.createTextNode(username); var self_text_ele = document.createTextNode("Users"); self_element.className = styles[((style_index++)%styles.length)]; self_element.appendChild(self_text_ele); users_element.appendChild(self_element); for (var user in users) { if (users.hasOwnProperty(user)) { var user_element = document.createElement("div"); var user_text_ele = document.createTextNode(users[user]); var kick_btn = create_kick_btn(user); user_element.className = styles[((style_index++)%styles.length)]; user_element.style.color = user_id_to_color(user); /* user_element.style.backgroundColor = user_id_to_color(user); user_element.style.color = "#f0f0f0"; */ if ( null !== kick_btn ) { user_element.appendChild(kick_btn); } user_element.appendChild(user_text_ele); users_element.appendChild(user_element); } } }; /*-------------------------------------------------------------------------------------------------- Set Cookies Helper --------------------------------------------------------------------------------------------------*/ var set_cookie_option = function(key, value) { var expiresDate = new Date(); expiresDate.setDate(expiresDate.getDate() + 30); docCookies.setItem(key, value, expiresDate); }; window.onload = function() { get_paths(); /*-------------------------------------------------------------------------------------------------- File Paths Refresh Button --------------------------------------------------------------------------------------------------*/ var refresh_button = document.getElementById("refresh-button"); refresh_button.onclick = function() { get_paths(); }; /*-------------------------------------------------------------------------------------------------- Messages Clear Button --------------------------------------------------------------------------------------------------*/ var clear_button = document.getElementById("clear-button"); clear_button.onclick = function() { var messages = document.getElementById("info-messages"); messages.innerHTML = ""; }; /*-------------------------------------------------------------------------------------------------- Username Input --------------------------------------------------------------------------------------------------*/ var username_bar = document.getElementById("username-bar"); if ( docCookies.hasItem("username") ) { username_bar.value = docCookies.getItem("username"); } username = username_bar.value || "anon"; username_bar.onkeyup = function() { username = username_bar.value || "anon"; set_cookie_option("username", username_bar.value); refresh_users_list(); }; refresh_users_list(); /*-------------------------------------------------------------------------------------------------- Use Tabs Checkbox --------------------------------------------------------------------------------------------------*/ var input_use_tabs = document.getElementById("input-use-tabs"); if ( docCookies.hasItem("useTabs") ) { useTabs = docCookies.getItem("useTabs") === "true"; } input_use_tabs.checked = useTabs; input_use_tabs.onchange = function() { useTabs = input_use_tabs.checked; set_cookie_option("useTabs", useTabs ? "true" : "false"); if ( ace_editor !== null ) { ace_editor.getSession().setUseSoftTabs(!useTabs); } }; /*-------------------------------------------------------------------------------------------------- Wrap Lines Checkbox --------------------------------------------------------------------------------------------------*/ var input_wrap_lines = document.getElementById("input-wrap-lines"); if ( docCookies.hasItem("wrapLines") ) { wrapLines = docCookies.getItem("wrapLines") === "true"; } input_wrap_lines.checked = wrapLines; input_wrap_lines.onchange = function() { wrapLines = input_wrap_lines.checked; set_cookie_option("wrapLines", wrapLines ? "true" : "false"); if ( ace_editor !== null ) { ace_editor.getSession().setUseWrapMode(wrapLines); } }; /*-------------------------------------------------------------------------------------------------- Key Mapping Drop Down Menu --------------------------------------------------------------------------------------------------*/ var input_select = document.getElementById("input-select"); for ( var keymap in keymaps ) { if ( keymaps.hasOwnProperty(keymap) ) { input_select.innerHTML += '<option value="' + keymap + '">' + keymaps[keymap] + "</option>"; } } if ( docCookies.hasItem("input") ) { binding = docCookies.getItem("input"); } input_select.value = binding; input_select.onchange = function() { binding = input_select.value; set_cookie_option("input", binding); if ( ace_editor !== null ) { var map = ""; if ( binding !== "none" ) { map = "ace/keyboard/" + binding; } ace_editor.setKeyboardHandler(map); } }; /*-------------------------------------------------------------------------------------------------- Theme Drop Down Menu --------------------------------------------------------------------------------------------------*/ var theme_select = document.getElementById("theme-select"); for ( var prop in themes ) { if ( themes.hasOwnProperty(prop) ) { theme_select.innerHTML += '<option value="' + prop + '">' + themes[prop] + "</option>"; } } if ( docCookies.hasItem("theme") ) { theme = docCookies.getItem("theme"); } theme_select.value = theme; theme_select.onchange = function() { theme = theme_select.value; set_cookie_option("theme", theme); if ( ace_editor !== null ) { ace_editor.setTheme("ace/theme/" + theme); } }; /*-------------------------------------------------------------------------------------------------- Chat Bar --------------------------------------------------------------------------------------------------*/ var chat_bar = document.getElementById("chat-bar"); chat_bar.onkeypress = function(e) { if ( typeof e !== 'object' ) { e = window.event; } var keyCode = e.keyCode || e.which; if ( keyCode == '13' && chat_bar.value.length > 0 ) { if ( leaps_client !== null ) { leaps_client.send_message(JSON.stringify({ username: username, text: chat_bar.value })); chat_message(null, username, chat_bar.value); chat_bar.value = ""; return false; } else { system_message( "You must open a document in order to send messages, " + "they will be readable by other users editing that document", "red" ); return true; } } }; var info_window = document.getElementById("info-window"); info_window.onclick = function() { chat_bar.focus(); }; /* We're using our own implementation of usernames by sending JSON objects in leaps messages, * so to keep all clients up to date across name changes lets just send it every second. It's a * painless job so why not? */ setInterval(function() { if ( leaps_client !== null ) { leaps_client.send_message(JSON.stringify({ username: username })); } }, 1000); // You can link directly to a filepath with <URL>#path:/this/is/the/path.go if ( window.location.hash.length > 0 && window.location.hash.substr(1, 5) === "path:" ) { var path = window.location.hash.substr(6); join_new_document(path); } }; })();
postfix/leaps
static/share_dir/leapshare.js
JavaScript
mit
28,988
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"./lang/ja":[function(require,module,exports){ module.exports = { accepted: ':attributeを確認してください。', alpha: ':attributeは英字のみで入力してください。', alpha_dash: ':attributeは英字とダッシュと下線のみで入力してください。', alpha_num: ':attributeは英数字のみで入力してください。', between: ':attributeは:min〜:max文字で入力してください。', confirmed: ':attributeは確認が一致しません。', email: ':attributeは正しいメールアドレスを入力してください。', date: ':attributeは正しい日付形式を入力してください', def: ':attributeは検証エラーが含まれています。', digits: ':attributeは:digitsの数字のみで入力してください。', different: ':attributeと:differentは同じであってはなりません。', 'in': '選択された:attributeは無効です。', integer: ':attributeは整数で入力してください。', min : { numeric : ":attributeは:min以上で入力してください。", string : ":attributeは:min文字以上で入力してください。" }, max : { numeric : ":attributeは:max以下で入力してください。", string : ":attributeは:max文字以下で入力してください。" }, not_in : "選択された:attributeは無効です。", numeric : ":attributeは数値で入力してください。", required : ":attributeは必須です。", required_if : ":otherは:valueになったら:attributeは必須です。", same : ":attributeと:sameは同じでなければなりません。", size : { numeric : ":attributeは:sizeを入力してください。", string : ":attributeは:size文字で入力してください。" }, url : ":attributeは正しいURIを入力してください。", regex : ":attributeの値 \":value\" はパターンにマッチする必要があります。", attributes : {} }; },{}]},{},[]);
smaccoun/wrapid-react-ts
node_modules/validatorjs/dist/lang/ja.js
JavaScript
mit
2,576
describe("AnchorJS", function() { var h, t; beforeEach(function() { h = document.createElement("h1"); t = document.createTextNode("⚡⚡⚡ Unicode icons are cool--but they definitely don't belong in a URL fragment."); h.appendChild(t); document.body.appendChild(h); }); afterEach(function() { document.body.removeChild(h); }); it("should add an anchor link to an h1 by default", function() { var anchorLink; anchors.add(); anchorLink = document.querySelector('h1 > .anchorjs-link'); expect(anchorLink).not.toBe(null); }); it("should have default options (right placement, hover visiblity, & link icon)", function() { var anchorLink, hasClass, opacity, icon; anchors.add(); anchorLink = document.getElementsByTagName('h1')[0].lastChild; hasClass = anchorLink.classList.contains('anchorjs-link'); opacity = anchorLink.style.opacity; icon = document.querySelector('.anchorjs-link').getAttribute('data-anchorjs-icon'); expect(hasClass).toBe(true); expect(opacity).not.toEqual('1'); expect(icon).toEqual('\ue9cb'); }); it("should set baseline styles in the document head", function() { var hasClass; anchors.add(); // We query for the first style tag because we are testing both that it's // there and that it's overridable by other styles later in the cascade. hasClass = document.head.querySelector('[rel="stylesheet"], style').classList.contains('anchorjs'); expect(hasClass).toBe(true); }); it("allows you to instantiate a new AnchorJS object that behaves like the default one.", function() { var anchorObj, anchorLink; anchorObj = new AnchorJS(); anchorObj.add(); anchorLink = document.querySelector('h1 > .anchorjs-link'); expect(anchorLink).not.toBe(null); }); it("ensures new AnchorJS instances don't add multiple baseline style tags.", function() { var anchorObj, anchorLink; anchors.add(); anchorObj = new AnchorJS(); anchorObj.add(); styleNodes = document.head.querySelectorAll('.anchorjs'); expect(styleNodes.length).toEqual(1); }); it("doesn't destroy default options when setting an incomplete options object.", function() { var anchorObj, anchorLink, hasClass, opacity, icon; anchors.options = { class: 'test-class' }; anchors.add(); anchorObj = new AnchorJS({ class: 'test-class' }); expect(anchors.options.icon).toEqual('\ue9cb'); expect(anchorObj.options.icon).toEqual('\ue9cb'); expect(anchors.options.visible).toEqual('hover'); expect(anchorObj.options.visible).toEqual('hover'); expect(anchors.options.placement).toEqual('right'); expect(anchorObj.options.placement).toEqual('right'); }); it("can remove anchors, using the .remove() method.", function() { var anchorLinkBefore, anchorLinkAfter; anchors.add(); anchorLinkBefore = document.querySelector('h1 > .anchorjs-link'); expect(anchorLinkBefore).not.toBe(null); anchors.remove('h1'); anchorLinkAfter = document.querySelector('h1 > .anchorjs-link'); expect(anchorLinkAfter).toBe(null); }); it("can chain methods.", function() { var anchorLinkBefore, anchorLinkAfter; anchors.add('h1').remove('h1'); anchorLinkBefore = document.querySelector('h1 > .anchorjs-link'); expect(anchorLinkBefore).toBe(null); anchors.remove('h1').add('h1'); anchorLinkAfter = document.querySelector('h1 > .anchorjs-link'); expect(anchorLinkAfter).not.toBe(null); }); it("should create a URL-appropriate ID (and href) for targeted elements without IDs.", function() { var href, id; anchors.add('h1'); href = document.querySelector('.anchorjs-link').getAttribute('href'); id = document.getElementsByTagName('h1')[0].getAttribute('id'); expect(href).toEqual('#unicode-icons-are-cool-but-they-definitely-dont-belong-in-a-url'); expect(id).toEqual('unicode-icons-are-cool-but-they-definitely-dont-belong-in-a-url'); }); it("should leave existing IDs in place, and use them as the href for anchors.", function() { var href, id; document.getElementsByTagName('h1')[0].setAttribute('id', 'test-id') anchors.add('h1'); href = document.querySelector('.anchorjs-link').getAttribute('href'); id = document.getElementsByTagName('h1')[0].getAttribute('id'); expect(href).toEqual('#test-id'); expect(id).toEqual('test-id'); }); it("should increment new IDs if multiple IDs are found on a page.", function() { var h1, t1, id1, href1, h2, t2, id2, href2, h3, t3, id3, href3, tags, links, i; h1 = document.createElement("h2"); t1 = document.createTextNode("Example Title"); h1.appendChild(t1); h2 = document.createElement("h2"); t2 = document.createTextNode("Example Title"); h2.appendChild(t2); h3 = document.createElement("h2"); t3 = document.createTextNode("Example Title"); h3.appendChild(t3); document.body.appendChild(h1); document.body.appendChild(h2); document.body.appendChild(h3); anchors.add('h2'); tags = document.getElementsByTagName('h2'); links = document.querySelectorAll('.anchorjs-link'); id1 = tags[0].getAttribute('id'); href1 = links[0].getAttribute('href'); id2 = tags[1].getAttribute('id'); href2 = links[1].getAttribute('href'); id3 = tags[2].getAttribute('id'); href3 = links[2].getAttribute('href'); expect(id1).toEqual('example-title'); expect(href1).toEqual('#example-title'); expect(id2).toEqual('example-title-1'); expect(href2).toEqual('#example-title-1'); expect(id3).toEqual('example-title-2'); expect(href3).toEqual('#example-title-2'); document.body.removeChild(h1); document.body.removeChild(h2); document.body.removeChild(h3); }); it("should throw an error if an inappropriate selector is provided.", function() { expect(function() { anchors.add(25); }).toThrowError("The selector provided to AnchorJS was invalid."); }); it("should place the ¶ icon, when that option is set.", function() { var icon; anchors.options.icon = '¶'; anchors.add('h1'); icon = document.querySelector('.anchorjs-link').getAttribute('data-anchorjs-icon'); expect(icon).toEqual('¶'); }); it("should place anchors to the left, when that option is set.", function() { var anchorNode; anchors.options.placement = 'left'; anchors.add('h1'); anchorNode = document.getElementsByTagName('h1')[0].firstChild; expect(anchorNode.style.position).toEqual('absolute'); expect(anchorNode.style.marginLeft).toEqual('-1em'); }); it("should make anchors always visible, when that option is set.", function() { var opacity; anchors.options.visible = 'always'; anchors.add('h1'); opacity = document.querySelector('.anchorjs-link').style.opacity; expect(opacity).toEqual('1'); }); it("should apply a provided class, when that option is set.", function() { var anchorLink; anchors.options.class = 'test-class'; anchors.add('h1'); anchorLink = document.querySelector('h1 > .test-class'); expect(anchorLink).not.toBe(null); }); });
staticmatrix/Triangle
_baseline/refer/modules/anchorjs/1.3.0/test/spec/AnchorSpec.js
JavaScript
mit
7,385
"use strict"; var each = require('lodash/each'); var uniq = require('lodash/uniq'); var uuid = require('../util/uuid'); // TODO: this should be implemented as transformations // A collection of methods to update annotations // -------- // // As we treat annotations as overlay of plain text we need to keep them up-to-date during editing. var insertedText = function(doc, coordinate, length) { if (!length) return; var index = doc.getIndex('annotations'); var annotations = index.get(coordinate.path); each(annotations, function(anno) { var pos = coordinate.offset; var start = anno.startOffset; var end = anno.endOffset; var newStart = start; var newEnd = end; if ( (pos < start) || (pos === start) ) { newStart += length; } // inline nodes do not expand automatically if ( (pos < end) || (pos === end && !anno.isInline()) ) { newEnd += length; } if (newStart !== start) { doc.set([anno.id, 'startOffset'], newStart); } if (newEnd !== end) { doc.set([anno.id, 'endOffset'], newEnd); } }); // same for container annotation anchors index = doc.getIndex('container-annotation-anchors'); var anchors = index.get(coordinate.path); each(anchors, function(anchor) { var pos = coordinate.offset; var start = anchor.offset; var changed = false; if ( (pos < start) || (pos === start && !coordinate.after) ) { start += length; changed = true; } if (changed) { var property = (anchor.isStart?'startOffset':'endOffset'); doc.set([anchor.id, property], start); } }); }; // TODO: clean up replaceText support hackz var deletedText = function(doc, path, startOffset, endOffset) { if (startOffset === endOffset) return; var index = doc.getIndex('annotations'); var annotations = index.get(path); var length = endOffset - startOffset; each(annotations, function(anno) { var pos1 = startOffset; var pos2 = endOffset; var start = anno.startOffset; var end = anno.endOffset; var newStart = start; var newEnd = end; if (pos2 <= start) { newStart -= length; newEnd -= length; doc.set([anno.id, 'startOffset'], newStart); doc.set([anno.id, 'endOffset'], newEnd); } else { if (pos1 <= start) { newStart = start - Math.min(pos2-pos1, start-pos1); } if (pos1 <= end) { newEnd = end - Math.min(pos2-pos1, end-pos1); } // delete the annotation if it has collapsed by this delete if (start !== end && newStart === newEnd) { doc.delete(anno.id); } else { if (start !== newStart) { doc.set([anno.id, 'startOffset'], newStart); } if (end !== newEnd) { doc.set([anno.id, 'endOffset'], newEnd); } } } }); // same for container annotation anchors index = doc.getIndex('container-annotation-anchors'); var anchors = index.get(path); var containerAnnoIds = []; each(anchors, function(anchor) { containerAnnoIds.push(anchor.id); var pos1 = startOffset; var pos2 = endOffset; var start = anchor.offset; var changed = false; if (pos2 <= start) { start -= length; changed = true; } else { if (pos1 <= start) { var newStart = start - Math.min(pos2-pos1, start-pos1); if (start !== newStart) { start = newStart; changed = true; } } } if (changed) { var property = (anchor.isStart?'startOffset':'endOffset'); doc.set([anchor.id, property], start); } }); // check all anchors after that if they have collapsed and remove the annotation in that case each(uniq(containerAnnoIds), function(id) { var anno = doc.get(id); var annoSel = anno.getSelection(); if(annoSel.isCollapsed()) { console.log("...deleting container annotation because it has collapsed" + id); doc.delete(id); } }); }; // used when breaking a node to transfer annotations to the new property var transferAnnotations = function(doc, path, offset, newPath, newOffset) { var index = doc.getIndex('annotations'); var annotations = index.get(path, offset); each(annotations, function(a) { var isInside = (offset > a.startOffset && offset < a.endOffset); var start = a.startOffset; var end = a.endOffset; var newStart, newEnd; // 1. if the cursor is inside an annotation it gets either split or truncated if (isInside) { // create a new annotation if the annotation is splittable if (a.canSplit()) { var newAnno = a.toJSON(); newAnno.id = uuid(a.type + "_"); newAnno.startOffset = newOffset; newAnno.endOffset = newOffset + a.endOffset - offset; newAnno.path = newPath; doc.create(newAnno); } // in either cases truncate the first part newStart = a.startOffset; newEnd = offset; // if after truncate the anno is empty, delete it if (newEnd === newStart) { doc.delete(a.id); } // ... otherwise update the range else { if (newStart !== start) { doc.set([a.id, "startOffset"], newStart); } if (newEnd !== end) { doc.set([a.id, "endOffset"], newEnd); } } } // 2. if the cursor is before an annotation then simply transfer the annotation to the new node else if (a.startOffset >= offset) { // Note: we are preserving the annotation so that anything which is connected to the annotation // remains valid. newStart = newOffset + a.startOffset - offset; newEnd = newOffset + a.endOffset - offset; doc.set([a.id, "path"], newPath); doc.set([a.id, "startOffset"], newStart); doc.set([a.id, "endOffset"], newEnd); } }); // same for container annotation anchors index = doc.getIndex('container-annotation-anchors'); var anchors = index.get(path); var containerAnnoIds = []; each(anchors, function(anchor) { containerAnnoIds.push(anchor.id); var start = anchor.offset; if (offset <= start) { var pathProperty = (anchor.isStart?'startPath':'endPath'); var offsetProperty = (anchor.isStart?'startOffset':'endOffset'); doc.set([anchor.id, pathProperty], newPath); doc.set([anchor.id, offsetProperty], newOffset + anchor.offset - offset); } }); // check all anchors after that if they have collapsed and remove the annotation in that case each(uniq(containerAnnoIds), function(id) { var anno = doc.get(id); var annoSel = anno.getSelection(); if(annoSel.isCollapsed()) { console.log("...deleting container annotation because it has collapsed" + id); doc.delete(id); } }); }; module.exports = { insertedText: insertedText, deletedText: deletedText, transferAnnotations: transferAnnotations };
abhaga/substance
model/annotationHelpers.js
JavaScript
mit
6,898
var RELANG = {}; RELANG['nl'] = { html: 'HTML', video: 'Video', image: 'Afbeelding', table: 'Tabel', link: 'Link', link_insert: 'Link invoegen...', unlink: 'Link ontkoppelen', formatting: 'Stijlen', paragraph: 'Paragraaf', quote: 'Citaat', code: 'Code', header1: 'Kop 1', header2: 'Kop 2', header3: 'Kop 3', header4: 'Kop 4', bold: 'Vet', italic: 'Cursief', fontcolor: 'Tekstkleur', backcolor: 'Achtergrondkleur', unorderedlist: 'Ongeordende lijst', orderedlist: 'Geordende lijst', outdent: 'Uitspringen', indent: 'Inspringen', redo: 'Opnieuw maken', undo: 'Ongedaan maken', cut: 'Knippen', cancel: 'Annuleren', insert: 'Invoegen', save: 'Opslaan', _delete: 'Verwijderen', insert_table: 'Tabel invoegen', insert_row_above: 'Rij hierboven invoegen', insert_row_below: 'Rij hieronder invoegen', insert_column_left: 'Kolom links toevoegen', insert_column_right: 'Kolom rechts toevoegen', delete_column: 'Verwijder kolom', delete_row: 'Verwijder rij', delete_table: 'Verwijder tabel', rows: 'Rijen', columns: 'Kolommen', add_head: 'Titel toevoegen', delete_head: 'Titel verwijderen', title: 'Titel', image_position: 'Positie', none: 'geen', left: 'links', right: 'rechts', image_web_link: 'Afbeelding link', text: 'Tekst', mailto: 'Email', web: 'URL', video_html_code: 'Video embed code', file: 'Bestand', upload: 'Uploaden', download: 'Downloaden', choose: 'Kies', or_choose: 'Of kies', drop_file_here: 'Sleep bestand hier', align_left: 'Links uitlijnen', align_center: 'Centreren', align_right: 'Rechts uitlijnen', align_justify: 'Uitvullen', horizontalrule: 'Horizontale lijn', fullscreen: 'Volledig scherm', deleted: 'Verwijderd', anchor: 'Anker', link_new_tab: 'Open link in new tab' };
cremol/symphony-demo
extensions/richtext_redactor/lib/lang/nl.js
JavaScript
mit
1,792
/** Creates reoccuring beeps (sinus) on one channel (usually left or right). After each beep a callback function (if provided) is called. Implementation uses the WebAudio API. The beep resembles DIN EN 60645-1 p. 27. WebAudio components: * this._audioOscillator (Oscillator) -> this._audioGain (Gain) -> this._audioMerger (ChannelMerger) -> destination (Sink, 2 channel) * NONE -> this._gainDummy (Gain) -> this._gainDummy is required to enforce stereo output (i.e., one channel silent). If a lower boundary for this._audioGain.gain is reached, a second GainNode could be used in addition. @class TheAudiometerBeepGenerator */ class TheAudiometerBeepGenerator { /** @param {int} frequency The frequency of the beeps. @param {int} channel The channel (index) to be used. @param {function} afterBeepCallback A callback function to be called after each beeps. */ constructor(frequency, channel, afterBeepCallback) { this._frequency = frequency; this._channel = channel; //0: Left? 1:Right? if (!(afterBeepCallback instanceof Function)) { console.error("afterBeepCallback is not a function!"); afterBeepCallback = function() {}; } this._afterBeepCallback = afterBeepCallback; this._scheduleNextBeep = true; this._gain = 0; //Setup audio infrastructure this._audioContext = new AudioContext(); this._audioMerger = this._audioContext.createChannelMerger(2); this._audioMerger.connect(this._audioContext.destination); this._audioGain = this._audioContext.createGain(); this._audioGain.connect(this._audioMerger, 0, this._channel); this._gainDummy = this._audioContext.createGain(); this._gainDummy.connect(this._audioMerger, 0, (this._channel + 1) % 2); this._audioOscillator = null; } _beeping() { this._afterBeepCallback(); if (!this._scheduleNextBeep) { TheFragebogen.logger.debug(this.constructor.name, "Last beep played."); this._audioContext.close(); return; } TheFragebogen.logger.debug(this.constructor.name, "Next beep with " + this.getFrequency() + "Hz and gain " + this.getGain()); this._audioOscillator = this._audioContext.createOscillator(); this._audioOscillator.connect(this._audioGain); this._audioOscillator.onended = () => this._beeping(); this._audioOscillator.frequency.value = this._frequency; const startTime = this._audioContext.currentTime; //Here we actually produce the beep (DIN EN 60645-1 p. 27) this._audioOscillator.start(startTime); this._audioGain.gain.setValueAtTime(0, startTime); this._audioGain.gain.linearRampToValueAtTime(this._gain, startTime + 0.05); // beep length must be more than 150 ms (we take 0.2s) this._audioGain.gain.setValueAtTime(this._gain, startTime + 0.05 + 0.2); // ramp length 20 - 50ms (choose 40ms) this._audioGain.gain.linearRampToValueAtTime(0, startTime + 0.05 + 0.2 + 0.05); this._audioOscillator.stop(startTime + 0.05 + 0.2 + 0.05 + 0.2); } start() { if (!this._scheduleNextBeep) { TheFragebogen.logger.error(this.constructor.name, "Cannot be reused. Please create a new one."); return; } this._scheduleNextBeep = true; this._beeping(); } stop() { this._scheduleNextBeep = false; } isStopped() { return !this._scheduleNextBeep; } getFrequency() { return this._frequency; } getGain() { return this._gain; } setGain(gain) { this._gain = gain; } }
TheFragebogen/thefragebogen.github.io
thefragebogen/examples_feasibility/TheAudiometer/src/theaudiometer_beepgenerator.js
JavaScript
mit
3,772
App.ApplicationController = Em.Controller.extend({ // Implement your controller here. });
dgeb/yeoman-ember-basic-example
app/scripts/controllers/application-controller.js
JavaScript
mit
93
import * as core from '../../core'; import glCore from 'pixi-gl-core'; import { default as Mesh } from '../Mesh'; const glslify = require('glslify'); // eslint-disable-line no-undef /** * WebGL renderer plugin for tiling sprites */ export class MeshRenderer extends core.ObjectRenderer { /** * constructor for renderer * * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. */ constructor(renderer) { super(renderer); this.shader = null; } /** * Sets up the renderer context and necessary buffers. * * @private */ onContextChange() { const gl = this.renderer.gl; this.shader = new core.Shader(gl, glslify('./mesh.vert'), glslify('./mesh.frag')); } /** * renders mesh * * @param {PIXI.mesh.Mesh} mesh mesh instance */ render(mesh) { const renderer = this.renderer; const gl = renderer.gl; const texture = mesh._texture; if (!texture.valid) { return; } let glData = mesh._glDatas[renderer.CONTEXT_UID]; if (!glData) { glData = { shader: this.shader, vertexBuffer: glCore.GLBuffer.createVertexBuffer(gl, mesh.vertices, gl.STREAM_DRAW), uvBuffer: glCore.GLBuffer.createVertexBuffer(gl, mesh.uvs, gl.STREAM_DRAW), indexBuffer: glCore.GLBuffer.createIndexBuffer(gl, mesh.indices, gl.STATIC_DRAW), // build the vao object that will render.. vao: new glCore.VertexArrayObject(gl), dirty: mesh.dirty, indexDirty: mesh.indexDirty, }; // build the vao object that will render.. glData.vao = new glCore.VertexArrayObject(gl) .addIndex(glData.indexBuffer) .addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0) .addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); mesh._glDatas[renderer.CONTEXT_UID] = glData; } if (mesh.dirty !== glData.dirty) { glData.dirty = mesh.dirty; glData.uvBuffer.upload(); } if (mesh.indexDirty !== glData.indexDirty) { glData.indexDirty = mesh.indexDirty; glData.indexBuffer.upload(); } glData.vertexBuffer.upload(); renderer.bindShader(glData.shader); renderer.bindTexture(texture, 0); renderer.state.setBlendMode(mesh.blendMode); glData.shader.uniforms.translationMatrix = mesh.worldTransform.toArray(true); glData.shader.uniforms.alpha = mesh.worldAlpha; glData.shader.uniforms.tint = mesh.tintRgb; const drawMode = mesh.drawMode === Mesh.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; glData.vao.bind() .draw(drawMode, mesh.indices.length) .unbind(); } } core.WebGLRenderer.registerPlugin('mesh', MeshRenderer);
twhitbeck/pixi.js
src/mesh/webgl/MeshRenderer.js
JavaScript
mit
3,175
/** * Please see `typhonjs-core-gulptasks` (https://www.npmjs.com/package/typhonjs-core-gulptasks) */ import gulp from 'gulp'; import gulpTasks from 'typhonjs-core-gulptasks'; // Import all tasks and set `rootPath` to the base project path and `srcGlob` to all JS sources in `./src`. gulpTasks(gulp, { rootPath: __dirname });
typhonjs-demos-deploy-electron/electron-backbone-parse-es6-todos-improved
gulpfile.babel.js
JavaScript
mit
339
{ var n = document.createEvent("HTMLEvents"); n.initEvent(e, !0, !0), t.dispatchEvent(n); }
stas-vilchik/bdd-ml
data/9258.js
JavaScript
mit
96
let addEmp180 = (employees) => { employees.push( {id:180, name: 'Jean Morris'} ) return employees; }; export {addEmp180};
dharapvj/learning-webpack2
step-01-with-webpack/modules/e180.js
JavaScript
mit
143
var models = require("mojo-models"); module.exports = models.Collection.extend({ createModel: function (properties) { return this.application.models.create("message", properties); } });
crcn-archive/mojo-pubnub
examples/chatroom/models/messages.js
JavaScript
mit
194
import {EventEmitter2 as EventEmitter} from 'eventemitter2'; import {List, Map} from 'immutable'; import AppDispatcher from '../dispatcher/AppDispatcher'; import ChatConstants from '../constants/ChatConstants'; const CHANGE_EVENT = 'change'; var _messages = List(); var _unseenCount = 0; var _isChatHidden = true; const ChatStore = Object.assign({}, EventEmitter.prototype, { getState() { return { messages: _messages, unseenCount: _unseenCount, isChatHidden: _isChatHidden }; } }); function toggleVisibility() { _isChatHidden = !_isChatHidden; _unseenCount = 0; } function submitMessage(message, className, received) { _messages = _messages.push(Map({ message: message, className: className })); if (received && _isChatHidden) { _unseenCount += 1; } } AppDispatcher.register(payload => { const action = payload.action; switch (action.actionType) { case ChatConstants.TOGGLE_VISIBILITY: toggleVisibility(); break; case ChatConstants.SUBMIT_MESSAGE: submitMessage(action.message, action.className, action.received); break; default: return true; } ChatStore.emit(CHANGE_EVENT); return true; }); export default ChatStore;
romanmatiasko/reti-chess
src/js/stores/ChatStore.js
JavaScript
mit
1,241
import { mockGroups } from 'tests/mocks'; const genMockGroup = (props) => () => new Promise((resolve) => resolve(props)); export const genBridge = (props, index) => ({ [`192.168.1.${index}`]: { bridge: { groups: genMockGroup(props) } } }); const initialMockBridge = genBridge(mockGroups, 0); const mockBridges = mockGroups.reduce((accumulated, mockBridge, index) => ({ ...accumulated, ...genBridge(mockBridge, index) }), initialMockBridge); export const genMockStore = (mockDispatch) => ({ getState: () => ({ meta: { hue: { userIds: ['foo', 'bar'], ...mockBridges } } }), dispatch: mockDispatch });
Nase00/moirai
tests/utils.js
JavaScript
mit
658
var _stylesheet = {}; /** * For awareness of KB262161, if 31 or more total stylesheets exist when invoking appendStyleSheet, insertStyleSheetBefore or replaceStyleSheet, an error will be thrown in ANY browser. * If you really want to disable this error (for non-IE), set this flag to true. * * Note: Once you hit 31 stylesheets in IE8 & IE9, you will be unable to create any new stylesheets successfully (regardless of this setting) and this will ALWAYS cause an error. */ _stylesheet.ignoreKB262161 = false; /** * Create an empty stylesheet and insert it into the DOM before the specified node. If no node is specified, then it will be appended at the end of the head. * * @param node - DOM element * @param callback - function(err, style) */ function insertEmptyStyleBefore(node, callback) { var style = document.createElement('style'); style.setAttribute('type', 'text/css'); var head = document.getElementsByTagName('head')[0]; if (node) { head.insertBefore(style, node); } else { head.appendChild(style); } if (style.styleSheet && style.styleSheet.disabled) { head.removeChild(style); callback('Unable to add any more stylesheets because you have exceeded the maximum allowable stylesheets. See KB262161 for more information.'); } else { callback(null, style); } } /** * Set the CSS text on the specified style element. * @param style * @param css * @param callback - function(err) */ function setStyleCss(style, css, callback) { try { // Favor cssText over textContent as it appears to be slightly faster for IE browsers. if (style.styleSheet) { style.styleSheet.cssText = css; } else if ('textContent' in style) { style.textContent = css; } else { style.appendChild(document.createTextNode(css)); } } catch (e) { // Ideally this should never happen but there are still obscure cases with IE where attempting to set cssText can fail. return callback(e); } return callback(null); } /** * Remove the specified style element from the DOM unless it's not in the DOM already. * * Note: This isn't doing anything special now, but if any edge-cases arise which need handling (e.g. IE), they can be implemented here. * @param node */ function removeStyleSheet(node) { if (node.tagName === 'STYLE' && node.parentNode) { node.parentNode.removeChild(node); } } /** * Create a stylesheet with the specified options. * @param options - options object. e.g. {ignoreKB262161: true, replace: null, css: 'body {}' } * @param callback - function(err, style) * * options * - css; The css text which will be used to create the new stylesheet. * - replace; Specify a style element which will be deleted and the new stylesheet will take its place. This overrides the 'insertBefore' option. * - insertBefore; If specified, the new stylesheet will be inserted before this DOM node. If this value is null or undefined, then it will be appended to the head element. */ function createStyleSheet(options, callback) { if (!_stylesheet.ignoreKB262161 && document.styleSheets.length >= 31) { callback('Unable to add any more stylesheets because you have exceeded the maximum allowable stylesheets. See KB262161 for more information.'); } insertEmptyStyleBefore(options.replace ? options.replace.nextSibling : options.insertBefore, function (err, style) { if (err) { callback(err); } else { setStyleCss(style, options.css || "", function (err) { if (err) { removeStyleSheet(style); callback(err); } else { // TODO: Desirable to duplicate attributes to the new stylesheet. (I have seen some unusual things in IE8 so I do not think this is trivial). if (options.replace) { removeStyleSheet(options.replace); } callback(null, style); } }); } }); } _stylesheet = { appendStyleSheet: function (css, callback) { createStyleSheet({ css: css }, callback); }, insertStyleSheetBefore: function (node, css, callback) { createStyleSheet({ insertBefore: node, css: css }, callback); }, replaceStyleSheet: function (node, css, callback) { createStyleSheet({ replace: node, css: css }, callback); }, removeStyleSheet: removeStyleSheet };
Duan112358/Duan112358.github.io
js/create-stylesheet.js
JavaScript
mit
4,643
/* Copyright (C) 2016 Adrien THIERRY http://seraum.com */ module.exports.httpsUtil = new httpsUtil(); UTILS.httpsUtil = new httpsUtil(); function httpsUtil() { this.getOption = function(str) { var result = {}; var arr = str.split(";"); for(var a in arr) { var tmp = arr[a].split(":"); if(tmp[1]) result[tmp[0]] = tmp[1]; } return result; } this.httpsGet = function(opt, cbError, cbOk, encoding) { if(!encoding) encoding = "utf8"; opt.path = encodeURI(opt.path); var get = https.request(opt); get.on("error", function(err) { cbError(err); }); get.on("response", function(response) { var data = ""; response.on("data", function(chunk) { data += chunk.toString(encoding); }); response.on("end", function() { cbOk(data); }); }); get.end(); return; } this.httpsGetPipe = function(opt, cbError,cbPipe, cbOk) { opt.path = encodeURI(opt.path); var get = https.request(opt); get.on("error", function(err) { cbError(err); }); get.on("response", function(response) { if(cbPipe) cbPipe(response); response.on("end", function() { if(cbOk) cbOk(); }); }); get.end(); return; } this.dataSuccess = function(req, res, message, data, version) { req.continue = false; var result = { success: true, status: "Ok", message: message, code: 0, ask: req.url, data: data, version: version, date: new Date(Date.now()), } res.end(JSON.stringify(result)); } this.dataError = function(req, res, status, message, code, version) { req.continue = false; var result = { success: false, status: status, code: code, message: message, ask: req.url, data: null, version: version, date: new Date(Date.now()), }; res.end(JSON.stringify(result)); } }
seraum/fortressjs-socketio-demochat
base/core/httpsutil.core.js
JavaScript
mit
2,477
/** * Created by maomao on 2020/4/20. */ Java.perform(function() { var cn = "android.webkit.WebSettings"; var target = Java.use(cn); if (target) { target.getMinimumFontSize.implementation = function(dest) { var myArray=new Array() myArray[0] = "INTERESTED" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "getMinimumFontSize"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.getMinimumFontSize.apply(this, arguments); }; target.setDefaultZoom.implementation = function(dest) { var myArray=new Array() myArray[0] = "INTERESTED" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "setDefaultZoom"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.setDefaultZoom.apply(this, arguments); }; target.setMinimumFontSize.implementation = function(dest) { var myArray=new Array() myArray[0] = "INTERESTED" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "setMinimumFontSize"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.setMinimumFontSize.apply(this, arguments); }; target.setTextSize.implementation = function(dest) { var myArray=new Array() myArray[0] = "INTERESTED" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "setTextSize"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.setTextSize.apply(this, arguments); }; } });
honeynet/droidbot
droidbot/resources/scripts/webkit/WebSettings.js
JavaScript
mit
1,988
define([ 'preact', 'htm', 'lib/formatters', 'components/DataTable', 'components/DataTable2', './LinkedDataSummary.styles' ], ( {Component, h}, htm, fmt, DataTable, DataTable2, styles ) => { const html = htm.bind(h); class LinkedDataSummary extends Component { renderLinkedDataSummaryTable() { const columns = [{ id: 'name', label: 'Sample Name/ID', display: true, isSortable: true, style: { flex: '2 0 0' }, render: (name, row) => { return html` <a href=${`/#samples/view/${row.id}/${row.version}`} target="_blank">${name}</a> `; } }, { id: 'typeCount', label: 'Unique data types', display: true, isSortable: true, style: { flex: '0 0 12em', textAlign: 'right', paddingRight: '1em' }, render: (typeCount) => { return html` <span>${typeCount}</span> `; } }, { id: 'objectCount', label: 'Total linked objects', display: true, isSortable: true, style: { flex: '0 0 12em', textAlign: 'right', paddingRight: '1em' }, render: (objectCount) => { return html` <span>${objectCount}</span> `; } }]; for (const name of this.props.data.types) { columns.push({ id: `type_${name}`, label: name, display: true, isSortable: true, style: { flex: '0 0 10em', textAlign: 'right', paddingRight: '1em' }, render: (count) => { return html` <span>${count}</span> `; } }); } const props = { columns, pageSize: 10, table: [], dataSource: this.props.data.summary .filter(({totals: {typeCount}}) => { return typeCount > 0; }) .map(({sample, totals, typeCounts}) => { const row = { id: sample.id, name: sample.name, version: sample.version, typeCount: totals.typeCount, objectCount: totals.objectCount, // source: sample.sample.dataSourceDefinition.source }; for (const name of this.props.data.types) { row[`type_${name}`] = typeCounts[name] || 0; } return row; }) }; const onRowClick = (row) => { window.open(`/#samples/view/${row.id}/${row.version}`, '_blank'); }; return html` <${DataTable} heights=${{row: 40, col: 40}} columnHeader=${3} onClick=${onRowClick} ...${props}/> `; } renderEmptySet() { return html` <div class="alert alert-warning" style=${{marginTop: '10px'}}> <span style=${{fontSize: '150%', marginRight: '4px'}}>∅</span> - Sorry, no linked data in this set. </div> `; } render() { if (this.props.data.summary.length === 0) { return this.renderEmptySet(); } return html` <div className="SampleSet" style=${styles.main}> ${this.renderLinkedDataSummaryTable()} </div> `; } } return LinkedDataSummary; });
eapearson/kbase-ui-plugin-dataview
src/plugin/iframe_root/modules/widgets/KBaseSets/SampleSet/components/LinkedDataSummary.js
JavaScript
mit
4,414
/** * Borra ejemplares anteriores y carga los nuevos * @param url */ var cargaEjemplaresSnib = function(url) { borraEjemplaresAnterioresSnib(); geojsonSnib(url); }; /** * Borra ejemplares anteriores */ var borraEjemplaresAnterioresSnib = function() { if (typeof snibLayer !== 'undefined') { if (map.hasLayer(snibLayer)) { map.removeControl(snib_control); map.removeLayer(snibLayer); } } snibLayer = L.markerClusterGroup({ chunkedLoading: true, spiderfyDistanceMultiplier: 2, spiderLegPolylineOptions: { weight: 1.5, color: 'white', opacity: 0.5 }, iconCreateFunction: function (cluster) { var markers = cluster.getAllChildMarkers(); return L.divIcon({ html: '<div><span>' + markers.length + '</span></div>', className: 'div-cluster-snib', iconSize: L.point(40, 40) }); } }); }; /** * La simbologia dentro del mapa */ var leyendaSnib = function() { snib_control = L.control.layers({}, {}, {collapsed: false, position: 'bottomleft'}).addTo(map); snib_control.addOverlay(snibLayer, '<b>Ejemplares del SNIB</b><br />(museos, colectas y proyectos) <sub>' + ejemplares_conteo + '</sub>' ); snib_control.addOverlay(coleccionesLayer, '<span aria-hidden="true" class="glyphicon glyphicon-map-marker div-icon-snib"></span>Especímenes en colecciones <sub>' + colecciones_conteo + '</sub>' ); snib_control.addOverlay(observacionesLayer, '<span aria-hidden="true" class="feather-ev-icon div-icon-snib"></span>Observaciones de aVerAves <sub>' + observaciones_conteo + '</sub>' ); snib_control.addOverlay(fosilesLayer, '<span aria-hidden="true" class="bone-ev-icon div-icon-snib"></span>Fósiles <sub>' + fosiles_conteo + '</sub>' ); snib_control.addOverlay(noCampoLayer, '<span aria-hidden="true" class="glyphicon glyphicon-flag div-icon-snib"></span>Localidad no de campo <sub>' + no_campo_conteo + '</sub>' ); }; /** * Añade los puntos en forma de fuentes */ var aniadePuntosSnib = function() { var geojsonFeature = { "type": "FeatureCollection", "features": allowedPoints.values() }; var colecciones = L.geoJson(geojsonFeature, { pointToLayer: function (feature, latlng) { // Para distinguir si son solo las coordenadas if (opciones.solo_coordenadas) { if (feature.properties.d[1] == 1) // Este campos quiere decir que es el deafult de la coleccion { colecciones_conteo++; return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: '<span aria-hidden="true" class="glyphicon glyphicon-map-marker"></span>'})}); } } else { if (!feature.properties.d.coleccion.toLowerCase().includes('averaves') && !feature.properties.d.coleccion.toLowerCase().includes('ebird') && feature.properties.d.ejemplarfosil.toLowerCase() != 'si' && feature.properties.d.probablelocnodecampo.toLowerCase() != 'si') { colecciones_conteo++; return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: '<span aria-hidden="true" class="glyphicon glyphicon-map-marker"></span>'})}); } } }, onEachFeature: function (feature, layer) { // Para distinguir si son solo las coordenadas if (opciones.solo_coordenadas) { layer.on("click", function () { ejemplarSnibGeojson(layer, feature.properties.d[0]); }); } else layer.bindPopup(ejemplarSnib(feature.properties.d)); } }); var observaciones = L.geoJson(geojsonFeature, { pointToLayer: function (feature, latlng) { // Para distinguir si son solo las coordenadas if (opciones.solo_coordenadas) { if (feature.properties.d[1] == 2) // Este campos quiere decir que es de aves aves { observaciones_conteo++; return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: '<span aria-hidden="true" class="feather-ev-icon"></span>'})}); } } else { if (feature.properties.d.coleccion.toLowerCase().includes('averaves') || feature.properties.d.coleccion.toLowerCase().includes('ebird')) { observaciones_conteo++; return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: '<span aria-hidden="true" class="feather-ev-icon"></span>'})}); } } }, onEachFeature: function (feature, layer) { // Para distinguir si son solo las coordenadas if (opciones.solo_coordenadas) { layer.on("click", function () { ejemplarSnibGeojson(layer, feature.properties.d[0]); }); } else layer.bindPopup(ejemplarSnib(feature.properties.d)); } }); var fosiles = L.geoJson(geojsonFeature, { pointToLayer: function (feature, latlng) { // Para distinguir si son solo las coordenadas if (opciones.solo_coordenadas) { if (feature.properties.d[1] == 3) // Este campos quiere decir que es de fosiles { fosiles_conteo++; return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: '<span aria-hidden="true" class="bone-ev-icon"></span>'})}); } } else { if (feature.properties.d.ejemplarfosil.toLowerCase() == 'si') { fosiles_conteo++; return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: '<span aria-hidden="true" class="bone-ev-icon"></span>'})}); } } }, onEachFeature: function (feature, layer) { // Para distinguir si son solo las coordenadas if (opciones.solo_coordenadas) { layer.on("click", function () { ejemplarSnibGeojson(layer, feature.properties.d[0]); }); } else layer.bindPopup(ejemplarSnib(feature.properties.d)); } }); var noCampo = L.geoJson(geojsonFeature, { pointToLayer: function (feature, latlng) { // Para distinguir si son solo las coordenadas if (opciones.solo_coordenadas) { if (feature.properties.d[1] == 4) // Este campos quiere decir que es de locacion no de campo { no_campo_conteo++; return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: '<span aria-hidden="true" class="glyphicon glyphicon-flag"></span>'})}); } } else { if (feature.properties.d.probablelocnodecampo.toLowerCase() == 'si') { no_campo_conteo++; return L.marker(latlng, {icon: L.divIcon({className: 'div-icon-snib', html: '<span aria-hidden="true" class="glyphicon glyphicon-flag"></span>'})}); } } }, onEachFeature: function (feature, layer) { // Para distinguir si son solo las coordenadas if (opciones.solo_coordenadas) { layer.on("click", function () { ejemplarSnibGeojson(layer, feature.properties.d[0]); }); } else layer.bindPopup(ejemplarSnib(feature.properties.d)); } }); coleccionesLayer = L.featureGroup.subGroup(snibLayer, colecciones); coleccionesLayer.addLayer(colecciones); observacionesLayer = L.featureGroup.subGroup(snibLayer, observaciones); observacionesLayer.addLayer(observaciones); fosilesLayer = L.featureGroup.subGroup(snibLayer, fosiles); fosilesLayer.addLayer(fosiles); noCampoLayer = L.featureGroup.subGroup(snibLayer, noCampo); noCampoLayer.addLayer(noCampo); map.addLayer(snibLayer); map.addLayer(coleccionesLayer); map.addLayer(observacionesLayer); map.addLayer(fosilesLayer); leyendaSnib(); }; /** * Hace una ajax request para la obtener la información de un taxon, esto es más rapido para muchos ejemplares * */ var ejemplarSnibGeojson = function(layer, id) { $.ajax({ url: "/especies/" + opciones.taxon + "/ejemplar-snib/" + id, dataType : "json", success : function (res){ if (res.estatus) { var contenido = ejemplarSnib(res.ejemplar); layer.bindPopup(contenido); layer.openPopup(); } else console.log("Hubo un error al retraer el ejemplar: " + res.msg); }, error: function( jqXHR , textStatus, errorThrown ){ console.log("error: " + textStatus); console.log(errorThrown); console.log(jqXHR.responseText); } }); // termina ajax }; /** * Lanza el pop up con la inforamcion del taxon, ya esta cargado; este metodo es lento con muchos ejemplares * */ var ejemplarSnib = function(prop) { // Sustituye las etiquetas h5 por h4 y centra el texto var nombre_f = $('<textarea/>').html(opciones.nombre).text().replace(/<h5/g, "<h4 class='text-center'").replace(/<\/h5/g, "</h4"); var contenido = ""; contenido += "" + nombre_f + ""; contenido += "<dt>Localidad: </dt><dd>" + prop.localidad + "</dd>"; contenido += "<dt>Municipio: </dt><dd>" + prop.municipiomapa + "</dd>"; contenido += "<dt>Estado: </dt><dd>" + prop.estadomapa + "</dd>"; contenido += "<dt>País: </dt><dd>" + prop.paismapa + "</dd>"; contenido += "<dt>Fecha: </dt><dd>" + prop.fechacolecta + "</dd>"; contenido += "<dt>Colector: </dt><dd>" + prop.colector + "</dd>"; contenido += "<dt>Colección: </dt><dd>" + prop.coleccion + "</dd>"; contenido += "<dt>Institución: </dt><dd>" + prop.institucion + "</dd>"; contenido += "<dt>País de la colección: </dt><dd>" + prop.paiscoleccion + "</dd>"; if (prop.proyecto.length > 0 && prop.urlproyecto.length > 0) contenido += "<dt>Proyecto: </dt><dd><a href='" + prop.urlproyecto + "' target='_blank'>" + prop.proyecto + "</a></dd>"; contenido += "<dt>Más información: </dt><dd><a href='" + prop.urlejemplar + "' target='_blank'>consultar</a></dd>"; //Para enviar un comentario acerca de un ejemplar en particular contenido += "<dt>¿Tienes un comentario?: </dt><dd><a href='/especies/" + opciones.taxon + "/comentarios/new?proveedor_id=" + prop.idejemplar + "&tipo_proveedor=6' target='_blank'>redactar</a></dd>"; return "<dl class='dl-horizontal'>" + contenido + "</dl>" + "<strong>ID SNIB: </strong>" + prop.idejemplar; }; /** * Carga el geojson para iterarlo * @param url */ var geojsonSnib = function(url) { $.ajax({ url: url, dataType : "json", success : function (d){ ejemplares_conteo = d.length; colecciones_conteo = 0; observaciones_conteo = 0; fosiles_conteo = 0; no_campo_conteo = 0; allowedPoints = d3.map([]); for(var i=0;i<d.length;i++) { var item_id = 'geo-' + i.toString(); if (opciones.solo_coordenadas) { allowedPoints.set(item_id, { "type" : "Feature", "properties": {d: [d[i][2], d[i][3]]}, "geometry" : {coordinates: [d[i][0], d[i][1]], type: "Point"} }); } else { allowedPoints.set(item_id, { "type" : "Feature", "properties": {d: d[i]}, "geometry" : JSON.parse(d[i].json_geom) }); } } aniadePuntosSnib(); }, error: function( jqXHR , textStatus, errorThrown ){ console.log("error: " + textStatus); console.log(errorThrown); console.log(jqXHR.responseText); } }); };
calonso-conabio/buscador
app/assets/javascripts/mapa/ejemplares_snib.js
JavaScript
mit
12,541
'use strict'; var should = require('should'), request = require('supertest'), app = require('../../server'), mongoose = require('mongoose'), User = mongoose.model('User'), EligibilityRule = mongoose.model('EligibilityRule'), agent = request.agent(app); /** * Globals */ var credentials, user, eligibilityRule; /** * Eligibility rule routes tests */ describe('Eligibility rule CRUD tests', function() { beforeEach(function(done) { // Create user credentials credentials = { username: 'username', password: 'password' }; // Create a new user user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: credentials.username, password: credentials.password, provider: 'local' }); // Save a user to the test db and create new Eligibility rule user.save(function() { eligibilityRule = { name: 'Eligibility rule Name' }; done(); }); }); it('should be able to save Eligibility rule instance if logged in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Eligibility rule agent.post('/eligibility-rules') .send(eligibilityRule) .expect(200) .end(function(eligibilityRuleSaveErr, eligibilityRuleSaveRes) { // Handle Eligibility rule save error if (eligibilityRuleSaveErr) done(eligibilityRuleSaveErr); // Get a list of Eligibility rules agent.get('/eligibility-rules') .end(function(eligibilityRulesGetErr, eligibilityRulesGetRes) { // Handle Eligibility rule save error if (eligibilityRulesGetErr) done(eligibilityRulesGetErr); // Get Eligibility rules list var eligibilityRules = eligibilityRulesGetRes.body; // Set assertions (eligibilityRules[0].user._id).should.equal(userId); (eligibilityRules[0].name).should.match('Eligibility rule Name'); // Call the assertion callback done(); }); }); }); }); it('should not be able to save Eligibility rule instance if not logged in', function(done) { agent.post('/eligibility-rules') .send(eligibilityRule) .expect(401) .end(function(eligibilityRuleSaveErr, eligibilityRuleSaveRes) { // Call the assertion callback done(eligibilityRuleSaveErr); }); }); it('should not be able to save Eligibility rule instance if no name is provided', function(done) { // Invalidate name field eligibilityRule.name = ''; agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Eligibility rule agent.post('/eligibility-rules') .send(eligibilityRule) .expect(400) .end(function(eligibilityRuleSaveErr, eligibilityRuleSaveRes) { // Set message assertion (eligibilityRuleSaveRes.body.message).should.match('Please fill Eligibility rule name'); // Handle Eligibility rule save error done(eligibilityRuleSaveErr); }); }); }); it('should be able to update Eligibility rule instance if signed in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Eligibility rule agent.post('/eligibility-rules') .send(eligibilityRule) .expect(200) .end(function(eligibilityRuleSaveErr, eligibilityRuleSaveRes) { // Handle Eligibility rule save error if (eligibilityRuleSaveErr) done(eligibilityRuleSaveErr); // Update Eligibility rule name eligibilityRule.name = 'WHY YOU GOTTA BE SO MEAN?'; // Update existing Eligibility rule agent.put('/eligibility-rules/' + eligibilityRuleSaveRes.body._id) .send(eligibilityRule) .expect(200) .end(function(eligibilityRuleUpdateErr, eligibilityRuleUpdateRes) { // Handle Eligibility rule update error if (eligibilityRuleUpdateErr) done(eligibilityRuleUpdateErr); // Set assertions (eligibilityRuleUpdateRes.body._id).should.equal(eligibilityRuleSaveRes.body._id); (eligibilityRuleUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?'); // Call the assertion callback done(); }); }); }); }); it('should be able to get a list of Eligibility rules if not signed in', function(done) { // Create new Eligibility rule model instance var eligibilityRuleObj = new EligibilityRule(eligibilityRule); // Save the Eligibility rule eligibilityRuleObj.save(function() { // Request Eligibility rules request(app).get('/eligibility-rules') .end(function(req, res) { // Set assertion res.body.should.be.an.Array.with.lengthOf(1); // Call the assertion callback done(); }); }); }); it('should be able to get a single Eligibility rule if not signed in', function(done) { // Create new Eligibility rule model instance var eligibilityRuleObj = new EligibilityRule(eligibilityRule); // Save the Eligibility rule eligibilityRuleObj.save(function() { request(app).get('/eligibility-rules/' + eligibilityRuleObj._id) .end(function(req, res) { // Set assertion res.body.should.be.an.Object.with.property('name', eligibilityRule.name); // Call the assertion callback done(); }); }); }); it('should be able to delete Eligibility rule instance if signed in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Eligibility rule agent.post('/eligibility-rules') .send(eligibilityRule) .expect(200) .end(function(eligibilityRuleSaveErr, eligibilityRuleSaveRes) { // Handle Eligibility rule save error if (eligibilityRuleSaveErr) done(eligibilityRuleSaveErr); // Delete existing Eligibility rule agent.delete('/eligibility-rules/' + eligibilityRuleSaveRes.body._id) .send(eligibilityRule) .expect(200) .end(function(eligibilityRuleDeleteErr, eligibilityRuleDeleteRes) { // Handle Eligibility rule error error if (eligibilityRuleDeleteErr) done(eligibilityRuleDeleteErr); // Set assertions (eligibilityRuleDeleteRes.body._id).should.equal(eligibilityRuleSaveRes.body._id); // Call the assertion callback done(); }); }); }); }); it('should not be able to delete Eligibility rule instance if not signed in', function(done) { // Set Eligibility rule user eligibilityRule.user = user; // Create new Eligibility rule model instance var eligibilityRuleObj = new EligibilityRule(eligibilityRule); // Save the Eligibility rule eligibilityRuleObj.save(function() { // Try deleting Eligibility rule request(app).delete('/eligibility-rules/' + eligibilityRuleObj._id) .expect(401) .end(function(eligibilityRuleDeleteErr, eligibilityRuleDeleteRes) { // Set message assertion (eligibilityRuleDeleteRes.body.message).should.match('User is not logged in'); // Handle Eligibility rule error error done(eligibilityRuleDeleteErr); }); }); }); afterEach(function(done) { User.remove().exec(); EligibilityRule.remove().exec(); done(); }); });
rajasekaran247/school-administrative-services
app/tests/eligibility-rule.server.routes.test.js
JavaScript
mit
7,745
L.Illustrate.ResizeHandle = L.Illustrate.EditHandle.extend({ options: { TYPE: 'resize' }, initialize: function(shape, options) { L.Illustrate.EditHandle.prototype.initialize.call(this, shape, options); this._corner = options.corner; }, _onHandleDrag: function(event) { var handle = event.target, offset = this._getOffset(handle.getLatLng()); this._handled.setSize(offset.abs().multiplyBy(2).round()); }, _getOffset: function(latlng) { var coord = this._latLngToTextboxCoords(latlng), minOffset = this._handled._minSize.divideBy(2), x = (Math.abs(coord.x) < minOffset.x) ? minOffset.x : coord.x, y = (Math.abs(coord.y) < minOffset.y) ? minOffset.y : coord.y; return new L.Point(x,y); }, updateHandle: function() { var size = this._handled.getSize(), height = Math.round(size.y/2), width = Math.round(size.x/2); switch (this._corner) { case 'upper-left': this._handleOffset = new L.Point(-width, height); break; case 'upper-right': this._handleOffset = new L.Point(width, height); break; case 'lower-left': this._handleOffset = new L.Point(-width, -height); break; case 'lower-right': this._handleOffset = new L.Point(width, -height); break; } L.Illustrate.EditHandle.prototype.updateHandle.call(this); } });
manleyjster/Leaflet.Illustrate
src/edit/handles/L.Illustrate.ResizeHandle.js
JavaScript
mit
1,296
'use strict'; module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.addColumn("Skus", "colorId", { type: Sequelize.INTEGER, references: { model: 'Colors', key: 'id' } }) }, down: function (queryInterface, Sequelize) { return queryInterface.removeColumn("Skus", "colorId") } };
PinguinJantan/openPackTrack-backend
migrations/20171205070341-add-column-colorId-on-sku.js
JavaScript
mit
363
cordova.define('aiq-plugin-client', function(require, exports, module) { var exec = require('cordova/exec'); var channel = require('cordova/channel'); var core = require('aiq-plugin-core'); // Wait for the AIQClient plugin to initialize which is done in the // onCordovaReady callback below. channel.createSticky('onAIQClientReady'); channel.waitForInitialization('onAIQClientReady'); function Client() { var that = this; channel.onCordovaReady.subscribe(function() { var callback = function(version) { that.version = version; channel.onAIQClientReady.fire(); }; exec(callback, undefined, 'AIQClient', 'getVersion', []); }); } Client.prototype.closeApp = function() { exec(undefined, undefined, 'AIQClient', 'closeApp', []); }; Client.prototype.getAppArguments = function() { var args = {}; if (window.location.search.length !== 0) { window.location.search.substring(1).split('&').forEach(function(param) { var pair = param.split('='); if (pair.length === 2) { args[pair[0]] = pair[1]; } else { args[pair[0]] = null; } }); } return args; }; Client.prototype.setAppTitle = function(title) { title = title || ''; exec(undefined, undefined, 'AIQClient', 'setAppTitle', [title]); }; Client.prototype.getCurrentUser = function(callbacks) { callbacks = callbacks || {}; exec(callbacks.success, core._proxyError(callbacks), 'AIQClient', 'getCurrentUser', []); }; Client.prototype.getSession = function(callbacks) { callbacks = callbacks || {}; exec(callbacks.success, core._proxyError(callbacks), 'AIQClient', 'getSession', []); }; module.exports = new Client(); });
appear/AIQJSBridge
Pod/Assets/plugins/aiq-plugin-client/www/client.js
JavaScript
mit
1,961
'use strict'; var assert = require('assert'); var fs = require('fs'); var Extractor = require('..').Extractor; var testExtract = require('./utils').testExtract; describe('Extract', function () { it('Extracts strings from views', function () { var files = [ 'test/fixtures/single.html' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 1); assert.equal(catalog.items[0].msgid, 'Hello!'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/single.html:3', 'test/fixtures/single.html:4']); }); it('Merges multiple views into one .pot', function () { var files = [ 'test/fixtures/single.html', 'test/fixtures/second.html', 'test/fixtures/custom.extension' ]; var catalog = testExtract(files); var i = catalog.items; assert.equal(i.length, 2); assert.equal(i[0].msgid, 'Hello!'); assert.equal(i[1].msgid, 'This is a test'); }); it('Merges duplicate strings with references', function () { var files = [ 'test/fixtures/single.html', 'test/fixtures/second.html', 'test/fixtures/custom.extension' ]; var catalog = testExtract(files); var i = catalog.items; assert.equal(i.length, 2); assert.equal(i[0].msgid, 'Hello!'); assert.deepEqual(i[0].references, ['test/fixtures/second.html:3', 'test/fixtures/single.html:3', 'test/fixtures/single.html:4']); assert.equal(i[1].msgid, 'This is a test'); assert.deepEqual(i[1].references, ['test/fixtures/second.html:4']); }); it('Works with inline templates', function () { var files = [ 'test/fixtures/inline-templates.html' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 1); assert.equal(catalog.items[0].msgid, 'Hello world!'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/inline-templates.html:4']); }); it('Does not encode entities', function () { var files = [ 'test/fixtures/entities.html' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 3); assert.equal(catalog.items[0].msgid, '&amp; & &apos; \' &gt; > &lt; < &quot; "'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/entities.html:3']); assert.equal(catalog.items[1].msgid, '<span id="&amp; & &apos; \' &gt; > &lt; <"></span>'); assert.equal(catalog.items[1].msgstr, ''); assert.deepEqual(catalog.items[1].references, ['test/fixtures/entities.html:4']); assert.equal(catalog.items[2].msgid, '<span id="&amp; & &gt; > &lt; < &quot;"></span>'); assert.equal(catalog.items[2].msgstr, ''); assert.deepEqual(catalog.items[2].references, ['test/fixtures/entities.html:5']); }); it('Strips whitespace around strings', function () { var files = [ 'test/fixtures/strip.html' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 1); assert.equal(catalog.items[0].msgid, 'Hello!'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/strip.html:3']); }); it('Handles attribute with < or >', function () { var files = [ 'test/fixtures/ngif.html' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 1); assert.equal(catalog.items[0].msgid, 'Show {{trackcount}} song...'); assert.equal(catalog.items[0].msgid_plural, 'Show all {{trackcount}} songs...'); assert.equal(catalog.items[0].msgstr.length, 2); assert.equal(catalog.items[0].msgstr[0], ''); assert.equal(catalog.items[0].msgstr[1], ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/ngif.html:3']); }); it('Can customize delimiters', function () { var files = [ 'test/fixtures/delim.html' ]; var catalog = testExtract(files, { startDelim: '[[', endDelim: ']]' }); assert.equal(catalog.items.length, 1); assert.equal(catalog.items[0].msgid, 'Hello'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/delim.html:3']); }); it('Sorts strings', function () { var files = [ 'test/fixtures/sort.html' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 3); assert.equal(catalog.items[0].msgid, 'a'); assert.equal(catalog.items[1].msgid, 'b'); assert.equal(catalog.items[2].msgid, 'c'); }); it('Extracts strings concatenation from JavaScript source', function () { var files = [ 'test/fixtures/concat.js' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 2); assert.equal(catalog.items[0].msgid, 'Hello one concat!'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/concat.js:2']); assert.equal(catalog.items[1].msgid, 'Hello two concat!'); assert.equal(catalog.items[1].msgstr, ''); assert.deepEqual(catalog.items[1].references, ['test/fixtures/concat.js:3']); }); it('Supports data-translate for old-school HTML style', function () { var files = [ 'test/fixtures/data.html' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 6); assert.equal(catalog.items[0].msgid, '1: Hello!'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/data.html:3']); assert.equal(catalog.items[1].msgid, '2: with comment'); assert.equal(catalog.items[1].msgstr, ''); assert.deepEqual(catalog.items[1].references, ['test/fixtures/data.html:4']); assert.deepEqual(catalog.items[1].extractedComments, ['comment']); assert.equal(catalog.items[2].msgid, '3: with data-comment'); assert.equal(catalog.items[2].msgstr, ''); assert.deepEqual(catalog.items[2].references, ['test/fixtures/data.html:5']); assert.deepEqual(catalog.items[2].extractedComments, ['comment']); assert.equal(catalog.items[3].msgid, '4: translate with data-comment'); assert.equal(catalog.items[3].msgstr, ''); assert.deepEqual(catalog.items[3].references, ['test/fixtures/data.html:6']); assert.deepEqual(catalog.items[3].extractedComments, ['comment']); assert.equal(catalog.items[4].msgid, '5: translate with data-plural'); assert.deepEqual(catalog.items[4].msgstr, ['', '']); assert.deepEqual(catalog.items[4].references, ['test/fixtures/data.html:7']); assert.equal(catalog.items[4].msgid_plural, 'foos'); assert.equal(catalog.items[5].msgid, '6: data-translate with data-plural'); assert.deepEqual(catalog.items[5].msgstr, ['', '']); assert.deepEqual(catalog.items[5].references, ['test/fixtures/data.html:10']); assert.equal(catalog.items[5].msgid_plural, 'foos'); }); it('Extracts strings from non-delimited attribute', function () { var files = [ 'test/fixtures/no_delimiter.html' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 3); assert.equal(catalog.items[0].msgid, 'Click to upload file'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/no_delimiter.html:3']); assert.equal(catalog.items[1].msgid, 'Selected a file to upload!'); assert.equal(catalog.items[1].msgstr, ''); assert.deepEqual(catalog.items[1].references, ['test/fixtures/no_delimiter.html:5']); }); it('Extracts strings from <translate> element', function () { var files = [ 'test/fixtures/translate-element.html' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 2); assert.equal(catalog.items[0].msgid, '1: message'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/translate-element.html:1']); assert.deepEqual(catalog.items[0].extractedComments, []); assert.equal(catalog.items[1].msgid, '2: message with comment and plural'); assert.equal(catalog.items[1].msgid_plural, 'foos'); assert.deepEqual(catalog.items[1].msgstr, ['', '']); assert.deepEqual(catalog.items[1].references, ['test/fixtures/translate-element.html:2']); assert.deepEqual(catalog.items[1].extractedComments, ['comment']); }); it('Can customize the marker name', function () { var files = [ 'test/fixtures/custom_marker_name.js' ]; var catalog = testExtract(files, { markerName: '__' }); assert.equal(catalog.items.length, 1); assert.equal(catalog.items[0].msgid, 'Hello custom'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/custom_marker_name.js:4']); }); it('Can customize multiple marker name functions', function () { var files = [ 'test/fixtures/custom_marker_names.js' ]; var catalog = testExtract(files, { markerNames: ['showError', 'showSuccess'] }); assert.equal(catalog.items.length, 3); assert.equal(catalog.items[0].msgid, 'Hello default'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/custom_marker_names.js:2']); assert.equal(catalog.items[1].msgid, 'Hello first custom'); assert.equal(catalog.items[1].msgstr, ''); assert.deepEqual(catalog.items[1].references, ['test/fixtures/custom_marker_names.js:6']); assert.equal(catalog.items[2].msgid, 'Hello second custom'); assert.equal(catalog.items[2].msgstr, ''); assert.deepEqual(catalog.items[2].references, ['test/fixtures/custom_marker_names.js:7']); }); it('Can post-process the catalog', function () { var called = false; var files = [ 'test/fixtures/single.html' ]; var catalog = testExtract(files, { postProcess: function (po) { called = true; po.headers.Test = 'Test'; } }); assert.equal(catalog.items.length, 1); assert.equal(catalog.items[0].msgid, 'Hello!'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/single.html:3', 'test/fixtures/single.html:4']); assert.equal(catalog.headers.Test, 'Test'); assert(called); }); it('Does not create empty-keyed items', function () { var files = [ 'test/fixtures/empty.html' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 0); }); // see https://github.com/rubenv/angular-gettext/issues/60 it('Adds Project-Id-Version header', function () { // can't use PO.parse b/c that sets headers for us var extractor = new Extractor(); var filename = 'test/fixtures/single.html'; extractor.parse(filename, fs.readFileSync(filename, 'utf8')); var poText = extractor.toString(); assert.equal(/\n"Project-Id-Version: \\n"\n/.test(poText), true); }); it('Supports Angular 1.3 bind once syntax', function () { var files = [ 'test/fixtures/bind-once.html' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 4); assert.equal(catalog.items[0].msgid, '0: no space'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/bind-once.html:1']); assert.equal(catalog.items[1].msgid, '1: trailing space'); assert.equal(catalog.items[1].msgstr, ''); assert.deepEqual(catalog.items[1].references, ['test/fixtures/bind-once.html:2']); assert.equal(catalog.items[2].msgid, '2: leading space'); assert.equal(catalog.items[2].msgstr, ''); assert.deepEqual(catalog.items[2].references, ['test/fixtures/bind-once.html:3']); assert.equal(catalog.items[3].msgid, '3: leading and trailing space'); assert.equal(catalog.items[3].msgstr, ''); assert.deepEqual(catalog.items[3].references, ['test/fixtures/bind-once.html:4']); }); it('Should extract context from HTML', function () { var files = [ 'test/fixtures/context.html' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 2); assert.equal(catalog.items[0].msgid, 'Hello!'); assert.equal(catalog.items[0].msgstr, ''); assert.strictEqual(catalog.items[0].msgctxt, null); assert.equal(catalog.items[1].msgid, 'Hello!'); assert.equal(catalog.items[1].msgstr, ''); assert.equal(catalog.items[1].msgctxt, 'male'); }); it('Extracts strings from an ES6 class', function () { var files = [ 'test/fixtures/es6-class.js' ]; var catalog = testExtract(files); assert.equal(catalog.items.length, 1); assert.equal(catalog.items[0].msgid, 'Hi from an ES6 class!'); assert.equal(catalog.items[0].msgstr, ''); assert.deepEqual(catalog.items[0].references, ['test/fixtures/es6-class.js:3']); }); });
kvantetore/angular-gettext-tools
test/extract.js
JavaScript
mit
14,072
import cxs from 'cxs' import { containerStyle, buttonStyles } from '../styles' import { renderHtml, renderBody } from '../render' export const cxsCase = caseName => { const getButtonClassName = i => cxs(buttonStyles[i]) const html = renderBody(caseName, cxs(containerStyle), getButtonClassName) const { css } = cxs cxs.reset() return renderHtml(css, html) }
risetechnologies/fela
benchmarks/ssr-comparison/src/style-overload-test/cases/cxs.js
JavaScript
mit
373
(function() { /* Copyright (c) 2002-2014 "Neo Technology," Network Engine for Objects in Lund AB [http://neotechnology.com] This file is part of Neo4j. Neo4j is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; define(["neo4j/webadmin/utils/ItemUrlResolver"], function(ItemUrlResolver) { var RelationshipSearcher; return RelationshipSearcher = (function() { function RelationshipSearcher(server) { this.extractNodeId = __bind(this.extractNodeId, this); this.exec = __bind(this.exec, this); this.match = __bind(this.match, this); this.server = server; this.urlResolver = new ItemUrlResolver(server); this.pattern = /^((rels)|(relationships)):([0-9]+)$/i; } RelationshipSearcher.prototype.match = function(statement) { return this.pattern.test(statement); }; RelationshipSearcher.prototype.exec = function(statement) { return this.server.node(this.urlResolver.getNodeUrl(this.extractNodeId(statement))).then(function(node, fulfill) { return node.getRelationships().then(function(relationships) { return fulfill(relationships); }); }); }; RelationshipSearcher.prototype.extractNodeId = function(statement) { var match; match = this.pattern.exec(statement); return match[4]; }; return RelationshipSearcher; })(); }); }).call(this);
ahmadassaf/Balloon
src/main/resources/webadmin-html/js/neo4j/webadmin/modules/databrowser/search/RelationshipsForNodeSearcher.js
JavaScript
mit
2,104
/*! * node-hbase-client - examples/helloworld.js * Copyright(c) 2013 fengmk2 <fengmk2@gmail.com> * MIT Licensed */ "use strict"; /** * Module dependencies. */ var config = require('../test/config_test'); var HBase = require('../'); // var client = HBase.create({ // zookeeperHosts: [ // '127.0.0.1:2181', '127.0.0.1:2182', // ], // zookeeperRoot: '/hbase-0.94', // }); var client = HBase.create(config); // Put var put = new HBase.Put('foo'); put.add('f1', 'name', 'foo'); put.add('f1', 'age', '18'); client.put('user', put, function (err) { console.log(err); }); function sendGet() { // Get `f1:name, f2:age` from `user` table. var param = new HBase.Get('foo'); param.addColumn('f1', 'name'); param.addColumn('f1', 'age'); client.get('user', param, function (err, result) { console.log(err); // var kvs = result.raw(); // for (var i = 0; i < kvs.length; i++) { // var kv = kvs[i]; // console.log('key: `%s`, value: `%s`', kv.toString(), kv.getValue().toString()); // } }); } sendGet(); setInterval(sendGet, 5000);
algoriz/node-hbase-client
examples/helloworld.js
JavaScript
mit
1,081
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.messages = exports.ruleName = undefined; exports.default = function (actual) { return function (root, result) { var validOptions = (0, _utils.validateOptions)(result, ruleName, { actual: actual }); if (!validOptions) { return; } root.walkDecls(function (decl) { if (!(0, _utils.isStandardSyntaxDeclaration)(decl) || !(0, _utils.isStandardSyntaxProperty)(decl.prop)) { return; } var prop = decl.prop, value = decl.value; var normalizedProp = _postcss.vendor.unprefixed(prop.toLowerCase()); // Ignore not shorthandable properties, and math operations if (isIgnoredCharacters(value) || !shorthandableProperties.has(normalizedProp) || ignoredShorthandProperties.has(normalizedProp)) { return; } var valuesToShorthand = []; (0, _postcssValueParser2.default)(value).walk(function (valueNode) { if (valueNode.type !== "word") { return; } valuesToShorthand.push(_postcssValueParser2.default.stringify(valueNode)); }); if (valuesToShorthand.length <= 1 || valuesToShorthand.length > 4) { return; } var shortestForm = canCondense.apply(undefined, valuesToShorthand); var shortestFormString = shortestForm.filter(function (value) { return value; }).join(" "); var valuesFormString = valuesToShorthand.join(" "); if (shortestFormString.toLowerCase() === valuesFormString.toLowerCase()) { return; } (0, _utils.report)({ message: messages.rejected(value, shortestFormString), node: decl, result: result, ruleName: ruleName }); }); }; }; var _utils = require("../../utils"); var _shorthandData = require("../../reference/shorthandData"); var _shorthandData2 = _interopRequireDefault(_shorthandData); var _postcssValueParser = require("postcss-value-parser"); var _postcssValueParser2 = _interopRequireDefault(_postcssValueParser); var _postcss = require("postcss"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ruleName = exports.ruleName = "shorthand-property-no-redundant-values"; var messages = exports.messages = (0, _utils.ruleMessages)(ruleName, { rejected: function rejected(unexpected, expected) { return "Unexpected longhand value '" + unexpected + "' instead of '" + expected + "'"; } }); var shorthandableProperties = new Set(Object.keys(_shorthandData2.default)); var ignoredCharacters = ["+", "-", "*", "/", "(", ")", "$", "@", "--", "var("]; var ignoredShorthandProperties = new Set(["background", "font", "border", "border-top", "border-bottom", "border-left", "border-right", "list-style", "transition"]); function isIgnoredCharacters(value) { return ignoredCharacters.some(function (char) { return value.indexOf(char) !== -1; }); } function canCondense(top, right) { var bottom = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var left = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var lowerTop = top.toLowerCase(); var lowerRight = right.toLowerCase(); var lowerBottom = bottom && bottom.toLowerCase(); var lowerLeft = left && left.toLowerCase(); if (canCondenseToOneValue(lowerTop, lowerRight, lowerBottom, lowerLeft)) { return [top]; } else if (canCondenseToTwoValues(lowerTop, lowerRight, lowerBottom, lowerLeft)) { return [top, right]; } else if (canCondenseToThreeValues(lowerTop, lowerRight, lowerBottom, lowerLeft)) { return [top, right, bottom]; } else { return [top, right, bottom, left]; } } function canCondenseToOneValue(top, right, bottom, left) { if (top !== right) { return false; } return top === bottom && (bottom === left || !left) || !bottom && !left; } function canCondenseToTwoValues(top, right, bottom, left) { return top === bottom && right === left || top === bottom && !left && top !== right; } function canCondenseToThreeValues(top, right, bottom, left) { return right === left; }
IgorKilipenko/KTS_React
node_modules/stylelint/dist/rules/shorthand-property-no-redundant-values/index.js
JavaScript
mit
4,175
define([ 'app', 'marionette' ], function(app, Marionette){ return Marionette.Region.extend({ onShow: function(view){ this.listenTo(view, "dialog:close", this.closeDialog); var self = this; this.$el.modal({ backdrop: true, keyboard: true, show: true }); }, closeDialog: function(){ this.stopListening(); this.close(); this.$el.modal('hide'); } }); });
danmux/floepublic
js/app/regions/dialog.js
JavaScript
mit
537
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- var exec = require('cordova/exec'); var platform = require('cordova/platform'); // Set up the callback for native events being sent back exec(onNativeEventRaised, onInitializeFailed, "NativeHost", "initialize", []); // // The layer that communicates with the native host // function ToNative() {} _pendingMessages = []; _handlesFromManagedCount = 0; // TODO: Lifetime: destroy APIs _objectsFromManaged = {}; _objectsFromNative = {}; MessageType = { Create: 0, Set: 1, Invoke: 2, EventAdd: 3, EventRemove: 4, StaticInvoke: 5, FieldGet: 6, StaticFieldGet: 7, GetInstance: 8, Navigate: 9, FieldSet: 10, PrivateFieldGet: 11 }; function onInitializeFailed(error) { var prefix = "Unable to initialize the Ace plugin: "; var suffix = ". The most common reason is that <feature name=\"NativeHost\">...</feature> is missing from the copy of config.xml in the platforms directory. " + "Try uninstalling the plugin then reinstalling it."; var message = error; if (!message.startsWith(prefix)) { message = prefix + error + suffix; } console.log(message); } function defaultOnError(error) { var help = "See http://ace.run/docs/errors for help."; throw new Error("Native error: " + error + "\r\n\r\n" + help); } ToNative.errorHandler = function (handler) { return handler ? handler : defaultOnError; }; function onNativeEventRaised(message) { /* TODO: No startupMarkup event: if (message instanceof ArrayBuffer) { // This is startup markup retured from initialize ace.XbfReader.loadBytes(message, function (root) { ace.getHostPage().setContent(root); }); return; } */ var handle = message[0]; var eventName = message[1]; var eventData = message[2]; var eventData2 = null; if (message.length > 3) { eventData2 = message[3]; } // iOS sets a null handle to -1 because otherwise the marshalled array gets cut off if (handle == null || handle == -1) { // TODO: Map ace.navigate to frame's navigate event? if (eventName == "ace.navigate") { ace.navigate(eventData); return; } else if (eventName == "ace.android.intentchanged") { ace.raiseEvent("android.intentchanged"); return; } } // Move the below to a call to instanceFromHandle? But re-wraps if can't be found. Should have option to console.warn + ignore for this case. // Get the instance from the handle var instance; if (handle.fromNative) { instance = _objectsFromNative[handle.value]; } else { instance = _objectsFromManaged[handle.value]; } if (!instance.raiseEvent(eventName, eventData, eventData2)) { // The event should only be raised if there are existing handlers console.warn(eventName + " raised from native code, but there are no handlers"); } } function debugPrintMessage(messageArray) { var debugArray = []; for (var i = 0; i < messageArray.length; i++) { var s = messageArray[i]; if (i == 0) { if (s == MessageType.Create) s = "Create"; else if (s == MessageType.Set) s = "Set"; else if (s == MessageType.Invoke) s = "Invoke"; else if (s == MessageType.EventAdd) s = "EventAdd"; else if (s == MessageType.EventRemove) s = "EventRemove"; else if (s == MessageType.StaticInvoke) s = "StaticInvoke"; else if (s == MessageType.FieldGet) s = "FieldGet"; else if (s == MessageType.StaticFieldGet) s = "StaticFieldGet"; else if (s == MessageType.GetInstance) s = "GetInstance"; else if (s == MessageType.Navigate) s = "Navigate"; else if (s == MessageType.FieldSet) s = "FieldSet"; else if (s == MessageType.PrivateFieldGet) s = "PrivateFieldGet"; else s = "UNKNOWN"; } else if (i == 1) { var n = s.fromNative; s = "$" + s.value; if (n) s += "N"; } debugArray.push(s); } console.log("Queue " + _pendingMessages.length + ": " + debugArray); } function queueMessage(messageArray) { if (_pendingMessages.length == 0) { // Set up the function to send the messages on idle setTimeout(ToNative.sendPendingMessages, 0); } // debugPrintMessage(messageArray); _pendingMessages.push(messageArray); } ToNative.instanceFromHandle = function (handle) { var instance; // Try to get the existing instance if (handle.fromNative) { instance = _objectsFromNative[handle.value]; } else { instance = _objectsFromManaged[handle.value]; } if (instance === undefined) { // Wrapping the handle in a new instance instance = new ace.WrappedNativeObject(handle); if (handle.fromNative) { _objectsFromNative[handle.value] = instance; } else { throw new Error("The instance is missing for a managed-initiated object"); } } return instance; }; ToNative.queueCreateMessage = function (instance, nativeTypeName, constructorArgs) { var handle = { _t: "H", value: _handlesFromManagedCount++ }; if (constructorArgs) { for (var i = 0; i < constructorArgs.length; i++) { // Marshal a NativeObject by sending its handle if (constructorArgs[i] instanceof ace.NativeObject) constructorArgs[i] = constructorArgs[i].handle; } queueMessage([MessageType.Create, handle, nativeTypeName, constructorArgs]); } else { queueMessage([MessageType.Create, handle, nativeTypeName]); } _objectsFromManaged[handle.value] = instance; return handle; }; ToNative.queueGetInstanceMessage = function (instance, nativeTypeName) { var handle = { _t: "H", value: _handlesFromManagedCount++ }; queueMessage([MessageType.GetInstance, handle, nativeTypeName]); _objectsFromManaged[handle.value] = instance; return handle; }; ToNative.queueInvokeMessage = function (instance, methodName, args) { for (var i = 0; i < args.length; i++) { // Marshal a NativeObject by sending its handle if (args[i] instanceof ace.NativeObject) args[i] = args[i].handle; } queueMessage([MessageType.Invoke, instance.handle, methodName, args]); }; ToNative.queueStaticInvokeMessage = function (className, methodName, args) { for (var i = 0; i < args.length; i++) { // Marshal a NativeObject by sending its handle if (args[i] instanceof ace.NativeObject) args[i] = args[i].handle; } queueMessage([MessageType.StaticInvoke, className, methodName, args]); }; ToNative.queueFieldGetMessage = function (instance, fieldName) { queueMessage([MessageType.FieldGet, instance.handle, fieldName]); }; ToNative.queueStaticFieldGetMessage = function (className, fieldName) { queueMessage([MessageType.StaticFieldGet, className, fieldName]); }; ToNative.queuePrivateFieldGetMessage = function (instance, fieldName) { queueMessage([MessageType.PrivateFieldGet, instance.handle, fieldName]); }; ToNative.queueSetMessage = function (instance, propertyName, propertyValue) { // Marshal a NativeObject by sending its handle if (propertyValue instanceof ace.NativeObject) propertyValue = propertyValue.handle; queueMessage([MessageType.Set, instance.handle, propertyName, propertyValue]); }; ToNative.queueFieldSetMessage = function (instance, fieldName, fieldValue) { // Marshal a NativeObject by sending its handle if (fieldValue instanceof ace.NativeObject) fieldValue = fieldValue.handle; queueMessage([MessageType.FieldSet, instance.handle, fieldName, fieldValue]); }; ToNative.queueEventAddMessage = function (instance, eventName) { queueMessage([MessageType.EventAdd, instance.handle, eventName]); }; ToNative.queueEventRemoveMessage = function (instance, eventName) { queueMessage([MessageType.EventRemove, instance.handle, eventName]); }; ToNative.queueNavigateMessage = function (instance) { queueMessage([MessageType.Navigate, instance.handle]); }; ToNative.sendPendingMessages = function (onSuccess, onError) { if (_pendingMessages.length > 0) { // Send all in one batch // onSuccess and onError are only sent in the case of invoking a method (in a "batch" of 1) // in which a return value is requested. exec(onSuccess, ToNative.errorHandler(onError), "NativeHost", "send", _pendingMessages); _pendingMessages = []; } }; ToNative.loadXbf = function (uri, onSuccess, onError) { exec(onSuccess, onError, "NativeHost", "loadXbf", [uri]); }; ToNative.loadPlatformSpecificMarkup = function (uri, onSuccess, onError) { exec(onSuccess, onError, "NativeHost", "loadPlatformSpecificMarkup", [uri]); }; ToNative.isSupported = function (onSuccess, onError) { exec(onSuccess, onError, "NativeHost", "isSupported", []); }; ToNative.navigate = function (root, onSuccess, onError) { exec(onSuccess, onError, "NativeHost", "navigate", [root.handle]); }; ToNative.setPopupsCloseOnHtmlNavigation = function (bool, onSuccess, onError) { exec(onSuccess, onError, "NativeHost", "setPopupsCloseOnHtmlNavigation", [bool]); }; // // Android-specific entry points: // ToNative.getAndroidId = function (name, onSuccess, onError) { exec(onSuccess, onError, "NativeHost", "getAndroidId", [name]); }; ToNative.startAndroidActivity = function (name, onSuccess, onError) { exec(onSuccess, onError, "NativeHost", "startAndroidActivity", [name]); }; module.exports = ToNative;
Microsoft/ace
www/ToNative.js
JavaScript
mit
10,342
import React from 'react'; const mediaEvents = [ 'abort', 'canplay', 'canplaythrough', 'durationchange', 'emptied', 'encrypted', 'ended', 'error', 'interruptbegin', 'interruptend', 'loadeddata', 'loadedmetadata', 'loadstart', 'onencrypted', 'pause', 'play', 'playing', /* 'progress', */ 'ratechange', 'seeked', 'seeking', 'stalled', /* 'suspend', */ 'timeupdate', 'volumechange', 'waiting', ]; const noop = () => {}; export default class Video extends React.Component { static propTypes = { src: React.PropTypes.string.isRequired, // eslint-disable-next-line react/no-unused-prop-types playing: React.PropTypes.bool.isRequired, // eslint-disable-next-line react/no-unused-prop-types position: React.PropTypes.number.isRequired, // eslint-disable-next-line react/forbid-prop-types style: React.PropTypes.object, className: React.PropTypes.string, onTimeUpdate: React.PropTypes.func.isRequired, onLoadedMetadata: React.PropTypes.func.isRequired, onClick: React.PropTypes.func, } static defaultProps = { onTimeUpdate: noop, onLoadedMetadata: noop, position: 0, } componentDidMount() { const video = this.videoNode; for (const mediaEvent of mediaEvents) { video.addEventListener(mediaEvent, this.onMediaEvent, true); } this.updateVideoElement(this.props); } componentWillReceiveProps(nextProps) { this.updateVideoElement(nextProps); } componentWillUnmount() { const video = this.videoNode; for (const mediaEvent of mediaEvents) { video.removeEventListener(mediaEvent, this.onMediaEvent, true); } } onMediaEvent = (event) => { const video = event.target; if (event.type === 'timeupdate') { this.currentVideoPos = video.currentTime; this.props.onTimeUpdate(this.currentVideoPos); } else if (event.type === 'loadedmetadata') { this.props.onLoadedMetadata({ duration: video.duration }); } } currentVideoPos = 0; updateVideoElement(props) { const video = this.videoNode; const { playing, position } = props; if (this.currentVideoPos !== position) { video.currentTime = position; } if (playing && video.paused) { video.play(); } else if (!playing && !video.paused) { video.pause(); } } render() { const { onClick, src, style, className } = this.props; return ( // eslint-disable-next-line jsx-a11y/no-static-element-interactions <video ref={(el) => { this.videoNode = el; }} src={src} onClick={onClick} style={style} className={className} /> ); } }
VirtualClub/vclub
src/components/Video/Video.js
JavaScript
mit
2,652
/** * @author Swagatam Mitra */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, document, console, brackets, $, Mustache */ define(function (require, exports, module) { "use strict"; var AppInit = brackets.getModule("utils/AppInit"); var FileUtils = brackets.getModule("file/FileUtils"); var RuleSetCreator = require("stylemodule/RuleSetCreator"); var RuleSetFinder = require("stylemodule/RuleSetFinder"), Resizer = brackets.getModule("utils/Resizer"); var lastSelectedRuleset = null; var MarkerTemplate = '<div class="keyframemarker intermediatemarker" id="{{id}}" style="left:{{left}};" data-markerat="{{markerat}}"><div class="keyframemarkerdragger"></div><div class="framebubble"><div class="framebubbledragger"></div></div></div>'; var FrameListEntryTemplate = '<li class="intermediatemarker" id="{{id}}">{{marker}}</li>'; var ChangeSetEntryTemplate = "<div id='{{id}}' style='float:left;width:99%;'><span style='float:left;width:40%;margin-top:4px;text-align:right;padding-right:3px;'>{{name}}</span><input class='topcoat-text-input keyframe-changeset-value' style='float:left;width:50% !important' value='{{value}}' data-key='{{name}}'></div>"; var KeyframeOptionTemplate = '<li><a role="menuitem" tabindex="-1" href="#" data-index={{index}}>{{label}}</a></li>'; var intermediateFrameSet = {}; var activeFrame = null; var activeAnim = null; var initialCSSSnapShot = null; var isLoadingDefInProgress = false; var accumulatedDefs = {}; var markersSnapshot = {}; var markersLocalSnapshot = {}; var changeSetLocalSnapshot = {}; var changeSetSnapshot = {}; var elementAnimConfigCache = []; var elementCache = []; var $hLayer1, $hLayer2, $vLayer1, $vLayer2, $xOffsetAxisGrid, $yOffsetAxisGrid; var changeSetProperties = []; var fetchedDefs = null; function _getID(){ var date = new Date(); var components = [ date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds() ]; var id = components.join(""); return "keyframe-"+id; } function _getFrameDef(frame){ var def = ""; for(var key in frame){ if(def){ def = def + ';'; } def = def + key + ":" + frame[key]; } return "{ "+def+" }"; } function _getFrames(nameParam){ var frames = $(".keyframemarker"); var def = ""; var marker = ""; frames.each(function( index ) { marker = $(this).data("markerat"); def = def + marker + _getFrameDef(intermediateFrameSet["entry-"+this.id]); }); return "@-webkit-keyframes "+nameParam+"{ "+def+" }"; } function _findWebkitKeyframeAnimSelector(){ var selectorInfo = []; } $(document).on("change",".keyframe-changeset-value",function(){ var key = $(this).data("key"); intermediateFrameSet[activeFrame][key]= $(this).val(); }); function _defineKeyFrame(nameParam){ var info = RuleSetFinder.findRuleByName(nameParam,true); if(info){ RuleSetCreator.updateRule(info[0],_getFrames(nameParam),info[1]); } else { RuleSetCreator.createNewRule(null,_getFrames(nameParam),0); } } function _playKeyFrame(name){ lastSelectedRuleset.element.offsetHeight = lastSelectedRuleset.element.offsetHeight; $(lastSelectedRuleset.element).css("-webkit-animation", name+" cubic-bezier("+$("#keyframe-timing-fn-value").val()+") "+$("#animation-duration-input").val()+"ms"); //Timeline bar movement $("#current-time-marker")[0].offsetHeight = $("#current-time-marker")[0].offsetHeight; $("#current-time-marker").css("-webkit-animation", "timeline-movement"+" cubic-bezier("+$("#keyframe-timing-fn-value").val()+") "+$("#animation-duration-input").val()+"ms"); } $(document).on("click","#play-keyframe-animation",function(event){ _hideSelection(); _playKeyFrame(activeAnim); window.setTimeout(_showSelection,$("#animation-duration-input").val()); }); function _getAnimConfigText(){ var iteration = $('#animation-infinite-loop:checked').length > 0 ? ' infinite' : ' '+$("#animation-loop-count").val(); return activeAnim +" cubic-bezier("+$("#keyframe-timing-fn-value").val()+") " +$("#animation-duration-input").val()+"ms " +$("#animation-delay-input").val()+"ms " +iteration; } function _fetchAnimConfig(def){ var config = null; var prop; for (prop in def) { if (def.hasOwnProperty(prop)) { config = config ? config +","+def[prop] : def[prop]; } } return config; } $(document).on("click","#play-all-keyframe-animation",function(event){ var index = 0; _hideSelection(); for (index = 0;index < elementCache.length;index++) { if (elementCache[index] && elementAnimConfigCache[index]) { $(elementCache[index]).css("-webkit-animation", _fetchAnimConfig(elementAnimConfigCache[index])); } } }); $(document).on("click","#stop-all-keyframe-animation",function(event){ var index = 0; for (index = 0;index < elementCache.length;index++) { if (elementCache[index]) { $(elementCache[index]).css("-webkit-animation", ""); } } _showSelection(); }); $(document).on("click","#apply-keyframe-animation",function(event){ var index = -1; var existingDef = null; if(lastSelectedRuleset){ index = elementCache.indexOf(lastSelectedRuleset.element); if(index >= 0){ existingDef = elementAnimConfigCache[index]; existingDef[activeAnim] = _getAnimConfigText(); elementAnimConfigCache[index] = existingDef; } else { existingDef = {}; existingDef[activeAnim] = _getAnimConfigText(); elementCache.push(lastSelectedRuleset.element); elementAnimConfigCache.push(existingDef); } } }); function _createNewMarker(leftOffset,markerID){ var marker = $(MarkerTemplate.replace("{{left}}",leftOffset+"px") .replace("{{id}}",_getID().replace("keyframe-","keyframe-"+markerID)) .replace("{{markerat}}",parseInt(markerID)+"%")) .appendTo("#frame-marker-container") .css('height',(parseInt($("#keyframe-timeline-editor").css('height'))-1)+'px'); $(FrameListEntryTemplate.replace("{{marker}}",parseInt(markerID)+"%").replace("{{id}}","entry-"+marker[0].id)).appendTo("#frame-deflist"); intermediateFrameSet["entry-"+marker[0].id] = {}; markersLocalSnapshot["entry-"+marker[0].id] = marker[0].outerHTML; changeSetLocalSnapshot["entry-"+marker[0].id] = $("#entry-"+marker[0].id)[0].outerHTML; $(marker).find(".framebubble").click(); markersSnapshot[activeAnim] = markersLocalSnapshot; changeSetSnapshot[activeAnim] = changeSetLocalSnapshot; } $(document).on("mouseover",".intermediatemarker .framebubble",function(event,rulesetref){ $(".intermediatemarker") .draggable({handle:'.framebubble', containment : '#frame-marker-container', axis: 'x', helper: 'clone', stop: _cloneThisMarker }); }); $(document).on("mouseover",".intermediatemarker .keyframemarkerdragger",function(event,rulesetref){ $(".intermediatemarker") .draggable({handle:'.keyframemarkerdragger', containment : '#frame-marker-container', axis: 'x', drag: function(){ event.stopPropagation(); event.preventDefault(); }, helper: 'none' }); }); $(document).on("ruleset-wrapper.created ruleset-wrapper.refreshed","#html-design-editor",function(event,rulesetref){ var asynchPromise = new $.Deferred(); lastSelectedRuleset = rulesetref; asynchPromise.resolve(); return asynchPromise.promise(); }); $(document).on("deselect.all","#html-design-editor",function(event){ lastSelectedRuleset = null; }); function _captureCSSChanges(event,key,value){ var asynchPromise = new $.Deferred(); var isMarkerReqd = true; if(intermediateFrameSet[activeFrame][key]){ isMarkerReqd = false; } intermediateFrameSet[activeFrame][key]= value; var frameOffset = $("#"+activeFrame.replace("entry-","")).css("left"); if(changeSetProperties.indexOf(key) < 0){ $('<li class="animentry" id="changeset-entry-'+key+'" name="'+activeAnim+'">'+key+'</li>').appendTo("#changeset-entries"); $('<li class="animentry" id="changeset-frame-entry-'+key+'" name="'+activeAnim+'"></li>').appendTo("#changeset-frame-marker"); changeSetProperties.push(key); } if(isMarkerReqd){ $('<div class="changebubble" name="'+activeFrame+'"id="frame-'+key+parseInt(frameOffset)+'" title="'+value+'"><div>').appendTo('#changeset-frame-entry-'+key+'[name="'+activeAnim+'"]').css("left",frameOffset); } else { $('#changeset-frame-entry-'+key+'[name="'+activeAnim+'"]').find('#frame-'+key+parseInt(frameOffset)).attr("title",value); } _showFrameChanges(); asynchPromise.resolve(); return asynchPromise.promise(); } function _showFrameChanges(frameID){ if(!frameID){ frameID = activeFrame; } $("#keyframe-set-entries").html(""); var changeSet = intermediateFrameSet[frameID]; var def = null; if(changeSet){ for(var key in changeSet){ def = changeSet[key]; $(ChangeSetEntryTemplate.split("{{name}}").join(key).split("{{id}}").join("keyframeprop-"+key).split("{{value}}").join(def)).appendTo("#keyframe-set-entries"); } } } function _createNewKeyFrameAnim(retain){ if(lastSelectedRuleset){ initialCSSSnapShot = lastSelectedRuleset.createSavePoint(); } intermediateFrameSet = {}; markersLocalSnapshot = {}; changeSetLocalSnapshot = {}; intermediateFrameSet["entry-keyframe-0"] = {}; intermediateFrameSet["entry-keyframe-100"] = {}; $("#new-keyframe-selector-value").val("anim-"+_getID()); $(".intermediatemarker").remove(); $("#keyframe-set-entries").html(""); changeSetProperties = []; if(!retain){ $("#changeset-entries").html(""); $("#changeset-frame-marker").html(""); accumulatedDefs = {}; markersSnapshot = {}; changeSetSnapshot = {}; elementCache = []; elementAnimConfigCache = []; } } $(document).on("click","#new-keyframe-animation",function(){ _createNewKeyFrameAnim(false); }); $(document).on("click",".framebubble",function(event){ $("#"+"entry-"+$(this).parent()[0].id).click(); event.preventDefault(); event.stopPropagation(); }); $(document).on("dblclick",".intermediatemarker .framebubble",function(event){ var target = "entry-"+$(this).parent()[0].id; $(this).parent().remove(); $(".changebubble[name="+activeFrame+"]").remove(); $("#"+target).prev().click(); delete intermediateFrameSet[target]; $("#"+target).remove(); event.preventDefault(); event.stopPropagation(); }); $(document).on("click","#stop-capture-frame-changes",function(event){ $("#stop-capture-frame-changes").removeClass("blinkingcaptureindicator"); $(".activeframeblink").removeClass("activeframeblink"); activeFrame = null; $("#html-design-editor").off("css-prop-modification css-prop-addition css-prop-removal", _captureCSSChanges); if(lastSelectedRuleset){ lastSelectedRuleset.rollBack(); } }); $(document).on("click","#frame-defset li",function(event){ $("#frame-defset li").removeClass("selected"); $(this).addClass("selected"); $(".activeframeblink").removeClass("activeframeblink"); $("#"+this.id.replace("entry-","")).find(".framebubble").addClass("activeframeblink"); activeFrame = this.id; _showFrameChanges(this.id); if(!isLoadingDefInProgress){ _simulateActiveFrame(); } $("#stop-capture-frame-changes").addClass("blinkingcaptureindicator"); $("#html-design-editor").off("css-prop-modification css-prop-addition css-prop-removal", _captureCSSChanges); $("#html-design-editor").on("css-prop-modification css-prop-addition css-prop-removal", _captureCSSChanges); }); $(document).on("dblclick","#frame-marker-container",function(event){ var x = event.clientX - $(this).offset().left; var frameID = parseInt((x/parseInt($(this).css('width')))*100); _createNewMarker(x,frameID); }); $(document).on("drag",".keyframemarker",function(){ var frameTag = parseInt((parseInt($(this).css('left'))/parseInt($("#frame-marker-container").css('width')))*100)+"%"; $("#entry-"+this.id).html(frameTag); markersLocalSnapshot["#entry-"+this.id] = this.outerHTML; changeSetLocalSnapshot["#entry-"+this.id] = $("#entry-"+this.id)[0].outerHTML; $(this).data("markerat",frameTag); $(".changebubble[name="+"entry-"+this.id+"]").css("left",$(this).css("left")); markersSnapshot[activeAnim] = markersLocalSnapshot; changeSetSnapshot[activeAnim] = changeSetLocalSnapshot; }); $(document).on("stop",".keyframemarker",function(){ var framePrcnt = (parseFloat($(this).css('left'))/parseInt($("#frame-marker-container").css('width')))*100 +"%"; $(".changebubble[name="+"entry-"+this.id+"]").css("left",framePrcnt); $(this).css("left",framePrcnt); }); function _showSelection(){ if(lastSelectedRuleset){ $("#selection-outline").show(); $hLayer1.show(); $hLayer2.show(); $vLayer1.show(); $vLayer2.show(); $xOffsetAxisGrid.show(); $yOffsetAxisGrid.show(); $(lastSelectedRuleset.element).css("-webkit-animation", ""); $("#current-time-marker").css("-webkit-animation", ""); } } function _hideSelection(){ $("#selection-outline").hide(); $hLayer1.hide(); $hLayer2.hide(); $vLayer1.hide(); $vLayer2.hide(); $xOffsetAxisGrid.hide(); $yOffsetAxisGrid.hide(); } $(document).on("input","#animation-duration-input",function(){ var timeTotal = $("#animation-duration-input").val(); var quarterMark = timeTotal/4; $("#quarter-time-mark").html(quarterMark*1+"ms"); $("#half-time-mark").html(quarterMark*2+"ms"); $("#three-quarter-time-mark").html(quarterMark*3+"ms"); }); $(document).on("click","#save-keyframe-animation",function(event){ _defineKeyFrame($("#new-keyframe-selector-value").val()); }); $(document).on("click","#browse-keyframe-animation",function(event){ var defs = RuleSetFinder.findKeyFrameDefinitions(); $("#browse-keyframe-options").html(""); var rule = null; for(var i=0;i<defs.length;i++){ rule = defs[i]; $(KeyframeOptionTemplate.replace("{{index}}",i).replace("{{label}}",rule.name)).appendTo("#browse-keyframe-options"); } $("#browse-keyframe-options-container") .addClass('open') .show(); fetchedDefs = defs; }); function _hideBrowseOptions(){ $("#browse-keyframe-options-container") .removeClass('open') .hide(); } $('html').click(function() { _hideBrowseOptions(); }); function _parseCSSText(cssText) { var returnObj = {}; if (cssText !== "" && cssText !== undefined && cssText.split(' ').join('') !== "{}") { cssText = cssText.replace(/; \}/g, "}") .replace(/ \{ /g, "{\"") .replace(/: /g, "\":\"") .replace(/; /g, "\",\"") .replace(/\}/g, "\"}"); returnObj = JSON.parse(cssText); } if (cssText === " { }") { returnObj = JSON.parse(cssText); } return returnObj; } function _createNewFrameFromDef(rule){ if(rule.keyText === "0%" || rule.keyText === "from"){ $("#entry-keyframe-0").click(); } else if(rule.keyText === "100%" || rule.keyText === "to"){ $("#entry-keyframe-100").click(); } else { var percent = parseInt(rule.keyText); var leftOffset = (percent*parseInt($("#frame-marker-container").css('width')))/100; _createNewMarker(leftOffset,percent); } } function _parseFetchedKeyframeDef(def){ isLoadingDefInProgress = true; var cssRules = def.cssRules; var rule = null; for ( var index = 0;index<cssRules.length;index++){ rule = cssRules[index]; _createNewFrameFromDef(rule); var props = _parseCSSText(' { '+rule.style.cssText+' }'); var prop; for (prop in props) { if (props.hasOwnProperty(prop)) { _captureCSSChanges(null,prop,props[prop]); } } } isLoadingDefInProgress = false; _simulateActiveFrame(); } function _reconstructTimelineForAnim(name){ intermediateFrameSet = accumulatedDefs[name]; markersLocalSnapshot = markersSnapshot[name]; changeSetLocalSnapshot = changeSetSnapshot[name]; $(".intermediatemarker").remove(); var marker; for (marker in markersLocalSnapshot) { if (markersLocalSnapshot.hasOwnProperty(marker)) { $(markersLocalSnapshot[marker]).appendTo("#frame-marker-container") .css('height',(parseInt($("#keyframe-timeline-editor").css('height'))-1)+'px');; } } for (marker in changeSetLocalSnapshot) { if (changeSetLocalSnapshot.hasOwnProperty(marker)) { $(changeSetLocalSnapshot[marker]).appendTo("#frame-deflist"); } } } function _simulateActiveFrame(){ var frameKeys = Object.keys(intermediateFrameSet); frameKeys.sort(); var currentFrameIndex = frameKeys.indexOf(activeFrame); var differentialCSS = {}; for(var index = 0;index<= currentFrameIndex;index++){ $.extend(differentialCSS,intermediateFrameSet[frameKeys[index]]); } var key; if(lastSelectedRuleset){ _hideSelection(); $("#html-design-editor").off("css-prop-modification css-prop-addition css-prop-removal", _captureCSSChanges); lastSelectedRuleset.rollBack(); for (key in differentialCSS) { if (differentialCSS.hasOwnProperty(key)) { lastSelectedRuleset.css(key,differentialCSS[key]); } } $("#html-design-editor").on("css-prop-modification css-prop-addition css-prop-removal", _captureCSSChanges); window.setTimeout(function(){ //To force CSS reflow $("#html-design-editor").trigger("refresh.element.selection"); },2); _showSelection(); } } $(document).on("click","#browse-keyframe-options li a",function(event){ var index = $(this).data('index'); var keyFrameDef = fetchedDefs[index]; activeAnim = keyFrameDef.name; $("#keyframe-selector-value").val(keyFrameDef.name); _createNewKeyFrameAnim(true); _hideInactiveAnimEntries(); $('<li class="animheader" id="anim-'+activeAnim+'" style="background:#2d2e30;">'+activeAnim+'{}</li>').appendTo("#changeset-entries"); $('<li class="animheader" id="anim-'+activeAnim+'" style="background:#2d2e30;padding-left:10px !important;">'+activeAnim+'{}</li>').appendTo("#changeset-frame-marker"); $("#new-keyframe-selector-value").val(keyFrameDef.name); _hideBrowseOptions(); _parseFetchedKeyframeDef(keyFrameDef); if(activeAnim){ accumulatedDefs[activeAnim] = intermediateFrameSet; markersSnapshot[activeAnim] = markersLocalSnapshot; changeSetSnapshot[activeAnim] = changeSetLocalSnapshot; } event.preventDefault(); event.stopPropagation(); }); function _showActiveAnimEntries(){ $("#changeset-entries li[name="+activeAnim+"]").show(); $("#changeset-frame-marker li[name="+activeAnim+"]").show(); _reconstructTimelineForAnim(activeAnim); } function _hideInactiveAnimEntries(){ $("#changeset-entries li.animentry[name!="+activeAnim+"]").hide(); $("#changeset-frame-marker li.animentry[name!="+activeAnim+"]").hide(); } $(document).on("click","#changeset-entries li.animheader",function(event){ var selectedEntry = $("#changeset-entries li.animheader.selected"); $("#changeset-entries li.animheader.selected").removeClass("selected"); $("#changeset-frame-marker li.animheader.selected").removeClass("selected"); $(this).addClass("selected"); $("#changeset-frame-marker li#"+this.id).addClass("selected"); activeAnim = this.id.replace("anim-",""); _hideInactiveAnimEntries(); _showActiveAnimEntries(); }); function _cloneThisMarker(event,ui){ var x = event.clientX - $("#frame-marker-container").offset().left; var frameID = parseInt((x/parseInt($("#frame-marker-container").css('width')))*100); _createNewMarker(x,frameID); var props = intermediateFrameSet["entry-"+event.target.id]; var prop; if(props){ isLoadingDefInProgress = true; for (prop in props) { if (props.hasOwnProperty(prop)) { _captureCSSChanges(null,prop,props[prop]); } } isLoadingDefInProgress = false; _simulateActiveFrame(); } markersSnapshot[activeAnim] = markersLocalSnapshot; accumulatedDefs[activeAnim] = intermediateFrameSet; changeSetSnapshot[activeAnim] = changeSetLocalSnapshot; } AppInit.appReady(function () { $("#current-time-marker") .draggable({handle:'.timedragger', containment : '#timeline-footer', axis: 'x' }); $(".keyframemarker") .draggable({handle:'.framebubble', containment : '#frame-marker-container', axis: 'x', helper: 'clone', stop: _cloneThisMarker }); Resizer.makeResizable($("#keyframe-timeline-editor")[0], Resizer.DIRECTION_VERTICAL, Resizer.POSITION_BOTTOM, 200, false, undefined, false); $("#keyframe-timeline-editor").on("panelResizeUpdate", function () { var asynchPromise = new $.Deferred(); $(".keyframemarker").css('height',(parseInt($("#keyframe-timeline-editor").css('height'))-1)+'px'); $("#current-time-marker").css('height',(parseInt($("#keyframe-timeline-editor").css('height'))-19)+'px'); asynchPromise.resolve(); return asynchPromise.promise(); }); $("#changeset-entries").on("scroll", function(){ $("#changeset-frame-marker").scrollTop($("#changeset-entries").scrollTop()); }); $hLayer1 = $("#h-layer1"); $hLayer2 = $("#h-layer2"); $vLayer1 = $("#v-layer1"); $vLayer2 = $("#v-layer2"); $xOffsetAxisGrid = $(".offsetHAxis"); $yOffsetAxisGrid = $(".offsetVAxis"); }); });
swmitra/html-designer
propertysheet/KeyframeTimelineToolboxHandler.js
JavaScript
mit
25,158
var express = require('express'), app = express(), model = require('./model'); app.get('/api/one/:timestamp/:range?', function (req, res) { if(req.params.timestamp === 'latest') { model.getLatestEntryPromise(req.params.timestamp) .then(function (data) { res.send(data); }); } else { model.getSinglePromise(req.params.timestamp) .then(function (data) { res.send(data); }); } }); app.get('/api/minmax/:timestampStart/:timestampEnd', function (req, res) { model.getMinMaxPromise(req.params.timestampStart, req.params.timestampEnd) .then(function (data) { res.send(data); }); }); app.get('/api/:timestamp/:range?', function (req, res) { if(req.params.range) { model.getAllInRangePromise(req.params.timestamp, req.params.range) .then(function (data) { res.send(data); }); } else { model.getSincePromise(req.params.timestamp) .then(function (data) { res.send(data); }); } }); app.use(express.static('htdocs')); var server = app.listen(8081, 'localhost', function () { var host = server.address().address; var port = server.address().port; console.log('Weather app listening at http://%s:%s', host, port); });
hamsterbacke23/frontend-boilerplate
app/api.js
JavaScript
mit
1,253
it('should fail', () => expect(1 + 4).toEqual(3));
Dakuan/gulp-jest
fixture-fail/index-test.js
JavaScript
mit
51
// Our fake people db var people = { '1': { name: 'Cameron', likes: ['music', 'bikes', 'cars', 'code'], followers: ['2', '3'] }, '2': { name: 'Scott', likes: ['cats', 'dogs', 'houses'] }, '3': { name: 'Dave', likes: ['cars', 'bikes'] } }; var api = {}; api.get = function(id, cb) { setTimeout(function() { cb(null, people[id]); }, Math.floor(Math.random() + 10)); // Simulate DB call }; api.likes = function(id, cb) { setTimeout(function() { cb(null, people[id].likes); }, Math.floor(Math.random() + 10)); // Simulate DB call }; api.followers = function(id, cb) { setTimeout(function() { cb(null, people[id].followers); }, Math.floor(Math.random() + 10)); // Simulate DB call }; module.exports = function(jsont) { jsont.use('user-likes', function(user, next) { if (typeof user !== 'object') user = {id: user}; api.likes(user.id, function(err, likes) { if (err) return next(err); user.likes = likes; next(null, user); }); }); jsont.use('user-followers', function(id, next) { api.followers(id, next); }); jsont.use('user', function(id, next) { api.get(id, function(err, user) { if (err) return next(err); user.id = id; next(null, user); }); }); jsont.use('length', function(user, property, position, next) { if (typeof position === 'function') return position(null, user[property].length); user[position] = user[property].length; next(null, user); }); return jsont; };
camshaft/jsont
test/cases/parallelization/index.js
JavaScript
mit
1,534
var dgram = require('dgram'), inherits = require('util').inherits, net = require('net'), uuid = require('uuid'), Base = require('./Base'), addrs = require('../Misc/addresses'), msgs = require('../Misc/messages'), TCPWrapper = require('../Misc/TCPWrapper'); // ---------------- // Server class // ---------------- // This server class contains information about // groups (for example: name) function Server(chan) { Base.call(this, chan); var self = this; this._server = net.createServer(); this._server.listen(chan.port); this._server.on('connection', function(sock) { self._connectionHandler(sock); }); // The data for the groups (name, connected clients, etc) this._groups = {}; // The groups a client is connected to this._sock_groups = {}; } inherits(Server, Base); // ---------------- // Server advertisement // @override Server.prototype._messageHandler = function(message, remote) { console.log('Server received UDP message...'); var sender_chan = new addrs.Channel(remote.address, remote.port); var data = JSON.parse(message); switch(data.type) { case msgs.types.SERVER_SOLICITATION: var message = new msgs.Message( msgs.types.SERVER_ADVERTISEMENT, this.getProfile(), this._server.address() ); this.sendUDP(sender_chan, message.toString()); } } // ---------------- // Server group handling // function _joinGroup // @param sock_uuid the socket uuid that wants to join the group // @param group_uuid the group to join // @returns true if the join was successful // false otherwise Server.prototype._joinGroup = function(sock_uuid, client_uuid, group_uuid) { // check if group exists if (this._groups[group_uuid]) { // Creates new sock group object if (!this._sock_groups[sock_uuid]) { this._sock_groups[sock_uuid] = {}; } // Does the client already joined the group? if (!this._sock_groups[sock_uuid][group_uuid]) { this._groups[group_uuid].members[sock_uuid] = client_uuid; // Joins the group this._sock_groups[sock_uuid][group_uuid] = true; } return true; } return false; } // function _leaveGroup // @param sock_uuid the sock that wishes to leave the group // @param group_uuid the group that the socket wants to leave (heh) // @returns true on success // false otherwise (probably the group doesn't exists if false // is returned) Server.prototype._leaveGroup = function(sock_uuid, group_uuid) { if (this._groups[group_uuid] && this._sock_groups[sock_uuid]) { if (this._sock_groups[sock_uuid][group_uuid]) { // Deletes group association delete this._groups[group_uuid].members[sock_uuid]; delete this._sock_groups[sock_uuid][group_uuid]; if (Object.keys(this._groups[group_uuid].members).length <= 0) delete this._groups[group_uuid]; return true; } } return false; } // function _getRawGroups // @returns an array of RawChannels Server.prototype._getRawGroups = function() { var array = []; for (key in this._groups) { array.push(this._groups[key].channel); } return array; } Server.prototype._connectionHandler = function(sock) { var self = this; // Unique reference to this socket var sock_uuid = uuid.v1(); console.log('> Socket "' + sock_uuid + '" connected...'); // Handling of data var tcp_wrapper = new TCPWrapper(sock); tcp_wrapper.on('message', function(message) { self._tcpMessageHandler(sock, sock_uuid, message); }); // Handling events sock.on('end', function() { sock.end(); }); sock.on('error', function(err) { console.log('> Socket "' + sock_uuid + '" error:'); console.log(err) }); sock.on('close', function(data) { console.log('> Socket "' + sock_uuid + '" disconnected...'); self._closeHandler(sock, sock_uuid, data); }); } Server.prototype._tcpMessageHandler = function(sock, sock_uuid, data) { console.log('> Server received TCP message...'); var self = this; data = JSON.parse(data.toString()); // Handle type switch(data.type) { case msgs.types.GROUP_CREATE: // Group creation // generates group multicast address var new_group_channel = addrs.getMulticast(this._getRawGroups()); var group_profile = { uuid: uuid.v1(), name: data.extras.name, created_by: data.sender.uuid, creation_date: Date.now(), members: {}, channel: new_group_channel } this._groups[group_profile.uuid] = group_profile; // Joins the group this._joinGroup(sock_uuid, data.sender.uuid, group_profile.uuid); // GROUP_CREATE_OK message var message = new msgs.Message( msgs.types.GROUP_CREATE_OK, this.getProfile(), group_profile ); sock.write(message.toString()); console.log('> Client: ' + data.sender.uuid); console.log(' Created group: ' + data.extras.name); break; case msgs.types.GROUP_JOIN: var joined = this._joinGroup(sock_uuid, data.sender.uuid, data.extras.uuid); if (joined) { // Send GROUP_JOIN_OK var message = new msgs.Message( msgs.types.GROUP_JOIN_OK, this.getProfile(), this._groups[data.extras.uuid] ); sock.write(message.toString()); console.log('> Client: ' + data.sender.uuid); console.log(' Joined group: ' + this._groups[data.extras.uuid].name); } else { // Send GROUP_JOIN_ERR var message = new msgs.Message( msgs.types.GROUP_JOIN_ERR, "Group with ID " + data.extras.uuid + " doesn't exists!" ); sock.write(message.toString()); } break; case msgs.types.GROUP_LEAVE: // Group leave logic var group_profile = this._groups[data.extras.uuid]; var left = this._leaveGroup(sock_uuid, data.extras.uuid); if (left) { var message = new msgs.Message( msgs.types.GROUP_LEAVE_OK, this.getProfile(), group_profile ); sock.write(message.toString()); console.log('> Client: ' + data.sender.uuid); console.log(' Left group: ' + group_profile.name); } else { var message = new msgs.Message( msgs.types.GROUP_LEAVE_ERR, 'Unable to leave the group (group doesn\'t exists?)' ); sock.write(message.toString()); } break; // ---------------- // Group solicitation & advertisement case msgs.types.GROUP_SOLICITATION: var message = new msgs.Message( msgs.types.GROUP_ADVERTISEMENT, this.getProfile(), this._groups ); sock.write(message.toString()); break; } // switch } // _tcpMessageHandler Server.prototype._closeHandler = function(sock, sock_uuid, data) { // Socket leaves all the groups he joined if (this._sock_groups[sock_uuid]) { for (group_uuid in this._sock_groups[sock_uuid]) { this._leaveGroup(sock_uuid, group_uuid); } } delete this._sock_groups[sock_uuid]; } // ---------------- // Exports // ---------------- module.exports = Server
DanielRS/node-chatty
lib/Agents/Server.js
JavaScript
mit
6,760
exports.models = { "Class": { "id": "Class", "description": "A javascript class template defined by a user", "required": ['name', 'author'], "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "author": { "type": "User" }, "description": { "type": "string" }, "properties": { "type": "array", "items": { "type": "string" } }, "methods": { "type": "array", "items": { "$ref": "Method" }, "description": "Methods defined as members of this class" }, "inherits": { "type": "Class" }, } }, "Mehtod": { "id": "Method", "required": ['name'], "properties": { "name": { "type": "string" }, "body": { "type": "string" }, "params": { "type": "array", "items": { "type": "string" } } } }, "User": { "id": "User", "required": ['name', 'email', 'username', 'password'], "properties": { "name": { "type": "string" }, "email": { "type": "string" }, "username": { "type": "string" }, "provider": { "type": "string" }, "password": { "type": "string" } } } }
tenevdev/goop-api
swagger/models/index.js
JavaScript
mit
1,412
class DefaultController { constructor() { let vm = this; let [year = 1995, rating = 78] = []; // jshint ignore:line vm.firstMovie = movie('Braveheart', 3, year, rating); vm.secondMovie = movie('Ant-Man', 2, undefined, 79); } } function movie (title, length, year = 2015, rating = 0) { return `${title} was ${length} hours long. It came out in ${year} and had a rating of ${rating}.`; } export default DefaultController;
allensb/Angular-ES6
app/components/default/default-controller.js
JavaScript
mit
480
import { deprecateV3 } from './util' export function parseRemote(remote) { if (remote && remote.host) return remote if (typeof remote !== 'string') throw new Error('A remote must be a string') if (remote === '') throw new Error('A remote cannot be an empty string') const matches = remote.match(/(([^@:]+)@)?([^@:]+)(:(.+))?/) if (matches) { const [, , user, host, , port] = matches const options = { user, host } if (port) options.port = Number(port) if (!user) { deprecateV3( 'Default user "deploy" is deprecated, please specify it explictly.', ) options.user = 'deploy' } return options } return { user: 'deploy', host: remote } } export function formatRemote({ user, host }) { return `${user}@${host}` }
shipitjs/ssh-pool
src/remote.js
JavaScript
mit
779
/** * Created by Didi on 2014/10/16. */ $(document).ready(function(){ $('.form').each(function(){ $(this).find('.file').attr("tabIndex", "0");//使得form中的span具有tab属 }); /*使input-info正方形*/ $('.input-info').each(function(){ var height = $(this).parent('.input-group') .children('input').height(); $(this).css({"width":(height)+"px"}); }); /*使得disabled可用*/ $('input[type="radio"]').each(function(){ if($(this).attr('disabled')){ var radioid=$(this).attr('id'); $(this).wrap('<div class="radio-input" disabled="disabled"></div>'); $(this).after('<label for='+radioid+' disabled="disabled"></label>'); }else{ var radioid1=$(this).attr('id'); $(this).wrap('<div class="radio-input"></div>'); $(this).after('<label for='+radioid1+'></label>'); } }); $('input[type="checkbox"]').each(function(){ if($(this).attr('disabled')){ var checkboxid=$(this).attr('id'); $(this).wrap('<div class="checkbox-input" disabled="disabled"></div>'); $(this).after('<label for='+checkboxid+' disabled="disabled"></label>'); }else { var checkboxid1 = $(this).attr('id'); $(this).wrap('<div class="checkbox-input"></div>'); $(this).after('<label for=' + checkboxid1 + '></label>'); } }); $(function () {//按钮样式的Checkbox、Radio $('input[type="checkbox"]:checked').each(function (){ $(this).parent('.checkbox-input').parent('.btn').addClass('active'); }); $('input[type="checkbox"]:not(:checked)').each(function (){ $(this).parent('.checkbox-input').parent('.btn').removeClass('active'); }); $('input[type="checkbox"]').click(function () { $('input[type="checkbox"]:checked').each(function (){ $(this).parent('.checkbox-input').parent('.btn').addClass('active'); }); $('input[type="checkbox"]:not(:checked)').each(function (){ $(this).parent('.checkbox-input').parent('.btn').removeClass('active'); }) }); $('input[type="radio"]:checked').each(function (){ $(this).parent('.radio-input').parent('.btn').addClass('active'); }); $('input[type="radio"]:not(:checked)').each(function (){ $(this).parent('.radio-input').parent('.btn').removeClass('active'); }); $('input[type="radio"]').click(function () { $('input[type="radio"]:checked').each(function (){ $(this).parent('.radio-input').parent('.btn').addClass('active'); }); $('input[type="radio"]:not(:checked)').each(function (){ $(this).parent('.radio-input').parent('.btn').removeClass('active'); }) }); }); });
Didichaoren/Didichaoren.github.io
javascript/forms.js
JavaScript
mit
2,947
const should = require('should'), sinon = require('sinon'), testUtils = require('../../utils'), urlService = require('../../../frontend/services/url'), models = require('../../../server/models'), helpers = require('../../../frontend/helpers'); describe('{{tags}} helper', function () { before(function () { models.init(); }); beforeEach(function () { sinon.stub(urlService, 'getUrlByResourceId'); }); afterEach(function () { sinon.restore(); }); it('can return string with tags', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'foo'}), testUtils.DataGenerator.forKnex.createTag({name: 'bar'}) ]; const rendered = helpers.tags.call({tags: tags}, {hash: {autolink: 'false'}}); should.exist(rendered); String(rendered).should.equal('foo, bar'); }); it('can use a different separator', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'haunted'}), testUtils.DataGenerator.forKnex.createTag({name: 'ghost'}) ]; const rendered = helpers.tags.call({tags: tags}, {hash: {separator: '|', autolink: 'false'}}); should.exist(rendered); String(rendered).should.equal('haunted|ghost'); }); it('can add a single prefix to multiple tags', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'haunted'}), testUtils.DataGenerator.forKnex.createTag({name: 'ghost'}) ]; const rendered = helpers.tags.call({tags: tags}, {hash: {prefix: 'on ', autolink: 'false'}}); should.exist(rendered); String(rendered).should.equal('on haunted, ghost'); }); it('can add a single suffix to multiple tags', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'haunted'}), testUtils.DataGenerator.forKnex.createTag({name: 'ghost'}) ]; const rendered = helpers.tags.call({tags: tags}, {hash: {suffix: ' forever', autolink: 'false'}}); should.exist(rendered); String(rendered).should.equal('haunted, ghost forever'); }); it('can add a prefix and suffix to multiple tags', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'haunted'}), testUtils.DataGenerator.forKnex.createTag({name: 'ghost'}) ]; const rendered = helpers.tags.call({tags: tags}, {hash: {suffix: ' forever', prefix: 'on ', autolink: 'false'}}); should.exist(rendered); String(rendered).should.equal('on haunted, ghost forever'); }); it('can add a prefix and suffix with HTML', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'haunted'}), testUtils.DataGenerator.forKnex.createTag({name: 'ghost'}) ]; const rendered = helpers.tags.call({tags: tags}, {hash: {suffix: ' &bull;', prefix: '&hellip; ', autolink: 'false'}}); should.exist(rendered); String(rendered).should.equal('&hellip; haunted, ghost &bull;'); }); it('does not add prefix or suffix if no tags exist', function () { const rendered = helpers.tags.call({}, {hash: {prefix: 'on ', suffix: ' forever', autolink: 'false'}}); should.exist(rendered); String(rendered).should.equal(''); }); it('can autolink tags to tag pages', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'foo', slug: 'foo-bar'}), testUtils.DataGenerator.forKnex.createTag({name: 'bar', slug: 'bar'}) ]; urlService.getUrlByResourceId.withArgs(tags[0].id).returns('tag url 1'); urlService.getUrlByResourceId.withArgs(tags[1].id).returns('tag url 2'); const rendered = helpers.tags.call({tags: tags}); should.exist(rendered); String(rendered).should.equal('<a href="tag url 1">foo</a>, <a href="tag url 2">bar</a>'); }); it('can limit no. tags output to 1', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'foo', slug: 'foo-bar'}), testUtils.DataGenerator.forKnex.createTag({name: 'bar', slug: 'bar'}) ]; urlService.getUrlByResourceId.withArgs(tags[0].id).returns('tag url 1'); const rendered = helpers.tags.call({tags: tags}, {hash: {limit: '1'}}); should.exist(rendered); String(rendered).should.equal('<a href="tag url 1">foo</a>'); }); it('can list tags from a specified no.', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'foo', slug: 'foo-bar'}), testUtils.DataGenerator.forKnex.createTag({name: 'bar', slug: 'bar'}) ]; urlService.getUrlByResourceId.withArgs(tags[1].id).returns('tag url 2'); const rendered = helpers.tags.call({tags: tags}, {hash: {from: '2'}}); should.exist(rendered); String(rendered).should.equal('<a href="tag url 2">bar</a>'); }); it('can list tags to a specified no.', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'foo', slug: 'foo-bar'}), testUtils.DataGenerator.forKnex.createTag({name: 'bar', slug: 'bar'}) ]; urlService.getUrlByResourceId.withArgs(tags[0].id).returns('tag url x'); const rendered = helpers.tags.call({tags: tags}, {hash: {to: '1'}}); should.exist(rendered); String(rendered).should.equal('<a href="tag url x">foo</a>'); }); it('can list tags in a range', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'foo', slug: 'foo-bar'}), testUtils.DataGenerator.forKnex.createTag({name: 'bar', slug: 'bar'}), testUtils.DataGenerator.forKnex.createTag({name: 'baz', slug: 'baz'}) ]; urlService.getUrlByResourceId.withArgs(tags[1].id).returns('tag url b'); urlService.getUrlByResourceId.withArgs(tags[2].id).returns('tag url c'); const rendered = helpers.tags.call({tags: tags}, {hash: {from: '2', to: '3'}}); should.exist(rendered); String(rendered).should.equal('<a href="tag url b">bar</a>, <a href="tag url c">baz</a>'); }); it('can limit no. tags and output from 2', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'foo', slug: 'foo-bar'}), testUtils.DataGenerator.forKnex.createTag({name: 'bar', slug: 'bar'}), testUtils.DataGenerator.forKnex.createTag({name: 'baz', slug: 'baz'}) ]; urlService.getUrlByResourceId.withArgs(tags[1].id).returns('tag url b'); const rendered = helpers.tags.call({tags: tags}, {hash: {from: '2', limit: '1'}}); should.exist(rendered); String(rendered).should.equal('<a href="tag url b">bar</a>'); }); it('can list tags in a range (ignore limit)', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'foo', slug: 'foo-bar'}), testUtils.DataGenerator.forKnex.createTag({name: 'bar', slug: 'bar'}), testUtils.DataGenerator.forKnex.createTag({name: 'baz', slug: 'baz'}) ]; urlService.getUrlByResourceId.withArgs(tags[0].id).returns('tag url a'); urlService.getUrlByResourceId.withArgs(tags[1].id).returns('tag url b'); urlService.getUrlByResourceId.withArgs(tags[2].id).returns('tag url c'); const rendered = helpers.tags.call({tags: tags}, {hash: {from: '1', to: '3', limit: '2'}}); should.exist(rendered); String(rendered).should.equal('<a href="tag url a">foo</a>, <a href="tag url b">bar</a>, <a href="tag url c">baz</a>'); }); describe('Internal tags', function () { const tags = [ testUtils.DataGenerator.forKnex.createTag({name: 'foo', slug: 'foo-bar'}), testUtils.DataGenerator.forKnex.createTag({name: '#bar', slug: 'hash-bar', visibility: 'internal'}), testUtils.DataGenerator.forKnex.createTag({name: 'bar', slug: 'bar'}), testUtils.DataGenerator.forKnex.createTag({name: 'baz', slug: 'baz'}), testUtils.DataGenerator.forKnex.createTag({name: 'buzz', slug: 'buzz'}) ]; const tags1 = [ testUtils.DataGenerator.forKnex.createTag({name: '#foo', slug: 'hash-foo-bar', visibility: 'internal'}), testUtils.DataGenerator.forKnex.createTag({name: '#bar', slug: 'hash-bar', visibility: 'internal'}) ]; beforeEach(function () { urlService.getUrlByResourceId.withArgs(tags[0].id).returns('1'); urlService.getUrlByResourceId.withArgs(tags[1].id).returns('2'); urlService.getUrlByResourceId.withArgs(tags[2].id).returns('3'); urlService.getUrlByResourceId.withArgs(tags[3].id).returns('4'); urlService.getUrlByResourceId.withArgs(tags[4].id).returns('5'); }); it('will not output internal tags by default', function () { const rendered = helpers.tags.call({tags: tags}); String(rendered).should.equal( '<a href="1">foo</a>, ' + '<a href="3">bar</a>, ' + '<a href="4">baz</a>, ' + '<a href="5">buzz</a>' ); }); it('should still correctly apply from & limit tags', function () { const rendered = helpers.tags.call({tags: tags}, {hash: {from: '2', limit: '2'}}); String(rendered).should.equal( '<a href="3">bar</a>, ' + '<a href="4">baz</a>' ); }); it('should output all tags with visibility="all"', function () { const rendered = helpers.tags.call({tags: tags}, {hash: {visibility: 'all'}}); String(rendered).should.equal( '<a href="1">foo</a>, ' + '<a href="2">#bar</a>, ' + '<a href="3">bar</a>, ' + '<a href="4">baz</a>, ' + '<a href="5">buzz</a>' ); }); it('should output all tags with visibility property set with visibility="public,internal"', function () { const rendered = helpers.tags.call({tags: tags}, {hash: {visibility: 'public,internal'}}); should.exist(rendered); String(rendered).should.equal( '<a href="1">foo</a>, ' + '<a href="2">#bar</a>, ' + '<a href="3">bar</a>, ' + '<a href="4">baz</a>, ' + '<a href="5">buzz</a>' ); }); it('Should output only internal tags with visibility="internal"', function () { const rendered = helpers.tags.call({tags: tags}, {hash: {visibility: 'internal'}}); should.exist(rendered); String(rendered).should.equal('<a href="2">#bar</a>'); }); it('should output nothing if all tags are internal', function () { const rendered = helpers.tags.call({tags: tags1}, {hash: {prefix: 'stuff'}}); should.exist(rendered); String(rendered).should.equal(''); }); }); });
kevinansfield/Ghost
core/test/unit/helpers/tags_spec.js
JavaScript
mit
11,414
// Karma configuration // Generated on Thu May 12 2016 14:37:52 GMT-0700 (PDT) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'test/bundle.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }) }
fit-cliques/fit_cliques
karma.conf.js
JavaScript
mit
1,673
(function () { 'use strict'; describe('Characters List Controller Tests', function () { // Initialize global variables var CharactersListController, $scope, $httpBackend, $state, Authentication, CharactersService, mockCharacter; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function () { jasmine.addMatchers({ toEqualData: function (util, customEqualityTesters) { return { compare: function (actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _CharactersService_) { // Set a new global scope $scope = $rootScope.$new(); // Point global variables to injected services $httpBackend = _$httpBackend_; $state = _$state_; Authentication = _Authentication_; CharactersService = _CharactersService_; // create mock article mockCharacter = new CharactersService({ _id: '525a8422f6d0f87f0e407a33', name: 'Character Name' }); // Mock logged in user Authentication.user = { roles: ['user'] }; // Initialize the Characters List controller. CharactersListController = $controller('CharactersListController as vm', { $scope: $scope }); //Spy on state go spyOn($state, 'go'); })); describe('Instantiate', function () { var mockCharacterList; beforeEach(function () { mockCharacterList = [mockCharacter, mockCharacter]; }); it('should send a GET request and return all Characters', inject(function (CharactersService) { // Set POST response $httpBackend.expectGET('api/characters').respond(mockCharacterList); $httpBackend.flush(); // Test form inputs are reset expect($scope.vm.characters.length).toEqual(2); expect($scope.vm.characters[0]).toEqual(mockCharacter); expect($scope.vm.characters[1]).toEqual(mockCharacter); })); }); }); })();
etkirsch/tolmea
modules/characters/tests/client/list-characters.client.controller.tests.js
JavaScript
mit
2,960
describe('Service: bulletUtils', function() { 'use strict'; beforeEach(module('bullet')); var bulletsMock, utils; beforeEach(inject(function(bulletUtils, bulletFactory) { utils = bulletUtils; bulletsMock = [ bulletFactory.newBullet([0], 'Developing with AngularJS', true, true, [bulletFactory.newBullet([0, 0], 'foo', false, false, [bulletFactory.newBullet([0,0,0], 'foo000')]), bulletFactory.newBullet([0, 1], 'foo2')]), bulletFactory.newBullet([1],'Add a shortcut to clean all complete tasks', false, false), bulletFactory.newBullet([2],'Add sub tasks', false, false), bulletFactory.newBullet([3],'Add localestorage for saving tasks', false, false), bulletFactory.newBullet([4],'Add the possibility to navigate through tasks', false, false), bulletFactory.newBullet([5],'Add breadcrumb', false, false) ]; })); describe(', when testing an array,', function() { it('should return the object utils if the parameter is an array', function() { expect(utils.checkArray([0, 1])).toEqual(utils); }); it('should throw an error if the parameter is undefined', function() { expect(function() {utils.checkArray();}).toThrow(new Error('undefined is not an array!')); }); it('should throw an error if the parameter is not an array', function() { var obj = {name: 'foobar'}; expect(function() {utils.checkArray(obj);}).toThrow(new Error(obj + ' is not an array!')); }); }); describe(', when testing a number,', function() { it('should return the object utils if the parameter is a number', function() { expect(utils.checkNumber(123)).toEqual(utils); }); it('should throw an error if the parameter is undefined', function() { expect(function() {utils.checkNumber();}).toThrow(new Error('undefined is not a number!')); }); it('should throw an error if the parameter is not a number', function() { var obj = {name: 'foobar'}; expect(function() {utils.checkNumber(obj);}).toThrow(new Error(obj + ' is not a number!')); }); }); it('should fetch the item 0 from a given list of bullets and index 0', function() { var bulletsArray = utils.findBulletsArray(bulletsMock, [0]), bullet = utils.findBullet(bulletsMock, [0]), bulletMock = bulletsMock[0]; expect(bulletsArray).toBeDefined(); expect(bullet.text).toEqual(bulletMock.text); expect(bullet.index).toEqual(bulletMock.index); expect(bullet.focus).toEqual(bulletMock.focus); expect(bullet.complete).toEqual(bulletMock.complete); }); it('should fetch the item 3 from a given list of bullets and index 3', function() { var bulletsArray = utils.findBulletsArray(bulletsMock, [3]), bullet = utils.findBullet(bulletsMock, [3]), bulletMock = bulletsMock[3]; expect(bulletsArray).toBeDefined(); expect(bullet.text).toEqual(bulletMock.text); expect(bullet.index).toEqual(bulletMock.index); expect(bullet.focus).toEqual(bulletMock.focus); expect(bullet.complete).toEqual(bulletMock.complete); }); it('should fetch the item 0-1 from a given list of bullets and index 0-0', function() { var bulletsArray = utils.findBulletsArray(bulletsMock, [0, 0]), bullet = utils.findBullet(bulletsMock, [0, 0]), bulletMock = bulletsMock[0].bullets[0]; expect(bulletsArray).toBeDefined(); expect(bullet.text).toEqual(bulletMock.text); expect(bullet.index).toEqual(bulletMock.index); expect(bullet.focus).toEqual(bulletMock.focus); expect(bullet.complete).toEqual(bulletMock.complete); }); it('should fetch the item 0-1 from a given list of bullets and index 0-1', function() { var bulletsArray = utils.findBulletsArray(bulletsMock, [0, 1]), firstBulletsArray = bulletsArray[0], bullet = utils.findBullet(bulletsMock, [0, 1]), firstBulletMock = bulletsMock[0].bullets[0], bulletMock = bulletsMock[0].bullets[1]; expect(bulletsArray).toBeDefined(); expect(firstBulletsArray.text).toEqual(firstBulletMock.text); expect(firstBulletsArray.index).toEqual(firstBulletMock.index); expect(firstBulletsArray.focus).toEqual(firstBulletMock.focus); expect(firstBulletsArray.complete).toEqual(firstBulletMock.complete); expect(bullet.text).toEqual(bulletMock.text); expect(bullet.index).toEqual(bulletMock.index); expect(bullet.focus).toEqual(bulletMock.focus); expect(bullet.complete).toEqual(bulletMock.complete); }); it('should fetch the item 0-0-0 from a given list of bullets and index 0-0-0', function() { var bulletsArray = utils.findBulletsArray(bulletsMock, [0, 0, 0]), bullet = utils.findBullet(bulletsMock, [0, 0, 0]), bulletMock = bulletsMock[0].bullets[0].bullets[0]; expect(bulletsArray).toBeDefined(); expect(bullet.text).toEqual(bulletMock.text); expect(bullet.index).toEqual(bulletMock.index); expect(bullet.focus).toEqual(bulletMock.focus); expect(bullet.complete).toEqual(bulletMock.complete); }); it('should throw an error if the bullet is not found from a given index', function() { expect(function() {utils.findBullet(bulletsMock, [0, 10]);}).toThrow(new Error('Bullet not found for indexes ' + [0, 10])); }); });
l-lin/bulletular
src/app/bullet/test/bulletUtils.spec.js
JavaScript
mit
5,693
import SimpleSchema from 'simpl-schema'; import { Mongo } from 'meteor/mongo'; /** * @summary Providers namespace * @namespace */ const Providers = {}; /** * @summary SASPs and Counties Collections * @type {Mongo.Collection} */ Providers.collection = new Mongo.Collection('providers'); Providers.counties = new Mongo.Collection('counties'); // Create custom validation messages SimpleSchema.setDefaultMessages({ messages: { en: { invalidLatitude: 'Latitude must be between 42.5 and 47.083', invalidLongitude: 'Longitude must be between -86.767 and -92.883', }, }, }); /** * @summary Providers Schema * @type {SimpleSchema} */ Providers.schema = new SimpleSchema({ /** ID */ _id: { type: String, optional: true, // ID is autogenerated }, /** Provider name */ name: { type: String, optional: false, }, /** Counties Covered by this Provider */ counties: { type: Array, defaultValue: [], optional: false, label: 'Counties Served by Provider', }, 'counties.$': { type: String, allowedValues: [ 'Adams', 'Ashland', 'Barron', 'Bayfield', 'Brown', 'Buffalo', 'Burnett', 'Calumet', 'Chippewa', 'Clark', 'Columbia', 'Crawford', 'Dane', 'Dodge', 'Door', 'Douglas', 'Dunn', 'Eau Claire', 'Florence', 'Fond Du Lac', 'Forest', 'Grant', 'Green', 'Green Lake', 'Iowa', 'Iron', 'Jackson', 'Jefferson', 'Juneau', 'Kenosha', 'Kewaunee', 'La Crosse', 'Lafayette', 'Langlade', 'Lincoln', 'Manitowoc', 'Marathon', 'Marinette', 'Marquette', 'Menominee', 'Milwaukee', 'Monroe', 'Oconto', 'Oneida', 'Outagamie', 'Ozaukee', 'Pepin', 'Pierce', 'Polk', 'Portage', 'Price', 'Racine', 'Richland', 'Rock', 'Rusk', 'Saint Croix', 'Sauk', 'Sawyer', 'Shawano', 'Sheboygan', 'Taylor', 'Trempealeau', 'Vernon', 'Vilas', 'Walworth', 'Washburn', 'Washington', 'Waukesha', 'Waupaca', 'Waushara', 'Winnebago', 'Wood', ], }, /** Provider's Address */ address: { type: String, optional: false, }, /** Coordinates of Provider Location */ coordinates: { type: Object, optional: false, minCount: 2, maxCount: 2, }, 'coordinates.lat': { type: Number, optional: false, custom: function () { // eslint-disable-line object-shorthand,func-names if (this.value < 42.5 || this.value > 47.083) { return 'invalidLatitude'; } return true; }, label: 'Latitude', }, 'coordinates.lon': { type: Number, optional: false, custom: function () { // eslint-disable-line object-shorthand,func-names if (this.value > -86.767 || this.value < -92.883) { return 'invalidLongitude'; } return true; }, label: 'Longitude', }, /** Provider Main Phone Number */ phones: { type: Array, defaultValue: [], optional: false, }, 'phones.$': { type: Object, }, 'phones.$.number': { type: String, optional: false, label: 'Main Phone Number', autoValue: function () { //eslint-disable-line // can't use arrow function because of `this` context return this.value.replace(/[^\d]/g, ''); }, }, 'phones.$.description': { type: String, optional: true, }, 'phones.$.tty': { type: Boolean, optional: true, label: 'Is this number TTY-enabled?', }, 'phones.$.ext': { type: Number, optional: true, }, /** Crisis Phone Number */ crisis: { type: Object, optional: false, defaultValue: {}, }, 'crisis.number': { type: String, optional: false, label: '24-hr Crisis Phone Number', autoValue: function () { //eslint-disable-line // can't use arrow function because of `this` context return this.value.replace(/[^\d]/g, ''); }, }, 'crisis.tty': { type: Boolean, optional: true, label: 'Is this number TTY-enabled?', }, 'crisis.ext': { type: Number, optional: true, }, /** Contact email address */ emails: { type: Array, optional: false, defaultValue: [], }, 'emails.$': { type: Object, optional: true, }, 'emails.$.address': { type: String, optional: false, regEx: SimpleSchema.RegEx.Email, }, 'emails.$.description': { type: String, optional: true, }, /** Website */ website: { type: String, optional: true, regEx: SimpleSchema.RegEx.Url, label: 'Website URL', }, /** Facebook link */ facebook: { type: String, optional: true, regEx: SimpleSchema.RegEx.Url, label: 'Facebook Page URL', }, /** Twitter feed */ twitter: { type: String, optional: true, regEx: SimpleSchema.RegEx.Url, label: 'Twitter Feed URL', }, /** Notes */ notes: { type: String, optional: true, }, /** Parent Location, if this is a satellite office */ parent: { type: String, optional: true, label: 'If this is a satellite office, select the Parent Location:', }, }); Providers.collection.attachSchema(Providers.schema); export default Providers;
enove/Thriver
logic/providers/schema.js
JavaScript
mit
5,093
$(function () { var $NS = $('body#site_calendar'); if (!$NS.length) { return; } // CALENDAR (ex-SELECTION CRITERIA) var $calendar_nav = $('#calendar_nav_links'), next_page = $calendar_nav.data('nextpage'), previous_page = $calendar_nav.data('previouspage'), path = location.pathname; if (previous_page.length) { $calendar_nav.append($('<a>Previous 30 days</a>').attr('class', 'button-outline button-green no-wrap mr1 ml1').attr('href', path + "?date=" + previous_page)); } if (next_page.length) { $calendar_nav.append($('<a>Next 30 days</a>').attr('class', 'button-outline button-green no-wrap mr1 ml1').attr('href', path + "?date=" + next_page)); } // This is kind of hacky but hides the intro once you start paginating if ($(location).attr('href').indexOf('week') >= 0) { $('body').scrollTop($('#nonprofits').position().top - $('.header-shim').outerHeight()); } $('.js-read-more-link').on('click', function (e) { $(this).closest('.js-read-more').find('.js-read-more-show').show(); $(this).closest('.js-read-more').find('.js-read-more-hide').hide(); e.preventDefault(); }); });
developer-star/dollar-a-day
app/assets/javascripts/calendar.js
JavaScript
mit
1,155
jui.define("chart.brush.donut", [ "util.base", "util.math", "util.color" ], function(_, math, ColorUtil) { /** * @class chart.brush.donut * * implements donut brush * * @extends chart.brush.pie * */ var DonutBrush = function() { var self = this, cache_active = {}; /** * @method drawDonut * * donut 을 그린다. * * @param {Number} centerX 중앙 위치 x * @param {Number} centerY 중앙 위치 y * @param {Number} innerRadius 안쪽 반지름 * @param {Number} outerRadius 바깥쪽 반지름 * @param {Number} startAngle 시작 지점 각도 * @param {Number} endAngle 시작지점에서 끝지점까지의 각도 * @param {Object} attr donut 설정될 svg 속성 리스트 * @param {Boolean} hasCircle * @return {util.svg.element} */ this.drawDonut = function(centerX, centerY, innerRadius, outerRadius, startAngle, endAngle, attr, hasCircle) { hasCircle = hasCircle || false; attr['stroke-width']= outerRadius - innerRadius; var g = this.chart.svg.group(), path = this.chart.svg.path(attr), dist = Math.abs(outerRadius - innerRadius); // 바깥 지름 부터 그림 var obj = math.rotate(0, -outerRadius, math.radian(startAngle)), startX = obj.x, startY = obj.y; // 시작 하는 위치로 옮김 path.MoveTo(startX, startY); // outer arc 에 대한 지점 설정 obj = math.rotate(startX, startY, math.radian(endAngle)); // 중심점 이동 g.translate(centerX, centerY); // outer arc 그림 path.Arc(outerRadius, outerRadius, 0, (endAngle > 180) ? 1 : 0, 1, obj.x, obj.y); g.append(path); if(hasCircle) { var centerCircle = math.rotate(0, -innerRadius - dist/2, math.radian(startAngle)), cX = centerCircle.x, cY = centerCircle.y, centerCircleLine = math.rotate(cX, cY, math.radian(endAngle)); var circle = this.chart.svg.circle({ cx : centerCircleLine.x, cy : centerCircleLine.y, r : dist/2, fill : attr.fill }); g.append(circle); var circle2 = this.chart.svg.circle({ cx : centerCircleLine.x, cy : centerCircleLine.y, r : 3, fill : "white" }); g.append(circle2); } return g; } /** * @method drawDonut3d * * donut 을 그린다. * * @param {Number} centerX 중앙 위치 x * @param {Number} centerY 중앙 위치 y * @param {Number} innerRadius 안쪽 반지름 * @param {Number} outerRadius 바깥쪽 반지름 * @param {Number} startAngle 시작 지점 각도 * @param {Number} endAngle 시작지점에서 끝지점까지의 각도 * @param {Object} attr donut 설정될 svg 속성 리스트 * @param {Boolean} hasCircle * @return {util.svg.element} */ this.drawDonut3d = function(centerX, centerY, innerRadius, outerRadius, startAngle, endAngle, attr, hasCircle, isLast) { var g = this.chart.svg.group(), path = this.chart.svg.path(attr), dist = Math.abs(outerRadius - innerRadius); outerRadius += dist/2; innerRadius = outerRadius - dist; // 바깥 지름 부터 그림 var obj = math.rotate(0, -outerRadius, math.radian(startAngle)), startX = obj.x, startY = obj.y; var innerObj = math.rotate(0, -innerRadius, math.radian(startAngle)), innerStartX = innerObj.x, innerStartY = innerObj.y; // 시작 하는 위치로 옮김 path.MoveTo(startX, startY); // outer arc 에 대한 지점 설정 obj = math.rotate(startX, startY, math.radian(endAngle)); innerObj = math.rotate(innerStartX, innerStartY, math.radian(endAngle)); // 중심점 이동 g.translate(centerX, centerY); // outer arc 그림 path.Arc(outerRadius, outerRadius, 0, (endAngle > 180) ? 1 : 0, 1, obj.x, obj.y); var y = obj.y + 10, x = obj.x + 5, innerY = innerObj.y + 10, innerX = innerObj.x + 5, targetX = startX + 5, targetY = startY + 10, innerTargetX = innerStartX + 5, innerTargetY = innerStartY + 10; path.LineTo(x, y); path.Arc(outerRadius, outerRadius, 0, (endAngle > 180) ? 1 : 0, 0, targetX, targetY) path.ClosePath(); g.append(path); // 안쪽 면 그리기 var innerPath = this.chart.svg.path(attr); // 시작 하는 위치로 옮김 innerPath.MoveTo(innerStartX, innerStartY); innerPath.Arc(innerRadius, innerRadius, 0, (endAngle > 180) ? 1 : 0, 1, innerObj.x, innerObj.y); innerPath.LineTo(innerX, innerY); innerPath.Arc(innerRadius, innerRadius, 0, (endAngle > 180) ? 1 : 0, 0, innerTargetX, innerTargetY); innerPath.ClosePath(); g.append(innerPath); return g; } this.drawDonut3dBlock = function(centerX, centerY, innerRadius, outerRadius, startAngle, endAngle, attr, hasCircle, isLast) { var g = this.chart.svg.group(), path = this.chart.svg.path(attr), dist = Math.abs(outerRadius - innerRadius); outerRadius += dist/2; innerRadius = outerRadius - dist; // 바깥 지름 부터 그림 var obj = math.rotate(0, -outerRadius, math.radian(startAngle)), startX = obj.x, startY = obj.y; var innerObj = math.rotate(0, -innerRadius, math.radian(startAngle)), innerStartX = innerObj.x, innerStartY = innerObj.y; // 시작 하는 위치로 옮김 path.MoveTo(startX, startY); // outer arc 에 대한 지점 설정 obj = math.rotate(startX, startY, math.radian(endAngle)); innerObj = math.rotate(innerStartX, innerStartY, math.radian(endAngle)); // 중심점 이동 g.translate(centerX, centerY); var y = obj.y + 10, x = obj.x + 5, innerY = innerObj.y + 10, innerX = innerObj.x + 5; // 왼쪽면 그리기 var rect = this.chart.svg.path(attr); rect.MoveTo(obj.x, obj.y).LineTo(x, y).LineTo(innerX, innerY).LineTo(innerObj.x, innerObj.y).ClosePath(); g.append(rect); return g; } this.drawUnit = function (index, data, g) { var obj = this.axis.c(index); var width = obj.width, height = obj.height, x = obj.x, y = obj.y, min = width; if (height < min) { min = height; } if (this.brush.size >= min/2) { this.brush.size = min/4; } // center var centerX = width / 2 + x, centerY = height / 2 + y, outerRadius = min / 2 - this.brush.size / 2, innerRadius = outerRadius - this.brush.size; var target = this.brush.target, active = this.brush.active, all = 360, startAngle = 0, max = 0; for (var i = 0; i < target.length; i++) { max += data[target[i]]; } if (this.brush['3d']) { // 화면 블럭 그리기 for (var i = 0; i < target.length; i++) { var value = data[target[i]], endAngle = all * (value / max), donut3d = this.drawDonut3dBlock(centerX, centerY, innerRadius, outerRadius, startAngle, endAngle, { fill : ColorUtil.darken(this.color(i), 0.5) }, i == target.length - 1); g.append(donut3d); startAngle += endAngle; } startAngle = 0; for (var i = 0; i < target.length; i++) { var value = data[target[i]], endAngle = all * (value / max), donut3d = this.drawDonut3d(centerX, centerY, innerRadius, outerRadius, startAngle, endAngle, { fill : ColorUtil.darken(this.color(i), 0.5) }, i == target.length - 1); g.append(donut3d); startAngle += endAngle; } } startAngle = 0; for (var i = 0; i < target.length; i++) { var value = data[target[i]], endAngle = all * (value / max), centerAngle = startAngle + (endAngle / 2) - 90, donut = this.drawDonut(centerX, centerY, innerRadius, outerRadius, startAngle, endAngle, { stroke : this.color(i), fill : 'transparent' }); // 설정된 키 활성화 if (active == target[i] || $.inArray(target[i], active) != -1) { this.setActiveEvent(donut, centerX, centerY, centerAngle); cache_active[centerAngle] = true; } // 활성화 이벤트 설정 if (this.brush.activeEvent != null) { (function (p, cx, cy, ca) { p.on(self.brush.activeEvent, function (e) { if (!cache_active[ca]) { self.setActiveEvent(p, cx, cy, ca); cache_active[ca] = true; } else { p.translate(cx, cy); cache_active[ca] = false; } }); p.attr({ cursor: "pointer" }); })(donut, centerX, centerY, centerAngle); } if(this.brush.showText) { var text = this.getFormatText(target[i], value), elem = this.drawText(centerX, centerY, centerAngle, outerRadius, text); this.addEvent(elem, index, i); g.append(elem); } this.addEvent(donut, index, i); g.append(donut); startAngle += endAngle; } } } DonutBrush.setup = function() { return { /** @cfg {Number} [size=50] donut stroke width */ size: 50 }; } return DonutBrush; }, "chart.brush.pie");
juijs/store.jui.io
public/js/jui/js/chart/brush/donut.js
JavaScript
mit
10,879
const BRACKET_MINIMUM_UPDATE_INTERVAL = 2 * 1000; const AUTO_DISQUALIFY_WARNING_TIMEOUT = 30 * 1000; const AUTO_START_MINIMUM_TIMEOUT = 30 * 1000; const MAX_REASON_LENGTH = 300; var TournamentGenerators = { roundrobin: require('./generator-round-robin.js').RoundRobin, elimination: require('./generator-elimination.js').Elimination }; var Tournament; exports.tournaments = {}; function usersToNames(users) { return users.map(function (user) { return user.name; }); } function createTournamentGenerator(generator, args, output) { var Generator = TournamentGenerators[toId(generator)]; if (!Generator) { output.sendReply(generator + " is not a valid type."); output.sendReply("Valid types: " + Object.keys(TournamentGenerators).join(", ")); return; } args.unshift(null); return new (Generator.bind.apply(Generator, args))(); } function createTournament(room, format, generator, playerCap, isRated, args, output) { if (room.type !== 'chat') { output.sendReply("Tournaments can only be created in chat rooms."); return; } if (exports.tournaments[room.id]) { output.sendReply("A tournament is already running in the room."); return; } if (Rooms.global.lockdown) { output.sendReply("The server is restarting soon, so a tournament cannot be created."); return; } format = Tools.getFormat(format); if (format.effectType !== 'Format' || !format.tournamentShow) { output.sendReply(format.id + " is not a valid tournament format."); output.sendReply("Valid formats: " + Object.values(Tools.data.Formats).filter(function (f) { return f.effectType === 'Format' && f.tournamentShow; }).map('name').join(", ")); return; } if (!TournamentGenerators[toId(generator)]) { output.sendReply(generator + " is not a valid type."); output.sendReply("Valid types: " + Object.keys(TournamentGenerators).join(", ")); return; } if (playerCap && playerCap < 2) { output.sendReply("You cannot have a player cap that is less than 2."); return; } return (exports.tournaments[room.id] = new Tournament(room, format, createTournamentGenerator(generator, args, output), playerCap, isRated)); } function deleteTournament(name, output) { var id = toId(name); var tournament = exports.tournaments[id]; if (!tournament) { output.sendReply(name + " doesn't exist."); return false; } tournament.forceEnd(output); delete exports.tournaments[id]; return true; } function getTournament(name, output) { var id = toId(name); if (exports.tournaments[id]) { return exports.tournaments[id]; } } Tournament = (function () { function Tournament(room, format, generator, playerCap, isRated) { this.room = room; this.format = toId(format); this.generator = generator; this.isRated = isRated; this.playerCap = parseInt(playerCap) || Config.tournamentDefaultPlayerCap || 0; this.scouting = true; if (Config.tournamentDefaultPlayerCap && this.playerCap > Config.tournamentDefaultPlayerCap) { ResourceMonitor.log('[ResourceMonitor] Room ' + room.id + ' starting a tour over default cap (' + this.playerCap + ')'); } this.isBracketInvalidated = true; this.lastBracketUpdate = 0; this.bracketUpdateTimer = null; this.bracketCache = null; this.isTournamentStarted = false; this.availableMatches = null; this.inProgressMatches = null; this.isAvailableMatchesInvalidated = true; this.availableMatchesCache = null; this.pendingChallenges = null; this.isEnded = false; room.add('|tournament|create|' + this.format + '|' + generator.name + '|' + this.playerCap); room.send('|tournament|update|' + JSON.stringify({ format: this.format, generator: generator.name, playerCap: this.playerCap, isStarted: false, isJoined: false })); this.update(); } Tournament.prototype.setGenerator = function (generator, output) { if (this.isTournamentStarted) { output.sendReply('|tournament|error|BracketFrozen'); return; } var isErrored = false; this.generator.getUsers().forEach(function (user) { var error = generator.addUser(user); if (typeof error === 'string') { output.sendReply('|tournament|error|' + error); isErrored = true; } }); if (isErrored) return; this.generator = generator; this.room.send('|tournament|update|' + JSON.stringify({generator: generator.name})); this.isBracketInvalidated = true; this.update(); return true; }; Tournament.prototype.forceEnd = function () { if (this.isTournamentStarted) { this.inProgressMatches.forEach(function (match) { if (match) { delete match.room.tour; match.room.addRaw("<div class=\"broadcast-red\"><b>The tournament was forcefully ended.</b><br />You can finish playing, but this battle is no longer considered a tournament battle.</div>"); } }); } else if (this.autoStartTimeout) { clearTimeout(this.autoStartTimeout); } this.isEnded = true; this.room.add('|tournament|forceend'); this.isEnded = true; }; Tournament.prototype.updateFor = function (targetUser, connection) { if (!connection) connection = targetUser; if (this.isEnded) return; if ((!this.bracketUpdateTimer && this.isBracketInvalidated) || (this.isTournamentStarted && this.isAvailableMatchesInvalidated)) { this.room.add( "Error: update() called with a target user when data invalidated: " + (!this.bracketUpdateTimer && this.isBracketInvalidated) + ", " + (this.isTournamentStarted && this.isAvailableMatchesInvalidated) + "; Please report this to an admin." ); return; } var isJoined = this.generator.getUsers().indexOf(targetUser) >= 0; connection.sendTo(this.room, '|tournament|update|' + JSON.stringify({ format: this.format, generator: this.generator.name, isStarted: this.isTournamentStarted, isJoined: isJoined, bracketData: this.bracketCache })); if (this.isTournamentStarted && isJoined) { connection.sendTo(this.room, '|tournament|update|' + JSON.stringify({ challenges: usersToNames(this.availableMatchesCache.challenges.get(targetUser)), challengeBys: usersToNames(this.availableMatchesCache.challengeBys.get(targetUser)) })); var pendingChallenge = this.pendingChallenges.get(targetUser); if (pendingChallenge && pendingChallenge.to) { connection.sendTo(this.room, '|tournament|update|' + JSON.stringify({challenging: pendingChallenge.to.name})); } else if (pendingChallenge && pendingChallenge.from) { connection.sendTo(this.room, '|tournament|update|' + JSON.stringify({challenged: pendingChallenge.from.name})); } } connection.sendTo(this.room, '|tournament|updateEnd'); }; Tournament.prototype.update = function (targetUser) { if (targetUser) throw new Error("Please use updateFor() to update the tournament for a specific user."); if (this.isEnded) return; if (this.isBracketInvalidated) { if (Date.now() < this.lastBracketUpdate + BRACKET_MINIMUM_UPDATE_INTERVAL) { if (this.bracketUpdateTimer) clearTimeout(this.bracketUpdateTimer); this.bracketUpdateTimer = setTimeout(function () { this.bracketUpdateTimer = null; this.update(); }.bind(this), BRACKET_MINIMUM_UPDATE_INTERVAL); } else { this.lastBracketUpdate = Date.now(); this.bracketCache = this.getBracketData(); this.isBracketInvalidated = false; this.room.send('|tournament|update|' + JSON.stringify({bracketData: this.bracketCache})); } } if (this.isTournamentStarted && this.isAvailableMatchesInvalidated) { this.availableMatchesCache = this.getAvailableMatches(); this.isAvailableMatchesInvalidated = false; this.availableMatchesCache.challenges.forEach(function (opponents, user) { user.sendTo(this.room, '|tournament|update|' + JSON.stringify({challenges: usersToNames(opponents)})); }, this); this.availableMatchesCache.challengeBys.forEach(function (opponents, user) { user.sendTo(this.room, '|tournament|update|' + JSON.stringify({challengeBys: usersToNames(opponents)})); }, this); } this.room.send('|tournament|updateEnd'); }; Tournament.prototype.purgeGhostUsers = function () { // "Ghost" users sometimes end up in the tournament because they've merged with another user. // This function is to remove those ghost users from the tournament. this.generator.getUsers(true).forEach(function (user) { var realUser = Users.getExact(user.userid); if (!realUser || realUser !== user) { // The two following functions are called without their second argument, // but the second argument will not be used in this situation if (this.isTournamentStarted) { if (!this.disqualifiedUsers.get(user)) { this.disqualifyUser(user); } } else { this.removeUser(user); } this.room.update(); } }, this); }; Tournament.prototype.addUser = function (user, isAllowAlts, output) { if (!user.named) { output.sendReply('|tournament|error|UserNotNamed'); return; } var users = this.generator.getUsers(); if (this.playerCap && users.length >= this.playerCap) { output.sendReply('|tournament|error|Full'); return; } if (!isAllowAlts) { for (var i = 0; i < users.length; i++) { if (users[i].latestIp === user.latestIp) { output.sendReply('|tournament|error|AltUserAlreadyAdded'); return; } } } var error = this.generator.addUser(user); if (typeof error === 'string') { output.sendReply('|tournament|error|' + error); return; } this.room.add('|tournament|join|' + user.name); user.sendTo(this.room, '|tournament|update|{"isJoined":true}'); this.isBracketInvalidated = true; this.update(); if (this.playerCap === (users.length + 1)) this.room.add("The tournament is now full."); }; Tournament.prototype.removeUser = function (user, output) { var error = this.generator.removeUser(user); if (typeof error === 'string') { output.sendReply('|tournament|error|' + error); return; } this.room.add('|tournament|leave|' + user.name); user.sendTo(this.room, '|tournament|update|{"isJoined":false}'); this.isBracketInvalidated = true; this.update(); }; Tournament.prototype.replaceUser = function (user, replacementUser, output) { var error = this.generator.replaceUser(user, replacementUser); if (typeof error === 'string') { output.sendReply('|tournament|error|' + error); return; } this.room.add('|tournament|replace|' + user.name + '|' + replacementUser.name); user.sendTo(this.room, '|tournament|update|{"isJoined":false}'); replacementUser.sendTo(this.room, '|tournament|update|{"isJoined":true}'); this.isBracketInvalidated = true; this.update(); }; Tournament.prototype.getBracketData = function () { var data = this.generator.getBracketData(); if (data.type === 'tree' && data.rootNode) { var queue = [data.rootNode]; while (queue.length > 0) { var node = queue.shift(); if (node.state === 'available') { var pendingChallenge = this.pendingChallenges.get(node.children[0].team); if (pendingChallenge && node.children[1].team === pendingChallenge.to) { node.state = 'challenging'; } var inProgressMatch = this.inProgressMatches.get(node.children[0].team); if (inProgressMatch && node.children[1].team === inProgressMatch.to) { node.state = 'inprogress'; node.room = inProgressMatch.room.id; } } if (node.team) node.team = node.team.name; node.children.forEach(function (child) { queue.push(child); }); } } else if (data.type === 'table') { if (this.isTournamentStarted) { data.tableContents.forEach(function (row, r) { var pendingChallenge = this.pendingChallenges.get(data.tableHeaders.rows[r]); var inProgressMatch = this.inProgressMatches.get(data.tableHeaders.rows[r]); if (pendingChallenge || inProgressMatch) { row.forEach(function (cell, c) { if (!cell) return; if (pendingChallenge && data.tableHeaders.cols[c] === pendingChallenge.to) { cell.state = 'challenging'; } if (inProgressMatch && data.tableHeaders.cols[c] === inProgressMatch.to) { cell.state = 'inprogress'; cell.room = inProgressMatch.room.id; } }); } }, this); } data.tableHeaders.cols = usersToNames(data.tableHeaders.cols); data.tableHeaders.rows = usersToNames(data.tableHeaders.rows); } return data; }; Tournament.prototype.startTournament = function (output) { if (this.isTournamentStarted) { output.sendReply('|tournament|error|AlreadyStarted'); return false; } this.purgeGhostUsers(); var users = this.generator.getUsers(); if (users.length < 2) { output.sendReply('|tournament|error|NotEnoughUsers'); return false; } this.generator.freezeBracket(); this.availableMatches = new Map(); this.inProgressMatches = new Map(); this.pendingChallenges = new Map(); this.disqualifiedUsers = new Map(); this.isAutoDisqualifyWarned = new Map(); this.lastActionTimes = new Map(); users.forEach(function (user) { this.availableMatches.set(user, new Map()); this.inProgressMatches.set(user, null); this.pendingChallenges.set(user, null); this.disqualifiedUsers.set(user, false); this.isAutoDisqualifyWarned.set(user, false); this.lastActionTimes.set(user, Date.now()); }, this); this.isTournamentStarted = true; this.autoDisqualifyTimeout = Infinity; if (this.autoStartTimeout) clearTimeout(this.autoStartTimeout); this.isBracketInvalidated = true; this.room.add('|tournament|start'); this.room.send('|tournament|update|{"isStarted":true}'); this.update(); return true; }; Tournament.prototype.getAvailableMatches = function () { var matches = this.generator.getAvailableMatches(); if (typeof matches === 'string') { this.room.add("Unexpected error from getAvailableMatches(): " + matches + ". Please report this to an admin."); return; } var users = this.generator.getUsers(); var challenges = new Map(); var challengeBys = new Map(); var oldAvailableMatches = new Map(); users.forEach(function (user) { challenges.set(user, []); challengeBys.set(user, []); var oldAvailableMatch = false; var availableMatches = this.availableMatches.get(user); if (availableMatches.size) { oldAvailableMatch = true; availableMatches.clear(); } oldAvailableMatches.set(user, oldAvailableMatch); }, this); matches.forEach(function (match) { challenges.get(match[0]).push(match[1]); challengeBys.get(match[1]).push(match[0]); this.availableMatches.get(match[0]).set(match[1], true); }, this); this.availableMatches.forEach(function (availableMatches, user) { if (oldAvailableMatches.get(user)) return; if (availableMatches.size) this.lastActionTimes.set(user, Date.now()); }, this); return { challenges: challenges, challengeBys: challengeBys }; }; Tournament.prototype.disqualifyUser = function (user, output, reason) { var error = this.generator.disqualifyUser(user); if (error) { output.sendReply('|tournament|error|' + error); return false; } if (this.disqualifiedUsers.get(user)) { output.sendReply('|tournament|error|AlreadyDisqualified'); return false; } this.disqualifiedUsers.set(user, true); this.generator.setUserBusy(user, false); var challenge = this.pendingChallenges.get(user); if (challenge) { this.pendingChallenges.set(user, null); if (challenge.to) { this.generator.setUserBusy(challenge.to, false); this.pendingChallenges.set(challenge.to, null); challenge.to.sendTo(this.room, '|tournament|update|{"challenged":null}'); } else if (challenge.from) { this.generator.setUserBusy(challenge.from, false); this.pendingChallenges.set(challenge.from, null); challenge.from.sendTo(this.room, '|tournament|update|{"challenging":null}'); } } var matchFrom = this.inProgressMatches.get(user); if (matchFrom) { this.generator.setUserBusy(matchFrom.to, false); this.inProgressMatches.set(user, null); delete matchFrom.room.tour; matchFrom.room.forfeit(user); } var matchTo = null; this.inProgressMatches.forEach(function (match, userFrom) { if (match && match.to === user) matchTo = userFrom; }); if (matchTo) { this.generator.setUserBusy(matchTo, false); var matchRoom = this.inProgressMatches.get(matchTo).room; delete matchRoom.tour; matchRoom.forfeit(user); this.inProgressMatches.set(matchTo, null); } this.room.add('|tournament|disqualify|' + user.name); user.sendTo(this.room, '|tournament|update|{"isJoined":false}'); user.popup("|modal|You have been disqualified from the tournament in " + this.room.title + (reason ? ":\n\n" + reason : ".")); this.isBracketInvalidated = true; this.isAvailableMatchesInvalidated = true; if (this.generator.isTournamentEnded()) { this.onTournamentEnd(); } else { this.update(); } return true; }; Tournament.prototype.setAutoStartTimeout = function (timeout, output) { if (this.isTournamentStarted) { output.sendReply('|tournament|error|AlreadyStarted'); return false; } timeout = parseFloat(timeout); if (timeout < AUTO_START_MINIMUM_TIMEOUT || isNaN(timeout)) { output.sendReply('|tournament|error|InvalidAutoStartTimeout'); return false; } if (this.autoStartTimeout) clearTimeout(this.autoStartTimeout); if (timeout === Infinity) { this.room.add('|tournament|autostart|off'); } else { this.autoStartTimeout = setTimeout(this.startTournament.bind(this, output), timeout); this.room.add('|tournament|autostart|on|' + timeout); } return true; }; Tournament.prototype.setAutoDisqualifyTimeout = function (timeout, output) { if (!this.isTournamentStarted) { output.sendReply('|tournament|error|NotStarted'); return false; } if (timeout < AUTO_DISQUALIFY_WARNING_TIMEOUT || isNaN(timeout)) { output.sendReply('|tournament|error|InvalidAutoDisqualifyTimeout'); return false; } this.autoDisqualifyTimeout = parseFloat(timeout); if (this.autoDisqualifyTimeout === Infinity) { this.room.add('|tournament|autodq|off'); } else { this.room.add('|tournament|autodq|on|' + this.autoDisqualifyTimeout); } this.runAutoDisqualify(); return true; }; Tournament.prototype.runAutoDisqualify = function (output) { if (!this.isTournamentStarted) { output.sendReply('|tournament|error|NotStarted'); return false; } this.lastActionTimes.forEach(function (time, user) { var availableMatches = false; if (this.availableMatches.get(user).size) availableMatches = true; var pendingChallenge = this.pendingChallenges.get(user); if (!availableMatches && !pendingChallenge) return; if (pendingChallenge && pendingChallenge.to) return; if (Date.now() > time + this.autoDisqualifyTimeout && this.isAutoDisqualifyWarned.get(user)) { this.disqualifyUser(user, output, "You failed to make or accept the challenge in time."); this.room.update(); } else if (Date.now() > time + this.autoDisqualifyTimeout - AUTO_DISQUALIFY_WARNING_TIMEOUT && !this.isAutoDisqualifyWarned.get(user)) { var remainingTime = this.autoDisqualifyTimeout - Date.now() + time; if (remainingTime <= 0) { remainingTime = AUTO_DISQUALIFY_WARNING_TIMEOUT; this.lastActionTimes.set(user, Date.now() - this.autoDisqualifyTimeout + AUTO_DISQUALIFY_WARNING_TIMEOUT); } this.isAutoDisqualifyWarned.set(user, true); user.sendTo(this.room, '|tournament|autodq|target|' + remainingTime); } else { this.isAutoDisqualifyWarned.set(user, false); } }, this); }; Tournament.prototype.challenge = function (from, to, output) { if (!this.isTournamentStarted) { output.sendReply('|tournament|error|NotStarted'); return; } if (!this.availableMatches.get(from) || !this.availableMatches.get(from).get(to)) { output.sendReply('|tournament|error|InvalidMatch'); return; } if (this.generator.getUserBusy(from) || this.generator.getUserBusy(to)) { this.room.add("Tournament backend breaks specifications. Please report this to an admin."); return; } this.generator.setUserBusy(from, true); this.generator.setUserBusy(to, true); this.isAvailableMatchesInvalidated = true; this.purgeGhostUsers(); this.update(); from.prepBattle(this.format, 'tournament', from, this.finishChallenge.bind(this, from, to, output)); }; Tournament.prototype.finishChallenge = function (from, to, output, result) { if (!result) { this.generator.setUserBusy(from, false); this.generator.setUserBusy(to, false); this.isAvailableMatchesInvalidated = true; this.update(); return; } this.lastActionTimes.set(from, Date.now()); this.lastActionTimes.set(to, Date.now()); this.pendingChallenges.set(from, {to: to, team: from.team}); this.pendingChallenges.set(to, {from: from, team: from.team}); from.sendTo(this.room, '|tournament|update|' + JSON.stringify({challenging: to.name})); to.sendTo(this.room, '|tournament|update|' + JSON.stringify({challenged: from.name})); this.isBracketInvalidated = true; this.update(); }; Tournament.prototype.cancelChallenge = function (user, output) { if (!this.isTournamentStarted) { output.sendReply('|tournament|error|NotStarted'); return; } var challenge = this.pendingChallenges.get(user); if (!challenge || challenge.from) return; this.generator.setUserBusy(user, false); this.generator.setUserBusy(challenge.to, false); this.pendingChallenges.set(user, null); this.pendingChallenges.set(challenge.to, null); user.sendTo(this.room, '|tournament|update|{"challenging":null}'); challenge.to.sendTo(this.room, '|tournament|update|{"challenged":null}'); this.isBracketInvalidated = true; this.isAvailableMatchesInvalidated = true; this.update(); }; Tournament.prototype.acceptChallenge = function (user, output) { if (!this.isTournamentStarted) { output.sendReply('|tournament|error|NotStarted'); return; } var challenge = this.pendingChallenges.get(user); if (!challenge || !challenge.from) return; user.prepBattle(this.format, 'tournament', user, this.finishAcceptChallenge.bind(this, user, challenge)); }; Tournament.prototype.finishAcceptChallenge = function (user, challenge, result) { if (!result) return; // Prevent battles between offline users from starting if (!challenge.from.connected || !user.connected) return; // Prevent double accepts and users that have been disqualified while between these two functions if (!this.pendingChallenges.get(challenge.from)) return; if (!this.pendingChallenges.get(user)) return; var room = Rooms.global.startBattle(challenge.from, user, this.format, challenge.team, user.team, {rated: this.isRated, tour: this}); if (!room) return; this.pendingChallenges.set(challenge.from, null); this.pendingChallenges.set(user, null); challenge.from.sendTo(this.room, '|tournament|update|{"challenging":null}'); user.sendTo(this.room, '|tournament|update|{"challenged":null}'); this.inProgressMatches.set(challenge.from, {to: user, room: room}); this.room.add('|tournament|battlestart|' + challenge.from.name + '|' + user.name + '|' + room.id).update(); this.isBracketInvalidated = true; this.runAutoDisqualify(); this.update(); }; Tournament.prototype.onBattleJoin = function (room, user) { if (this.scouting || this.isEnded || user.latestIp === room.p1.latestIp || user.latestIp === room.p2.latestIp) return; var roomid = (room && room.id ? room.id : room); var users = this.generator.getUsers(true); for (var i = 0; i < users.length; i++) { if (users[i].latestIp === user.latestIp) { return "Scouting is banned: tournament players can't watch other tournament battles."; } } }; Tournament.prototype.onBattleWin = function (room, winner) { var from = Users.get(room.p1); var to = Users.get(room.p2); var result = 'draw'; if (from === winner) { result = 'win'; } else if (to === winner) { result = 'loss'; } if (result === 'draw' && !this.generator.isDrawingSupported) { this.room.add('|tournament|battleend|' + from.name + '|' + to.name + '|' + result + '|' + room.battle.score.join(',') + '|fail'); this.generator.setUserBusy(from, false); this.generator.setUserBusy(to, false); this.inProgressMatches.set(from, null); this.isBracketInvalidated = true; this.isAvailableMatchesInvalidated = true; this.runAutoDisqualify(); this.update(); return this.room.update(); } var error = this.generator.setMatchResult([from, to], result, room.battle.score); if (error) { // Should never happen return this.room.add("Unexpected " + error + " from setMatchResult([" + from.userid + ", " + to.userid + "], " + result + ", " + room.battle.score + ") in onBattleWin(" + room.id + ", " + winner.userid + "). Please report this to an admin.").update(); } this.room.add('|tournament|battleend|' + from.name + '|' + to.name + '|' + result + '|' + room.battle.score.join(',')); this.generator.setUserBusy(from, false); this.generator.setUserBusy(to, false); this.inProgressMatches.set(from, null); this.isBracketInvalidated = true; this.isAvailableMatchesInvalidated = true; if (this.generator.isTournamentEnded()) { this.onTournamentEnd(); } else { this.runAutoDisqualify(); this.update(); } this.room.update(); }; Tournament.prototype.onTournamentEnd = function () { this.room.add('|tournament|end|' + JSON.stringify({ results: this.generator.getResults().map(usersToNames), format: this.format, generator: this.generator.name, bracketData: this.getBracketData() })); this.isEnded = true; delete exports.tournaments[toId(this.room.id)]; // // Tournament Winnings // var color = '#088cc7'; var sizeRequiredToEarn = 4; var currencyName = function (amount) { var name = " buck"; return amount === 1 ? name : name + "s"; }; var data = this.generator.getResults().map(usersToNames).toString(); var winner, runnerUp; if (data.indexOf(',') >= 0) { data = data.split(','); winner = data[0]; if (data[1]) runnerUp = data[1]; } else { winner = data; } var wid = toId(winner); var rid = toId(runnerUp); var tourSize = this.generator.users.size; if (this.room.isOfficial && tourSize >= sizeRequiredToEarn) { var firstMoney = Math.round(tourSize / 4); var secondMoney = Math.round(firstMoney / 2); Database.read('money', wid, function (err, amount) { if (err) throw err; if (!amount) amount = 0; Database.write('money', amount + firstMoney, wid, function (err) { if (err) throw err; }); }); this.room.addRaw("<b><font color='" + color + "'>" + Tools.escapeHTML(winner) + "</font> has won " + "<font color='" + color + "'>" + firstMoney + "</font>" + currencyName(firstMoney) + " for winning the tournament!</b>"); if (runnerUp) { Database.read('money', rid, function (err, amount) { if (err) throw err; if (!amount) amount = 0; Database.write('money', amount + secondMoney, rid, function (err) { if (err) throw err; }); }); this.room.addRaw("<b><font color='" + color + "'>" + Tools.escapeHTML(runnerUp) + "</font> has won " + "<font color='" + color + "'>" + secondMoney + "</font>" + currencyName(secondMoney) + " for winning the tournament!</b>"); } } }; return Tournament; })(); var commands = { basic: { j: 'join', in: 'join', join: function (tournament, user) { tournament.addUser(user, false, this); }, l: 'leave', out: 'leave', leave: function (tournament, user) { if (tournament.isTournamentStarted) { tournament.disqualifyUser(user, this); } else { tournament.removeUser(user, this); } }, getusers: function (tournament) { if (!this.canBroadcast()) return; var users = usersToNames(tournament.generator.getUsers(true).sort()); this.sendReplyBox("<strong>" + users.length + " users remain in this tournament:</strong><br />" + Tools.escapeHTML(users.join(", "))); }, getupdate: function (tournament, user) { tournament.updateFor(user); this.sendReply("Your tournament bracket has been updated."); }, challenge: function (tournament, user, params, cmd) { if (params.length < 1) { return this.sendReply("Usage: " + cmd + " <user>"); } var targetUser = Users.get(params[0]); if (!targetUser) { return this.sendReply("User " + params[0] + " not found."); } tournament.challenge(user, targetUser, this); }, cancelchallenge: function (tournament, user) { tournament.cancelChallenge(user, this); }, acceptchallenge: function (tournament, user) { tournament.acceptChallenge(user, this); } }, creation: { settype: function (tournament, user, params, cmd) { if (params.length < 1) { return this.sendReply("Usage: " + cmd + " <type> [, <comma-separated arguments>]"); } var playerCap = parseInt(params.splice(1, 1)); var generator = createTournamentGenerator(params.shift(), params, this); if (generator && tournament.setGenerator(generator, this)) { if (playerCap && playerCap >= 2) { tournament.playerCap = playerCap; if (Config.tournamentDefaultPlayerCap && tournament.playerCap > Config.tournamentDefaultPlayerCap) { ResourceMonitor.log('[ResourceMonitor] Room ' + tournament.room.id + ' starting a tour over default cap (' + tournament.playerCap + ')'); } } this.sendReply("Tournament set to " + generator.name + (playerCap ? " with a player cap of " + tournament.playerCap : "") + "."); } }, begin: 'start', start: function (tournament, user) { if (tournament.startTournament(this)) { this.sendModCommand("(" + user.name + " started the tournament.)"); } } }, moderation: { dq: 'disqualify', disqualify: function (tournament, user, params, cmd) { if (params.length < 1) { return this.sendReply("Usage: " + cmd + " <user>"); } var targetUser = Users.get(params[0]); if (!targetUser) { return this.sendReply("User " + params[0] + " not found."); } var reason = ''; if (params[1]) { reason = params[1].trim(); if (reason.length > MAX_REASON_LENGTH) return this.sendReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters."); } if (tournament.disqualifyUser(targetUser, this, reason)) { this.privateModCommand("(" + targetUser.name + " was disqualified from the tournament by " + user.name + (reason ? " (" + reason + ")" : "") + ")"); } }, autostart: 'setautostart', setautostart: function (tournament, user, params, cmd) { if (params.length < 1) { return this.sendReply("Usage: " + cmd + " <minutes|off>"); } if (params[0].toLowerCase() === 'infinity' || params[0] === '0') params[0] = 'off'; var timeout = params[0].toLowerCase() === 'off' ? Infinity : params[0]; if (tournament.setAutoStartTimeout(timeout * 60 * 1000, this)) { this.privateModCommand("(The tournament auto start timeout was set to " + params[0] + " by " + user.name + ")"); } }, autodq: 'setautodq', setautodq: function (tournament, user, params, cmd) { if (params.length < 1) { return this.sendReply("Usage: " + cmd + " <minutes|off>"); } if (params[0].toLowerCase() === 'infinity' || params[0] === '0') params[0] = 'off'; var timeout = params[0].toLowerCase() === 'off' ? Infinity : params[0]; if (tournament.setAutoDisqualifyTimeout(timeout * 60 * 1000, this)) { this.privateModCommand("(The tournament auto disqualify timeout was set to " + params[0] + " by " + user.name + ")"); } }, runautodq: function (tournament) { tournament.runAutoDisqualify(this); }, scout: 'setscouting', scouting: 'setscouting', setscout: 'setscouting', setscouting: function (tournament, user, params, cmd) { if (params.length < 1) { if (tournament.scouting) { return this.sendReply("This tournament allows spectating other battles while in a tournament."); } else { return this.sendReply("This tournament disallows spectating other battles while in a tournament."); } } var option = params[0].toLowerCase(); if (option === 'on' || option === 'true' || option === 'allow' || option === 'allowed') { tournament.scouting = true; this.room.add('|tournament|scouting|allow'); this.privateModCommand("(The tournament was set to allow scouting by " + user.name + ")"); } else if (option === 'off' || option === 'false' || option === 'disallow' || option === 'disallowed') { tournament.scouting = false; this.room.add('|tournament|scouting|disallow'); this.privateModCommand("(The tournament was set to disallow scouting by " + user.name + ")"); } else { return this.sendReply("Usage: " + cmd + " <allow|disallow>"); } }, end: 'delete', stop: 'delete', delete: function (tournament, user) { if (deleteTournament(tournament.room.title, this)) { this.privateModCommand("(" + user.name + " forcibly ended a tournament.)"); } } } }; CommandParser.commands.tour = 'tournament'; CommandParser.commands.tours = 'tournament'; CommandParser.commands.tournaments = 'tournament'; CommandParser.commands.tournament = function (paramString, room, user) { var cmdParts = paramString.split(' '); var cmd = cmdParts.shift().trim().toLowerCase(); var params = cmdParts.join(' ').split(',').map(function (param) { return param.trim(); }); if (!params[0]) params = []; if (cmd === '') { if (!this.canBroadcast()) return; this.sendReply('|tournaments|info|' + JSON.stringify(Object.keys(exports.tournaments).filter(function (tournament) { tournament = exports.tournaments[tournament]; return !tournament.room.isPrivate && !tournament.room.staffRoom; }).map(function (tournament) { tournament = exports.tournaments[tournament]; return {room: tournament.room.title, format: tournament.format, generator: tournament.generator.name, isStarted: tournament.isTournamentStarted}; }))); } else if (cmd === 'help') { return this.parse('/help tournament'); } else if (cmd === 'on' || cmd === 'enable') { if (!this.can('tournamentsmanagement', null, room)) return; if (room.toursEnabled) { return this.sendReply("Tournaments are already enabled."); } room.toursEnabled = true; if (room.chatRoomData) { room.chatRoomData.toursEnabled = true; Rooms.global.writeChatRoomData(); } return this.sendReply("Tournaments enabled."); } else if (cmd === 'off' || cmd === 'disable') { if (!this.can('tournamentsmanagement', null, room)) return; if (!room.toursEnabled) { return this.sendReply("Tournaments are already disabled."); } delete room.toursEnabled; if (room.chatRoomData) { delete room.chatRoomData.toursEnabled; Rooms.global.writeChatRoomData(); } return this.sendReply("Tournaments disabled."); } else if (cmd === 'create' || cmd === 'new') { if (room.toursEnabled) { if (!this.can('tournaments', null, room)) return; } else { if (!user.can('tournamentsmanagement', null, room)) { return this.sendReply("Tournaments are disabled in this room (" + room.id + ")."); } } if (params.length < 2) { return this.sendReply("Usage: " + cmd + " <format>, <type> [, <comma-separated arguments>]"); } var tour = createTournament(room, params.shift(), params.shift(), params.shift(), Config.istournamentsrated, params, this); if (tour) { this.privateModCommand("(" + user.name + " created a tournament in " + tour.format + " format.)"); if (Config.tourannouncements && Config.tourannouncements.indexOf(room.id) >= 0) { var tourRoom = Rooms.search(Config.tourroom || 'tournaments'); if (tourRoom) tourRoom.addRaw('<div class="infobox"><a href="/' + room.id + '" class="ilink"><b>' + Tools.getFormat(tour.format).name + '</b> tournament created in <b>' + room.title + '</b>.</a></div>'); } } } else { var tournament = getTournament(room.title); if (!tournament) { return this.sendReply("There is currently no tournament running in this room."); } var commandHandler = null; if (commands.basic[cmd]) { commandHandler = typeof commands.basic[cmd] === 'string' ? commands.basic[commands.basic[cmd]] : commands.basic[cmd]; } if (commands.creation[cmd]) { if (room.toursEnabled) { if (!this.can('tournaments', null, room)) return; } else { if (!user.can('tournamentsmanagement', null, room)) { return this.sendReply("Tournaments are disabled in this room (" + room.id + ")."); } } commandHandler = typeof commands.creation[cmd] === 'string' ? commands.creation[commands.creation[cmd]] : commands.creation[cmd]; } if (commands.moderation[cmd]) { if (!user.can('tournamentsmoderation', null, room)) { return this.sendReply(cmd + " - Access denied."); } commandHandler = typeof commands.moderation[cmd] === 'string' ? commands.moderation[commands.moderation[cmd]] : commands.moderation[cmd]; } if (!commandHandler) { this.sendReply(cmd + " is not a tournament command."); } else { commandHandler.call(this, tournament, user, params, cmd); } } }; CommandParser.commands.tournamenthelp = function (target, room, user) { if (!this.canBroadcast()) return; return this.sendReplyBox( "- create/new &lt;format>, &lt;type> [, &lt;comma-separated arguments>]: Creates a new tournament in the current room.<br />" + "- settype &lt;type> [, &lt;comma-separated arguments>]: Modifies the type of tournament after it's been created, but before it has started.<br />" + "- end/stop/delete: Forcibly ends the tournament in the current room.<br />" + "- begin/start: Starts the tournament in the current room.<br />" + "- dq/disqualify &lt;user>: Disqualifies a user.<br />" + "- autodq/setautodq &lt;minutes|off>: Sets the automatic disqualification timeout.<br />" + "- runautodq: Manually run the automatic disqualifier.<br />" + "- scouting: Specifies whether joining tournament matches while in a tournament is allowed.<br />" + "- getusers: Lists the users in the current tournament.<br />" + "- on/off: Enables/disables allowing mods to start tournaments.<br />" + "More detailed help can be found <a href=\"https://gist.github.com/verbiage/0846a552595349032fbe\">here</a>" ); }; exports.Tournament = Tournament; exports.TournamentGenerators = TournamentGenerators; exports.createTournament = createTournament; exports.deleteTournament = deleteTournament; exports.get = getTournament; exports.commands = commands;
TheDiabolicGift/Showdown-Boilerplate
tournaments/index.js
JavaScript
mit
38,424
describe('<ion-slide-pager> directive', function() { beforeEach(module('ionic', 'ngAnimateMock')); beforeEach(function() { spyOn(ionic, 'requestAnimationFrame').andCallFake(function(cb) { cb(); }); }); it('should create pager elements', inject(function($compile, $rootScope, $timeout) { var el = $compile('<ion-slide-box>' + '<ion-slide>A</ion-slide>' + '<ion-slide>B</ion-slide>' + '<ion-slide ng-if="showThird">C</ion-slide>' + '<ion-slide-pager></ion-slide-pager>' + '</ion-slide-box>')($rootScope); $rootScope.$apply(); var pager = el.find('ion-slide-pager'); var slideBoxCtrl = el.controller('ionSlideBox'); expect(pager.find('.slider-pager-page').length).toBe(2); $rootScope.$apply('showThird = true'); expect(pager.find('.slider-pager-page').length).toBe(3); $rootScope.$apply('showThird = false'); expect(pager.find('.slider-pager-page').length).toBe(2); })); it('should by default select on click', inject(function($compile, $rootScope, $timeout) { var el = $compile('<ion-slide-box>' + '<ion-slide>A</ion-slide>' + '<ion-slide>B</ion-slide>' + '<ion-slide>C</ion-slide>' + '<ion-slide-pager></ion-slide-pager>' + '</ion-slide-box>')($rootScope); $rootScope.$apply(); $timeout.flush(); var slideBoxCtrl = el.controller('ionSlideBox'); var pagers = el.find('.slider-pager-page'); expect(slideBoxCtrl.selected()).toBe(0); pagers.eq(1).click(); $timeout.flush(); expect(slideBoxCtrl.selected()).toBe(1); pagers.eq(2).click(); $timeout.flush(); expect(slideBoxCtrl.selected()).toBe(2); })); it('should allow custom click action which overrides default', inject(function($compile, $rootScope, $timeout) { $rootScope.click = jasmine.createSpy('pagerClick'); var el = $compile('<ion-slide-box>' + '<ion-slide>A</ion-slide>' + '<ion-slide>B</ion-slide>' + '<ion-slide>C</ion-slide>' + '<ion-slide-pager ng-click="click($slideIndex)"></ion-slide-pager>' + '</ion-slide-box>')($rootScope); $rootScope.$apply(); $timeout.flush(); var slideBoxCtrl = el.controller('ionSlideBox'); var pagers = el.find('.slider-pager-page'); pagers.eq(1).click(); expect(slideBoxCtrl.selected()).toBe(0); expect($rootScope.click).toHaveBeenCalledWith(1); pagers.eq(2).click(); expect(slideBoxCtrl.selected()).toBe(0); expect($rootScope.click).toHaveBeenCalledWith(2); })); });
baiyanghese/ionic
test/unit/angular/directive/slidePager.unit.js
JavaScript
mit
2,776
import path from 'path'; import test from 'ava'; import clintonRuleTester from './fixtures/rule-tester'; const opts = { cwd: 'test/fixtures/no-git-merge-conflict', rules: { 'no-git-merge-conflict': 'error' } }; const ruleTester = clintonRuleTester(opts); const createError = file => ({ message: 'Resolve all Git merge conflicts.', file: path.resolve(opts.cwd, file), ruleId: 'no-git-merge-conflict', severity: 'error' }); test(async t => { const result = await ruleTester(t, '.'); result.sort((a, b) => a.file.localeCompare(b.file)); t.deepEqual(result, [ createError('bar.txt'), createError('rainbow.txt'), createError('test.txt'), createError('unicorn.txt') ]); });
SamVerschueren/gh-lint
test/no-git-merge-conflict.js
JavaScript
mit
694
import eventsSaga from './events' export default function* rootSaga() { yield [ eventsSaga() ] }
Restuta/rcn.io
src/shared/sagas/root.js
JavaScript
mit
106
var express = require('express'); var router = express.Router(); var db = require('../db'); var jwt = require('jsonwebtoken'); var _ = require('lodash'); var app = require('../server'); var google = require('googleapis'); var OAuth2Client = google.auth.OAuth2; var plus = google.plus('v1'); var cities = require('../cities'); var CLIENT_ID = '1007941048671-mqral0q9jeg17ervhv01gknh7tml237i.apps.googleusercontent.com'; var CLIENT_SECRET = 'smDen4IcdnGxks6QMeTS6J5s'; var REDIRECT_URL = 'http://127.0.0.1:5679/oauthsignin'; var oauth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL); router.get('/', function(req, res) { function getAccessToken(oauth2Client, callback) { var url = oauth2Client.generateAuthUrl({ access_type: 'offline', scope: 'https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email' }); oauth2Client.getToken(req.query.code, function(err, tokens) { oauth2Client.setCredentials(tokens); callback(); }); } getAccessToken(oauth2Client, function() { plus.people.get({ userId: 'me', auth: oauth2Client }, function(err, profile) { if (err) { console.log('An error occured', err); return; } var username = profile.emails[0].value, firstname = profile.name.givenName, lastname = profile.name.familyName, email = profile.emails[0].value, gravatarUrl = profile.image.url; db.User.findOne({username: username}, function(err, foundUser){ console.log('err:', err); console.log('foundUser:', foundUser); if (foundUser === null) { console.log('new user') var user = new db.User({ username: username, firstname: firstname, lastname: lastname, email: email, categories: {test:'test'}, friends: {test:false}, beenTo: {test:false}, gravatarUrl: gravatarUrl }); user.markModified('categories'); user.markModified('beenTo'); console.log('user:', user); user.save(function(err, user) { if (err) { console.log('err saving'); res.send(err) } else { console.log('inside save'); var city = _.shuffle(cities).pop(); var token = jwt.sign(user, app.get('superSecret'), { expiresInminutes:1440 }); request_yelp({location:city},function(yelpErr,yelpRes,yelpBody){ var parsed = JSON.parse(yelpBody); var businesses = parsed.businesses; businesses = _.shuffle(businesses); for (var i=0; i<businesses.length; i++) { businesses[i].image_url = businesses[i].image_url.slice(0,-6)+'o.jpg'; } res.json({ success: true, message: 'Enjoy your token!', token: token, username: user.username, firstname: user.firstname, lastname: user.lastname, businesses:businesses });//end of res.json })//end of request_yelp } }) } else { // not a new user db.User.findOne({username: username}, function(err, user){ if (err) { console.log('err finding user'); res.send(err); } else { var token = jwt.sign(user, app.get('superSecret'), {expiresIn: 1400}); res.json({ success: true, message: 'Enjoy your token!', token: token, username: username, beenTo: user.beenTo }); } }) } }) }); }) }) module.exports = router;
carlbernardo/gut
server/routes/oauthSigninRoute.js
JavaScript
mit
3,853
var fs = require('fs'); var framework = require('./../../../framework'); var WebService = module.exports = function HttpService() { }; framework.inheritService(WebService); WebService.prototype.webRequest_ = function(request, response) { fs.readFile(__dirname + '/html/index.html', function(err, data) { response.writeHead(200, {'Content-Type': 'text/html'}); response.write(data); response.end(); }); };
mexxik/strym-framework
examples/socket_register/services/web.js
JavaScript
mit
453
(function() { 'use strict'; angular .module('blog') .controller('PageCtrl', function($scope, $route, Page) { $scope.page = Page.get({ slug: $route.current.activeNav }); }); }());
Chitrank-Dixit/sinatra-angular-blog
public/js/controllers/PageCtrl.js
JavaScript
mit
202
'use strict'; var React = require('react');
AgtLucas/react-backbone
assets/js/main.js
JavaScript
mit
44
/* eslint-env mocha */ import A from 'assert'; import reduce from './reduce'; import util from '../../lib/util'; describe('list.reduce(fn, accum, list)', () => { const concat = (a, b) => a.concat(b); const validLists = [ ['b', 'c', 'd'], util.arrayLike('b', 'c', 'd'), ]; it('uses "fn" to reduce "accum" and the values in "list" to a single value', () => { validLists.forEach((list) => { A.equal(reduce(concat, 'a', list), 'abcd'); }); }); it('"fn" receives the current index as its third argument', () => { validLists.forEach((list) => { let k = 0; reduce((_, __, i) => A.equal(i, k++), '', list); }); }); it('allows partial application', () => { A.equal(reduce(concat)('a')('b'), 'ab'); A.equal(reduce(concat)('a', 'b'), 'ab'); A.equal(reduce(concat, 'a')('b'), 'ab'); }); });
vtfn/tolb
src/list/reduce_test.js
JavaScript
mit
856
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _rcTrigger = require('rc-trigger'); var _rcTrigger2 = _interopRequireDefault(_rcTrigger); var _Menus = require('./Menus'); var _Menus2 = _interopRequireDefault(_Menus); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } var BUILT_IN_PLACEMENTS = { bottomLeft: { points: ['tl', 'bl'], offset: [0, 4], overflow: { adjustX: 1, adjustY: 1 } }, topLeft: { points: ['bl', 'tl'], offset: [0, -4], overflow: { adjustX: 1, adjustY: 1 } }, bottomRight: { points: ['tr', 'br'], offset: [0, 4], overflow: { adjustX: 1, adjustY: 1 } }, topRight: { points: ['br', 'tr'], offset: [0, -4], overflow: { adjustX: 1, adjustY: 1 } } }; var Cascader = function (_React$Component) { _inherits(Cascader, _React$Component); function Cascader(props) { _classCallCheck(this, Cascader); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); _this.setPopupVisible = function (popupVisible) { if (!('popupVisible' in _this.props)) { _this.setState({ popupVisible: popupVisible }); } // sync activeValue with value when panel open if (popupVisible && !_this.state.visible) { _this.setState({ activeValue: _this.state.value }); } _this.props.onPopupVisibleChange(popupVisible); }; _this.handleChange = function (options, setProps) { _this.props.onChange(options.map(function (o) { return o.value; }), options); _this.setPopupVisible(setProps.visible); }; _this.handlePopupVisibleChange = function (popupVisible) { _this.setPopupVisible(popupVisible); }; _this.handleSelect = function (_ref) { var info = _objectWithoutProperties(_ref, []); if ('value' in _this.props) { delete info.value; } _this.setState(info); }; var initialValue = []; if ('value' in props) { initialValue = props.value || []; } else if ('defaultValue' in props) { initialValue = props.defaultValue || []; } _this.state = { popupVisible: props.popupVisible, activeValue: initialValue, value: initialValue }; return _this; } Cascader.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if ('value' in nextProps && this.props.value !== nextProps.value) { var newValues = { value: nextProps.value || [], activeValue: nextProps.value || [] }; // allow activeValue diff from value // https://github.com/ant-design/ant-design/issues/2767 if ('loadData' in nextProps) { delete newValues.activeValue; } this.setState(newValues); } if ('popupVisible' in nextProps) { this.setState({ popupVisible: nextProps.popupVisible }); } }; Cascader.prototype.getPopupDOMNode = function getPopupDOMNode() { return this.refs.trigger.getPopupDomNode(); }; Cascader.prototype.render = function render() { var props = this.props; var prefixCls = props.prefixCls; var transitionName = props.transitionName; var popupClassName = props.popupClassName; var popupPlacement = props.popupPlacement; var restProps = _objectWithoutProperties(props, ['prefixCls', 'transitionName', 'popupClassName', 'popupPlacement']); // Did not show popup when there is no options var menus = _react2["default"].createElement('div', null); var emptyMenuClassName = ''; if (props.options && props.options.length > 0) { menus = _react2["default"].createElement(_Menus2["default"], _extends({}, props, { value: this.state.value, activeValue: this.state.activeValue, onSelect: this.handleSelect, onChange: this.handleChange, visible: this.state.popupVisible })); } else { emptyMenuClassName = ' ' + prefixCls + '-menus-empty'; } return _react2["default"].createElement( _rcTrigger2["default"], _extends({ ref: 'trigger' }, restProps, { popupPlacement: popupPlacement, builtinPlacements: BUILT_IN_PLACEMENTS, popupTransitionName: transitionName, action: props.disabled ? [] : ['click'], popupVisible: props.disabled ? false : this.state.popupVisible, onPopupVisibleChange: this.handlePopupVisibleChange, prefixCls: prefixCls + '-menus', popupClassName: popupClassName + emptyMenuClassName, popup: menus }), props.children ); }; return Cascader; }(_react2["default"].Component); Cascader.defaultProps = { options: [], onChange: function onChange() {}, onPopupVisibleChange: function onPopupVisibleChange() {}, disabled: false, transitionName: '', prefixCls: 'rc-cascader', popupClassName: '', popupPlacement: 'bottomLeft' }; Cascader.propTypes = { value: _react2["default"].PropTypes.array, defaultValue: _react2["default"].PropTypes.array, options: _react2["default"].PropTypes.array.isRequired, onChange: _react2["default"].PropTypes.func, onPopupVisibleChange: _react2["default"].PropTypes.func, popupVisible: _react2["default"].PropTypes.bool, disabled: _react2["default"].PropTypes.bool, transitionName: _react2["default"].PropTypes.string, popupClassName: _react2["default"].PropTypes.string, popupPlacement: _react2["default"].PropTypes.string, prefixCls: _react2["default"].PropTypes.string, dropdownMenuColumnStyle: _react2["default"].PropTypes.object }; exports["default"] = Cascader; module.exports = exports['default'];
wangi4myself/myFirstReactJs
node_modules/rc-cascader/lib/Cascader.js
JavaScript
mit
7,554
// Events export const EV_FRAME = 'frame'; export const EV_TIMER = 'session-timer'; export const EV_START = 'vm-start'; export const EV_STOP = 'vm-stop'; export const EV_KEYDOWN = 'keydown'; export const EV_MOUSEMOVE = 'mouse'; export const EV_RESIZE = 'resize'; export const EV_SESSIONS_UPDATE = 'sessions-available'; // Reasons export const RS_SESSION_EXPIRED = 'session-expired';
Albyxyz/oszoo
src/constants/socket-events.js
JavaScript
mit
384
class VacancyTypeListController { constructor ($scope, $state, $compile, $log, DTOptionsBuilder, DTColumnBuilder, API) { 'ngInject' this.API = API this.$state = $state this.$log = $log let Users = this.API.service('vacancytype') Users.getList() .then((response) => { let dataSet = response.plain() this.dtOptions = DTOptionsBuilder.newOptions() .withOption('data', dataSet) .withOption('createdRow', createdRow) .withOption('responsive', true) .withBootstrap() this.dtColumns = [ DTColumnBuilder.newColumn(null).withTitle('Actions') .withOption('width', '10%') .notSortable() .renderWith(actionsHtml), DTColumnBuilder.newColumn('name').withTitle('Name'), DTColumnBuilder.newColumn('description').withTitle('Description') ] this.displayTable = true }) let createdRow = (row) => { $compile(angular.element(row).contents())($scope) } let actionsHtml = (data) => { return ` <a class="btn btn-xs btn-warning" ui-sref="app.vacancytypeform({vacancyTypeId: '${data.id}'})"> <i class="fa fa-edit"></i> </a> &nbsp <button class="btn btn-xs btn-danger" ng-click="vm.delete('${data.id}')"> <i class="fa fa-trash-o"></i> </button>` } } delete (id) { let API = this.API let $state = this.$state swal({ title: 'Are you sure?', text: 'You will not be able to recover this data!', type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: 'Yes, delete it!', closeOnConfirm: false, showLoaderOnConfirm: true, html: false }, function () { API.one('vacancytype/detail', id).remove() .then(() => { swal({ title: 'Deleted!', text: 'Vacancy Type has been deleted.', type: 'success', confirmButtonText: 'OK', closeOnConfirm: true }, function () { $state.reload() }) }) }) } $onInit () {} } export const VacancyTypeListComponent = { templateUrl: './views/app/components/vacancy-type/vacancy-type-list/vacancy-type-list.component.html', controller: VacancyTypeListController, controllerAs: 'vm', bindings: {} }
dhianpratama/perakjoogja
angular/app/components/vacancy-type/vacancy-type-list/vacancy-type-list.component.js
JavaScript
mit
2,486