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
|
---|---|---|---|---|---|
'use strict';
module.exports = function(sequelize, DataTypes) {
var GuardianMetaUpdateCheckIn = sequelize.define('GuardianMetaUpdateCheckIn', {
}, {
classMethods: {
associate: function(models) {
GuardianMetaUpdateCheckIn.belongsTo(models.Guardian, {as: 'Guardian'});
GuardianMetaUpdateCheckIn.belongsTo(models.GuardianSoftwareVersion, {as: 'Version'});
}
},
tableName: "GuardianMetaUpdateCheckIns"
});
return GuardianMetaUpdateCheckIn;
}; | tanapop/rfcx-api | models/guardian-meta/guardian-meta-updatecheckin.js | JavaScript | apache-2.0 | 487 |
/**
* Created by mdylag on 17/03/15.
*/
function callCallback(callback) {
console.log("Function callCallback");
if (callback && typeof callback === "function") {
callback();
}
}
function myCallBack() {
console.log("Function myCallBack");
}
writeCode(myCallBack);
| ms-courses/JavaScriptAdvance | functions/callback.js | JavaScript | apache-2.0 | 292 |
const root = '../../';
jest.useFakeTimers();
describe('call-function plugin', function(){
beforeEach(function(){
require(root + 'jspsych.js');
require(root + 'plugins/jspsych-call-function.js');
});
test('loads correctly', function(){
expect(typeof window.jsPsych.plugins['call-function']).not.toBe('undefined');
});
// SKIP FOR NOW
test.skip('calls function', function(){
var myFunc = function() {
return 1;
}
var trial = {
type: 'call-function',
func: myFunc
}
jsPsych.init({
timeline: [trial]
});
expect(jsPsych.getDisplayElement().innerHTML).toBe("");
});
});
| JATOS/JATOS_examples | study_assets_root/clock_drawing/jsPsych/tests/plugins/plugin-call-function.test.js | JavaScript | apache-2.0 | 612 |
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import 'style/exit.scss'
import {GA} from 'utils/GA'
import {isMobile, is360} from 'utils/Helpers'
export class ExitButton {
constructor(){
const element = this.element = document.querySelector('#exitButton')
element.addEventListener('click', () => {
GA('ui', 'click', 'exit')
window.location.reload()
})
const scene = document.querySelector('a-scene')
scene.addEventListener('enter-360', () => this.show())
scene.addEventListener('enter-vr', () => this.show())
scene.addEventListener('exit-vr', () => this.hide())
}
show(){
setTimeout(() => {
if (!isMobile() || (isMobile() && is360())){
this.element.classList.add('visible')
}
}, 10)
}
hide(){
window.location.reload()
this.element.classList.remove('visible')
}
} | googlecreativelab/inside-music | src/interface/ExitButton.js | JavaScript | apache-2.0 | 1,360 |
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
'use strict';
angular.module('${artifactId}App').factory('Applications', function (Restangular) {
return Restangular.service('applications');
});
| meruvian/yama-archetypes | starter/src/main/resources/archetype-resources/webapp/app/backend/admin/application/application.service.js | JavaScript | apache-2.0 | 234 |
/**
* Copyright 2021 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as Preact from '../../../src/preact';
import {Option, Selector} from './component';
import {PreactBaseElement} from '../../../src/preact/base-element';
import {
closestAncestorElementBySelector,
createElementWithAttributes,
toggleAttribute,
tryFocus,
} from '../../../src/dom';
import {devAssert} from '../../../src/log';
import {dict} from '../../../src/core/types/object';
import {toArray} from '../../../src/core/types/array';
import {useCallback, useLayoutEffect, useRef} from '../../../src/preact';
export class BaseElement extends PreactBaseElement {
/** @override */
init() {
const {element} = this;
this.optionState = [];
// Listen for mutations
const mu = new MutationObserver(() => {
if (this.isExpectedMutation) {
this.isExpectedMutation = false;
return;
}
const {children, options} = getOptions(element, mu);
this.optionState = options;
this.mutateProps({children, options});
});
mu.observe(element, {
attributeFilter: ['option', 'selected', 'disabled'],
childList: true,
subtree: true,
});
// TODO(wg-bento): This hack is in place to prevent doubly rendering.
// See https://github.com/ampproject/amp-react-prototype/issues/40.
const onChangeHandler = (event) => {
const {option, value} = event;
this.triggerEvent(
this.element,
'select',
dict({
'targetOption': option,
'selectedOptions': value,
})
);
this.isExpectedMutation = true;
this.mutateProps(dict({'value': value}));
};
// Return props
const {children, value, options} = getOptions(element, mu);
this.optionState = options;
return dict({
'as': SelectorShim,
'shimDomElement': element,
'children': children,
'value': value,
'options': options,
'onChange': onChangeHandler,
});
}
}
/**
* @param {!Element} element
* @param {MutationObserver} mu
* @return {!JsonObject}
*/
function getOptions(element, mu) {
const children = [];
const options = [];
const value = [];
const optionChildren = toArray(element.querySelectorAll('[option]'));
optionChildren
// Skip options that are themselves within an option
.filter(
(el) =>
!closestAncestorElementBySelector(
devAssert(el.parentElement?.nodeType == 1, 'Expected an element'),
'[option]'
)
)
.forEach((child, index) => {
const option = child.getAttribute('option') || index.toString();
const selected = child.hasAttribute('selected');
const disabled = child.hasAttribute('disabled');
const tabIndex = child.getAttribute('tabindex');
const props = {
as: OptionShim,
option,
disabled,
index,
onFocus: () => tryFocus(child),
role: child.getAttribute('role') || 'option',
shimDomElement: child,
// TODO(wg-bento): This implementation causes infinite loops on DOM mutation.
// See https://github.com/ampproject/amp-react-prototype/issues/40.
postRender: () => {
// Skip mutations to avoid cycles.
mu.takeRecords();
},
selected,
tabIndex,
};
if (selected) {
value.push(option);
}
const optionChild = <Option {...props} />;
options.push(option);
children.push(optionChild);
});
return {value, children, options};
}
/**
* @param {!SelectorDef.OptionProps} props
* @return {PreactDef.Renderable}
*/
export function OptionShim({
shimDomElement,
onClick,
onFocus,
onKeyDown,
selected,
disabled,
role = 'option',
tabIndex,
}) {
const syncEvent = useCallback(
(type, handler) => {
if (!handler) {
return;
}
shimDomElement.addEventListener(type, handler);
return () => shimDomElement.removeEventListener(type, devAssert(handler));
},
[shimDomElement]
);
useLayoutEffect(() => syncEvent('click', onClick), [onClick, syncEvent]);
useLayoutEffect(() => syncEvent('focus', onFocus), [onFocus, syncEvent]);
useLayoutEffect(() => syncEvent('keydown', onKeyDown), [
onKeyDown,
syncEvent,
]);
useLayoutEffect(() => {
toggleAttribute(shimDomElement, 'selected', !!selected);
}, [shimDomElement, selected]);
useLayoutEffect(() => {
toggleAttribute(shimDomElement, 'disabled', !!disabled);
shimDomElement.setAttribute('aria-disabled', !!disabled);
}, [shimDomElement, disabled]);
useLayoutEffect(() => {
shimDomElement.setAttribute('role', role);
}, [shimDomElement, role]);
useLayoutEffect(() => {
if (tabIndex != undefined) {
shimDomElement.tabIndex = tabIndex;
}
}, [shimDomElement, tabIndex]);
return <div></div>;
}
/**
* @param {!SelectorDef.Props} props
* @return {PreactDef.Renderable}
*/
function SelectorShim({
shimDomElement,
children,
form,
multiple,
name,
disabled,
onKeyDown,
role = 'listbox',
tabIndex,
value,
}) {
const input = useRef(null);
if (!input.current) {
input.current = createElementWithAttributes(
shimDomElement.ownerDocument,
'input',
{
'hidden': '',
}
);
}
useLayoutEffect(() => {
const el = input.current;
shimDomElement.insertBefore(el, shimDomElement.firstChild);
return () => shimDomElement.removeChild(el);
}, [shimDomElement]);
const syncAttr = useCallback((attr, value) => {
if (value) {
input.current.setAttribute(attr, value);
} else {
input.current.removeAttribute(attr);
}
}, []);
useLayoutEffect(() => syncAttr('form', form), [form, syncAttr]);
useLayoutEffect(() => syncAttr('name', name), [name, syncAttr]);
useLayoutEffect(() => syncAttr('value', value), [value, syncAttr]);
useLayoutEffect(() => {
if (!onKeyDown) {
return;
}
shimDomElement.addEventListener('keydown', onKeyDown);
return () =>
shimDomElement.removeEventListener('keydown', devAssert(onKeyDown));
}, [shimDomElement, onKeyDown]);
useLayoutEffect(() => {
toggleAttribute(shimDomElement, 'multiple', !!multiple);
shimDomElement.setAttribute('aria-multiselectable', !!multiple);
}, [shimDomElement, multiple]);
useLayoutEffect(() => {
toggleAttribute(shimDomElement, 'disabled', !!disabled);
shimDomElement.setAttribute('aria-disabled', !!disabled);
}, [shimDomElement, disabled]);
useLayoutEffect(() => {
shimDomElement.setAttribute('role', role);
}, [shimDomElement, role]);
useLayoutEffect(() => {
if (tabIndex != undefined) {
shimDomElement.tabIndex = tabIndex;
}
}, [shimDomElement, tabIndex]);
return <div children={children} />;
}
/** @override */
BaseElement['Component'] = Selector;
/** @override */
BaseElement['detached'] = true;
/** @override */
BaseElement['props'] = {
'disabled': {attr: 'disabled', type: 'boolean'},
'form': {attr: 'form'},
'multiple': {attr: 'multiple', type: 'boolean'},
'name': {attr: 'name'},
'role': {attr: 'role'},
'tabIndex': {attr: 'tabindex'},
'keyboardSelectMode': {attr: 'keyboard-select-mode', media: true},
};
| nexxtv/amphtml | extensions/amp-selector/1.0/base-element.js | JavaScript | apache-2.0 | 7,802 |
/**
* @licstart The following is the entire license notice for the
* Javascript code in this page
*
* Copyright 2021 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @licend The above is the entire license notice for the
* Javascript code in this page
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.XFAFactory = void 0;
var _xfa_object = require("./xfa_object.js");
var _bind = require("./bind.js");
var _data = require("./data.js");
var _fonts = require("./fonts.js");
var _utils = require("./utils.js");
var _util = require("../../shared/util.js");
var _parser = require("./parser.js");
var _xhtml = require("./xhtml.js");
class XFAFactory {
constructor(data) {
try {
this.root = new _parser.XFAParser().parse(XFAFactory._createDocument(data));
const binder = new _bind.Binder(this.root);
this.form = binder.bind();
this.dataHandler = new _data.DataHandler(this.root, binder.getData());
this.form[_xfa_object.$globalData].template = this.form;
} catch (e) {
(0, _util.warn)(`XFA - an error occurred during parsing and binding: ${e}`);
}
}
isValid() {
return this.root && this.form;
}
_createPagesHelper() {
const iterator = this.form[_xfa_object.$toPages]();
return new Promise((resolve, reject) => {
const nextIteration = () => {
try {
const value = iterator.next();
if (value.done) {
resolve(value.value);
} else {
setTimeout(nextIteration, 0);
}
} catch (e) {
reject(e);
}
};
setTimeout(nextIteration, 0);
});
}
async _createPages() {
try {
this.pages = await this._createPagesHelper();
this.dims = this.pages.children.map(c => {
const {
width,
height
} = c.attributes.style;
return [0, 0, parseInt(width), parseInt(height)];
});
} catch (e) {
(0, _util.warn)(`XFA - an error occurred during layout: ${e}`);
}
}
getBoundingBox(pageIndex) {
return this.dims[pageIndex];
}
async getNumPages() {
if (!this.pages) {
await this._createPages();
}
return this.dims.length;
}
setImages(images) {
this.form[_xfa_object.$globalData].images = images;
}
setFonts(fonts) {
this.form[_xfa_object.$globalData].fontFinder = new _fonts.FontFinder(fonts);
const missingFonts = [];
for (let typeface of this.form[_xfa_object.$globalData].usedTypefaces) {
typeface = (0, _utils.stripQuotes)(typeface);
const font = this.form[_xfa_object.$globalData].fontFinder.find(typeface);
if (!font) {
missingFonts.push(typeface);
}
}
if (missingFonts.length > 0) {
return missingFonts;
}
return null;
}
appendFonts(fonts, reallyMissingFonts) {
this.form[_xfa_object.$globalData].fontFinder.add(fonts, reallyMissingFonts);
}
async getPages() {
if (!this.pages) {
await this._createPages();
}
const pages = this.pages;
this.pages = null;
return pages;
}
serializeData(storage) {
return this.dataHandler.serialize(storage);
}
static _createDocument(data) {
if (!data["/xdp:xdp"]) {
return data["xdp:xdp"];
}
return Object.values(data).join("");
}
static getRichTextAsHtml(rc) {
if (!rc || typeof rc !== "string") {
return null;
}
try {
let root = new _parser.XFAParser(_xhtml.XhtmlNamespace, true).parse(rc);
if (!["body", "xhtml"].includes(root[_xfa_object.$nodeName])) {
const newRoot = _xhtml.XhtmlNamespace.body({});
newRoot[_xfa_object.$appendChild](root);
root = newRoot;
}
const result = root[_xfa_object.$toHTML]();
if (!result.success) {
return null;
}
const {
html
} = result;
const {
attributes
} = html;
if (attributes) {
if (attributes.class) {
attributes.class = attributes.class.filter(attr => !attr.startsWith("xfa"));
}
attributes.dir = "auto";
}
return {
html,
str: root[_xfa_object.$text]()
};
} catch (e) {
(0, _util.warn)(`XFA - an error occurred during parsing of rich text: ${e}`);
}
return null;
}
}
exports.XFAFactory = XFAFactory; | mozilla/pdfjs-dist | lib/core/xfa/factory.js | JavaScript | apache-2.0 | 4,930 |
//// [functionOverloads2.js]
function foo(bar) {
return bar;
}
;
var x = foo(true);
| fdecampredon/jsx-typescript-old-version | tests/baselines/reference/functionOverloads2.js | JavaScript | apache-2.0 | 94 |
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
closestByTag,
closestBySelector,
scopedQuerySelector,
} from '../../../src/dom';
import {dev, user} from '../../../src/log';
import {resourcesForDoc} from '../../../src/resources';
import {getParentWindowFrameElement} from '../../../src/service';
import {timerFor} from '../../../src/timer';
import {isFiniteNumber} from '../../../src/types';
import {viewportForDoc} from '../../../src/viewport';
import {viewerForDoc} from '../../../src/viewer';
import {VisibilityState} from '../../../src/visibility-state';
import {startsWith} from '../../../src/string';
import {DEFAULT_THRESHOLD} from '../../../src/intersection-observer-polyfill';
/** @const {number} */
const LISTENER_INITIAL_RUN_DELAY_ = 20;
// Variables that are passed to the callback.
const MAX_CONTINUOUS_TIME = 'maxContinuousVisibleTime';
const TOTAL_VISIBLE_TIME = 'totalVisibleTime';
const FIRST_SEEN_TIME = 'firstSeenTime';
const LAST_SEEN_TIME = 'lastSeenTime';
const FIRST_VISIBLE_TIME = 'fistVisibleTime';
const LAST_VISIBLE_TIME = 'lastVisibleTime';
const MIN_VISIBLE = 'minVisiblePercentage';
const MAX_VISIBLE = 'maxVisiblePercentage';
const ELEMENT_X = 'elementX';
const ELEMENT_Y = 'elementY';
const ELEMENT_WIDTH = 'elementWidth';
const ELEMENT_HEIGHT = 'elementHeight';
const TOTAL_TIME = 'totalTime';
const LOAD_TIME_VISIBILITY = 'loadTimeVisibility';
const BACKGROUNDED = 'backgrounded';
const BACKGROUNDED_AT_START = 'backgroundedAtStart';
// Variables that are not exposed outside this class.
const CONTINUOUS_TIME = 'cT';
const LAST_UPDATE = 'lU';
const IN_VIEWPORT = 'iV';
const TIME_LOADED = 'tL';
const SCHEDULED_RUN_ID = 'schId';
const LAST_CHANGE_ENTRY = 'lCE';
// Keys used in VisibilitySpec
const CONTINUOUS_TIME_MAX = 'continuousTimeMax';
const CONTINUOUS_TIME_MIN = 'continuousTimeMin';
const TOTAL_TIME_MAX = 'totalTimeMax';
const TOTAL_TIME_MIN = 'totalTimeMin';
const VISIBLE_PERCENTAGE_MIN = 'visiblePercentageMin';
const VISIBLE_PERCENTAGE_MAX = 'visiblePercentageMax';
const TAG_ = 'Analytics.Visibility';
/**
* Checks if the value is undefined or positive number like.
* "", 1, 0, undefined, 100, 101 are positive. -1, NaN are not.
*
* Visible for testing.
*
* @param {number} num The number to verify.
* @return {boolean}
* @private
*/
export function isPositiveNumber_(num) {
return num === undefined || (typeof num == 'number' && Math.sign(num) >= 0);
}
/**
* Checks if the value is undefined or a number between 0 and 100.
* "", 1, 0, undefined, 100 return true. -1, NaN and 101 return false.
*
* Visible for testing.
*
* @param {number} num The number to verify.
* @return {boolean}
*/
export function isValidPercentage_(num) {
return num === undefined ||
(typeof num == 'number' && Math.sign(num) >= 0 && num <= 100);
}
/**
* Checks and outputs information about visibilitySpecValidation.
* @param {!JSONType} config Configuration for instrumentation.
* @return {boolean} True if the spec is valid.
* @private
*/
export function isVisibilitySpecValid(config) {
if (!config['visibilitySpec']) {
return true;
}
const spec = config['visibilitySpec'];
const selector = spec['selector'];
if (!selector || (!startsWith(selector, '#') &&
!startsWith(selector, 'amp-') &&
selector != ':root' &&
selector != ':host')) {
user().error(TAG_, 'Visibility spec requires an id selector, a tag ' +
'name starting with "amp-" or ":root"');
return false;
}
const ctMax = spec[CONTINUOUS_TIME_MAX];
const ctMin = spec[CONTINUOUS_TIME_MIN];
const ttMax = spec[TOTAL_TIME_MAX];
const ttMin = spec[TOTAL_TIME_MIN];
if (!isPositiveNumber_(ctMin) || !isPositiveNumber_(ctMax) ||
!isPositiveNumber_(ttMin) || !isPositiveNumber_(ttMax)) {
user().error(TAG_,
'Timing conditions should be positive integers when specified.');
return false;
}
if (ctMax < ctMin || ttMax < ttMin) {
user().warn('AMP-ANALYTICS', 'Max value in timing conditions should be ' +
'more than the min value.');
return false;
}
if (!isValidPercentage_(spec[VISIBLE_PERCENTAGE_MAX]) ||
!isValidPercentage_(spec[VISIBLE_PERCENTAGE_MIN])) {
user().error(TAG_,
'visiblePercentage conditions should be between 0 and 100.');
return false;
}
if (spec[VISIBLE_PERCENTAGE_MAX] < spec[VISIBLE_PERCENTAGE_MIN]) {
user().error(TAG_, 'visiblePercentageMax should be greater than ' +
'visiblePercentageMin');
return false;
}
return true;
}
/**
* Returns the element that matches the selector. If the selector is an
* id, the element with that id is returned. If the selector is a tag name, an
* ancestor of the analytics element with that tag name is returned.
*
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc.
* @param {string} selector The selector for the element to track.
* @param {!Element} analyticsEl Element whose ancestors to search.
* @param {!String} selectionMethod The method to use to find the element.
* @return {?Element} Element corresponding to the selector if found.
*/
export function getElement(ampdoc, selector, analyticsEl, selectionMethod) {
if (!analyticsEl) {
return null;
}
let foundEl;
const friendlyFrame = getParentWindowFrameElement(analyticsEl, ampdoc.win);
// Special case for root selector.
if (selector == ':host' || selector == ':root') {
// TODO(dvoytenko, #6794): Remove old `-amp-element` form after the new
// form is in PROD for 1-2 weeks.
foundEl = friendlyFrame ?
closestBySelector(
friendlyFrame, '.-amp-element,.i-amphtml-element') : null;
} else if (selectionMethod == 'closest') {
// Only tag names are supported currently.
foundEl = closestByTag(analyticsEl, selector);
} else if (selectionMethod == 'scope') {
foundEl = scopedQuerySelector(
dev().assertElement(analyticsEl.parentElement), selector);
} else if (selector[0] == '#') {
const containerDoc = friendlyFrame ? analyticsEl.ownerDocument : ampdoc;
foundEl = containerDoc.getElementById(selector.slice(1));
}
if (foundEl) {
// Restrict result to be contained by ampdoc.
const isContainedInDoc = ampdoc.contains(friendlyFrame || foundEl);
if (isContainedInDoc) {
return foundEl;
}
}
return null;
}
/**
* @typedef {{
* state: !Object,
* config: !Object,
* callback: function(!Object),
* shouldBeVisible: boolean,
* }}
*/
let VisibilityListenerDef;
/**
* Allows tracking of AMP elements in the viewport.
*
* This class allows a caller to specify conditions to evaluate when an element
* is in viewport and for how long. If the conditions are satisfied, a provided
* callback is called.
*/
export class Visibility {
/** @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc */
constructor(ampdoc) {
/** @const {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc */
this.ampdoc = ampdoc;
/**
* key: resource id.
* value: [VisibilityListenerDef]
* @type {!Object<!Array<VisibilityListenerDef>>}
* @private
*/
this.listeners_ = Object.create(null);
/** @const {!../../../src/service/timer-impl.Timer} */
this.timer_ = timerFor(this.ampdoc.win);
/** @private {Array<!../../../src/service/resource.Resource>} */
this.resources_ = [];
/** @private @const {function()} */
this.boundScrollListener_ = this.scrollListener_.bind(this);
/** @private @const {function()} */
this.boundVisibilityListener_ = this.visibilityListener_.bind(this);
/** @private {boolean} */
this.scrollListenerRegistered_ = false;
/** @private {boolean} */
this.visibilityListenerRegistered_ = false;
/** @private {!../../../src/service/resources-impl.Resources} */
this.resourcesService_ = resourcesForDoc(this.ampdoc);
/** @private {number|string|null} */
this.scheduledRunId_ = null;
/** @private {number} Amount of time to wait for next calculation. */
this.timeToWait_ = Infinity;
/** @private {boolean} */
this.scheduledLoadedPromises_ = false;
/** @private @const {!../../../src/service/viewer-impl.Viewer} */
this.viewer_ = viewerForDoc(this.ampdoc);
/** @private {boolean} */
this.backgroundedAtStart_ = !this.viewer_.isVisible();
/** @private {boolean} */
this.backgrounded_ = this.backgroundedAtStart_;
}
/** @private */
registerForVisibilityEvents_() {
if (!this.visibilityListenerRegistered_) {
this.viewer_.onVisibilityChanged(this.boundVisibilityListener_);
this.visibilityListenerRegistered_ = true;
this.visibilityListener_();
}
}
/** @private */
registerForViewportEvents_() {
if (!this.scrollListenerRegistered_) {
const viewport = viewportForDoc(this.ampdoc);
// Currently unlistens are not being used. In the event that no resources
// are actively being monitored, the scrollListener should be very cheap.
viewport.onScroll(this.boundScrollListener_);
viewport.onChanged(this.boundScrollListener_);
this.scrollListenerRegistered_ = true;
}
}
/**
* @param {!Object} config
* @param {function(!Object)} callback
* @param {boolean} shouldBeVisible True if the element should be visible
* when callback is called. False otherwise.
* @param {!Element} analyticsElement The amp-analytics element that the
* config is associated with.
*/
listenOnce(config, callback, shouldBeVisible, analyticsElement) {
const selector = config['selector'];
const element = user().assertElement(
getElement(this.ampdoc, selector,
dev().assertElement(analyticsElement),
config['selectionMethod']),
'Element not found for visibilitySpec: ' + selector);
const resource =
this.resourcesService_.getResourceForElementOptional(element);
user().assert(
resource, 'Visibility tracking not supported on element: ', element);
this.registerForViewportEvents_();
this.registerForVisibilityEvents_();
const resId = resource.getId();
this.listeners_[resId] = (this.listeners_[resId] || []);
const state = {};
state[TIME_LOADED] = Date.now();
this.listeners_[resId].push({config, callback, state, shouldBeVisible});
this.resources_.push(resource);
if (this.scheduledRunId_ === null) {
this.scheduledRunId_ = this.timer_.delay(() => {
this.scrollListener_();
}, LISTENER_INITIAL_RUN_DELAY_);
}
}
/**
* @param {!Object} config
* @param {function(!Object)} callback
* @param {boolean} shouldBeVisible True if the element should be visible
* when callback is called. False otherwise.
* @param {!Element} analyticsElement The amp-analytics element that the
* config is associated with.
*/
listenOnceV2(config, callback, shouldBeVisible, analyticsElement) {
const selector = config['selector'];
const element = user().assertElement(
getElement(this.ampdoc, selector,
dev().assertElement(analyticsElement),
config['selectionMethod']),
'Element not found for visibilitySpec: ' + selector);
const resource =
this.resourcesService_.getResourceForElementOptional(element);
user().assert(
resource, 'Visibility tracking not supported on element: ', element);
if (!this.intersectionObserver_) {
const onIntersectionChange = this.onIntersectionChange_.bind(this);
/** @private {!IntersectionObserver} */
this.intersectionObserver_ =
// TODO: polyfill IntersectionObserver
new this.ampdoc.win.IntersectionObserver(entries => {
entries.forEach(onIntersectionChange);
}, {threshold: DEFAULT_THRESHOLD});
}
// Visible trigger
resource.loadedOnce().then(() => {
this.intersectionObserver_.observe(element);
const resId = resource.getId();
this.listeners_[resId] = (this.listeners_[resId] || []);
const state = {};
state[TIME_LOADED] = Date.now();
this.listeners_[resId].push({config, callback, state, shouldBeVisible});
this.resources_.push(resource);
});
// Hidden trigger
if (!shouldBeVisible && !this.visibilityListenerRegistered_) {
this.viewer_.onVisibilityChanged(() => {
if (!this.viewer_.isVisible()) {
this.onDocumentHidden_();
}
});
this.visibilityListenerRegistered_ = true;
}
}
/** @private */
onIntersectionChange_(change) {
const resource =
this.resourcesService_.getResourceForElement(change.target);
const listeners = this.listeners_[resource.getId()];
const visible = change.intersectionRatio * 100;
for (let c = listeners.length - 1; c >= 0; c--) {
const listener = listeners[c];
const shouldBeVisible = !!listener.shouldBeVisible;
const config = listener.config;
const state = listener.state;
state[LAST_CHANGE_ENTRY] = change;
// Update states and check if all conditions are satisfied
const conditionsMet =
this.updateCounters_(visible, listener, shouldBeVisible);
if (!shouldBeVisible) {
// For "hidden" trigger, only update state, don't trigger.
continue;
}
if (conditionsMet) {
if (state[SCHEDULED_RUN_ID]) {
this.timer_.cancel(state[SCHEDULED_RUN_ID]);
state[SCHEDULED_RUN_ID] = null;
}
this.prepareStateForCallback_(state, resource.getLayoutBox());
listener.callback(state);
listeners.splice(c, 1);
} else if (state[IN_VIEWPORT] && !state[SCHEDULED_RUN_ID]) {
// There is unmet duration condition, schedule a check
const timeToWait = this.computeTimeToWait_(state, config);
if (timeToWait <= 0) {
continue;
}
state[SCHEDULED_RUN_ID] = this.timer_.delay(() => {
dev().assert(state[IN_VIEWPORT], 'should have been in viewport');
const lastChange = state[LAST_CHANGE_ENTRY];
if (this.updateCounters_(
lastChange.intersectionRatio * 100,
listener, /* shouldBeVisible */ true)) {
this.prepareStateForCallback_(state, resource.getLayoutBox());
listener.callback(state);
listeners.splice(listeners.indexOf(listener), 1);
}
}, timeToWait);
} else if (!state[IN_VIEWPORT] && state[SCHEDULED_RUN_ID]) {
this.timer_.cancel(state[SCHEDULED_RUN_ID]);
state[SCHEDULED_RUN_ID] = null;
}
}
// Remove target that have no listeners.
if (listeners.length == 0) {
this.intersectionObserver_.unobserve(change.target);
}
}
/** @private */
onDocumentHidden_() {
for (let i = 0; i < this.resources_.length; i++) {
const resource = this.resources_[i];
if (!resource.hasLoadedOnce()) {
continue;
}
const listeners = this.listeners_[resource.getId()];
for (let j = listeners.length - 1; j >= 0; j--) {
const listener = listeners[j];
if (listener.shouldBeVisible) {
continue;
}
const state = listener.state;
const lastChange = state[LAST_CHANGE_ENTRY];
const lastVisible = lastChange ? lastChange.intersectionRatio * 100 : 0;
if (this.updateCounters_(
lastVisible, listener, /* shouldBeVisible */ false)) {
this.prepareStateForCallback_(state, resource.getLayoutBox());
listener.callback(state);
listeners.splice(j, 1);
}
}
}
}
/** @private */
visibilityListener_() {
const state = this.viewer_.getVisibilityState();
if (state == VisibilityState.HIDDEN || state == VisibilityState.PAUSED ||
state == VisibilityState.INACTIVE) {
this.backgrounded_ = true;
}
this.scrollListener_();
}
/** @private */
scrollListener_() {
if (this.scheduledRunId_ != null) {
this.timer_.cancel(this.scheduledRunId_);
this.scheduledRunId_ = null;
}
const loadedPromises = [];
for (let r = this.resources_.length - 1; r >= 0; r--) {
const res = this.resources_[r];
if (!res.hasLoadedOnce()) {
loadedPromises.push(res.loadedOnce());
continue;
}
const change = res.element.getIntersectionChangeEntry();
const visible = !isFiniteNumber(change.intersectionRatio) ? 0
: change.intersectionRatio * 100;
const listeners = this.listeners_[res.getId()];
for (let c = listeners.length - 1; c >= 0; c--) {
const shouldBeVisible = !!listeners[c]['shouldBeVisible'];
if (this.updateCounters_(visible, listeners[c], shouldBeVisible) &&
this.viewer_.isVisible() == shouldBeVisible) {
this.prepareStateForCallback_(
listeners[c]['state'], res.getLayoutBox());
listeners[c].callback(listeners[c]['state']);
listeners.splice(c, 1);
} else {
this.computeTimeToWait_(
listeners[c]['state'], listeners[c]['config']);
}
}
// Remove resources that have no listeners.
if (listeners.length == 0) {
this.resources_.splice(r, 1);
}
}
// Schedule a calculation for the time when one of the conditions is
// expected to be satisfied.
if (this.scheduledRunId_ === null &&
this.timeToWait_ < Infinity && this.timeToWait_ > 0) {
this.scheduledRunId_ = this.timer_.delay(() => {
this.scrollListener_();
}, this.timeToWait_);
}
// Schedule a calculation for when a resource gets loaded.
if (loadedPromises.length > 0 && !this.scheduledLoadedPromises_) {
Promise.race(loadedPromises).then(() => {
this.scheduledLoadedPromises_ = false;
this.scrollListener_();
});
this.scheduledLoadedPromises_ = true;
}
}
/**
* Updates counters for a given listener.
* @param {number} visible Percentage of element visible in viewport.
* @param {Object<string,Object>} listener The listener whose counters need
* updating.
* @param {boolean} triggerType True if element should be visible.
* False otherwise.
* @return {boolean} true if all visibility conditions are satisfied
* @private
*/
updateCounters_(visible, listener, triggerType) {
const config = listener['config'];
const state = listener['state'] || {};
if (visible > 0) {
const timeElapsed = Date.now() - state[TIME_LOADED];
state[FIRST_SEEN_TIME] = state[FIRST_SEEN_TIME] || timeElapsed;
state[LAST_SEEN_TIME] = timeElapsed;
// Consider it as load time visibility if this happens within 300ms of
// page load.
if (state[LOAD_TIME_VISIBILITY] == undefined && timeElapsed < 300) {
state[LOAD_TIME_VISIBILITY] = visible;
}
}
const wasInViewport = state[IN_VIEWPORT];
const timeSinceLastUpdate = Date.now() - state[LAST_UPDATE];
state[IN_VIEWPORT] = this.isInViewport_(visible,
config[VISIBLE_PERCENTAGE_MIN], config[VISIBLE_PERCENTAGE_MAX]);
if (state[IN_VIEWPORT] && wasInViewport) {
// Keep counting.
this.setState_(state, visible, timeSinceLastUpdate);
} else if (!state[IN_VIEWPORT] && wasInViewport) {
// The resource went out of view. Do final calculations and reset state.
dev().assert(state[LAST_UPDATE] > 0, 'lastUpdated time in weird state.');
state[MAX_CONTINUOUS_TIME] = Math.max(state[MAX_CONTINUOUS_TIME],
state[CONTINUOUS_TIME] + timeSinceLastUpdate);
state[LAST_UPDATE] = -1;
state[TOTAL_VISIBLE_TIME] += timeSinceLastUpdate;
state[CONTINUOUS_TIME] = 0; // Clear only after max is calculated above.
state[LAST_VISIBLE_TIME] = Date.now() - state[TIME_LOADED];
} else if (state[IN_VIEWPORT] && !wasInViewport) {
// The resource came into view. start counting.
dev().assert(state[LAST_UPDATE] == undefined ||
state[LAST_UPDATE] == -1, 'lastUpdated time in weird state.');
state[FIRST_VISIBLE_TIME] = state[FIRST_VISIBLE_TIME] ||
Date.now() - state[TIME_LOADED];
this.setState_(state, visible, 0);
}
listener['state'] = state;
return ((triggerType && state[IN_VIEWPORT]) || !triggerType) &&
(config[TOTAL_TIME_MIN] === undefined ||
state[TOTAL_VISIBLE_TIME] >= config[TOTAL_TIME_MIN]) &&
(config[TOTAL_TIME_MAX] === undefined ||
state[TOTAL_VISIBLE_TIME] <= config[TOTAL_TIME_MAX]) &&
(config[CONTINUOUS_TIME_MIN] === undefined ||
(state[MAX_CONTINUOUS_TIME] || 0) >= config[CONTINUOUS_TIME_MIN]) &&
(config[CONTINUOUS_TIME_MAX] === undefined ||
(state[MAX_CONTINUOUS_TIME] || 0) <= config[CONTINUOUS_TIME_MAX]);
}
/**
* @param {!Object} state
* @param {!Object} config
* @return {number}
* @private
*/
computeTimeToWait_(state, config) {
const waitForContinuousTime =
config[CONTINUOUS_TIME_MIN] > state[CONTINUOUS_TIME]
? config[CONTINUOUS_TIME_MIN] - state[CONTINUOUS_TIME]
: 0;
const waitForTotalTime =
config[TOTAL_TIME_MIN] > state[TOTAL_VISIBLE_TIME]
? config[TOTAL_TIME_MIN] - state[TOTAL_VISIBLE_TIME]
: 0;
// Wait for minimum of (previous timeToWait, positive values of
// waitForContinuousTime and waitForTotalTime).
this.timeToWait_ = Math.min(this.timeToWait_,
waitForContinuousTime || Infinity,
waitForTotalTime || Infinity);
// Return a max of wait time (used by V2)
return Math.max(waitForContinuousTime, waitForTotalTime);
}
/**
* For the purposes of these calculations, a resource is in viewport if the
* visibility conditions are satisfied or they are not defined.
* @param {number} visible Percentage of element visible
* @param {number} min Lower bound of visibility condition. Not inclusive
* @param {number} max Upper bound of visibility condition. Inclusive.
* @return {boolean} true if the conditions are satisfied.
* @private
*/
isInViewport_(visible, min, max) {
return !!(visible > (min || 0) && visible <= (max || 100));
}
/**
* @param {!Object} s State of the listener
* @param {number} visible Percentage of element visible
* @param {number} sinceLast Milliseconds since last update
* @private
*/
setState_(s, visible, sinceLast) {
s[LAST_UPDATE] = Date.now();
s[TOTAL_VISIBLE_TIME] = s[TOTAL_VISIBLE_TIME] !== undefined
? s[TOTAL_VISIBLE_TIME] + sinceLast : 0;
s[CONTINUOUS_TIME] = s[CONTINUOUS_TIME] !== undefined
? s[CONTINUOUS_TIME] + sinceLast : 0;
s[MAX_CONTINUOUS_TIME] = s[MAX_CONTINUOUS_TIME] !== undefined
? Math.max(s[MAX_CONTINUOUS_TIME], s[CONTINUOUS_TIME]) : 0;
s[MIN_VISIBLE] =
s[MIN_VISIBLE] ? Math.min(s[MIN_VISIBLE], visible) : visible;
s[MAX_VISIBLE] =
s[MAX_VISIBLE] ? Math.max(s[MAX_VISIBLE], visible) : visible;
s[LAST_VISIBLE_TIME] = Date.now() - s[TIME_LOADED];
}
/**
* Sets variable values for callback. Cleans up existing values.
* @param {Object<string, *>} state The state object to populate
* @param {!../../../src/layout-rect.LayoutRectDef} layoutBox The bounding rectangle
* for the element
* @private
*/
prepareStateForCallback_(state, layoutBox) {
state[ELEMENT_X] = layoutBox.left;
state[ELEMENT_Y] = layoutBox.top;
state[ELEMENT_WIDTH] = layoutBox.width;
state[ELEMENT_HEIGHT] = layoutBox.height;
state[TOTAL_TIME] = this.getTotalTime_() || '';
state[LOAD_TIME_VISIBILITY] = state[LOAD_TIME_VISIBILITY] || 0;
if (state[MIN_VISIBLE] !== undefined) {
state[MIN_VISIBLE] =
Math.round(dev().assertNumber(state[MIN_VISIBLE]) * 100) / 100;
}
if (state[MAX_VISIBLE] !== undefined) {
state[MAX_VISIBLE] =
Math.round(dev().assertNumber(state[MAX_VISIBLE]) * 100) / 100;
}
state[BACKGROUNDED] = this.backgrounded_ ? '1' : '0';
state[BACKGROUNDED_AT_START] = this.backgroundedAtStart_ ? '1' : '0';
// Remove the state that need not be public and call callback.
delete state[CONTINUOUS_TIME];
delete state[LAST_UPDATE];
delete state[IN_VIEWPORT];
delete state[TIME_LOADED];
delete state[SCHEDULED_RUN_ID];
delete state[LAST_CHANGE_ENTRY];
for (const k in state) {
if (state.hasOwnProperty(k)) {
state[k] = String(state[k]);
}
}
}
getTotalTime_() {
const perf = this.ampdoc.win.performance;
return perf && perf.timing && perf.timing.domInteractive
? Date.now() - perf.timing.domInteractive
: null;
}
}
| DistroScale/amphtml | extensions/amp-analytics/0.1/visibility-impl.js | JavaScript | apache-2.0 | 25,331 |
import { toLength, toBoolean } from "../utils/native";
import { UNDEFINED } from "../types/primitive-type";
import { executeCallback } from "./array-helpers";
import { assertIsNotNullOrUndefined, assertIsFunction } from "../utils/contracts";
export default function ($target, env, factory) {
$target.define("findIndex", factory.createBuiltInFunction(function* (predicate, thisArg) {
assertIsNotNullOrUndefined(this.object, "Array.prototype.findIndex");
let length = yield toLength(this.object);
assertIsFunction(predicate, "predicate");
let i = 0;
while (i < length) {
let propInfo = this.object.getProperty(i);
let value = propInfo ? propInfo.getValue() : UNDEFINED;
let passed = toBoolean(yield executeCallback(env, predicate, { key: i, value }, thisArg, this.object));
if (passed) {
return factory.createPrimitive(i);
}
i++;
}
return factory.createPrimitive(-1);
}, 1, "Array.prototype.findIndex"));
} | jrsearles/SandBoxr | src/es6/array.find-index.js | JavaScript | apache-2.0 | 986 |
function getTableRpj(){
return 'tb_rpj';
}
function dbLoad(){
var db = Ti.Database.open(Ti.App.Properties.getString(DATABASE_FILE));
return db;
}
function createRpj() {
db = dbLoad();
db.execute('CREATE TABLE IF NOT EXISTS ' + getTableRpj() + '(
id INTEGER PRIMARY KEY, rpj_id INTEGER, rpj_razao TEXT, rpj_cnpj TEXT, rpj_fantasia TEXT, rpj_ie TEXT, rpj_im TEXT, fk_rp INTEGER, ep_id INTEGER
);');
db.close();
}
function dropRpj() {
db = dbLoad();
db.execute('DROP TABLE IF EXISTS ' + getTableRpj());
db.close();
}
function insertRpj(rpj_id, rpj_razao, rpj_cnpj, rpj_fantasia, rpj_ie, rpj_im, fk_rp, ep_id) {
db = dbLoad();
db.execute('INSERT INTO ' + getTableRpj() + ' (
rpj_id, rpj_razao, rpj_cnpj, rpj_fantasia, rpj_ie, rpj_im, fk_rp, ep_id)
VALUES (?,?,?,?,?,?,?)',
rpj_id, rpj_razao, rpj_cnpj, rpj_fantasia, rpj_ie, rpj_im, fk_rp, ep_id);
db.close();
}
function selectallRpj() {
db = dbLoad();
var rpj = db.execute('SELECT * FROM ' + getTableRpj());
if (Ti.Platform.osname == "android") {
db.close();
}
return rpj;
}
function processRpj(jsonTxt) {
dropRpj();
createRpj();
var jsonObject = JSON.parse(jsonTxt);
for (var j = 0; j < jsonObject.length; j++) {
var rpj_id = jsonObject[j].rpj_id;
var rpj_razao = jsonObject[j].rpj_razao;
var rpj_cnpj = jsonObject[j].rpj_cnpj;
var rpj_fantasia = jsonObject[j].rpj_fantasia;
var rpj_ie = jsonObject[j].rpj_ie;
var rpj_im = jsonObject[j].rpj_im;
var fk_rp = jsonObject[j].fk_rp;
var ep_id = jsonObject[j].ep_id;
insertRpj(rpj_id, rpj_razao, rpj_cnpj, rpj_fantasia, rpj_ie, rpj_im, fk_rp, ep_id);
}
} | lukas-conka/mobile-app | app/assets/database/rpj.js | JavaScript | apache-2.0 | 1,662 |
var ANIMATION_SPEED = 1000,
snap = Snap(),
els = {},
container,
els_map = {};
Snap.load('face.svg', add);
function add(fragment) {
snap.append(fragment);
container = snap.select('g');
container.drag();
setElements();
animateAll();
}
function setElements() {
els = {
lefteye: snap.select('#moon #left-eye'),
righteye: snap.select('#moon #right-eye'),
mouth: snap.select('#moon #mouth'),
nose: snap.select('#moon #nose'),
body: snap.select('#moon #body')
};
els_map = {
lefteye: {
d: 'M182.665,140.929c0,0,1.334-10-44.666-10s-46,10-46,10s9.731-39.428,45.041-39.428 C172.351,101.501,182.665,140.929,182.665,140.929z'
},
righteye: {
d: 'M375.329,140.929c0,0,1.334-10-44.666-10s-46.002,10-46.002,10 s9.732-39.428,45.043-39.428S375.329,140.929,375.329,140.929z'
},
mouth: {
d: 'M51.999,212.167h363.333c0,0-60.832,118-180.5,118 C115.166,330.167,51.999,212.167,51.999,212.167z'
},
nose: {
d: 'M232.01,100c0,0,9.832,68.999,9.666,77s-18.334,13-18.334,13s32.5,3.999,36.334-1.667 S232.01,100,232.01,100z'
},
body: {
d: 'M588.167,292.167H951.5c0,0-60.833,118-180.5,118S588.167,292.167,588.167,292.167z',
fill: '#EDD64F'
}
};
}
function animateAll() {
// set slight timeout so it doesn't
// animate as soon as the page loads.
setTimeout(function(){
for(var el in els) {
animate(el, els_map[el]);
}
}, 1000);
}
function animate(elem, attrs) {
els[elem].animate(attrs, ANIMATION_SPEED);
}
| christabor/etude | 11-07-2013/animatey.js | JavaScript | apache-2.0 | 1,447 |
//This module creates a window to show all the pictures in a gallery
Ti.include('helper.js');
var Gallery = (function(){
function Gallery(a_navigation_group){
this.gallery_path = Ti.Filesystem.applicationDataDirectory + "/Gallery/";
this.nav_group = a_navigation_group;
this.colons_num = 0;
this.rows_num = 0;
this.gallery_window = Ti.UI.createWindow({
title:'Gallery'
});
this.gallery_view = Ti.UI.createView({
layout:'vertical',
height:Ti.UI.FILL,
width:Ti.UI.FILL
});
if (isAndroid()) {
this.gallery_window.addEventListener('open', eventHandler = function(e){
var the_window = e.source;
var action_bar = the_window.getActivity().getActionBar();
if (action_bar) {
action_bar.setDisplayHomeAsUp(true);
action_bar.onHomeIconItemSelected = function(){
the_window.close();
the_window.removeEventListener('open', eventHandler);
Gallery.prototype.dealloc();
the_window = null;
action_bar = null;
}
}
});
}
this.gallery_window.add(this.gallery_view);
//this.gallery_window.open();
}
Gallery.prototype.getWindow = function(){
return this.gallery_window;
};
Gallery.prototype.buildGallery = function(){
var dir = Ti.Filesystem.getFile(this.gallery_path);
var pictures = dir.getDirectoryListing();
var pic_num = pictures.length;
var image_container;
var file;
var vertical_view, horizontal_view;
var row = [];
horizontal_view = Ti.UI.createScrollView({
width:Ti.UI.FILL,
height:'100',
layout:'horizontal'
});
this.rows_num = 1;
for (var i = 0; i < pic_num; i++) {
if ((i%3) != 0) {
file = Ti.Filesystem.getFile(this.gallery_path + pictures[i]);
image_container = Ti.UI.createImageView({
height:'100',
width:'100',
image:file.nativePath
});
horizontal_view.add(image_container);
this.colons_num++;
}
else if (i == 0) {
file = Ti.Filesystem.getFile(this.gallery_path + pictures[i]);
Ti.API.info('Entro qui! ' + pictures[i]);
image_container = Ti.UI.createImageView({
height:'100',
width:'100',
image:file.nativePath
});
horizontal_view.add(image_container);
this.colons_num++;
}
else {
//va aggiunta quella in posizione i per il quale i%3 == 0
//this.gallery_view.add(vertical_view);
row.push(horizontal_view);
horizontal_view = Ti.UI.createScrollView({
width:Ti.UI.FILL,
height:'100',
layout:'horizontal'
});
file = Ti.Filesystem.getFile(this.gallery_path + pictures[i]);
Ti.API.info('Entro qui! ' + pictures[i]);
image_container = Ti.UI.createImageView({
height:'100',
width:'100',
image:file.nativePath
});
horizontal_view.add(image_container);
this.rows_num++;
}
}
for (var i = 0; i < row.length; i++) {
this.gallery_view.add(row[i]);
}
//this.gallery_view.add(horizontal_view);
Ti.API.info('Allah! ' + horizontal_view.children + " window: " + this.gallery_window);
//this.gallery_window.add(this.gallery_view);
Ti.API.info('mah: ' + this.gallery_window.children);
};
Gallery.prototype.dealloc = function(){
this.gallery_path = null;
this.nav_group = null;
};
return Gallery;
})();
module.exports = Gallery;
| AlessandroSangiuliano/myDiary | Resources/gallery.js | JavaScript | apache-2.0 | 3,581 |
L.Draw.Marker = L.Draw.Feature.extend({
statics: {
TYPE: 'marker'
},
options: {
icon: new L.Icon.Default(),
repeatMode: false,
zIndexOffset: 2000, // This should be > than the highest z-index any markers
buttonIconClass: 'leaflet-mouse-marker',
type: 'marker'
},
initialize: function (map, options) {
// Save the type so super can fire, need to do this as cannot do this.TYPE :(
this.type = options.type || this.options.type;
L.Draw.Feature.prototype.initialize.call(this, map, options);
},
addHooks: function () {
L.Draw.Feature.prototype.addHooks.call(this);
if (this._map) {
this._tooltip.updateContent({text: L.drawLocal.draw.handlers.marker.tooltip.start});
// Same mouseMarker as in Draw.Polyline
if (!this._mouseMarker) {
this._mouseMarker = L.marker(this._map.getCenter(), {
icon: L.divIcon({
className: 'leaflet-mouse-marker',
iconAnchor: [20, 20],
iconSize: [40, 40]
}),
opacity: 0,
zIndexOffset: this.options.zIndexOffset
});
}
this._mouseMarker
.on('click', this._onClick, this)
.addTo(this._map);
this._map.on('mousemove', this._onMouseMove, this);
}
},
removeHooks: function () {
L.Draw.Feature.prototype.removeHooks.call(this);
if (this._map) {
if (this._marker) {
this._marker.off('click', this._onClick, this);
this._map
.off('click', this._onClick, this)
.removeLayer(this._marker);
delete this._marker;
}
this._mouseMarker.off('click', this._onClick, this);
this._map.removeLayer(this._mouseMarker);
delete this._mouseMarker;
this._map.off('mousemove', this._onMouseMove, this);
}
},
_onMouseMove: function (e) {
var latlng = e.latlng;
this._tooltip.updatePosition(latlng);
this._mouseMarker.setLatLng(latlng);
if (!this._marker) {
this._marker = new L.Marker(latlng, {
icon: this.options.icon,
zIndexOffset: this.options.zIndexOffset
});
// Bind to both marker and map to make sure we get the click event.
this._marker.on('click', this._onClick, this);
this._map
.on('click', this._onClick, this)
.addLayer(this._marker);
}
else {
latlng = this._mouseMarker.getLatLng();
this._marker.setLatLng(latlng);
}
},
_onClick: function () {
this._fireCreatedEvent();
this.disable();
if (this.options.repeatMode) {
this.enable();
}
},
_fireCreatedEvent: function () {
var marker = new L.Marker(this._marker.getLatLng(), {icon: this.options.icon});
L.Draw.Feature.prototype._fireCreatedEvent.call(this, marker);
}
});
| IITDU-Spartans/IITDU.SIUSC | FarmerBazaarClient/bower_components/Leaflet.draw-master/src/draw/handler/Draw.Marker.js | JavaScript | apache-2.0 | 3,241 |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
'use strict';
function main(service) {
// [START servicemanagement_v1_generated_ServiceManager_CreateService_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* Required. Initial values for the service resource.
*/
// const service = {}
// Imports the Servicemanagement library
const {ServiceManagerClient} = require('@google-cloud/service-management').v1;
// Instantiates a client
const servicemanagementClient = new ServiceManagerClient();
async function callCreateService() {
// Construct request
const request = {
service,
};
// Run request
const [operation] = await servicemanagementClient.createService(request);
const [response] = await operation.promise();
console.log(response);
}
callCreateService();
// [END servicemanagement_v1_generated_ServiceManager_CreateService_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
| googleapis/nodejs-service-management | samples/generated/v1/service_manager.create_service.js | JavaScript | apache-2.0 | 1,829 |
/**
* Copyright 2015-2019 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {LitElement, html} from "lit";
import UtilsNew from "../../../core/utilsNew.js";
export default class SampleGenotypeFilter extends LitElement {
constructor() {
super();
// Set status and init private properties
this._init();
}
createRenderRoot() {
return this;
}
static get properties() {
return {
sample: {
type: String
},
genotypes: {
type: Array
},
sampleId: {
type: String
},
config: {
type: Object
}
};
}
_init() {
this._prefix = UtilsNew.randomString(8);
this._config = this.getDefaultConfig();
}
update(changedProperties) {
if (changedProperties.has("sample") && this.sample) {
const keyValue = this.sample.split(":");
if (keyValue.length === 2) {
this.sampleId = keyValue[0];
this.genotypes = keyValue[1].split(",");
} else {
// No genotypes provided
this.sampleId = keyValue[0];
this.genotypes = ["0/1", "1/1", "NA"];
}
}
if (changedProperties.has("config")) {
this._config = {...this.getDefaultConfig(), ...this.config};
}
super.update(changedProperties);
}
filterChange(e) {
// select-field-filter already emits a bubbled filterChange event.
// Prepare sample query filter
let sampleFilter = this.sampleId;
if (e.detail.value) {
sampleFilter += ":" + e.detail.value;
}
const event = new CustomEvent("filterChange", {
detail: {
value: sampleFilter
},
bubbles: true,
composed: true
});
this.dispatchEvent(event);
}
getDefaultConfig() {
// HOM_REF, HOM_ALT, HET, HET_REF, HET_ALT and MISS e.g. HG0097:HOM_REF;HG0098:HET_REF,HOM_ALT . 3)
return {
genotypes: [
{
id: "0/1", name: "HET"
},
{
id: "1/1", name: "HOM ALT"
},
{
separator: true
},
{
id: "./.", name: "Missing"
},
{
id: "NA", name: "NA"
}
]
};
}
render() {
return html`
<select-field-filter
multiple
.data="${this._config.genotypes}"
.value=${this.genotypes}
.multiple="true"
@filterChange="${this.filterChange}">
</select-field-filter>
`;
}
}
customElements.define("sample-genotype-filter", SampleGenotypeFilter);
| opencb/jsorolla | src/webcomponents/commons/filters/sample-genotype-filter.js | JavaScript | apache-2.0 | 3,559 |
var templates = function () {
'use strict';
var handlebars = window.handlebars || window.Handlebars,
Handlebars = window.handlebars || window.Handlebars,
cache = {};
function get(name) {
var promise = new Promise(function (resolve, reject) {
//if (cache[name]) {
// resolve(cache[name]);
// return;
//}
var url = '/Scripts/app/templates/' + name + '.handlebars';
$.get(url, function (html) {
var template = handlebars.compile(html);
cache[name] = template;
resolve(template);
}).then(function(res){
reject(res);
});
});
return promise;
}
return {
get: get
};
}(); | deyantodorov/Zeus-WebServicesCould-TeamWork | Source/ChatSystem/Server/ChatSystem.Server/Scripts/app/templates.js | JavaScript | apache-2.0 | 804 |
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/iter/randu' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var isIteratorLike = require( '@stdlib/assert/is-iterator-like' );
var pkg = require( './../package.json' ).name;
var iterAbs2 = require( './../lib' );
// MAIN //
bench( pkg, function benchmark( b ) {
var rand;
var iter;
var i;
rand = randu();
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
iter = iterAbs2( rand );
if ( typeof iter !== 'object' ) {
b.fail( 'should return an object' );
}
}
b.toc();
if ( !isIteratorLike( iter ) ) {
b.fail( 'should return an iterator protocol-compliant object' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::iteration', function benchmark( b ) {
var rand;
var iter;
var z;
var i;
rand = randu();
iter = iterAbs2( rand );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
z = iter.next().value;
if ( isnan( z ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( z ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
| stdlib-js/stdlib | lib/node_modules/@stdlib/math/iter/special/abs2/benchmark/benchmark.js | JavaScript | apache-2.0 | 1,768 |
/**
* Copyright 2021 The Google Earth Engine Community Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// [START earthengine__apidocs__ee_geometry_multipolygon_length]
// Define a MultiPolygon object.
var multiPolygon = ee.Geometry.MultiPolygon(
[[[[-122.092, 37.424],
[-122.086, 37.418],
[-122.079, 37.425],
[-122.085, 37.423]]],
[[[-122.081, 37.417],
[-122.086, 37.421],
[-122.089, 37.416]]]]);
// Apply the length method to the MultiPolygon object.
var multiPolygonLength = multiPolygon.length();
// Print the result to the console.
print('multiPolygon.length(...) =', multiPolygonLength);
// Display relevant geometries on the map.
Map.setCenter(-122.085, 37.422, 15);
Map.addLayer(multiPolygon,
{'color': 'black'},
'Geometry [black]: multiPolygon');
// [END earthengine__apidocs__ee_geometry_multipolygon_length] | google/earthengine-community | samples/javascript/apidocs/ee-geometry-multipolygon-length.js | JavaScript | apache-2.0 | 1,415 |
var Backbone = require('backbone')
, _ = require('underscore')
, Garam = require('../../Garam')
, Cluster = require('cluster')
, Base = require('../../Base')
, assert = require('assert')
, fs = require('fs')
, async = require('async');
var ModelFactory = function(namespace,config) {
assert(config);
this.namespace = namespace;
this.models = {};
this.config = config;
if (this.config.redisModel) {
this.type = 'redis';
} else {
assert(this.config.type);
this.type = this.config.type;
}
}
module.exports = ModelFactory;
_.extend(ModelFactory.prototype, Base.prototype, {
addModel : function(model) {
if (typeof model.modelType ==='undefined') {
model.modelType = 'redis';
}
model._create(model.dbName);
var db = Garam.getDB(this.namespace);
db.addProcedure(model.name,model);
//Garam.setModel(model.name,model);
},
create : function(model_dir) {
var self = this;
var namespace = this.namespace;
var modelDir = this.appDir + '/model/'+namespace;
this.appDir = Garam.getInstance().get('appDir');
this._sql = {};
if(!fs.existsSync(this.appDir + '/model/'+namespace)) {
Garam.getInstance().log.error(modelDir,'not find model dir');
return;
}
var dir = process.cwd()+'/'+ this.appDir + '/model/'+namespace;
read(dir);
function read(dir) {
var list = fs.readdirSync(dir);
var total =list.length;
list.forEach(function (file,i) {
var stats = fs.statSync(dir + '/'+ file);
if (stats.isFile()) {
var Model = require(dir + '/'+ file);
var t = new Model(this.type,self.config.namespace);
self.addModel(t);
} else {
read(dir+'/'+file);
}
if (total === (i+1)) {
Garam.getInstance().emit('completeWork',namespace);
Garam.getInstance().emit('databaseOnReady',namespace);
}
});
}
},
addCreateModel : function() {
}
});
ModelFactory.extend = Garam.extend; | ssdosso/garam | server/lib/database/model/ModelFactory.js | JavaScript | apache-2.0 | 2,328 |
// Author: Charles
var ResultMessage = require('./ResultMessage');
var Ladder = require('./Ladder');
var RandomUtil = require('./RandomUtil');
var util = require('util');
var ladderTime = require('../model/LadderTime.json');
var schedule = require('node-schedule');
var ladderManager = null;
function LadderManager() {
var games = {};
this.getRandomTime = function(time) {
var randomDay = RandomUtil.randomFromRange(time.dayofweek);
var hour = RandomUtil.randomFromRange(time.hour);
var minute = RandomUtil.randomFromRange(time.minute);
return util.format('%s %s * * %s', minute, hour, randomDay);
}
this.run = function(ladderRunner) {
var resultMessage = new ResultMessage();
resultMessage.message = '랜덤 사다리 알람 설정 완료!!';
resultMessage.result = true;
var jobs = {};
for(var key in ladderTime) {
var timeStr = this.getRandomTime(ladderTime[key]);
console.log(key + ': ' + timeStr);
schedule.scheduleJob(key, this.getRandomTime(ladderTime[key]), function () {
pushMessage();
});
}
var weeklyTime = util.format('0 0 * * 0');
var weeklyLadderManageJob = schedule.scheduleJob(weeklyTime, function () {
schedule.rescheduleJob(ladderJob, this.getRandomTime());
});
return resultMessage;
}
}
function getLadderManager() {
if(!ladderManager) {
ladderManager = new LadderManager();
}
return ladderManager;
}
function LadderRunner() {
this.ladderManager = getLadderManager();
}
LadderRunner.prototype.run = function() {
return this.ladderManager.run(this);
}
LadderRunner.prototype.setChannelAccessToken = function(_token) {
this.token = _token;
}
LadderRunner.prototype.getChannelAccessToken = function() {
return this.token;
}
LadderRunner.prototype.setId = function(_id) {
this.id = _id;
}
LadderRunner.prototype.getId = function() {
return this.id;
}
LadderRunner.prototype.getQuery = function() {
return this.query;
}
LadderRunner.prototype.getResult = function() {
return this.result;
}
module.exports = LadderRunner; | Charleslee522/8ctci | server/MasterOfTime/controller/LadderRunner.js | JavaScript | apache-2.0 | 2,122 |
var q = {a:5};
q.a++;
dumpValue(q.a);
assert(q.a == 6);
var x = {a:6}
x.a ^= 42;
assert(x.a == 44);
| keil/TbDA | test/micro/test84.js | JavaScript | apache-2.0 | 109 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* Evaluate the common logarithm (base ten).
*
* @module @stdlib/math/base/special/log10
*
* @example
* var log10 = require( '@stdlib/math/base/special/log10' );
*
* var v = log10( 100.0 );
* // returns ~0.602
*
* v = log10( 8.0 );
* // returns ~0.903
*
* v = log10( 0.0 );
* // returns -Infinity
*
* v = log10( Infinity );
* // returns Infinity
*
* v = log10( NaN );
* // returns NaN
*
* v = log10( -4.0 );
* // returns NaN
*/
// MODULES //
var log10 = require( './log10.js' );
// EXPORTS //
module.exports = log10;
| stdlib-js/stdlib | lib/node_modules/@stdlib/math/base/special/log10/lib/index.js | JavaScript | apache-2.0 | 1,158 |
var newick_tree = function () {
var tree = biojs.vis.tree.tree();
var theme = function(ta,div) {
var newick = '((A,B),C);';
ta.data(biojs.io.newick.newick(newick));
ta.width = 600;
ta.scale = false;
//tree.layout (tree.layout.vertical());
ta(div);
}
return theme;
}
| rajido/biojs2 | biojs-vis-tree/newick-tree.js | JavaScript | apache-2.0 | 292 |
var deepExtend = require('deep-extend');
var flat = require('flat');
var fs = require('fs');
var path = require('path');
var propsParser = require('properties-parser');
var defaultConfig = require(path.join(__dirname,'config.json'));
var homePath = process.env[(process.platform === 'win32') ?
'USERPROFILE' : 'HOME'];
var currentConfigPath = path.join(process.cwd(),'stormpath.json');
var userConfigPath = path.join(homePath,'stormpath.json');
var currentConfig = fs.existsSync(currentConfigPath) ?
fs.readSync(currentConfigPath) : {};
var userConfig = fs.existsSync(userConfigPath) ?
fs.readSync(userConfigPath) : {};
/**
* @class Config
* @param {Object} config Config overrides
*
* Constructs a Stormpath Config object, by looking in the following locations:
*
* 0. use default internal config
* 1. stormpath.json in ~/.stormpath/stormpath.json
* 2. stormpath.json in current directory
* 3. read from environment variables
* 4. passed in to constructor
*
*/
function Config(options){
deepExtend(this, defaultConfig);
deepExtend(this, userConfig||{});
deepExtend(this, currentConfig||{});
deepExtend(this, this.getEnvVars());
deepExtend(this, options||{});
var apiKeyFileName = this.client.apiKey.file;
if (
apiKeyFileName &&
!this.client.apiKey.id &&
!this.client.apiKey.secret
){
if (!fs.existsSync(apiKeyFileName)) {
throw new Error('Client API key file not found: '+ apiKeyFileName);
}
var props = propsParser.read(apiKeyFileName);
if (!props || !props.id || !props.secret) {
throw new Error('Unable to read properties file: ' + apiKeyFileName);
}
this.client.apiKey.id = props.id;
this.client.apiKey.secret = props.secret;
}
}
Config.prototype.getEnvVars = function(){
var flattendDefaultConfig = flat.flatten(this,{
delimiter: '_'
});
var flatEnvValues = Object.keys(flattendDefaultConfig)
.reduce(function(envVarMap,key){
var envKey = 'STORMPATH_' + key.toUpperCase();
var value = process.env[envKey];
if(value!==undefined){
envVarMap[key] = typeof flattendDefaultConfig[key] === 'number' ?
parseInt(value,10) : value;
}
return envVarMap;
},{});
return flat.unflatten(flatEnvValues,{delimiter:'_'});
};
module.exports = Config;
| wakashige/stormpath-sdk-node | lib/Config.js | JavaScript | apache-2.0 | 2,308 |
var request = require('supertest');
var assert = require('chai').assert;
describe('testing user authentication', function() {
var server;
beforeEach(function(done) {
delete require.cache[require.resolve('../src/server')];
server = require('../src/server');
done();
});
afterEach(function(done) {
server.close(done);
});
it('returns authentication token', function test(done) {
var auth = {
"email": "[email protected]",
"password": "password",
};
request(server).post('/api/authenticate').send(auth)
.expect('Content-Type', 'application/json')
.end(function(err, result) {
assert.equal(result.body.success, true);
assert.equal(result.body.message, "Your token is valid for 8 hours");
done();
});
});
});
| jcaple/giphy_search | test/test-authenticate.js | JavaScript | apache-2.0 | 762 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { combineReducers } from 'redux';
import {
INIT_PAYMENT_METHODS,
ADD_PAYMENT_METHOD,
EDIT_SUPPORTED_METHODS,
EDIT_PAYMENT_METHOD_DATA,
REMOVE_PAYMENT_METHOD,
INIT_TOTAL,
EDIT_TOTAL_LABEL,
EDIT_TOTAL_VALUE,
EDIT_TOTAL_CURRENCY,
INIT_DISPLAY_ITEMS,
ADD_DISPLAY_ITEM,
EDIT_DISPLAY_ITEM_LABEL,
EDIT_DISPLAY_ITEM_VALUE,
EDIT_DISPLAY_ITEM_CURRENCY,
REMOVE_DISPLAY_ITEM,
INIT_OPTIONS,
EDIT_OPTIONS_NAME,
EDIT_OPTIONS_PHONE,
EDIT_OPTIONS_EMAIL,
EDIT_OPTIONS_BILLING,
EDIT_OPTIONS_SHIPPING,
EDIT_OPTIONS_SHIPPING_TYPE,
REMOVE_OPTIONS_SHIPPING_TYPE,
INIT_SHIPPING_OPTIONS,
ADD_SHIPPING_OPTION,
EDIT_SHIPPING_OPTION_ID,
EDIT_SHIPPING_OPTION_LABEL,
EDIT_SHIPPING_OPTION_VALUE,
EDIT_SHIPPING_OPTION_CURRENCY,
EDIT_SHIPPING_OPTION_SELECTED,
REMOVE_SHIPPING_OPTION,
SHOW_RESULT
} from './actions.js';
/*
Example data structure:
{
paymentMethods: [...],
details: {
displayItems: [...],
total: {...},
shippingOptions: [...]
},
options: {...},
}
*/
const request = (state = [], action) => {
let { paymentMethods = [], details = {}, options = {} } = state;
let { displayItems = [], total = {}, shippingOptions = [] } = details;
switch (action.type) {
case INIT_PAYMENT_METHODS:
paymentMethods = [{
supportedMethods: "https://google.com/pay",
data: `{
"environment": "TEST",
"apiVersion": 2,
"apiVersionMinor": 0,
"merchantInfo": {
"merchantName": "Merchant Demo"
},
"allowedPaymentMethods": [{
"type": "CARD",
"parameters": {
"allowedAuthMethods": ["PAN_ONLY", "CRYPTOGRAM_3DS"],
"allowedCardNetworks": ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"]
},
"tokenizationSpecification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway":"stripe",
"stripe:publishableKey":"pk_test_fkdoiK6FR5BLZMFNbSGoDjpn",
"stripe:version":"2018-10-31"
}
}
}]
}`
}, {
supportedMethods: 'https://bobbucks.dev/pay',
data: '{}'
}];
return { ...state, paymentMethods }
case ADD_PAYMENT_METHOD:
paymentMethods = [...paymentMethods, {
supportedMethods: '',
data: ''
}];
return { ...state, paymentMethods };
case EDIT_SUPPORTED_METHODS:
paymentMethods = paymentMethods.map((paymentMethod, index) => {
if (index === action.index) {
return {...paymentMethod, supportedMethods: action.supportedMethods }
}
return paymentMethod;
});
return { ...state, paymentMethods };
case EDIT_PAYMENT_METHOD_DATA:
paymentMethods = paymentMethods.map((paymentMethod, index) => {
if (index === action.index) {
return {...paymentMethod, data: action.data }
}
return paymentMethod;
});
return { ...state, paymentMethods };
case REMOVE_PAYMENT_METHOD:
paymentMethods = paymentMethods.filter((_, index) => index !== action.index);
return { ...state, paymentMethods };
case INIT_DISPLAY_ITEMS:
displayItems = [{
label: 'Original Donation Amount',
amount: { value: '10.00', currency: 'USD' }
}];
return { ...state, details: { displayItems, total, shippingOptions }};
case ADD_DISPLAY_ITEM:
displayItems = [
...displayItems,
{
label: '',
amount: { value: '', currency: '' }
}
];
return { ...state, details: { displayItems, total, shippingOptions }};
case EDIT_DISPLAY_ITEM_LABEL:
displayItems = displayItems.map((displayItem, index) => {
if (index === action.index) {
return {
label: action.label,
amount: {
value: displayItem.amount.value,
currency: displayItem.amount.currency
}
}
}
return displayItem;
});
return { ...state, details: { displayItems, total, shippingOptions }};
case EDIT_DISPLAY_ITEM_VALUE:
displayItems = displayItems.map((displayItem, index) => {
if (index === action.index) {
return {
label: displayItem.label,
amount: {
value: action.value,
currency: displayItem.amount.currency
}
}
}
return displayItem;
});
return { ...state, details: { displayItems, total, shippingOptions }};
case EDIT_DISPLAY_ITEM_CURRENCY:
displayItems = displayItems.map((displayItem, index) => {
if (index === action.index) {
return {
label: displayItem.label,
amount: {
value: displayItem.amount.value,
currency: action.currency
}
}
}
return displayItem;
});
return { ...state, details: { displayItems, total, shippingOptions }};
case REMOVE_DISPLAY_ITEM:
displayItems = displayItems.filter((_, index) => index !== action.index);
return { ...state, details: { displayItems, total, shippingOptions }};
case INIT_TOTAL:
total = {
label: 'Total',
amount: { value: '10.00', currency: 'USD' }
}
return { ...state, details: { displayItems, total, shippingOptions }};
case EDIT_TOTAL_LABEL:
total = {
label: action.total,
amount: {
value: total.amount.value,
currency: total.amount.currency
}
};
return { ...state, details: { displayItems, total, shippingOptions }};
case EDIT_TOTAL_VALUE:
total = {
label: total.label,
amount: {
value: action.value,
currency: total.amount.currency
}
};
return { ...state, details: { displayItems, total, shippingOptions }};
case EDIT_TOTAL_CURRENCY:
total = {
label: total.label,
amount: {
value: total.amount.value,
currency: action.currency
}
};
return { ...state, details: { displayItems, total, shippingOptions }};
case INIT_SHIPPING_OPTIONS:
shippingOptions = [{
id: 'standard',
label: 'Standard',
amount: { value: '0.00', currency: 'USD' },
selected: true
}, {
id: 'express',
label: 'Express',
amount: { value: '5.00', currency: 'USD' }
}, {
id: 'international',
label: 'International',
amount: { value: '10.00', currency: 'USD' }
}]
return { ...state, details: { displayItems, total, shippingOptions }};
case ADD_SHIPPING_OPTION:
shippingOptions = [
...shippingOptions,
{
id: '',
label: '',
amount: { value: '', currency: '' },
selected: false
}
];
return { ...state, details: { displayItems, total, shippingOptions }};
case EDIT_SHIPPING_OPTION_ID:
shippingOptions = shippingOptions.map((shippingOption, index) => {
if (index === action.index) {
return { ...shippingOption, id: action.id }
}
return shippingOption;
});
return { ...state, details: { displayItems, total, shippingOptions }};
case EDIT_SHIPPING_OPTION_LABEL:
shippingOptions = shippingOptions.map((shippingOption, index) => {
if (index === action.index) {
return { ...shippingOption, label: action.label }
}
return shippingOption;
});
return { ...state, details: { displayItems, total, shippingOptions }};
case EDIT_SHIPPING_OPTION_VALUE:
shippingOptions = shippingOptions.map((shippingOption, index) => {
if (index === action.index) {
return { ...shippingOption,
amount: {
value: action.value,
currency: shippingOption.amount.currency
}
}
}
return shippingOption;
});
return { ...state, details: { displayItems, total, shippingOptions }};
case EDIT_SHIPPING_OPTION_CURRENCY:
shippingOptions = shippingOptions.map((shippingOption, index) => {
if (index === action.index) {
return { ...shippingOption,
amount: {
value: shippingOption.amount.value,
currency: action.currency
}
}
}
return shippingOption;
});
return { ...state, details: { displayItems, total, shippingOptions }};
case EDIT_SHIPPING_OPTION_SELECTED:
shippingOptions = shippingOptions.map((shippingOption, index) => {
if (index === action.index) {
return { ...shippingOption, selected: action.selected }
}
return shippingOption;
});
return { ...state, details: { displayItems, total, shippingOptions }};
case REMOVE_SHIPPING_OPTION:
shippingOptions = shippingOptions.filter((_, index) => index !== action.index);
return { ...state, details: { displayItems, total, shippingOptions }};
case INIT_OPTIONS:
options = {
requestPayerName: false,
requestPayerPhone: false,
requestPayerEmail: false,
requestPayerBillingAddress: false,
requestShipping: false
}
return { ...state, options };
case EDIT_OPTIONS_NAME:
options = { ...options, requestPayerName: action.checked }
return { ...state, options };
case EDIT_OPTIONS_PHONE:
options = { ...options, requestPayerPhone: action.checked }
return { ...state, options };
case EDIT_OPTIONS_EMAIL:
options = { ...options, requestPayerEmail: action.checked }
return { ...state, options };
case EDIT_OPTIONS_BILLING:
options = { ...options, requestPayerBillingAddress: action.checked }
return { ...state, options };
case EDIT_OPTIONS_SHIPPING:
options = { ...options, requestShipping: action.checked }
return { ...state, options };
case EDIT_OPTIONS_SHIPPING_TYPE:
options = { ...options, shippingType: action.shippingType }
return { ...state, options };
case REMOVE_OPTIONS_SHIPPING_TYPE:
delete options.shippingType;
return { ...state, options };
default:
return state;
}
}
const result = (state = [], action) => {
switch (action.type) {
case SHOW_RESULT:
return action.result;
default:
return state;
}
}
export const PaymentRequestApp = combineReducers({
request,
result
});
| GoogleChromeLabs/paymentrequest-show | src/store/reducers.js | JavaScript | apache-2.0 | 11,202 |
const pkg = require("/package.json").peabodyos;
const util = require("util");
if(pkg.installer) {
console.log("[PeabodyOS] Please Wait while the installer starts...");
require("./installer");
} else {
console.log("[PeabodyOS] Please Wait while the server is booting...");
//process.termout.write(util.format(runtime.pci.deviceList)+"\n");
} | SpaceboyRoss01/PeabodyOS | src/system/sys/distro/server/index.js | JavaScript | apache-2.0 | 357 |
import App from "../app";
export function launchProbe({id}) {
const system = App.systems.find(s => s.id === id);
if (!system) return {};
return {simulatorId: system.simulatorId};
}
export function probeProcessedData({id, simulatorId}) {
if (simulatorId) return {simulatorId};
const system = App.systems.find(s => s.id === id);
if (!system) return {};
return {simulatorId: system.simulatorId};
}
| Thorium-Sim/thorium | server/triggers/probes.js | JavaScript | apache-2.0 | 410 |
$(function() {
$("#remarkButton").click(function() {
var remark = $("#remark").val().trim();
if (remark == "") {
return false;
}
var tokenId = $("#tokenId").val();
var patientId = $("#patientId").val();
var request = {
text: remark
};
$.ajax("/api/secure/remarks/new", {
method: "POST",
headers: {
'X-IPED-TOKEN-ID': tokenId,
'X-IPED-PATIENT-ID': patientId,
},
data: {parameter: JSON.stringify(request)},
dataType: "json",
success: function(response) {
location.reload();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('送信に失敗しました');
},
});
return false;
});
});
| nakaken0629/iped | server/src/main/webapp/web/js/meeting.js | JavaScript | apache-2.0 | 748 |
//////////// load required libraries
var url = require('url'),
http = require('http'),
path = require('path'),
fs = require('fs'),
WAMS = require(path.resolve('../../server')); // When using this example as base, make sure that this points to the correct WAMS server library path.
///////////////////////////////
//////////// web server section
// Set up required variables
var port = process.env.PORT || 3000;
var homeDir = path.resolve(process.cwd(), '.');
var stat404 = fs.readFileSync(path.join(homeDir, '/status_404.html'));
// HTTP-server main function (handle incoming requests and serves files)
var serverFunc = function (req, res) {
var uri = url.parse(req.url).pathname;
if (uri == "/") uri = "/index.html";
file = fs.readFile(path.join(homeDir, uri), function (err, data) {
if (err) { // If file doesn't exist, serve 404 error.
res.writeHead(404, {'Content-Type': 'text/html', 'Content-Length': stat404.length});
res.end(stat404);
}
else {
switch (/.*\.([^\?.]*).*/.exec(uri)[1]) { // extract file type
case "htm":
case "html":
// handler for HTML-files
res.writeHead(200, {'Content-Type': 'text/html', 'Content-Length': data.length}); break;
case "js":
// handler for JavsScript-files
res.writeHead(200, {'Content-Type': 'application/javascript', 'Content-Length': data.length}); break;
default:
// handler for all other file types
res.writeHead(200, {'Content-Type': 'text/plain', 'Content-Length': data.length}); break;
}
res.end(data);
}
});
};
/////////////////////////
//////////// WAMS section
// Set up HTTP-server: listen on port 8080 and use serverFunc (see above) to serve files to clients.
var httpServer = http.createServer(serverFunc).listen(port);
// Start WAMS using the HTTP-server
WAMS.listen(httpServer);
// Disable log-output
WAMS.set('log level', 1);
// Register callback onGreeting when WAMP receives "greeting"-message
WAMS.on("greeting", onGreeting);
function onGreeting(data) {
// Upon receiving a "greeting"-message, send out a "response"-message to all clients
WAMS.emit("response", "Welcome, " + data.data.from + "!");
} | scottbateman/wams.js | examples/HelloWorld/server.js | JavaScript | apache-2.0 | 2,213 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var round = require( '@stdlib/math/base/special/round' );
var randu = require( '@stdlib/random/base/randu' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pkg = require( './../package.json' ).name;
var pmf = require( './../lib' );
// MAIN //
bench( pkg, function benchmark( b ) {
var N;
var K;
var n;
var x;
var y;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
x = round( randu()*10.0 );
N = round( randu()*100.0 );
K = round( randu()*N );
n = round( randu()*N );
y = pmf( x, N, K, n );
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+':factory', function benchmark( b ) {
var mypmf;
var N;
var K;
var n;
var x;
var y;
var i;
N = round( randu()*100.0 );
K = round( randu()*N );
n = round( randu()*N );
mypmf = pmf.factory( N, K, n );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
x = round( randu()*40.0 );
y = mypmf( x );
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
| stdlib-js/stdlib | lib/node_modules/@stdlib/stats/base/dists/hypergeometric/pmf/benchmark/benchmark.js | JavaScript | apache-2.0 | 1,914 |
// Copyright 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/** @fileoverview Sentinel main class. */
'use strict';
const {DateTime} = require('luxon');
const {
firestore: {DataSource, FirestoreAccessBase,},
cloudfunctions: {
ValidatedStorageFile,
CloudFunction,
adaptNode6,
validatedStorageTrigger,
},
pubsub: {EnhancedPubSub, getMessage,},
utils: {getLogger, replaceParameters,},
} = require('@google-cloud/nodejs-common');
const {
TaskConfigDao,
TaskType,
ErrorOptions,
} = require('./task_config/task_config_dao.js');
const {
TaskLog,
TaskLogDao,
FIELD_NAMES,
TaskLogStatus,
} = require('./task_log/task_log_dao.js');
const {
buildTask,
BaseTask,
RetryableError,
} = require('./tasks/index.js');
const {buildReport} = require('./tasks/report/index.js');
const {
resumeStatusCheck,
pauseStatusCheck,
} = require('./utils/cronjob_helper.js');
const {StatusCheckTask} = require('./tasks/internal/status_check_task.js');
const {
TaskManagerOptions,
TaskManager,
} = require('./task_manager.js');
/**
* String value of BigQuery job status 'done' in BigQuery logging messages.
* @const {string}
*/
const JOB_STATUS_DONE = 'DONE';
/**
* String value of BigQuery Data Transfer job status 'SUCCEEDED'
* in BigQuery Data Transfer pubsub messages.
* @const {string}
*/
const DATATRANSFER_JOB_STATUS_DONE = 'SUCCEEDED';
/**
* Types of internal (intrinsic) tasks.
* @enum {string}
*/
const INTERNAL_TASK_TYPE = Object.freeze({
STATUS_CHECK: 'status_check',
});
/**
* Sentinel is a Cloud Functions based solution to coordinate BigQuery related
* jobs(tasks), e.g. loading file from Cloud Storage, querying or exporting data
* to Cloud Storage. Besides these jobs, it also support AutoML Tables batch
* prediction job.
*/
class Sentinel {
/**
* Initializes the Sentinel instance.
* @param {!TaskManagerOptions} options
* @param {function(Object<string,*>,Object<string,*>):!BaseTask} buildTaskFn
* Function to build a task instance based on given configuration and
* parameters.
*/
constructor(options, buildTaskFn = buildTask) {
/** @const {!TaskManager} */ this.taskManager = new TaskManager(options);
/** @const {!TaskManagerOptions} */ this.options = options;
/** @const {!TaskConfigDao} */ this.taskConfigDao = options.taskConfigDao;
/** @const {!TaskLogDao} */ this.taskLogDao = options.taskLogDao;
/** @const {function(Object<string,*>,Object<string,*>):!BaseTask} */
this.buildTask = buildTaskFn;
/** @const {!Logger} */ this.logger = getLogger('S.MAIN');
}
/**
* Gets the Cloud Functions 'Storage Monitor' which will send out starting
* related task(s) messages based on the the name of the file added to the
* monitored directory.
* It match Tasks in following order. It will skip second step if Task Id is
* found in the first step:
* 1. If there is `task[TASK_CONFIG_ID]` in the file name, just starts the
* task with TaskConfig Id as `TASK_CONFIG_ID`;
* 2. Tries to match the file name with all LOAD tasks' configuration
* `fileNamePattern` and starts all matching Tasks.
* @param {string} inbound The folder that this function monitors.
* @return {!CloudFunction}
*/
getStorageMonitor(inbound) {
/**
* Monitors the Cloud Storage for new files. Sends 'start load task' message
* if it identifies any new files related to Load tasks.
* @param {!ValidatedStorageFile} file Validated Storage file information
* from the function 'validatedStorageTrigger'.
* @return {!Promise<(!Array<string>|undefined)>} IDs of the 'start load
* task' messages.
*/
const monitorStorage = (file) => {
return this.getTaskIdByFile_(file.name).then((taskIds) => {
if (taskIds.length === 0) {
throw new Error(`Can't find Load Task for file: '${file.name}'`);
}
this.logger.debug(`Find ${taskIds.length} Task for [${file.name}]`);
return Promise.all(taskIds.map((taskId) => {
const parameters = JSON.stringify({
file,
partitionDay: getDatePartition(file.name),
});
this.logger.debug(`Trigger Load task: ${taskId}.`);
return this.taskManager.sendTaskMessage(parameters, {taskId});
}));
}).catch((error) => {
console.error(`Error in handling file: ${file.name}`, error);
throw error;
});
};
return this.options.validatedStorageTrigger(monitorStorage, inbound);
}
/**
* Returns collection of task IDs which are triggered by the given file name.
* @param {string} fileName Name of ingested file.
* @return {!Promise<!Array<string>>}
* @private
*/
getTaskIdByFile_(fileName) {
const regex = /task\[([\w-]*)]/i;
const task = fileName.match(regex);
if (task) return Promise.resolve([task[1]]);
const hasFileNamePattern = (config) => {
const sourceConfig = config.source;
return sourceConfig && sourceConfig.fileNamePattern;
};
const matchesFileNamePattern =
(config) => new RegExp(config.source.fileNamePattern).test(fileName);
return this.taskConfigDao.list(
[{property: 'type', value: TaskType.LOAD}]).then((configs) => {
return configs
.filter(({entity: config}) => hasFileNamePattern(config))
.filter(({entity: config}) => matchesFileNamePattern(config))
.map((config) => config.id);
});
}
/**
* Gets the Cloud Functions 'Task Coordinator' which is triggered by a Pub/Sub
* message. There are four different kinds of messages:
* 1. Starting a task. Message attributes (only string typed value) have
* following keys:
* a. taskId (TaskConfig Id) determines the TaskConfig of the task;
* b. parentId (TaskLog Id) Id of the TaskLog that triggered this one;
* Message data is a JSON string for the dynamic parameter values, e.g.
* 'today'. It supports type other than string values.
* 2. Finishing a task. Message attributes (only string typed value) have
* following keys:
* a. taskLogId (TaskLog Id) determines the TaskConfig of the task;
* 3. Logs from Cloud Logging system of subscribed events, e.g. BigQuery job
* complete event. This function will complete the matched Task.
* 4. Pubsub message from BigQuery Data Transfer after a Transfer Run job is
* finished. The message attributes only have two keys:
* a. eventType: The type of event that has just occurred.
* TRANSFER_RUN_FINISHED is the only possible value.
* b. payloadFormat: The format of the object payload.
* JSON_API_V1 is the only possible value
* Go https://cloud.google.com/bigquery-transfer/docs/transfer-run-notifications#format
* to have more information of the format.
*/
getTaskCoordinator() {
/**
* @see method 'finishTask_()'
* @see method 'startTask_()'
* @see method 'handleResourceEvent_()'
* @type {!CloudFunctionNode8}
*/
const coordinateTask = (message, context) => {
if (this.isStartTaskMessage_(message)) {
return this.startTaskByMessage_(message, context);
}
if (this.isFinishTaskMessage_(message)) {
return this.finishTaskByMessage_(message);
}
if (this.isBigQueryLoggingMessage_(message)) {
return this.finishBigQueryTask_(message);
}
if (this.isBigQueryDataTransferMessage_(message)) {
return this.finishBigQueryDataTransferTask_(message);
}
throw new Error(`Unknown message: ${getMessage(message)}`);
};
return adaptNode6(coordinateTask);
}
/** Returns whether this is a message to start a new task. */
isStartTaskMessage_(message) {
const attributes = message.attributes || {};
return !!attributes.taskId;
}
/** Starts the task based on a Pub/sub message. */
startTaskByMessage_(message, context) {
const attributes = message.attributes || {};
const data = getMessage(message);
this.logger.debug('message.data decoded:', data);
const messageId = context.eventId; // New TaskLog Id.
this.logger.debug('message id:', messageId);
let parametersStr;
if (!data) {
parametersStr = '{}';
} else if (data.indexOf('${') === -1) { // No placeholder in parameters.
parametersStr = data;
} else { // There are placeholders in parameters. Need default values.
const regex = /\${([^}]*)}/g;
const parameters = data.match(regex).map((match) => {
return match.substring(2, match.length - 1);
});
const {timezone} = JSON.parse(data);
parametersStr = replaceParameters(data,
getDefaultParameters(parameters, timezone));
}
const taskLog = {
parameters: parametersStr,
...attributes,
};
return this.startTask_(messageId, taskLog);
}
/** Returns whether this is a message to finish a task. */
isFinishTaskMessage_(message) {
const attributes = message.attributes || {};
return !!attributes.taskLogId;
}
/** Finishes the task based on a Pub/sub message. */
finishTaskByMessage_(message) {
const attributes = message.attributes || {};
this.logger.debug(`Complete task ${attributes.taskLogId}`);
return this.finishTask_(attributes.taskLogId);
}
/**
* Returns whether this is a message from BigQuery Logging of a completed job.
*/
isBigQueryLoggingMessage_(message) {
const data = getMessage(message);
try {
const payload = JSON.parse(data);
return payload.resource
&& payload.resource.type === 'bigquery_resource'
&& payload.protoPayload
&& payload.protoPayload.methodName === 'jobservice.jobcompleted';
} catch (error) {
console.warn('Error when checking when the message is from BigQuery',
error);
return false;
}
}
/** Finishes the task (if any) related to the completed job in the message. */
finishBigQueryTask_(message) {
const data = getMessage(message);
const payload = JSON.parse(data);
const event = payload.protoPayload.serviceData.jobCompletedEvent;
return this.handleBigQueryJobCompletedEvent_(event);
}
/**
* Returns whether this is a message from BigQuery Data Transfer of a completed run job.
*/
isBigQueryDataTransferMessage_(message) {
try {
const attributes = message.attributes || {};
return attributes.eventType === 'TRANSFER_RUN_FINISHED'
&& attributes.payloadFormat === 'JSON_API_V1';
} catch (error) {
this.logger.error(
'Error when checking when the message is from BigQuery Data Transfer',
error
);
return false;
}
}
/** Finishes the task (if any) related to the completed job in the message. */
finishBigQueryDataTransferTask_(message) {
const data = getMessage(message);
const payload = JSON.parse(data);
return this.handleBigQueryDataTransferTask_(payload);
}
/**
* Starts a task in a 'duplicated message proof' way by using
* 'TaskLogDao.startTask' to check the status.
* @param {(string|number)} taskLogId
* @param {!TaskLog} taskLog
* @return {!Promise<(string | number)>} taskLogId
* @private
*/
startTask_(taskLogId, taskLog) {
// Get the 'lock' to start this task to prevent duplicate messages.
return this.taskLogDao.startTask(taskLogId, taskLog).then((started) => {
if (started) return this.startTaskJob_(taskLogId, taskLog);
console.warn(`TaskLog ${taskLogId} exists. Duplicated? Quit.`);
});
}
/**
* Starts a task job:
* 1. Using TaskConfigId and parameters to create the instance of Task, then
* run 'Task.start()' to start the real job in the task;
* 2. Using 'TaskLogDao.afterStart' to merge the output of 'Task.start()' to
* TaskLog, e.g. jobId or other job identity from external systems.
* 3. Checking whether this task is already done (returns true when this is
* a synchronous task). If yes, continue to finish the task.
* @param {(string|number)} taskLogId
* @param {!TaskLog} taskLog
* @return {!Promise<(string | number)>} taskLogId
* @private
*/
startTaskJob_(taskLogId, taskLog) {
const parameters = JSON.parse(taskLog.parameters);
return this.prepareTask(taskLog.taskId, parameters).then((task) => {
return task.start()
.then((updatesToTaskLog) => {
console.log('Task started with:', JSON.stringify(updatesToTaskLog));
return this.taskLogDao.afterStart(taskLogId, updatesToTaskLog);
})
// Waits for async `afterStart` to complete.
.then(() => task.isDone())
.then((done) => {
if (done) return this.finishTask_(taskLogId);
})
// Waits for async `finishTask_` to complete.
.then(() => taskLogId);
}).catch((error) => {
console.error(error);
return this.taskLogDao.saveErrorMessage(taskLogId, error);
});
}
/**
* Returns the task object based on TaskConfigId and parameters, with
* TaskManagerOptions injected.
* @param {string} taskConfigId
* @param {object} parameters Parameters for this Task. There is a special
* property named 'intrinsic' in parameters to indicate this task is
* offered by Sentinel and doesn't exists in TaskConfig.
* The purpose is to let those intrinsic(internal) tasks to reuse
* Sentinel's framework of managing the lifecycle of a task.
* Using the 'intrinsic' to avoid the possible clash of parameter names.
* @return {!Promise<!BaseTask>} Task instance.
*/
async prepareTask(taskConfigId, parameters = {}) {
/** @const {!BaseTask} */
const task = parameters.intrinsic
? this.prepareInternalTask_(parameters.intrinsic, parameters)
: await this.prepareExternalTask_(taskConfigId, parameters);
return task;
}
/**
* Returns an 'internal' task instance based on the task type and parameters.
*
* @param {!INTERNAL_TASK_TYPE} type Internal task type.
* @param {Object} parameters
* @return {!BaseTask}
* @private
*/
prepareInternalTask_(type, parameters) {
if (type === INTERNAL_TASK_TYPE.STATUS_CHECK) {
const task = new StatusCheckTask({}, parameters);
task.setPrepareExternalTaskFn(this.prepareExternalTask_.bind(this));
task.injectContext(this.options);
return task;
}
throw new Error(`Unsupported internal task: ${type}`);
}
/**
* Returns an external task instance based on the TaskConfig Id and parameters
* with context (TaskManagerOptions) injected.
* When Sentinel starts or finishes an external task, the task information is
* passed as a TaskConfig Id and an object of parameters. This function will
* use TaskConfigDao to get the TaskConfig(config), then use the config and
* parameters to get the Task object.
* This function will also be passed into Status Check Task to initialize
* other external tasks.
* @param {string} taskConfigId
* @param {Object} parameters
* @return {!Promise<!BaseTask>}
* @private
*/
async prepareExternalTask_(taskConfigId, parameters) {
const taskConfig = await this.taskConfigDao.load(taskConfigId);
if (!taskConfig) throw new Error(`Fail to load Task ${taskConfigId}`);
const task = this.buildTask(taskConfig, parameters);
task.injectContext(this.options);
return task;
};
/**
* Finishes a task in a 'duplicated message proof' way by using
* 'TaskLogDao.finishTask' to check the status.
* @param {(string|number)} taskLogId
* @return {!Promise<(!Array<string>|undefined)>} Ids of messages to trigger
* next task(s).
* @private
*/
finishTask_(taskLogId) {
this.logger.debug(`Start to finish task ${taskLogId}`);
return this.taskLogDao.load(taskLogId).then((taskLog) => {
return this.taskLogDao.finishTask(taskLogId).then((finished) => {
if (finished) return this.finishTaskJob_(taskLogId, taskLog);
console.warn(`Fail to finish the taskLog [${taskLogId}]. Quit.`);
})
});
}
/**
* Finishes a task job:
* 1. Using TaskConfigId and parameters to create the instance of Task, then
* run 'Task.finish()' to finish the job in the task, e.g. download files
* from external system;
* 2. Using 'TaskLogDao.afterFinish' to merge the output of 'Task.finish()'
* to TaskLog;
* 3. Triggering next Tasks if there are.
* @param {(string|number)} taskLogId
* @param {!TaskLog} taskLog
* @return {!Promise<(!Array<string>|undefined)>} Ids of messages to trigger
* next task(s).
* @private
*/
async finishTaskJob_(taskLogId, taskLog) {
const parameters = JSON.parse(taskLog.parameters);
let updatedParameterStr = taskLog.parameters;
const task = await this.prepareTask(taskLog.taskId, parameters);
try {
const updatesToTaskLog = await task.finish();
this.logger.debug('Task finished with', JSON.stringify(updatesToTaskLog));
if (updatesToTaskLog.parameters) {
updatedParameterStr = updatesToTaskLog.parameters;
}
// 'afterFinish' won't throw 'RetryableError' which can trigger retry.
await this.taskLogDao.afterFinish(taskLogId, updatesToTaskLog);
} catch (error) {
console.error(error);
const taskConfig = await this.taskConfigDao.load(taskLog.taskId);
/**@type {!ErrorOptions} */
const errorOptions = Object.assign({
// Default retry 3 times before recognize it's a real failure.
retryTimes: 3,
ignoreError: false, // Default error is not ignored.
}, taskConfig.errorOptions);
if (error instanceof RetryableError) {
const retriedTimes = taskLog[FIELD_NAMES.RETRIED_TIMES] || 0;
if (retriedTimes < errorOptions.retryTimes) {
// Roll back task status from 'FINISHING' to 'STARTED' and set task
// needs regular status check (to trigger next retry).
// TODO(lushu) If there are tasks other than report task needs retry,
// consider move this part into the detailed tasks.
return this.taskLogDao.merge({
status: TaskLogStatus.STARTED,
[FIELD_NAMES.REGULAR_CHECK]: true,
[FIELD_NAMES.RETRIED_TIMES]: retriedTimes + 1,
}, taskLogId);
}
console.log(
'Reach the maximum retry times, continue to mark this task failed.');
}
if (errorOptions.ignoreError !== true) {
return this.taskLogDao.saveErrorMessage(taskLogId, error);
}
// Save the error information for 'ignore error' task then continue to
// trigger its next task(s).
await this.taskLogDao.saveErrorMessage(taskLogId, error, true);
}
return this.taskManager.startTasks(taskLog.next,
{[FIELD_NAMES.PARENT_ID]: taskLogId},
updatedParameterStr);
}
/**
* Based on the incoming message, updates the TaskLog and triggers next tasks
* if there is any in TaskConfig of the current finished task.
* For Load/Query/Export tasks, the taskLog saves 'job Id' generated when the
* job starts at the beginning. When these kinds of job is done, the log event
* will be sent here with 'job Id'. So we can match to TaskLogs in database
* waiting for the job is done.
* @param event
* @return {!Promise<(!Array<string>|number|undefined)>} The message Id array
* of the next tasks and an empty Array if there is no followed task.
* Returns taskLogId (number) when an error occurs.
* Returns undefined if there is no related taskLog.
* @private
*/
handleBigQueryJobCompletedEvent_(event) {
const job = event.job;
const eventName = event.eventName;
const jobId = job.jobName.jobId;
const jobStatus = job.jobStatus.state;
this.logger.debug(`Task JobId[${jobId}] [${eventName}] [${jobStatus}]`);
const filter = {property: 'jobId', value: jobId};
return this.taskLogDao.list([filter]).then((taskLogs) => {
if (taskLogs.length > 1) {
throw new Error(`Find more than one task with Job Id: ${jobId}`);
}
if (taskLogs.length === 1) {
const {id: taskLogId} = taskLogs[0];
if (jobStatus === JOB_STATUS_DONE) return this.finishTask_(taskLogId);
console.log(`Job Status is not DONE: `, event);
return this.taskLogDao.saveErrorMessage(taskLogId, job.jobStatus.error);
}
this.logger.debug(`BigQuery JobId[${jobId}] is not a Sentinel Job.`);
}).catch((error) => {
console.error(error);
throw error;
});
}
/**
* Based on the incoming message, updates the TaskLog and triggers next tasks
* if there is any in TaskConfig of the current finished task.
* For Data Transfer tasks, the taskLog saves the 'name' of run job
* as 'job id' which is generated when the job starts at the beginning.
* When the job is done, the datatransfer job will be sent here with the run
* job 'name'. So we can match to TaskLogs in database
* waiting for the job is done.
* @param payload
* @return {!Promise<(!Array<string>|number|undefined)>} The message Id array
* of the next tasks and an empty Array if there is no followed task.
* Returns taskLogId (number) when an error occurs.
* Returns undefined if there is no related taskLog.
* @private
*/
handleBigQueryDataTransferTask_(payload) {
const jobId = payload.name;
const jobStatus = payload.state;
this.logger.debug(
`The JobId of Data Transfer Run: ${jobId} and the status is: ${jobStatus}`
);
const filter = {property: 'jobId', value: jobId};
return this.taskLogDao
.list([filter])
.then((taskLogs) => {
if (taskLogs.length > 1) {
throw new Error(`Find more than one task with Job Id: ${jobId}`);
}
if (taskLogs.length === 1) {
const {id: taskLogId} = taskLogs[0];
if (jobStatus === DATATRANSFER_JOB_STATUS_DONE) {
return this.finishTask_(taskLogId);
}
this.logger.info(`Job Status is not DONE: `, payload);
return this.taskLogDao.saveErrorMessage(
taskLogId,
payload.errorStatus
);
}
this.logger.debug(
`BigQuery Data Transfer JobId[${jobId}] is not a Sentinel Job.`
);
})
.catch((error) => {
this.logger.error(error);
throw error;
});
}
}
/**
* Extracts the date information from the file name. If there is no date
* recognized, will return today's date.
* @param {string} filename. It is supposed to contain date information in
* format 'YYYY-MM-DD' or 'YYYYMMDD'. Though it will also take 'YYYY-MMDD'
* or 'YYYYMM-DD'.
* @return {string} Date string in format "YYYYMMDD".
*/
const getDatePartition = (filename) => {
const reg = /\d{4}-?\d{2}-?\d{2}/;
const date = reg.exec(filename);
let partition;
if (date) {
partition = date[0];
} else {
partition = (new Date()).toISOString().split('T')[0];
console.log(
`No date find in file: ${filename}. Using current date: ${partition}.`);
}
return partition.replace(/-/g, '');
};
/**
* Returns the default parameter object. Currently, it support following rules:
* now - Date ISO String
* today - format 'YYYYMMDD'
* today_set_X - set the day as X based on today's date, format 'YYYYMMDD'
* today_sub_X - sub the X days based on today's date, format 'YYYYMMDD'
* today_add_X - add the X days based on today's date, format 'YYYYMMDD'
* Y_hyphenated - 'Y' could be any of previous date, format 'YYYY-MM-DD'
* Y_timestamp_ms - 'Unix milliseconds timestamp of the start of date 'Y'
* yesterday - quick access as 'today_sub_1'. It can has follow ups as well,
* e.g. yesterday_sub_X, yesterday_hyphenated, etc.
* Parameters get values ignoring their cases status (lower or upper).
* @param {Array<string>} parameters Names of default parameter.
* @param {string=} timezone Default value is UTC.
* @param {number=} unixMillis Unix timestamps in milliseconds. Default value is
* now. Used for test.
* @return {{string: string}}
*/
const getDefaultParameters = (parameters, timezone = 'UTC',
unixMillis = Date.now()) => {
/**
* Returns the value based on the given parameter name.
* @param {string=} parameter
* @return {string|number}
*/
const getDefaultValue = (parameter) => {
let realParameter = parameter.toLocaleLowerCase();
const now = DateTime.fromMillis(unixMillis, {zone: timezone});
if (realParameter === 'now') return now.toISO(); // 'now' is a Date ISO String.
if (realParameter === 'today') return now.toFormat('yyyyMMdd');
realParameter = realParameter.replace(/^yesterday/, 'today_sub_1');
if (!realParameter.startsWith('today')) {
throw new Error(`Unknown default parameter: ${parameter}`);
}
const suffixes = realParameter.split('_');
let date = now;
for (let index = 1; index < suffixes.length; index++) {
if (suffixes[index] === 'hyphenated') return date.toISODate();
if (suffixes[index] === 'timestamp' && suffixes[index + 1] === 'ms') {
return date.startOf('days').toMillis();
}
const operator = suffixes[index];
let operationOfLib;
switch (operator) {
case 'add':
operationOfLib = 'plus';
break;
case 'set':
operationOfLib = 'set';
break;
case 'sub':
operationOfLib = 'minus';
break;
default:
throw new Error(
`Unknown operator in default parameter: ${parameter}`);
}
const day = suffixes[++index];
if (typeof day === "undefined") {
throw new Error(`Malformed of default parameter: ${parameter}`);
}
date = date[operationOfLib]({days: day});
}
return date.toFormat('yyyyMMdd');
}
const result = {};
parameters.forEach((parameter) => {
result[parameter] = getDefaultValue(parameter);
})
return result;
};
/**
* Returns a Sentinel instance based on the parameters.
* Sentinel works on several components which depend on the configuration. This
* factory function will seal the details in product environment and let the
* Sentinel class be more friendly to test.
*
* @param {string} namespace The `namespace` of this instance, e.g. prefix of
* the topics, Firestore root collection name, Datastore namespace, etc.
* @param {!DataSource} datasource The underlying datasource type.
* @return {!Sentinel} The Sentinel instance.
*/
const getSentinel = (namespace, datasource) => {
/** @type {TaskManagerOptions} */
const options = {
namespace,
taskConfigDao: new TaskConfigDao(datasource, namespace),
taskLogDao: new TaskLogDao(datasource, namespace),
pubsub: EnhancedPubSub.getInstance(),
buildReport,
statusCheckCronJob: {
pause: pauseStatusCheck,
resume: resumeStatusCheck,
},
validatedStorageTrigger,
};
console.log(
`Init Sentinel for namespace[${namespace}], Datasource[${datasource}]`);
return new Sentinel(options);
};
/**
* Probes the Google Cloud Project's Firestore mode (Native or Datastore), then
* uses it to create an instance of Sentinel.
* @param {(string|undefined)=} namespace
* @return {!Promise<!Sentinel>}
*/
const guessSentinel = (namespace = process.env['PROJECT_NAMESPACE']) => {
if (!namespace) {
console.warn(
'Fail to find ENV variables PROJECT_NAMESPACE, will set as `sentinel`');
namespace = 'sentinel';
}
return FirestoreAccessBase.isNativeMode().then((isNative) => {
const dataSource = isNative ? DataSource.FIRESTORE : DataSource.DATASTORE;
return getSentinel(namespace, dataSource);
});
};
module.exports = {
Sentinel,
getSentinel,
guessSentinel,
getDatePartition,
getDefaultParameters,
};
| GoogleCloudPlatform/cloud-for-marketing | marketing-analytics/activation/data-tasks-coordinator/src/sentinel.js | JavaScript | apache-2.0 | 28,561 |
'use strict';
'use console';
/* eslint-disable no-console */
/* eslint-disable no-await-in-loop */
const fs = require('fs-extra');
const prompt = require('syncprompt');
const _ = require('lodash');
const reply = require('../../lib/reply')();
const display = require('../../lib/display')();
module.exports = (cliConfig) => {
const terasliceClient = require('teraslice-client-js')({
host: cliConfig.cluster_url
});
const annotation = require('../../lib/annotation')(cliConfig);
cliConfig.type = 'job';
async function showPrompt(actionIn) {
let answer = false;
const action = _.startCase(actionIn);
const response = prompt(`${action} (Y/N)? > `);
if (response === 'Y' || response === 'y') {
answer = true;
}
return answer;
}
async function restart() {
if (await stop()) {
await start();
}
if (cliConfig.add_annotation) {
await annotation.add('Restart');
}
}
async function stop(action = 'stop') {
let waitCountStop = 0;
const waitMaxStop = 10;
let stopTimedOut = false;
let jobsStopped = 0;
let allJobsStopped = false;
let jobs = [];
if (cliConfig.all_jobs) {
jobs = await save();
} else {
await checkForId();
jobs = await save(false);
const id = _.find(jobs, { job_id: cliConfig.job_id });
if (id !== undefined) {
jobs = [];
jobs.push(id);
console.log(`Stop job: ${cliConfig.job_id}`);
}
}
if (jobs.length === 0) {
reply.error(`No jobs to ${action}`);
return;
}
if (jobs.length === 1) {
cliConfig.yes = true;
}
if (cliConfig.yes || await showPrompt(action)) {
while (!stopTimedOut) {
if (waitCountStop >= waitMaxStop) {
break;
}
try {
await changeStatus(jobs, action);
stopTimedOut = true;
} catch (err) {
stopTimedOut = false;
reply.error(`> ${action} job(s) had an error [${err.message}]`);
jobsStopped = await status(false, false);
}
waitCountStop += 1;
}
let waitCount = 0;
const waitMax = 15;
while (!allJobsStopped) {
jobsStopped = await status(false, false);
await _.delay(() => {}, 50);
if (jobsStopped.length === 0) {
allJobsStopped = true;
}
if (waitCount >= waitMax) {
break;
}
waitCount += 1;
}
if (allJobsStopped) {
console.log('> All jobs %s.', await setAction(action, 'past'));
if (cliConfig.add_annotation) {
console.log('adding annotation');
await annotation.add(_.startCase(action));
}
}
}
return allJobsStopped;
}
async function checkForId() {
if (!_.has(cliConfig, 'job_id')) {
reply.fatal('job id required');
}
}
async function start(action = 'start') {
let jobs = [];
// start job with job file
if (!cliConfig.all_jobs) {
await checkForId();
const id = await terasliceClient.jobs.wrap(cliConfig.job_id).config();
if (id !== undefined) {
id.slicer = {};
id.slicer.workers_active = id.workers;
jobs.push(id);
}
} else {
jobs = await fs.readJson(cliConfig.state_file);
}
if (jobs.length === 0) {
reply.error(`No jobs to ${action}`);
return;
}
if (cliConfig.info) {
await displayInfo();
}
await displayJobs(jobs, true);
/*
if (_.has(cliConfig, 'job_id')) {
cliConfig.yes = true;
}
*/
if (jobs.length === 1) {
cliConfig.yes = true;
}
if (cliConfig.yes || await showPrompt(action)) {
await changeStatus(jobs, action);
let waitCount = 0;
const waitMax = 10;
let jobsStarted = 0;
let allWorkersStarted = false;
console.log('> Waiting for workers to start');
while (!allWorkersStarted || waitCount < waitMax) {
jobsStarted = await status(false, false);
waitCount += 1;
allWorkersStarted = await checkWorkerCount(jobs, jobsStarted);
}
let allAddedWorkersStarted = false;
if (allWorkersStarted) {
// add extra workers
waitCount = 0;
await addWorkers(jobs, jobsStarted);
while (!allAddedWorkersStarted || waitCount < waitMax) {
jobsStarted = await status(false, false);
waitCount += 1;
allAddedWorkersStarted = await checkWorkerCount(jobs, jobsStarted, true);
}
}
if (allAddedWorkersStarted) {
await status(false, true);
console.log('> All jobs and workers %s', await setAction(action, 'past'));
if (cliConfig.add_annotation) {
await annotation.add(_.startCase(action));
}
}
} else {
console.log('bye!');
}
}
async function workers() {
await checkForId();
const response = await terasliceClient.jobs.wrap(cliConfig.job_id)
.changeWorkers(cliConfig.action, cliConfig.num);
console.log(`> job: ${cliConfig.job_id} ${response}`);
}
async function pause() {
await stop('pause');
}
async function resume() {
await start('resume');
}
async function addWorkers(expectedJobs, actualJobs) {
for (const job of actualJobs) {
for (const expectedJob of expectedJobs) {
let addWorkersOnce = true;
if (expectedJob.job_id === job.job_id) {
if (addWorkersOnce) {
let workers2add = 0;
if (_.has(expectedJob, 'slicer.workers_active')) {
workers2add = expectedJob.slicer.workers_active - expectedJob.workers;
}
if (workers2add > 0) {
console.log(`> Adding ${workers2add} worker(s) to ${job.job_id}`);
await terasliceClient.jobs.wrap(job.job_id).changeWorkers('add', workers2add);
await _.delay(() => {}, 50);
}
addWorkersOnce = false;
}
}
}
}
}
async function checkWorkerCount(expectedJobs, actualJobs, addedWorkers = false) {
let allWorkersStartedCount = 0;
let allWorkers = false;
let expectedWorkers = 0;
let activeWorkers = 0;
for (const job of actualJobs) {
for (const expectedJob of expectedJobs) {
if (expectedJob.job_id === job.job_id) {
if (addedWorkers) {
if (_.has(expectedJob, 'slicer.workers_active')) {
expectedWorkers = job.slicer.workers_active;
} else {
reply.fatal('no expected workers');
}
} else {
expectedWorkers = expectedJob.workers;
}
if (_.has(job, 'slicer.workers_active')) {
activeWorkers = job.slicer.workers_active;
}
if (expectedWorkers === activeWorkers) {
allWorkersStartedCount += 1;
}
}
}
}
if (allWorkersStartedCount === expectedJobs.length) {
allWorkers = true;
}
return allWorkers;
}
async function save() {
return status(true, true);
}
async function status(saveState = false, showJobs = true) {
const jobs = [];
if (cliConfig.info) {
await displayInfo();
}
let controllers = '';
try {
controllers = await terasliceClient.cluster.controllers();
} catch (e) {
controllers = await terasliceClient.cluster.slicers();
}
for (const jobStatus of cliConfig.statusList) {
let jobsTemp = '';
const exResult = await terasliceClient.ex.list(jobStatus);
jobsTemp = await controllerStatus(exResult, jobStatus, controllers);
_.each(jobsTemp, (job) => {
jobs.push(job);
});
}
if (jobs.length > 0) {
if (showJobs) {
await displayJobs(jobs);
}
if (saveState) {
await fs.writeJson(cliConfig.state_file, jobs, { spaces: 4 });
}
} else {
reply.error(`no jobs on ${cliConfig.cluster}`);
}
return jobs;
}
async function list() {
if (cliConfig.info) {
await displayInfo();
}
const jobs = await terasliceClient.jobs.list();
if (jobs.length > 0) {
await displayJobsList(jobs, false);
}
return jobs;
}
async function run() {
await start();
}
async function recover() {
const response = await terasliceClient.jobs.wrap(cliConfig.job_id).recover();
if (_.has(response, 'job_id')) {
console.log(`> job_id ${cliConfig.job_id} recovered`);
} else {
console.log(response);
}
}
async function view() {
// view job on cluster
await checkForId();
const response = await terasliceClient.jobs.wrap(cliConfig.job_id).config();
console.log(JSON.stringify(response, null, 4));
}
async function errors() {
await checkForId();
const response = await terasliceClient.jobs.wrap(cliConfig.job_id).errors();
if (response.length === 0) {
console.log(`job_id:${cliConfig.job_id} no errors`);
} else {
let count = 0;
const size = parseInt(cliConfig.size, 10);
console.log(`Errors job_id:${cliConfig.job_id}`);
_.each(response, (error) => {
_.each(error, (value, key) => {
console.log(`${key} : ${value}`);
});
count += 1;
console.log('-'.repeat(80));
if (count >= size) {
return false;
}
});
}
}
async function displayJobs(jobs, file = false) {
const headerJobs = await setHeaderDefaults(file);
let jobsParsed = '';
if (cliConfig.output_style === 'txt') {
jobsParsed = await parseJobResponseTxt(jobs, file);
} else {
jobsParsed = await parseJobResponse(jobs, file);
}
await display.display(headerJobs, jobsParsed, cliConfig.output_style);
}
async function displayJobsList(jobs, file = false) {
const headerJobs = ['job_id', 'name', 'lifecycle', 'slicers', 'workers', '_created', '_updated'];
let jobsParsed = '';
if (cliConfig.output_style === 'txt') {
jobsParsed = await parseJobResponseTxt(jobs, true);
} else {
jobsParsed = await parseJobResponse(jobs, file, true);
}
await display.display(headerJobs, jobsParsed, cliConfig.output_style);
}
async function setAction(action, tense) {
if (action === 'stop' && tense === 'past') {
return 'stopped';
}
if (action === 'stop' && tense === 'present') {
return 'stopping';
}
if (action === 'start' && tense === 'past') {
return 'started';
}
if (action === 'stop' && tense === 'present') {
return 'starting';
}
if (action === 'pause' && tense === 'past') {
return 'paused';
}
if (action === 'stop' && tense === 'present') {
return 'pausing';
}
if (action === 'restart' && tense === 'past') {
return 'restarted';
}
if (action === 'restart' && tense === 'present') {
return 'restarting';
}
if (action === 'resume' && tense === 'past') {
return 'resumed';
}
if (action === 'resume' && tense === 'present') {
return 'resuming';
}
return action;
}
async function displayInfo() {
const header = ['host', 'state_file'];
const rows = [];
if (cliConfig.output_style === 'txt') {
const row = {};
row.host = cliConfig.hostname;
row.state_file = cliConfig.state_file;
rows.push(row);
} else {
const row = [];
row.push(cliConfig.hostname);
row.push(cliConfig.state_file);
rows.push(row);
}
await display.display(header, rows, cliConfig.output_style);
}
async function parseJobResponseTxt(response, isList = false) {
if (!isList) {
_.each(response, (value, node) => {
if (_.has(response[node], 'slicer.workers_active')) {
response[node].workers_active = response[node].slicer.workers_active;
} else {
response[node].workers_active = 0;
}
});
}
return response;
}
async function parseJobResponse(response, file = false, isList = false) {
const rows = [];
_.each(response, (value, node) => {
const row = [];
row.push(response[node].job_id);
row.push(response[node].name);
if (!file || !isList) {
row.push(response[node]._status);
}
row.push(response[node].lifecycle);
row.push(response[node].slicers);
row.push(response[node].workers);
if (!isList) {
if (_.has(response[node], 'slicer.workers_active')) {
row.push(response[node].slicer.workers_active);
} else {
row.push(0);
}
}
row.push(response[node]._created);
row.push(response[node]._updated);
rows.push(row);
});
return rows;
}
async function setHeaderDefaults(file = false) {
let defaults = [];
if (file) {
defaults = ['job_id', 'name', 'lifecycle', 'slicers', 'workers', 'workers_active', '_created', '_updated'];
} else {
defaults = ['job_id', 'name', '_status', 'lifecycle', 'slicers', 'workers', 'workers_active', '_created', '_updated'];
}
return defaults;
}
async function changeStatus(jobs, action) {
console.log(`> Waiting for jobs to ${action}`);
const response = jobs.map((job) => {
if (action === 'stop') {
return terasliceClient.jobs.wrap(job.job_id).stop()
.then((stopResponse) => {
if (stopResponse.status.status === 'stopped' || stopResponse.status === 'stopped') {
return setAction(action, 'past')
.then((setActionResult) => {
console.log('> job: %s %s', job.job_id, setActionResult);
});
} else {
return setAction(action, 'present')
.then((setActionResult) => {
console.log('> job: %s error %s', job.job_id, setActionResult);
});
}
});
}
if (action === 'start') {
return terasliceClient.jobs.wrap(job.job_id).start()
.then((startResponse) => {
if (startResponse.job_id === job.job_id) {
return setAction(action, 'past')
.then((setActionResult) => {
console.log('> job: %s %s', job.job_id, setActionResult);
});
} else {
return setAction(action, 'present')
.then((setActionResult) => {
console.log('> job: %s error %s', job.job_id, setActionResult);
});
}
});
}
if (action === 'resume') {
return terasliceClient.jobs.wrap(job.job_id).resume()
.then((resumeResponse) => {
if (resumeResponse.status.status === 'running' || resumeResponse.status === 'running') {
return setAction(action, 'past')
.then((setActionResult) => {
console.log('> job: %s %s', job.job_id, setActionResult);
});
} else {
return setAction(action, 'present')
.then((setActionResult) => {
console.log('> job: %s error %s', job.job_id, setActionResult);
});
}
});
}
if (action === 'pause') {
return terasliceClient.jobs.wrap(job.job_id).pause()
.then((pauseResponse) => {
if (pauseResponse.status.status === 'paused' || pauseResponse.status === 'paused') {
return setAction(action, 'past')
.then((setActionResult) => {
console.log('> job: %s %s', job.job_id, setActionResult);
});
} else {
return setAction(action, 'present')
.then((setActionResult) => {
reply.error('> job: %s error %s', job.job_id, setActionResult);
});
}
});
}
});
return Promise.all(response);
}
async function controllerStatus(result, jobStatus, controllerList) {
const jobs = [];
for (const item of result) {
if (jobStatus === 'running' || jobStatus === 'failing') {
_.set(item, 'slicer', _.find(controllerList, { job_id: `${item.job_id}` }));
} else {
item.slicer = 0;
}
jobs.push(item);
}
return jobs;
}
return {
errors,
list,
pause,
recover,
restart,
resume,
run,
save,
start,
status,
stop,
workers,
view,
};
};
| jsnoble/teraslice | packages/teraslice-cli/cmds/jobs/lib/index.js | JavaScript | apache-2.0 | 19,757 |
/**
* Copyright 2018 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import keyMirror from 'keymirror';
import { defineMessages } from 'react-intl';
export const CONFIG_DOWNLOAD_MESSAGE = 'CONFIG_DOWNLOAD_MESSAGE';
export const GET_DEPLOYMENT_STATUS_FAILED = 'GET_DEPLOYMENT_STATUS_FAILED';
export const GET_DEPLOYMENT_STATUS_SUCCESS = 'GET_DEPLOYMENT_STATUS_SUCCESS';
export const GET_DEPLOYMENT_STATUS_PENDING = 'GET_DEPLOYMENT_STATUS_PENDING';
export const START_DEPLOYMENT_FAILED = 'START_DEPLOYMENT_FAILED';
export const START_DEPLOYMENT_SUCCESS = 'START_DEPLOYMENT_SUCCESS';
export const START_DEPLOYMENT_PENDING = 'START_DEPLOYMENT_PENDING';
export const DEPLOYMENT_FAILED = 'DEPLOYMENT_FAILED';
export const DEPLOYMENT_SUCCESS = 'DEPLOYMENT_SUCCESS';
export const START_UNDEPLOY_FAILED = 'START_UNDEPLOY_FAILED';
export const START_UNDEPLOY_SUCCESS = 'START_UNDEPLOY_SUCCESS';
export const START_UNDEPLOY_PENDING = 'START_UNDEPLOY_PENDING';
export const UNDEPLOY_FAILED = 'UNDEPLOY_FAILED';
export const UNDEPLOY_SUCCESS = 'UNDEPLOY_SUCCESS';
export const RECOVER_DEPLOYMENT_STATUS_FAILED =
'RECOVER_DEPLOYMENT_STATUS_FAILED';
export const RECOVER_DEPLOYMENT_STATUS_SUCCESS =
'RECOVER_DEPLOYMENT_STATUS_SUCCESS';
export const RECOVER_DEPLOYMENT_STATUS_PENDING =
'RECOVER_DEPLOYMENT_STATUS_PENDING';
export const deploymentStates = keyMirror({
UNDEPLOYED: null,
DEPLOY_SUCCESS: null,
DEPLOYING: null,
UNDEPLOYING: null,
DEPLOY_FAILED: null,
UNDEPLOY_FAILED: null,
UNKNOWN: null
});
export const shortDeploymentStatusMessages = defineMessages({
UNDEPLOYED: {
id: 'DeploymentStatusShort.undeployed',
defaultMessage: 'Not deployed'
},
DEPLOY_SUCCESS: {
id: 'DeploymentStatusShort.deployed',
defaultMessage: 'Deployment succeeded'
},
DEPLOYING: {
id: 'DeploymentStatusShort.deploying',
defaultMessage: 'Deployment in progress'
},
UNDEPLOYING: {
id: 'DeploymentStatusShort.undeploying',
defaultMessage: 'Deployment deletion in progress'
},
DEPLOY_FAILED: {
id: 'DeploymentStatusShort.deploymentFailed',
defaultMessage: 'Deployment failed'
},
UNDEPLOY_FAILED: {
id: 'DeploymentStatusShort.undeployFailed',
defaultMessage: 'Undeploy failed'
},
UNKNOWN: {
id: 'DeploymentStatusShort.unknown',
defaultMessage: 'Deployment status could not be loaded'
}
});
export const deploymentStatusMessages = defineMessages({
UNDEPLOYED: {
id: 'DeploymentStatus.undeployed',
defaultMessage: 'Deployment not started'
},
DEPLOY_SUCCESS: {
id: 'DeploymentStatus.deployed',
defaultMessage: 'Deployment succeeded'
},
DEPLOYING: {
id: 'DeploymentStatus.deploying',
defaultMessage: 'Deployment of {planName} plan is currently in progress'
},
UNDEPLOYING: {
id: 'DeploymentStatus.undeploying',
defaultMessage:
'Deletion of {planName} plan deployment is currently in progress'
},
DEPLOY_FAILED: {
id: 'DeploymentStatus.deploymentFailed',
defaultMessage: 'Deployment of {planName} plan failed'
},
UNDEPLOY_FAILED: {
id: 'DeploymentStatus.undeployFailed',
defaultMessage: 'Undeploy failed'
},
UNKNOWN: {
id: 'DeploymentStatus.unknown',
defaultMessage: 'Plan {planName} deployment status could not be loaded'
}
});
| knowncitizen/tripleo-ui | src/js/constants/DeploymentConstants.js | JavaScript | apache-2.0 | 3,813 |
var classorg_1_1onosproject_1_1provider_1_1of_1_1packet_1_1impl_1_1OpenFlowPacketProviderTest =
[
[ "emit", "classorg_1_1onosproject_1_1provider_1_1of_1_1packet_1_1impl_1_1OpenFlowPacketProviderTest.html#aa94466b84da02fb4a176033b6158f825", null ],
[ "handlePacket", "classorg_1_1onosproject_1_1provider_1_1of_1_1packet_1_1impl_1_1OpenFlowPacketProviderTest.html#a79dd2e6e6c9b0ef5c82e969eb73cf70a", null ],
[ "startUp", "classorg_1_1onosproject_1_1provider_1_1of_1_1packet_1_1impl_1_1OpenFlowPacketProviderTest.html#a43702ef94d6cc9ab19104d1c2c2e9ec2", null ],
[ "teardown", "classorg_1_1onosproject_1_1provider_1_1of_1_1packet_1_1impl_1_1OpenFlowPacketProviderTest.html#adaa63dabc787e18449cb055b80126a63", null ],
[ "wrongScheme", "classorg_1_1onosproject_1_1provider_1_1of_1_1packet_1_1impl_1_1OpenFlowPacketProviderTest.html#a98102b12a4e42b4a82025ab5778c07f4", null ]
]; | onosfw/apis | onos/apis/classorg_1_1onosproject_1_1provider_1_1of_1_1packet_1_1impl_1_1OpenFlowPacketProviderTest.js | JavaScript | apache-2.0 | 891 |
import * as actionTypes from '../comm/actionTypes';
import {service} from '../comm/service';
function dayData(code,line){
let values=line.split('~');
let v={
code:code,
name:values[1],
close:parseFloat(values[3]),
last:parseFloat(values[4]),
open:parseFloat(values[5]),
volume:parseInt(values[6]),
buy1:values[9],buy1Vol:values[10],
buy2:values[11],buy2Vol:values[12],
buy3:values[13],buy3Vol:values[14],
buy4:values[15],buy4Vol:values[16],
buy5:values[17],buy5Vol:values[18],
sell1:values[19],sell1Vol:values[20],
sell2:values[21],sell2Vol:values[22],
sell3:values[23],sell3Vol:values[24],
sell4:values[25],sell4Vol:values[26],
sell5:values[27],sell5Vol:values[28],
time:values[30],high:values[33],low:values[34],
amount:parseInt(values[37]),
turnoverRate:values[38]
};
if(code==='sh000001' || code==='sz399001'){
v.avg='';
}else{
v.avg=(v.amount/v.volume*100).toFixed(2);
}
return v;
}
export function fetchDay(codes){
return (dispatch,getState)=>{
service.stock.fetchData(codes).then(res=>{
let stocks={};
let data=res._bodyText.split('\n');
data.forEach(line=>{
if(line.length<10) return;
let code=line.slice(2,10);
stocks[code]=stocks[code]||{};
stocks[code]=Object.assign(stocks[code],dayData(code,line));
});
dispatch({type:actionTypes.FETCH_STOCK_DATA,data:stocks});
});
}
}
export function fetchMinutes(code){
return (dispatch,getState)=>{
service.stock.fetchMinData(code).then(res=>{
debugger;
let data=res._bodyText;
});
}
}
export function fetchDayK(code){
return (dispatch,getState)=>{
}
} | jackz3/yunguba-onsenui | js/actions/stock.js | JavaScript | apache-2.0 | 1,655 |
var a = require('A/a');
a.A();
| wangyanxing/TypeScript | tests/baselines/reference/projectOutput/relativePaths/node/app.js | JavaScript | apache-2.0 | 33 |
(function () {
'use strict';
/**
* Provides AddMe dialog to add/remove a user to a contact collection.
*
* @requires
* emailMeDialog.html and ui.bootstrap module
*/
var controllerId1 = 'emailMeController';
var controllerId2 = 'emailMeModalController';
angular.module('app').controller(controllerId1, ['$scope', '$uibModal', 'common', emailMeController]);
angular.module('app').controller(controllerId2, ['$rootScope', '$uibModalInstance', 'profile',
'common', 'config', 'profileCollectionService',emailMeModalController]);
/**
* Parent controller, it passes profile to the child controller.
*
* @example
* To use this <a class="btn"
* ng-controller="emailMeController"
* ng-click="openEmailMeModal(vm.profile)">
*/
function emailMeController($scope, $uibModal, common) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId1);
/**
* Opens the AddMe modal dialog for the authenticated user in attempt
* to add/remove the target user.
* The button that has this method attached to should NOT show up if
* the request is not authenticated.
*
* @param
* profile: the user profile who is being added or removed by the
* authenticated user.
*/
$scope.openEmailMeModal = function (profile) {
var modalInstance = $uibModal.open({
templateUrl: '/wwwroot/app/profile/emailMe/emailMeDialog.html',
controller: 'emailMeModalController as vm',
resolve: { // passing to child controller below
profile: function () {
return profile;
},
}
});
};
}
/**
* Child controller used by the AddMeDialog.html, if a user is not authenticated
* the user should not see this modal.
*
* @param
* $rootScope: needed for $broadcast
* $modalInstance: needed for close and dismiss of the dialog
* profile: the target user profile
* common: for logging
* config: for events names
*/
function emailMeModalController($rootScope, $uibModalInstance, profile,
common, config, profileCollectionService) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId2);
var logError = getLogFn(controllerId2, 'error');
var logSuccess = getLogFn(controllerId2, 'success');
/* ---------------------------------------------------------- view model */
var vm = this;
vm.message = "";
vm.profile = profile;
vm.disableButton = false;
vm.send = send;
vm.cancel = cancel;
vm.btnText = "Send";
/* ---------------------------------------------------------- public methods */
// todo: disable send button once clicked
function send() {
vm.disableButton = true;
vm.btnText = "Sending...";
profileCollectionService.emailMe(profile.userName, vm.message).then(success, failed);
function success() {
$uibModalInstance.dismiss('cancel');
}
function failed(err) {
logError(err);
vm.disableButton = false;
vm.btnText = "Send";
}
}
function cancel() {
$uibModalInstance.dismiss('cancel');
};
}
})(); | FanrayMedia/Chef.me | Projects/Chef.Web/wwwroot/app/profile/emailMe/emailMeDialog.js | JavaScript | apache-2.0 | 3,593 |
/**
* @fileoverview
* (This file was autogenerated by opprotoc)
*
* The application is created in two steps:
*
* Step 1: All objects that do not depend on the services available from the
* debuggee. The only exception is the scope service, as it is needed
* to query the debuggee about what services it provides. All scope
* debuggees run the scope service, and it can not be disabled.
*
* Step 2: All service objects are created, based on their counterpart on
* the debuggee side. The second step uses
* a pattern where each service has a build function in
* "app.builders.<servuce class name>.<service version>.
* The builders are called as soon as service information have been
* received from the scope service. It's possible to hook up a callback
* after the second step has finished. The callback can either be
* passed as an argument to the build_application call, or by defining
* a function named window.app.on_services_created, which
* will be called automatically
*
*
* There is an other moment to hook up a callback.
* That is when all services are sucessfully enabled.
* The callback can either be passed to the build_application call
* as second argument or by defining a function named
* window.app.on_services_enabled
*
*/
if( window.app )
{
throw "window.app does already exist";
}
window.app = {};
/**
* If the connected host has a core intergation point prior to 168 the
* application will reload an according older application version.
* Core integartion 168 supports the following service versions:
*
* scope: 1.1
* console-logger: 2.0
* cookie-manager: 1.1.1
* document-manager: 1.1
* http-logger: 2.0
* exec: 2.1
* window-manager: 2.1
* widget-manager: 1.0
* resource-manager: 1.1
* prefs: 1.0
* ecmascript: 1.0
* ecmascript-debugger: 6.6
*
* "http-logger" is not present in this build.
* It is replaced by the "resource-manager".
*
*/
window.app.MIN_SUPPORTED_CORE_VERSION = 167;
window.cls.MessageMixin.apply(window.app); // Give the app object message handling powers
window.app.profiles = {};
window.app.profiles.DEFAULT = 1;
window.app.profiles.PROFILER = 2;
window.app.profiles.HTTP_PROFILER = 3;
window.app.profiles[window.app.profiles.DEFAULT] = ["window-manager",
"console-logger",
"exec",
"ecmascript-debugger",
"cookie-manager",
"resource-manager",
"document-manager"];
window.app.profiles[window.app.profiles.DEFAULT].is_enabled = false;
window.app.profiles[window.app.profiles.PROFILER] = ["window-manager",
"exec",
"profiler",
"overlay"];
window.app.profiles[window.app.profiles.PROFILER].is_enabled = false;
window.app.profiles[window.app.profiles.HTTP_PROFILER] = ["window-manager",
"resource-manager",
"document-manager",
"exec"];
window.app.profiles[window.app.profiles.HTTP_PROFILER].is_enabled = false;
window.app.build_application = function(on_services_created, on_services_enabled)
{
var app_ctx = {messages: window.messages};
var _find_compatible_version = function(version, version_list)
{
var
numbers = version.split(".").map(Number),
match = null,
ver, nums;
// Find the best match for the current version
for (ver in version_list)
{
nums = ver.split(".").map(Number);
if (nums[0] != numbers[0])
continue;
if (!match || (nums[1] > match[1][1] && nums[1] <= numbers[1]))
match = [ver, nums];
}
return match && match[0];
}
var on_host_info_callback = function(service_descriptions, hello_message)
{
var core_version = hello_message.coreVersion;
var core_integration = core_version && parseInt(core_version.split('.')[2]);
if (core_integration >= window.app.MIN_SUPPORTED_CORE_VERSION)
{
new window.cls.ScopeInterfaceGenerator().get_interface(service_descriptions,
function(map)
{
window.message_maps = map;
window.cls.ServiceBase.populate_map(map);
build_and_enable_services(service_descriptions, map);
},
function(error)
{
opera.postError(error.message);
},
Boolean(window.ini.debug)
);
}
else
{
window.client.handle_fallback("ci-168");
}
};
/**
* This callback is invoked when host info is received from the debuggee.
*
*/
var build_and_enable_services = function(service_descriptions, map)
{
var
service_name = '',
service = null,
class_name = '',
re_version = /(^\d+\.\d+)(?:\.\d+)?$/,
version = null,
i = 0,
builder = null,
numbers = null;
window.messages.clear_session_listeners();
var session_ctx =
{
messages: app_ctx.messages,
helpers: app_ctx.helpers,
tag_manager: app_ctx.tag_manager,
show_dragonfly_window: app_ctx.show_dragonfly_window,
services: app_ctx.services
};
for (service_name in service_descriptions)
{
service = service_descriptions[service_name];
version = re_version.exec(service.version);
version = version && version[1] || "0";
class_name = window.app.helpers.dash_to_class_name(service_name);
if (service_name != "scope")
{
if (window.services[service_name] &&
window.services[service_name].create_and_expose_interface(version, map[service_name]))
{
var
match_version = _find_compatible_version(version, window.app.builders[class_name]),
builder = window.app.builders[class_name] && window.app.builders[class_name][match_version];
if (builder)
{
// service_description is a dict of services
// with name and version for each service
// return false if the service shall not be enabled
var is_implemented = builder(service,
service_descriptions,
session_ctx);
window.services[service_name].is_implemented = is_implemented;
}
}
}
}
window.app.post('services-created', {'service_description': service_descriptions});
if (window.app.on_services_created)
{
window.app.on_services_created(service_descriptions);
}
if (on_services_created)
{
on_services_created(service_descriptions);
}
window.services.scope.enable_profile(window.settings.general.get("profile-mode") ||
window.app.profiles.DEFAULT);
}
var create_raw_interface = function(service_name)
{
var ServiceClass = function()
{
this.name = service_name;
this.is_implemented = false;
}
ServiceClass.prototype = new cls.ServiceBase();
ServiceClass.prototype.constructor = ServiceClass; // this is not really needed
window.services.add(new ServiceClass());
}
var report_usage = function()
{
if (settings.general.get("track-usage") &&
// Don't phone home when developing
// (port is typically only used in that situation).
!location.port)
{
var trackerurl = "/app/user-count"
var tracker = new cls.UserTracker(trackerurl);
var cb = function(status, url)
{
if (status != 200 && !cls.ScopeHTTPInterface.is_enabled)
{
opera.postError("Usertracker could not send heartbeat to tracker server at " + url + ". Got status " + status);
}
};
tracker.call_home(cb);
}
}
// ensure that the static methods on cls.ServiceBase exist.
new cls.ServiceBase();
new ActionBroker();
window.messages.addListener("application-setup", report_usage, true);
// global objects
window.tagManager = window.tag_manager = app_ctx.tag_manager = new window.cls.TagManager();
window.helpers = app_ctx.helpers = new cls.Helpers();
// create window.services namespace and register it.
app_ctx.services = new cls.Namespace("services");
cls.ServiceBase.register_services(app_ctx.services);
[
'scope',
'console-logger',
'exec',
'window-manager',
'ecmascript-debugger',
'cookie-manager',
'resource-manager',
'document-manager',
'profiler',
'overlay'
].forEach(create_raw_interface);
var params = this.helpers.parse_url_arguments();
if(params.debug)
{
cls.debug.create_debug_environment(params);
}
app_ctx.show_dragonfly_window = Boolean(params.showdfl);
var namespace = cls.Scope && cls.Scope["1.1"];
namespace.Service.apply(window.services.scope.constructor.prototype);
window.services.scope.is_implemented = true;
window.services.scope.set_host_info_callback(on_host_info_callback);
window.services.scope.set_services_enabled_callback(on_services_enabled);
/* Instatiations needed to setup the client */
/* General */
cls.GeneralView.prototype = ViewBase;
new cls.GeneralView('general', ui_strings.M_SETTING_LABEL_GENERAL, '');
cls.GeneralView.create_ui_widgets();
/* Monospace font selection */
cls.MonospaceFontView.prototype = ViewBase;
var view = new cls.MonospaceFontView('monospacefont',
ui_strings.M_VIEW_LABEL_MONOSPACE_FONT);
cls.MonospaceFontView.create_ui_widgets();
view.set_font_style();
/* Debug remote */
cls.DebugRemoteSettingView.prototype = ViewBase;
new cls.DebugRemoteSettingView('debug_remote_setting', ui_strings.S_SWITCH_REMOTE_DEBUG, '');
cls.DebugRemoteSettingView.create_ui_widgets();
/* PO tester */
new cls.PoTestView("test-po-file", "Test PO file", "scroll");
/* Shortcut config */
var GlobalView = function(id, name)
{
this.init(id, name);
};
GlobalView.prototype = ViewBase;
new GlobalView(ActionBroker.GLOBAL_HANDLER_ID, ui_strings.S_GLOBAL_KEYBOARD_SHORTCUTS_SECTION_TITLE);
cls.ShortcutConfigView.prototype = ViewBase;
new cls.ShortcutConfigView('shortcut-config', ui_strings.S_KEYBOARD_SHORTCUTS_CONFIGURATION, '');
cls.ShortcutConfigView.create_ui_widgets();
/* Modebar */
cls.ModebarView.prototype = ViewBase;
new cls.ModebarView('modebar', ui_strings.S_TOGGLE_DOM_MODEBAR_HEADER, '');
// create the client
if(window.services.scope)
{
window.ui_framework.setup();
window.client = new cls.Client();
client.setup();
messages.post('application-setup');
}
else
{
throw "scope service couldn't be created, application creation aborted";
}
}
/**
* The builders for each service and version.
* These calls can also be used to create other parts of the application
* which support a given service version.
* It is recommended ( but not required ) that classes which support a given
* service version are organized in an appropirate namespace, like
* ls.<service class name>.<service version>.
*/
window.app.builders = {};
window.app.helpers = {};
window.app.helpers.parse_url_arguments = function()
{
/*
supported arguments:
- debug
- log-filter
- showdfl
*/
var args = location.search.slice(1).split(/[;&]/);
var params = {};
for (var i = 0, arg; arg = args[i]; i++)
{
arg = arg.split('=');
params[arg[0].trim()] = arg[1] && arg[1].trim() || true;
}
return params;
}
window.app.helpers.dash_to_class_name = function(name)
{
for ( var cur = '', i = 0, ret = '', do_upper = true; cur = name[i]; i++)
{
if(cur == '-')
{
do_upper = true;
continue;
}
ret += do_upper && cur.toUpperCase() || cur;
do_upper = false;
}
return ret;
}
window.onload = function()
{
window.clearTimeout(window.load_screen_timeout);
new OperaDBLclickMenuController();
window.app.build_application();
}
| operasoftware/dragonfly | src/build-application/build_application.js | JavaScript | apache-2.0 | 12,434 |
/*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
* See README.md for more information
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific
*
*/
import _ from "lodash";
import {CORE_API} from "../../../common/services/core-api-utils";
import {buildHierarchies, doSearch, prepareSearchNodes} from "../../../common/hierarchy-utils";
import template from "./data-type-usage-count-tree.html";
import {mkAuthoritativeRatingSchemeItems} from "../../../ratings/rating-utils";
const bindings = {
onSelection: "<"
};
function ratingToRag(r) {
switch(r){
case "PRIMARY":
return "G";
case "SECONDARY":
return "A";
case "DISCOURAGED":
return "R";
case "NO_OPINION":
return "Z";
default:
return r;
}
}
function prepareTree(dataTypes = [], usageCounts = []) {
const dataTypesById = _.keyBy(dataTypes, "id");
_.chain(usageCounts)
.filter(uc => uc.decoratorEntityReference.kind === "DATA_TYPE")
.filter(uc => ! _.isNil(dataTypesById[uc.decoratorEntityReference.id]))
.forEach(uc => {
const dtId = uc.decoratorEntityReference.id;
const dt = dataTypesById[dtId];
const rag = ratingToRag(uc.rating);
dt.directCounts = Object.assign(
{},
dt.directCounts,
{ [rag] : uc.count });
})
.value();
const hierarchy = buildHierarchies(_.values(dataTypesById), false);
const sumBy = (rating, n) => {
if (!n) return 0;
const childTotals = _.sum(_.map(n.children, c => sumBy(rating, c)));
const total = childTotals + _.get(n, `directCounts.${rating}`, 0);
n.cumulativeCounts = Object.assign({}, n.cumulativeCounts, { [rating] : total });
return total;
};
_.forEach(hierarchy, root => {
const R = sumBy("R", root);
const A = sumBy("A", root);
const G = sumBy("G", root);
const Z = sumBy("Z", root);
root.cumulativeCounts = {
R,
A,
G,
Z,
total: R + A + G + Z
};
});
return hierarchy;
}
function prepareExpandedNodes(hierarchy = []) {
return hierarchy.length < 6 // pre-expand small trees
? _.clone(hierarchy)
: [];
}
function controller(displayNameService, serviceBroker) {
const vm = this;
vm.$onInit = () => {
vm.ratingSchemeItems = mkAuthoritativeRatingSchemeItems(displayNameService);
serviceBroker
.loadAppData(CORE_API.DataTypeStore.findAll, [])
.then(r => {
vm.dataTypes = r.data;
vm.searchNodes = prepareSearchNodes(vm.dataTypes);
})
.then(() => serviceBroker.loadViewData(CORE_API.LogicalFlowDecoratorStore.summarizeInboundForAll))
.then(r => {
vm.hierarchy = prepareTree(vm.dataTypes, r.data);
vm.maxTotal = _
.chain(vm.hierarchy)
.map("cumulativeCounts.total")
.max()
.value();
});
};
vm.treeOptions = {
nodeChildren: "children",
dirSelectable: true,
equality: (a, b) => a && b && a.id === b.id
};
vm.searchTermsChanged = (termStr = "") => {
const matchingNodes = doSearch(termStr, vm.searchNodes);
vm.hierarchy = prepareTree(matchingNodes);
vm.expandedNodes = prepareExpandedNodes(vm.hierarchy);
};
vm.clearSearch = () => {
vm.searchTermsChanged("");
vm.searchTerms = "";
};
}
controller.$inject = [
"DisplayNameService",
"ServiceBroker"
];
const component = {
bindings,
template,
controller
};
const id = "waltzDataTypeUsageCountTree";
export default {
id,
component
} | rovats/waltz | waltz-ng/client/data-types/components/usage-count-tree/data-type-usage-count-tree.js | JavaScript | apache-2.0 | 4,378 |
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDOMIDOperations
* @typechecks static-only
*/
/*jslint evil: true */
"use strict";
var CSSPropertyOperations = require("./CSSPropertyOperations");
var DOMChildrenOperations = require("./DOMChildrenOperations");
var DOMPropertyOperations = require("./DOMPropertyOperations");
var ReactID = require("./ReactID");
var getTextContentAccessor = require("./getTextContentAccessor");
var invariant = require("./invariant");
/**
* Errors for properties that should not be updated with `updatePropertyById()`.
*
* @type {object}
* @private
*/
var INVALID_PROPERTY_ERRORS = {
dangerouslySetInnerHTML:
'`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.',
style: '`style` must be set using `updateStylesByID()`.'
};
/**
* The DOM property to use when setting text content.
*
* @type {string}
* @private
*/
var textContentAccessor = getTextContentAccessor() || 'NA';
/**
* Operations used to process updates to DOM nodes. This is made injectable via
* `ReactComponent.DOMIDOperations`.
*/
var ReactDOMIDOperations = {
/**
* Updates a DOM node with new property values. This should only be used to
* update DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A valid property name, see `DOMProperty`.
* @param {*} value New value of the property.
* @internal
*/
updatePropertyByID: function(id, name, value) {
var node = ReactID.getNode(id);
invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name));
DOMPropertyOperations.setValueForProperty(node, name, value);
},
/**
* Updates a DOM node to remove a property. This should only be used to remove
* DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A property name to remove, see `DOMProperty`.
* @internal
*/
deletePropertyByID: function(id, name, value) {
var node = ReactID.getNode(id);
invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name));
DOMPropertyOperations.deleteValueForProperty(node, name, value);
},
/**
* This should almost never be used instead of `updatePropertyByID()` due to
* the extra object allocation required by the API. That said, this is useful
* for batching up several operations across worker thread boundaries.
*
* @param {string} id ID of the node to update.
* @param {object} properties A mapping of valid property names.
* @internal
* @see {ReactDOMIDOperations.updatePropertyByID}
*/
updatePropertiesByID: function(id, properties) {
for (var name in properties) {
if (!properties.hasOwnProperty(name)) {
continue;
}
ReactDOMIDOperations.updatePropertiesByID(id, name, properties[name]);
}
},
/**
* Updates a DOM node with new style values. If a value is specified as '',
* the corresponding style property will be unset.
*
* @param {string} id ID of the node to update.
* @param {object} styles Mapping from styles to values.
* @internal
*/
updateStylesByID: function(id, styles) {
var node = ReactID.getNode(id);
CSSPropertyOperations.setValueForStyles(node, styles);
},
/**
* Updates a DOM node's innerHTML set by `props.dangerouslySetInnerHTML`.
*
* @param {string} id ID of the node to update.
* @param {object} html An HTML object with the `__html` property.
* @internal
*/
updateInnerHTMLByID: function(id, html) {
var node = ReactID.getNode(id);
// HACK: IE8- normalize whitespace in innerHTML, removing leading spaces.
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
node.innerHTML = (html && html.__html || '').replace(/^ /g, ' ');
},
/**
* Updates a DOM node's text content set by `props.content`.
*
* @param {string} id ID of the node to update.
* @param {string} content Text content.
* @internal
*/
updateTextContentByID: function(id, content) {
var node = ReactID.getNode(id);
node[textContentAccessor] = content;
},
/**
* Replaces a DOM node that exists in the document with markup.
*
* @param {string} id ID of child to be replaced.
* @param {string} markup Dangerous markup to inject in place of child.
* @internal
* @see {Danger.dangerouslyReplaceNodeWithMarkup}
*/
dangerouslyReplaceNodeWithMarkupByID: function(id, markup) {
var node = ReactID.getNode(id);
DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup);
},
/**
* TODO: We only actually *need* to purge the cache when we remove elements.
* Detect if any elements were removed instead of blindly purging.
*/
manageChildrenByParentID: function(parentID, domOperations) {
var parent = ReactID.getNode(parentID);
DOMChildrenOperations.manageChildren(parent, domOperations);
}
};
module.exports = ReactDOMIDOperations;
| jordwalke/npm-react-core | modules/ReactDOMIDOperations.js | JavaScript | apache-2.0 | 5,510 |
// web/js/app/views/disabled-toggle-row.js
/* global Ember, App */
'use strict';
App.DisabledToggleRowView = Ember.View.extend({
templateName: 'disabledtogglerow',
tagName: 'tr',
classNames: ['no-hover']
});
| gophronesis/penny-sae | old/web/js/app/views/disabled-toggle-row.js | JavaScript | apache-2.0 | 216 |
// defaultable require() wrapper tests
//
// Copyright 2011 Jason Smith, Jarrett Cruger and contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var test = require('tap').test
, defaultable = require('../defaultable')
, D = defaultable
;
var m0dule = module;
test('require function', function(t) {
var _require = require;
defaultable({}, function(mod, exp, DEFS, require) {
t.ok(require, 'Defaultable provides a require paramenter')
t.type(require, 'function', 'provided require is a function')
t.equal(require.length, _require.length, 'Proved require() has the correct arity')
t.equal(require.name, _require.name, 'Provided require() is named correctly')
t.isNot(require, _require, 'Provided require() is not the normal require()')
})
t.end();
})
test('Exporting required modules', function(t) {
t.doesNotThrow(go, 'No problems with a defaultable re-exporting another defaultable');
function go() {
var mod;
mod = require('./mod/defaultable_reexporter');
t.type(mod.defaults, 'function', 'Re-exported defaults exists')
t.ok(mod.defaults._defaultable, 'Re-exporteed .defaults are mine')
t.equal(mod.defaultable_example, 'Defaultable dependency example', 'Re-exported defaults works')
mod = mod.defaults({'value': 'New value'})
t.type(mod.defaults, 'function', 'Re-exported re-defaulted defaults exists')
t.ok(mod.defaults._defaultable, 'Re-exporteed re-defaulted .defaults are mine')
t.equal(mod.defaultable_example, 'New value', 'Re-exported defaults override works')
}
t.end();
})
test('requiring defaultable modules passes defaults to them', function(t) {
function i_require_stuff(_mod, exps, _DEF, require) {
exps.is = require('./mod/is_defaultable');
exps.is_not = require('./mod/is_not_defaultable');
exps.legacy = require('./mod/legacy_defaults');
exps.fresh = require('./mod/fresh_defaultable');
}
var mod;
var defs = { 'should': 'first' };
t.doesNotThrow(function() { mod = D(m0dule, defs, i_require_stuff) }, 'Defaultable and non-defaultable modules are usable')
check_mod('first');
mod = mod.defaults({should:'second'});
check_mod('second');
mod = mod.defaults({should:'third'});
check_mod('third');
t.end();
function check_mod(should_val) {
t.type(mod.legacy.defaults, 'function', 'Legacy modules can export .defaults()')
t.notOk(mod.legacy.defaults._defaultable, 'Legacy modules .defaults are not mine')
t.throws(mod.legacy.defaults, 'Legacy .defaults() function runs like it always has')
t.type(mod.is_not.get, 'function', 'Normal modules still export normally')
t.equal(mod.is_not.get(), 'normal', 'Normal modules export normal stuff')
t.notOk(mod.is_not.defaults, 'Normal modules do not have a defaults() function')
t.equal(Object.keys(mod.is_not).length, 2, 'Normal modules export the same exact stuff')
t.notOk(mod.is_not.req._defaultable, 'Normal modules require is not special')
t.type(mod.is.get, 'function', 'Defaultable modules export normally')
t.equal(mod.is.get('original'), 'value', 'Defaultable module still has its defaults')
t.equal(mod.is.get('should'), should_val, 'Defaultable module inherits defaults with require() ' + should_val)
t.type(mod.is.defaults, 'function', 'Defaultable modules still have defaults() functions')
t.ok(mod.is.defaults._defaultable, 'Defaultable modules default() functions are recognizable')
t.equal(Object.keys(mod.is).length, 3+1, 'Defaultable modules export the same stuff, plus defaults()')
t.ok(mod.is.req._defaultable, 'Defaultable modules get the special require')
t.equal(mod.is.dep(), 'Example dependency', 'Defaultable module can require stuff from node_modules/')
t.type(mod.fresh.get, 'function', 'Fresh defaultable module still exports normally')
t.type(mod.fresh.defaults, 'function', 'Fresh defaultable module still has defaults() function')
t.ok(mod.fresh.defaults._defaultable, 'Fresh defautlable module defaults() is recognizable')
t.equal(mod.fresh.get('should'), 'always fresh', 'Fresh defaultable module defauts not changed by require')
var fresh2 = mod.fresh.defaults({'should':should_val});
t.equal(fresh2.get('should'), should_val, 'Fresh defaultable module can set defaults normally')
}
})
| nodejitsu/defaultable | t/require.js | JavaScript | apache-2.0 | 4,847 |
$(document).ready(function() {
$('#fieldrent_maintain').DataTable(
{
"aLengthMenu" : [ 2, 4, 6, 8, 10 ], //动态指定分页后每页显示的记录数。
"lengthChange" : true, //是否启用改变每页显示多少条数据的控件
"bSort" : false,
"iDisplayLength" : 8, //默认每页显示多少条记录
"dom" : 'ftipr<"bottom"l>',
"ajax" : {
"url" : "landRentInfo.do",
"type" : "POST"
},
"aoColumns" : [
{
"mData" : "id",
"orderable" : true, // 禁用排序
"sDefaultContent" : "",
"sWidth" : "6%",
},
{
"mData" : "startTime",
"orderable" : true, // 禁用排序
"sDefaultContent" : "",
"sWidth" : "6%"
},
{
"mData" : "endTime",
"orderable" : true, // 禁用排序
"sDefaultContent" : "",
"sWidth" : "6%"
},
{
"mData" : "bname",
"orderable" : false, // 禁用排序
"sDefaultContent" : "",
"sWidth" : "10%"
},
{
"mData" : "lid",
"orderable" : true, // 禁用排序
"sDefaultContent" : "",
"sWidth" : "8%"
},
{
"mData" : "name",
"orderable" : true, // 禁用排序
"sDefaultContent" : "",
"sWidth" : "8%"
},
{
"mData" : "deptName",
"orderable" : true, // 禁用排序
"sDefaultContent" : "",
"sWidth" : "8%"
},
{
"mData" : "times",
"orderable" : true, // 禁用排序
"sDefaultContent" : "",
"sWidth" : "8%"
},
{
"mData" : "planting",
"orderable" : true, // 禁用排序
"sDefaultContent" : "",
"sWidth" : "8%"
},
{
"mData" : "lr_id",
"orderable" : false, // 禁用排序
"sDefaultContent" : '',
"sWidth" : "5%",
"render" : function(data, type, row) { //render改变该列样式,4个参数,其中参数数量是可变的。
return data = '<span class="glyphicon glyphicon-pencil" data-id='+data+' data-toggle="modal" data-target="#myModal3"></span>';
}
}
//data指该行获取到的该列数据
//row指该行,可用row.name或row[2]获取第3列字段名为name的值
//type调用数据类型,可用类型“filter”,"display","type","sort",具体用法还未研究
//meta包含请求行索引,列索引,tables各参数等信息
],
"columnDefs" :
[{
"orderable" : false, // 禁用排序
"targets" : [0], // 指定的列
"data" : "id",
"render" : function(data, type, row) {
data=row.lr_id;
return '<input type="checkbox" value="'+ data + '" name="idname" />';
}
}],
"language" : {
"lengthMenu" : "每页 _MENU_ 条记录",
"zeroRecords" : "没有找到记录",
"info" : "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )",
"infoEmpty" : "无记录",
"infoFiltered" : "(从 _MAX_ 条记录过滤)",
"sSearch" : "模糊查询:",
"oPaginate" : {
"sFirst" : "首页",
"sPrevious" : " 上一页 ",
"sNext" : " 下一页 ",
"sLast" : " 尾页 "
}
}
});
});
/* 全选,反选按钮 */
/*
* allCkBox2(); function allCkBox2(id){ var tableBox =
* document.getElementById(id||"fieldrent_maintain"), ck =
* tableBox.getElementsByClassName("ck"), ckAll =
* tableBox.getElementsByClassName("ck-all")[0], ckRe =
* tableBox.getElementsByClassName("ck-re")[0]; ckAll.onchange = function(){
* allCk(this.checked); }; ckRe.onchange = function(){ reCk(); }; function
* allCk(bool){ for(var i =0; i<ck.length;i++){ ck[i].checked = bool; } }
*
* function reCk(){ for(var i =0; i<ck.length;i++){ ck[i].checked ?
* ck[i].checked = false : ck[i].checked = true; } } }
*/ | pange123/PB_Management | 前台界面/pbweb/js/myNeed/rentMaintain.js | JavaScript | apache-2.0 | 3,837 |
'use strict';
// mocha defines to avoid JSHint breakage
/* global describe, it, before, beforeEach, after, afterEach */
var assert = require('../utils/assert.js');
var server = require('../utils/server.js');
var preq = require('preq');
var P = require('bluebird');
var simple_service = require('../../mods/simple_service');
describe('simple_service', function () {
this.timeout(20000);
before(function () { return server.start(); });
// A test page that includes the current date, so that it changes if
// re-rendered more than a second apart.
var testPage = server.config.baseURL + '/service/test/User:GWicke%2fDate';
function hasTextContentType(res) {
assert.contentType(res, 'text/html');
}
var slice;
it('retrieve content from backend service', function () {
var tid1;
var tid2;
return preq.get({
uri: testPage
})
.then(function (res) {
assert.deepEqual(res.status, 200);
tid1 = res.headers.etag;
hasTextContentType(res);
// Delay for 1s to make sure that the content differs on
// re-render, then force a re-render and check that it happened.
slice = server.config.logStream.slice();
return P.delay(1100)
.then(function() {
return preq.get({
uri: testPage,
headers: { 'cache-control': 'no-cache' }
});
});
})
.then(function (res) {
tid2 = res.headers.etag;
assert.notDeepEqual(tid2, tid1);
assert.notDeepEqual(tid2, undefined);
hasTextContentType(res);
slice.halt();
assert.remoteRequests(slice, true);
// delay for 1s to let the content change on re-render
slice = server.config.logStream.slice();
// Check retrieval of a stored render
return P.delay(1100)
.then(function() {
return preq.get({
uri: testPage,
});
});
})
.then(function (res) {
var tid3 = res.headers.etag;
assert.deepEqual(tid3, tid2);
assert.notDeepEqual(tid3, undefined);
// Check that there were no remote requests
slice.halt();
assert.remoteRequests(slice, false);
hasTextContentType(res);
});
});
it('validates config: checks parallel returning requests', function() {
return P.try(function() {
simple_service({
paths: {
test_path: {
get: {
on_request: [
{
get_one: {
request: {
uri: 'http://en.wikipedia.org/wiki/One'
},
return: '{$.get_one}'
},
get_two: {
request: {
uri: 'http://en.wikipedia.org/wiki/Two'
},
return: '{$.get_two}'
}
}
]
}
}
}
})
})
.then(function() {
throw new Error('Should throw error');
}, function(e) {
// Error expected
assert.deepEqual(/^Invalid spec\. Returning requests cannot be parallel\..*/.test(e.message), true);
});
});
it('validates config: requires either return or request', function() {
return P.try(function() {
simple_service({
paths: {
test_path: {
get: {
on_request: [
{
get_one: {}
}
]
}
}
}
})
})
.then(function() {
throw new Error('Should throw error');
}, function(e) {
// Error expected
assert.deepEqual(/^Invalid spec\. Either request or return must be specified\..*/.test(e.message), true);
});
});
it('validates config: requires request for return_if', function() {
return P.try(function() {
simple_service({
paths: {
test_path: {
get: {
on_request: [
{
get_one: {
return_if: {
status: '5xx'
},
return: '$.request'
}
}
]
}
}
}
})
})
.then(function() {
throw new Error('Should throw error');
}, function(e) {
// Error expected
assert.deepEqual(/^Invalid spec\. return_if should have a matching request\..*/.test(e.message), true);
});
});
it('validates config: requires request for catch', function() {
return P.try(function() {
simple_service({
paths: {
test_path: {
get: {
on_request: [
{
get_one: {
catch: {
status: '5xx'
},
return: '$.request'
}
}
]
}
}
}
})
})
.then(function() {
throw new Error('Should throw error');
}, function(e) {
// Error expected
assert.deepEqual(/^Invalid spec\. catch should have a matching request\..*/.test(e.message), true);
});
});
});
| physikerwelt/restbase | test/features/simple_service.js | JavaScript | apache-2.0 | 6,685 |
/*global QUnit */
sap.ui.define([
"sap/m/Button",
"sap/m/CheckBox",
"sap/m/OverflowToolbar",
"sap/m/OverflowToolbarButton",
"sap/m/Panel",
"sap/ui/dt/DesignTime",
"sap/ui/dt/OverlayRegistry",
"sap/ui/fl/write/api/ChangesWriteAPI",
"sap/ui/rta/command/CommandFactory",
"sap/ui/rta/plugin/Combine",
"sap/ui/rta/Utils",
"sap/ui/thirdparty/sinon-4",
"test-resources/sap/ui/rta/qunit/RtaQunitUtils",
"sap/ui/core/mvc/View",
"sap/ui/core/Core"
], function(
Button,
CheckBox,
OverflowToolbar,
OverflowToolbarButton,
Panel,
DesignTime,
OverlayRegistry,
ChangesWriteAPI,
CommandFactory,
CombinePlugin,
Utils,
sinon,
RtaQunitUtils,
View,
oCore
) {
"use strict";
var DEFAULT_DTM = "default";
var oMockedAppComponent = RtaQunitUtils.createAndStubAppComponent(sinon, "Dummy");
var sandbox = sinon.createSandbox();
var fnSetOverlayDesigntimeMetadata = function (oOverlay, oDesignTimeMetadata, bEnabled) {
bEnabled = bEnabled === undefined || bEnabled === null ? true : bEnabled;
if (oDesignTimeMetadata === DEFAULT_DTM) {
oDesignTimeMetadata = {
actions: {
combine: {
changeType: "combineStuff",
changeOnRelevantContainer: true,
isEnabled: bEnabled
}
}
};
}
oOverlay.setDesignTimeMetadata(oDesignTimeMetadata);
};
//Designtime Metadata with fake isEnabled function (returns false)
var oDesignTimeMetadata1 = {
actions: {
combine: {
changeType: "combineStuff",
changeOnRelevantContainer: true,
isEnabled: function() {
return false;
}
}
}
};
//Designtime Metadata with fake isEnabled function (returns true)
var oDesignTimeMetadata2 = {
actions: {
combine: {
changeType: "combineStuff",
changeOnRelevantContainer: true,
isEnabled: function() {
return true;
}
}
}
};
// DesignTime Metadata without changeType
var oDesignTimeMetadata3 = {
actions: {
combine: {
changeOnRelevantContainer: true,
isEnabled: true
}
}
};
// DesignTime Metadata without changeOnRelevantContainer
var oDesigntimeMetadata4 = {
actions: {
combine: {
changeType: "combineStuff",
isEnabled: function() {
return true;
}
}
}
};
//DesignTime Metadata with different changeType
var oDesignTimeMetadata5 = {
actions: {
combine: {
changeType: "combineOtherStuff",
changeOnRelevantContainer: true,
isEnabled: true
}
}
};
QUnit.module("Given a designTime and combine plugin are instantiated", {
beforeEach: function(assert) {
var done = assert.async();
sandbox.stub(ChangesWriteAPI, "getChangeHandler").resolves();
this.oCommandFactory = new CommandFactory();
this.oCombinePlugin = new CombinePlugin({
commandFactory: this.oCommandFactory
});
this.oButton1 = new Button("button1");
this.oButton2 = new Button("button2");
this.oButton3 = new Button("button3");
this.oButton4 = new Button("button4");
this.oButton5 = new Button("button5");
this.oPanel = new Panel("panel", {
content: [
this.oButton1,
this.oButton2,
this.oButton3,
this.oButton4
]
});
this.oPanel2 = new Panel("panel2", {
content: [
this.oButton5
]
});
this.oOverflowToolbarButton1 = new OverflowToolbarButton("owerflowbutton1");
this.oButton6 = new Button("button6");
this.oCheckBox1 = new CheckBox("checkbox1");
this.OverflowToolbar = new OverflowToolbar("OWFlToolbar", {
content: [
this.oOverflowToolbarButton1,
this.oButton6,
this.oCheckBox1
]
});
this.oView = new View({
content: [
this.oPanel,
this.oPanel2,
this.OverflowToolbar
]
}).placeAt("qunit-fixture");
oCore.applyChanges();
this.oDesignTime = new DesignTime({
rootElements: [this.oPanel, this.oPanel2, this.OverflowToolbar],
plugins: [this.oCombinePlugin],
designTimeMetadata: {
"sap.m.Button": {
actions: {
combine: {
changeType: "combineStuff",
changeOnRelevantContainer: true,
isEnabled: true
}
}
},
"sap.m.OverflowToolbarButton": {
actions: {
combine: {
changeType: "combineStuff",
changeOnRelevantContainer: true,
isEnabled: true
}
}
},
"sap.m.CheckBox": {
actions: {
combine: {
changeType: "combineOtherStuff",
changeOnRelevantContainer: true,
isEnabled: true
}
}
}
}
});
this.oDesignTime.attachEventOnce("synced", function() {
this.oButton1Overlay = OverlayRegistry.getOverlay(this.oButton1);
this.oButton2Overlay = OverlayRegistry.getOverlay(this.oButton2);
this.oButton3Overlay = OverlayRegistry.getOverlay(this.oButton3);
this.oButton4Overlay = OverlayRegistry.getOverlay(this.oButton4);
this.oButton5Overlay = OverlayRegistry.getOverlay(this.oButton5);
this.oButton6Overlay = OverlayRegistry.getOverlay(this.oButton6);
this.oPanelOverlay = OverlayRegistry.getOverlay(this.oPanel);
this.oPanel2Overlay = OverlayRegistry.getOverlay(this.oPanel2);
this.oOverflowToolbarButton1Overlay = OverlayRegistry.getOverlay(this.oOverflowToolbarButton1);
this.oCheckBox1Overlay = OverlayRegistry.getOverlay(this.oCheckBox1);
this.OverflowToolbarOverlay = OverlayRegistry.getOverlay(this.OverflowToolbar);
done();
}.bind(this));
},
afterEach: function() {
sandbox.restore();
this.oDesignTime.destroy();
this.oPanel.destroy();
this.oPanel2.destroy();
this.OverflowToolbar.destroy();
}
}, function() {
QUnit.test("when an overlay has no combine action in designTime metadata", function(assert) {
fnSetOverlayDesigntimeMetadata(this.oButton1Overlay, {});
fnSetOverlayDesigntimeMetadata(this.oButton2Overlay, {});
assert.strictEqual(
this.oCombinePlugin.isAvailable([this.oButton1Overlay]),
false,
"isAvailable is called and returns false"
);
assert.strictEqual(
this.oCombinePlugin.isEnabled([this.oButton1Overlay]),
false,
"isEnabled is called and returns false"
);
return Promise.resolve()
.then(this.oCombinePlugin._isEditable.bind(this.oCombinePlugin, this.oButton1Overlay))
.then(function(bEditable) {
assert.strictEqual(
bEditable,
false,
"then the overlay is not editable"
);
});
});
QUnit.test("when an overlay has a combine action in designTime metadata", function(assert) {
fnSetOverlayDesigntimeMetadata(this.oButton1Overlay, DEFAULT_DTM);
fnSetOverlayDesigntimeMetadata(this.oButton2Overlay, oDesignTimeMetadata2);
sandbox.stub(Utils, "checkSourceTargetBindingCompatibility").returns(true);
sandbox.stub(this.oCombinePlugin, "hasChangeHandler").resolves(true);
assert.strictEqual(
this.oCombinePlugin.isAvailable([this.oButton1Overlay, this.oButton2Overlay]),
true,
"isAvailable is called and returns true"
);
assert.strictEqual(
this.oCombinePlugin.isEnabled([this.oButton1Overlay, this.oButton2Overlay]),
true,
"isEnabled is called and returns true"
);
return this.oCombinePlugin._isEditable(this.oButton1Overlay)
.then(function(bEditable) {
assert.strictEqual(
bEditable,
true,
"then the overlay is editable"
);
});
});
QUnit.test("when two elements have different binding context", function(assert) {
sandbox.stub(Utils, "checkSourceTargetBindingCompatibility").returns(false);
assert.strictEqual(
this.oCombinePlugin.isAvailable([this.oButton1Overlay, this.oButton2Overlay]),
true,
"isAvailable is called and returns true"
);
assert.strictEqual(
this.oCombinePlugin.isEnabled([this.oButton1Overlay, this.oButton2Overlay]),
false,
"isEnabled is called and returns false"
);
});
QUnit.test("when only one control is specified", function(assert) {
fnSetOverlayDesigntimeMetadata(this.oButton1Overlay, DEFAULT_DTM);
assert.strictEqual(
this.oCombinePlugin.isAvailable([this.oButton1Overlay]),
false,
"isAvailable is called and returns false"
);
assert.strictEqual(
this.oCombinePlugin.isEnabled([this.oButton1Overlay]),
false,
"isEnabled is called and returns false"
);
});
QUnit.test("when controls which enabled function delivers false are specified", function(assert) {
fnSetOverlayDesigntimeMetadata(this.oButton1Overlay, oDesignTimeMetadata1);
fnSetOverlayDesigntimeMetadata(this.oButton2Overlay, oDesignTimeMetadata1);
assert.strictEqual(
this.oCombinePlugin.isAvailable([this.oButton1Overlay, this.oButton2Overlay]),
true,
"isAvailable is called and returns true"
);
assert.strictEqual(
this.oCombinePlugin.isEnabled([this.oButton1Overlay, this.oButton2Overlay]),
false,
"isEnabled is called and returns false"
);
});
QUnit.test("when a control without change type is specified", function(assert) {
fnSetOverlayDesigntimeMetadata(this.oButton1Overlay, DEFAULT_DTM);
fnSetOverlayDesigntimeMetadata(this.oButton4Overlay, oDesignTimeMetadata3);
assert.strictEqual(
this.oCombinePlugin.isAvailable([this.oButton1Overlay]),
false,
"isAvailable is called and returns false"
);
assert.strictEqual(
this.oCombinePlugin.isEnabled([this.oButton1Overlay]),
false,
"isEnabled is called and returns false"
);
});
QUnit.test("when controls from different relevant containers are specified", function(assert) {
fnSetOverlayDesigntimeMetadata(this.oButton1Overlay, DEFAULT_DTM);
fnSetOverlayDesigntimeMetadata(this.oButton5Overlay, DEFAULT_DTM);
assert.strictEqual(
this.oCombinePlugin.isAvailable([this.oButton1Overlay]),
false,
"isAvailable is called and returns false"
);
assert.strictEqual(
this.oCombinePlugin.isEnabled([this.oButton1Overlay]),
false,
"isEnabled is called and returns false"
);
});
QUnit.test("when handleCombine is called with two elements, being triggered on the second element", function(assert) {
var oFireElementModifiedSpy = sandbox.spy(this.oCombinePlugin, "fireElementModified");
var oGetCommandForSpy = sandbox.spy(this.oCommandFactory, "getCommandFor");
fnSetOverlayDesigntimeMetadata(this.oButton1Overlay, DEFAULT_DTM);
fnSetOverlayDesigntimeMetadata(this.oButton2Overlay, DEFAULT_DTM);
return this.oCombinePlugin.handleCombine([this.oButton1Overlay, this.oButton2Overlay], this.oButton2)
.then(function() {
assert.ok(oFireElementModifiedSpy.calledOnce, "fireElementModified is called once");
assert.ok(oGetCommandForSpy.calledWith(this.oButton2), "command creation is triggered with correct context element");
}.bind(this))
.catch(function (oError) {
assert.ok(false, "catch must never be called - Error: " + oError);
});
});
QUnit.test("when an overlay has a combine action designTime metadata which has no changeOnRelevantContainer", function(assert) {
fnSetOverlayDesigntimeMetadata(this.oButton1Overlay, oDesigntimeMetadata4);
return Promise.resolve()
.then(this.oCombinePlugin._isEditable.bind(this.oCombinePlugin, this.oButton1Overlay))
.then(function(bEditable) {
assert.strictEqual(bEditable, false, "then the overlay is not editable");
});
});
QUnit.test("when Controls of different type with same change type are specified", function (assert) {
assert.expect(9);
fnSetOverlayDesigntimeMetadata(this.oOverflowToolbarButton1Overlay, DEFAULT_DTM);
fnSetOverlayDesigntimeMetadata(this.oButton6Overlay, DEFAULT_DTM);
sandbox.stub(Utils, "checkSourceTargetBindingCompatibility").returns(true);
assert.strictEqual(
this.oCombinePlugin.isAvailable([this.oOverflowToolbarButton1Overlay, this.oButton6Overlay]),
true,
"isAvailable is called and returns true"
);
assert.strictEqual(
this.oCombinePlugin.isEnabled([this.oOverflowToolbarButton1Overlay, this.oButton6Overlay]),
true,
"isEnabled is called and returns true"
);
var bIsAvailable = true;
sinon.stub(this.oCombinePlugin, "isAvailable").callsFake(function (aElementOverlays) {
assert.equal(aElementOverlays[0].getId(), this.oButton6Overlay.getId(), "the 'available' function calls isAvailable with the correct overlay");
return bIsAvailable;
}.bind(this));
sinon.stub(this.oCombinePlugin, "handleCombine").callsFake(function (aElementOverlays, oCombineElement) {
assert.equal(aElementOverlays[0].getId(), this.oButton6Overlay.getId(), "the 'handler' method is called with the right overlay");
assert.equal(oCombineElement.getId(), this.oButton6.getId(), "the 'handler' method is called with the right combine element");
}.bind(this));
var aMenuItems = this.oCombinePlugin.getMenuItems([this.oButton6Overlay]);
assert.equal(aMenuItems[0].id, "CTX_GROUP_FIELDS", "'getMenuItems' returns the context menu item for the plugin");
aMenuItems[0].handler([this.oButton6Overlay], { contextElement: this.oButton6 });
aMenuItems[0].enabled([this.oButton6Overlay]);
bIsAvailable = false;
assert.equal(this.oCombinePlugin.getMenuItems([this.oButton6Overlay]).length, 0, "and if plugin is not available for the overlay, no menu items are returned");
});
QUnit.test("when Controls of different type with different change type are specified", function(assert) {
fnSetOverlayDesigntimeMetadata(this.oOverflowToolbarButton1Overlay, DEFAULT_DTM);
fnSetOverlayDesigntimeMetadata(this.oCheckBox1Overlay, oDesignTimeMetadata5);
assert.strictEqual(
this.oCombinePlugin.isAvailable([this.oOverflowToolbarButton1Overlay, this.oCheckBox1Overlay]),
false,
"isAvailable is called and returns false"
);
assert.strictEqual(
this.oCombinePlugin.isEnabled([this.oOverflowToolbarButton1Overlay, this.oCheckBox1Overlay]),
false,
"isEnabled is called and returns false"
);
});
QUnit.test("when the relevant container does not have a stable id", function(assert) {
fnSetOverlayDesigntimeMetadata(this.oOverflowToolbarButton1Overlay, DEFAULT_DTM);
sandbox.stub(this.oCombinePlugin, "hasStableId").callsFake(function(oOverlay) {
if (oOverlay === this.OverflowToolbarOverlay) {
return false;
}
return true;
}.bind(this));
return this.oCombinePlugin._isEditable(this.oOverflowToolbarButton1Overlay)
.then(function(bEditable) {
assert.strictEqual(
bEditable,
false,
"_isEditable returns false"
);
});
});
});
QUnit.done(function() {
oMockedAppComponent.destroy();
jQuery("#qunit-fixture").hide();
});
});
| SAP/openui5 | src/sap.ui.rta/test/sap/ui/rta/qunit/plugin/Combine.qunit.js | JavaScript | apache-2.0 | 14,533 |
'use strict';
const _ = require('lodash');
/**
A location.
@param options.address string The top address line of the delivery pickup options.
@param options.address_2 string The second address line of the delivery pickup options such as the apartment number. This field is optional.
@param options.city string The city of the delivery pickup options.
@param options.state string The state of the delivery pickup options such as “CA”.
@param options.postal_code string The postal code of the delivery pickup options.
@param options.country string The country of the delivery pickup options such as “US".
*/
class Location {
constructor(options) {
_.each(options, (value, key) => {
if (key == 'country') {
if (!value || value.length != 2) return false;
}
this[key] = value;
});
}
}
module.exports = Location;
| mjk/uber-rush | lib/Location.js | JavaScript | apache-2.0 | 871 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* Logistic distribution cumulative distribution function (CDF).
*
* @module @stdlib/stats/base/dists/logistic/cdf
*
* @example
* var cdf = require( '@stdlib/stats/base/dists/logistic/cdf' );
*
* var y = cdf( 2.0, 0.0, 1.0 );
* // returns ~0.881
*
* var mycdf = cdf.factory( 3.0, 1.5 );
*
* y = mycdf( 1.0 );
* // returns ~0.209
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var cdf = require( './cdf.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( cdf, 'factory', factory );
// EXPORTS //
module.exports = cdf;
| stdlib-js/stdlib | lib/node_modules/@stdlib/stats/base/dists/logistic/cdf/lib/index.js | JavaScript | apache-2.0 | 1,237 |
(function () {
'use strict';
angular
.module('wordsearchApp')
.config(pagerConfig);
pagerConfig.$inject = ['uibPagerConfig', 'paginationConstants'];
function pagerConfig(uibPagerConfig, paginationConstants) {
uibPagerConfig.itemsPerPage = paginationConstants.itemsPerPage;
uibPagerConfig.previousText = '«';
uibPagerConfig.nextText = '»';
}
})();
| hillwater/wordsearch | src/main/webapp/app/blocks/config/uib-pager.config.js | JavaScript | apache-2.0 | 412 |
/**
* Copyright 2015 Brendan Murray
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
// Dependency - dht sensor package
var sensorLib = require("node-dht-sensor");
module.exports = function(RED) {
"use strict";
// The main node definition - most things happen in here
function dht22Sensor(config) {
// Mapping tables
var gpio = [ -1, -1, 8, -1, 9, -1, 7, 15, -1, 16,
0, 1, 2, -1, 3, 4, -1, 5, 12, -1,
13, 6, 14, 10, -1, 11, -1, -1, 21, -1,
22, 26, 23, -1, 24, 27, 25, 28, -1, 29 ];
var bcm1 = [ -1, -1, 0, -1, 1, -1, 4, 14, -1, 15,
17, 18, 21, -1, 22, 23, -1, 24, 10, -1,
9, 25, 11, 8, -1, 7, -1, -1, 5, -1,
6, 12, 13, -1, 19, 16, 26, 20, -1, 21 ];
var bcm2 = [ -1, -1, 2, -1, 3, -1, 4, 14, -1, 15,
17, 18, 27, -1, 22, 23, -1, 24, 10, -1,
9, 25, 11, 8, -1, 7, -1, -1, 5, -1,
6, 12, 13, -1, 19, 16, 26, 20, -1, 21 ];
// Create a RED node
RED.nodes.createNode(this, config);
// Store local copies of the node configuration (as defined in the .html)
var node = this;
this.topic = config.topic;
this.dht = config.dht;
if (config.pintype == 0) { // BCM GPIO pin
this.pin = config.pin;
} else if (config.pintype == 1) { // Physical pin number - Rev 1
this.pin = bcm1[config.pin-1];
} else if (config.pintype == 2) { // Physical pin number - Rev 2
this.pin = bcm2[config.pin-1];
} else if (config.pintype == 3) { // WiringPi pin number - Rev 1
for (var iX=0; iX<40; iX++) {
if (gpio[iX] == config.pin) {
this.pin = bcm1[iX];
break;
}
}
} else { // WiringPi pin number - Rev 2
for (var iX=0; iX<40; iX++) {
if (gpio[iX] == config.pin) {
this.pin = bcm2[iX];
break;
}
}
}
// Read the data & return a message object
this.read = function(msgIn) {
var msg = msgIn ? msgIn : {};
var reading = { temperature : 100.0, humidity : 110.0 };
if (this.dht === undefined || this.pin === undefined) {
// Miscommunication - use silly values
} else {
// Read the data from the sensors
reading = sensorLib.read(this.dht, this.pin);
}
msg.payload = reading.temperature.toFixed(2);
msg.humidity = reading.humidity.toFixed(2);
msg.isValid = reading.isValid;
msg.errors = reading.errors;
msg.topic = node.topic || node.name;
msg.location = node.name;
msg.sensorid = 'dht' + node.dht;
return msg;
};
// respond to inputs....
this.on('input', function (msg) {
msg = this.read(msg);
if (msg)
node.send(msg);
});
// var msg = this.read();
// // send out the message to the rest of the workspace.
// if (msg)
// this.send(msg);
}
// Register the node by name.
RED.nodes.registerType("rpi-dht22", dht22Sensor);
}
| bpmurray/node-red-contrib-dht-sensor | dht22-node/dht22-node.js | JavaScript | apache-2.0 | 3,759 |
'use strict';
/**
* Removes server error when user updates input
*/
angular.module('fluxApp')
.directive('mongooseError', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
element.on('keydown', function() {
return ngModel.$setValidity('mongoose', true);
});
}
};
}); | mysmartcity/flux | client/components/mongoose-error/mongoose-error.directive.js | JavaScript | apache-2.0 | 388 |
define(['jquery'],
function($){
var internals = {};
internals.createTooltip = function(){
internals.tooltip = internals.settings.el.find('.tooltip');
internals.onLoad();
};
internals.updateTooltip = function(e){
if (e.countyDisplay){
internals.tooltip.html(e.statistics.location + '<br />' + e.statistics.state);
}
else{
internals.tooltip.html(e.statistics.location);
}
};
internals.showTooltip = function(){
internals.settings.el.css('opacity','1');
};
internals.hideTooltip = function(){
internals.settings.el.css('opacity','0');
};
internals.moveTooltip = function(e){
var width = internals.tooltip.outerWidth();
var height = internals.tooltip.outerHeight();
var topMargin = -(height + 20);
var leftMargin = -(width/2);
if (e.hoverPosition.x < 110){
leftMargin = -10;
}
else if (e.hoverPosition.x > $('.map').outerWidth() - 110){
leftMargin = -(width - 10);
}
if (e.hoverPosition.y < (height + 20)){
internals.settings.el.addClass('display-under');
topMargin = 0;
}
else{
internals.settings.el.removeClass('display-under');
}
internals.settings.el.css({
'top': e.hoverPosition.y,
'left': e.hoverPosition.x
});
internals.tooltip.css({
'margin-top': topMargin,
'margin-left': leftMargin
});
};
internals.onLoad = function(){
$(internals.self).trigger('load');
};
return function (options){
var defaults = {
el: $('.tooltip-wrapper'),
includeGeocoder: true
};
internals.settings = $.extend(true,defaults,options);
internals.self = this;
this.init = function(){
internals.createTooltip();
};
$(internals.settings.data).on('tooltip-show',internals.showTooltip);
$(internals.settings.data).on('tooltip-hide',internals.hideTooltip);
$(internals.settings.data).on('select',internals.updateTooltip);
$(internals.settings.data).on('hover-position-change',internals.moveTooltip);
};
}); | ssylvia/living-wage-map | src/javascript/ui/Tooltip.js | JavaScript | apache-2.0 | 2,186 |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
/// <reference path="C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0\ExtensionSDKs\Microsoft.WinJS.1.0\1.0\DesignTime\CommonConfiguration\Neutral\Microsoft.WinJS.1.0\js\base.js" />
/// <reference path="C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0\ExtensionSDKs\Microsoft.WinJS.1.0\1.0\DesignTime\CommonConfiguration\Neutral\Microsoft.WinJS.1.0\js\ui.js" />
/// <reference path="..\..\js\MobileServices.Internals.js" />
/// <reference path="..\..\generated\Tests.js" />
$testGroup('Push')
.functional()
.tag('push')
.tests(
$test('InitialUnregisterAll')
.description('Unregister all registrations with both the default and updated channel. Ensure no registrations still exist for either.')
.checkAsync(function () {
var client = $getClient();
var channelUri = defaultChannel;
return client.push.unregisterAll(channelUri)
.then(
function () {
return client.push.registrationManager.pushHttpClient.listRegistrations(channelUri);
})
.then(
function (registrations) {
$assert.isTrue(Array.isArray(registrations), 'Expect to get an array from listRegistrations');
$assert.areEqual(registrations.length, 0, 'Expect no registrations to be returned after unregisterAll');
$assert.areEqual(client.push.registrationManager.localStorageManager.registrations.size, 0, 'Expect local storage to contain no registrations after unregisterAll');
channelUri = updatedChannel;
return client.push.unregisterAll(channelUri);
})
.then(
function () {
return client.push.registrationManager.pushHttpClient.listRegistrations(channelUri);
})
.then(
function (registrations) {
$assert.isTrue(Array.isArray(registrations), 'Expect to get an array from listRegistrations');
$assert.areEqual(registrations.length, 0, 'Expect no registrations to be returned after unregisterAll');
$assert.areEqual(client.push.registrationManager.localStorageManager.registrations.size, 0, 'Expect local storage to contain no registrations after unregisterAll');
return WinJS.Promise.wrap();
});
}),
$test('RegisterNativeUnregisterNative')
.description('Register a native channel followed by unregistering it.')
.checkAsync(function () {
var client = $getClient();
var channelUri = defaultChannel;
return client.push.registerNative(channelUri)
.then(
function () {
return client.push.registrationManager.pushHttpClient.listRegistrations(channelUri);
})
.then(
function (registrations) {
$assert.isTrue(Array.isArray(registrations), 'Expect to get an array from listRegistrations');
$assert.areEqual(registrations.length, 1, 'Expect 1 registration to be returned after register');
$assert.areEqual(client.push.registrationManager.localStorageManager.registrations.size, 1, 'Expect local storage to contain 1 registration after register');
var localRegistration = client.push.registrationManager.localStorageManager.getFirstRegistrationByRegistrationId(registrations[0].registrationId);
$assert.isTrue(localRegistration, 'Expect local storage to have the registrationId returned from service');
$assert.areEqual(client.push.registrationManager.localStorageManager.channelUri, registrations[0].deviceId, 'Local storage should have channelUri from returned registration');
return client.push.unregisterNative();
})
.then(
function () {
return client.push.registrationManager.pushHttpClient.listRegistrations(channelUri);
})
.then(
function (registrations) {
$assert.isTrue(Array.isArray(registrations), 'Expect to get an array from listRegistrations');
$assert.areEqual(registrations.length, 0, 'Expect no registrations to be returned after unregisterNative');
$assert.areEqual(client.push.registrationManager.localStorageManager.registrations.size, 0, 'Expect local storage to contain no registrations after unregisterNative');
return WinJS.Promise.wrap();
});
}),
$test('RegisterTemplateUnregisterTemplate')
.description('Register a template followed by unregistering it.')
.checkAsync(function () {
var client = $getClient();
var channelUri = defaultChannel;
return client.push.registerTemplate(channelUri, templateBody, templateName, defaultHeaders, defaultTags)
.then(
function () {
return client.push.registrationManager.pushHttpClient.listRegistrations(channelUri);
})
.then(
function (registrations) {
$assert.isTrue(Array.isArray(registrations), 'Expect to get an array from listRegistrations');
$assert.areEqual(registrations.length, 1, 'Expect 1 registration to be returned after register');
$assert.areEqual(client.push.registrationManager.localStorageManager.registrations.size, 1, 'Expect local storage to contain 1 registration after register');
var localRegistration = client.push.registrationManager.localStorageManager.getFirstRegistrationByRegistrationId(registrations[0].registrationId);
$assert.isTrue(localRegistration, 'Expect local storage to have the registrationId returned from service');
$assert.areEqual(client.push.registrationManager.localStorageManager.channelUri, registrations[0].deviceId, 'Local storage should have channelUri from returned registration');
$assert.areEqual(registrations[0].deviceId, channelUri, 'Returned registration should use channelUri sent from registered template');
Object.getOwnPropertyNames(registrations[0].headers).forEach(function (header) {
$assert.areEqual(registrations[0].headers[header], defaultHeaders[header], 'Each header returned by registration should match what was registered.');
});
$assert.areEqual(Object.getOwnPropertyNames(registrations[0].headers).length, Object.getOwnPropertyNames(defaultHeaders).length, 'Returned registration should contain same number of headers sent from registered template');
$assert.areEqual(registrations[0].tags.length, defaultTags.length + 1, 'Returned registration should contain tags sent from registered template and 1 extra for installationId');
// TODO: Re-enable when .Net runtime supports installationID in service
//$assert.isTrue(registrations[0].tags.indexOf(WindowsAzure.MobileServiceClient._applicationInstallationId) > -1, 'Expected the installationID in the tags');
$assert.areEqual(registrations[0].templateName, templateName, 'Expected returned registration to use templateName it was fed');
$assert.areEqual(registrations[0].templateBody, templateBody, 'Expected returned registration to use templateBody it was fed');
$assert.areEqual(client.push.registrationManager.localStorageManager.getRegistration(templateName).registrationId, registrations[0].registrationId, 'Expected the stored registrationId to equal the one returned from service');
return client.push.unregisterTemplate(templateName);
})
.then(
function () {
return client.push.registrationManager.pushHttpClient.listRegistrations(channelUri);
})
.then(
function (registrations) {
$assert.isTrue(Array.isArray(registrations), 'Expect to get an array from listRegistrations');
$assert.areEqual(registrations.length, 0, 'Expect no registrations to be returned after unregisterTemplate');
$assert.areEqual(client.push.registrationManager.localStorageManager.registrations.size, 0, 'Expect local storage to contain no registrations after unregisterTemplate');
});
}),
$test('RegisterRefreshRegisterWithUpdatedChannel')
.description('Register a template followed by a refresh of the client local storage followed by updated register of same template name.')
.checkAsync(function () {
var client = $getClient();
var channelUri = defaultChannel;
return client.push.registerTemplate(channelUri, templateBody, templateName, defaultHeaders, defaultTags)
.then(
function () {
return client.push.registrationManager.pushHttpClient.listRegistrations(channelUri);
})
.then(
function (registrations) {
$assert.isTrue(Array.isArray(registrations), 'Expect to get an array from listRegistrations');
$assert.areEqual(registrations.length, 1, 'Expect 1 registration to be returned after register');
$assert.areEqual(client.push.registrationManager.localStorageManager.registrations.size, 1, 'Expect local storage to contain 1 registration after register');
var localRegistration = client.push.registrationManager.localStorageManager.getFirstRegistrationByRegistrationId(registrations[0].registrationId);
$assert.isTrue(localRegistration, 'Expect local storage to have the registrationId returned from service');
$assert.areEqual(client.push.registrationManager.localStorageManager.channelUri, registrations[0].deviceId, 'Local storage should have channelUri from returned registration');
$assert.areEqual(registrations[0].deviceId, channelUri, 'Returned registration should use channelUri sent from registered template');
Object.getOwnPropertyNames(registrations[0].headers).forEach(function (header) {
$assert.areEqual(registrations[0].headers[header], defaultHeaders[header], 'Each header returned by registration should match what was registered.');
});
$assert.areEqual(Object.getOwnPropertyNames(registrations[0].headers).length, Object.getOwnPropertyNames(defaultHeaders).length, 'Returned registration should contain same number of headers sent from registered template');
$assert.areEqual(registrations[0].tags.length, defaultTags.length + 1, 'Returned registration should contain tags sent from registered template and 1 extra for installationId');
// TODO: Re-enable when .Net runtime supports installationID in service
//$assert.isTrue(registrations[0].tags.indexOf(WindowsAzure.MobileServiceClient._applicationInstallationId) > -1, 'Expected the installationID in the tags');
$assert.areEqual(registrations[0].templateName, templateName, 'Expected returned registration to use templateName it was fed');
$assert.areEqual(registrations[0].templateBody, templateBody, 'Expected returned registration to use templateBody it was fed');
$assert.areEqual(client.push.registrationManager.localStorageManager.getRegistration(templateName).registrationId, registrations[0].registrationId, 'Expected the stored registrationId to equal the one returned from service');
client.push.registrationManager.localStorageManager.isRefreshNeeded = true;
channelUri = updatedChannel;
return client.push.registerTemplate(channelUri, templateBody, templateName, defaultHeaders, defaultTags);
})
.then(
function () {
return client.push.registrationManager.pushHttpClient.listRegistrations(channelUri);
})
.then(
function (registrations) {
$assert.isTrue(Array.isArray(registrations), 'Expect to get an array from listRegistrations');
$assert.areEqual(registrations.length, 1, 'Expect 1 registration to be returned after register');
$assert.areEqual(client.push.registrationManager.localStorageManager.registrations.size, 1, 'Expect local storage to contain 1 registration after register');
var localRegistration = client.push.registrationManager.localStorageManager.getFirstRegistrationByRegistrationId(registrations[0].registrationId);
$assert.isTrue(localRegistration, 'Expect local storage to have the registrationId returned from service');
$assert.areEqual(client.push.registrationManager.localStorageManager.channelUri, registrations[0].deviceId, 'Local storage should have channelUri from returned registration');
$assert.areEqual(registrations[0].deviceId, channelUri, 'Returned registration should use channelUri sent from registered template');
Object.getOwnPropertyNames(registrations[0].headers).forEach(function (header) {
$assert.areEqual(registrations[0].headers[header], defaultHeaders[header], 'Each header returned by registration should match what was registered.');
});
$assert.areEqual(Object.getOwnPropertyNames(registrations[0].headers).length, Object.getOwnPropertyNames(defaultHeaders).length, 'Returned registration should contain same number of headers sent from registered template');
$assert.areEqual(registrations[0].tags.length, defaultTags.length + 1, 'Returned registration should contain tags sent from registered template and 1 extra for installationId');
// TODO: Re-enable when .Net runtime supports installationID in service
//$assert.isTrue(registrations[0].tags.indexOf(WindowsAzure.MobileServiceClient._applicationInstallationId) > -1, 'Expected the installationID in the tags');
$assert.areEqual(registrations[0].templateName, templateName, 'Expected returned registration to use templateName it was fed');
$assert.areEqual(registrations[0].templateBody, templateBody, 'Expected returned registration to use templateBody it was fed');
$assert.areEqual(client.push.registrationManager.localStorageManager.getRegistration(templateName).registrationId, registrations[0].registrationId, 'Expected the stored registrationId to equal the one returned from service');
$assert.areEqual(registrations[0].deviceId, updatedChannel, 'Expected the return channelUri to be the updated one');
$assert.areEqual(client.push.registrationManager.localStorageManager.channelUri, updatedChannel, 'Expected localstorage channelUri to be the updated one');
return client.push.unregisterTemplate(templateName);
})
.then(
function () {
return client.push.registrationManager.pushHttpClient.listRegistrations(channelUri);
})
.then(
function (registrations) {
$assert.isTrue(Array.isArray(registrations), 'Expect to get an array from listRegistrations');
$assert.areEqual(registrations.length, 0, 'Expect no registrations to be returned after unregisterTemplate');
$assert.areEqual(client.push.registrationManager.localStorageManager.registrations.size, 0, 'Expect local storage to contain no registrations after unregisterTemplate');
});
})
);
var defaultChannel = 'https://bn2.notify.windows.com/?token=AgYAAADs42685sa5PFCEy82eYpuG8WCPB098AWHnwR8kNRQLwUwf%2f9p%2fy0r82m4hxrLSQ%2bfl5aNlSk99E4jrhEatfsWgyutFzqQxHcLk0Xun3mufO2G%2fb2b%2ftjQjCjVcBESjWvY%3d';
var updatedChannel = 'https://bn2.notify.windows.com/?token=BgYAAADs42685sa5PFCEy82eYpuG8WCPB098AWHnwR8kNRQLwUwf%2f9p%2fy0r82m4hxrLSQ%2bfl5aNlSk99E4jrhEatfsWgyutFzqQxHcLk0Xun3mufO2G%2fb2b%2ftjQjCjVcBESjWvY%3d';
var templateBody = '<toast><visual><binding template=\"ToastText01\"><text id=\"1\">$(message)</text></binding></visual></toast>';
var templateName = 'templateForToastWinJS';
var defaultTags = ['fooWinJS', 'barWinJS'];
var defaultHeaders = { 'x-wns-type': 'wns/toast', 'x-wns-ttl': '100000' }; | manimaranm7/azure-mobile-services | sdk/Javascript/test/winJS/tests/winJsOnly/push.js | JavaScript | apache-2.0 | 17,764 |
/*
* Copyright 2016 Maroš Šeleng
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
angular.module('symphonia.services')
.factory('SaveAndSendService', function ($q, $log, $cordovaDevice, $cordovaFile, $cordovaEmailComposer, $cordovaFileOpener2) {
var outputData = '';
var format = '';
var tmpName = 'tmpData';
var cacheFolder = undefined;
var savedFileDetails = {
path: undefined,
name: undefined // WITHOUT EXTENSION!!
};
function _open() {
var mime = format === 'xml' ? 'text/xml' : 'application/pdf';
return $cordovaFileOpener2.open(savedFileDetails.path + savedFileDetails.name + '.' + format, mime);
}
function _compose() {
if (savedFileDetails.path !== undefined) {
//file already saved!
return alreadySaved();
} else {
cacheFolder = getCacheDir();
return $cordovaFile.writeFile(cacheFolder, tmpName + '.' + format, outputData, true)
.then(function () {
$log.info('File \'' + tmpName + '.' + format + '\' saved at: \'' + cacheFolder + '\'.');
savedFileDetails.path = cacheFolder;
savedFileDetails.name = tmpName;
return selectAttachment(cacheFolder, tmpName);
}, function (error) {
$log.error('Failed to save file to cache directory:' + error);
return $q.reject('An error occurred while saving the file.');
});
}
}
function _saveFile(filename) {
var saveDestination = $cordovaDevice.getPlatform() === 'iOS' ? cordova.file.dataDirectory : cordova.file.externalDataDirectory;
if (savedFileDetails.path !== undefined && savedFileDetails.path === getCacheDir()) {
//already saved in the cache folder
return alreadyInCache(saveDestination, filename);
} else {
return $cordovaFile.writeFile(saveDestination, filename + '.' + format, outputData, true)
.then(function (success) {
savedFileDetails.path = saveDestination;
savedFileDetails.name = filename;
var message = 'File \'' + filename + '.' + format + '\' saved to \'' + saveDestination + '\'.';
$log.info(message);
return $q.resolve(message);
}, function (error) {
var message = 'Failed to save the file';
$log.error(message + '\n' + error);
return $q.reject(message);
});
}
}
function alreadySaved() {
$log.info('Picking a file \'' + savedFileDetails.name + '.' + format + '\' from \'' + savedFileDetails.path + '\' instead of caching one.');
return selectAttachment(savedFileDetails.path, savedFileDetails.name);
}
function selectAttachment(directory, fileName) {
$log.info('Selecting a file \'' + fileName + '.' + format + '\' from \'' + directory + '\' as an attachment.');
return $cordovaFile.readAsDataURL(directory, fileName + '.' + format)
.then(function (success) {
var data64 = success.split(';base64,').pop();
return openComposer(data64);
}, function (error) {
$log.info('File (\'' + fileName + '.' + format + '\' in \'' + directory + '\') to send NOT read:\n' + error);
return $q.reject('Failed to read the attachment file.');
});
}
function openComposer(data) {
var attachment = 'base64:' + savedFileDetails.name + '.' + format + '//' + data;
return $cordovaEmailComposer.isAvailable()
.then(function () {
var emailDetails = {
app: 'mailto',
attachments: [
attachment
],
subject: 'Digitized music scores',
body: 'This email contains file with music scores, that was produced by the <a href="https://www.symphonia.io">SYMPHONIA.IO</a> service.',
isHtml: true
};
return $cordovaEmailComposer.open(emailDetails)
.catch(function () {
return $q.resolve();
// because the open() function always goes to the error callback; no matter if success or not.
});
}, function () {
return $q.reject('Email composer not available.');
});
}
function alreadyInCache(newDestination, newName) {
return $cordovaFile.moveFile(getCacheDir(), tmpName + '.' + format, newDestination, newName + '.' + format)
.then(function () {
$log.info('File \'' + tmpName + '.' + format + '\' moved from cache and saved to \'' + newDestination + '\' as \'' + newName + '.' + format + '\'.');
savedFileDetails.path = newDestination;
savedFileDetails.name = newName;
var message = 'File \'' + newName + '.' + format + '\' saved to \'' + newDestination + '\'.';
return $q.resolve(message);
}, function (error) {
$log.error('Failed to move file from cache to storage: ' + error);
return $q.reject('Failed to save the file.');
});
}
function getCacheDir() {
return cordova.file.cacheDirectory;
}
function fuckIt(buffer) {
return new Blob([buffer], {type: 'application/pdf'});
}
return {
setOutputDataAndFormat: function (data, dataFormat) {
// FIXME: Is this really a good way?
outputData = fuckIt(data);
cacheFolder = undefined;
savedFileDetails.path = undefined;
savedFileDetails.name = undefined;
format = dataFormat == 'musicxml' ? 'xml' : 'pdf';
},
open: _open,
composeEmail: _compose,
saveFile: _saveFile,
showSendButton: function () {
return $cordovaEmailComposer.isAvailable()
}
}
});
| SymphoniaIO/Symphonia.io-Mobile | www/js/service/SaveAndSendService.js | JavaScript | apache-2.0 | 6,208 |
export function foo() {
return 'hello world';
}
| ampproject/rollup-plugin-closure-compiler | test/hashbang/fixtures/hashbang-banner.js | JavaScript | apache-2.0 | 49 |
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const DatastoreOperation_1 = require("./DatastoreOperation");
const Core_1 = require("../Core");
const BasicUtils_1 = require("../utility/BasicUtils");
const Messaging_1 = require("../Messaging");
class DatastoreFlush extends DatastoreOperation_1.DatastoreBaseOperation {
constructor(model, idsOrKeys) {
super(model);
this.flushIds = [];
this.usingKeys = false;
if (idsOrKeys != null) {
if (Array.isArray(idsOrKeys)) {
this.flushIds = idsOrKeys;
}
else {
this.flushIds = [idsOrKeys];
}
if (typeof this.flushIds[0] === "object") {
if (this.flushIds[0].kind === this.kind) {
this.usingKeys = true;
}
else {
Messaging_1.throwError(Messaging_1.CreateMessage.OPERATION_KEYS_WRONG(this.model, "FLUSH IN CACHE"));
}
}
else {
this.flushIds = this.flushIds.map(id => {
if (this.idType === "int" && BasicUtils_1.isNumber(id)) {
return Core_1.default.Instance.dsModule.int(id);
}
else if (this.idType === "string" && typeof id === "string") {
if (id.length === 0) {
Messaging_1.throwError(Messaging_1.CreateMessage.OPERATION_STRING_ID_EMPTY(this.model, "FLUSH IN CACHE"));
}
return id;
}
Messaging_1.throwError(Messaging_1.CreateMessage.OPERATION_DATA_ID_TYPE_ERROR(this.model, "FLUSH IN CACHE", id));
});
}
}
}
run() {
return __awaiter(this, void 0, void 0, function* () {
let flushKeys;
if (this.usingKeys) {
flushKeys = this.flushIds.map(this.augmentKey);
}
else {
const baseKey = this.getBaseKey();
flushKeys = this.flushIds.map(id => {
return this.createFullKey(baseKey.concat(this.kind, id));
});
}
if (Core_1.default.Instance.cacheStore != null) {
yield Core_1.default.Instance.cacheStore.flushEntitiesByKeys(flushKeys);
}
else {
Messaging_1.warn(`Trying to flush some ids / keys of [${this.kind}] - but no Cache Store has been set on Pebblebed instance!`);
}
});
}
}
exports.default = DatastoreFlush;
//# sourceMappingURL=DatastoreFlush.js.map | lostpebble/pebblebed | dist/operations/DatastoreFlush.js | JavaScript | apache-2.0 | 3,302 |
describe('sandbox library - xml2Json', function () {
this.timeout(1000 * 60);
var Sandbox = require('../../../'),
context;
beforeEach(function (done) {
Sandbox.createContext({}, function (err, ctx) {
context = ctx;
done(err);
});
});
afterEach(function () {
context.dispose();
context = null;
});
it('should exist', function (done) {
context.execute(`
var assert = require('assert');
assert.strictEqual(typeof xml2Json, 'function', 'typeof xml2Json must be function');
`, done);
});
it('should have basic functionality working', function (done) {
context.execute(`
var assert = require('assert'),
xml = '<food><key>Homestyle Breakfast</key><value>950</value></food>',
object = xml2Json(xml).food;
assert.strictEqual(object.key, 'Homestyle Breakfast', 'xml2Json conversion must be valid');
assert.strictEqual(object.value, '950', 'xml2Json conversion must be valid');
`, done);
});
});
| postmanlabs/postman-sandbox | test/unit/sandbox-libraries/xml2Json.test.js | JavaScript | apache-2.0 | 1,119 |
var querystring = require('querystring');
var http = require('http');
var config = require("../conf/conf.js");
var static_cookie = "";
var callNsApi = function(opt, post,cb) {
if (!opt.headers)
opt.headers = {};
if (static_cookie && opt) {
cookie = (static_cookie + "").split(";").shift();
opt.headers.Cookie = cookie;
//console.log("SEND",static_cookie,opt.path);
}else{
//console.log(static_cookie);
}
if(post){
opt.headers['Content-Type'] ='application/x-www-form-urlencoded';
opt.headers['Content-Length'] = post.length;
}
//console.log("SEND",opt);
//console.log("SEND",opt.path);
//console.log(opt,post);
var post_req = http.request(opt, function(res) {
res.setEncoding('utf8');
if(res.headers["set-cookie"])
static_cookie = res.headers["set-cookie"];
//console.log("REP",res.headers)
var data = "";
res.on('data', function (chunk) {
data += chunk;
});
res.on('error',function(err){
cb(err,null);
});
res.on('end', function (){
try{
var json_data = JSON.parse(data);
if(json_data.error)
cb(json_data.error,data);
else
cb(null, json_data);
}catch(e){
console.log(data);
cb(e, null);
}
});
});
post_req.on('error',function(err){
cb(err,null);
});
if(post){
post_req.write(post);
}
post_req.end();
};
module.exports.pushUri =function (uri,post,cb){
var post_data = null;
if(post)
post_data = querystring.stringify(post);
var opt = {
host: config.api.url,
port: 80,
path: '/api/1/'+config.api.key+uri,
headers: null
};
if (post)
opt.method='POST';
callNsApi(opt,post_data,cb);
};
| Iragne/NSAPIUnitTest | libs/http.js | JavaScript | apache-2.0 | 1,754 |
({
browsers: ['GOOGLECHROME', "IE11"],
selector: {
literal: '.m-literal span',
expression: '.m-expr span',
changeValuesBtn: '.change-values'
},
testFalsy: {
test: [
function(cmp) {
var expected = 'false';
var element = cmp
.getElement()
.shadowRoot
.querySelector(this.selector.literal);
return new Promise(function(resolve) {
var actual = element.textContent;
$A.test.assertEquals(actual, expected, 'Wrong literal');
resolve();
});
}
]
},
testGVPexpression: {
test: [
function(cmp) {
var expected = 'Renderer';
var element = cmp
.getElement()
.shadowRoot
.querySelector(this.selector.expression);
return new Promise(function(resolve) {
var actual = element.textContent;
$A.test.assertEquals(actual, expected, 'Wrong expression result');
resolve();
});
}
]
},
testProgrammaticInstantiation: {
test: [
function (cmp) {
var done = false;
$A.createComponent('markup://moduleTest:simpleCmp', {
'aura:id': 'programmatic'
}, $A.getCallback(function (simpleCmp) {
cmp.set('v.programmatic', simpleCmp);
done = true;
}));
$A.test.addWaitFor(true, function () {
return done;
});
},
function (cmp) {
var el = document
.querySelector('.programmatic')
.querySelector('moduletest-simple-cmp');
var message = 'Should support programmatic instantiation with an aura:id';
$A.test.assertTrue(el !== null, message);
}
]
},
testAttributesAreReflectedOnInteropComponent: {
test: [
function defaultProps(cmp) {
var list = cmp.find('list');
$A.test.assertEquals(
list.get('v.items').length,
0,
'Wrong number of items on InteropComponent'
);
$A.test.assertEquals(
list.getElement().items.length,
0,
'Wrong number of items on Element'
);
},
function updateProps(cmp) {
var list = cmp.find('list');
cmp.set('v.items', [{ label: 'item1', id: "1" }, { label: 'item2', id: "2" }]);
$A.test.assertEquals(
list.get('v.items').length,
2,
'Wrong number of items on InteropComponent'
);
$A.test.assertEquals(
list.getElement().items.length,
2,
'Wrong number of items on Element'
);
},
function renderUpdatedProps(cmp) {
var itemElement = cmp
.find('list')
.getElement()
.shadowRoot
.querySelectorAll('li');
$A.test.assertEquals(
itemElement.length,
2,
'Wrong number of items has been rendered'
);
}
]
},
testReturnsDefaultFromInteropComponent: {
test: [
function defaultProps(cmp) {
var list = cmp.find('list-without-items');
// The default value held by the InteropComponent element shouldn't be retrievable using the cmp.get
$A.test.assertEquals(
0,
list.get('v.items').length,
'Wrong number of items on InteropComponent'
);
$A.test.assertEquals(
0,
list.getElement().items.length,
'Wrong number of items on Element'
);
}
]
},
testUpdateAttributeWhenNotBoundInTheTemplate: {
test: [
function updateProps(cmp) {
var list = cmp.find('list-without-items');
list.set('v.items', [{ label: 'item1', id: 1 }, { label: 'item2', id: 2 }]);
$A.test.assertEquals(
2,
list.get('v.items').length,
'Wrong number of items on InteropComponent'
);
$A.test.assertEquals(
2,
list.getElement().items.length,
'Wrong number of items on Element'
);
},
function renderUpdatedProps(cmp) {
var itemElement = cmp
.find('list-without-items')
.getElement()
.shadowRoot
.querySelectorAll('li');
$A.test.assertEquals(
2,
itemElement.length,
'Wrong number of items has been rendered'
);
}
]
},
testCanReadPublicAccessors: {
test: [
function (cmp) {
var interopCmp = cmp.find('main');
$A.test.assertEquals('accessor-test-value', interopCmp.get('v.myAccessor'), 'should be able to read public accessor');
}
]
},
testCanReadUpdatedAccessorValue: {
test: [
function (cmp) {
var interopCmp = cmp.find('main');
interopCmp.getElement().shadowRoot.querySelector(this.selector.changeValuesBtn).click();
$A.test.assertEquals('modified-accessor-value', interopCmp.get('v.myAccessor'), 'should be able to read accessor modified value');
}
]
},
testCanPassPRV: {
test: [
function (cmp) {
$A.test.assertEquals('accessor-test-value', cmp.get('v.accessorValue'), 'accessor value should be reflected on the PRV.');
var interopCmp = cmp.find('main');
interopCmp.getElement().shadowRoot.querySelector(this.selector.changeValuesBtn).click();
$A.test.assertEquals('modified-accessor-value', cmp.get('v.accessorValue'), 'should be able to read accessor modified value from the bound template');
}
]
},
testAccessorIgnoresPassedPrimitiveValue: {
test: [
function (cmp) {
var interopCmp = cmp.find('accessor-primitive-value');
$A.test.assertEquals('accessor-test-value', interopCmp.get('v.myAccessor'), 'accessor should ignore passed primitive value.');
var interopCmp = cmp.find('accessor-primitive-value');
interopCmp.getElement().shadowRoot.querySelector(this.selector.changeValuesBtn).click();
$A.test.assertEquals('modified-accessor-value', interopCmp.get('v.myAccessor'), 'should be able to read accessor modified value');
}
]
},
// Interop: Cannot get value of attribute that's not bound to parent cmp #784
testCanGetUnboundAttributes: {
test: [
function(cmp) {
var unboundChild = cmp.find('unbound');
var attributes = ['literal', 'bound', 'unbound', 'expression', 'nested'];
attributes.forEach(function(attribute) {
$A.test.assertDefined(unboundChild.get('v.' + attribute), 'attribute [' + attribute + '] should be defined');
});
}
]
},
getNullValueText: function (cmp) {
return cmp
.find('nullTest')
.getElement()
.shadowRoot
.querySelector('.null-test')
.innerText;
},
testNullValue: {
attributes: {
'nullValueTest': 'John',
},
test: [
function(cmp) {
var actual = this.getNullValueText(cmp);
$A.test.assertEquals('John', actual, 'The bound value should be John');
cmp.set("v.nullValueTest", null);
},
function (cmp) {
var actual = this.getNullValueText(cmp);
$A.test.assertEquals('', actual, 'After setting the nullTest attribute to null the rendered text should be empty');
}
]
},
testUndefinedValue: {
attributes: {
'nullValueTest': 'John',
},
test: [
function(cmp) {
var actual = this.getNullValueText(cmp);
$A.test.assertEquals('John', actual, 'The bound value should be John');
cmp.set("v.nullValueTest", undefined);
},
function (cmp) {
var actual = this.getNullValueText(cmp);
$A.test.assertEquals('', actual, 'After setting the nullTest attribute to undefined the rendered text should be empty');
}
]
},
testReadOnlyAttrUpdatesWhenItsDependentChanged: {
test: [
function(cmp) {
var target = cmp.find('input');
var validity = target.get('v.validity');
$A.test.assertEquals('', validity);
target.set('v.value', 'foo');
validity = target.get('v.validity');
$A.test.assertEquals('foo', validity);
}
]
},
testReadOnlyBoundAttrUpdatesWhenItsDependentChanged: {
test: [
function(cmp) {
var target = cmp.find('input');
var myValidity = cmp.get('v.myValidity');
$A.test.assertEquals('', myValidity);
target.set('v.value', 'foo');
myValidity = cmp.get('v.myValidity');
$A.test.assertEquals('foo', myValidity);
}
]
},
testAuraActionAttributeIsCalledWhenEventIsFired: {
attributes: {
'result': '',
},
test: [
function(cmp) {
var target = cmp.find('input1');
target.set('v.value', 'foo');
var detail = {
value: 'foo'
};
target.getElement().shadowRoot.querySelector('input').dispatchEvent(
new CustomEvent('change', {
composed: true,
bubbles: true,
detail: detail,
})
);
$A.test.assertEquals(cmp.get('v.result'), 'foo');
}
]
},
testCreateComponentWithAuraActionAttribute: {
test: [
function(cmp) {
$A.createComponent(
"moduleTest:simpleInput",
{
"onchange": cmp.get('v.onChange'),
"aura:id": "input2"
},
function(newCmp) {
var body = cmp.get("v.body");
body.push(newCmp);
cmp.set("v.body", body);
}
);
},
function(cmp) {
var target = cmp.find('input2');
target.set('v.value', 'bar');
var detail = {
value: 'bar'
};
target.getElement().shadowRoot.querySelector('input').dispatchEvent(
new CustomEvent('change', {
composed: true,
bubbles: true,
detail: detail,
})
);
$A.test.assertEquals(cmp.get('v.result'), 'bar');
}
]
},
testBooleanAttributeUpdatesWhenChangeHappenedInElement: {
test: [
function(cmp) {
var target = cmp.find('inputRadio');
target.set('v.checked', false);
target.getElement().shadowRoot.querySelector('input').click();
$A.test.assertTrue(cmp.get('v.radioChecked'));
}
]
},
testCompatGetAttribute: {
test: [
function(cmp) {
var target = cmp.find('input');
target.set('v.value', 'foo');
var validity = target.get('v.inputValidity');
$A.test.assertTrue(validity.valid);
}
]
},
testDynamicCreationNonExistentAttr: {
test: [
function(cmp) {
var createdCmp;
$A.createComponent("moduletest:simpleCmp", { nonExistent: "foo" }, function(newCmp) {
createdCmp = newCmp;
});
$A.test.addWaitFor(true, function() { return createdCmp !== undefined; }, function() {
$A.test.assertNotNull(createdCmp, "No component returned from $A.createComponent");
var qualifiedName = createdCmp.getDef().getDescriptor().getQualifiedName();
$A.test.assertEquals("markup://moduleTest:simpleCmp", qualifiedName, "Unexpected component returned from $A.createComponent");
});
}
]
}
})
| forcedotcom/aura | aura-modules/src/test/components/moduleTest/interopAttrTest/interopAttrTestTest.js | JavaScript | apache-2.0 | 13,703 |
define(['backbone', 'backbone.paginator'], function(Backbone, PageableCollection) {
var LogLine = Backbone.Model.extend({
idAttribute: 'LINE',
})
return PageableCollection.extend({
model: LogLine,
url: function() { return '/status/log/'+this.bl },
mode: 'infinite',
initialize: function(attrs, options){
this.bl = options.bl
this.running = true
if (options && options.running == false) this.running = false
this.refresh_thread = null
},
stop: function() {
clearTimeout(this.refresh_thread)
this.running = false
},
parseRecords: function(r, options) {
clearTimeout(this.refresh_thread)
if (this.running) this.refresh_thread = setTimeout(this.fetch.bind(this), 5000)
var lines = []
_.each(r.reverse(), function(l) {
lines.push({ LINE: l })
})
return lines
},
})
}) | DiamondLightSource/SynchWeb | client/src/js/modules/status/collections/gda.js | JavaScript | apache-2.0 | 1,142 |
function manualInput(){
let manualCheckBox = document.getElementById("checkBoxManual").checked;
let manualID = document.getElementById("manual");
if(manualCheckBox === true){
manualID.style.display = "block";
}else{
manualID.style.display = "none";
}
}
function printArray(arrayString){
let length = arrayString.length;
let result = "";
for(let i = 0; i < length; i++){
result += arrayString[i] + " ";
}
console.log(result);
result = "Result: " + result;
let resultID = document.getElementById("result");
resultID.innerHTML = result;
resultID.style.display = "block";
}
function animateBubbleSort(arrayString){
let length = arrayString.length;
let swapCounter = 0;
for(let i = 0; i < length; i++){
for(let j = 1; j < length; j++){
if(arrayString[j-1] > arrayString[j]){
let temp = arrayString[j-1];
arrayString[j-1] = arrayString[j];
arrayString[j] = temp;
swapCounter++;
}
}
if(swapCounter < 0) break;
}
printArray(arrayString);
}
function startAlgorithm(){
let bubbleSort = document.getElementById("bubbleSort").checked;
if(bubbleSort === true){
let manualinput = document.getElementById("checkBoxManual").checked;
if(manualinput === true){
let numberString = document.getElementById("numberString").value.trim();
let arrayString = numberString.split(" ");
animateBubbleSort(arrayString);
}else{
let length = document.getElementById("length").value;
let array = [length];
for(let i = 0; i < length; i++){
array[i] = Math.floor(Math.random()*50);
}
animateBubbleSort(array);
}
}else{
console.log("Please select a algorithm");
}
} | jliang27/jliang27.github.io | projects/pr3/scripts/algorithm.js | JavaScript | apache-2.0 | 1,688 |
define("clickableguide/bootstrap-3", ["jquery-1", "istats-1", "clickableguide/pubsub"], function(e, s) {
var t = function() {
if (/iP(hone|od|ad)/.test(navigator.platform)) {
var e = navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
return [parseInt(e[1], 10), parseInt(e[2], 10), parseInt(e[3] || 0, 10)] >= 5
}
return navigator.userAgent.match(/Android 2./) ? !1 : /MSIE 7/.test(navigator.userAgent) ? !1 : !0
};
return {
$: e,
pubsub: e,
empConfig: {
paths: {
"bump-3": "http://emp.bbci.co.uk/emp/bump-3/bump-3",
"jquery-1.9": "http://static.bbci.co.uk/frameworks/jquery/0.3.0/sharedmodules/jquery-1.9.1"
}
},
istats: s,
browserNotOnThePositionFixedNaughtyList: t
}
}), define("clickableguide/minihash-3", [], function() {
var e = function() {
this._keysSorted = !1, this._sortedKeys = [], this._map = {}, this.isEmpty = !0, this.size = 0
};
return e.prototype = {
keys: function() {
e = this;
var s, t = [];
for (s in e._map) e._map.hasOwnProperty.call(e._map, s) && t.push(s);
return t
},
values: function() {
e = this;
var s, t = [];
for (s in e._map) e._map.hasOwnProperty.call(e._map, s) && t.push(e._map[s]);
return t
},
put: function(s, t) {
if ("object" == typeof s) throw new Error("TypeError: Keys should be Strings or Numbers");
e = this, e._keysSorted = !1, this._map[s] = t, this.size = this.size + 1, this.isEmpty && (this.isEmpty = !1)
},
get: function(e) {
return void 0 !== this._map[e] ? this._map[e] : !1
},
del: function(e) {
return void 0 !== this._map[e] ? (delete this._map[e], this.size = this.size - 1, 0 === this.size && (this.isEmpty = !0), !0) : !1
},
sortKeys: function() {
return e = this, e._keysSorted ? e._sortedKeys : (e._sortedKeys = e.keys().sort(function(e, s) {
return e - s
}), e._keysSorted = !0, e._sortedKeys)
}
}, e
}), define("clickableguide/carousel-3", ["clickableguide/bootstrap-3"], function(e) {
var s = function(s, t, i, n) {
this.elm = e.$(s), this.vocab = t, this.pubsubNamespace = "ns-carousel-russell_sq--" + i, this.items = this.elm.find(".ns-carousel-russell_sq__item"), this.currentItem = 0, this.ctaOffset = n - 32, this.addNav();
var a = this;
e.pubsub.on(this.pubsubNamespace + ":prev", function() {
a.prev()
}), e.pubsub.on(this.pubsubNamespace + ":next", function() {
a.next()
}), e.pubsub.on("ns-panel-russell_sq:show", function(e) {
a.fadeInNav(e)
}), e.pubsub.on(this.pubsubNamespace + ":show_nav", function(e) {
void 0 === e && (e = a.insideVisibleSection()), a.fadeInNav(e)
}), e.pubsub.on(this.pubsubNamespace + ":hide_nav", function() {
a.fadeOutNav()
}), this.elm[0].addEventListener("click", function(s) {
a.navDelegation(s), e.pubsub.emit("ns-clickable_guide-russell_sq:carousel:navigated")
}, !1), this.elm[0].addEventListener("mouseover", function() {
e.pubsub.emit(a.pubsubNamespace + ":show_nav")
}, !1), this.elm[0].addEventListener("mouseout", function() {
e.pubsub.emit(a.pubsubNamespace + ":hide_nav")
}, !1), this.show(0)
};
return s.prototype = {
fadeInNav: function(e) {
(e || this.insideVisibleSection()) && this.elm.find(".ns-carousel-russell_sq__nav").addClass("ns-carousel-russell_sq__nav--faded-in")
},
fadeOutNav: function() {
this.elm.find(".ns-carousel-russell_sq__nav").removeClass("ns-carousel-russell_sq__nav--faded-in")
},
insideVisibleSection: function() {
return !!this.elm.find(".ns-carousel-russell_sq__nav").closest(".ns-panel-russell_sq__section--show").length
},
show: function(s) {
this.currentItem = s, this.items.removeClass("ns-carousel-russell_sq__item--show"), e.$(this.items[s]).addClass("ns-carousel-russell_sq__item--show")
},
next: function() {
var e = this.currentItem + 1;
e >= this.items.length && (e = 0), this.show(e)
},
prev: function() {
var e = this.currentItem - 1;
0 > e && (e = this.items.length - 1), this.show(e)
},
addNav: function() {
this.elm.append('<div class="ns-carousel-russell_sq__nav"><a href="#" class="ns-carousel-russell_sq__next-prev ns-carousel-russell_sq__prev" ><span class="ns-panel-russell_sq__hide">' + this.vocab.prevImage + '</span><span class="ns-carousel-russell_sq__arrow-left "></span><span class="ns-carousel-russell_sq__arrow-left--inside"></span></a><a href="#" class="ns-carousel-russell_sq__next-prev ns-carousel-russell_sq__next" ><span class="ns-panel-russell_sq__hide">' + this.vocab.nextImage + '</span><span class="ns-carousel-russell_sq__arrow-right"></span><span class="ns-carousel-russell_sq__arrow-right--inside"></span></a></div>')
},
navDelegation: function(s) {
var t = e.$(s.target).closest(".ns-carousel-russell_sq__next-prev");
return t.length > 0 && (t.hasClass("ns-carousel-russell_sq__prev") && e.pubsub.emit(this.pubsubNamespace + ":prev"), t.hasClass("ns-carousel-russell_sq__next") && e.pubsub.emit(this.pubsubNamespace + ":next")), s.preventDefault(), s.stopPropagation(), !1
}
}, s
}), define("clickableguide/imager-3", ["clickableguide/bootstrap-3"], function(e) {
var s = function(e) {
this.widths = e.availableWidths || [320, 640, 1024], this.regex = e.regex || /^(.+\/)\d+$/i, this.is_resizing = !1, this.onImagesReplaced = e.onImagesReplaced || function() {}, this.change_divs_to_imgs(), this.init_resize_images()
};
return s.prototype = {
change_divs_to_imgs: function() {
var s = this;
e.$(".idt-delayed-image-load-russell_sq").each(function(t, i) {
var n = e.$(i);
i.className.search("js-no_replace") > -1 || setTimeout(function() {
n.removeClass("delayed-image-load");
var t = e.$('<img src="' + s.calc_img_src(n.attr("data-src"), n.width()) + '" alt="' + (n.attr("data-alt") || "") + '" class="js-image_replace ' + n.attr("class") + '" />');
n.after(t)
}, 1)
})
},
calc_img_src: function(e, s) {
return null === e ? !1 : e.replace(/(\/{cg_width}\/)/, "/" + this.match_closest_value(s, this.widths) + "/")
},
match_closest_value: function(e, s) {
for (var t = s[0], i = 0, n = s.length; n > i; i++) {
if (e < s[i]) return t;
t = s[i]
}
return t
},
init_resize_images: function() {
var e = this;
window.addEventListener("resize", function() {
e.resize_images()
}, !1)
},
resize_images: function() {
var s = e.$(".js-image_replace"),
t = this;
this.is_resizing || (this.is_resizing = !0, null !== s && s.each(function() {
if (!e.$(this).hasClass("js-no_replace")) {
var s = t.calc_img_src(this.getAttribute("datasrc") || this.src, this.clientWidth);
s && this.src !== s && (this.src = s)
}
}), this.is_resizing = !1, this.onImagesReplaced())
}
}, s
}), define("js/clickableguide/main-3", ["clickableguide/bootstrap-3", "clickableguide/minihash-3", "clickableguide/carousel-3", "clickableguide/imager-3"], function(e, s, t, i) {
var n = function(s, t, i) {
this.elm = e.$(s), this.vocab = t, this.opts = i || {
panelPosition: "centre_of_interactive"
}, this.initPanels(), this.initCarousels(), this.callImager(this.opts), this.applyOptions(this.opts), this.setupPubsubs(), this.empVisible = !1, this.tellIstatsTheInitialLayoutMode(e.$(window).width(), e.$(window).height(), i), this.setResponsiveSiteToBeFullWidth(this.opts)
};
return n.prototype = {
initPanels: function() {
this.panels = new s, this.empPanels = new s, this.buildMiniHash(this.elm.find(".ns-panel-russell_sq__section--int"), this.panels), this.buildMiniHash(this.elm.find(".ns-panel-russell_sq__section--emp"), this.empPanels), this.currentPanel = this.panels.sortKeys()[0], this.poster = ""
},
initCarousels: function() {
var e = this;
this.elm.find(".ns-carousel-russell_sq").each(function(s) {
{
var i = this;
new t(i, e.vocab, e.createUniqueId(), e.getOffsetValue(s))
}
})
},
applyOptions: function(e) {
e.panelsPosition = e.panelsPosition || "default", this.choosePanelPosition(e.panelsPosition), this.addMask(e.mask), this.setMinWidthAndHeight(e), e.nextPrevButtons && this.addNextPrevButtons()
},
setupPubsubs: function() {
this.listenForPubsubEvents(), this.listenForClicks()
},
callImager: function(s) {
var t = {
availableWidths: [96, 130, 165, 200, 235, 270, 304, 340, 375, 410, 445, 485, 520, 555, 590, 625, 660, 695, 736, 772, 800, 834, 872, 904, 936, 976],
onImagesReplaced: function() {
var t = s.panelsPosition || "default";
e.pubsub.emit("ns-clickable_guide-russell_sq:imager:updated", [t])
}
};
s.responsive || (t.onResize = !1), new i(t)
},
listenForPubsubEvents: function() {
var s = this;
e.pubsub.on("ns-panel-russell_sq:show", function(t) {
s.hide(), s.choosePanelPosition(s.opts.panelsPosition), s.show(t), e.istats.log("open-panel", "newsindep-interaction", {
view: t
})
}), e.pubsub.on("ns-panel-russell_sq:hide", function() {
s.hide()
}), e.pubsub.on("ns-clickable_guide-russell_sq:imager:updated", function(e) {
s.choosePanelPosition(e)
}), e.pubsub.on("ns-clickable_guide-russell_sq:carousel:navigated", function() {})
},
listenForClicks: function() {
var s = this;
e.$(".ns-panel-russell_sq__hotspot ").click(function(e) {
return s.preventDefaults(e, function() {
s.launchPanel(e, s)
})
}), e.$(".ns-panel-russell_sq__video__cta").on("mousedown", function(e) {
return s.preventDefaults(e, function() {
s.launchPanel(e, s), s.isVideoInViewport(e.currentTarget) || e.currentTarget.scrollIntoView(!1)
})
}), e.$(".ns-panel-russell_sq__prev").click(function(e) {
return s.preventDefaults(e, function() {
s.prev()
})
}), e.$(".ns-panel-russell_sq__next").click(function(e) {
return s.preventDefaults(e, function() {
s.next()
})
}), e.$(".ns-panel-russell_sq__section-close").click(function(t) {
return s.preventDefaults(t, function() {
e.pubsub.emit("ns-panel-russell_sq:hide")
})
}), this.maskElm && this.maskElm[0].addEventListener("click", function() {
e.pubsub.emit("ns-panel-russell_sq:hide")
}, !1)
},
launchPanel: function(s, t) {
var i = t.getPanelIndexFromHref(e.$(s.currentTarget).attr("href"));
e.pubsub.emit("ns-panel-russell_sq:show", [i])
},
getPanelIndexFromHref: function(e) {
return e.replace(/^\D+/g, "")
},
setMinWidthAndHeight: function(s) {
var t = this;
t.interactiveMinWidth = 0, t.interactiveMinHeight = 0, s.interactiveMinWidth && s.responsive && s.interactiveMinHeight && (this.interactiveMinWidth = s.interactiveMinWidth, this.interactiveMinHeight = s.interactiveMinHeight, window.addEventListener("resize", function() {
t.showHideClickableGuide(e.$(window).width(), e.$(window).height())
}, !1)), this.showHideClickableGuide(e.$(window).width(), e.$(window).height())
},
buildMiniHash: function(s, t) {
s.each(function() {
var s = e.$(this);
t.put(s.attr("id").split("section-")[1], s)
})
},
getOffsetValue: function(s) {
return e.$(this.panels.get(s)).find(".ns-panel-russell_sq__section-header").outerHeight(!0) || 0 + e.$(this.panels.get(s)).find(".ns-panel-russell_sq__section-sub-header").outerHeight(!0) || 0
},
getContextSize: function() {
return this.elm.find(".ns-panel-russell_sq__hotspots>img").outerHeight(!0) + this.elm.find(".ns-panel-russell_sq__clickable").outerHeight(!0)
},
createUniqueId: function() {
return this.elm.attr("id") + (new Date).getTime()
},
loadBump: function(s) {
var t = this;
require(e.empConfig, ["bump-3"], function(e) {
t.loadEmp(e, s)
})
},
loadEmp: function(s, t) {
var i = this,
n = t.find(".ns-panel-russell_sq__section-emp-data"),
a = n.attr("data-playlist"),
o = (new Date).getTime();
this.poster = t.find(".ns-panel-russell_sq__section-emp-img"), this.empVisible || (this.empVisible = !0, i.elm.append('<div id="ns-player--' + o + '" class="ns-panel-russell_sq__emp_player"></div>'), i.emp = {
elm: e.$("#ns-player--" + o),
player: s("#ns-player--" + o).player({
product: "news",
playerProfile: a,
responsive: !1,
autoplay: !0
})
}), this.poster.addClass("ns-panel-russell_sq__section-emp-img--hide"), i.emp.player.poster(this.poster.attr("src")), i.sizeEmp(), i.emp.player.load(a), n.after(i.emp.elm)
},
sizeEmp: function() {
this.empVisible && null !== this.poster.width() && null !== this.poster.height() && (this.emp.player.width(this.poster.width().toString() || "640"), this.emp.player.height((.5625 * this.emp.player.width()).toString() || "360"))
},
hideEmp: function() {
e.$(".ns-panel-russell_sq__section-emp-img").removeClass("ns-panel-russell_sq__section-emp-img--hide"), this.empVisible && (this.elm.find(".ns-panel-russell_sq__emp_player").remove(), this.empVisible = !1)
},
show: function(s) {
this.hide(), this.currentPanel = s;
var t = e.$(this.panels.get(s));
t.addClass("ns-panel-russell_sq__section--show"), this.setHotspotActiveState(s), this.maskElm && (this.showMask(), this.maskElm.height(e.$("#blq-container-outer, #blq-container")[0].clientHeight)), this.empPanels.get(s) !== !1 ? this.loadBump(t) : this.hideEmp()
},
hide: function() {
this.hideEmp(), this.elm.find(".ns-panel-russell_sq__section--show").removeClass("ns-panel-russell_sq__section--show"), this.currentPanel = this.panels.sortKeys()[0], this.hideMask(), this.setHotspotActiveState(0)
},
next: function() {
var s, t = this.panels.sortKeys();
t.indexOf(this.currentPanel) === t.length - 1 ? s = this.currentPanel : (s = t[t.indexOf(this.currentPanel) + 1], e.pubsub.emit("ns-panel-russell_sq:show", [s]))
},
prev: function() {
var s = this.panels.sortKeys();
if (s.indexOf(this.currentPanel) > 0) {
var t = s[s.indexOf(this.currentPanel) - 1];
e.pubsub.emit("ns-panel-russell_sq:show", [t])
}
},
addNextPrevButtons: function() {
for (var s = this, t = s.panels.sortKeys(), i = 0; i < s.panels.size; i++) {
var n = t[i],
a = '<a href="#ns-panel-russell_sq__section-' + t[i - 1] + '" class="ns-panel-russell_sq__next-prev ns-panel-russell_sq__prev">',
o = '<a href="#ns-panel-russell_sq__section-' + t[i + 1] + '" class="ns-panel-russell_sq__next-prev ns-panel-russell_sq__next">';
0 === i ? a = '<a href="#" class="ns-panel-russell_sq__next-prev ns-panel-russell_sq__prev ns-panel-russell_sq__next-prev--disabled">' : i === s.panels.size - 1 && (o = '<a href="#" class="ns-panel-russell_sq__next-prev ns-panel-russell_sq__next ns-panel-russell_sq__next-prev--disabled">'), e.$(s.panels.get(n)).append('<div class="ns-panel-russell_sq__section-nav">' + a + '<span class="ns-panel-russell_sq__hide">' + s.vocab.prev + '</span><span class="ns-panel-russell_sq__arrow-left "></span><span class="ns-panel-russell_sq__arrow-left--inside"></span></a><div class="ns-panel-russell_sq__counter"> ' + (i + 1) + " " + s.vocab.pagingDivider + " " + s.panels.size + " </div>" + o + '<span class="ns-panel-russell_sq__hide">' + s.vocab.next + '</span><span class="ns-panel-russell_sq__arrow-right"></span><span class="ns-panel-russell_sq__arrow-right--inside"></span></a></div>')
}
},
showHideClickableGuide: function(e, s) {
this.viewportIsBigEnoughForClickableGuide(e, s) ? (this.elm.addClass("ns-panel-russell_sq--interactive"), 0 !== this.currentPanel && this.showMask()) : (this.elm.removeClass("ns-panel-russell_sq--interactive"), this.hideMask()), this.sizeEmp()
},
viewportIsBigEnoughForClickableGuide: function(e, s) {
return e >= this.interactiveMinWidth && s >= this.interactiveMinHeight
},
tellIstatsTheInitialLayoutMode: function(s, t, i) {
var n = "list";
(this.viewportIsBigEnoughForClickableGuide(s, t) || i.responsive !== !0) && (n = "interactive"), e.istats.log("layout-mode", "newsindep-nonuser", {
view: n
})
},
addMask: function(s) {
("white" === s || "black" === s) && (e.$("body").append('<div class="ns-panel-russell_sq__mask ns-panel-russell_sq__mask--' + s + '"></div>'), this.maskElm = e.$(".ns-panel-russell_sq__mask"))
},
showMask: function() {
this.maskElm && (this.maskElm.addClass("ns-panel-russell_sq__mask--show"), this.maskElm.height(e.$("body").height()))
},
hideMask: function() {
this.maskElm && this.maskElm.removeClass("ns-panel-russell_sq__mask--show")
},
preventDefaults: function(e, s) {
return e.preventDefault(), e.stopPropagation(), s(), !1
},
choosePanelPosition: function(s) {
var t, i, n = this;
if ("default" === s || "centre_of_interactive" === s)
for (t in n.panels._map) i = n.panels.get(t), i.css({
top: (n.getContextSize() - i.height()) / 2 + "px"
});
else if ("right_of_interactive" === s)
for (t in n.panels._map) i = n.panels.get(t), i.addClass("ns-panel-russell_sq__section--align-right");
else if ("centre_of_screen" === s && e.browserNotOnThePositionFixedNaughtyList)
for (t in n.panels._map) i = n.panels.get(t), i.addClass("ns-panel-russell_sq__section--centre_of_screen"), i.css({
marginTop: "-" + i.height() / 2 + "px",
marginLeft: "-" + i.width() / 2 + "px"
})
},
isVideoInViewport: function(e) {
var s = e.getBoundingClientRect();
return s.top >= 0 && s.left >= 0 && s.bottom <= (window.innerHeight || document.documentElement.clientHeight) && s.right <= (window.innerWidth || document.documentElement.clientWidth)
},
setHotspotActiveState: function(s) {
e.$(".ns-panel-russell_sq__hotspot").removeClass("ns-panel-russell_sq__hotspot--active"), e.$(".ns-panel-russell_sq__hotspot--" + s).addClass("ns-panel-russell_sq__hotspot--active")
},
setResponsiveSiteToBeFullWidth: function(e) {
"interactiveMinWidth" in e && e.interactiveMinWidth >= 976
}
}, n
});
//# sourceMappingURL=ns_clickableguide_all.js
//# sourceMappingURL=ns_clickableguide_all.js.map | BBCVisualJournalism/newsspec_11531 | russell_sq/ns_clickableguide_all-russell_sq.js | JavaScript | apache-2.0 | 20,724 |
/**
* Module that controls the Dataverse node settings. Includes Knockout view-model
* for syncing data.
*/
var ko = require('knockout');
var bootbox = require('bootbox');
require('knockout.punches');
var Raven = require('raven-js');
var osfHelpers = require('js/osfHelpers');
ko.punches.enableAll();
function ViewModel(url) {
var self = this;
self.url = url;
self.urls = ko.observable();
self.dataverseUsername = ko.observable();
self.dataversePassword = ko.observable();
self.ownerName = ko.observable();
self.nodeHasAuth = ko.observable(false);
self.userHasAuth = ko.observable(false);
self.userIsOwner = ko.observable(false);
self.connected = ko.observable(false);
self.loadedSettings = ko.observable(false);
self.loadedStudies = ko.observable(false);
self.submitting = ko.observable(false);
self.dataverses = ko.observableArray([]);
self.studies = ko.observableArray([]);
self.badStudies = ko.observableArray([]);
self.savedStudyHdl = ko.observable();
self.savedStudyTitle = ko.observable();
self.savedDataverseAlias = ko.observable();
self.savedDataverseTitle = ko.observable();
self.studyWasFound = ko.observable(false);
self.messages = {
userSettingsError: ko.pureComputed(function() {
return 'Could not retrieve settings. Please refresh the page or ' +
'contact <a href="mailto: [email protected]">[email protected]</a> if the ' +
'problem persists.';
}),
confirmNodeDeauth: ko.pureComputed(function() {
return 'Are you sure you want to unlink this Dataverse account? This will ' +
'revoke the ability to view, download, modify, and upload files ' +
'to studies on the Dataverse from the OSF. This will not remove your ' +
'Dataverse authorization from your <a href="' + self.urls().settings + '">user settings</a> ' +
'page.';
}),
confirmImportAuth: ko.pureComputed(function() {
return 'Are you sure you want to authorize this project with your Dataverse credentials?';
}),
deauthError: ko.pureComputed(function() {
return 'Could not unlink Dataverse at this time. Please refresh the page or ' +
'contact <a href="mailto: [email protected]">[email protected]</a> if the ' +
'problem persists.';
}),
deauthSuccess: ko.pureComputed(function() {
return 'Successfully unlinked your Dataverse account.';
}),
authInvalid: ko.pureComputed(function() {
return 'Your Dataverse username or password is invalid.';
}),
authError: ko.pureComputed(function() {
return 'There was a problem connecting to the Dataverse. Please refresh the page or ' +
'contact <a href="mailto: [email protected]">[email protected]</a> if the ' +
'problem persists.';
}),
importAuthSuccess: ko.pureComputed(function() {
return 'Successfully linked your Dataverse account';
}),
importAuthError: ko.pureComputed(function() {
return 'There was a problem connecting to the Dataverse. Please refresh the page or ' +
'contact <a href="mailto: [email protected]">[email protected]</a> if the ' +
'problem persists.';
}),
studyDeaccessioned: ko.pureComputed(function() {
return 'This study has already been deaccessioned on the Dataverse ' +
'and cannot be connected to the OSF.';
}),
forbiddenCharacters: ko.pureComputed(function() {
return 'This study cannot be connected due to forbidden characters ' +
'in one or more of the study\'s file names. This issue has been forwarded to our ' +
'development team.';
}),
setInfoSuccess: ko.pureComputed(function() {
var filesUrl = window.contextVars.node.urls.web + 'files/';
return 'Successfully linked study \'' + self.savedStudyTitle() + '\'. Go to the <a href="' +
filesUrl + '">Files page</a> to view your content.';
}),
setStudyError: ko.pureComputed(function() {
return 'Could not connect to this study. Please refresh the page or ' +
'contact <a href="mailto: [email protected]">[email protected]</a> if the ' +
'problem persists.';
}),
getStudiesError: ko.pureComputed(function() {
return 'Could not load studies. Please refresh the page or ' +
'contact <a href="mailto: [email protected]">[email protected]</a> if the ' +
'problem persists.';
})
};
self.savedStudyUrl = ko.pureComputed(function() {
return (self.urls()) ? self.urls().studyPrefix + self.savedStudyHdl() : null;
});
self.savedDataverseUrl = ko.pureComputed(function() {
return (self.urls()) ? self.urls().dataversePrefix + self.savedDataverseAlias() : null;
});
self.selectedDataverseAlias = ko.observable();
self.selectedStudyHdl = ko.observable();
self.selectedDataverseTitle = ko.pureComputed(function() {
for (var i = 0; i < self.dataverses().length; i++) {
var data = self.dataverses()[i];
if (data.alias === self.selectedDataverseAlias()) {
return data.title;
}
}
return null;
});
self.selectedStudyTitle = ko.pureComputed(function() {
for (var i = 0; i < self.studies().length; i++) {
var data = self.studies()[i];
if (data.hdl === self.selectedStudyHdl()) {
return data.title;
}
}
return null;
});
self.dataverseHasStudies = ko.pureComputed(function() {
return self.studies().length > 0;
});
self.showStudySelect = ko.pureComputed(function() {
return self.loadedStudies() && self.dataverseHasStudies();
});
self.showNoStudies = ko.pureComputed(function() {
return self.loadedStudies() && !self.dataverseHasStudies();
});
self.showLinkedStudy = ko.pureComputed(function() {
return self.savedStudyHdl();
});
self.showLinkDataverse = ko.pureComputed(function() {
return self.userHasAuth() && !self.nodeHasAuth() && self.loadedSettings();
});
self.credentialsChanged = ko.pureComputed(function() {
return self.nodeHasAuth() && !self.connected();
});
self.showInputCredentials = ko.pureComputed(function() {
return (self.credentialsChanged() && self.userIsOwner()) ||
(!self.userHasAuth() && !self.nodeHasAuth() && self.loadedSettings());
});
self.hasDataverses = ko.pureComputed(function() {
return self.dataverses().length > 0;
});
self.hasBadStudies = ko.pureComputed(function() {
return self.badStudies().length > 0;
});
self.showNotFound = ko.pureComputed(function() {
return self.savedStudyHdl() && self.loadedStudies() && !self.studyWasFound();
});
self.showSubmitStudy = ko.pureComputed(function() {
return self.nodeHasAuth() && self.connected() && self.userIsOwner();
});
self.enableSubmitStudy = ko.pureComputed(function() {
return !self.submitting() && self.dataverseHasStudies() &&
self.savedStudyHdl() !== self.selectedStudyHdl();
});
// Flashed messages
self.message = ko.observable('');
self.messageClass = ko.observable('text-info');
// Update above observables with data from the server
$.ajax({
url: url,
type: 'GET',
dataType: 'json'
}).done(function(response) {
// Update view model
self.updateFromData(response.result);
self.loadedSettings(true);
}).fail(function(xhr, textStatus, error) {
self.changeMessage(self.messages.userSettingsError, 'text-warning');
Raven.captureMessage('Could not GET dataverse settings', {
url: url,
textStatus: textStatus,
error: error
});
});
}
/**
* Update the view model from data returned from the server.
*/
ViewModel.prototype.updateFromData = function(data) {
var self = this;
self.urls(data.urls);
self.dataverseUsername(data.dataverseUsername);
self.ownerName(data.ownerName);
self.nodeHasAuth(data.nodeHasAuth);
self.userHasAuth(data.userHasAuth);
self.userIsOwner(data.userIsOwner);
if (self.nodeHasAuth()) {
self.dataverses(data.dataverses);
self.savedDataverseAlias(data.savedDataverse.alias);
self.savedDataverseTitle(data.savedDataverse.title);
self.selectedDataverseAlias(data.savedDataverse.alias);
self.savendStudyHdl(data.savedStudy.hdl);
self.savedStudyTitle(data.savedStudy.title);
self.connected(data.connected);
if (self.userIsOwner()) {
self.getStudies(); // Sets studies, selectedStudyHdl
}
}
};
ViewModel.prototype.setInfo = function() {
var self = this;
self.submitting(true);
return osfHelpers.postJSON(
self.urls().set,
ko.toJS({
dataverse: {
alias: self.selectedDataverseAlias
},
study: {
hdl: self.selectedStudyHdl
}
})
).done(function() {
self.submitting(false);
self.savedDataverseAlias(self.selectedDataverseAlias());
self.savedDataverseTitle(self.selectedDataverseTitle());
self.savedStudyHdl(self.selectedStudyHdl());
self.savedStudyTitle(self.selectedStudyTitle());
self.studyWasFound(true);
self.changeMessage(self.messages.setInfoSuccess, 'text-success');
}).fail(function(xhr, textStatus, error) {
self.submitting(false);
var errorMessage = (xhr.status === 410) ? self.messages.studyDeaccessioned :
(xhr.status = 406) ? self.messages.forbiddenCharacters : self.messages.setStudyError;
self.changeMessage(errorMessage, 'text-danger');
Raven.captureMessage('Could not authenticate with Dataverse', {
url: self.urls().set,
textStatus: textStatus,
error: error
});
});
};
/**
* Looks for study in list of studies when first loaded.
* This prevents an additional request to the server, but requires additional logic.
*/
ViewModel.prototype.findStudy = function() {
var self = this;
for (var i in self.studies()) {
if (self.studies()[i].hdl === self.savedStudyHdl()) {
self.studyWasFound(true);
return;
}
}
};
ViewModel.prototype.getStudies = function() {
var self = this;
self.studies([]);
self.badStudies([]);
self.loadedStudies(false);
return osfHelpers.postJSON(
self.urls().getStudies,
ko.toJS({
alias: self.selectedDataverseAlias
})
).done(function(response) {
self.studies(response.studies);
self.badStudies(response.badStudies);
self.loadedStudies(true);
self.selectedStudyHdl(self.savedStudyHdl());
self.findStudy();
}).fail(function() {
self.changeMessage(self.messages.getStudiesError, 'text-danger');
});
};
ViewModel.prototype.authorizeNode = function() {
var self = this;
return osfHelpers.putJSON(
self.urls().importAuth, {}
).done(function(response) {
self.updateFromData(response.result);
self.changeMessage(self.messages.importAuthSuccess, 'text-success', 3000);
}).fail(function() {
self.changeMessage(self.messages.importAuthError, 'text-danger');
});
};
/** Send POST request to authorize Dataverse */
ViewModel.prototype.sendAuth = function() {
var self = this;
return osfHelpers.postJSON(
self.urls().create,
ko.toJS({
dataverse_username: self.dataverseUsername,
dataverse_password: self.dataversePassword
})
).done(function() {
// User now has auth
self.authorizeNode();
}).fail(function(xhr) {
var errorMessage = (xhr.status === 401) ? self.messages.authInvalid : self.messages.authError;
self.changeMessage(errorMessage, 'text-danger');
});
};
/**
* Send PUT request to import access token from user profile.
*/
ViewModel.prototype.importAuth = function() {
var self = this;
bootbox.confirm({
title: 'Link to Dataverse Account?',
message: self.messages.confirmImportAuth(),
callback: function(confirmed) {
if (confirmed) {
self.authorizeNode();
}
}
});
};
ViewModel.prototype.clickDeauth = function() {
var self = this;
function sendDeauth() {
return $.ajax({
url: self.urls().deauthorize,
type: 'DELETE'
}).done(function() {
self.nodeHasAuth(false);
self.userIsOwner(false);
self.connected(false);
self.changeMessage(self.messages.deauthSuccess, 'text-success', 3000);
}).fail(function() {
self.changeMessage(self.messages.deauthError, 'text-danger');
});
}
bootbox.confirm({
title: 'Deauthorize?',
message: self.messages.confirmNodeDeauth(),
callback: function(confirmed) {
if (confirmed) {
sendDeauth();
}
}
});
};
/** Change the flashed status message */
ViewModel.prototype.changeMessage = function(text, css, timeout) {
var self = this;
if (typeof text === 'function') {
text = text();
}
self.message(text);
var cssClass = css || 'text-info';
self.messageClass(cssClass);
if (timeout) {
// Reset message after timeout period
setTimeout(function() {
self.message('');
self.messageClass('text-info');
}, timeout);
}
};
function DataverseNodeConfig(selector, url) {
// Initialization code
var self = this;
self.selector = selector;
self.url = url;
// On success, instantiate and bind the ViewModel
self.viewModel = new ViewModel(url);
osfHelpers.applyBindings(self.viewModel, '#dataverseScope');
}
module.exports = DataverseNodeConfig;
| himanshuo/osf.io | website/addons/dataverse/static/dataverseNodeConfig.js | JavaScript | apache-2.0 | 14,334 |
module.exports = [{"isApi":true,"priority":1000.0048,"key":"Label","style":{width:Ti.UI.SIZE,height:Ti.UI.SIZE,textAlign:Ti.UI.TEXT_ALIGNMENT_CENTER,font:{color:"#5C5E61",fontWeight:"normal",fontSize:"48",},}},{"isApi":true,"priority":1000.0049,"key":"TableViewRow","style":{width:Ti.UI.SIZE,height:"36",color:"#5C5E61",font:{fontSize:"20",fontStyle:"bold",},}},{"isApi":true,"priority":1000.005,"key":"Tab","style":{font:{fontSize:"56dp",fontWeight:"bold",textStyle:Ti.UI.TEXT_STYLE_HEADLINE,},width:Ti.UI.SIZE,height:Ti.UI.SIZE,}},{"isApi":true,"priority":1000.0053,"key":"TextField","style":{width:Ti.UI.SIZE,height:"36",color:"#5C5E61",font:{fontSize:"18",},}},{"isClass":true,"priority":10000.0047,"key":"container","style":{backgroundColor:"white",}},{"isId":true,"priority":100000.0051,"key":"header","style":{color:"blue",font:{fontSize:"30",fontStyle:"bold",},}},{"isId":true,"priority":100000.0052,"key":"balance","style":{font:{fontSize:"48",fontStyle:"bold",},}}]; | phakhruddin/allowance | Resources/iphone/alloy/styles/settings.js | JavaScript | apache-2.0 | 976 |
// Karma configuration
// Generated on Sat Sep 19 2015 21:44:51 GMT+0700 (SE Asia Standard Time)
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: ['browserify', 'jasmine'],
browserify: {
debug: true,
transform: ['partialify', 'babelify']
},
// list of files / patterns to load in the browser
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'src/**/*',
'test/**/*Spec.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: {
'src/**/*': ['browserify'],
'test/**/*Spec.js': ['browserify']
},
// 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: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
| phucpnt/ng-timemachine | karma.conf.js | JavaScript | apache-2.0 | 1,881 |
function __processArg(obj, key) {
var arg = null;
if (obj) {
arg = obj[key] || null;
delete obj[key];
}
return arg;
}
function Controller() {
function back() {
"prepaid" == Alloy.Globals.userPlan ? DRAWER.navigation("prepaidStatement", 1) : DRAWER.navigation("postpaidStatement", 1);
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "iddVoice";
if (arguments[0]) {
{
__processArg(arguments[0], "__parentSymbol");
}
{
__processArg(arguments[0], "$model");
}
{
__processArg(arguments[0], "__itemTemplate");
}
}
var $ = this;
var exports = {};
var __defers = {};
$.__views.iddVoice = Ti.UI.createView({
backgroundColor: "white",
layout: "vertical",
fullscreen: "true",
id: "iddVoice"
});
$.__views.iddVoice && $.addTopLevelView($.__views.iddVoice);
$.__views.__alloyId1002 = Alloy.createController("_header", {
id: "__alloyId1002",
__parentSymbol: $.__views.iddVoice
});
$.__views.__alloyId1002.setParent($.__views.iddVoice);
$.__views.__alloyId1003 = Ti.UI.createView({
layout: "composite",
height: "50",
backgroundColor: "#E91D2F",
id: "__alloyId1003"
});
$.__views.iddVoice.add($.__views.__alloyId1003);
$.__views.__alloyId1004 = Ti.UI.createLabel({
text: "Bill Statement",
backgroundColor: "transparent",
color: "white",
left: "20",
id: "__alloyId1004"
});
$.__views.__alloyId1003.add($.__views.__alloyId1004);
$.__views.__alloyId1005 = Ti.UI.createImageView({
backgroundColor: "transparent",
width: "30",
height: "30",
right: "10",
image: "/images/close_icon.png",
id: "__alloyId1005"
});
$.__views.__alloyId1003.add($.__views.__alloyId1005);
back ? $.__views.__alloyId1005.addEventListener("click", back) : __defers["$.__views.__alloyId1005!click!back"] = true;
$.__views.__alloyId1006 = Ti.UI.createView({
layout: "composite",
height: "40",
backgroundColor: "#F2F2F2",
id: "__alloyId1006"
});
$.__views.iddVoice.add($.__views.__alloyId1006);
$.__views.__alloyId1007 = Ti.UI.createLabel({
text: "IDD Voice Calls",
textAlign: "center",
color: "black",
left: "10",
id: "__alloyId1007"
});
$.__views.__alloyId1006.add($.__views.__alloyId1007);
var __alloyId1008 = [];
$.__views.__alloyId1009 = Ti.UI.createTableViewSection({
id: "__alloyId1009"
});
__alloyId1008.push($.__views.__alloyId1009);
$.__views.__alloyId1010 = Ti.UI.createTableViewRow({
height: "80",
width: "100%",
layout: "horizontal",
separatorColor: "#000",
id: "__alloyId1010"
});
$.__views.__alloyId1009.add($.__views.__alloyId1010);
$.__views.__alloyId1011 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1011"
});
$.__views.__alloyId1010.add($.__views.__alloyId1011);
$.__views.__alloyId1012 = Ti.UI.createLabel({
text: "01/03/2015 12:05:07",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1012"
});
$.__views.__alloyId1011.add($.__views.__alloyId1012);
$.__views.__alloyId1013 = Ti.UI.createView({
width: "33%",
height: "100",
id: "__alloyId1013"
});
$.__views.__alloyId1010.add($.__views.__alloyId1013);
$.__views.__alloyId1014 = Ti.UI.createLabel({
text: "On Net 6017000000",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1014"
});
$.__views.__alloyId1013.add($.__views.__alloyId1014);
$.__views.__alloyId1015 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1015"
});
$.__views.__alloyId1010.add($.__views.__alloyId1015);
$.__views.__alloyId1016 = Ti.UI.createLabel({
text: "9 (sec) RM0.05",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1016"
});
$.__views.__alloyId1015.add($.__views.__alloyId1016);
$.__views.__alloyId1017 = Ti.UI.createTableViewRow({
height: "80",
width: "100%",
layout: "horizontal",
separatorColor: "#000",
id: "__alloyId1017"
});
$.__views.__alloyId1009.add($.__views.__alloyId1017);
$.__views.__alloyId1018 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1018"
});
$.__views.__alloyId1017.add($.__views.__alloyId1018);
$.__views.__alloyId1019 = Ti.UI.createLabel({
text: "02/03/2015 12:05:07",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1019"
});
$.__views.__alloyId1018.add($.__views.__alloyId1019);
$.__views.__alloyId1020 = Ti.UI.createView({
width: "33%",
height: "100",
id: "__alloyId1020"
});
$.__views.__alloyId1017.add($.__views.__alloyId1020);
$.__views.__alloyId1021 = Ti.UI.createLabel({
text: "On Net 6017000000",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1021"
});
$.__views.__alloyId1020.add($.__views.__alloyId1021);
$.__views.__alloyId1022 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1022"
});
$.__views.__alloyId1017.add($.__views.__alloyId1022);
$.__views.__alloyId1023 = Ti.UI.createLabel({
text: "9 (sec) RM0.05",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1023"
});
$.__views.__alloyId1022.add($.__views.__alloyId1023);
$.__views.__alloyId1024 = Ti.UI.createTableViewRow({
height: "80",
width: "100%",
layout: "horizontal",
separatorColor: "#000",
id: "__alloyId1024"
});
$.__views.__alloyId1009.add($.__views.__alloyId1024);
$.__views.__alloyId1025 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1025"
});
$.__views.__alloyId1024.add($.__views.__alloyId1025);
$.__views.__alloyId1026 = Ti.UI.createLabel({
text: "03/03/2015 12:05:07",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1026"
});
$.__views.__alloyId1025.add($.__views.__alloyId1026);
$.__views.__alloyId1027 = Ti.UI.createView({
width: "33%",
height: "100",
id: "__alloyId1027"
});
$.__views.__alloyId1024.add($.__views.__alloyId1027);
$.__views.__alloyId1028 = Ti.UI.createLabel({
text: "On Net 6017000000",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1028"
});
$.__views.__alloyId1027.add($.__views.__alloyId1028);
$.__views.__alloyId1029 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1029"
});
$.__views.__alloyId1024.add($.__views.__alloyId1029);
$.__views.__alloyId1030 = Ti.UI.createLabel({
text: "9 (sec) RM0.05",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1030"
});
$.__views.__alloyId1029.add($.__views.__alloyId1030);
$.__views.__alloyId1031 = Ti.UI.createTableViewRow({
height: "80",
width: "100%",
layout: "horizontal",
separatorColor: "#000",
id: "__alloyId1031"
});
$.__views.__alloyId1009.add($.__views.__alloyId1031);
$.__views.__alloyId1032 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1032"
});
$.__views.__alloyId1031.add($.__views.__alloyId1032);
$.__views.__alloyId1033 = Ti.UI.createLabel({
text: "04/03/2015 12:05:07",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1033"
});
$.__views.__alloyId1032.add($.__views.__alloyId1033);
$.__views.__alloyId1034 = Ti.UI.createView({
width: "33%",
height: "100",
id: "__alloyId1034"
});
$.__views.__alloyId1031.add($.__views.__alloyId1034);
$.__views.__alloyId1035 = Ti.UI.createLabel({
text: "On Net 6017000000",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1035"
});
$.__views.__alloyId1034.add($.__views.__alloyId1035);
$.__views.__alloyId1036 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1036"
});
$.__views.__alloyId1031.add($.__views.__alloyId1036);
$.__views.__alloyId1037 = Ti.UI.createLabel({
text: "9 (sec) RM0.05",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1037"
});
$.__views.__alloyId1036.add($.__views.__alloyId1037);
$.__views.__alloyId1038 = Ti.UI.createTableViewRow({
height: "80",
width: "100%",
layout: "horizontal",
separatorColor: "#000",
id: "__alloyId1038"
});
$.__views.__alloyId1009.add($.__views.__alloyId1038);
$.__views.__alloyId1039 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1039"
});
$.__views.__alloyId1038.add($.__views.__alloyId1039);
$.__views.__alloyId1040 = Ti.UI.createLabel({
text: "05/03/2015 12:05:07",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1040"
});
$.__views.__alloyId1039.add($.__views.__alloyId1040);
$.__views.__alloyId1041 = Ti.UI.createView({
width: "33%",
height: "100",
id: "__alloyId1041"
});
$.__views.__alloyId1038.add($.__views.__alloyId1041);
$.__views.__alloyId1042 = Ti.UI.createLabel({
text: "On Net 6017000000",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1042"
});
$.__views.__alloyId1041.add($.__views.__alloyId1042);
$.__views.__alloyId1043 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1043"
});
$.__views.__alloyId1038.add($.__views.__alloyId1043);
$.__views.__alloyId1044 = Ti.UI.createLabel({
text: "9 (sec) RM0.05",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1044"
});
$.__views.__alloyId1043.add($.__views.__alloyId1044);
$.__views.__alloyId1045 = Ti.UI.createTableViewRow({
height: "80",
width: "100%",
layout: "horizontal",
separatorColor: "#000",
id: "__alloyId1045"
});
$.__views.__alloyId1009.add($.__views.__alloyId1045);
$.__views.__alloyId1046 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1046"
});
$.__views.__alloyId1045.add($.__views.__alloyId1046);
$.__views.__alloyId1047 = Ti.UI.createLabel({
text: "06/03/2015 12:05:07",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1047"
});
$.__views.__alloyId1046.add($.__views.__alloyId1047);
$.__views.__alloyId1048 = Ti.UI.createView({
width: "33%",
height: "100",
id: "__alloyId1048"
});
$.__views.__alloyId1045.add($.__views.__alloyId1048);
$.__views.__alloyId1049 = Ti.UI.createLabel({
text: "On Net 6017000000",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1049"
});
$.__views.__alloyId1048.add($.__views.__alloyId1049);
$.__views.__alloyId1050 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1050"
});
$.__views.__alloyId1045.add($.__views.__alloyId1050);
$.__views.__alloyId1051 = Ti.UI.createLabel({
text: "9 (sec) RM0.05",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1051"
});
$.__views.__alloyId1050.add($.__views.__alloyId1051);
$.__views.__alloyId1052 = Ti.UI.createTableViewRow({
height: "80",
width: "100%",
layout: "horizontal",
separatorColor: "#000",
id: "__alloyId1052"
});
$.__views.__alloyId1009.add($.__views.__alloyId1052);
$.__views.__alloyId1053 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1053"
});
$.__views.__alloyId1052.add($.__views.__alloyId1053);
$.__views.__alloyId1054 = Ti.UI.createLabel({
text: "07/03/2015 12:05:07",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1054"
});
$.__views.__alloyId1053.add($.__views.__alloyId1054);
$.__views.__alloyId1055 = Ti.UI.createView({
width: "33%",
height: "100",
id: "__alloyId1055"
});
$.__views.__alloyId1052.add($.__views.__alloyId1055);
$.__views.__alloyId1056 = Ti.UI.createLabel({
text: "On Net 6017000000",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1056"
});
$.__views.__alloyId1055.add($.__views.__alloyId1056);
$.__views.__alloyId1057 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1057"
});
$.__views.__alloyId1052.add($.__views.__alloyId1057);
$.__views.__alloyId1058 = Ti.UI.createLabel({
text: "9 (sec) RM0.05",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1058"
});
$.__views.__alloyId1057.add($.__views.__alloyId1058);
$.__views.__alloyId1059 = Ti.UI.createTableViewRow({
height: "80",
width: "100%",
layout: "horizontal",
separatorColor: "#000",
id: "__alloyId1059"
});
$.__views.__alloyId1009.add($.__views.__alloyId1059);
$.__views.__alloyId1060 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1060"
});
$.__views.__alloyId1059.add($.__views.__alloyId1060);
$.__views.__alloyId1061 = Ti.UI.createLabel({
text: "08/03/2015 12:05:07",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1061"
});
$.__views.__alloyId1060.add($.__views.__alloyId1061);
$.__views.__alloyId1062 = Ti.UI.createView({
width: "33%",
height: "100",
id: "__alloyId1062"
});
$.__views.__alloyId1059.add($.__views.__alloyId1062);
$.__views.__alloyId1063 = Ti.UI.createLabel({
text: "On Net 6017000000",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1063"
});
$.__views.__alloyId1062.add($.__views.__alloyId1063);
$.__views.__alloyId1064 = Ti.UI.createView({
width: "33%",
height: "100%",
id: "__alloyId1064"
});
$.__views.__alloyId1059.add($.__views.__alloyId1064);
$.__views.__alloyId1065 = Ti.UI.createLabel({
text: "9 (sec) RM0.05",
backgroundColor: "transparent",
color: "black",
textAlign: "left",
left: "10",
id: "__alloyId1065"
});
$.__views.__alloyId1064.add($.__views.__alloyId1065);
$.__views.table = Ti.UI.createTableView({
data: __alloyId1008,
id: "table",
scrollable: "true"
});
$.__views.iddVoice.add($.__views.table);
exports.destroy = function() {};
_.extend($, $.__views);
__defers["$.__views.__alloyId1005!click!back"] && $.__views.__alloyId1005.addEventListener("click", back);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller; | hardikamal/xox | Resources/iphone/alloy/controllers/iddVoice.js | JavaScript | apache-2.0 | 16,804 |
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const ksuid = require('ksuid');
const cloneDeep = require('clone-deep');
const { OADAError } = require('oada-error');
const { default: config } = require('./config');
const requester = require('./requester');
const router = express.Router();
const { users } = require('@oada/lib-arangodb');
function sanitizeDbResult(user) {
if (!user) return null;
const u = cloneDeep(user);
if (u._rev) delete u._rev;
if (u.password) delete u.password;
return u;
}
//router.post('/', bodyParser.json({
// strict: false,
// type: ['json', '+json'],
// limit: '20mb',
//}));
router.use(
bodyParser.json({
strict: false,
type: ['json', '+json'],
limit: '20mb',
})
);
function requestUserWrite(req, id) {
// TODO: Sanitize POST body?
return requester
.send(
{
connection_id: req.id,
domain: req.get('host'),
token: req.get('authorization'),
authorization: req.authorization,
user: req.body,
userid: id, // need for PUT, ignored for POST
},
config.get('kafka.topics.userRequest')
)
.tap(function chkSuccess(resp) {
switch (resp.code) {
case 'success':
return Promise.resolve();
default:
let msg = 'write failed with code ' + resp.code;
return Promise.reject(new OADAError(msg));
}
});
}
router.post('/', function (req, res) {
req.log.info('Users POST, body = %O', req.body);
// Note: if the username already exists, the ksuid() below will end up
// silently discarded and replaced in the response with the real one.
const newid = ksuid.randomSync().string; // generate a random string for ID
// generate an ID for this particular request
if (!req.id) req.id = ksuid.randomSync().string;
return requestUserWrite(req, newid).then((resp) => {
// TODO: Better status code choices?
// if db didn't send back a user, it was an update so use id from URL
const id = resp && resp.user ? resp.user['_key'] : newid;
// return res.redirect(201, req.baseUrl + '/' + id)
res.set('content-location', req.baseUrl + '/' + id);
return res.status(200).end();
});
});
// Update (merge) a user:
router.put('/:id', function (req, res) {
req.log.info('Users PUT(id: ' + req.params.id + '), body = %O', req.body);
// generate an ID for this particular request
if (!req.id) req.id = ksuid.randomSync().string;
return requestUserWrite(req, req.params.id).then((resp) => {
// TODO: Better status code choices?
// if db didn't send back a user, it was an update so use id from URL
const id = resp && resp.user ? resp.user['_key'] : req.params.id;
// return res.redirect(201, req.baseUrl + '/' + id)
res.set('content-location', req.baseUrl + '/' + id);
return res.status(200).end();
});
});
// Lookup a username, limited to tokens and users with oada.admin.user scope
router.get('/username-index/:uname', function (req, res) {
// Check token scope
req.log.trace(
'username-index: Checking token scope, req.authorization.scope = %s',
req.authorization ? req.authorization.scope : null
);
const havetokenscope = req.authorization.scope.find(
(s) => s === 'oada.admin.user:read' || s === 'oada.admin.user:all'
);
if (!havetokenscope) {
req.log.warn(
'WARNING: attempt to lookup user by username (username-index), but token does not have oada.admin.user:read or oada.admin.user:all scope!'
);
throw new OADAError(
'Token does not have required oada.admin.user scope',
401
);
}
// Check user's scope
req.log.trace('username-index: Checking user scope, req.user = %O', req.user);
const haveuserscope =
Array.isArray(req.user.scope) &&
req.user.scope.find(
(s) => s === 'oada.admin.user:read' || s === 'oada.admin.user:all'
);
if (!haveuserscope) {
req.log.warn(
'WARNING: attempt to lookup user by username (username-index), but USER does not have oada.admin.user:read or oada.admin.user:all scope!'
);
throw new OADAError(
'USER does not have required oada.admin.user scope',
403
);
}
return users
.findByUsername(req.params.uname)
.then((u) => {
u = sanitizeDbResult(u);
if (!u) {
req.log.info(
`#username-index: 404: username ${req.params.uname} does not exist`
);
res
.status(404)
.send('Username ' + req.params.uname + ' does not exist.');
return res.end();
}
req.log.info(
`#username-index: found user, returning info for userid ${u._id}`
);
res
.set('content-location', `/${u._id}`)
.set('content-type', 'application/vnd.oada.user.1+json')
.status(200)
.json(u);
return res.end();
})
.catch((e) => {
req.log.error(
'FAILED to find user in DB for username-index, username = ' +
req.params.uname +
'. Error was: %O',
e
);
res.status(500).send('Internal Error: ', e.toString());
return res.end();
});
});
router.get('/me', function (req, res, next) {
req.url = req.url.replace(
/^\/me/,
`/${req.user['user_id'].replace(/^users\//, '')}`
);
next();
});
//TODO: don't return stuff to anyone anytime
router.get('/:id', function (req, res) {
return users.findById(req.params.id).then((response) => {
// Copy and get rid of password field
// eslint-disable-next-line no-unused-vars
let user = cloneDeep(response);
if (!user) {
return res.status(404).end();
}
if (user.password) delete user.password;
// let { password, ...user } = response // doesn't work if no password comes back
res.set('Content-Location', '/users/' + req.params.id);
return res.json(user);
});
});
module.exports = router;
| OADA/oada-srvc-docker | oada/services/http-handler/src/users.js | JavaScript | apache-2.0 | 5,909 |
angular.module('BitGo.API.EnterpriseAPI', [])
/*
Notes:
- This module is for managing all http requests and local caching/state
for all Enterprise objects in the app
*/
.factory('EnterpriseAPI', ['$q', '$location', '$resource', '$rootScope', 'UtilityService', 'CacheService', 'EnterpriseModel', 'NotifyService',
function($q, $location, $resource, $rootScope, UtilityService, CacheService, EnterpriseModel, NotifyService) {
var DEFAULT_CACHED_ENTERPRISE_ID = 'personal';
var kApiServer = UtilityService.API.apiServer;
var PromiseSuccessHelper = UtilityService.API.promiseSuccessHelper;
var PromiseErrorHelper = UtilityService.API.promiseErrorHelper;
// Cache setup
var enterpriseCache = new CacheService.Cache('localStorage', 'Enterprises', 120 * 60 * 1000);
/**
* update the user's cached current enterprise
* @param enterprise {String} id for the new enterprise to set in cache
* @private
*/
function updateUserCurrentEnterpriseCache(enterprise) {
var userId = $rootScope.currentUser.settings.id;
if (!enterprise || !userId) {
throw new Error('missing params');
}
enterpriseCache.add('currentEnterprise' + userId, enterprise);
}
/**
* Set up a default current enterprise before a user is set
* @private
*/
function initUserCurrentEnterpriseCache() {
var userId = $rootScope.currentUser && $rootScope.currentUser.settings.id;
var cachedEnterprise = userId && enterpriseCache.get('currentEnterprise' + userId);
if (cachedEnterprise) {
// if the user has cached preferences, update the cache based on them
return updateUserCurrentEnterpriseCache(cachedEnterprise);
} else {
// otherwise update the cache with a default current enterprise ('personal')
return updateUserCurrentEnterpriseCache(DEFAULT_CACHED_ENTERPRISE_ID);
}
}
/**
* Returns the current enterprise
* @returns {String} current enterprise id || undefined
* @private
*/
function getCurrentEnterprise() {
// If there is no user, return the default cached enterprise
var userId = $rootScope.currentUser && $rootScope.currentUser.settings.id;
if (!userId) {
console.error('Missing current user id');
return;
}
// Return the user's last cached current enterprise or default to personal
var curEnterpriseId = enterpriseCache.get('currentEnterprise' + userId) || 'personal';
return curEnterpriseId;
}
/**
* Sets the new current enterprise object on rootScope
* @param enterprise {String} id for the new current enterprise
* @private
*/
function setCurrentEnterprise(enterprise) {
if (!enterprise) {
throw new Error('Missing enterprise');
}
if (_.isEmpty($rootScope.enterprises.all)) {
throw new Error('Missing $rootScope.enterprises.all');
}
var newCurrentEnterprise = $rootScope.enterprises.all[enterprise.id];
if (!newCurrentEnterprise) {
throw new Error('Could not find the enterprise: ' + enterprise.id);
}
// Set the new current enterprise in the app and cache
$rootScope.enterprises.current = newCurrentEnterprise;
updateUserCurrentEnterpriseCache($rootScope.enterprises.current.id);
// If the new enterprise is different from the one the user is currently in,
// broadcast the new event and go to the enterprise's wallets list page
if ($rootScope.enterprises.current.id !== UtilityService.Url.getEnterpriseIdFromUrl()) {
$rootScope.$emit('EnterpriseAPI.CurrentEnterpriseSet', {
enterprises: $rootScope.enterprises
});
}
}
// Fetch all enterprises for the user
function getAllEnterprises() {
var resource = $resource(kApiServer + '/enterprise', {});
return resource.get({}).$promise
.then(
function(data) {
// Array of enterprises returned
var enterprises = data.enterprises;
// Reset the rootScope enterprise list
$rootScope.enterprises.all = {};
// Create all 'real' enterprise objects
_.forEach(enterprises, function(enterpriseData) {
enterprise = new EnterpriseModel.Enterprise(enterpriseData);
$rootScope.enterprises.all[enterprise.id] = enterprise;
enterpriseCache.add(enterprise.name, enterprise);
});
// Create the 'personal' enterprise object
var personalEnterprise = new EnterpriseModel.Enterprise();
$rootScope.enterprises.all[personalEnterprise.id] = personalEnterprise;
enterpriseCache.add(personalEnterprise.name, personalEnterprise);
// If an enterprise is set in the url use it; otherwise default to personal
var curEnterpriseId = getCurrentEnterprise();
_.forIn($rootScope.enterprises.all, function(enterprise) {
if (enterprise.id === curEnterpriseId) {
$rootScope.enterprises.current = enterprise;
}
});
// Let listeners in the app know that the enterprise list was set
$rootScope.$emit('EnterpriseAPI.CurrentEnterpriseSet', { enterprises: $rootScope.enterprises });
return enterprises;
},
PromiseErrorHelper()
);
}
/**
* Creates an enterprise inquiry for the marketing team
* @param inquiry {Object} contains necessary params for the post
* @private
*/
function createInquiry(inquiry) {
if (!inquiry) {
throw new Error('invalid params');
}
var resource = $resource(kApiServer + '/enterprise/inquiry', {});
return new resource.save(inquiry).$promise
.then(
PromiseSuccessHelper(),
PromiseErrorHelper()
);
}
/**
* Sets the users on the current enterprise
* @private
*/
function setCurrentEnterpriseUsers() {
if (!$rootScope.enterprises.current) {
console.log('Cannot set users on the current enterprise without a current enterprise');
return false;
}
$rootScope.enterprises.current.setUsers($rootScope.wallets.all);
}
/**
* Decorates each enterprise with wallet data once every wallet returns
* @param wallets {Object} collection of BitGo client wallet objects
* @private
*/
function decorateEnterprisesWithWalletShareData(walletShares) {
_.forIn($rootScope.enterprises.all, function(enterprise) {
enterprise.setWalletShareCount(walletShares);
});
}
/**
* Decorates each enterprise with wallet data once every wallet returns
* @param wallets {Object} collection of BitGo client wallet objects
* @private
*/
function decorateEnterprisesWithWalletData(wallets) {
_.forIn($rootScope.enterprises.all, function(enterprise) {
enterprise.setWalletCount(wallets);
enterprise.setBalance(wallets);
});
}
/**
* Returns basic info for an enterprise - used publicly, not scoped to a user
* @param { String } enterpriseName
* @private
* @returns { Promise }
*/
function getInfoByName(enterprise) {
if (!enterprise) {
throw new Error('missing enterprise');
}
var resource = $resource(kApiServer + '/enterprise/name/' + enterprise, {});
return new resource.get({}).$promise
.then(
PromiseSuccessHelper(),
PromiseErrorHelper()
);
}
// Event Handling
$rootScope.$on('UserAPI.CurrentUserSet', function(evt, user) {
initUserCurrentEnterpriseCache();
getAllEnterprises();
});
$rootScope.$on('UserAPI.UserLogoutEvent', function(evt, user) {
// clear enterprises on rootscope on logout
init();
});
$rootScope.$on('WalletsAPI.UserWalletsSet', function(evt, data) {
if (_.isEmpty(data.allWallets)) {
return;
}
// Set users on the current enterprise
setCurrentEnterpriseUsers();
// Decorate all enterprises with the latest wallet data
decorateEnterprisesWithWalletData(data.allWallets);
});
$rootScope.$on('WalletSharesAPI.AllUserWalletSharesSet', function(evt, data) {
if (_.isEmpty(data.walletShares.incoming) && _.isEmpty(data.walletShares.outgoing)) {
return;
}
// Decorate all enterprises with the latest walletShares data
decorateEnterprisesWithWalletShareData(data.walletShares);
});
function init() {
$rootScope.enterprises = {
all: {},
current: null
};
}
init();
// In-client API
return {
getInfoByName: getInfoByName,
getAllEnterprises: getAllEnterprises,
setCurrentEnterprise: setCurrentEnterprise,
getCurrentEnterprise: getCurrentEnterprise,
createInquiry: createInquiry
};
}
]);
| jmaurice/bitgo-chrome | api/scripts/enterpriseAPI.js | JavaScript | apache-2.0 | 8,868 |
export const ChampionMastery = new Mongo.Collection('championMastery');
import {updateChampionMasteries} from '../riot/championMastery';
import {Champions} from './champion';
import {Summoners} from './summoner';
import {Regions} from './region.js';
ChampionMastery.helpers({
champion: function(){
return Champions.findOne({id:this.data.championId});
},
summoner:function(){
return Summoners.findOne({id:this.data.playerId})
}
});
if (Meteor.isServer) {
var Future = Npm.require('fibers/future');
// This code only runs on the server
Meteor.publish('SummonerChampionMastery', function (region, summonerId) {
check(region, String);
check(summonerId, Number);
let masteries = ChampionMastery.find({
"data.playerId": summonerId,
region: region
});
if(masteries.count() == 0){
var regionObject = Regions.findOne({slug:region});
updateChampionMasteries(regionObject,summonerId);
}
return masteries;
});
Meteor.publish('ChampionLeaderBoards', function (regions, championId, size, offset) {
check(regions, Array);
check(championId, Number);
check(size, Number);
check(offset, Number);
let championMasteries = ChampionMastery.find({
"data.championId": championId,
region: {$in: regions}
}, {
sort: {"data.championPoints": -1},
limit: size,
skip: size * offset
});
var ids = championMasteries.map(function(championMastery){
return championMastery.data.playerId;
});
let users = Summoners.find({
id: {$in: ids}
});
return [
championMasteries,
users
]
});
Meteor.publish("leaderBoardsCount", function (regions, championId) {
check(regions, Array);
check(championId, Number);
let subscription = this;
let summonerCount = ChampionMastery.find({
"data.championId": championId,
region: {$in: regions}
}).count();
let countObject = {};
countObject.summonerCount = summonerCount;
countObject.type = 'leaderboard'; // should be added because all your counts will be contained in one collection
subscription.added('counts', Random.id(), countObject);
subscription.ready();
});
}
Meteor.methods({
'updateSummonerStats'(regionSlug, summonerId) {
check(regionSlug, String);
check(summonerId, String);
if(Meteor.isServer){
let region = Regions.findOne({slug:regionSlug});
updateChampionMasteries(region,summonerId);
}
},
'getLeaderBoardPosition'(championId, regionSlug, summonerId){
check(regionSlug, String);
check(summonerId, Number);
check(championId, Number);
if(Meteor.isServer){
var future = new Future();
let championMasteries = ChampionMastery.find({
"data.championId": championId,
region: regionSlug
},{sort: {"data.championPoints": -1}});
championMasteries.forEach(function(mastery, index){
if(mastery.region === regionSlug && mastery.data.playerId == summonerId){
future.return(index);
}
});
return future.wait();
}
},
'refreshMasteries'(region, summonerId){
check(region, String);
check(summonerId, Number);
let regionObject = Regions.findOne({slug:region});
let summoner = Summoners.findOne({
id: summonerId,
region: region
});
if(!summoner.hasOwnProperty('statsRefreshedAt')){
summoner.statsRefreshedAt = new Date();
Summoners.update(summoner._id, summoner);
updateChampionMasteries(regionObject,summonerId);
}else {
var minutes = moment(new Date()).diff(moment(summoner.statsRefreshedAt), 'minutes');
if(minutes > 60){
summoner.statsRefreshedAt = new Date();
Summoners.update(summoner._id, summoner);
updateChampionMasteries(regionObject,summonerId);
}
}
}
});
| Dragonpurse/mastery-lb | imports/api/championMastery.js | JavaScript | apache-2.0 | 4,333 |
/* global angular */
'use strict';
var controllers = angular.module('participantDialogControllers', []);
/**
* The New Conversation Controller provides a UI for creating a new Conversation.
* This consists of a place to edit a title bar, a list of users to select,
* and a place to enter a first message.
*/
controllers.controller('participantsDialogCtrl', function($scope) {
/**
* Hacky DOMish way of getting the selected users
* Angular developers should feel free to improve on this
* and submit a PR :-)
*/
function getSelectedUsers() {
var result = Array.prototype.slice.call(document.querySelectorAll('.participant-list :checked'))
.map(function(node) {
return $scope.appCtrlState.client.getIdentity(node.value);
});
return result;
}
/**
* On typing a message and hitting ENTER, the send method is called.
* $scope.chatCtrlState.currentConversation is a basic object; we use it to get the
* Conversation instance and use the instance to interact with Layer Services
* sending the Message.
*
* See: http://static.layer.com/sdk/docs/#!/api/layer.Conversation
*
* For this method, we simply do nothing if no participants;
* ideally, some helpful error would be reported to the user...
*
* Once the Conversation itself has been created, update the URL
* to point to that Conversation.
*/
$scope.createConversation = function() {
// Get the userIds of all selected users
var participants = getSelectedUsers();
if (participants.length) {
// Create the Conversation
var conversationInstance = $scope.appCtrlState.client.createConversation({
participants: participants,
distinct: participants.length === 1,
});
// Update our location.
location.hash = '#' + conversationInstance.id.substring(8);
Array.prototype.slice.call(document.querySelectorAll('.participant-list :checked')).forEach(function(input) {
input.checked = false;
});
}
};
});
| layerhq/layer-js-sampleapps | examples/websdk-samples/angular/app/participant-dialog-controllers.js | JavaScript | apache-2.0 | 2,024 |
/**
* Created by mario (https://github.com/hyprstack) on 10/07/15.
*/
var imageUpLoad = Backbone.View.extend({
template: _.template(document.getElementById("file-uploader-template").innerHTML),
// global variables passed in through options - required
_file: null, // our target file
cb: null,
maxFileSize: null, // megabytes
maxHeight: null, // pixels - resize target
maxWidth: null, // pixels - resize target
minWidth: null, // pixels
maxAllowedHeight: null, //pixels
maxAllowedWidth: null, // pixels
// globals determined through function
sourceWidth: null,
sourceHeight: null,
initialize: function (options) {
this._file = options.file;
this.cb = options.cb;
this.maxHeight = options.maxHeight;
this.maxWidth = options.maxWidth;
this.maxFileSize = options.maxFileSize;
this.minWidth = options.minWidth;
this.maxAllowedHeight = options.maxAllowedHeight;
this.maxAllowedWidth = options.maxAllowedWidth;
},
render: function () {
this.setElement(this.template());
this.mainFn(this._file);
return this;
},
// reads file data to determine if exif exists or not. returns a data object
readFileData: function (file, callback) {
loadImage.parseMetaData(
file,
_.bind(this.resizeImage, this, file, callback)
);
},
// resizes image if needs to be resized, otherwise simply corrects orientation
resizeImage: function (file, callback, data) {
var options = this.sizeConfig(file);
if (data.exif) {
options.orientation = data.exif.get('Orientation');
}
loadImage(
file,
_.bind(this.returnDataUrl, this),
options
);
},
// call callback and passes dataUrl
returnDataUrl: function (src) {
var dataUrl = src.toDataURL("image/png");
this.cb(dataUrl);
},
transformImg: function (file) {
// triggers event warning if image width is less than minWidth
if ( this.sourceWidth < this.minWidth ) {
this.trigger("image-small");
return;
}
this.readFileData(file);
},
// returns the width and height of the source file and calls the transform function
mainFn: function (file) {
var fr = new FileReader();
var that = this;
fr.onloadend = function () {
var _img = new Image();
// image width and height can only be determined once the image has loaded
_img.onload = function () {
that.sourceWidth = _img.width;
that.sourceHeight = _img.height;
that.transformImg(file);
};
_img.src = fr.result;
};
fr.readAsDataURL(file);
},
// check and configure our options for resizing
sizeConfig: function (file) {
var _size = file.size;
if ( _size > this.maxFileSize && (this.sourceHeight > this.maxAllowedHeight || this.sourceWidth > this.maxAllowedWidth) ) {
return this.resizeConf();
} else if ( _size < this.maxFileSize && (this.sourceHeight > this.maxAllowedHeight || this.sourceWidth > this.maxAllowedWidth) ) {
return this.resizeConf();
} else {
return {
contain: true,
canvas: true
}
}
},
resizeConf: function () {
return {
contain: true,
maxWidth: this.maxWidth,
maxHeight: this.maxHeight,
canvas: true
}
}
});
| hevnly/js-image-resizer | js/views/image-upload.js | JavaScript | apache-2.0 | 3,693 |
import React from 'react';
import {storiesOf} from '@kadira/storybook';
import 'codemirror/mode/python/python';
import {CodeWindow} from '../CodeWindow';
class ColorPickSpan extends React.Component {
static propTypes = {
onChange: React.PropTypes.func,
color: React.PropTypes.string,
span: React.PropTypes.object,
children: React.PropTypes.node,
};
mouseOver = () => {
this.props.onChange([{color: this.props.color, span: this.props.span}]);
}
mouseOut = () => {
this.props.onChange([]);
}
render() {
return (
<span
style={{
backgroundColor: this.props.color
}}
onMouseOver={this.mouseOver}
onMouseOut={this.mouseOut}
>
{this.props.children}
</span>
);
}
}
class HighlightPicker extends React.Component {
state = { highlights: [] }
changeHighlight = (highlights) => {
this.setState({
highlights: highlights
});
}
render() {
return (
<div>
<div>
<ColorPickSpan
onChange={this.changeHighlight}
color="#eee"
span={{from:{line: 0, ch: 0}, to: {line:0, ch: 5}}}
>
Gray
</ColorPickSpan>
<ColorPickSpan
onChange={this.changeHighlight}
color="blue"
span={{from:{line: 1, ch: 5}, to: {line:1, ch: 10}}}
>
Blue
</ColorPickSpan>
</div>
<CodeWindow
source={"print('Ahoy world')\ncheck: 2 + 2 is 4 end"}
codemirrorOptions={{ mode: "python" }}
highlights={this.state.highlights}
/>
</div>
);
}
}
storiesOf("CodeWindow", module)
.add("withSource", () => (
<CodeWindow
source={"print('Ahoy, world!')"}
codemirrorOptions={{
mode: "python"
}}
/>
))
.add("highlighted", () => (
<CodeWindow
source={"print('Ahoy, world!')"}
codemirrorOptions={{
mode: "python"
}}
highlights={[
{
color: "#eeeeee",
span: {from: {line: 0, ch: 1}, to: {line: 0, ch: 5}}
}
]}
/>
))
.add("highlightChoice", () => (
<HighlightPicker />
));
| pcardune/pyret-ide | src/components/stories/CodeWindow.js | JavaScript | apache-2.0 | 2,215 |
/**
* @license Copyright 2018 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
const Audit = require('./audit.js');
const URL = require('../lib/url-shim.js');
const NetworkRecords = require('../computed/network-records.js');
class NetworkRequests extends Audit {
/**
* @return {LH.Audit.Meta}
*/
static get meta() {
return {
id: 'network-requests',
scoreDisplayMode: Audit.SCORING_MODES.INFORMATIVE,
title: 'Network Requests',
description: 'Lists the network requests that were made during page load.',
requiredArtifacts: ['devtoolsLogs'],
};
}
/**
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<LH.Audit.Product>}
*/
static audit(artifacts, context) {
const devtoolsLog = artifacts.devtoolsLogs[Audit.DEFAULT_PASS];
return NetworkRecords.request(devtoolsLog, context).then(records => {
const earliestStartTime = records.reduce(
(min, record) => Math.min(min, record.startTime),
Infinity
);
/** @param {number} time */
const timeToMs = time => time < earliestStartTime || !Number.isFinite(time) ?
undefined : (time - earliestStartTime) * 1000;
const results = records.map(record => {
const endTimeDeltaMs = record.lrStatistics && record.lrStatistics.endTimeDeltaMs;
const TCPMs = record.lrStatistics && record.lrStatistics.TCPMs;
const requestMs = record.lrStatistics && record.lrStatistics.requestMs;
const responseMs = record.lrStatistics && record.lrStatistics.responseMs;
return {
url: URL.elideDataURI(record.url),
startTime: timeToMs(record.startTime),
endTime: timeToMs(record.endTime),
finished: record.finished,
transferSize: record.transferSize,
resourceSize: record.resourceSize,
statusCode: record.statusCode,
mimeType: record.mimeType,
resourceType: record.resourceType,
lrEndTimeDeltaMs: endTimeDeltaMs, // Only exists on Lightrider runs
lrTCPMs: TCPMs, // Only exists on Lightrider runs
lrRequestMs: requestMs, // Only exists on Lightrider runs
lrResponseMs: responseMs, // Only exists on Lightrider runs
};
});
// NOTE(i18n): this audit is only for debug info in the LHR and does not appear in the report.
/** @type {LH.Audit.Details.Table['headings']} */
const headings = [
{key: 'url', itemType: 'url', text: 'URL'},
{key: 'startTime', itemType: 'ms', granularity: 1, text: 'Start Time'},
{key: 'endTime', itemType: 'ms', granularity: 1, text: 'End Time'},
{
key: 'transferSize',
itemType: 'bytes',
displayUnit: 'kb',
granularity: 1,
text: 'Transfer Size',
},
{
key: 'resourceSize',
itemType: 'bytes',
displayUnit: 'kb',
granularity: 1,
text: 'Resource Size',
},
{key: 'statusCode', itemType: 'text', text: 'Status Code'},
{key: 'mimeType', itemType: 'text', text: 'MIME Type'},
{key: 'resourceType', itemType: 'text', text: 'Resource Type'},
];
const tableDetails = Audit.makeTableDetails(headings, results);
return {
score: 1,
details: tableDetails,
};
});
}
}
module.exports = NetworkRequests;
| umaar/lighthouse | lighthouse-core/audits/network-requests.js | JavaScript | apache-2.0 | 3,962 |
module.exports.handler = (event, context) => {
if (!context.iopipe || !context.iopipe.mark) {
return context.succeed(new Error('No plugins'));
}
return context.succeed(200);
};
| iopipe/serverless-plugin-iopipe | testProjects/cosmi/handlers/simple.js | JavaScript | apache-2.0 | 187 |
/**
* KnowledgeWorkbenchModel
* A workbench for wiring relations among topics
*/
var types = require('tqtopicmap/lib/types'),
icons = require('tqtopicmap/lib/icons'),
properties = require('tqtopicmap/lib/properties'),
constants = require('../../core/constants'),
tagmodel = require('../tag/tagmodel'),
relationlist = require('./relationlist')
;
var KnowledgeWorkbenchModel = module.exports = function(environment, cm, tmenv) {
var CommonModel = cm;
if (!CommonModel) {
CommonModel = environment.getCommonModel();
}
var myEnvironment = environment;
var topicMapEnvironment = tmenv;
if (!topicMapEnvironment) {
topicMapEnvironment = environment.getTopicMapEnvironment();
}
var DataProvider = topicMapEnvironment.getDataProvider(),
TopicModel = topicMapEnvironment.getTopicModel(),
RelationModel = topicMapEnvironment.getRelationModel(),
TagModel = new tagmodel(environment, CommonModel, topicMapEnvironment),
queryDSL = topicMapEnvironment.getQueryDSL(),
relationForm = [];
function buildForm() {
var x = relationlist.RelationList;
var y;
for (var i=0;i<x.length;i++) {
y = {};
y.val = x[i];
relationForm.push(y);
}
}
buildForm();
var self = this;
self.getNewRelationForm = function() {
return relationForm;
};
self.arrayContains = function(array, value) {
return (array.indexOf(value) > -1);
};
/**
* Called from CommonModel.__doAjaxFetch
* @param theNode
* @param callback signature (result)
*/
self.showRelations = function(theNode, callback) {
console.log("KnowledgeWorkbenchModel.showRelations "+theNode);
var result = [];
//TODO this ignores private relations
//This looks at tuples and shows those which are found on the RelationList;
// Push relation structs to result
var relns = theNode.listRelations();
myEnvironment.logDebug("KnowledgeWorkbenchModel.showRelations "+theNode.getLocator()+" "+relns);
if (relns) {
var len = relns.length;
var rx;
for (var i=0;i<len;i++) {
rx = relns[i];
if (self.arrayContains(relationlist.RelationList, rx.relationType)) {
result.push(rx);
}
}
return callback(result);
} else {
return callback(result);
}
};
/**
* Create a connection between two nodes
* @param sourceLocator
* @param targetLocator
* @param relationType
* @param userObject
* @param taglist
* @param callback signature (err, relationnode)
*/
//TODO needs isPrivate
self.createConnection = function(sourceLocator, targetLocator, relationType, userObject, taglist, callback) {
console.log("KnowledgeWorkbenchModel.createConnection "+sourceLocator+" "+targetLocator+" "+relationType);
var error = "",
result, //the tuple
sourceNode,
targetNode,
userTopic,
isPrivate = false; //TODO
credentials = userObject.credentials,
userLocator = userObject.handle;
myEnvironment.logDebug("KnowledgeWorkbenchModel.createConnection "+sourceLocator+" "+targetLocator+" "+relationType+" "+taglist+" "+userLocator);
//get UserTopic
DataProvider.getNodeByLocator(userLocator,credentials, function(err,usr) {
userTopic = usr;
DataProvider.getNodeByLocator(sourceLocator,credentials,function(err,p1) {
if (err) {error += err;}
sourceNode = p1;
DataProvider.getNodeByLocator(targetLocator,credentials,function(err,p2) {
if (err) {error += err;}
targetNode = p2;
myEnvironment.logDebug("KnowledgeWorkbenchModel.createConnection-x ");
RelationModel.createRelation(sourceNode,targetNode,relationType,userLocator,credentials,isPrivate,function(err,data) {
myEnvironment.logDebug("KnowledgeWorkbenchModel.createConnection-1 "+err+" "+data);
//TODO seeing some kind of internal bug which returns undefined
if (err) {error += err;}
result = data;
if (result) {
myEnvironment.addRecentConnection(result.getLocator(), result.getLabel("en"));
//If there are tags, process them
if (taglist.length > 0) {
myEnvironment.logDebug("KnowledgeWorkbenchModel.createConnection-2 "+userLocator+" | "+err+" | "+userTopic);
TagModel.processTagList(taglist, userTopic, result, credentials, function(err,rsx) {
if (err) {error += err;}
console.log('NEW_POST-1 '+rsx);
//result could be an empty list;
//TagModel already added Tag_Doc and Doc_Tag relations
console.log("ARTICLES_CREATE_2 "+JSON.stringify(rsx));
DataProvider.putNode(result, function(err,data) {
console.log('ARTICLES_CREATE-3 '+err);
if (err) {console.log('ARTICLES_CREATE-3a '+err)}
console.log('ARTICLES_CREATE-3b '+userTopic);
TopicModel.relateExistingNodesAsPivots(userTopic,result,types.CREATOR_DOCUMENT_RELATION_TYPE,
userTopic.getLocator(),
icons.RELATION_ICON, icons.RELATION_ICON, false, credentials, function(err,data) {
if (err) {console.log('ARTICLES_CREATE-3d '+err);}
myEnvironment.logDebug("KnowledgeWorkbenchModel.createConnection-3 "+userLocator+" | "+err+" | "+result);
//modified to return entire node
return callback(err,result);
}); //r1
}); //putnode
}); // processtaglist
} else {
DataProvider.putNode(result, function(err,data) {
console.log('ARTICLES_CREATE-3 '+err);
if (err) {console.log('ARTICLES_CREATE-3a '+err)}
console.log('ARTICLES_CREATE-3b '+userTopic);
TopicModel.relateExistingNodesAsPivots(userTopic,result,types.CREATOR_DOCUMENT_RELATION_TYPE,
userTopic.getLocator(),icons.RELATION_ICON, icons.RELATION_ICON, false, credentials, function(err,data) {
if (err) {console.log('ARTICLES_CREATE-3d '+err);}
myEnvironment.logDebug("KnowledgeWorkbenchModel.createConnection-4 "+userLocator+" | "+err+" | "+result);
callback(err,result);
}); //r1
}); //putnode
}
} else {
return callback(error,result);
}
}); //relatenodes
}); //gettarget
}); // getsource
}); // getuser
};
}; | KnowledgeGarden/TQPortal | apps/kwb/kwbmodel.js | JavaScript | apache-2.0 | 7,937 |
import {
defaultReactions,
details,
mergeInEmptyDraft,
} from "../detail-definitions.js";
import vocab from "../../app/service/vocab.js";
export const persona = {
identifier: "persona",
label: "Persona",
icon: undefined, //No Icon For Persona UseCase (uses identicon)
draft: {
...mergeInEmptyDraft({
content: {
type: [vocab.WON.PersonaCompacted],
sockets: {
"#chatSocket": vocab.CHAT.ChatSocketCompacted,
"#holderSocket": vocab.HOLD.HolderSocketCompacted,
"#buddySocket": vocab.BUDDY.BuddySocketCompacted,
// "#worksForSocket": vocab.WXSCHEMA.WorksForSocketCompacted, // TODO: Currently not in use in favour of more generic member -> Role -> member relation
"#memberOfSocket": vocab.WXSCHEMA.MemberOfSocketCompacted,
"#interestSocket": vocab.WXPERSONA.InterestSocketCompacted,
"#expertiseSocket": vocab.WXPERSONA.ExpertiseSocketCompacted,
// "#sReviewSocket": vocab.WXSCHEMA.ReviewSocketCompacted, //TODO: exclude the ability to review a persona for now
"#sEventSocket": vocab.WXSCHEMA.EventSocketCompacted,
"#sAttendeeInverseSocket":
vocab.WXSCHEMA.AttendeeInverseSocketCompacted,
// "#PrimaryAccountableOfSocket":
// vocab.WXVALUEFLOWS.PrimaryAccountableOfSocketCompacted,
// "#CustodianOfSocket": vocab.WXVALUEFLOWS.CustodianOfSocketCompacted,
// "#ActorActivitySocket":
// vocab.WXVALUEFLOWS.ActorActivitySocketCompacted, //TODO VALUEFLOWS SOCKETS CURRENTLY EXCLUDED
},
},
seeks: {},
}),
},
reactions: {
...defaultReactions,
// [vocab.WXVALUEFLOWS.ActorActivitySocketCompacted]: {
// [vocab.WXVALUEFLOWS.ActorSocketCompacted]: {
// useCaseIdentifiers: ["activity"],
// },
// },
// [vocab.WXVALUEFLOWS.PrimaryAccountableOfSocketCompacted]: {
// [vocab.WXVALUEFLOWS.PrimaryAccountableSocketCompacted]: {
// useCaseIdentifiers: ["resource"],
// },
// },
// [vocab.WXVALUEFLOWS.CustodianOfSocketCompacted]: {
// [vocab.WXVALUEFLOWS.CustodianSocketCompacted]: {
// useCaseIdentifiers: ["resource"],
// },
// },
// [vocab.WXVALUEFLOWS.ResourceActivitySocketCompacted]: {
// [vocab.WXVALUEFLOWS.ActorSocket]: {
// useCaseIdentifiers: ["action"],
// },
// },
// TODO: Currently not in use in favour of more generic member -> Role -> member relation
// [vocab.WXSCHEMA.WorksForSocketCompacted]: {
// [vocab.WXSCHEMA.WorksForInverseSocketCompacted]: {
// useCaseIdentifiers: ["organization"],
// },
// },
[vocab.WXSCHEMA.MemberOfSocketCompacted]: {
[vocab.WXSCHEMA.MemberSocketCompacted]: {
useCaseIdentifiers: ["organization"],
labels: {
owned: {
default: "Organization",
addNew: "Add to New Organization",
picker: "Pick a Organization to join",
},
nonOwned: {
default: "Organization",
addNew: "Add to New Organization",
picker: "Pick a Organization to join",
},
},
},
},
[vocab.HOLD.HolderSocketCompacted]: {
[vocab.HOLD.HoldableSocketCompacted]: {
useCaseIdentifiers: ["*"],
refuseNonOwned: true,
},
},
[vocab.WXPERSONA.InterestSocketCompacted]: {
[vocab.WXPERSONA.InterestOfSocketCompacted]: {
useCaseIdentifiers: [
"afterpartyInterest",
"breakfastInterest",
"cyclingInterest",
"genericInterest",
"lunchInterest",
"pokemonInterest",
"sightseeingInterest",
],
refuseNonOwned: true,
},
},
[vocab.WXPERSONA.ExpertiseSocketCompacted]: {
[vocab.WXPERSONA.ExpertiseOfSocketCompacted]: {
useCaseIdentifiers: ["*"],
refuseNonOwned: true,
},
},
[vocab.CHAT.ChatSocketCompacted]: {
[vocab.CHAT.ChatSocketCompacted]: {
useCaseIdentifiers: ["persona"],
refuseOwned: true,
},
[vocab.GROUP.GroupSocketCompacted]: {
useCaseIdentifiers: ["*"],
},
},
[vocab.WXSCHEMA.AttendeeInverseSocketCompacted]: {
[vocab.WXSCHEMA.AttendeeSocketCompacted]: {
useCaseIdentifiers: ["event"],
labels: {
owned: {
default: "Join Event",
addNew: "Join New Event",
picker: "Pick an Event to join",
},
nonOwned: {
default: "Join Event",
addNew: "Join New Event",
picker: "Pick an Event to join",
},
},
},
},
},
details: {
personaName: { ...details.personaName, mandatory: true },
description: { ...details.description },
website: { ...details.website },
images: { ...details.images },
location: { ...details.location },
},
seeksDetails: {},
};
| researchstudio-sat/webofneeds | webofneeds/won-owner-webapp/src/main/webapp/config/usecases/uc-persona.js | JavaScript | apache-2.0 | 4,969 |
const {now} = require('./time');
const thriftTypes = require('./gen-nodejs/zipkinCore_types');
const {
MutableSpan,
Endpoint,
ZipkinAnnotation,
BinaryAnnotation
} = require('./internalRepresentations');
class BatchRecorder {
constructor({
logger,
timeout = 60 * 1000000 // default timeout = 60 seconds
}) {
this.logger = logger;
this.timeout = timeout;
this.partialSpans = new Map();
// read through the partials spans regularly
// and collect any timed-out ones
const timer = setInterval(() => {
this.partialSpans.forEach((span, id) => {
if (this._timedOut(span)) {
this._writeSpan(id);
}
});
}, 1000);
if (timer.unref) { // unref might not be available in browsers
timer.unref(); // Allows Node to terminate instead of blocking on timer
}
}
_writeSpan(id) {
const spanToWrite = this.partialSpans.get(id);
// ready for garbage collection
this.partialSpans.delete(id);
this.logger.logSpan(spanToWrite);
}
_updateSpanMap(id, updater) {
let span;
if (this.partialSpans.has(id)) {
span = this.partialSpans.get(id);
} else {
span = new MutableSpan(id);
}
updater(span);
if (span.complete) {
this._writeSpan(id);
} else {
this.partialSpans.set(id, span);
}
}
_timedOut(span) {
return span.started + this.timeout < now();
}
_annotate(span, {timestamp}, value) {
span.addAnnotation(new ZipkinAnnotation({
timestamp,
value
}));
}
_binaryAnnotate(span, key, value) {
span.addBinaryAnnotation(new BinaryAnnotation({
key,
value,
annotationType: thriftTypes.AnnotationType.STRING
}));
}
record(rec) {
const id = rec.traceId;
this._updateSpanMap(id, span => {
switch (rec.annotation.annotationType) {
case 'ClientSend':
this._annotate(span, rec, thriftTypes.CLIENT_SEND);
break;
case 'ClientRecv':
this._annotate(span, rec, thriftTypes.CLIENT_RECV);
break;
case 'ServerSend':
this._annotate(span, rec, thriftTypes.SERVER_SEND);
break;
case 'ServerRecv':
this._annotate(span, rec, thriftTypes.SERVER_RECV);
break;
case 'Message':
this._annotate(span, rec, rec.annotation.message);
break;
case 'Rpc':
span.setName(rec.annotation.name);
break;
case 'ServiceName':
span.setServiceName(rec.annotation.serviceName);
break;
case 'BinaryAnnotation':
this._binaryAnnotate(span, rec.annotation.key, rec.annotation.value);
break;
case 'LocalAddr':
span.setEndpoint(new Endpoint({
host: rec.annotation.host.toInt(),
port: rec.annotation.port
}));
break;
default:
break;
}
});
}
toString() {
return 'BatchRecorder()';
}
}
module.exports = BatchRecorder;
| redhat-developer-demos/openshift-next-demo | msa/bonjour/node_modules/zipkin/src/batch-recorder.js | JavaScript | apache-2.0 | 3,024 |
var fs = require('fs');
var writeStream = fs.createWriteStream('./log.txt', {
flags: 'a',
encoding: 'utf8',
node: 0666
});
writeStream.on('open', function () {
var counter = 0;
//get list of files
fs.readdir('/home/abondar/IdeaProjects/NodeJSBase/', function (err, files) {
if (err) {
console.log(err);
} else {
files.forEach(function (name) {
fs.stat('/home/abondar/IdeaProjects/NodeJSBase/'+name, function (err, stats) {
if (err) {
return err;
}
if (!stats.isFile()){
counter++;
return;
}
writeStream.write('read '+name+ '\n',function (err) {
if (err){
console.error(err.message);
} else {
console.log('finished '+ name);
counter++;
if (counter>=files.length){
console.log("all read")
}
}
});
})
})
}
})
}); | Dr762/NodeJSBase | basics/read_dirs.js | JavaScript | apache-2.0 | 1,276 |
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
import {checkAccess} from "./authentication";
import Backbone from "backbone";
import _ from "lodash";
var beforeUnloads = {};
export default Backbone.Router.extend({
routes: {},
beforeUnload: function (name, fn) {
beforeUnloads[name] = fn;
},
removeBeforeUnload: function (name) {
delete beforeUnloads[name];
},
navigate: function (fragment, options) {
let continueNav = true;
const msg = _.find(_.map(beforeUnloads, function (fn) { return fn(); }), function (beforeReturn) {
if (beforeReturn) { return true; }
});
if (msg) {
continueNav = window.confirm(msg);
}
if (options && options.redirect) {
return window.location = fragment;
}
if (continueNav) {
Backbone.Router.prototype.navigate(fragment, options);
}
},
addModuleRouteObject: function (RouteObject) {
const that = this;
const routeUrls = RouteObject.prototype.getRouteUrls();
routeUrls.forEach(route => {
this.route(route, route.toString(), (...args) => {
const roles = RouteObject.prototype.getRouteRoles(route);
checkAccess(roles).then(() => {
if (!that.activeRouteObject || !that.activeRouteObject.hasRoute(route)) {
that.activeRouteObject = new RouteObject(route, args);
}
const routeObject = that.activeRouteObject;
const component = routeObject.routeCallback(route, args);
that.currentRouteOptions = {
selectedHeader: this.activeRouteObject.selectedHeader,
component,
roles,
route: route.toString()
};
that.trigger('new-component', this.currentRouteOptions);
}, () => {/* do nothing on reject*/ });
});
});
},
setModuleRoutes: function (addons) {
_.each(addons, function (module) {
if (module) {
module.initialize();
// This is pure routes the addon provides
if (module.RouteObjects) {
_.each(module.RouteObjects, this.addModuleRouteObject, this);
}
}
}, this);
},
initialize: function (addons) {
this.addons = addons;
// NOTE: This must be below creation of the layout
// FauxtonAPI header links and others depend on existence of the layout
this.setModuleRoutes(addons);
this.lastPages = [];
//keep last pages visited in Fauxton
Backbone.history.on('route', function () {
this.lastPages.push(Backbone.history.fragment);
if (this.lastPages.length > 2) {
this.lastPages.shift();
}
}, this);
}
});
| popojargo/couchdb-fauxton | app/core/router.js | JavaScript | apache-2.0 | 3,129 |
/**
* CodeOrgApp: Applab
*
* Copyright 2014-2015 Code.org
*
*/
'use strict';
import Blockly from '../blockly';
import msg from '../locale';
import codegen from '../codegen';
import utils from '../utils';
import _ from 'lodash';
var RANDOM_VALUE = 'random';
var HIDDEN_VALUE = '"hidden"';
var CLICK_VALUE = '"click"';
var VISIBLE_VALUE = '"visible"';
var generateSetterCode = function (opts) {
var value = opts.ctx.getTitleValue('VALUE');
if (value === RANDOM_VALUE) {
var possibleValues =
_(opts.ctx.VALUES)
.map(function (item) { return item[1]; })
.without(RANDOM_VALUE, HIDDEN_VALUE, CLICK_VALUE);
value = 'Applab.randomFromArray([' + possibleValues + '])';
}
return 'Applab.' + opts.name + '(\'block_id_' + opts.ctx.id + '\', ' +
(opts.extraParams ? opts.extraParams + ', ' : '') + value + ');\n';
};
// Install extensions to Blockly's language and JavaScript generator.
export function install(blockly, blockInstallOptions) {
var skin = blockInstallOptions.skin;
var isK1 = blockInstallOptions.isK1;
var generator = blockly.JavaScript;
generator.applab_eventHandlerPrologue = function () {
return '\n';
};
installContainer(blockly, generator, blockInstallOptions);
};
function installContainer(blockly, generator, blockInstallOptions) {
blockly.Blocks.applab_container = {
helpUrl: '',
init: function () {
this.setHSV(184, 1.00, 0.74);
this.appendDummyInput().appendTitle(msg.container());
this.appendValueInput('ID');
this.appendValueInput('HTML');
this.setPreviousStatement(true);
this.setInputsInline(true);
this.setNextStatement(true);
this.setTooltip(msg.containerTooltip());
}
};
generator.applab_container = function () {
var idParam = Blockly.JavaScript.valueToCode(this, 'ID',
Blockly.JavaScript.ORDER_NONE) || '';
var htmlParam = Blockly.JavaScript.valueToCode(this, 'HTML',
Blockly.JavaScript.ORDER_NONE) || '';
return 'Applab.container(\'block_id_' + this.id +
'\', ' + idParam + ', ' + htmlParam + ');\n';
};
}
| BoldIdeaInc/appmaker | app/applab/blocks.js | JavaScript | apache-2.0 | 2,112 |
// @@@LICENSE
//
// Copyright (c) 2010-2012 Hewlett-Packard Development Company, L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// LICENSE@@@
enyo.depends
(
"../data/EmailAccount.js",
"../data/AttachmentManager.js",
"../facades/Attachment.js",
"AttachmentsDrawer.js",
"FolderListPopup.js",
"BasicFadeScroller.js",
"Dialogs.js",
"../css/controls.css"
);
| fxspec06/com.palm.app.email | controls/depends.js | JavaScript | apache-2.0 | 946 |
var $ = require('jquery');
var foundation = require('foundation');
var _ = require('lodash');
$(document).foundation();
console.log("Hello Worldz");
| abits/static-boilerplate | src/js/app.js | JavaScript | bsd-2-clause | 176 |
/*!
* OS.js - JavaScript Cloud/Web Desktop Platform
*
* Copyright (c) 2011-2016, Anders Evenrud <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Anders Evenrud <[email protected]>
* @licence Simplified BSD License
*/
(function(_osjs, _http, _path, _url, _fs, _qs, _multipart, Cookies) {
'use strict';
var instance, server;
/////////////////////////////////////////////////////////////////////////////
// HELPERS
/////////////////////////////////////////////////////////////////////////////
/**
* Respond to HTTP Call
*/
function respond(data, mime, response, headers, code, pipeFile) {
data = data || '';
headers = headers || [];
mime = mime || 'text/html; charset=utf-8';
code = code || 200;
function _end() {
if ( instance.handler && instance.handler.onRequestEnd ) {
instance.handler.onRequestEnd(null, response);
}
response.end();
}
for ( var i = 0; i < headers.length; i++ ) {
response.writeHead.apply(response, headers[i]);
}
response.writeHead(code, {'Content-Type': mime});
if ( pipeFile ) {
var stream = _fs.createReadStream(pipeFile, {bufferSize: 64 * 1024});
stream.on('end', function() {
_end();
});
stream.pipe(response);
} else {
response.write(data);
_end();
}
}
/**
* Respond with JSON data
*/
function respondJSON(data, response, headers) {
data = JSON.stringify(data);
if ( instance.config.logging ) {
console.log('>>>', 'application/json');
}
respond(data, 'application/json', response, headers);
}
/**
* Respond with a file
*/
function respondFile(path, request, response, jpath) {
var fullPath = jpath ? path : instance.vfs.getRealPath(path, instance.config, request).root;
_fs.exists(fullPath, function(exists) {
if ( exists ) {
var mime = instance.vfs.getMime(fullPath, instance.config);
if ( instance.config.logging ) {
console.log('>>>', mime, path);
}
respond(null, mime, response, null, null, fullPath);
} else {
if ( instance.config.logging ) {
console.log('!!!', '404', fullPath);
}
respond('404 Not Found', null, response, null, 404);
}
});
}
/**
* Handles file requests
*/
function fileGET(path, request, response, arg) {
if ( !arg ) {
if ( instance.config.logging ) {
console.log('===', 'FileGET', path);
}
try {
instance.handler.checkPrivilege(request, response, 'vfs');
} catch ( e ) {
respond(e, 'text/plain', response, null, 500);
}
}
respondFile(unescape(path), request, response, arg);
}
/**
* Handles file uploads
*/
function filePOST(fields, files, request, response) {
try {
instance.handler.checkPrivilege(request, response, 'upload');
} catch ( e ) {
respond(e, 'text/plain', response, null, 500);
}
instance.vfs.upload([
files.upload.path,
files.upload.name,
fields.path,
String(fields.overwrite) === 'true'
], request, function(err, result) {
if ( err ) {
respond(err, 'text/plain', response, null, 500);
} else {
respond(result, 'text/plain', response);
}
}, instance.config);
}
/**
* Handles Core API HTTP Request
*/
function coreAPI(url, path, POST, request, response) {
if ( path.match(/^\/API/) ) {
try {
var data = JSON.parse(POST);
var method = data.method;
var args = data['arguments'] || {};
if ( instance.config.logging ) {
console.log('===', 'CoreAPI', method, args);
}
instance.request(method, args, function(error, result) {
respondJSON({result: result, error: error}, response);
}, request, response);
} catch ( e ) {
console.error('!!! Caught exception', e);
console.warn(e.stack);
respondJSON({result: null, error: '500 Internal Server Error: ' + e}, response);
}
return true;
}
return false;
}
/**
* Handles a HTTP Request
*/
function httpCall(request, response) {
var url = _url.parse(request.url, true),
path = decodeURIComponent(url.pathname),
cookies = new Cookies(request, response);
request.cookies = cookies;
if ( path === '/' ) {
path += 'index.html';
}
if ( instance.config.logging ) {
console.log('<<<', path);
}
if ( instance.handler && instance.handler.onRequestStart ) {
instance.handler.onRequestStart(request, response);
}
if ( request.method === 'POST' ) {
if ( path.match(/^\/FS$/) ) { // File upload
var form = new _multipart.IncomingForm({
uploadDir: instance.config.tmpdir
});
form.parse(request, function(err, fields, files) {
if ( err ) {
if ( instance.config.logging ) {
console.log('>>>', 'ERR', 'Error on form parse', err);
}
} else {
filePOST(fields, files, request, response);
}
});
} else { // API Calls
var body = '';
request.on('data', function(data) {
body += data;
});
request.on('end', function() {
if ( !coreAPI(url, path, body, request, response) ) {
if ( instance.config.logging ) {
console.log('>>>', '404', path);
}
respond('404 Not Found', null, response, [[404, {}]]);
}
});
}
} else { // File reads
if ( path.match(/^\/FS/) ) {
fileGET(path.replace(/^\/FS/, ''), request, response, false);
} else {
fileGET(_path.join(instance.config.distdir, path.replace(/^\//, '')), request, response, true);
}
}
}
/////////////////////////////////////////////////////////////////////////////
// EXPORTS
/////////////////////////////////////////////////////////////////////////////
/**
* Create HTTP server and listen
*
* @param Object setup Configuration (see osjs.js)
*
* @option setup int port Listening port (default=null/auto)
* @option setup String dirname Server running dir (ex: /osjs/src/server/node)
* @option setup String root Installation root directory (ex: /osjs)
* @option setup String dist Build root directory (ex: /osjs/dist)
* @option setup boolean nw NW build (default=false)
* @option setup boolean logging Enable logging (default=true)
*
* @api http.listen
*/
module.exports.listen = function(setup) {
instance = _osjs.init(setup);
server = _http.createServer(httpCall);
if ( setup.logging !== false ) {
console.log(JSON.stringify(instance.config, null, 2));
}
if ( instance.handler && instance.handler.onServerStart ) {
instance.handler.onServerStart(instance.config);
}
server.listen(setup.port || instance.config.port);
};
/**
* Closes the active HTTP server
*
* @param Function cb Callback function
*
* @api http.close
*/
module.exports.close = function(cb) {
cb = cb || function() {};
if ( instance.handler && instance.handler.onServerEnd ) {
instance.handler.onServerEnd(instance.config);
}
if ( server ) {
server.close(cb);
} else {
cb();
}
};
})(
require('osjs'),
require('http'),
require('path'),
require('url'),
require('node-fs-extra'),
require('querystring'),
require('formidable'),
require('cookies')
);
| afang/OS.js-Apps | src/server/node/http.js | JavaScript | bsd-2-clause | 9,042 |
require(['lib/domReady', 'match'], function (domReady, matchClass) {
// Don't let events bubble up
if (Event.halt === undefined) {
// Don't let events bubble up
Event.prototype.halt = function () {
this.stopPropagation();
this.preventDefault();
};
};
// Add toggleClass method similar to jquery
HTMLElement.prototype.toggleClass = function (c1, c2) {
var cl = this.classList;
if (cl.contains(c1)) {
cl.add(c2);
cl.remove(c1);
}
else {
cl.remove(c2);
cl.add(c1);
};
};
domReady(function () {
var inactiveLi = document.querySelectorAll(
'#search > ol > li:not(.active)'
);
var i = 0;
for (i = 0; i < inactiveLi.length; i++) {
inactiveLi[i].addEventListener('click', function (e) {
if (this._match !== undefined) {
if (this._match.open())
e.halt();
}
else {
matchClass.create(this).open();
};
});
};
});
});
| KorAP/Rabbid | dev/js/src/app.js | JavaScript | bsd-2-clause | 946 |
goog.provide('ol.layer.Group');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.math');
goog.require('goog.object');
goog.require('ol.Collection');
goog.require('ol.CollectionEvent');
goog.require('ol.CollectionEventType');
goog.require('ol.Object');
goog.require('ol.ObjectEventType');
goog.require('ol.layer.Base');
goog.require('ol.source.State');
/**
* @enum {string}
*/
ol.layer.GroupProperty = {
LAYERS: 'layers'
};
/**
* @constructor
* @extends {ol.layer.Base}
* @param {olx.layer.GroupOptions=} opt_options Layer options.
* @todo observable layers {ol.Collection} collection of {@link ol.layer} layers
* that are part of this group
* @todo api
*/
ol.layer.Group = function(opt_options) {
var options = goog.isDef(opt_options) ? opt_options : {};
var baseOptions = /** @type {olx.layer.GroupOptions} */
(goog.object.clone(options));
delete baseOptions.layers;
var layers = options.layers;
goog.base(this, baseOptions);
/**
* @private
* @type {Object.<string, goog.events.Key>}
*/
this.listenerKeys_ = null;
goog.events.listen(this,
ol.Object.getChangeEventType(ol.layer.GroupProperty.LAYERS),
this.handleLayersChanged_, false, this);
if (goog.isDef(layers)) {
if (goog.isArray(layers)) {
layers = new ol.Collection(goog.array.clone(layers));
} else {
goog.asserts.assertInstanceof(layers, ol.Collection);
layers = layers;
}
} else {
layers = new ol.Collection();
}
this.setLayers(layers);
};
goog.inherits(ol.layer.Group, ol.layer.Base);
/**
* @private
*/
ol.layer.Group.prototype.handleLayerChange_ = function() {
if (this.getVisible()) {
this.dispatchChangeEvent();
}
};
/**
* @param {goog.events.Event} event Event.
* @private
*/
ol.layer.Group.prototype.handleLayersChanged_ = function(event) {
if (!goog.isNull(this.listenerKeys_)) {
goog.array.forEach(
goog.object.getValues(this.listenerKeys_), goog.events.unlistenByKey);
this.listenerKeys_ = null;
}
var layers = this.getLayers();
if (goog.isDefAndNotNull(layers)) {
this.listenerKeys_ = {
'add': goog.events.listen(layers, ol.CollectionEventType.ADD,
this.handleLayersAdd_, false, this),
'remove': goog.events.listen(layers, ol.CollectionEventType.REMOVE,
this.handleLayersRemove_, false, this)
};
var layersArray = layers.getArray();
var i, ii, layer;
for (i = 0, ii = layersArray.length; i < ii; i++) {
layer = layersArray[i];
this.listenerKeys_[goog.getUid(layer).toString()] =
goog.events.listen(layer,
[ol.ObjectEventType.PROPERTYCHANGE, goog.events.EventType.CHANGE],
this.handleLayerChange_, false, this);
}
}
this.dispatchChangeEvent();
};
/**
* @param {ol.CollectionEvent} collectionEvent Collection event.
* @private
*/
ol.layer.Group.prototype.handleLayersAdd_ = function(collectionEvent) {
var layer = /** @type {ol.layer.Base} */ (collectionEvent.element);
this.listenerKeys_[goog.getUid(layer).toString()] = goog.events.listen(
layer, [ol.ObjectEventType.PROPERTYCHANGE, goog.events.EventType.CHANGE],
this.handleLayerChange_, false, this);
this.dispatchChangeEvent();
};
/**
* @param {ol.CollectionEvent} collectionEvent Collection event.
* @private
*/
ol.layer.Group.prototype.handleLayersRemove_ = function(collectionEvent) {
var layer = /** @type {ol.layer.Base} */ (collectionEvent.element);
var key = goog.getUid(layer).toString();
goog.events.unlistenByKey(this.listenerKeys_[key]);
delete this.listenerKeys_[key];
this.dispatchChangeEvent();
};
/**
* @return {ol.Collection|undefined} Collection of layers.
*/
ol.layer.Group.prototype.getLayers = function() {
return /** @type {ol.Collection|undefined} */ (this.get(
ol.layer.GroupProperty.LAYERS));
};
goog.exportProperty(
ol.layer.Group.prototype,
'getLayers',
ol.layer.Group.prototype.getLayers);
/**
* @param {ol.Collection|undefined} layers Collection of layers.
*/
ol.layer.Group.prototype.setLayers = function(layers) {
this.set(ol.layer.GroupProperty.LAYERS, layers);
};
goog.exportProperty(
ol.layer.Group.prototype,
'setLayers',
ol.layer.Group.prototype.setLayers);
/**
* @inheritDoc
*/
ol.layer.Group.prototype.getLayersArray = function(opt_array) {
var array = (goog.isDef(opt_array)) ? opt_array : [];
this.getLayers().forEach(function(layer) {
layer.getLayersArray(array);
});
return array;
};
/**
* @inheritDoc
*/
ol.layer.Group.prototype.getLayerStatesArray = function(opt_states) {
var states = (goog.isDef(opt_states)) ? opt_states : [];
var pos = states.length;
this.getLayers().forEach(function(layer) {
layer.getLayerStatesArray(states);
});
var ownLayerState = this.getLayerState();
var i, ii, layerState;
for (i = pos, ii = states.length; i < ii; i++) {
layerState = states[i];
layerState.brightness = goog.math.clamp(
layerState.brightness + ownLayerState.brightness, -1, 1);
layerState.contrast *= ownLayerState.contrast;
layerState.hue += ownLayerState.hue;
layerState.opacity *= ownLayerState.opacity;
layerState.saturation *= ownLayerState.saturation;
layerState.visible = layerState.visible && ownLayerState.visible;
layerState.maxResolution = Math.min(
layerState.maxResolution, ownLayerState.maxResolution);
layerState.minResolution = Math.max(
layerState.minResolution, ownLayerState.minResolution);
}
return states;
};
/**
* @inheritDoc
*/
ol.layer.Group.prototype.getSourceState = function() {
return ol.source.State.READY;
};
| jeluard/cljs-ol3js | resources/closure-js/libs/ol-v3.0.0-beta.5/ol/layer/layergroup.js | JavaScript | bsd-2-clause | 5,759 |
/**
* @module ol/style/RegularShape
*/
import {asString} from '../color.js';
import {asColorLike} from '../colorlike.js';
import {createCanvasContext2D} from '../dom.js';
import {CANVAS_LINE_DASH} from '../has.js';
import ImageState from '../ImageState.js';
import {defaultStrokeStyle, defaultFillStyle, defaultLineCap, defaultLineWidth, defaultLineJoin, defaultMiterLimit} from '../render/canvas.js';
import ImageStyle from './Image.js';
/**
* Specify radius for regular polygons, or radius1 and radius2 for stars.
* @typedef {Object} Options
* @property {import("./Fill.js").default} [fill] Fill style.
* @property {number} points Number of points for stars and regular polygons. In case of a polygon, the number of points
* is the number of sides.
* @property {number} [radius] Radius of a regular polygon.
* @property {number} [radius1] Outer radius of a star.
* @property {number} [radius2] Inner radius of a star.
* @property {number} [angle=0] Shape's angle in radians. A value of 0 will have one of the shape's point facing up.
* @property {import("./Stroke.js").default} [stroke] Stroke style.
* @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).
* @property {boolean} [rotateWithView=false] Whether to rotate the shape with the view.
* @property {import("./AtlasManager.js").default} [atlasManager] The atlas manager to use for this symbol. When
* using WebGL it is recommended to use an atlas manager to avoid texture switching. If an atlas manager is given, the
* symbol is added to an atlas. By default no atlas manager is used.
*/
/**
* @typedef {Object} RenderOptions
* @property {import("../colorlike.js").ColorLike} [strokeStyle]
* @property {number} strokeWidth
* @property {number} size
* @property {string} lineCap
* @property {Array<number>} lineDash
* @property {number} lineDashOffset
* @property {string} lineJoin
* @property {number} miterLimit
*/
/**
* @classdesc
* Set regular shape style for vector features. The resulting shape will be
* a regular polygon when `radius` is provided, or a star when `radius1` and
* `radius2` are provided.
* @api
*/
class RegularShape extends ImageStyle {
/**
* @param {Options} options Options.
*/
constructor(options) {
/**
* @type {boolean}
*/
const rotateWithView = options.rotateWithView !== undefined ?
options.rotateWithView : false;
super({
opacity: 1,
rotateWithView: rotateWithView,
rotation: options.rotation !== undefined ? options.rotation : 0,
scale: 1
});
/**
* @private
* @type {Array<string|number>}
*/
this.checksums_ = null;
/**
* @private
* @type {HTMLCanvasElement}
*/
this.canvas_ = null;
/**
* @private
* @type {HTMLCanvasElement}
*/
this.hitDetectionCanvas_ = null;
/**
* @private
* @type {import("./Fill.js").default}
*/
this.fill_ = options.fill !== undefined ? options.fill : null;
/**
* @private
* @type {Array<number>}
*/
this.origin_ = [0, 0];
/**
* @private
* @type {number}
*/
this.points_ = options.points;
/**
* @protected
* @type {number}
*/
this.radius_ = /** @type {number} */ (options.radius !== undefined ?
options.radius : options.radius1);
/**
* @private
* @type {number|undefined}
*/
this.radius2_ = options.radius2;
/**
* @private
* @type {number}
*/
this.angle_ = options.angle !== undefined ? options.angle : 0;
/**
* @private
* @type {import("./Stroke.js").default}
*/
this.stroke_ = options.stroke !== undefined ? options.stroke : null;
/**
* @private
* @type {Array<number>}
*/
this.anchor_ = null;
/**
* @private
* @type {import("../size.js").Size}
*/
this.size_ = null;
/**
* @private
* @type {import("../size.js").Size}
*/
this.imageSize_ = null;
/**
* @private
* @type {import("../size.js").Size}
*/
this.hitDetectionImageSize_ = null;
/**
* @protected
* @type {import("./AtlasManager.js").default|undefined}
*/
this.atlasManager_ = options.atlasManager;
this.render_(this.atlasManager_);
}
/**
* Clones the style. If an atlasmanager was provided to the original style it will be used in the cloned style, too.
* @return {RegularShape} The cloned style.
* @api
*/
clone() {
const style = new RegularShape({
fill: this.getFill() ? this.getFill().clone() : undefined,
points: this.getPoints(),
radius: this.getRadius(),
radius2: this.getRadius2(),
angle: this.getAngle(),
stroke: this.getStroke() ? this.getStroke().clone() : undefined,
rotation: this.getRotation(),
rotateWithView: this.getRotateWithView(),
atlasManager: this.atlasManager_
});
style.setOpacity(this.getOpacity());
style.setScale(this.getScale());
return style;
}
/**
* @inheritDoc
* @api
*/
getAnchor() {
return this.anchor_;
}
/**
* Get the angle used in generating the shape.
* @return {number} Shape's rotation in radians.
* @api
*/
getAngle() {
return this.angle_;
}
/**
* Get the fill style for the shape.
* @return {import("./Fill.js").default} Fill style.
* @api
*/
getFill() {
return this.fill_;
}
/**
* @inheritDoc
*/
getHitDetectionImage(pixelRatio) {
return this.hitDetectionCanvas_;
}
/**
* @inheritDoc
* @api
*/
getImage(pixelRatio) {
return this.canvas_;
}
/**
* @inheritDoc
*/
getImageSize() {
return this.imageSize_;
}
/**
* @inheritDoc
*/
getHitDetectionImageSize() {
return this.hitDetectionImageSize_;
}
/**
* @inheritDoc
*/
getImageState() {
return ImageState.LOADED;
}
/**
* @inheritDoc
* @api
*/
getOrigin() {
return this.origin_;
}
/**
* Get the number of points for generating the shape.
* @return {number} Number of points for stars and regular polygons.
* @api
*/
getPoints() {
return this.points_;
}
/**
* Get the (primary) radius for the shape.
* @return {number} Radius.
* @api
*/
getRadius() {
return this.radius_;
}
/**
* Get the secondary radius for the shape.
* @return {number|undefined} Radius2.
* @api
*/
getRadius2() {
return this.radius2_;
}
/**
* @inheritDoc
* @api
*/
getSize() {
return this.size_;
}
/**
* Get the stroke style for the shape.
* @return {import("./Stroke.js").default} Stroke style.
* @api
*/
getStroke() {
return this.stroke_;
}
/**
* @inheritDoc
*/
listenImageChange(listener, thisArg) {
return undefined;
}
/**
* @inheritDoc
*/
load() {}
/**
* @inheritDoc
*/
unlistenImageChange(listener, thisArg) {}
/**
* @protected
* @param {import("./AtlasManager.js").default|undefined} atlasManager An atlas manager.
*/
render_(atlasManager) {
let imageSize;
let lineCap = '';
let lineJoin = '';
let miterLimit = 0;
let lineDash = null;
let lineDashOffset = 0;
let strokeStyle;
let strokeWidth = 0;
if (this.stroke_) {
strokeStyle = this.stroke_.getColor();
if (strokeStyle === null) {
strokeStyle = defaultStrokeStyle;
}
strokeStyle = asColorLike(strokeStyle);
strokeWidth = this.stroke_.getWidth();
if (strokeWidth === undefined) {
strokeWidth = defaultLineWidth;
}
lineDash = this.stroke_.getLineDash();
lineDashOffset = this.stroke_.getLineDashOffset();
if (!CANVAS_LINE_DASH) {
lineDash = null;
lineDashOffset = 0;
}
lineJoin = this.stroke_.getLineJoin();
if (lineJoin === undefined) {
lineJoin = defaultLineJoin;
}
lineCap = this.stroke_.getLineCap();
if (lineCap === undefined) {
lineCap = defaultLineCap;
}
miterLimit = this.stroke_.getMiterLimit();
if (miterLimit === undefined) {
miterLimit = defaultMiterLimit;
}
}
let size = 2 * (this.radius_ + strokeWidth) + 1;
/** @type {RenderOptions} */
const renderOptions = {
strokeStyle: strokeStyle,
strokeWidth: strokeWidth,
size: size,
lineCap: lineCap,
lineDash: lineDash,
lineDashOffset: lineDashOffset,
lineJoin: lineJoin,
miterLimit: miterLimit
};
if (atlasManager === undefined) {
// no atlas manager is used, create a new canvas
const context = createCanvasContext2D(size, size);
this.canvas_ = context.canvas;
// canvas.width and height are rounded to the closest integer
size = this.canvas_.width;
imageSize = size;
this.draw_(renderOptions, context, 0, 0);
this.createHitDetectionCanvas_(renderOptions);
} else {
// an atlas manager is used, add the symbol to an atlas
size = Math.round(size);
const hasCustomHitDetectionImage = !this.fill_;
let renderHitDetectionCallback;
if (hasCustomHitDetectionImage) {
// render the hit-detection image into a separate atlas image
renderHitDetectionCallback =
this.drawHitDetectionCanvas_.bind(this, renderOptions);
}
const id = this.getChecksum();
const info = atlasManager.add(
id, size, size, this.draw_.bind(this, renderOptions),
renderHitDetectionCallback);
this.canvas_ = info.image;
this.origin_ = [info.offsetX, info.offsetY];
imageSize = info.image.width;
if (hasCustomHitDetectionImage) {
this.hitDetectionCanvas_ = info.hitImage;
this.hitDetectionImageSize_ =
[info.hitImage.width, info.hitImage.height];
} else {
this.hitDetectionCanvas_ = this.canvas_;
this.hitDetectionImageSize_ = [imageSize, imageSize];
}
}
this.anchor_ = [size / 2, size / 2];
this.size_ = [size, size];
this.imageSize_ = [imageSize, imageSize];
}
/**
* @private
* @param {RenderOptions} renderOptions Render options.
* @param {CanvasRenderingContext2D} context The rendering context.
* @param {number} x The origin for the symbol (x).
* @param {number} y The origin for the symbol (y).
*/
draw_(renderOptions, context, x, y) {
let i, angle0, radiusC;
// reset transform
context.setTransform(1, 0, 0, 1, 0, 0);
// then move to (x, y)
context.translate(x, y);
context.beginPath();
let points = this.points_;
if (points === Infinity) {
context.arc(
renderOptions.size / 2, renderOptions.size / 2,
this.radius_, 0, 2 * Math.PI, true);
} else {
const radius2 = (this.radius2_ !== undefined) ? this.radius2_
: this.radius_;
if (radius2 !== this.radius_) {
points = 2 * points;
}
for (i = 0; i <= points; i++) {
angle0 = i * 2 * Math.PI / points - Math.PI / 2 + this.angle_;
radiusC = i % 2 === 0 ? this.radius_ : radius2;
context.lineTo(renderOptions.size / 2 + radiusC * Math.cos(angle0),
renderOptions.size / 2 + radiusC * Math.sin(angle0));
}
}
if (this.fill_) {
let color = this.fill_.getColor();
if (color === null) {
color = defaultFillStyle;
}
context.fillStyle = asColorLike(color);
context.fill();
}
if (this.stroke_) {
context.strokeStyle = renderOptions.strokeStyle;
context.lineWidth = renderOptions.strokeWidth;
if (renderOptions.lineDash) {
context.setLineDash(renderOptions.lineDash);
context.lineDashOffset = renderOptions.lineDashOffset;
}
context.lineCap = /** @type {CanvasLineCap} */ (renderOptions.lineCap);
context.lineJoin = /** @type {CanvasLineJoin} */ (renderOptions.lineJoin);
context.miterLimit = renderOptions.miterLimit;
context.stroke();
}
context.closePath();
}
/**
* @private
* @param {RenderOptions} renderOptions Render options.
*/
createHitDetectionCanvas_(renderOptions) {
this.hitDetectionImageSize_ = [renderOptions.size, renderOptions.size];
if (this.fill_) {
this.hitDetectionCanvas_ = this.canvas_;
return;
}
// if no fill style is set, create an extra hit-detection image with a
// default fill style
const context = createCanvasContext2D(renderOptions.size, renderOptions.size);
this.hitDetectionCanvas_ = context.canvas;
this.drawHitDetectionCanvas_(renderOptions, context, 0, 0);
}
/**
* @private
* @param {RenderOptions} renderOptions Render options.
* @param {CanvasRenderingContext2D} context The context.
* @param {number} x The origin for the symbol (x).
* @param {number} y The origin for the symbol (y).
*/
drawHitDetectionCanvas_(renderOptions, context, x, y) {
// reset transform
context.setTransform(1, 0, 0, 1, 0, 0);
// then move to (x, y)
context.translate(x, y);
context.beginPath();
let points = this.points_;
if (points === Infinity) {
context.arc(
renderOptions.size / 2, renderOptions.size / 2,
this.radius_, 0, 2 * Math.PI, true);
} else {
const radius2 = (this.radius2_ !== undefined) ? this.radius2_
: this.radius_;
if (radius2 !== this.radius_) {
points = 2 * points;
}
let i, radiusC, angle0;
for (i = 0; i <= points; i++) {
angle0 = i * 2 * Math.PI / points - Math.PI / 2 + this.angle_;
radiusC = i % 2 === 0 ? this.radius_ : radius2;
context.lineTo(renderOptions.size / 2 + radiusC * Math.cos(angle0),
renderOptions.size / 2 + radiusC * Math.sin(angle0));
}
}
context.fillStyle = asString(defaultFillStyle);
context.fill();
if (this.stroke_) {
context.strokeStyle = renderOptions.strokeStyle;
context.lineWidth = renderOptions.strokeWidth;
if (renderOptions.lineDash) {
context.setLineDash(renderOptions.lineDash);
context.lineDashOffset = renderOptions.lineDashOffset;
}
context.stroke();
}
context.closePath();
}
/**
* @return {string} The checksum.
*/
getChecksum() {
const strokeChecksum = this.stroke_ ?
this.stroke_.getChecksum() : '-';
const fillChecksum = this.fill_ ?
this.fill_.getChecksum() : '-';
const recalculate = !this.checksums_ ||
(strokeChecksum != this.checksums_[1] ||
fillChecksum != this.checksums_[2] ||
this.radius_ != this.checksums_[3] ||
this.radius2_ != this.checksums_[4] ||
this.angle_ != this.checksums_[5] ||
this.points_ != this.checksums_[6]);
if (recalculate) {
const checksum = 'r' + strokeChecksum + fillChecksum +
(this.radius_ !== undefined ? this.radius_.toString() : '-') +
(this.radius2_ !== undefined ? this.radius2_.toString() : '-') +
(this.angle_ !== undefined ? this.angle_.toString() : '-') +
(this.points_ !== undefined ? this.points_.toString() : '-');
this.checksums_ = [checksum, strokeChecksum, fillChecksum,
this.radius_, this.radius2_, this.angle_, this.points_];
}
return /** @type {string} */ (this.checksums_[0]);
}
}
export default RegularShape;
| mzur/ol3 | src/ol/style/RegularShape.js | JavaScript | bsd-2-clause | 15,429 |
// Copyright (C) 2015 Mike Pennisi. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-array.prototype-@@unscopables
description: >
Initial value of `Symbol.unscopables` property
info: |
22.1.3.32 Array.prototype [ @@unscopables ]
1. Let unscopableList be ObjectCreate(null).
2. Perform CreateDataProperty(unscopableList, "copyWithin", true).
3. Perform CreateDataProperty(unscopableList, "entries", true).
4. Perform CreateDataProperty(unscopableList, "fill", true).
5. Perform CreateDataProperty(unscopableList, "find", true).
6. Perform CreateDataProperty(unscopableList, "findIndex", true).
7. Perform CreateDataProperty(unscopableList, "includes", true).
8. Perform CreateDataProperty(unscopableList, "keys", true).
9. Perform CreateDataProperty(unscopableList, "values", true).
10. Assert: Each of the above calls will return true.
11. Return unscopableList.
includes: [propertyHelper.js]
features: [Symbol.unscopables]
---*/
var unscopables = Array.prototype[Symbol.unscopables];
assert.sameValue(Object.getPrototypeOf(unscopables), null);
assert.sameValue(unscopables.copyWithin, true, '`copyWithin` property value');
verifyEnumerable(unscopables, 'copyWithin');
verifyWritable(unscopables, 'copyWithin');
verifyConfigurable(unscopables, 'copyWithin');
assert.sameValue(unscopables.entries, true, '`entries` property value');
verifyEnumerable(unscopables, 'entries');
verifyWritable(unscopables, 'entries');
verifyConfigurable(unscopables, 'entries');
assert.sameValue(unscopables.fill, true, '`fill` property value');
verifyEnumerable(unscopables, 'fill');
verifyWritable(unscopables, 'fill');
verifyConfigurable(unscopables, 'fill');
assert.sameValue(unscopables.find, true, '`find` property value');
verifyEnumerable(unscopables, 'find');
verifyWritable(unscopables, 'find');
verifyConfigurable(unscopables, 'find');
assert.sameValue(unscopables.findIndex, true, '`findIndex` property value');
verifyEnumerable(unscopables, 'findIndex');
verifyWritable(unscopables, 'findIndex');
verifyConfigurable(unscopables, 'findIndex');
assert.sameValue(unscopables.includes, true, '`includes` property value');
verifyEnumerable(unscopables, 'includes');
verifyWritable(unscopables, 'includes');
verifyConfigurable(unscopables, 'includes');
assert.sameValue(unscopables.keys, true, '`keys` property value');
verifyEnumerable(unscopables, 'keys');
verifyWritable(unscopables, 'keys');
verifyConfigurable(unscopables, 'keys');
assert.sameValue(unscopables.values, true, '`values` property value');
verifyEnumerable(unscopables, 'values');
verifyWritable(unscopables, 'values');
verifyConfigurable(unscopables, 'values');
| sebastienros/jint | Jint.Tests.Test262/test/built-ins/Array/prototype/Symbol.unscopables/value.js | JavaScript | bsd-2-clause | 2,739 |
#!/usr/bin/env node
function main() {
if (process.env.SUPPRESS_SUPPORT || process.env.OPENCOLLECTIVE_HIDE) {
return;
}
try {
const Configstore = require('configstore');
const pkg = require(__dirname + '/../package.json');
const now = Date.now();
var week = 1000 * 60 * 60 * 24 * 7;
// create a Configstore instance with an unique ID e.g.
// Package name and optionally some default values
const conf = new Configstore(pkg.name);
const last = conf.get('lastCheck');
if (!last || now - week > last) {
console.log('\u001b[32mLove nodemon? You can now support the project via the open collective:\u001b[22m\u001b[39m\n > \u001b[96m\u001b[1mhttps://opencollective.com/nodemon/donate\u001b[0m\n');
conf.set('lastCheck', now);
}
} catch (e) {
console.log('\u001b[32mLove nodemon? You can now support the project via the open collective:\u001b[22m\u001b[39m\n > \u001b[96m\u001b[1mhttps://opencollective.com/nodemon/donate\u001b[0m\n');
}
}
main();
| nihospr01/OpenSpeechPlatform-UCSD | Sources/ewsnodejs-server/node_modules/nodemon/bin/postinstall.js | JavaScript | bsd-2-clause | 1,017 |
import isLength from './isLength';
import toObject from './toObject';
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
var length = collection ? collection.length : 0;
if (!isLength(length)) {
return eachFunc(collection, iteratee);
}
var index = fromRight ? length : -1,
iterable = toObject(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
export default createBaseEach;
| wushuyi/remoteMultiSketchpad | frontend/assets/libs/lodash-3.6.0-es/internal/createBaseEach.js | JavaScript | bsd-2-clause | 861 |
exports.testFuncPointerFailed = function() {
console.log("[JS]: Test function pointer Start!!!");
var IOLIB = (typeof require === 'function') ? require('../../../../'): this.IOLIB;
var io = new IOLIB.IO({
log: true,
//rpc: true,
port: 2000,
hostname: 'localhost',
quickInit: false
});
var cb_v_r_intp = function(a) {
io.fail_func_v_r_intp(a);
}
ret = io.fail_func_int_r_int_fp1(2, cb_v_r_intp);
ga = io.getFail_gafpV8();
if (ret != 2 || ga != 26)
throw Error("Failed!!!")
console.log("[JS]: Test function pointer Passed!!!");
}
| ilc-opensource/io-js | utils/autogen/testSuite/test_failed/funcPoint_failed.js | JavaScript | bsd-3-clause | 582 |
/*
* Copyright 2014, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
// Start the main app logic.
requirejs([
'../node_modules/happyfuntimes/dist/hft',
'../node_modules/hft-sample-ui/dist/sample-ui',
'../node_modules/hft-game-utils/dist/game-utils',
], function(
hft,
sampleUI,
gameUtils) {
var GameClient = hft.GameClient;
var CommonUI = sampleUI.commonUI;
var Input = sampleUI.input;
var Misc = sampleUI.misc;
var MobileHacks = sampleUI.mobileHacks;
var Touch = sampleUI.touch;
var globals = {
debug: false,
};
Misc.applyUrlSettings(globals);
MobileHacks.fixHeightHack();
var score = 0;
var statusElem = document.getElementById("gamestatus");
var inputElem = document.getElementById("inputarea");
var colorElem = document.getElementById("display");
var client = new GameClient();
CommonUI.setupStandardControllerUI(client, globals);
CommonUI.askForNameOnce(); // ask for the user's name if not set
CommonUI.showMenu(true); // shows the gear menu
var randInt = function(range) {
return Math.floor(Math.random() * range);
};
// Sends a move command to the game.
//
// This will generate a 'move' event in the corresponding
// NetPlayer object in the game.
var sendMoveCmd = function(position, target) {
client.sendCmd('move', {
x: position.x / target.clientWidth,
y: position.y / target.clientHeight,
});
};
// Pick a random color
var color = 'rgb(' + randInt(256) + "," + randInt(256) + "," + randInt(256) + ")";
// Send the color to the game.
//
// This will generate a 'color' event in the corresponding
// NetPlayer object in the game.
client.sendCmd('color', {
color: color,
});
colorElem.style.backgroundColor = color;
// Send a message to the game when the screen is touched
inputElem.addEventListener('pointermove', function(event) {
var position = Input.getRelativeCoordinates(event.target, event);
sendMoveCmd(position, event.target);
event.preventDefault();
});
// Update our score when the game tells us.
client.addEventListener('scored', function(cmd) {
score += cmd.points;
statusElem.innerHTML = "You scored: " + cmd.points + " total: " + score;
});
});
| greggman/hft-simple | scripts/controller.js | JavaScript | bsd-3-clause | 3,761 |
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
function CoayoloDAO(){
if (false === (this instanceof CoayoloDAO)) {
console.log('Warning: CoayoloDAO constructor called without "new" operator');
return new CoayoloDAO();
}
//fix
this.Alumno = new Schema({
//hay dos campos que pueden usarse como id_alumno con cual nos vamos aquedar
id_alumno : Number,
id_avatar : Number,
matricula : String,
email : String,
pass : String,
nombre_usu : String,
id_avatar : Number,
sexo : String,
pass : String,
fecha_nacimiento : String,
escuela : [],
casa : [],
misiones : []
});
/*
db.alumnos.insert({
id_alumno : 0, id_avatar : 0, matricula : 'whatever', id_avatar : 0,nombre_usu : 'none', sexo : 'hombre', pass : 'none',
id_casa : 0, fecha_nacimiento : new Date(), area : [{ id_area : 0, nombre_area : 'hola'}], escuela : [{id_escuela : 0, nombre_escuela : 'ctin'}],
misiones : [{id_mision : 0, nombre_mision : 'marte', avance : 0, fecha_ini_mision : new Date()}]
})
*/
this.Casa = new Schema({
id_casa : Number,
nombre_casa : String,
id_administrador : Number
});
this.Escuela = new Schema({
id_escuela : Number,
nombre_esc : String
});
this.Mision = new Schema({
id_mision : Number,
nombre_mision : String,
avance : Number,
fecha_ini_mision : {type : Date, default : Date.now}
});
////////////////////////////////
//fix
this.Avatar = new Schema({
id_avatar : Number,
url_avatar : String,
alumnos_id_alumnos : Number,
piel : [],
cabello : []
});
this.Cabello = new Schema({
id_cabello : Number,
url_cabello : String
});
/*
this.Piel = new Schema({
id_piel : Number,
url_piel : String
});
*/
this.Top = new Schema({
id_top = Number,
url_top = String
})
this.Bottom = new Schema({
id_bottom = Number,
url bottom = Stirng
});
/*
db.avatar.insert({
id_avatar : 0, url_avatar : '/src/photo.jpg', alumno_id : 0, piel : [{id_piel : 0, url_piel : '/src/piel.jpg'}], cabello : [{id_cabello : 0, url_cabello : '/src/cabello.jpg'}]
});
Ejemplos de queries: encontrar avatar donde id_avatar sea mayor o igual a 1
db.avatar.find({id_avatar : {$gte : 1}});
Ejemplos de queries: encontrar avatar donde alumno_id sea mayor o igual a 10 y no projecta el id_avatar
db.avatar.find({alumno_id : {$gte : 10}}, {id_avatar : 0});
*/
this.Administrador = new Schema({
id_admin : Number,
nombre_admin : String,
pass_admin : String
});
//Son como las misiones
this.Experimento = new Schema({
id_experimento : Number,
descripcion_experimento : String,
id_experimento : Number
});
/*
db.casa.insert({
id_casa : 0, nombre_casa : 'Griffindor', administrador : [{id_administrador : 0, nombre_administrador : 'vatslavds', pass_admin : 'Hola pass'}],
})
*/
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
this.hcAll = new Schema({
phc : [],
rhc : []
});
this.gralAll = new Schema({
pgral : [],
rgral : []
});
this.Respuestashc = new Schema({
id_respuestashc : Number,
texto_resp_hc : String,
f_v_hc : Boolean,
preghc_id_preghc : Number
});
this.Preghc = new Schema({
id_preghc : Number,
descripcion_hc : String,
id_mision : Number,
id_casa : Number
});
this.Preggral = new Schema({
id_preggral : Number,
descripcion_gral : String,
id_casa : Number,
id_mision : Number
});
this.Respuestasgral = new Schema({
id_respuestasgral : Number,
texto_resp_gral : String,
f_v_gral : Boolean,
id_preggral : Number
});
/*
Ejemplo de inserccinnn de datos
db.preguntashc.insert({id_preghc : 0, descripcion_hc : "A los shumies les gustan las manzanas", id_misinnn : 0, id_casa : 0});
db.respuestashc.insert({id_respuestashc : 0, texto_resp_hc : "Tienes raznnn, a los shumies ls gustan las manzanas", id_misinnn : 0, id_casa : 0});
db.preguntasgral.insert({id_preggral : 0, descripcion_gral : "Mozart compositor alemdb.respuestasgral.insert({id_respuestasgral : 0, texto_resp_gral : "Cierto... Mozart es alem*/
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
this.Publicacion = new Schema({
id_publicacion : Number,
fecha_publicacion : {type : Date, default : Date.now},
texto_publicacion : String,
id_alumnos : Number
});
/*
db.publicacion.insert({
fecha_publicacion : new Date(), id_publicacion : 0, texto_publicacion : 'Hola mundo de ninos', no_arias : 1, id_alumno : 0
});
*/
this.Notificaciones = new Schema({
id_notificacion : Number,
texto_notificacion : String,
id_alumnos: Number,
id_publicacion : Number
});
/*
db.notificaciones.insert({
id_notificacion : 0, texto_notificacion : 'tal persona publico', id_alumnos : 0, id_publicacion : 0
});
*/
this.Rol = new Schema({
//Moderador social, experimentos, admin
id_rol : Number,
nombre : String,
});
//contiene el test de ingreso alas casas
this.Test = new Schema({
id_alumno : Number,
});
this.Arias = new Schema({
id_arias : Number,
num_arias : Number,
//alumnos : [Alumnos]
});
}
module.exports = CoayoloDAO;
/*
1.- AP sombrero
2.- AP registro
3.- AP avatar
4.-
*/
| VUH-Tec/cuayolo-db | CoayoloDAO.js | JavaScript | bsd-3-clause | 5,441 |
//>>built
define("dojo/cldr/nls/zh-hant/chinese",{"dateFormatItem-GyMMM":"U\u5e74MMM","dateFormat-medium":"U\u5e74MMMd\u65e5","dateFormatItem-yMd":"U\u5e74M\u6708d\u65e5","dateFormatItem-MMMEd":"MMMd\u65e5E","dateFormatItem-MEd":"M/dE","dateFormatItem-yyyyMMM":"U\u5e74MMM","dateFormatItem-GyMMMd":"U\u5e74MMMd\u65e5","dateFormatItem-y":"U\u5e74","dateFormatItem-Md":"M/d","dateFormatItem-yyyyQQQQ":"U\u5e74QQQQ","months-standAlone-narrow":"\u6b63 \u4e8c \u4e09 \u56db \u4e94 \u516d \u4e03 \u516b \u4e5d \u5341 \u5341\u4e00 \u5341\u4e8c".split(" "),
"dateFormatItem-GyMMMEd":"U\u5e74MMMd\u65e5E","dateFormatItem-M":"MMM","dateFormatItem-yyyyMMMEd":"U\u5e74MMMd\u65e5E","dateFormatItem-yyyyMEd":"U\u5e74M\u6708d\u65e5\uff0cE","dateFormatItem-yyyy":"U\u5e74","dateFormat-long":"U\u5e74MMMd\u65e5","dateFormatItem-yyyyQQQ":"U\u5e74QQQQ","dateFormat-short":"U/M/d","months-format-wide":"\u6b63\u6708 \u4e8c\u6708 \u4e09\u6708 \u56db\u6708 \u4e94\u6708 \u516d\u6708 \u4e03\u6708 \u516b\u6708 \u4e5d\u6708 \u5341\u6708 \u5341\u4e00\u6708 \u5341\u4e8c\u6708".split(" "),
"dateFormatItem-Gy":"U\u5e74","dateFormatItem-d":"d\u65e5","dateFormatItem-yyyyMMMd":"U\u5e74MMMd\u65e5","dateFormatItem-yyyyM":"U\u5e74M\u6708","dateFormat-full":"U\u5e74MMMd\u65e5EEEE","dateFormatItem-MMMd":"MMMd\u65e5","dateFormatItem-yyyyMd":"U\u5e74M\u6708d\u65e5","dateFormatItem-Ed":"d\u65e5E"});
//@ sourceMappingURL=chinese.js.map | xblox/control-freak | Code/client/src/xfile/dojo/cldr/nls/zh-hant/chinese.js | JavaScript | bsd-3-clause | 1,403 |
var classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d =
[
[ "Function2D", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a5d1f29ecd5a972b2b774b34c0c73567f", null ],
[ "getHeight", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a0967402a3ebb011faa4ea231857687ea", null ],
[ "getWidth", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a43117cf81c33211a41e0f67f6e51f6ae", null ],
[ "value", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a41ea396f31047c219a41fbc34ce83d9d", null ],
[ "function", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a96c4a66aa532e87fd212e36ec5e66800", null ],
[ "fxi", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a2369979613653a0c43ac90f18acb204b", null ],
[ "width", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a54cb3873835476e031f94914e6fa1291", null ]
]; | DweebsUnited/CodeMonkey | resources/hemesh/ref/html/classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.js | JavaScript | bsd-3-clause | 949 |
$(document).ready(function() {
Drupal.dupe.clearDOB();
});
Drupal.dupe = {};
Drupal.dupe.clearDOB = function() {
y = $("#edit-profile-dob-year").val();
var years = '';
var d = new Date();
var max_year = d.getFullYear() - 18;
for (i = 1900; i <= max_year; i++) years += '<option value="' + i + '">' + i + '</option>';
$("#edit-profile-dob-year").html(years);
if (y > max_year) y = max_year;
$("#edit-profile-dob-year").val(y);
}
Drupal.dupe.stepOne = function() {
$("#user-register div fieldset:eq(0)").show();
$("#user-register div fieldset:eq(1)").show();
$("#user-register div fieldset:eq(2)").show();
$("#edit-submit").val("Continue");
};
Drupal.dupe.stepTwo = function() {
//$("#user-register div fieldset:eq(2)").slideDown();
};
Drupal.dupe.cancel = function() {
window.location = '';
}
Drupal.dupe.clearErrors = function() {
$("#user-register div fieldset input").removeClass('error');
};
Drupal.dupe.dupeUserYes = function() {
$("#user-register").append('<input type="hidden" name="i_am_dupe" value="1">');
$("#user-register").submit();
};
Drupal.dupe.dupeUserNo = function() {
$("#user-register").append('<input type="hidden" name="i_am_dupe" value="0">');
$("#user-register").submit();
};
| NCIP/edct-collector | collector-CMS/sites/all/modules/custom/dupe/dupe.js | JavaScript | bsd-3-clause | 1,290 |
$().ready(function() {
$("a[rel^='prettyPhoto']").prettyPhoto();
}); | Freecer/freecer.net | themes/bootlance/js/js.js | JavaScript | bsd-3-clause | 73 |
/*
* Toady
* Copyright 2013 Tom Frost
*/
// Dependencies
var fs = require('fs'),
config = require('config'),
objUtil = require('../util/Object'),
env = process.env.NODE_ENV || 'default';
const CONFIG_PATH = __dirname + "/../../config/" + env + "-mod_{mod}.json";
const CONFIG_PREFIX = 'mod_';
/**
* Gets a path to save a config file specific to a mod.
*
* @param {String} modId The mod ID to associate with the file
* @returns {String} A path appropriate for a config file for this mod ID
*/
function getPath(modId) {
return CONFIG_PATH.replace('{mod}', modId);
}
/**
* Gets a closure that will JSONify any enumerable properties on 'this' and
* save it to a file unique to the given modId when called.
*
* @param {String} modId The modId for which to generate the closure. This
* determines the filename to which the JSON will be saved.
* @returns {Function} A closure which, when called, will save the enumerable
* local properties of 'this' as JSON to a file. Arguments are:
* - {Array} OPTIONAL: An array of top-level properties to save. If
* omitted, every enumerable property will be saved.
* - {Function} OPTIONAL: A callback function to be executed when
* complete. Arguments:
* - {Error} If an error occurred while saving the file.
*/
var getSaveFunc = function(modId) {
return function(props, cb) {
var serial = this,
self = this;
if (typeof props == 'function') {
cb = props;
props = null;
}
if (props) {
serial = {};
props.forEach(function(key) {
if (self.hasOwnProperty(key))
serial[key] = self[key];
});
}
fs.writeFile(getPath(modId), JSON.stringify(serial, null, '\t'), cb);
};
};
/**
* Gets an object containing configuration values for a given mod, as well
* as a non-enumerable non-writable function called "save" that will persist
* any runtime changes to this config to a file.
*
* The configuration object is created in the following fashion:
* 1: Start with any properties passed in with the 'defaults' argument.
* Note that, when writing a Toady mod, this will be whatever has
* been set to module.exports.configDefault (if anything)
* 2: Deep-merge that with any values set in the mod_MODID section of the
* default.yaml file (or, for multiple server configs, the SERVER.yaml
* file). Conflicting properties will be overwritten.
* 3: Deep-merge that with any properties that have been set using
* config.save() (where 'config' is the object returned in the
* callback of this function). Conflicting properties will be
* overridden
*
* Using the returned config object is very straightforward. Just add whatever
* you like:
*
* config.foo = "bar";
* config.hello = {world: "!"};
*
* and save it!
*
* config.save();
* // OR:
* config.save(function(err) {
* if (err) console.log(err);
* else console.log('Saved!');
* }
* // OR:
* config.save([prop1, prop2, prop4]);
*
* Anything saved will still exist when the bot is restarted or the module
* is reloaded, thanks to step 3 above.
*
* Note that calling this function consecutive times with the same
* modId/defaults will NOT return the same config object, and is not an
* appropriate method for changing the config for a mod from a different mod.
* If that functionality is necessary, it's strongly recommended to access the
* 'config' property of a mod to read its values, but change those values only
* with the Config mod's setConfig() function.
*
* In the Toady framework, the config object returned by this function is
* passed directly to each mod when the mod is loaded.
*
* @param {String} modId The mod ID whose configuration should be loaded
* @param {Object|null} defaults An object containing default properties
* to be set if neither the bot config or the mod config file has
* those properties set.
* @param {Function} cb A callback function to be executed on completion.
* Arguments provided are:
* - {Error} An error object, if an error occurred
* - {Object} An object containing all this mod's config properties,
* as well as a save([cb]) function to save any future changes.
*/
function getConfig(modId, defaults, cb) {
var conf = objUtil.deepMerge(defaults || {},
config[CONFIG_PREFIX + modId] || {});
getModConfigFile(modId, function(err, modFile) {
conf = objUtil.deepMerge(conf, modFile);
Object.defineProperty(conf, 'save', {
value: getSaveFunc(modId).bind(conf)
});
cb(null, conf);
});
}
/**
* Gets the contents of the mod's JSON-formatted config file, parses it, and
* returns it in a callback. If the config file does not (yet) exist, an
* empty object will be passed back instead.
*
* Note that, unlike {@link #getConfig}, the object produced by this function
* will NOT be merged from any other config source and will NOT contain a
* save() function to persist changes. The contents of the mod config file
* will be only what the mod itself was responsible for saving manually.
*
* @param {String} modId The ID of the mod whose file should be loaded
* @param {Function} cb A callback function to be executed on completion. Args:
* - {Error} An error object, if an error occurred. Most likely errors
* include issues reading the file (excepting the file not existing)
* and inability to parse the file's JSON.
* - {Object} The parsed config object stored in the file
*/
function getModConfigFile(modId, cb) {
fs.readFile(getPath(modId), function(err, json) {
if (err && err.code != 'ENOENT')
cb(err);
else {
var success = true,
savedConf = {};
if (json) {
try {
savedConf = JSON.parse(json);
}
catch (e) {
success = false;
cb(e);
}
}
if (success)
cb(null, savedConf || {});
}
});
}
module.exports = {
CONFIG_PATH: CONFIG_PATH,
CONFIG_PREFIX: CONFIG_PREFIX,
getConfig: getConfig,
getModConfigFile: getModConfigFile
};
| TomFrost/Toady | app/modmanager/ModConfig.js | JavaScript | bsd-3-clause | 6,115 |
(function(){
var routineServices = angular.module('routineApp.routineServices', []);
var domain = 'http://127.0.0.1:8000/';
routineServices.factory("RoutineService", ['$http', function($http){
var routine = {};
routine.getRoutines = function() {
return $http.get(domain + 'routines/routines/');
};
routine.getRoutine = function(routineId) {
return $http.get(domain + 'routines/routines/' + routineId + '/');
};
routine.createRoutine = function(routineJson) {
return $http.post(domain + 'routines/routines/', routineJson);
};
routine.editRoutine = function(routineJson, routineId) {
return $http.put(domain + 'routines/routines/' + routineId +'/', routineJson);
};
routine.deleteRoutine = function(routineId) {
return $http.delete(domain + 'routines/routines/' + routineId + '/');
};
routine.getExercises = function(routineId) {
return $http.get(domain + 'routines/exercises/', {
params: {
routineId: routineId
}
});
}
routine.createExercises = function(exercisesJson) {
return $http.post(domain + 'routines/exercises/create-many/', exercisesJson);
};
routine.createExercise = function(exerciseJson) {
return $http.post(domain + 'routines/exercises/', exerciseJson);
};
routine.editExercise = function(exerciseJson, exerciseId) {
return $http.put(domain + 'routines/exercises/' + exerciseId + '/', exerciseJson);
};
routine.deleteExercise = function(exerciseId) {
return $http.delete(domain + 'routines/exercises/' + exerciseId + '/');
};
return routine;
}]);
})();
| Kayra/Thunder | client/js/routines/routineServices.js | JavaScript | bsd-3-clause | 1,858 |
jQuery(document).ready(function(){
module("TiddlyWiki core");
test("RGB tests", function() {
expect(4);
var actual = new RGB(1,0,1).toString();
var expected = "#ff00ff";
ok(actual==expected,'RGB(1,0,1) is the same as #ff00ff');
actual = new RGB("#f00").toString();
expected = "#ff0000";
ok(actual==expected,'#ff0000 is the same as #f00');
actual = new RGB("#123").toString();
console.log("actual",actual);
expected = "#112233";
ok(actual==expected,'#112233 is the same as #123');
actual = new RGB("#abc").toString();
console.log("actual",actual);
expected = "#aabbcc";
ok(actual==expected,'#aabbcc is the same as #abc');
actual = new RGB("#123456").toString();
expected = "#123456";
ok(actual==expected,'#123456 is the same as #123456');
actual = new RGB("rgb(0,255,0)").toString();
expected = "#00ff00";
ok(actual==expected,'RGB object created from rgb value > toString method gives hex');
actual = new RGB("rgb(120,0,0)").mix(new RGB("#00ff00"),0.5).toString();
//120 + (0 - 120) *0.5 and 0 + (255-0) * 0.5
expected = new RGB("rgb(60,127,0)").toString();
ok(actual==expected,'RGB mix function proportion 0.5');
});
});
| TeravoxelTwoPhotonTomography/nd | doc/node_modules/tiddlywiki/editions/tw2/source/tiddlywiki/test/js/RGB.js | JavaScript | bsd-3-clause | 1,187 |
Subsets and Splits