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
import styled from "styled-components" export const Code = styled.code` padding: 3px 8px; background-color: ${({ theme }) => theme.posts.inlineCodeBackground}; color: ${({ theme }) => theme.posts.inlineCodeColor}; border-radius: 6px; `
nicolasthy/nicolasthy.github.io
components/posts/InlineCode/styles/index.js
JavaScript
mit
245
var searchData= [ ['textobject',['TextObject',['../class_oxy_1_1_framework_1_1_objects_1_1_text_object.html',1,'Oxy::Framework::Objects']]], ['textrenderer',['TextRenderer',['../class_oxy_1_1_framework_1_1_text_renderer.html',1,'Oxy::Framework']]], ['textrenderer',['TextRenderer',['../class_oxy_1_1_framework_1_1_text_renderer.html#aaefdc30b6a2d1b161cf9561092425ea6',1,'Oxy::Framework::TextRenderer']]], ['texture',['Texture',['../class_oxy_1_1_framework_1_1_text_renderer.html#a8f88234b584876dbbdb015c3e1d4636b',1,'Oxy::Framework::TextRenderer']]], ['translate',['Translate',['../class_oxy_1_1_framework_1_1_graphics.html#ac854767976984446279c8cfbc04f2099',1,'Oxy::Framework::Graphics']]] ];
OxyTeam/OxyEngine
docs/html/search/all_10.js
JavaScript
mit
704
'use strict'; angular.module('polaris.directives') .directive('spinner', [function() { function link(scope) { scope.$watch('disappear', function() { if (scope.disappear) { scope.hideSpinner = true; } else { scope.hideSpinner = false; } }); } var tpl = '<div ng-hide="hideSpinner" class="loading">' + '<div class="aligner"></div>' + '<div class="spinner">' + '<div class="rect1"></div>' + '<div class="rect2"></div>' + '<div class="rect3"></div>' + '<div class="rect4"></div>' + '<div class="rect5"></div>' + '</div>' + '</div>'; return { restrict: 'E', template: tpl, replace: true, scope: { 'disappear': '=' }, link: link }; }]);
eleme/polaris
assets/js/directives/spinner.js
JavaScript
mit
838
'use strict'; var should = require('chai').should(); describe('Cache', function(){ var Hexo = require('../../../lib/hexo'); var hexo = new Hexo(); var Cache = hexo.model('Cache'); it('_id - required', function(){ return Cache.insert({}).catch(function(err){ err.should.have.property('message', 'ID is not defined'); }); }); });
znanl/znanl
test/scripts/models/cache.js
JavaScript
mit
354
class MenuController { constructor(translate) { this.languages = [{locale: 'es', name: 'Español'}, {locale: 'en', name: 'English'}]; this.translate = translate; this.loc = 'es'; } changeLocale(loc) { this.loc = loc || this.loc; this.translate.use(this.loc); } } MenuController.$inject = ['$translate']; export { MenuController };
boriscy/timecheck
app/javascript/controllers/menu_controller.es6.js
JavaScript
mit
363
(function() { 'use strict'; var mergeModuleExports = require('../../utils/mergemoduleexports'); mergeModuleExports(module.exports, require('./loader')); mergeModuleExports(module.exports, require('./any')); })();
crowdworks/lopache
lib/routes/conditions/index.js
JavaScript
mit
231
var Message = function() { this._data = { 'push_type': 1, 'android': { 'doings': 1 } }; return this; }; /* * Notification bar上显示的标题 * 必须 */ Message.prototype.title = function(title) { return this.setAndroid('notification_title', title); }; /* * Notification bar上显示的内容 * 必须 */ Message.prototype.content = function(content) { return this.setAndroid('notification_content', content); }; /* * 系统小图标名称 * 该图标预置在客户端,在通知栏顶部展示 */ Message.prototype.status_icon = function(status_icon) { return this.setAndroid('notification_status_icon', status_icon); }; /* * 用户自定义 dict * "extras":{"season":"Spring", "weather":"raining"}] */ Message.prototype.extras = function(extras) { if (!Array.isArray(extras)) { var extraArray = []; var keys = Object.keys(extras); keys.forEach(function(key){ var v = {}; v[key] = extras[key]; extraArray.push(v) }) extras = extraArray } return this.setAndroid('extras', extras); }; /* * 推送范围 * 1:指定用户,必须指定tokens字段 * 2:所有人,无需指定tokens,tags,exclude_tags * 3:一群人,必须指定tags或者exclude_tags字段 */ Message.prototype.push_type = function(push_type) { return this.set('push_type', push_type); }; /* * 用户标签,目前仅对android用户生效 * 样例:{"tags":[{"location":["ShangHai","GuangZhou"]},}"age":["20","30"]}]} * 含义:在广州或者上海,并且年龄为20或30岁的用户 */ Message.prototype.tags = function(tags) { return this.set('tags', tags); }; /* * 需要剔除的用户的标签,目前仅对android用户生效 * 样例:{"exclude_tags":[{"music":["blue"]},{"fruit":["apple"]}]} * 含义:不给喜欢蓝调音乐的用户,或者喜欢苹果的用户发送消息 */ Message.prototype.exclude_tags = function(exclude_tags) { return this.set('exclude_tags', exclude_tags); }; /* * 消息生效时间。如果不携带该字段,则表示消息实时生效。实际使用时,该字段精确到分 * 消息发送时间戳,timestamp格式ISO 8601:2013-06-03T17:30:08+08:00 */ Message.prototype.send_time = function(send_time) { return this.set('send_time', send_time); }; /* * 消息过期删除时间 * 消息过期时间,timestamp格式ISO 8601:2013-06-03T17:30:08+08:00 */ Message.prototype.expire_time = function(expire_time) { return this.set('expire_time', expire_time); }; /* * 目标设备类型 * 1:android * 2:ios * 默认为android */ Message.prototype.device_type = function(device_type) { return this.set('device_type', device_type); }; /* * 1:直接打开应用 * 2:通过自定义动作打开应用 * 3:打开URL * 4:富媒体消息 * 5:短信收件箱广告 * 6:彩信收件箱广告 * 注意:当手机收到短信、彩信收件箱广告后,在收件人一栏显示的是应用在联盟上注册的名字哦~ */ Message.prototype.doings = function(doings) { return this.setAndroid('doings', doings); }; Message.prototype.setAndroid = function(key, value) { this._data['android'][key] = value; return this; }; Message.prototype.set = function(key, value) { this._data[key] = value; return this; }; Message.prototype.getAndroidData = function() { return this._data; }; Message.prototype.getData = function() { return this._data; }; Message.prototype.toString = function() { return JSON.stringify(this._data); }; module.exports = Message;
ijinmao/Huawei-push
lib/message.js
JavaScript
mit
3,563
'use strict'; const periodic = require('periodicjs'); const capitalize = require('capitalize'); const pluralize = require('pluralize'); const reactappLocals = periodic.locals.extensions.get('periodicjs.ext.reactapp'); const reactapp = reactappLocals.reactapp(); function userRoleForm(options = {}) { const { entity } = options; const entityDisplay = getEntityDisplay(entity); return reactappLocals.server_manifest.forms.createForm({ method: (options.update) ? 'PUT' : 'POST', action: (options.update) ? `${reactapp.manifest_prefix}contentdata/standard_${entityDisplay.plural}/:id?format=json` : `${reactapp.manifest_prefix}contentdata/standard_${entityDisplay.plural}?format=json`, onSubmit:'closeModal', onComplete: 'refresh', // loadingScreen: true, style: { paddingTop:'1rem', }, hiddenFields: [ ], // validations: [ ], rows: [ { formElements: [ { type: 'text', passProps: { disabled: true, state: 'isDisabled', }, label:'Email', name:'email', }, ], }, { formElements: [ { type: 'datalist', name: 'userroles', label: 'User Roles', datalist: { multi: true, // selector: '_id', entity:'standard_userrole', resourceUrl:`${reactapp.manifest_prefix}contentdata/standard_userroles?format=json` } // passProps: { // // multiple:true, // }, }, ], }, { formElements: [ { type: 'submit', value: (options.update) ? 'Update User Role' : 'Add User Role', layoutProps: { style: { textAlign:'center', }, }, }, ], }, ], actionParams: (options.update) ? [ { key: ':id', val: '_id', }, ] : undefined, // hiddenFields formProps: { flattenFormData:false, }, asyncprops: (options.update) ? { formdata: [ 'accessdata', 'data' ], } : {}, }); } function getEntityDisplay(entity) { return { plural: pluralize(entity), capitalized: capitalize(entity), pluralCapitalized: pluralize(capitalize(entity)), }; } function getPageTitle(options) { const { entity } = options; const entityDisplay = getEntityDisplay(entity); return reactappLocals.server_manifest.helpers.getPageTitle({ styles: { // ui: {} }, title: `Manage ${entityDisplay.capitalized} Access`, // action: { // type: 'modal', // title: `Manage ${entityDisplay.capitalized} Access`, // pathname: `${reactapp.manifest_prefix}edit-${entity}-access`, // buttonProps: { // props: { // color:'isSuccess', // }, // }, // }, }) } function getAccessPage(options) { const { entity } = options; const entityDisplay = getEntityDisplay(entity); return { layout: { component: 'Container', props: { style: { padding: '6rem 0', }, }, children: [ getPageTitle({ entity, }), reactappLocals.server_manifest.table.getTable({ schemaName: `standard_${entityDisplay.plural}`, baseUrl: `${reactapp.manifest_prefix}contentdata/standard_${entityDisplay.plural}?format=json`, asyncdataprops: 'accessdata', headers: [ { buttons: [ { passProps: { onClick: 'func:this.props.createModal', onclickThisProp: 'onclickPropObject', onclickProps: { title: `Edit ${entityDisplay.capitalized} Access`, pathname: `${reactapp.manifest_prefix}edit-${entity}-access/:id`, params: [ { key: ':id', val: '_id', } ], }, buttonProps: { color: 'isInfo', buttonStyle: 'isOutlined', icon: 'fa fa-pencil', }, }, } ], sortid: '_id', sortable: true, label: 'ID', }, { sortable: true, sortid: 'email', label: 'Email', }, { sortable: true, sortid: 'firstname', label: 'First name', }, { sortable: true, sortid: 'lastname', label: 'Last Name', }, { sortable: true, sortid: 'userroles', customCellLayout: { component: 'DynamicLayout', // ignoreReduxProps:true, thisprops: { items:['cell'], }, bindprops:true, props: { layout: { bindprops:true, component: 'Tag', props: { color: 'isDark', style: { margin:'0.25rem' } }, children: [ { bindprops:true, component: 'span', thisprops: { _children:['name'] } }, // { // component: 'span', // children:': ', // }, // { // bindprops:true, // component: 'span', // thisprops: { // _children:['userroleid'] // } // } ] } } }, label: 'User Roles', }, ], }), ], }, resources: { accessdata: `${reactapp.manifest_prefix}contentdata/standard_${entityDisplay.plural}?format=json`, }, pageData: { title: `Manage ${entityDisplay.capitalized} Access`, }, }; } function getModalPage(options) { const { entity } = options; const entityDisplay = getEntityDisplay(entity); return { layout: { component: 'Content', children: [ userRoleForm({ update: true, entity, }), ], }, resources: { accessdata: `${reactapp.manifest_prefix}contentdata/standard_${entityDisplay.plural}/:id?format=json`, }, pageData: { title: `Edit ${entityDisplay.capitalized} Access`, }, }; } const uacSettings = periodic.settings.extensions[ 'periodicjs.ext.user_access_control' ]; module.exports = { containers: (uacSettings.use_manifests) ? { [ `${reactapp.manifest_prefix}ext/uac/account-access` ]: getAccessPage({ entity: 'account' }), [ `${reactapp.manifest_prefix}ext/uac/user-access` ]: getAccessPage({ entity: 'user' }), [ `${reactapp.manifest_prefix}edit-account-access/:id` ]: getModalPage({ entity: 'account' }), [ `${reactapp.manifest_prefix}edit-user-access/:id` ]: getModalPage({ entity: 'user' }), } : {}, };
typesettin/periodicjs.ext.user_access_control
views/reactapp/manifests/mange_access.manifest.js
JavaScript
mit
8,008
var Court = artifacts.require("./Court.sol"); contract('Court', (accounts) => { it("test kleroterion", () => {}) })
kleroterion/dapp
test/kleroterion.js
JavaScript
mit
119
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchWeather } from '../actions/index'; class SearchBar extends Component { constructor(props) { super(props); this.state = { term: '' }; this.onInputChange = this.onInputChange.bind(this); this.onFormSubmit = this.onFormSubmit.bind(this); } onInputChange(event) { this.setState({ term: event.target.value }); } onFormSubmit(event) { event.preventDefault(); //We need to fetch data this.props.fetchWeather(this.state.term); //Reset the search bar this.setState({ term: '' }); } render() { return( <form onSubmit={this.onFormSubmit} className="input-group"> <input placeholder="Give a five-day forecast in your favorite cities" className="form-control" value={this.state.term} onChange={this.onInputChange} /> <span className="input-group-btn"> <button type="submit" className="btn btn-secondary">Search</button> </span> </form> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchWeather }, dispatch); } //Passing null to connect in first argument (application state or Redux state) is indicating //that our container or SmartComponent does not care about the application state export default connect(null, mapDispatchToProps)(SearchBar);
neosepulveda/react-redux-weather-forecast
src/containers/search_bar.js
JavaScript
mit
1,471
/** * 检查文件名后缀,判断是否为合法的日志文件 * * @param fileName 文件名字符串 * @returns {bool} 文件名是否合法,true 合法,false 非法 */ function isValidLogFile(fileName) { if(fileName === null || fileName === '') throw new Error('file name empty!'); return (lastValid = /.*\.slf$/.test(fileName)); } var lastValid = false; function wasLastFileNameValid() { return lastValid; } module.exports.isValidLogFile = isValidLogFile; module.exports.wasLastFileNameValid = wasLastFileNameValid;
wangding/demo-code
unit-testing-art/ch02/log-and-notification.js
JavaScript
mit
542
version https://git-lfs.github.com/spec/v1 oid sha256:9e6f79a284bf0e25e4a049856c97549792145e4af30916b5044b69d4779caae2 size 23494
yogeshsaroya/new-cdnjs
ajax/libs/angular.js/1.2.13/angular-resource.js
JavaScript
mit
130
/** * @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)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } global.ng.common.locales['ur'] = [ 'ur', [['a', 'p'], ['AM', 'PM'], u], [['AM', 'PM'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'ہفتہ'], u, u ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], [ 'جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر' ], u ], u, [['قبل مسیح', 'عیسوی'], u, u], 0, [6, 0], ['d/M/yy', '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}', u, u, u], ['.', ',', ';', '%', '\u200e+', '\u200e-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'PKR', 'Rs', 'پاکستانی روپیہ', {'JPY': ['JP¥', '¥'], 'PKR': ['Rs'], 'THB': ['฿'], 'TWD': ['NT$']}, 'rtl', plural, [ [ ['آدھی رات', 'صبح', 'دوپہر', 'سہ پہر', 'شام', 'رات'], u, [ 'آدھی رات', 'صبح میں', 'دوپہر میں', 'سہ پہر', 'شام میں', 'رات میں' ] ], [['آدھی رات', 'صبح', 'دوپہر', 'سہ پہر', 'شام', 'رات'], u, u], [ '00:00', ['04:00', '12:00'], ['12:00', '16:00'], ['16:00', '18:00'], ['18:00', '20:00'], ['20:00', '04:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
matsko/angular
packages/common/locales/global/ur.js
JavaScript
mit
2,353
import { Meteor } from 'meteor/meteor' import { composeWithTracker } from 'react-komposer' import { Semesters, RegStatuses, Classrooms, Sessions, Categories, Classes, Terms } from '../../api/data/data' import CourseCreation from '../components/CourseCreation' import Loading from '../components/loading' const composer = (params, onData) => { const subSemesters = Meteor.subscribe('semesters') const subRegStatuses = Meteor.subscribe('semesters') const subClassrooms = Meteor.subscribe('classrooms') const subSessions = Meteor.subscribe('sessions') const subCategories = Meteor.subscribe('categories') const subClasses = Meteor.subscribe('classes') const subTerms = Meteor.subscribe('terms') if (subSemesters.ready() && subRegStatuses.ready() && subClassrooms.ready() && subSessions.ready() && subCategories.ready() && subTerms.ready() && subClasses.ready()) { const semesters = Semesters.find().fetch() const regstatuses = RegStatuses.find().fetch() const classrooms = Classrooms.find().fetch() const sessions = Sessions.find().fetch() const categories = Categories.find().fetch() const classes = Classes.find().fetch() const terms = Terms.find().fetch() onData(null, { semesters, regstatuses, classrooms, sessions, categories, classes, terms }) } } export default composeWithTracker(composer, Loading)(CourseCreation)
hanstest/hxgny
imports/ui/containers/course-creation.js
JavaScript
mit
1,396
define([ 'jquery', 'room-info', 'local-session', 'utils', 'connection', 'mode-list' ], function ($, roomInfo, localSession, Utils, connection, modeList) { "use strict"; /** * タブ単体の制御 * @param {String} viewerId * @param {String} tabId * @param {String} tabName */ var Tab = function (viewerId, tabId, tabName) { /** * AceのインスタンスID * @type {String} */ this._aceId = viewerId + '-' + tabId; /** * このタブのviewerId * @type {String} */ this._viewerId = viewerId; /** * タブID * @type {String} */ this.id = tabId; /** * タブ名 * @type {String} */ this.tabName = tabName; /** * 自身かどうか * @type {Boolean} */ this.isSelf = viewerId === localSession.get(roomInfo.room.id); /** * タブHTML要素の初期化 */ this._initTabElement(viewerId, tabId, tabName); /** * エディタのルートHTML要素 * @type {Object} */ this._$editor = $('#' + this._aceId); /** * Aceのインスタンス * @type {Object} */ this.ace = ace.edit(this._aceId); /** * ファイルの更新日時監視タイマー * @type {Number} */ this._FILE_MONITOR_INTERVAL = null; /** * ファイルの最終更新日時 * @type {Number} */ this._fileLastMod = -1; var _self = this; /** * 受信データ反映時の処理マッピング * @type {Object} */ this._update = { /** * 選択範囲 * @param {Range} range */ range: function (range) { _self.ace.selection.setSelectionRange(range); }, /** * スクロール位置 * @param {Object} scroll */ scroll: function (scroll) { _self.ace.session.setScrollTop(scroll.top); _self.ace.session.setScrollLeft(scroll.left); }, /** * 言語モード * @param {String} mode */ mode: function (mode) { _self.ace.session.setMode("ace/mode/" + mode); }, /** * カラーテーマ * @param {String} theme */ theme: function (theme) { _self.ace.setTheme("ace/theme/" + theme); }, /** * フォントサイズ * @param {Number} size */ fontsize: function (size) { _self.ace.setFontSize(size|0); }, /** * タブ名 * @param {String} tabName */ tabname: function (tabName) { if (_self.tabName === tabName) return; _self.tabName = tabName; _self.$tabLabel.text(decodeURIComponent(tabName)); }, /** * テキスト * @param {String} text */ text: function (text) { var range = _self.ace.session.selection.getRange(); var scrollTop = _self.ace.session.getScrollTop(); var scrollLeft = _self.ace.session.getScrollLeft(); _self.ace.setValue(decodeURIComponent(text)); _self.ace.selection.setSelectionRange(range); _self.ace.session.setScrollTop(scrollTop); _self.ace.session.setScrollLeft(scrollLeft); }, /** * カーソル位置 * @param {Object} cursor */ cursor: function (cursor) { var current = _self.ace.getCursorPosition(); if (cursor.top !== current.top || cursor.left !== current.left) { _self.ace.moveCursorToPosition(cursor); } } } /** * 初期化 */ this._init(); } Tab.prototype = { /** * タブのHTML要素初期化 * @param {String} viewerId * @param {String} tabId * @param {String} tabName */ _initTabElement: function (viewerId, tabId, tabName) { var $root = $('#' + viewerId); var editorRegion = $('#editor-region'); var tabItemText = '<li class="tab-item" data-tab-id="%s"><a class="label" title="">%s</a><a class="close" data-tab-id="%s">x</a></li>'; var editorText = '<div id="%s" data-tab-id="%s"></div>'; // data属性がうまく反映されず、テンプレート化いったん断念 $(Utils.sprintf(editorText, this._aceId, tabId)).width(editorRegion.width()).height(editorRegion.height() - 37).appendTo($root.find('.editor-list:first')); $(Utils.sprintf(tabItemText, tabId, tabName, tabId)).appendTo($root.find('.tab-list')); this.$tabLabel = $root.find('.tab-list').find('[data-tab-id="' + this.id + '"] > .label'); }, /** * 初期化 */ _init: function () { this.ace.session.setUseSoftTabs(true); this.ace.setAnimatedScroll(true); this.applyData({ theme: 'cobalt', mode: 'text', fontsize: 12 }); this.isSelf ? this._initSelf() : this.ace.setReadOnly(true); }, /** * 自身の初期化(エディタが操作されたらメンバーに送信など) */ _initSelf: function () { var sendActionList = [ 'insertText', 'removeText', 'insertLines', 'removeLines' ]; var _self = this; var sendState = (function () { var timer = null; return function () { clearTimeout(timer); timer = setTimeout(function () { _self._sendData('state', _self.getState()); }, 10); } }()); this.ace.session.on('changeScrollLeft', sendState); this.ace.session.on('changeScrollTop', sendState); this.ace.session.selection.on('changeSelection', sendState); this.ace.session.selection.on('changeCursor', sendState); this.ace.session.on('change', function (e) { if (sendActionList.indexOf(e.data.action) == -1) { return; } this._sendData('text', { text: this.getText() }); }.bind(this)); }, /** * データを送信する * @param {String} type - 送信タイプ * @param {Object} data * @param {Boolean} toServer - サーバに送信するならtrue * @param {String} command */ _sendData: function (type, data, toServer, command) { // TODO: この中をもっと整える var tmpData = { viewerId: this._viewerId, tabId: this.id, tabName: encodeURIComponent(this.tabName), data: data }; if (command) tmpData.command = command; var editorData = { type: 'editor_change_' + type, data: JSON.stringify(tmpData) }; if (toServer) { connection.send(editorData); return; } var sendData = {}; sendData.updated = true; sendData[editorData.type] = { type: '', data: [editorData] }; connection.sendRTC(sendData); }, /** * タブの情報を送信. 複数ファイルを一度にドラッグ&ドロップされたときなど * @param {Object} textData * @param {Boolean} toServer - サーバに送信するならtrue * @return {Tab} 自身 */ send: function (textData, toServer) { // サーバー側のremoveTabを上書きするためchange_state this._sendData('state', this.getState(), toServer); this._sendData('text', textData, toServer); return this; }, /** * タブの情報をサーバに送信 * @param {Object} textData */ saveToServer: function (textData) { this.send(textData, true); }, /** * タブの状態をまとめた送信用オブジェクト生成 * @return {Object} 送信用オブジェクト */ serialize: function () { var data = this.getState(); data.text = this.getText(); return { "viewer_id": this._viewerId, "tab_id": this.id, "data": JSON.stringify({ viewerId: this._viewerId, tabId: this.id, tabName: encodeURIComponent(this.tabName), data: data }) }; }, /** * ドロップされたファイルの更新日時を監視。外部で更新されたらエディタに反映。 * @param {File} file */ startMonitoringFile: function (file) { this._fileLastMod = file.lastModifiedDate; clearInterval(this._FILE_MONITOR_INTERVAL); this._FILE_MONITOR_INTERVAL = setInterval(function () { if (this._fileLastMod.getTime() === file.lastModifiedDate.getTime()) { return; } this._fileLastMod = file.lastModifiedDate; var reader = new FileReader(); reader.onload = function (e) { this.applyData({ text: Utils.arrayBufferToString(e.target.result) }); }.bind(this); reader.readAsArrayBuffer(file); }.bind(this), 1000); return this; }, /** * タブを表示する * @return {Tab} 自身 */ show: function () { this._$editor.removeClass('hidden'); return this; }, /** * タブを非表示にする * @return {Tab} 自身 */ hide: function () { this._$editor.addClass('hidden'); return this; }, /** * リサイズ * @return {Tab} 自身 */ resize: function () { this.ace.resize(); return this; }, /** * タブを点滅させる * @param {Boolean} flashing * @return {Tab} self */ setFlashing: function (flashing) { $('#' + this._viewerId).find('[data-tab-id="' + this.id + '"]')[flashing ? 'addClass' : 'removeClass']('flashing'); return this; }, /** * エディタのテキストをURIencodeして取得(送信用) * @return {String} 送信用テキスト */ getText: function () { return encodeURIComponent(this.ace.getValue()); }, /** * エディタの状態をまとめたオブジェクト生成 * @return {Object} */ getState: function () { return { tabname: this.tabName, scroll: { top: this.ace.session.getScrollTop(), left: this.ace.session.getScrollLeft() }, cursor: this.ace.getCursorPosition(), range: this.ace.session.selection.getRange(), theme: this.ace.getTheme().substr(10), mode: this.ace.session.getMode().$id.substr(9), fontsize: this.ace.getFontSize() }; }, /** * 受信データを反映する * @param {Object} data * @return {Tab} 自身 */ applyData: function (data) { // textだったら言語モード再取得. 言語モードが正しく反映されない問題の仮対応. if (data.mode === 'text') { data.mode = modeList.getModeForPath(data.tabname || this.tabName).name; } // 入ってきたプロパティだけ反映する for (var prop in data) if (data.hasOwnProperty(prop)) { if (prop in this._update) { this._update[prop](data[prop]); } else { console.warn('無効なプロパティ: ', data); } } return this; }, /** * タブ削除 * @return {Tab} 自身 */ remove: function () { clearInterval(this._FILE_MONITOR_INTERVAL); this.ace.destroy(); if (this.isSelf) { this._sendData('state', {}, true, 'removeTab'); } return this; } } return Tab; });
setchi/ko-cha2
assets/js/editor-tab.js
JavaScript
mit
10,034
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'toolbar', 'zh', { toolbarCollapse: '摺疊工具列', toolbarExpand: '展開工具列', toolbarGroups: { document: '文件', clipboard: '剪貼簿/復原', editing: '編輯選項', forms: '格式', basicstyles: '基本樣式', paragraph: '段落', links: '連結', insert: '插入', styles: '樣式', colors: '顏色', tools: '工具' }, toolbars: '編輯器工具列' } );
otto-torino/gino
ckeditor/plugins/toolbar/lang/zh.js
JavaScript
mit
616
/** @constructor */ Libraries.SyntaxHighlighter = function (){}; /** @type {Function} */ Libraries.SyntaxHighlighter.all; /** @type {Object} */ Libraries.SyntaxHighlighter.defaults; /** @type {Function} */ Libraries.SyntaxHighlighter.highlight; /** @type {Object} */ Libraries.SyntaxHighlighter.Highlighter; /** @type {Object} */ Libraries.SyntaxHighlighter.brushes; /** @type {Object} */ Libraries.SyntaxHighlighter.regexLib; /** @type {RegExp} */ SyntaxHighlighter.regexLib.aspScriptTags /** @type {RegExp} */ SyntaxHighlighter.regexLib.doubleQuotedString /** @type {RegExp} */ SyntaxHighlighter.regexLib.multiLineCComments /** @type {RegExp} */ SyntaxHighlighter.regexLib.multiLineDoubleQuotedString /** @type {RegExp} */ SyntaxHighlighter.regexLib.multiLineSingleQuotedString /** @type {RegExp} */ SyntaxHighlighter.regexLib.phpScriptTags /** @type {RegExp} */ SyntaxHighlighter.regexLib.scriptScriptTags /** @type {RegExp} */ SyntaxHighlighter.regexLib.singleLineCComments /** @type {RegExp} */ SyntaxHighlighter.regexLib.singleLinePerlComments /** @type {RegExp} */ SyntaxHighlighter.regexLib.singleQuotedString /** @type {RegExp} */ SyntaxHighlighter.regexLib.xmlComments
tgckpg/BotanJS-SyntaxHighlighter
externs/Libraries.SyntaxHighLighter.js
JavaScript
mit
1,183
 /** * @ngdoc controller * @name NavigationController * @function * * @description * Handles the section area of the app * * @param {navigationService} navigationService A reference to the navigationService */ function NavigationController($scope,$rootScope, $location, $log, navigationService, dialogService, historyService, sectionResource, angularHelper) { //Put the navigation service on this scope so we can use it's methods/properties in the view. // IMPORTANT: all properties assigned to this scope are generally available on the scope object on dialogs since // when we create a dialog we pass in this scope to be used for the dialog's scope instead of creating a new one. $scope.nav = navigationService; $scope.selectedId = navigationService.currentId; $scope.sections = navigationService.sections; sectionResource.getSections() .then(function(result) { $scope.sections = result; }); //This reacts to clicks passed to the body element which emits a global call to close all dialogs $rootScope.$on("closeDialogs", function (event) { if (navigationService.ui.stickyNavigation && (!event.target || $(event.target).parents(".umb-modalcolumn").size() == 0)) { navigationService.hideNavigation(); angularHelper.safeApply($scope); } }); //this reacts to the options item in the tree $scope.$on("treeOptionsClick", function (ev, args) { $scope.currentNode = args.node; args.scope = $scope; navigationService.showMenu(ev, args); }); //this reacts to tree items themselves being clicked //the tree directive should not contain any handling, simply just bubble events $scope.$on("treeNodeSelect", function (ev, args) { var n = args.node; //here we need to check for some legacy tree code if (n.jsClickCallback && n.jsClickCallback !== "") { //this is a legacy tree node! var jsPrefix = "javascript:"; var js; if (n.jsClickCallback.startsWith(jsPrefix)) { js = n.jsClickCallback.substr(jsPrefix.length); } else { js = n.jsClickCallback; } try { var func = eval(js); //this is normally not necessary since the eval above should execute the method and will return nothing. if (func != null && (typeof func === "function")) { func.call(); } } catch(ex) { $log.error("Error evaluating js callback from legacy tree node: " + ex); } } else { //add action to the history service historyService.add({name: n.name, link: n.view, icon: n.icon}); //not legacy, lets just set the route value and clear the query string if there is one. $location.path(n.view).search(null); } }); /** Opens a dialog but passes in this scope instance to be used for the dialog */ $scope.openDialog = function (currentNode, action, currentSection) { navigationService.showDialog({ scope: $scope, node: currentNode, action: action, section: currentSection }); }; } //register it angular.module('umbraco').controller("NavigationController", NavigationController);
protherj/Umbraco-CMS
src/Umbraco.Web.UI.Client/src/views/common/navigation.controller.js
JavaScript
mit
3,588
import { remove, attempt, isError } from 'lodash'; import uuid from 'uuid/v4'; import { fileExtension } from 'Lib/pathHelper' import AuthenticationPage from './AuthenticationPage'; window.repoFiles = window.repoFiles || {}; function getFile(path) { const segments = path.split('/'); let obj = window.repoFiles; while (obj && segments.length) { obj = obj[segments.shift()]; } return obj || {}; } export default class TestRepo { constructor(config) { this.config = config; this.assets = []; } authComponent() { return AuthenticationPage; } restoreUser(user) { return this.authenticate(user); } authenticate() { return Promise.resolve(); } logout() { return null; } getToken() { return Promise.resolve(''); } entriesByFolder(collection, extension) { const entries = []; const folder = collection.get('folder'); if (folder) { for (const path in window.repoFiles[folder]) { if (fileExtension(path) !== extension) { continue; } const file = { path: `${ folder }/${ path }` }; entries.push( { file, data: window.repoFiles[folder][path].content, } ); } } return Promise.resolve(entries); } entriesByFiles(collection) { const files = collection.get('files').map(collectionFile => ({ path: collectionFile.get('file'), label: collectionFile.get('label'), })); return Promise.all(files.map(file => ({ file, data: getFile(file.path).content, }))); } getEntry(collection, slug, path) { return Promise.resolve({ file: { path }, data: getFile(path).content, }); } persistEntry(entry, mediaFiles = [], options) { const newEntry = options.newEntry || false; const folder = entry.path.substring(0, entry.path.lastIndexOf('/')); const fileName = entry.path.substring(entry.path.lastIndexOf('/') + 1); window.repoFiles[folder] = window.repoFiles[folder] || {}; window.repoFiles[folder][fileName] = window.repoFiles[folder][fileName] || {}; if (newEntry) { window.repoFiles[folder][fileName] = { content: entry.raw }; } else { window.repoFiles[folder][fileName].content = entry.raw; } return Promise.resolve(); } getMedia() { return Promise.resolve(this.assets); } persistMedia({ fileObj }) { const { name, size } = fileObj; const objectUrl = attempt(window.URL.createObjectURL, fileObj); const url = isError(objectUrl) ? '' : objectUrl; const normalizedAsset = { id: uuid(), name, size, path: url, url }; this.assets.push(normalizedAsset); return Promise.resolve(normalizedAsset); } deleteFile(path, commitMessage) { const assetIndex = this.assets.findIndex(asset => asset.path === path); if (assetIndex > -1) { this.assets.splice(assetIndex, 1); } else { const folder = path.substring(0, path.lastIndexOf('/')); const fileName = path.substring(path.lastIndexOf('/') + 1); delete window.repoFiles[folder][fileName]; } return Promise.resolve(); } }
Aloomaio/netlify-cms
src/backends/test-repo/implementation.js
JavaScript
mit
3,150
import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import TutorialScreen from '../components/tutorialScreen'; import { toggleAutoplay, } from '../actions/audio'; import { tutorialPageDidChange, hideTutorial, } from '../actions/tutorial'; const mapStateToProps = (state) => { return { timerActive: state.bottomPlayer.timerActive, autoplayOn: state.bottomPlayer.autoplayOn, bluetoothOn: state.beacon.bluetoothOn, locationServicesStatus: state.beacon.locationServicesStatus, currentPage: state.tutorial.currentPage, tutorialHidden: state.tutorial.tutorialHidden, }; }; const mapDispatchToProps = (dispatch) => { return { actions: bindActionCreators({ toggleAutoplay, tutorialPageDidChange, hideTutorial, }, dispatch), }; }; export default connect( mapStateToProps, mapDispatchToProps )(TutorialScreen);
CMP-Studio/TheWarholOutLoud
app/containers/tutorial.js
JavaScript
mit
921
/* Copyright Ben Trask and other contributors. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module.exports = unique; function unique(array) { var r = [], l = array.length, x; for(var i = 0; i < l; ++i) { x = array[i]; if(-1 === r.indexOf(x)) r.push(x); } return r; }
btrask/earthfs-js-old
utilities/unique.js
JavaScript
mit
1,279
// Karma configuration // Generated on Sat Jul 04 2015 21:07:22 GMT-0300 (BRT) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'bower_components/angular/angular.min.js', 'bower_components/angular-mocks/angular-mocks.js', 'node_modules/*', 'src/FormulaOne/DataServices/GERequest.js', 'tests/unit/FormulaOne/DataServices/GERequestSpec.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }) }
marcusesa/formula-one-simulator
karma.conf.js
JavaScript
mit
1,786
function onLoaded() { var csInterface = new CSInterface(); var appName = csInterface.hostEnvironment.appName; if(appName != "FLPR"){ loadJSX(); } var appNames = ["PHXS"]; for (var i = 0; i < appNames.length; i++) { var name = appNames[i]; if (appName.indexOf(name) >= 0) { var btn = document.getElementById("btn_" + name); if (btn) btn.disabled = false; } } updateThemeWithAppSkinInfo(csInterface.hostEnvironment.appSkinInfo); // Update the color of the panel when the theme color of the product changed. csInterface.addEventListener(CSInterface.THEME_COLOR_CHANGED_EVENT, onAppThemeColorChanged); } /** * Update the theme with the AppSkinInfo retrieved from the host product. */ function updateThemeWithAppSkinInfo(appSkinInfo) { //Update the background color of the panel var panelBackgroundColor = appSkinInfo.panelBackgroundColor.color; document.body.bgColor = toHex(panelBackgroundColor); var styleId = "ppstyle"; var csInterface = new CSInterface(); var appName = csInterface.hostEnvironment.appName; if(appName == "PHXS"){ addRule(styleId, "button, select, input[type=button], input[type=submit]", "border-radius:3px;"); } if(appName == "PHXS" || appName == "PPRO" || appName == "PRLD") { //////////////////////////////////////////////////////////////////////////////////////////////// // NOTE: Below theme related code are only suitable for Photoshop. // // If you want to achieve same effect on other products please make your own changes here. // //////////////////////////////////////////////////////////////////////////////////////////////// var gradientBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, 40) + " , " + toHex(panelBackgroundColor, 10) + ");"; var gradientDisabledBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, 15) + " , " + toHex(panelBackgroundColor, 5) + ");"; var boxShadow = "-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);"; var boxActiveShadow = "-webkit-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6);"; var isPanelThemeLight = panelBackgroundColor.red > 127; var fontColor, disabledFontColor; var borderColor; var inputBackgroundColor; var gradientHighlightBg; if(isPanelThemeLight) { fontColor = "#000000;"; disabledFontColor = "color:" + toHex(panelBackgroundColor, -70) + ";"; borderColor = "border-color: " + toHex(panelBackgroundColor, -90) + ";"; inputBackgroundColor = toHex(panelBackgroundColor, 54) + ";"; gradientHighlightBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, -40) + " , " + toHex(panelBackgroundColor,-50) + ");"; } else { fontColor = "#ffffff;"; disabledFontColor = "color:" + toHex(panelBackgroundColor, 100) + ";"; borderColor = "border-color: " + toHex(panelBackgroundColor, -45) + ";"; inputBackgroundColor = toHex(panelBackgroundColor, -20) + ";"; gradientHighlightBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, -20) + " , " + toHex(panelBackgroundColor, -30) + ");"; } //Update the default text style with pp values addRule(styleId, ".default", "font-size:" + appSkinInfo.baseFontSize + "px" + "; color:" + fontColor + "; background-color:" + toHex(panelBackgroundColor) + ";"); addRule(styleId, "button, select, input[type=text], input[type=button], input[type=submit]", borderColor); addRule(styleId, "button, select, input[type=button], input[type=submit]", gradientBg); addRule(styleId, "button, select, input[type=button], input[type=submit]", boxShadow); addRule(styleId, "button:enabled:active, input[type=button]:enabled:active, input[type=submit]:enabled:active", gradientHighlightBg); addRule(styleId, "button:enabled:active, input[type=button]:enabled:active, input[type=submit]:enabled:active", boxActiveShadow); addRule(styleId, "[disabled]", gradientDisabledBg); addRule(styleId, "[disabled]", disabledFontColor); addRule(styleId, "input[type=text]", "padding:1px 3px;"); addRule(styleId, "input[type=text]", "background-color: " + inputBackgroundColor) + ";"; addRule(styleId, "input[type=text]:focus", "background-color: #ffffff;"); addRule(styleId, "input[type=text]:focus", "color: #000000;"); } else { // For AI, ID and FL use old implementation addRule(styleId, ".default", "font-size:" + appSkinInfo.baseFontSize + "px" + "; color:" + reverseColor(panelBackgroundColor) + "; background-color:" + toHex(panelBackgroundColor, 20)); addRule(styleId, "button", "border-color: " + toHex(panelBgColor, -50)); } } function addRule(stylesheetId, selector, rule) { var stylesheet = document.getElementById(stylesheetId); if (stylesheet) { stylesheet = stylesheet.sheet; if( stylesheet.addRule ){ stylesheet.addRule(selector, rule); } else if( stylesheet.insertRule ){ stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length); } } } function reverseColor(color, delta) { return toHex({red:Math.abs(255-color.red), green:Math.abs(255-color.green), blue:Math.abs(255-color.blue)}, delta); } /** * Convert the Color object to string in hexadecimal format; */ function toHex(color, delta) { function computeValue(value, delta) { var computedValue = !isNaN(delta) ? value + delta : value; if (computedValue < 0) { computedValue = 0; } else if (computedValue > 255) { computedValue = 255; } computedValue = computedValue.toString(16); return computedValue.length == 1 ? "0" + computedValue : computedValue; } var hex = ""; if (color) { with (color) { hex = computeValue(red, delta) + computeValue(green, delta) + computeValue(blue, delta); }; } return "#" + hex; } function onAppThemeColorChanged(event) { // Should get a latest HostEnvironment object from application. var skinInfo = JSON.parse(window.__adobe_cep__.getHostEnvironment()).appSkinInfo; // Gets the style information such as color info from the skinInfo, // and redraw all UI controls of your extension according to the style info. updateThemeWithAppSkinInfo(skinInfo); } /** * Load JSX file into the scripting context of the product. All the jsx files in * folder [ExtensionRoot]/jsx will be loaded. */ function loadJSX() { var csInterface = new CSInterface(); var extensionRoot = csInterface.getSystemPath(SystemPath.EXTENSION) + "/jsx/"; csInterface.evalScript('$._ext.evalFiles("' + extensionRoot + '")'); } function evalScript(script, callback) { new CSInterface().evalScript(script, callback); } function onClickButton(ppid) { if(ppid == "FLPR"){ var jsfl = 'fl.createDocument(); fl.getDocumentDOM().addNewText({left:100, top:100, right:300, bottom:300} , "Hello Flash!" ); '; evalScript(jsfl); } else { var extScript = "$._ext_" + ppid + ".run()"; evalScript(extScript); } }
pbojinov/iconfinder-photoshop-extension
ext.js
JavaScript
mit
7,586
/* First Roll 1 2 3 4 5 6 S 1 ! @ # $ % ^ e 2 & * ( ) - = c 3 + [ ] { } \ o 4 | ` ; : ' " n 5 < > / ? . , d 6 ~ _ 3 5 7 9 */ var special = { 11: "!", 12: "&", 13: "+", 14: "|", 15: "<", 16: "~", 21: "@", 22: "*", 23: "[", 24: "`", 25: ">", 26: "_", 31: "#", 32: "(", 33: "]", 34: ";", 35: "/", 36: "3", 41: "$", 42: ")", 43: "{", 44: ":", 45: "?", 46: "5", 51: "%", 52: "-", 53: "}", 54: "'", 55: ".", 56: "7", 61: "^", 62: "=", 63: "\\", 64: "\"", 65: ",", 66: "9" };
grempe/diceware
lists/special.js
JavaScript
mit
646
import Ember from 'ember'; export default Ember.Component.extend({ hasErrors: Ember.computed.notEmpty('model.errors.[]') });
mhs/t2-people
app/pods/components/errors-for/component.js
JavaScript
mit
128
import fetch from '../api' import config from '../config' export const login = (source, token) => fetch( 'POST', `${config.API_URL}/login`, {}, false, {'X-Auth-Source': source, 'X-Auth-Token': token} )
ppoliani/cryptosis
js/ui/app/services/auth/common.js
JavaScript
mit
213
var Taco = Taco || {}; Taco.Util = Taco.Util || {}; Taco.Util.HTML = Taco.Util.HTML || {}; Taco.Util.HTML.render = function(str, html) { html = (typeof html != 'undefined') ? html : false; return (html === true) ? str : Taco.Util.Str.htmlEntities(str); }; Taco.Util.HTML.attribs = function(attribs, leading_space) { leading_space = (typeof leading_space != 'undefined') ? leading_space : true; if(Taco.Util.Obj.getObjectLength(attribs) < 1) return ''; var out = []; for(var key in attribs) { var value = attribs[key]; value = (typeof value == 'object') ? Taco.Util.Obj.objectJoin(' ', value) : value; out.push(key + '="' + String(value).replace(/\"/, '\"') + '"'); } return ((leading_space) ? ' ' : '') + out.join(' '); }; Taco.Util.HTML.getTextInputTypes = function() { return [ 'text', 'image', 'file', 'search', 'email', 'url', 'tel', 'number', 'range', 'date', 'month', 'week', 'time', 'datetime', 'datetime-local', 'color' ]; }; Taco.Util.HTML.tag = function(element_type, body, attribs, close, is_html) { body = (typeof body == 'undefined' || body === null) ? '' : body; attribs = (typeof attribs == 'undefined') ? [] : attribs; close = (typeof close == 'undefined') ? true : close; is_html = (typeof is_html == 'undefined') ? false : is_html; var not_self_closing = ['a', 'div', 'iframe', 'textarea']; var is_self_closing = false; if(close && Taco.Util.General.empty(body) && !Taco.Util.Arr.inArray( element_type.toLowerCase(), not_self_closing )) { is_self_closing = true; } if(is_self_closing) { return '<' + element_type + this.attribs(attribs) + ' />'; } return [ '<' + element_type + this.attribs(attribs) + '>', this.render(body, is_html), (close) ? '</' + element_type + '>' : '' ].join(''); }; Taco.Util.HTML.selecty = function(options, selected, attribs) { selected = (typeof selected != 'undefined') ? selected : null; attribs = (typeof attribs != 'undefined') ? attribs : []; var htmls = []; htmls.push(this.tag('select', null, attribs, false)); if(Taco.Util.Obj.isIterable(options)) { for(var key in options) { value = options[key]; var option_attribs = { value: key }; if(String(selected) === String(value)) { option_attribs.selected = 'selected'; } htmls.push(this.tag('option', value, option_attribs)); } } htmls.push('</select>'); return htmls.join("\n"); };
jasand-pereza/addmany
src/Frontend/js/lib/util/html.js
JavaScript
mit
2,577
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { emailChanged, passwordChanged, signinUser } from '../core/actions'; import { Container, Content, Form, Item, Input, Grid, Col, Spinner, Toast, Icon, Button, Text } from 'native-base'; class Login extends Component { static navigationOptions = { title: 'Login', header: { backTitle: null, visible: false, } }; onLogin() { const { email, password, navigation } = this.props; this.props.signinUser(navigation, email, password); } onRegister() { this.props.navigation.navigate('Register'); } componentWillMount() { } onEmailChange(text) { this.props.emailChanged(text); } onPasswordChange(text) { this.props.passwordChanged(text); } renderSpinner() { if (this.props.loading) { return (<Spinner />); } else { return ( <Grid> <Col> <Button full rounded onPress={this.onLogin.bind(this)}> <Text>Login</Text> </Button> </Col> <Col> <Button full rounded onPress={this.onRegister.bind(this)}> <Text>Register</Text> </Button> </Col> </Grid> ); } } render() { const { navigate } = this.props.navigation; return ( <Container> <Content> <Form> <Item rounded> <Input placeholder="E-Mail" value={this.props.email} keyboardType='email-address' onChangeText={this.onEmailChange.bind(this)} /> </Item> <Item rounded> <Input placeholder="Password" value={this.props.password} secureTextEntry onChangeText={this.onPasswordChange.bind(this)} /> </Item> <Item> <Text style={styles.errorTextStyle}> {this.props.loginError} </Text> </Item> <Item last> {this.renderSpinner()} </Item> </Form> </Content> </Container> ); } } const styles = { errorTextStyle: { fontSize: 20, alignSelf: 'center', color: 'red' }, imageStyle: { width: 50, height: 50, } }; const mapStateToProps = ({ authReducer }) => { const { email, password, loginError, loading } = authReducer; return { email, password, loginError, loading }; }; export default connect(mapStateToProps, { emailChanged, passwordChanged, signinUser })(Login);
Blacktoviche/RNChat
src/compos/Login.js
JavaScript
mit
3,076
Miogen.require(['Component.BaseComponent', 'Component.Button'], function () { Miogen.define('Component.Toolbar', Miogen.Component.BaseComponent.extend({ construct: function (cfg) { this._super(cfg); }, build: function (cb) { var t = this; // // t.addComponent(new Miogen.Component.Button()); // t.addComponent(new Miogen.Component.Button()); // Render the base widget and newly added components this._super(function () { cb.call(this); this.el.addClass('toolbar'); }); //this.el = $('<div class="miogen-widget"><div class="pad">Collection widget</div></div>'); } })); });
medatech/MiogenPHP
lib/client/lib/miogen/js/Component/Toolbar.js
JavaScript
mit
837
/** * syntaxEnvironment.js * Andrea Tino - 2015 */ /** * Main collection point for types to be rendered. */ module.exports = function() { var tsClass = require('./class.js'); var tsInterface = require('./interface.js'); var tsEnum = require('./enum.js'); // Configuration: { classIds = [], interfaceIds = [], enumIds = [] } var config = null; // Associative arrays: id -> Typescript mapper (ts[Class|Interface|Enum]) var classes = {}; var interfaces = {}; var enums = {}; return { /** * Initializes the module. * _config: Configuration: * { classIds = [], interfaceIds = [], enumIds = [] } */ initialize: function(_config) { if (!_config) { throw 'Error: Configuration cannot be null or undefined!'; } config = _config; }, /** * Builds TypeScript classes. */ buildClasses: function() { }, /** * Builds TypeScript interfaces. */ buildInterfaces: function() { }, /** * Build enums. */ buildEnums: function() { } }; };
andry-tino/sankaku
lib/syntaxEnvironment.js
JavaScript
mit
1,114
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/license */ CKEDITOR.plugins.setLang("specialchar","id",{euro:"Tanda Euro",lsquo:"Left single quotation mark",rsquo:"Right single quotation mark",ldquo:"Left double quotation mark",rdquo:"Right double quotation mark",ndash:"En dash",mdash:"Em dash",iexcl:"Inverted exclamation mark",cent:"Cent sign",pound:"Pound sign",curren:"Currency sign",yen:"Tanda Yen",brvbar:"Broken bar",sect:"Section sign",uml:"Diaeresis",copy:"Tanda Hak Cipta",ordf:"Feminine ordinal indicator",laquo:"Left-pointing double angle quotation mark", not:"Not sign",reg:"Tanda Telah Terdaftar",macr:"Macron",deg:"Degree sign",sup2:"Superscript two",sup3:"Superscript three",acute:"Acute accent",micro:"Micro sign",para:"Pilcrow sign",middot:"Middle dot",cedil:"Cedilla",sup1:"Superscript one",ordm:"Masculine ordinal indicator",raquo:"Right-pointing double angle quotation mark",frac14:"Vulgar fraction one quarter",frac12:"Vulgar fraction one half",frac34:"Vulgar fraction three quarters",iquest:"Inverted question mark",Agrave:"Latin capital letter A with grave accent", Aacute:"Latin capital letter A with acute accent",Acirc:"Latin capital letter A with circumflex",Atilde:"Latin capital letter A with tilde",Auml:"Latin capital letter A with diaeresis",Aring:"Latin capital letter A with ring above",AElig:"Latin capital letter Æ",Ccedil:"Latin capital letter C with cedilla",Egrave:"Latin capital letter E with grave accent",Eacute:"Latin capital letter E with acute accent",Ecirc:"Latin capital letter E with circumflex",Euml:"Latin capital letter E with diaeresis",Igrave:"Latin capital letter I with grave accent", Iacute:"Latin capital letter I with acute accent",Icirc:"Latin capital letter I with circumflex",Iuml:"Latin capital letter I with diaeresis",ETH:"Latin capital letter Eth",Ntilde:"Latin capital letter N with tilde",Ograve:"Latin capital letter O with grave accent",Oacute:"Latin capital letter O with acute accent",Ocirc:"Latin capital letter O with circumflex",Otilde:"Latin capital letter O with tilde",Ouml:"Latin capital letter O with diaeresis",times:"Multiplication sign",Oslash:"Latin capital letter O with stroke", Ugrave:"Latin capital letter U with grave accent",Uacute:"Latin capital letter U with acute accent",Ucirc:"Latin capital letter U with circumflex",Uuml:"Latin capital letter U with diaeresis",Yacute:"Latin capital letter Y with acute accent",THORN:"Latin capital letter Thorn",szlig:"Latin small letter sharp s",agrave:"Latin small letter a with grave accent",aacute:"Latin small letter a with acute accent",acirc:"Latin small letter a with circumflex",atilde:"Latin small letter a with tilde",auml:"Latin small letter a with diaeresis", aring:"Latin small letter a with ring above",aelig:"Latin small letter æ",ccedil:"Latin small letter c with cedilla",egrave:"Latin small letter e with grave accent",eacute:"Latin small letter e with acute accent",ecirc:"Latin small letter e with circumflex",euml:"Latin small letter e with diaeresis",igrave:"Latin small letter i with grave accent",iacute:"Latin small letter i with acute accent",icirc:"Latin small letter i with circumflex",iuml:"Latin small letter i with diaeresis",eth:"Latin small letter eth", ntilde:"Latin small letter n with tilde",ograve:"Latin small letter o with grave accent",oacute:"Latin small letter o with acute accent",ocirc:"Latin small letter o with circumflex",otilde:"Latin small letter o with tilde",ouml:"Latin small letter o with diaeresis",divide:"Division sign",oslash:"Latin small letter o with stroke",ugrave:"Latin small letter u with grave accent",uacute:"Latin small letter u with acute accent",ucirc:"Latin small letter u with circumflex",uuml:"Latin small letter u with diaeresis", yacute:"Latin small letter y with acute accent",thorn:"Latin small letter thorn",yuml:"Latin small letter y with diaeresis",OElig:"Latin capital ligature OE",oelig:"Latin small ligature oe",372:"Latin capital letter W with circumflex",374:"Latin capital letter Y with circumflex",373:"Latin small letter w with circumflex",375:"Latin small letter y with circumflex",sbquo:"Single low-9 quotation mark",8219:"Single high-reversed-9 quotation mark",bdquo:"Double low-9 quotation mark",hellip:"Horizontal ellipsis", trade:"Trade mark sign",9658:"Black right-pointing pointer",bull:"Bullet",rarr:"Rightwards arrow",rArr:"Rightwards double arrow",hArr:"Left right double arrow",diams:"Black diamond suit",asymp:"Almost equal to"});
maukoese/jabali
app/assets/js/ckeditor/plugins/specialchar/dialogs/lang/id.js
JavaScript
mit
4,553
;(function() { MozVisibility = { _MAX_TRIES: 10, _date: new Date, _tries: 0, _timer: null, _isVisible: undefined, _proxy: function(fn, context) { context = context || window; return function() { fn.apply(context, arguments); }; }, _getEvent: function() { if (!this._event) { this._event = document.createEvent('HTMLEvents'); this._event.initEvent('mozvisibilitychange', true, true); this._event.eventName = 'mozvisibilitychange'; } return this._event; }, _setVisibilityState: function(state) { this._isVisible = (state === 'visible'); document.mozVisibilityState = state; document.mozHidden = !this._isVisible; document.dispatchEvent(this._getEvent()); }, _visibilityCheck: function() { this._date = new Date; this._tries = 0; this._timer = setTimeout(this._invisibilityCheckTimeout, 0); }, _invisibilityCheckTimeoutTemplate: function() { var newdate = new Date; var delta = newdate - this._date; this._date = newdate; this._tries++; if (delta > 1000) { this._setVisibilityState('hidden'); } else if (this._tries < this._MAX_TRIES) { this._timer = setTimeout(this._invisibilityCheckTimeout, 0); } }, _onFocus: function() { clearTimeout(this._timer); if (!this._isVisible) { this._setVisibilityState('visible'); } }, _onBlur: function() { if (!this._isVisible) { return; } this._visibilityCheck(); }, canBeEmulated: function() { var rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, ua = navigator.userAgent.toLowerCase(); var match = ua.indexOf('compatible') < 0 && rmozilla.exec(ua) || []; return (window.top === window && // not in IFRAME match[2] && parseInt(match[2]) >= 5 && // Firefox 5.0+ !document.visibilityState && !document.MozVisibilityState); // visibility API is not already supported }, emulate: function() { if (!this.canBeEmulated()) { return false; } this._invisibilityCheckTimeout = this._proxy(this._invisibilityCheckTimeoutTemplate, this); window.addEventListener("focus", this._proxy(this._onFocus, this), false); window.addEventListener("blur", this._proxy(this._onBlur, this), false); this._visibilityCheck(); return true; } }; MozVisibility.emulate(); })();
private-face/mozvisibility
dev/mozvisibility.js
JavaScript
mit
2,334
const { createCompileTsFilesTask, createDeleteDistFolderTask, createLintTsFilesTask, createRunIntegrationTestsTask, createRunUnitTestsTask, } = require("../tasks"); const {parallel, series} = require("gulp"); const failAfterError = true; exports.createBuildWorkflow = (moduleName) => series( createDeleteDistFolderTask(moduleName), parallel( createCompileTsFilesTask(moduleName, "main.js", failAfterError), createCompileTsFilesTask(moduleName, "unit.js", failAfterError), createCompileTsFilesTask(moduleName, "integration.js", failAfterError) ), createLintTsFilesTask(moduleName, failAfterError), createRunUnitTestsTask(moduleName, failAfterError), createRunIntegrationTestsTask(moduleName, failAfterError) );
broodlab/archiveboy
toolbox/workflows/build.workflow-factory.js
JavaScript
mit
823
/* jQuery OSM field 2014 by Thomas netAction Schmidt for Sinnwerkstatt https://www.sinnwerkstatt.com/ MIT License */ (function ($) { $.fn.osmfield = function () { return this.each(function () { // Create HTML elements for osmfield var lang, map, marker, tile_url, idAttribute = $(this).attr('id'), idLatElement = $(this).data('lat-field'), idLonElement = $(this).data('lon-field'), idDataElement = $(this).data('data-field'), osmfieldElement = $(this); if (idLatElement === undefined) { idLatElement = '#' + idAttribute + '_lat'; } else { idLatElement = '#id_' + idLatElement; } if (idLonElement === undefined) { idLonElement = '#' + idAttribute + '_lon'; } else { idLonElement = '#id_' + idLonElement; } if (idDataElement === undefined) { idDataElement = '#' + idAttribute + '_data'; } else { idDataElement = '#id_' + idDataElement; } $(this).addClass('osmfield-input'); // Create map container when not existent. // Wrapper is only for CSS. if (!$('#' + idAttribute + '-map').length) { $(this).before('<div class="osmfield-wrapper"><div id="' + idAttribute + '-map"></div></div>'); } $(this).data('lat-element', $(idLatElement)); $(this).data('lng-element', $(idLonElement)); $(this).data('data-element', $(idDataElement)); $(this).data('map-element', $('#' + idAttribute + '-map')); $(this).data('map-element').addClass('osmfield-map'); // initialize Leaflet map, tile layer and marker map = L.map(osmfieldElement.data('map-element')[0]).setView([0, 0], 15); tile_url = (window.location.protocol === 'http:') ? 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png' : 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png'; L.tileLayer(tile_url, { attribution: 'CartoDB | Open Streetmap', maxZoom: 18 }).addTo(map); marker = L.marker([0, 0], {draggable: true}).addTo(map); // bubble up the dom to find out language or use 'en' as default lang = osmfieldElement.closest('[lang]').attr('lang'); if (lang) { lang = lang.split('-'); lang = lang[0]; } else { lang = 'en'; } osmfieldElement.data('language', lang); // magic that happens when marker in map is dragged (function (osmfieldElement) { marker.on('dragend', function (event) { var language = osmfieldElement.data('language'), position = event.target.getLatLng(), url = 'https://nominatim.openstreetmap.org/reverse?json_callback=?', zoom = map.getZoom(); map.panTo(position); osmfieldElement.data('lat-element').val(position.lat); osmfieldElement.data('lng-element').val(position.lng); $.getJSON( url, { format: 'json', lat: position.lat, lon: position.lng, zoom: zoom, addressdetails: 1, 'accept-language': language }, function (data) { osmfieldElement.val(data.display_name); osmfieldElement.data('data-element').val(JSON.stringify(data)); } ); }); })(osmfieldElement); // User enters something in INPUT field osmfieldElement.on('propertychange keyup input paste change', function () { if ($(this).data('oldvalue') === $(this).val()) { return; } $(this).data('oldvalue', $(this).val()); function search(nameInputElement) { var language = nameInputElement.data('language'), url = 'https://nominatim.openstreetmap.org/search?json_callback=?'; (function (osmfieldElement) { // We could kill previous ajax requests here. $.getJSON( url, { format: 'json', q: nameInputElement.val(), addressdetails: 1, 'accept-language': language }, function (data) { // coordinates found for this address? if (data.length) { var lat = data[0].lat, lng = data[0].lon, // name = data[0].display_name, newLatLng = new L.LatLng(lat, lng), eldata = JSON.stringify(data[0]); osmfieldElement.data('lat-element').val(lat); osmfieldElement.data('lng-element').val(lng); osmfieldElement.data('data-element').val(eldata); marker.setLatLng(newLatLng); map.panTo(newLatLng); } else { osmfieldElement.data('map-element').slideUp(); osmfieldElement.data('lat-element').val(''); osmfieldElement.data('lng-element').val(''); osmfieldElement.data('data-element').val(''); } // Show map when INPUT has focus and coordinates are known if ( osmfieldElement.is(":focus") && osmfieldElement.data('lat-element').val() && osmfieldElement.data('lng-element').val() ) { osmfieldElement.data('map-element').slideDown(function () { window.dispatchEvent(new Event('resize')); }); } else { osmfieldElement.data('map-element').slideUp(); } } ); })(nameInputElement); } // Wait 500ms for INPUT updates until Ajax request clearTimeout($.data(this, 'timer')); var nameInputElement = $(this), wait = setTimeout(function () { search(nameInputElement); }, 500); $(this).data('timer', wait); }); // Initialize INPUT, map and data attributes osmfieldElement.data('map-element').hide(); // Use start values if given if (osmfieldElement.data('lat-element').val() && osmfieldElement.data('lng-element').val()) { var newLatLng = new L.LatLng( osmfieldElement.data('lat-element').val(), osmfieldElement.data('lng-element').val() ); marker.setLatLng(newLatLng); map.panTo(newLatLng); } else { // Maybe OpenStreetMap has coordinates or hide the map osmfieldElement.trigger('change'); } // Hide map when clicking outside $(document).click(function (event) { // A child of INPUT or map was clicked var thisosmfield = $(event.target).closest('.osmfield-input, .osmfield-map'); if (thisosmfield.length) { // hide all maps except of this if (thisosmfield.hasClass('osmfield-input')) { thisosmfield = thisosmfield.data('map-element'); } $('.osmfield-map').not(thisosmfield).slideUp(); } else { // hide all $('.osmfield-map').slideUp(); } }); // Show map when INPUT gets focus and position is known (function (osmfieldElement) { osmfieldElement.focus(function () { if (osmfieldElement.data('lat-element').val() && osmfieldElement.data('lng-element').val()) { osmfieldElement.data('map-element').slideDown(function () { window.dispatchEvent(new Event('resize')); }); } }); })(osmfieldElement); }); // each osmfield element }; // jQuery plugin end }(jQuery));
MarkusH/django-osm-field
osm_field/static/js/osm_field.js
JavaScript
mit
9,667
var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { devtool: 'source-map', entry: { app: './src/main.js' }, output: { filename: '[name].min.js', path: path.join(__dirname, 'dist'), publicPath: '' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.NoErrorsPlugin(), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production'), }, '__DEV_TOOLS__': false }), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }), //new ExtractTextPlugin('app.css', { allChunks: true }), new HtmlWebpackPlugin({ title: 'Redux Boilerplate', filename: 'index.html', template: 'index.template.html', favicon: path.join(__dirname, 'assets/images/favicon.ico') }) ], module: { loaders: [ { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!cssnext-loader') }, { test: /\.js$/, loaders: ['babel'], exclude: /node_modules/ } ] }, cssnext: { browsers: 'last 2 versions' } };
mawie81/redux-async-test
webpack.config.production.js
JavaScript
mit
1,257
$(function () { $.widget("as24.qr", { _create: function () { var self = this; $(self.element).find('[data-description="QR-Code Generation"]').find("p").hide(); $(self.element).find('[data-generate="qr-code"]').click(function () { $(self.element).find('[data-description="QR-Code Generation"]').find("p").show(); var url = $(self.element).find('[name="urlQRCode"]').val(); var featureName = $(self.element).find('[name="name"]').val(); var featureEnabled = url + "?" + $.param({ "FeatureBee": '#' + featureName + "=true#" }); var featureDisabled = url + "?" + $.param({ "FeatureBee": '#' + featureName + "=false#" }); $(self.element).find('#qrcode_enable').empty(); $(self.element).find('#qrcode_enable').qrcode(featureEnabled); $(self.element).find('#qrcode_disable').empty(); $(self.element).find('#qrcode_disable').qrcode(featureDisabled); }); } }); })
AutoScout24/FeatureBee
FeatureBee.Server/Scripts/featureBee/qr.js
JavaScript
mit
1,095
(function () { 'use strict'; angular .module('app.web') .service('fileUpload', Service); Service.$inject = ['$http']; function Service($http) { this.uploadFile = uploadFile; //////////////// function uploadFile(file, url, done) { var fd = new FormData(); fd.append('file',file); $http.post(url, fd, { transformRequest: angular.identity, headers: { 'Content-Type': undefined } }).success(function (response) { done(null, response); }).error(function (e) { done(e, null); }); } } })();
periface/AbpCinotamZero-SmartAdmin
Cinotam.AbpModuleZero.Web/App/SysAdmin/Main/services/fileUpload.js
JavaScript
mit
691
function util() { var self = this; if (typeof Object.beget !== 'function') { Object.beget = function (o) { var F = function () {}; F.prototype = o; return new F(); }; } }; exports.util = new util();
ericmcdaniel/codechat
lib/app/exports/exports.util.js
JavaScript
mit
220
// Heavily influenced by Mike Bostock's Scatter Matrix example // http://mbostock.github.io/d3/talk/20111116/iris-splom.html // ScatterMatrix = function(url, data, dom_id) { this.__url = url; if (data === undefined || data === null) { this.__data = undefined; } else { this.__data = data; } this.__cell_size = 80; if (dom_id === undefined) { this.__dom_id = 'body'; } else { this.__dom_id = dom_id; } }; ScatterMatrix.prototype.cellSize = function(n) { this.__cell_size = n; return this; }; ScatterMatrix.prototype.onData = function(cb) { if (this.__data) { cb(); return; } var self = this; d3.csv(self.__url, function(data) { //self.__data = data; cb(); }); }; ScatterMatrix.prototype.render = function() { var self = this; var container = d3.select(this.__dom_id).append('div') .attr('class', 'scatter-matrix-container'); var control = container.append('div') .attr('class', 'scatter-matrix-control toggled') .style('background-color', '#ffffff'); var svg = container.append('div') .attr('class', 'scatter-matrix-svg') .html('<em>Loading data...</em>'); this.onData(function() { var data = self.__data; //// NOTE: passing raw data to local data // Divide variables into string and numeric variables var original_numeric_variables = []; self.__numeric_variables = []; for (k in data[0]) { var is_numeric = true; data.forEach(function(d) { var v = d[k]; if (isNaN(+v)) is_numeric = false; }); if (is_numeric) { self.__numeric_variables.push(k); original_numeric_variables.push(k); } } var scid = 0; data.forEach(function(d) { d.scid = scid; scid += 1; }); //console.log(string_variables);//------------------------------------------------------------------ // Add controls on the left var size_control = control.append('div').attr('class', 'scatter-matrix-size-control'); var color_control = control.append('div').attr('class', 'scatter-matrix-color-control'); var filter_control = control.append('div').attr('class', 'scatter-matrix-filter-control'); var variable_control = control.append('div').attr('class', 'scatter-matrix-variable-control'); var drill_control = control.append('div').attr('class', 'scatter-matrix-drill-control'); // shared control states var to_include = self.__numeric_variables.slice(-3, -1); var color_variable = undefined; var selected_colors = undefined; var drill_variables = []; function set_filter(variable) { filter_control.selectAll('*').remove(); if (variable) { // Get unique values for this variable var values = []; data.forEach(function(d) { var v = d[variable]; if (values.indexOf(v) < 0) { values.push(v); } }); selected_colors = values.slice(0, 5); var filter_li = filter_control .append('p').text('Filter by ' + variable + ': ') .append('ul') .selectAll('li') .data(values) .enter().append('li'); filter_li.append('input') .attr('type', 'checkbox') .attr('checked', function(d, i) { if (selected_colors.indexOf(d) >= 0) return 'checked'; return null; }) .on('click', function(d, i) { var new_selected_colors = []; for (var j in selected_colors) { var v = selected_colors[j]; if (v !== d || this.checked) { new_selected_colors.push(v); } } if (this.checked) { new_selected_colors.push(d); } selected_colors = new_selected_colors; self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables); }); filter_li.append('label') .html(function(d) { return d; }); } } // -----------------------------------Here starts the control menu list-------------------------------------------------------// size_a = size_control.append('div').attr('class', 'btn-group col-xs-12').style('margin-bottom', '20px'); var orgSize = self.__cell_size; size_a.append('a') .attr('class', 'btn btn-default btn-xs') .attr('href', 'javascript:void(0);') .html('-') .on('click', function() { self.__cell_size -= 50; self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables); }); size_a.append('a') .attr('class', 'btn btn-default btn-xs') .attr('href', 'javascript:void(0);') .html('Change plot size') .on('click', function() { self.__cell_size = orgSize; self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables); }); size_a.append('a') .attr('class', 'btn btn-default btn-xs') .attr('href', 'javascript:void(0);') .html('+') .on('click', function() { self.__cell_size += 50; self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables); }); //set to full screen mode;------------------------------------------------------------------------------------------------- var isRightChartFullScreenToggled = false; var windowHeight = window.innerHeight; var originalCellSize = self.__cell_size; $("#scatter-fullscreen-toggle").click(function(e) { isRightChartFullScreenToggled = !isRightChartFullScreenToggled; if (isRightChartFullScreenToggled) { self.__cell_size = (windowHeight - 250) / 2; d3.selectAll(".cell circle").attr("r", "3"); } else { self.__cell_size = originalCellSize; d3.selectAll(".cell circle").attr("r", "1"); } self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables); }); var variable_li = variable_control .append('p').text('Vertical Variables: ') .append('ul') .selectAll('li') .data(self.__numeric_variables) .enter().append('li'); variable_li.append('input') .attr('type', 'checkbox') .attr('checked', function(d, i) { if (to_include.indexOf(d) >= 0) return "checked"; return null; }) .on('click', function(d, i) { var new_to_include = []; for (var j in to_include) { var v = to_include[j]; if (v !== d || this.checked) { new_to_include.push(v); } } if (this.checked) { new_to_include.push(d); } to_include = new_to_include; self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables); }); variable_li.append('label') .html(function(d) { var i = self.__numeric_variables.indexOf(d) + 1; return '' + i + ': ' + d; }); // drill_li = // drill_control // .append('p').text('Horizontal Variable:') // .append('ul') // .selectAll('li') // .data(original_numeric_variables) // .enter().append('li'); // // drill_li.append('input') // .attr('type', 'checkbox') // .on('click', function(d, i) { // var new_drill_variables = []; // for (var j in drill_variables) { // var v = drill_variables[j]; // if (v !== d || this.checked) { // new_drill_variables.push(v); // } // } // if (this.checked) { // new_drill_variables.push(d); // } // drill_variables = new_drill_variables; // self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables); // }); // drill_li.append('label') // .html(function(d) { // return d; // }); self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables); }); }; // NOTE: unique id for each Circle function getCircleID(d) { var id = "scatter_" + d.scid; return id; } ScatterMatrix.prototype.__draw = function(cell_size, container_el, color_variable, selected_colors, to_include, drill_variables) { var self = this; this.onData(function() { var data = self.__data; // filter data by selected colors if (color_variable && selected_colors) { data = []; self.__data.forEach(function(d) { if (selected_colors.indexOf(d[color_variable]) >= 0) { data.push(d); } }); } container_el.selectAll('*').remove(); // If no data, don't do anything if (data.length === 0) { return; } // Parse headers from first row of data var variables_to_draw = to_include.slice(0); // Get values of the string variable var colors = []; if (color_variable) { // Using self.__data (all data), instead of data (data to be drawn), so // our css classes are consistent when we filter by value. self.__data.forEach(function(d) { var s = d[color_variable]; if (colors.indexOf(s) < 0) { colors.push(s); } }); } function color_class(d) { var c = d; if (color_variable && d[color_variable]) { c = d[color_variable]; } return colors.length > 0 ? 'color-' + colors.indexOf(c) : 'color-2'; } // Size parameters var size = cell_size, padding = 10, axis_width = 20, axis_height = 15, legend_width = 0, label_height = 15; // Get x and y scales for each numeric variable var x = {}, y = {}; variables_to_draw.forEach(function(trait) { // Coerce values to numbers. data.forEach(function(d) { d[trait] = +d[trait]; }); var value = function(d) { return d[trait]; }, domain = [d3.min(data, value), d3.max(data, value)], range_x = [padding / 2, size - padding / 2], range_y = [padding / 2, size - padding / 2]; x[trait] = d3.scale.linear().domain(domain).range(range_x); y[trait] = d3.scale.linear().domain(domain).range(range_y.reverse()); }); // When drilling, user select one or more variables. The first drilled // variable becomes the x-axis variable for all columns, and each column // contains only data points that match specific values for each of the // drilled variables other than the first. var drill_values = []; var drill_degrees = [] drill_variables.forEach(function(variable) { // Skip first one, since that's just the x axis if (drill_values.length == 0) { drill_values.push([]); drill_degrees.push(1); } else { var values = []; data.forEach(function(d) { var v = d[variable]; if (v !== undefined && values.indexOf(v) < 0) { values.push(v); } }); values.sort(); drill_values.push(values); drill_degrees.push(values.length); } }); var total_columns = 1; drill_degrees.forEach(function(d) { total_columns *= d; }); // Pick out stuff to draw on horizontal and vertical dimensions if (drill_variables.length > 0) { // First drill is now the x-axis variable for all columns x_variables = []; for (var i = 0; i < total_columns; i++) { x_variables.push(drill_variables[0]); } } else x_variables = variables_to_draw.slice(0); if (drill_variables.length > 0) { // Don't draw any of the "drilled" variables in vertical dimension y_variables = []; variables_to_draw.forEach(function(variable) { if (drill_variables.indexOf(variable) < 0) { y_variables.push(variable); } }); } else y_variables = variables_to_draw.slice(0); y_variables = y_variables.reverse(); var filter_descriptions = 0; if (drill_variables.length > 1) { filter_descriptions = drill_variables.length - 1; } // Formatting for axis var intf = d3.format('d'); var fltf = d3.format('.f'); var scif = d3.format('.1e'); // Brush - for highlighting regions of data var brush = d3.svg.brush() .on("brushstart", brushstart) .on("brush", brush) .on("brushend", brushend); // Root panel var svg = container_el.append("svg:svg") .attr("width", label_height + size * x_variables.length + axis_width + padding + legend_width) .attr("height", size * y_variables.length + axis_height + label_height + label_height * filter_descriptions) .append("svg:g") .attr("transform", "translate(" + label_height + ",0)"); // Push legend to the side var legend = svg.selectAll("g.legend") .data(colors) .enter().append("svg:g") .attr("class", "legend") .attr("transform", function(d, i) { return "translate(" + (label_height + size * x_variables.length + padding) + "," + (i * 20 + 10) + ")"; }); legend.append("svg:text") .attr("x", 12) .attr("dy", ".31em") .text(function(d) { return d; }); var shorten = function(s) { if (s.length > 16) return s.slice(0, 12) + '...' + s.slice(s.length - 8, s.length); return s; }; var reshape_axis = function(axis, k) { axis.ticks(5) .tickFormat(function(d) { if (Math.abs(+d) > 10000 || (Math.abs(d) < 0.001 && Math.abs(d) != 0)) { return scif(d); } if (parseInt(d) == +d) { return intf(d); } return fltf(d); }); return axis; }; // Draw X-axis svg.selectAll("g.x.axis") .data(x_variables) .enter().append("svg:g") .attr("class", "x axis") .attr("transform", function(d, i) { return "translate(" + i * size + ",0)"; }) .each(function(k) { var axis = reshape_axis(d3.svg.axis(), k); axis.tickSize(size * y_variables.length); d3.select(this).call(axis.scale(x[k]).orient('bottom')); }); // Draw Y-axis svg.selectAll("g.y.axis") .data(y_variables) .enter().append("svg:g") .attr("class", "y axis") .attr("transform", function(d, i) { return "translate(0," + i * size + ")"; }) .each(function(k) { var axis = reshape_axis(d3.svg.axis(), k); axis.tickSize(size * x_variables.length); d3.select(this).call(axis.scale(y[k]).orient('right')); }); // Draw scatter plot var cell = svg.selectAll("g.cell") .data(cross(x_variables, y_variables)) .enter().append("svg:g") .attr("class", "cell") .attr("transform", function(d) { return "translate(" + d.i * size + "," + d.j * size + ")"; }) .each(plot); // Add titles for y variables cell.filter(function(d) { return d.i == 0; }).append("svg:text") .attr("x", padding - size) .attr("y", -label_height) .attr("dy", ".71em") .attr("transform", function(d) { return "rotate(-90)"; }) .text(function(d) { var s = self.__numeric_variables.indexOf(d.y) + 1; s = '' + s + ': ' + d.y; return shorten(s); }); function plot(p) { var data_to_draw = data; // If drilling, compute what values of the drill variables correspond to // this column. // var filter = {}; if (drill_variables.length > 1) { var column = p.i; var cap = 1; for (var i = drill_variables.length - 1; i > 0; i--) { var var_name = drill_variables[i]; var var_value = undefined; if (i == drill_variables.length - 1) { // for the last drill variable, we index by % var_value = drill_values[i][column % drill_degrees[i]]; } else { // otherwise divide by capacity of subsequent variables to get value array index var_value = drill_values[i][parseInt(column / cap)]; } filter[var_name] = var_value; cap *= drill_degrees[i]; } data_to_draw = []; data.forEach(function(d) { var pass = true; for (k in filter) { if (d[k] != filter[k]) { pass = false; break; } } if (pass === true) { data_to_draw.push(d); } }); } var cell = d3.select(this); // Frame cell.append("svg:rect") .attr("class", "frame") .attr("x", padding / 2) .attr("y", padding / 2) .attr("width", size - padding) .attr("height", size - padding); // Scatter plot dots cell.selectAll("circle") .data(data_to_draw) .enter().append("svg:circle") .attr("id", function(d) { //console.log(d); return getCircleID(d); }) // .attr("class", "selected") .attr("cx", function(d) { return x[p.x](d[p.x]); }) .attr("cy", function(d) { return y[p.y](d[p.y]); }) .attr("r",function(d){ return isRightChartFullScreenToggled?2:1; }); // Add titles for x variables and drill variable values if (p.j == y_variables.length - 1) { cell.append("svg:text") .attr("x", padding) .attr("y", size + axis_height) .attr("dy", ".71em") .text(function(d) { var s = self.__numeric_variables.indexOf(d.x) + 1; s = '' + s + ': ' + d.x; return shorten(s); }); if (drill_variables.length > 1) { var i = 0; for (k in filter) { i += 1; cell.append("svg:text") .attr("x", padding) .attr("y", size + axis_height + label_height * i) .attr("dy", ".71em") .text(function(d) { return shorten(filter[k] + ': ' + k); }); } } } // Brush cell.call(brush.x(x[p.x]).y(y[p.y])); } // Clear the previously-active brush, if any function brushstart(p) { if (brush.data !== p) { cell.call(brush.clear()); brush.x(x[p.x]).y(y[p.y]).data = p; } } // Highlight selected circles function brush(p) { var e = brush.extent(); svg.selectAll(".cell circle").classed("faded", function(d) { return e[0][0] <= d[p.x] && d[p.x] <= e[1][0] && e[0][1] <= d[p.y] && d[p.y] <= e[1][1] ? false : true; }); } // If brush is empty, select all circles function brushend() { if (brush.empty()) svg.selectAll(".scatter-matrix-svg .cell circle").classed("faded", true); } function cross(a, b) { var c = [], n = a.length, m = b.length, i, j; for (i = -1; ++i < n;) for (j = -1; ++j < m;) c.push({ x: a[i], i: i, y: b[j], j: j }); return c; } }); updateScatterChart(); //for selected data highlightScatterDot();//for highlighted Data update_sc_colorsOnly(); };
serenayl/DesignExplorer
lib/scatter_matrix_source_files/scatter-matrix.js
JavaScript
mit
23,208
const times = require('lodash/times'); const {GameEngine} = require('../../lib/common/engine'); const {R, G, B, _} = require('../../lib/common/panel-league/util'); module.exports.testAdd = ((test) => { const game = new GameEngine(); game.addEvent({ time: 0, type: 'addGarbage', slab: {x: 0, width: game.width, height: 1} }); game.step(); const state = game.step(); test.expect(1); test.strictEqual(state.garbage.length, 1, "No garbage slab found"); test.done(); }); module.exports.testFit = ((test) => { const game = new GameEngine({initialRows: 0, width: 6}); game.addEvent({ time: 0, type: 'addGarbage', slab: {x: 0, width: 2, height: 1} }); game.addEvent({ time: 1, type: 'addGarbage', slab: {x: 2, width: 2, height: 2} }); times(100, () => game.step()); state = game.step(); test.expect(6); for (let i = 0; i < 4; ++i) { test.ok(state.blocks[i + state.width * (state.height - 1)].color, "Empty block found"); } for (let i = 4; i < 6; ++i) { test.ok(!state.blocks[i + state.width * (state.height - 1)].color, "Non-empty block found"); } test.done(); }); module.exports.testOverhang = ((test) => { const game = new GameEngine({initialRows: 0}); game.addEvent({ time: 0, type: 'addGarbage', slab: {x: 0, width: 1, height: 2} }); game.addEvent({ time: 1, type: 'addGarbage', slab: {x: 0, width: game.width, height: 2} }); times(100, () => game.step()); state = game.step(); test.expect(2 * game.width - 1); for (let i = 1; i < game.width; ++i) { test.ok(!state.blocks[i + state.width * (state.height - 1)].color, "Non-empty block found"); } for (let i = 0; i < game.width; ++i) { test.ok(state.blocks[i + state.width * (state.height - 3)].color, "Empty block found"); } test.done(); }); module.exports.testShock = ((test) => { setup = [ _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, G, R, G, G, B, B, ]; const game = new GameEngine({width: 6, height: 5, colors: setup}); game.addEvent({ time: 0, type: 'addGarbage', slab: {x: 0, width: game.width, height: 2} }); game.addEvent({ time: 1, type: 'addGarbage', slab: {x: 0, width: game.width, height: 2} }); game.addEvent({ time: 101, type: 'swap', index: 24 }); test.expect(2 + 2 * game.width); times(99, () => game.step()); let state = game.step(); let numGarbage = state.blocks.reduce((sum, block) => sum + block.garbage, 0); test.strictEqual(numGarbage, game.width * 4, 'Not enough garbage found'); times(99, () => game.step()); state = game.step(); numGarbage = state.blocks.reduce((sum, block) => sum + block.garbage, 0); test.strictEqual(numGarbage, game.width * 2, 'Garbage not released correctly'); // We don't control RNG here so prepare for rare matches. const shift = game.width * !state.blocks[0].color; for (let i = 0; i < game.width; ++i) { test.ok(state.blocks[i + shift].garbage, "Garbage not preserved"); test.ok(!state.blocks[i + game.width + shift].garbage, "Garbage not released"); } test.done(); });
frostburn/panel-league
test/panel-league/test-garbage.js
JavaScript
mit
3,160
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { let root = arguments.length <= 0 || arguments[0] === undefined ? '.' : arguments[0]; let options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; root = (0, _path.normalize)((0, _path.resolve)(root)); options.routes = clone(options.routes || []); options = Object.assign({ routes: null, index: '/index' }, options); for (let route of options.routes) { route.url = (0, _pathToRegexp2.default)(route.url); } return function* (next) { for (let route of options.routes) { let matched, params; if (this.path === '/') { break; } if (!(matched = route.url.exec(this.path))) { continue; } params = {}; matched = matched.slice(1); route.url.keys.forEach((item, index) => { params[item.name] = matched[index]; }); this.params = params; this.path = route.controller; break; } if (this.params) { if (!this.state.renderData) { this.state.renderData = {}; } Object.assign(this.state.renderData, this.params); } let path = (0, _path.join)(root, (this.path === '/' ? options.index : this.path) + '.js'); try { if ((yield _coFs2.default.stat(path)).isFile()) { yield _interopRequireDefault(require(path)).default().call(this); } } catch (err) { if (~['ENOENT', 'ENAMETOOLONG', 'ENOTDIR'].indexOf(err.code)) { return; } } yield next; }; }; var _coFs = require('co-fs'); var _coFs2 = _interopRequireDefault2(_coFs); var _pathToRegexp = require('path-to-regexp'); var _pathToRegexp2 = _interopRequireDefault2(_pathToRegexp); var _path = require('path'); function _interopRequireDefault2(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function clone(obj) { return JSON.parse(JSON.stringify(obj)); }
koa-robots/koa-robots-router
dist/index.js
JavaScript
mit
2,320
'use strict'; /** * Home controller simply lists all the videos */ angular.module("nodeVideoCMS.videos").controller("VideosCtrl", function($scope, $routeParams, api){ var videosPerPage = 12, criteria; $scope.maxSize = 5; $scope.currentPage = 1; $scope.paginationVisible = false; if($routeParams && $routeParams.categoryID) { criteria = { category : parseInt($routeParams.categoryID) } } api.videos.list(0, videosPerPage, criteria).success(function (res) { $scope.totalItems = res.total_record_count; $scope.videos = res.records; $scope.paginationVisible = $scope.totalItems > videosPerPage; }); api.categories.list().success(function (categories) { $scope.categories = categories; }); $scope.pageChanged = function() { var start = videosPerPage * ($scope.currentPage - 1), end = videosPerPage * $scope.currentPage; api.videos.list(start, end, criteria).success(function (res) { $scope.videos = res.records; }); }; });
madhukard/node-video-cms
client/modules/videos/videosController.js
JavaScript
mit
1,013
/* global window */ import React from 'react' import NProgress from 'nprogress' import PropTypes from 'prop-types' import { connect } from 'dva' import { Helmet } from 'react-helmet' import { withRouter } from 'dva/router' let lastHref const App = ({ children, dispatch, app, loading, location }) => { const href = window.location.href if (lastHref !== href) { NProgress.start() if (!loading.global) { NProgress.done() lastHref = href } } return ( <div> <Helmet> <title>DVA DEMO</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </Helmet> <div> { children } </div> </div> ) } App.propTypes = { children: PropTypes.element.isRequired, location: PropTypes.object, dispatch: PropTypes.func, app: PropTypes.object, loading: PropTypes.object, } export default withRouter(connect(({ app, loading }) => ({ app, loading }))(App))
Alfred-sg/plutarch
packages/plutarch/tpls/dva-project/src/routes/app.js
JavaScript
mit
958
'use strict'; describe("Calling the fromTo-function of a moment", function(){ moment.period .add({name: 'fromTo15Minutes', count: 15, unit: 'minute'}) .add({name: 'fromTo1Month', count: 1, unit: 'month'}); it("should create an object with properties for from and to", function(){ expect(moment().fromTo().from).toBeDefined(); expect(moment().fromTo().to).toBeDefined(); }); it("should return a fromTo where from and to are same as moment if no period is defined", function(){ var testMoment = moment(); expect(testMoment.isSame(testMoment.fromTo().from)).toBe(true); expect(testMoment.isSame(testMoment.fromTo().to)).toBe(true); }); it("should return the start and the end of the period of a moment", function() { var testMoment = moment.utc({ years :2010, months :5, date :5, hours :5, minutes :8, seconds :3, milliseconds : 9 }).period('fromTo15Minutes'); expect(testMoment.clone().period(true).isSame(testMoment.fromTo().from)).toBe(true); expect(testMoment.clone().period(false).isSame(testMoment.fromTo().to)).toBe(true); }); it("should return the start and the end of a named period for a moment", function() { var testMoment = moment.utc({ years :2010, months :5, date :5, hours :5, minutes :8, seconds :3, milliseconds : 9 }).period('fromTo15Minutes'); expect(testMoment.clone().period('fromTo1Month').period(true).isSame(testMoment.fromTo('fromTo1Month').from)).toBe(true); expect(testMoment.clone().period('fromTo1Month').period(false).isSame(testMoment.fromTo('fromTo1Month').to)).toBe(true); }); });
smartin85/moment-period
tests/period-from-to.spec.js
JavaScript
mit
1,661
(function() { 'use strict'; angular.module('journal.component.editor') .service('EditorService', ['$http', 'AuthService', 'CONFIG', EditorService]); function EditorService($http, AuthService, CONFIG) { this.apiUrl = CONFIG.API_URL; this.checkSlug = function(title, id) { var url = this.apiUrl + '/posts/check_slug?slug=' + (title || ''); // check if id is set if (id) { url += '&post_id=' + id; } // do an API request return $http.get(url); }; this.getPost = function(id) { return $http.get(this.apiUrl + '/posts/get_post?post_id=' + id); }; this.getTags = function() { return $http.get(this.apiUrl + '/tags/all'); }; this.save = function(post) { var token = AuthService.getToken(), url = this.apiUrl + '/posts/save?token=' + token, authorId = post.author_id || '', title = post.title || '', markdown = post.markdown || '', featuredImage = post.featured_image || '', slug = post.slug || '', status = post.status || 2, tags = post.tags || [], publishedAt = post.published_at.getTime() / 1000 || Math.floor(Date.now() / 1000); // check if post_id is set if (post.id) { url += '&post_id=' + post.id; } // send the request to the API return $http.post(url, { author_id : authorId, title : title, markdown : markdown, featured_image : featuredImage, slug : slug, status : status, tags : tags, published_at : publishedAt}); }; } })();
ricomonster/journal-blogging-platform
resources/src/components/editor/EditorService.js
JavaScript
mit
2,048
/*global module, process*/ /*eslint no-use-before-define:0 */ var webpack = require('webpack'); var webpackDevServer = require('webpack-dev-server'); var path = require('path'); // Support for extra commandline arguments var argv = require('optimist') //--env=XXX: sets a global ENV variable (i.e. window.ENV='XXX') .alias('e', 'env').default('e', 'dev') .argv; var config = { context: __dirname, entry: {'bundle': './main'}, output: { path: path.join(__dirname, 'dist'), filename: '[name].js', publicPath: isDevServer() ? '/' : '' }, devServer: { publicPath: '/' }, reload: isDevServer() ? 'localhost' : null, module: { loaders: [ { test: /\.json$/, loader: 'json-loader' }, { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.less$/, loader: 'style-loader!css-loader!less-loader' }, { test: /\.(png|jpg|gif)$/, loader: 'url-loader?limit=5000&name=[path][name].[ext]&context=./src' }, { test: /\.eot$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' }, { test: /\.ttf$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' }, { test: /\.svg$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' }, { test: /\.woff$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' }, { test: /index\.html$/, loader: 'file-loader?name=[path][name].[ext]&context=.' } ] }, resolve: { alias: { 'famous-flex': 'famous-flex/src' } }, plugins: [ new webpack.DefinePlugin({ VERSION: JSON.stringify(require('../package.json').version), ENV: JSON.stringify(argv.env) }) ] }; function isDevServer() { return process.argv.join('').indexOf('webpack-dev-server') > -1; } module.exports = config;
IjzerenHein/famous-lib-tester
webpack/webpack.config.js
JavaScript
mit
1,894
var hello = function() { alert("My name is" name) };
progressions/epic
features/data/javascripts/invalid_uncompressed.js
JavaScript
mit
54
var _ = require("lodash-node"); module.exports = function(client) { client.connect(function(err) { if(err) { return console.error('could not connect to postgres', err); } // 1. clear any previous migrations, db constraints will cascade on theme links and maplayers // var query = "DELETE FROM oskari_layergroup; DELETE FROM oskari_resource WHERE resource_mapping LIKE '%_migrated+collection';"; runSQL(client, query, copyLayerGroups, 'could not clear previous migration!'); }); // 2. Create layer groups (organisations) function copyLayerGroups(client) { var query = "INSERT INTO oskari_layergroup (id, locale) SELECT id, locale FROM portti_layerclass WHERE parent IS NULL"; runSQL(client, query, fixGroupIdSequence, 'could not copy layer groups'); } // 3. update serial column sequence value since we inserted ids manually!! function fixGroupIdSequence(client) { var fixSequenceSQL = "SELECT setval(pg_get_serial_sequence('oskari_layergroup', 'id'), (SELECT MAX(id) FROM oskari_layergroup));"; runSQL(client, fixSequenceSQL, copyNormalLayers, 'could not fix sequence for oskari_layergroup.id'); } // 4. Copy independent/normal layers (that are not sublayers) function copyNormalLayers(client) { var selectSQL = "SELECT id, -1 AS parentId, layer_type, false AS base_map, layerclassid AS groupId, wmsname, wmsurl, " + "locale, opacity, '' AS style, minscale, maxscale, legend_image, dataurl, " + "tile_matrix_set_id, tile_matrix_set_data, gfi_type, xslt, " + "created, updated " + "FROM portti_maplayer WHERE layerclassid IN (SELECT id FROM oskari_layergroup);"; var insertSQL = "INSERT INTO oskari_maplayer(" + "id, parentid, type, base_map, groupid, name, url," + "locale, opacity, style, minscale, maxscale, legend_image, metadataid," + "tile_matrix_set_id, tile_matrix_set_data, gfi_type, gfi_xslt, " + "created, updated) "; runSQL(client, insertSQL + selectSQL, copySubLayers, 'could not copy normal layers'); } // 5. copy layers that are sublayers function copySubLayers(client) { // NOTE! sublayers will have groupId=1 and parentId as layerclassid var selectSQL = "SELECT id, layerclassid AS parentId, layer_type, false AS base_map, 1 AS groupId, wmsname, wmsurl, " + "locale, opacity, style, minscale, maxscale, legend_image, dataurl, " + "tile_matrix_set_id, tile_matrix_set_data, gfi_type, xslt, " + "created, updated " + "FROM portti_maplayer WHERE layerclassid NOT IN (SELECT id FROM oskari_layergroup);"; var insertSQL = "INSERT INTO oskari_maplayer(" + "id, parentid, type, base_map, groupid, name, url," + "locale, opacity, style, minscale, maxscale, legend_image, metadataid," + "tile_matrix_set_id, tile_matrix_set_data, gfi_type, gfi_xslt, " + "created, updated) "; runSQL(client, insertSQL + selectSQL, fixIdSequence, 'could not copy sublayers'); } // 6. update serial column sequence value since we inserted ids manually!! function fixIdSequence(client) { var fixSequenceSQL = "SELECT setval(pg_get_serial_sequence('oskari_maplayer', 'id'), (SELECT MAX(id) FROM oskari_maplayer));"; runSQL(client, fixSequenceSQL, createNewBaseLayers, 'could not fix sequence for oskari_maplayer.id'); } // 7. establish new rows to oskari_maplayers from portti_layerclass base/group layers function createNewBaseLayers(client) { var selectSQL = "SELECT -1 AS parentId, id AS externalId, 'collection' AS type, NOT group_map AS base_map, parent AS groupId, " + "id || '_migrated' AS name, 'collection' AS url, " + "locale, 100 AS opacity, '' AS style, -1 AS minscale, -1 AS maxscale, legend_image, dataurl AS metadataId, " + "'' AS tile_matrix_set_id, '' AS tile_matrix_set_data, '' AS gfi_type, '' AS gfi_xslt " + "FROM portti_layerclass WHERE parent IS NOT NULL"; var insertSQL = "INSERT INTO oskari_maplayer(" + "parentid, externalId, type, base_map, groupid, name, url," + "locale, opacity, style, minscale, maxscale, legend_image, metadataid," + "tile_matrix_set_id, tile_matrix_set_data, gfi_type, gfi_xslt) "; runSQL(client, insertSQL + selectSQL, linkSublayers, 'could not establish new collection layers'); } // 8. link sublayers to new baselayers function linkSublayers(client) { var linkSQL = "UPDATE oskari_maplayer SET parentId = m.id FROM oskari_maplayer m " + "WHERE oskari_maplayer.parentId != -1 AND oskari_maplayer.parentId = m.externalId::integer" //runSQL(client, linkSQL, updateExternalIds, 'could not link sublayers'); runSQL(client, linkSQL, copyBaseLayerPermissions, 'could not link sublayers'); } // 8.5 setup base/group layer permissions function copyBaseLayerPermissions(client) { var selectGroupsSQL = "SELECT id, name, url, externalId FROM oskari_maplayer WHERE type='collection'"; client.query(selectGroupsSQL, function(err, groupLayers) { if(err) { return console.error("Couldn't find collection layers", err); } console.log('got collection layers', groupLayers.rows.length); var count = 0; var resources = []; function permissionsCopied(err) { /* if(err) { // if previous layer had no permissions -> an error will occur, // so skipping any errors since this _should_ work :) console.log("Permissions with resource ids:", resources); return console.error("Couldn't insert permissions for resource", err); }*/ count++; // after all sqls executed -> go to next step if(count == groupLayers.rows.length) { console.log("Inserted new resources/permissions with resource ids:", resources); updateExternalIds(client); } } _.forEach(groupLayers.rows, function(layer) { //console.log('Handling layer:', layer); // insert as new resources var insertResource = "INSERT INTO oskari_resource (resource_type, resource_mapping) " + "VALUES ('maplayer', '" + layer.url + "+" + layer.name + "') " + "RETURNING ID;"; client.query(insertResource, function(err, insertResult) { if(err) { count++; return console.error("Couldn't insert grouplayer as resource", layer, err); } var resourceId = insertResult.rows[0].id; resources.push(resourceId); // copy permissions from matching layerclass var copyPermissionsSQL = "INSERT INTO oskari_permission (oskari_resource_id, external_type, permission, external_id) " + "SELECT " + resourceId + ", p.external_type, p.permission, p.external_id FROM oskari_resource r, oskari_permission p " + "WHERE r.id = p.oskari_resource_id AND r.resource_type='layerclass' AND r.resource_mapping = 'BASE+" + layer.externalid + "'"; runSQL(client, copyPermissionsSQL, permissionsCopied, 'Could not copy permissions for layer: ' + JSON.stringify(layer)); }); }); }); } // 9. update externalId with base_ prefix function updateExternalIds(client) { var prefixSQL = "UPDATE oskari_maplayer SET externalId = 'base_' || externalId " + "WHERE externalId IS NOT NULL"; runSQL(client, prefixSQL, linkInspireThemesForNormalLayers, 'could not prefix external ids'); } // 10. link themes from old db table for layers that exist there (non baselayers) // TODO: check collection layers inspire themes! function linkInspireThemesForNormalLayers(client) { var query = "INSERT INTO oskari_maplayer_themes (maplayerid, themeid) SELECT id, inspire_theme_id FROM portti_maplayer"; runSQL(client, query, linkInspireThemesForCollectionLayers, 'could not link inspire themes'); } // 11. Add inspire theme links to base/grouplayers function linkInspireThemesForCollectionLayers(client) { var selectSQL = "SELECT DISTINCT m1.id AS baseId, t.themeid FROM oskari_maplayer m1, oskari_maplayer m2, " + "oskari_maplayer_themes t WHERE m1.id = m2.parentId AND t.maplayerid = m2.id;" var linkSql = "INSERT INTO oskari_maplayer_themes (maplayerid, themeid) "; runSQL(client, linkSql + selectSQL, updateStylesForWMS, 'could not link inspire themes'); } // 12. update default styles for wms layers // TODO: check if wmts needs this!! function updateStylesForWMS(client) { var updateSQL = "UPDATE oskari_maplayer SET style = substr(m.style, 1, 100) FROM portti_maplayer m " + "WHERE oskari_maplayer.id = m.id AND m.layer_type = 'wmslayer'" runSQL(client, updateSQL, allDone, 'could not update default styles for layers'); } // 13. all done function allDone(client) { console.log("Upgrade complete, you can now remove portti_maplayer and portti_layerclass tables from database"); client.end(); } function runSQL(client, sql, callback, errorMsg) { client.query(sql, function(err) { if(err) { return console.error(errorMsg, err); } callback(client); }); } }
uhef/Oskari-Routing
content-resources/db-upgrade/scripts/oskari_maplayers_migration.js
JavaScript
mit
9,887
import React from 'react'; import _ from 'lodash'; import { FlatButton, RaisedButton } from 'material-ui'; const DialogStandardButtons = ({ handleCancel, handleConfirm, submitLabel = 'Confirm', cancelLabel = 'Cancel', inverted, disabled, submitDisabled, cancelDisabled, ...other }) => { const styles = { rootInverted: { display: 'flex', flexDirection: 'row-reverse', justifyContent: 'flex-end', marginLeft: -10 }, button: { marginLeft: 10, borderRadius: '4px' } }; return ( <div style={inverted && styles.rootInverted}> <FlatButton key="cancel" label={cancelLabel} labelStyle={{ textTransform: 'none' }} buttonStyle={{ borderRadius: '4px' }} style={styles.button} disabled={disabled || cancelDisabled} onTouchTap={_.debounce(handleCancel, 500, { leading: true })} data-e2e={other['data-e2e-cancel']} /> <RaisedButton key="confirm" label={submitLabel} labelStyle={{ textTransform: 'none', color: '#436E1D' }} buttonStyle={{ borderRadius: '4px' }} backgroundColor="#B8E986" style={styles.button} disabled={disabled || submitDisabled} onTouchTap={_.debounce(handleConfirm, 500, { leading: true })} data-e2e={other['data-e2e-submit']} /> </div> ); }; export default DialogStandardButtons;
Syncano/syncano-dashboard
src/common/Dialog/DialogStandardButtons.js
JavaScript
mit
1,435
var mongoose = require('mongoose'); var workLogSchema = mongoose.Schema({ startedAt: { type: Date, required: true, default: Date.now }, timeSpent: { type: Number, required: true, validate: [ function (value) { return value > 0; }, 'Time spent must be greater than zero.' ] }, task: { type: mongoose.Schema.Types.ObjectId, ref: 'Task' }, user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }); workLogSchema.static({ findById: function (id, callback) { this.findOne({ _id: id }) .select('-task -user -__v') .exec(callback); }, findByIdAndTaskId: function (options, callback) { this.findOne({ _id: options.id, task: options.taskId }) .select('-task -user -__v') .exec(callback); }, findByTaskId: function (taskId, callback) { this.find({ task: taskId }) .select('-task -user -__v') .exec(callback); }, findByUserId: function (userId, callback) { this.find({ user: userId }) .select('-task -user -__v') .exec(callback); } }); workLogSchema.set('toJSON', { transform: function (doc, ret, options) { ret.id = ret._id; delete ret._id; delete ret.__v; } }); module.exports = mongoose.model('WorkLog', workLogSchema);
rodrigo-medeiros/simple-time-tracker-api
models/worklog.js
JavaScript
mit
1,333
import React, {Component} from 'react' import {findDOMNode} from 'react-dom' import styles from '../sass/Form' import {Button, Form, Input, DatePicker, Select} from 'antd' class FormComponent extends Component { constructor() { super() this.handleSubmit = this.handleSubmit.bind(this) } handleSubmit(e) { e.preventDefault() const {form, actions} = this.props form.validateFields((err, values) => { if (!err) { actions.getItems(values) } }) } render() { const {form, schools, cats} = this.props return ( <Form onSubmit={this.handleSubmit} className={styles.form} inline> <Form.Item label="学校"> {form.getFieldDecorator('school',{initialValue: schools[0]?schools[0].id:''})( <Select className={styles.select}> {schools.map(school => <Select.Option key={school.id} value={school.id}>{school.schoolName}</Select.Option> )} </Select> )} </Form.Item> <Form.Item label="分类"> {form.getFieldDecorator('cat',{initialValue: ''})( <Select className={styles.select}> <Select.Option value="">全部</Select.Option> {cats.map(cat => <Select.Option key={cat.id} value={cat.id}>{cat.catName}</Select.Option> )} </Select> )} </Form.Item> <Form.Item> <Button htmlType="submit" type="primary">查询</Button> </Form.Item> </Form> ) } } export default Form.create()(FormComponent)
chikara-chan/full-stack-javascript
manager/client/item/components/Form.js
JavaScript
mit
1,646
/** * Core dependencies. */ var path = require('path'); var dirname = path.dirname; /** * Create path. * * @param {String} pattern * @returns {Object} * @api private */ function createPattern(pattern) { return { pattern: pattern, included: true, served: true, watched: false }; } /** * Insert hydro into the loaded files. * * @param {Array} files * @api public */ function init(config) { var hydroConfig = config.hydro || {}; var hydroJs = hydroConfig.path || dirname(dirname(require.resolve('hydro'))) + '/dist/hydro.js'; var before = hydroConfig.before || []; config.files.unshift(createPattern(__dirname + '/adapter.js')); config.files.unshift(createPattern(hydroJs)); before.reverse().forEach(function(file) { config.files.unshift(createPattern(path.resolve(file))); }); } /** * Inject. */ init.$inject = [ 'config' ]; /** * Primary export. */ module.exports = { 'framework:hydro': [ 'factory', init ] };
hydrojs/karma-hydro
index.js
JavaScript
mit
977
/* * This class represent a game paddle */ 'use strict'; import Vector from 'Vector.js'; export default class { constructor(x, y, width, height, color = '#FFFFFF', speed = 3) { this.width = width; this.height = height; this.color = color; this.position = new Vector(x, y); this.velocity = new Vector(speed, 0); this.computer = false; // Control keys. this.rightPressed = false; this.leftPressed = false; } // Setting the paddle to a specific position. setPosition(x, y) { this.position.setCoordinates(x, y); } move(doMove) { if (this.rightPressed || this.leftPressed) { if (this.rightPressed) { this.velocity.x = Math.abs(this.velocity.x); } else if (this.leftPressed) { this.velocity.x = -Math.abs(this.velocity.x); } if (doMove) { this.position.add(this.velocity); } } } // Returns relevant drawing information related to // the paddle. getDrawInfo() { return { drawType: 'rect', color: this.color, params: [ this.position.x, this.position.y, this.width, this.height ] }; } }
BAJ-/robot-breakout
js/Paddle.js
JavaScript
mit
1,176
// // resourcetiming-decompression.js // // Decompresses ResourceTiming data compressed via resourcetiming-compression.js. // // See http://nicj.net/compressing-resourcetiming/ // // https://github.com/nicjansma/resourcetiming-compression.js // (function(window) { "use strict"; // save old ResourceTimingDecompression object for noConflict() var root; var previousObj; if (typeof window !== "undefined") { root = window; previousObj = root.ResourceTimingDecompression; } // model var ResourceTimingDecompression = {}; // // Functions // /** * Returns the index of the first value in the array such that it is * greater or equal to x. * The search is performed using binary search and the array is assumed * to be sorted in ascending order. * * @param {array} arr haystack * @param {any} x needle * @param {function} by transform function (optional) * * @returns {number} the desired index or arr.length if x is more than all values. */ ResourceTimingDecompression.searchSortedFirst = function(arr, x, by) { if (!arr || arr.length === 0) { return -1; } function ident(a) { return a; } by = by || ident; x = by(x); var min = -1; var max = arr.length; var m = 0; while (min < (max - 1)) { m = (min + max) >>> 1; if (by(arr[m]) < x) { min = m; } else { max = m; } } return max; }; /** * Returns the index of the last value in the array such that is it less * than or equal to x. * The search is performed using binary search and the array is assumed * to be sorted in ascending order. * * @param {array} arr haystack * @param {any} x needle * @param {function} by transform function (optional) * * @returns {number} the desired index or -1 if x is less than all values. */ ResourceTimingDecompression.searchSortedLast = function(arr, x, by) { if (!arr || arr.length === 0) { return -1; } function ident(a) { return a; } by = by || ident; x = by(x); var min = -1; var max = arr.length; var m = 0; while (min < (max - 1)) { m = (min + max) >>> 1; if (x < by(arr[m])) { max = m; } else { min = m; } } return min; }; /** * Changes the value of ResourceTimingDecompression back to its original value, returning * a reference to the ResourceTimingDecompression object. * * @returns {object} Original ResourceTimingDecompression object */ ResourceTimingDecompression.noConflict = function() { root.ResourceTimingDecompression = previousObj; return ResourceTimingDecompression; }; /** * Initiator type map */ ResourceTimingDecompression.INITIATOR_TYPES = { "other": 0, "img": 1, "link": 2, "script": 3, "css": 4, "xmlhttprequest": 5, "html": 6, // IMAGE element inside a SVG "image": 7, "beacon": 8, "fetch": 9 }; /** * Dimension name map */ ResourceTimingDecompression.DIMENSION_NAMES = { "height": 0, "width": 1, "y": 2, "x": 3, "naturalHeight": 4, "naturalWidth": 5 }; /** * Script mask map */ ResourceTimingDecompression.SCRIPT_ATTRIBUTES = { "scriptAsync": 1, "scriptDefer": 2, "scriptBody": 4 }; /** * Returns a map with key/value pairs reversed. * * @param {object} origMap Map we want to reverse. * * @returns {object} New map with reversed mappings. */ ResourceTimingDecompression.getRevMap = function(origMap) { var revMap = {}; for (var key in origMap) { if (origMap.hasOwnProperty(key)) { revMap[origMap[key]] = key; } } return revMap; }; /** * Reverse initiator type map */ ResourceTimingDecompression.REV_INITIATOR_TYPES = ResourceTimingDecompression. getRevMap(ResourceTimingDecompression.INITIATOR_TYPES); /** * Reverse dimension name map */ ResourceTimingDecompression.REV_DIMENSION_NAMES = ResourceTimingDecompression. getRevMap(ResourceTimingDecompression.DIMENSION_NAMES); /** * Reverse script attribute map */ ResourceTimingDecompression.REV_SCRIPT_ATTRIBUTES = ResourceTimingDecompression. getRevMap(ResourceTimingDecompression.SCRIPT_ATTRIBUTES); // Any ResourceTiming data time that starts with this character is not a time, // but something else (like dimension data) var SPECIAL_DATA_PREFIX = "*"; // Dimension data special type var SPECIAL_DATA_DIMENSION_TYPE = "0"; var SPECIAL_DATA_DIMENSION_PREFIX = SPECIAL_DATA_PREFIX + SPECIAL_DATA_DIMENSION_TYPE; // Dimension data special type var SPECIAL_DATA_SIZE_TYPE = "1"; // Dimension data special type var SPECIAL_DATA_SCRIPT_TYPE = "2"; // Regular Expression to parse a URL var HOSTNAME_REGEX = /^(https?:\/\/)([^\/]+)(.*)/; /** * Decompresses a compressed ResourceTiming trie * * @param {object} rt ResourceTiming trie * @param {string} prefix URL prefix for the current node * * @returns {ResourceTiming[]} ResourceTiming array */ ResourceTimingDecompression.decompressResources = function(rt, prefix) { var resources = []; // Dimension data for resources. var dimensionData; prefix = prefix || ""; for (var key in rt) { // skip over inherited properties if (!rt.hasOwnProperty(key)) { continue; } var node = rt[key]; var nodeKey = prefix + key; // strip trailing pipe, which is used to designate a node that is a prefix for // other nodes but has resTiming data if (nodeKey.indexOf("|", nodeKey.length - 1) !== -1) { nodeKey = nodeKey.substring(0, nodeKey.length - 1); } if (typeof node === "string") { // add all occurences var timings = node.split("|"); if (timings.length === 0) { continue; } // Make sure we reset the dimensions before each new resource. dimensionData = undefined; if (this.isDimensionData(timings[0])) { dimensionData = this.decompressDimension(timings[0]); // Remove the dimension data from our timings array timings = timings.splice(1); } // end-node for (var i = 0; i < timings.length; i++) { var resourceData = timings[i]; if (resourceData.length > 0 && resourceData[0] === SPECIAL_DATA_PREFIX) { // dimensions or sizes for this resource continue; } // Decode resource and add dimension data to it. resources.push( this.addDimension( this.decodeCompressedResource(resourceData, nodeKey), dimensionData ) ); } } else { // continue down var nodeResources = this.decompressResources(node, nodeKey); resources = resources.concat(nodeResources); } } return resources; }; /* * Checks that the input contains dimension information. * * @param {string} resourceData The string we want to check. * * @returns boolean True if resourceData starts with SPECIAL_DATA_DIMENSION_PREFIX, false otherwise. */ ResourceTimingDecompression.isDimensionData = function(resourceData) { return resourceData && resourceData.substring(0, SPECIAL_DATA_DIMENSION_PREFIX.length) === SPECIAL_DATA_DIMENSION_PREFIX; }; /** * Extract height, width, y and x from a string. * * @param {string} resourceData A string containing dimension data. * * @returns {object} Dimension data with keys defined by DIMENSION_NAMES. */ ResourceTimingDecompression.decompressDimension = function(resourceData) { var dimensions, i; var dimensionData = {}; // If the string does not contain dimension information, do nothing. if (!this.isDimensionData(resourceData)) { return dimensionData; } // Remove special prefix resourceData = resourceData.substring(SPECIAL_DATA_DIMENSION_PREFIX.length); dimensions = resourceData.split(","); // The data should contain at least height/width. if (dimensions.length < 2) { return dimensionData; } // Base 36 decode and assign to correct keys of dimensionData. for (i = 0; i < dimensions.length; i++) { if (dimensions[i] === "") { dimensionData[this.REV_DIMENSION_NAMES[i]] = 0; } else { dimensionData[this.REV_DIMENSION_NAMES[i]] = parseInt(dimensions[i], 36); } } return dimensionData; }; /** * Adds dimension data to the given resource. * * @param {object} resource The resource we want to edit. * @param {object} dimensionData The dimension data we want to add. * * @returns {object} The resource with added dimensions. */ ResourceTimingDecompression.addDimension = function(resource, dimensionData) { // If the resource or data are not defined, do nothing. if (!resource || !dimensionData) { return resource; } // Add all the dimensions to our resource. for (var key in this.DIMENSION_NAMES) { if (this.DIMENSION_NAMES.hasOwnProperty(key) && dimensionData.hasOwnProperty(key)) { resource[key] = dimensionData[key]; } } return resource; }; /** * Compute a list of cells based on the start/end times of the * given array of resources. * The returned list of cells is sorted in chronological order. * * @param {array} rts array of resource timings. * * @returns {array} Array of cells. */ ResourceTimingDecompression.getSortedCells = function(rts) { // We have exactly 2 events per resource (start and end). // var cells = new Array(rts.length * 2); var cells = []; for (var i = 0; i < rts.length; i++) { // Ignore resources with duration <= 0 if (rts[i].responseEnd <= rts[i].startTime) { continue; } // Increment on resource start cells.push({ ts: rts[i].startTime, val: 1.0 }); // Decrement on resource end cells.push({ ts: rts[i].responseEnd, val: -1.0 }); } // Sort in chronological order cells.sort(function(x, y) { return x.ts - y.ts; }); return cells; }; /** * Add contributions to the array of cells. * * @param {array} cells array of cells that need contributions. * * @returns {array} Array of cells with their contributions. */ ResourceTimingDecompression.addCellContributions = function(cells) { var tot = 0.0; var incr = 0.0; var deleteIdx = []; var currentSt = cells[0].ts; var cellLen = cells.length; var c = {}; for (var i = 0; i < cellLen; i++) { c = cells[i]; // The next timestamp is the same. // We don't want to have cells of duration 0, so // we aggregate them. if ((i < (cellLen - 1)) && (cells[i + 1].ts === c.ts)) { cells[i + 1].val += c.val; deleteIdx.push(i); continue; } incr = c.val; if (tot > 0) { // divide time delta by number of active resources. c.val = (c.ts - currentSt) / tot; } currentSt = c.ts; tot += incr; } // Delete timestamps that don't delimit cells. for (i = deleteIdx.length - 1; i >= 0; i--) { cells.splice(deleteIdx[i], 1); } return cells; }; /** * Sum the contributions of a single resource based on an array of cells. * * @param {array} cells Array of cells with their contributions. * @param {ResourceTiming} rt a single resource timing object. * * @returns {number} The total contribution for that resource. */ ResourceTimingDecompression.sumContributions = function(cells, rt) { if (!rt || typeof rt.startTime === "undefined" || typeof rt.responseEnd === "undefined") { return 0.0; } var startTime = rt.startTime + 1; var responseEnd = rt.responseEnd; function getTs(x) { return x.ts; } // Find indices of cells that were affected by our resource. var low = this.searchSortedFirst(cells, {ts: startTime}, getTs); var up = this.searchSortedLast(cells, {ts: responseEnd}, getTs); var tot = 0.0; // Sum contributions across all those cells for (var i = low; i <= up; i++) { tot += cells[i].val; } return tot; }; /** * Adds contribution scores to all resources in the array. * * @param {array} rts array of resource timings. * * @returns {array} Array of resource timings with their contributions. */ ResourceTimingDecompression.addContribution = function(rts) { if (!rts || rts.length === 0) { return rts; } // Get cells in chronological order. var cells = this.getSortedCells(rts); // We need at least two cells and they need to begin // with a start event. Furthermore, the last timestamp // should be > 0. if (cells.length < 2 || cells[0].val < 1.0 || cells[cells.length - 1].ts <= 0 ) { return rts; } // Compute each cell's contribution. this.addCellContributions(cells); // Total load time for this batch of resources. var loadTime = cells[cells.length - 1].ts; for (var i = 0; i < rts.length; i++) { // Compute the contribution of each resource. // Normalize by total load time. rts[i].contribution = this.sumContributions(cells, rts[i]) / loadTime; } return rts; }; /** * Determines the initiatorType from a lookup * * @param {number} index Initiator type index * * @returns {string} initiatorType, or "other" if not known */ ResourceTimingDecompression.getInitiatorTypeFromIndex = function(index) { if (this.REV_INITIATOR_TYPES.hasOwnProperty(index)) { return this.REV_INITIATOR_TYPES[index]; } else { return "other"; } }; /** * Decodes a compressed ResourceTiming data string * * @param {string} data Compressed timing data * @param {string} url URL * * @returns {ResourceTiming} ResourceTiming pseudo-object (containing all of the properties of a * ResourceTiming object) */ ResourceTimingDecompression.decodeCompressedResource = function(data, url) { if (!data || !url) { return {}; } url = ResourceTimingDecompression.reverseHostname(url); var initiatorType = parseInt(data[0], 10); data = data.length > 1 ? data.split(SPECIAL_DATA_PREFIX) : []; var timings = data.length > 0 && data[0].length > 1 ? data[0].substring(1).split(",") : []; var sizes = data.length > 1 ? data[1] : ""; var specialData = data.length > 1 ? data[1] : ""; // convert all timings from base36 for (var i = 0; i < timings.length; i++) { if (timings[i] === "") { // startTime being 0 timings[i] = 0; } else { // de-base36 timings[i] = parseInt(timings[i], 36); } } // special case timestamps var startTime = timings.length >= 1 ? timings[0] : 0; // fetchStart is either the redirectEnd time, or startTime var fetchStart = timings.length < 10 ? startTime : this.decodeCompressedResourceTimeStamp(timings, 9, startTime); // all others are offset from startTime var res = { name: url, initiatorType: this.getInitiatorTypeFromIndex(initiatorType), startTime: startTime, redirectStart: this.decodeCompressedResourceTimeStamp(timings, 9, startTime) > 0 ? startTime : 0, redirectEnd: this.decodeCompressedResourceTimeStamp(timings, 9, startTime), fetchStart: fetchStart, domainLookupStart: this.decodeCompressedResourceTimeStamp(timings, 8, startTime), domainLookupEnd: this.decodeCompressedResourceTimeStamp(timings, 7, startTime), connectStart: this.decodeCompressedResourceTimeStamp(timings, 6, startTime), secureConnectionStart: this.decodeCompressedResourceTimeStamp(timings, 5, startTime), connectEnd: this.decodeCompressedResourceTimeStamp(timings, 4, startTime), requestStart: this.decodeCompressedResourceTimeStamp(timings, 3, startTime), responseStart: this.decodeCompressedResourceTimeStamp(timings, 2, startTime), responseEnd: this.decodeCompressedResourceTimeStamp(timings, 1, startTime) }; res.duration = res.responseEnd > 0 ? (res.responseEnd - res.startTime) : 0; // decompress resource size data if (sizes.length > 0) { this.decompressSpecialData(specialData, res); } return res; }; /** * Decodes a timestamp from a compressed RT array * * @param {number[]} timings ResourceTiming timings * @param {number} idx Index into array * @param {number} startTime NavigationTiming The Resource's startTime * * @returns {number} Timestamp, or 0 if unknown or missing */ ResourceTimingDecompression.decodeCompressedResourceTimeStamp = function(timings, idx, startTime) { if (timings && timings.length >= (idx + 1)) { if (timings[idx] !== 0) { return timings[idx] + startTime; } } return 0; }; /** * Decompresses script load type into the specified resource. * * @param {string} compressed String with a single integer. * @param {ResourceTiming} resource ResourceTiming object. * @returns {ResourceTiming} ResourceTiming object with decompressed script type. */ ResourceTimingDecompression.decompressScriptType = function(compressed, resource) { var data = parseInt(compressed, 10); if (!resource) { resource = {}; } for (var key in this.SCRIPT_ATTRIBUTES) { if (this.SCRIPT_ATTRIBUTES.hasOwnProperty(key)) { resource[key] = (data & this.SCRIPT_ATTRIBUTES[key]) === this.SCRIPT_ATTRIBUTES[key]; } } return resource; }; /** * Decompresses size information back into the specified resource * * @param {string} compressed Compressed string * @param {ResourceTiming} resource ResourceTiming bject * @returns {ResourceTiming} ResourceTiming object with decompressed sizes */ ResourceTimingDecompression.decompressSize = function(compressed, resource) { var split, i; if (typeof resource === "undefined") { resource = {}; } split = compressed.split(","); for (i = 0; i < split.length; i++) { if (split[i] === "_") { // special non-delta value split[i] = 0; } else { // fill in missing numbers if (split[i] === "") { split[i] = 0; } // convert back from Base36 split[i] = parseInt(split[i], 36); if (i > 0) { // delta against first number split[i] += split[0]; } } } // fill in missing if (split.length === 1) { // transferSize is a delta from encodedSize split.push(split[0]); } if (split.length === 2) { // decodedSize is a delta from encodedSize split.push(split[0]); } // re-add attributes to the resource resource.encodedBodySize = split[0]; resource.transferSize = split[1]; resource.decodedBodySize = split[2]; return resource; }; /** * Decompresses special data such as resource size or script type into the given resource. * * @param {string} compressed Compressed string * @param {ResourceTiming} resource ResourceTiming object * @returns {ResourceTiming} ResourceTiming object with decompressed special data */ ResourceTimingDecompression.decompressSpecialData = function(compressed, resource) { var dataType; if (!compressed || compressed.length === 0) { return resource; } dataType = compressed[0]; compressed = compressed.substring(1); if (dataType === SPECIAL_DATA_SIZE_TYPE) { resource = this.decompressSize(compressed, resource); } else if (dataType === SPECIAL_DATA_SCRIPT_TYPE) { resource = this.decompressScriptType(compressed, resource); } return resource; }; /** * Reverse the hostname portion of a URL * * @param {string} url a fully-qualified URL * @returns {string} the input URL with the hostname portion reversed, if it can be found */ ResourceTimingDecompression.reverseHostname = function(url) { return url.replace(HOSTNAME_REGEX, function(m, p1, p2, p3) { // p2 is everything after the first `://` and before the next `/` // which includes `<username>:<password>@` and `:<port-number>`, if present return p1 + ResourceTimingDecompression.reverseString(p2) + p3; }); }; /** * Reverse a string * * @param {string} i a string * @returns {string} the reversed string */ ResourceTimingDecompression.reverseString = function(i) { var l = i.length, o = ""; while (l--) { o += i[l]; } return o; }; // // Export to the appropriate location // if (typeof define === "function" && define.amd) { // // AMD / RequireJS // define([], function() { return ResourceTimingDecompression; }); } else if (typeof module !== "undefined" && module.exports) { // // Node.js // module.exports = ResourceTimingDecompression; } else if (typeof root !== "undefined") { // // Browser Global // root.ResourceTimingDecompression = ResourceTimingDecompression; } }(typeof window !== "undefined" ? window : undefined));
cvazac/resourcetiming-compression.js
src/resourcetiming-decompression.js
JavaScript
mit
24,045
var through = require('through2'); var escapeStr = require('js-string-escape'); var STYLE_HEADER = '!function(){var a="'; var STYLE_FOOTER = '",b=document.createElement("style");b.type="text/css",b.styleSheet?b.styleSheet.cssText=a:b.appendChild(document.createTextNode(a)),(document.head||document.getElementsByTagName("head")[0]).appendChild(b)}();'; function cssTojs() { function transform(file, enc, callback) { var css = file.contents.toString(); var content = STYLE_HEADER + escapeStr(css) + STYLE_FOOTER; file.contents = new Buffer(content); callback(null, file); } return through.obj(transform); } module.exports = cssTojs;
tamtakoe/gulp-css-to-js
index.js
JavaScript
mit
684
var angular = require('angular'); // import the hello UI component require('./hello/main'); // compose the app and the routes module.exports = angular .module('myApp', [ 'ngRoute', 'hello' ]) .config([ '$routeProvider', function ($routeProvider) { $routeProvider.when( '/', { templateUrl: 'app/hello/base.html', controller: 'HelloCtrl' } ); $routeProvider.otherwise({ redirectTo: '/' }); } ]); // start the application angular.bootstrap(document, ['myApp']);
RaveJS/rave-start-angular
app/main.js
JavaScript
mit
491
const chai = require('chai'); const MemoryCache = require('..'); const observable = require('../lib/observable'); const constants = require('../lib/constants'); const { expect, assert } = chai; const testObj = () => ({ a: { b: 'c' }, deep: { nested: { obj: { is: { set: 'yes' }}}}, arr: [1,2,3,4,5] }); const noop = () => {}; describe('Observable', function () { it('is a function', function () { expect(observable).to.be.a('function'); }); it('returns observable functions', function () { const x = observable(); expect(x.on).to.be.a('function'); expect(x.one).to.be.a('function'); expect(x.off).to.be.a('function'); expect(x.trigger).to.be.a('function'); }); it('does not observe non-symbol event', function () { const x = observable(); expect(() => { x.on('test', noop); }).to.throw(); }); it('observes symbol events', function () { const x = observable(); expect(() => { x.on(constants.get, noop); x.one(constants.get, noop); x.trigger(constants.get, noop); x.off(constants.get, noop); }).to.not.throw(); }); it('triggers functions bound to an event', function () { const x = observable(); let i = 0; x.on(constants.get, () => i++); x.trigger(constants.get) x.trigger(constants.get) x.trigger(constants.get) expect(i).to.equal(3); }); it('passes arguments to functions bound to an event', function () { const x = observable(); let args; x.on(constants.get, (a,b,c) => args = [a,b,c]); x.trigger(constants.get, 'a', 'b', 'c'); expect(args).to.include('a', 'b', 'c') }); it('removes functions bound to an event', function () { const x = observable(); let passed = true; const fn = () => passed = false; x.on(constants.get, fn); x.off(constants.get, fn); x.trigger(constants.get); expect(passed).to.equal(true); }); it('triggers functions bound to an event only one time', function () { const x = observable(); let i = 0; x.one(constants.get, () => i++); x.trigger(constants.get); x.trigger(constants.get); x.trigger(constants.get); expect(i).to.equal(1); }); }); describe('MemoryCache', function () { const test = testObj(); let cache; it('should be a function', function () { expect(MemoryCache).to.be.a('function'); }); it('should have all api functions', function () { cache = new MemoryCache(); // Assert all functions are set expect(cache).to.be.an('object'); expect(cache.set).to.be.a('function'); expect(cache.get).to.be.a('function'); expect(cache.remove).to.be.a('function'); expect(cache.expire).to.be.a('function'); expect(cache.merge).to.be.a('function'); expect(cache.concat).to.be.a('function'); expect(cache.reset).to.be.a('function'); expect(cache.has).to.be.a('function'); expect(cache.debug).to.not.equal(undefined); expect(cache.events).to.not.equal(undefined); expect(cache.size).to.not.equal(undefined); expect(cache.keys).to.not.equal(undefined); expect(cache.onGet).to.be.a('function'); expect(cache.oneGet).to.be.a('function'); expect(cache.offGet).to.be.a('function'); expect(cache.onSet).to.be.a('function'); expect(cache.oneSet).to.be.a('function'); expect(cache.offSet).to.be.a('function'); expect(cache.onRemove).to.be.a('function'); expect(cache.oneRemove).to.be.a('function'); expect(cache.offRemove).to.be.a('function'); expect(cache.onExpire).to.be.a('function'); expect(cache.oneExpire).to.be.a('function'); expect(cache.offExpire).to.be.a('function'); expect(cache.onMerge).to.be.a('function'); expect(cache.oneMerge).to.be.a('function'); expect(cache.offMerge).to.be.a('function'); expect(cache.onConcat).to.be.a('function'); expect(cache.oneConcat).to.be.a('function'); expect(cache.offConcat).to.be.a('function'); expect(cache.onReset).to.be.a('function'); expect(cache.oneReset).to.be.a('function'); expect(cache.offReset).to.be.a('function'); }); it('should set a key and return it', function () { const returnValue = cache.set('test', test); expect(returnValue).to.be.an('object'); }); it('should get a key', function () { const value = cache.get('test'); expect(value).to.be.an('object'); expect(value.a.b).to.equal(test.a.b); }); it('should get the whole cache when passed true as key', function () { assert.deepEqual(cache.get(true).test, test); }); it('should delete a key', function () { cache.set('remove', test); assert.deepEqual(cache.get('remove'), test); expect(cache.remove('remove')).to.equal(true); expect(cache.get('remove')).to.equal(undefined); }); it('should concat an array key', function () { cache.set('concat', [1,2,3]); expect(cache.get('concat')).to.not.include(4,5); cache.concat('concat', [4,5]); expect(cache.get('concat')).to.include(1,2,3,4,5); }); it('should merge an object key', function () { cache.set('merge', { merge: true }); expect(cache.get('merge')).to.not.have.any.keys('merged'); cache.merge('merge', { merged: true}); expect(cache.get('merge')).to.have.any.keys('merge','merged'); expect(cache.get('merge')).to.deep.equal({ merge: true, merged: true }); }); it('should expire a set key', function (done) { expect(cache.get('merge')).to.deep.equal({ merge: true, merged: true }); cache.expire('merge', 1); expect(cache.get('merge')).to.not.equal(undefined); setTimeout(() => { expect(cache.get('merge')).to.equal(undefined); done(); }, 5); }); it('should set a key and expire if time is set', function (done) { cache.set('set-and-expire', true, 1); expect(cache.get('set-and-expire')).to.equal(true); setTimeout(() => { expect(cache.get('set-and-expire')).to.equal(undefined); done(); }, 5); }); it('should reset cache', function () { expect(cache.size).to.equal(2) cache.reset(); expect(cache.size).to.equal(0) }); it('should return all cache keys', function () { cache.set('1', 1); cache.set('2', 2); cache.set('3', 3); expect(cache.keys).to.include('1', '2', '3'); }); it('should check to see if cache has a key', function () { expect(cache.has('1')).to.equal(true); expect(cache.has('4')).to.equal(false); }); it('should iterate through cache', function () { const keys = []; const values = [] cache.each((val, key) => { values.push(val); keys.push(key); }); expect(values).to.include(1,2,3); expect(keys).to.include('1','2','3'); }); it('should return cache size', function () { expect(cache.size).to.equal(3); }); it('should bind to events', function (done) { // Assert events const eventsTested = { get: false, set: false, merge: false, concat: false, remove: false, expire: false, reset: false }; expect(cache.events).to.equal(false); cache.events = true; expect(cache.events).to.equal(true); // Bind events to fire 1 time. All events should set true. cache.oneGet(() => { eventsTested.get = true; }); cache.oneSet(() => { eventsTested.set = true; }); cache.oneRemove(() => { eventsTested.remove = true; }); cache.oneExpire(() => { eventsTested.expire = true; }); cache.oneMerge(() => { eventsTested.merge = true; }); cache.oneConcat(() => { eventsTested.concat = true; }); cache.oneReset(() => { eventsTested.reset = true; }); cache.set('merge', {}); cache.set('concat', []); cache.set('remove', true); cache.get('merge'); cache.merge('merge', {}); cache.concat('concat', []); cache.expire('remove', 0); cache.remove('remove'); cache.reset(); setTimeout(() => { expect(Object.values(eventsTested)).to.not.include(false); done(); }, 10); }); it('should cache passed object', function () { const c = { test: true, taste: 'good', tats: 'lots', tits: 'blitz' } cache = new MemoryCache(c); expect(cache.keys).to.include('test', 'taste', 'tats', 'tits'); expect(cache.get(true)).to.deep.equal(c); }); });
damusix/memory-cache
test/index.js
JavaScript
mit
9,186
var URL = require('url'); var Pagination = function(request, model){ this.request = request; this.model = model; this.paginate = function(query, limit, sort, selected, onDataReception){ var url = URL.parse(this.request.url).pathname; var page = this.request.param('page'); page = page === undefined ? 0 : page; this.model.find(query).sort(sort).skip(page*limit).limit( (limit + 1) ).select( selected ).exec(function(err, members){ //Fetched more than the limit members.splice(limit, 1); var paginatedMembers = { data : members }; if(members.length >= limit ){ nextPage = parseInt(page) + 1; paginatedMembers["next"] = url + "?page=" + nextPage; } if (page >= 1) { prevPage = parseInt(page) - 1; paginatedMembers["prev"] = url + "?page=" + prevPage; }; onDataReception(paginatedMembers); }); }; } module.exports = function(request, model){ return new Pagination(request, model); }
mz52arsi/NODEJS-Express-bootstrap
app/models/pagination/paginate.js
JavaScript
mit
965
define( [ 'solarfield/lightship-js/src/Solarfield/Lightship/Environment', 'solarfield/ok-kit-js/src/Solarfield/Ok/ObjectUtils' ], function (LightshipEnvironment, ObjectUtils) { "use strict"; var Environment = ObjectUtils.extend(LightshipEnvironment, { }); return Environment; } );
solarfield/lightship-bin-php
src/Lightship/Bin/lightship/stub/www/__/App/Environment.js
JavaScript
mit
305
'use strict'; exports.BattleScripts = { inherit: 'gen5', gen: 4, init: function () { for (let i in this.data.Pokedex) { delete this.data.Pokedex[i].abilities['H']; } }, modifyDamage: function (baseDamage, pokemon, target, move, suppressMessages) { // DPP divides modifiers into several mathematically important stages // The modifiers run earlier than other generations are called with ModifyDamagePhase1 and ModifyDamagePhase2 if (!move.type) move.type = '???'; let type = move.type; // Burn if (pokemon.status === 'brn' && baseDamage && move.category === 'Physical' && !pokemon.hasAbility('guts')) { baseDamage = this.modify(baseDamage, 0.5); } // Other modifiers (Reflect/Light Screen/etc) baseDamage = this.runEvent('ModifyDamagePhase1', pokemon, target, move, baseDamage); // Double battle multi-hit if (move.spreadHit) { let spreadModifier = move.spreadModifier || 0.75; this.debug('Spread modifier: ' + spreadModifier); baseDamage = this.modify(baseDamage, spreadModifier); } // Weather baseDamage = this.runEvent('WeatherModifyDamage', pokemon, target, move, baseDamage); if (this.gen === 3 && move.category === 'Physical' && !Math.floor(baseDamage)) { baseDamage = 1; } baseDamage += 2; if (move.crit) { baseDamage = this.modify(baseDamage, move.critModifier || 2); } // Mod 2 (Damage is floored after all multipliers are in) baseDamage = Math.floor(this.runEvent('ModifyDamagePhase2', pokemon, target, move, baseDamage)); // this is not a modifier baseDamage = this.randomizer(baseDamage); // STAB if (move.hasSTAB || type !== '???' && pokemon.hasType(type)) { // The "???" type never gets STAB // Not even if you Roost in Gen 4 and somehow manage to use // Struggle in the same turn. // (On second thought, it might be easier to get a Missingno.) baseDamage = this.modify(baseDamage, move.stab || 1.5); } // types move.typeMod = target.runEffectiveness(move); move.typeMod = this.clampIntRange(move.typeMod, -6, 6); if (move.typeMod > 0) { if (!suppressMessages) this.add('-supereffective', target); for (let i = 0; i < move.typeMod; i++) { baseDamage *= 2; } } if (move.typeMod < 0) { if (!suppressMessages) this.add('-resisted', target); for (let i = 0; i > move.typeMod; i--) { baseDamage = Math.floor(baseDamage / 2); } } if (move.crit && !suppressMessages) this.add('-crit', target); // Final modifier. baseDamage = this.runEvent('ModifyDamage', pokemon, target, move, baseDamage); if (!Math.floor(baseDamage)) { return 1; } return Math.floor(baseDamage); }, calcRecoilDamage: function (damageDealt, move) { return this.clampIntRange(Math.floor(damageDealt * move.recoil[0] / move.recoil[1]), 1); }, randomSet: function (template, slot, teamDetails) { if (slot === undefined) slot = 1; let baseTemplate = (template = this.getTemplate(template)); let species = template.species; if (!template.exists || (!template.randomBattleMoves && !template.learnset)) { template = this.getTemplate('unown'); let err = new Error('Template incompatible with random battles: ' + species); require('../../crashlogger')(err, 'The gen 4 randbat set generator'); } if (template.battleOnly) species = template.baseSpecies; let movePool = (template.randomBattleMoves ? template.randomBattleMoves.slice() : Object.keys(template.learnset)); let moves = []; let ability = ''; let item = ''; let evs = { hp: 85, atk: 85, def: 85, spa: 85, spd: 85, spe: 85, }; let ivs = { hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31, }; let hasType = {}; hasType[template.types[0]] = true; if (template.types[1]) { hasType[template.types[1]] = true; } let hasAbility = {}; hasAbility[template.abilities[0]] = true; if (template.abilities[1]) { hasAbility[template.abilities[1]] = true; } let availableHP = 0; for (let i = 0, len = movePool.length; i < len; i++) { if (movePool[i].substr(0, 11) === 'hiddenpower') availableHP++; } // These moves can be used even if we aren't setting up to use them: let SetupException = { closecombat:1, extremespeed:1, suckerpunch:1, superpower:1, dracometeor:1, leafstorm:1, overheat:1, }; let counterAbilities = { 'Adaptability':1, 'Hustle':1, 'Iron Fist':1, 'Skill Link':1, }; let hasMove, counter; do { // Keep track of all moves we have: hasMove = {}; for (let k = 0; k < moves.length; k++) { if (moves[k].substr(0, 11) === 'hiddenpower') { hasMove['hiddenpower'] = true; } else { hasMove[moves[k]] = true; } } // Choose next 4 moves from learnset/viable moves and add them to moves list: while (moves.length < 4 && movePool.length) { let moveid = this.sampleNoReplace(movePool); if (moveid.substr(0, 11) === 'hiddenpower') { availableHP--; if (hasMove['hiddenpower']) continue; hasMove['hiddenpower'] = true; } else { hasMove[moveid] = true; } moves.push(moveid); } counter = this.queryMoves(moves, hasType, hasAbility, movePool); // Iterate through the moves again, this time to cull them: for (let k = 0; k < moves.length; k++) { let move = this.getMove(moves[k]); let moveid = move.id; let rejected = false; let isSetup = false; switch (moveid) { // Not very useful without their supporting moves case 'batonpass': if (!counter.setupType && !counter['speedsetup'] && !hasMove['substitute']) rejected = true; break; case 'eruption': case 'waterspout': if (counter.Physical + counter.Special < 4) rejected = true; break; case 'focuspunch': if (!hasMove['substitute'] || counter.damagingMoves.length < 2) rejected = true; if (hasMove['hammerarm']) rejected = true; break; case 'rest': { if (movePool.includes('sleeptalk')) rejected = true; break; } case 'sleeptalk': if (!hasMove['rest']) rejected = true; if (movePool.length > 1) { let rest = movePool.indexOf('rest'); if (rest >= 0) this.fastPop(movePool, rest); } break; // Set up once and only if we have the moves for it case 'bellydrum': case 'bulkup': case 'curse': case 'dragondance': case 'swordsdance': if (counter.setupType !== 'Physical' || counter['physicalsetup'] > 1) { if (!hasMove['growth'] || hasMove['sunnyday']) rejected = true; } if (counter.Physical + counter['physicalpool'] < 2 && !hasMove['batonpass'] && (!hasMove['rest'] || !hasMove['sleeptalk'])) rejected = true; isSetup = true; break; case 'calmmind': case 'growth': case 'nastyplot': case 'tailglow': if (counter.setupType !== 'Special' || counter['specialsetup'] > 1) rejected = true; if (counter.Special + counter['specialpool'] < 2 && !hasMove['batonpass'] && (!hasMove['rest'] || !hasMove['sleeptalk'])) rejected = true; isSetup = true; break; case 'agility': case 'rockpolish': if (counter.damagingMoves.length < 2 && !hasMove['batonpass']) rejected = true; if (hasMove['rest'] && hasMove['sleeptalk']) rejected = true; if (!counter.setupType) isSetup = true; break; // Bad after setup case 'explosion': case 'selfdestruct': if (counter.stab < 2 || counter.setupType || !!counter['recovery'] || hasMove['rest']) rejected = true; break; case 'foresight': case 'protect': case 'roar': if (counter.setupType && !hasAbility['Speed Boost']) rejected = true; break; case 'rapidspin': if (teamDetails.rapidSpin) rejected = true; break; case 'stealthrock': if (counter.setupType || !!counter['speedsetup'] || hasMove['rest'] || teamDetails.stealthRock) rejected = true; break; case 'switcheroo': case 'trick': if (counter.Physical + counter.Special < 3 || counter.setupType) rejected = true; if (hasMove['lightscreen'] || hasMove['reflect'] || hasMove['suckerpunch'] || hasMove['trickroom']) rejected = true; break; case 'toxic': case 'toxicspikes': if (counter.setupType || teamDetails.toxicSpikes) rejected = true; break; case 'trickroom': if (counter.setupType || !!counter['speedsetup'] || counter.damagingMoves.length < 2) rejected = true; if (hasMove['lightscreen'] || hasMove['reflect'] || hasMove['rest'] && hasMove['sleeptalk']) rejected = true; break; case 'uturn': if (counter.setupType || !!counter['speedsetup'] || hasMove['batonpass'] || hasMove['substitute']) rejected = true; if (hasType['Bug'] && counter.stab < 2 && counter.damagingMoves.length > 2) rejected = true; break; // Bit redundant to have both // Attacks: case 'bodyslam': case 'doubleedge': if (hasMove['return']) rejected = true; break; case 'judgment': if (counter.setupType !== 'Special' && counter.stab > 1) rejected = true; break; case 'quickattack': if (hasMove['thunderwave']) rejected = true; break; case 'firepunch': case 'flamethrower': if (hasMove['fireblast']) rejected = true; break; case 'hydropump': if (hasMove['surf']) rejected = true; break; case 'waterfall': if (hasMove['aquatail']) rejected = true; break; case 'discharge': if (hasMove['thunderbolt']) rejected = true; break; case 'energyball': if (hasMove['grassknot']) rejected = true; break; case 'leafstorm': if (counter.setupType || hasMove['batonpass'] || hasMove['powerwhip']) rejected = true; break; case 'solarbeam': if (counter.setupType === 'Physical' || !hasMove['sunnyday'] && !movePool.includes('sunnyday')) rejected = true; break; case 'icepunch': if (!counter.setupType && hasMove['icebeam']) rejected = true; break; case 'brickbreak': if (hasMove['substitute'] && hasMove['focuspunch']) rejected = true; break; case 'focusblast': if (hasMove['crosschop']) rejected = true; break; case 'seismictoss': if (hasMove['nightshade'] || counter.Physical + counter.Special >= 1) rejected = true; break; case 'gunkshot': if (hasMove['poisonjab']) rejected = true; break; case 'zenheadbutt': if (hasMove['psychocut']) rejected = true; break; case 'rockslide': if (hasMove['stoneedge']) rejected = true; break; case 'shadowclaw': if (hasMove['shadowforce']) rejected = true; break; case 'dragonclaw': if (hasMove['outrage']) rejected = true; break; case 'dracometeor': if (hasMove['calmmind']) rejected = true; break; case 'crunch': case 'nightslash': if (hasMove['suckerpunch']) rejected = true; break; case 'pursuit': if (counter.setupType || hasMove['payback']) rejected = true; break; case 'gyroball': case 'flashcannon': if (hasMove['ironhead'] && counter.setupType !== 'Special') rejected = true; break; // Status: case 'leechseed': case 'painsplit': case 'wish': if (hasMove['moonlight'] || hasMove['rest'] || hasMove['rockpolish'] || hasMove['synthesis']) rejected = true; break; case 'substitute': if (hasMove['pursuit'] || hasMove['rest'] || hasMove['taunt']) rejected = true; break; case 'thunderwave': if (hasMove['toxic'] || hasMove['trickroom']) rejected = true; break; } // Increased/decreased priority moves are unneeded with moves that boost only speed if (move.priority !== 0 && !!counter['speedsetup']) { rejected = true; } // This move doesn't satisfy our setup requirements: if ((move.category === 'Physical' && counter.setupType === 'Special') || (move.category === 'Special' && counter.setupType === 'Physical')) { // Reject STABs last in case the setup type changes later on if (!SetupException[moveid] && (!hasType[move.type] || counter.stab > 1 || counter[move.category] < 2)) rejected = true; } if (counter.setupType && !isSetup && move.category !== counter.setupType && counter[counter.setupType] < 2 && !hasMove['batonpass'] && moveid !== 'rest' && moveid !== 'sleeptalk') { // Mono-attacking with setup and RestTalk is allowed // Reject Status moves only if there is nothing else to reject if (move.category !== 'Status' || counter[counter.setupType] + counter.Status > 3 && counter['physicalsetup'] + counter['specialsetup'] < 2) rejected = true; } if (counter.setupType === 'Special' && moveid === 'hiddenpower' && template.types.length > 1 && counter['Special'] <= 2 && !hasType[move.type] && !counter['Physical'] && counter['specialpool']) { // Hidden Power isn't good enough rejected = true; } // Pokemon should have moves that benefit their Ability/Type/Weather, as well as moves required by its forme if ((hasType['Electric'] && !counter['Electric']) || (hasType['Fighting'] && !counter['Fighting'] && (counter.setupType || !counter['Status'])) || (hasType['Fire'] && !counter['Fire']) || (hasType['Ground'] && !counter['Ground'] && (counter.setupType || counter['speedsetup'] || hasMove['raindance'] || !counter['Status'])) || (hasType['Ice'] && !counter['Ice']) || (hasType['Psychic'] && !!counter['Psychic'] && !hasType['Flying'] && template.types.length > 1 && counter.stab < 2) || (hasType['Water'] && !counter['Water'] && (!hasType['Ice'] || !counter['Ice'])) || ((hasAbility['Adaptability'] && !counter.setupType && template.types.length > 1 && (!counter[template.types[0]] || !counter[template.types[1]])) || (hasAbility['Guts'] && hasType['Normal'] && movePool.includes('facade')) || (hasAbility['Slow Start'] && movePool.includes('substitute')) || (counter['defensesetup'] && !counter.recovery && !hasMove['rest']) || (template.requiredMove && movePool.includes(toId(template.requiredMove)))) && (counter['physicalsetup'] + counter['specialsetup'] < 2 && (!counter.setupType || (move.category !== counter.setupType && move.category !== 'Status') || counter[counter.setupType] + counter.Status > 3))) { // Reject Status or non-STAB if (!isSetup && !move.weather && moveid !== 'judgment' && moveid !== 'rest' && moveid !== 'sleeptalk') { if (move.category === 'Status' || !hasType[move.type] || (move.basePower && move.basePower < 40 && !move.multihit)) rejected = true; } } // Sleep Talk shouldn't be selected without Rest if (moveid === 'rest' && rejected) { let sleeptalk = movePool.indexOf('sleeptalk'); if (sleeptalk >= 0) { if (movePool.length < 2) { rejected = false; } else { this.fastPop(movePool, sleeptalk); } } } // Remove rejected moves from the move list if (rejected && (movePool.length - availableHP || availableHP && (moveid === 'hiddenpower' || !hasMove['hiddenpower']))) { moves.splice(k, 1); break; } } if (moves.length === 4 && !counter.stab && !hasMove['metalburst'] && (counter['physicalpool'] || counter['specialpool'])) { // Move post-processing: if (counter.damagingMoves.length === 0) { // A set shouldn't have no attacking moves moves.splice(this.random(moves.length), 1); } else if (counter.damagingMoves.length === 1) { // In most cases, a set shouldn't have no STAB let damagingid = counter.damagingMoves[0].id; if (movePool.length - availableHP || availableHP && (damagingid === 'hiddenpower' || !hasMove['hiddenpower'])) { let replace = false; if (!counter.damagingMoves[0].damage && template.species !== 'Porygon2') { replace = true; } if (replace) moves.splice(counter.damagingMoveIndex[damagingid], 1); } } else if (!counter.damagingMoves[0].damage && !counter.damagingMoves[1].damage && template.species !== 'Porygon2') { // If you have three or more attacks, and none of them are STAB, reject one of them at random. let rejectableMoves = []; let baseDiff = movePool.length - availableHP; for (let l = 0; l < counter.damagingMoves.length; l++) { if (baseDiff || availableHP && (!hasMove['hiddenpower'] || counter.damagingMoves[l].id === 'hiddenpower')) { rejectableMoves.push(counter.damagingMoveIndex[counter.damagingMoves[l].id]); } } if (rejectableMoves.length) { moves.splice(rejectableMoves[this.random(rejectableMoves.length)], 1); } } } } while (moves.length < 4 && movePool.length); // If Hidden Power has been removed, reset the IVs if (!hasMove['hiddenpower']) { ivs = {hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31}; } let abilities = Object.values(baseTemplate.abilities); abilities.sort((a, b) => this.getAbility(b).rating - this.getAbility(a).rating); let ability0 = this.getAbility(abilities[0]); let ability1 = this.getAbility(abilities[1]); ability = ability0.name; if (abilities[1]) { if (ability0.rating <= ability1.rating) { if (this.random(2)) ability = ability1.name; } else if (ability0.rating - 0.6 <= ability1.rating) { if (!this.random(3)) ability = ability1.name; } let rejectAbility = false; if (ability in counterAbilities) { // Adaptability, Hustle, Iron Fist, Skill Link rejectAbility = !counter[toId(ability)]; } else if (ability === 'Blaze') { rejectAbility = !counter['Fire']; } else if (ability === 'Chlorophyll') { rejectAbility = !hasMove['sunnyday']; } else if (ability === 'Compound Eyes' || ability === 'No Guard') { rejectAbility = !counter['inaccurate']; } else if (ability === 'Gluttony') { rejectAbility = !hasMove['bellydrum']; } else if (ability === 'Lightning Rod') { rejectAbility = template.types.includes('Ground'); } else if (ability === 'Limber') { rejectAbility = template.types.includes('Electric'); } else if (ability === 'Overgrow') { rejectAbility = !counter['Grass']; } else if (ability === 'Poison Heal') { rejectAbility = abilities.includes('Technician') && !!counter['technician']; } else if (ability === 'Reckless' || ability === 'Rock Head') { rejectAbility = !counter['recoil']; } else if (ability === 'Sand Veil') { rejectAbility = !teamDetails['sand']; } else if (ability === 'Serene Grace') { rejectAbility = !counter['serenegrace'] || template.id === 'chansey' || template.id === 'blissey'; } else if (ability === 'Simple') { rejectAbility = !counter.setupType && !hasMove['cosmicpower'] && !hasMove['flamecharge']; } else if (ability === 'Snow Cloak') { rejectAbility = !teamDetails['hail']; } else if (ability === 'Solar Power') { rejectAbility = !counter['Special']; } else if (ability === 'Sturdy') { rejectAbility = !!counter['recoil'] && !counter['recovery']; } else if (ability === 'Swift Swim') { rejectAbility = !hasMove['raindance'] && !teamDetails['rain']; } else if (ability === 'Swarm') { rejectAbility = !counter['Bug']; } else if (ability === 'Synchronize') { rejectAbility = counter.Status < 2; } else if (ability === 'Tinted Lens') { rejectAbility = counter['damage'] >= counter.damagingMoves.length; } else if (ability === 'Torrent') { rejectAbility = !counter['Water']; } if (rejectAbility) { if (ability === ability1.name) { // or not ability = ability0.name; } else if (ability1.rating > 1) { // only switch if the alternative doesn't suck ability = ability1.name; } } if (abilities.includes('Swift Swim') && hasMove['raindance']) { ability = 'Swift Swim'; } } item = 'Leftovers'; if (template.requiredItems) { item = template.requiredItems[this.random(template.requiredItems.length)]; // First, the extra high-priority items } else if (template.species === 'Deoxys-Attack') { item = (slot === 0 && hasMove['stealthrock']) ? 'Focus Sash' : 'Life Orb'; } else if (template.species === 'Farfetch\'d') { item = 'Stick'; } else if (template.species === 'Marowak') { item = 'Thick Club'; } else if (template.species === 'Pikachu') { item = 'Light Ball'; } else if (template.species === 'Shedinja' || template.species === 'Smeargle') { item = 'Focus Sash'; } else if (template.species === 'Unown') { item = 'Choice Specs'; } else if (template.species === 'Wobbuffet') { item = hasMove['destinybond'] ? 'Custap Berry' : ['Leftovers', 'Sitrus Berry'][this.random(2)]; } else if (hasMove['switcheroo'] || hasMove['trick']) { let randomNum = this.random(3); if (counter.Physical >= 3 && (template.baseStats.spe < 60 || template.baseStats.spe > 108 || randomNum)) { item = 'Choice Band'; } else if (counter.Special >= 3 && (template.baseStats.spe < 60 || template.baseStats.spe > 108 || randomNum)) { item = 'Choice Specs'; } else { item = 'Choice Scarf'; } } else if (hasMove['bellydrum']) { item = 'Sitrus Berry'; } else if (ability === 'Magic Guard') { item = 'Life Orb'; } else if (ability === 'Poison Heal' || ability === 'Toxic Boost') { item = 'Toxic Orb'; } else if (hasMove['rest'] && !hasMove['sleeptalk'] && ability !== 'Natural Cure' && ability !== 'Shed Skin') { item = (hasMove['raindance'] && ability === 'Hydration') ? 'Damp Rock' : 'Chesto Berry'; } else if (hasMove['raindance']) { item = (ability === 'Swift Swim' && counter.Status < 2) ? 'Life Orb' : 'Damp Rock'; } else if (hasMove['sunnyday']) { item = (ability === 'Chlorophyll' && counter.Status < 2) ? 'Life Orb' : 'Heat Rock'; } else if (hasMove['lightscreen'] && hasMove['reflect']) { item = 'Light Clay'; } else if (ability === 'Guts') { item = 'Flame Orb'; } else if (ability === 'Quick Feet' && hasMove['facade']) { item = 'Toxic Orb'; } else if (ability === 'Unburden') { item = 'Sitrus Berry'; // Medium priority } else if (counter.Physical >= 4 && !hasMove['bodyslam'] && !hasMove['fakeout'] && !hasMove['rapidspin'] && !hasMove['suckerpunch']) { item = template.baseStats.spe >= 60 && template.baseStats.spe <= 108 && !counter['priority'] && this.random(3) ? 'Choice Scarf' : 'Choice Band'; } else if ((counter.Special >= 4 || (counter.Special >= 3 && (hasMove['batonpass'] || hasMove['uturn']))) && !hasMove['chargebeam']) { item = template.baseStats.spe >= 60 && template.baseStats.spe <= 108 && ability !== 'Speed Boost' && !counter['priority'] && this.random(3) ? 'Choice Scarf' : 'Choice Specs'; } else if (hasMove['endeavor'] || hasMove['flail'] || hasMove['reversal']) { item = 'Focus Sash'; } else if (hasMove['outrage'] && counter.setupType) { item = 'Lum Berry'; } else if (ability === 'Slow Start' || hasMove['curse'] || hasMove['detect'] || hasMove['protect'] || hasMove['sleeptalk']) { item = 'Leftovers'; } else if (hasMove['substitute']) { item = !counter['drain'] || counter.damagingMoves.length < 2 ? 'Leftovers' : 'Life Orb'; } else if (hasMove['lightscreen'] || hasMove['reflect']) { item = 'Light Clay'; } else if (counter.damagingMoves.length >= 4) { item = (!!counter['Normal'] || hasMove['chargebeam'] || (hasMove['suckerpunch'] && !hasType['Dark'])) ? 'Life Orb' : 'Expert Belt'; } else if (counter.damagingMoves.length >= 3 && !hasMove['superfang']) { item = (template.baseStats.hp + template.baseStats.def + template.baseStats.spd < 285 || !!counter['speedsetup'] || hasMove['trickroom']) ? 'Life Orb' : 'Leftovers'; } else if (template.species === 'Palkia' && (hasMove['dracometeor'] || hasMove['spacialrend']) && hasMove['hydropump']) { item = 'Lustrous Orb'; } else if (slot === 0 && !counter['recoil'] && !counter['recovery'] && template.baseStats.hp + template.baseStats.def + template.baseStats.spd < 285) { item = 'Focus Sash'; // This is the "REALLY can't think of a good item" cutoff } else if (hasType['Poison']) { item = 'Black Sludge'; } else if (this.getEffectiveness('Rock', template) >= 1 || hasMove['roar']) { item = 'Leftovers'; } else if (counter.Status <= 1 && !hasMove['rapidspin']) { item = 'Life Orb'; } else { item = 'Leftovers'; } // For Trick / Switcheroo if (item === 'Leftovers' && hasType['Poison']) { item = 'Black Sludge'; } let levelScale = { LC: 87, NFE: 85, NU: 83, BL2: 81, UU: 79, BL: 77, OU: 75, Uber: 71, }; let tier = template.tier; let level = levelScale[tier] || 75; // Prepare optimal HP let hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10); if (hasMove['substitute'] && item === 'Sitrus Berry') { // Two Substitutes should activate Sitrus Berry while (hp % 4 > 0) { evs.hp -= 4; hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10); } } else if (hasMove['bellydrum'] && item === 'Sitrus Berry') { // Belly Drum should activate Sitrus Berry if (hp % 2 > 0) evs.hp -= 4; } else if (hasMove['substitute'] && hasMove['reversal']) { // Reversal users should be able to use four Substitutes if (hp % 4 === 0) evs.hp -= 4; } else { // Maximize number of Stealth Rock switch-ins let srWeakness = this.getEffectiveness('Rock', template); if (srWeakness > 0 && hp % (4 / srWeakness) === 0) evs.hp -= 4; } // Minimize confusion damage if (!counter['Physical'] && !hasMove['transform']) { evs.atk = 0; ivs.atk = hasMove['hiddenpower'] ? ivs.atk - 28 : 0; } if (hasMove['gyroball'] || hasMove['trickroom']) { evs.spe = 0; ivs.spe = hasMove['hiddenpower'] ? ivs.spe - 28 : 0; } return { name: template.baseSpecies, species: species, moves: moves, ability: ability, evs: evs, ivs: ivs, item: item, level: level, shiny: !this.random(1024), }; }, randomTeam: function (side) { let pokemon = []; let allowedNFE = {'Porygon2':1, 'Scyther':1}; let pokemonPool = []; for (let id in this.data.FormatsData) { let template = this.getTemplate(id); if (template.gen > 4 || template.isNonstandard || !template.randomBattleMoves || template.nfe && !allowedNFE[template.species]) continue; pokemonPool.push(id); } let typeCount = {}; let typeComboCount = {}; let baseFormes = {}; let uberCount = 0; let nuCount = 0; let teamDetails = {}; while (pokemonPool.length && pokemon.length < 6) { let template = this.getTemplate(this.sampleNoReplace(pokemonPool)); if (!template.exists) continue; // Limit to one of each species (Species Clause) if (baseFormes[template.baseSpecies]) continue; let tier = template.tier; switch (tier) { case 'Uber': // Ubers are limited to 2 but have a 20% chance of being added anyway. if (uberCount > 1 && this.random(5) >= 1) continue; break; case 'NU': // NUs are limited to 2 but have a 20% chance of being added anyway. if (nuCount > 1 && this.random(5) >= 1) continue; } // Adjust rate for species with multiple formes switch (template.baseSpecies) { case 'Arceus': if (this.random(17) >= 1) continue; break; case 'Castform': if (this.random(4) >= 1) continue; break; case 'Cherrim': if (this.random(2) >= 1) continue; break; case 'Rotom': if (this.random(6) >= 1) continue; break; } let types = template.types; // Limit 2 of any type let skip = false; for (let t = 0; t < types.length; t++) { if (typeCount[types[t]] > 1 && this.random(5) >= 1) { skip = true; break; } } if (skip) continue; let set = this.randomSet(template, pokemon.length, teamDetails); // Limit 1 of any type combination let typeCombo = types.slice().sort().join(); if (set.ability === 'Drought' || set.ability === 'Drizzle' || set.ability === 'Sand Stream') { // Drought, Drizzle and Sand Stream don't count towards the type combo limit typeCombo = set.ability; if (typeCombo in typeComboCount) continue; } else { if (typeComboCount[typeCombo] >= 1) continue; } // Okay, the set passes, add it to our team pokemon.push(set); // Now that our Pokemon has passed all checks, we can increment our counters baseFormes[template.baseSpecies] = 1; // Increment type counters for (let t = 0; t < types.length; t++) { if (types[t] in typeCount) { typeCount[types[t]]++; } else { typeCount[types[t]] = 1; } } if (typeCombo in typeComboCount) { typeComboCount[typeCombo]++; } else { typeComboCount[typeCombo] = 1; } // Increment Uber/NU counters if (tier === 'Uber') { uberCount++; } else if (tier === 'NU') { nuCount++; } // Team has if (set.ability === 'Snow Warning') teamDetails['hail'] = 1; if (set.ability === 'Drizzle' || set.moves.includes('raindance')) teamDetails['rain'] = 1; if (set.ability === 'Sand Stream') teamDetails['sand'] = 1; if (set.moves.includes('stealthrock')) teamDetails['stealthRock'] = 1; if (set.moves.includes('toxicspikes')) teamDetails['toxicSpikes'] = 1; if (set.moves.includes('rapidspin')) teamDetails['rapidSpin'] = 1; } return pokemon; }, };
profshroomish/gamerhole
mods/gen4/scripts.js
JavaScript
mit
29,165
$(function(){ var InvitationForm = Backbone.View.extend({ el: $('fieldset[data-control=invitation]'), events: { }, initialize: function(){ if(!this.$el.length) return null; this.listenTo(Backbone, 'showInvitationForm', this.showInvitationForm); this.listenTo(Backbone, 'hideInvitationForm', this.hideInvitationForm); }, showInvitationForm: function(){ this.$el.removeClass('hidden'); }, hideInvitationForm: function(){ this.$el.addClass('hidden'); } }); var invitationForm = new InvitationForm(); });
Josebaseba/shark-trap
assets/js/app/views/invitationForm.js
JavaScript
mit
583
import React, { PropTypes } from 'react'; class AutoFocus extends React.Component { constructor( props ) { super( props ); this.receiveRef = this.receiveRef.bind( this ); } componentDidMount() { if ( this.ref ) { this.ref.focus(); } } receiveRef( node ) { this.ref = node; } render() { return this.props.children( this.receiveRef ); } } AutoFocus.propTypes = { children: PropTypes.func.isRequired, }; export default AutoFocus;
Pairboard/Pairboard
client/src/components/AutoFocus.js
JavaScript
mit
482
var DObject_8h = [ [ "DObject", "classHelix_1_1Logic_1_1dev_1_1DObject.html", "classHelix_1_1Logic_1_1dev_1_1DObject" ], [ "DObject_svect", "DObject_8h.html#a56460b28b8ab9b64a1aecf912b2f14ac", null ] ];
smc314/helix
html/devdoc/html/DObject_8h.js
JavaScript
mit
210
/* * Sidebar toggle function */ (function(document) { var toggle = document.querySelector('.sidebar-toggle'); var sidebar = document.querySelector('#sidebar'); var checkbox = document.querySelector('#sidebar-checkbox'); document.addEventListener('click', function(e) { var target = e.target; if(!checkbox.checked || sidebar.contains(target) || (target === checkbox || target === toggle)) return; checkbox.checked = false; }, false); })(document); /*global jQuery */ /*jshint browser:true */ /*! * FitVids 1.1 * * Copyright 2013, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com * Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/ * Released under the WTFPL license - http://sam.zoy.org/wtfpl/ * */ ;(function( $ ){ 'use strict'; $.fn.fitVids = function( options ) { var settings = { customSelector: null, ignore: null }; if(!document.getElementById('fit-vids-style')) { // appendStyles: https://github.com/toddmotto/fluidvids/blob/master/dist/fluidvids.js var head = document.head || document.getElementsByTagName('head')[0]; var css = '.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}'; var div = document.createElement("div"); div.innerHTML = '<p>x</p><style id="fit-vids-style">' + css + '</style>'; head.appendChild(div.childNodes[1]); } if ( options ) { $.extend( settings, options ); } return this.each(function(){ var selectors = [ 'iframe[src*="player.vimeo.com"]', 'iframe[src*="youtube.com"]', 'iframe[src*="youtube-nocookie.com"]', 'iframe[src*="kickstarter.com"][src*="video.html"]', 'object', 'embed' ]; if (settings.customSelector) { selectors.push(settings.customSelector); } var ignoreList = '.fitvidsignore'; if(settings.ignore) { ignoreList = ignoreList + ', ' + settings.ignore; } var $allVideos = $(this).find(selectors.join(',')); $allVideos = $allVideos.not('object object'); // SwfObj conflict patch $allVideos = $allVideos.not(ignoreList); // Disable FitVids on this video. $allVideos.each(function(){ var $this = $(this); if($this.parents(ignoreList).length > 0) { return; // Disable FitVids on this video. } if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; } if ((!$this.css('height') && !$this.css('width')) && (isNaN($this.attr('height')) || isNaN($this.attr('width')))) { $this.attr('height', 9); $this.attr('width', 16); } var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(), width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(), aspectRatio = height / width; if(!$this.attr('id')){ var videoID = 'fitvid' + Math.floor(Math.random()*999999); $this.attr('id', videoID); } $this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+'%'); $this.removeAttr('height').removeAttr('width'); }); }); }; // Works with either jQuery or Zepto })( window.jQuery || window.Zepto ); /* * Show disqus comments */ jQuery(document).ready(function() { jQuery(".post").fitVids(); // Load discus comment function initDisqusComments(){ if(config.disqus_shortname != '' && config.disqus_shortname != null && config.disqus_shortname != undefined) { var disqus_shortname = config.disqus_shortname; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); }else { alert("Please check Disqus short name configuration on your _config.yml"); } } initDisqusComments(); $(this).fadeOut(200); /*$('.load-view').click(function(){ initDisqusComments(); $(this).fadeOut(200); });*/ }); /* * Scroll to top button */ jQuery(document).ready(function($){ // browser window scroll (in pixels) after which the "back to top" link is shown var offset = 300, //browser window scroll (in pixels) after which the "back to top" link opacity is reduced offset_opacity = 1200, //duration of the top scrolling animation (in ms) scroll_top_duration = 700, //grab the "back to top" link $back_to_top = $('.wc-top'); //hide or show the "back to top" link $(window).scroll(function(){ ( $(this).scrollTop() > offset ) ? $back_to_top.addClass('wc-is-visible') : $back_to_top.removeClass('wc-is-visible wc-fade-out'); if( $(this).scrollTop() > offset_opacity ) { $back_to_top.addClass('wc-fade-out'); } }); //smooth scroll to top $back_to_top.on('click', function(event){ event.preventDefault(); $('body,html').animate({ scrollTop: 0 , }, scroll_top_duration ); }); });
levichen/levichen.github.io
assets/js/gaya.js
JavaScript
mit
5,582
import React from 'react'; import PropTypes from 'prop-types'; import { reduxForm } from 'redux-form'; import { connect } from 'react-redux'; import compose from 'recompose/compose'; import getDefaultValues from './getDefaultValues'; import FormField from './FormField'; import Toolbar from './Toolbar'; const noop = () => {}; export const SimpleForm = ({ children, handleSubmit, invalid, record, resource, basePath, submitOnEnter }) => { return ( <form onSubmit={ submitOnEnter ? handleSubmit : noop } className="simple-form"> <div style={{ padding: '0 1em 1em 1em' }}> {React.Children.map(children, input => input && ( <div key={input.props.source} className={`aor-input-${input.props.source}`} style={input.props.style}> <FormField input={input} resource={resource} record={record} basePath={basePath} /> </div> ))} </div> <Toolbar invalid={invalid} submitOnEnter={submitOnEnter} /> </form> ); }; SimpleForm.propTypes = { children: PropTypes.node, defaultValue: PropTypes.oneOfType([ PropTypes.object, PropTypes.func, ]), handleSubmit: PropTypes.func, invalid: PropTypes.bool, record: PropTypes.object, resource: PropTypes.string, basePath: PropTypes.string, validate: PropTypes.func, submitOnEnter: PropTypes.bool, }; SimpleForm.defaultProps = { submitOnEnter: true, }; const enhance = compose( connect((state, props) => ({ initialValues: getDefaultValues(state, props), })), reduxForm({ form: 'record-form', enableReinitialize: true, }), ); export default enhance(SimpleForm);
matteolc/admin-on-rest
src/mui/form/SimpleForm.js
JavaScript
mit
1,744
export function allDaysDisabledBefore (day, unit, { minDate, includeDates } = {}) { const dateBefore = day.clone().subtract(1, unit) return (minDate && dateBefore.isBefore(minDate, unit)) || (includeDates && includeDates.every(includeDate => dateBefore.isBefore(includeDate, unit))) || false }
drioemgaoin/react-responsive-form
lib/components/datepicker/utils.js
JavaScript
mit
306
var util = require('util'); var fs = require('fs'); var path = require('path'); var ltrim = require('underscore.string/ltrim'); exports.isCommand = function (input) { if (input.toLowerCase().substr(0, prefix.length) === prefix) return true; else return false; }; exports.isNumber = function (n) { return !isNaN(parseFloat(n)) && isFinite(n); }; exports.isURL = function (str) { var pattern = new RedExp( '^' + '(?:(?:https?|ftp)://)' + '(?:\\S+(?::\\S*)?@)?' + '(?:' + '(?!(?:10|127)(?:\\.\\d{1,3}){3})' + '(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})' + '(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})' + '(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])' + '(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}' + '(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))' + '|' + '(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)' + '(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' + '(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))' + '\\.?' + ')' + '(?::\\d{2,5})?' + '(?:[/?#]\\S*)?' + '$', 'i' ); if (!pattern.test(str)) return false; else return true; }; exports.getCommand = function (input) { return input.replace(prefix, '').split(' ')[0]; }; exports.getFolders = function (SourcePath) { return fs.readdirSync(SourcePath).filter(function (file) { return fs.statSync(path.join(SourcePath, file)).isDirectory(); }); }; exports.getMessage = function (input) { return input.replace(prefix, ''); }; exports.getParams = function (text) { return text.split(' ').slice(1); }; exports.normalizeChannel = function (channel) { return util.format('#%s', ltrim(channel.toLowerCase() , '#')); }; exports.numParams = function (text) { return text.split(' ').length - 1; }; exports.splitInput = function (splitAt, message, intSplit) { var data = message.split(splitAt)[1]; return data.slice(0, data.length - intSplit); };
MatthewSH/node-tbjs
Functions.js
JavaScript
mit
1,945
//window.twttr=(function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],t=window.twttr||{};if(d.getElementById(id))return;js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);t._e=[];t.ready=function(f){t._e.push(f);};return t;}(document,"script","twitter-wjs")); function textchange(e) { $('#twitter').attr({href: 'https://twitter.com/share?url=tw&text=' + encodeURIComponent($(this).val())}); // http://stackoverflow.com/a/2848483 length = $(this).val().length; $('#length').text(140-length); } jQuery(document).ready(function($) { $('#text').spellcheck({events: 'keyup', url: '/spellcheck.php'}); $('#text').change(textchange); $('#text').keyup(textchange); $( "#slider" ).slider({ value:1, min: 1, max: 5, step: 1, slide: function( event, ui ) { $( "#depth" ).val( ui.value ); //$('#text').trigger('keyup'); } }); });
adamobeng/chirp
static/tw.js
JavaScript
mit
915
function main() { var N = 10000; var lines = generateLines(N); //timeCanvas2D(lines, N); timeBatchDraw(lines, N); } function generateLines(N) { var lines = new Array(N); let canvas = document.getElementById("canvas"); let w = canvas.width; let h = canvas.height; // Create funky lines: for (i=0; i<N; i++) { lines[i] = { fromX: (1.3*i/N) * w, fromY: 0.5/(2*(i/N) + 1) * h, toX: (0.1*i-1)/(N - i) * w, toY: (0.3*N)/(5*(i*i)/N) * 0.5 * h }; } //console.log(lines); return lines; } function timeBatchDraw(lines, N) { let canvas = document.getElementById("canvas"); let params = { maxLines: N, clearColor: {r: 1, g: 1, b: 1, a: 1} }; let batchDrawer = new BatchDrawer(canvas, params); if (batchDrawer.error != null) { console.log(batchDrawer.error); return; } console.time("BatchDraw"); for (i=0; i<N; i++) { batchDrawer.addLine(lines[i].fromX, lines[i].fromY, lines[i].toX, lines[i].toY, 0.001, 1, 0.5, 0.1, 1); } batchDrawer.draw(false); console.timeEnd("BatchDraw"); } function timeCanvas2D(lines, N) { let canvas = document.getElementById("canvas"); let ctx = canvas.getContext("2d"); ctx.lineWidth = 0.01; ctx.strokeStyle = '#ffa500'; ctx.fillStyle="#FFFFFF"; console.time("Canvas2D"); ctx.clearRect(0, 0, canvas.width, canvas.height); for (i=0; i<N; i++) { ctx.beginPath(); ctx.moveTo(lines[i].fromX, lines[i].fromY); ctx.lineTo(lines[i].toX, lines[i].toY); ctx.stroke(); } console.timeEnd("Canvas2D"); }
lragnarsson/WebGL-BatchDraw
test/test.js
JavaScript
mit
1,736
marriageMapApp.factory('MapService', ['UtilArrayService', function(UtilArrayService) { var mapLoading = true; var observerPOIShowCallback = null; var map = { center: { latitude: null, longitude: null }, zoom: null }; var poisDay = [ { id : 10, coords : { latitude : 48.8143725, longitude : -3.4430839999999753 }, icon : "img/church/blue-outline-church-64.png", iconInverse : "img/church/blank-outline-church-64.png", options : "", title : "L'église", description : "Nous vous donnons rendez-vous à 10h45 pour la célébration qui aura lieu à l'église Saint Jacques à Perros Guirec.", astuces : [{type : "astuce", value : "Pour vous garer, pensez au parking du Carrefour City, ou celui derrière l'église (place des halles) ou dans le centre ville."}] }, { id : 20, coords : { latitude : 48.8156313, longitude : -3.4447666 }, icon : "img/ring/blue-outline-ring-64.png", iconInverse : "img/ring/blank-outline-ring-64.png", options : "", title : "La mairie", description : "La cérémonie civile aura lieu à 10h dans la mairie de Perros-Guirec.", astuces : [{type : "astuce", value : "Pour vous garer, pensez au parking de la police municipale (rue Anatole France), nous nous rendrons ensuite à l'église à pied."}] }, { id : 30, coords : { latitude : 48.8151101, longitude : -3.4543653 }, icon : "img/glasses/blue-outline-glasses-64.png", iconInverse : "img/glasses/blank-outline-glasses-64.png", options : "", title : "Le vin d'honneur", description : "Après l'église, retrouvons nous pour partager un moment de convivialité au palais des Congrès, rue du Maréchal Foch.", astuces : [{type : "astuce", value : "Nous irons à pied depuis l'église (15 min de marche). Prévoyez des chaussures adéquates !"}] }, { id : 40, coords : { latitude : 48.8155061, longitude : -3.3579911 }, icon : "img/servers/blue-outline-servers-64.png", iconInverse : "img/servers/blank-outline-servers-64.png", options : "", title : "Le repas", description : "Les festivités se dérouleront dans la salle des fêtes de Trévou Tréguignec, 23 rue de la mairie.", astuces : [{type : "astuce", value : "Les logements proposés sur la carte sont tous à moins de 10 min à pied de la salle."},{type : "astuce", value : "N'hésitez pas à regarder aussi les chambres d'hôtes, gîtes ou locations non mentionnés ici."}] } ]; var poisSleep = [ { id : 100, coords : { latitude : 48.819331, longitude : -3.352362 }, icon : "img/camping/blue-outline-camping-64.png", iconInverse : "img/camping/blank-outline-camping-64.png", options : "", distance : "à 700 m de la salle", title : "Camping le Mat", description : "<i>Entre Paimpol et Perros-Guirec, la vue sur les 7 îles est imprenable. La grande plage de sable fin de la baie de Trestel, spot reconnu par les amateurs de glisse, vous invite à la détente ou à des vacances dynamiques. C 'est la Bretagne de la Côte de Granit Rose, avec ses sentiers côtiers et ses longues balades iodées. Au camping, autour de la piscine chauffée : flânerie, aquagym, et en été, nocturnes-piscine, concerts et danses bretonnes.</i><br><img src ='img/addresses/mat.jpg'>", astuces : [ { type : "astuce", value : "Si vous réservez pour une seule nuit, pensez à préciser qu'il s'agit de notre mariage afin de faciliter votre réservation." }, { type : "phone", value : "02 96 23 71 52" }, { type : "website", value : "<a target='_new' href ='http://www.flowercampings.com/camping-bretagne/camping-le-mat'>Consulter le site internet (nouvel onglet)</a>" } ] }, { id : 110, coords : { latitude : 48.8189145, longitude : -3.3538073 }, icon : "img/hotel/blue-outline-hotel-64.png", iconInverse : "img/hotel/blank-outline-hotel-64.png", options : "", distance : "à 600 m de la salle", title : "Les Terrasses de Trestel", description : "<i>Entre Tréguier et Perros-Guirec, en bordure d'une magnifique plage de sable fin, la Résidence Hôtelière «les terrasses de Trestel» vous ouvre les portes de la côte de Granit Rose. Vous aurez le bonheur d'habiter une maisonnette ou un appartement au coeur d'un grand jardin devant la mer.</i><br><img src='img/addresses/trestel.jpg'>", astuces : [ { type : "phone", value : "02 96 15 10 10" }, { type : "website", value : "<a target='_new' href ='http://location-bord-de-mer-appartement-vacances-piscine-tourisme.terrasses-trestel.fr/'>Consulter le site internet (nouvel onglet)</a>" } ] }, { id : 120, coords : { latitude : 48.8165061, longitude : -3.3597911 }, icon : "img/camping/blue-outline-camping-64.png", iconInverse : "img/camping/blank-outline-camping-64.png", options : "", title : "Camping les Macareux", distance : "à 300 m de la salle", description : "<i>Camping familial, très calme et reposant (ni piscine ,ni animation), ombragé situé dans un site remarquable à 800 mètres de la grande plage de sable fin de Trestel et à 400 mètres du port de plaisance 'Port Le Goff'.</i><br><img src ='img/addresses/macareux.jpg'>", astuces : [ { type : "astuce", value : "Si vous réservez pour une seule nuit, pensez à préciser qu'il s'agit de notre mariage afin de faciliter votre réservation." }, { type : "phone", value : "02 96 23 71 45" }, { type : "website", value : "<a target='_new' href ='http://camping-les-macareux.monsite-orange.fr/'>Consulter le site internet (nouvel onglet)</a>" } ] } ]; var currentPois = []; var service = { /** * Retourne le centre de la carte */ getMap : function () { return map; }, /** * Retourne les points d'intérêts */ currentPois : currentPois, setCurrentPoisDay : function(set) { angular.forEach(currentPois, function(value, key) { value.options = {animation : null}; }); if (set) { angular.forEach(poisDay, function(value, key) { value.options = {animation : 2}; }); UtilArrayService.addArrayToArray(currentPois, poisDay); if(observerPOIShowCallback) observerPOIShowCallback(poisDay); } else { UtilArrayService.removeArrayFromArrayByAttribute("id", currentPois, poisDay); } }, setCurrentPoisSleep : function(set) { angular.forEach(currentPois, function(value, key) { value.options = {animation : null}; }); if (set) { angular.forEach(poisSleep, function(value, key) { value.options = {animation : 2}; }); UtilArrayService.addArrayToArray(currentPois, poisSleep); if(observerPOIShowCallback) observerPOIShowCallback(poisSleep, true); } else { UtilArrayService.removeArrayFromArrayByAttribute("id", currentPois, poisSleep); } }, setMapLoading : function(value) { mapLoading = value; }, getMapLoading : function() { return mapLoading; }, setObserverPOIShow : function(callback) { observerPOIShowCallback = callback; } } service.setCurrentPoisDay(true); return service; }]);
frynt/marriage-map
src/angular/map/mapService.js
JavaScript
mit
7,336
xdescribe('uiMask', function () { var inputHtml = "<input ui-mask=\"'(9)9'\" ng-model='x'>"; var $compile, $rootScope, element; beforeEach(module('ui.directives')); beforeEach(inject(function (_$rootScope_, _$compile_) { $rootScope = _$rootScope_; $compile = _$compile_; })); describe('ui changes on model changes', function () { it('should update ui valid model value', function () { $rootScope.x = undefined; element = $compile(inputHtml)($rootScope); $rootScope.$digest(); expect(element.val()).toBe(''); $rootScope.$apply(function () { $rootScope.x = 12; }); expect(element.val()).toBe('(1)2'); }); it('should wipe out ui on invalid model value', function () { $rootScope.x = 12; element = $compile(inputHtml)($rootScope); $rootScope.$digest(); expect(element.val()).toBe('(1)2'); $rootScope.$apply(function () { $rootScope.x = 1; }); expect(element.val()).toBe(''); }); }); describe('model binding on ui change', function () { //TODO: was having har time writing those tests, will open a separate issue for those }); describe('should fail', function() { it('errors on missing quotes', function() { $rootScope.x = 42; var errorInputHtml = "<input ui-mask=\"(9)9\" ng-model='x'>"; element = $compile(errorInputHtml)($rootScope); expect($rootScope.$digest).toThrow('The Mask widget is not correctly set up'); }); }); });
inergex/meetups
2014Q2/bower_components/angular-ui/modules/directives/mask/test/maskSpec.js
JavaScript
mit
1,508
$(document).ready(function() { ///*определение ширины скролбара // создадим элемент с прокруткой var div = document.createElement('div'); div.style.overflowY = 'scroll'; div.style.width = '50px'; div.style.height = '50px'; div.style.position = 'absolute'; div.style.zIndex = '-1'; // при display:none размеры нельзя узнать // нужно, чтобы элемент был видим, // visibility:hidden - можно, т.к. сохраняет геометрию div.style.visibility = 'hidden'; document.body.appendChild(div); var scrollWidth = div.offsetWidth - div.clientWidth; document.body.removeChild(div); //*/ var fixedblock = $('#fixed'); var stick_state = false; function fxm() { if ($(window).width() > 640-scrollWidth) { fixedblock.trigger("sticky_kit:detach"); fixedblock.stick_in_parent({ parent: '#main .columns', offset_top: 30, inner_scrolling: false }); fixedblock.stick_in_parent() .on("sticky_kit:stick", function(e) { stick_state = true; }) .on("sticky_kit:unstick", function(e) { stick_state = false; }); } else { fixedblock.trigger("sticky_kit:detach"); } } fxm(); var navigation = document.getElementById('navigation'); if (navigation) { var new_fix_elem = document.createElement('div'); new_fix_elem.setAttribute('class', 'nav__bounce__element'); navigation.parentNode.insertBefore(new_fix_elem, navigation); } var my__abs__list = document.querySelector('.my__abs__list'); var count_change = -1; var fix_flag = false; var navleft = navigation.querySelector('.block--left .menu'); /* шаг скролла */ var topless = 0; var difference = 0; function navig_fixit() { var cont_top = window.pageYOffset ? window.pageYOffset : document.body.scrollTop; var docHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; difference = cont_top - topless; topless = cont_top; if (navigation) { if ($(window).width() > 768 - scrollWidth) { var height = navigation.offsetHeight; var rect = navigation.getBoundingClientRect(); var rect2 = new_fix_elem.getBoundingClientRect(); navigation.style.left = rect.left + 'px'; navigation.style.width = new_fix_elem.offsetWidth + 'px'; if (navleft.classList.contains('open') === true) { var rectus = navleft.getBoundingClientRect(); console.log(rectus.height); if (navigation.style.marginTop == '') { navigation.style.marginTop = '0px'; } var ms = parseInt(navigation.style.marginTop); ms = Math.abs(ms); ms += difference; if (ms >= 0) { var x_height = height + rectus.height - 50; if (ms <= x_height - docHeight) { navigation.style.marginTop = -ms+'px'; } else { if (difference < 0) { navigation.style.marginTop = -ms+'px'; } } } /* navigation.classList.remove('fixed'); */ new_fix_elem.style.height = '0px'; return false; } if (fix_flag === false) { if (rect2.top + height*2 < 0) { if (rect2.top > count_change) { navigation.classList.add('fixed'); new_fix_elem.style.height = height + 'px'; fix_flag = true; fixedblock.css('margin-top', height + 'px'); if (stick_state === false) { fixedblock.css('margin-top', '0px'); } } else { navigation.classList.remove('fixed'); new_fix_elem.style.height = '0px'; fix_flag = false; my__abs__list.classList.remove('active'); fixedblock.css('margin-top', '0px'); } } } else { if (rect2.top > count_change) { navigation.classList.add('fixed'); new_fix_elem.style.height = height + 'px'; fix_flag = true; fixedblock.css('margin-top', height + 'px'); if (stick_state === false) { fixedblock.css('margin-top', '0px'); } if (rect2.top > 0) { navigation.classList.remove('fixed'); new_fix_elem.style.height = '0px'; fix_flag = false; my__abs__list.classList.remove('active'); } } else { navigation.classList.remove('fixed'); new_fix_elem.style.height = '0px'; fix_flag = false; my__abs__list.classList.remove('active'); fixedblock.css('margin-top', '0px'); } } count_change = rect2.top; } else { navigation.classList.remove('fixed'); navigation.style = ''; new_fix_elem.style.height = '0px'; my__abs__list.classList.remove('active'); } } } navig_fixit(); //debounce function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; // Использование var myEfficientFn = debounce(function() { // All the taxing stuff you do navig_fixit(); fxm(); if (navigation) { navigation.classList.remove('active'); } }, 200); /* var myEfficientFn2 = debounce(function() { // All the taxing stuff you do fxm(); }, 250); */ window.addEventListener('resize', myEfficientFn); /* window.addEventListener('scroll', myEfficientFn2); */ $(window).scroll(function() { navig_fixit(); }); });
raleschenko/SportSchool
wp-content/themes/sportschool/js/fix.js
JavaScript
mit
5,536
<script type="text/javascript"> //set the interval temporary variable var setIntrVal = null; var intrVal = 3000; //lets get the slider elements var slides = document.getElementById('slides'); //get the <ul id="slides"> var slide = document.getElementsByClassName('slide'); //get the <li class="slide"> var active = document.getElementsByClassName('active'); //get the <li class="slide active"> //lets set z-index properties to the slides var j = 99; //lets initialize a higher value, change this if you need to for (var i = 0; i < slide.length; i++) { slide[i].style.zIndex = j; j--; } var ywtSlider = { init: function (newIntrVal) { //pass the new interval value into the intrVal variable if(newIntrVal) intrVal = newIntrVal; //start cycle on init ywtSlider.cycle(); }, cycle: function() { //check if cycle is already started then clear the cycle //this will clear the current interval if(setIntrVal) clearInterval(setIntrVal); //ok lets start another cycle setIntrVal = setInterval(function () { ywtSlider.slide('next'); }, intrVal); //console.log(interVal); }, slide: function (dir) { //lets get the slide index number so we can set this to the slide var nodeList = Array.prototype.slice.call(slides.children); var itemIndex = nodeList.indexOf(active[active.length - 1]); if (dir == 'back') { //check and run if the direction is back //if the direction is back //lets remove the class starting from the current item to the last for (k = itemIndex; k < slide.length; k++) { slide[k].className = 'slide'; } } else if (dir == 'next') { //check and run if the direction is next //lets check first the position of the current item if (itemIndex + 1 < slide.length - 1) { //if the next item index is not the last item lets set the 'active' class //to the next item slide[itemIndex + 1].className += ' active'; } else { //if the next item supposed to be the last item, lets remove the 'active' class //from all slide elements for (var k = 0; k < slide.length; k++) { slide[k].className = 'slide'; } } } //continue the cycle ywtSlider.cycle(); } }; window.onload = function() { ywtSlider.init(5000); } </script>
iahnn/PureJSlider
purejslider.js
JavaScript
mit
2,839
/** * Created by Cai Kang Jie on 2017/7/31. */ import lazyLoading from './../../store/modules/routeConfig/lazyLoading' export default { name: 'UI Features', expanded: false, sidebarMeta: { title: 'UI Features', icon: 'ion-android-laptop', order: 1 }, subMenu: [{ name: 'Panels', path: '/ui/panels', component: lazyLoading('ui/panels'), sidebarMeta: { title: 'Panels', order: 100 } }, { name: 'Typography', path: '/ui/typography', component: lazyLoading('ui/typography'), sidebarMeta: { title: 'Typography', order: 200 } }, { name: 'Grid', path: '/ui/grid', component: lazyLoading('ui/grid'), sidebarMeta: { title: 'Grid', order: 400 } }, { name: 'Buttons', path: '/ui/buttons', component: lazyLoading('ui/buttons'), sidebarMeta: { title: 'Buttons', order: 500 } }, { name: 'Progress Bars', path: '/ui/progressBars', component: lazyLoading('ui/progressBars'), sidebarMeta: { title: 'Progress Bars', order: 600 } }, { name: 'Alerts', path: '/ui/alerts', component: lazyLoading('ui/alerts'), sidebarMeta: { title: 'Alerts', order: 700 } }] }
MrGoldens/vue-admin
src/pages/ui/index.js
JavaScript
mit
1,267
'use strict'; function Memoized() {} const memoize = ( // Create memoized function fn // function, sync or async // Returns: function, memoized ) => { const cache = new Map(); const memoized = function(...args) { const callback = args.pop(); const key = args[0]; const record = cache.get(key); if (record) { callback(record.err, record.data); return; } fn(...args, (err, data) => { memoized.add(key, err, data); memoized.emit('memoize', key, err, data); callback(err, data); }); }; const fields = { cache, timeout: 0, limit: 0, size: 0, maxSize: 0, maxCount: 0, events: { timeout: null, memoize: null, overflow: null, add: null, del: null, clear: null } }; Object.setPrototypeOf(memoized, Memoized.prototype); return Object.assign(memoized, fields); }; Memoized.prototype.clear = function() { this.emit('clear'); this.cache.clear(); }; Memoized.prototype.add = function(key, err, data) { this.emit('add', err, data); this.cache.set(key, { err, data }); return this; }; Memoized.prototype.del = function(key) { this.emit('del', key); this.cache.delete(key); return this; }; Memoized.prototype.get = function(key, callback) { const record = this.cache.get(key); callback(record.err, record.data); return this; }; Memoized.prototype.on = function( eventName, // string listener // function, handler // on('memoize', function(err, data)) // on('add', function(key, err, data)) // on('del', function(key)) // on('clear', function()) ) { if (eventName in this.events) { this.events[eventName] = listener; } }; Memoized.prototype.emit = function( // Emit Collector events eventName, // string ...args // rest arguments ) { const event = this.events[eventName]; if (event) event(...args); }; module.exports = { memoize, };
DzyubSpirit/MetaSync
lib/memoize.js
JavaScript
mit
1,927
$(document).ready(function() { $(".container").hide(); $(".container").fadeIn('5000'); $(".showcase-wrapper").hide(); $(".showcase-wrapper").fadeIn("slow"); }); /* var toggle = false; $('.nav-toggle').on('click', function () { if (toggle == false) { $('#sidebar-wrapper').stop().animate({ 'left': '4px' }); toggle = true; } else { $('#sidebar-wrapper').stop().animate({ 'left': '250px' }); toggle = false; } }); */ $(function() { $('.project-box>.row>.project-post').append('<span class="more-info">Click for more information</span>'); $('.project-box').click(function(e) { if (e.target.tagName == "A" || e.target.tagName == "IMG") { return true; } $(this).find('.more-info').toggle(); $(this).find('.post').slideToggle(); }); });
ALenfant/alenfant.github.io
js/hc.js
JavaScript
mit
885
var jwt = require('jsonwebtoken'); /** * Middleware */ module.exports = function(scullog){ return { realIp: function* (next) { this.req.ip = this.headers['x-forwarded-for'] || this.ip; yield* next; }, handelError: function* (next) { try { yield* next; } catch (err) { this.status = err.status || 500; this.body = err.message; C.logger.error(err.stack); this.app.emit('error', err, this); } }, loadRealPath: function* (next) { // router url format must be /api/(.*) this.request.fPath = scullog.getFileManager().filePath(this.params[0], this.request.query.base); C.logger.info(this.request.fPath); yield* next; }, checkPathExists: function* (next) { // Must after loadRealPath if (!(yield scullog.getFileManager().exists(this.request.fPath))) { this.status = 404; this.body = 'Path Not Exists!'; } else { yield* next; } }, checkBase: function* (next){ var base = this.request.query.base; if (!!!base || scullog.getConfiguration().directory.indexOf(base) == -1) { this.status = 400; this.body = 'Invalid Base Location!'; } else { yield* next; } }, checkPathNotExists: function* (next) { // Must after loadRealPath if (this.query.type != 'UPLOAD_FILE' && (yield scullog.getFileManager().exists(this.request.fPath))) { this.status = 400; this.body = 'Path Has Exists!'; } else { yield* next; } }, checkAccessCookie: function* (next) { if (this.request.url.indexOf('/access') == -1) { var accessJwt = this.cookies.get(scullog.getConfiguration().id); if (accessJwt) { try { var decoded = jwt.verify(accessJwt, scullog.getConfiguration().secret); } catch (e) { this.append('access-expired', 'true'); } } else if (this.request.header["access-role"] != "default") { this.append('access-expired', 'true'); } } yield* next; } } };
sanketbajoria/scullog
server/tools.js
JavaScript
mit
2,165
var Thermostat = function() { this.temp = 20; this.mode = 'power saving'; this.min = 10; this.max = 25; }; Thermostat.prototype.setPowerSaving = function(value) { this.mode = (value ? 'power saving' : 'normal'); this.max = (value ? 25 : 32); }; Thermostat.prototype.increase = function() { if(this.temp < this.max) {this.temp++} }; Thermostat.prototype.decrease = function() { if(this.temp > this.min) {this.temp--} }; Thermostat.prototype.resetTemp = function() { this.temp = 20; };
bat020/tue-thermostat
src/Thermostat.js
JavaScript
mit
506
/* @flow */ import React from "react"; import PropTypes from "prop-types"; import { Text, TouchableOpacity, Platform, StyleSheet, ScrollView, PixelRatio, View } from "react-native"; import Modal from "react-native-modalbox"; type Props = { styleContainer?: Object, coverScreen?: boolean, backButtonEnabled?: boolean, height?: number, title?: string, options: Array<Object>, refs: Function, fontFamily?: string, titleFontFamily?: string, isOpen?: boolean, cancelButtonIndex?: number, itemDivider?: number }; type State = void; class BottomSheet extends React.PureComponent<Props, State> { open: Function; static propTypes = { styleContainer: PropTypes.object, coverScreen: PropTypes.bool, backButtonEnabled: PropTypes.bool, height: PropTypes.number, title: PropTypes.string, options: PropTypes.arrayOf(PropTypes.object).isRequired, refs: PropTypes.func.isRequired, fontFamily: PropTypes.string, titleFontFamily: PropTypes.string, isOpen: PropTypes.bool, cancelButtonIndex: PropTypes.number, itemDivider: PropTypes.number }; renderOption = (options: Array<Object>) => { return options.map((item, index) => { return ( <View style={{ flexDirection: "column" }} key={index}> <TouchableOpacity onPress={item.onPress}> <View style={styles.item}> {item.icon} <Text style={[styles.text, { fontFamily: this.props.fontFamily }]} > {item.title} </Text> </View> </TouchableOpacity> {this.props.itemDivider === index + 1 ? ( <View style={styles.separator} /> ) : null} </View> ); }); }; renderTitle = () => { if (!this.props.title) { return; } return ( <Text style={[styles.title, { fontFamily: this.props.titleFontFamily }]}> {this.props.title} </Text> ); }; render() { return ( <Modal style={[this.props.styleContainer, { height: this.props.height }]} backButtonClose={this.props.backButtonEnabled} position="bottom" isOpen={this.props.isOpen} ref={this.props.refs} coverScreen={this.props.coverScreen} > <ScrollView style={styles.modal}> {this.renderTitle()} {this.renderOption(this.props.options)} </ScrollView> </Modal> ); } } const styles = StyleSheet.create({ text: { paddingHorizontal: 32, fontFamily: "Roboto", textAlignVertical: "center", color: "#000", opacity: 0.87 }, item: { flexDirection: "row", height: 48, alignItems: "center", paddingLeft: 16, paddingRight: 16 }, title: { height: 42, color: "#000", opacity: 0.54, marginLeft: 16 }, modal: { marginTop: 16 }, separator: { height: 1 / PixelRatio.get(), backgroundColor: "#CCCCCC", marginTop: 7, marginBottom: 8, width: "100%" } }); export default BottomSheet;
sonnylazuardi/alkitab-app
old/src/components/BottomSheet.js
JavaScript
mit
3,079
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, describe, it, expect, beforeEach, afterEach, waitsFor, runs, $ */ define(function (require, exports, module) { 'use strict'; var Editor = require("editor/Editor").Editor, EditorCommandHandlers = require("editor/EditorCommandHandlers"), Commands = require("command/Commands"), CommandManager = require("command/CommandManager"), SpecRunnerUtils = require("spec/SpecRunnerUtils"), EditorUtils = require("editor/EditorUtils"); describe("EditorCommandHandlers", function () { var defaultContent = "function foo() {\n" + " function bar() {\n" + " \n" + " a();\n" + " \n" + " }\n" + "\n" + "}"; var myDocument, myEditor; beforeEach(function () { // create dummy Document for the Editor myDocument = SpecRunnerUtils.createMockDocument(defaultContent); // create Editor instance (containing a CodeMirror instance) $("body").append("<div id='editor'/>"); myEditor = new Editor(myDocument, true, "javascript", $("#editor").get(0), {}); // Must be focused so editor commands target it myEditor.focus(); }); afterEach(function () { myEditor.destroy(); myEditor = null; $("#editor").remove(); myDocument = null; }); // Helper functions for testing cursor position / selection range function expectCursorAt(pos) { var selection = myEditor.getSelection(); expect(selection.start).toEqual(selection.end); expect(selection.start).toEqual(pos); } function expectSelection(sel) { expect(myEditor.getSelection()).toEqual(sel); } describe("Line comment/uncomment", function () { it("should comment/uncomment a single line, cursor at start", function () { myEditor.setCursorPos(3, 0); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[3] = "// a();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 3, ch: 2}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectCursorAt({line: 3, ch: 0}); }); it("should comment/uncomment a single line, cursor at end", function () { myEditor.setCursorPos(3, 12); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[3] = "// a();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 3, ch: 14}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectCursorAt({line: 3, ch: 12}); }); it("should comment/uncomment first line in file", function () { myEditor.setCursorPos(0, 0); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[0] = "//function foo() {"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 0, ch: 2}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectCursorAt({line: 0, ch: 0}); }); it("should comment/uncomment a single partly-selected line", function () { // select "function" on line 1 myEditor.setSelection({line: 1, ch: 4}, {line: 1, ch: 12}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 6}, end: {line: 1, ch: 14}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 4}, end: {line: 1, ch: 12}}); }); it("should comment/uncomment a single selected line", function () { // selection covers all of line's text, but not \n at end myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 20}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 1, ch: 22}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 1, ch: 20}}); }); it("should comment/uncomment a single fully-selected line (including LF)", function () { // selection including \n at end of line myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 2, ch: 0}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 2, ch: 0}}); }); it("should comment/uncomment multiple selected lines", function () { // selection including \n at end of line myEditor.setSelection({line: 1, ch: 0}, {line: 6, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; lines[2] = "// "; lines[3] = "// a();"; lines[4] = "// "; lines[5] = "// }"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}}); }); it("should comment/uncomment ragged multi-line selection", function () { myEditor.setSelection({line: 1, ch: 6}, {line: 3, ch: 9}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; lines[2] = "// "; lines[3] = "// a();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 8}, end: {line: 3, ch: 11}}); expect(myEditor.getSelectedText()).toEqual("nction bar() {\n// \n// a"); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 6}, end: {line: 3, ch: 9}}); }); it("should comment/uncomment after select all", function () { myEditor.setSelection({line: 0, ch: 0}, {line: 7, ch: 1}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); var expectedText = "//function foo() {\n" + "// function bar() {\n" + "// \n" + "// a();\n" + "// \n" + "// }\n" + "//\n" + "//}"; expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 0, ch: 0}, end: {line: 7, ch: 3}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 0, ch: 0}, end: {line: 7, ch: 1}}); }); it("should comment/uncomment lines that were partially commented out already, our style", function () { // Start with line 3 commented out, with "//" at column 0 var lines = defaultContent.split("\n"); lines[3] = "// a();"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select lines 1-3 myEditor.setSelection({line: 1, ch: 0}, {line: 4, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; lines[2] = "// "; lines[3] = "//// a();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(startingContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}}); }); it("should comment/uncomment lines that were partially commented out already, comment closer to code", function () { // Start with line 3 commented out, with "//" snug against the code var lines = defaultContent.split("\n"); lines[3] = " //a();"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select lines 1-3 myEditor.setSelection({line: 1, ch: 0}, {line: 4, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); lines = defaultContent.split("\n"); lines[1] = "// function bar() {"; lines[2] = "// "; lines[3] = "// //a();"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(startingContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}}); }); it("should uncomment indented, aligned comments", function () { // Start with lines 1-5 commented out, with "//" all aligned at column 4 var lines = defaultContent.split("\n"); lines[1] = " //function bar() {"; lines[2] = " // "; lines[3] = " // a();"; lines[4] = " // "; lines[5] = " //}"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select lines 1-5 myEditor.setSelection({line: 1, ch: 0}, {line: 6, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}}); }); it("should uncomment ragged partial comments", function () { // Start with lines 1-5 commented out, with "//" snug up against each non-blank line's code var lines = defaultContent.split("\n"); lines[1] = " //function bar() {"; lines[2] = " "; lines[3] = " //a();"; lines[4] = " "; lines[5] = " //}"; var startingContent = lines.join("\n"); myDocument.setText(startingContent); // select lines 1-5 myEditor.setSelection({line: 1, ch: 0}, {line: 6, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}}); }); }); describe("Duplicate", function () { it("should duplicate whole line if no selection", function () { // place cursor in middle of line 1 myEditor.setCursorPos(1, 10); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 0, " function bar() {"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 2, ch: 10}); }); it("should duplicate line + \n if selected line is at end of file", function () { var lines = defaultContent.split("\n"), len = lines.length; // place cursor at the beginning of the last line myEditor.setCursorPos(len - 1, 0); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); lines.push("}"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: len, ch: 0}); }); it("should duplicate first line", function () { // place cursor at start of line 0 myEditor.setCursorPos(0, 0); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines.splice(0, 0, "function foo() {"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 1, ch: 0}); }); it("should duplicate empty line", function () { // place cursor on line 6 myEditor.setCursorPos(6, 0); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines.splice(6, 0, ""); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 7, ch: 0}); }); it("should duplicate selection within a line", function () { // select "bar" on line 1 myEditor.setSelection({line: 1, ch: 13}, {line: 1, ch: 16}); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines[1] = " function barbar() {"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 16}, end: {line: 1, ch: 19}}); }); it("should duplicate when entire line selected, excluding newline", function () { // select all of line 1, EXcluding trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 20}); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines[1] = " function bar() { function bar() {"; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 20}, end: {line: 1, ch: 40}}); }); it("should duplicate when entire line selected, including newline", function () { // select all of line 1, INcluding trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 0, " function bar() {"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 2, ch: 0}, end: {line: 3, ch: 0}}); }); it("should duplicate when multiple lines selected", function () { // select lines 1-3 myEditor.setSelection({line: 1, ch: 0}, {line: 4, ch: 0}); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 0, " function bar() {", " ", " a();"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 4, ch: 0}, end: {line: 7, ch: 0}}); }); it("should duplicate selection crossing line boundary", function () { // select from middle of line 1 to middle of line 3 myEditor.setSelection({line: 1, ch: 13}, {line: 3, ch: 11}); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var lines = defaultContent.split("\n"); lines.splice(1, 3, " function bar() {", " ", " a()bar() {", " ", " a();"); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 3, ch: 11}, end: {line: 5, ch: 11}}); }); it("should duplicate after select all", function () { myEditor.setSelection({line: 0, ch: 0}, {line: 7, ch: 1}); CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor); var expectedText = defaultContent + defaultContent; expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 7, ch: 1}, end: {line: 14, ch: 1}}); }); }); describe("Move Lines Up/Down", function () { it("should move whole line up if no selection", function () { // place cursor in middle of line 1 myEditor.setCursorPos(1, 10); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[0]; lines[0] = lines[1]; lines[1] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 0, ch: 10}); }); it("should move whole line down if no selection", function () { // place cursor in middle of line 1 myEditor.setCursorPos(1, 10); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[2]; lines[2] = lines[1]; lines[1] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 2, ch: 10}); }); it("shouldn't move up first line", function () { // place cursor at start of line 0 myEditor.setCursorPos(0, 0); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectCursorAt({line: 0, ch: 0}); }); it("shouldn't move down last line", function () { var lines = defaultContent.split("\n"), len = lines.length; // place cursor at the beginning of the last line myEditor.setCursorPos(len - 1, 0); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: len - 1, ch: 0}); }); it("should move up empty line", function () { // place cursor on line 6 myEditor.setCursorPos(6, 0); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[5]; lines[5] = lines[6]; lines[6] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 5, ch: 0}); }); it("should move down empty line", function () { // place cursor on line 6 myEditor.setCursorPos(6, 0); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[7]; lines[7] = lines[6]; lines[6] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 7, ch: 0}); }); it("should move up when entire line selected, excluding newline", function () { // select all of line 1, EXcluding trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 20}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[0]; lines[0] = lines[1]; lines[1] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 0, ch: 0}, end: {line: 0, ch: 20}}); }); it("should move down when entire line selected, excluding newline", function () { // select all of line 1, EXcluding trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 20}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[2]; lines[2] = lines[1]; lines[1] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 2, ch: 0}, end: {line: 2, ch: 20}}); }); it("should move up when entire line selected, including newline", function () { // select all of line 1, INcluding trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[0]; lines[0] = lines[1]; lines[1] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 0, ch: 0}, end: {line: 1, ch: 0}}); }); it("should move down when entire line selected, including newline", function () { // select all of line 1, INcluding trailing \n myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[2]; lines[2] = lines[1]; lines[1] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 2, ch: 0}, end: {line: 3, ch: 0}}); }); it("should move up when multiple lines selected", function () { // select lines 2-3 myEditor.setSelection({line: 2, ch: 0}, {line: 4, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[1]; lines[1] = lines[2]; lines[2] = lines[3]; lines[3] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 3, ch: 0}}); }); it("should move down when multiple lines selected", function () { // select lines 2-3 myEditor.setSelection({line: 2, ch: 0}, {line: 4, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[4]; lines[4] = lines[3]; lines[3] = lines[2]; lines[2] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 3, ch: 0}, end: {line: 5, ch: 0}}); }); it("should move up selection crossing line boundary", function () { // select from middle of line 2 to middle of line 3 myEditor.setSelection({line: 2, ch: 8}, {line: 3, ch: 11}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[1]; lines[1] = lines[2]; lines[2] = lines[3]; lines[3] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 8}, end: {line: 2, ch: 11}}); }); it("should move down selection crossing line boundary", function () { // select from middle of line 2 to middle of line 3 myEditor.setSelection({line: 2, ch: 8}, {line: 3, ch: 11}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[4]; lines[4] = lines[3]; lines[3] = lines[2]; lines[2] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 3, ch: 8}, end: {line: 4, ch: 11}}); }); it("should move the last line up", function () { // place cursor in last line myEditor.setCursorPos(7, 0); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[6]; lines[6] = lines[7]; lines[7] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 6, ch: 0}); }); it("should move the first line down", function () { // place cursor in first line myEditor.setCursorPos(0, 0); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[1]; lines[1] = lines[0]; lines[0] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectCursorAt({line: 1, ch: 0}); }); it("should move the last lines up", function () { // select lines 6-7 myEditor.setSelection({line: 6, ch: 0}, {line: 7, ch: 1}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); var lines = defaultContent.split("\n"); var temp = lines[5]; lines[5] = lines[6]; lines[6] = lines[7]; lines[7] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 5, ch: 0}, end: {line: 6, ch: 1}}); }); it("should move the first lines down", function () { // select lines 0-1 myEditor.setSelection({line: 0, ch: 0}, {line: 2, ch: 0}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); var lines = defaultContent.split("\n"); var temp = lines[2]; lines[2] = lines[1]; lines[1] = lines[0]; lines[0] = temp; var expectedText = lines.join("\n"); expect(myDocument.getText()).toEqual(expectedText); expectSelection({start: {line: 1, ch: 0}, end: {line: 3, ch: 0}}); }); it("shouldn't move up after select all", function () { myEditor.setSelection({line: 0, ch: 0}, {line: 7, ch: 1}); CommandManager.execute(Commands.EDIT_LINE_UP, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 0, ch: 0}, end: {line: 7, ch: 1}}); }); it("shouldn't move down after select all", function () { myEditor.setSelection({line: 0, ch: 0}, {line: 7, ch: 1}); CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor); expect(myDocument.getText()).toEqual(defaultContent); expectSelection({start: {line: 0, ch: 0}, end: {line: 7, ch: 1}}); }); }); }); });
zcbenz/brackets
test/spec/EditorCommandHandlers-test.js
JavaScript
mit
36,777
var ParseIndex = require("../../index"); module.exports = function addRole(params) { Parse.Cloud.define("addRole", (req, res) => { if (req.params.masterKey === ParseIndex.config.masterKey) { var roleName = req.params.roleName; if (roleName.length > 2) { var roleACL = new Parse.ACL(); roleACL.setPublicReadAccess(true); var roleName = req.params.roleName; var role = new Parse.Role(roleName, roleACL); role.save().then( ok => { res.success(`Đã tạo thành công role : ${roleName} ! ✅`); }, e => { res.error(e.message); } ); } else { res.error("⛔️ Tên role quá ngắn, yêu cần tối thiểu 3 ký tự ⛔️"); } } else { res.error("⛔️ Sai mật khẩu quản trị (masterKey) 🔑"); } //end check Masterkey }); //end define }; //end cloud
cuduy197/parse-express
cloud/role/addRole.js
JavaScript
mit
929
/* global describe, it, require */ 'use strict'; // MODULES // var // Expectation library: chai = require( 'chai' ), // Check whether an element is a finite number isFiniteNumber = require( 'validate.io-finite' ), // Module to be tested: quantile = require( './../lib/array.js' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'array quantile', function tests() { var validationData = require( './fixtures/array.json' ), lambda = validationData.lambda; it( 'should export a function', function test() { expect( quantile ).to.be.a( 'function' ); }); it( 'should evaluate the quantile function', function test() { var data, actual, expected, i; data = validationData.data; actual = new Array( data.length ); actual = quantile( actual, data, lambda ); expected = validationData.expected.map( function( d ) { if (d === 'Inf' ) { return Number.POSITIVE_INFINITY; } if ( d === '-Inf' ) { return Number.NEGATIVE_INFINITY; } return d; }); for ( i = 0; i < actual.length; i++ ) { if ( isFiniteNumber( actual[ i ] ) && isFiniteNumber( expected[ i ] ) ) { assert.closeTo( actual[ i ], expected[ i ], 1e-12 ); } } }); it( 'should return an empty array if provided an empty array', function test() { assert.deepEqual( quantile( [], [], lambda ), [] ); }); it( 'should handle non-numeric values by setting the element to NaN', function test() { var data, actual, expected; data = [ true, null, [], {} ]; actual = new Array( data.length ); actual = quantile( actual, data, lambda ); expected = [ NaN, NaN, NaN, NaN ]; assert.deepEqual( actual, expected ); }); });
distributions-io/exponential-quantile
test/test.array.js
JavaScript
mit
1,695
// JS specifically for the toolkit documentation (function( $, window, document ) { // Masthead // ----------------------------------- var $window = $(window), winTop = $window.scrollTop(), $masthead = $('.masthead'), $mastheadTitle = $masthead.find('.page-title'), $pageTitle = $('.jumbotron h1'), threshold = $pageTitle.offset().top - $masthead.outerHeight(), fadeIn, fadeOut; $window.scroll(function(){ winTop = $window.scrollTop(); fadeIn = -1 + ( winTop / threshold ); fadeOut = 2 - ( winTop / (threshold/2) ); // ^ OFFSET ^ FADESPEED // Numbers further from Higher numbers increase // zero will delay the the speed of the fade. // opacity change. $mastheadTitle.css( 'opacity', fadeIn ); $pageTitle.css( 'opacity', fadeOut ); }); }( window.jQuery, window, document ));
ObjectiveSubject/oakland-pattern-portfolio
docs/js/docs.js
JavaScript
mit
858
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'pagebreak', 'km', { alt: 'បំបែក​ទំព័រ', toolbar: 'បន្ថែម​ការ​បំបែក​ទំព័រ​មុន​បោះពុម្ព' } );
Rudhie/simlab
assets/ckeditor/plugins/pagebreak/lang/km.js
JavaScript
mit
359
// Copyright 2016 Hewlett-Packard Development Company, L.P. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // END OF TERMS AND CONDITIONS const nock = require('nock'); const expect = require('chai').expect; const encryptUtil = require('./../app/routes/auth/encrypt.es6'); const fs = require('fs'); const async = require('async'); const resources = require('../app/resources/strings.es6'); // TODO: add test for TTL expiration. // Disable eslint to allow for Nock generated objects /* eslint-disable quote-props*/ /* eslint-disable no-unused-expressions */ /* eslint-disable no-useless-escape */ /* eslint-disable camelcase */ process.env.HE_ISSUER = "issue"; process.env.HE_AUTH_SERVICE_PORT = 0; process.env.HE_AUTH_NO_COLLECTOR = 1; process.env.HE_AUDIENCE = "audience"; process.env.HE_AUTH_MOCK_AUTH = "true"; process.env.HE_AUTH_SSL_PASS = "default"; process.env.JWE_SECRETS_PATH = "./test/assets/jwe_secrets_assets.pem"; process.env.VAULT_DEV_ROOT_TOKEN_ID = "default"; process.env.HE_IDENTITY_PORTAL_ENDPOINT = "http://example.com"; process.env.HE_IDENTITY_WS_ENDPOINT = "http://example.com"; process.env.JWE_TOKEN_PATH = "./test/assets/jwe_secrets_assets.pem"; process.env.JWE_TOKEN_URL_PATH = "./test/assets/jwe_secrets_assets.pem"; process.env.JWT_TOKEN_PATH = "./test/assets/jwe_secrets_assets.pem"; process.env.JWE_TOKEN_URL_PATH_PUB = "./test/assets/jwe_secrets_pub_assets.pem"; process.env.JWT_TOKEN_PATH_PUB = "./test/assets/jwe_secrets_pub_assets.pem"; process.env.HE_AUTH_SSL_KEY = "./test/assets/key.pem"; process.env.HE_AUTH_SSL_CERT = "./test/assets/cert.pem"; if (process.env.HTTP_PROXY || process.env.http_proxy) { process.env.NO_PROXY = process.env.NO_PROXY ? process.env.NO_PROXY + ',vault' : 'vault'; process.env.no_proxy = process.env.no_proxy ? process.env.no_proxy + ',vault' : 'vault'; process.env.NO_PROXY = process.env.NO_PROXY ? process.env.NO_PROXY + ',basicauth' : 'basicauth'; process.env.no_proxy = process.env.no_proxy ? process.env.no_proxy + ',basicauth' : 'basicauth'; process.env.NO_PROXY = process.env.NO_PROXY ? process.env.NO_PROXY + ',localhost' : 'localhost'; process.env.no_proxy = process.env.no_proxy ? process.env.no_proxy + ',localhost' : 'localhost'; } nock('http://vault:8200', {"encodedQueryParams": true}) .get('/v1/sys/init') .reply(200, {"initialized": true}, ['Content-Type', 'application/json', 'Date', 'Tue, 01 Nov 2016 05:04:04 GMT', 'Content-Length', '21', 'Connection', 'close']); nock('http://vault:8200', {"encodedQueryParams": true}) .get('/v1/sys/seal-status') .reply(200, { "sealed": false, "t": 1, "n": 1, "progress": 0, "version": "Vault v0.6.1", "cluster_name": "vault-cluster-8ed1001e", "cluster_id": "48a3ee1a-14fd-be4e-3cc5-bb023c56024e" }, [ 'Content-Type', 'application/json', 'Date', 'Tue, 01 Nov 2016 05:04:04 GMT', 'Content-Length', '159', 'Connection', 'close' ]); nock('http://vault:8200', {"encodedQueryParams": true}) .get('/v1/sys/mounts') .reply(200, { "secret/": { "config": { "default_lease_ttl": 0, "max_lease_ttl": 0 }, "description": "generic secret storage", "type": "generic" }, "cubbyhole/": { "config": { "default_lease_ttl": 0, "max_lease_ttl": 0 }, "description": "per-token private secret storage", "type": "cubbyhole" }, "sys/": { "config": { "default_lease_ttl": 0, "max_lease_ttl": 0 }, "description": "system endpoints used for control, policy and debugging", "type": "system" }, "request_id": "93f8c930-6ddf-6165-7989-63c598c14aac", "lease_id": "", "renewable": false, "lease_duration": 0, "data": { "cubbyhole/": { "config": { "default_lease_ttl": 0, "max_lease_ttl": 0 }, "description": "per-token private secret storage", "type": "cubbyhole" }, "secret/": { "config": { "default_lease_ttl": 0, "max_lease_ttl": 0 }, "description": "generic secret storage", "type": "generic" }, "sys/": { "config": { "default_lease_ttl": 0, "max_lease_ttl": 0 }, "description": "system endpoints used for control, policy and debugging", "type": "system" } }, "wrap_info": null, "warnings": null, "auth": null }, [ 'Content-Type', 'application/json', 'Date', 'Tue, 01 Nov 2016 05:04:04 GMT', 'Content-Length', '961', 'Connection', 'close' ]); nock('http://vault:8200', {"encodedQueryParams": true}) .get('/v1/sys/auth') .reply(200, { "token/": { "config": { "default_lease_ttl": 0, "max_lease_ttl": 0 }, "description": "token based credentials", "type": "token" }, "request_id": "ad9b37e3-7963-3848-95b3-7915d8504202", "lease_id": "", "renewable": false, "lease_duration": 0, "data": { "token/": { "config": { "default_lease_ttl": 0, "max_lease_ttl": 0 }, "description": "token based credentials", "type": "token" } }, "wrap_info": null, "warnings": null, "auth": null }, [ 'Content-Type', 'application/json', 'Date', 'Tue, 01 Nov 2016 05:04:04 GMT', 'Content-Length', '393', 'Connection', 'close' ]); nock('http://vault:8200', {"encodedQueryParams": true}) .put('/v1/secret/abcd/integration', { "integration_info": { "name": "integration", "auth": {"type": "basic_auth"} }, "user_info": { "id": "abcd" }, "secrets": {"token": "YWRtaW46YWRtaW4="} }) .reply(204, "", ['Content-Type', 'application/json', 'Date', 'Tue, 01 Nov 2016 04:18:12 GMT', 'Connection', 'close']); nock('http://vault:8200', {"encodedQueryParams": true}) .get('/v1/secret/abcd/integration') .reply(200, { "request_id": "c48cf5e1-e9c2-c16d-dfaa-847944584e20", "lease_id": "", "renewable": false, "lease_duration": 2592000, "data": { "integration_info": {"auth": "auth", "name": "integration"}, "secrets": {"username": "admin", "password": "admin"}, "user_info": {"id": "abcd"} }, "wrap_info": null, "warnings": null, "auth": null }, ['Content-Type', 'application/json', 'Date', 'Fri, 11 Nov 2016 14:44:08 GMT', 'Content-Length', '273', 'Connection', 'close']); nock('http://vault:8200', {"encodedQueryParams": true}) .get('/v1/secret/DoesNotExists/integration') .reply(404, {"errors": []}, ['Content-Type', 'application/json', 'Date', 'Fri, 11 Nov 2016 14:45:20 GMT', 'Content-Length', '14', 'Connection', 'close']); nock('http://vault:8200', {"encodedQueryParams": true}) .get('/v1/secret/abcd/DoesNotExists') .reply(404, {"errors": []}, ['Content-Type', 'application/json', 'Date', 'Fri, 11 Nov 2016 14:45:20 GMT', 'Content-Length', '14', 'Connection', 'close']); nock('http://basicauth', {"encodedQueryParams": true}) .get('/success') .reply(200, {"authenticated": true, "user": "admin"}, ['Server', 'nginx', 'Date', 'Sat, 12 Nov 2016 03:10:08 GMT', 'Content-Type', 'application/json', 'Content-Length', '48', 'Connection', 'close', 'Access-Control-Allow-Origin', '*', 'Access-Control-Allow-Credentials', 'true']); nock('http://basicauth', {"encodedQueryParams": true}) .get('/failure') .reply(401, {"authenticated": true, "user": "admin"}, ['Server', 'nginx', 'Date', 'Sat, 12 Nov 2016 03:10:08 GMT', 'Content-Type', 'application/json', 'Content-Length', '48', 'Connection', 'close', 'Access-Control-Allow-Origin', '*', 'Access-Control-Allow-Credentials', 'true']); nock('http://vault:8200', {"encodedQueryParams": true}) .put('/v1/secret/abcd/integration', { "integration_info": { "name": "integration", "auth": { "type": "basic_auth", "params": { "endpoint": { url: "http://basicauth/success", verb: "GET" } } } }, "user_info": { "id": "abcd" }, "secrets": { "token": "YWRtaW46YWRtaW4=" } }) .reply(204, "", ['Content-Type', 'application/json', 'Date', 'Sat, 12 Nov 2016 03:10:08 GMT', 'Connection', 'close']); nock('http://vault:8200', {"encodedQueryParams": true}) .put('/v1/secret/abcd/integration', { "integration_info": { "name": "integration", "auth": { "type": "basic_auth", "params": { } } }, "user_info": { "id": "abcd" }, "secrets": { "token": "YWRtaW46YWRtaW4=" } }) .reply(204, "", ['Content-Type', 'application/json', 'Date', 'Sat, 12 Nov 2016 03:10:08 GMT', 'Connection', 'close']); nock('http://vault:8200', {"encodedQueryParams": true}) .put('/v1/secret/abcd/integration', { "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http:\/\/idmauth\/success", verb: "POST" } } } }, "user_info": { "id": "abcd" }, "secrets": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ", "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ" } }) .reply(204, "", ['Content-Type', 'application/json', 'Date', 'Sat, 12 Nov 2016 03:10:08 GMT', 'Connection', 'close']); const authService = require('../server.es6'); const request = require('supertest')(authService.app); /* eslint-disable no-undef */ let token = ""; let secret = ""; let secretPayload = {"username": "admin", "password": "admin"}; describe('Auth Service tests', function() { this.timeout(20000); before(function(done) { let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem'); encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload), (err, encryptedSecrets) => { if (err) return done(err); secret = encryptedSecrets; done(); }); }); it('should fail to yield token if fields are not properly set', function(done) { request .post('/token_urls') .send({}) .expect(500, done); }); it('should fail to yield token if url_props is not set', function(done) { request .post('/token_urls') .send({ "user_info": {"id": "abcd"}, "integration_info": {"name": "integration", "auth": "auth"}, "bot_info": "xyz" }) .expect(500, done); }); it('should fail to yield token if bot_info is not set', function(done) { request .post('/token_urls') .send({ "user_info": {"id": "abcd"}, "integration_info": {"name": "integration", "auth": "auth"}, "url_props": {"ttl": 300} }) .expect(500, done); }); it('should fail to yield token if integration_info is not set', function(done) { request .post('/token_urls') .send({ "user_info": {"id": "abcd"}, "bot_info": "xyz", "url_props": {"ttl": 300} }) .expect(500, done); }); it('should fail to yield token if user_info is not set', function(done) { request .post('/token_urls') .send({ "integration_info": {"name": "integration", "auth": "auth"}, "bot_info": "xyz", "url_props": {"ttl": 300} }) .expect(500, done); }); it('should fail to yield token if integration_info.name is not set', function(done) { request .post('/token_urls') .send({ "integration_info": {"auth": "auth"}, "bot_info": "xyz", "url_props": {"ttl": 300} }) .expect(500, done); }); it('should fail to yield token if integration_info.auth is not set', function(done) { request .post('/token_urls') .send({ "integration_info": {"name": "integration"}, "bot_info": "xyz", "url_props": {"ttl": 300} }) .expect(500, done); }); it('should yield valid token if body is correctly built', function(done) { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": {"type": "basic_auth"} }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); }); it('should return an error when posting secrets without providing a token or secret', function(done) { request .post('/secrets') .send({}) .expect(500, done); }); it('should return an error when posting secrets without providing a valid token', function(done) { request .post('/secrets') .send({"secrets": secret}) .expect(500, done); }); it('should return an error when posting secrets without providing a valid secret', function(done) { request .post('/secrets') .send({"secrets": {"invalid": "secret"}, "token": token}) .expect(500, done); }); it('should store the secret given a valid token and secret', function(done) { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(201, done); }); it('should be able to retrieve the stored secret', function(done) { let userID = 'abcd'; let integrationName = 'integration'; request .get(`/secrets/${userID}/${integrationName}`) .expect(200) .expect(resp => { expect(resp).to.exist; expect(resp.body).to.exist; expect(resp.body.secrets).to.exist; expect(resp.body.secrets).to.be.an('object'); expect(resp.body.integration_info).to.exist; expect(resp.body.integration_info).to.be.an('object'); expect(resp.body.integration_info.name).to.exist; expect(resp.body.integration_info.auth).to.exist; expect(resp.body.user_info).to.exist; expect(resp.body.user_info).to.be.an('object'); expect(resp.body.user_info.id).to.exist; }) .end(done); }); it('should error out when a non-existing userID is given', function(done) { let userID = 'DoesNotExists'; let integrationName = 'integration'; request .get(`/secrets/${userID}/${integrationName}`) .expect(404, done); }); it('should error out when a non-existing integrationName is given', function(done) { let userID = 'abcd'; let integrationName = 'DoesNotExists'; request .get(`/secrets/${userID}/${integrationName}`) .expect(404, done); }); }); describe('Auth Service endpoint authentication test', function() { it('should yield valid token with an embedded endpoint (credentials set to admin:admin)', function(done) { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "basic_auth", "params": { "endpoint": { url: "http://basicauth/success", verb: "GET" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); }); it('should store the secret given valid credentials', function(done) { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(201, done); }); }); describe('Auth Service endpoint authentication test for failure', function() { it('should yield valid token with an embedded endpoint (credentials set to admin:newPassword)', function(done) { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "basic_auth", "params": { "endpoint": { url: "http://basicauth/failure", verb: "GET" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); }); it('should not store the secret given invalid credentials', function(done) { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(401, done); }); it('should not store the secret if `verb` is not specified', function(done) { async.series([ done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "basic_auth", "params": { "endpoint": { url: "http://basicauth/success" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(500, done); }); }); it('should not store the secret if `url` is not specified', function(done) { async.series([ done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "basic_auth", "params": { "endpoint": { verb: "GET" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(500, done); }); }); it('should store the secret if `endpoint` is not specified', function(done) { async.series([ done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "basic_auth", "params": { } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(201, done); }); }); }); describe('Test IDM authentication', function() { it('Should fail if missing endpoint', function(done) { async.series([ done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(500, done); }); }); it('Should fail if missing url', function(done) { async.series([ done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { verb: "POST" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(500, done); }); }); it('Should fail if missing verb', function(done) { async.series([ done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http://basicauth/success" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(500, done); }); }); it('Should fail if missing secrets', function(done) { request .post('/secrets') .send({"token": token}) .expect(500, done); }); it('Should fail if missing user', function(done) { async.series([ done => { let secretPayload = { "tenant": { "username": "admin", "password": "admin" } }; let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem'); encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload), (err, encryptedSecrets) => { if (err) return done(err); secret = encryptedSecrets; done(); }); }, done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http://basicauth/success", verb: "POST" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(500, done); }); }); it('Should fail if missing username in user structure', function(done) { async.series([ done => { let secretPayload = { "user": { "password": "admin" }, "tenant": { "username": "admin", "password": "admin" } }; let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem'); encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload), (err, encryptedSecrets) => { if (err) return done(err); secret = encryptedSecrets; done(); }); }, done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http://basicauth/success", verb: "POST" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(500, done); }); }); it('Should fail if missing password in user structure', function(done) { async.series([ done => { let secretPayload = { "user": { "username": "admin" }, "tenant": { "username": "admin", "password": "admin" } }; let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem'); encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload), (err, encryptedSecrets) => { if (err) return done(err); secret = encryptedSecrets; done(); }); }, done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http://basicauth/success", verb: "POST" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(500, done); }); }); it('Should fail if missing tenant', function(done) { async.series([ done => { let secretPayload = { "user": { "username": "admin", "password": "admin" } }; let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem'); encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload), (err, encryptedSecrets) => { if (err) return done(err); secret = encryptedSecrets; done(); }); }, done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http://basicauth/success", verb: "POST" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(500, done); }); }); it('Should fail if missing username in tenant structure', function(done) { async.series([ done => { let secretPayload = { "user": { "username": "admin", "password": "admin" }, "tenant": { "password": "admin" } }; let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem'); encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload), (err, encryptedSecrets) => { if (err) return done(err); secret = encryptedSecrets; done(); }); }, done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http://basicauth/success", verb: "POST" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(500, done); }); }); it('Should fail if missing password in tenant structure', function(done) { async.series([ done => { let secretPayload = { "user": { "username": "admin", "password": "admin" }, "tenant": { "username": "admin" } }; let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem'); encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload), (err, encryptedSecrets) => { if (err) return done(err); secret = encryptedSecrets; done(); }); }, done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http://basicauth/success", verb: "POST" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(500, done); }); }); it('Should fail if missing NAME in tenant structure', function(done) { async.series([ done => { let secretPayload = { "user": { "username": "admin", "password": "admin" }, "tenant": { "username": "admin", "password": "admin" } }; let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem'); encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload), (err, encryptedSecrets) => { if (err) return done(err); secret = encryptedSecrets; done(); }); }, done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http://basicauth/success", verb: "POST" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(500, done); }); }); it('Should fail if an unsupported http verb is given.', function(done) { async.series([ done => { let secretPayload = { "user": { "username": "admin", "password": "admin" }, "tenant": { "username": "admin", "password": "admin" } }; let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem'); encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload), (err, encryptedSecrets) => { if (err) return done(err); secret = encryptedSecrets; done(); }); }, done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http://idmauth/success", verb: "GET" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(500, done); }); }); it('Should successfully authenticate when payload is built correctly.', function(done) { async.series([ done => { let secretPayload = { "user": { "username": resources.MOCK_IDM_CREDS.username, "password": resources.MOCK_IDM_CREDS.password }, "tenant": { "name": resources.MOCK_IDM_CREDS.tenantName, "username": resources.MOCK_IDM_CREDS.tenantUsername, "password": resources.MOCK_IDM_CREDS.tenantPassword } }; let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem'); encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload), (err, encryptedSecrets) => { if (err) return done(err); secret = encryptedSecrets; done(); }); }, done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http://idmauth/success", verb: "POST" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(201, done); }); }); it('Should not allow access to an agent with incorrect user credentials.', function(done) { async.series([ done => { let secretPayload = { "user": { "username": "wrong", "password": "wrong" }, "tenant": { "name": resources.MOCK_IDM_CREDS.tenantName, "username": resources.MOCK_IDM_CREDS.tenantUsername, "password": resources.MOCK_IDM_CREDS.tenantPassword } }; let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem'); encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload), (err, encryptedSecrets) => { if (err) return done(err); secret = encryptedSecrets; done(); }); }, done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http://idmauth/failure", verb: "POST" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(401, done); }); }); it('Should not allow access to an agent with incorrect tenant credentials.', function(done) { async.series([ done => { let secretPayload = { "user": { "username": resources.MOCK_IDM_CREDS.username, "password": resources.MOCK_IDM_CREDS.password }, "tenant": { "name": resources.MOCK_IDM_CREDS.tenantName, "username": "wrong", "password": "wrong" } }; let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem'); encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload), (err, encryptedSecrets) => { if (err) return done(err); secret = encryptedSecrets; done(); }); }, done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http://idmauth/failure", verb: "POST" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(401, done); }); }); it('Should not allow access to an agent with incorrect tenant NAME', function(done) { async.series([ done => { let secretPayload = { "user": { "username": resources.MOCK_IDM_CREDS.username, "password": resources.MOCK_IDM_CREDS.password }, "tenant": { "name": "wrong", "username": resources.MOCK_IDM_CREDS.tenantUsername, "password": resources.MOCK_IDM_CREDS.tenantPassword } }; let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem'); encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload), (err, encryptedSecrets) => { if (err) return done(err); secret = encryptedSecrets; done(); }); }, done => { let payload = { "user_info": { "id": "abcd" }, "integration_info": { "name": "integration", "auth": { "type": "idm_auth", "params": { "endpoint": { url: "http://idmauth/failure", verb: "POST" } } } }, "bot_info": "xyz", "url_props": { "ttl": 300 } }; request .post('/token_urls') .send(payload) .expect(201) .expect(res => { expect(res.body).exists; expect(res.body.token).exists; expect(res.body.message).equals('token_url created'); token = res.body.token; }) .end(err => { if (err) { return done(err); } done(); }); } ], () => { request .post('/secrets') .send({"secrets": secret, "token": token}) .expect(401, done); }); }); });
eedevops/he-auth-service
test/auth_service.js
JavaScript
mit
47,884
/*: * @plugindesc Basic plugin for manipulating important parameters. * @author RM CoreScript team * * @help * Basic plugin for manipulating important parameters. * There is no plugin command. * * Caching images improves performance but increases memory allocation. * On mobile devices, a lot of memory allocation causes the browser to crash. * Therefore, the upper limit of memory allocation is set with cacheLimit. * * If you want to regain high performance, just increase cacheLimit. * There is no need to revert to 1.4. * * @param cacheLimit * @type number * @desc The upper limit of images' cached size (MPixel) * @default 10 * * @param screenWidth * @type number * @desc The resolution of screen width * @default 816 * * @param screenHeight * @type number * @desc The resolution of screen height * @default 624 * * @param changeWindowWidthTo * @type number * @desc If set, change window width to this value * * @param changeWindowHeightTo * @type number * @desc If set, change window height to this value * * @param renderingMode * @type select * @option canvas * @option webgl * @option auto * @desc The rendering mode (canvas/webgl/auto) * @default auto * * @param alwaysDash * @type boolean * @desc The initial value whether the player always dashes (on/off) * @on ON * @off OFF * @default false * * @param textSpeed * @type number * @desc The text speed on "Show Text". The larger this parameter is, the slower text speed. (0: show all texts at once) * @default 1 * * @param autoSaveFileId * @type number * @desc The file number to auto save when "Transfer Player" (0: off) * @default 0 * * @param errorMessage * @type string * @desc The message when error occurred * @default Error occurred. Please ask to the creator of this game. * * @param showErrorDetail * @type boolean * @desc Show where the error is caused and stack trace when error * @default true * * @param enableProgressBar * @type boolean * @desc Show progress bar when it takes a long time to load resources * @default true * * @param maxRenderingFps * @type number * @desc The maximum value of rendering frame per seconds (0: unlimited) * @default 0 */ /*:ja * @plugindesc 基本的なパラメーターを設定するプラグインです。 * @author RM CoreScript team * * @help * 基本的なパラメーターを設定するプラグインです。 * このプラグインにはプラグインコマンドはありません。 * * 画像をキャッシュするとパフォーマンスは向上しますが、その分メモリ確保も増大します。 * モバイルデバイスでは、たくさんのメモリ確保はブラウザをクラッシュさせます。 * そこで、メモリ確保の上限を「画像キャッシュ上限値」で設定しています。 * * もし高いパフォーマンスを取り戻したければ、ただ画像キャッシュ上限値を増加させればよいです。 * 1.4に戻す必要はありません。 * * @param cacheLimit * @type number * @text 画像キャッシュ上限値 * @desc 画像のメモリへのキャッシュの上限値 (MPix) * @default 10 * * @param screenWidth * @type number * @text ゲーム画面の幅 * @default 816 * * @param screenHeight * @type number * @text ゲーム画面の高さ * @default 624 * * @param changeWindowWidthTo * @type number * @text ウィンドウの幅 * @desc 値が設定されなかった場合、ゲーム画面の幅と同じ * * @param changeWindowHeightTo * @type number * @text ウィンドウの高さ * @desc 値が設定されなかった場合、ゲーム画面の高さと同じ * * @param renderingMode * @type select * @option canvas * @option webgl * @option auto * @text レンダリングモード * @default auto * * @param alwaysDash * @type boolean * @text 「常時ダッシュ」の初期値 * @on ON * @off OFF * @default false * * @param textSpeed * @type number * @text 「文章の表示」のスピード * @desc 数字が大きいほど文章の表示スピードが遅くなります (0を指定した場合は一度に全文を表示します) * @default 1 * * @param autoSaveFileId * @type number * @text オートセーブ番号 * @desc 「場所移動」の際に指定したファイル番号にオートセーブします(0を指定した場合はオートセーブしません) * @default 0 * * @param errorMessage * @type string * @text エラーメッセージ * @desc エラー時にプレイヤーに向けて表示するメッセージです * @default エラーが発生しました。ゲームの作者にご連絡ください。 * * @param showErrorDetail * @type boolean * @text エラー詳細表示 * @desc ONにすると、エラー時にエラーを発生させたイベントの情報とスタックトレースを表示します * @default true * * @param enableProgressBar * @type boolean * @text ロード進捗バー有効化 * @desc ONにすると、読み込みに時間がかかっている時にロード進捗バーを表示します * @default true * * @param maxRenderingFps * @type number * @text 描画FPS上限値 * @desc 描画FPSの上限値を設定します (0を指定した場合は制限なし) * @default 0 */ (function() { 'use strict'; function isNumber(str) { return !!str && !isNaN(str); } function toNumber(str, def) { return isNumber(str) ? +str : def; } var parameters = PluginManager.parameters('Community_Basic'); var cacheLimit = toNumber(parameters['cacheLimit'], 10); var screenWidth = toNumber(parameters['screenWidth'], 816); var screenHeight = toNumber(parameters['screenHeight'], 624); var renderingMode = parameters['renderingMode'].toLowerCase(); var alwaysDash = (parameters['alwaysDash'] === 'true') ||(parameters['alwaysDash'] === 'on'); var textSpeed = toNumber(parameters['textSpeed'], 1); var windowWidthTo = toNumber(parameters['changeWindowWidthTo'], 0); var windowHeightTo = toNumber(parameters['changeWindowHeightTo'], 0); var maxRenderingFps = toNumber(parameters['maxRenderingFps'], 0); var autoSaveFileId = toNumber(parameters['autoSaveFileId'], 0); var errorMessage = parameters['errorMessage']; var showErrorDetail = parameters['showErrorDetail'] === 'true'; var enableProgressBar = parameters['enableProgressBar'] === 'true'; var windowWidth; var windowHeight; if(windowWidthTo){ windowWidth = windowWidthTo; }else if(screenWidth !== SceneManager._screenWidth){ windowWidth = screenWidth; } if(windowHeightTo){ windowHeight = windowHeightTo; }else if(screenHeight !== SceneManager._screenHeight){ windowHeight = screenHeight; } ImageCache.limit = cacheLimit * 1000 * 1000; SceneManager._screenWidth = screenWidth; SceneManager._screenHeight = screenHeight; SceneManager._boxWidth = screenWidth; SceneManager._boxHeight = screenHeight; SceneManager.preferableRendererType = function() { if (Utils.isOptionValid('canvas')) { return 'canvas'; } else if (Utils.isOptionValid('webgl')) { return 'webgl'; } else if (renderingMode === 'canvas') { return 'canvas'; } else if (renderingMode === 'webgl') { return 'webgl'; } else { return 'auto'; } }; var _ConfigManager_applyData = ConfigManager.applyData; ConfigManager.applyData = function(config) { _ConfigManager_applyData.apply(this, arguments); if (config['alwaysDash'] === undefined) { this.alwaysDash = alwaysDash; } }; var _Window_Message_clearFlags = Window_Message.prototype.clearFlags; Window_Message.prototype.clearFlags = function(textState) { _Window_Message_clearFlags.apply(this, arguments); this._textSpeed = textSpeed - 1; }; var _SceneManager_initNwjs = SceneManager.initNwjs; SceneManager.initNwjs = function() { _SceneManager_initNwjs.apply(this, arguments); if (Utils.isNwjs() && windowWidth && windowHeight) { var dw = windowWidth - window.innerWidth; var dh = windowHeight - window.innerHeight; window.moveBy(-dw / 2, -dh / 2); window.resizeBy(dw, dh); } }; if (maxRenderingFps) { var currentTime = Date.now(); var deltaTime = 1000 / maxRenderingFps; var accumulator = 0; var _SceneManager_renderScene = SceneManager.renderScene; SceneManager.renderScene = function() { var newTime = Date.now(); accumulator += newTime - currentTime; currentTime = newTime; if (accumulator >= deltaTime) { accumulator -= deltaTime; _SceneManager_renderScene.apply(this, arguments); } }; } DataManager.setAutoSaveFileId(autoSaveFileId); Graphics.setErrorMessage(errorMessage); Graphics.setShowErrorDetail(showErrorDetail); Graphics.setProgressEnabled(enableProgressBar); })();
rpgtkoolmv/corescript
plugins/Community_Basic.js
JavaScript
mit
9,228
pinion.on("create.message.systemMessagesList", function(data) { data.element.settings.data = pinion.messages.reverse(); }); pinion.backend.renderer.SystemMessageRenderer = (function($) { var constr, modules = pinion.php.modules; // public API -- constructor constr = function(settings, backend) { var data = settings.data; this.$element = $("<div class='pinion-backend-renderer-SystemMessageRenderer'></div>") .append("<div class='pinion-colorfield-left'></div>") .append("<div class='pinion-colorfield-right'></div>") .addClass("pinion-"+data.type); // ICON if(data.module) { $("<div class='pinion-moduleIcon'><img src='"+modules[data.module].icon+"' /></div>").appendTo(this.$element); } // MESSAGE $("<div class='pinion-textWrapper'><div class='pinion-systemMessage'>"+data.text+"</div></div>").appendTo(this.$element); } // public API -- prototype constr.prototype = { constructor: pinion.backend.renderer.SystemMessageRenderer } return constr; }(jQuery));
friedolinfoerder/pinion
modules/message/backend/js/SystemMessageRenderer.js
JavaScript
mit
1,173
function solve(args){ var i, array = []; for(i = 0; i < args.length; i++){ array[i] = +args[i]; } var sum = 0, count = 0, min = array[0], max = array[0], avg = 0; for(i = 0; i < array.length; i++){ sum += array[i]; count++; if(array[i] < min){ min = array[i]; } if(array[i] > max){ max = array[i]; } } avg = sum / count; console.log('min=' + Number(min).toFixed(2)); console.log('max=' + Number(max).toFixed(2)); console.log('sum=' + Number(sum).toFixed(2)); console.log('avg=' + Number(avg).toFixed(2)); } solve(['2', '5', '1']);
marianamn/Telerik-Academy-Activities
Homeworks/06. JavaScript-Fundamentals/04. JS Loops/Loops - judge system/02_MMSA.js
JavaScript
mit
702
define(["globals", "ember", "core_ext", "ember-i18n", "ember-bootstrap", "select2", "moment", "mediaelement", "jquery.highlight-search-results", "jquery.autogrow-textarea", "jquery.anchorlinks", "jquery.hashtags", "jquery.expander", "bootstrap.file-input"], function(globals, Ember){ if (!globals.app) { var options = {} if (typeof DEBUG !== 'undefined') { Ember.LOG_BINDINGS = true; options = { // log when Ember generates a controller or a route from a generic class LOG_ACTIVE_GENERATION: true, // log when Ember looks up a template or a view LOG_VIEW_LOOKUPS: true, LOG_TRANSITIONS: true // LOG_TRANSITIONS_INTERNAL: true } } App = Ember.Application.create(options); // We need to delay initialization to load the rest of the application App.deferReadiness() globals.app = App } return globals.app; });
clbn/pepyatka-html
public/js/app/app.js
JavaScript
mit
1,018
import React from 'react'; import PropTypes from 'prop-types'; import './Todo.css'; const ARCHIVE_SHORTCUT_KEY_CODE = 65; // 'a' const onArchiveShortcutPress = (handler, event) => { if(event.keyCode === ARCHIVE_SHORTCUT_KEY_CODE) handler(event); }; const Todo = ({text, completed, onClick, onDeleteClick}) => ( <li className={completed ? 'TodoList_Item-completed' : 'TodoList_Item'}> <span className={completed ? 'TodoList_Text-completed' : 'TodoList_Text'} onClick={onClick} onKeyDown={onArchiveShortcutPress.bind(null, onClick)} role='button' tabIndex='0' > {text} </span> <button className='Todo_Delete' onClick={onDeleteClick} style={{color: 'red'}}> <svg width="26" height="26" viewBox="0 0 1024 1024"> <g style={{fill: '#b3b3b3'}}> <path d="M640.35,91.169H536.971V23.991C536.971,10.469,526.064,0,512.543,0c-1.312,0-2.187,0.438-2.614,0.875 C509.491,0.438,508.616,0,508.179,0H265.212h-1.74h-1.75c-13.521,0-23.99,10.469-23.99,23.991v67.179H133.916 c-29.667,0-52.783,23.116-52.783,52.783v38.387v47.981h45.803v491.6c0,29.668,22.679,52.346,52.346,52.346h415.703 c29.667,0,52.782-22.678,52.782-52.346v-491.6h45.366v-47.981v-38.387C693.133,114.286,670.008,91.169,640.35,91.169z M285.713,47.981h202.84v43.188h-202.84V47.981z M599.349,721.922c0,3.061-1.312,4.363-4.364,4.363H179.282 c-3.052,0-4.364-1.303-4.364-4.363V230.32h424.431V721.922z M644.715,182.339H129.551v-38.387c0-3.053,1.312-4.802,4.364-4.802 H640.35c3.053,0,4.365,1.749,4.365,4.802V182.339z"/> <rect x="475.031" y="286.593" width="48.418" height="396.942"/> <rect x="363.361" y="286.593" width="48.418" height="396.942"/> <rect x="251.69" y="286.593" width="48.418" height="396.942"/> </g> </svg> </button> </li> ); Todo.propTypes = { text: PropTypes.string.isRequired, completed: PropTypes.bool.isRequired, onClick: PropTypes.func.isRequired, onDeleteClick: PropTypes.func.isRequired }; export default Todo;
andresilveira/yato
src/components/Todo.js
JavaScript
mit
2,086
// Generated on 2015-05-19 using generator-angular-fullstack 2.0.13 'use strict'; module.exports = function (grunt) { var localConfig; try { localConfig = require('./server/config/local.env'); } catch(e) { localConfig = {}; } // Load grunt tasks automatically, when needed require('jit-grunt')(grunt, { express: 'grunt-express-server', useminPrepare: 'grunt-usemin', ngtemplates: 'grunt-angular-templates', cdnify: 'grunt-google-cdn', protractor: 'grunt-protractor-runner', injector: 'grunt-asset-injector', buildcontrol: 'grunt-build-control' }); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Define the configuration for all the tasks grunt.initConfig({ // Project settings pkg: grunt.file.readJSON('package.json'), yeoman: { // configurable paths client: require('./bower.json').appPath || 'client', dist: 'dist' }, express: { options: { port: process.env.PORT || 9000 }, dev: { options: { script: 'server/app.js', debug: true } }, prod: { options: { script: 'dist/server/app.js' } } }, open: { server: { url: 'http://localhost:<%= express.options.port %>' } }, watch: { injectJS: { files: [ '<%= yeoman.client %>/{app,components}/**/*.js', '!<%= yeoman.client %>/{app,components}/**/*.spec.js', '!<%= yeoman.client %>/{app,components}/**/*.mock.js', '!<%= yeoman.client %>/app/app.js'], tasks: ['injector:scripts'] }, injectCss: { files: [ '<%= yeoman.client %>/{app,components}/**/*.css' ], tasks: ['injector:css'] }, mochaTest: { files: ['server/**/*.spec.js'], tasks: ['env:test', 'mochaTest'] }, jsTest: { files: [ '<%= yeoman.client %>/{app,components}/**/*.spec.js', '<%= yeoman.client %>/{app,components}/**/*.mock.js' ], tasks: ['newer:jshint:all', 'karma'] }, injectSass: { files: [ '<%= yeoman.client %>/{app,components}/**/*.{scss,sass}'], tasks: ['injector:sass'] }, sass: { files: [ '<%= yeoman.client %>/{app,components}/**/*.{scss,sass}'], tasks: ['sass', 'autoprefixer'] }, jade: { files: [ '<%= yeoman.client %>/{app,components}/*', '<%= yeoman.client %>/{app,components}/**/*.jade'], tasks: ['jade'] }, gruntfile: { files: ['Gruntfile.js'] }, livereload: { files: [ '{.tmp,<%= yeoman.client %>}/{app,components}/**/*.css', '{.tmp,<%= yeoman.client %>}/{app,components}/**/*.html', '{.tmp,<%= yeoman.client %>}/{app,components}/**/*.js', '!{.tmp,<%= yeoman.client %>}{app,components}/**/*.spec.js', '!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.mock.js', '<%= yeoman.client %>/assets/images/{,*//*}*.{png,jpg,jpeg,gif,webp,svg}' ], options: { livereload: true } }, express: { files: [ 'server/**/*.{js,json}' ], tasks: ['express:dev', 'wait'], options: { livereload: true, nospawn: true //Without this option specified express won't be reloaded } } }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '<%= yeoman.client %>/.jshintrc', reporter: require('jshint-stylish') }, server: { options: { jshintrc: 'server/.jshintrc' }, src: [ 'server/**/*.js', '!server/**/*.spec.js' ] }, serverTest: { options: { jshintrc: 'server/.jshintrc-spec' }, src: ['server/**/*.spec.js'] }, all: [ '<%= yeoman.client %>/{app,components}/**/*.js', '!<%= yeoman.client %>/{app,components}/**/*.spec.js', '!<%= yeoman.client %>/{app,components}/**/*.mock.js' ], test: { src: [ '<%= yeoman.client %>/{app,components}/**/*.spec.js', '<%= yeoman.client %>/{app,components}/**/*.mock.js' ] } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= yeoman.dist %>/*', '!<%= yeoman.dist %>/.git*', '!<%= yeoman.dist %>/.openshift', '!<%= yeoman.dist %>/Procfile' ] }] }, server: '.tmp' }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['last 1 version'] }, dist: { files: [{ expand: true, cwd: '.tmp/', src: '{,*/}*.css', dest: '.tmp/' }] } }, // Debugging with node inspector 'node-inspector': { custom: { options: { 'web-host': 'localhost' } } }, // Use nodemon to run server in debug mode with an initial breakpoint nodemon: { debug: { script: 'server/app.js', options: { nodeArgs: ['--debug-brk'], env: { PORT: process.env.PORT || 9000 }, callback: function (nodemon) { nodemon.on('log', function (event) { console.log(event.colour); }); // opens browser on initial server start nodemon.on('config:update', function () { setTimeout(function () { require('open')('http://localhost:8080/debug?port=5858'); }, 500); }); } } } }, // Automatically inject Bower components into the app wiredep: { target: { src: '<%= yeoman.client %>/index.html', ignorePath: '<%= yeoman.client %>/', exclude: [/bootstrap-sass-official/, /bootstrap.js/, '/json3/', '/es5-shim/', /bootstrap.css/, /font-awesome.css/ ] } }, // Renames files for browser caching purposes rev: { dist: { files: { src: [ '<%= yeoman.dist %>/public/{,*/}*.js', '<%= yeoman.dist %>/public/{,*/}*.css', '<%= yeoman.dist %>/public/assets/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', '<%= yeoman.dist %>/public/assets/fonts/*' ] } } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { html: ['<%= yeoman.client %>/index.html'], options: { dest: '<%= yeoman.dist %>/public' } }, // Performs rewrites based on rev and the useminPrepare configuration usemin: { html: ['<%= yeoman.dist %>/public/{,*/}*.html'], css: ['<%= yeoman.dist %>/public/{,*/}*.css'], js: ['<%= yeoman.dist %>/public/{,*/}*.js'], options: { assetsDirs: [ '<%= yeoman.dist %>/public', '<%= yeoman.dist %>/public/assets/images' ], // This is so we update image references in our ng-templates patterns: { js: [ [/(assets\/images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images'] ] } } }, // The following *-min tasks produce minified files in the dist folder imagemin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.client %>/assets/images', src: '{,*/}*.{png,jpg,jpeg,gif}', dest: '<%= yeoman.dist %>/public/assets/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.client %>/assets/images', src: '{,*/}*.svg', dest: '<%= yeoman.dist %>/public/assets/images' }] } }, // Allow the use of non-minsafe AngularJS files. Automatically makes it // minsafe compatible so Uglify does not destroy the ng references ngAnnotate: { dist: { files: [{ expand: true, cwd: '.tmp/concat', src: '*/**.js', dest: '.tmp/concat' }] } }, // Package all the html partials into a single javascript payload ngtemplates: { options: { // This should be the name of your apps angular module module: 'joggingApp', htmlmin: { collapseBooleanAttributes: true, collapseWhitespace: true, removeAttributeQuotes: true, removeEmptyAttributes: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true }, usemin: 'app/app.js' }, main: { cwd: '<%= yeoman.client %>', src: ['{app,components}/**/*.html'], dest: '.tmp/templates.js' }, tmp: { cwd: '.tmp', src: ['{app,components}/**/*.html'], dest: '.tmp/tmp-templates.js' } }, // Replace Google CDN references cdnify: { dist: { html: ['<%= yeoman.dist %>/public/*.html'] } }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.client %>', dest: '<%= yeoman.dist %>/public', src: [ '*.{ico,png,txt}', '.htaccess', 'bower_components/**/*', 'assets/images/{,*/}*.{webp}', 'assets/fonts/**/*', 'index.html' ] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/public/assets/images', src: ['generated/*'] }, { expand: true, dest: '<%= yeoman.dist %>', src: [ 'package.json', 'server/**/*' ] }] }, styles: { expand: true, cwd: '<%= yeoman.client %>', dest: '.tmp/', src: ['{app,components}/**/*.css'] } }, buildcontrol: { options: { dir: 'dist', commit: true, push: true, connectCommits: false, message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%' }, heroku: { options: { remote: 'heroku', branch: 'master' } }, openshift: { options: { remote: 'openshift', branch: 'master' } } }, // Run some tasks in parallel to speed up the build process concurrent: { server: [ 'jade', 'sass', ], test: [ 'jade', 'sass', ], debug: { tasks: [ 'nodemon', 'node-inspector' ], options: { logConcurrentOutput: true } }, dist: [ 'jade', 'sass', 'imagemin', 'svgmin' ] }, // Test settings karma: { unit: { configFile: 'karma.conf.js', singleRun: true } }, mochaTest: { options: { reporter: 'spec' }, src: ['server/**/*.spec.js'] }, protractor: { options: { configFile: 'protractor.conf.js' }, chrome: { options: { args: { browser: 'chrome' } } } }, env: { test: { NODE_ENV: 'test' }, prod: { NODE_ENV: 'production' }, all: localConfig }, // Compiles Jade to html jade: { compile: { options: { data: { debug: false } }, files: [{ expand: true, cwd: '<%= yeoman.client %>', src: [ '{app,components}/**/*.jade' ], dest: '.tmp', ext: '.html' }] } }, // Compiles Sass to CSS sass: { server: { options: { loadPath: [ '<%= yeoman.client %>/bower_components', '<%= yeoman.client %>/app', '<%= yeoman.client %>/components' ], compass: false }, files: { '.tmp/app/app.css' : '<%= yeoman.client %>/app/app.scss' } } }, injector: { options: { }, // Inject application script files into index.html (doesn't include bower) scripts: { options: { transform: function(filePath) { filePath = filePath.replace('/client/', ''); filePath = filePath.replace('/.tmp/', ''); return '<script src="' + filePath + '"></script>'; }, starttag: '<!-- injector:js -->', endtag: '<!-- endinjector -->' }, files: { '<%= yeoman.client %>/index.html': [ ['{.tmp,<%= yeoman.client %>}/{app,components}/**/*.js', '!{.tmp,<%= yeoman.client %>}/app/app.js', '!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.spec.js', '!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.mock.js'] ] } }, // Inject component scss into app.scss sass: { options: { transform: function(filePath) { filePath = filePath.replace('/client/app/', ''); filePath = filePath.replace('/client/components/', ''); return '@import \'' + filePath + '\';'; }, starttag: '// injector', endtag: '// endinjector' }, files: { '<%= yeoman.client %>/app/app.scss': [ '<%= yeoman.client %>/{app,components}/**/*.{scss,sass}', '!<%= yeoman.client %>/app/app.{scss,sass}' ] } }, // Inject component css into index.html css: { options: { transform: function(filePath) { filePath = filePath.replace('/client/', ''); filePath = filePath.replace('/.tmp/', ''); return '<link rel="stylesheet" href="' + filePath + '">'; }, starttag: '<!-- injector:css -->', endtag: '<!-- endinjector -->' }, files: { '<%= yeoman.client %>/index.html': [ '<%= yeoman.client %>/{app,components}/**/*.css' ] } } }, }); // Used for delaying livereload until after server has restarted grunt.registerTask('wait', function () { grunt.log.ok('Waiting for server reload...'); var done = this.async(); setTimeout(function () { grunt.log.writeln('Done waiting!'); done(); }, 1500); }); grunt.registerTask('express-keepalive', 'Keep grunt running', function() { this.async(); }); grunt.registerTask('serve', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'env:all', 'env:prod', 'express:prod', 'wait', 'open', 'express-keepalive']); } if (target === 'debug') { return grunt.task.run([ 'clean:server', 'env:all', 'injector:sass', 'concurrent:server', 'injector', 'wiredep', 'autoprefixer', 'concurrent:debug' ]); } grunt.task.run([ 'clean:server', 'env:all', 'injector:sass', 'concurrent:server', 'injector', 'wiredep', 'autoprefixer', 'express:dev', 'wait', 'open', 'watch' ]); }); grunt.registerTask('server', function () { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run(['serve']); }); grunt.registerTask('test', function(target) { if (target === 'server') { return grunt.task.run([ 'env:all', 'env:test', 'mochaTest' ]); } else if (target === 'client') { return grunt.task.run([ 'clean:server', 'env:all', 'injector:sass', 'concurrent:test', 'injector', 'autoprefixer', 'karma' ]); } else if (target === 'e2e') { return grunt.task.run([ 'clean:server', 'env:all', 'env:test', 'injector:sass', 'concurrent:test', 'injector', 'wiredep', 'autoprefixer', 'express:dev', 'protractor' ]); } else grunt.task.run([ 'test:server', 'test:client' ]); }); grunt.registerTask('build', [ 'clean:dist', 'injector:sass', 'concurrent:dist', 'injector', 'wiredep', 'useminPrepare', 'autoprefixer', 'ngtemplates', 'concat', 'ngAnnotate', 'copy:dist', 'cdnify', 'cssmin', 'uglify', 'rev', 'usemin' ]); grunt.registerTask('default', [ //'newer:jshint', 'test', 'build' ]); };
budacode/jogging-app
Gruntfile.js
JavaScript
mit
17,301
module.exports = function(grunt){ grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { ctags: { files: ['ctags'], tasks: ['shell:ctags'], options: { nospawn: false, }, } }, shell: { ctags: { command: [ 'cp ctags $HOME/.ctags', 'cp taglist.vim $HOME/.vim/bundle/taglist/plugin/taglist.vim', 'ctags -f - --format=2 --excmd=pattern --fields=nks '+ '--sort=no --language-force=css --css-types=cis test.css' ].join('&&') }, release: { command: 'cp ctags $HOME/.ctags', }, options:{ stdout:true } }, }); grunt.loadNpmTasks('grunt-shell'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['watch']); grunt.registerTask('release', ['shell:release']); };
CarterTsai/ctagsTest
Gruntfile.js
JavaScript
mit
1,105
var TreeNode = require('../dist/treenode').TreeNode; describe("TreeNode Class", function() { var tree; var data = [ { name: 'I am ROOT', status: 'initial' }, { name: 'Node 1', status: 'initial' }, { name: 'Node 2', status: 'initial' }, { name: 'Node 3', status: 'initial' } ]; beforeEach(function() { tree = new TreeNode(data[0]); }); it("should allow a child to be added and return as a TreeNode object", function() { var leaf = tree.addChild(data[1]); expect(leaf.data.name).toEqual(data[1].name); }); it("should return its root", function() { expect(tree.root().data.name).toEqual(data[0].name); var leaf = tree.addChild(data[1]); expect(leaf.root().data.name).toEqual(data[0].name) }); it("should find data", function() { tree.addChild(data[1]); tree.addChild(data[2]); expect(tree.find(data[1]).data).toEqual(data[1]); expect(tree.find(data[2]).data).toEqual(data[2]); expect(tree.find(data[3])).toBe(null); }); it("should find leaves", function() { tree.addChild(data[1]); var intermediateNode = tree.addChild(data[2]); intermediateNode.addChild(data[3]); var leaves = tree.leaves(); // we've added 3 nodes, but only two are leaves expect(leaves.length).toBe(2); }); it("should execute forEach() callback on all child nodes", function() { var intermediateNode = tree.addChild(data[1]); var childNode = intermediateNode.addChild(data[2]); var grandchildNode = childNode.addChild(data[3]); intermediateNode.forEach(function(node) { node.data.status = 'updated'; }); expect(tree.root().data.status).toBe('initial'); expect(intermediateNode.data.status).toBe('updated'); expect(childNode.data.status).toBe('updated'); expect(grandchildNode.data.status).toBe('updated'); }); it("should return the number of children", function() { expect(tree.numChildren()).toBe(0); tree.addChild(data[1]); expect(tree.numChildren()).toBe(1); var intermediateNode = tree.addChild(data[2]); expect(tree.numChildren()).toBe(2); intermediateNode.addChild(data[3]); expect(tree.numChildren()).toBe(2); expect(intermediateNode.numChildren()).toBe(1); }); });
deztopia/treenode
test/treenode.spec.js
JavaScript
mit
2,563
/* * Copyright (c) 2015-2017 Steven Soloff * * This is free software: you can redistribute it and/or modify it under the * terms of the MIT License (https://opensource.org/licenses/MIT). * This software comes with ABSOLUTELY NO WARRANTY. */ 'use strict' const _ = require('underscore') const diceExpressionResult = require('./dice-expression-result') const diceExpressionTypeIds = require('./dice-expression-type-ids') /** * Provides methods for creating dice expressions. * * @module dice-expression */ module.exports = { /** * Creates a new addition expression. * * @param {module:dice-expression~Expression!} augendExpression - The * augend expression. * @param {module:dice-expression~Expression!} addendExpression - The * addend expression. * * @returns {module:dice-expression~AdditionExpression!} The new addition * expression. * * @throws {Error} If `augendExpression` is not defined or if * `addendExpression` is not defined. */ forAddition (augendExpression, addendExpression) { if (!augendExpression) { throw new Error('augend expression is not defined') } else if (!addendExpression) { throw new Error('addend expression is not defined') } /** * An expression that adds two expressions. * * @namespace AdditionExpression */ return { /** * The addend expression. * * @memberOf module:dice-expression~AdditionExpression * * @type {module:dice-expression~Expression!} */ addendExpression, /** * The augend expression. * * @memberOf module:dice-expression~AdditionExpression * * @type {module:dice-expression~Expression!} */ augendExpression, /** * Evaluates the expression. * * @memberOf module:dice-expression~AdditionExpression * * @returns {module:dice-expression-result~AdditionExpressionResult!} * The result of evaluating the expression. */ evaluate () { return diceExpressionResult.forAddition( augendExpression.evaluate(), addendExpression.evaluate() ) }, /** * The expression type identifier. * * @memberOf module:dice-expression~AdditionExpression * * @type {String!} */ typeId: diceExpressionTypeIds.ADDITION } }, /** * Creates a new array expression. * * @param {module:dice-expression~Expression[]!} expressions - The * expressions that are the array elements. * * @returns {module:dice-expression~ArrayExpression!} The new array * expression. * * @throws {Error} If `expressions` is not an array. */ forArray (expressions) { if (!_.isArray(expressions)) { throw new Error('expressions is not an array') } /** * An expression that acts as an array of expressions. * * @namespace ArrayExpression */ return { /** * Evaluates the expression. * * @memberOf module:dice-expression~ArrayExpression * * @returns {module:dice-expression-result~ArrayExpressionResult!} * The result of evaluating the expression. */ evaluate () { return diceExpressionResult.forArray(_.invoke(expressions, 'evaluate')) }, /** * The expressions that are the array elements. * * @memberOf module:dice-expression~ArrayExpression * * @type {module:dice-expression~Expression[]!} */ expressions, /** * The expression type identifier. * * @memberOf module:dice-expression~ArrayExpression * * @type {String!} */ typeId: diceExpressionTypeIds.ARRAY } }, /** * Creates a new constant expression. * * @param {Number!} constant - The constant. * * @returns {module:dice-expression~ConstantExpression!} The new constant * expression. * * @throws {Error} If `constant` is not a number. */ forConstant (constant) { if (!_.isNumber(constant)) { throw new Error('constant is not a number') } /** * An expression that represents a constant value. * * @namespace ConstantExpression */ return { /** * The constant associated with the expression. * * @memberOf module:dice-expression~ConstantExpression * * @type {Number!} */ constant, /** * Evaluates the expression. * * @memberOf module:dice-expression~ConstantExpression * * @returns {module:dice-expression-result~ConstantExpressionResult!} * The result of evaluating the expression. */ evaluate () { return diceExpressionResult.forConstant(constant) }, /** * The expression type identifier. * * @memberOf module:dice-expression~ConstantExpression * * @type {String!} */ typeId: diceExpressionTypeIds.CONSTANT } }, /** * Creates a new die expression. * * @param {module:dice-bag~Die!} die - The die. * * @returns {module:dice-expression~DieExpression!} The new die expression. * * @throws {Error} If `die` is not defined. */ forDie (die) { if (!die) { throw new Error('die is not defined') } /** * An expression that represents a die. * * @namespace DieExpression */ return { /** * The die associated with the expression. * * @memberOf module:dice-expression~DieExpression * * @type {module:dice-bag~Die!} */ die, /** * Evaluates the expression. * * @memberOf module:dice-expression~DieExpression * * @returns {module:dice-expression-result~DieExpressionResult!} * The result of evaluating the expression. */ evaluate () { return diceExpressionResult.forDie(die) }, /** * The expression type identifier. * * @memberOf module:dice-expression~DieExpression * * @type {String!} */ typeId: diceExpressionTypeIds.DIE } }, /** * Creates a new division expression. * * @param {module:dice-expression~Expression!} dividendExpression - The * dividend expression. * @param {module:dice-expression~Expression!} divisorExpression - The * divisor expression. * * @returns {module:dice-expression~DivisionExpression!} The new division * expression. * * @throws {Error} If `dividendExpression` is not defined or if * `divisorExpression` is not defined. */ forDivision (dividendExpression, divisorExpression) { if (!dividendExpression) { throw new Error('dividend expression is not defined') } else if (!divisorExpression) { throw new Error('divisor expression is not defined') } /** * An expression that divides two expressions. * * @namespace DivisionExpression */ return { /** * The dividend expression. * * @memberOf module:dice-expression~DivisionExpression * * @type {module:dice-expression~Expression!} */ dividendExpression, /** * The divisor expression. * * @memberOf module:dice-expression~DivisionExpression * * @type {module:dice-expression~Expression!} */ divisorExpression, /** * Evaluates the expression. * * @memberOf module:dice-expression~DivisionExpression * * @returns {module:dice-expression-result~DivisionExpressionResult!} * The result of evaluating the expression. */ evaluate () { return diceExpressionResult.forDivision( dividendExpression.evaluate(), divisorExpression.evaluate() ) }, /** * The expression type identifier. * * @memberOf module:dice-expression~DivisionExpression * * @type {String!} */ typeId: diceExpressionTypeIds.DIVISION } }, /** * Creates a new function call expression. * * @param {String!} name - The function name. * @param {Function!} func - The function. * @param {module:dice-expression~Expression[]!} argumentListExpressions - * The expressions that represent the arguments to the function call. * * @returns {module:dice-expression~FunctionCallExpression!} The new * function call expression. * * @throws {Error} If `name` is not a string, or if `func` is not a * function, or if `argumentListExpressions` is not an array. */ forFunctionCall (name, func, argumentListExpressions) { if (!_.isString(name)) { throw new Error('function name is not a string') } else if (!_.isFunction(func)) { throw new Error('function is not a function') } else if (!_.isArray(argumentListExpressions)) { throw new Error('function argument list expressions is not an array') } /** * An expression that calls a function. * * @namespace FunctionCallExpression */ return { /** * The expressions that represent the arguments to the function * call. * * @memberOf module:dice-expression~FunctionCallExpression * * @type {module:dice-expression~Expression[]!} */ argumentListExpressions, /** * Evaluates the expression. * * @memberOf module:dice-expression~FunctionCallExpression * * @returns {module:dice-expression-result~FunctionCallExpressionResult!} * The result of evaluating the expression. */ evaluate () { const argumentListExpressionResults = _.invoke(argumentListExpressions, 'evaluate') const argumentList = _.pluck(argumentListExpressionResults, 'value') const returnValue = func.apply(null, argumentList) return diceExpressionResult.forFunctionCall(returnValue, name, argumentListExpressionResults) }, /** * The function name. * * @memberOf module:dice-expression~FunctionCallExpression * * @type {String!} */ name, /** * The expression type identifier. * * @memberOf module:dice-expression~FunctionCallExpression * * @type {String!} */ typeId: diceExpressionTypeIds.FUNCTION_CALL } }, /** * Creates a new group expression. * * @param {module:dice-expression~Expression!} childExpression - The * expression that is grouped. * * @returns {module:dice-expression~GroupExpression!} The new group * expression. * * @throws {Error} If `childExpression` is not defined. */ forGroup (childExpression) { if (!childExpression) { throw new Error('child expression is not defined') } /** * An expression that groups another expression. * * @namespace GroupExpression */ return { /** * The expression that is grouped. * * @memberOf module:dice-expression~GroupExpression * * @type {module:dice-expression~Expression!} */ childExpression, /** * Evaluates the expression. * * @memberOf module:dice-expression~GroupExpression * * @returns {module:dice-expression-result~GroupExpressionResult!} * The result of evaluating the expression. */ evaluate () { return diceExpressionResult.forGroup(childExpression.evaluate()) }, /** * The expression type identifier. * * @memberOf module:dice-expression~GroupExpression * * @type {String!} */ typeId: diceExpressionTypeIds.GROUP } }, /** * Creates a new modulo expression. * * @param {module:dice-expression~Expression!} dividendExpression - The * dividend expression. * @param {module:dice-expression~Expression!} divisorExpression - The * divisor expression. * * @returns {module:dice-expression~ModuloExpression!} The new modulo * expression. * * @throws {Error} If `dividendExpression` is not defined or if * `divisorExpression` is not defined. */ forModulo (dividendExpression, divisorExpression) { if (!dividendExpression) { throw new Error('dividend expression is not defined') } else if (!divisorExpression) { throw new Error('divisor expression is not defined') } /** * An expression that modulos two expressions. * * @namespace ModuloExpression */ return { /** * The dividend expression. * * @memberOf module:dice-expression~ModuloExpression * * @type {module:dice-expression~Expression!} */ dividendExpression, /** * The divisor expression. * * @memberOf module:dice-expression~ModuloExpression * * @type {module:dice-expression~Expression!} */ divisorExpression, /** * Evaluates the expression. * * @memberOf module:dice-expression~ModuloExpression * * @returns {module:dice-expression-result~ModuloExpressionResult!} * The result of evaluating the expression. */ evaluate () { return diceExpressionResult.forModulo( dividendExpression.evaluate(), divisorExpression.evaluate() ) }, /** * The expression type identifier. * * @memberOf module:dice-expression~ModuloExpression * * @type {String!} */ typeId: diceExpressionTypeIds.MODULO } }, /** * Creates a new multiplication expression. * * @param {module:dice-expression~Expression!} multiplicandExpression - The * multiplicand expression. * @param {module:dice-expression~Expression!} multiplierExpression - The * multiplier expression. * * @returns {module:dice-expression~MultiplicationExpression!} The new * multiplication expression. * * @throws {Error} If `multiplicandExpression` is not defined or if * `multiplierExpression` is not defined. */ forMultiplication (multiplicandExpression, multiplierExpression) { if (!multiplicandExpression) { throw new Error('multiplicand expression is not defined') } else if (!multiplierExpression) { throw new Error('multiplier expression is not defined') } /** * An expression that multiplies two expressions. * * @namespace MultiplicationExpression */ return { /** * Evaluates the expression. * * @memberOf module:dice-expression~MultiplicationExpression * * @returns {module:dice-expression-result~MultiplicationExpressionResult!} * The result of evaluating the expression. */ evaluate () { return diceExpressionResult.forMultiplication( multiplicandExpression.evaluate(), multiplierExpression.evaluate() ) }, /** * The multiplicand expression. * * @memberOf module:dice-expression~MultiplicationExpression * * @type {module:dice-expression~Expression!} */ multiplicandExpression, /** * The multiplier expression. * * @memberOf module:dice-expression~MultiplicationExpression * * @type {module:dice-expression~Expression!} */ multiplierExpression, /** * The expression type identifier. * * @memberOf module:dice-expression~MultiplicationExpression * * @type {String!} */ typeId: diceExpressionTypeIds.MULTIPLICATION } }, /** * Creates a new negative expression. * * @param {module:dice-expression~Expression!} childExpression - The * expression to be negated. * * @returns {module:dice-expression~NegativeExpression!} The new negative * expression. * * @throws {Error} If `childExpression` is not defined. */ forNegative (childExpression) { if (!childExpression) { throw new Error('child expression is not defined') } /** * An expression that negates another expression. * * @namespace NegativeExpression */ return { /** * The expression to be negated. * * @memberOf module:dice-expression~NegativeExpression * * @type {module:dice-expression~Expression!} */ childExpression, /** * Evaluates the expression. * * @memberOf module:dice-expression~NegativeExpression * * @returns {module:dice-expression-result~NegativeExpressionResult!} * The result of evaluating the expression. */ evaluate () { return diceExpressionResult.forNegative(childExpression.evaluate()) }, /** * The expression type identifier. * * @memberOf module:dice-expression~NegativeExpression * * @type {String!} */ typeId: diceExpressionTypeIds.NEGATIVE } }, /** * Creates a new positive expression. * * @param {module:dice-expression~Expression!} childExpression - The * expression to be applied. * * @returns {module:dice-expression~PositiveExpression!} The new positive * expression. * * @throws {Error} If `childExpression` is not defined. */ forPositive (childExpression) { if (!childExpression) { throw new Error('child expression is not defined') } /** * An expression that applies another expression. * * @namespace PositiveExpression */ return { /** * The expression to be applied. * * @memberOf module:dice-expression~PositiveExpression * * @type {module:dice-expression~Expression!} */ childExpression, /** * Evaluates the expression. * * @memberOf module:dice-expression~PositiveExpression * * @returns {module:dice-expression-result~PositiveExpressionResult!} * The result of evaluating the expression. */ evaluate () { return diceExpressionResult.forPositive(childExpression.evaluate()) }, /** * The expression type identifier. * * @memberOf module:dice-expression~PositiveExpression * * @type {String!} */ typeId: diceExpressionTypeIds.POSITIVE } }, /** * Creates a new subtraction expression. * * @param {module:dice-expression~Expression!} minuendExpression - The * minuend expression. * @param {module:dice-expression~Expression!} subtrahendExpression - The * subtrahend expression. * * @returns {module:dice-expression~SubtractionExpression!} The new * subtraction expression. * * @throws {Error} If `minuendExpression` is not defined or if * `subtrahendExpression` is not defined. */ forSubtraction (minuendExpression, subtrahendExpression) { if (!minuendExpression) { throw new Error('minuend expression is not defined') } else if (!subtrahendExpression) { throw new Error('subtrahend expression is not defined') } /** * An expression that subtracts two expressions. * * @namespace SubtractionExpression */ return { /** * Evaluates the expression. * * @memberOf module:dice-expression~SubtractionExpression * * @returns {module:dice-expression-result~SubtractionExpressionResult!} * The result of evaluating the expression. */ evaluate () { return diceExpressionResult.forSubtraction( minuendExpression.evaluate(), subtrahendExpression.evaluate() ) }, /** * The minuend expression. * * @memberOf module:dice-expression~SubtractionExpression * * @type {module:dice-expression~Expression!} */ minuendExpression, /** * The subtrahend expression. * * @memberOf module:dice-expression~SubtractionExpression * * @type {module:dice-expression~Expression!} */ subtrahendExpression, /** * The expression type identifier. * * @memberOf module:dice-expression~SubtractionExpression * * @type {String!} */ typeId: diceExpressionTypeIds.SUBTRACTION } } }
ssoloff/dice-server-js
src/server/model/dice-expression.js
JavaScript
mit
20,703
// inheritientence!! function Pet() { this.animal = ""; this.name=""; this.setAnimal = function(newAnimal){ this.animal = newAnimal; } this.setName = function(newName){ this.name = newName; } } var myCat = new Pet(); myCat.setAnimal = "cat"; myCat.setName = "Sylvester"; function Dog(){ this.breed =""; this.setBread = function(newBreed){ this.breed = newBreed; } } Dog.prototype = new Pet(); // Now I can access the propertites and methods of Pet in addition to Dog var myDog = new Dog(); myDog.setName("Alan"); myDog.setBreed("Greyhound"); alert(myDog.name + "is a " myDog.breed);
brianlmosley/javascript-24
pet.js
JavaScript
mit
619
export const u1F443 = {"viewBox":"0 0 2600 2760.837","children":[{"name":"path","attribs":{"d":"M2043 2036q-41 85-119.5 119.5T1784 2190q-25 0-46-3.5t-39-8.5l-35-8q-16-4-30-4-47 0-130.5 53t-204.5 53q-70 0-119-16t-86-37l-64-37q-29-16-63-16-17 0-33 4l-35 8q-17 5-38 8.5t-46 3.5q-58 0-134.5-31.5t-121-118.5-44.5-195q0-66 28-141.5t74-155.5l67-117q27-46 50.5-107t48.5-135l55-160h-1q59-171 108-265.5T1094.5 603t204.5-66q98 0 200.5 63t160 174 131.5 343 124 314l18 29q55 86 103 191t48 197q0 103-41 188zm-128.5-319q-32.5-78-100.5-186l-17-30q-30-52-54.5-114.5T1692 1249l-56-163q-59-172-96-243.5T1438.5 725 1316 675l-16-1-16 1q-54 4-117.5 46t-103 112T963 1085l-55 163q-26 75-50.5 138T803 1501l-18 30-44 76q-37 63-63 127t-26 112q0 94 39.5 149t123.5 55q17 0 34-4l34-7 38-7q19-3 42-3 90 0 168 53t168 53 169-53 164-53q22 0 38.5 2t47.5 8l33 7q16 4 33 4 54 0 91-23t54.5-74.5T1947 1848t-32.5-131z"},"children":[]}]};
wmira/react-icons-kit
src/noto_emoji_regular/u1F443.js
JavaScript
mit
897
//= require fluent/admin/admin.js
LosYear/FluentCMS-Rails
app/assets/javascripts/fluent/admin.js
JavaScript
mit
33
'use strict' import ObjectUtils from 'es-common-core/object-utils'; import Asset from 'rpgmv-asset-manager-core/datas/asset'; import AssetFileDeserializer from 'rpgmv-asset-manager-core/datas/asset-file-deserializer'; /** * Asset Manager MV * アセットデシリアライザ * * @since 2016/01/03 * @author RaTTiE */ export default class AssetDeserializer { /** * オブジェクトのデシリアライズを行う。 * * @param data デシリアライズに使用するデータ。 * @return デシリアライズしたインスタンス。 */ static deserialize(data) { if (data == null) return null; var asset = new Asset(); var files = []; for (var i = 0; i < data.files.length; i++) { files.push(AssetFileDeserializer.deserialize(data.files[i])); } ObjectUtils.setFields(asset, { name: data.name, type: data.type, files: files, using: data.using, checked: data.checked, selected: data.selected }); return asset; } }
RaTTiE/AssetManagerMV
src/node_modules/rpgmv-asset-manager-core/datas/asset-deserializer.js
JavaScript
mit
984
// Use require('arpjs') if youre running this example elsewhere. var arp = require('../') // arp.setInterface('en0'); arp.send({ 'op': 'request', 'src_ip': '10.105.50.100', 'dst_ip': '10.105.50.1', 'src_mac': '8f:3f:20:33:54:44', 'dst_mac': 'ff:ff:ff:ff:ff:11' })
skepticfx/arpjs
examples/example.js
JavaScript
mit
274
class AddAktModalController{ constructor(API, $uibModal, $state,$timeout){ 'ngInject'; let vm=this; vm.API=API; vm.program=vm.resolve.program; vm.programs=vm.resolve.programs; vm.data={ program:vm.program.id, title:null, date:new Date() }; vm.dateOptions = { altInputFormats: ['yyyy-MM-dd', 'dd.MM.yyyy'], formatDay: 'dd', formatMonth: 'MM', formatYear: 'yyyy', minDate: new Date(), startingDay: 1 }; vm.date = { opened: false }; vm.openCalendar=()=>{ vm.date.opened=true; }; vm.close=()=>{ this.modalInstance.dismiss('cancel'); }; vm.add=()=>{ let calendar = this.API.all('akt'); calendar.post({ program:vm.data.program, title:vm.data.title, date:moment(vm.data.date).format('YYYY-MM-DD'), }).then((response) => { vm.success=true; $timeout( ()=>{ $state.reload(); }, 300); $timeout(()=> { vm.close(); }, 500); }, (response) => { vm.message=response.data.uniqemessage; vm.errors=response.data.errors; }); } // } $onInit(){ } } export const AddAktModalComponent = { templateUrl: './views/app/components/addAktModal/addAktModal.component.html', controller: AddAktModalController, controllerAs: 'vm', bindings: { modalInstance: "<", resolve: "<" } }
SovietBerkut/ADM
angular/app/components/addAktModal/addAktModal.component.js
JavaScript
mit
1,810