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(angular) {
'use strict';
//-----------------------------Controller Start------------------------------------
function AddBrandModalController($state, $http) {
var ctrl = this;
ctrl.init = function() {
ctrl.brandDetail = (ctrl.resolve && ctrl.resolve.details) || {};
}
ctrl.save = function(brand) {
var data = {
brandName: brand
}
$http({
url: "admin/addBrand",
method: "POST",
data: JSON.stringify(data),
dataType: JSON
}).then(function(response) {
ctrl.modalInstance.close({ action: 'update'});
})
.catch(function(error) {
console.log("Error while adding brand modal")
})
}
ctrl.cancel = function() {
ctrl.modalInstance.close();
};
ctrl.init();
//------------------------------------Controller End------------------------------------
}
angular.module('addBrandModalModule')
.component('addBrandModalComponent', {
templateUrl: 'admin/addBrand-modal/addBrand-modal.template.html',
controller: ['$state', '$http', AddBrandModalController],
bindings: {
modalInstance: '<',
resolve: '<'
}
});
})(window.angular);
| ironydips/UI-itemsSellPurchase | app/admin/addBrand-modal/addBrand-modal.component.js | JavaScript | mit | 1,485 |
$(function() {
$('input:not(.button)').blur(function() {
if (validation.isFieldValid(this.id, $(this).val())) {
$('.error').text('').hide();
} else {
$('.error').text(validation.form[this.id].errorMessage).show();
}
});
});
| nicholasly/Web | Week10/public/javascripts/signup.js | JavaScript | mit | 238 |
'use strict';
/* Service to retrieve data from backend (CouchDB store) */
pissalotApp.factory('pissalotCouchService', function ($resource) {
return $resource('http://192.168.1.4:8080/measurement/:listType',{
listType: '@listType'
}, {
get: {
method: 'GET',
isArray: false
}
});
});
| mdonkers/slim-prototype | pissalot-angular/app/js/services/pissalotCouchService.js | JavaScript | mit | 344 |
const assert = require("assert");
describe("chain of iterators", function() {
it("should conform to ES", function() {
let finallyCalledSrc = 0;
let finallyCalled1 = 0;
let finallyCalled2 = 0;
let cb;
let p1 = new Promise(i => (cb = i));
let tasks = [];
let cbtask;
let p2 = {
then(next) {
tasks.push(next);
cbtask();
}
};
async function scheduler() {
await new Promise(i => (cbtask = i));
tasks.pop()("t1");
}
scheduler();
async function* src() {
try {
yield await p1;
yield await p2;
assert.fail("never");
} finally {
finallyCalledSrc++;
}
}
async function* a1() {
try {
for await (const i of src()) yield `a1:${i}`;
assert.fail("never");
} finally {
finallyCalled1 = true;
}
assert.fail("never");
}
async function* a2() {
try {
yield* a1();
assert.fail("never");
} finally {
finallyCalled2 = true;
}
}
async function* a3() {
const v = a2();
try {
for (let i; !(i = await v.next()).done; ) {
yield `a3:${i.value}`;
}
assert.fail("never");
} finally {
await v.return();
}
return 2;
}
async function a4() {
const v = a3();
const i1 = await v.next();
assert.ok(!i1.done);
assert.equal(i1.value, "a3:a1:hi");
const n = v.next();
const i2 = await n;
assert.ok(!i2.done);
assert.equal(i2.value, "a3:a1:t1");
const i3 = await v.return(4);
assert.ok(i3.done);
assert.equal(i3.value, 4);
assert.ok(finallyCalledSrc);
assert.ok(finallyCalled1);
assert.ok(finallyCalled2);
return 3;
}
const t4 = a4();
const res = t4.then(i => {
assert.equal(i, 3);
});
cb("hi");
return res;
});
});
| awto/effectfuljs | packages/es/test/samples/src/asyncGeneratorsTest.js | JavaScript | mit | 1,934 |
require("sdk/system/unload").when(function() {
let prefService = require("sdk/preferences/service");
prefService.reset("general.useragent.site_specific_overrides");
prefService.reset("general.useragent.override.youtube.com");
prefService.reset("media.mediasource.enabled");
});
let prefService = require("sdk/preferences/service");
prefService.set('general.useragent.site_specific_overrides', true);
prefService.set("general.useragent.override.youtube.com",
"Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile Safari/537.36"
);
prefService.set("media.mediasource.enabled", true);
| ispedals/Enable-Youtube-Player-Mobile | index.js | JavaScript | mit | 659 |
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var orders = require('../../app/controllers/orders.server.controller');
// Orders Routes
app.route('/orders')
.get(orders.list)
.post(users.requiresLogin, orders.create);
app.route('/orders-analytics')
.get(orders.analytics)
app.route('/orders/:orderId')
.get(orders.read)
.put(users.requiresLogin, orders.hasAuthorization, orders.update)
.delete(users.requiresLogin, orders.hasAuthorization, orders.delete);
// Finish by binding the Order middleware
app.param('orderId', orders.orderByID);
};
| gehlotchirag/sfa-services | app/routes/orders.server.routes.js | JavaScript | mit | 642 |
// 2016-08-22
//
// This is the wrapper for the native side
/*
prelim: start a server from the lib dir:
python -m SimpleHTTPServer (python 2.x) (linux)
python -m http.server (python 3.x) (windows)
1a) load jquery (note: may need a real active file open for this to work)
Note: get message 'VM148:52 Uncaught (in promise) TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.(…)'
if a real file is not open and active, when loading the second file.
Note: refer to yaml libray as 'jsyaml' e.g. 'jsyaml.load()'
fetch('http://code.jquery.com/jquery-latest.min.js').then(r => r.text()).then(r => {eval(r); eval(r);});
1b) make sure you're editing a real file.
test: make sure:
document.getElementById('workbench.editors.files.textFileEditor')
1c) load all the other files
Note: you'll get this message if not in a split-panel
'editor-theme-change-listener.js:39 Uncaught (in promise) TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node''
document.MTA_VS = {};
$.when(
fetch('http://localhost:8000/editor-theme-change-listener.js').then(r => r.text()).then(r => eval(r)),
fetch('http://localhost:8000/local-theme-manager-native.js').then(r => r.text()).then(r => eval(r)),
fetch('http://localhost:8000/mta-vs-native.js').then(r => r.text()).then(r => eval(r))
)
.done(function(first_call, second_call, third_call){
console.log('all loaded');
})
.fail(function(){
console.log('load failed');
});
// Note: server now automatically starts when your run 'mta-vs'
3)
// then do a word setup so a "Theme:" appears in the status line
4) then change the theme with 'mta-vs'
*/
fetch('http://localhost:8000/cmd-channel-listener-native.js')
.then(r => r.text())
.then(r => eval(r))
.then(() => {
console.log('mta-vs-naitve: Now in final then for cmd-channel-listener setup.')
var cmdChannelListenerNative = new document.CmdChannelListenerNative();
cmdChannelListenerNative.observe();
});
//@ sourceURL=mta-vs-native.js
| vt5491/mta-vs | lib/mta-vs-native.js | JavaScript | mit | 2,067 |
(function(){
function newThreadCtrl($location, $state, MessageEditorService){
var vm = this;
vm.getConstants = function(){
return MessageEditorService.pmConstants;
};
vm.newThread = MessageEditorService.getThreadTemplate($location.search().boardId);
vm.returnToBoard = function(){
var boardId = $location.search().boardId;
$state.go('board',{boardId: boardId});
};
vm.previewThread = function(){
vm.previewThread = MessageEditorService.getThreadPreview(vm.newThread);
vm.previewThread.$promise.then(function(data){
vm.preview = true;
});
};
vm.postThread = function(){
MessageEditorService.saveThread(vm.newThread).$promise.then(function(data){
});
}
vm.isOpen = false;
}
angular.module('zfgc.forum')
.controller('newThreadCtrl', ['$location', '$state', 'MessageEditorService', newThreadCtrl]);
})(); | ZFGCCP/ZFGC3 | src/main/webapp/scripts/forum/thread/new-thread.controller.js | JavaScript | mit | 898 |
angular.module('starter.controllers', [])
// A simple controller that fetches a list of data from a service
.controller('JobIndexCtrl', function($rootScope, PetService) {
// "Pets" is a service returning mock data (services.js)
$rootScope.pets = PetService.all();
})
// A simple controller that shows a tapped item's data
.controller('PetDetailCtrl', function($scope, $rootScope, $state, $stateParams, PetService) {
$rootScope.pet = PetService.get($stateParams.jobId);
$scope.goBack = $state.go('job.pet-index');
})
.controller('NewJobDetailCtrl', function($scope, $rootScope, $state, $stateParams, PetService) {
$rootScope.pet = PetService.get($stateParams.jobId);
$scope.goBack = $state.go('new-job');
})
.controller('LoginCtrl', function($scope, $state) {
$scope.login = function () {
$state.go("tab.adopt");
};
})
.controller('JobCreationCtrl', function($scope, $rootScope, $state, $stateParams, $localstorage, PetService) {
$scope.createJob = function () {
var title = document.getElementById("title");
var desc = document.getElementById("desc");
var location = document.getElementById("location");
if (title.value.trim() !== "" && desc.value.trim() !== "" && location.value.trim() !== "") {
var newJobId = $localstorage.length() - 1;
var newJob = {
id: String(newJobId),
title: String(title.value.trim()),
description: String(desc.value.trim()),
location: String(location.value.trim()),
quote: {
damageDesc: "",
estimatedCost: "",
estimatedTime: "",
},
report: {
fixDesc: "",
actualCost: "",
startTime: "",
finishTime: ""
}
};
$rootScope.pet = PetService.get(newJobId);
$rootScope.pets = PetService.all();
$localstorage.setObject(newJobId, newJob);
$state.go('new-quote', {'jobId' : newJobId});
}
}
});
| KhanhHB/test | www/js/controllers.js | JavaScript | mit | 1,947 |
(function () {
'use strict';
describe('Posts Route Tests', function () {
// Initialize global variables
var $scope,
PostsService;
//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 ($rootScope, _PostsService_) {
// Set a new global scope
$scope = $rootScope.$new();
PostsService = _PostsService_;
}));
describe('Route Config', function () {
describe('Main Route', function () {
var mainstate;
beforeEach(inject(function ($state) {
mainstate = $state.get('posts');
}));
it('Should have the correct URL', function () {
expect(mainstate.url).toEqual('/posts');
});
it('Should be abstract', function () {
expect(mainstate.abstract).toBe(true);
});
it('Should have template', function () {
expect(mainstate.template).toBe('<ui-view/>');
});
});
describe('View Route', function () {
var viewstate,
PostsController,
mockPost;
beforeEach(inject(function ($controller, $state, $templateCache) {
viewstate = $state.get('posts.view');
$templateCache.put('modules/posts/client/views/view-post.client.view.html', '');
// create mock Post
mockPost = new PostsService({
_id: '525a8422f6d0f87f0e407a33',
name: 'Post Name'
});
//Initialize Controller
PostsController = $controller('PostsController as vm', {
$scope: $scope,
postResolve: mockPost
});
}));
it('Should have the correct URL', function () {
expect(viewstate.url).toEqual('/:postId');
});
it('Should have a resolve function', function () {
expect(typeof viewstate.resolve).toEqual('object');
expect(typeof viewstate.resolve.postResolve).toEqual('function');
});
it('should respond to URL', inject(function ($state) {
expect($state.href(viewstate, {
postId: 1
})).toEqual('/posts/1');
}));
it('should attach an Post to the controller scope', function () {
expect($scope.vm.post._id).toBe(mockPost._id);
});
it('Should not be abstract', function () {
expect(viewstate.abstract).toBe(undefined);
});
it('Should have templateUrl', function () {
expect(viewstate.templateUrl).toBe('modules/posts/client/views/view-post.client.view.html');
});
});
describe('Create Route', function () {
var createstate,
PostsController,
mockPost;
beforeEach(inject(function ($controller, $state, $templateCache) {
createstate = $state.get('posts.create');
$templateCache.put('modules/posts/client/views/form-post.client.view.html', '');
// create mock Post
mockPost = new PostsService();
//Initialize Controller
PostsController = $controller('PostsController as vm', {
$scope: $scope,
postResolve: mockPost
});
}));
it('Should have the correct URL', function () {
expect(createstate.url).toEqual('/create');
});
it('Should have a resolve function', function () {
expect(typeof createstate.resolve).toEqual('object');
expect(typeof createstate.resolve.postResolve).toEqual('function');
});
it('should respond to URL', inject(function ($state) {
expect($state.href(createstate)).toEqual('/posts/create');
}));
it('should attach an Post to the controller scope', function () {
expect($scope.vm.post._id).toBe(mockPost._id);
expect($scope.vm.post._id).toBe(undefined);
});
it('Should not be abstract', function () {
expect(createstate.abstract).toBe(undefined);
});
it('Should have templateUrl', function () {
expect(createstate.templateUrl).toBe('modules/posts/client/views/form-post.client.view.html');
});
});
describe('Edit Route', function () {
var editstate,
PostsController,
mockPost;
beforeEach(inject(function ($controller, $state, $templateCache) {
editstate = $state.get('posts.edit');
$templateCache.put('modules/posts/client/views/form-post.client.view.html', '');
// create mock Post
mockPost = new PostsService({
_id: '525a8422f6d0f87f0e407a33',
name: 'Post Name'
});
//Initialize Controller
PostsController = $controller('PostsController as vm', {
$scope: $scope,
postResolve: mockPost
});
}));
it('Should have the correct URL', function () {
expect(editstate.url).toEqual('/:postId/edit');
});
it('Should have a resolve function', function () {
expect(typeof editstate.resolve).toEqual('object');
expect(typeof editstate.resolve.postResolve).toEqual('function');
});
it('should respond to URL', inject(function ($state) {
expect($state.href(editstate, {
postId: 1
})).toEqual('/posts/1/edit');
}));
it('should attach an Post to the controller scope', function () {
expect($scope.vm.post._id).toBe(mockPost._id);
});
it('Should not be abstract', function () {
expect(editstate.abstract).toBe(undefined);
});
it('Should have templateUrl', function () {
expect(editstate.templateUrl).toBe('modules/posts/client/views/form-post.client.view.html');
});
xit('Should go to unauthorized route', function () {
});
});
});
});
})();
| tupm58/GoJob-mean | modules/posts/tests/client/posts.client.routes.tests.js | JavaScript | mit | 6,174 |
goog.provide('glift.displays.commentbox');
glift.displays.commentbox = {};
| Kashomon/glift | src/displays/commentbox/commentbox.js | JavaScript | mit | 76 |
/**YEngine2D
* author:YYC
* date:2014-04-21
* email:395976266@qq.com
* qq: 395976266
* blog:http://www.cnblogs.com/chaogex/
*/
describe("CallFunc", function () {
var action = null;
var sandbox = null;
beforeEach(function () {
sandbox = sinon.sandbox.create();
action = new YE.CallFunc();
});
afterEach(function () {
});
describe("init", function () {
it("获得方法上下文、方法、传入方法的参数数组", function () {
});
});
describe("update", function () {
// it("如果方法为空,则直接完成动作", function () {
// sandbox.stub(action, "finish");
//
// action.update();
//
// expect(action.finish).toCalledOnce();
// });
// describe("否则", function () {
var context = null,
func = null,
data = null,
target = null;
function setParam(func, context, dataArr) {
action.ye___context = context;
action.ye___callFunc = func;
action.ye___dataArr = dataArr;
}
beforeEach(function () {
context = {};
func = sandbox.createSpyObj("call");
data = 1;
target = {a: 1};
setParam(func, context, [data]);
sandbox.stub(action, "getTarget").returns(target);
});
it("调用方法,设置其上下文为context,并传入target和参数数组", function () {
action.update();
expect(func.call).toCalledWith(context, target, [data]);
});
it("完成动作", function () {
sandbox.stub(action, "finish");
action.update();
expect(action.finish).toCalledOnce();
});
// });
});
describe("copy", function () {
it("返回动作副本", function () {
var a = action.copy();
expect(a).toBeInstanceOf(YE.CallFunc);
expect(a === action).toBeFalsy();
});
it("传入的参数要进行深拷贝", function () {
var data = {a: 1};
action.ye___dataArr = [data];
var a = action.copy();
a.ye___dataArr[0].a = 100;
expect(data.a).toEqual(1);
});
});
describe("reverse", function () {
it("直接返回动作", function () {
expect(action.reverse()).toBeSame(action);
});
});
// describe("isFinish", function () {
// it("返回true", function () {
// expect(action.isFinish()).toBeTruthy();
// });
// });
describe("create", function () {
it("创建实例并返回", function () {
expect(YE.CallFunc.create()).toBeInstanceOf(YE.CallFunc);
});
});
});
| yyc-git/YEngine2D | test/unit/action/CallFuncSpec.js | JavaScript | mit | 2,823 |
///////////////////////////////////////////////////////////////////////////
// Copyright © 2014 - 2016 Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define([
'dojo/_base/declare',
'jimu/BaseFeatureAction',
'jimu/WidgetManager'
], function(declare, BaseFeatureAction, WidgetManager) {
var clazz = declare(BaseFeatureAction, {
iconClass: 'icon-direction-to',
isFeatureSupported: function(featureSet) {
return featureSet.features.length === 1 && featureSet.geometryType === "point";
},
onExecute: function(featureSet) {
WidgetManager.getInstance().triggerWidgetOpen(this.widgetId).then(function(directionWidget) {
if (featureSet.features.length === 1 && featureSet.geometryType === "point") {
if (featureSet.features[0].geometry && featureSet.features[0].geometry.type === "point") {
directionWidget.addStop(featureSet.features[0].geometry);
}
}
});
}
});
return clazz;
}); | cmccullough2/cmv-wab-widgets | wab/2.2/widgets/Directions/DirectionToFeatureAction.js | JavaScript | mit | 1,585 |
module.exports = {
path: {
scripts: '/assets/scripts',
styles: '/assets/styles',
images: '/assets/images'
},
site: {
url: require('./package.json').mylly.url,
name: 'My website',
lang: 'en',
charset: 'utf-8',
ua: '' // UA-XXXXXX-XX
},
page: {}
}; | niklasramo/mylly | src/_base.ctx.js | JavaScript | mit | 288 |
/* eslint-env mocha */
'use strict'
const path = require('path')
const cwd = process.cwd()
const NetSuite = require(path.join(cwd, 'netsuite'))
const chai = require('chai')
const expect = chai.expect
const config = require('config')
describe('NetSuite class', function () {
this.timeout(24 * 60 * 60 * 1000)
it('should export a function', function () {
expect(NetSuite).to.be.a('function')
expect(new NetSuite({})).to.be.a('object')
})
it('should search and searchMoreWithId', async function () {
let ns = new NetSuite(opts())
let result = await ns.search({type: 'FolderSearch'})
expect(result.searchResult).to.be.a('object')
expect(result.searchResult.status).to.be.a('object')
expect(result.searchResult.status.attributes).to.be.a('object')
expect(result.searchResult.status.attributes.isSuccess).to.equal('true')
expect(result.searchResult.pageIndex).to.equal(1)
let more = await ns.searchMoreWithId(result)
expect(more.searchResult).to.be.a('object')
expect(more.searchResult.pageIndex).to.equal(2)
})
it('should search folders', async function () {
let ns = new NetSuite(opts())
let result = await ns.search({type: 'FolderSearch'})
expect(result.searchResult.status.attributes.isSuccess).to.equal('true')
})
it('should search files', async function () {
let ns = new NetSuite(opts())
let result = await ns.search({type: 'FileSearch'})
expect(result.searchResult.status.attributes.isSuccess).to.equal('true')
})
it('should get files', async function () {
let ns = new NetSuite(opts())
let internalId = '88'
let result = await ns.get({type: 'file', internalId: internalId})
expect(result.readResponse).to.be.a('object')
expect(result.readResponse.status).to.be.a('object')
expect(result.readResponse.status.attributes).to.be.a('object')
expect(result.readResponse.status.attributes.isSuccess).to.equal('true')
expect(result.readResponse.record.attributes.internalId).to.equal(internalId)
})
})
const opts = () => {
return {
appId: config.get('appId'),
passport: {account: config.get('account'), email: config.get('email'), password: config.get('password')},
searchPrefs: {bodyFieldsOnly: false, pageSize: 10},
debug: false
}
}
| trujaytim/netsuite-v2017.2 | test/netsuite-test.js | JavaScript | mit | 2,283 |
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Popup windows
//>>label: Popups
//>>group: Widgets
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css
//>>css.structure: ../css/structure/jquery.mobile.popup.css,../css/structure/jquery.mobile.transition.css,../css/structure/jquery.mobile.transition.fade.css
// Lessons:
// You must remove nav bindings even if there is no history. Make sure you
// remove nav bindings in the same frame as the beginning of the close process
// if there is no history. If there is history, remove nav bindings from the nav
// bindings handler - that way, only one of them can fire per close process.
define( [
"jquery",
"../links",
"../widget",
"../support",
"../events/navigate",
"../navigation/path",
"../navigation/history",
"../navigation/navigator",
"../navigation/method",
"../animationComplete",
"../navigation",
"jquery-plugins/jquery.hashchange" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {
function fitSegmentInsideSegment( windowSize, segmentSize, offset, desired ) {
var returnValue = desired;
if ( windowSize < segmentSize ) {
// Center segment if it's bigger than the window
returnValue = offset + ( windowSize - segmentSize ) / 2;
} else {
// Otherwise center it at the desired coordinate while keeping it completely inside the window
returnValue = Math.min( Math.max( offset, desired - segmentSize / 2 ), offset + windowSize - segmentSize );
}
return returnValue;
}
function getWindowCoordinates( theWindow ) {
return {
x: theWindow.scrollLeft(),
y: theWindow.scrollTop(),
cx: ( theWindow[ 0 ].innerWidth || theWindow.width() ),
cy: ( theWindow[ 0 ].innerHeight || theWindow.height() )
};
}
$.widget( "mobile.popup", {
options: {
wrapperClass: null,
theme: null,
overlayTheme: null,
shadow: true,
corners: true,
transition: "none",
positionTo: "origin",
tolerance: null,
closeLinkSelector: "a:jqmData(rel='back')",
closeLinkEvents: "click.popup",
navigateEvents: "navigate.popup",
closeEvents: "navigate.popup pagebeforechange.popup",
dismissible: true,
enhanced: false,
// NOTE Windows Phone 7 has a scroll position caching issue that
// requires us to disable popup history management by default
// https://github.com/jquery/jquery-mobile/issues/4784
//
// NOTE this option is modified in _create!
history: !$.mobile.browser.oldIE
},
_create: function() {
var theElement = this.element,
myId = theElement.attr( "id" ),
currentOptions = this.options;
// We need to adjust the history option to be false if there's no AJAX nav.
// We can't do it in the option declarations because those are run before
// it is determined whether there shall be AJAX nav.
currentOptions.history = currentOptions.history && $.mobile.ajaxEnabled && $.mobile.hashListeningEnabled;
// Define instance variables
$.extend( this, {
_scrollTop: 0,
_page: theElement.closest( ".ui-page" ),
_ui: null,
_fallbackTransition: "",
_currentTransition: false,
_prerequisites: null,
_isOpen: false,
_tolerance: null,
_resizeData: null,
_ignoreResizeTo: 0,
_orientationchangeInProgress: false
});
if ( this._page.length === 0 ) {
this._page = $( "body" );
}
if ( currentOptions.enhanced ) {
this._ui = {
container: theElement.parent(),
screen: theElement.parent().prev(),
placeholder: $( this.document[ 0 ].getElementById( myId + "-placeholder" ) )
};
} else {
this._ui = this._enhance( theElement, myId );
this._applyTransition( currentOptions.transition );
}
this
._setTolerance( currentOptions.tolerance )
._ui.focusElement = this._ui.container;
// Event handlers
this._on( this._ui.screen, { "vclick": "_eatEventAndClose" } );
this._on( this.window, {
orientationchange: $.proxy( this, "_handleWindowOrientationchange" ),
resize: $.proxy( this, "_handleWindowResize" ),
keyup: $.proxy( this, "_handleWindowKeyUp" )
});
this._on( this.document, { "focusin": "_handleDocumentFocusIn" } );
},
_enhance: function( theElement, myId ) {
var currentOptions = this.options,
wrapperClass = currentOptions.wrapperClass,
ui = {
screen: $( "<div class='ui-screen-hidden ui-popup-screen " +
this._themeClassFromOption( "ui-overlay-", currentOptions.overlayTheme ) + "'></div>" ),
placeholder: $( "<div style='display: none;'><!-- placeholder --></div>" ),
container: $( "<div class='ui-popup-container ui-popup-hidden ui-popup-truncate" +
( wrapperClass ? ( " " + wrapperClass ) : "" ) + "'></div>" )
},
fragment = this.document[ 0 ].createDocumentFragment();
fragment.appendChild( ui.screen[ 0 ] );
fragment.appendChild( ui.container[ 0 ] );
if ( myId ) {
ui.screen.attr( "id", myId + "-screen" );
ui.container.attr( "id", myId + "-popup" );
ui.placeholder
.attr( "id", myId + "-placeholder" )
.html( "<!-- placeholder for " + myId + " -->" );
}
// Apply the proto
this._page[ 0 ].appendChild( fragment );
// Leave a placeholder where the element used to be
ui.placeholder.insertAfter( theElement );
theElement
.detach()
.addClass( "ui-popup " +
this._themeClassFromOption( "ui-body-", currentOptions.theme ) + " " +
( currentOptions.shadow ? "ui-overlay-shadow " : "" ) +
( currentOptions.corners ? "ui-corner-all " : "" ) )
.appendTo( ui.container );
return ui;
},
_eatEventAndClose: function( theEvent ) {
theEvent.preventDefault();
theEvent.stopImmediatePropagation();
if ( this.options.dismissible ) {
this.close();
}
return false;
},
// Make sure the screen covers the entire document - CSS is sometimes not
// enough to accomplish this.
_resizeScreen: function() {
var screen = this._ui.screen,
popupHeight = this._ui.container.outerHeight( true ),
screenHeight = screen.removeAttr( "style" ).height(),
// Subtracting 1 here is necessary for an obscure Andrdoid 4.0 bug where
// the browser hangs if the screen covers the entire document :/
documentHeight = this.document.height() - 1;
if ( screenHeight < documentHeight ) {
screen.height( documentHeight );
} else if ( popupHeight > screenHeight ) {
screen.height( popupHeight );
}
},
_handleWindowKeyUp: function( theEvent ) {
if ( this._isOpen && theEvent.keyCode === $.mobile.keyCode.ESCAPE ) {
return this._eatEventAndClose( theEvent );
}
},
_expectResizeEvent: function() {
var windowCoordinates = getWindowCoordinates( this.window );
if ( this._resizeData ) {
if ( windowCoordinates.x === this._resizeData.windowCoordinates.x &&
windowCoordinates.y === this._resizeData.windowCoordinates.y &&
windowCoordinates.cx === this._resizeData.windowCoordinates.cx &&
windowCoordinates.cy === this._resizeData.windowCoordinates.cy ) {
// timeout not refreshed
return false;
} else {
// clear existing timeout - it will be refreshed below
clearTimeout( this._resizeData.timeoutId );
}
}
this._resizeData = {
timeoutId: this._delay( "_resizeTimeout", 200 ),
windowCoordinates: windowCoordinates
};
return true;
},
_resizeTimeout: function() {
if ( this._isOpen ) {
if ( !this._expectResizeEvent() ) {
if ( this._ui.container.hasClass( "ui-popup-hidden" ) ) {
// effectively rapid-open the popup while leaving the screen intact
this._ui.container.removeClass( "ui-popup-hidden ui-popup-truncate" );
this.reposition( { positionTo: "window" } );
this._ignoreResizeEvents();
}
this._resizeScreen();
this._resizeData = null;
this._orientationchangeInProgress = false;
}
} else {
this._resizeData = null;
this._orientationchangeInProgress = false;
}
},
_stopIgnoringResizeEvents: function() {
this._ignoreResizeTo = 0;
},
_ignoreResizeEvents: function() {
if ( this._ignoreResizeTo ) {
clearTimeout( this._ignoreResizeTo );
}
this._ignoreResizeTo = this._delay( "_stopIgnoringResizeEvents", 1000 );
},
_handleWindowResize: function(/* theEvent */) {
if ( this._isOpen && this._ignoreResizeTo === 0 ) {
if ( ( this._expectResizeEvent() || this._orientationchangeInProgress ) &&
!this._ui.container.hasClass( "ui-popup-hidden" ) ) {
// effectively rapid-close the popup while leaving the screen intact
this._ui.container
.addClass( "ui-popup-hidden ui-popup-truncate" )
.removeAttr( "style" );
}
}
},
_handleWindowOrientationchange: function(/* theEvent */) {
if ( !this._orientationchangeInProgress && this._isOpen && this._ignoreResizeTo === 0 ) {
this._expectResizeEvent();
this._orientationchangeInProgress = true;
}
},
// When the popup is open, attempting to focus on an element that is not a
// child of the popup will redirect focus to the popup
_handleDocumentFocusIn: function( theEvent ) {
var target,
targetElement = theEvent.target,
ui = this._ui;
if ( !this._isOpen ) {
return;
}
if ( targetElement !== ui.container[ 0 ] ) {
target = $( targetElement );
if ( 0 === target.parents().filter( ui.container[ 0 ] ).length ) {
$( this.document[ 0 ].activeElement ).one( "focus", function(/* theEvent */) {
target.blur();
});
ui.focusElement.focus();
theEvent.preventDefault();
theEvent.stopImmediatePropagation();
return false;
} else if ( ui.focusElement[ 0 ] === ui.container[ 0 ] ) {
ui.focusElement = target;
}
}
this._ignoreResizeEvents();
},
_themeClassFromOption: function( prefix, value ) {
return ( value ? ( value === "none" ? "" : ( prefix + value ) ) : ( prefix + "inherit" ) );
},
_applyTransition: function( value ) {
if ( value ) {
this._ui.container.removeClass( this._fallbackTransition );
if ( value !== "none" ) {
this._fallbackTransition = $.mobile._maybeDegradeTransition( value );
if ( this._fallbackTransition === "none" ) {
this._fallbackTransition = "";
}
this._ui.container.addClass( this._fallbackTransition );
}
}
return this;
},
_setOptions: function( newOptions ) {
var currentOptions = this.options,
theElement = this.element,
screen = this._ui.screen;
if ( newOptions.wrapperClass !== undefined ) {
this._ui.container
.removeClass( currentOptions.wrapperClass )
.addClass( newOptions.wrapperClass );
}
if ( newOptions.theme !== undefined ) {
theElement
.removeClass( this._themeClassFromOption( "ui-body-", currentOptions.theme ) )
.addClass( this._themeClassFromOption( "ui-body-", newOptions.theme ) );
}
if ( newOptions.overlayTheme !== undefined ) {
screen
.removeClass( this._themeClassFromOption( "ui-overlay-", currentOptions.overlayTheme ) )
.addClass( this._themeClassFromOption( "ui-overlay-", newOptions.overlayTheme ) );
if ( this._isOpen ) {
screen.addClass( "in" );
}
}
if ( newOptions.shadow !== undefined ) {
theElement.toggleClass( "ui-overlay-shadow", newOptions.shadow );
}
if ( newOptions.corners !== undefined ) {
theElement.toggleClass( "ui-corner-all", newOptions.corners );
}
if ( newOptions.transition !== undefined ) {
if ( !this._currentTransition ) {
this._applyTransition( newOptions.transition );
}
}
if ( newOptions.tolerance !== undefined ) {
this._setTolerance( newOptions.tolerance );
}
if ( newOptions.disabled !== undefined ) {
if ( newOptions.disabled ) {
this.close();
}
}
return this._super( newOptions );
},
_setTolerance: function( value ) {
var tol = { t: 30, r: 15, b: 30, l: 15 },
ar;
if ( value !== undefined ) {
ar = String( value ).split( "," );
$.each( ar, function( idx, val ) { ar[ idx ] = parseInt( val, 10 ); } );
switch( ar.length ) {
// All values are to be the same
case 1:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = tol.r = tol.b = tol.l = ar[ 0 ];
}
break;
// The first value denotes top/bottom tolerance, and the second value denotes left/right tolerance
case 2:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = tol.b = ar[ 0 ];
}
if ( !isNaN( ar[ 1 ] ) ) {
tol.l = tol.r = ar[ 1 ];
}
break;
// The array contains values in the order top, right, bottom, left
case 4:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = ar[ 0 ];
}
if ( !isNaN( ar[ 1 ] ) ) {
tol.r = ar[ 1 ];
}
if ( !isNaN( ar[ 2 ] ) ) {
tol.b = ar[ 2 ];
}
if ( !isNaN( ar[ 3 ] ) ) {
tol.l = ar[ 3 ];
}
break;
default:
break;
}
}
this._tolerance = tol;
return this;
},
_clampPopupWidth: function( infoOnly ) {
var menuSize,
windowCoordinates = getWindowCoordinates( this.window ),
// rectangle within which the popup must fit
rectangle = {
x: this._tolerance.l,
y: windowCoordinates.y + this._tolerance.t,
cx: windowCoordinates.cx - this._tolerance.l - this._tolerance.r,
cy: windowCoordinates.cy - this._tolerance.t - this._tolerance.b
};
if ( !infoOnly ) {
// Clamp the width of the menu before grabbing its size
this._ui.container.css( "max-width", rectangle.cx );
}
menuSize = {
cx: this._ui.container.outerWidth( true ),
cy: this._ui.container.outerHeight( true )
};
return { rc: rectangle, menuSize: menuSize };
},
_calculateFinalLocation: function( desired, clampInfo ) {
var returnValue,
rectangle = clampInfo.rc,
menuSize = clampInfo.menuSize;
// Center the menu over the desired coordinates, while not going outside
// the window tolerances. This will center wrt. the window if the popup is
// too large.
returnValue = {
left: fitSegmentInsideSegment( rectangle.cx, menuSize.cx, rectangle.x, desired.x ),
top: fitSegmentInsideSegment( rectangle.cy, menuSize.cy, rectangle.y, desired.y )
};
// Make sure the top of the menu is visible
returnValue.top = Math.max( 0, returnValue.top );
// If the height of the menu is smaller than the height of the document
// align the bottom with the bottom of the document
returnValue.top -= Math.min( returnValue.top,
Math.max( 0, returnValue.top + menuSize.cy - this.document.height() ) );
return returnValue;
},
// Try and center the overlay over the given coordinates
_placementCoords: function( desired ) {
return this._calculateFinalLocation( desired, this._clampPopupWidth() );
},
_createPrerequisites: function( screenPrerequisite, containerPrerequisite, whenDone ) {
var prerequisites,
self = this;
// It is important to maintain both the local variable prerequisites and
// self._prerequisites. The local variable remains in the closure of the
// functions which call the callbacks passed in. The comparison between the
// local variable and self._prerequisites is necessary, because once a
// function has been passed to .animationComplete() it will be called next
// time an animation completes, even if that's not the animation whose end
// the function was supposed to catch (for example, if an abort happens
// during the opening animation, the .animationComplete handler is not
// called for that animation anymore, but the handler remains attached, so
// it is called the next time the popup is opened - making it stale.
// Comparing the local variable prerequisites to the widget-level variable
// self._prerequisites ensures that callbacks triggered by a stale
// .animationComplete will be ignored.
prerequisites = {
screen: $.Deferred(),
container: $.Deferred()
};
prerequisites.screen.then( function() {
if ( prerequisites === self._prerequisites ) {
screenPrerequisite();
}
});
prerequisites.container.then( function() {
if ( prerequisites === self._prerequisites ) {
containerPrerequisite();
}
});
$.when( prerequisites.screen, prerequisites.container ).done( function() {
if ( prerequisites === self._prerequisites ) {
self._prerequisites = null;
whenDone();
}
});
self._prerequisites = prerequisites;
},
_animate: function( args ) {
// NOTE before removing the default animation of the screen
// this had an animate callback that would resolve the deferred
// now the deferred is resolved immediately
// TODO remove the dependency on the screen deferred
this._ui.screen
.removeClass( args.classToRemove )
.addClass( args.screenClassToAdd );
args.prerequisites.screen.resolve();
if ( args.transition && args.transition !== "none" ) {
if ( args.applyTransition ) {
this._applyTransition( args.transition );
}
if ( this._fallbackTransition ) {
this._ui.container
.addClass( args.containerClassToAdd )
.removeClass( args.classToRemove )
.animationComplete( $.proxy( args.prerequisites.container, "resolve" ) );
return;
}
}
this._ui.container.removeClass( args.classToRemove );
args.prerequisites.container.resolve();
},
// The desired coordinates passed in will be returned untouched if no reference element can be identified via
// desiredPosition.positionTo. Nevertheless, this function ensures that its return value always contains valid
// x and y coordinates by specifying the center middle of the window if the coordinates are absent.
// options: { x: coordinate, y: coordinate, positionTo: string: "origin", "window", or jQuery selector
_desiredCoords: function( openOptions ) {
var offset,
dst = null,
windowCoordinates = getWindowCoordinates( this.window ),
x = openOptions.x,
y = openOptions.y,
pTo = openOptions.positionTo;
// Establish which element will serve as the reference
if ( pTo && pTo !== "origin" ) {
if ( pTo === "window" ) {
x = windowCoordinates.cx / 2 + windowCoordinates.x;
y = windowCoordinates.cy / 2 + windowCoordinates.y;
} else {
try {
dst = $( pTo );
} catch( err ) {
dst = null;
}
if ( dst ) {
dst.filter( ":visible" );
if ( dst.length === 0 ) {
dst = null;
}
}
}
}
// If an element was found, center over it
if ( dst ) {
offset = dst.offset();
x = offset.left + dst.outerWidth() / 2;
y = offset.top + dst.outerHeight() / 2;
}
// Make sure x and y are valid numbers - center over the window
if ( $.type( x ) !== "number" || isNaN( x ) ) {
x = windowCoordinates.cx / 2 + windowCoordinates.x;
}
if ( $.type( y ) !== "number" || isNaN( y ) ) {
y = windowCoordinates.cy / 2 + windowCoordinates.y;
}
return { x: x, y: y };
},
_reposition: function( openOptions ) {
// We only care about position-related parameters for repositioning
openOptions = {
x: openOptions.x,
y: openOptions.y,
positionTo: openOptions.positionTo
};
this._trigger( "beforeposition", undefined, openOptions );
this._ui.container.offset( this._placementCoords( this._desiredCoords( openOptions ) ) );
},
reposition: function( openOptions ) {
if ( this._isOpen ) {
this._reposition( openOptions );
}
},
_openPrerequisitesComplete: function() {
var id = this.element.attr( "id" );
this._ui.container.addClass( "ui-popup-active" );
this._isOpen = true;
this._resizeScreen();
this._ui.container.attr( "tabindex", "0" ).focus();
this._ignoreResizeEvents();
if ( id ) {
this.document.find( "[aria-haspopup='true'][aria-owns='" + id + "']" ).attr( "aria-expanded", true );
}
this._trigger( "afteropen" );
},
_open: function( options ) {
var openOptions = $.extend( {}, this.options, options ),
// TODO move blacklist to private method
androidBlacklist = ( function() {
var ua = navigator.userAgent,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9\.]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
androidmatch = ua.match( /Android (\d+(?:\.\d+))/ ),
andversion = !!androidmatch && androidmatch[ 1 ],
chromematch = ua.indexOf( "Chrome" ) > -1;
// Platform is Android, WebKit version is greater than 534.13 ( Android 3.2.1 ) and not Chrome.
if ( androidmatch !== null && andversion === "4.0" && wkversion && wkversion > 534.13 && !chromematch ) {
return true;
}
return false;
}());
// Count down to triggering "popupafteropen" - we have two prerequisites:
// 1. The popup window animation completes (container())
// 2. The screen opacity animation completes (screen())
this._createPrerequisites(
$.noop,
$.noop,
$.proxy( this, "_openPrerequisitesComplete" ) );
this._currentTransition = openOptions.transition;
this._applyTransition( openOptions.transition );
this._ui.screen.removeClass( "ui-screen-hidden" );
this._ui.container.removeClass( "ui-popup-truncate" );
// Give applications a chance to modify the contents of the container before it appears
this._reposition( openOptions );
this._ui.container.removeClass( "ui-popup-hidden" );
if ( this.options.overlayTheme && androidBlacklist ) {
/* TODO: The native browser on Android 4.0.X ("Ice Cream Sandwich") suffers from an issue where the popup overlay appears to be z-indexed above the popup itself when certain other styles exist on the same page -- namely, any element set to `position: fixed` and certain types of input. These issues are reminiscent of previously uncovered bugs in older versions of Android's native browser: https://github.com/scottjehl/Device-Bugs/issues/3
This fix closes the following bugs ( I use "closes" with reluctance, and stress that this issue should be revisited as soon as possible ):
https://github.com/jquery/jquery-mobile/issues/4816
https://github.com/jquery/jquery-mobile/issues/4844
https://github.com/jquery/jquery-mobile/issues/4874
*/
// TODO sort out why this._page isn't working
this.element.closest( ".ui-page" ).addClass( "ui-popup-open" );
}
this._animate({
additionalCondition: true,
transition: openOptions.transition,
classToRemove: "",
screenClassToAdd: "in",
containerClassToAdd: "in",
applyTransition: false,
prerequisites: this._prerequisites
});
},
_closePrerequisiteScreen: function() {
this._ui.screen
.removeClass( "out" )
.addClass( "ui-screen-hidden" );
},
_closePrerequisiteContainer: function() {
this._ui.container
.removeClass( "reverse out" )
.addClass( "ui-popup-hidden ui-popup-truncate" )
.removeAttr( "style" );
},
_closePrerequisitesDone: function() {
var container = this._ui.container,
id = this.element.attr( "id" );
container.removeAttr( "tabindex" );
// remove the global mutex for popups
$.mobile.popup.active = undefined;
// Blur elements inside the container, including the container
$( ":focus", container[ 0 ] ).add( container[ 0 ] ).blur();
if ( id ) {
this.document.find( "[aria-haspopup='true'][aria-owns='" + id + "']" ).attr( "aria-expanded", false );
}
// alert users that the popup is closed
this._trigger( "afterclose" );
},
_close: function( immediate ) {
this._ui.container.removeClass( "ui-popup-active" );
this._page.removeClass( "ui-popup-open" );
this._isOpen = false;
// Count down to triggering "popupafterclose" - we have two prerequisites:
// 1. The popup window reverse animation completes (container())
// 2. The screen opacity animation completes (screen())
this._createPrerequisites(
$.proxy( this, "_closePrerequisiteScreen" ),
$.proxy( this, "_closePrerequisiteContainer" ),
$.proxy( this, "_closePrerequisitesDone" ) );
this._animate( {
additionalCondition: this._ui.screen.hasClass( "in" ),
transition: ( immediate ? "none" : ( this._currentTransition ) ),
classToRemove: "in",
screenClassToAdd: "out",
containerClassToAdd: "reverse out",
applyTransition: true,
prerequisites: this._prerequisites
});
},
_unenhance: function() {
if ( this.options.enhanced ) {
return;
}
// Put the element back to where the placeholder was and remove the "ui-popup" class
this._setOptions( { theme: $.mobile.popup.prototype.options.theme } );
this.element
// Cannot directly insertAfter() - we need to detach() first, because
// insertAfter() will do nothing if the payload div was not attached
// to the DOM at the time the widget was created, and so the payload
// will remain inside the container even after we call insertAfter().
// If that happens and we remove the container a few lines below, we
// will cause an infinite recursion - #5244
.detach()
.insertAfter( this._ui.placeholder )
.removeClass( "ui-popup ui-overlay-shadow ui-corner-all ui-body-inherit" );
this._ui.screen.remove();
this._ui.container.remove();
this._ui.placeholder.remove();
},
_destroy: function() {
if ( $.mobile.popup.active === this ) {
this.element.one( "popupafterclose", $.proxy( this, "_unenhance" ) );
this.close();
} else {
this._unenhance();
}
return this;
},
_closePopup: function( theEvent, data ) {
var parsedDst, toUrl,
currentOptions = this.options,
immediate = false;
if ( ( theEvent && theEvent.isDefaultPrevented() ) || $.mobile.popup.active !== this ) {
return;
}
// restore location on screen
window.scrollTo( 0, this._scrollTop );
if ( theEvent && theEvent.type === "pagebeforechange" && data ) {
// Determine whether we need to rapid-close the popup, or whether we can
// take the time to run the closing transition
if ( typeof data.toPage === "string" ) {
parsedDst = data.toPage;
} else {
parsedDst = data.toPage.jqmData( "url" );
}
parsedDst = $.mobile.path.parseUrl( parsedDst );
toUrl = parsedDst.pathname + parsedDst.search + parsedDst.hash;
if ( this._myUrl !== $.mobile.path.makeUrlAbsolute( toUrl ) ) {
// Going to a different page - close immediately
immediate = true;
} else {
theEvent.preventDefault();
}
}
// remove nav bindings
this.window.off( currentOptions.closeEvents );
// unbind click handlers added when history is disabled
this.element.undelegate( currentOptions.closeLinkSelector, currentOptions.closeLinkEvents );
this._close( immediate );
},
// any navigation event after a popup is opened should close the popup
// NOTE the pagebeforechange is bound to catch navigation events that don't
// alter the url (eg, dialogs from popups)
_bindContainerClose: function() {
this.window
.on( this.options.closeEvents, $.proxy( this, "_closePopup" ) );
},
widget: function() {
return this._ui.container;
},
// TODO no clear deliniation of what should be here and
// what should be in _open. Seems to be "visual" vs "history" for now
open: function( options ) {
var url, hashkey, activePage, currentIsDialog, hasHash, urlHistory,
self = this,
currentOptions = this.options;
// make sure open is idempotent
if ( $.mobile.popup.active || currentOptions.disabled ) {
return this;
}
// set the global popup mutex
$.mobile.popup.active = this;
this._scrollTop = this.window.scrollTop();
// if history alteration is disabled close on navigate events
// and leave the url as is
if ( !( currentOptions.history ) ) {
self._open( options );
self._bindContainerClose();
// When histoy is disabled we have to grab the data-rel
// back link clicks so we can close the popup instead of
// relying on history to do it for us
self.element
.delegate( currentOptions.closeLinkSelector, currentOptions.closeLinkEvents, function( theEvent ) {
self.close();
theEvent.preventDefault();
});
return this;
}
// cache some values for min/readability
urlHistory = $.mobile.navigate.history;
hashkey = $.mobile.dialogHashKey;
activePage = $.mobile.activePage;
currentIsDialog = ( activePage ? activePage.hasClass( "ui-dialog" ) : false );
this._myUrl = url = urlHistory.getActive().url;
hasHash = ( url.indexOf( hashkey ) > -1 ) && !currentIsDialog && ( urlHistory.activeIndex > 0 );
if ( hasHash ) {
self._open( options );
self._bindContainerClose();
return this;
}
// if the current url has no dialog hash key proceed as normal
// otherwise, if the page is a dialog simply tack on the hash key
if ( url.indexOf( hashkey ) === -1 && !currentIsDialog ) {
url = url + (url.indexOf( "#" ) > -1 ? hashkey : "#" + hashkey);
} else {
url = $.mobile.path.parseLocation().hash + hashkey;
}
// Tack on an extra hashkey if this is the first page and we've just reconstructed the initial hash
if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) {
url += hashkey;
}
// swallow the the initial navigation event, and bind for the next
this.window.one( "beforenavigate", function( theEvent ) {
theEvent.preventDefault();
self._open( options );
self._bindContainerClose();
});
this.urlAltered = true;
$.mobile.navigate( url, { role: "dialog" } );
return this;
},
close: function() {
// make sure close is idempotent
if ( $.mobile.popup.active !== this ) {
return this;
}
this._scrollTop = this.window.scrollTop();
if ( this.options.history && this.urlAltered ) {
$.mobile.back();
this.urlAltered = false;
} else {
// simulate the nav bindings having fired
this._closePopup();
}
return this;
}
});
// TODO this can be moved inside the widget
$.mobile.popup.handleLink = function( $link ) {
var offset,
path = $.mobile.path,
// NOTE make sure to get only the hash from the href because ie7 (wp7)
// returns the absolute href in this case ruining the element selection
popup = $( path.hashToSelector( path.parseUrl( $link.attr( "href" ) ).hash ) ).first();
if ( popup.length > 0 && popup.data( "mobile-popup" ) ) {
offset = $link.offset();
popup.popup( "open", {
x: offset.left + $link.outerWidth() / 2,
y: offset.top + $link.outerHeight() / 2,
transition: $link.jqmData( "transition" ),
positionTo: $link.jqmData( "position-to" )
});
}
//remove after delay
setTimeout( function() {
$link.removeClass( $.mobile.activeBtnClass );
}, 300 );
};
// TODO move inside _create
$.mobile.document.on( "pagebeforechange", function( theEvent, data ) {
if ( data.options.role === "popup" ) {
$.mobile.popup.handleLink( data.options.link );
theEvent.preventDefault();
}
});
})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
| hinaloe/jqm-demo-ja | js/widgets/popup.js | JavaScript | mit | 30,374 |
/**
* version: 1.1.10
*/
angular.module('ngWig', ['ngwig-app-templates']);
angular.module('ngWig')
.directive('ngWig', function () {
return {
scope: {
content: '=ngWig'
},
restrict: 'A',
replace: true,
templateUrl: 'ng-wig/views/ng-wig.html',
link: function (scope, element, attrs) {
scope.editMode = false;
scope.autoexpand = !('autoexpand' in attrs) || attrs['autoexpand'] !== 'off';
scope.toggleEditMode = function () {
scope.editMode = !scope.editMode;
};
scope.execCommand = function (command, options) {
if (command === 'createlink') {
options = prompt('Please enter the URL', 'http://');
}
if (command === 'insertimage') {
options = prompt('Please enter an image URL to insert', 'http://');
}
if (options !== null) {
scope.$emit('execCommand', {command: command, options: options});
}
};
scope.styles = [
{name: 'Normal text', value: 'p'},
{name: 'Header 1', value: 'h1'},
{name: 'Header 2', value: 'h2'},
{name: 'Header 3', value: 'h3'}
];
scope.style = scope.styles[0];
scope.$on("colorpicker-selected", function ($event, color) {
scope.execCommand('foreColor', color.value);
});
}
}
});
angular.module('ngWig')
.directive('ngWigEditable', function () {
function init(scope, $element, attrs, ctrl) {
var document = $element[0].ownerDocument;
$element.attr('contenteditable', true);
//model --> view
ctrl.$render = function () {
$element.html(ctrl.$viewValue || '');
};
//view --> model
function viewToModel() {
ctrl.$setViewValue($element.html());
//to support Angular 1.2.x
if (angular.version.minor < 3) {
scope.$apply();
}
}
$element.bind('blur keyup change paste', viewToModel);
scope.$on('execCommand', function (event, params) {
$element[0].focus();
var ieStyleTextSelection = document.selection,
command = params.command,
options = params.options;
if (ieStyleTextSelection) {
var textRange = ieStyleTextSelection.createRange();
}
document.execCommand(command, false, options);
if (ieStyleTextSelection) {
textRange.collapse(false);
textRange.select();
}
viewToModel();
});
}
return {
restrict: 'A',
require: 'ngModel',
replace: true,
link: init
}
}
);
angular.module('ngwig-app-templates', ['ng-wig/views/ng-wig.html']);
angular.module("ng-wig/views/ng-wig.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("ng-wig/views/ng-wig.html",
"<div class=\"ng-wig\">\n" +
" <ul class=\"nw-toolbar\">\n" +
" <li class=\"nw-toolbar__item\">\n" +
" <select class=\"nw-select\" ng-model=\"style\" ng-change=\"execCommand('formatblock', style.value)\" ng-options=\"style.name for style in styles\">\n" +
" </select>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--unordered-list\" title=\"Unordered List\" ng-click=\"execCommand('insertunorderedlist')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--ordered-list\" title=\"Ordered List\" ng-click=\"execCommand('insertorderedlist')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--bold\" title=\"Bold\" ng-click=\"execCommand('bold')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--italic\" title=\"Italic\" ng-click=\"execCommand('italic')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button colorpicker ng-model=\"fontcolor\" class=\"nw-button nw-button--text-color\" title=\"Font Color\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--link\" title=\"link\" ng-click=\"execCommand('createlink')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--image\" title=\"image\" ng-click=\"execCommand('insertimage')\"></button>\n" +
" </li><!--\n" +
" --><li class=\"nw-toolbar__item\">\n" +
" <button type=\"button\" class=\"nw-button nw-button--source\" ng-class=\"{ 'nw-button--active': editMode }\" ng-click=\"toggleEditMode()\"></button>\n" +
" </li>\n" +
" </ul>\n" +
"\n" +
" <div class=\"nw-editor-container\">\n" +
" <div class=\"nw-editor\">\n" +
" <textarea class=\"nw-editor__src\" ng-show=\"editMode\" ng-model=\"content\"></textarea>\n" +
" <div ng-class=\"{'nw-invisible': editMode, 'nw-autoexpand': autoexpand}\" class=\"nw-editor__res\" ng-model=\"content\" ng-wig-editable></div>\n" +
" </div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
| lenstr/ngWig | dist/ng-wig.js | JavaScript | mit | 5,442 |
/**
* main.js: The entry point for MuTube.
* Plays the role of the 'main process' in Electron.
*/
// define constants from various packages for the main process
const {
app,
BrowserWindow,
ipcMain
} = require('electron');
let mainWindow;
// execute the application
app.on('ready', () => {
// create the main broswer window with the following array values
mainWindow = new BrowserWindow({
title: "MuTube",
width: 600,
height: 600,
minWidth: 600,
minHeight: 600,
center: true,
backgroundColor: "#181818",
// mainly for Linux-based OSes running GTK
darkTheme: true,
// only for macOS when scrolling passed the beginning and ends of page
scrollBounce: true
});
// remove the menu bar
mainWindow.setMenu(null);
// load broswer window content
mainWindow.loadURL('file://' + __dirname + '/html/index.html');
});
// when ipc receives signal, 'toggleDevTools', from renderer
ipcMain.on('toggleDevTools', function() {
if (mainWindow.isDevToolsOpened()) {
mainWindow.closeDevTools();
} else {
mainWindow.openDevTools({
mode: 'detach'
});
}
});
| lenku/mu-tube | main.js | JavaScript | mit | 1,217 |
/*global Backbone */
var Generator = Generator || {};
(function () {
'use strict';
// Aspect Model
// ----------
Generator.Aspect = Backbone.Model.extend({
defaults: {
result: 0,
text: ''
}
});
})();
| amsross/random-sword-sorcery-adventure-generator | assets/js/models/aspect.js | JavaScript | mit | 218 |
version https://git-lfs.github.com/spec/v1
oid sha256:4fc049501415815d5fa555bc735c359c381441d2107851b32b30ae5ba192a892
size 11548
| yogeshsaroya/new-cdnjs | ajax/libs/wow/0.1.12/wow.js | JavaScript | mit | 130 |
function Loader() {
var self = this;
self.cache = {}; // Filename -> {Geometry, Material, [callbacks]}
self.textureCache = {}; // Filename -> Texture
self.loader = new THREE.JSONLoader();
}
Loader.prototype.loadTexture = function(filename, callback) {
var self = this;
var texture = self.textureCache[filename];
if(texture === undefined) {
texture = THREE.ImageUtils.loadTexture(filename, undefined, callback);
self.textureCache[filename] = texture;
}
return texture;
};
Loader.prototype.loadTextureCube = function(filenames, callback) {
var self = this;
var filename = filenames[0]; // Use the first texture as the lookup name
var texture = self.textureCache[filename];
if(texture === undefined) {
texture = THREE.ImageUtils.loadTextureCube(filenames, undefined, callback);
self.textureCache[filename] = texture;
} else {
callback(texture);
}
};
Loader.prototype.loadMesh = function(filename, callback) {
var self = this;
// Don't worry about texture caching because ThreeJS caches all loaded images
// and material.clone creates shallow copies of textures.
var cacheData = self.cache[filename];
if(cacheData === undefined) {
// Not found in cache, load now
// Add initial entry to cache
var cacheData = {
loaded: false,
geometry: null,
material: null,
callbacks: []
};
self.cache[filename] = cacheData;
// Load the json file
self.loader.load(filename, function(geometry, materials) {
// Finished loading
// Update the cache
var material = self.createMaterial(materials);
cacheData.geometry = geometry;
cacheData.material = material;
cacheData.loaded = true;
// Call the callback on this
callback(geometry, self.cloneMaterial(material));
// Call the callbacks for all other objects created before this finished loading
for(var i = 0; i < cacheData.callbacks.length; i++) {
var callbackCached = cacheData.callbacks[i];
callbackCached(geometry, self.cloneMaterial(material));
}
});
} else {
// Check if the cache data is loaded. If not add the callback
if(cacheData.loaded) {
var geometry = cacheData.geometry;
var material = self.cloneMaterial(cacheData.material);
callback(geometry, material);
} else {
cacheData.callbacks.push(callback);
}
}
};
Loader.prototype.createMaterial = function(materials) {
var meshMaterial;
if(materials === undefined){
meshMaterial = new THREE.MeshLambertMaterial();
materials = [meshMaterial];
}
else if(materials.length == 1) meshMaterial = materials[0];
else meshMaterial = new THREE.MeshFaceMaterial(materials);
// Fix materials
for(var i = 0; i < materials.length; i++) {
var material = materials[i];
if(material.map) {
material.map.wrapS = material.map.wrapT = THREE.RepeatWrapping; // Set repeat wrapping
//if(material.transparent) material.opacity = 1.0; // If transparent and it has a texture, set opacity to 1.0
}
if(material.transparent) {
material.depthWrite = false;
//material.side = THREE.DoubleSide;
material.side = THREE.FrontSide;
} else {
material.side = THREE.FrontSide;
}
// For editor purposes
material.transparentOld = material.transparent;
material.opacityOld = material.opacity;
}
return meshMaterial;
};
Loader.prototype.cloneMaterial = function(material) {
var newMaterial = material.clone();
newMaterial.transparentOld = material.transparentOld;
newMaterial.opacityOld = material.opacityOld;
return newMaterial;
};
Loader.prototype.dispose = function() {
// Not really necessary to call this function since the memory will be reused elsewhere
var self = this;
// Dispose geometries
var geometryKeys = Object.keys(self.geometryCache);
for(var i = 0; i < geometryKeys.length; i++) {
var key = geometryKeys[i];
var geometry = self.geometryCache[key];
geometry.dispose();
}
self.geometryCache = {};
// Dispose materials
// No listeners are attached in the ThreeJS source, so this doesn't do anything
var materialKeys = Object.keys(self.materialCache);
for(var i = 0; i < materialKeys.length; i++) {
var key = materialKeys[i];
var material = self.matericalCache[key];
var materials = Util.getMaterials(material); // Get all the materials in the material (e.g. MeshFaceMaterial)
for(var j = 0; j < materials.length; j++) {
var material = materials[j];
material.dispose();
}
}
self.materialCache = {};
// TO-DO: Dispose textures.
// Find all the textures on all the materials
// or go directly to WebGLTextures.js and manually delete there
};
| PhiladelphiaGameLab/Flip | js/util/Loader.js | JavaScript | mit | 5,180 |
import header from 'head';
class Loader {
constructor () {
// Singleton Object
if(window.CM == null){
window.CM = {};
}
window.CM.Loader = this;
let scope = this;
head.ready(document, function() {
head.load([ "/assets/css/app.css",
"/assets/js/app.js",
"/assets/js/shim.js",
"//fast.fonts.com/cssapi/6536d2ad-a624-4b33-9405-4c303cfb6253.css"
], CM.Loader.startApplication);
});
}
removeGFX (){
document.body.setAttribute("class", document.body.getAttribute("class").split("hideloader").join("run"));
CM.App.showPage();
let preloader = document.getElementsByClassName("preloader")[0];
if(preloader && preloader.parentNode){
preloader.parentNode.removeChild(preloader);
}
}
startApplication (){
if(window.CM.App == undefined){
setTimeout(CM.Loader.startApplication, 500);
} else {
CM.App.blastoff();
document.body.setAttribute("class", document.body.getAttribute("class").split("loading").join("loaded") );
setTimeout(function(){
document.body.setAttribute("class", document.body.getAttribute("class").split("loaded").join("hideloader") );
}, 500);
setTimeout(function(){ CM.Loader.removeGFX(); }, 1750);
}
}
};
export default new Loader();
| youonlyliveonce/24-1 | src/javascript/loader.js | JavaScript | mit | 1,256 |
/* ajax_windows.js. Support for modal popup windows in Umlaut items. */
jQuery(document).ready(function($) {
var populate_modal = function(data, textStatus, jqXHR) {
// Wrap the data object in jquery object
var body = $("<div/>").html(data);
// Remove the first heading from the returned data
var header = body.find("h1, h2, h3, h4, h5, h6").eq(0).remove();
// Remove the first submit button from the returned data
var footer = body.find("form").find("input[type=submit]").eq(0).remove();
// Add in content
if (header) $("#modal").find("[data-role=modal-title-content]").text(header.text());
if (body) $("#modal").find("[data-role=modal-body-content]").html(body.html());
if (footer) $("#modal").find("[data-role=modal-footer-content]").html(footer);
// Toggle the ajax-loader
$("#modal").find(".ajax-loader").hide();
}
var cleanup_modal = function() {
$("#modal").find("[data-role=modal-title-content]").text('');
$("#modal").find("[data-role=modal-body-content]").text('');
$("#modal").find("[data-role=modal-footer-content]").text('');
$("#modal").find(".ajax-loader").hide();
}
var display_modal = function(event) {
event.preventDefault();
cleanup_modal();
$("#modal").find(".ajax-loader").show();
$("#modal").modal("show");
$.get(this.href, "", populate_modal, "html");
}
var ajax_form_catch = function(event) {
event.preventDefault();
$("#modal").find(".ajax-loader").show();
var form = $("#modal").find("form");
$.post(form.attr("action"), form.serialize(), populate_modal, "html");
cleanup_modal();
};
$(document).on("click", "a.ajax_window", display_modal);
$(document).on("click", "#modal .modal-footer input[type=submit]", ajax_form_catch);
$(document).on("submit", "#modal form", ajax_form_catch);
}); | team-umlaut/umlaut | app/assets/javascripts/umlaut/ajax_windows.js | JavaScript | mit | 1,854 |
'use strict';
moduloCategoria.factory('categoriaService', ['serverService', function (serverService) {
return {
getFields: function () {
return [
{name: "id", shortname: "ID", longname: "Identificador", visible: true, type: "id"},
{name: "nombre", shortname: "Nombre", longname: "Nombre", visible: true, type: "text", required: true,pattern: serverService.getRegExpr("alpha-numeric"), help: serverService.getRegExpl("alpha-numeric")},
];
},
getIcon: function () {
return "fa-tags";
},
getObTitle: function () {
return "categoria";
},
getTitle: function () {
return "categoria";
}
};
}]);
| Samyfos/Facturacion-Samuel | public_html/js/categoria/service.js | JavaScript | mit | 826 |
var NAVTREE =
[
[ "game_of_life", "index.html", [
[ "game_of_life", "md__r_e_a_d_m_e.html", null ],
[ "Classes", null, [
[ "Class List", "annotated.html", "annotated" ],
[ "Class Index", "classes.html", null ],
[ "Class Members", "functions.html", [
[ "All", "functions.html", null ],
[ "Functions", "functions_func.html", null ]
] ]
] ],
[ "Files", null, [
[ "File List", "files.html", "files" ],
[ "File Members", "globals.html", [
[ "All", "globals.html", null ],
[ "Functions", "globals_func.html", null ],
[ "Variables", "globals_vars.html", null ]
] ]
] ]
] ]
];
var NAVTREEINDEX =
[
"annotated.html"
];
var SYNCONMSG = 'click to disable panel synchronisation';
var SYNCOFFMSG = 'click to enable panel synchronisation';
var navTreeSubIndices = new Array();
function getData(varName)
{
var i = varName.lastIndexOf('/');
var n = i>=0 ? varName.substring(i+1) : varName;
return eval(n.replace(/\-/g,'_'));
}
function stripPath(uri)
{
return uri.substring(uri.lastIndexOf('/')+1);
}
function stripPath2(uri)
{
var i = uri.lastIndexOf('/');
var s = uri.substring(i+1);
var m = uri.substring(0,i+1).match(/\/d\w\/d\w\w\/$/);
return m ? uri.substring(i-6) : s;
}
function localStorageSupported()
{
try {
return 'localStorage' in window && window['localStorage'] !== null && window.localStorage.getItem;
}
catch(e) {
return false;
}
}
function storeLink(link)
{
if (!$("#nav-sync").hasClass('sync') && localStorageSupported()) {
window.localStorage.setItem('navpath',link);
}
}
function deleteLink()
{
if (localStorageSupported()) {
window.localStorage.setItem('navpath','');
}
}
function cachedLink()
{
if (localStorageSupported()) {
return window.localStorage.getItem('navpath');
} else {
return '';
}
}
function getScript(scriptName,func,show)
{
var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.id = scriptName;
script.type = 'text/javascript';
script.onload = func;
script.src = scriptName+'.js';
if ($.browser.msie && $.browser.version<=8) {
// script.onload does not work with older versions of IE
script.onreadystatechange = function() {
if (script.readyState=='complete' || script.readyState=='loaded') {
func(); if (show) showRoot();
}
}
}
head.appendChild(script);
}
function createIndent(o,domNode,node,level)
{
var level=-1;
var n = node;
while (n.parentNode) { level++; n=n.parentNode; }
var imgNode = document.createElement("img");
imgNode.style.paddingLeft=(16*level).toString()+'px';
imgNode.width = 16;
imgNode.height = 22;
imgNode.border = 0;
if (node.childrenData) {
node.plus_img = imgNode;
node.expandToggle = document.createElement("a");
node.expandToggle.href = "javascript:void(0)";
node.expandToggle.onclick = function() {
if (node.expanded) {
$(node.getChildrenUL()).slideUp("fast");
node.plus_img.src = node.relpath+"ftv2pnode.png";
node.expanded = false;
} else {
expandNode(o, node, false, false);
}
}
node.expandToggle.appendChild(imgNode);
domNode.appendChild(node.expandToggle);
imgNode.src = node.relpath+"ftv2pnode.png";
} else {
imgNode.src = node.relpath+"ftv2node.png";
domNode.appendChild(imgNode);
}
}
var animationInProgress = false;
function gotoAnchor(anchor,aname,updateLocation)
{
var pos, docContent = $('#doc-content');
if (anchor.parent().attr('class')=='memItemLeft' ||
anchor.parent().attr('class')=='fieldtype' ||
anchor.parent().is(':header'))
{
pos = anchor.parent().position().top;
} else if (anchor.position()) {
pos = anchor.position().top;
}
if (pos) {
var dist = Math.abs(Math.min(
pos-docContent.offset().top,
docContent[0].scrollHeight-
docContent.height()-docContent.scrollTop()));
animationInProgress=true;
docContent.animate({
scrollTop: pos + docContent.scrollTop() - docContent.offset().top
},Math.max(50,Math.min(500,dist)),function(){
if (updateLocation) window.location.href=aname;
animationInProgress=false;
});
}
}
function newNode(o, po, text, link, childrenData, lastNode)
{
var node = new Object();
node.children = Array();
node.childrenData = childrenData;
node.depth = po.depth + 1;
node.relpath = po.relpath;
node.isLast = lastNode;
node.li = document.createElement("li");
po.getChildrenUL().appendChild(node.li);
node.parentNode = po;
node.itemDiv = document.createElement("div");
node.itemDiv.className = "item";
node.labelSpan = document.createElement("span");
node.labelSpan.className = "label";
createIndent(o,node.itemDiv,node,0);
node.itemDiv.appendChild(node.labelSpan);
node.li.appendChild(node.itemDiv);
var a = document.createElement("a");
node.labelSpan.appendChild(a);
node.label = document.createTextNode(text);
node.expanded = false;
a.appendChild(node.label);
if (link) {
var url;
if (link.substring(0,1)=='^') {
url = link.substring(1);
link = url;
} else {
url = node.relpath+link;
}
a.className = stripPath(link.replace('#',':'));
if (link.indexOf('#')!=-1) {
var aname = '#'+link.split('#')[1];
var srcPage = stripPath($(location).attr('pathname'));
var targetPage = stripPath(link.split('#')[0]);
a.href = srcPage!=targetPage ? url : "javascript:void(0)";
a.onclick = function(){
storeLink(link);
if (!$(a).parent().parent().hasClass('selected'))
{
$('.item').removeClass('selected');
$('.item').removeAttr('id');
$(a).parent().parent().addClass('selected');
$(a).parent().parent().attr('id','selected');
}
var anchor = $(aname);
gotoAnchor(anchor,aname,true);
};
} else {
a.href = url;
a.onclick = function() { storeLink(link); }
}
} else {
if (childrenData != null)
{
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expandToggle.onclick;
}
}
node.childrenUL = null;
node.getChildrenUL = function() {
if (!node.childrenUL) {
node.childrenUL = document.createElement("ul");
node.childrenUL.className = "children_ul";
node.childrenUL.style.display = "none";
node.li.appendChild(node.childrenUL);
}
return node.childrenUL;
};
return node;
}
function showRoot()
{
var headerHeight = $("#top").height();
var footerHeight = $("#nav-path").height();
var windowHeight = $(window).height() - headerHeight - footerHeight;
(function (){ // retry until we can scroll to the selected item
try {
var navtree=$('#nav-tree');
navtree.scrollTo('#selected',0,{offset:-windowHeight/2});
} catch (err) {
setTimeout(arguments.callee, 0);
}
})();
}
function expandNode(o, node, imm, showRoot)
{
if (node.childrenData && !node.expanded) {
if (typeof(node.childrenData)==='string') {
var varName = node.childrenData;
getScript(node.relpath+varName,function(){
node.childrenData = getData(varName);
expandNode(o, node, imm, showRoot);
}, showRoot);
} else {
if (!node.childrenVisited) {
getNode(o, node);
} if (imm || ($.browser.msie && $.browser.version>8)) {
// somehow slideDown jumps to the start of tree for IE9 :-(
$(node.getChildrenUL()).show();
} else {
$(node.getChildrenUL()).slideDown("fast");
}
if (node.isLast) {
node.plus_img.src = node.relpath+"ftv2mlastnode.png";
} else {
node.plus_img.src = node.relpath+"ftv2mnode.png";
}
node.expanded = true;
}
}
}
function glowEffect(n,duration)
{
n.addClass('glow').delay(duration).queue(function(next){
$(this).removeClass('glow');next();
});
}
function highlightAnchor()
{
var aname = $(location).attr('hash');
var anchor = $(aname);
if (anchor.parent().attr('class')=='memItemLeft'){
var rows = $('.memberdecls tr[class$="'+
window.location.hash.substring(1)+'"]');
glowEffect(rows.children(),300); // member without details
} else if (anchor.parents().slice(2).prop('tagName')=='TR') {
glowEffect(anchor.parents('div.memitem'),1000); // enum value
} else if (anchor.parent().attr('class')=='fieldtype'){
glowEffect(anchor.parent().parent(),1000); // struct field
} else if (anchor.parent().is(":header")) {
glowEffect(anchor.parent(),1000); // section header
} else {
glowEffect(anchor.next(),1000); // normal member
}
gotoAnchor(anchor,aname,false);
}
function selectAndHighlight(hash,n)
{
var a;
if (hash) {
var link=stripPath($(location).attr('pathname'))+':'+hash.substring(1);
a=$('.item a[class$="'+link+'"]');
}
if (a && a.length) {
a.parent().parent().addClass('selected');
a.parent().parent().attr('id','selected');
highlightAnchor();
} else if (n) {
$(n.itemDiv).addClass('selected');
$(n.itemDiv).attr('id','selected');
}
if ($('#nav-tree-contents .item:first').hasClass('selected')) {
$('#nav-sync').css('top','30px');
} else {
$('#nav-sync').css('top','5px');
}
showRoot();
}
function showNode(o, node, index, hash)
{
if (node && node.childrenData) {
if (typeof(node.childrenData)==='string') {
var varName = node.childrenData;
getScript(node.relpath+varName,function(){
node.childrenData = getData(varName);
showNode(o,node,index,hash);
},true);
} else {
if (!node.childrenVisited) {
getNode(o, node);
}
$(node.getChildrenUL()).show();
if (node.isLast) {
node.plus_img.src = node.relpath+"ftv2mlastnode.png";
} else {
node.plus_img.src = node.relpath+"ftv2mnode.png";
}
node.expanded = true;
var n = node.children[o.breadcrumbs[index]];
if (index+1<o.breadcrumbs.length) {
showNode(o,n,index+1,hash);
} else {
if (typeof(n.childrenData)==='string') {
var varName = n.childrenData;
getScript(n.relpath+varName,function(){
n.childrenData = getData(varName);
node.expanded=false;
showNode(o,node,index,hash); // retry with child node expanded
},true);
} else {
var rootBase = stripPath(o.toroot.replace(/\..+$/, ''));
if (rootBase=="index" || rootBase=="pages" || rootBase=="search") {
expandNode(o, n, true, true);
}
selectAndHighlight(hash,n);
}
}
}
} else {
selectAndHighlight(hash);
}
}
function getNode(o, po)
{
po.childrenVisited = true;
var l = po.childrenData.length-1;
for (var i in po.childrenData) {
var nodeData = po.childrenData[i];
po.children[i] = newNode(o, po, nodeData[0], nodeData[1], nodeData[2],
i==l);
}
}
function gotoNode(o,subIndex,root,hash,relpath)
{
var nti = navTreeSubIndices[subIndex][root+hash];
o.breadcrumbs = $.extend(true, [], nti ? nti : navTreeSubIndices[subIndex][root]);
if (!o.breadcrumbs && root!=NAVTREE[0][1]) { // fallback: show index
navTo(o,NAVTREE[0][1],"",relpath);
$('.item').removeClass('selected');
$('.item').removeAttr('id');
}
if (o.breadcrumbs) {
o.breadcrumbs.unshift(0); // add 0 for root node
showNode(o, o.node, 0, hash);
}
}
function navTo(o,root,hash,relpath)
{
var link = cachedLink();
if (link) {
var parts = link.split('#');
root = parts[0];
if (parts.length>1) hash = '#'+parts[1];
else hash='';
}
if (hash.match(/^#l\d+$/)) {
var anchor=$('a[name='+hash.substring(1)+']');
glowEffect(anchor.parent(),1000); // line number
hash=''; // strip line number anchors
//root=root.replace(/_source\./,'.'); // source link to doc link
}
var url=root+hash;
var i=-1;
while (NAVTREEINDEX[i+1]<=url) i++;
if (i==-1) { i=0; root=NAVTREE[0][1]; } // fallback: show index
if (navTreeSubIndices[i]) {
gotoNode(o,i,root,hash,relpath)
} else {
getScript(relpath+'navtreeindex'+i,function(){
navTreeSubIndices[i] = eval('NAVTREEINDEX'+i);
if (navTreeSubIndices[i]) {
gotoNode(o,i,root,hash,relpath);
}
},true);
}
}
function showSyncOff(n,relpath)
{
n.html('<img src="'+relpath+'sync_off.png" title="'+SYNCOFFMSG+'"/>');
}
function showSyncOn(n,relpath)
{
n.html('<img src="'+relpath+'sync_on.png" title="'+SYNCONMSG+'"/>');
}
function toggleSyncButton(relpath)
{
var navSync = $('#nav-sync');
if (navSync.hasClass('sync')) {
navSync.removeClass('sync');
showSyncOff(navSync,relpath);
storeLink(stripPath2($(location).attr('pathname'))+$(location).attr('hash'));
} else {
navSync.addClass('sync');
showSyncOn(navSync,relpath);
deleteLink();
}
}
function initNavTree(toroot,relpath)
{
var o = new Object();
o.toroot = toroot;
o.node = new Object();
o.node.li = document.getElementById("nav-tree-contents");
o.node.childrenData = NAVTREE;
o.node.children = new Array();
o.node.childrenUL = document.createElement("ul");
o.node.getChildrenUL = function() { return o.node.childrenUL; };
o.node.li.appendChild(o.node.childrenUL);
o.node.depth = 0;
o.node.relpath = relpath;
o.node.expanded = false;
o.node.isLast = true;
o.node.plus_img = document.createElement("img");
o.node.plus_img.src = relpath+"ftv2pnode.png";
o.node.plus_img.width = 16;
o.node.plus_img.height = 22;
if (localStorageSupported()) {
var navSync = $('#nav-sync');
if (cachedLink()) {
showSyncOff(navSync,relpath);
navSync.removeClass('sync');
} else {
showSyncOn(navSync,relpath);
}
navSync.click(function(){ toggleSyncButton(relpath); });
}
navTo(o,toroot,window.location.hash,relpath);
$(window).bind('hashchange', function(){
if (window.location.hash && window.location.hash.length>1){
var a;
if ($(location).attr('hash')){
var clslink=stripPath($(location).attr('pathname'))+':'+
$(location).attr('hash').substring(1);
a=$('.item a[class$="'+clslink+'"]');
}
if (a==null || !$(a).parent().parent().hasClass('selected')){
$('.item').removeClass('selected');
$('.item').removeAttr('id');
}
var link=stripPath2($(location).attr('pathname'));
navTo(o,link,$(location).attr('hash'),relpath);
} else if (!animationInProgress) {
$('#doc-content').scrollTop(0);
$('.item').removeClass('selected');
$('.item').removeAttr('id');
navTo(o,toroot,window.location.hash,relpath);
}
})
$(window).load(showRoot);
}
| cpowell/game_of_life | html/navtree.js | JavaScript | mit | 14,888 |
var ConfigInitializer = {
name: 'config',
initialize: function (container, application) {
var apps = $('body').data('apps'),
tagsUI = $('body').data('tagsui'),
fileStorage = $('body').data('filestorage'),
blogUrl = $('body').data('blogurl'),
blogTitle = $('body').data('blogtitle');
application.register(
'ghost:config', {apps: apps, fileStorage: fileStorage, blogUrl: blogUrl, tagsUI: tagsUI, blogTitle: blogTitle}, {instantiate: false}
);
application.inject('route', 'config', 'ghost:config');
application.inject('controller', 'config', 'ghost:config');
application.inject('component', 'config', 'ghost:config');
}
};
export default ConfigInitializer;
| Aaron1992/Ghost | core/client/initializers/ghost-config.js | JavaScript | mit | 778 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
var u = undefined;
function plural(n) {
var i = Math.floor(Math.abs(n));
if (i === 0 || i === 1) return 1;
return 5;
}
global.ng.common.locales['fr-vu'] = [
'fr-VU',
[['AM', 'PM'], u, u],
u,
[
['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
['di', 'lu', 'ma', 'me', 'je', 've', 'sa']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.',
'déc.'
],
[
'janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre',
'octobre', 'novembre', 'décembre'
]
],
u,
[['av. J.-C.', 'ap. J.-C.'], u, ['avant Jésus-Christ', 'après Jésus-Christ']],
1,
[6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
['{1} {0}', '{1} \'à\' {0}', u, u],
[',', '\u202f', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'],
'VUV',
'VT',
'vatu vanuatuan',
{
'ARS': ['$AR', '$'],
'AUD': ['$AU', '$'],
'BEF': ['FB'],
'BMD': ['$BM', '$'],
'BND': ['$BN', '$'],
'BZD': ['$BZ', '$'],
'CAD': ['$CA', '$'],
'CLP': ['$CL', '$'],
'CNY': [u, '¥'],
'COP': ['$CO', '$'],
'CYP': ['£CY'],
'EGP': [u, '£E'],
'FJD': ['$FJ', '$'],
'FKP': ['£FK', '£'],
'FRF': ['F'],
'GBP': ['£GB', '£'],
'GIP': ['£GI', '£'],
'HKD': [u, '$'],
'IEP': ['£IE'],
'ILP': ['£IL'],
'ITL': ['₤IT'],
'JPY': [u, '¥'],
'KMF': [u, 'FC'],
'LBP': ['£LB', '£L'],
'MTP': ['£MT'],
'MXN': ['$MX', '$'],
'NAD': ['$NA', '$'],
'NIO': [u, '$C'],
'NZD': ['$NZ', '$'],
'RHD': ['$RH'],
'RON': [u, 'L'],
'RWF': [u, 'FR'],
'SBD': ['$SB', '$'],
'SGD': ['$SG', '$'],
'SRD': ['$SR', '$'],
'TOP': [u, '$T'],
'TTD': ['$TT', '$'],
'TWD': [u, 'NT$'],
'USD': ['$US', '$'],
'UYU': ['$UY', '$'],
'VUV': ['VT'],
'WST': ['$WS'],
'XCD': [u, '$'],
'XPF': ['FCFP'],
'ZMW': [u, 'Kw']
},
'ltr',
plural,
[
[
['minuit', 'midi', 'mat.', 'ap.m.', 'soir', 'nuit'], u,
['minuit', 'midi', 'du matin', 'de l’après-midi', 'du soir', 'du matin']
],
[
['minuit', 'midi', 'mat.', 'ap.m.', 'soir', 'nuit'], u,
['minuit', 'midi', 'matin', 'après-midi', 'soir', 'nuit']
],
[
'00:00', '12:00', ['04:00', '12:00'], ['12:00', '18:00'], ['18:00', '24:00'],
['00:00', '04:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
| matsko/angular | packages/common/locales/global/fr-VU.js | JavaScript | mit | 3,514 |
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2012, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/logiql', ['require', 'exports', 'module', 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/logiql_highlight_rules', 'ace/mode/folding/coffee', 'ace/token_iterator', 'ace/range', 'ace/mode/behaviour/cstyle', 'ace/mode/matching_brace_outdent'], function (require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var LogiQLHighlightRules = require("./logiql_highlight_rules").LogiQLHighlightRules;
var FoldMode = require("./folding/coffee").FoldMode;
var TokenIterator = require("../token_iterator").TokenIterator;
var Range = require("../range").Range;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Mode = function Mode() {
this.HighlightRules = LogiQLHighlightRules;
this.foldingRules = new FoldMode();
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
};
oop.inherits(Mode, TextMode);
(function () {
this.lineCommentStart = "//";
this.blockComment = { start: "/*", end: "*/" };
this.getNextLineIndent = function (state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (/comment|string/.test(endState)) return indent;
if (tokens.length && tokens[tokens.length - 1].type == "comment.single") return indent;
var match = line.match();
if (/(-->|<--|<-|->|{)\s*$/.test(line)) indent += tab;
return indent;
};
this.checkOutdent = function (state, line, input) {
if (this.$outdent.checkOutdent(line, input)) return true;
if (input !== "\n" && input !== "\r\n") return false;
if (!/^\s+/.test(line)) return false;
return true;
};
this.autoOutdent = function (state, doc, row) {
if (this.$outdent.autoOutdent(doc, row)) return;
var prevLine = doc.getLine(row);
var match = prevLine.match(/^\s+/);
var column = prevLine.lastIndexOf(".") + 1;
if (!match || !row || !column) return 0;
var line = doc.getLine(row + 1);
var startRange = this.getMatching(doc, { row: row, column: column });
if (!startRange || startRange.start.row == row) return 0;
column = match[0].length;
var indent = this.$getIndent(doc.getLine(startRange.start.row));
doc.replace(new Range(row + 1, 0, row + 1, column), indent);
};
this.getMatching = function (session, row, column) {
if (row == undefined) row = session.selection.lead;
if ((typeof row === 'undefined' ? 'undefined' : _typeof(row)) == "object") {
column = row.column;
row = row.row;
}
var startToken = session.getTokenAt(row, column);
var KW_START = "keyword.start",
KW_END = "keyword.end";
var tok;
if (!startToken) return;
if (startToken.type == KW_START) {
var it = new TokenIterator(session, row, column);
it.step = it.stepForward;
} else if (startToken.type == KW_END) {
var it = new TokenIterator(session, row, column);
it.step = it.stepBackward;
} else return;
while (tok = it.step()) {
if (tok.type == KW_START || tok.type == KW_END) break;
}
if (!tok || tok.type == startToken.type) return;
var col = it.getCurrentTokenColumn();
var row = it.getCurrentTokenRow();
return new Range(row, col, row, col + tok.value.length);
};
this.$id = "ace/mode/logiql";
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/logiql_highlight_rules', ['require', 'exports', 'module', 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function (require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var LogiQLHighlightRules = function LogiQLHighlightRules() {
this.$rules = { start: [{ token: 'comment.block',
regex: '/\\*',
push: [{ token: 'comment.block', regex: '\\*/', next: 'pop' }, { defaultToken: 'comment.block' }]
}, { token: 'comment.single',
regex: '//.*'
}, { token: 'constant.numeric',
regex: '\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?[fd]?'
}, { token: 'string',
regex: '"',
push: [{ token: 'string', regex: '"', next: 'pop' }, { defaultToken: 'string' }]
}, { token: 'constant.language',
regex: '\\b(true|false)\\b'
}, { token: 'entity.name.type.logicblox',
regex: '`[a-zA-Z_:]+(\\d|\\a)*\\b'
}, { token: 'keyword.start', regex: '->', comment: 'Constraint' }, { token: 'keyword.start', regex: '-->', comment: 'Level 1 Constraint' }, { token: 'keyword.start', regex: '<-', comment: 'Rule' }, { token: 'keyword.start', regex: '<--', comment: 'Level 1 Rule' }, { token: 'keyword.end', regex: '\\.', comment: 'Terminator' }, { token: 'keyword.other', regex: '!', comment: 'Negation' }, { token: 'keyword.other', regex: ',', comment: 'Conjunction' }, { token: 'keyword.other', regex: ';', comment: 'Disjunction' }, { token: 'keyword.operator', regex: '<=|>=|!=|<|>', comment: 'Equality' }, { token: 'keyword.other', regex: '@', comment: 'Equality' }, { token: 'keyword.operator', regex: '\\+|-|\\*|/', comment: 'Arithmetic operations' }, { token: 'keyword', regex: '::', comment: 'Colon colon' }, { token: 'support.function',
regex: '\\b(agg\\s*<<)',
push: [{ include: '$self' }, { token: 'support.function',
regex: '>>',
next: 'pop' }]
}, { token: 'storage.modifier',
regex: '\\b(lang:[\\w:]*)'
}, { token: ['storage.type', 'text'],
regex: '(export|sealed|clauses|block|alias|alias_all)(\\s*\\()(?=`)'
}, { token: 'entity.name',
regex: '[a-zA-Z_][a-zA-Z_0-9:]*(@prev|@init|@final)?(?=(\\(|\\[))'
}, { token: 'variable.parameter',
regex: '([a-zA-Z][a-zA-Z_0-9]*|_)\\s*(?=(,|\\.|<-|->|\\)|\\]|=))'
}] };
this.normalizeRules();
};
oop.inherits(LogiQLHighlightRules, TextHighlightRules);
exports.LogiQLHighlightRules = LogiQLHighlightRules;
});
define('ace/mode/folding/coffee', ['require', 'exports', 'module', 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function (require, exports, module) {
var oop = require("../../lib/oop");
var BaseFoldMode = require("./fold_mode").FoldMode;
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function () {};
oop.inherits(FoldMode, BaseFoldMode);
(function () {
this.getFoldWidgetRange = function (session, foldStyle, row) {
var range = this.indentationBlock(session, row);
if (range) return range;
var re = /\S/;
var line = session.getLine(row);
var startLevel = line.search(re);
if (startLevel == -1 || line[startLevel] != "#") return;
var startColumn = line.length;
var maxRow = session.getLength();
var startRow = row;
var endRow = row;
while (++row < maxRow) {
line = session.getLine(row);
var level = line.search(re);
if (level == -1) continue;
if (line[level] != "#") break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.getFoldWidget = function (session, foldStyle, row) {
var line = session.getLine(row);
var indent = line.search(/\S/);
var next = session.getLine(row + 1);
var prev = session.getLine(row - 1);
var prevIndent = prev.search(/\S/);
var nextIndent = next.search(/\S/);
if (indent == -1) {
session.foldWidgets[row - 1] = prevIndent != -1 && prevIndent < nextIndent ? "start" : "";
return "";
}
if (prevIndent == -1) {
if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") {
session.foldWidgets[row - 1] = "";
session.foldWidgets[row + 1] = "";
return "start";
}
} else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") {
if (session.getLine(row - 2).search(/\S/) == -1) {
session.foldWidgets[row - 1] = "start";
session.foldWidgets[row + 1] = "";
return "";
}
}
if (prevIndent != -1 && prevIndent < indent) session.foldWidgets[row - 1] = "start";else session.foldWidgets[row - 1] = "";
if (indent < nextIndent) return "start";else return "";
};
}).call(FoldMode.prototype);
});
define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module', 'ace/lib/oop', 'ace/mode/behaviour', 'ace/token_iterator', 'ace/lib/lang'], function (require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");
var SAFE_INSERT_IN_TOKENS = ["text", "paren.rparen", "punctuation.operator"];
var SAFE_INSERT_BEFORE_TOKENS = ["text", "paren.rparen", "punctuation.operator", "comment"];
var context;
var contextCache = {};
var initContext = function initContext(editor) {
var id = -1;
if (editor.multiSelect) {
id = editor.selection.id;
if (contextCache.rangeCount != editor.multiSelect.rangeCount) contextCache = { rangeCount: editor.multiSelect.rangeCount };
}
if (contextCache[id]) return context = contextCache[id];
context = contextCache[id] = {
autoInsertedBrackets: 0,
autoInsertedRow: -1,
autoInsertedLineEnd: "",
maybeInsertedBrackets: 0,
maybeInsertedRow: -1,
maybeInsertedLineStart: "",
maybeInsertedLineEnd: ""
};
};
var CstyleBehaviour = function CstyleBehaviour() {
this.add("braces", "insertion", function (state, action, editor, session, text) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (text == '{') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
return {
text: '{' + selected + '}',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) {
CstyleBehaviour.recordAutoInsert(editor, session, "}");
return {
text: '{}',
selection: [1, 1]
};
} else {
CstyleBehaviour.recordMaybeInsert(editor, session, "{");
return {
text: '{',
selection: [1, 1]
};
}
}
} else if (text == '}') {
initContext(editor);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', { column: cursor.column + 1, row: cursor.row });
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n" || text == "\r\n") {
initContext(editor);
var closing = "";
if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
closing = lang.stringRepeat("}", context.maybeInsertedBrackets);
CstyleBehaviour.clearMaybeInsertedClosing();
}
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === '}') {
var openBracePos = session.findMatchingBracket({ row: cursor.row, column: cursor.column + 1 }, '}');
if (!openBracePos) return null;
var next_indent = this.$getIndent(session.getLine(openBracePos.row));
} else if (closing) {
var next_indent = this.$getIndent(line);
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
return;
}
var indent = next_indent + session.getTabString();
return {
text: '\n' + indent + '\n' + next_indent + closing,
selection: [1, indent.length, 1, indent.length]
};
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
}
});
this.add("braces", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
} else {
context.maybeInsertedBrackets--;
}
}
});
this.add("parens", "insertion", function (state, action, editor, session, text) {
if (text == '(') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '(' + selected + ')',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, ")");
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', { column: cursor.column + 1, row: cursor.row });
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("brackets", "insertion", function (state, action, editor, session, text) {
if (text == '[') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '[' + selected + ']',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, "]");
return {
text: '[]',
selection: [1, 1]
};
}
} else if (text == ']') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ']') {
var matching = session.$findOpeningBracket(']', { column: cursor.column + 1, row: cursor.row });
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("brackets", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '[') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ']') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
initContext(editor);
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
return {
text: quote + selected + quote,
selection: false
};
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column - 1, cursor.column);
if (leftChar == '\\') {
return null;
}
var tokens = session.getTokens(selection.start.row);
var col = 0,
token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf(quote);
}
if (token.value.length + col > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
if (!token || quotepos < 0 && token.type !== "comment" && (token.type !== "string" || selection.start.column !== token.value.length + col - 1 && token.value.lastIndexOf(quote) === token.value.length - 1)) {
if (!CstyleBehaviour.isSaneInsertion(editor, session)) return;
return {
text: quote + quote,
selection: [1, 1]
};
} else if (token && token.type === "string") {
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == quote) {
return {
text: '',
selection: [1, 1]
};
}
}
}
}
});
this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == selected) {
range.end.column++;
return range;
}
}
});
};
CstyleBehaviour.isSaneInsertion = function (editor, session) {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) return false;
}
iterator.stepForward();
return iterator.getCurrentTokenRow() !== cursor.row || this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
};
CstyleBehaviour.$matchTokenType = function (token, types) {
return types.indexOf(token.type || token) > -1;
};
CstyleBehaviour.recordAutoInsert = function (editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) context.autoInsertedBrackets = 0;
context.autoInsertedRow = cursor.row;
context.autoInsertedLineEnd = bracket + line.substr(cursor.column);
context.autoInsertedBrackets++;
};
CstyleBehaviour.recordMaybeInsert = function (editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isMaybeInsertedClosing(cursor, line)) context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = cursor.row;
context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
context.maybeInsertedLineEnd = line.substr(cursor.column);
context.maybeInsertedBrackets++;
};
CstyleBehaviour.isAutoInsertedClosing = function (cursor, line, bracket) {
return context.autoInsertedBrackets > 0 && cursor.row === context.autoInsertedRow && bracket === context.autoInsertedLineEnd[0] && line.substr(cursor.column) === context.autoInsertedLineEnd;
};
CstyleBehaviour.isMaybeInsertedClosing = function (cursor, line) {
return context.maybeInsertedBrackets > 0 && cursor.row === context.maybeInsertedRow && line.substr(cursor.column) === context.maybeInsertedLineEnd && line.substr(0, cursor.column) == context.maybeInsertedLineStart;
};
CstyleBehaviour.popAutoInsertedClosing = function () {
context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1);
context.autoInsertedBrackets--;
};
CstyleBehaviour.clearMaybeInsertedClosing = function () {
if (context) {
context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = -1;
}
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module', 'ace/range'], function (require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function MatchingBraceOutdent() {};
(function () {
this.checkOutdent = function (line, input) {
if (!/^\s+$/.test(line)) return false;
return (/^\s*\}/.test(input)
);
};
this.autoOutdent = function (doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({ row: row, column: column });
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column - 1), indent);
};
this.$getIndent = function (line) {
return line.match(/^\s*/)[0];
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
}); | IonicaBizau/test-youtube-api | public/ace/mode-logiql.js | JavaScript | mit | 28,710 |
/**
* @param {string} s
* @return {boolean}
*/
const checkValidString = function (s) {
let leftCount = 0, rightCount = 0, starCount = 0;
let idx = 0;
while (idx < s.length) {
let ch = s[idx++];
if (ch === '(') {
++leftCount;
} else if (ch === '*') {
++starCount;
} else { // ch === ')'
++rightCount;
if (rightCount > leftCount + starCount) {
return false;
}
}
}
idx = s.length - 1;
leftCount = rightCount = starCount = 0;
while (idx >= 0) {
let ch = s[idx--];
if (ch === ')') {
++rightCount;
} else if (ch === '*') {
++starCount;
} else { // ch === '('
++leftCount;
if (leftCount > rightCount + starCount) {
return false;
}
}
}
return true;
};
module.exports = checkValidString; | alenny/leetcode | src/valid-parenthesis-string/index.js | JavaScript | mit | 956 |
// noinspection JSUnusedLocalSymbols
const React = require('react')
const moment = require('moment')
const agent = require('../agent')
import {Link} from 'react-router'
import {Row, Col} from 'react-bootstrap'
import ClientForm from './ClientForm'
import _ from 'underscore'
class RegisterClient extends React.Component {
constructor (props, context) {
super(props)
this.state = {}
}
save () {
let client = JSON.parse(JSON.stringify(_(this.state).omit(['loading'])))
client.dob = moment(client.dob).valueOf()
this.setState({loading: true})
agent.post('/services/clients')
.send(client)
.then(({body}) => {
body.saved = true
this.setState(body)
if (this.props.location.query.returnTo) {
this.props.router.push({
pathname: `${this.props.location.query.returnTo}/${body.id}`
})
}
})
.catch((error) => {
console.error(error)
this.setState(client)
})
}
render () {
const {query} = this.props.location
const state = this.state
return (
<div className='container'>
<Row>
<Col>
<h1>
<span>Register a New Client </span>
<small>
<span>or </span>
<Link to={{pathname: `/clients/locate`, query: query}}>find an existing client</Link>
</small>
</h1>
</Col>
</Row>
<ClientForm {...state}
setState={(x) => this.setState(x)}
save={() => this.save()}
location={this.props.location}
history={this.props.history}
/>
</div>
)
}
}
RegisterClient.propTypes = {
location: React.PropTypes.object,
history: React.PropTypes.object,
router: React.PropTypes.object
}
export default RegisterClient
| ocelotconsulting/global-hack-6 | src/clients/RegisterClient.js | JavaScript | mit | 1,814 |
/**
* Created by liushuo on 17/2/20.
*/
import React , {Component} from 'react';
import {AppRegistry , ListView , Text , View, StyleSheet,TouchableOpacity, Image, Dimensions} from 'react-native';
let badgeDatas = require('../Json/BadgeData.json')
let {width,height,scale} = Dimensions.get("window");
let cols = 3;
let bWidth = 100;
let hM = (width - 3 * bWidth) / (cols + 1)
let vM = 25;
export default class BagImageDemo extends Component {
renderAllBadge(){
let allBadgeDatas = [];
for (let i = 0; i<badgeDatas.data.length;i++){
let data = badgeDatas.data[i];
allBadgeDatas.push(
<View key={i} style={styles.outViewStyle}>
<Image style={styles.imageStyle} source={{uri:data.icon}}></Image>
<Text style={styles.bottomTextsStyle}>{data.title}</Text>
</View>
);
}
return allBadgeDatas;
}
render() {
return (
<View style={styles.contain}>
{/*返回所有数据包*/}
{this.renderAllBadge()}
</View>
)
}
}
const styles = StyleSheet.create({
contain:{
backgroundColor:'#F5FCFF',
flexDirection:"row",
flexWrap:'wrap',
},
outViewStyle:{
width:bWidth,
height: bWidth,
marginLeft:hM,
marginTop:vM,
backgroundColor:'red',
alignItems:"center"
},
imageStyle:{
width:80,
height:80
},
bottomTextsStyle:{
fontSize:12
}
});
| liuboshuo/react-native | RNDemo/src/Demo/bagImageDemo.js | JavaScript | mit | 1,577 |
$ = require("jquery");
jQuery = require("jquery");
var StatusTable = require("./content/status-table");
var ArchiveTable = require("./content/archive-table");
var FailuresTable = require("./content/failures-table");
var UploadTestFile = require("./content/upload-test-file");
var UploadCredentials = require("./content/upload-credentials");
var UploadServerInfo = require("./content/upload-server-info");
var UploadBatch = require("./content/upload-batch");
var Bluebird = require("bluebird");
var StandardReport = require("./content/standard-report");
var JmeterReportTable = require("./content/jmeter-report-table");
require('expose?$!expose?jQuery!jquery');
require("bootstrap-webpack");
require('./vendor/startbootstrap-sb-admin-2-1.0.8/deps');
require("./vendor/startbootstrap-sb-admin-2-1.0.8/dist/js/sb-admin-2");
var ss = require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/bower_components/bootstrap/dist/css/bootstrap.min.css").toString();
ss += require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/bower_components/metisMenu/dist/metisMenu.min.css").toString();
ss += require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/dist/css/sb-admin-2.css").toString();
ss += require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/bower_components/font-awesome/css/font-awesome.min.css").toString();
ss += require("css-loader!./vendor/startbootstrap-sb-admin-2-1.0.8/bower_components/datatables/media/css/dataTables.jqueryui.min.css").toString();
function GetQueryStringParams(sParam){
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++){
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam){
return sParameterName[1];
}
}
}
//module.exports = function(){
$(document).ready(function(){
$("<style></style>").text(ss).appendTo($("head"));
new UploadTestFile($("form"));
//new SwimLanes($("#swimlanes"));
new UploadCredentials($("#credentials"));
new UploadServerInfo($("#server-info"));
new UploadBatch($("#batch"));
if($("#batches-status")){
new StatusTable($("#batches-status"), "batches");
}
if($("#runs-status")){
new StatusTable($("#runs-status"), "runs");
}
if($("#standard-report")){
if(GetQueryStringParams("batchId")){
var batchId = GetQueryStringParams("batchId");
new StandardReport($("#standard-report"), batchId);
new JmeterReportTable($("#jmeter-report-table"), batchId);
} else {
new FailuresTable($("#failures-table"));
new ArchiveTable($("#archive-table"));
}
}
});
//}
| stierma1/performance-storm | client/index.js | JavaScript | mit | 2,709 |
Meteor.publish('movieDetails.user', publishUserMovieDetails);
function publishUserMovieDetails({ movieId }) {
validate();
this.autorun(autorun);
return;
function validate() {
new SimpleSchema({
movieId: ML.fields.id
}).validate({ movieId });
}
function autorun(computation) {
if (!this.userId) {
return this.ready();
} else {
return Movies.find({ _id: movieId }, { fields: Movies.publicFields });
}
}
} | nunof07/meteor-movielist | app/movies/server/movies.publications.js | JavaScript | mit | 513 |
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'ul',
classNames: 'ember-autocomplete-list',
});
| balinterdi/ember-cli-autocomplete | addon/components/auto-complete-list.js | JavaScript | mit | 149 |
/**
* Widget Footer Directive
*/
angular
.module('Home')
.directive('rdWidgetFooter', rdWidgetFooter);
function rdWidgetFooter() {
var directive = {
requires: '^rdWidget',
transclude: true,
template: '<div class="widget-footer" ng-transclude></div>',
restrict: 'E'
};
return directive;
}; | royzhao/prot-coderun | src/home/js/directives/widget-footer.js | JavaScript | mit | 344 |
game.PlayScreen = me.ScreenObject.extend({
/**
* action to perform on state change
*/
onResetEvent: function() {
// reset the score
game.data.score = 0;
me.levelDirector.loadLevel("level01");
this.resetPlayer(0, 420);
// the level i'm going to load
// levelDirector is telling it what to look at
var gameTimerManager = me.pool.pull("GameTimerManager", 0, 0, {});
me.game.world.addChild(gameTimerManager, 0);
// this adds the player to the screen
var heroDeathManager = me.pool.pull("HeroDeathManager", 0, 0, {});
me.game.world.addChild(heroDeathManager, 0);
var experienceManager = me.pool.pull("ExperienceManager", 0, 0, {});
me.game.world.addChild(experienceManager, 0);
me.input.bindKey(me.input.KEY.RIGHT, "right");
me.input.bindKey(me.input.KEY.LEFT, "left");
me.input.bindKey(me.input.KEY.SPACE, "jump");
me.input.bindKey(me.input.KEY.A, "attack");
// add our HUD to the game world
this.HUD = new game.HUD.Container();
me.game.world.addChild(this.HUD);
},
/**
* action to perform when leaving this screen (state change)
*/
onDestroyEvent: function() {
// remove the HUD from the game world
me.game.world.removeChild(this.HUD);
},
resetPlayer: function(x, y){
game.data.player = me.pool.pull("player", x, y, {});
me.game.world.addChild(game.data.player, 5);
}
});
// where the game starts | gisellenoriega/GiselleAwesomenauts | js/screens/play.js | JavaScript | mit | 1,369 |
Palette = function(name,colors){
this.name = name;
this.colors = colors;
};
Palette.prototype.hasName = function(name){
return this.name.toLowerCase() == name.toLowerCase()?true:false;
};
Palette.prototype.getRandomColor = function(){
return this.colors[(Math.floor(Math.random() * this.colors.length))];
};
Palette.prototype.getName = function(){
return this.name;
};
Palette.prototype.setName = function(name){
this.name = name;
};
Palette.prototype.getColors = function(){
return this.colors;
};
Palette.prototype.setColors = function(colors){
this.colors = colors;
};
Palette.generateRandomPalette = function(){
var colors = [];
for(var i = 0; i< 5; i++){
colors.push(('#'+Math.floor(Math.random()*16777215).toString(16)).toUpperCase());
}
return new Palette("RandomizePalette",colors);
}; | sirCamp/supercolor | src/palette.js | JavaScript | mit | 825 |
'use strict';
const inflect = require('i')();
const _ = require('lodash');
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const options = {
adapter: 'mongodb',
connectionString: 'mongodb://127.0.0.1:27017/testDB',
db: 'testDB',
inflect: true
};
console.log(JSON.stringify(options));
const runningAsScript = !module.parent;
/*
*** Elastic-Search mapping maker. ***
* -------------------------------- *
Generate scaffolded elastic-search mapping from a harvester app.
Meant to be run @cmd line, but can also be required and used in code.
#Usage: node mappingMaker.js path-to-harvester-app primary-es-graph-resource(e.g. people) file-to-create.json
NB: argv[3] (in this case, "file-to-create.json") is optional. If not specified, no file will be written to disk;
instead the mapping will
be console.logged.
*/
const functionTypeLookup = {
'function Stri': 'string',
'function Numb': 'number',
'function Bool': 'boolean',
'function Date': 'date',
'function Buff': 'buffer',
'function Arra': 'array'
};
function getFunctionType(fn) {
return functionTypeLookup[fn.toString().substr(0, 13)];
}
function MappingMaker() {
}
MappingMaker.prototype.generateMapping = function generateMapping(harvestApp, pov, outputFile) {
let harvesterApp;
if (_.isString(harvestApp)) {
harvesterApp = require(harvestApp)(options);
} else {
harvesterApp = Promise.resolve(harvestApp);
}
return harvesterApp
.catch() // harvestApp doesn't have to work perfectly; we just need its schemas.
.then((_harvesterApp) => {
return make(_harvesterApp, pov);
})
.then((mappingData) => {
if (outputFile) {
console.log(`Saving mapping to ${outputFile}`);
return fs.writeFileAsync(outputFile, JSON.stringify(mappingData, null, 4)).then(() => {
console.log('Saved.');
return mappingData;
}).error((e) => {
console.error('Unable to save file, because: ', e.message);
});
}
console.log('Generated Mapping: ');
console.log(JSON.stringify(mappingData, null, 4));
return mappingData;
});
};
function make(harvestApp, pov) {
const schemaName = inflect.singularize(pov);
const startingSchema = harvestApp._schema[schemaName];
const maxDepth = 4;
const _depth = 0;
const retVal = {};
retVal[pov] = { properties: {} };
const _cursor = retVal[pov].properties;
function getNextLevelSchema(propertyName, propertyValue, cursor, depth) {
let nextCursor;
if (depth === 1) {
cursor.links = cursor.links || { type: 'nested' };
cursor.links.properties = cursor.links.properties || {};
cursor.links.properties[propertyName] = {
type: 'nested',
properties: {}
};
nextCursor = cursor.links.properties[propertyName].properties;
} else {
if (depth === maxDepth) {
return;
}
cursor[propertyName] = {
type: 'nested',
properties: {}
};
nextCursor = cursor[propertyName].properties;
}
harvestApp._schema[propertyValue] && getLinkedSchemas(harvestApp._schema[propertyValue], nextCursor, depth);
}
function getLinkedSchemas(_startingSchema, cursor, depth) {
if (depth >= maxDepth) {
console.warn(`[Elastic-harvest] Graph depth of ${depth} exceeds ${maxDepth}. Graph dive halted prematurely` +
' - please investigate.'); // harvest schema may have circular references.
return null;
}
const __depth = depth + 1;
_.each(_startingSchema, (propertyValue, propertyName) => {
if (typeof propertyValue !== 'function') {
if (_.isString(propertyValue)) {
getNextLevelSchema(propertyName, propertyValue, cursor, __depth);
} else if (_.isArray(propertyValue)) {
if (_.isString(propertyValue[0])) {
getNextLevelSchema(propertyName, propertyValue[0], cursor, __depth);
} else {
getNextLevelSchema(propertyName, propertyValue[0].ref, cursor, __depth);
}
} else if (_.isObject(propertyValue)) {
getNextLevelSchema(propertyName, propertyValue.ref, cursor, __depth);
}
} else {
const fnType = getFunctionType(propertyValue);
if (fnType === 'string') {
cursor.id = {
type: 'string',
index: 'not_analyzed'
};
cursor[propertyName] = {
type: 'string',
index: 'not_analyzed'
};
} else if (fnType === 'number') {
cursor[propertyName] = {
type: 'long'
};
} else if (fnType === 'date') {
cursor[propertyName] = {
type: 'date'
};
} else if (fnType === 'boolean') {
cursor[propertyName] = {
type: 'boolean'
};
} else if (fnType === 'array') {
console.warn('[mapping-maker] Array-type scaffolding not yet implemented; ' +
`The elastic-search mapping scaffolded for this app will be incomplete wrt '${propertyName}' property.`);
} else if (fnType === 'buffer') {
console.warn('[mapping-maker] Buffer-type scaffolding not yet implemented; ' +
`The elastic-search mapping scaffolded for this app will be incomplete wrt '${propertyName}' property.`);
} else {
console.warn('[mapping-maker] unsupported type; ' +
`The elastic-search mapping scaffolded for this app will be incomplete wrt '${propertyName}' property.`);
}
}
});
return cursor;
}
getLinkedSchemas(startingSchema, _cursor, _depth);
return retVal;
}
if (runningAsScript) {
const mappingMaker = new MappingMaker();
mappingMaker.generateMapping(process.argv[2], process.argv[3], process.argv[4]);
} else {
module.exports = MappingMaker;
}
| agco/elastic-harvesterjs | non-functionals/mappingMaker.js | JavaScript | mit | 5,856 |
$(document).ready(function(){(new WOW).init()}),$(document).ready(function(){var e=document.getElementById("scene");new Parallax(e);$.stellar()}); | HealthSamurai/fhir.ru | src/js/main.min.js | JavaScript | mit | 146 |
function noReservedDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < reservedDays.length; i++) {
if ($.inArray((m + 1) + '-' + d + '-' + y, reservedDays) !== -1) {
return [false];
}
}
return [true];
}
$("#input_from").datepicker({
dayNames: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
dayNamesShort: ["Son", "Mon", "Din", "Mit", "Don", "Fra", "Sam"],
dayNamesMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
monthNames: ["Januar", "Februar", ";ärz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
monthNamesShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sept", "Okt", "Nov", "Dez"],
firstDay: 1,
dateFormat: "dd.mm.yy",
constrainInput: true,
beforeShowDay: noReservedDays,
minDate: 0,
onSelect: function(selected) {
$("#input_until").datepicker("option", "minDate", selected);
}
});
$("#input_until").datepicker({
dayNames: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
dayNamesShort: ["Son", "Mon", "Din", "Mit", "Don", "Fra", "Sam"],
dayNamesMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
monthNames: ["Januar", "Februar", ";ärz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
monthNamesShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sept", "Okt", "Nov", "Dez"],
firstDay: 1,
dateFormat: "dd.mm.yy",
constrainInput: true,
beforeShowDay: noReservedDays,
minDate: 1,
onSelect: function(selected) {
$("#input_from").datepicker("option", "maxDate", selected);
}
});
| fashionweb/moraso | application/skins/fashionweb/js/Bookingsystem/request.js | JavaScript | mit | 1,828 |
define([], function() {
function System(options) {
var options = options || {},
requirements = options.requires ? options.requires.slice(0).sort() : [];
return {
getRequirements: function() {
return requirements;
},
init: options.init || function() {},
shutdown: options.shutdown || function() {},
update: options.update || function(game, entities) {
for (var i = 0, len = entities.length; i < len; ++i) {
this.updateEach(game, entities[i]);
}
},
updateEach: options.updateEach
};
}
return System;
});
| jlippitt/bovine | src/System.js | JavaScript | mit | 704 |
export const ic_alternate_email_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M12 1.95c-5.52 0-10 4.48-10 10s4.48 10 10 10h5v-2h-5c-4.34 0-8-3.66-8-8s3.66-8 8-8 8 3.66 8 8v1.43c0 .79-.71 1.57-1.5 1.57s-1.5-.78-1.5-1.57v-1.43c0-2.76-2.24-5-5-5s-5 2.24-5 5 2.24 5 5 5c1.38 0 2.64-.56 3.54-1.47.65.89 1.77 1.47 2.96 1.47 1.97 0 3.5-1.6 3.5-3.57v-1.43c0-5.52-4.48-10-10-10zm0 13c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z"},"children":[]}]}; | wmira/react-icons-kit | src/md/ic_alternate_email_outline.js | JavaScript | mit | 555 |
/**
* @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details
*/
/*jslint sloppy: true, plusplus: true */
/*global define, java, Packages, com */
define(['logger', 'env!env/file'], function (logger, file) {
//Add .reduce to Rhino so UglifyJS can run in Rhino,
//inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce
//but rewritten for brevity, and to be good enough for use by UglifyJS.
if (!Array.prototype.reduce) {
Array.prototype.reduce = function (fn /*, initialValue */) {
var i = 0,
length = this.length,
accumulator;
if (arguments.length >= 2) {
accumulator = arguments[1];
} else {
if (length) {
while (!(i in this)) {
i++;
}
accumulator = this[i++];
}
}
for (; i < length; i++) {
if (i in this) {
accumulator = fn.call(undefined, accumulator, this[i], i, this);
}
}
return accumulator;
};
}
var JSSourceFilefromCode, optimize,
mapRegExp = /"file":"[^"]+"/;
//Bind to Closure compiler, but if it is not available, do not sweat it.
try {
JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
} catch (e) {}
//Helper for closure compiler, because of weird Java-JavaScript interactions.
function closurefromCode(filename, content) {
return JSSourceFilefromCode.invoke(null, [filename, content]);
}
function getFileWriter(fileName, encoding) {
var outFile = new java.io.File(fileName), outWriter, parentDir;
parentDir = outFile.getAbsoluteFile().getParentFile();
if (!parentDir.exists()) {
if (!parentDir.mkdirs()) {
throw "Could not create directory: " + parentDir.getAbsolutePath();
}
}
if (encoding) {
outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
} else {
outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
}
return new java.io.BufferedWriter(outWriter);
}
optimize = {
closure: function (fileName, fileContents, outFileName, keepLines, config) {
config = config || {};
var result, mappings, optimized, compressed, baseName, writer,
outBaseName, outFileNameMap, outFileNameMapContent,
srcOutFileName, concatNameMap,
jscomp = Packages.com.google.javascript.jscomp,
flags = Packages.com.google.common.flags,
//Set up source input
jsSourceFile = closurefromCode(String(fileName), String(fileContents)),
sourceListArray = new java.util.ArrayList(),
options, option, FLAG_compilation_level, compiler,
Compiler = Packages.com.google.javascript.jscomp.Compiler,
CommandLineRunner = Packages.com.google.javascript.jscomp.CommandLineRunner;
logger.trace("Minifying file: " + fileName);
baseName = (new java.io.File(fileName)).getName();
//Set up options
options = new jscomp.CompilerOptions();
for (option in config.CompilerOptions) {
// options are false by default and jslint wanted an if statement in this for loop
if (config.CompilerOptions[option]) {
options[option] = config.CompilerOptions[option];
}
}
options.prettyPrint = keepLines || options.prettyPrint;
FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS'];
FLAG_compilation_level.setOptionsForCompilationLevel(options);
if (config.generateSourceMaps) {
mappings = new java.util.ArrayList();
mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + ".src.js"));
options.setSourceMapLocationMappings(mappings);
options.setSourceMapOutputPath(fileName + ".map");
}
//Trigger the compiler
Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']);
compiler = new Compiler();
//fill the sourceArrrayList; we need the ArrayList because the only overload of compile
//accepting the getDefaultExterns return value (a List) also wants the sources as a List
sourceListArray.add(jsSourceFile);
result = compiler.compile(CommandLineRunner.getDefaultExterns(), sourceListArray, options);
if (result.success) {
optimized = String(compiler.toSource());
if (config.generateSourceMaps && result.sourceMap && outFileName) {
outBaseName = (new java.io.File(outFileName)).getName();
srcOutFileName = outFileName + ".src.js";
outFileNameMap = outFileName + ".map";
//If previous .map file exists, move it to the ".src.js"
//location. Need to update the sourceMappingURL part in the
//src.js file too.
if (file.exists(outFileNameMap)) {
concatNameMap = outFileNameMap.replace(/\.map$/, '.src.js.map');
file.saveFile(concatNameMap, file.readFile(outFileNameMap));
file.saveFile(srcOutFileName,
fileContents.replace(/\/\# sourceMappingURL=(.+).map/,
'/# sourceMappingURL=$1.src.js.map'));
} else {
file.saveUtf8File(srcOutFileName, fileContents);
}
writer = getFileWriter(outFileNameMap, "utf-8");
result.sourceMap.appendTo(writer, outFileName);
writer.close();
//Not sure how better to do this, but right now the .map file
//leaks the full OS path in the "file" property. Manually
//modify it to not do that.
file.saveFile(outFileNameMap,
file.readFile(outFileNameMap).replace(mapRegExp, '"file":"' + baseName + '"'));
fileContents = optimized + "\n//# sourceMappingURL=" + outBaseName + ".map";
} else {
fileContents = optimized;
}
return fileContents;
} else {
throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.');
}
return fileContents;
}
};
return optimize;
}); | quantumlicht/collarbone | public/js/libs/rjs/build/jslib/rhino/optimize.js | JavaScript | mit | 7,398 |
module.exports = ({ config }, options = {}) => config.module
.rule('style')
.test(/\.css$/)
.use('style')
.loader(require.resolve('style-loader'))
.when(options.style, use => use.options(options.style))
.end()
.use('css')
.loader(require.resolve('css-loader'))
.when(options.css, use => use.options(options.css));
| mirotik666/-web-project-portfol | node_modules/neutrino-middleware-style-loader/index.js | JavaScript | mit | 372 |
/**
* Created by Kaloyan on 24.5.2015 ã..
*/
console.log('============');
console.log('Exercise 1: Exchange if first is greater');
var a = 5;
var b = 2;
if (a > b) {
var temp = a;
a = b;
b = temp;
}
console.log(a + ' ' + b);
| KaloyanMarshalov/Telerik-Academy-Homeworks | Module One - Programming/Javascript Basics/03.Conditional-Statements/01.ExchangeIfGreater.js | JavaScript | mit | 242 |
$(document).ready(function () {
// Regex pour avoir les contenus des balises <amb>
// Exemple : L'<amb>avocat</amb> mange des <amb>avocats</amb>.
// Donne : $1 = avocat, puis $1 = avocats
var regAmb = new RegExp('<amb>(.*?)</amb>', 'ig');
// Regex pour avoir les contenus des balises <amb> et leurs id
// Exemple : L'<amb id="1">avocat</amb> mange des <amb id="2">avocats</amb>.
// Donne : $1 = 1 et $3 = avocat, puis $1 = 2 et $3 = avocats
var regAmbId = new RegExp('<amb id="([0-9]+)"( title=".*")?>(.*?)</amb>', 'ig');
// Le formulaire d'édition
var editorForm = $("#phrase-editor-form");
// Div contenant le prototype du formulaire MAP
var $container = $('div#proto_motsAmbigusPhrase');
// La div modifiable
var phraseEditor = $("div.phrase-editor");
// Div des erreurs
var errorForm = $('#form-errors');
// Le mode actif
var modeEditor = $('#nav-editor li.active').data('mode');
// Pour numéroter le mot ambigu
var indexMotAmbigu = 0;
// Tableau des mots ambigus de la phrase
var motsAmbigus = [];
function getPhraseTexte() {
return phraseEditor
.html()
.replace(/ /ig, ' ')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/<br>/g, '')
.replace(/ style=""/g, '')
.replace(/ title="Ce mot est ambigu \(id : [0-9]+\)"/ig, '');
}
// Mise à jour du mode d'éditeur
$('#nav-editor li').on('click', function(){
$('#nav-editor li.active').removeClass('active');
$(this).addClass('active');
var oldModeEditor = modeEditor;
modeEditor = $(this).data('mode');
if (oldModeEditor != modeEditor) {
if (modeEditor === 'wysiwyg') {
// Affiche la phrase en mode HTML
phraseEditor.html(phraseEditor.text());
$.each(phraseEditor.find('amb'), function (i, val) {
$(this).attr('title', 'Ce mot est ambigu (id : ' + $(this).attr('id') + ')');
});
}
else if (modeEditor === 'source') {
// Affiche la phrase en mode texte
phraseEditor.text(getPhraseTexte());
}
}
});
// Ajout d'un mot ambigu
$("#addAmb").on('click', function () {
var sel = window.getSelection();
var selText = sel.toString();
// S'il y a bien un mot séléctionné
if (selText.trim() !== '') {
var regAlpha = /[a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ]/;
var parentBase = sel.anchorNode.parentNode;
var parentFocus = sel.focusNode.parentNode;
var numPrevChar = Math.min(sel.focusOffset, sel.anchorOffset) - 1;
var numFirstChar = Math.min(sel.focusOffset, sel.anchorOffset);
var numLastChar = Math.max(sel.focusOffset, sel.anchorOffset) - 1;
var numNextChar = Math.max(sel.focusOffset, sel.anchorOffset);
var prevChar = sel.focusNode.textContent.charAt(numPrevChar);
var firstChar = sel.focusNode.textContent.charAt(numFirstChar);
var lastChar = sel.focusNode.textContent.charAt(numLastChar);
var nextChar = sel.focusNode.textContent.charAt(numNextChar);
errorForm.empty();
var success = true;
if (phraseEditor.html() != parentBase.innerHTML || phraseEditor.html() != parentFocus.innerHTML) {
errorForm.append('Le mot sélectionné est déjà ambigu<br>');
success = false;
}
if (sel.anchorNode != sel.focusNode) {
errorForm.append('Le mot sélectionné contient déjà un mot ambigu<br>');
success = false;
}
if (prevChar.match(regAlpha)) {
errorForm.append('Le premier caractère sélectionné ne doit pas être précédé d\'un caractère alphabétique<br>');
success = false;
}
if (!firstChar.match(regAlpha)) {
errorForm.append('Le premier caractère sélectionné doit être alphabétique<br>');
success = false;
}
if (!lastChar.match(regAlpha)) {
errorForm.append('Le dernier caractère sélectionné doit être alphabétique<br>');
success = false;
}
if (nextChar.match(regAlpha)) {
errorForm.append('Le dernier caractère sélectionné ne doit pas être suivi d\'un caractère alphabétique<br>');
success = false;
}
// S'il y a une erreur on affiche la div des erreurs
if (!success) {
errorForm.show();
return false;
}
// Sinon on cache la div
else {
errorForm.hide();
}
// Transformation du texte sélectionné en mot ambigu selon le mode utilisé
var range = document.getSelection().getRangeAt(0);
var clone = $(range.cloneContents());
range.deleteContents();
range.insertNode($('<amb>').append(clone).get(0));
document.getSelection().setPosition(null);
phraseEditor.trigger('input');
}
});
// A chaque modification de la phrase
phraseEditor.on('input', function (){
var phrase = getPhraseTexte();
// Compte le nombre d'occurence de balise <amb>
var replaced = phrase.search(regAmb) >= 0;
// Si au moins 1
if(replaced) {
// On ajout dans la balise <amb> l'id du mot ambigu
var temp = phrase.replace(regAmb, function ($0, motAmbigu) {
indexMotAmbigu++;
var indexLocal = indexMotAmbigu;
motsAmbigus[indexMotAmbigu] = motAmbigu;
// On ajoute le nom unique et l'id
var template = $container.attr('data-prototype')
.replace(/__name__label__/g, '')
.replace(/__name__/g, indexMotAmbigu)
.replace(/__id__/g, indexMotAmbigu)
.replace(/__MA__/g, motAmbigu);
var $prototype = $(template);
// Trouve la balise qui à la class amb
var amb = $prototype.find('.amb');
// Ajoute la valeur du mot ambigu en supprimant les espaces avant et après le mot, et ajoute l'id
amb.val(motAmbigu);
$prototype.attr('id', 'rep' + indexMotAmbigu);
var $deleteLink = $('<a href="#" class="sup-amb btn btn-danger">Supprimer le mot ambigu</a>');
$prototype.find('.gloseAction').append($deleteLink);
getGloses($prototype.find('select.gloses'), motAmbigu, function () {
// Pour la page d'édition, sélection des gloses automatique
if (typeof reponsesOri != 'undefined') {
reponsesOri.forEach((item, index) => {
if (item.map_ordre == indexLocal) {
$prototype.find('option[value=' + item.glose_id + ']').prop('selected', true)
}
});
}
});
$container.append($prototype);
if (modeEditor == 'wysiwyg') {
return '<amb id="' + indexMotAmbigu + '" title="Ce mot est ambigu (id : ' + indexMotAmbigu + ')">' + motAmbigu + '</amb>';
}
else {
return '<amb id="' + indexMotAmbigu + '">' + motAmbigu + '</amb>';
}
});
if (modeEditor == 'wysiwyg') {
phraseEditor.html(temp);
}
else {
phraseEditor.text(temp);
}
}
var phrase = getPhraseTexte();
phrase.replace(regAmbId, function ($0, $1, $2, $3) {
var motAmbiguForm = $('#phrase_motsAmbigusPhrase_' + $1 + '_valeur');
// Mot ambigu modifié dans la phrase -> passage en rouge du MA dans le formulaire
if (motsAmbigus[$1] != $3) {
motAmbiguForm.val($3).css('color', 'red');
}
// Si le MA modifié reprend sa valeur initiale -> efface la couleur rouge du MA dans le formulaire
else if (motsAmbigus[$1] != motAmbiguForm.val($3)) {
motAmbiguForm.val(motsAmbigus[$1]).css('color', '');
}
});
});
phraseEditor.trigger('input'); // Pour mettre en forme en cas de phrase au chargement (édition ou création échouée)
// Mise à jour des gloses des mots ambigus
phraseEditor.on('focusout', function () {
var phrase = getPhraseTexte();
phrase.replace(regAmbId, function ($0, $1, $2, $3) {
if (motsAmbigus[$1] != $3) {
$('#phrase_motsAmbigusPhrase_' + $1 + '_valeur').trigger('focusout');
motsAmbigus[$1] = $3;
}
});
});
// Désactive la touche entrée dans l'éditeur de phrase
phraseEditor.on('keypress', function(e) {
var keyCode = e.which;
if (keyCode == 13) {
return false;
}
});
// Coller sans le formatage
phraseEditor.on('paste', function(e) {
e.preventDefault();
var text = (e.originalEvent || e).clipboardData.getData('text/plain');
if (modeEditor == 'wysiwyg') {
$(this).html(text);
}
else {
$(this).text(text);
}
phraseEditor.trigger('input'); // Pour mettre en forme après avoir collé
});
// Modification d'un mot ambigu
editorForm.on('input', '.amb', function () {
// On récupère l'id qui est dans l'attribut id (id="rep1"), en supprimant le rep
var id = $(this).closest('.reponseGroupe').attr('id').replace(/rep/, '');
// Mot ambigu modifié -> passage en rouge du MA
if (motsAmbigus[id] != $(this).val()) {
$(this).css('color', 'red');
}
// Si le MA modifié reprend sa valeur initiale -> efface la couleur rouge du MA
else {
$(this).css('color', '');
}
var phrase = getPhraseTexte();
// Regex pour trouver la bonne balise <amb id="">, et en récupérer le contenu
var reg3 = new RegExp('<amb id="' + id + '">(.*?)' + '</amb>', 'g');
// Met à jour le mot ambigu dans la phrase
if (modeEditor == 'wysiwyg') {
phraseEditor.html(phrase.replace(reg3, '<amb id="' + id + '" title="Ce mot est ambigu (id : ' + id + ')">' + $(this).val() + '</amb>'));
}
else {
phraseEditor.text(phrase.replace(reg3, '<amb id="' + id + '">' + $(this).val() + '</amb>'));
}
});
// Mise à jour des gloses d'un mot ambigu
editorForm.on('focusout', '.amb', function (){
// On récupère l'id qui est dans l'attribut id (id="rep1"), en supprimant le rep
var id = $(this).closest('.reponseGroupe').attr('id').replace(/rep/, '');
if (motsAmbigus[id] != $(this).val()) {
$(this).css('color', '');
motsAmbigus[id] = $(this).val();
var phrase = getPhraseTexte();
// Regex pour trouver la bonne balise <amb id="">, et en récupérer le contenu
var reg3 = new RegExp('<amb id="' + id + '">(.*?)' + '</amb>', 'g');
// Met à jour le mot ambigu dans la phrase
if (modeEditor == 'wysiwyg') {
phraseEditor.html(phrase.replace(reg3, '<amb id="' + id + '" title="Ce mot est ambigu (id : ' + id + ')">' + $(this).val() + '</amb>'));
}
else {
phraseEditor.text(phrase.replace(reg3, '<amb id="' + id + '">' + $(this).val() + '</amb>'));
}
getGloses($(this).closest('.colAmb').next().find('select.gloses'), $(this).val());
}
});
// Suppression d'un mot ambigu
editorForm.on('click', '.sup-amb', function(e) {
$(this).closest('.reponseGroupe').trigger('mouseleave');
var phrase = getPhraseTexte();
// On récupère l'id qui est dans l'attribut id (id="rep1"), en supprimant le rep
var id = $(this).closest('.reponseGroupe').attr('id').replace(/rep/, '');
delete motsAmbigus[id];
// Regex pour trouver la bonne balise <amb id="">, et en récupérer le contenu
var reg3 = new RegExp('<amb id="' + id + '">(.*?)</amb>', 'g');
// Modifie le textarea pour supprimé la balise <amb id=""></amb> et remettre le contenu
if (modeEditor == 'wysiwyg') {
phraseEditor.html(phrase.replace(reg3, '$1'));
}
else {
phraseEditor.text(phrase.replace(reg3, '$1'));
}
$(this).closest('.reponseGroupe').remove();
e.preventDefault(); // Évite qu'un # soit ajouté dans l'URL
});
// A la soumission du formulaire
$('.btn-phrase-editor').on('click', function(){
$('#phrase_contenu').val(getPhraseTexte());
});
});
| alexdu98/Ambiguss | web/js/editeur.js | JavaScript | mit | 13,282 |
'use strict';
var express = require('express'),
logger = require('morgan'),
bodyParser = require('body-parser'),
stylus = require('stylus'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
passport = require('passport');
module.exports = function(app, config) {
function compile(str, path) {
// compile function for stylus
return stylus(str).set('filename', path);
}
app.set('views', config.rootPath + '/server/views');
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(cookieParser());
app.use(bodyParser());
app.use(session({secret: 'multi vision unicorns'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(stylus.middleware(
{
src: config.rootPath + '/public',
compile: compile
}
));
app.use(express.static(config.rootPath + '/public'));
}
| misterdavemeister/meanio | tests/IMS/server/config/express.js | JavaScript | mit | 864 |
/**
* Created by cin on 1/18/14.
*/
/**
* Created by cin on 1/18/14.
*/
var _ = require('underscore'),
chance = new (require('chance'))(),
syBookshelf = require('./base'),
User = require('./user'),
CoStatus = require('./co-status'),
UserCooperation = require('./user-cooperation'),
UserCooperations = UserCooperation.Set,
Picture = require('./picture'),
Pictures = Picture.Set,
CoComment = require('./co-comment'),
Cooperation, Cooperations,
config = require('../config'),
tbCooperation = 'cooperations',
fkStatus = 'statusid',
fkCooperation = 'cooperationid',
fkOwner = 'ownerid';
Cooperation = module.exports = syBookshelf.Model.extend({
tableName: tbCooperation,
fields: [
'id', 'name', 'description', 'company', 'avatar', 'statusid', 'ownerid', 'isprivate', 'regdeadline', 'createtime'
],
appended: ['user', 'status'],
fieldToAssets: { avatar: 'cooperations' },
defaults: function () {
return {
createtime: new Date()
}
},
toJSON: function () {
var self = this, Model = this.constructor,
ret = Model.__super__.toJSON.apply(this, arguments);
_.each(this.fieldToAssets, function (type, field) {
if (self.get(field) != null) {
var file = self.getAssetPath(type);
ret[field] = config.toStaticURI(file) + '?t=' + ret[field];
}
});
return ret;
},
saving: function () {
return Cooperation.__super__
.saving.apply(this, arguments);
},
usership: function () {
return this.hasMany(UserCooperations, fkCooperation);
},
fetched: function (model, attrs, options) {
return Cooperation.__super__.fetched.apply(this, arguments)
.return(model)
.call('countComments')
.call('countUsership')
.call('countPictures')
.then(function (cooperation) {
return model.related('pictures').fetch();
})
.then(function () {
if (!options['detailed']) return;
return model.related('cocomments')
.query(function (qb) {
qb.orderBy('id', 'desc');
}).fetch();
})
},
countUsership: function () {
var self = this;
return this.usership().fetch()
.then(function (userships) {
var numUserships = userships.length;
return self.data('numUserships', numUserships);
})
},
status: function () {
return this.belongsTo(CoStatus, fkStatus);
},
user: function () {
return this.belongsTo(require('./user'), fkOwner);
},
cocomments: function () {
return this.hasMany(CoComment, 'cooperationid');
},
pictures: function () {
return this.hasMany(Picture, 'cooperationid');
},
countComments: function () {
var self = this;
return this.cocomments().fetch()
.then(function (cocomments) {
var numComments = cocomments.length;
return self.data('numComments', numComments);
});
},
countPictures: function () {
var self = this;
return Pictures.forge().query()
.where(fkCooperation, '=', self.id)
.count('id')
.then(function (d) {
return self.data('numPictures', d[0]["count(`id`)"]);
});
}
}, {
randomForge: function () {
var status = _.random(1, 2);
return Cooperation.forge({
'name': chance.word(),
'description': chance.paragraph(),
'ownerid': chance.integer({
min: 1,
max: 20
}),
'company': chance.word(),
'avatar': chance.word(),
'statusid': status,
'isprivate': chance.bool(),
'regdeadline': chance.date({ year: 2013 })
});
}
});
Cooperations = Cooperation.Set = syBookshelf.Collection.extend({
model: Cooperation,
lister: function (req, qb) {
var query = req.query;
this.qbWhere(qb, req, query, ['id', 'statusid', 'ownerid', 'isprivate'], tbCooperation);
if (!req.query['fuzzy']) {
this.qbWhere(qb, req, query, ['name', 'company'], tbCooperation);
} else {
this.qbWhereLike(qb, req, query, ['name', 'description', 'company'], tbCooperation);
}
}
});
| node-fun/siyuan | models/cooperation.js | JavaScript | mit | 3,781 |
'use strict';
var mongoose = require('mongoose');
require('./models/StockPoint');
require('./models/Pattern');
var mongoDbURL = 'mongodb://localhost/pttnrs';
if (process.env.MONGOHQ_URL) {
mongoDbURL = process.env.MONGOHQ_URL;
}
mongoose.connect(mongoDbURL);
| connyay/PTTRNS | db.js | JavaScript | mit | 266 |
function setMaximizeCookie(i,e,a){if(a){var o=new Date;o.setTime(o.getTime()+864e5*a);var t="; expires="+o.toGMTString()}else var t="";document.cookie=i+"="+e+t+"; path=/"}function getMaximizeCookie(i){for(var e=i+"=",a=document.cookie.split(";"),o=0;o<a.length;o++){for(var t=a[o];" "==t.charAt(0);)t=t.substring(1,t.length);if(0==t.indexOf(e))return t.substring(e.length,t.length)}return null}var cookie_scaniaBootstrap_maximize=getMaximizeCookie("scaniaBootstrap_maximize");"maximized"===cookie_scaniaBootstrap_maximize&&($("body").addClass("maximized"),$("#maximize-icon").toggleClass("icon-fullscreen icon-resize-small")),$("#maximize-button").click(function(){$(this).children("#maximize-icon").toggleClass("icon-fullscreen icon-resize-small"),$("body").toggleClass("maximized"),$("body").hasClass("maximized")?setMaximizeCookie("scaniaBootstrap_maximize","maximized",30):setMaximizeCookie("scaniaBootstrap_maximize","minimized",30)}); | mohammed-softordi/scania-bootstrap-ui | js/bootstrap/min/scania-bootstrap-addons.min.js | JavaScript | mit | 941 |
// Copyright IBM Corp. 2014. All Rights Reserved.
// Node module: async-tracker
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
var assert = require('assert');
require('../index.js');
var fs = require('fs');
var util = require('util');
var cnt = 0;
var Listener = function() {
var evtName = asyncTracker.events.fs.open;
this.deferredCreated = {};
this.invokeDeferred = {};
this.deferredReleased = {};
this.deferredCreated[evtName] = function(fName, fId, args) {
assert.equal(cnt, 0);
cnt += 1;
};
this.deferredCreated['default'] = function(fName, fId, args) {
assert.equal(cnt, 4);
cnt += 1;
};
this.invokeDeferred[evtName] = function(fName, fId, next) {
assert.equal(cnt, 2);
cnt += 1;
next();
};
this.invokeDeferred['default'] = function(fName, fId, next) {
assert.equal(cnt, 6);
cnt += 1;
next();
};
this.deferredReleased[evtName] = function(fName, fId) {
assert.equal(cnt, 5);
cnt += 1;
};
this.deferredReleased['default'] = function(fName, fId) {
assert.equal(cnt, 7);
cnt += 1;
};
this.objectCreated = function(obj) {
assert.equal(cnt, 1);
cnt += 1;
};
this.objectReleased = function(obj) {
assert.equal(cnt, 3);
cnt += 1;
};
};
var listener = new Listener();
asyncTracker.addListener(listener, 'listener');
function closeCallback() {
}
function openCallback(err, fd) {
fs.close(fd, closeCallback);
}
fs.open(__filename, 'r', openCallback);
asyncTracker.removeListener('listener'); | strongloop/async-tracker | test/test-fs-open-close.js | JavaScript | mit | 1,581 |
var prettyURLs = require('../middleware/pretty-urls'),
cors = require('../middleware/api/cors'),
urlRedirects = require('../middleware/url-redirects'),
auth = require('../../auth');
/**
* Auth Middleware Packages
*
* IMPORTANT
* - cors middleware MUST happen before pretty urls, because otherwise cors header can get lost on redirect
* - cors middleware MUST happen after authenticateClient, because authenticateClient reads the trusted domains
* - url redirects MUST happen after cors, otherwise cors header can get lost on redirect
*/
/**
* Authentication for public endpoints
*/
module.exports.authenticatePublic = [
auth.authenticate.authenticateClient,
auth.authenticate.authenticateUser,
// This is a labs-enabled middleware
auth.authorize.requiresAuthorizedUserPublicAPI,
cors,
urlRedirects,
prettyURLs
];
/**
* Authentication for private endpoints
*/
module.exports.authenticatePrivate = [
auth.authenticate.authenticateClient,
auth.authenticate.authenticateUser,
auth.authorize.requiresAuthorizedUser,
cors,
urlRedirects,
prettyURLs
];
/**
* Authentication for client endpoints
*/
module.exports.authenticateClient = function authenticateClient(client) {
return [
auth.authenticate.authenticateClient,
auth.authenticate.authenticateUser,
auth.authorize.requiresAuthorizedClient(client),
cors,
urlRedirects,
prettyURLs
];
};
| kpsuperplane/personal-website | versions/1.19.0/core/server/web/api/middleware.js | JavaScript | mit | 1,470 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _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) : subClass.__proto__ = superClass; }
var SearchBar = function (_Component) {
_inherits(SearchBar, _Component);
function SearchBar(props) {
_classCallCheck(this, SearchBar);
var _this = _possibleConstructorReturn(this, (SearchBar.__proto__ || Object.getPrototypeOf(SearchBar)).call(this, props));
_this.state = { term: '' };
_this.onInputChange = _this.onInputChange.bind(_this);
return _this;
}
_createClass(SearchBar, [{
key: 'onInputChange',
value: function onInputChange(term) {
this.setState({ term: term });
this.props.getResults(term);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
return _react2.default.createElement(
'div',
{ className: 'searchBarContainer' },
_react2.default.createElement('input', { type: 'text',
value: this.state.term,
onChange: function onChange(event) {
return _this2.onInputChange(event.target.value);
}
})
);
}
}]);
return SearchBar;
}(_react.Component);
exports.default = SearchBar;
{/*<button><i id="searchIcon" className="fa fa-search" /></button>*/}
//# sourceMappingURL=searchbar-compiled.js.map | ShaneFairweather/React-iTunes | src/components/searchbar-compiled.js | JavaScript | mit | 3,071 |
var SuperheroesShowRoute = Ember.Route.extend({
model: function(params) {
return(this.store.find('superhero', params.id));
}
});
export default SuperheroesShowRoute;
| trianglegrrl/superheroes | app/routes/superheroes/show.js | JavaScript | mit | 176 |
{
if (this.props.x === 227) {
return React.createElement(
"span",
{
className: "_38my"
},
"Campaign Details",
null,
React.createElement("span", {
className: "_c1c"
})
);
}
if (this.props.x === 265) {
return React.createElement(
"span",
{
className: "_38my"
},
[
React.createElement(
"span",
{
key: 1
},
"Campaign ID",
": ",
"98010048849317"
),
React.createElement(
"div",
{
className: "_5lh9",
key: 2
},
React.createElement(
FluxContainer_AdsCampaignGroupStatusSwitchContainer_119,
{
x: 264
}
)
)
],
null,
React.createElement("span", {
className: "_c1c"
})
);
}
}
| stas-vilchik/bdd-ml | data/5657.js | JavaScript | mit | 939 |
const Discord = require("discord.js");
const client = new Discord.Client();
const settings = require("./settings.json");
const chalk = require("chalk");
const fs = require("fs");
const moment = require("moment");
require("./util/eventLoader")(client);
const log = message => {
console.log(`[${moment().format("YYYY-MM-DD HH:mm:ss")}] ${message}`);
};
client.commands = new Discord.Collection();
client.aliases = new Discord.Collection();
fs.readdir('./commands/', (err, files) => {
if (err) console.error(err);
log(`Loading a total of ${files.length} commands.`);
files.forEach(f => {
let props = require(`./commands/${f}`);
log(`Loading Command: ${props.help.name}. 👌`);
client.commands.set(props.help.name, props);
props.conf.aliases.forEach(alias => {
client.aliases.set(alias, props.help.name);
});
});
});
client.reload = command => {
return new Promise((resolve, reject) => {
try {
delete require.cache[require.resolve(`./commands/${command}`)];
let cmd = require(`./commands/${command}`);
client.commands.delete(command);
client.aliases.forEach((cmd, alias) => {
if (cmd === command) client.aliases.delete(alias);
});
client.commands.set(command, cmd);
cmd.conf.aliases.forEach(alias => {
client.aliases.set(alias, cmd.help.name);
});
resolve();
} catch (e) {
reject(e);
}
});
};
client.on("ready", () => {
const games = ["Not a Game", "The Joker Game Returns", "The Coven", "Nintendo: Choose Your Own Character 2!", "PokéDonalds"];
setInterval(() => {
const playingGame = games[~~(Math.random() * games.length)];
console.log(`Changing playing game to ${playingGame} now`);
client.user.setGame(playingGame);
}, 1800000);
client.channels.get("339257481740156928").fetchMessages({
limit: 30
})
.then(messages => console.log(`Received ${messages.size} messages`))
.catch(console.error);
});
client.elevation = message => {
/* This function should resolve to an ELEVATION level which
is then sent to the command handler for verification*/
let permlvl = 0;
let mod_role = message.guild.roles.find("name", settings.modrolename);
if (mod_role && message.member.roles.has(mod_role.id)) permlvl = 2;
let admin_role = message.guild.roles.find("name", settings.adminrolename);
if (admin_role && message.member.roles.has(admin_role.id)) permlvl = 3;
if (message.author.id === settings.ownerid) permlvl = 4;
return permlvl;
};
let autoResponse = {
"ayy": "lmao",
"ayyy": "lmao",
"ayyyy": "lmao",
"that's hot": "eso es caliente",
"lenny": "( ͡° ͜ʖ ͡°)",
"eso es caliente": "that's hot",
"drewbie": "!kick drewbie"
};
client.on("message", message => {
if (message.content === "lala") {
console.log(guild.members.find(nickname, 'asd'));
}
if (message.author.bot) return;
let msg = message.content.toLowerCase();
if (autoResponse[msg]) {
message.channel.send(autoResponse[msg]);
}
});
var regToken = /[\w\d]{24}\.[\w\d]{6}\.[\w\d-_]{27}/g;
// client.on('debug', e => {
// console.log(chalk.bgBlue.green(e.replace(regToken, 'that was redacted')));
// });
client.on("warn", e => {
console.log(chalk.bgYellow(e.replace(regToken, "that was redacted")));
});
client.on("error", e => {
console.log(chalk.bgRed(e.replace(regToken, "that was redacted")));
});
client.login(process.env.TOKEN);
| JohnnyMustang/UGbot | app.js | JavaScript | mit | 3,317 |
/*
* provider.js: Abstraction providing an interface into pluggable configuration storage.
*
* (C) 2011, Nodejitsu Inc.
*
*/
var async = require('async'),
common = require('./common');
//
// ### function Provider (options)
// #### @options {Object} Options for this instance.
// Constructor function for the Provider object responsible
// for exposing the pluggable storage features of `nconf`.
//
var Provider = exports.Provider = function (options) {
//
// Setup default options for working with `stores`,
// `overrides`, `process.env` and `process.argv`.
//
options = options || {};
this.stores = {};
this.sources = [];
this.init(options);
};
//
// Define wrapper functions for using basic stores
// in this instance
//
['argv', 'env', 'file'].forEach(function (type) {
Provider.prototype[type] = function (options) {
return this.add(type, options);
};
});
//
// Define wrapper functions for using
// overrides and defaults
//
['defaults', 'overrides'].forEach(function (type) {
Provider.prototype[type] = function (options) {
return this.add('literal', options);
};
});
//
// ### function use (name, options)
// #### @type {string} Type of the nconf store to use.
// #### @options {Object} Options for the store instance.
// Adds (or replaces) a new store with the specified `name`
// and `options`. If `options.type` is not set, then `name`
// will be used instead:
//
// provider.use('file');
// provider.use('file', { type: 'file', filename: '/path/to/userconf' })
//
Provider.prototype.use = function (name, options) {
options = options || {};
var type = options.type || name;
function sameOptions (store) {
return Object.keys(options).every(function (key) {
return options[key] === store[key];
});
}
var store = this.stores[name],
update = store && !sameOptions(store);
if (!store || update) {
if (update) {
this.remove(name);
}
this.add(name, options);
}
return this;
};
//
// ### function add (name, options)
// #### @name {string} Name of the store to add to this instance
// #### @options {Object} Options for the store to create
// Adds a new store with the specified `name` and `options`. If `options.type`
// is not set, then `name` will be used instead:
//
// provider.add('memory');
// provider.add('userconf', { type: 'file', filename: '/path/to/userconf' })
//
Provider.prototype.add = function (name, options) {
options = options || {};
var type = options.type || name;
if (!require('../nconf')[common.capitalize(type)]) {
throw new Error('Cannot add store with unknown type: ' + type);
}
this.stores[name] = this.create(type, options);
if (this.stores[name].loadSync) {
this.stores[name].loadSync();
}
return this;
};
//
// ### function remove (name)
// #### @name {string} Name of the store to remove from this instance
// Removes a store with the specified `name` from this instance. Users
// are allowed to pass in a type argument (e.g. `memory`) as name if
// this was used in the call to `.add()`.
//
Provider.prototype.remove = function (name) {
delete this.stores[name];
return this;
};
//
// ### function create (type, options)
// #### @type {string} Type of the nconf store to use.
// #### @options {Object} Options for the store instance.
// Creates a store of the specified `type` using the
// specified `options`.
//
Provider.prototype.create = function (type, options) {
return new (require('../nconf')[common.capitalize(type.toLowerCase())])(options);
};
//
// ### function init (options)
// #### @options {Object} Options to initialize this instance with.
// Initializes this instance with additional `stores` or `sources` in the
// `options` supplied.
//
Provider.prototype.init = function (options) {
var self = this;
//
// Add any stores passed in through the options
// to this instance.
//
if (options.type) {
this.add(options.type, options);
}
else if (options.store) {
this.add(options.store.name || options.store.type, options.store);
}
else if (options.stores) {
Object.keys(options.stores).forEach(function (name) {
var store = options.stores[name];
self.add(store.name || name || store.type, store);
});
}
//
// Add any read-only sources to this instance
//
if (options.source) {
this.sources.push(this.create(options.source.type || options.source.name, options.source));
}
else if (options.sources) {
Object.keys(options.sources).forEach(function (name) {
var source = options.sources[name];
self.sources.push(self.create(source.type || source.name || name, source));
});
}
};
//
// ### function get (key, callback)
// #### @key {string} Key to retrieve for this instance.
// #### @callback {function} **Optional** Continuation to respond to when complete.
// Retrieves the value for the specified key (if any).
//
Provider.prototype.get = function (key, callback) {
//
// If there is no callback we can short-circuit into the default
// logic for traversing stores.
//
if (!callback) {
return this._execute('get', 1, key, callback);
}
//
// Otherwise the asynchronous, hierarchical `get` is
// slightly more complicated because we do not need to traverse
// the entire set of stores, but up until there is a defined value.
//
var current = 0,
names = Object.keys(this.stores),
self = this,
response;
async.whilst(function () {
return typeof response === 'undefined' && current < names.length;
}, function (next) {
var store = self.stores[names[current]];
current++;
if (store.get.length >= 2) {
return store.get(key, function (err, value) {
if (err) {
return next(err);
}
response = value;
next();
});
}
response = store.get(key);
next();
}, function (err) {
return err ? callback(err) : callback(null, response);
});
};
//
// ### function set (key, value, callback)
// #### @key {string} Key to set in this instance
// #### @value {literal|Object} Value for the specified key
// #### @callback {function} **Optional** Continuation to respond to when complete.
// Sets the `value` for the specified `key` in this instance.
//
Provider.prototype.set = function (key, value, callback) {
return this._execute('set', 2, key, value, callback);
};
//
// ### function reset (callback)
// #### @callback {function} **Optional** Continuation to respond to when complete.
// Clears all keys associated with this instance.
//
Provider.prototype.reset = function (callback) {
return this._execute('reset', 0, callback);
};
//
// ### function clear (key, callback)
// #### @key {string} Key to remove from this instance
// #### @callback {function} **Optional** Continuation to respond to when complete.
// Removes the value for the specified `key` from this instance.
//
Provider.prototype.clear = function (key, callback) {
return this._execute('clear', 1, key, callback);
};
//
// ### function merge ([key,] value [, callback])
// #### @key {string} Key to merge the value into
// #### @value {literal|Object} Value to merge into the key
// #### @callback {function} **Optional** Continuation to respond to when complete.
// Merges the properties in `value` into the existing object value at `key`.
//
// 1. If the existing value `key` is not an Object, it will be completely overwritten.
// 2. If `key` is not supplied, then the `value` will be merged into the root.
//
Provider.prototype.merge = function () {
var self = this,
args = Array.prototype.slice.call(arguments),
callback = typeof args[args.length - 1] === 'function' && args.pop(),
value = args.pop(),
key = args.pop();
function mergeProperty (prop, next) {
return self._execute('merge', 2, prop, value[prop], next);
}
if (!key) {
if (Array.isArray(value) || typeof value !== 'object') {
return onError(new Error('Cannot merge non-Object into top-level.'), callback);
}
return async.forEach(Object.keys(value), mergeProperty, callback || function () { })
}
return this._execute('merge', 2, key, value, callback);
};
//
// ### function load (callback)
// #### @callback {function} Continuation to respond to when complete.
// Responds with an Object representing all keys associated in this instance.
//
Provider.prototype.load = function (callback) {
var self = this;
function getStores () {
return Object.keys(self.stores).map(function (name) {
return self.stores[name];
});
}
function loadStoreSync(store) {
if (!store.loadSync) {
throw new Error('nconf store ' + store.type + ' has no loadSync() method');
}
return store.loadSync();
}
function loadStore(store, next) {
if (!store.load && !store.loadSync) {
return next(new Error('nconf store ' + store.type + ' has no load() method'));
}
return store.loadSync
? next(null, store.loadSync())
: store.load(next);
}
function loadBatch (targets, done) {
if (!done) {
return common.merge(targets.map(loadStoreSync));
}
async.map(targets, loadStore, function (err, objs) {
return err ? done(err) : done(null, common.merge(objs));
});
}
function mergeSources (data) {
//
// If `data` was returned then merge it into
// the system store.
//
if (data && typeof data === 'object') {
self.use('sources', {
type: 'literal',
store: data
});
}
}
function loadSources () {
//
// If we don't have a callback and the current
// store is capable of loading synchronously
// then do so.
//
if (!callback) {
mergeSources(loadBatch(self.sources));
return loadBatch(getStores());
}
loadBatch(self.sources, function (err, data) {
if (err) {
return callback(err);
}
mergeSources(data);
return loadBatch(getStores(), callback);
});
}
return self.sources.length
? loadSources()
: loadBatch(getStores(), callback);
};
//
// ### function save (value, callback)
// #### @value {Object} **Optional** Config object to set for this instance
// #### @callback {function} Continuation to respond to when complete.
// Removes any existing configuration settings that may exist in this
// instance and then adds all key-value pairs in `value`.
//
Provider.prototype.save = function (value, callback) {
if (!callback && typeof value === 'function') {
callback = value;
value = null;
}
var self = this,
names = Object.keys(this.stores);
function saveStoreSync(name) {
var store = self.stores[name];
//
// If the `store` doesn't have a `saveSync` method,
// just ignore it and continue.
//
return store.saveSync
? store.saveSync()
: null;
}
function saveStore(name, next) {
var store = self.stores[name];
//
// If the `store` doesn't have a `save` or saveSync`
// method(s), just ignore it and continue.
//
if (!store.save && !store.saveSync) {
return next();
}
return store.saveSync
? next(null, store.saveSync())
: store.save(next);
}
//
// If we don't have a callback and the current
// store is capable of saving synchronously
// then do so.
//
if (!callback) {
return common.merge(names.map(saveStoreSync));
}
async.map(names, saveStore, function (err, objs) {
return err ? callback(err) : callback();
});
};
//
// ### @private function _execute (action, syncLength, [arguments])
// #### @action {string} Action to execute on `this.store`.
// #### @syncLength {number} Function length of the sync version.
// #### @arguments {Array} Arguments array to apply to the action
// Executes the specified `action` on all stores for this instance, ensuring a callback supplied
// to a synchronous store function is still invoked.
//
Provider.prototype._execute = function (action, syncLength /* [arguments] */) {
var args = Array.prototype.slice.call(arguments, 2),
callback = typeof args[args.length - 1] === 'function' && args.pop(),
destructive = ['set', 'clear', 'merge'].indexOf(action) !== -1,
self = this,
response;
function runAction (name, next) {
var store = self.stores[name];
if (destructive && store.readOnly) {
return next();
}
return store[action].length > syncLength
? store[action].apply(store, args.concat(next))
: next(null, store[action].apply(store, args));
}
if (callback) {
return async.forEach(Object.keys(this.stores), runAction, function (err) {
return err ? callback(err) : callback();
});
}
Object.keys(this.stores).forEach(function (name) {
if (typeof response === 'undefined') {
var store = self.stores[name];
if (destructive && store.readOnly) {
return;
}
response = store[action].apply(store, args);
}
});
return response;
}
//
// Throw the `err` if a callback is not supplied
//
function onError(err, callback) {
if (callback) {
return callback(err);
}
throw err;
} | linyows/forever | node_modules/nconf/lib/nconf/provider.js | JavaScript | mit | 13,317 |
import React from 'react';
import { storiesOf } from '@storybook/react';
import moment from 'moment';
import {
withKnobs,
number,
object,
boolean,
text,
select,
date,
array,
color,
files,
} from '../../src';
const stories = storiesOf('Example of Knobs', module);
stories.addDecorator(withKnobs);
stories.add('simple example', () => <button>{text('Label', 'Hello Button')}</button>);
stories.add('with all knobs', () => {
const name = text('Name', 'Tom Cary');
const dob = date('DOB', new Date('January 20 1887'));
const bold = boolean('Bold', false);
const selectedColor = color('Color', 'black');
const favoriteNumber = number('Favorite Number', 42);
const comfortTemp = number('Comfort Temp', 72, { range: true, min: 60, max: 90, step: 1 });
const passions = array('Passions', ['Fishing', 'Skiing']);
const images = files('Happy Picture', 'image/*', [
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QA/4ePzL8AAAAHdElNRQfiARwMCyEWcOFPAAAAP0lEQVQoz8WQMQoAIAwDL/7/z3GwghSp4KDZyiUpBMCYUgd8rehtH16/l3XewgU2KAzapjXBbNFaPS6lDMlKB6OiDv3iAH1OAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE4LTAxLTI4VDEyOjExOjMzLTA3OjAwlAHQBgAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxOC0wMS0yOFQxMjoxMTozMy0wNzowMOVcaLoAAAAASUVORK5CYII=',
]);
const customStyle = object('Style', {
fontFamily: 'Arial',
padding: 20,
});
const style = {
...customStyle,
fontWeight: bold ? 800 : 400,
favoriteNumber,
color: selectedColor,
};
return (
<div style={style}>
I'm {name} and I was born on "{moment(dob).format('DD MMM YYYY')}" I like:{' '}
<ul>{passions.map(p => <li key={p}>{p}</li>)}</ul>
<p>My favorite number is {favoriteNumber}.</p>
<p>My most comfortable room temperature is {comfortTemp} degrees Fahrenheit.</p>
<p>
When I am happy I look like this: <img src={images[0]} alt="happy" />
</p>
</div>
);
});
stories.add('dates Knob', () => {
const today = date('today');
const dob = date('DOB', null);
const myDob = date('My DOB', new Date('July 07 1993'));
return (
<ul style={{ listStyleType: 'none', listStyle: 'none', paddingLeft: '15px' }}>
<li>
<p>
<b>Javascript Date</b> default value, passes date value
</p>
<blockquote>
<code>const myDob = date('My DOB', new Date('July 07 1993'));</code>
<pre>{`// I was born in: "${moment(myDob).format('DD MMM YYYY')}"`}</pre>
</blockquote>
</li>
<li>
<p>
<b>undefined</b> default value passes today's date
</p>
<blockquote>
<code>const today = date('today');</code>
<pre>{`// Today's date is: "${moment(today).format('DD MMM YYYY')}"`}</pre>
</blockquote>
</li>
<li>
<p>
<b>null</b> default value passes null value
</p>
<blockquote>
<code>const dob = date('DOB', null);</code>
<pre>
{`// You were born in: "${
dob ? moment(dob).format('DD MMM YYYY') : 'Please select date.'
}"`}
</pre>
</blockquote>
</li>
</ul>
);
});
stories.add('dynamic knobs', () => {
const showOptional = select('Show optional', ['yes', 'no'], 'yes');
return (
<div>
<div>{text('compulsary', 'I must be here')}</div>
{showOptional === 'yes' ? <div>{text('optional', 'I can disapear')}</div> : null}
</div>
);
});
stories.add('without any knob', () => <button>This is a button</button>);
| rhalff/storybook | addons/knobs/example/stories/index.js | JavaScript | mit | 3,615 |
import { expect } from 'chai'
import { describe, it } from 'mocha'
import { or } from 'opensource-challenge-client/helpers/or'
describe('Unit | Helper | or', function() {
it('works', function() {
expect(or([42, 42])).to.equal(true)
expect(or([false, 42, false])).to.equal(true)
expect(or([true, 42])).to.equal(true)
expect(or([null, undefined, 1])).to.equal(true)
})
})
| opensource-challenge/opensource-challenge-client | tests/unit/helpers/or-test.js | JavaScript | mit | 392 |
/* */
define(['exports', './i18n', 'aurelia-event-aggregator', 'aurelia-templating', './utils'], function (exports, _i18n, _aureliaEventAggregator, _aureliaTemplating, _utils) {
'use strict';
exports.__esModule = true;
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var TValueConverter = (function () {
TValueConverter.inject = function inject() {
return [_i18n.I18N];
};
function TValueConverter(i18n) {
_classCallCheck(this, TValueConverter);
this.service = i18n;
}
TValueConverter.prototype.toView = function toView(value, options) {
return this.service.tr(value, options);
};
return TValueConverter;
})();
exports.TValueConverter = TValueConverter;
var TParamsCustomAttribute = (function () {
_createClass(TParamsCustomAttribute, null, [{
key: 'inject',
value: [Element],
enumerable: true
}]);
function TParamsCustomAttribute(element) {
_classCallCheck(this, _TParamsCustomAttribute);
this.element = element;
}
TParamsCustomAttribute.prototype.valueChanged = function valueChanged() {};
var _TParamsCustomAttribute = TParamsCustomAttribute;
TParamsCustomAttribute = _aureliaTemplating.customAttribute('t-params')(TParamsCustomAttribute) || TParamsCustomAttribute;
return TParamsCustomAttribute;
})();
exports.TParamsCustomAttribute = TParamsCustomAttribute;
var TCustomAttribute = (function () {
_createClass(TCustomAttribute, null, [{
key: 'inject',
value: [Element, _i18n.I18N, _aureliaEventAggregator.EventAggregator, _utils.LazyOptional.of(TParamsCustomAttribute)],
enumerable: true
}]);
function TCustomAttribute(element, i18n, ea, tparams) {
_classCallCheck(this, _TCustomAttribute);
this.element = element;
this.service = i18n;
this.ea = ea;
this.lazyParams = tparams;
}
TCustomAttribute.prototype.bind = function bind() {
var _this = this;
this.params = this.lazyParams();
setTimeout(function () {
if (_this.params) {
_this.params.valueChanged = function (newParams, oldParams) {
_this.paramsChanged(_this.value, newParams, oldParams);
};
}
var p = _this.params !== null ? _this.params.value : undefined;
_this.subscription = _this.ea.subscribe('i18n:locale:changed', function () {
_this.service.updateValue(_this.element, _this.value, p);
});
setTimeout(function () {
_this.service.updateValue(_this.element, _this.value, p);
});
});
};
TCustomAttribute.prototype.paramsChanged = function paramsChanged(newValue, newParams) {
this.service.updateValue(this.element, newValue, newParams);
};
TCustomAttribute.prototype.valueChanged = function valueChanged(newValue) {
var p = this.params !== null ? this.params.value : undefined;
this.service.updateValue(this.element, newValue, p);
};
TCustomAttribute.prototype.unbind = function unbind() {
this.subscription.dispose();
};
var _TCustomAttribute = TCustomAttribute;
TCustomAttribute = _aureliaTemplating.customAttribute('t')(TCustomAttribute) || TCustomAttribute;
return TCustomAttribute;
})();
exports.TCustomAttribute = TCustomAttribute;
}); | mbroadst/aurelia-plunker | jspm_packages/npm/aurelia-i18n@0.4.1/t.js | JavaScript | mit | 4,011 |
class sppcomapi_elevationconfig_1 {
constructor() {
// ISPPLUA Elevated () {get}
this.Elevated = undefined;
// bool IsElevated () {get}
this.IsElevated = undefined;
// _ElevationConfigOptions Mode () {get} {set}
this.Mode = undefined;
// uint64 UIHandle () {set}
this.UIHandle = undefined;
}
// void ConfigureObject (IUnknown)
ConfigureObject(IUnknown) {
}
}
module.exports = sppcomapi_elevationconfig_1;
| mrpapercut/wscript | testfiles/COMobjects/JSclasses/SppComApi.ElevationConfig.1.js | JavaScript | mit | 498 |
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
// require rails-ujs
//= require turbolinks
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require bootstrap.file-input
document.addEventListener("turbolinks:load", function() {
if ($('.btn-file').length === 0) {
$('input[type=file]').bootstrapFileInput();
$('.file-inputs').bootstrapFileInput();
}
});
$(document).ready(function() {
// Javascript for button validation
$(document).on('click', 'input[type=radio]', function() {
el = $(this);
col = el.data("col");
el
.parents(".table")
.find("input[data-col=" + col + "]")
.prop("checked", false);
el.prop("checked", true);
})
// Javascript for submit button validation
$(document).on('click', '#quizSubmit', function() {
var questions = validate_form();
if(questions.size == 0 ) {
return;
}
else {
questionString = "";
questions.forEach(function(value) {
questionString = questionString + ", " + value;
});
if (questions.size == 1) {
alert("Please finish question" + questionString.substring(1) + " before submitting!");
} else {
alert("Please finish questions" + questionString.substring(1) + " before submitting!");
}
event.preventDefault();
}
})
// Iterates through all answers and checks that they are ranked
// Returns 0 if all are checked, otherwise returns first question that isn't finished
function validate_form() {
var numbers = new Set();
scroll = 0;
for (i = 1; i < 19; i++) {
$("#q" + i).css("border", "2px solid white");
for (j = 1; j < 5; j++) {
name = "q" + i + "a" + j;
if ($("input[name='" + name + "']:checked").length == 0) {
numbers.add(i);
$("#q" + i).css("border", "2px solid red");
if (scroll == 0) {
var top = $('#q' + i).position().top;
$(window).scrollTop( top - 75); //Offset because header blocks some of screen
scroll = 1;
}
}
}
}
return numbers;
}
// Prevents arrow keys from moving radio button
$(document).on('click', 'input[type=radio]', function() {
document.addEventListener("keydown", function (e) {
if ([37].indexOf(e.keyCode) > -1) { // left
e.preventDefault();
window.scrollBy(-50, -0);
}
if ([38].indexOf(e.keyCode) > -1) { //up
e.preventDefault();
window.scrollBy(0, -50);
}
if ([39].indexOf(e.keyCode) > -1) { //right
e.preventDefault();
window.scrollBy(50, 0);
}
if([40].indexOf(e.keyCode) > -1) { //down
e.preventDefault();
window.scrollBy(0, 50);
}
}, false);
})
});
| famendola1/Worksheet-Digitalization | app/assets/javascripts/application.js | JavaScript | mit | 3,217 |
version https://git-lfs.github.com/spec/v1
oid sha256:7678f6e4188a6066c45fd9a295882aea8e986bbc11eea3dbeabf24eca190b774
size 394
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.17.1/calendar-base/lang/calendar-base_ru.js | JavaScript | mit | 128 |
version https://git-lfs.github.com/spec/v1
oid sha256:d1ae7db9f7928706e5601ba8c7d71d4c9fbd1c4463c6b6465b502115eae45c07
size 77153
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.17.1/matrix/matrix-coverage.js | JavaScript | mit | 130 |
"use strict";
////////////////////////////////////////////////////////////////////////////////
// デスクトップ通知履歴
////////////////////////////////////////////////////////////////////////////////
Contents.notify_history = function( cp )
{
var p = $( '#' + cp.id );
var cont = p.find( 'div.contents' );
var notify_history_list;
var scrollPos = null;
cp.SetIcon( 'icon-bubble' );
////////////////////////////////////////////////////////////
// リスト部作成
////////////////////////////////////////////////////////////
var ListMake = function( type ) {
var s = '';
for ( var i = g_cmn.notsave.notify_history.length - 1 ; i >= 0 ; i-- )
{
var assign = {};
for ( var arg in g_cmn.notsave.notify_history[i].data )
{
try {
assign[arg] = decodeURIComponent( g_cmn.notsave.notify_history[i].data[arg] );
}
catch ( err )
{
assign[arg] = g_cmn.notsave.notify_history[i].data[arg];
}
}
s += OutputTPL( 'notify_' + g_cmn.notsave.notify_history[i].type, assign );
}
notify_history_list.html( s )
.scrollTop( 0 );
notify_history_list.find( '.notify' ).each( function() {
var account_id = $( this ).attr( 'account_id' );
$( this ).find( '.notify_username' ).click( function( e ) {
OpenUserTimeline( $( this ).attr( 'src' ), account_id );
e.stopPropagation();
} );
$( this ).find( '.notify_dmname' ).click( function( e ) {
var _cp = new CPanel( null, null, 360, $( window ).height() * 0.75 );
_cp.SetType( 'timeline' );
_cp.SetParam( {
account_id: account_id,
timeline_type: 'dmrecv',
reload_time: g_cmn.cmn_param['reload_time'],
} );
_cp.Start();
e.stopPropagation();
} );
$( this ).find( '.notify_followname' ).click( function( e ) {
var _cp = new CPanel( null, null, 320, 360 );
var num = $( this ).attr( 'num' );
_cp.SetType( 'follow' );
_cp.SetParam( {
type: 'followers',
account_id: account_id,
screen_name: g_cmn.account[account_id].screen_name,
number: num,
} );
_cp.Start();
e.stopPropagation();
} );
$( this ).find( '.notify_listname' ).click( function( e ) {
var _cp = new CPanel( null, null, 360, $( window ).height() * 0.75 );
_cp.SetType( 'timeline' );
_cp.SetParam( {
account_id: account_id,
timeline_type: 'list',
list_id: $( this ).attr( 'list_id' ),
screen_name: $( this ).attr( 'screen_name' ),
slug: $( this ).attr( 'slug' ),
reload_time: g_cmn.cmn_param['reload_time'],
} );
_cp.Start();
e.stopPropagation();
} );
} );
cont.trigger( 'contents_resize' );
};
////////////////////////////////////////////////////////////
// 開始処理
////////////////////////////////////////////////////////////
this.start = function() {
////////////////////////////////////////
// 最小化/設定切替時のスクロール位置
// 保存/復元
////////////////////////////////////////
cont.on( 'contents_scrollsave', function( e, type ) {
// 保存
if ( type == 0 )
{
if ( scrollPos == null )
{
scrollPos = notify_history_list.scrollTop();
}
}
// 復元
else
{
if ( scrollPos != null )
{
notify_history_list.scrollTop( scrollPos );
scrollPos = null;
}
}
} );
////////////////////////////////////////
// リサイズ処理
////////////////////////////////////////
cont.on( 'contents_resize', function() {
$( '#notify_history_list' ).height( cont.height() - cont.find( '.panel_btns' ).height() - 1 );
} );
// 全体を作成
cont.addClass( 'notify_history' )
.html( OutputTPL( 'notify_history', {} ) );
notify_history_list = $( '#notify_history_list' );
////////////////////////////////////////
// 更新ボタンクリック
////////////////////////////////////////
$( '#notify_history_reload' ).click( function( e ) {
// disabledなら処理しない
if ( $( this ).hasClass( 'disabled' ) )
{
return;
}
ListMake();
} );
// リスト部作成処理
ListMake();
};
////////////////////////////////////////////////////////////
// 終了処理
////////////////////////////////////////////////////////////
this.stop = function() {
};
}
| hotuta/hottwi | js/contents/notify_history.js | JavaScript | mit | 4,259 |
import net from 'net';
import log from './log.js';
export default function(options, onConnect) {
// proxy server
let proxy = net.createServer(function(client) {
let server;
// Create a new connection to the target server
server = net.connect(options.port);
// 2-way pipe between proxy and target server
client.pipe(server).pipe(client);
client.on('close', function() {
server.end();
});
server.on('close', function() {
client.end();
});
client.on('error', function(err) {
log.error('Client: ' + err.toString());
client.end();
server.end();
});
server.on('error', function(err) {
log.error('Server: ' + err.toString());
client.end();
server.end();
});
onConnect(client, server);
});
proxy.listen(options.proxyPort);
}
| flashhhh/node-pg-spy | src/proxy.js | JavaScript | mit | 839 |
'use strict';
var util = require('util')
, yeoman = require('yeoman-generator')
, github = require('../lib/github')
, path = require('path')
, inflect = require('inflect');
var BBBGenerator = module.exports = function BBBGenerator(args, options, config) {
// By calling `NamedBase` here, we get the argument to the subgenerator call
// as `this.name`.
yeoman.generators.NamedBase.apply(this, arguments);
if (!this.name) {
this.log.error('You have to provide a name for the subgenerator.');
process.exit(1);
}
this.on('end', function () {
this.installDependencies({ skipInstall: options['skip-install'] });
// Set destination root back to project root to help with testability
this.destinationRoot('../../');
});
this.appName = this.name;
this.destPath = util.format('client/%s', this.appName);
};
util.inherits(BBBGenerator, yeoman.generators.NamedBase);
BBBGenerator.prototype.askFor = function askFor() {
var cb = this.async();
// have Yeoman greet the user.
console.log(this.yeoman);
var prompts = [{
name: 'githubUser',
message: 'Tell me again your username on Github?',
default: 'someuser'
},{
name: 'appDescription',
message: 'Give this app a description',
},{
name: 'version',
message: 'What is the starting version number for this app you\'d like to use?',
default: '0.1.0'
}];
this.prompt(prompts, function (props) {
this.githubUser = props.githubUser;
this.appDescription = props.appDescription;
this.version = props.version;
cb();
}.bind(this));
};
BBBGenerator.prototype.userInfo = function userInfo() {
var self = this
, done = this.async();
github.githubUserInfo(this.githubUser, function (res) {
/*jshint camelcase:false */
self.realname = res.name;
self.email = res.email;
self.githubUrl = res.html_url;
done();
});
};
BBBGenerator.prototype.createDestFolder = function createDestFolder() {
this.mkdir(this.destPath);
this.destinationRoot(path.join(this.destinationRoot(), this.destPath));
};
BBBGenerator.prototype.fetchBoilerplate = function fetchBoilerplate() {
var self = this
, done = this.async();
this.remote('duro', 'clutch-backbone-boilerplate', function(err, remote) {
self.sourceRoot(remote.cachePath);
done();
});
};
BBBGenerator.prototype.buildApp = function buildSkeleton() {
var self = this;
this.directory('.','.');
};
| duro/generator-clutch | bbb/index.js | JavaScript | mit | 2,456 |
import {mount, render, shallow} from 'enzyme';
global.mount = mount;
global.render = render;
global.shallow = shallow;
| wzolleis/fitness_aws_react_client | src/__tests__/helpers.js | JavaScript | mit | 120 |
'use strict';
var _require = require('./parseProps'),
parsePropTypes = _require.parsePropTypes,
parseDefaultProps = _require.parseDefaultProps,
resolveToValue = require('./util/resolveToValue');
module.exports = function (state) {
var json = state.result,
components = state.seen;
var isAssigning = function isAssigning(node, name) {
return node.operator === '=' && node.left.property && node.left.property.name === name;
};
var seenClass = function seenClass(name, scope) {
return components.indexOf(name) !== -1 && scope.hasBinding(name);
};
return {
enter: function enter(_ref) {
var node = _ref.node,
scope = _ref.scope;
var component = node.left.object && node.left.object.name;
if (isAssigning(node, 'propTypes') && seenClass(component, scope)) parsePropTypes(resolveToValue(node.right, scope), json[component], scope);else if (isAssigning(node, 'defaultProps') && seenClass(component, scope)) {
parseDefaultProps(resolveToValue(node.right, scope), json[component], state.file, scope);
}
}
};
}; | jquense/react-component-metadata | lib/assignment-visitor.js | JavaScript | mit | 1,098 |
'use strict';
const expect = require('chai').expect;
const deepfind = require('../index');
const simpleFixture = {
'key': 'value'
};
const complexFixture = {
'key1': {
'key': 'value1'
},
'key2': {
'key': 'value2'
},
'key3': {
'key': 'value3'
}
};
describe('deepfind', () => {
it('should throw an error when given no object', () => {
expect(() => deepfind(null, 'key')).to.throw('deepfind must be supplied an object');
});
it('should throw an error when given no key', () => {
expect(() => deepfind({}, null)).to.throw('deepfind must be supplied a key');
});
it('should return an empty array when no key is found', () => {
expect(deepfind({}, 'key')).to.be.an.array;
expect(deepfind({}, 'key')).to.be.empty;
});
it('should return an array when one value matches', () => {
expect(deepfind(simpleFixture, 'key')).to.be.an.array;
expect(deepfind(simpleFixture, 'key')).to.deep.equal(['value']);
});
it('should return an array when multiple values match', () => {
expect(deepfind(complexFixture, 'key')).to.be.an.array;
expect(deepfind(complexFixture, 'key')).to.deep.equal(['value1', 'value2', 'value3'])
});
});
| lemonJS/DeepFind | test/index.js | JavaScript | mit | 1,197 |
/**
* Created by Roman on 16.12.13.
*/
var moment = require('moment');
function AuthController($scope, $api) {
var ctrl = this;
$scope.client_id = store.get('client_id');
$scope.api_key = store.get('api_key');
$scope.api_secret = store.get('api_secret');
$scope.err = null;
// catch html pieces
var $modal = $('#modal-auth').modal({backdrop: true, show: false});
$scope.authenticate_clicked = function(){
NProgress.start();
$scope.err = null;
// validate keys and update scopes
$api.bitstamp.get_transactions($scope.api_key, $scope.api_secret, $scope.client_id)
.success(function(transactions){
$modal.modal('hide');
// save data
store.set('client_id', $scope.client_id);
store.set('api_key', $scope.api_key);
store.set('api_secret', $scope.api_secret);
store.set('transactions', transactions);
store.set('transactions_updated', moment().unix());
// notify parent that we authenticated
$scope.$parent.authenticated();
NProgress.done();
})
.error(function(){
$scope.err = "Failed to verify credentials. Are they correct?";
NProgress.done();
});
};
// init code
$('#btn-start').click(function(){
$modal.modal('show');
});
}
module.exports = AuthController;
| rnikitin/bitcapitalist | public/js/app/controllers/AuthController.js | JavaScript | mit | 1,499 |
require('babel-core/register')
const path = require('path')
const jsdom = require('jsdom').jsdom
const exposedProperties = ['window', 'navigator', 'document']
global.document = jsdom('')
global.window = document.defaultView
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property)
global[property] = document.defaultView[property]
}
})
global.navigator = {
userAgent: 'node.js'
}
global.__base = `${path.resolve()}/`
| ritz078/react-component-boilerplate | tests/config/setup.js | JavaScript | mit | 515 |
module.exports = (client, reaction, user) => {
client.log('Log', `${user.tag} reagiu à mensagem de id ${reaction.message.id} com a reação: ${reaction.emoji}`);
}; | GiuliannoO/Giulianno | events/messageReactionAdd.js | JavaScript | mit | 167 |
const exec = require('child_process').exec;
const ver = require('../package.json').version;
let hash;
module.exports.init = function (b) {
exec('git rev-parse HEAD', (error, stdout, stderr) => {
if (error != null) {
hash = null;
console.err("git's broken yo");
}
hash = stdout;
});
};
module.exports.run = function (r, parts, reply) {
reply(`${ver}: ${hash}`);
};
module.exports.commands = ['version'];
| gmackie/EuIrcBot | modules/version.js | JavaScript | mit | 438 |
/*!
Tiny table
*/
var TINY = {};
function T$(i) {
return document.getElementById(i);
}
function T$$(e, p) {
return p.getElementsByTagName(e);
}
TINY.table = function() {
function sorter(n, t, p) {
this.n = n;
this.id = t;
this.p = p;
if (this.p.init) {
this.init();
}
}
sorter.prototype.init = function() {
this.set();
var t = this.t, i = d = 0;
t.h = T$$('tr', t)[0];
if (t.r.length !== 0) {
t.l = t.r.length;
t.w = t.r[0].cells.length;
if (t.r.length > this.p.size) {
$('#' + this.p.navid).show();
$('.' + this.p.navid).show();
}
t.a = [];
t.c = [];
this.p.is = this.p.size;
if (this.p.colddid) {
d = T$(this.p.colddid);
var o = document.createElement('option');
o.value = -1;
o.innerHTML = 'Todas las columnas';
d.appendChild(o);
}
for (i; i < t.w; i++) {
var c = t.h.cells[i];
t.c[i] = {};
if (c.className != 'nosort') {
c.className = this.p.headclass;
c.onclick = new Function(this.n + '.sort(' + i + ')');
c.onmousedown = function() {
return false;
};
}
if (this.p.columns) {
var l = this.p.columns.length, x = 0;
for (x; x < l; x++) {
if (this.p.columns[x].index == i) {
var g = this.p.columns[x];
t.c[i].format = g.format == null ? 1 : g.format;
t.c[i].decimals = g.decimals == null ? 2 : g.decimals;
}
}
}
if (d) {
var o = document.createElement('option');
o.value = i;
o.innerHTML = T$$('span', c)[0].innerHTML;
d.appendChild(o);
}
}
this.reset();
}
};
sorter.prototype.reset = function() {
var t = this.t;
t.t = t.l;
for (var i = 0; i < t.l; i++) {
t.a[i] = {};
t.a[i].s = 1;
}
if (this.p.sortcolumn != undefined) {
this.sort(this.p.sortcolumn, 1, this.p.is);
} else {
if (this.p.paginate) {
this.size();
}
this.alt();
this.sethover();
}
this.calc();
};
sorter.prototype.sort = function(x, f, z) {
var t = this.t;
t.y = x;
var x = t.h.cells[t.y], i = 0, n = document.createElement('tbody');
for (i; i < t.l; i++) {
t.a[i].o = i;
var v = t.r[i].cells[t.y];
t.r[i].style.display = '';
while (v.hasChildNodes()) {
v = v.firstChild;
}
t.a[i].v = v.nodeValue ? v.nodeValue : '';
}
for (i = 0; i < t.w; i++) {
var c = t.h.cells[i];
if (c.className != 'nosort') {
c.className = this.p.headclass;
}
}
if (t.p == t.y && !f) {
t.a.reverse();
x.className = t.d ? this.p.ascclass : this.p.descclass;
t.d = t.d ? 0 : 1;
}
else {
t.p = t.y;
f && this.p.sortdir == -1 ? t.a.sort(cp).reverse() : t.a.sort(cp);
t.d = 0;
x.className = this.p.ascclass;
}
$(t.h.cells).children().children().removeClass().addClass('glyphicon glyphicon-sort');
var addclass = t.h.cells[t.p].className == 'asc' ? 'glyphicon glyphicon-sort-by-attributes' : 'glyphicon glyphicon-sort-by-attributes-alt';
$(t.h.cells[t.p]).children().children().removeClass().addClass(addclass);
for (i = 0; i < t.l; i++) {
var r = t.r[t.a[i].o].cloneNode(true);
n.appendChild(r);
}
t.replaceChild(n, t.b);
this.set();
this.alt();
if (this.p.paginate) {
this.size(z);
}
this.sethover();
};
sorter.prototype.sethover = function() {
if (this.p.hoverid) {
for (var i = 0; i < this.t.l; i++) {
var r = this.t.r[i];
r.setAttribute('onmouseover', this.n + '.hover(' + i + ',1)');
r.setAttribute('onmouseout', this.n + '.hover(' + i + ',0)');
}
}
};
sorter.prototype.calc = function() {
if (this.p.sum || this.p.avg) {
var t = this.t, i = x = 0, f, r;
if (!T$$('tfoot', t)[0]) {
f = document.createElement('tfoot');
t.appendChild(f);
} else {
f = T$$('tfoot', t)[0];
while (f.hasChildNodes()) {
f.removeChild(f.firstChild);
}
}
if (this.p.sum) {
r = this.newrow(f);
for (i; i < t.w; i++) {
var j = r.cells[i];
if (this.p.sum.exists(i)) {
var s = 0, m = t.c[i].format || '';
for (x = 0; x < this.t.l; x++) {
if (t.a[x].s) {
s += parseFloat(t.r[x].cells[i].innerHTML.replace(/(\$|\,)/g, ''));
}
}
s = decimals(s, t.c[i].decimals ? t.c[i].decimals : 2);
s = isNaN(s) ? 'n/a' : m == '$' ? s = s.currency(t.c[i].decimals) : s + m;
r.cells[i].innerHTML = s;
} else {
r.cells[i].innerHTML = ' ';
}
}
}
if (this.p.avg) {
r = this.newrow(f);
for (i = 0; i < t.w; i++) {
var j = r.cells[i];
if (this.p.avg.exists(i)) {
var s = c = 0, m = t.c[i].format || '';
for (x = 0; x < this.t.l; x++) {
if (t.a[x].s) {
s += parseFloat(t.r[x].cells[i].innerHTML.replace(/(\$|\,)/g, ''));
c++;
}
}
s = decimals(s / c, t.c[i].decimals ? t.c[i].decimals : 2);
s = isNaN(s) ? 'n/a' : m == '$' ? s = s.currency(t.c[i].decimals) : s + m;
j.innerHTML = s;
} else {
j.innerHTML = ' ';
}
}
}
}
};
sorter.prototype.newrow = function(p) {
var r = document.createElement('tr'), i = 0;
p.appendChild(r);
for (i; i < this.t.w; i++) {
r.appendChild(document.createElement('td'));
}
return r;
};
sorter.prototype.alt = function() {
var t = this.t, i = x = 0;
for (i; i < t.l; i++) {
var r = t.r[i];
if (t.a[i].s) {
r.className = x % 2 == 0 ? this.p.evenclass : this.p.oddclass;
var cells = T$$('td', r);
for (var z = 0; z < t.w; z++) {
cells[z].className = t.y == z ? x % 2 == 0 ? this.p.evenselclass : this.p.oddselclass : '';
}
x++;
}
if (!t.a[i].s) {
r.style.display = 'none';
}
}
};
sorter.prototype.page = function(s) {
var t = this.t, i = x = 0, l = s + parseInt(this.p.size);
if (this.p.totalrecid) {
T$(this.p.totalrecid).innerHTML = t.t;
}
if (this.p.currentid) {
T$(this.p.currentid).innerHTML = this.g;
}
if (this.p.startingrecid) {
var b = ((this.g - 1) * this.p.size) + 1, m = b + (this.p.size - 1);
m = m < t.l ? m : t.t;
m = m < t.t ? m : t.t;
T$(this.p.startingrecid).innerHTML = t.t == 0 ? 0 : b;
;
T$(this.p.endingrecid).innerHTML = m;
}
for (i; i < t.l; i++) {
var r = t.r[i];
if (t.a[i].s) {
r.style.display = x >= s && x < l ? '' : 'none';
x++;
} else {
r.style.display = 'none';
}
}
};
sorter.prototype.addfirstdisclass = function() {
$('.prev-page').parent().addClass('disabled');
$('.first-page').parent().addClass('disabled');
};
sorter.prototype.addlastdisclass = function() {
$('.next-page').parent().addClass('disabled');
$('.last-page').parent().addClass('disabled');
};
sorter.prototype.removefirstdisclass = function() {
$('.prev-page').parent().removeClass('disabled');
$('.first-page').parent().removeClass('disabled');
};
sorter.prototype.removelastdisclass = function() {
$('.next-page').parent().removeClass('disabled');
$('.last-page').parent().removeClass('disabled');
};
sorter.prototype.disablepag = function(d, m) {
var selval = parseInt($('#pagedropdown').find(":selected").val());
var selsumres = selval + parseInt(d);
var optionsize = $('#pagedropdown option').size();
if (m) {
if (d > 0) {
$("#pagedropdown").val(optionsize).attr('selected', true);
this.removefirstdisclass();
this.addlastdisclass();
} else if (d < 0) {
$("#pagedropdown").val(1).attr('selected', true);
this.removelastdisclass();
this.addfirstdisclass();
}
} else {
if (d > 0) {
this.addlastdisclass();
if (selval < optionsize - 1) {
$("#pagedropdown").val(selsumres).attr('selected', true);
this.removefirstdisclass();
this.removelastdisclass();
} else if (selval === optionsize - 1) {
$("#pagedropdown").val(selsumres).attr('selected', true);
this.removefirstdisclass();
}
} else if (d < 0) {
this.addfirstdisclass();
if (selval > 2) {
$("#pagedropdown").val(selsumres).attr('selected', true);
this.removelastdisclass();
this.removefirstdisclass();
} else if (selval === 2) {
$("#pagedropdown").val(selsumres).attr('selected', true);
this.removelastdisclass();
}
}
}
};
sorter.prototype.mueve = function(d, m) {
this.vea(d == 1 ? (m ? this.d : this.g + 1) : (m ? 1 : this.g - 1));
this.disablepag(d, m);
};
sorter.prototype.vea = function(s) {
if (s <= this.d && s > 0) {
this.g = s;
this.page((s - 1) * this.p.size);
}
if (s == 1) {
this.removelastdisclass();
this.addfirstdisclass();
} else if (s == ((parseInt(this.p.size) - parseInt(1)))) {
this.removefirstdisclass();
this.addlastdisclass();
} else {
this.removelastdisclass();
this.removefirstdisclass();
}
};
sorter.prototype.size = function(s) {
var t = this.t;
if (s) {
this.p.size = s;
}
this.g = 1;
this.d = Math.ceil(this.t.t / this.p.size);
this.page(0);
if (this.p.totalid) {
T$(this.p.totalid).innerHTML = t.t == 0 ? 1 : this.d;
}
if (this.p.pageddid) {
var d = T$(this.p.pageddid), l = this.d + 1;
d.setAttribute('onchange', this.n + '.vea(this.value)');
while (d.hasChildNodes()) {
d.removeChild(d.firstChild);
}
for (var i = 1; i <= this.d; i++) {
var o = document.createElement('option');
o.value = i;
o.innerHTML = i;
d.appendChild(o);
}
}
this.removelastdisclass();
this.addfirstdisclass();
};
sorter.prototype.showall = function() {
this.size(this.t.t);
};
sorter.prototype.search = function(f) {
var i = x = n = 0, k = -1, q = T$(f).value.toLowerCase();
if (this.p.colddid) {
k = T$(this.p.colddid).value;
}
var s = (k == -1) ? 0 : k, e = (k == -1) ? this.t.w : parseInt(s) + 1;
for (i; i < this.t.l; i++) {
var r = this.t.r[i], v;
if (q == '') {
v = 1;
} else {
for (x = s; x < e; x++) {
var b = r.cells[x].innerHTML.toLowerCase();
if (b.indexOf(q) == -1) {
v = 0;
} else {
v = 1;
break;
}
}
}
if (v) {
n++;
}
this.t.a[i].s = v;
}
this.t.t = n;
if (this.p.paginate) {
this.size();
}
this.calc();
this.alt();
};
sorter.prototype.hover = function(i, d) {
this.t.r[i].id = d ? this.p.hoverid : '';
};
sorter.prototype.set = function() {
var t = T$(this.id);
t.b = T$$('tbody', t)[0];
t.r = t.b.rows;
this.t = t;
};
Array.prototype.exists = function(v) {
for (var i = 0; i < this.length; i++) {
if (this[i] == v) {
return 1;
}
}
return 0;
};
Number.prototype.currency = function(c) {
var n = this, d = n.toFixed(c).split('.');
d[0] = d[0].split('').reverse().join('').replace(/(\d{3})(?=\d)/g, '$1,').split('').reverse().join('');
return '$' + d.join('.');
};
function decimals(n, d) {
return Math.round(n * Math.pow(10, d)) / Math.pow(10, d);
}
function cp(f, c) {
var g, h;
f = g = f.v.toLowerCase();
c = h = c.v.toLowerCase();
var i = parseFloat(f.replace(/(\$|\,)/g, '')), n = parseFloat(c.replace(/(\$|\,)/g, ''));
if (!isNaN(i) && !isNaN(n)) {
g = i, h = n;
}
i = Date.parse(f);
n = Date.parse(c);
if (!isNaN(i) && !isNaN(n)) {
g = i;
h = n;
}
return g > h ? 1 : (g < h ? -1 : 0);
}
return { sorter: sorter };
}(); | CollDev/terapiyo | web/js/tinyTableV3.js | JavaScript | mit | 14,941 |
(function () {
function getQueryVariable(variable) {
var query = window.location.search.substring(1),
vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] === variable) {
return pair[1];
}
}
}
function getPreview(query, content, previewLength) {
previewLength = previewLength || (content.length * 2);
var parts = query.split(" "),
match = content.toLowerCase().indexOf(query.toLowerCase()),
matchLength = query.length,
preview;
// Find a relevant location in content
for (var i = 0; i < parts.length; i++) {
if (match >= 0) {
break;
}
match = content.toLowerCase().indexOf(parts[i].toLowerCase());
matchLength = parts[i].length;
}
// Create preview
if (match >= 0) {
var start = match - (previewLength / 2),
end = start > 0 ? match + matchLength + (previewLength / 2) : previewLength;
preview = content.substring(start, end).trim();
if (start > 0) {
preview = "..." + preview;
}
if (end < content.length) {
preview = preview + "...";
}
// Highlight query parts
preview = preview.replace(new RegExp("(" + parts.join("|") + ")", "gi"), "<strong>$1</strong>");
} else {
// Use start of content if no match found
preview = content.substring(0, previewLength).trim() + (content.length > previewLength ? "..." : "");
}
return preview;
}
function displaySearchResults(results, query) {
var searchResultsEl = document.getElementById("search-results"),
searchProcessEl = document.getElementById("search-process");
if (results.length) {
var resultsHTML = "";
results.forEach(function (result) {
var item = window.data[result.ref],
contentPreview = getPreview(query, item.content, 170),
titlePreview = getPreview(query, item.title);
resultsHTML += "<li><h4><a href='" + item.url.trim() + "'>" + titlePreview + "</a></h4><p><small>" + contentPreview + "</small></p></li>";
});
searchResultsEl.innerHTML = resultsHTML;
searchProcessEl.innerText = "Exibindo";
} else {
searchResultsEl.style.display = "none";
searchProcessEl.innerText = "No";
}
}
window.index = lunr(function () {
this.field("id");
this.field("title", {boost: 10});
this.field("date");
this.field("url");
this.field("content");
});
var query = decodeURIComponent((getQueryVariable("q") || "").replace(/\+/g, "%20")),
searchQueryContainerEl = document.getElementById("search-query-container"),
searchQueryEl = document.getElementById("search-query");
searchQueryEl.innerText = query;
searchQueryContainerEl.style.display = "inline";
for (var key in window.data) {
window.index.add(window.data[key]);
}
displaySearchResults(window.index.search(query), query); // Hand the results off to be displayed
})();
| macielbombonato/macielbombonato.github.io | _site/assets/js/search.js | JavaScript | mit | 2,822 |
define([
"./core",
"./core/access",
"./var/document",
"./var/documentElement",
"./css/var/rnumnonpx",
"./css/curCSS",
"./css/addGetHookIf",
"./css/support",
"./core/init",
"./css",
"./selector" // contains
], function( jQuery, access, document, documentElement, rnumnonpx, curCSS, addGetHookIf, support ) {
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
// Preserve chaining for setter
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none) or disconnected
if ( rect.width || rect.height || elem.getClientRects().length ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// Assume getBoundingClientRect is there when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
// Subtract offsetParent scroll positions
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ) -
offsetParent.scrollTop();
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ) -
offsetParent.scrollLeft();
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent;
while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : win.pageXOffset,
top ? val : win.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Support: Safari<7+, Chrome<37+
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// If curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
return jQuery;
});
| macrodatalab/browser-bosh | jquerysrc/src/offset.js | JavaScript | mit | 6,155 |
import UnitConverter from '../../../UnitConverter'
import { Fraction, mul, div } from '../../../../numbers'
import { Mass } from '../../domains'
import { UnitedStates } from '../../authorities'
import { OunceConverter } from '../../us/customary/mass'
import { ChickenEggs } from '../../systems'
import { Jumbo, VeryLarge, Large, Medium, Small, Peewee } from '../../units'
const jumboScalar = new Fraction(5, 2)
export const JumboConverter =
new UnitConverter(
Mass,
UnitedStates,
ChickenEggs,
Jumbo,
OunceConverter,
value => mul(value, jumboScalar),
value => div(value, jumboScalar))
const veryLargeScalar = new Fraction(9, 4)
export const VeryLargeConverter =
new UnitConverter(
Mass,
UnitedStates,
ChickenEggs,
VeryLarge,
OunceConverter,
value => mul(value, veryLargeScalar),
value => div(value, veryLargeScalar))
const largeScalar = 2
export const LargeConverter =
new UnitConverter(
Mass,
UnitedStates,
ChickenEggs,
Large,
OunceConverter,
value => mul(value, largeScalar),
value => div(value, largeScalar))
const mediumScalar = new Fraction(7, 4)
export const MediumConverter =
new UnitConverter(
Mass,
UnitedStates,
ChickenEggs,
Medium,
OunceConverter,
value => mul(value, mediumScalar),
value => div(value, mediumScalar))
const smallScalar = new Fraction(3, 2)
export const SmallConverter =
new UnitConverter(
Mass,
UnitedStates,
ChickenEggs,
Small,
OunceConverter,
value => mul(value, smallScalar),
value => div(value, smallScalar))
const peeweeScalar = new Fraction(5, 4);
export const PeeweeConverter =
new UnitConverter(
Mass,
UnitedStates,
ChickenEggs,
Peewee,
OunceConverter,
value => mul(value, peeweeScalar),
value => div(value, peeweeScalar))
export function collectUnitConverters() {
return [
JumboConverter,
VeryLargeConverter,
LargeConverter,
MediumConverter,
SmallConverter,
PeeweeConverter
]
} | rob-blackbourn/scratch-js | react-converter/src/converters/definitions/us/food/chickenEggs.js | JavaScript | mit | 2,237 |
'use strict';
var path = require('path');
var generators = require('yeoman-generator');
var yaml = require('js-yaml');
var _ = require('lodash');
var chalk = require('chalk');
var GitHub = require('github');
module.exports = generators.Base.extend({
_logHeading: function (msg) {
this.log("\n");
this.log.writeln(chalk.bold(msg));
this.log.writeln(chalk.bold('-------------------------------'));
},
_listPlugins: function () {
var github = new GitHub({
version: '3.0.0'
});
github.search.repos({
q: 'wok-plugin+in:name'
}, function (err, response) {
console.log(response.items.length);
});
},
// The name `constructor` is important here
constructor: function () {
// Calling the super constructor is important so our generator is correctly set up
generators.Base.apply(this, arguments);
this.answers = {};
},
askForProject: function () {
var done = this.async();
var _utils = this._;
this._logHeading('Collecting new project infos...');
var prompts = [{
type: 'text',
name: 'name',
message: 'Project name',
'default': 'awesome-wok-project',
filter: function (value) {
return _utils.slugify(value)
}
}, {
type: 'text',
name: 'description',
message: 'Project description',
'default': 'Awesome WOK Project'
}, {
type: 'text',
name: 'author',
message: 'Author',
'default': this.user.git.name()
}, {
type: 'text',
name: 'license',
message: 'License',
'default': 'MIT'
}];
this.prompt(prompts, function (answers) {
this.answers.projectData = answers;
done();
}.bind(this));
},
askForFolders: function () {
var done = this.async();
var _utils = this._;
this._logHeading('Filesystem setup...');
var prompts = [ {
type: 'text',
name: 'www',
message: 'Public assets folder',
'default': 'www',
filter: function (value) {
return _utils.slugify(value)
}
}];
this.prompt(prompts, function (answers) {
answers.rsync = answers.www;
this.answers.folders = answers;
done();
}.bind(this));
},
fetchRepo: function () {
var done = this.async();
this.remote('fevrcoding', 'wok', 'master', function (err, remote, files) {
if (err) {
//TODO manage error
this.log.error('Unable to download latest version of https://github.com/fevrcoding/wok');
return false;
}
this.wokRepo = remote;
this.wokFiles = files;
done();
}.bind(this));
//this._listPlugins();
},
copyFiles: function () {
var remote = this.wokRepo;
var files = this.wokFiles;
//copy main application folder
remote.directory('application', 'application');
//build folder
remote.dest.mkdir('build');
//copy unchanged configuration files
['hosts.yml', 'properties.yml'].forEach(function (filename) {
var fullpath = path.join('build', 'grunt-config', filename);
remote.copy(fullpath, fullpath);
});
//copy unchanged files
['build/Gruntfile.js', 'build/compass.rb', 'bower.json', 'Gemfile'].forEach(function (filepath) {
remote.copy(filepath, filepath);
});
//copy dot files
files.filter(function (path) {
return path.indexOf('.') === 0 && path !== '.bowerrc';
}).forEach(function (el) {
remote.copy(el, el);
});
},
package: function () {
var pkg = this.wokRepo.src.readJSON('package.json');
pkg = _.extend(pkg || {}, {
version: '0.0.1',
contributors: []
}, this.answers.projectData);
this.wokRepo.dest.write('package.json', JSON.stringify(pkg, null, 4));
return pkg;
},
config: function (remote) {
var remote = this.wokRepo;
var pathCfg = yaml.safeLoad(remote.src.read('build/grunt-config/paths.yml'));
var defaultPublic = pathCfg.www;
pathCfg = _.extend(pathCfg, this.answers.folders);
remote.dest.write('build/grunt-config/paths.yml', yaml.safeDump(pathCfg));
//public www data to destination public folder
remote.directory(defaultPublic, pathCfg.www);
//write .bowerrc
remote.dest.write('.bowerrc', JSON.stringify({directory: pathCfg.www + '/vendor'}, null, 4));
return pathCfg;
},
readme: function () {
//generate an empty readme file
this.wokRepo.dest.write('README.md', '#' + this.answers.projectDescription + "\n\n");
},
install: function () {
if (!this.options['skip-install']) {
this.spawnCommand('bundler', ['install']);
this.installDependencies({
skipMessage: true
});
}
var template = _.template('\n\nI\'m all done. ' +
'<%= skipInstall ? "Just run" : "Running" %> <%= commands %> ' +
'<%= skipInstall ? "" : "for you " %>to install the required dependencies.' +
'<% if (!skipInstall) { %> If this fails, try running the command yourself.<% } %>\n\n'
);
this.log(template({
skipInstall: this.options['skip-install'],
commands: chalk.yellow.bold(['bower install', 'npm install', 'bundler install'].join(' & '))
}));
}
}); | fevrcoding/generator-wok | app/index.js | JavaScript | mit | 5,876 |
class MetaFloorController extends MRM.MetaBaseWallController{
constructor(dom){
super(dom);
this.dom = dom;
this.metaObject = this.createMetaObject()
this.metaVerse = null;
this.setupComponent();
this.updateMetaObject();
}
get metaAttachedActions(){
return {
attachMetaObject: true,
assignRoomDimension: true
}
}
get propertiesSettings(){
return {
width: { type: Number, default: 1 },
length: { type: Number, default: 1 },
roomWidth: {
type: Number,
default: 1,
onChange: "updateMetaObject"
},
roomHeight: {
type: Number,
default: 1,
onChange: "updateMetaObject"
},
roomLength: {
type: Number,
default: 1,
onChange: "updateMetaObject"
}
};
}
get tagName() {
return "meta-floor"
}
get metaChildrenNames(){
return ["meta-table", "meta-picture", "meta-text", "meta-board", "meta-item"]
}
get eventActionSettings(){
return {
"meta-style": ['propagateMetaStyle'],
"class": ["propagateMetaStyle"],
"id": ["propagateMetaStyle"]
}
}
updateMetaObject() {
var mesh = this.metaObject.mesh;
var group = this.metaObject.group;
this.properties.width = this.properties.roomWidth;
this.properties.length = this.properties.roomLength;
group.rotation.x = 270 * (Math.PI/180);
group.position.set(0, 0 , 0);
mesh.scale.set(this.properties.roomWidth, this.properties.roomLength , 1);
this.updateChildrenDisplayInline();
}
}
class MetaFloor extends MRM.MetaComponent {
createdCallback() {
this.controller = new MetaFloorController(this);
super.createdCallback();
}
metaDetached(e) {
var targetController = e.detail.controller;
if (this.controller.isChildren(targetController.tagName) ){
e.stopPropagation();
this.controller.metaObject.group.remove(targetController.metaObject.group);
}
}
metaChildAttributeChanged(e){
var targetController = e.detail.controller;
var attrName = e.detail.attrName
if (this.controller.isChildren(targetController.tagName) ){
if(targetController.isAllowedAttribute(attrName)) {
if (e.detail.actions.updateChildrenDisplayInline) {
this.controller.updateChildrenDisplayInline()
delete e.detail.actions.updateChildrenDisplayInline
}
}
}
}
}
document.registerElement('meta-floor', MetaFloor);
| cbas/MetaRoomMarkup | src/meta-floor.js | JavaScript | mit | 2,486 |
import 'isomorphic-fetch'
import base64 from 'base-64'
import utf8 from 'utf8'
import Request from './Request'
function encodeAccount(username, password) {
let bytes = utf8.encode(`${ username }:${ password }`)
return base64.encode(bytes)
}
export default class Stormpath {
constructor({ application, authentication } = {}) {
this.application = application
this.authentication = authentication
}
retrieveApplication() {
let url = `https://api.stormpath.com/v1/applications/${ this.application }/accounts`
let options = { authentication: this.authentication }
return Request.get(url, options)
}
createAccount(payload) {
let url = `https://api.stormpath.com/v1/applications/${ this.application }/accounts`
let options = {
authentication: this.authentication,
payload: payload
}
return Request.post(url, options)
}
retrieveAccount(account) {
let url = `https://api.stormpath.com/v1/accounts/${ account }`
let options = {
authentication: this.authentication
}
return Request.get(url, options)
}
authenticateAccount({ username, password } = {}) {
let url = `https://api.stormpath.com/v1/applications/${ this.application }/loginAttempts`
//url = 'http://requestb.in/uwektzuw'
let payload = {
type: 'basic',
value: encodeAccount(username, password)
}
let options = {
authentication: this.authentication,
payload: payload
}
return Request.post(url, options)
}
}
if (require.main === module) {
const credentials = {
application: 'zDhRIszpk93AwssJDXuPs',
authentication: {
username: '1HU99B538PG3SW50K5M2NPJBW',
password: '7ukbB9oDRjgyMEX/057SKtAwwLtOR3fbKvNQOp4i/uI'
}
}
const account = {
givenName: 'Denis',
surname: 'Storm',
username: 'DenisCarriere',
email: 'foo.bar2@gmail.com',
password: 'Denis44C',
customData: { number: 4 }
}
const stormpath = new Stormpath(credentials)
//stormpath.createAccount(account)
//stormpath.retrieveApplication()
stormpath.authenticateAccount(account)
stormpath.retrieveAccount('3NElH12QutCmRSi3e6PAmI')
.then(
data => console.log(data),
error => console.log(error)
)
}
| KrateLabs/KrateLabs-REST | app/utils/Stormpath.js | JavaScript | mit | 2,234 |
/* global Fae, SimpleMDE, toolbarBuiltInButtons */
/**
* Fae form text
* @namespace form.text
* @memberof form
*/
Fae.form.text = {
init: function() {
this.overrideMarkdownDefaults();
this.initMarkdown();
},
/**
* Override SimpleMDE's preference for font-awesome icons and use a modal for the guide
* @see {@link modals.markdownModal}
*/
overrideMarkdownDefaults: function() {
toolbarBuiltInButtons['bold'].className = 'icon-bold';
toolbarBuiltInButtons['italic'].className = 'icon-italic';
toolbarBuiltInButtons['heading'].className = 'icon-font';
toolbarBuiltInButtons['code'].className = 'icon-code';
toolbarBuiltInButtons['unordered-list'].className = 'icon-list-ul';
toolbarBuiltInButtons['ordered-list'].className = 'icon-list-ol';
toolbarBuiltInButtons['link'].className = 'icon-link';
toolbarBuiltInButtons['image'].className = 'icon-image';
toolbarBuiltInButtons['quote'].className = 'icon-quote';
toolbarBuiltInButtons['fullscreen'].className = 'icon-fullscreen no-disable no-mobile';
toolbarBuiltInButtons['horizontal-rule'].className = 'icon-minus';
toolbarBuiltInButtons['preview'].className = 'icon-eye no-disable';
toolbarBuiltInButtons['side-by-side'].className = 'icon-columns no-disable no-mobile';
toolbarBuiltInButtons['guide'].className = 'icon-question';
// Override SimpleMDE's default guide and use a homegrown modal
toolbarBuiltInButtons['guide'].action = Fae.modals.markdownModal;
},
/**
* Find all markdown fields and initialize them with a markdown GUI
* @has_test {features/form_helpers/fae_input_spec.rb}
*/
initMarkdown: function() {
$('.js-markdown-editor:not(.mde-enabled)').each(function() {
var $this = $(this);
var editor = new SimpleMDE({
element: this,
autoDownloadFontAwesome: false,
status: false,
spellChecker: false,
hideIcons: ['image', 'side-by-side', 'fullscreen', 'preview']
});
// Disable tabbing within editor
editor.codemirror.options.extraKeys['Tab'] = false;
editor.codemirror.options.extraKeys['Shift-Tab'] = false;
$this.addClass('mde-enabled');
// code mirror events to hook into current form element functions
editor.codemirror.on('change', function(){
// updates the original textarea's value for JS validations
$this.val(editor.value());
// update length counter
Fae.form.validator.length_counter.updateCounter($this);
});
editor.codemirror.on('focus', function(){
$this.parent().addClass('mde-focus');
});
editor.codemirror.on('blur', function(){
// trigger blur on the original textarea to trigger JS validations
$this.blur();
$this.parent().removeClass('mde-focus');
});
});
}
};
| emersonthis/fae | app/assets/javascripts/fae/form/inputs/_text.js | JavaScript | mit | 2,856 |
'use babel';
// eslint-disable-next-line
import { CompositeDisposable, TextEditor, Directory } from 'atom';
import config from './config';
import Creator from './Creator';
import Insertor from './Insertor';
class DavsPackage {
constructor() {
this.reactReduxUtilsView = null;
this.modalPanel = null;
this.subscriptions = null;
this.config = config;
}
activate() {
// Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
this.subscriptions = new CompositeDisposable();
this.creator = new Creator();
this.insertor = new Insertor();
// Register command that toggles this view
this.subscriptions.add(atom.commands.add('atom-workspace', {
'davs-package:create': context => this.create(context),
'davs-package:insert': context => this.insert(context),
'core:confirm': (event) => {
this.creator.confirmSelection();
event.stopPropagation();
},
}));
}
deactivate() {
this.subscriptions.dispose();
}
create(context) {
this.creator.create(context);
}
insert() {
this.insertor.insert();
}
}
export default new DavsPackage();
| el-dav/davs-package | lib/davs-package.js | JavaScript | mit | 1,177 |
import React from 'react';
import PropTypes from 'prop-types';
import Text from '../Text/Text';
import { Styled } from './CalloutGroupItem.styles';
const CalloutGroupItem = ({ text, imgSrc, imgAlt, emoji }) => {
return (
<>
{!imgSrc ? (
!emoji ? (
<Text>{text}</Text>
) : (
<Text>
<Styled.CalloutGroupItemTool>
<Styled.CalloutGroupItemEmoji role="img"
aria-label={imgAlt}>
{emoji}
</Styled.CalloutGroupItemEmoji>
{text}
</Styled.CalloutGroupItemTool>
</Text>
)
) : (
<Text>
<Styled.CalloutGroupItemTool>
<Styled.CalloutGroupItemLogo src={imgSrc}
alt={imgAlt}
aria-label={imgAlt} />
{text}
</Styled.CalloutGroupItemTool>
</Text>
)}
</>
);
};
CalloutGroupItem.defaultProps = {
imgSrc: null,
imgAlt: null,
emoji: null,
};
CalloutGroupItem.propTypes = {
emoji: PropTypes.string,
text: PropTypes.oneOfType([PropTypes.node, PropTypes.string]).isRequired,
imgSrc: PropTypes.node,
imgAlt: PropTypes.string,
};
export default CalloutGroupItem;
| matthewgallo/portfolio | src/components/DetailPage/CalloutGroupItem.js | JavaScript | mit | 1,081 |
// Render home page and json data
exports.view = function(req, res){
// Import json data
var logData = require("../data/log.json");
// Set ateFoodGroup to numerical values
var ateGrains;
if(req.body.ateGrains == null){ateGrains = 0;}
else ateGrains = 1;
var ateFruit;
if(req.body.ateFruit == null){ateFruit = 0;}
else ateFruit = 1;
var ateDairy;
if(req.body.ateDairy == null){ateDairy = 0;}
else ateDairy = 1;
var ateProtein;
if(req.body.ateProtein == null){ateProtein = 0;}
else ateProtein = 1;
var ateVeggies;
if(req.body.ateVeggies == null){ateVeggies = 0;}
else ateVeggies = 1;
// Creat new JSON and append to log
var newLog = {
"id": logData.length + 1,
"name": req.body.food,
"dd": req.body.dd,
"mm": req.body.mm,
"year": req.body.yy,
"cal": parseInt(req.body.cal),
"mood": parseInt(req.body.mood),
"info": req.body.info,
"image": "public/images/food/oj.jpg",
"ateGrains": ateGrains,
"ateFruit": ateFruit,
"ateVeggies": ateVeggies,
"ateProtein": ateProtein,
"ateDairy": ateDairy
}
logData.push(newLog);
var newData = JSON.stringify(logData);
var fs = require('fs');
fs.writeFile("data/log.json",newData, function(err) {
if(err) {
return console.log(err);
}
console.log("The new log was saved!");
res.redirect('/vet');
});
};
| siddarthrg/fido_tracker | routes/feed_save.js | JavaScript | mit | 1,341 |
var expect = require('expect.js');
var Promise = require('bluebird');
var ZugZug = require('../lib/zugzug');
var Job = require('../lib/job');
describe('job.delete():Promise(self)', function() {
var zz, job;
beforeEach(function() {
zz = new ZugZug();
job = new Job(zz, 'default');
});
afterEach(function(done) {
Promise.promisify(zz._client.flushall, zz._client)()
.then(zz.quit.bind(zz))
.done(function() {done();});
});
it('returns a promise', function(done) {
job.save()
.then(function() {
var p = job.delete();
expect(p).to.be.a(Promise);
return p.thenReturn();
})
.done(done);
});
it('resolves to the instance', function(done) {
job.save()
.then(function() {
return job.delete();
})
.then(function(res) {
expect(res).to.equal(job);
})
.done(done);
});
it('deletes the job from the database', function(done) {
var id;
job.save()
.then(function() {
expect(job.id).to.equal('1');
id = job.id;
return job.delete();
})
.then(function() {
return zz.getJob(id);
})
.then(function(res) {
expect(res).to.equal(null);
})
.done(done);
});
it('resets the job\'s state', function(done) {
job.save()
.then(function() {
return job.delete();
})
.then(function() {
expect(job.id).to.be(undefined);
expect(job.created).to.be(undefined);
expect(job.updated).to.be(undefined);
expect(job.state).to.be(undefined);
})
.done(done);
});
it('deletes the job\'s log', function(done) {
var id;
job.save()
.then(function() {
expect(job.id).to.equal('1');
id = job.id;
return job.delete();
})
.then(function() {
var m = zz._client.multi()
.llen('zugzug:job:' + id + ':log');
return Promise.promisify(m.exec, m)();
})
.spread(function(newlen) {
expect(newlen).to.equal(0);
})
.done(done);
});
}); | pluma/zugzug | spec/job_delete.spec.js | JavaScript | mit | 1,989 |
'use strict';
module.exports = {
app: {
title: 'Surf Around The Corner',
description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
keywords: 'MongoDB, Express, AngularJS, Node.js'
},
port: process.env.PORT || 3000,
templateEngine: 'swig',
sessionSecret: 'MEAN',
sessionCollection: 'sessions',
assets: {
lib: {
css: [
'public/lib/components-font-awesome/css/font-awesome.css',
'public/lib/angular-ui-select/dist/select.css',
'http://fonts.googleapis.com/css?family=Bree+Serif',
'http://fonts.googleapis.com/css?family=Open+Sans',
'http://fonts.googleapis.com/css?family=Playfair+Display',
'http://fonts.googleapis.com/css?family=Dancing+Script',
'http://fonts.googleapis.com/css?family=Nunito'
//'http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css'
],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/jquery/dist/jquery.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
'public/lib/angular-ui-select/dist/select.js',
'public/lib/ng-lodash/build/ng-lodash.js',
'public/lib/ng-backstretch/dist/ng-backstretch.js',
'public/lib/ngFitText/src/ng-FitText.js'
]
},
css: [
'public/less/*.css',
'public/modules/**/css/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
};
| flimble/surfaroundthecorner | config/env/all.js | JavaScript | mit | 1,896 |
// anonymous closure - BEGIN
(function(jQuery){
// anonymous closure - BEGIN
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// include microevent.js //
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
var microevent = function(){}
microevent.prototype = {
fcts : {},
bind : function(event, fct){
this.fcts[event] = this.fcts[event] || [];
this.fcts[event].push(fct);
return this;
},
unbind : function(event, fct){
console.assert(typeof fct === 'function')
var arr = this.fcts[event];
if( typeof arr !== 'undefined' ) return this;
console.assert(arr.indexOf(fct) !== -1);
arr.splice(arr.indexOf(fct), 1);
return this;
},
trigger : function(event /* , args... */){
var arr = this.fcts[event];
if( typeof arr === 'undefined' ) return this;
for(var i = 0; i < arr.length; i++){
arr[i].apply(this, Array.prototype.slice.call(arguments, 1))
}
return this;
}
};
microevent.mixin = function(destObject){
var props = ['bind', 'unbind', 'trigger'];
for(var i = 0; i < props.length; i ++){
destObject.prototype[props[i]] = microevent.prototype[props[i]];
}
destObject.prototype['fcts'] = {};
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// Acewidget class //
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* The internal class of the jquery plugin
*
* - it has an event emitter.
* - acewidget.bind('load', function(){console.log("widget loaded")})
* - acewidget.unbind('load', function(){console.log("widget loaded")})
})
*/
var Acewidget = function(ctorOpts, jQueryContainer) {
var self = this;
// determine the options
var opts = jQuery.extend(true, {}, {
width : "600px",
height : "400px",
theme : "twilight",
mode : "javascript",
iframeUrl : "http://jeromeetienne.github.com/acewidget/iframe.html"
}, ctorOpts);
// build the queryUrl
var queryUrl = "";
if( opts.theme) queryUrl += (queryUrl?"&":'') + "theme="+opts.theme;
if( opts.mode ) queryUrl += (queryUrl?"&":'') + "mode=" +opts.mode;
// init some variables
var finalUrl = opts.iframeUrl + (queryUrl?'?'+queryUrl:'')
var domId = "acewidget-"+Math.floor(Math.random()*99999).toString(36);
this.elemSelect = "#"+domId;
// build the dom element
var elem = jQuery("<iframe>").attr({
src : finalUrl,
id : domId,
width : opts.width,
height : opts.height
})
// empty the container and insert the just built element
$(jQueryContainer).empty().append(elem);
// bind the element 'load' event
jQuery(elem).bind("load", function(){ self.trigger("load"); });
// bind message
jQuery(window).bind('message', {self: this}, this._onMessage);
}
/**
* Destructor
*/
Acewidget.prototype.destroy = function(){
// unbind message
jQuery(window).unbind('message', this._onMessage);
jQuery(this.elemSelect).remove();
}
/**
* Received the message from the iframe
*/
Acewidget.prototype._onMessage = function(jQueryEvent){
var event = jQueryEvent.originalEvent;
//console.log("event.data", event.data);
var data = JSON.parse(event.data);
// notify the callback if specified
if( 'userdata' in data && 'callback' in data.userdata ){
//console.log("notify callback to", data.userdata.callback, "with", data)
var callback = window[data.userdata.callback];
// remove the callback from the dom
delete window[data.userdata.callback];
// remove the callback from data.userdata
// - thus the user get its userdata unchanged
delete data.userdata.callback;
// if data.userdata is now empty, remove it
if( Object.keys(data.userdata).length === 0 ) delete data.userdata;
// notify the caller
callback(data);
}
}
/**
* Send message to the iframe
*/
Acewidget.prototype._send = function(event, callback){
var iframeWin = jQuery(this.elemSelect).get(0).contentWindow;
// if a callback is present, install it now
if( callback ){
event.userdata = event.userdata || {}
event.userdata.callback = "acewidgetCall-"+Math.floor(Math.random()*99999).toString(36);
window[event.userdata.callback] = function(data){
callback(data)
};
}
// post the message
iframeWin.postMessage(JSON.stringify(event), "*");
}
/**
* Helper for setValue event
*
* - this is a helper function on top of acewidget.send()
*
* @param {String} text the text to push in acewidget
* @param {Function} callback will be notified with the result (jsend compliant)
*/
Acewidget.prototype.setValue = function(text, callback){
this._send({
type : "setValue",
data : {
text: text
}
}, callback);
}
/**
* Helper for setValue event
*
* - this is a helper function on top of acewidget.send()
*
* @param {String} text the text to push in acewidget
* @param {Function} callback will be notified with the result (jsend compliant)
*/
Acewidget.prototype.getValue = function(callback){
this._send({
type : "getValue"
}, callback);
}
/**
* Helper for setValue event
*
* - this is a helper function on top of acewidget.send()
*
* @param {String} text the text to push in acewidget
* @param {Function} callback will be notified with the result (jsend compliant)
*/
Acewidget.prototype.setTabSize = function(tabSize, callback){
this._send({
type : "setTabSize",
data : {
size: tabSize
}
}, callback);
}
// mixin microevent.js in Acewidget
microevent.mixin(Acewidget);
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// jQuery plugin itself //
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// declare the jquery plugin
jQuery.fn.acewidget = function(ctorOpts) {
var jQueryContainer = this;
return new Acewidget(ctorOpts, jQueryContainer)
}
// anonymous closure - END
})(jQuery)
// anonymous closure - END
| jeromeetienne/acewidget | contrib/jquery.acewidget/jquery.acewidget.js | JavaScript | mit | 6,321 |
"use strict";
var assert = require("assert");
var stringmap = require("stringmap");
var stringset = require("stringset");
var is = require("simple-is");
var fmt = require("simple-fmt");
var error = require("./error");
var UUID = 1;
function Scope(args) {
assert(is.someof(args.kind, ["hoist", "block", "catch-block"]));
assert(is.object(args.node));
assert(args.parent === null || is.object(args.parent));
this.uuid = UUID++;
// kind === "hoist": function scopes, program scope, injected globals
// kind === "block": ES6 block scopes
// kind === "catch-block": catch block scopes
this.kind = args.kind;
// the AST node the block corresponds to
this.node = args.node;
// parent scope
this.parent = args.parent;
// this Scope is a wrapper. wrapper scopes will be skipped from hoist scope searching
this.wrapper = !!args.wrapper;
// children scopes for easier traversal (populated internally)
this.children = [];
// scope declarations. decls[variable_name] = {
// kind: "fun" for functions,
// "param" for function parameters,
// "caught" for catch parameter
// "var",
// "const",
// "let"
// node: the AST node the declaration corresponds to
// from: source code index from which it is visible at earliest
// (only stored for "const", "let" [and "var"] nodes)
// }
this.decls = stringmap();
// variables (probably temporary) that are free-for-change
this.freeVariables = [];
// names of all declarations within this scope that was ever written
// TODO move to decls.w?
// TODO create corresponding read?
this.written = stringset();
// names of all variables declared outside this hoist scope but
// referenced in this scope (immediately or in child).
// only stored on hoist scopes for efficiency
// (because we currently generate lots of empty block scopes)
this.propagates = (this.kind === "hoist" ? stringset() : null);
// scopes register themselves with their parents for easier traversal
if (this.parent) {
this.parent.children.push(this);
}
}
Scope.setOptions = function(options) {
Scope.options = options;
};
Scope.prototype.print = function(indent) {
indent = indent || 0;
var scope = this;
var names = this.decls.keys().map(function(name) {
return fmt("{0} [{1}]", name, scope.decls.get(name).kind);
}).join(", ");
var propagates = this.propagates ? this.propagates.items().join(", ") : "";
console.log(fmt("{0}{1}: {2}. propagates: {3}", fmt.repeat(" ", indent), this.node.type, names, propagates));
this.children.forEach(function(c) {
c.print(indent + 2);
});
};
function isObjectPattern(node) {
return node && node.type === 'ObjectPattern';
}
function isArrayPattern(node) {
return node && node.type === 'ArrayPattern';
}
function isFunction(node) {
var type;
return node && ((type = node.type) === "FunctionDeclaration" || type === "FunctionExpression" || type === "ArrowFunctionExpression");
}
function isLoop(node) {
var type;
return node && ((type = node.type) === "ForStatement" || type === "ForInStatement" || type === "ForOfStatement" || type === "WhileStatement" || type === "DoWhileStatement");
}
function isBlockScoped(kind) {
return is.someof(kind, ["const", "let", "caught"]);
}
Scope.prototype.mutate = function(newKind) {
if( this.kind !== newKind ) {
assert(is.someof(newKind, ["hoist", "block", "catch-block"]));
this.kind = newKind;
this.propagates = (this.kind === "hoist" ? stringset() : null);
}
};
Scope.prototype.add = function(name, kind, node, referableFromPos, freeFromPosition, originalDeclarator) {
assert(is.someof(kind, ["fun", "param", "var", "caught", "const", "let", "get", "set"]), kind + " is a wrong kind");
var isGlobal = node && (node.range || [])[0] < 0;
if (!name && isObjectPattern(node)) {
node.properties.forEach(function(property) {
property && this.add(property.value.name, kind, property.value, referableFromPos, freeFromPosition, property.key);
}, this);
return;
}
if (!name && isArrayPattern(node)) {
node.elements.forEach(function(element) {
element && this.add(element.name, kind, element, element.range[0])
}, this);
return;
}
if (!name && node.type === "SpreadElement") {
name = node.argument.name;
}
function isConstLet(kind) {
return is.someof(kind, ["const", "let"]);
}
var scope = this;
// search nearest hoist-scope for fun, param and var's
// const, let and caught variables go directly in the scope (which may be hoist, block or catch-block)
if (is.someof(kind, ["fun", "param", "var"])) {
while (scope.kind !== "hoist") {
if (scope.decls.has(name) && isConstLet(scope.decls.get(name).kind)) { // could be caught
return error(node.loc.start.line, "{0} is already declared", name);
}
scope = scope.parent;
}
}
{// name exists in scope and either new or existing kind is const|let|catch => error
var hasAlready = scope.decls.has(name);
var existingKind;
if ( hasAlready ) {
existingKind = scope.decls.get(name).kind;
}
else {// Special test for "catch-block". Maybe it's not so prettily, but it works
var parentScope = scope.parent;
if ( parentScope && parentScope.kind === "catch-block" ) {
hasAlready = parentScope.decls.has(name)
&& (existingKind = parentScope.decls.get(name).kind) === "caught"
;
}
}
if ( hasAlready ) {
if ( kind == 'get' && existingKind == 'set' || kind == 'set' && existingKind == 'get' ) {
// all is fine
//TODO:: do something to allow getter and setter declaration both be in scope.decls
}
else if ( Scope.options.disallowDuplicated || isBlockScoped(existingKind) || isBlockScoped(kind) ) {
return error(node.loc.start.line, "{0} is already declared", name);
}
}
}
var declaration = {
kind: kind,
node: node,
isGlobal: isGlobal,
refs: [
/*reference node's*/
]
};
if ( referableFromPos !== void 0 ) {
assert(is.someof(kind, ["var", "const", "let"]), kind + " is not one of [var, const, let]");
if (originalDeclarator) {
declaration.from = originalDeclarator.range[0];
}
else {
declaration.from = referableFromPos;
}
}
if ( freeFromPosition !== void 0 ) {
assert(is.someof(kind, ["var", "const", "let"]), kind + " is not one of [var, const, let]");
if (originalDeclarator) {
declaration.to = originalDeclarator.range[1];
}
else {
declaration.to = freeFromPosition;
}
}
scope.decls.set(name, declaration);
};
Scope.prototype.getKind = function(name) {
assert(is.string(name), "name " + "'" + name + "' must be a string");
var decl = this.decls.get(name);
return decl ? decl.kind : null;
};
Scope.prototype.getNode = function(name) {
assert(is.string(name), "name " + "'" + name + "' must be a string");
var decl = this.decls.get(name);
return decl ? decl.node : null;
};
Scope.prototype.getFromPos = function(name) {
assert(is.string(name), "name " + "'" + name + "' must be a string");
var decl = this.decls.get(name);
return decl ? decl.from : null;
};
Scope.prototype.addRef = function(node) {
assert(node && typeof node === 'object');
var name = node.name;
assert(is.string(name), "name " + "'" + name + "' must be a string");
var decl = this.decls.get(name);
assert(decl, "could not find declaration for reference " + name);
decl.refs.push(node);
};
Scope.prototype.getRefs = function(name) {
assert(is.string(name), "name " + "'" + name + "' must be a string");
var decl = this.decls.get(name);
return decl ? decl.refs : null;
};
Scope.prototype.get = function(name) {
return this.decls.get(name);
};
Scope.prototype.hasOwn = function(name) {
return this.decls.has(name);
};
Scope.prototype.remove = function(name) {
return this.decls.delete(name);
};
Scope.prototype.pushFree = function(name, endsFrom) {
this.freeVariables.push({name: name, endsFrom: endsFrom});
return name;
};
Scope.prototype.popFree = function(startsFrom) {
var candidate;
for( var index = 0, length = this.freeVariables.length ; index < length ; index++ ) {
candidate = this.freeVariables[index];
if( candidate.endsFrom && candidate.endsFrom <= startsFrom ) {
this.freeVariables.splice(index, 1);
candidate = candidate.name;
break;
}
candidate = null;
}
return candidate || null;
};
Scope.prototype.doesPropagate = function(name) {
assert(this.kind === "hoist");
return this.kind === "hoist" && this.propagates.has(name);
};
Scope.prototype.markPropagates = function(name) {
assert(this.kind === "hoist");
this.propagates.add(name);
};
Scope.prototype.doesThisUsing = function() {
return this.__thisUsing || false;
};
Scope.prototype.markThisUsing = function() {
this.__thisUsing = true;
};
Scope.prototype.doesArgumentsUsing = function() {
return this.__argumentsUsing || false;
};
Scope.prototype.markArgumentsUsing = function() {
this.__argumentsUsing = true;
};
Scope.prototype.closestHoistScope = function() {
var scope = this;
while ( scope.kind !== "hoist" || scope.wrapper ) {
scope = scope.parent;
}
return scope;
};
Scope.prototype.lookup = function(name) {
for (var scope = this; scope; scope = scope.parent) {
if (scope.decls.has(name)
|| isFunction(scope.node)
&& scope.node.rest
&& scope.node.rest.name == name
) {
return scope;
} else if (scope.kind === "hoist") {
scope.propagates.add(name);
}
}
return null;
};
Scope.prototype.markWrite = function(name) {
assert(is.string(name), "name " + "'" + name + "' must be a string");
this.written.add(name);
};
// detects let variables that are never modified (ignores top-level)
Scope.prototype.detectUnmodifiedLets = function() {
var outmost = this;
function detect(scope) {
if (scope !== outmost) {
scope.decls.keys().forEach(function(name) {
if (scope.getKind(name) === "let" && !scope.written.has(name)) {
return error(scope.getNode(name).loc.start.line, "{0} is declared as let but never modified so could be const", name);
}
});
}
scope.children.forEach(function(childScope) {
detect(childScope);;
});
}
detect(this);
};
Scope.prototype.traverse = function(options) {
options = options || {};
var pre = options.pre;
var post = options.post;
function visit(scope) {
if (pre) {
pre(scope);
}
scope.children.forEach(function(childScope) {
visit(childScope);
});
if (post) {
post(scope);
}
}
visit(this);
};
//function __show(__a, scope) {
// __a += " " ;
//
// if( scope ) {
// console.log(__a + " | " + scope.uuid);
//
// if( (scope.children[0] || {}).uuid == scope.uuid ) {
// throw new Error("123")
// }
// scope.children.forEach(__show.bind(null, __a))
// }
//}
//
//Object.keys(Scope.prototype).forEach(function(name) {//wrap all
// var fun = Scope.prototype[name];
// Scope.prototype[name] = function() {
// try {
// return fun.apply(this, arguments);
// }
// catch(e) {
// console.error("ERROR:", name)
// __show(" ", this);
// }
// }
//})
module.exports = Scope;
| LarsMq73/Greenfield | src/client/node_modules/es6-loader/node_modules/es6-transpiler/build/es5/lib/scope.js | JavaScript | mit | 12,355 |
"use strict";var assert;module.watch(require('assert'),{default(v){assert=v}},0);var unhexArray;module.watch(require('./testutil'),{unhexArray(v){unhexArray=v}},1);var table;module.watch(require('../src/table'),{default(v){table=v}},2);
describe('table.js', function() {
it('should make a ScriptList table', function() {
// https://www.microsoft.com/typography/OTSPEC/chapter2.htm Examples 1 & 2
var expectedData = unhexArray(
'0003 68616E69 0014 6B616E61 0020 6C61746E 002E' + // Example 1 (hani, kana, latn)
'0004 0000 0000 FFFF 0001 0003' + // hani lang sys
'0004 0000 0000 FFFF 0002 0003 0004' + // kana lang sys
'000A 0001 55524420 0016' + // Example 2 for latn
'0000 FFFF 0003 0000 0001 0002' + // DefLangSys
'0000 0003 0003 0000 0001 0002' // UrduLangSys
);
assert.deepEqual(new table.ScriptList([
{ tag: 'hani', script: {
defaultLangSys: {
reserved: 0,
reqFeatureIndex: 0xffff,
featureIndexes: [3]
},
langSysRecords: [] } },
{ tag: 'kana', script: {
defaultLangSys: {
reserved: 0,
reqFeatureIndex: 0xffff,
featureIndexes: [3, 4]
},
langSysRecords: [] } },
{ tag: 'latn', script: {
defaultLangSys: {
reserved: 0,
reqFeatureIndex: 0xffff,
featureIndexes: [0, 1, 2]
},
langSysRecords: [{
tag: 'URD ',
langSys: {
reserved: 0,
reqFeatureIndex: 3,
featureIndexes: [0, 1, 2]
}
}]
} },
]).encode(), expectedData);
});
});
| lic3351/lingyang | node_modules/opentype.js/.reify-cache/de96b7a322c512a247dbf49cad92f67ae6c33fd6.js | JavaScript | mit | 2,060 |
/*jshint node:true */
module.exports = function( grunt ) {
"use strict";
var entryFiles = grunt.file.expandFiles( "entries/*.xml" );
grunt.loadNpmTasks( "grunt-clean" );
grunt.loadNpmTasks( "grunt-wordpress" );
grunt.loadNpmTasks( "grunt-jquery-content" );
grunt.loadNpmTasks( "grunt-check-modules" );
grunt.initConfig({
clean: {
folder: "dist"
},
lint: {
grunt: "grunt.js"
},
xmllint: {
all: [].concat( entryFiles, "categories.xml", "entries2html.xsl" )
},
xmltidy: {
all: [].concat( entryFiles, "categories.xml" )
},
"build-pages": {
all: grunt.file.expandFiles( "pages/**" )
},
"build-xml-entries": {
all: entryFiles
},
"build-resources": {
all: grunt.file.expandFiles( "resources/**" )
},
wordpress: grunt.utils._.extend({
dir: "dist/wordpress"
}, grunt.file.readJSON( "config.json" ) ),
watch: {
scripts: {
files: 'entries/*.xml',
tasks: ['wordpress-deploy'],
options: {
interrupt: true
}
}
}
});
grunt.registerTask( "default", "build-wordpress" );
grunt.registerTask( "build", "build-pages build-xml-entries build-xml-categories build-xml-full build-resources" );
grunt.registerTask( "build-wordpress", "check-modules clean lint xmllint build" );
grunt.registerTask( "tidy", "xmllint xmltidy" );
};
| angelozerr/tern.jqueryapi | api/jquery-mobile/1.5/grunt.js | JavaScript | mit | 1,265 |
var searchData=
[
['slot_5fcount',['SLOT_COUNT',['../classmastermind_1_1_mastermind.html#ad4cfc8127641ff8dfe89d65ae232331c',1,'mastermind::Mastermind']]]
];
| DocGerd/MastermindCPP | Documentation/html/search/variables_2.js | JavaScript | mit | 159 |
(function() {
var AS = this, Fn = AS.Fn;
// assign
$.extend(Fn, {
execConvPrint: execConvPrint
});
return;
function execConvPrint() {
var b_FPR = AS.Bo.FPR;
var fn = null;
try {
if(b_FPR.Value('convfn') == "function(i, f, a){\n}")
throw Error('Function is not modified');
fn = eval('(' + (b_FPR.Value('convfn') || null) + ')');
if(typeof fn != 'function')
throw Error('Not function.');
} catch(e) {
return b_FPR.error(e);
}
if(execConvPrint.last) // TODO remove
console.log(execConvPrint.last);
var fncs = b_FPR.Value('items[func]');
var args = b_FPR.Value('items[args]');
var memo = {};
fncs.forEach(function(func, i) {
var a = null;
try {
a = eval('(' + args[i] + ')');
} catch(e) {
return console.log('JSON.parse fail No.' + i, args[i]);
}
var nval = fn.call(b_FPR, i, func, $.extend(true, [], a));
nval && (function() {
console.log('changing idx[' + i + ']', a, nval);
b_FPR.Value('items[args][' + i + ']', JSON.stringify(nval));
memo[i] = {}, memo[i].func = func, memo[i].args = a;
})();
});
execConvPrint.last = memo;
b_FPR.notice('変換完了', Fn.noticeOpt());
}
}).call(window.AppSpace);
| EastCloud/synqueryERP | js/Fn_execConvPrint.js | JavaScript | mit | 1,309 |
const gulp = require('gulp');
const spawn = require('../lib/spawn');
const config = require('../config');
gulp.task('webpack', (callback) => {
if (config.context === 'production') {
process.env.NODE_ENV = 'production';
}
process.env.WEBPACK_CONTEXT = config.context;
const options = [];
if (config.context === 'watch') {
options.push('-w');
}
spawn('node_modules/.bin/webpack', options, callback);
});
| spatie-custom/blender-gulp | tasks/webpack.js | JavaScript | mit | 453 |
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2014 SAP AG or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.declare("sap.m.BusyDialogRenderer");sap.m.BusyDialogRenderer={};
sap.m.BusyDialogRenderer.render=function(r,c){r.write("<div");r.writeControlData(c);r.addClass("sapMBusyDialog sapMCommonDialog");if(jQuery.device.is.iphone){r.addClass("sapMDialogHidden")}if(!c._isPlatformDependent){if(!c.getText()&&!c.getTitle()&&!c.getShowCancelButton()){r.addClass("sapMBusyDialogSimple")}}if(sap.m._bSizeCompact){r.addClass("sapUiSizeCompact")}r.writeClasses();var t=c.getTooltip_AsString();if(t){r.writeAttributeEscaped("title",t)}r.write(">");if(c.getTitle()){r.write("<header class=\"sapMDialogTitle\">");r.writeEscaped(c.getTitle());r.write("</header>")}if(sap.ui.Device.os.ios||!c._isPlatformDependent){r.renderControl(c._oLabel);r.renderControl(c._busyIndicator)}else{r.renderControl(c._busyIndicator);r.renderControl(c._oLabel)}if(c.getShowCancelButton()){if(sap.ui.Device.system.phone){r.write("<footer class='sapMBusyDialogFooter sapMFooter-CTX'>");r.renderControl(c._oButton);r.write("</footer>")}else{r.renderControl(c._oButtonToolBar)}}r.write("</div>")};
| johnwargo/ac4p | chapter 17/ex17.5 - OpenUI5/resources/sap/m/BusyDialogRenderer.js | JavaScript | mit | 1,264 |
'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var Holodeck = require('../../../holodeck'); /* jshint ignore:line */
var Request = require(
'../../../../../lib/http/request'); /* jshint ignore:line */
var Response = require(
'../../../../../lib/http/response'); /* jshint ignore:line */
var RestException = require(
'../../../../../lib/base/RestException'); /* jshint ignore:line */
var Twilio = require('../../../../../lib'); /* jshint ignore:line */
var serialize = require(
'../../../../../lib/base/serialize'); /* jshint ignore:line */
var client;
var holodeck;
describe('Sink', function() {
beforeEach(function() {
holodeck = new Holodeck();
client = new Twilio('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'AUTHTOKEN', {
httpClient: holodeck
});
});
it('should generate valid fetch request',
function(done) {
holodeck.mock(new Response(500, {}));
var promise = client.events.v1.sinks('DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch();
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var sid = 'DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var url = `https://events.twilio.com/v1/Sinks/${sid}`;
holodeck.assertHasRequest(new Request({
method: 'GET',
url: url
}));
}
);
it('should generate valid fetch response',
function(done) {
var body = {
'status': 'initialized',
'sink_configuration': {
'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test',
'role_arn': 'arn:aws:iam::111111111:role/Role',
'external_id': '1234567890'
},
'description': 'A Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'date_created': '2015-07-30T20:00:00Z',
'sink_type': 'kinesis',
'date_updated': '2015-07-30T20:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate'
}
};
holodeck.mock(new Response(200, body));
var promise = client.events.v1.sinks('DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch();
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid create request',
function(done) {
holodeck.mock(new Response(500, {}));
var opts = {'description': 'description', 'sinkConfiguration': {}, 'sinkType': 'kinesis'};
var promise = client.events.v1.sinks.create(opts);
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var url = 'https://events.twilio.com/v1/Sinks';
var values = {
'Description': 'description',
'SinkConfiguration': serialize.object({}),
'SinkType': 'kinesis',
};
holodeck.assertHasRequest(new Request({
method: 'POST',
url: url,
data: values
}));
}
);
it('should generate valid create response',
function(done) {
var body = {
'status': 'initialized',
'sink_configuration': {
'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test',
'role_arn': 'arn:aws:iam::111111111:role/Role',
'external_id': '1234567890'
},
'description': 'My Kinesis Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'date_created': '2015-07-30T20:00:00Z',
'sink_type': 'kinesis',
'date_updated': '2015-07-30T20:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate'
}
};
holodeck.mock(new Response(201, body));
var opts = {'description': 'description', 'sinkConfiguration': {}, 'sinkType': 'kinesis'};
var promise = client.events.v1.sinks.create(opts);
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid create_segment response',
function(done) {
var body = {
'status': 'initialized',
'sink_configuration': {
'write_key': 'MY_WRITEKEY'
},
'description': 'My segment Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'date_created': '2015-07-30T20:00:00Z',
'sink_type': 'segment',
'date_updated': '2015-07-30T20:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate'
}
};
holodeck.mock(new Response(201, body));
var opts = {'description': 'description', 'sinkConfiguration': {}, 'sinkType': 'kinesis'};
var promise = client.events.v1.sinks.create(opts);
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid remove request',
function(done) {
holodeck.mock(new Response(500, {}));
var promise = client.events.v1.sinks('DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').remove();
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var sid = 'DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var url = `https://events.twilio.com/v1/Sinks/${sid}`;
holodeck.assertHasRequest(new Request({
method: 'DELETE',
url: url
}));
}
);
it('should generate valid delete response',
function(done) {
var body = null;
holodeck.mock(new Response(204, body));
var promise = client.events.v1.sinks('DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').remove();
promise.then(function(response) {
expect(response).toBe(true);
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should treat the first each arg as a callback',
function(done) {
var body = {
'sinks': [
{
'status': 'initialized',
'sink_configuration': {
'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test',
'role_arn': 'arn:aws:iam::111111111:role/Role',
'external_id': '1234567890'
},
'description': 'A Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'date_created': '2015-07-30T19:00:00Z',
'sink_type': 'kinesis',
'date_updated': '2015-07-30T19:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate'
}
},
{
'status': 'initialized',
'sink_configuration': {
'arn': 'arn:aws:kinesis:us-east-1:222222222:stream/test',
'role_arn': 'arn:aws:iam::111111111:role/Role',
'external_id': '1234567890'
},
'description': 'ANOTHER Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab',
'date_created': '2015-07-30T20:00:00Z',
'sink_type': 'kinesis',
'date_updated': '2015-07-30T20:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Validate'
}
},
{
'status': 'active',
'sink_configuration': {
'destination': 'http://example.org/webhook',
'method': 'POST',
'batch_events': true
},
'description': 'A webhook Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac',
'date_created': '2015-07-30T21:00:00Z',
'sink_type': 'webhook',
'date_updated': '2015-07-30T21:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Validate'
}
}
],
'meta': {
'page': 0,
'page_size': 20,
'first_page_url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0',
'previous_page_url': null,
'url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0',
'next_page_url': null,
'key': 'sinks'
}
};
holodeck.mock(new Response(200, body));
client.events.v1.sinks.each(() => done());
}
);
it('should treat the second arg as a callback',
function(done) {
var body = {
'sinks': [
{
'status': 'initialized',
'sink_configuration': {
'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test',
'role_arn': 'arn:aws:iam::111111111:role/Role',
'external_id': '1234567890'
},
'description': 'A Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'date_created': '2015-07-30T19:00:00Z',
'sink_type': 'kinesis',
'date_updated': '2015-07-30T19:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate'
}
},
{
'status': 'initialized',
'sink_configuration': {
'arn': 'arn:aws:kinesis:us-east-1:222222222:stream/test',
'role_arn': 'arn:aws:iam::111111111:role/Role',
'external_id': '1234567890'
},
'description': 'ANOTHER Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab',
'date_created': '2015-07-30T20:00:00Z',
'sink_type': 'kinesis',
'date_updated': '2015-07-30T20:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Validate'
}
},
{
'status': 'active',
'sink_configuration': {
'destination': 'http://example.org/webhook',
'method': 'POST',
'batch_events': true
},
'description': 'A webhook Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac',
'date_created': '2015-07-30T21:00:00Z',
'sink_type': 'webhook',
'date_updated': '2015-07-30T21:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Validate'
}
}
],
'meta': {
'page': 0,
'page_size': 20,
'first_page_url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0',
'previous_page_url': null,
'url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0',
'next_page_url': null,
'key': 'sinks'
}
};
holodeck.mock(new Response(200, body));
client.events.v1.sinks.each({pageSize: 20}, () => done());
holodeck.assertHasRequest(new Request({
method: 'GET',
url: 'https://events.twilio.com/v1/Sinks',
params: {PageSize: 20},
}));
}
);
it('should find the callback in the opts object',
function(done) {
var body = {
'sinks': [
{
'status': 'initialized',
'sink_configuration': {
'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test',
'role_arn': 'arn:aws:iam::111111111:role/Role',
'external_id': '1234567890'
},
'description': 'A Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'date_created': '2015-07-30T19:00:00Z',
'sink_type': 'kinesis',
'date_updated': '2015-07-30T19:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate'
}
},
{
'status': 'initialized',
'sink_configuration': {
'arn': 'arn:aws:kinesis:us-east-1:222222222:stream/test',
'role_arn': 'arn:aws:iam::111111111:role/Role',
'external_id': '1234567890'
},
'description': 'ANOTHER Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab',
'date_created': '2015-07-30T20:00:00Z',
'sink_type': 'kinesis',
'date_updated': '2015-07-30T20:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Validate'
}
},
{
'status': 'active',
'sink_configuration': {
'destination': 'http://example.org/webhook',
'method': 'POST',
'batch_events': true
},
'description': 'A webhook Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac',
'date_created': '2015-07-30T21:00:00Z',
'sink_type': 'webhook',
'date_updated': '2015-07-30T21:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Validate'
}
}
],
'meta': {
'page': 0,
'page_size': 20,
'first_page_url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0',
'previous_page_url': null,
'url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0',
'next_page_url': null,
'key': 'sinks'
}
};
holodeck.mock(new Response(200, body));
client.events.v1.sinks.each({callback: () => done()}, () => fail('wrong callback!'));
}
);
it('should generate valid list request',
function(done) {
holodeck.mock(new Response(500, {}));
var promise = client.events.v1.sinks.list();
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var url = 'https://events.twilio.com/v1/Sinks';
holodeck.assertHasRequest(new Request({
method: 'GET',
url: url
}));
}
);
it('should generate valid read_empty response',
function(done) {
var body = {
'sinks': [],
'meta': {
'page': 0,
'page_size': 10,
'first_page_url': 'https://events.twilio.com/v1/Sinks?PageSize=10&Page=0',
'previous_page_url': null,
'url': 'https://events.twilio.com/v1/Sinks?PageSize=10&Page=0',
'next_page_url': null,
'key': 'sinks'
}
};
holodeck.mock(new Response(200, body));
var promise = client.events.v1.sinks.list();
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid read_results response',
function(done) {
var body = {
'sinks': [
{
'status': 'initialized',
'sink_configuration': {
'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test',
'role_arn': 'arn:aws:iam::111111111:role/Role',
'external_id': '1234567890'
},
'description': 'A Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'date_created': '2015-07-30T19:00:00Z',
'sink_type': 'kinesis',
'date_updated': '2015-07-30T19:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate'
}
},
{
'status': 'initialized',
'sink_configuration': {
'arn': 'arn:aws:kinesis:us-east-1:222222222:stream/test',
'role_arn': 'arn:aws:iam::111111111:role/Role',
'external_id': '1234567890'
},
'description': 'ANOTHER Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab',
'date_created': '2015-07-30T20:00:00Z',
'sink_type': 'kinesis',
'date_updated': '2015-07-30T20:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Validate'
}
},
{
'status': 'active',
'sink_configuration': {
'destination': 'http://example.org/webhook',
'method': 'POST',
'batch_events': true
},
'description': 'A webhook Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac',
'date_created': '2015-07-30T21:00:00Z',
'sink_type': 'webhook',
'date_updated': '2015-07-30T21:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Validate'
}
}
],
'meta': {
'page': 0,
'page_size': 20,
'first_page_url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0',
'previous_page_url': null,
'url': 'https://events.twilio.com/v1/Sinks?PageSize=20&Page=0',
'next_page_url': null,
'key': 'sinks'
}
};
holodeck.mock(new Response(200, body));
var promise = client.events.v1.sinks.list();
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid read_results_in_use response',
function(done) {
var body = {
'sinks': [
{
'status': 'initialized',
'sink_configuration': {
'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test',
'role_arn': 'arn:aws:iam::111111111:role/Role',
'external_id': '1234567890'
},
'description': 'A Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'date_created': '2015-07-30T19:00:00Z',
'sink_type': 'kinesis',
'date_updated': '2015-07-30T19:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate'
}
},
{
'status': 'initialized',
'sink_configuration': {
'arn': 'arn:aws:kinesis:us-east-1:222222222:stream/test',
'role_arn': 'arn:aws:iam::111111111:role/Role',
'external_id': '1234567890'
},
'description': 'ANOTHER Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab',
'date_created': '2015-07-30T20:00:00Z',
'sink_type': 'kinesis',
'date_updated': '2015-07-30T20:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab/Validate'
}
},
{
'status': 'active',
'sink_configuration': {
'destination': 'http://example.org/webhook',
'method': 'POST',
'batch_events': true
},
'description': 'A webhook Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac',
'date_created': '2015-07-30T21:00:00Z',
'sink_type': 'webhook',
'date_updated': '2015-07-30T21:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Validate'
}
}
],
'meta': {
'page': 0,
'page_size': 20,
'first_page_url': 'https://events.twilio.com/v1/Sinks?InUse=True&PageSize=20&Page=0',
'previous_page_url': null,
'url': 'https://events.twilio.com/v1/Sinks?InUse=True&PageSize=20&Page=0',
'next_page_url': null,
'key': 'sinks'
}
};
holodeck.mock(new Response(200, body));
var promise = client.events.v1.sinks.list();
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid read_results_status response',
function(done) {
var body = {
'sinks': [
{
'status': 'active',
'sink_configuration': {
'destination': 'http://example.org/webhook',
'method': 'POST',
'batch_events': true
},
'description': 'A webhook Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac',
'date_created': '2015-07-30T21:00:00Z',
'sink_type': 'webhook',
'date_updated': '2015-07-30T21:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac/Validate'
}
}
],
'meta': {
'page': 0,
'page_size': 20,
'first_page_url': 'https://events.twilio.com/v1/Sinks?Status=active&PageSize=20&Page=0',
'previous_page_url': null,
'url': 'https://events.twilio.com/v1/Sinks?Status=active&PageSize=20&Page=0',
'next_page_url': null,
'key': 'sinks'
}
};
holodeck.mock(new Response(200, body));
var promise = client.events.v1.sinks.list();
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid update request',
function(done) {
holodeck.mock(new Response(500, {}));
var opts = {'description': 'description'};
var promise = client.events.v1.sinks('DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').update(opts);
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var sid = 'DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var url = `https://events.twilio.com/v1/Sinks/${sid}`;
var values = {'Description': 'description', };
holodeck.assertHasRequest(new Request({
method: 'POST',
url: url,
data: values
}));
}
);
it('should generate valid update response',
function(done) {
var body = {
'status': 'initialized',
'sink_configuration': {
'arn': 'arn:aws:kinesis:us-east-1:111111111:stream/test',
'role_arn': 'arn:aws:iam::111111111:role/Role',
'external_id': '1234567890'
},
'description': 'My Kinesis Sink',
'sid': 'DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'date_created': '2015-07-30T20:00:00Z',
'sink_type': 'kinesis',
'date_updated': '2015-07-30T20:00:00Z',
'url': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'links': {
'sink_test': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Test',
'sink_validate': 'https://events.twilio.com/v1/Sinks/DGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Validate'
}
};
holodeck.mock(new Response(200, body));
var opts = {'description': 'description'};
var promise = client.events.v1.sinks('DGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').update(opts);
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
});
| twilio/twilio-node | spec/integration/rest/events/v1/sink.spec.js | JavaScript | mit | 30,402 |
module.exports = {
attributes: {
group: {
model: 'Group'
},
user: {
model: 'User'
},
synchronized: 'boolean',
active: 'boolean',
child_group: {
model: 'Group'
},
level: 'integer'
},
migrate: 'safe',
tableName: 'all_membership_group',
autoUpdatedAt: false,
autoCreatedAt: false
}; | scientilla/scientilla | api/models/AllMembershipGroup.js | JavaScript | mit | 411 |
var Type = require("@kaoscript/runtime").Type;
module.exports = function() {
let tt = foo();
if(!Type.isValue(tt)) {
tt = bar;
}
}; | kaoscript/kaoscript | test/fixtures/compile/operator/operator.nullcoalescing.assign.default.js | JavaScript | mit | 136 |
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TaskSchema = new Schema({
name: String,
description: String,
point: Number,
task_users: [{ type: Schema.Types.ObjectId, ref: "TaskUser"}],
_week: { type: Schema.Types.ObjectId, ref: "Week"}
});
module.exports = mongoose.model('Task', TaskSchema);
| pinoytech/awesomex | server/api/task/task.model.js | JavaScript | mit | 344 |
const path = require("path");
const Nightmare = require("nightmare");
const { EncryptionAlgorithm, createAdapter } = require("../../dist/index.node.js");
const TEXT = "Hi there!\nThis is some test text.\n\të ";
const sandboxURL = `file://${path.resolve(__dirname, "./sandbox.html")}`;
const nightmare = Nightmare({
executionTimeout: 15000,
loadTimeout: 5000,
show: false
});
describe("environment consistency", function() {
beforeEach(async function() {
nightmare.on("console", (log, ...args) => {
console.log(`[Web] (${log})`, ...args);
});
await nightmare.goto(sandboxURL);
await nightmare.wait(1000);
await nightmare.inject("js", path.resolve(__dirname, "../../web/index.js"));
await nightmare.wait(1000);
});
after(async function() {
await nightmare.end();
});
describe("from node to web", function() {
describe("text", function() {
it("decrypts AES-CBC from node", async function() {
const encrypted = await createAdapter()
.setAlgorithm(EncryptionAlgorithm.CBC)
.encrypt(TEXT, "sample-pass");
const result = await nightmare.evaluate(function(encrypted, done) {
const { createAdapter } = window.iocane;
createAdapter()
.decrypt(encrypted, "sample-pass")
.then(output => done(null, output))
.catch(done);
}, encrypted);
expect(result).to.equal(TEXT);
});
it("decrypts AES-GCM from node", async function() {
const encrypted = await createAdapter()
.setAlgorithm(EncryptionAlgorithm.GCM)
.encrypt(TEXT, "sample-pass");
const result = await nightmare.evaluate(function(encrypted, done) {
const { createAdapter } = window.iocane;
createAdapter()
.decrypt(encrypted, "sample-pass")
.then(output => done(null, output))
.catch(done);
}, encrypted);
expect(result).to.equal(TEXT);
});
});
describe("data", function() {
beforeEach(function() {
this.randomData = [];
for (let i = 0; i < 50000; i += 1) {
this.randomData.push(Math.floor(Math.random() * 256));
}
this.data = Buffer.from(this.randomData);
});
it("decrypts AES-CBC from node", async function() {
const encrypted = await createAdapter()
.setAlgorithm(EncryptionAlgorithm.CBC)
.encrypt(this.data, "sample-pass");
const result = await nightmare.evaluate(function(encrypted, done) {
const { createAdapter } = window.iocane;
const data = window.helpers.base64ToArrayBuffer(encrypted);
createAdapter()
.decrypt(data, "sample-pass")
.then(output => done(null, window.helpers.arrayBufferToBase64(output)))
.catch(done);
}, encrypted.toString("base64"));
expect(Buffer.from(result, "base64")).to.satisfy(res => res.equals(this.data));
});
it("decrypts AES-GCM from node", async function() {
const encrypted = await createAdapter()
.setAlgorithm(EncryptionAlgorithm.GCM)
.encrypt(this.data, "sample-pass");
const result = await nightmare.evaluate(function(encrypted, done) {
const { createAdapter } = window.iocane;
const data = window.helpers.base64ToArrayBuffer(encrypted);
createAdapter()
.decrypt(data, "sample-pass")
.then(output => done(null, window.helpers.arrayBufferToBase64(output)))
.catch(done);
}, encrypted.toString("base64"));
expect(Buffer.from(result, "base64")).to.satisfy(res => res.equals(this.data));
});
});
});
describe("from web to node", function() {
describe("text", function() {
it("decrypts AES-CBC from web", async function() {
const encrypted = await nightmare.evaluate(function(raw, done) {
const { EncryptionAlgorithm, createAdapter } = window.iocane;
createAdapter()
.setAlgorithm(EncryptionAlgorithm.CBC)
.encrypt(raw, "sample-pass")
.then(output => done(null, output))
.catch(done);
}, TEXT);
const decrypted = await createAdapter().decrypt(encrypted, "sample-pass");
expect(decrypted).to.equal(TEXT);
});
it("decrypts AES-GCM from web", async function() {
const encrypted = await nightmare.evaluate(function(raw, done) {
const { EncryptionAlgorithm, createAdapter } = window.iocane;
createAdapter()
.setAlgorithm(EncryptionAlgorithm.GCM)
.encrypt(raw, "sample-pass")
.then(output => done(null, output))
.catch(done);
}, TEXT);
const decrypted = await createAdapter().decrypt(encrypted, "sample-pass");
expect(decrypted).to.equal(TEXT);
});
});
describe("data", function() {
beforeEach(function() {
this.randomData = [];
for (let i = 0; i < 50000; i += 1) {
this.randomData.push(Math.floor(Math.random() * 256));
}
this.data = Buffer.from(this.randomData);
});
it("decrypts AES-CBC from web", async function() {
const encrypted = await nightmare.evaluate(function(raw, done) {
const { EncryptionAlgorithm, createAdapter } = window.iocane;
const data = window.helpers.base64ToArrayBuffer(raw);
createAdapter()
.setAlgorithm(EncryptionAlgorithm.CBC)
.encrypt(data, "sample-pass")
.then(output => done(null, window.helpers.arrayBufferToBase64(output)))
.catch(done);
}, this.data.toString("base64"));
const decrypted = await createAdapter().decrypt(
Buffer.from(encrypted, "base64"),
"sample-pass"
);
expect(decrypted).to.satisfy(res => res.equals(this.data));
});
it("decrypts AES-GCM from web", async function() {
const encrypted = await nightmare.evaluate(function(raw, done) {
const { EncryptionAlgorithm, createAdapter } = window.iocane;
const data = window.helpers.base64ToArrayBuffer(raw);
createAdapter()
.setAlgorithm(EncryptionAlgorithm.GCM)
.encrypt(data, "sample-pass")
.then(output => done(null, window.helpers.arrayBufferToBase64(output)))
.catch(done);
}, this.data.toString("base64"));
const decrypted = await createAdapter().decrypt(
Buffer.from(encrypted, "base64"),
"sample-pass"
);
expect(decrypted).to.satisfy(res => res.equals(this.data));
});
});
});
});
| perry-mitchell/iocane | test/cross-env/web-node-compare.spec.js | JavaScript | mit | 7,913 |