max_stars_repo_path
stringlengths
3
961
max_stars_repo_name
stringlengths
5
122
max_stars_count
int64
0
224k
id
stringlengths
1
8
content
stringlengths
2
1.07M
score
float64
-0.95
3.88
int_score
int64
0
4
hispanoFail/node_modules/ionic-native/dist/esm/plugins/filepath.js
Relabtive/hispanoFail
7
815
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import { Plugin, Cordova } from './plugin'; /** * @name FilePath * @description * * This plugin allows you to resolve the native filesystem path for Android content URIs and is based on code in the aFileChooser library. * * @usage * ``` * import {FilePath} from 'ionic-native'; * * FilePath.resolveNativePath(path) * .then(filePath => console.log(filePath); * .catch(err => console.log(err); * * ``` */ export var FilePath = (function () { function FilePath() { } /** * Resolve native path for given content URL/path. * @param {String} path Content URL/path. * @returns {Promise<string>} */ FilePath.resolveNativePath = function (path) { return; }; __decorate([ Cordova() ], FilePath, "resolveNativePath", null); FilePath = __decorate([ Plugin({ pluginName: 'FilePath', plugin: 'cordova-plugin-filepath', pluginRef: 'window.FilePath', repo: 'https://github.com/hiddentao/cordova-plugin-filepath', platforms: ['Android'] }) ], FilePath); return FilePath; }()); //# sourceMappingURL=filepath.js.map
1.734375
2
node_modules/@tensorflow/tfjs-core/dist/test_util.js
ofuen/TensorFlowJSExample
2
823
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var environment_1 = require("./environment"); var tensor_1 = require("./tensor"); var util = require("./util"); var util_1 = require("./util"); exports.WEBGL_ENVS = { 'HAS_WEBGL': true }; exports.NODE_ENVS = { 'IS_NODE': true }; exports.CHROME_ENVS = { 'IS_CHROME': true }; exports.BROWSER_ENVS = { 'IS_BROWSER': true }; exports.CPU_ENVS = { 'HAS_WEBGL': false }; exports.ALL_ENVS = {}; function expectArraysClose(actual, expected, epsilon) { if (epsilon == null) { epsilon = environment_1.ENV.get('TEST_EPSILON'); } return expectArraysPredicate(actual, expected, function (a, b) { return areClose(a, Number(b), epsilon); }); } exports.expectArraysClose = expectArraysClose; function expectArraysPredicate(actual, expected, predicate) { if (!(actual instanceof tensor_1.Tensor) && !(expected instanceof tensor_1.Tensor)) { var aType = actual.constructor.name; var bType = expected.constructor.name; if (aType !== bType) { throw new Error("Arrays are of different type actual: " + aType + " " + ("vs expected: " + bType)); } } else if (actual instanceof tensor_1.Tensor && expected instanceof tensor_1.Tensor) { if (actual.dtype !== expected.dtype) { throw new Error("Arrays are of different type actual: " + actual.dtype + " " + ("vs expected: " + expected.dtype + ".")); } if (!util.arraysEqual(actual.shape, expected.shape)) { throw new Error("Arrays are of different shape actual: " + actual.shape + " " + ("vs expected: " + expected.shape + ".")); } } var actualValues; var expectedValues; if (actual instanceof tensor_1.Tensor) { actualValues = actual.dataSync(); } else { actualValues = actual; } if (expected instanceof tensor_1.Tensor) { expectedValues = expected.dataSync(); } else { expectedValues = expected; } if (actualValues.length !== expectedValues.length) { throw new Error("Arrays have different lengths actual: " + actualValues.length + " vs " + ("expected: " + expectedValues.length + ".\n") + ("Actual: " + actualValues + ".\n") + ("Expected: " + expectedValues + ".")); } for (var i = 0; i < expectedValues.length; ++i) { var a = actualValues[i]; var e = expectedValues[i]; if (!predicate(a, e)) { throw new Error("Arrays differ: actual[" + i + "] = " + a + ", expected[" + i + "] = " + e + ".\n" + ("Actual: " + actualValues + ".\n") + ("Expected: " + expectedValues + ".")); } } } function expectPromiseToFail(fn, done) { fn().then(function () { return done.fail(); }, function () { return done(); }); } exports.expectPromiseToFail = expectPromiseToFail; function expectArraysEqual(actual, expected) { if (actual instanceof tensor_1.Tensor && actual.dtype === 'string' || expected instanceof tensor_1.Tensor && expected.dtype === 'string' || actual instanceof Array && util_1.isString(actual[0]) || expected instanceof Array && util_1.isString(expected[0])) { return expectArraysPredicate(actual, expected, function (a, b) { return a == b; }); } return expectArraysClose(actual, expected, 0); } exports.expectArraysEqual = expectArraysEqual; function expectNumbersClose(a, e, epsilon) { if (epsilon == null) { epsilon = environment_1.ENV.get('TEST_EPSILON'); } if (!areClose(a, e, epsilon)) { throw new Error("Numbers differ: actual === " + a + ", expected === " + e); } } exports.expectNumbersClose = expectNumbersClose; function areClose(a, e, epsilon) { if (isNaN(a) && isNaN(e)) { return true; } if (isNaN(a) || isNaN(e) || Math.abs(a - e) > epsilon) { return false; } return true; } function expectValuesInRange(actual, low, high) { var actualVals; if (actual instanceof tensor_1.Tensor) { actualVals = actual.dataSync(); } else { actualVals = actual; } for (var i = 0; i < actualVals.length; i++) { if (actualVals[i] < low || actualVals[i] > high) { throw new Error("Value out of range:" + actualVals[i] + " low: " + low + ", high: " + high); } } } exports.expectValuesInRange = expectValuesInRange; function expectArrayBuffersEqual(actual, expected) { expect(new Float32Array(actual)).toEqual(new Float32Array(expected)); } exports.expectArrayBuffersEqual = expectArrayBuffersEqual; //# sourceMappingURL=test_util.js.map
1.351563
1
src/clone.js
nonoll/html2canvas-modify
5
831
var log = require('./log'); var Promise = require('./promise'); var html2canvasCanvasCloneAttribute = "data-html2canvas-canvas-clone"; var html2canvasCanvasCloneIndex = 0; function cloneNodeValues(document, clone, nodeName) { var originalNodes = document.getElementsByTagName(nodeName); var clonedNodes = clone.getElementsByTagName(nodeName); var count = originalNodes.length; for (var i = 0; i < count; i++) { clonedNodes[i].value = originalNodes[i].value; } } function restoreOwnerScroll(ownerDocument, x, y) { if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) { ownerDocument.defaultView.scrollTo(x, y); } } function labelCanvasElements(ownerDocument) { [].slice.call(ownerDocument.querySelectorAll("canvas"), 0).forEach(function(canvas) { canvas.setAttribute(html2canvasCanvasCloneAttribute, "canvas-" + html2canvasCanvasCloneIndex++); }); } function cloneCanvasContents(ownerDocument, documentClone) { [].slice.call(ownerDocument.querySelectorAll("[" + html2canvasCanvasCloneAttribute + "]"), 0).forEach(function(canvas) { try { var clonedCanvas = documentClone.querySelector('[' + html2canvasCanvasCloneAttribute + '="' + canvas.getAttribute(html2canvasCanvasCloneAttribute) + '"]'); if (clonedCanvas) { clonedCanvas.width = canvas.width; clonedCanvas.height = canvas.height; clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0); } } catch(e) { log("Unable to copy canvas content from", canvas, e); } canvas.removeAttribute(html2canvasCanvasCloneAttribute); }); } function removeScriptNodes(parent) { [].slice.call(parent.childNodes, 0).filter(isElementNode).forEach(function(node) { if (node.tagName === "SCRIPT") { parent.removeChild(node); } else { removeScriptNodes(node); } }); return parent; } function isIE9() { return document.documentMode && document.documentMode <= 9; } // https://github.com/niklasvh/html2canvas/issues/503 function cloneNodeIE9(node, javascriptEnabled) { var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false); var child = node.firstChild; while(child) { if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') { clone.appendChild(cloneNodeIE9(child, javascriptEnabled)); } child = child.nextSibling; } return clone; } function isElementNode(node) { return node.nodeType === Node.ELEMENT_NODE; } module.exports = function(ownerDocument, containerDocument, width, height, options, x ,y) { labelCanvasElements(ownerDocument); var documentElement = isIE9() ? cloneNodeIE9(ownerDocument.documentElement, options.javascriptEnabled) : ownerDocument.documentElement.cloneNode(true); var container = containerDocument.createElement("iframe"); container.className = "html2canvas-container"; container.style.visibility = "hidden"; container.style.position = "fixed"; container.style.left = "-10000px"; container.style.top = "0px"; container.style.border = "0"; container.width = width; container.height = height; container.scrolling = "no"; // ios won't scroll without it containerDocument.body.appendChild(container); return new Promise(function(resolve) { var documentClone = container.contentWindow.document; cloneNodeValues(ownerDocument.documentElement, documentElement, "textarea"); cloneNodeValues(ownerDocument.documentElement, documentElement, "select"); /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle if window url is about:blank, we can assign the url to current by writing onto the document */ container.contentWindow.onload = container.onload = function() { var interval = setInterval(function() { if (documentClone.body.childNodes.length > 0) { cloneCanvasContents(ownerDocument, documentClone); clearInterval(interval); if (options.type === "view") { container.contentWindow.scrollTo(x, y); } resolve(container); } }, 50); }; documentClone.open(); documentClone.write("<!DOCTYPE html><html></html>"); // Chrome scrolls the parent document for some reason after the write to the cloned window??? restoreOwnerScroll(ownerDocument, x, y); documentClone.replaceChild(options.javascriptEnabled === true ? documentClone.adoptNode(documentElement) : removeScriptNodes(documentClone.adoptNode(documentElement)), documentClone.documentElement); documentClone.close(); }); };
1.398438
1
dist/packages/material/menu/menu-content.js
ttestman4/material2
0
839
/** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Directive, TemplateRef, ComponentFactoryResolver, ApplicationRef, Injector, ViewContainerRef, Inject, } from '@angular/core'; import { TemplatePortal, DomPortalOutlet } from '@angular/cdk/portal'; import { DOCUMENT } from '@angular/common'; import { Subject } from 'rxjs'; /** * Menu content that will be rendered lazily once the menu is opened. */ export class MatMenuContent { /** * @param {?} _template * @param {?} _componentFactoryResolver * @param {?} _appRef * @param {?} _injector * @param {?} _viewContainerRef * @param {?} _document */ constructor(_template, _componentFactoryResolver, _appRef, _injector, _viewContainerRef, _document) { this._template = _template; this._componentFactoryResolver = _componentFactoryResolver; this._appRef = _appRef; this._injector = _injector; this._viewContainerRef = _viewContainerRef; this._document = _document; /** * Emits when the menu content has been attached. */ this._attached = new Subject(); } /** * Attaches the content with a particular context. * \@docs-private * @param {?=} context * @return {?} */ attach(context = {}) { if (!this._portal) { this._portal = new TemplatePortal(this._template, this._viewContainerRef); } this.detach(); if (!this._outlet) { this._outlet = new DomPortalOutlet(this._document.createElement('div'), this._componentFactoryResolver, this._appRef, this._injector); } /** @type {?} */ const element = this._template.elementRef.nativeElement; // Because we support opening the same menu from different triggers (which in turn have their // own `OverlayRef` panel), we have to re-insert the host element every time, otherwise we // risk it staying attached to a pane that's no longer in the DOM. (/** @type {?} */ (element.parentNode)).insertBefore(this._outlet.outletElement, element); this._portal.attach(this._outlet, context); this._attached.next(); } /** * Detaches the content. * \@docs-private * @return {?} */ detach() { if (this._portal.isAttached) { this._portal.detach(); } } /** * @return {?} */ ngOnDestroy() { if (this._outlet) { this._outlet.dispose(); } } } MatMenuContent.decorators = [ { type: Directive, args: [{ selector: 'ng-template[matMenuContent]' },] }, ]; /** @nocollapse */ MatMenuContent.ctorParameters = () => [ { type: TemplateRef }, { type: ComponentFactoryResolver }, { type: ApplicationRef }, { type: Injector }, { type: ViewContainerRef }, { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] } ]; if (false) { /** * @type {?} * @private */ MatMenuContent.prototype._portal; /** * @type {?} * @private */ MatMenuContent.prototype._outlet; /** * Emits when the menu content has been attached. * @type {?} */ MatMenuContent.prototype._attached; /** * @type {?} * @private */ MatMenuContent.prototype._template; /** * @type {?} * @private */ MatMenuContent.prototype._componentFactoryResolver; /** * @type {?} * @private */ MatMenuContent.prototype._appRef; /** * @type {?} * @private */ MatMenuContent.prototype._injector; /** * @type {?} * @private */ MatMenuContent.prototype._viewContainerRef; /** * @type {?} * @private */ MatMenuContent.prototype._document; } //# sourceMappingURL=menu-content.js.map
1.375
1
web3.js/module.flow.js
TheLoneRonin/solana
0
847
/** * Flow Library definition for @solana/web3.js * * This file is manually maintained * * Usage: add the following line under the [libs] section of your project's * .flowconfig: * [libs] * node_modules/@solana/web3.js/module.flow.js * */ import {Buffer} from 'buffer'; import * as BufferLayout from 'buffer-layout'; import {PublicKey} from './src/publickey'; declare module '@solana/web3.js' { // === src/publickey.js === declare export type PublicKeyNonce = [PublicKey, number]; declare export class PublicKey { constructor( value: number | string | Buffer | Uint8Array | Array<number>, ): PublicKey; static createWithSeed( fromPublicKey: PublicKey, seed: string, programId: PublicKey, ): Promise<PublicKey>; static createProgramAddress( seeds: Array<Buffer | Uint8Array>, programId: PublicKey, ): Promise<PublicKey>; static findProgramAddress( seeds: Array<Buffer | Uint8Array>, programId: PublicKey, ): Promise<PublicKeyNonce>; equals(publickey: PublicKey): boolean; toBase58(): string; toBuffer(): Buffer; toString(): string; } // === src/blockhash.js === declare export type Blockhash = string; // === src/account.js === declare export class Account { constructor(secretKey?: Buffer | Uint8Array | Array<number>): Account; publicKey: PublicKey; secretKey: Buffer; } // === src/fee-calculator.js === declare export type FeeCalculator = { lamportsPerSignature: number, }; // === src/connection.js === declare export type Context = { slot: number, }; declare export type SendOptions = { skipPreflight: ?boolean, }; declare export type ConfirmOptions = { commitment: ?Commitment, skipPreflight: ?boolean, }; declare export type ConfirmedSignaturesForAddress2Options = { before?: TransactionSignature, limit?: number, }; declare export type TokenAccountsFilter = | { mint: PublicKey, } | { programId: PublicKey, }; declare export type RpcResponseAndContext<T> = { context: Context, value: T, }; declare export type Commitment = | 'max' | 'recent' | 'root' | 'single' | 'singleGossip'; declare export type LargestAccountsFilter = 'circulating' | 'nonCirculating'; declare export type GetLargestAccountsConfig = { commitment: ?Commitment, filter: ?LargestAccountsFilter, }; declare export type SignatureStatusConfig = { searchTransactionHistory: boolean, }; declare export type SignatureStatus = { slot: number, err: TransactionError | null, confirmations: number | null, }; declare export type ConfirmedSignatureInfo = { signature: string, slot: number, err: TransactionError | null, memo: string | null, }; declare export type BlockhashAndFeeCalculator = { blockhash: Blockhash, feeCalculator: FeeCalculator, }; declare export type PublicKeyAndAccount<T> = { pubkey: PublicKey, account: AccountInfo<T>, }; declare export type AccountInfo<T> = { executable: boolean, owner: PublicKey, lamports: number, data: T, rentEpoch: number | null, }; declare export type ContactInfo = { pubkey: string, gossip: string | null, tpu: string | null, rpc: string | null, version: string | null, }; declare export type SimulatedTransactionResponse = { err: TransactionError | string | null, logs: Array<string> | null, }; declare export type ConfirmedTransactionMeta = { fee: number, preBalances: Array<number>, postBalances: Array<number>, err: TransactionError | null, }; declare export type ConfirmedBlock = { blockhash: Blockhash, previousBlockhash: Blockhash, parentSlot: number, transactions: Array<{ transaction: Transaction, meta: ConfirmedTransactionMeta | null, }>, }; declare export type ConfirmedTransaction = { slot: number, transaction: Transaction, meta: ConfirmedTransactionMeta | null, }; declare export type ParsedAccountData = { program: string, parsed: any, space: number, }; declare export type ParsedMessageAccount = { pubkey: PublicKey, signer: boolean, writable: boolean, }; declare export type ParsedInstruction = {| programId: PublicKey, program: string, parsed: string, |}; declare export type PartiallyDecodedInstruction = {| programId: PublicKey, accounts: Array<PublicKey>, data: string, |}; declare export type ParsedTransaction = { signatures: Array<string>, message: { accountKeys: ParsedMessageAccount[], instructions: (ParsedInstruction | PartiallyDecodedInstruction)[], recentBlockhash: string, }, }; declare export type ParsedConfirmedTransaction = { slot: number, transaction: ParsedTransaction, meta: ConfirmedTransactionMeta | null, }; declare export type KeyedAccountInfo = { accountId: PublicKey, accountInfo: AccountInfo<Buffer>, }; declare export type Version = { 'solana-core': string, }; declare export type VoteAccountInfo = { votePubkey: string, nodePubkey: string, stake: number, commission: number, }; declare export type SlotInfo = { parent: number, slot: number, root: number, }; declare export type TokenAmount = { uiAmount: number, decimals: number, amount: string, }; declare export type TokenAccountBalancePair = { address: PublicKey, amount: string, decimals: number, uiAmount: number, }; declare type AccountChangeCallback = ( accountInfo: AccountInfo<Buffer>, context: Context, ) => void; declare type ProgramAccountChangeCallback = ( keyedAccountInfo: KeyedAccountInfo, context: Context, ) => void; declare type SlotChangeCallback = (slotInfo: SlotInfo) => void; declare type SignatureResultCallback = ( signatureResult: SignatureResult, context: Context, ) => void; declare type RootChangeCallback = (root: number) => void; declare export type TransactionError = {}; declare export type SignatureResult = {| err: TransactionError | null, |}; declare export type InflationGovernor = { foundation: number, foundationTerm: number, initial: number, taper: number, terminal: number, }; declare export type EpochSchedule = { slotsPerEpoch: number, leaderScheduleSlotOffset: number, warmup: boolean, firstNormalEpoch: number, firstNormalSlot: number, }; declare export type EpochInfo = { epoch: number, slotIndex: number, slotsInEpoch: number, absoluteSlot: number, blockHeight: ?number, }; declare export type LeaderSchedule = { [address: string]: number[], }; declare export type Supply = { total: number, circulating: number, nonCirculating: number, nonCirculatingAccounts: Array<PublicKey>, }; declare export type AccountBalancePair = { address: PublicKey, lamports: number, }; declare export type VoteAccountStatus = { current: Array<VoteAccountInfo>, delinquent: Array<VoteAccountInfo>, }; declare export class Connection { constructor(endpoint: string, commitment: ?Commitment): Connection; commitment: ?Commitment; getAccountInfoAndContext( publicKey: PublicKey, commitment: ?Commitment, ): Promise<RpcResponseAndContext<AccountInfo<Buffer> | null>>; getAccountInfo( publicKey: PublicKey, commitment: ?Commitment, ): Promise<AccountInfo<Buffer> | null>; getParsedAccountInfo( publicKey: PublicKey, commitment: ?Commitment, ): Promise< RpcResponseAndContext<AccountInfo<Buffer | ParsedAccountData> | null>, >; getProgramAccounts( programId: PublicKey, commitment: ?Commitment, ): Promise<Array<PublicKeyAndAccount<Buffer>>>; getParsedProgramAccounts( programId: PublicKey, commitment: ?Commitment, ): Promise<Array<PublicKeyAndAccount<Buffer | ParsedAccountData>>>; getBalanceAndContext( publicKey: PublicKey, commitment: ?Commitment, ): Promise<RpcResponseAndContext<number>>; getBalance(publicKey: PublicKey, commitment: ?Commitment): Promise<number>; getBlockTime(slot: number): Promise<number | null>; getMinimumLedgerSlot(): Promise<number>; getFirstAvailableBlock(): Promise<number>; getSupply(commitment: ?Commitment): Promise<RpcResponseAndContext<Supply>>; getTokenSupply( tokenMintAddress: PublicKey, commitment: ?Commitment, ): Promise<RpcResponseAndContext<TokenAmount>>; getTokenAccountBalance( tokenAddress: PublicKey, commitment: ?Commitment, ): Promise<RpcResponseAndContext<TokenAmount>>; getTokenAccountsByOwner( ownerAddress: PublicKey, filter: TokenAccountsFilter, commitment: ?Commitment, ): Promise< RpcResponseAndContext< Array<{pubkey: PublicKey, account: AccountInfo<Buffer>}>, >, >; getLargestAccounts( config: ?GetLargestAccountsConfig, ): Promise<RpcResponseAndContext<Array<AccountBalancePair>>>; getTokenLargestAccounts( mintAddress: PublicKey, commitment: ?Commitment, ): Promise<RpcResponseAndContext<Array<TokenAccountBalancePair>>>; getClusterNodes(): Promise<Array<ContactInfo>>; getConfirmedBlock(slot: number): Promise<ConfirmedBlock>; getConfirmedTransaction( signature: TransactionSignature, ): Promise<ConfirmedTransaction | null>; getParsedConfirmedTransaction( signature: TransactionSignature, ): Promise<ParsedConfirmedTransaction | null>; getConfirmedSignaturesForAddress( address: PublicKey, startSlot: number, endSlot: number, ): Promise<Array<TransactionSignature>>; getConfirmedSignaturesForAddress2( address: PublicKey, options: ?ConfirmedSignaturesForAddress2Options, ): Promise<Array<ConfirmedSignatureInfo>>; getVoteAccounts(commitment: ?Commitment): Promise<VoteAccountStatus>; confirmTransaction( signature: TransactionSignature, commitment: ?Commitment, ): Promise<RpcResponseAndContext<SignatureResult>>; getSlot(commitment: ?Commitment): Promise<number>; getSlotLeader(commitment: ?Commitment): Promise<string>; getSignatureStatus( signature: TransactionSignature, config: ?SignatureStatusConfig, ): Promise<RpcResponseAndContext<SignatureStatus | null>>; getSignatureStatuses( signatures: Array<TransactionSignature>, config: ?SignatureStatusConfig, ): Promise<RpcResponseAndContext<Array<SignatureStatus | null>>>; getTransactionCount(commitment: ?Commitment): Promise<number>; getTotalSupply(commitment: ?Commitment): Promise<number>; getVersion(): Promise<Version>; getInflationGovernor(commitment: ?Commitment): Promise<InflationGovernor>; getLeaderSchedule(): Promise<LeaderSchedule>; getEpochSchedule(): Promise<EpochSchedule>; getEpochInfo(commitment: ?Commitment): Promise<EpochInfo>; getRecentBlockhashAndContext( commitment: ?Commitment, ): Promise<RpcResponseAndContext<BlockhashAndFeeCalculator>>; getFeeCalculatorForBlockhash( blockhash: Blockhash, commitment: ?Commitment, ): Promise<RpcResponseAndContext<FeeCalculator | null>>; getRecentBlockhash( commitment: ?Commitment, ): Promise<BlockhashAndFeeCalculator>; requestAirdrop( to: PublicKey, amount: number, ): Promise<TransactionSignature>; sendTransaction( transaction: Transaction, signers: Array<Account>, options?: SendOptions, ): Promise<TransactionSignature>; sendEncodedTransaction( encodedTransaction: string, options?: SendOptions, ): Promise<TransactionSignature>; sendRawTransaction( wireTransaction: Buffer | Uint8Array | Array<number>, options?: SendOptions, ): Promise<TransactionSignature>; simulateTransaction( transaction: Transaction, signers?: Array<Account>, ): Promise<RpcResponseAndContext<SimulatedTransactionResponse>>; onAccountChange( publickey: PublicKey, callback: AccountChangeCallback, commitment: ?Commitment, ): number; removeAccountChangeListener(id: number): Promise<void>; onProgramAccountChange( programId: PublicKey, callback: ProgramAccountChangeCallback, commitment: ?Commitment, ): number; removeProgramAccountChangeListener(id: number): Promise<void>; onSlotChange(callback: SlotChangeCallback): number; removeSlotChangeListener(id: number): Promise<void>; onSignature( signature: TransactionSignature, callback: SignatureResultCallback, commitment: ?Commitment, ): number; removeSignatureListener(id: number): Promise<void>; onRootChange(callback: RootChangeCallback): number; removeRootChangeListener(id: number): Promise<void>; validatorExit(): Promise<boolean>; getMinimumBalanceForRentExemption( dataLength: number, commitment: ?Commitment, ): Promise<number>; getNonce( nonceAccount: PublicKey, commitment: ?Commitment, ): Promise<NonceAccount>; getNonceAndContext( nonceAccount: PublicKey, commitment: ?Commitment, ): Promise<RpcResponseAndContext<NonceAccount>>; } // === src/nonce-account.js === declare export class NonceAccount { authorizedPubkey: PublicKey; nonce: Blockhash; feeCalculator: FeeCalculator; static fromAccountData( buffer: Buffer | Uint8Array | Array<number>, ): NonceAccount; } declare export var NONCE_ACCOUNT_LENGTH: number; // === src/validator-info.js === declare export var VALIDATOR_INFO_KEY; declare export type Info = {| name: string, website?: string, details?: string, keybaseUsername?: string, |}; declare export class ValidatorInfo { key: PublicKey; info: Info; constructor(key: PublicKey, info: Info): ValidatorInfo; static fromConfigData( buffer: Buffer | Uint8Array | Array<number>, ): ValidatorInfo | null; } // === src/sysvar.js === declare export var SYSVAR_CLOCK_PUBKEY; declare export var SYSVAR_RENT_PUBKEY; declare export var SYSVAR_REWARDS_PUBKEY; declare export var SYSVAR_STAKE_HISTORY_PUBKEY; // === src/vote-account.js === declare export var VOTE_PROGRAM_ID; declare export type Lockout = {| slot: number, confirmationCount: number, |}; declare export type EpochCredits = {| epoch: number, credits: number, prevCredits: number, |}; declare export class VoteAccount { votes: Array<Lockout>; nodePubkey: PublicKey; authorizedVoterPubkey: PublicKey; commission: number; rootSlot: number | null; epoch: number; credits: number; lastEpochCredits: number; epochCredits: Array<EpochCredits>; static fromAccountData( buffer: Buffer | Uint8Array | Array<number>, ): VoteAccount; } // === src/instruction.js === declare export type InstructionType = {| index: number, layout: typeof BufferLayout, |}; declare export function encodeData(type: InstructionType, fields: {}): Buffer; // === src/message.js === declare export type MessageHeader = { numRequiredSignatures: number, numReadonlySignedAccounts: number, numReadonlyUnsignedAccounts: number, }; declare export type CompiledInstruction = { programIdIndex: number, accounts: number[], data: string, }; declare export type MessageArgs = { header: MessageHeader, accountKeys: string[], recentBlockhash: Blockhash, instructions: CompiledInstruction[], }; declare export class Message { header: MessageHeader; accountKeys: PublicKey[]; recentBlockhash: Blockhash; instructions: CompiledInstruction[]; constructor(args: MessageArgs): Message; isAccountWritable(index: number): boolean; serialize(): Buffer; } // === src/transaction.js === declare export type TransactionSignature = string; declare export type AccountMeta = { pubkey: PublicKey, isSigner: boolean, isWritable: boolean, }; declare type TransactionInstructionCtorFields = {| keys: ?Array<AccountMeta>, programId?: PublicKey, data?: Buffer, |}; declare export class TransactionInstruction { keys: Array<AccountMeta>; programId: PublicKey; data: Buffer; constructor( opts?: TransactionInstructionCtorFields, ): TransactionInstruction; } declare type SignaturePubkeyPair = {| signature: Buffer | null, publicKey: PublicKey, |}; declare type NonceInformation = {| nonce: Blockhash, nonceInstruction: TransactionInstruction, |}; declare type TransactionCtorFields = {| recentBlockhash?: Blockhash, nonceInfo?: NonceInformation, signatures?: Array<SignaturePubkeyPair>, |}; declare export type SerializeConfig = { requireAllSignatures?: boolean, verifySignatures?: boolean, }; declare export class Transaction { signatures: Array<SignaturePubkeyPair>; signature: ?Buffer; instructions: Array<TransactionInstruction>; recentBlockhash: ?Blockhash; nonceInfo: ?NonceInformation; feePayer: PublicKey | null; constructor(opts?: TransactionCtorFields): Transaction; static from(buffer: Buffer | Uint8Array | Array<number>): Transaction; static populate(message: Message, signatures: Array<string>): Transaction; add( ...items: Array< Transaction | TransactionInstruction | TransactionInstructionCtorFields, > ): Transaction; compileMessage(): Message; serializeMessage(): Buffer; sign(...signers: Array<Account>): void; partialSign(...partialSigners: Array<Account>): void; addSignature(pubkey: PublicKey, signature: Buffer): void; setSigners(...signers: Array<PublicKey>): void; verifySignatures(): boolean; serialize(config?: SerializeConfig): Buffer; } // === src/stake-program.js === declare export type StakeAuthorizationType = {| index: number, |}; declare export class Authorized { staker: PublicKey; withdrawer: PublicKey; constructor(staker: PublicKey, withdrawer: PublicKey): Authorized; } declare export class Lockup { unixTimestamp: number; epoch: number; custodian: PublicKey; constructor( unixTimestamp: number, epoch: number, custodian: PublicKey, ): Lockup; } declare export type CreateStakeAccountParams = {| fromPubkey: PublicKey, stakePubkey: PublicKey, authorized: Authorized, lockup: Lockup, lamports: number, |}; declare export type CreateStakeAccountWithSeedParams = {| fromPubkey: PublicKey, stakePubkey: PublicKey, basePubkey: PublicKey, seed: string, authorized: Authorized, lockup: Lockup, lamports: number, |}; declare export type InitializeStakeParams = {| stakePubkey: PublicKey, authorized: Authorized, lockup: Lockup, |}; declare export type DelegateStakeParams = {| stakePubkey: PublicKey, authorizedPubkey: PublicKey, votePubkey: PublicKey, |}; declare export type AuthorizeStakeParams = {| stakePubkey: PublicKey, authorizedPubkey: PublicKey, newAuthorizedPubkey: PublicKey, stakeAuthorizationType: StakeAuthorizationType, |}; declare export type AuthorizeWithSeedStakeParams = {| stakePubkey: PublicKey, authorityBase: PublicKey, authoritySeed: string, authorityOwner: PublicKey, newAuthorizedPubkey: PublicKey, stakeAuthorizationType: StakeAuthorizationType, |}; declare export type SplitStakeParams = {| stakePubkey: PublicKey, authorizedPubkey: PublicKey, splitStakePubkey: PublicKey, lamports: number, |}; declare export type WithdrawStakeParams = {| stakePubkey: PublicKey, authorizedPubkey: PublicKey, toPubkey: PublicKey, lamports: number, |}; declare export type DeactivateStakeParams = {| stakePubkey: PublicKey, authorizedPubkey: PublicKey, |}; declare export class StakeProgram { static programId: PublicKey; static space: number; static createAccount(params: CreateStakeAccountParams): Transaction; static createAccountWithSeed( params: CreateStakeAccountWithSeedParams, ): Transaction; static delegate(params: DelegateStakeParams): Transaction; static authorize(params: AuthorizeStakeParams): Transaction; static split(params: SplitStakeParams): Transaction; static withdraw(params: WithdrawStakeParams): Transaction; static deactivate(params: DeactivateStakeParams): Transaction; } declare export type StakeInstructionType = | 'Initialize' | 'Authorize' | 'AuthorizeWithSeed' | 'Delegate' | 'Split' | 'Withdraw' | 'Deactivate'; declare export var STAKE_INSTRUCTION_LAYOUTS: { [StakeInstructionType]: InstructionType, }; declare export class StakeInstruction { static decodeInstructionType( instruction: TransactionInstruction, ): StakeInstructionType; static decodeInitialize( instruction: TransactionInstruction, ): InitializeStakeParams; static decodeDelegate( instruction: TransactionInstruction, ): DelegateStakeParams; static decodeAuthorize( instruction: TransactionInstruction, ): AuthorizeStakeParams; static decodeSplit(instruction: TransactionInstruction): SplitStakeParams; static decodeWithdraw( instruction: TransactionInstruction, ): WithdrawStakeParams; static decodeDeactivate( instruction: TransactionInstruction, ): DeactivateStakeParams; } // === src/system-program.js === declare export type CreateAccountParams = {| fromPubkey: PublicKey, newAccountPubkey: PublicKey, lamports: number, space: number, programId: PublicKey, |}; declare export type CreateAccountWithSeedParams = {| fromPubkey: PublicKey, newAccountPubkey: PublicKey, basePubkey: PublicKey, seed: string, lamports: number, space: number, programId: PublicKey, |}; declare export type AllocateParams = {| accountPubkey: PublicKey, space: number, |}; declare export type AllocateWithSeedParams = {| accountPubkey: PublicKey, basePubkey: PublicKey, seed: string, space: number, programId: PublicKey, |}; declare export type AssignParams = {| accountPubkey: PublicKey, programId: PublicKey, |}; declare export type AssignWithSeedParams = {| accountPubkey: PublicKey, basePubkey: PublicKey, seed: string, programId: PublicKey, |}; declare export type TransferParams = {| fromPubkey: PublicKey, toPubkey: PublicKey, lamports: number, |}; declare export type CreateNonceAccountParams = {| fromPubkey: PublicKey, noncePubkey: PublicKey, authorizedPubkey: PublicKey, lamports: number, |}; declare export type CreateNonceAccountWithSeedParams = {| fromPubkey: PublicKey, noncePubkey: PublicKey, authorizedPubkey: PublicKey, lamports: number, basePubkey: PublicKey, seed: string, |}; declare export type InitializeNonceParams = {| noncePubkey: PublicKey, authorizedPubkey: PublicKey, |}; declare export type AdvanceNonceParams = {| noncePubkey: PublicKey, authorizedPubkey: PublicKey, |}; declare export type WithdrawNonceParams = {| noncePubkey: PublicKey, authorizedPubkey: PublicKey, toPubkey: PublicKey, lamports: number, |}; declare export type AuthorizeNonceParams = {| noncePubkey: PublicKey, authorizedPubkey: PublicKey, newAuthorizedPubkey: PublicKey, |}; declare export class SystemProgram { static programId: PublicKey; static createAccount(params: CreateAccountParams): TransactionInstruction; static createAccountWithSeed( params: CreateAccountWithSeedParams, ): TransactionInstruction; static allocate( params: AllocateParams | AllocateWithSeedParams, ): TransactionInstruction; static assign( params: AssignParams | AssignWithSeedParams, ): TransactionInstruction; static transfer(params: TransferParams): TransactionInstruction; static createNonceAccount( params: CreateNonceAccountParams | CreateNonceAccountWithSeedParams, ): Transaction; static nonceAdvance(params: AdvanceNonceParams): TransactionInstruction; static nonceWithdraw(params: WithdrawNonceParams): TransactionInstruction; static nonceAuthorize(params: AuthorizeNonceParams): TransactionInstruction; } declare export type SystemInstructionType = | 'Create' | 'CreateWithSeed' | 'Allocate' | 'AllocateWithSeed' | 'Assign' | 'AssignWithSeed' | 'Transfer' | 'AdvanceNonceAccount' | 'WithdrawNonceAccount' | 'InitializeNonceAccount' | 'AuthorizeNonceAccount'; declare export var SYSTEM_INSTRUCTION_LAYOUTS: { [SystemInstructionType]: InstructionType, }; declare export class SystemInstruction { static decodeInstructionType( instruction: TransactionInstruction, ): SystemInstructionType; static decodeCreateAccount( instruction: TransactionInstruction, ): CreateAccountParams; static decodeCreateWithSeed( instruction: TransactionInstruction, ): CreateAccountWithSeedParams; static decodeAllocate(instruction: TransactionInstruction): AllocateParams; static decodeAllocateWithSeed( instruction: TransactionInstruction, ): AllocateWithSeedParams; static decodeAssign(instruction: TransactionInstruction): AssignParams; static decodeAssignWithSeed( instruction: TransactionInstruction, ): AssignWithSeedParams; static decodeTransfer(instruction: TransactionInstruction): TransferParams; static decodeNonceInitialize( instruction: TransactionInstruction, ): InitializeNonceParams; static decodeNonceAdvance( instruction: TransactionInstruction, ): AdvanceNonceParams; static decodeNonceWithdraw( instruction: TransactionInstruction, ): WithdrawNonceParams; static decodeNonceAuthorize( instruction: TransactionInstruction, ): AuthorizeNonceParams; } // === src/loader.js === declare export class Loader { static getMinNumSignatures(dataLength: number): number; static load( connection: Connection, payer: Account, program: Account, programId: PublicKey, data: Buffer | Uint8Array | Array<number>, ): Promise<PublicKey>; } // === src/bpf-loader.js === declare export var BPF_LOADER_PROGRAM_ID; declare export class BpfLoader { static getMinNumSignatures(dataLength: number): number; static load( connection: Connection, payer: Account, program: Account, elfBytes: Buffer | Uint8Array | Array<number>, loaderProgramId: PublicKey, ): Promise<PublicKey>; } // === src/bpf-loader-deprecated.js === declare export var BPF_LOADER_DEPRECATED_PROGRAM_ID; // === src/util/send-and-confirm-transaction.js === declare export function sendAndConfirmTransaction( connection: Connection, transaction: Transaction, signers: Array<Account>, options: ?ConfirmOptions, ): Promise<TransactionSignature>; // === src/util/send-and-confirm-raw-transaction.js === declare export function sendAndConfirmRawTransaction( connection: Connection, wireTransaction: Buffer, options: ?ConfirmOptions, ): Promise<TransactionSignature>; // === src/util/cluster.js === declare export type Cluster = 'devnet' | 'testnet' | 'mainnet-beta'; declare export function clusterApiUrl( cluster?: Cluster, tls?: boolean, ): string; // === src/index.js === declare export var LAMPORTS_PER_SOL: number; }
1.195313
1
src/index.js
maxnope/reverse-int
0
855
module.exports = function reverse (n) { let n_positive = Math.abs(n) let n_string = n_positive.toString() return n_string.split('').reverse().join(''); }
1.203125
1
node_modules/@iconify/icons-mdi/src/settings-bluetooth.js
FAD95/NEXT.JS-Course
1
863
let data = { "body": "<path d=\"M14.88 14.29L13 16.17v-3.76l1.88 1.88M13 3.83l1.88 1.88L13 7.59m4.71-1.88L12 0h-1v7.59L6.41 3L5 4.41L10.59 10L5 15.59L6.41 17L11 12.41V20h1l5.71-5.71l-4.3-4.29l4.3-4.29M15 24h2v-2h-2m-8 2h2v-2H7m4 2h2v-2h-2v2z\" fill=\"currentColor\"/>", "width": 24, "height": 24 }; export default data;
0.261719
0
taxcalc-ui/src/api/tax/feedback.js
junditech/tax-calculator
2
871
import request from '@/utils/request' // 查询问题反馈列表 export function listFeedback(query) { return request({ url: '/tax/feedback/list', method: 'get', params: query }) } // 查询问题反馈详细 export function getFeedback(feedbackId) { return request({ url: '/tax/feedback/' + feedbackId, method: 'get' }) } // 新增问题反馈 export function addFeedback(data) { return request({ url: '/tax/feedback', method: 'post', data: data }) } // 修改问题反馈 export function updateFeedback(data) { return request({ url: '/tax/feedback', method: 'put', data: data }) } // 删除问题反馈 export function delFeedback(feedbackId) { return request({ url: '/tax/feedback/' + feedbackId, method: 'delete' }) } // 导出问题反馈 export function exportFeedback(query) { return request({ url: '/tax/feedback/export', method: 'get', params: query }) }
0.835938
1
src/tests/components/ExpenseList.test.js
protatodev/expensify-app
0
879
import React from 'react'; import { shallow } from 'enzyme'; import { ExpenseList } from '../../components/ExpenseList'; import expenses from '../fixtures/expenses'; test('should render ExpenseList with expenses', () => { const wrapper = shallow(<ExpenseList expenses={expenses} />); expect(wrapper).toMatchSnapshot(); }); test('should render ExpenseList with empty message', () => { const wrapper = shallow(<ExpenseList expenses={[]}/>); expect(wrapper).toMatchSnapshot(); });
1.234375
1
test/api/auth.js
el-tu/citizenos-api
0
887
'use strict'; /** * Log in - call '/api/auth/login' API endpoint * * @param {object} agent SuperAgent is in the interface so other tests preparing data could provide their agent. Useful when agent holds a state (for ex session). * @param {string} email E-mail * @param {string} password Password * @param {string} expectedHttpCode Expected HTTP code * * @returns {Promise<Object>} SuperAgent response object * * @private */ const _login = async function (agent, email, password, expectedHttpCode) { const path = '/api/auth/login'; const a = agent .post(path) .set('Content-Type', 'application/json') .send({ email: email, password: password }) .expect(expectedHttpCode) .expect('Content-Type', /json/); if (expectedHttpCode === 200) { a.expect('set-cookie', /.*\.sid=.*; Path=\/api; Expires=.*; HttpOnly/); } return a; }; const login = async function (agent, email, password) { return _login(agent, email, password, 200); }; const _loginId = async function (agent, token, clientCert, expectedHttpCode) { const path = '/api/auth/id'; const a = agent .post(path) .set('Content-Type', 'application/json'); if (clientCert) { a.set('X-SSL-Client-Cert', clientCert); } if (token) { a.send({token: token}); } return a.expect(expectedHttpCode) .expect('Content-Type', /json/) .then(function (res, err) { if (err) return err; const data = res.body.data; if (data && !data.token && !data.hash) { a.expect('set-cookie', /.*\.sid=.*; Path=\/api; Expires=.*; HttpOnly/); } }); } /** * Initialize Mobiil-ID login - call '/api/auth/mobile/init' API endpoint * * @param {object} agent SuperAgent is in the interface so other tests preparing data could provide their agent. Useful when agent holds a state (for ex session). * @param {string} pid Personal identification number * @param {string} phoneNumber Phone number * @param {number} expectedHttpCode Expected HTTP response code * * @return {void} * * @private */ const _loginMobileInit = async function (agent, pid, phoneNumber, expectedHttpCode) { const path = '/api/auth/mobile/init'; return agent .post(path) .set('Content-Type', 'application/json') .send({ pid: pid, phoneNumber: phoneNumber }) .expect(expectedHttpCode) .expect('Content-Type', /json/); }; const loginMobileInit = async function (agent, pid, phoneNumber) { return _loginMobileInit(agent, pid, phoneNumber, 200); }; /** * Initialize Smart-ID login - call '/api/auth/smartid/init' API endpoint * * @param {object} agent SuperAgent is in the interface so other tests preparing data could provide their agent. Useful when agent holds a state (for ex session). * @param {string} pid Personal identification number * @param {number} expectedHttpCode Expected HTTP response code * * @return {void} * * @private */ const _loginSmartIdInit = async function (agent, pid, expectedHttpCode) { const path = '/api/auth/smartid/init'; return agent .post(path) .set('Content-Type', 'application/json') .send({pid: pid}) .expect(expectedHttpCode) .expect('Content-Type', /json/); }; const loginSmartIdInit = async function (agent, pid) { return _loginSmartIdInit(agent, pid, 200); }; /** * Check mobile authentication status - call '/api/auth/mobile/status' * * @param {object} agent SuperAgent is in the interface so other tests preparing data could provide their agent. Useful when agent holds a state (for ex session). * @param {string} token JWT token issued when login was initiated * @param {number} expectedHttpCode Expected HTTP response code * * @return {void} * * @private */ const _loginMobilestatus = async function (agent, token, expectedHttpCode) { const path = '/api/auth/mobile/status'; return agent .get(path) .query({ token: token }) .expect(expectedHttpCode) .expect('Content-Type', /json/) }; const loginMobilestatus = async function (agent, token) { return new Promise(function (resolve, reject) { const maxRetries = 20; const retryInterval = 1000; // milliseconds; let retries = 0; const statusInterval = setInterval(async function () { try { if (retries < maxRetries) { retries++; const loginMobileStatusResponse = await _loginMobilestatus(agent, token, 200); if (loginMobileStatusResponse.body.status.code !== 20001) { clearInterval(statusInterval); return resolve(loginMobileStatusResponse); } } else { clearInterval(statusInterval); return reject(new Error(`loginMobileStatus maximum retry limit ${maxRetries} reached!`)); } } catch (err) { // Whatever blows, stop polling clearInterval(statusInterval); return reject(err); } }, retryInterval); }); }; /** * Check smart-ID authentication status - call '/api/auth/smartid/status' * * @param {object} agent SuperAgent is in the interface so other tests preparing data could provide their agent. Useful when agent holds a state (for ex session). * @param {string} token JWT token that was issued when flow was initiated * * @return {void} * * @private */ const _loginSmartIdstatus = async function (agent, token) { const path = '/api/auth/smartid/status'; return agent .get(path) .query({ token: token }) .expect('Content-Type', /json/); }; const loginSmartIdstatus = async function (agent, token, interval) { return new Promise(function (resolve, reject) { const maxRetries = 20; const retryInterval = interval || 1000; // milliseconds; let retries = 0; const statusInterval = setInterval(async function () { try { if (retries < maxRetries) { retries++; const loginSmartIdStatusResponse = await _loginSmartIdstatus(agent, token, 200); if (loginSmartIdStatusResponse.body.status.code !== 20001) { clearInterval(statusInterval); return resolve(loginSmartIdStatusResponse); } } else { clearInterval(statusInterval); return reject(new Error(`loginSmartIdStatus maximum retry limit ${maxRetries} reached!`)); } } catch (err) { // Whatever blows, stop polling clearInterval(statusInterval); return reject(err); } }, retryInterval); }); }; /** * Log out - call '/api/auth/logout' API endpoint * * @param {object} agent SuperAgent is in the interface so other tests preparing data could provide their agent. Useful when agent holds a state (for ex session). * * @return {void} */ const logout = async function (agent) { const path = '/api/auth/logout'; return agent .post(path) .set('Content-Type', 'application/json') .expect(200) .expect('Content-Type', /json/) }; /** * Sign up - call '/api/auth/signup' API endpoint * * @param {object} agent SuperAgent is in the interface so other tests preparing data could provide their agent. Useful when agent holds a state (for ex session). * @param {string} email E-mail * @param {string} password Password * @param {string} language Users preferred language ISO 2 char language code * * @return {void} */ const _signup = async function (agent, email, password, language, expectedHttpCode) { const path = '/api/auth/signup'; return agent .post(path) .set('Content-Type', 'application/json') .send({ email: email, password: password, language: language }) .expect(expectedHttpCode) .expect('Content-Type', /json/); }; const signup = async function (agent, email, password, language) { return _signup(agent, email, password, language, 200); }; /** * Set password - call '/api/auth/password' API endpoint * * @param {object} agent SuperAgent is in the interface so other tests preparing data could provide their agent. Useful when agent holds a state (for ex session). * @param {string} currentPassword <PASSWORD> * @param {string} newPassword <PASSWORD> * @param {number} expectedHttpCode Expected HTTP response code * * @return {void} * * @private */ const _passwordSet = async function (agent, currentPassword, newPassword, expectedHttpCode) { const path = '/api/auth/password'; return agent .post(path) .set('Content-Type', 'application/json') .send({ currentPassword: <PASSWORD>, newPassword: <PASSWORD> }) .expect(expectedHttpCode) .expect('Content-Type', /json/); }; /** * Set password - call '/api/auth/password' API endpoint * * @param {object} agent SuperAgent is in the interface so other tests preparing data could provide their agent. Useful when agent holds a state (for ex session). * @param {string} currentPassword <PASSWORD> * @param {string} newPassword <PASSWORD> * * @return {void} */ const passwordSet = async function (agent, currentPassword, newPassword) { return _passwordSet(agent, currentPassword, newPassword, 200); }; /** * Send user password reset email with reset code - call '/api/auth/password/reset' API endpoint * * @param {object} agent SuperAgent is in the interface so other tests preparing data could provide their agent. Useful when agent holds a state (for ex session). * @param {string} email E-mail of the user who's password is to be reset * @param {number} expectedHttpCode Expected HTTP response code * * @return {void} * * @private */ const _passwordResetSend = async function (agent, email, expectedHttpCode) { const path = '/api/auth/password/reset/send'; return agent .post(path) .set('Content-Type', 'application/json') .send({email: email}) .expect(expectedHttpCode) .expect('Content-Type', /json/); }; const passwordResetSend = function (agent, email) { return _passwordResetSend(agent, email, 200); }; const _passwordResetComplete = async function (agent, email, password, passwordResetCode, expectedHttpCode) { const path = '/api/auth/password/reset'; return agent .post(path) .set('Content-Type', 'application/json') .send({ email: email, password: password, passwordResetCode: passwordResetCode }) .expect(expectedHttpCode) .expect('Content-Type', /json/); }; const passwordResetComplete = async function (agent, email, password, passwordResetCode) { return _passwordResetComplete(agent, email, password, passwordResetCode, 200); }; /** * Verify e-mail - call '/api/auth/verify/:code' * * @param {object} agent SuperAgent is in the interface so other tests preparing data could provide their agent. Useful when agent holds a state (for ex session). * @param {string} emailVerificationCode Verification code e-mailed to the user. * * @return {void} */ const verify = async function (agent, emailVerificationCode) { const path = '/api/auth/verify/:code'.replace(':code', emailVerificationCode); return agent .get(path) .expect(302) .expect('Location', /\/account\/login\?email=.*/); }; /** * Check auth status - call '/api/auth/status' * * @param {object} agent SuperAgent is in the interface so other tests preparing data could provide their agent. Useful when agent holds a state (for ex session). * @param {number} expectedHttpCode Expected HTTP response code * * @return {void} * * @private */ const _status = async function (agent, expectedHttpCode) { const path = '/api/auth/status'; return agent .get(path) .set('Content-Type', 'application/json') .expect(expectedHttpCode) .expect('Content-Type', /json/); }; /** * Check auth status - call '/api/auth/status' * * @param {object} agent SuperAgent is in the interface so other tests preparing data could provide their agent. Useful when agent holds a state (for ex session). * * @return {void} */ const status = async function (agent) { return _status(agent, 200); }; const _openIdAuthorize = async function (agent, responseType, clientId, redirectUri, nonce, scope, state, expectedHttpCode) { const path = '/api/auth/openid/authorize'; return agent .get(path) .query({ response_type: responseType, client_id: clientId, redirect_uri: redirectUri, nonce: nonce, scope: scope, state: state }) .expect(expectedHttpCode); }; const openIdAuthorize = async function (agent, responseType, clientId, redirectUri, scope, state, nonce) { return _openIdAuthorize(agent, responseType, clientId, redirectUri, nonce, scope, state, 302); }; //Export the above function call so that other tests could use it to prepare data. module.exports.login = login; module.exports.login = login; module.exports.logout = logout; module.exports.logout = logout; module.exports.signup = signup; module.exports.signup = signup; module.exports.verify = verify; module.exports.status = status; module.exports._status = _status; module.exports.status = status; module.exports._status = _status; const request = require('supertest'); const app = require('../../app'); const models = app.get('models'); const uuid = require('uuid'); const fs = require('fs'); const assert = require('chai').assert; const config = app.get('config'); const jwt = app.get('jwt'); const urlLib = app.get('urlLib'); const objectEncrypter = app.get('objectEncrypter'); const shared = require('../utils/shared'); const userLib = require('./lib/user')(app); const User = models.User; const UserConnection = models.UserConnection; const UserConsent = models.UserConsent; const Partner = models.Partner; const db = models.sequelize; suite('Auth', function () { suiteSetup(async function () { return shared .syncDb(); }); suite('Login', function () { suite('Username & password', function () { const agent = request.agent(app); const email = 'test_' + new Date().getTime() + '@test.ee'; const password = '<PASSWORD>'; suiteSetup(async function () { await userLib.createUser(agent, email, password, null); }); test('Success', async function () { const res = await login(agent, email, password); const user = res.body.data; assert.equal(user.email, email); assert.property(user, 'id'); assert.notProperty(res.body, 'name'); //TODO: would be nice if null values were not returned in the response assert.notProperty(user, 'password'); assert.notProperty(user, 'emailIsVerified'); assert.notProperty(user, 'emailVerificationCode'); assert.notProperty(user, 'createdAt'); assert.notProperty(user, 'updatedAt'); assert.notProperty(user, 'deletedAt'); }); test('Fail - 40001 - account does not exist', async function () { const res = await agent .post('/api/auth/login') .set('Content-Type', 'application/json') .send({ email: 'test_nonexistent_' + new Date().getTime() + '@test.ee', password: password }) .expect(400) .expect('Content-Type', /json/); const status = res.body.status; assert.equal(status.code, 40001); assert.equal(status.message, 'The account does not exists.'); }); test('Fail - 40002 - account has not been verified', async function () { const agent = request.agent(app); const email = 'test_notverif_' + new Date().getTime() + '@test.ee'; const password = '<PASSWORD>'; await signup(agent, email, password, null); const res = await _login(agent, email, password, 400); const status = res.body.status; assert.equal(status.code, 40002); assert.equal(status.message, 'The account verification has not been completed. Please check your e-mail.'); }); test('Fail - 40003 - wrong password', async function () { const res = await agent .post('/api/auth/login') .set('Content-Type', 'application/json') .send({ email: email, password: '<PASSWORD>' }) .expect(400) .expect('Content-Type', /json/); const status = res.body.status; assert.equal(status.code, 40003); assert.equal(res.body.errors.password, '<PASSWORD>'); }); }); suite('ID-card', function () { teardown(async function () { return UserConnection .destroy({ where: { connectionId: UserConnection.CONNECTION_IDS.esteid, connectionUserId: ['PNOEE-37101010021'] }, force: true }); }); test('Success - client certificate in X-SSL-Client-Cert header', async function () { this.timeout(5000); //eslint-disable-line no-invalid-this const agent = request.agent(app); const cert = fs.readFileSync('./test/resources/certificates/good-jaak-kristjan_jõeorg_esteid_sign.pem', {encoding: 'utf8'}).replace(/\n/g, ''); //eslint-disable-line no-sync await _loginId(agent, null, cert, 200); }); test('Fail - no token or client certificate in header', async function () { await _loginId(request.agent(app), null, null, 400); }); }); suite('Mobiil-ID', function () { suite('Init', function () { setup(async function () { await UserConnection .destroy({ where: { connectionId: UserConnection.CONNECTION_IDS.esteid, connectionUserId: ['PNOEE-60001019906'] }, force: true }); }); test('Success - 20001 - Estonian mobile number and PID', async function () { this.timeout(15000); //eslint-disable-line no-invalid-this const phoneNumber = '+37200000766'; const pid = '60001019906'; const response = (await loginMobileInit(request.agent(app), pid, phoneNumber)).body; assert.equal(response.status.code, 20001); assert.match(response.data.challengeID, /[0-9]{4}/); const tokenData = jwt.verify(response.data.token, config.session.publicKey, {algorithms: [config.session.algorithm]}); const loginMobileFlowData = objectEncrypter(config.session.secret).decrypt(tokenData.sessionDataEncrypted); assert.property(loginMobileFlowData, 'sessionHash'); const responseData = (await loginMobilestatus(request.agent(app), response.data.token)).body.data; assert.property(responseData, 'id'); delete responseData.id; assert.deepEqual(responseData, { name: '<NAME>', company: null, language: 'en', email: null, imageUrl: null, termsVersion: null, termsAcceptedAt: null }); }); test('Fail - 40021 - Invalid phone number', async function () { const phoneNumber = '+372519'; const pid = '51001091072'; const response = (await _loginMobileInit(request.agent(app), pid, phoneNumber, 400)).body; assert.equal(response.status.code, 40000); const expectedResponse = { status: { code: 40000, message: 'phoneNumber must contain of + and numbers(8-30)' } }; assert.deepEqual(response, expectedResponse); }); test('Fail - 40021 - Invalid PID', async function () { const phoneNumber = '+37260000007'; const pid = '1072'; const response = (await _loginMobileInit(request.agent(app), pid, phoneNumber, 400)).body; const expectedResponse = { status: { code: 40000, message: 'nationalIdentityNumber must contain of 11 digits' } }; assert.deepEqual(response, expectedResponse); }); test('Fail - 40022 - Mobile-ID user certificates are revoked or suspended for Estonian citizen', async function () { const phoneNumber = '+37200000266'; const pid = '60001019939'; const response = (await loginMobileInit(request.agent(app), pid, phoneNumber)).body.data; const responseData = (await _loginMobilestatus(request.agent(app), response.token, 400)).body; const expectedResponse = { status: { code: 40013, message: 'Mobile-ID functionality of the phone is not yet ready' } }; assert.deepEqual(responseData, expectedResponse); }); test('Fail - 40022 - Mobile-ID user certificates are revoked or suspended for Lithuanian citizen', async function () { const phoneNumber = '+37060000266'; const pid = '50001018832'; const response = (await loginMobileInit(request.agent(app), pid, phoneNumber)).body.data; const responseData = (await _loginMobilestatus(request.agent(app), response.token, 400)).body; const expectedResponse = { status: { code: 40013, message: 'Mobile-ID functionality of the phone is not yet ready' } }; assert.deepEqual(responseData, expectedResponse); }); test('Fail - 40023 - User certificate is not activated for Estonian citizen.', async function () { const phoneNumber = '+37200001'; const pid = '38002240211'; const response = (await loginMobileInit(request.agent(app), pid, phoneNumber)).body.data; const responseData = (await _loginMobilestatus(request.agent(app), response.token, 400)).body; const expectedResponse = { status: { code: 40013, message: 'Mobile-ID functionality of the phone is not yet ready' } }; assert.deepEqual(responseData, expectedResponse); }); test('Fail - 40023 - Mobile-ID is not activated for Lithuanian citizen', async function () { const phoneNumber = '+37060000001'; const pid = '51001091006'; const response = (await loginMobileInit(request.agent(app), pid, phoneNumber)).body.data; const responseData = (await _loginMobilestatus(request.agent(app), response.token, 400)).body; const expectedResponse = { status: { code: 40013, message: 'Mobile-ID functionality of the phone is not yet ready' } }; assert.deepEqual(responseData, expectedResponse); }); test.skip('Fail - 40024 - User certificate is suspended', async function () { //TODO: No test phone numbers available for errorcode = 304 - http://id.ee/?id=36373 }); test.skip('Fail - 40025 - User certificate is expired', async function () { //TODO: No test phone numbers available for errorcode = 305 - http://id.ee/?id=36373 }); }); suite('Status', function () { const phoneNumber = '+37200000766'; const pid = '60001019906'; suite('New User', function () { setup(async function () { return UserConnection .destroy({ where: { connectionId: UserConnection.CONNECTION_IDS.esteid, connectionUserId: ['PNOEE-' + pid] }, force: true }); }); test('Success - 20003 - created', async function () { this.timeout(35000); //eslint-disable-line no-invalid-this const agent = request.agent(app); const response = (await loginMobileInit(agent, pid, phoneNumber)).body.data; const userInfoFromMobiilIdStatusResponse = (await loginMobilestatus(agent, response.token)).body; assert.equal(userInfoFromMobiilIdStatusResponse.status.code, 20003); const userFromStatus = (await status(agent)).body.data; // Makes sure login succeeded AND consistency between /auth/status and /auth/mobile/status endpoints assert.deepEqual(userFromStatus, userInfoFromMobiilIdStatusResponse.data); assert.equal(userInfoFromMobiilIdStatusResponse.data.name, '<NAME>'); // Special check for encoding issues }); }); suite('Existing User', function () { const agent2 = request.agent(app); setup(async function () { const user = await userLib.createUser(agent2, null, null, null); return UserConnection .findOrCreate({ where: { connectionId: UserConnection.CONNECTION_IDS.esteid, connectionUserId: 'PNOEE-'+pid }, defaults: { userId: user.id, connectionId: UserConnection.CONNECTION_IDS.esteid, connectionUserId: 'PNOEE-'+pid } }); }); teardown(async function () { return UserConnection .destroy({ where: { connectionId: UserConnection.CONNECTION_IDS.esteid, connectionUserId: ['PNOEE-60001019906'] }, force: true }); }); test('Success - 20002 - existing User', async function () { this.timeout(35000); //eslint-disable-line no-invalid-this const response = (await loginMobileInit(agent2, pid, phoneNumber)).body.data; const userInfoFromMobiilIdStatusResponse = (await loginMobilestatus(agent2, response.token)).body; assert.equal(userInfoFromMobiilIdStatusResponse.status.code, 20002); const userFromStatus = (await status(agent2)).body.data; assert.deepEqual(userFromStatus, userInfoFromMobiilIdStatusResponse.data); }); }); }); }); suite('Smart-ID', function () { suite('Init', function () { let pid = '30303039914'; teardown(async function () { return UserConnection .destroy({ where: { connectionId: UserConnection.CONNECTION_IDS.smartid, connectionUserId: ['PNOEE-' + pid] // Remove the good user so that test would run multiple times. Also other tests use same numbers }, force: true }); }); test('Success - 20001 - Estonian PID', async function () { this.timeout(5000); //eslint-disable-line no-invalid-this const response = (await loginSmartIdInit(request.agent(app), pid)).body; assert.equal(response.status.code, 20001); assert.match(response.data.challengeID, /[0-9]{4}/); const token = response.data.token; assert.isNotNull(token); const tokenData = jwt.verify(token, config.session.publicKey, {algorithms: [config.session.algorithm]}); const loginMobileFlowData = objectEncrypter(config.session.secret).decrypt(tokenData.sessionDataEncrypted); assert.property(loginMobileFlowData, 'sessionId'); assert.property(loginMobileFlowData, 'sessionHash'); assert.property(loginMobileFlowData, 'challengeID'); assert.equal(loginMobileFlowData.challengeID, response.data.challengeID); }); test('Fail - 40400 - Invalid PID', async function () { pid = '1010101'; const response = (await _loginSmartIdInit(request.agent(app), pid, 404)).body; const expectedResponse = { status: { code: 40400, message: 'Not Found' } }; assert.deepEqual(response, expectedResponse); }); }); suite('Status', function () { let pid = '30303039914'; suite('New User', function () { teardown(async function () { return UserConnection .destroy({ where: { connectionId: UserConnection.CONNECTION_IDS.smartid, connectionUserId: ['PNOEE-' + pid] // Remove the good user so that test would run multiple times. Also other tests use same numbers }, force: true }); }); test('Success - 20003 - created', async function () { this.timeout(40000); //eslint-disable-line no-invalid-this const agent = request.agent(app); const initResponse = (await loginSmartIdInit(agent, pid)).body.data; const userInfoFromSmartIdStatusResponse = (await loginSmartIdstatus(agent, initResponse.token)).body; assert.equal(userInfoFromSmartIdStatusResponse.status.code, 20003); const userFromStatus = (await status(agent)).body.data; assert.deepEqual(userFromStatus, userInfoFromSmartIdStatusResponse.data); assert.equal('Qualified Ok1 Testnumber', userInfoFromSmartIdStatusResponse.data.name); // Special check for encoding issues }); test('Fail - 40010 - User refused', async function () { this.timeout(40000); //eslint-disable-line no-invalid-this pid = '30403039939'; const agent = request.agent(app); const initResponse = (await loginSmartIdInit(agent, pid)).body.data; const smartIdStatusResponse = (await loginSmartIdstatus(agent, initResponse.token, 2000)).body; const expectedResponse = { status: { code: 40010, message: 'User refused' } }; assert.deepEqual(expectedResponse, smartIdStatusResponse); }); test('Fail - 40011 - Timeout', async function () { this.timeout(120000); //eslint-disable-line no-invalid-this pid = '30403039983' const agent = request.agent(app); const initResponse = (await loginSmartIdInit(agent, pid)).body.data; const smartIdStatusResponse = (await loginSmartIdstatus(agent, initResponse.token, 5000)).body; const expectedResponse = { status: { code: 40011, message: 'The transaction has expired' } }; assert.deepEqual(expectedResponse, smartIdStatusResponse); }); }); suite('Existing User', function () { const agent2 = request.agent(app); test('Success - 20002 - existing User', async function () { this.timeout(30000); //eslint-disable-line no-invalid-this pid = '30303039914'; const user = await userLib.createUser(agent2, null, null, null); await UserConnection .findOrCreate({ where: { connectionId: UserConnection.CONNECTION_IDS.smartid, connectionUserId: 'PNOEE-'+pid }, defaults: { userId: user.id, connectionId: UserConnection.CONNECTION_IDS.smartid, connectionUserId: 'PNOEE-'+pid } }); const initResponse = (await loginSmartIdInit(agent2, pid)).body.data; const smartIdStatusResponse = (await loginSmartIdstatus(agent2, initResponse.token, 5000)).body; assert.equal(smartIdStatusResponse.status.code, 20002); const userFromStatus = (await status(agent2)).body.data; assert.deepEqual(userFromStatus, smartIdStatusResponse.data); }); }); }); }); }); suite('Logout', function () { test('Success', async function () { const agent = request.agent(app); const email = 'test_' + new Date().getTime() + '@test.ee'; const password = '<PASSWORD>'; const user = await userLib.createUserAndLogin(agent, email, password, null); const userFromStatus = (await status(agent)).body.data; let expectedUser = user.toJSON(); expectedUser.termsVersion = user.termsVersion; expectedUser.termsAcceptedAt = user.termsAcceptedAt; assert.deepEqual(expectedUser, userFromStatus); await logout(agent); const statusResponse = (await _status(agent, 401)).body; const expectedBody = { status: { code: 40100, message: 'Unauthorized' } }; assert.deepEqual(statusResponse, expectedBody); }); }); suite('Signup', function () { const agent = request.agent(app); test('Success', async function () { const email = 'test_' + new Date().getTime() + '@test.ee'; const password = '<PASSWORD>'; const user = (await signup(agent, email, password, null)).body.data; assert.equal(user.email, email); assert.property(user, 'id'); assert.notProperty(user, 'password'); assert.notProperty(user, 'emailIsVerified'); assert.notProperty(user, 'emailVerificationCode'); assert.notProperty(user, 'passwordResetCode'); assert.notProperty(user, 'createdAt'); assert.notProperty(user, 'updatedAt'); assert.notProperty(user, 'deletedAt'); }); test('Success - invited user - User with NULL password in DB should be able to sign up', async function () { // Users with NULL password are created on User invite const agent = request.agent(app); const email = 'test_' + new Date().getTime() + '_invited<EMAIL>'; const password = '<PASSWORD>'; const language = 'et'; const user = await User.create({ email: email, password: <PASSWORD>, name: email, source: User.SOURCES.citizenos }); const userSignedup = (await signup(agent, user.email, password, language)).body.data; assert.equal(userSignedup.email, email); assert.equal(userSignedup.language, user.language); }); test('Fail - 40000 - email cannot be null', async function () { const email = null; const password = '<PASSWORD>'; const signupResult = (await _signup(agent, email, password, null, 400)).body; const expected = { status: { code: 40000 }, errors: { email: 'Invalid email.' } }; assert.deepEqual(signupResult, expected); }); test('Fail - 40000 - invalid email', async function () { const email = 'this is an invalid email'; const password = '<PASSWORD>'; const signupResult = (await _signup(agent, email, password, null, 400)).body; const expected = { status: { code: 40000 }, errors: { email: 'Invalid email.' } }; assert.deepEqual(signupResult, expected); }); test('Fail - 40000 - missing password', async function () { const email = 'test_' + new Date().getTime() + '@test.ee'; const password = null; const signupResult = (await _signup(agent, email, password, null, 400)).body; const expected = { status: { code: 40000 }, errors: { password: 'Password must be at least 6 character long, containing at least 1 digit, 1 lower and upper case character.' } }; assert.deepEqual(signupResult, expected); }); test('Fail - 40000 - invalid password', async function () { const email = 'test_' + new Date().getTime() + '@test.ee'; const password = '<PASSWORD>'; const signupResult = (await _signup(agent, email, password, null, 400)).body; const expected = { status: { code: 40000 }, errors: { password: 'Password must be at least 6 character long, containing at least 1 digit, 1 lower and upper case character.' } }; assert.deepEqual(signupResult, expected); }); test('Fail - 40000 - invalid password and invalid email', async function () { const email = 'notvalidatall'; const password = '<PASSWORD>'; const signupResult = (await _signup(agent, email, password, null, 400)).body; const expected = { status: { code: 40000 }, errors: { email: "Invalid email.", password: 'Password must be at least 6 character long, containing at least 1 digit, 1 lower and upper case character.' } }; assert.deepEqual(signupResult, expected); }); test('Fail - 40001 - email already in use', async function () { const email = 'test_emailinuse_' + new Date().getTime() + '@test.ee'; const password = '<PASSWORD>'; await signup(agent, email, password, null); const signupResult = (await _signup(agent, email, password, null, 400)).body; const expected = { status: { code: 40001 }, errors: { email: 'The email address is already in use.' } }; assert.deepEqual(signupResult, expected); }); }); suite('Verify', function () { const agent = request.agent(app); // Success is already tested as a part of 'Login' suite. test.skip('Success - signup sets redirectSuccess and verify should redirect to it', async function () { }); test('Fail - invalid emailVerificationCode', async function () { return agent .get('/api/auth/verify/thisCodeDoesNotExist') .expect(302) .expect('Location', urlLib.getFe('/', null, {error: 'emailVerificationFailed'})); }); }); suite('Password', function () { suite('Set', function () { const agent = request.agent(app); const email = 'test_' + new Date().getTime() + '@test.ee'; const password = '<PASSWORD>'; const newPassword = '<PASSWORD>'; suiteSetup(async function () { return userLib.createUserAndLogin(agent, email, password, null); }); test('Success', async function () { await passwordSet(agent, password, newPassword); const loginResult = (await login(request.agent(app), email, newPassword)).body; assert.equal(loginResult.status.code, 20000); assert.equal(loginResult.data.email, email); }); test('Fail - invalid new password which does not contain special characters needed', async function () { const currentPassword = <PASSWORD>; const invalidNewPassword = '<PASSWORD>'; const resultBody = (await _passwordSet(agent, currentPassword, invalidNewPassword, 400)).body; const expected = { status: { code: 40000 }, errors: { password: 'Password must be at least 6 character long, containing at least 1 digit, 1 lower and upper case character.' } }; assert.deepEqual(resultBody, expected); }); test('Fail - invalid old password', async function () { const invalidCurrentPassword = '<PASSWORD>'; const validNewPassword = '<PASSWORD>'; const resultBody = (await _passwordSet(agent, invalidCurrentPassword, validNewPassword, 400)).body; assert.equal(resultBody.status.message, 'Invalid email or new password.'); }); test('Fail - Unauthorized', async function () { const agent = request.agent(app); await _passwordSet(agent, 'oldPassSomething', 'newPassSomething', 401); }); }); suite('Reset', function () { const agent = request.agent(app); const email = 'test_reset_' + new Date().getTime() + '@test.ee'; const password = '<PASSWORD>'; const language = 'et'; suiteSetup(async function () { return userLib.createUser(agent, email, password, language); }); suite('Send', function () { test('Success', async function () { await passwordResetSend(agent, email); const user = await User.findOne({ where: db.where(db.fn('lower', db.col('email')), db.fn('lower', email)) }); const passwordResetCode = user.passwordResetCode; assert.property(user, 'passwordResetCode'); assert.isNotNull(passwordResetCode); assert.lengthOf(passwordResetCode, 36); }); test('Fail - 40000 - missing email', async function () { const resetBody = (await _passwordResetSend(agent, null, 400)).body; const expectedBody = { status: { code: 40000 }, errors: { email: 'Invalid email' } }; assert.deepEqual(resetBody, expectedBody); }); test('Fail - 40001 - non existent email', async function () { const resetBody = (await _passwordResetSend(agent, '<EMAIL>', 400)).body; const expectedBody = { status: { code: 40002 }, errors: { email: 'Account with this email does not exist.' } }; assert.deepEqual(resetBody, expectedBody); }); }); suite('Complete', function () { let passwordResetCode; suiteSetup(async function () { await passwordResetSend(agent, email); const user = await User.findOne({ where: db.where(db.fn('lower', db.col('email')), db.fn('lower', email)) }); passwordResetCode = user.passwordResetCode; }); test('Fail - invalid reset code', async function () { const resBody = (await _passwordResetComplete(agent, email, password, uuid.v4(), 400)).body assert.equal(resBody.status.message, 'Invalid email, password or password reset code.'); }); test('Fail - missing reset code', async function () { const resBody = (await _passwordResetComplete(agent, email, password, null, 400)).body assert.equal(resBody.status.message, 'Invalid email, password or password reset code.'); }); test('Fail - invalid password', async function () { const resBody = (await _passwordResetComplete(agent, email, 'thispassisnotinvalidformat', passwordResetCode, 400)).body const expected = { status: { code: 40000 }, errors: { password: 'Password must be at least 6 character long, containing at least 1 digit, 1 lower and upper case character.' } }; assert.deepEqual(resBody, expected); }); test('Fail - invalid email', async function () { const resBody = (await _passwordResetComplete(agent, '<EMAIL>', password, passwordResetCode, 400)).body assert.equal(resBody.status.message, 'Invalid email, password or password reset code.'); }); test('Fail - no password reset has been requested by user (passwordResetCode is null)', async function () { const agent = request.agent(app); const email = 'test_' + new Date().getTime() + '@test.ee'; const password = '<PASSWORD>'; await signup(agent, email, password, null); const resBody = (await _passwordResetComplete(agent, email, password, null, 400)).body assert.equal(resBody.status.message, 'Invalid email, password or password reset code.'); }); test('Success', async function () { await passwordResetComplete(agent, email, password, passwordResetCode); const loginRes = await login(agent, email, password); assert.equal(email, loginRes.body.data.email); const user = await User.findOne({ where: db.where(db.fn('lower', db.col('email')), db.fn('lower', email)) }); assert.notEqual(user.passwordResetCode, passwordResetCode); }); }); }); }); suite('Status', function () { const agent = request.agent(app); const email = 'test_status_' + new Date().getTime() + '@test.ee'; const password = '<PASSWORD>'; suiteSetup(async function () { return userLib.createUser(agent, email, password, null); }); test('Success', async function () { await login(agent, email, password); const user = (await status(agent)).body.data; assert.equal(user.email, email); }); test('Fail - Unauthorized', async function () { await _status(request.agent(app), 401); }); test('Fail - Unauthorized - JWT token expired', async function () { const agent = request.agent(app); const path = '/api/auth/status'; const token = jwt.sign({ id: '<PASSWORD>', scope: 'all' }, config.session.privateKey, { expiresIn: '.1ms', algorithm: config.session.algorithm }); const res = await agent .get(path) .set('Content-Type', 'application/json') .set('Authorization', 'Bearer ' + token) .expect(401) .expect('Content-Type', /json/); const expectedResponse = { status: { code: 40100, message: 'JWT token has expired' } }; assert.deepEqual(res.body, expectedResponse); }); }); suite('Open ID', function () { const TEST_RESPONSE_TYPE = 'id_token token'; const TEST_PARTNER = { id: '<PASSWORD>', website: 'https://citizenospartner.ee', redirectUriRegexp: '^https:\\/\\/([^\\.]*\\.)?citizenospartner.ee(:[0-9]{2,5})?\\/.*' }; const TEST_CALLBACK_URI = 'https://dev.citizenospartner.ee/callback'; const agent = request.agent(app); suiteSetup(async function () { return shared .syncDb(); }); suite('Authorize', function () { suiteSetup(async function () { return Partner .upsert(TEST_PARTNER); }); test('Success - 302 - User is logged in to CitizenOS AND has agreed before -> redirect_uri', async function () { const agent = request.agent(app); const user = await userLib.createUserAndLogin(agent, null, null, null); await UserConsent.create({ userId: user.id, partnerId: TEST_PARTNER.id }); const state = '123213asdasas1231'; const authRes = await openIdAuthorize(agent, TEST_RESPONSE_TYPE, TEST_PARTNER.id, TEST_CALLBACK_URI, 'openid', state, 'dasd12312sdasAA'); const uriParts = authRes.headers.location.split('#'); assert.equal(uriParts[0], TEST_CALLBACK_URI); const hashParams = uriParts[1]; const matchExp = new RegExp('^access_token=[^&]*&id_token=[^&]*&state=' + state + '$'); assert.match(hashParams, matchExp); }); test('Success - 302 - User is logged in to CitizenOS AND has NOT agreed before -> /consent -> redirect_uri', async function () { const agent = request.agent(app); await userLib.createUserAndLogin(agent, null, null, null); const authRes = await openIdAuthorize(agent, TEST_RESPONSE_TYPE, TEST_PARTNER.id, TEST_CALLBACK_URI, 'openid', '123213asdasas1231', 'dasd12312sdasAA'); const expectedUrl = urlLib.getFe('/:language/partners/:partnerId/consent', { partnerId: TEST_PARTNER.id, language: 'en' }); assert.equal(authRes.headers.location, expectedUrl); }); test.skip('Success - 302 - User is NOT logged in AND has agreed before -> /login -> redirect_uri', async function () { }); test.skip('Success - 302 - User is NOT logged in AND has not agreed before -> /login -> /consent -> redirect_uri', async function () { }); test.skip('Success - 302 - User is NOT registered -> /register -> /verify -> /consent -> redirect_uri', async function () { }); test('Fail - 400 - Invalid or missing "client_id" parameter value', async function () { const authRes = await _openIdAuthorize(agent, null, null, null, null, null, null, 400); assert.equal(authRes.text, 'Invalid or missing "client_id" parameter value.'); }); test('Fail - 400 - Invalid partner configuration. Please contact system administrator.', async function () { const authRes = await _openIdAuthorize(agent, null, uuid.v4(), null, null, null, null, 400); assert.equal(authRes.text, 'Invalid partner configuration. Please contact system administrator.'); }); test('Fail - 400 - Invalid referer. Referer header does not match expected partner URI scheme.', async function () { const res = await agent .get('/api/auth/openid/authorize') .set('Referer', 'https://invalidtest.ee/invalid/referer') .query({ client_id: TEST_PARTNER.id }) .expect(400); assert.equal(res.text, 'Invalid referer. Referer header does not match expected partner URI scheme.'); }); test('Fail - 400 - Invalid or missing "redirect_uri" parameter value.', async function () { const authRes = await _openIdAuthorize(agent, null, TEST_PARTNER.id, 'https://invalidtest.ee/callback', null, null, null, 400); assert.equal(authRes.text, 'Invalid or missing "redirect_uri" parameter value.'); }); test('Fail - 400 - Invalid "redirect_uri". Cannot contain fragment component "#".', async function () { const authRes = await _openIdAuthorize(agent, null, TEST_PARTNER.id, TEST_CALLBACK_URI + '#', null, null, null, 400); assert.equal(authRes.text, 'Invalid "redirect_uri". Cannot contain fragment component "#".'); }); test('Fail - 302 - Unsupported "response_type" parameter value. Only "token id_token" is supported.', async function () { const authRes = await openIdAuthorize(agent, 'code', TEST_PARTNER.id, TEST_CALLBACK_URI, null, null, null); assert.equal(authRes.headers.location, TEST_CALLBACK_URI + '#error=unsupported_response_type&error_description=Unsupported%20%22response_type%22%20parameter%20value.%20Only%20%22token%20id_token%22%20is%20supported.'); }); test('Fail - 302 - Unsupported "scope" parameter value. Only "openid" is supported.', async function () { const authRes = await openIdAuthorize(agent, TEST_RESPONSE_TYPE, TEST_PARTNER.id, TEST_CALLBACK_URI, 'invalid', null, null); assert.equal(authRes.headers.location, TEST_CALLBACK_URI + '#error=invalid_scope&error_description=Unsupported%20%22scope%22%20parameter%20value.%20Only%20%22openid%22%20is%20supported.'); }); test('Fail - 302 - Invalid or missing "nonce" parameter value. "nonce" must be a random string with at least 14 characters of length.', async function () { const authRes = await openIdAuthorize(agent, TEST_RESPONSE_TYPE, TEST_PARTNER.id, TEST_CALLBACK_URI, 'openid', null, null); assert.equal(authRes.headers.location, TEST_CALLBACK_URI + '#error=invalid_request&error_description=Invalid%20or%20missing%20%22nonce%22%20parameter%20value.%20%22nonce%22%20must%20be%20a%20random%20string%20with%20at%20least%2014%20characters%20of%20length.&error_uri=http%3A%2F%2Fopenid.net%2Fspecs%2Fopenid-connect-implicit-1_0.html%23RequestParameters'); }); }); }); });
1.617188
2
example/src/store/sagas/usersSaga.js
rasha08/redux-saga-combine-watchers
0
895
import { put, takeLatest } from 'redux-saga/effects'; import {setUsers} from "../actions"; import {GET_USERS} from "../types"; import {apiUrl} from "../../config"; const usersEndpoint = 'users?_format=json&access-token=<KEY>' function* fetchUsers() { const users = yield fetch(`${apiUrl}/${usersEndpoint}`).then(res => res.json()); yield put(setUsers(users.result)) } function* getUsersWatcher() { yield takeLatest(GET_USERS, fetchUsers) } export const userWatchers = [getUsersWatcher]
1.140625
1
application/routes/home/react/server.js
prizerok/test01
0
903
export default function(req, res) { res.setData("a", 222); res.end(); }
0.386719
0
src/js/index.js
paggcerto-sa/paggcerto-lightbox
7
911
import Lightbox from './lightbox' import LightboxOptions from './lightbox-options' const paggcerto = { async lightbox(options) { options = new LightboxOptions(options).asObject() await new Lightbox(options).initialize() } } export default paggcerto
0.546875
1
Employe portal/modal/comSchema.js
boby-tudu-au6/Projects
4
919
mongoose = require("mongoose") Schema = mongoose.Schema; comSchema = Schema({ name:{ type:String, required:true }, owner: { type: mongoose.ObjectId, ref: "users" }, started: { type: Date, default: Date.now }, emplyees: { type: Array } }) Companies = mongoose.model("companies", comSchema); module.exports = Companies
1.046875
1
www/dashboard_iot/show_wtrl/app.js
dookda/ecc_mis
1
927
var map = L.map('map', { center: [13.335017, 101.719808], zoom: 7, zoomControl: false }); var osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', lyr: 'basemap' }); var CartoDB_DarkMatter = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>', subdomains: 'abcd', maxZoom: 19, lyr: 'basemap' }); var CartoDB_Positron = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>', subdomains: 'abcd', maxZoom: 19, lyr: 'basemap' }); const grod = L.tileLayer('https://{s}.google.com/vt/lyrs=r&x={x}&y={y}&z={z}', { maxZoom: 20, subdomains: ['mt0', 'mt1', 'mt2', 'mt3'], lyr: 'basemap' }); const ghyb = L.tileLayer('https://{s}.google.com/vt/lyrs=y,m&x={x}&y={y}&z={z}', { maxZoom: 20, subdomains: ['mt0', 'mt1', 'mt2', 'mt3'], lyr: 'basemap' }); const tam = L.tileLayer.wms("https://rti2dss.com:8443/geoserver/th/wms?", { layers: "th:tambon_4326", format: "image/png", transparent: true, CQL_FILTER: 'pro_code=20 OR pro_code=21 OR pro_code=22 OR pro_code=23 OR pro_code=24 OR pro_code=25 OR pro_code=26 OR pro_code=27' }); const amp = L.tileLayer.wms("https://rti2dss.com:8443/geoserver/th/wms?", { layers: "th:amphoe_4326", format: "image/png", transparent: true, CQL_FILTER: 'pro_code=20 OR pro_code=21 OR pro_code=22 OR pro_code=23 OR pro_code=24 OR pro_code=25 OR pro_code=26 OR pro_code=27' }); const pro = L.tileLayer.wms("https://rti2dss.com:8443/geoserver/th/wms?", { layers: "th:province_4326", format: "image/png", transparent: true, CQL_FILTER: 'pro_code=20 OR pro_code=21 OR pro_code=22 OR pro_code=23 OR pro_code=24 OR pro_code=25 OR pro_code=26 OR pro_code=27' }); let mk1 = L.marker([12.8661616, 100.9989804]).bindPopup('อบต.ห้วยใหญ่3'), mk2 = L.marker([12.848099999999983, 100.95313000000002]).bindPopup('อบต.ห้วยใหญ่2'), mk3 = L.marker([12.846510200000028, 100.9376361]).bindPopup('อบต.ห้วยใหญ่1'), mk4 = L.marker([12.694406999999996, 101.44470699999997]).bindPopup('อบต.สำนักทอง1'), mk5 = L.marker([12.703484000000008, 101.468717]).bindPopup('อบต.สำนักทอง2'), mk6 = L.marker([12.70139960000001, 101.49543049999]).bindPopup('อบต.กะเฉด3'), mk7 = L.marker([12.985111299999994, 101.6776677]).bindPopup('อบต.เขาชะเมา1'), mk8 = L.marker([12.909515899999995, 101.71460159999998]).bindPopup('อบต.น้ำเป็น2'), mk9 = L.marker([12.836749900000017, 101.73254899999998]).bindPopup('อบต.น้ำเป็น3'); var sensor = L.layerGroup([mk1, mk2, mk3, mk4, mk5, mk6, mk7, mk8, mk9]); var baseMap = { "แผนที่ OSM": osm, "แผนที่ CartoDB": CartoDB_Positron, "แผนที่ถนน": grod, "แผนที่ภาพถ่าย": ghyb.addTo(map) } var overlayMap = { "ขอบเขตตำบล": tam.addTo(map), "ขอบเขตอำเภอ": amp.addTo(map), "ขอบเขตจังหวัด": pro.addTo(map), "ตำแหน่ง sensor": sensor.addTo(map) } L.control.layers(baseMap, overlayMap).addTo(map) // L.control.zoom({ position: 'bottomright' }).addTo(map); let onLocationFound = () => { }; map.on("locationfound", onLocationFound); // map.on("locationerror", onLocationError); // map.locate({ setView: true, maxZoom: 19 }); var lc = L.control.locate({ position: 'topleft', strings: { title: "" }, locateOptions: { enableHighAccuracy: true, } }).addTo(map); lc.start(); var chart; let showChart = async (station, param, unit, dat) => { Highcharts.chart(param, { chart: { type: 'spline', animation: Highcharts.svg, // marginRight: 100, events: { load: function () { var series = this.series[0]; setInterval(async () => { await axios.post("https://eec-onep.soc.cmu.ac.th/api/wtrl-api.php", { station: station, param: param, limit: 1 }).then((r) => { console.log(r); let x = (new Date()).getTime(); let y = Number(r.data.data[0].val); return series.addPoint([x, y], true, true); }) }, 10000); } }, zoomType: 'x' }, time: { useUTC: false }, title: false, accessibility: { announceNewData: { enabled: true, minAnnounceInterval: 15000, announcementFormatter: function (allSeries, newSeries, newPoint) { if (newPoint) { return 'New point added. Value: ' + newPoint.y; } return false; } } }, xAxis: { type: 'datetime', tickPixelInterval: 120, minorTickInterval: 'auto', startOnTick: false, endOnTick: false }, yAxis: { title: { text: unit }, // min: -5, // max: 5, plotLines: [{ value: 0, width: 1, color: '#808080' }], tickInterval: 1 }, tooltip: { headerFormat: '<b>{series.name}</b><br/>', // pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f} cm' pointFormat: 'เวลา {point.x:%H:%M:%S} น.<br/>{point.y:.2f} cm' }, legend: { enabled: false }, exporting: { enabled: false }, plotOptions: { series: { marker: { enabled: false } } }, series: [{ name: param, data: dat }] }) } $("#station").on("change", async function () { let station = this.value; let deep = "deep"; let humidity = "humidity"; let temperature = "temperature"; await axios.post("https://eec-onep.soc.cmu.ac.th/api/wtrl-api.php", { station: station, param: deep, limit: 15 }).then(async (r) => { console.log(r); let data = []; let time = (new Date()).getTime(); r.data.data.map((i, k) => { data.push({ x: time + k * 500, y: Number(i.val) }); }) showChart(station, deep, "cm", data) }) await axios.post("https://eec-onep.soc.cmu.ac.th/api/wtrl-api.php", { station: station, param: humidity, limit: 15 }).then(async (r) => { console.log(r); let data = []; let time = (new Date()).getTime(); r.data.data.map((i, k) => { data.push({ x: time + k * 500, y: Number(i.val) }); }) showChart(station, humidity, "%", data) }) await axios.post("https://eec-onep.soc.cmu.ac.th/api/wtrl-api.php", { station: station, param: temperature, limit: 15 }).then((r) => { console.log(r); let data = []; let time = (new Date()).getTime(); r.data.data.map((i, k) => { data.push({ x: time + k * 500, y: Number(i.val) }); }) showChart(station, temperature, "°C", data) }) })
1.234375
1
native-base-theme/components/ListItem.js
Lambda-School-Labs/council-fe
0
935
// @flow import { Platform, PixelRatio } from 'react-native' import pickerTheme from './Picker' import variables, { platform, PLATFORM } from './../variables/commonColor' export default _ => { const { ui, text } = variables.councils const selectedStyle = { 'NativeBase.Text': { color: variables.listItemSelected }, 'NativeBase.Icon': { color: variables.listItemSelected } }; return { 'NativeBase.InputGroup': { 'NativeBase.Icon': { paddingRight: 5 }, 'NativeBase.IconNB': { paddingRight: 5 }, 'NativeBase.Input': { paddingHorizontal: 5 }, flex: 1, borderWidth: null, margin: -10, borderBottomColor: 'transparent' }, '.searchBar': { 'NativeBase.Item': { 'NativeBase.Icon': { backgroundColor: 'transparent', color: variables.dropdownLinkColor, fontSize: platform === PLATFORM.IOS ? variables.iconFontSize - 10 : variables.iconFontSize - 5, alignItems: 'center', marginTop: 2, paddingRight: 8 }, 'NativeBase.IconNB': { backgroundColor: 'transparent', color: null, alignSelf: 'center' }, 'NativeBase.Input': { alignSelf: 'center' }, alignSelf: 'center', alignItems: 'center', justifyContent: 'flex-start', flex: 1, height: platform === PLATFORM.IOS ? 30 : 40, borderColor: 'transparent', backgroundColor: '#fff', borderRadius: 5 }, 'NativeBase.Button': { '.transparent': { 'NativeBase.Text': { fontWeight: '500' }, paddingHorizontal: null, paddingLeft: platform === PLATFORM.IOS ? 10 : null }, paddingHorizontal: platform === PLATFORM.IOS ? undefined : null, width: platform === PLATFORM.IOS ? undefined : 0, height: platform === PLATFORM.IOS ? undefined : 0 }, backgroundColor: variables.toolbarInputColor, padding: 10, marginLeft: null }, 'NativeBase.CheckBox': { marginLeft: -10, marginRight: 10 }, '.first': { '.itemHeader': { paddingTop: variables.listItemPadding + 3 } }, '.itemHeader': { '.first': { paddingTop: variables.listItemPadding + 3 }, borderBottomWidth: platform === PLATFORM.IOS ? variables.borderWidth : null, marginLeft: null, padding: variables.listItemPadding, paddingLeft: variables.listItemPadding + 5, paddingTop: platform === PLATFORM.IOS ? variables.listItemPadding + 25 : undefined, paddingBottom: platform === PLATFORM.ANDROID ? variables.listItemPadding + 20 : undefined, flexDirection: 'row', borderColor: variables.listBorderColor, 'NativeBase.Text': { fontSize: 14, color: platform === PLATFORM.IOS ? undefined : variables.listNoteColor } }, '.itemDivider': { borderBottomWidth: null, marginLeft: null, padding: variables.listItemPadding, paddingLeft: variables.listItemPadding + 5, backgroundColor: variables.listDividerBg, flexDirection: 'row', borderColor: variables.listBorderColor }, '.selected': { 'NativeBase.Left': { ...selectedStyle }, 'NativeBase.Body': { ...selectedStyle }, 'NativeBase.Right': { ...selectedStyle }, ...selectedStyle }, 'NativeBase.Left': { 'NativeBase.Body': { 'NativeBase.Text': { '.note': { color: variables.listNoteColor, fontWeight: '200' }, fontWeight: '600' }, marginLeft: 10, alignItems: null, alignSelf: null }, 'NativeBase.Icon': { width: variables.iconFontSize - 10, fontSize: variables.iconFontSize - 10 }, 'NativeBase.IconNB': { width: variables.iconFontSize - 10, fontSize: variables.iconFontSize - 10 }, 'NativeBase.Text': { alignSelf: 'center' }, flexDirection: 'row' }, 'NativeBase.Body': { 'NativeBase.Text': { marginHorizontal: variables.listItemPadding, '.note': { color: variables.listNoteColor, fontWeight: '200' } }, alignSelf: null, alignItems: null }, 'NativeBase.Right': { 'NativeBase.Badge': { alignSelf: null }, 'NativeBase.PickerNB': { 'NativeBase.Button': { marginRight: -15, 'NativeBase.Text': { color: variables.topTabBarActiveTextColor } } }, 'NativeBase.Button': { alignSelf: null, '.transparent': { 'NativeBase.Text': { color: variables.topTabBarActiveTextColor } } }, 'NativeBase.Icon': { alignSelf: null, fontSize: variables.iconFontSize - 8, color: '#c9c8cd' }, 'NativeBase.IconNB': { alignSelf: null, fontSize: variables.iconFontSize - 8, color: '#c9c8cd' }, 'NativeBase.Text': { '.note': { color: variables.listNoteColor, fontWeight: '200' }, alignSelf: null }, 'NativeBase.Thumbnail': { alignSelf: null }, 'NativeBase.Image': { alignSelf: null }, 'NativeBase.Radio': { alignSelf: null }, 'NativeBase.Checkbox': { alignSelf: null }, 'NativeBase.Switch': { alignSelf: null }, padding: null, flex: 0.28 }, 'NativeBase.Text': { '.note': { color: variables.listNoteColor, fontWeight: '200' }, alignSelf: 'center' }, '.last': { marginLeft: -(variables.listItemPadding + 5), paddingLeft: (variables.listItemPadding + 5) * 2, top: 1 }, '.avatar': { 'NativeBase.Left': { flex: 0, alignSelf: 'flex-start', paddingTop: 14 }, 'NativeBase.Body': { 'NativeBase.Text': { marginLeft: null, color: text.darkGreenBlue }, flex: 1, paddingVertical: variables.listItemPadding, borderBottomWidth: 0, borderColor: variables.listBorderColor, marginLeft: variables.listItemPadding + 5, }, 'NativeBase.Right': { 'NativeBase.Text': { '.note': { fontSize: variables.noteFontSize - 2 } }, flex: 0, paddingRight: variables.listItemPadding + 5, alignSelf: 'stretch', paddingVertical: variables.listItemPadding, borderBottomWidth: 0, borderColor: variables.listBorderColor }, '.noBorder': { 'NativeBase.Body': { borderBottomWidth: null }, 'NativeBase.Right': { borderBottomWidth: null } }, borderBottomWidth: null, paddingVertical: null, paddingRight: null }, '.thumbnail': { 'NativeBase.Left': { flex: 0 }, 'NativeBase.Body': { 'NativeBase.Text': { marginLeft: null }, flex: 1, paddingVertical: variables.listItemPadding + 8, borderBottomWidth: variables.borderWidth, borderColor: variables.listBorderColor, marginLeft: variables.listItemPadding + 5 }, 'NativeBase.Right': { 'NativeBase.Button': { '.transparent': { 'NativeBase.Text': { fontSize: variables.listNoteSize, color: variables.sTabBarActiveTextColor } }, height: null }, flex: 0, justifyContent: 'center', alignSelf: 'stretch', paddingRight: variables.listItemPadding + 5, paddingVertical: variables.listItemPadding + 5, borderBottomWidth: variables.borderWidth, borderColor: variables.listBorderColor }, '.noBorder': { 'NativeBase.Body': { borderBottomWidth: null }, 'NativeBase.Right': { borderBottomWidth: null } }, borderBottomWidth: null, paddingVertical: null, paddingRight: null }, '.icon': { '.last': { 'NativeBase.Body': { borderBottomWidth: null }, 'NativeBase.Right': { borderBottomWidth: null }, borderBottomWidth: variables.borderWidth, borderColor: variables.listBorderColor }, 'NativeBase.Left': { 'NativeBase.Button': { 'NativeBase.IconNB': { marginHorizontal: null, fontSize: variables.iconFontSize - 5 }, 'NativeBase.Icon': { marginHorizontal: null, fontSize: variables.iconFontSize - 8 }, alignSelf: 'center', height: 29, width: 29, borderRadius: 6, paddingVertical: null, paddingHorizontal: null, alignItems: 'center', justifyContent: 'center' }, 'NativeBase.Icon': { width: variables.iconFontSize - 5, fontSize: variables.iconFontSize - 2 }, 'NativeBase.IconNB': { width: variables.iconFontSize - 5, fontSize: variables.iconFontSize - 2 }, paddingRight: variables.listItemPadding + 5, flex: 0, height: 44, justifyContent: 'center', alignItems: 'center' }, 'NativeBase.Body': { 'NativeBase.Text': { marginLeft: null, fontSize: 17 }, flex: 1, height: 44, justifyContent: 'center', borderBottomWidth: 1 / PixelRatio.getPixelSizeForLayoutSize(1), borderColor: variables.listBorderColor }, 'NativeBase.Right': { 'NativeBase.Text': { textAlign: 'center', color: '#8F8E95', fontSize: 17 }, 'NativeBase.IconNB': { color: '#C8C7CC', fontSize: variables.iconFontSize - 10, alignSelf: 'center', paddingLeft: 10, paddingTop: 3 }, 'NativeBase.Icon': { color: '#C8C7CC', fontSize: variables.iconFontSize - 10, alignSelf: 'center', paddingLeft: 10, paddingTop: 3 }, 'NativeBase.Switch': { marginRight: Platform.OS === PLATFORM.IOS ? undefined : -5, alignSelf: null }, 'NativeBase.PickerNB': { ...pickerTheme() }, flexDirection: 'row', alignItems: 'center', flex: 0, alignSelf: 'stretch', height: 44, justifyContent: 'flex-end', borderBottomWidth: 1 / PixelRatio.getPixelSizeForLayoutSize(1), borderColor: variables.listBorderColor, paddingRight: variables.listItemPadding + 5 }, '.noBorder': { 'NativeBase.Body': { borderBottomWidth: null }, 'NativeBase.Right': { borderBottomWidth: null } }, borderBottomWidth: null, paddingVertical: null, paddingRight: null, height: 44, justifyContent: 'center' }, '.noBorder': { borderBottomWidth: null }, '.noIndent': { marginLeft: null, padding: variables.listItemPadding, paddingLeft: variables.listItemPadding + 6 }, alignItems: 'center', flexDirection: 'row', paddingRight: variables.listItemPadding + 6, paddingVertical: variables.listItemPadding + 3, marginLeft: variables.listItemPadding + 6, borderBottomWidth: 1 / PixelRatio.getPixelSizeForLayoutSize(1), backgroundColor: variables.listBg, borderColor: variables.listBorderColor } }
1.351563
1
js/vendor/angular-soundmanager2.js
cqs1995/listen1_chrome_extension
2
943
/** @license * * SoundManager 2: JavaScript Sound for the Web * ---------------------------------------------- * http://schillmania.com/projects/soundmanager2/ * * Copyright (c) 2007, <NAME>. All rights reserved. * Code provided under the BSD License: * http://schillmania.com/projects/soundmanager2/license.txt * * V2.97a.20140901 */ /*global window, SM2_DEFER, sm2Debugger, console, document, navigator, setTimeout, setInterval, clearInterval, Audio, opera, module, define */ /*jslint regexp: true, sloppy: true, white: true, nomen: true, plusplus: true, todo: true */ /** * About this file * ------------------------------------------------------------------------------------- * This is the fully-commented source version of the SoundManager 2 API, * recommended for use during development and testing. * * See soundmanager2-nodebug-jsmin.js for an optimized build (~11KB with gzip.) * http://schillmania.com/projects/soundmanager2/doc/getstarted/#basic-inclusion * Alternately, serve this file with gzip for 75% compression savings (~30KB over HTTP.) * * You may notice <d> and </d> comments in this source; these are delimiters for * debug blocks which are removed in the -nodebug builds, further optimizing code size. * * Also, as you may note: Whoa, reliable cross-platform/device audio support is hard! ;) */ (function(window, _undefined) { "use strict"; if(!window || !window.document) { // Don't cross the [environment] streams. SM2 expects to be running in a browser, not under node.js etc. // Additionally, if a browser somehow manages to fail this test, as Egon said: "It would be bad." throw new Error('SoundManager requires a browser with window and document objects.'); } var soundManager = null; /** * The SoundManager constructor. * * @constructor * @param {string} smURL Optional: Path to SWF files * @param {string} smID Optional: The ID to use for the SWF container element * @this {SoundManager} * @return {SoundManager} The new SoundManager instance */ function SoundManager(smURL, smID) { /** * soundManager configuration options list * defines top-level configuration properties to be applied to the soundManager instance (eg. soundManager.flashVersion) * to set these properties, use the setup() method - eg., soundManager.setup({url: '/swf/', flashVersion: 9}) */ this.setupOptions = { 'url': (smURL || null), // path (directory) where SoundManager 2 SWFs exist, eg., /path/to/swfs/ 'flashVersion': 8, // flash build to use (8 or 9.) Some API features require 9. 'debugMode': true, // enable debugging output (console.log() with HTML fallback) 'debugFlash': false, // enable debugging output inside SWF, troubleshoot Flash/browser issues 'useConsole': true, // use console.log() if available (otherwise, writes to #soundmanager-debug element) 'consoleOnly': true, // if console is being used, do not create/write to #soundmanager-debug 'waitForWindowLoad': false, // force SM2 to wait for window.onload() before trying to call soundManager.onload() 'bgColor': '#ffffff', // SWF background color. N/A when wmode = 'transparent' 'useHighPerformance': false, // position:fixed flash movie can help increase js/flash speed, minimize lag 'flashPollingInterval': null, // msec affecting whileplaying/loading callback frequency. If null, default of 50 msec is used. 'html5PollingInterval': null, // msec affecting whileplaying() for HTML5 audio, excluding mobile devices. If null, native HTML5 update events are used. 'flashLoadTimeout': 1000, // msec to wait for flash movie to load before failing (0 = infinity) 'wmode': null, // flash rendering mode - null, 'transparent', or 'opaque' (last two allow z-index to work) 'allowScriptAccess': 'always', // for scripting the SWF (object/embed property), 'always' or 'sameDomain' 'useFlashBlock': false, // *requires flashblock.css, see demos* - allow recovery from flash blockers. Wait indefinitely and apply timeout CSS to SWF, if applicable. 'useHTML5Audio': true, // use HTML5 Audio() where API is supported (most Safari, Chrome versions), Firefox (no MP3/MP4.) Ideally, transparent vs. Flash API where possible. 'html5Test': /^(probably|maybe)$/i, // HTML5 Audio() format support test. Use /^probably$/i; if you want to be more conservative. 'preferFlash': false, // overrides useHTML5audio, will use Flash for MP3/MP4/AAC if present. Potential option if HTML5 playback with these formats is quirky. 'noSWFCache': false, // if true, appends ?ts={date} to break aggressive SWF caching. 'idPrefix': 'sound' // if an id is not provided to createSound(), this prefix is used for generated IDs - 'sound0', 'sound1' etc. }; this.defaultOptions = { /** * the default configuration for sound objects made with createSound() and related methods * eg., volume, auto-load behaviour and so forth */ 'autoLoad': false, // enable automatic loading (otherwise .load() will be called on demand with .play(), the latter being nicer on bandwidth - if you want to .load yourself, you also can) 'autoPlay': false, // enable playing of file as soon as possible (much faster if "stream" is true) 'from': null, // position to start playback within a sound (msec), default = beginning 'loops': 1, // how many times to repeat the sound (position will wrap around to 0, setPosition() will break out of loop when >0) 'onid3': null, // callback function for "ID3 data is added/available" 'onload': null, // callback function for "load finished" 'whileloading': null, // callback function for "download progress update" (X of Y bytes received) 'onplay': null, // callback for "play" start 'onpause': null, // callback for "pause" 'onresume': null, // callback for "resume" (pause toggle) 'whileplaying': null, // callback during play (position update) 'onposition': null, // object containing times and function callbacks for positions of interest 'onstop': null, // callback for "user stop" 'onfailure': null, // callback function for when playing fails 'onfinish': null, // callback function for "sound finished playing" 'multiShot': true, // let sounds "restart" or layer on top of each other when played multiple times, rather than one-shot/one at a time 'multiShotEvents': false, // fire multiple sound events (currently onfinish() only) when multiShot is enabled 'position': null, // offset (milliseconds) to seek to within loaded sound data. 'pan': 0, // "pan" settings, left-to-right, -100 to 100 'stream': true, // allows playing before entire file has loaded (recommended) 'to': null, // position to end playback within a sound (msec), default = end 'type': null, // MIME-like hint for file pattern / canPlay() tests, eg. audio/mp3 'usePolicyFile': false, // enable crossdomain.xml request for audio on remote domains (for ID3/waveform access) 'volume': 100 // self-explanatory. 0-100, the latter being the max. }; this.flash9Options = { /** * flash 9-only options, * merged into defaultOptions if flash 9 is being used */ 'isMovieStar': null, // "MovieStar" MPEG4 audio mode. Null (default) = auto detect MP4, AAC etc. based on URL. true = force on, ignore URL 'usePeakData': false, // enable left/right channel peak (level) data 'useWaveformData': false, // enable sound spectrum (raw waveform data) - NOTE: May increase CPU load. 'useEQData': false, // enable sound EQ (frequency spectrum data) - NOTE: May increase CPU load. 'onbufferchange': null, // callback for "isBuffering" property change 'ondataerror': null // callback for waveform/eq data access error (flash playing audio in other tabs/domains) }; this.movieStarOptions = { /** * flash 9.0r115+ MPEG4 audio options, * merged into defaultOptions if flash 9+movieStar mode is enabled */ 'bufferTime': 3, // seconds of data to buffer before playback begins (null = flash default of 0.1 seconds - if AAC playback is gappy, try increasing.) 'serverURL': null, // rtmp: FMS or FMIS server to connect to, required when requesting media via RTMP or one of its variants 'onconnect': null, // rtmp: callback for connection to flash media server 'duration': null // rtmp: song duration (msec) }; this.audioFormats = { /** * determines HTML5 support + flash requirements. * if no support (via flash and/or HTML5) for a "required" format, SM2 will fail to start. * flash fallback is used for MP3 or MP4 if HTML5 can't play it (or if preferFlash = true) */ 'mp3': { 'type': ['audio/mpeg; codecs="mp3"', 'audio/mpeg', 'audio/mp3', 'audio/MPA', 'audio/mpa-robust'], 'required': true }, 'mp4': { 'related': ['aac', 'm4a', 'm4b'], // additional formats under the MP4 container 'type': ['audio/mp4; codecs="mp4a.40.2"', 'audio/aac', 'audio/x-m4a', 'audio/MP4A-LATM', 'audio/mpeg4-generic'], 'required': false }, 'ogg': { 'type': ['audio/ogg; codecs=vorbis'], 'required': false }, 'opus': { 'type': ['audio/ogg; codecs=opus', 'audio/opus'], 'required': false }, 'wav': { 'type': ['audio/wav; codecs="1"', 'audio/wav', 'audio/wave', 'audio/x-wav'], 'required': false } }; // HTML attributes (id + class names) for the SWF container this.movieID = 'sm2-container'; this.id = (smID || 'sm2movie'); this.debugID = 'soundmanager-debug'; this.debugURLParam = /([#?&])debug=1/i; // dynamic attributes this.versionNumber = 'V2.97a.20140901'; this.version = null; this.movieURL = null; this.altURL = null; this.swfLoaded = false; this.enabled = false; this.oMC = null; this.sounds = {}; this.soundIDs = []; this.muted = false; this.didFlashBlock = false; this.filePattern = null; this.filePatterns = { 'flash8': /\.mp3(\?.*)?$/i, 'flash9': /\.mp3(\?.*)?$/i }; // support indicators, set at init this.features = { 'buffering': false, 'peakData': false, 'waveformData': false, 'eqData': false, 'movieStar': false }; // flash sandbox info, used primarily in troubleshooting this.sandbox = { // <d> 'type': null, 'types': { 'remote': 'remote (domain-based) rules', 'localWithFile': 'local with file access (no internet access)', 'localWithNetwork': 'local with network (internet access only, no local access)', 'localTrusted': 'local, trusted (local+internet access)' }, 'description': null, 'noRemote': null, 'noLocal': null // </d> }; /** * format support (html5/flash) * stores canPlayType() results based on audioFormats. * eg. { mp3: boolean, mp4: boolean } * treat as read-only. */ this.html5 = { 'usingFlash': null // set if/when flash fallback is needed }; // file type support hash this.flash = {}; // determined at init time this.html5Only = false; // used for special cases (eg. iPad/iPhone/palm OS?) this.ignoreFlash = false; /** * a few private internals (OK, a lot. :D) */ var SMSound, sm2 = this, globalHTML5Audio = null, flash = null, sm = 'soundManager', smc = sm + ': ', h5 = 'HTML5::', id, ua = navigator.userAgent, wl = window.location.href.toString(), doc = document, doNothing, setProperties, init, fV, on_queue = [], debugOpen = true, debugTS, didAppend = false, appendSuccess = false, didInit = false, disabled = false, windowLoaded = false, _wDS, wdCount = 0, initComplete, mixin, assign, extraOptions, addOnEvent, processOnEvents, initUserOnload, delayWaitForEI, waitForEI, rebootIntoHTML5, setVersionInfo, handleFocus, strings, initMovie, preInit, domContentLoaded, winOnLoad, didDCLoaded, getDocument, createMovie, catchError, setPolling, initDebug, debugLevels = ['log', 'info', 'warn', 'error'], defaultFlashVersion = 8, disableObject, failSafely, normalizeMovieURL, oRemoved = null, oRemovedHTML = null, str, flashBlockHandler, getSWFCSS, swfCSS, toggleDebug, loopFix, policyFix, complain, idCheck, waitingForEI = false, initPending = false, startTimer, stopTimer, timerExecute, h5TimerCount = 0, h5IntervalTimer = null, parseURL, messages = [], canIgnoreFlash, needsFlash = null, featureCheck, html5OK, html5CanPlay, html5Ext, html5Unload, domContentLoadedIE, testHTML5, event, slice = Array.prototype.slice, useGlobalHTML5Audio = false, lastGlobalHTML5URL, hasFlash, detectFlash, badSafariFix, html5_events, showSupport, flushMessages, wrapCallback, idCounter = 0, is_iDevice = ua.match(/(ipad|iphone|ipod)/i), isAndroid = ua.match(/android/i), isIE = ua.match(/msie/i), isWebkit = ua.match(/webkit/i), isSafari = (ua.match(/safari/i) && !ua.match(/chrome/i)), isOpera = (ua.match(/opera/i)), mobileHTML5 = (ua.match(/(mobile|pre\/|xoom)/i) || is_iDevice || isAndroid), isBadSafari = (!wl.match(/usehtml5audio/i) && !wl.match(/sm2\-ignorebadua/i) && isSafari && !ua.match(/silk/i) && ua.match(/OS X 10_6_([3-7])/i)), // Safari 4 and 5 (excluding Kindle Fire, "Silk") occasionally fail to load/play HTML5 audio on Snow Leopard 10.6.3 through 10.6.7 due to bug(s) in QuickTime X and/or other underlying frameworks. :/ Confirmed bug. https://bugs.webkit.org/show_bug.cgi?id=32159 hasConsole = (window.console !== _undefined && console.log !== _undefined), isFocused = (doc.hasFocus !== _undefined ? doc.hasFocus() : null), tryInitOnFocus = (isSafari && (doc.hasFocus === _undefined || !doc.hasFocus())), okToDisable = !tryInitOnFocus, flashMIME = /(mp3|mp4|mpa|m4a|m4b)/i, msecScale = 1000, emptyURL = 'about:blank', // safe URL to unload, or load nothing from (flash 8 + most HTML5 UAs) emptyWAV = 'data:audio/wave;base64,/UklGRiYAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQIAAAD//w==', // tiny WAV for HTML5 unloading overHTTP = (doc.location ? doc.location.protocol.match(/http/i) : null), http = (!overHTTP ? 'http:/' + '/' : ''), // mp3, mp4, aac etc. netStreamMimeTypes = /^\s*audio\/(?:x-)?(?:mpeg4|aac|flv|mov|mp4||m4v|m4a|m4b|mp4v|3gp|3g2)\s*(?:$|;)/i, // Flash v9.0r115+ "moviestar" formats netStreamTypes = ['mpeg4', 'aac', 'flv', 'mov', 'mp4', 'm4v', 'f4v', 'm4a', 'm4b', 'mp4v', '3gp', '3g2'], netStreamPattern = new RegExp('\\.(' + netStreamTypes.join('|') + ')(\\?.*)?$', 'i'); this.mimePattern = /^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i; // default mp3 set // use altURL if not "online" this.useAltURL = !overHTTP; swfCSS = { 'swfBox': 'sm2-object-box', 'swfDefault': 'movieContainer', 'swfError': 'swf_error', // SWF loaded, but SM2 couldn't start (other error) 'swfTimedout': 'swf_timedout', 'swfLoaded': 'swf_loaded', 'swfUnblocked': 'swf_unblocked', // or loaded OK 'sm2Debug': 'sm2_debug', 'highPerf': 'high_performance', 'flashDebug': 'flash_debug' }; /** * basic HTML5 Audio() support test * try...catch because of IE 9 "not implemented" nonsense * https://github.com/Modernizr/Modernizr/issues/224 */ this.hasHTML5 = (function() { try { // new Audio(null) for stupid Opera 9.64 case, which throws not_enough_arguments exception otherwise. return(Audio !== _undefined && (isOpera && opera !== _undefined && opera.version() < 10 ? new Audio(null) : new Audio()).canPlayType !== _undefined); } catch(e) { return false; } }()); /** * Public SoundManager API * ----------------------- */ /** * Configures top-level soundManager properties. * * @param {object} options Option parameters, eg. { flashVersion: 9, url: '/path/to/swfs/' } * onready and ontimeout are also accepted parameters. call soundManager.setup() to see the full list. */ this.setup = function(options) { var noURL = (!sm2.url); // warn if flash options have already been applied if(options !== _undefined && didInit && needsFlash && sm2.ok() && (options.flashVersion !== _undefined || options.url !== _undefined || options.html5Test !== _undefined)) { complain(str('setupLate')); } // TODO: defer: true? assign(options); // special case 1: "Late setup". SM2 loaded normally, but user didn't assign flash URL eg., setup({url:...}) before SM2 init. Treat as delayed init. if(options) { if(noURL && didDCLoaded && options.url !== _undefined) { sm2.beginDelayedInit(); } // special case 2: If lazy-loading SM2 (DOMContentLoaded has already happened) and user calls setup() with url: parameter, try to init ASAP. if(!didDCLoaded && options.url !== _undefined && doc.readyState === 'complete') { setTimeout(domContentLoaded, 1); } } return sm2; }; this.ok = function() { return(needsFlash ? (didInit && !disabled) : (sm2.useHTML5Audio && sm2.hasHTML5)); }; this.supported = this.ok; // legacy this.getMovie = function(smID) { // safety net: some old browsers differ on SWF references, possibly related to ExternalInterface / flash version return id(smID) || doc[smID] || window[smID]; }; /** * Creates a SMSound sound object instance. * * @param {object} oOptions Sound options (at minimum, id and url parameters are required.) * @return {object} SMSound The new SMSound object. */ this.createSound = function(oOptions, _url) { var cs, cs_string, options, oSound = null; // <d> cs = sm + '.createSound(): '; cs_string = cs + str(!didInit ? 'notReady' : 'notOK'); // </d> if(!didInit || !sm2.ok()) { complain(cs_string); return false; } if(_url !== _undefined) { // function overloading in JS! :) ..assume simple createSound(id, url) use case oOptions = { 'id': oOptions, 'url': _url }; } // inherit from defaultOptions options = mixin(oOptions); options.url = parseURL(options.url); // generate an id, if needed. if(options.id === undefined) { options.id = sm2.setupOptions.idPrefix + (idCounter++); } // <d> if(options.id.toString().charAt(0).match(/^[0-9]$/)) { sm2._wD(cs + str('badID', options.id), 2); } sm2._wD(cs + options.id + (options.url ? ' (' + options.url + ')' : ''), 1); // </d> if(idCheck(options.id, true)) { sm2._wD(cs + options.id + ' exists', 1); return sm2.sounds[options.id]; } function make() { options = loopFix(options); sm2.sounds[options.id] = new SMSound(options); sm2.soundIDs.push(options.id); return sm2.sounds[options.id]; } if(html5OK(options)) { oSound = make(); sm2._wD(options.id + ': Using HTML5'); oSound._setup_html5(options); } else { if(sm2.html5Only) { sm2._wD(options.id + ': No HTML5 support for this sound, and no Flash. Exiting.'); return make(); } // TODO: Move HTML5/flash checks into generic URL parsing/handling function. if(sm2.html5.usingFlash && options.url && options.url.match(/data\:/i)) { // data: URIs not supported by Flash, either. sm2._wD(options.id + ': data: URIs not supported via Flash. Exiting.'); return make(); } if(fV > 8) { if(options.isMovieStar === null) { // attempt to detect MPEG-4 formats options.isMovieStar = !! (options.serverURL || (options.type ? options.type.match(netStreamMimeTypes) : false) || (options.url && options.url.match(netStreamPattern))); } // <d> if(options.isMovieStar) { sm2._wD(cs + 'using MovieStar handling'); if(options.loops > 1) { _wDS('noNSLoop'); } } // </d> } options = policyFix(options, cs); oSound = make(); if(fV === 8) { flash._createSound(options.id, options.loops || 1, options.usePolicyFile); } else { flash._createSound(options.id, options.url, options.usePeakData, options.useWaveformData, options.useEQData, options.isMovieStar, (options.isMovieStar ? options.bufferTime : false), options.loops || 1, options.serverURL, options.duration || null, options.autoPlay, true, options.autoLoad, options.usePolicyFile); if(!options.serverURL) { // We are connected immediately oSound.connected = true; if(options.onconnect) { options.onconnect.apply(oSound); } } } if(!options.serverURL && (options.autoLoad || options.autoPlay)) { // call load for non-rtmp streams oSound.load(options); } } // rtmp will play in onconnect if(!options.serverURL && options.autoPlay) { oSound.play(); } return oSound; }; /** * Destroys a SMSound sound object instance. * * @param {string} sID The ID of the sound to destroy */ this.destroySound = function(sID, _bFromSound) { // explicitly destroy a sound before normal page unload, etc. if(!idCheck(sID)) { return false; } var oS = sm2.sounds[sID], i; // Disable all callbacks while the sound is being destroyed oS._iO = {}; oS.stop(); oS.unload(); for(i = 0; i < sm2.soundIDs.length; i++) { if(sm2.soundIDs[i] === sID) { sm2.soundIDs.splice(i, 1); break; } } if(!_bFromSound) { // ignore if being called from SMSound instance oS.destruct(true); } oS = null; delete sm2.sounds[sID]; return true; }; /** * Calls the load() method of a SMSound object by ID. * * @param {string} sID The ID of the sound * @param {object} oOptions Optional: Sound options */ this.load = function(sID, oOptions) { if(!idCheck(sID)) { return false; } return sm2.sounds[sID].load(oOptions); }; /** * Calls the unload() method of a SMSound object by ID. * * @param {string} sID The ID of the sound */ this.unload = function(sID) { if(!idCheck(sID)) { return false; } return sm2.sounds[sID].unload(); }; /** * Calls the onPosition() method of a SMSound object by ID. * * @param {string} sID The ID of the sound * @param {number} nPosition The position to watch for * @param {function} oMethod The relevant callback to fire * @param {object} oScope Optional: The scope to apply the callback to * @return {SMSound} The SMSound object */ this.onPosition = function(sID, nPosition, oMethod, oScope) { if(!idCheck(sID)) { return false; } return sm2.sounds[sID].onposition(nPosition, oMethod, oScope); }; // legacy/backwards-compability: lower-case method name this.onposition = this.onPosition; /** * Calls the clearOnPosition() method of a SMSound object by ID. * * @param {string} sID The ID of the sound * @param {number} nPosition The position to watch for * @param {function} oMethod Optional: The relevant callback to fire * @return {SMSound} The SMSound object */ this.clearOnPosition = function(sID, nPosition, oMethod) { if(!idCheck(sID)) { return false; } return sm2.sounds[sID].clearOnPosition(nPosition, oMethod); }; /** * Calls the play() method of a SMSound object by ID. * * @param {string} sID The ID of the sound * @param {object} oOptions Optional: Sound options * @return {SMSound} The SMSound object */ this.play = function(sID, oOptions) { var result = null, // legacy function-overloading use case: play('mySound', '/path/to/some.mp3'); overloaded = (oOptions && !(oOptions instanceof Object)); if(!didInit || !sm2.ok()) { complain(sm + '.play(): ' + str(!didInit ? 'notReady' : 'notOK')); return false; } if(!idCheck(sID, overloaded)) { if(!overloaded) { // no sound found for the given ID. Bail. return false; } if(overloaded) { oOptions = { url: oOptions }; } if(oOptions && oOptions.url) { // overloading use case, create+play: .play('someID', {url:'/path/to.mp3'}); sm2._wD(sm + '.play(): Attempting to create "' + sID + '"', 1); oOptions.id = sID; result = sm2.createSound(oOptions).play(); } } else if(overloaded) { // existing sound object case oOptions = { url: oOptions }; } if(result === null) { // default case result = sm2.sounds[sID].play(oOptions); } return result; }; this.start = this.play; // just for convenience /** * Calls the setPosition() method of a SMSound object by ID. * * @param {string} sID The ID of the sound * @param {number} nMsecOffset Position (milliseconds) * @return {SMSound} The SMSound object */ this.setPosition = function(sID, nMsecOffset) { if(!idCheck(sID)) { return false; } return sm2.sounds[sID].setPosition(nMsecOffset); }; /** * Calls the stop() method of a SMSound object by ID. * * @param {string} sID The ID of the sound * @return {SMSound} The SMSound object */ this.stop = function(sID) { if(!idCheck(sID)) { return false; } sm2._wD(sm + '.stop(' + sID + ')', 1); return sm2.sounds[sID].stop(); }; /** * Stops all currently-playing sounds. */ this.stopAll = function() { var oSound; sm2._wD(sm + '.stopAll()', 1); for(oSound in sm2.sounds) { if(sm2.sounds.hasOwnProperty(oSound)) { // apply only to sound objects sm2.sounds[oSound].stop(); } } }; /** * Calls the pause() method of a SMSound object by ID. * * @param {string} sID The ID of the sound * @return {SMSound} The SMSound object */ this.pause = function(sID) { if(!idCheck(sID)) { return false; } return sm2.sounds[sID].pause(); }; /** * Pauses all currently-playing sounds. */ this.pauseAll = function() { var i; for(i = sm2.soundIDs.length - 1; i >= 0; i--) { sm2.sounds[sm2.soundIDs[i]].pause(); } }; /** * Calls the resume() method of a SMSound object by ID. * * @param {string} sID The ID of the sound * @return {SMSound} The SMSound object */ this.resume = function(sID) { if(!idCheck(sID)) { return false; } return sm2.sounds[sID].resume(); }; /** * Resumes all currently-paused sounds. */ this.resumeAll = function() { var i; for(i = sm2.soundIDs.length - 1; i >= 0; i--) { sm2.sounds[sm2.soundIDs[i]].resume(); } }; /** * Calls the togglePause() method of a SMSound object by ID. * * @param {string} sID The ID of the sound * @return {SMSound} The SMSound object */ this.togglePause = function(sID) { if(!idCheck(sID)) { return false; } return sm2.sounds[sID].togglePause(); }; /** * Calls the setPan() method of a SMSound object by ID. * * @param {string} sID The ID of the sound * @param {number} nPan The pan value (-100 to 100) * @return {SMSound} The SMSound object */ this.setPan = function(sID, nPan) { if(!idCheck(sID)) { return false; } return sm2.sounds[sID].setPan(nPan); }; /** * Calls the setVolume() method of a SMSound object by ID. * * @param {string} sID The ID of the sound * @param {number} nVol The volume value (0 to 100) * @return {SMSound} The SMSound object */ this.setVolume = function(sID, nVol) { if(!idCheck(sID)) { return false; } return sm2.sounds[sID].setVolume(nVol); }; /** * Calls the mute() method of either a single SMSound object by ID, or all sound objects. * * @param {string} sID Optional: The ID of the sound (if omitted, all sounds will be used.) */ this.mute = function(sID) { var i = 0; if(sID instanceof String) { sID = null; } if(!sID) { sm2._wD(sm + '.mute(): Muting all sounds'); for(i = sm2.soundIDs.length - 1; i >= 0; i--) { sm2.sounds[sm2.soundIDs[i]].mute(); } sm2.muted = true; } else { if(!idCheck(sID)) { return false; } sm2._wD(sm + '.mute(): Muting "' + sID + '"'); return sm2.sounds[sID].mute(); } return true; }; /** * Mutes all sounds. */ this.muteAll = function() { sm2.mute(); }; /** * Calls the unmute() method of either a single SMSound object by ID, or all sound objects. * * @param {string} sID Optional: The ID of the sound (if omitted, all sounds will be used.) */ this.unmute = function(sID) { var i; if(sID instanceof String) { sID = null; } if(!sID) { sm2._wD(sm + '.unmute(): Unmuting all sounds'); for(i = sm2.soundIDs.length - 1; i >= 0; i--) { sm2.sounds[sm2.soundIDs[i]].unmute(); } sm2.muted = false; } else { if(!idCheck(sID)) { return false; } sm2._wD(sm + '.unmute(): Unmuting "' + sID + '"'); return sm2.sounds[sID].unmute(); } return true; }; /** * Unmutes all sounds. */ this.unmuteAll = function() { sm2.unmute(); }; /** * Calls the toggleMute() method of a SMSound object by ID. * * @param {string} sID The ID of the sound * @return {SMSound} The SMSound object */ this.toggleMute = function(sID) { if(!idCheck(sID)) { return false; } return sm2.sounds[sID].toggleMute(); }; /** * Retrieves the memory used by the flash plugin. * * @return {number} The amount of memory in use */ this.getMemoryUse = function() { // flash-only var ram = 0; if(flash && fV !== 8) { ram = parseInt(flash._getMemoryUse(), 10); } return ram; }; /** * Undocumented: NOPs soundManager and all SMSound objects. */ this.disable = function(bNoDisable) { // destroy all functions var i; if(bNoDisable === _undefined) { bNoDisable = false; } if(disabled) { return false; } disabled = true; _wDS('shutdown', 1); for(i = sm2.soundIDs.length - 1; i >= 0; i--) { disableObject(sm2.sounds[sm2.soundIDs[i]]); } // fire "complete", despite fail initComplete(bNoDisable); event.remove(window, 'load', initUserOnload); return true; }; /** * Determines playability of a MIME type, eg. 'audio/mp3'. */ this.canPlayMIME = function(sMIME) { var result; if(sm2.hasHTML5) { result = html5CanPlay({ type: sMIME }); } if(!result && needsFlash) { // if flash 9, test netStream (movieStar) types as well. result = (sMIME && sm2.ok() ? !! ((fV > 8 ? sMIME.match(netStreamMimeTypes) : null) || sMIME.match(sm2.mimePattern)) : null); // TODO: make less "weird" (per JSLint) } return result; }; /** * Determines playability of a URL based on audio support. * * @param {string} sURL The URL to test * @return {boolean} URL playability */ this.canPlayURL = function(sURL) { var result; if(sm2.hasHTML5) { result = html5CanPlay({ url: sURL }); } if(!result && needsFlash) { result = (sURL && sm2.ok() ? !! (sURL.match(sm2.filePattern)) : null); } return result; }; /** * Determines playability of an HTML DOM &lt;a&gt; object (or similar object literal) based on audio support. * * @param {object} oLink an HTML DOM &lt;a&gt; object or object literal including href and/or type attributes * @return {boolean} URL playability */ this.canPlayLink = function(oLink) { if(oLink.type !== _undefined && oLink.type) { if(sm2.canPlayMIME(oLink.type)) { return true; } } return sm2.canPlayURL(oLink.href); }; /** * Retrieves a SMSound object by ID. * * @param {string} sID The ID of the sound * @return {SMSound} The SMSound object */ this.getSoundById = function(sID, _suppressDebug) { if(!sID) { return null; } var result = sm2.sounds[sID]; // <d> if(!result && !_suppressDebug) { sm2._wD(sm + '.getSoundById(): Sound "' + sID + '" not found.', 2); } // </d> return result; }; /** * Queues a callback for execution when SoundManager has successfully initialized. * * @param {function} oMethod The callback method to fire * @param {object} oScope Optional: The scope to apply to the callback */ this.onready = function(oMethod, oScope) { var sType = 'onready', result = false; if(typeof oMethod === 'function') { // <d> if(didInit) { sm2._wD(str('queue', sType)); } // </d> if(!oScope) { oScope = window; } addOnEvent(sType, oMethod, oScope); processOnEvents(); result = true; } else { throw str('needFunction', sType); } return result; }; /** * Queues a callback for execution when SoundManager has failed to initialize. * * @param {function} oMethod The callback method to fire * @param {object} oScope Optional: The scope to apply to the callback */ this.ontimeout = function(oMethod, oScope) { var sType = 'ontimeout', result = false; if(typeof oMethod === 'function') { // <d> if(didInit) { sm2._wD(str('queue', sType)); } // </d> if(!oScope) { oScope = window; } addOnEvent(sType, oMethod, oScope); processOnEvents({ type: sType }); result = true; } else { throw str('needFunction', sType); } return result; }; /** * Writes console.log()-style debug output to a console or in-browser element. * Applies when debugMode = true * * @param {string} sText The console message * @param {object} nType Optional log level (number), or object. Number case: Log type/style where 0 = 'info', 1 = 'warn', 2 = 'error'. Object case: Object to be dumped. */ this._writeDebug = function(sText, sTypeOrObject) { // pseudo-private console.log()-style output // <d> var sDID = 'soundmanager-debug', o, oItem; if(!sm2.debugMode) { return false; } if(hasConsole && sm2.useConsole) { if(sTypeOrObject && typeof sTypeOrObject === 'object') { // object passed; dump to console. console.log(sText, sTypeOrObject); } else if(debugLevels[sTypeOrObject] !== _undefined) { console[debugLevels[sTypeOrObject]](sText); } else { console.log(sText); } if(sm2.consoleOnly) { return true; } } o = id(sDID); if(!o) { return false; } oItem = doc.createElement('div'); if(++wdCount % 2 === 0) { oItem.className = 'sm2-alt'; } if(sTypeOrObject === _undefined) { sTypeOrObject = 0; } else { sTypeOrObject = parseInt(sTypeOrObject, 10); } oItem.appendChild(doc.createTextNode(sText)); if(sTypeOrObject) { if(sTypeOrObject >= 2) { oItem.style.fontWeight = 'bold'; } if(sTypeOrObject === 3) { oItem.style.color = '#ff3333'; } } // top-to-bottom // o.appendChild(oItem); // bottom-to-top o.insertBefore(oItem, o.firstChild); o = null; // </d> return true; }; // <d> // last-resort debugging option if(wl.indexOf('sm2-debug=alert') !== -1) { this._writeDebug = function(sText) { window.alert(sText); }; } // </d> // alias this._wD = this._writeDebug; /** * Provides debug / state information on all SMSound objects. */ this._debug = function() { // <d> var i, j; _wDS('currentObj', 1); for(i = 0, j = sm2.soundIDs.length; i < j; i++) { sm2.sounds[sm2.soundIDs[i]]._debug(); } // </d> }; /** * Restarts and re-initializes the SoundManager instance. * * @param {boolean} resetEvents Optional: When true, removes all registered onready and ontimeout event callbacks. * @param {boolean} excludeInit Options: When true, does not call beginDelayedInit() (which would restart SM2). * @return {object} soundManager The soundManager instance. */ this.reboot = function(resetEvents, excludeInit) { // reset some (or all) state, and re-init unless otherwise specified. // <d> if(sm2.soundIDs.length) { sm2._wD('Destroying ' + sm2.soundIDs.length + ' SMSound object' + (sm2.soundIDs.length !== 1 ? 's' : '') + '...'); } // </d> var i, j, k; for(i = sm2.soundIDs.length - 1; i >= 0; i--) { sm2.sounds[sm2.soundIDs[i]].destruct(); } // trash ze flash (remove from the DOM) if(flash) { try { if(isIE) { oRemovedHTML = flash.innerHTML; } oRemoved = flash.parentNode.removeChild(flash); } catch(e) { // Remove failed? May be due to flash blockers silently removing the SWF object/embed node from the DOM. Warn and continue. _wDS('badRemove', 2); } } // actually, force recreate of movie. oRemovedHTML = oRemoved = needsFlash = flash = null; sm2.enabled = didDCLoaded = didInit = waitingForEI = initPending = didAppend = appendSuccess = disabled = useGlobalHTML5Audio = sm2.swfLoaded = false; sm2.soundIDs = []; sm2.sounds = {}; idCounter = 0; if(!resetEvents) { // reset callbacks for onready, ontimeout etc. so that they will fire again on re-init for(i in on_queue) { if(on_queue.hasOwnProperty(i)) { for(j = 0, k = on_queue[i].length; j < k; j++) { on_queue[i][j].fired = false; } } } } else { // remove all callbacks entirely on_queue = []; } // <d> if(!excludeInit) { sm2._wD(sm + ': Rebooting...'); } // </d> // reset HTML5 and flash canPlay test results sm2.html5 = { 'usingFlash': null }; sm2.flash = {}; // reset device-specific HTML/flash mode switches sm2.html5Only = false; sm2.ignoreFlash = false; window.setTimeout(function() { preInit(); // by default, re-init if(!excludeInit) { sm2.beginDelayedInit(); } }, 20); return sm2; }; this.reset = function() { /** * Shuts down and restores the SoundManager instance to its original loaded state, without an explicit reboot. All onready/ontimeout handlers are removed. * After this call, SM2 may be re-initialized via soundManager.beginDelayedInit(). * @return {object} soundManager The soundManager instance. */ _wDS('reset'); return sm2.reboot(true, true); }; /** * Undocumented: Determines the SM2 flash movie's load progress. * * @return {number or null} Percent loaded, or if invalid/unsupported, null. */ this.getMoviePercent = function() { /** * Interesting syntax notes... * Flash/ExternalInterface (ActiveX/NPAPI) bridge methods are not typeof "function" nor instanceof Function, but are still valid. * Additionally, JSLint dislikes ('PercentLoaded' in flash)-style syntax and recommends hasOwnProperty(), which does not work in this case. * Furthermore, using (flash && flash.PercentLoaded) causes IE to throw "object doesn't support this property or method". * Thus, 'in' syntax must be used. */ return(flash && 'PercentLoaded' in flash ? flash.PercentLoaded() : null); // Yes, JSLint. See nearby comment in source for explanation. }; /** * Additional helper for manually invoking SM2's init process after DOM Ready / window.onload(). */ this.beginDelayedInit = function() { windowLoaded = true; domContentLoaded(); setTimeout(function() { if(initPending) { return false; } createMovie(); initMovie(); initPending = true; return true; }, 20); delayWaitForEI(); }; /** * Destroys the SoundManager instance and all SMSound instances. */ this.destruct = function() { sm2._wD(sm + '.destruct()'); sm2.disable(true); }; /** * SMSound() (sound object) constructor * ------------------------------------ * * @param {object} oOptions Sound options (id and url are required attributes) * @return {SMSound} The new SMSound object */ SMSound = function(oOptions) { var s = this, resetProperties, add_html5_events, remove_html5_events, stop_html5_timer, start_html5_timer, attachOnPosition, onplay_called = false, onPositionItems = [], onPositionFired = 0, detachOnPosition, applyFromTo, lastURL = null, lastHTML5State, urlOmitted; lastHTML5State = { // tracks duration + position (time) duration: null, time: null }; this.id = oOptions.id; // legacy this.sID = this.id; this.url = oOptions.url; this.options = mixin(oOptions); // per-play-instance-specific options this.instanceOptions = this.options; // short alias this._iO = this.instanceOptions; // assign property defaults this.pan = this.options.pan; this.volume = this.options.volume; // whether or not this object is using HTML5 this.isHTML5 = false; // internal HTML5 Audio() object reference this._a = null; // for flash 8 special-case createSound() without url, followed by load/play with url case urlOmitted = (this.url ? false : true); /** * SMSound() public methods * ------------------------ */ this.id3 = {}; /** * Writes SMSound object parameters to debug console */ this._debug = function() { // <d> sm2._wD(s.id + ': Merged options:', s.options); // </d> }; /** * Begins loading a sound per its *url*. * * @param {object} oOptions Optional: Sound options * @return {SMSound} The SMSound object */ this.load = function(oOptions) { var oSound = null, instanceOptions; if(oOptions !== _undefined) { s._iO = mixin(oOptions, s.options); } else { oOptions = s.options; s._iO = oOptions; if(lastURL && lastURL !== s.url) { _wDS('manURL'); s._iO.url = s.url; s.url = null; } } if(!s._iO.url) { s._iO.url = s.url; } s._iO.url = parseURL(s._iO.url); // ensure we're in sync s.instanceOptions = s._iO; // local shortcut instanceOptions = s._iO; sm2._wD(s.id + ': load (' + instanceOptions.url + ')'); if(!instanceOptions.url && !s.url) { sm2._wD(s.id + ': load(): url is unassigned. Exiting.', 2); return s; } // <d> if(!s.isHTML5 && fV === 8 && !s.url && !instanceOptions.autoPlay) { // flash 8 load() -> play() won't work before onload has fired. sm2._wD(s.id + ': Flash 8 load() limitation: Wait for onload() before calling play().', 1); } // </d> if(instanceOptions.url === s.url && s.readyState !== 0 && s.readyState !== 2) { _wDS('onURL', 1); // if loaded and an onload() exists, fire immediately. if(s.readyState === 3 && instanceOptions.onload) { // assume success based on truthy duration. wrapCallback(s, function() { instanceOptions.onload.apply(s, [( !! s.duration)]); }); } return s; } // reset a few state properties s.loaded = false; s.readyState = 1; s.playState = 0; s.id3 = {}; // TODO: If switching from HTML5 -> flash (or vice versa), stop currently-playing audio. if(html5OK(instanceOptions)) { oSound = s._setup_html5(instanceOptions); if(!oSound._called_load) { s._html5_canplay = false; // TODO: review called_load / html5_canplay logic // if url provided directly to load(), assign it here. if(s.url !== instanceOptions.url) { sm2._wD(_wDS('manURL') + ': ' + instanceOptions.url); s._a.src = instanceOptions.url; // TODO: review / re-apply all relevant options (volume, loop, onposition etc.) // reset position for new URL s.setPosition(0); } // given explicit load call, try to preload. // early HTML5 implementation (non-standard) s._a.autobuffer = 'auto'; // standard property, values: none / metadata / auto // reference: http://msdn.microsoft.com/en-us/library/ie/ff974759%28v=vs.85%29.aspx s._a.preload = 'auto'; s._a._called_load = true; } else { sm2._wD(s.id + ': Ignoring request to load again'); } } else { if(sm2.html5Only) { sm2._wD(s.id + ': No flash support. Exiting.'); return s; } if(s._iO.url && s._iO.url.match(/data\:/i)) { // data: URIs not supported by Flash, either. sm2._wD(s.id + ': data: URIs not supported via Flash. Exiting.'); return s; } try { s.isHTML5 = false; s._iO = policyFix(loopFix(instanceOptions)); // if we have "position", disable auto-play as we'll be seeking to that position at onload(). if(s._iO.autoPlay && (s._iO.position || s._iO.from)) { sm2._wD(s.id + ': Disabling autoPlay because of non-zero offset case'); s._iO.autoPlay = false; } // re-assign local shortcut instanceOptions = s._iO; if(fV === 8) { flash._load(s.id, instanceOptions.url, instanceOptions.stream, instanceOptions.autoPlay, instanceOptions.usePolicyFile); } else { flash._load(s.id, instanceOptions.url, !! (instanceOptions.stream), !! (instanceOptions.autoPlay), instanceOptions.loops || 1, !! (instanceOptions.autoLoad), instanceOptions.usePolicyFile); } } catch(e) { _wDS('smError', 2); debugTS('onload', false); catchError({ type: 'SMSOUND_LOAD_JS_EXCEPTION', fatal: true }); } } // after all of this, ensure sound url is up to date. s.url = instanceOptions.url; return s; }; /** * Unloads a sound, canceling any open HTTP requests. * * @return {SMSound} The SMSound object */ this.unload = function() { // Flash 8/AS2 can't "close" a stream - fake it by loading an empty URL // Flash 9/AS3: Close stream, preventing further load // HTML5: Most UAs will use empty URL if(s.readyState !== 0) { sm2._wD(s.id + ': unload()'); if(!s.isHTML5) { if(fV === 8) { flash._unload(s.id, emptyURL); } else { flash._unload(s.id); } } else { stop_html5_timer(); if(s._a) { s._a.pause(); // update empty URL, too lastURL = html5Unload(s._a); } } // reset load/status flags resetProperties(); } return s; }; /** * Unloads and destroys a sound. */ this.destruct = function(_bFromSM) { sm2._wD(s.id + ': Destruct'); if(!s.isHTML5) { // kill sound within Flash // Disable the onfailure handler s._iO.onfailure = null; flash._destroySound(s.id); } else { stop_html5_timer(); if(s._a) { s._a.pause(); html5Unload(s._a); if(!useGlobalHTML5Audio) { remove_html5_events(); } // break obvious circular reference s._a._s = null; s._a = null; } } if(!_bFromSM) { // ensure deletion from controller sm2.destroySound(s.id, true); } }; /** * Begins playing a sound. * * @param {object} oOptions Optional: Sound options * @return {SMSound} The SMSound object */ this.play = function(oOptions, _updatePlayState) { var fN, allowMulti, a, onready, audioClone, onended, oncanplay, startOK = true, exit = null; // <d> fN = s.id + ': play(): '; // </d> // default to true _updatePlayState = (_updatePlayState === _undefined ? true : _updatePlayState); if(!oOptions) { oOptions = {}; } // first, use local URL (if specified) if(s.url) { s._iO.url = s.url; } // mix in any options defined at createSound() s._iO = mixin(s._iO, s.options); // mix in any options specific to this method s._iO = mixin(oOptions, s._iO); s._iO.url = parseURL(s._iO.url); s.instanceOptions = s._iO; // RTMP-only if(!s.isHTML5 && s._iO.serverURL && !s.connected) { if(!s.getAutoPlay()) { sm2._wD(fN + ' Netstream not connected yet - setting autoPlay'); s.setAutoPlay(true); } // play will be called in onconnect() return s; } if(html5OK(s._iO)) { s._setup_html5(s._iO); start_html5_timer(); } if(s.playState === 1 && !s.paused) { allowMulti = s._iO.multiShot; if(!allowMulti) { sm2._wD(fN + 'Already playing (one-shot)', 1); if(s.isHTML5) { // go back to original position. s.setPosition(s._iO.position); } exit = s; } else { sm2._wD(fN + 'Already playing (multi-shot)', 1); } } if(exit !== null) { return exit; } // edge case: play() with explicit URL parameter if(oOptions.url && oOptions.url !== s.url) { // special case for createSound() followed by load() / play() with url; avoid double-load case. if(!s.readyState && !s.isHTML5 && fV === 8 && urlOmitted) { urlOmitted = false; } else { // load using merged options s.load(s._iO); } } if(!s.loaded) { if(s.readyState === 0) { sm2._wD(fN + 'Attempting to load'); // try to get this sound playing ASAP if(!s.isHTML5 && !sm2.html5Only) { // flash: assign directly because setAutoPlay() increments the instanceCount s._iO.autoPlay = true; s.load(s._iO); } else if(s.isHTML5) { // iOS needs this when recycling sounds, loading a new URL on an existing object. s.load(s._iO); } else { sm2._wD(fN + 'Unsupported type. Exiting.'); exit = s; } // HTML5 hack - re-set instanceOptions? s.instanceOptions = s._iO; } else if(s.readyState === 2) { sm2._wD(fN + 'Could not load - exiting', 2); exit = s; } else { sm2._wD(fN + 'Loading - attempting to play...'); } } else { // "play()" sm2._wD(fN.substr(0, fN.lastIndexOf(':'))); } if(exit !== null) { return exit; } if(!s.isHTML5 && fV === 9 && s.position > 0 && s.position === s.duration) { // flash 9 needs a position reset if play() is called while at the end of a sound. sm2._wD(fN + 'Sound at end, resetting to position:0'); oOptions.position = 0; } /** * Streams will pause when their buffer is full if they are being loaded. * In this case paused is true, but the song hasn't started playing yet. * If we just call resume() the onplay() callback will never be called. * So only call resume() if the position is > 0. * Another reason is because options like volume won't have been applied yet. * For normal sounds, just resume. */ if(s.paused && s.position >= 0 && (!s._iO.serverURL || s.position > 0)) { // https://gist.github.com/37b17df75cc4d7a90bf6 sm2._wD(fN + 'Resuming from paused state', 1); s.resume(); } else { s._iO = mixin(oOptions, s._iO); /** * Preload in the event of play() with position under Flash, * or from/to parameters and non-RTMP case */ if(((!s.isHTML5 && s._iO.position !== null && s._iO.position > 0) || (s._iO.from !== null && s._iO.from > 0) || s._iO.to !== null) && s.instanceCount === 0 && s.playState === 0 && !s._iO.serverURL) { onready = function() { // sound "canplay" or onload() // re-apply position/from/to to instance options, and start playback s._iO = mixin(oOptions, s._iO); s.play(s._iO); }; // HTML5 needs to at least have "canplay" fired before seeking. if(s.isHTML5 && !s._html5_canplay) { // this hasn't been loaded yet. load it first, and then do this again. sm2._wD(fN + 'Beginning load for non-zero offset case'); s.load({ // note: custom HTML5-only event added for from/to implementation. _oncanplay: onready }); exit = false; } else if(!s.isHTML5 && !s.loaded && (!s.readyState || s.readyState !== 2)) { // to be safe, preload the whole thing in Flash. sm2._wD(fN + 'Preloading for non-zero offset case'); s.load({ onload: onready }); exit = false; } if(exit !== null) { return exit; } // otherwise, we're ready to go. re-apply local options, and continue s._iO = applyFromTo(); } // sm2._wD(fN + 'Starting to play'); // increment instance counter, where enabled + supported if(!s.instanceCount || s._iO.multiShotEvents || (s.isHTML5 && s._iO.multiShot && !useGlobalHTML5Audio) || (!s.isHTML5 && fV > 8 && !s.getAutoPlay())) { s.instanceCount++; } // if first play and onposition parameters exist, apply them now if(s._iO.onposition && s.playState === 0) { attachOnPosition(s); } s.playState = 1; s.paused = false; s.position = (s._iO.position !== _undefined && !isNaN(s._iO.position) ? s._iO.position : 0); if(!s.isHTML5) { s._iO = policyFix(loopFix(s._iO)); } if(s._iO.onplay && _updatePlayState) { s._iO.onplay.apply(s); onplay_called = true; } s.setVolume(s._iO.volume, true); s.setPan(s._iO.pan, true); if(!s.isHTML5) { startOK = flash._start(s.id, s._iO.loops || 1, (fV === 9 ? s.position : s.position / msecScale), s._iO.multiShot || false); if(fV === 9 && !startOK) { // edge case: no sound hardware, or 32-channel flash ceiling hit. // applies only to Flash 9, non-NetStream/MovieStar sounds. // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/media/Sound.html#play%28%29 sm2._wD(fN + 'No sound hardware, or 32-sound ceiling hit', 2); if(s._iO.onplayerror) { s._iO.onplayerror.apply(s); } } } else { if(s.instanceCount < 2) { // HTML5 single-instance case start_html5_timer(); a = s._setup_html5(); s.setPosition(s._iO.position); a.play(); } else { // HTML5 multi-shot case sm2._wD(s.id + ': Cloning Audio() for instance #' + s.instanceCount + '...'); audioClone = new Audio(s._iO.url); onended = function() { event.remove(audioClone, 'ended', onended); s._onfinish(s); // cleanup html5Unload(audioClone); audioClone = null; }; oncanplay = function() { event.remove(audioClone, 'canplay', oncanplay); try { audioClone.currentTime = s._iO.position / msecScale; } catch(err) { complain(s.id + ': multiShot play() failed to apply position of ' + (s._iO.position / msecScale)); } audioClone.play(); }; event.add(audioClone, 'ended', onended); // apply volume to clones, too if(s._iO.volume !== undefined) { audioClone.volume = Math.max(0, Math.min(1, s._iO.volume / 100)); } // playing multiple muted sounds? if you do this, you're weird ;) - but let's cover it. if(s.muted) { audioClone.muted = true; } if(s._iO.position) { // HTML5 audio can't seek before onplay() event has fired. // wait for canplay, then seek to position and start playback. event.add(audioClone, 'canplay', oncanplay); } else { // begin playback at currentTime: 0 audioClone.play(); } } } } return s; }; // just for convenience this.start = this.play; /** * Stops playing a sound (and optionally, all sounds) * * @param {boolean} bAll Optional: Whether to stop all sounds * @return {SMSound} The SMSound object */ this.stop = function(bAll) { var instanceOptions = s._iO, originalPosition; if(s.playState === 1) { sm2._wD(s.id + ': stop()'); s._onbufferchange(0); s._resetOnPosition(0); s.paused = false; if(!s.isHTML5) { s.playState = 0; } // remove onPosition listeners, if any detachOnPosition(); // and "to" position, if set if(instanceOptions.to) { s.clearOnPosition(instanceOptions.to); } if(!s.isHTML5) { flash._stop(s.id, bAll); // hack for netStream: just unload if(instanceOptions.serverURL) { s.unload(); } } else { if(s._a) { originalPosition = s.position; // act like Flash, though s.setPosition(0); // hack: reflect old position for onstop() (also like Flash) s.position = originalPosition; // html5 has no stop() // NOTE: pausing means iOS requires interaction to resume. s._a.pause(); s.playState = 0; // and update UI s._onTimer(); stop_html5_timer(); } } s.instanceCount = 0; s._iO = {}; if(instanceOptions.onstop) { instanceOptions.onstop.apply(s); } } return s; }; /** * Undocumented/internal: Sets autoPlay for RTMP. * * @param {boolean} autoPlay state */ this.setAutoPlay = function(autoPlay) { sm2._wD(s.id + ': Autoplay turned ' + (autoPlay ? 'on' : 'off')); s._iO.autoPlay = autoPlay; if(!s.isHTML5) { flash._setAutoPlay(s.id, autoPlay); if(autoPlay) { // only increment the instanceCount if the sound isn't loaded (TODO: verify RTMP) if(!s.instanceCount && s.readyState === 1) { s.instanceCount++; sm2._wD(s.id + ': Incremented instance count to ' + s.instanceCount); } } } }; /** * Undocumented/internal: Returns the autoPlay boolean. * * @return {boolean} The current autoPlay value */ this.getAutoPlay = function() { return s._iO.autoPlay; }; /** * Sets the position of a sound. * * @param {number} nMsecOffset Position (milliseconds) * @return {SMSound} The SMSound object */ this.setPosition = function(nMsecOffset) { if(nMsecOffset === _undefined) { nMsecOffset = 0; } var position, position1K, // Use the duration from the instance options, if we don't have a track duration yet. // position >= 0 and <= current available (loaded) duration offset = (s.isHTML5 ? Math.max(nMsecOffset, 0) : Math.min(s.duration || s._iO.duration, Math.max(nMsecOffset, 0))); s.position = offset; position1K = s.position / msecScale; s._resetOnPosition(s.position); s._iO.position = offset; if(!s.isHTML5) { position = (fV === 9 ? s.position : position1K); if(s.readyState && s.readyState !== 2) { // if paused or not playing, will not resume (by playing) flash._setPosition(s.id, position, (s.paused || !s.playState), s._iO.multiShot); } } else if(s._a) { // Set the position in the canplay handler if the sound is not ready yet if(s._html5_canplay) { if(s._a.currentTime !== position1K) { /** * DOM/JS errors/exceptions to watch out for: * if seek is beyond (loaded?) position, "DOM exception 11" * "INDEX_SIZE_ERR": DOM exception 1 */ sm2._wD(s.id + ': setPosition(' + position1K + ')'); try { s._a.currentTime = position1K; if(s.playState === 0 || s.paused) { // allow seek without auto-play/resume s._a.pause(); } } catch(e) { sm2._wD(s.id + ': setPosition(' + position1K + ') failed: ' + e.message, 2); } } } else if(position1K) { // warn on non-zero seek attempts sm2._wD(s.id + ': setPosition(' + position1K + '): Cannot seek yet, sound not ready', 2); return s; } if(s.paused) { // if paused, refresh UI right away // force update s._onTimer(true); } } return s; }; /** * Pauses sound playback. * * @return {SMSound} The SMSound object */ this.pause = function(_bCallFlash) { if(s.paused || (s.playState === 0 && s.readyState !== 1)) { return s; } sm2._wD(s.id + ': pause()'); s.paused = true; if(!s.isHTML5) { if(_bCallFlash || _bCallFlash === _undefined) { flash._pause(s.id, s._iO.multiShot); } } else { s._setup_html5().pause(); stop_html5_timer(); } if(s._iO.onpause) { s._iO.onpause.apply(s); } return s; }; /** * Resumes sound playback. * * @return {SMSound} The SMSound object */ /** * When auto-loaded streams pause on buffer full they have a playState of 0. * We need to make sure that the playState is set to 1 when these streams "resume". * When a paused stream is resumed, we need to trigger the onplay() callback if it * hasn't been called already. In this case since the sound is being played for the * first time, I think it's more appropriate to call onplay() rather than onresume(). */ this.resume = function() { var instanceOptions = s._iO; if(!s.paused) { return s; } sm2._wD(s.id + ': resume()'); s.paused = false; s.playState = 1; if(!s.isHTML5) { if(instanceOptions.isMovieStar && !instanceOptions.serverURL) { // Bizarre Webkit bug (Chrome reported via 8tracks.com dudes): AAC content paused for 30+ seconds(?) will not resume without a reposition. s.setPosition(s.position); } // flash method is toggle-based (pause/resume) flash._pause(s.id, instanceOptions.multiShot); } else { s._setup_html5().play(); start_html5_timer(); } if(!onplay_called && instanceOptions.onplay) { instanceOptions.onplay.apply(s); onplay_called = true; } else if(instanceOptions.onresume) { instanceOptions.onresume.apply(s); } return s; }; /** * Toggles sound playback. * * @return {SMSound} The SMSound object */ this.togglePause = function() { sm2._wD(s.id + ': togglePause()'); if(s.playState === 0) { s.play({ position: (fV === 9 && !s.isHTML5 ? s.position : s.position / msecScale) }); return s; } if(s.paused) { s.resume(); } else { s.pause(); } return s; }; /** * Sets the panning (L-R) effect. * * @param {number} nPan The pan value (-100 to 100) * @return {SMSound} The SMSound object */ this.setPan = function(nPan, bInstanceOnly) { if(nPan === _undefined) { nPan = 0; } if(bInstanceOnly === _undefined) { bInstanceOnly = false; } if(!s.isHTML5) { flash._setPan(s.id, nPan); } // else { no HTML5 pan? } s._iO.pan = nPan; if(!bInstanceOnly) { s.pan = nPan; s.options.pan = nPan; } return s; }; /** * Sets the volume. * * @param {number} nVol The volume value (0 to 100) * @return {SMSound} The SMSound object */ this.setVolume = function(nVol, _bInstanceOnly) { /** * Note: Setting volume has no effect on iOS "special snowflake" devices. * Hardware volume control overrides software, and volume * will always return 1 per Apple docs. (iOS 4 + 5.) * http://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/AddingSoundtoCanvasAnimations/AddingSoundtoCanvasAnimations.html */ if(nVol === _undefined) { nVol = 100; } if(_bInstanceOnly === _undefined) { _bInstanceOnly = false; } if(!s.isHTML5) { flash._setVolume(s.id, (sm2.muted && !s.muted) || s.muted ? 0 : nVol); } else if(s._a) { if(sm2.muted && !s.muted) { s.muted = true; s._a.muted = true; } // valid range: 0-1 s._a.volume = Math.max(0, Math.min(1, nVol / 100)); } s._iO.volume = nVol; if(!_bInstanceOnly) { s.volume = nVol; s.options.volume = nVol; } return s; }; /** * Mutes the sound. * * @return {SMSound} The SMSound object */ this.mute = function() { s.muted = true; if(!s.isHTML5) { flash._setVolume(s.id, 0); } else if(s._a) { s._a.muted = true; } return s; }; /** * Unmutes the sound. * * @return {SMSound} The SMSound object */ this.unmute = function() { s.muted = false; var hasIO = (s._iO.volume !== _undefined); if(!s.isHTML5) { flash._setVolume(s.id, hasIO ? s._iO.volume : s.options.volume); } else if(s._a) { s._a.muted = false; } return s; }; /** * Toggles the muted state of a sound. * * @return {SMSound} The SMSound object */ this.toggleMute = function() { return(s.muted ? s.unmute() : s.mute()); }; /** * Registers a callback to be fired when a sound reaches a given position during playback. * * @param {number} nPosition The position to watch for * @param {function} oMethod The relevant callback to fire * @param {object} oScope Optional: The scope to apply the callback to * @return {SMSound} The SMSound object */ this.onPosition = function(nPosition, oMethod, oScope) { // TODO: basic dupe checking? onPositionItems.push({ position: parseInt(nPosition, 10), method: oMethod, scope: (oScope !== _undefined ? oScope : s), fired: false }); return s; }; // legacy/backwards-compability: lower-case method name this.onposition = this.onPosition; /** * Removes registered callback(s) from a sound, by position and/or callback. * * @param {number} nPosition The position to clear callback(s) for * @param {function} oMethod Optional: Identify one callback to be removed when multiple listeners exist for one position * @return {SMSound} The SMSound object */ this.clearOnPosition = function(nPosition, oMethod) { var i; nPosition = parseInt(nPosition, 10); if(isNaN(nPosition)) { // safety check return false; } for(i = 0; i < onPositionItems.length; i++) { if(nPosition === onPositionItems[i].position) { // remove this item if no method was specified, or, if the method matches if(!oMethod || (oMethod === onPositionItems[i].method)) { if(onPositionItems[i].fired) { // decrement "fired" counter, too onPositionFired--; } onPositionItems.splice(i, 1); } } } }; this._processOnPosition = function() { var i, item, j = onPositionItems.length; if(!j || !s.playState || onPositionFired >= j) { return false; } for(i = j - 1; i >= 0; i--) { item = onPositionItems[i]; if(!item.fired && s.position >= item.position) { item.fired = true; onPositionFired++; item.method.apply(item.scope, [item.position]); j = onPositionItems.length; // reset j -- onPositionItems.length can be changed in the item callback above... occasionally breaking the loop. } } return true; }; this._resetOnPosition = function(nPosition) { // reset "fired" for items interested in this position var i, item, j = onPositionItems.length; if(!j) { return false; } for(i = j - 1; i >= 0; i--) { item = onPositionItems[i]; if(item.fired && nPosition <= item.position) { item.fired = false; onPositionFired--; } } return true; }; /** * SMSound() private internals * -------------------------------- */ applyFromTo = function() { var instanceOptions = s._iO, f = instanceOptions.from, t = instanceOptions.to, start, end; end = function() { // end has been reached. sm2._wD(s.id + ': "To" time of ' + t + ' reached.'); // detach listener s.clearOnPosition(t, end); // stop should clear this, too s.stop(); }; start = function() { sm2._wD(s.id + ': Playing "from" ' + f); // add listener for end if(t !== null && !isNaN(t)) { s.onPosition(t, end); } }; if(f !== null && !isNaN(f)) { // apply to instance options, guaranteeing correct start position. instanceOptions.position = f; // multiShot timing can't be tracked, so prevent that. instanceOptions.multiShot = false; start(); } // return updated instanceOptions including starting position return instanceOptions; }; attachOnPosition = function() { var item, op = s._iO.onposition; // attach onposition things, if any, now. if(op) { for(item in op) { if(op.hasOwnProperty(item)) { s.onPosition(parseInt(item, 10), op[item]); } } } }; detachOnPosition = function() { var item, op = s._iO.onposition; // detach any onposition()-style listeners. if(op) { for(item in op) { if(op.hasOwnProperty(item)) { s.clearOnPosition(parseInt(item, 10)); } } } }; start_html5_timer = function() { if(s.isHTML5) { startTimer(s); } }; stop_html5_timer = function() { if(s.isHTML5) { stopTimer(s); } }; resetProperties = function(retainPosition) { if(!retainPosition) { onPositionItems = []; onPositionFired = 0; } onplay_called = false; s._hasTimer = null; s._a = null; s._html5_canplay = false; s.bytesLoaded = null; s.bytesTotal = null; s.duration = (s._iO && s._iO.duration ? s._iO.duration : null); s.durationEstimate = null; s.buffered = []; // legacy: 1D array s.eqData = []; s.eqData.left = []; s.eqData.right = []; s.failures = 0; s.isBuffering = false; s.instanceOptions = {}; s.instanceCount = 0; s.loaded = false; s.metadata = {}; // 0 = uninitialised, 1 = loading, 2 = failed/error, 3 = loaded/success s.readyState = 0; s.muted = false; s.paused = false; s.peakData = { left: 0, right: 0 }; s.waveformData = { left: [], right: [] }; s.playState = 0; s.position = null; s.id3 = {}; }; resetProperties(); /** * Pseudo-private SMSound internals * -------------------------------- */ this._onTimer = function(bForce) { /** * HTML5-only _whileplaying() etc. * called from both HTML5 native events, and polling/interval-based timers * mimics flash and fires only when time/duration change, so as to be polling-friendly */ var duration, isNew = false, time, x = {}; if(s._hasTimer || bForce) { // TODO: May not need to track readyState (1 = loading) if(s._a && (bForce || ((s.playState > 0 || s.readyState === 1) && !s.paused))) { duration = s._get_html5_duration(); if(duration !== lastHTML5State.duration) { lastHTML5State.duration = duration; s.duration = duration; isNew = true; } // TODO: investigate why this goes wack if not set/re-set each time. s.durationEstimate = s.duration; time = (s._a.currentTime * msecScale || 0); if(time !== lastHTML5State.time) { lastHTML5State.time = time; isNew = true; } if(isNew || bForce) { s._whileplaying(time, x, x, x, x); } } /* else { // sm2._wD('_onTimer: Warn for "'+s.id+'": '+(!s._a?'Could not find element. ':'')+(s.playState === 0?'playState bad, 0?':'playState = '+s.playState+', OK')); return false; }*/ return isNew; } }; this._get_html5_duration = function() { var instanceOptions = s._iO, // if audio object exists, use its duration - else, instance option duration (if provided - it's a hack, really, and should be retired) OR null d = (s._a && s._a.duration ? s._a.duration * msecScale : (instanceOptions && instanceOptions.duration ? instanceOptions.duration : null)), result = (d && !isNaN(d) && d !== Infinity ? d : null); return result; }; this._apply_loop = function(a, nLoops) { /** * boolean instead of "loop", for webkit? - spec says string. http://www.w3.org/TR/html-markup/audio.html#audio.attrs.loop * note that loop is either off or infinite under HTML5, unlike Flash which allows arbitrary loop counts to be specified. */ // <d> if(!a.loop && nLoops > 1) { sm2._wD('Note: Native HTML5 looping is infinite.', 1); } // </d> a.loop = (nLoops > 1 ? 'loop' : ''); }; this._setup_html5 = function(oOptions) { var instanceOptions = mixin(s._iO, oOptions), a = useGlobalHTML5Audio ? globalHTML5Audio : s._a, dURL = decodeURI(instanceOptions.url), sameURL; /** * "First things first, I, Poppa..." (reset the previous state of the old sound, if playing) * Fixes case with devices that can only play one sound at a time * Otherwise, other sounds in mid-play will be terminated without warning and in a stuck state */ if(useGlobalHTML5Audio) { if(dURL === decodeURI(lastGlobalHTML5URL)) { // global HTML5 audio: re-use of URL sameURL = true; } } else if(dURL === decodeURI(lastURL)) { // options URL is the same as the "last" URL, and we used (loaded) it sameURL = true; } if(a) { if(a._s) { if(useGlobalHTML5Audio) { if(a._s && a._s.playState && !sameURL) { // global HTML5 audio case, and loading a new URL. stop the currently-playing one. a._s.stop(); } } else if(!useGlobalHTML5Audio && dURL === decodeURI(lastURL)) { // non-global HTML5 reuse case: same url, ignore request s._apply_loop(a, instanceOptions.loops); return a; } } if(!sameURL) { // don't retain onPosition() stuff with new URLs. if(lastURL) { resetProperties(false); } // assign new HTML5 URL a.src = instanceOptions.url; s.url = instanceOptions.url; lastURL = instanceOptions.url; lastGlobalHTML5URL = instanceOptions.url; a._called_load = false; } } else { if(instanceOptions.autoLoad || instanceOptions.autoPlay) { s._a = new Audio(instanceOptions.url); s._a.load(); } else { // null for stupid Opera 9.64 case s._a = (isOpera && opera.version() < 10 ? new Audio(null) : new Audio()); } // assign local reference a = s._a; a._called_load = false; if(useGlobalHTML5Audio) { globalHTML5Audio = a; } } s.isHTML5 = true; // store a ref on the track s._a = a; // store a ref on the audio a._s = s; add_html5_events(); s._apply_loop(a, instanceOptions.loops); if(instanceOptions.autoLoad || instanceOptions.autoPlay) { s.load(); } else { // early HTML5 implementation (non-standard) a.autobuffer = false; // standard ('none' is also an option.) a.preload = 'auto'; } return a; }; add_html5_events = function() { if(s._a._added_events) { return false; } var f; function add(oEvt, oFn, bCapture) { return s._a ? s._a.addEventListener(oEvt, oFn, bCapture || false) : null; } s._a._added_events = true; for(f in html5_events) { if(html5_events.hasOwnProperty(f)) { add(f, html5_events[f]); } } return true; }; remove_html5_events = function() { // Remove event listeners var f; function remove(oEvt, oFn, bCapture) { return(s._a ? s._a.removeEventListener(oEvt, oFn, bCapture || false) : null); } sm2._wD(s.id + ': Removing event listeners'); s._a._added_events = false; for(f in html5_events) { if(html5_events.hasOwnProperty(f)) { remove(f, html5_events[f]); } } }; /** * Pseudo-private event internals * ------------------------------ */ this._onload = function(nSuccess) { var fN, // check for duration to prevent false positives from flash 8 when loading from cache. loadOK = !! nSuccess || (!s.isHTML5 && fV === 8 && s.duration); // <d> fN = s.id + ': '; sm2._wD(fN + (loadOK ? 'onload()' : 'Failed to load / invalid sound?' + (!s.duration ? ' Zero-length duration reported.' : ' -') + ' (' + s.url + ')'), (loadOK ? 1 : 2)); if(!loadOK && !s.isHTML5) { if(sm2.sandbox.noRemote === true) { sm2._wD(fN + str('noNet'), 1); } if(sm2.sandbox.noLocal === true) { sm2._wD(fN + str('noLocal'), 1); } } // </d> s.loaded = loadOK; s.readyState = loadOK ? 3 : 2; s._onbufferchange(0); if(s._iO.onload) { wrapCallback(s, function() { s._iO.onload.apply(s, [loadOK]); }); } return true; }; this._onbufferchange = function(nIsBuffering) { if(s.playState === 0) { // ignore if not playing return false; } if((nIsBuffering && s.isBuffering) || (!nIsBuffering && !s.isBuffering)) { return false; } s.isBuffering = (nIsBuffering === 1); if(s._iO.onbufferchange) { sm2._wD(s.id + ': Buffer state change: ' + nIsBuffering); s._iO.onbufferchange.apply(s, [nIsBuffering]); } return true; }; /** * Playback may have stopped due to buffering, or related reason. * This state can be encountered on iOS < 6 when auto-play is blocked. */ this._onsuspend = function() { if(s._iO.onsuspend) { sm2._wD(s.id + ': Playback suspended'); s._iO.onsuspend.apply(s); } return true; }; /** * flash 9/movieStar + RTMP-only method, should fire only once at most * at this point we just recreate failed sounds rather than trying to reconnect */ this._onfailure = function(msg, level, code) { s.failures++; sm2._wD(s.id + ': Failure (' + s.failures + '): ' + msg); if(s._iO.onfailure && s.failures === 1) { s._iO.onfailure(msg, level, code); } else { sm2._wD(s.id + ': Ignoring failure'); } }; /** * flash 9/movieStar + RTMP-only method for unhandled warnings/exceptions from Flash * e.g., RTMP "method missing" warning (non-fatal) for getStreamLength on server */ this._onwarning = function(msg, level, code) { if(s._iO.onwarning) { s._iO.onwarning(msg, level, code); } }; this._onfinish = function() { // store local copy before it gets trashed... var io_onfinish = s._iO.onfinish; s._onbufferchange(0); s._resetOnPosition(0); // reset some state items if(s.instanceCount) { s.instanceCount--; if(!s.instanceCount) { // remove onPosition listeners, if any detachOnPosition(); // reset instance options s.playState = 0; s.paused = false; s.instanceCount = 0; s.instanceOptions = {}; s._iO = {}; stop_html5_timer(); // reset position, too if(s.isHTML5) { s.position = 0; } } if(!s.instanceCount || s._iO.multiShotEvents) { // fire onfinish for last, or every instance if(io_onfinish) { sm2._wD(s.id + ': onfinish()'); wrapCallback(s, function() { io_onfinish.apply(s); }); } } } }; this._whileloading = function(nBytesLoaded, nBytesTotal, nDuration, nBufferLength) { var instanceOptions = s._iO; s.bytesLoaded = nBytesLoaded; s.bytesTotal = nBytesTotal; s.duration = Math.floor(nDuration); s.bufferLength = nBufferLength; if(!s.isHTML5 && !instanceOptions.isMovieStar) { if(instanceOptions.duration) { // use duration from options, if specified and larger. nobody should be specifying duration in options, actually, and it should be retired. s.durationEstimate = (s.duration > instanceOptions.duration) ? s.duration : instanceOptions.duration; } else { s.durationEstimate = parseInt((s.bytesTotal / s.bytesLoaded) * s.duration, 10); } } else { s.durationEstimate = s.duration; } // for flash, reflect sequential-load-style buffering if(!s.isHTML5) { s.buffered = [{ 'start': 0, 'end': s.duration }]; } // allow whileloading to fire even if "load" fired under HTML5, due to HTTP range/partials if((s.readyState !== 3 || s.isHTML5) && instanceOptions.whileloading) { instanceOptions.whileloading.apply(s); } }; this._whileplaying = function(nPosition, oPeakData, oWaveformDataLeft, oWaveformDataRight, oEQData) { var instanceOptions = s._iO, eqLeft; if(isNaN(nPosition) || nPosition === null) { // flash safety net return false; } // Safari HTML5 play() may return small -ve values when starting from position: 0, eg. -50.120396875. Unexpected/invalid per W3, I think. Normalize to 0. s.position = Math.max(0, nPosition); s._processOnPosition(); if(!s.isHTML5 && fV > 8) { if(instanceOptions.usePeakData && oPeakData !== _undefined && oPeakData) { s.peakData = { left: oPeakData.leftPeak, right: oPeakData.rightPeak }; } if(instanceOptions.useWaveformData && oWaveformDataLeft !== _undefined && oWaveformDataLeft) { s.waveformData = { left: oWaveformDataLeft.split(','), right: oWaveformDataRight.split(',') }; } if(instanceOptions.useEQData) { if(oEQData !== _undefined && oEQData && oEQData.leftEQ) { eqLeft = oEQData.leftEQ.split(','); s.eqData = eqLeft; s.eqData.left = eqLeft; if(oEQData.rightEQ !== _undefined && oEQData.rightEQ) { s.eqData.right = oEQData.rightEQ.split(','); } } } } if(s.playState === 1) { // special case/hack: ensure buffering is false if loading from cache (and not yet started) if(!s.isHTML5 && fV === 8 && !s.position && s.isBuffering) { s._onbufferchange(0); } if(instanceOptions.whileplaying) { // flash may call after actual finish instanceOptions.whileplaying.apply(s); } } return true; }; this._oncaptiondata = function(oData) { /** * internal: flash 9 + NetStream (MovieStar/RTMP-only) feature * * @param {object} oData */ sm2._wD(s.id + ': Caption data received.'); s.captiondata = oData; if(s._iO.oncaptiondata) { s._iO.oncaptiondata.apply(s, [oData]); } }; this._onmetadata = function(oMDProps, oMDData) { /** * internal: flash 9 + NetStream (MovieStar/RTMP-only) feature * RTMP may include song title, MovieStar content may include encoding info * * @param {array} oMDProps (names) * @param {array} oMDData (values) */ sm2._wD(s.id + ': Metadata received.'); var oData = {}, i, j; for(i = 0, j = oMDProps.length; i < j; i++) { oData[oMDProps[i]] = oMDData[i]; } s.metadata = oData; console.log('updated metadata', s.metadata); if(s._iO.onmetadata) { s._iO.onmetadata.call(s, s.metadata); } }; this._onid3 = function(oID3Props, oID3Data) { /** * internal: flash 8 + flash 9 ID3 feature * may include artist, song title etc. * * @param {array} oID3Props (names) * @param {array} oID3Data (values) */ sm2._wD(s.id + ': ID3 data received.'); var oData = [], i, j; for(i = 0, j = oID3Props.length; i < j; i++) { oData[oID3Props[i]] = oID3Data[i]; } s.id3 = mixin(s.id3, oData); if(s._iO.onid3) { s._iO.onid3.apply(s); } }; // flash/RTMP-only this._onconnect = function(bSuccess) { bSuccess = (bSuccess === 1); sm2._wD(s.id + ': ' + (bSuccess ? 'Connected.' : 'Failed to connect? - ' + s.url), (bSuccess ? 1 : 2)); s.connected = bSuccess; if(bSuccess) { s.failures = 0; if(idCheck(s.id)) { if(s.getAutoPlay()) { // only update the play state if auto playing s.play(_undefined, s.getAutoPlay()); } else if(s._iO.autoLoad) { s.load(); } } if(s._iO.onconnect) { s._iO.onconnect.apply(s, [bSuccess]); } } }; this._ondataerror = function(sError) { // flash 9 wave/eq data handler // hack: called at start, and end from flash at/after onfinish() if(s.playState > 0) { sm2._wD(s.id + ': Data error: ' + sError); if(s._iO.ondataerror) { s._iO.ondataerror.apply(s); } } }; // <d> this._debug(); // </d> }; // SMSound() /** * Private SoundManager internals * ------------------------------ */ getDocument = function() { return(doc.body || doc.getElementsByTagName('div')[0]); }; id = function(sID) { return doc.getElementById(sID); }; mixin = function(oMain, oAdd) { // non-destructive merge var o1 = (oMain || {}), o2, o; // if unspecified, o2 is the default options object o2 = (oAdd === _undefined ? sm2.defaultOptions : oAdd); for(o in o2) { if(o2.hasOwnProperty(o) && o1[o] === _undefined) { if(typeof o2[o] !== 'object' || o2[o] === null) { // assign directly o1[o] = o2[o]; } else { // recurse through o2 o1[o] = mixin(o1[o], o2[o]); } } } return o1; }; wrapCallback = function(oSound, callback) { /** * 03/03/2013: Fix for Flash Player 11.6.602.171 + Flash 8 (flashVersion = 8) SWF issue * setTimeout() fix for certain SMSound callbacks like onload() and onfinish(), where subsequent calls like play() and load() fail when Flash Player 11.6.602.171 is installed, and using soundManager with flashVersion = 8 (which is the default). * Not sure of exact cause. Suspect race condition and/or invalid (NaN-style) position argument trickling down to the next JS -> Flash _start() call, in the play() case. * Fix: setTimeout() to yield, plus safer null / NaN checking on position argument provided to Flash. * https://getsatisfaction.com/schillmania/topics/recent_chrome_update_seems_to_have_broken_my_sm2_audio_player */ if(!oSound.isHTML5 && fV === 8) { window.setTimeout(callback, 0); } else { callback(); } }; // additional soundManager properties that soundManager.setup() will accept extraOptions = { 'onready': 1, 'ontimeout': 1, 'defaultOptions': 1, 'flash9Options': 1, 'movieStarOptions': 1 }; assign = function(o, oParent) { /** * recursive assignment of properties, soundManager.setup() helper * allows property assignment based on whitelist */ var i, result = true, hasParent = (oParent !== _undefined), setupOptions = sm2.setupOptions, bonusOptions = extraOptions; // <d> // if soundManager.setup() called, show accepted parameters. if(o === _undefined) { result = []; for(i in setupOptions) { if(setupOptions.hasOwnProperty(i)) { result.push(i); } } for(i in bonusOptions) { if(bonusOptions.hasOwnProperty(i)) { if(typeof sm2[i] === 'object') { result.push(i + ': {...}'); } else if(sm2[i] instanceof Function) { result.push(i + ': function() {...}'); } else { result.push(i); } } } sm2._wD(str('setup', result.join(', '))); return false; } // </d> for(i in o) { if(o.hasOwnProperty(i)) { // if not an {object} we want to recurse through... if(typeof o[i] !== 'object' || o[i] === null || o[i] instanceof Array || o[i] instanceof RegExp) { // check "allowed" options if(hasParent && bonusOptions[oParent] !== _undefined) { // valid recursive / nested object option, eg., { defaultOptions: { volume: 50 } } sm2[oParent][i] = o[i]; } else if(setupOptions[i] !== _undefined) { // special case: assign to setupOptions object, which soundManager property references sm2.setupOptions[i] = o[i]; // assign directly to soundManager, too sm2[i] = o[i]; } else if(bonusOptions[i] === _undefined) { // invalid or disallowed parameter. complain. complain(str((sm2[i] === _undefined ? 'setupUndef' : 'setupError'), i), 2); result = false; } else { /** * valid extraOptions (bonusOptions) parameter. * is it a method, like onready/ontimeout? call it. * multiple parameters should be in an array, eg. soundManager.setup({onready: [myHandler, myScope]}); */ if(sm2[i] instanceof Function) { sm2[i].apply(sm2, (o[i] instanceof Array ? o[i] : [o[i]])); } else { // good old-fashioned direct assignment sm2[i] = o[i]; } } } else { // recursion case, eg., { defaultOptions: { ... } } if(bonusOptions[i] === _undefined) { // invalid or disallowed parameter. complain. complain(str((sm2[i] === _undefined ? 'setupUndef' : 'setupError'), i), 2); result = false; } else { // recurse through object return assign(o[i], i); } } } } return result; }; function preferFlashCheck(kind) { // whether flash should play a given type return(sm2.preferFlash && hasFlash && !sm2.ignoreFlash && (sm2.flash[kind] !== _undefined && sm2.flash[kind])); } /** * Internal DOM2-level event helpers * --------------------------------- */ event = (function() { // normalize event methods var old = (window.attachEvent), evt = { add: (old ? 'attachEvent' : 'addEventListener'), remove: (old ? 'detachEvent' : 'removeEventListener') }; // normalize "on" event prefix, optional capture argument function getArgs(oArgs) { var args = slice.call(oArgs), len = args.length; if(old) { // prefix args[1] = 'on' + args[1]; if(len > 3) { // no capture args.pop(); } } else if(len === 3) { args.push(false); } return args; } function apply(args, sType) { // normalize and call the event method, with the proper arguments var element = args.shift(), method = [evt[sType]]; if(old) { // old IE can't do apply(). element[method](args[0], args[1]); } else { element[method].apply(element, args); } } function add() { apply(getArgs(arguments), 'add'); } function remove() { apply(getArgs(arguments), 'remove'); } return { 'add': add, 'remove': remove }; }()); /** * Internal HTML5 event handling * ----------------------------- */ function html5_event(oFn) { // wrap html5 event handlers so we don't call them on destroyed and/or unloaded sounds return function(e) { var s = this._s, result; if(!s || !s._a) { // <d> if(s && s.id) { sm2._wD(s.id + ': Ignoring ' + e.type); } else { sm2._wD(h5 + 'Ignoring ' + e.type); } // </d> result = null; } else { result = oFn.call(this, e); } return result; }; } html5_events = { // HTML5 event-name-to-handler map abort: html5_event(function() { sm2._wD(this._s.id + ': abort'); }), // enough has loaded to play canplay: html5_event(function() { var s = this._s, position1K; if(s._html5_canplay) { // this event has already fired. ignore. return true; } s._html5_canplay = true; sm2._wD(s.id + ': canplay'); s._onbufferchange(0); // position according to instance options position1K = (s._iO.position !== _undefined && !isNaN(s._iO.position) ? s._iO.position / msecScale : null); // set the position if position was provided before the sound loaded if(this.currentTime !== position1K) { sm2._wD(s.id + ': canplay: Setting position to ' + position1K); try { this.currentTime = position1K; } catch(ee) { sm2._wD(s.id + ': canplay: Setting position of ' + position1K + ' failed: ' + ee.message, 2); } } // hack for HTML5 from/to case if(s._iO._oncanplay) { s._iO._oncanplay(); } }), canplaythrough: html5_event(function() { var s = this._s; if(!s.loaded) { s._onbufferchange(0); s._whileloading(s.bytesLoaded, s.bytesTotal, s._get_html5_duration()); s._onload(true); } }), durationchange: html5_event(function() { // durationchange may fire at various times, probably the safest way to capture accurate/final duration. var s = this._s, duration; duration = s._get_html5_duration(); if(!isNaN(duration) && duration !== s.duration) { sm2._wD(this._s.id + ': durationchange (' + duration + ')' + (s.duration ? ', previously ' + s.duration : '')); s.durationEstimate = s.duration = duration; } }), // TODO: Reserved for potential use /* emptied: html5_event(function() { sm2._wD(this._s.id + ': emptied'); }), */ ended: html5_event(function() { var s = this._s; sm2._wD(s.id + ': ended'); s._onfinish(); }), error: html5_event(function() { sm2._wD(this._s.id + ': HTML5 error, code ' + this.error.code); /** * HTML5 error codes, per W3C * Error 1: Client aborted download at user's request. * Error 2: Network error after load started. * Error 3: Decoding issue. * Error 4: Media (audio file) not supported. * Reference: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#error-codes */ // call load with error state? this._s._onload(false); }), loadeddata: html5_event(function() { var s = this._s; sm2._wD(s.id + ': loadeddata'); // safari seems to nicely report progress events, eventually totalling 100% if(!s._loaded && !isSafari) { s.duration = s._get_html5_duration(); } }), loadedmetadata: html5_event(function() { sm2._wD(this._s.id + ': loadedmetadata'); }), loadstart: html5_event(function() { sm2._wD(this._s.id + ': loadstart'); // assume buffering at first this._s._onbufferchange(1); }), play: html5_event(function() { // sm2._wD(this._s.id + ': play()'); // once play starts, no buffering this._s._onbufferchange(0); }), playing: html5_event(function() { sm2._wD(this._s.id + ': playing ' + String.fromCharCode(9835)); // once play starts, no buffering this._s._onbufferchange(0); }), progress: html5_event(function(e) { // note: can fire repeatedly after "loaded" event, due to use of HTTP range/partials var s = this._s, i, j, progStr, buffered = 0, isProgress = (e.type === 'progress'), ranges = e.target.buffered, // firefox 3.6 implements e.loaded/total (bytes) loaded = (e.loaded || 0), total = (e.total || 1); // reset the "buffered" (loaded byte ranges) array s.buffered = []; if(ranges && ranges.length) { // if loaded is 0, try TimeRanges implementation as % of load // https://developer.mozilla.org/en/DOM/TimeRanges // re-build "buffered" array // HTML5 returns seconds. SM2 API uses msec for setPosition() etc., whether Flash or HTML5. for(i = 0, j = ranges.length; i < j; i++) { s.buffered.push({ 'start': ranges.start(i) * msecScale, 'end': ranges.end(i) * msecScale }); } // use the last value locally buffered = (ranges.end(0) - ranges.start(0)) * msecScale; // linear case, buffer sum; does not account for seeking and HTTP partials / byte ranges loaded = Math.min(1, buffered / (e.target.duration * msecScale)); // <d> if(isProgress && ranges.length > 1) { progStr = []; j = ranges.length; for(i = 0; i < j; i++) { progStr.push(e.target.buffered.start(i) * msecScale + '-' + e.target.buffered.end(i) * msecScale); } sm2._wD(this._s.id + ': progress, timeRanges: ' + progStr.join(', ')); } if(isProgress && !isNaN(loaded)) { sm2._wD(this._s.id + ': progress, ' + Math.floor(loaded * 100) + '% loaded'); } // </d> } if(!isNaN(loaded)) { // TODO: prevent calls with duplicate values. s._whileloading(loaded, total, s._get_html5_duration()); if(loaded && total && loaded === total) { // in case "onload" doesn't fire (eg. gecko 1.9.2) html5_events.canplaythrough.call(this, e); } } }), ratechange: html5_event(function() { sm2._wD(this._s.id + ': ratechange'); }), suspend: html5_event(function(e) { // download paused/stopped, may have finished (eg. onload) var s = this._s; sm2._wD(this._s.id + ': suspend'); html5_events.progress.call(this, e); s._onsuspend(); }), stalled: html5_event(function() { sm2._wD(this._s.id + ': stalled'); }), timeupdate: html5_event(function() { this._s._onTimer(); }), waiting: html5_event(function() { var s = this._s; // see also: seeking sm2._wD(this._s.id + ': waiting'); // playback faster than download rate, etc. s._onbufferchange(1); }) }; html5OK = function(iO) { // playability test based on URL or MIME type var result; if(!iO || (!iO.type && !iO.url && !iO.serverURL)) { // nothing to check result = false; } else if(iO.serverURL || (iO.type && preferFlashCheck(iO.type))) { // RTMP, or preferring flash result = false; } else { // Use type, if specified. Pass data: URIs to HTML5. If HTML5-only mode, no other options, so just give 'er result = ((iO.type ? html5CanPlay({ type: iO.type }) : html5CanPlay({ url: iO.url }) || sm2.html5Only || iO.url.match(/data\:/i))); } return result; }; html5Unload = function(oAudio) { /** * Internal method: Unload media, and cancel any current/pending network requests. * Firefox can load an empty URL, which allegedly destroys the decoder and stops the download. * https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox#Stopping_the_download_of_media * However, Firefox has been seen loading a relative URL from '' and thus requesting the hosting page on unload. * Other UA behaviour is unclear, so everyone else gets an about:blank-style URL. */ var url; if(oAudio) { // Firefox and Chrome accept short WAVe data: URIs. Chome dislikes audio/wav, but accepts audio/wav for data: MIME. // Desktop Safari complains / fails on data: URI, so it gets about:blank. url = (isSafari ? emptyURL : (sm2.html5.canPlayType('audio/wav') ? emptyWAV : emptyURL)); oAudio.src = url; // reset some state, too if(oAudio._called_unload !== undefined) { oAudio._called_load = false; } } if(useGlobalHTML5Audio) { // ensure URL state is trashed, also lastGlobalHTML5URL = null; } return url; }; html5CanPlay = function(o) { /** * Try to find MIME, test and return truthiness * o = { * url: '/path/to/an.mp3', * type: 'audio/mp3' * } */ if(!sm2.useHTML5Audio || !sm2.hasHTML5) { return false; } var url = (o.url || null), mime = (o.type || null), aF = sm2.audioFormats, result, offset, fileExt, item; // account for known cases like audio/mp3 if(mime && sm2.html5[mime] !== _undefined) { return(sm2.html5[mime] && !preferFlashCheck(mime)); } if(!html5Ext) { html5Ext = []; for(item in aF) { if(aF.hasOwnProperty(item)) { html5Ext.push(item); if(aF[item].related) { html5Ext = html5Ext.concat(aF[item].related); } } } html5Ext = new RegExp('\\.(' + html5Ext.join('|') + ')(\\?.*)?$', 'i'); } // TODO: Strip URL queries, etc. fileExt = (url ? url.toLowerCase().match(html5Ext) : null); if(!fileExt || !fileExt.length) { if(!mime) { result = false; } else { // audio/mp3 -> mp3, result should be known offset = mime.indexOf(';'); // strip "audio/X; codecs..." fileExt = (offset !== -1 ? mime.substr(0, offset) : mime).substr(6); } } else { // match the raw extension name - "mp3", for example fileExt = fileExt[1]; } if(fileExt && sm2.html5[fileExt] !== _undefined) { // result known result = (sm2.html5[fileExt] && !preferFlashCheck(fileExt)); } else { mime = 'audio/' + fileExt; result = sm2.html5.canPlayType({ type: mime }); sm2.html5[fileExt] = result; // sm2._wD('canPlayType, found result: ' + result); result = (result && sm2.html5[mime] && !preferFlashCheck(mime)); } return result; }; testHTML5 = function() { /** * Internal: Iterates over audioFormats, determining support eg. audio/mp3, audio/mpeg and so on * assigns results to html5[] and flash[]. */ if(!sm2.useHTML5Audio || !sm2.hasHTML5) { // without HTML5, we need Flash. sm2.html5.usingFlash = true; needsFlash = true; return false; } // double-whammy: Opera 9.64 throws WRONG_ARGUMENTS_ERR if no parameter passed to Audio(), and Webkit + iOS happily tries to load "null" as a URL. :/ var a = (Audio !== _undefined ? (isOpera && opera.version() < 10 ? new Audio(null) : new Audio()) : null), item, lookup, support = {}, aF, i; function cp(m) { var canPlay, j, result = false, isOK = false; if(!a || typeof a.canPlayType !== 'function') { return result; } if(m instanceof Array) { // iterate through all mime types, return any successes for(i = 0, j = m.length; i < j; i++) { if(sm2.html5[m[i]] || a.canPlayType(m[i]).match(sm2.html5Test)) { isOK = true; sm2.html5[m[i]] = true; // note flash support, too sm2.flash[m[i]] = !! (m[i].match(flashMIME)); } } result = isOK; } else { canPlay = (a && typeof a.canPlayType === 'function' ? a.canPlayType(m) : false); result = !! (canPlay && (canPlay.match(sm2.html5Test))); } return result; } // test all registered formats + codecs aF = sm2.audioFormats; for(item in aF) { if(aF.hasOwnProperty(item)) { lookup = 'audio/' + item; support[item] = cp(aF[item].type); // write back generic type too, eg. audio/mp3 support[lookup] = support[item]; // assign flash if(item.match(flashMIME)) { sm2.flash[item] = true; sm2.flash[lookup] = true; } else { sm2.flash[item] = false; sm2.flash[lookup] = false; } // assign result to related formats, too if(aF[item] && aF[item].related) { for(i = aF[item].related.length - 1; i >= 0; i--) { // eg. audio/m4a support['audio/' + aF[item].related[i]] = support[item]; sm2.html5[aF[item].related[i]] = support[item]; sm2.flash[aF[item].related[i]] = support[item]; } } } } support.canPlayType = (a ? cp : null); sm2.html5 = mixin(sm2.html5, support); sm2.html5.usingFlash = featureCheck(); needsFlash = sm2.html5.usingFlash; return true; }; strings = { // <d> notReady: 'Unavailable - wait until onready() has fired.', notOK: 'Audio support is not available.', domError: sm + 'exception caught while appending SWF to DOM.', spcWmode: 'Removing wmode, preventing known SWF loading issue(s)', swf404: smc + 'Verify that %s is a valid path.', tryDebug: 'Try ' + sm + '.debugFlash = true for more security details (output goes to SWF.)', checkSWF: 'See SWF output for more debug info.', localFail: smc + 'Non-HTTP page (' + doc.location.protocol + ' URL?) Review Flash player security settings for this special case:\nhttp://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html\nMay need to add/allow path, eg. c:/sm2/ or /users/me/sm2/', waitFocus: smc + 'Special case: Waiting for SWF to load with window focus...', waitForever: smc + 'Waiting indefinitely for Flash (will recover if unblocked)...', waitSWF: smc + 'Waiting for 100% SWF load...', needFunction: smc + 'Function object expected for %s', badID: 'Sound ID "%s" should be a string, starting with a non-numeric character', currentObj: smc + '_debug(): Current sound objects', waitOnload: smc + 'Waiting for window.onload()', docLoaded: smc + 'Document already loaded', onload: smc + 'initComplete(): calling soundManager.onload()', onloadOK: sm + '.onload() complete', didInit: smc + 'init(): Already called?', secNote: 'Flash security note: Network/internet URLs will not load due to security restrictions. Access can be configured via Flash Player Global Security Settings Page: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html', badRemove: smc + 'Failed to remove Flash node.', shutdown: sm + '.disable(): Shutting down', queue: smc + 'Queueing %s handler', smError: 'SMSound.load(): Exception: JS-Flash communication failed, or JS error.', fbTimeout: 'No flash response, applying .' + swfCSS.swfTimedout + ' CSS...', fbLoaded: 'Flash loaded', fbHandler: smc + 'flashBlockHandler()', manURL: 'SMSound.load(): Using manually-assigned URL', onURL: sm + '.load(): current URL already assigned.', badFV: sm + '.flashVersion must be 8 or 9. "%s" is invalid. Reverting to %s.', as2loop: 'Note: Setting stream:false so looping can work (flash 8 limitation)', noNSLoop: 'Note: Looping not implemented for MovieStar formats', needfl9: 'Note: Switching to flash 9, required for MP4 formats.', mfTimeout: 'Setting flashLoadTimeout = 0 (infinite) for off-screen, mobile flash case', needFlash: smc + 'Fatal error: Flash is needed to play some required formats, but is not available.', gotFocus: smc + 'Got window focus.', policy: 'Enabling usePolicyFile for data access', setup: sm + '.setup(): allowed parameters: %s', setupError: sm + '.setup(): "%s" cannot be assigned with this method.', setupUndef: sm + '.setup(): Could not find option "%s"', setupLate: sm + '.setup(): url, flashVersion and html5Test property changes will not take effect until reboot().', noURL: smc + 'Flash URL required. Call soundManager.setup({url:...}) to get started.', sm2Loaded: 'SoundManager 2: Ready. ' + String.fromCharCode(10003), reset: sm + '.reset(): Removing event callbacks', mobileUA: 'Mobile UA detected, preferring HTML5 by default.', globalHTML5: 'Using singleton HTML5 Audio() pattern for this device.' // </d> }; str = function() { // internal string replace helper. // arguments: o [,items to replace] // <d> var args, i, j, o, sstr; // real array, please args = slice.call(arguments); // first argument o = args.shift(); sstr = (strings && strings[o] ? strings[o] : ''); if(sstr && args && args.length) { for(i = 0, j = args.length; i < j; i++) { sstr = sstr.replace('%s', args[i]); } } return sstr; // </d> }; loopFix = function(sOpt) { // flash 8 requires stream = false for looping to work if(fV === 8 && sOpt.loops > 1 && sOpt.stream) { _wDS('as2loop'); sOpt.stream = false; } return sOpt; }; policyFix = function(sOpt, sPre) { if(sOpt && !sOpt.usePolicyFile && (sOpt.onid3 || sOpt.usePeakData || sOpt.useWaveformData || sOpt.useEQData)) { sm2._wD((sPre || '') + str('policy')); sOpt.usePolicyFile = true; } return sOpt; }; complain = function(sMsg) { // <d> if(hasConsole && console.warn !== _undefined) { console.warn(sMsg); } else { sm2._wD(sMsg); } // </d> }; doNothing = function() { return false; }; disableObject = function(o) { var oProp; for(oProp in o) { if(o.hasOwnProperty(oProp) && typeof o[oProp] === 'function') { o[oProp] = doNothing; } } oProp = null; }; failSafely = function(bNoDisable) { // general failure exception handler if(bNoDisable === _undefined) { bNoDisable = false; } if(disabled || bNoDisable) { sm2.disable(bNoDisable); } }; normalizeMovieURL = function(smURL) { var urlParams = null, url; if(smURL) { if(smURL.match(/\.swf(\?.*)?$/i)) { urlParams = smURL.substr(smURL.toLowerCase().lastIndexOf('.swf?') + 4); if(urlParams) { // assume user knows what they're doing return smURL; } } else if(smURL.lastIndexOf('/') !== smURL.length - 1) { // append trailing slash, if needed smURL += '/'; } } url = (smURL && smURL.lastIndexOf('/') !== -1 ? smURL.substr(0, smURL.lastIndexOf('/') + 1) : './') + sm2.movieURL; if(sm2.noSWFCache) { url += ('?ts=' + new Date().getTime()); } return url; }; setVersionInfo = function() { // short-hand for internal use fV = parseInt(sm2.flashVersion, 10); if(fV !== 8 && fV !== 9) { sm2._wD(str('badFV', fV, defaultFlashVersion)); sm2.flashVersion = fV = defaultFlashVersion; } // debug flash movie, if applicable var isDebug = (sm2.debugMode || sm2.debugFlash ? '_debug.swf' : '.swf'); if(sm2.useHTML5Audio && !sm2.html5Only && sm2.audioFormats.mp4.required && fV < 9) { sm2._wD(str('needfl9')); sm2.flashVersion = fV = 9; } sm2.version = sm2.versionNumber + (sm2.html5Only ? ' (HTML5-only mode)' : (fV === 9 ? ' (AS3/Flash 9)' : ' (AS2/Flash 8)')); // set up default options if(fV > 8) { // +flash 9 base options sm2.defaultOptions = mixin(sm2.defaultOptions, sm2.flash9Options); sm2.features.buffering = true; // +moviestar support sm2.defaultOptions = mixin(sm2.defaultOptions, sm2.movieStarOptions); sm2.filePatterns.flash9 = new RegExp('\\.(mp3|' + netStreamTypes.join('|') + ')(\\?.*)?$', 'i'); sm2.features.movieStar = true; } else { sm2.features.movieStar = false; } // regExp for flash canPlay(), etc. sm2.filePattern = sm2.filePatterns[(fV !== 8 ? 'flash9' : 'flash8')]; // if applicable, use _debug versions of SWFs sm2.movieURL = (fV === 8 ? 'soundmanager2.swf' : 'soundmanager2_flash9.swf').replace('.swf', isDebug); sm2.features.peakData = sm2.features.waveformData = sm2.features.eqData = (fV > 8); }; setPolling = function(bPolling, bHighPerformance) { if(!flash) { return false; } flash._setPolling(bPolling, bHighPerformance); }; initDebug = function() { // starts debug mode, creating output <div> for UAs without console object // allow force of debug mode via URL // <d> if(sm2.debugURLParam.test(wl)) { sm2.debugMode = true; } if(id(sm2.debugID)) { return false; } var oD, oDebug, oTarget, oToggle, tmp; if(sm2.debugMode && !id(sm2.debugID) && (!hasConsole || !sm2.useConsole || !sm2.consoleOnly)) { oD = doc.createElement('div'); oD.id = sm2.debugID + '-toggle'; oToggle = { 'position': 'fixed', 'bottom': '0px', 'right': '0px', 'width': '1.2em', 'height': '1.2em', 'lineHeight': '1.2em', 'margin': '2px', 'textAlign': 'center', 'border': '1px solid #999', 'cursor': 'pointer', 'background': '#fff', 'color': '#333', 'zIndex': 10001 }; oD.appendChild(doc.createTextNode('-')); oD.onclick = toggleDebug; oD.title = 'Toggle SM2 debug console'; if(ua.match(/msie 6/i)) { oD.style.position = 'absolute'; oD.style.cursor = 'hand'; } for(tmp in oToggle) { if(oToggle.hasOwnProperty(tmp)) { oD.style[tmp] = oToggle[tmp]; } } oDebug = doc.createElement('div'); oDebug.id = sm2.debugID; oDebug.style.display = (sm2.debugMode ? 'block' : 'none'); if(sm2.debugMode && !id(oD.id)) { try { oTarget = getDocument(); oTarget.appendChild(oD); } catch(e2) { throw new Error(str('domError') + ' \n' + e2.toString()); } oTarget.appendChild(oDebug); } } oTarget = null; // </d> }; idCheck = this.getSoundById; // <d> _wDS = function(o, errorLevel) { return(!o ? '' : sm2._wD(str(o), errorLevel)); }; toggleDebug = function() { var o = id(sm2.debugID), oT = id(sm2.debugID + '-toggle'); if(!o) { return false; } if(debugOpen) { // minimize oT.innerHTML = '+'; o.style.display = 'none'; } else { oT.innerHTML = '-'; o.style.display = 'block'; } debugOpen = !debugOpen; }; debugTS = function(sEventType, bSuccess, sMessage) { // troubleshooter debug hooks if(window.sm2Debugger !== _undefined) { try { sm2Debugger.handleEvent(sEventType, bSuccess, sMessage); } catch(e) { // oh well return false; } } return true; }; // </d> getSWFCSS = function() { var css = []; if(sm2.debugMode) { css.push(swfCSS.sm2Debug); } if(sm2.debugFlash) { css.push(swfCSS.flashDebug); } if(sm2.useHighPerformance) { css.push(swfCSS.highPerf); } return css.join(' '); }; flashBlockHandler = function() { // *possible* flash block situation. var name = str('fbHandler'), p = sm2.getMoviePercent(), css = swfCSS, error = { type: 'FLASHBLOCK' }; if(sm2.html5Only) { // no flash, or unused return false; } if(!sm2.ok()) { if(needsFlash) { // make the movie more visible, so user can fix sm2.oMC.className = getSWFCSS() + ' ' + css.swfDefault + ' ' + (p === null ? css.swfTimedout : css.swfError); sm2._wD(name + ': ' + str('fbTimeout') + (p ? ' (' + str('fbLoaded') + ')' : '')); } sm2.didFlashBlock = true; // fire onready(), complain lightly processOnEvents({ type: 'ontimeout', ignoreInit: true, error: error }); catchError(error); } else { // SM2 loaded OK (or recovered) // <d> if(sm2.didFlashBlock) { sm2._wD(name + ': Unblocked'); } // </d> if(sm2.oMC) { sm2.oMC.className = [getSWFCSS(), css.swfDefault, css.swfLoaded + (sm2.didFlashBlock ? ' ' + css.swfUnblocked : '')].join(' '); } } }; addOnEvent = function(sType, oMethod, oScope) { if(on_queue[sType] === _undefined) { on_queue[sType] = []; } on_queue[sType].push({ 'method': oMethod, 'scope': (oScope || null), 'fired': false }); }; processOnEvents = function(oOptions) { // if unspecified, assume OK/error if(!oOptions) { oOptions = { type: (sm2.ok() ? 'onready' : 'ontimeout') }; } if(!didInit && oOptions && !oOptions.ignoreInit) { // not ready yet. return false; } if(oOptions.type === 'ontimeout' && (sm2.ok() || (disabled && !oOptions.ignoreInit))) { // invalid case return false; } var status = { success: (oOptions && oOptions.ignoreInit ? sm2.ok() : !disabled) }, // queue specified by type, or none srcQueue = (oOptions && oOptions.type ? on_queue[oOptions.type] || [] : []), queue = [], i, j, args = [status], canRetry = (needsFlash && !sm2.ok()); if(oOptions.error) { args[0].error = oOptions.error; } for(i = 0, j = srcQueue.length; i < j; i++) { if(srcQueue[i].fired !== true) { queue.push(srcQueue[i]); } } if(queue.length) { // sm2._wD(sm + ': Firing ' + queue.length + ' ' + oOptions.type + '() item' + (queue.length === 1 ? '' : 's')); for(i = 0, j = queue.length; i < j; i++) { if(queue[i].scope) { queue[i].method.apply(queue[i].scope, args); } else { queue[i].method.apply(this, args); } if(!canRetry) { // useFlashBlock and SWF timeout case doesn't count here. queue[i].fired = true; } } } return true; }; initUserOnload = function() { window.setTimeout(function() { if(sm2.useFlashBlock) { flashBlockHandler(); } processOnEvents(); // call user-defined "onload", scoped to window if(typeof sm2.onload === 'function') { _wDS('onload', 1); sm2.onload.apply(window); _wDS('onloadOK', 1); } if(sm2.waitForWindowLoad) { event.add(window, 'load', initUserOnload); } }, 1); }; detectFlash = function() { // hat tip: Flash Detect library (BSD, (C) 2007) by Carl "DocYes" <NAME> - http://featureblend.com/javascript-flash-detection-library.html / http://featureblend.com/license.txt if(hasFlash !== _undefined) { // this work has already been done. return hasFlash; } var hasPlugin = false, n = navigator, nP = n.plugins, obj, type, types, AX = window.ActiveXObject; if(nP && nP.length) { type = 'application/x-shockwave-flash'; types = n.mimeTypes; if(types && types[type] && types[type].enabledPlugin && types[type].enabledPlugin.description) { hasPlugin = true; } } else if(AX !== _undefined && !ua.match(/MSAppHost/i)) { // Windows 8 Store Apps (MSAppHost) are weird (compatibility?) and won't complain here, but will barf if Flash/ActiveX object is appended to the DOM. try { obj = new AX('ShockwaveFlash.ShockwaveFlash'); } catch(e) { // oh well obj = null; } hasPlugin = ( !! obj); // cleanup, because it is ActiveX after all obj = null; } hasFlash = hasPlugin; return hasPlugin; }; featureCheck = function() { var flashNeeded, item, formats = sm2.audioFormats, // iPhone <= 3.1 has broken HTML5 audio(), but firmware 3.2 (original iPad) + iOS4 works. isSpecial = (is_iDevice && !! (ua.match(/os (1|2|3_0|3_1)\s/i))); if(isSpecial) { // has Audio(), but is broken; let it load links directly. sm2.hasHTML5 = false; // ignore flash case, however sm2.html5Only = true; // hide the SWF, if present if(sm2.oMC) { sm2.oMC.style.display = 'none'; } } else { if(sm2.useHTML5Audio) { if(!sm2.html5 || !sm2.html5.canPlayType) { sm2._wD('SoundManager: No HTML5 Audio() support detected.'); sm2.hasHTML5 = false; } // <d> if(isBadSafari) { sm2._wD(smc + 'Note: Buggy HTML5 Audio in Safari on this OS X release, see https://bugs.webkit.org/show_bug.cgi?id=32159 - ' + (!hasFlash ? ' would use flash fallback for MP3/MP4, but none detected.' : 'will use flash fallback for MP3/MP4, if available'), 1); } // </d> } } if(sm2.useHTML5Audio && sm2.hasHTML5) { // sort out whether flash is optional, required or can be ignored. // innocent until proven guilty. canIgnoreFlash = true; for(item in formats) { if(formats.hasOwnProperty(item)) { if(formats[item].required) { if(!sm2.html5.canPlayType(formats[item].type)) { // 100% HTML5 mode is not possible. canIgnoreFlash = false; flashNeeded = true; } else if(sm2.preferFlash && (sm2.flash[item] || sm2.flash[formats[item].type])) { // flash may be required, or preferred for this format. flashNeeded = true; } } } } } // sanity check... if(sm2.ignoreFlash) { flashNeeded = false; canIgnoreFlash = true; } sm2.html5Only = (sm2.hasHTML5 && sm2.useHTML5Audio && !flashNeeded); return(!sm2.html5Only); }; parseURL = function(url) { /** * Internal: Finds and returns the first playable URL (or failing that, the first URL.) * @param {string or array} url A single URL string, OR, an array of URL strings or {url:'/path/to/resource', type:'audio/mp3'} objects. */ var i, j, urlResult = 0, result; if(url instanceof Array) { // find the first good one for(i = 0, j = url.length; i < j; i++) { if(url[i] instanceof Object) { // MIME check if(sm2.canPlayMIME(url[i].type)) { urlResult = i; break; } } else if(sm2.canPlayURL(url[i])) { // URL string check urlResult = i; break; } } // normalize to string if(url[urlResult].url) { url[urlResult] = url[urlResult].url; } result = url[urlResult]; } else { // single URL case result = url; } return result; }; startTimer = function(oSound) { /** * attach a timer to this sound, and start an interval if needed */ if(!oSound._hasTimer) { oSound._hasTimer = true; if(!mobileHTML5 && sm2.html5PollingInterval) { if(h5IntervalTimer === null && h5TimerCount === 0) { h5IntervalTimer = setInterval(timerExecute, sm2.html5PollingInterval); } h5TimerCount++; } } }; stopTimer = function(oSound) { /** * detach a timer */ if(oSound._hasTimer) { oSound._hasTimer = false; if(!mobileHTML5 && sm2.html5PollingInterval) { // interval will stop itself at next execution. h5TimerCount--; } } }; timerExecute = function() { /** * manual polling for HTML5 progress events, ie., whileplaying() (can achieve greater precision than conservative default HTML5 interval) */ var i; if(h5IntervalTimer !== null && !h5TimerCount) { // no active timers, stop polling interval. clearInterval(h5IntervalTimer); h5IntervalTimer = null; return false; } // check all HTML5 sounds with timers for(i = sm2.soundIDs.length - 1; i >= 0; i--) { if(sm2.sounds[sm2.soundIDs[i]].isHTML5 && sm2.sounds[sm2.soundIDs[i]]._hasTimer) { sm2.sounds[sm2.soundIDs[i]]._onTimer(); } } }; catchError = function(options) { options = (options !== _undefined ? options : {}); if(typeof sm2.onerror === 'function') { sm2.onerror.apply(window, [{ type: (options.type !== _undefined ? options.type : null) }]); } if(options.fatal !== _undefined && options.fatal) { sm2.disable(); } }; badSafariFix = function() { // special case: "bad" Safari (OS X 10.3 - 10.7) must fall back to flash for MP3/MP4 if(!isBadSafari || !detectFlash()) { // doesn't apply return false; } var aF = sm2.audioFormats, i, item; for(item in aF) { if(aF.hasOwnProperty(item)) { if(item === 'mp3' || item === 'mp4') { sm2._wD(sm + ': Using flash fallback for ' + item + ' format'); sm2.html5[item] = false; // assign result to related formats, too if(aF[item] && aF[item].related) { for(i = aF[item].related.length - 1; i >= 0; i--) { sm2.html5[aF[item].related[i]] = false; } } } } } }; /** * Pseudo-private flash/ExternalInterface methods * ---------------------------------------------- */ this._setSandboxType = function(sandboxType) { // <d> var sb = sm2.sandbox; sb.type = sandboxType; sb.description = sb.types[(sb.types[sandboxType] !== _undefined ? sandboxType : 'unknown')]; if(sb.type === 'localWithFile') { sb.noRemote = true; sb.noLocal = false; _wDS('secNote', 2); } else if(sb.type === 'localWithNetwork') { sb.noRemote = false; sb.noLocal = true; } else if(sb.type === 'localTrusted') { sb.noRemote = false; sb.noLocal = false; } // </d> }; this._externalInterfaceOK = function(swfVersion) { // flash callback confirming flash loaded, EI working etc. // swfVersion: SWF build string if(sm2.swfLoaded) { return false; } var e; debugTS('swf', true); debugTS('flashtojs', true); sm2.swfLoaded = true; tryInitOnFocus = false; if(isBadSafari) { badSafariFix(); } // complain if JS + SWF build/version strings don't match, excluding +DEV builds // <d> if(!swfVersion || swfVersion.replace(/\+dev/i, '') !== sm2.versionNumber.replace(/\+dev/i, '')) { e = sm + ': Fatal: JavaScript file build "' + sm2.versionNumber + '" does not match Flash SWF build "' + swfVersion + '" at ' + sm2.url + '. Ensure both are up-to-date.'; // escape flash -> JS stack so this error fires in window. setTimeout(function versionMismatch() { throw new Error(e); }, 0); // exit, init will fail with timeout return false; } // </d> // IE needs a larger timeout setTimeout(init, isIE ? 100 : 1); }; /** * Private initialization helpers * ------------------------------ */ createMovie = function(smID, smURL) { if(didAppend && appendSuccess) { // ignore if already succeeded return false; } function initMsg() { // <d> var options = [], title, msg = [], delimiter = ' + '; title = 'SoundManager ' + sm2.version + (!sm2.html5Only && sm2.useHTML5Audio ? (sm2.hasHTML5 ? ' + HTML5 audio' : ', no HTML5 audio support') : ''); if(!sm2.html5Only) { if(sm2.preferFlash) { options.push('preferFlash'); } if(sm2.useHighPerformance) { options.push('useHighPerformance'); } if(sm2.flashPollingInterval) { options.push('flashPollingInterval (' + sm2.flashPollingInterval + 'ms)'); } if(sm2.html5PollingInterval) { options.push('html5PollingInterval (' + sm2.html5PollingInterval + 'ms)'); } if(sm2.wmode) { options.push('wmode (' + sm2.wmode + ')'); } if(sm2.debugFlash) { options.push('debugFlash'); } if(sm2.useFlashBlock) { options.push('flashBlock'); } } else { if(sm2.html5PollingInterval) { options.push('html5PollingInterval (' + sm2.html5PollingInterval + 'ms)'); } } if(options.length) { msg = msg.concat([options.join(delimiter)]); } sm2._wD(title + (msg.length ? delimiter + msg.join(', ') : ''), 1); showSupport(); // </d> } if(sm2.html5Only) { // 100% HTML5 mode setVersionInfo(); initMsg(); sm2.oMC = id(sm2.movieID); init(); // prevent multiple init attempts didAppend = true; appendSuccess = true; return false; } // flash path var remoteURL = (smURL || sm2.url), localURL = (sm2.altURL || remoteURL), swfTitle = 'JS/Flash audio component (SoundManager 2)', oTarget = getDocument(), extraClass = getSWFCSS(), isRTL = null, html = doc.getElementsByTagName('html')[0], oEmbed, oMovie, tmp, movieHTML, oEl, s, x, sClass; isRTL = (html && html.dir && html.dir.match(/rtl/i)); smID = (smID === _undefined ? sm2.id : smID); function param(name, value) { return '<param name="' + name + '" value="' + value + '" />'; } // safety check for legacy (change to Flash 9 URL) setVersionInfo(); sm2.url = normalizeMovieURL(overHTTP ? remoteURL : localURL); smURL = sm2.url; sm2.wmode = (!sm2.wmode && sm2.useHighPerformance ? 'transparent' : sm2.wmode); if(sm2.wmode !== null && (ua.match(/msie 8/i) || (!isIE && !sm2.useHighPerformance)) && navigator.platform.match(/win32|win64/i)) { /** * extra-special case: movie doesn't load until scrolled into view when using wmode = anything but 'window' here * does not apply when using high performance (position:fixed means on-screen), OR infinite flash load timeout * wmode breaks IE 8 on Vista + Win7 too in some cases, as of January 2011 (?) */ messages.push(strings.spcWmode); sm2.wmode = null; } oEmbed = { 'name': smID, 'id': smID, 'src': smURL, 'quality': 'high', 'allowScriptAccess': sm2.allowScriptAccess, 'bgcolor': sm2.bgColor, 'pluginspage': http + 'www.macromedia.com/go/getflashplayer', 'title': swfTitle, 'type': 'application/x-shockwave-flash', 'wmode': sm2.wmode, // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html 'hasPriority': 'true' }; if(sm2.debugFlash) { oEmbed.FlashVars = 'debug=1'; } if(!sm2.wmode) { // don't write empty attribute delete oEmbed.wmode; } if(isIE) { // IE is "special". oMovie = doc.createElement('div'); movieHTML = ['<object id="' + smID + '" data="' + smURL + '" type="' + oEmbed.type + '" title="' + oEmbed.title + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="' + http + 'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0">', param('movie', smURL), param('AllowScriptAccess', sm2.allowScriptAccess), param('quality', oEmbed.quality), (sm2.wmode ? param('wmode', sm2.wmode) : ''), param('bgcolor', sm2.bgColor), param('hasPriority', 'true'), (sm2.debugFlash ? param('FlashVars', oEmbed.FlashVars) : ''), '</object>' ].join(''); } else { oMovie = doc.createElement('embed'); for(tmp in oEmbed) { if(oEmbed.hasOwnProperty(tmp)) { oMovie.setAttribute(tmp, oEmbed[tmp]); } } } initDebug(); extraClass = getSWFCSS(); oTarget = getDocument(); if(oTarget) { sm2.oMC = (id(sm2.movieID) || doc.createElement('div')); if(!sm2.oMC.id) { sm2.oMC.id = sm2.movieID; sm2.oMC.className = swfCSS.swfDefault + ' ' + extraClass; s = null; oEl = null; if(!sm2.useFlashBlock) { if(sm2.useHighPerformance) { // on-screen at all times s = { 'position': 'fixed', 'width': '8px', 'height': '8px', // >= 6px for flash to run fast, >= 8px to start up under Firefox/win32 in some cases. odd? yes. 'bottom': '0px', 'left': '0px', 'overflow': 'hidden' }; } else { // hide off-screen, lower priority s = { 'position': 'absolute', 'width': '6px', 'height': '6px', 'top': '-9999px', 'left': '-9999px' }; if(isRTL) { s.left = Math.abs(parseInt(s.left, 10)) + 'px'; } } } if(isWebkit) { // soundcloud-reported render/crash fix, safari 5 sm2.oMC.style.zIndex = 10000; } if(!sm2.debugFlash) { for(x in s) { if(s.hasOwnProperty(x)) { sm2.oMC.style[x] = s[x]; } } } try { if(!isIE) { sm2.oMC.appendChild(oMovie); } oTarget.appendChild(sm2.oMC); if(isIE) { oEl = sm2.oMC.appendChild(doc.createElement('div')); oEl.className = swfCSS.swfBox; oEl.innerHTML = movieHTML; } appendSuccess = true; } catch(e) { throw new Error(str('domError') + ' \n' + e.toString()); } } else { // SM2 container is already in the document (eg. flashblock use case) sClass = sm2.oMC.className; sm2.oMC.className = (sClass ? sClass + ' ' : swfCSS.swfDefault) + (extraClass ? ' ' + extraClass : ''); sm2.oMC.appendChild(oMovie); if(isIE) { oEl = sm2.oMC.appendChild(doc.createElement('div')); oEl.className = swfCSS.swfBox; oEl.innerHTML = movieHTML; } appendSuccess = true; } } didAppend = true; initMsg(); // sm2._wD(sm + ': Trying to load ' + smURL + (!overHTTP && sm2.altURL ? ' (alternate URL)' : ''), 1); return true; }; initMovie = function() { if(sm2.html5Only) { createMovie(); return false; } // attempt to get, or create, movie (may already exist) if(flash) { return false; } if(!sm2.url) { /** * Something isn't right - we've reached init, but the soundManager url property has not been set. * User has not called setup({url: ...}), or has not set soundManager.url (legacy use case) directly before init time. * Notify and exit. If user calls setup() with a url: property, init will be restarted as in the deferred loading case. */ _wDS('noURL'); return false; } // inline markup case flash = sm2.getMovie(sm2.id); if(!flash) { if(!oRemoved) { // try to create createMovie(sm2.id, sm2.url); } else { // try to re-append removed movie after reboot() if(!isIE) { sm2.oMC.appendChild(oRemoved); } else { sm2.oMC.innerHTML = oRemovedHTML; } oRemoved = null; didAppend = true; } flash = sm2.getMovie(sm2.id); } if(typeof sm2.oninitmovie === 'function') { setTimeout(sm2.oninitmovie, 1); } // <d> flushMessages(); // </d> return true; }; delayWaitForEI = function() { setTimeout(waitForEI, 1000); }; rebootIntoHTML5 = function() { // special case: try for a reboot with preferFlash: false, if 100% HTML5 mode is possible and useFlashBlock is not enabled. window.setTimeout(function() { complain(smc + 'useFlashBlock is false, 100% HTML5 mode is possible. Rebooting with preferFlash: false...'); sm2.setup({ preferFlash: false }).reboot(); // if for some reason you want to detect this case, use an ontimeout() callback and look for html5Only and didFlashBlock == true. sm2.didFlashBlock = true; sm2.beginDelayedInit(); }, 1); }; waitForEI = function() { var p, loadIncomplete = false; if(!sm2.url) { // No SWF url to load (noURL case) - exit for now. Will be retried when url is set. return false; } if(waitingForEI) { return false; } waitingForEI = true; event.remove(window, 'load', delayWaitForEI); if(hasFlash && tryInitOnFocus && !isFocused) { // Safari won't load flash in background tabs, only when focused. _wDS('waitFocus'); return false; } if(!didInit) { p = sm2.getMoviePercent(); if(p > 0 && p < 100) { loadIncomplete = true; } } setTimeout(function() { p = sm2.getMoviePercent(); if(loadIncomplete) { // special case: if movie *partially* loaded, retry until it's 100% before assuming failure. waitingForEI = false; sm2._wD(str('waitSWF')); window.setTimeout(delayWaitForEI, 1); return false; } // <d> if(!didInit) { sm2._wD(sm + ': No Flash response within expected time. Likely causes: ' + (p === 0 ? 'SWF load failed, ' : '') + 'Flash blocked or JS-Flash security error.' + (sm2.debugFlash ? ' ' + str('checkSWF') : ''), 2); if(!overHTTP && p) { _wDS('localFail', 2); if(!sm2.debugFlash) { _wDS('tryDebug', 2); } } if(p === 0) { // if 0 (not null), probably a 404. sm2._wD(str('swf404', sm2.url), 1); } debugTS('flashtojs', false, ': Timed out' + overHTTP ? ' (Check flash security or flash blockers)' : ' (No plugin/missing SWF?)'); } // </d> // give up / time-out, depending if(!didInit && okToDisable) { if(p === null) { // SWF failed to report load progress. Possibly blocked. if(sm2.useFlashBlock || sm2.flashLoadTimeout === 0) { if(sm2.useFlashBlock) { flashBlockHandler(); } _wDS('waitForever'); } else { // no custom flash block handling, but SWF has timed out. Will recover if user unblocks / allows SWF load. if(!sm2.useFlashBlock && canIgnoreFlash) { rebootIntoHTML5(); } else { _wDS('waitForever'); // fire any regular registered ontimeout() listeners. processOnEvents({ type: 'ontimeout', ignoreInit: true, error: { type: 'INIT_FLASHBLOCK' } }); } } } else { // SWF loaded? Shouldn't be a blocking issue, then. if(sm2.flashLoadTimeout === 0) { _wDS('waitForever'); } else { if(!sm2.useFlashBlock && canIgnoreFlash) { rebootIntoHTML5(); } else { failSafely(true); } } } } }, sm2.flashLoadTimeout); }; handleFocus = function() { function cleanup() { event.remove(window, 'focus', handleFocus); } if(isFocused || !tryInitOnFocus) { // already focused, or not special Safari background tab case cleanup(); return true; } okToDisable = true; isFocused = true; _wDS('gotFocus'); // allow init to restart waitingForEI = false; // kick off ExternalInterface timeout, now that the SWF has started delayWaitForEI(); cleanup(); return true; }; flushMessages = function() { // <d> // SM2 pre-init debug messages if(messages.length) { sm2._wD('SoundManager 2: ' + messages.join(' '), 1); messages = []; } // </d> }; showSupport = function() { // <d> flushMessages(); var item, tests = []; if(sm2.useHTML5Audio && sm2.hasHTML5) { for(item in sm2.audioFormats) { if(sm2.audioFormats.hasOwnProperty(item)) { tests.push(item + ' = ' + sm2.html5[item] + (!sm2.html5[item] && needsFlash && sm2.flash[item] ? ' (using flash)' : (sm2.preferFlash && sm2.flash[item] && needsFlash ? ' (preferring flash)' : (!sm2.html5[item] ? ' (' + (sm2.audioFormats[item].required ? 'required, ' : '') + 'and no flash support)' : '')))); } } sm2._wD('SoundManager 2 HTML5 support: ' + tests.join(', '), 1); } // </d> }; initComplete = function(bNoDisable) { if(didInit) { return false; } if(sm2.html5Only) { // all good. _wDS('sm2Loaded', 1); didInit = true; initUserOnload(); debugTS('onload', true); return true; } var wasTimeout = (sm2.useFlashBlock && sm2.flashLoadTimeout && !sm2.getMoviePercent()), result = true, error; if(!wasTimeout) { didInit = true; } error = { type: (!hasFlash && needsFlash ? 'NO_FLASH' : 'INIT_TIMEOUT') }; sm2._wD('SoundManager 2 ' + (disabled ? 'failed to load' : 'loaded') + ' (' + (disabled ? 'Flash security/load error' : 'OK') + ') ' + String.fromCharCode(disabled ? 10006 : 10003), disabled ? 2 : 1); if(disabled || bNoDisable) { if(sm2.useFlashBlock && sm2.oMC) { sm2.oMC.className = getSWFCSS() + ' ' + (sm2.getMoviePercent() === null ? swfCSS.swfTimedout : swfCSS.swfError); } processOnEvents({ type: 'ontimeout', error: error, ignoreInit: true }); debugTS('onload', false); catchError(error); result = false; } else { debugTS('onload', true); } if(!disabled) { if(sm2.waitForWindowLoad && !windowLoaded) { _wDS('waitOnload'); event.add(window, 'load', initUserOnload); } else { // <d> if(sm2.waitForWindowLoad && windowLoaded) { _wDS('docLoaded'); } // </d> initUserOnload(); } } return result; }; /** * apply top-level setupOptions object as local properties, eg., this.setupOptions.flashVersion -> this.flashVersion (soundManager.flashVersion) * this maintains backward compatibility, and allows properties to be defined separately for use by soundManager.setup(). */ setProperties = function() { var i, o = sm2.setupOptions; for(i in o) { if(o.hasOwnProperty(i)) { // assign local property if not already defined if(sm2[i] === _undefined) { sm2[i] = o[i]; } else if(sm2[i] !== o[i]) { // legacy support: write manually-assigned property (eg., soundManager.url) back to setupOptions to keep things in sync sm2.setupOptions[i] = sm2[i]; } } } }; init = function() { // called after onload() if(didInit) { _wDS('didInit'); return false; } function cleanup() { event.remove(window, 'load', sm2.beginDelayedInit); } if(sm2.html5Only) { if(!didInit) { // we don't need no steenking flash! cleanup(); sm2.enabled = true; initComplete(); } return true; } // flash path initMovie(); try { // attempt to talk to Flash flash._externalInterfaceTest(false); // apply user-specified polling interval, OR, if "high performance" set, faster vs. default polling // (determines frequency of whileloading/whileplaying callbacks, effectively driving UI framerates) setPolling(true, (sm2.flashPollingInterval || (sm2.useHighPerformance ? 10 : 50))); if(!sm2.debugMode) { // stop the SWF from making debug output calls to JS flash._disableDebug(); } sm2.enabled = true; debugTS('jstoflash', true); if(!sm2.html5Only) { // prevent browser from showing cached page state (or rather, restoring "suspended" page state) via back button, because flash may be dead // http://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ event.add(window, 'unload', doNothing); } } catch(e) { sm2._wD('js/flash exception: ' + e.toString()); debugTS('jstoflash', false); catchError({ type: 'JS_TO_FLASH_EXCEPTION', fatal: true }); // don't disable, for reboot() failSafely(true); initComplete(); return false; } initComplete(); // disconnect events cleanup(); return true; }; domContentLoaded = function() { if(didDCLoaded) { return false; } didDCLoaded = true; // assign top-level soundManager properties eg. soundManager.url setProperties(); initDebug(); /** * Temporary feature: allow force of HTML5 via URL params: sm2-usehtml5audio=0 or 1 * Ditto for sm2-preferFlash, too. */ // <d> (function() { var a = 'sm2-usehtml5audio=', a2 = 'sm2-preferflash=', b = null, b2 = null, l = wl.toLowerCase(); if(l.indexOf(a) !== -1) { b = (l.charAt(l.indexOf(a) + a.length) === '1'); if(hasConsole) { console.log((b ? 'Enabling ' : 'Disabling ') + 'useHTML5Audio via URL parameter'); } sm2.setup({ 'useHTML5Audio': b }); } if(l.indexOf(a2) !== -1) { b2 = (l.charAt(l.indexOf(a2) + a2.length) === '1'); if(hasConsole) { console.log((b2 ? 'Enabling ' : 'Disabling ') + 'preferFlash via URL parameter'); } sm2.setup({ 'preferFlash': b2 }); } }()); // </d> if(!hasFlash && sm2.hasHTML5) { sm2._wD('SoundManager 2: No Flash detected' + (!sm2.useHTML5Audio ? ', enabling HTML5.' : '. Trying HTML5-only mode.'), 1); sm2.setup({ 'useHTML5Audio': true, // make sure we aren't preferring flash, either // TODO: preferFlash should not matter if flash is not installed. Currently, stuff breaks without the below tweak. 'preferFlash': false }); } testHTML5(); if(!hasFlash && needsFlash) { messages.push(strings.needFlash); // TODO: Fatal here vs. timeout approach, etc. // hack: fail sooner. sm2.setup({ 'flashLoadTimeout': 1 }); } if(doc.removeEventListener) { doc.removeEventListener('DOMContentLoaded', domContentLoaded, false); } initMovie(); return true; }; domContentLoadedIE = function() { if(doc.readyState === 'complete') { domContentLoaded(); doc.detachEvent('onreadystatechange', domContentLoadedIE); } return true; }; winOnLoad = function() { // catch edge case of initComplete() firing after window.load() windowLoaded = true; // catch case where DOMContentLoaded has been sent, but we're still in doc.readyState = 'interactive' domContentLoaded(); event.remove(window, 'load', winOnLoad); }; /** * miscellaneous run-time, pre-init stuff */ preInit = function() { if(mobileHTML5) { // prefer HTML5 for mobile + tablet-like devices, probably more reliable vs. flash at this point. // <d> if(!sm2.setupOptions.useHTML5Audio || sm2.setupOptions.preferFlash) { // notify that defaults are being changed. messages.push(strings.mobileUA); } // </d> sm2.setupOptions.useHTML5Audio = true; sm2.setupOptions.preferFlash = false; if(is_iDevice || (isAndroid && !ua.match(/android\s2\.3/i))) { // iOS and Android devices tend to work better with a single audio instance, specifically for chained playback of sounds in sequence. // common use case: exiting sound onfinish() -> createSound() -> play() // <d> messages.push(strings.globalHTML5); // </d> if(is_iDevice) { sm2.ignoreFlash = true; } useGlobalHTML5Audio = true; } } }; preInit(); // sniff up-front detectFlash(); // focus and window load, init (primarily flash-driven) event.add(window, 'focus', handleFocus); event.add(window, 'load', delayWaitForEI); event.add(window, 'load', winOnLoad); if(doc.addEventListener) { doc.addEventListener('DOMContentLoaded', domContentLoaded, false); } else if(doc.attachEvent) { doc.attachEvent('onreadystatechange', domContentLoadedIE); } else { // no add/attachevent support - safe to assume no JS -> Flash either debugTS('onload', false); catchError({ type: 'NO_DOM2_EVENTS', fatal: true }); } } // SoundManager() // SM2_DEFER details: http://www.schillmania.com/projects/soundmanager2/doc/getstarted/#lazy-loading if(window.SM2_DEFER === undefined || !SM2_DEFER) { soundManager = new SoundManager(); } /** * SoundManager public interfaces * ------------------------------ */ if(typeof module === 'object' && module && typeof module.exports === 'object') { /** * commonJS module * note: SM2 requires a window global due to Flash, which makes calls to window.soundManager. * flash may not always be needed, but this is not known until async init and SM2 may even "reboot" into Flash mode. */ window.soundManager = soundManager; module.exports.SoundManager = SoundManager; module.exports.soundManager = soundManager; } else if(typeof define === 'function' && define.amd) { // AMD - requireJS define('SoundManager', [], function() { return { SoundManager: SoundManager, soundManager: soundManager }; }); } else { // standard browser case window.SoundManager = SoundManager; // constructor window.soundManager = soundManager; // public API, flash callbacks etc. } }(window)); var ngSoundManager = angular.module('angularSoundManager', []) .config(['$logProvider', function($logProvider){ $logProvider.debugEnabled(false); }]); ngSoundManager.filter('humanTime', function () { return function (input) { function pad(d) { return (d < 10) ? '0' + d.toString() : d.toString(); } var min = (input / 1000 / 60) << 0, sec = Math.floor((input / 1000) % 60); return pad(min) + ':' + pad(sec); }; }); ngSoundManager.factory('angularPlayer', ['$rootScope', '$log', function($rootScope, $log) { var currentTrack = null, repeat = false, autoPlay = true, isPlaying = false, volume = 90, trackProgress = 0, playlist = [], shuffle = false, repeatOne = false, shufflelist= [], shuffleCount = 0, shuffleIndex = -1, bootstrapTrack = null; return { /** * Initialize soundmanager, * requires soundmanager2 to be loaded first */ init: function() { if(typeof soundManager === 'undefined') { alert('Please include SoundManager2 Library!'); } soundManager.setup({ //url: '/path/to/swfs/', //flashVersion: 9, preferFlash: false, // prefer 100% HTML5 mode, where both supported debugMode: false, // enable debugging output ($log.debug() with HTML fallback) useHTML5Audio: true, onready: function() { //$log.debug('sound manager ready!'); }, ontimeout: function() { alert('SM2 failed to start. Flash missing, blocked or security error?'); alert('The status is ' + status.success + ', the error type is ' + status.error.type); }, defaultOptions: { // set global default volume for all sound objects autoLoad: false, // enable automatic loading (otherwise .load() will call with .play()) autoPlay: false, // enable playing of file ASAP (much faster if "stream" is true) from: null, // position to start playback within a sound (msec), see demo loops: 1, // number of times to play the sound. Related: looping (API demo) multiShot: false, // let sounds "restart" or "chorus" when played multiple times.. multiShotEvents: false, // allow events (onfinish()) to fire for each shot, if supported. onid3: null, // callback function for "ID3 data is added/available" onload: null, // callback function for "load finished" onstop: null, // callback for "user stop" onfailure: 'nextTrack', // callback function for when playing fails onpause: null, // callback for "pause" onplay: null, // callback for "play" start onresume: null, // callback for "resume" (pause toggle) position: null, // offset (milliseconds) to seek to within downloaded sound. pan: 0, // "pan" settings, left-to-right, -100 to 100 stream: true, // allows playing before entire file has loaded (recommended) to: null, // position to end playback within a sound (msec), see demo type: 'audio/mp3', // MIME-like hint for canPlay() tests, eg. 'audio/mp3' usePolicyFile: false, // enable crossdomain.xml request for remote domains (for ID3/waveform access) volume: volume, // self-explanatory. 0-100, the latter being the max. whileloading: function() { //soundManager._writeDebug('sound '+this.id+' loading, '+this.bytesLoaded+' of '+this.bytesTotal); var trackLoaded = ((this.bytesLoaded/this.bytesTotal)*100); $rootScope.$broadcast('track:loaded', trackLoaded); }, whileplaying: function() { //soundManager._writeDebug('sound '+this.id+' playing, '+this.position+' of '+this.duration); //broadcast current playing track id currentTrack = this.id; //$rootScope.$broadcast('track:id', this.id); //broadcast current playing track progress trackProgress = ((this.position / this.duration) * 100); $rootScope.$broadcast('track:progress', trackProgress); //broadcast track position $rootScope.$broadcast('currentTrack:position', this.position); //broadcast track duration $rootScope.$broadcast('currentTrack:duration', this.duration); }, onfinish: function() { soundManager._writeDebug(this.id + ' finished playing'); if(autoPlay === true) { //play next track if autoplay is on //get your angular app var elem = angular.element(document.querySelector('[ng-app]')); //get the injector. var injector = elem.injector(); //get the service. var angularPlayer = injector.get('angularPlayer'); // repeat current track if(repeatOne === true) { angularPlayer.playTrack(this.id); } else { angularPlayer.nextTrack(); } $rootScope.$broadcast('track:id', currentTrack); } } } }); soundManager.onready(function() { $log.debug('song manager ready!'); // Ready to use; soundManager.createSound() etc. can now be called. var isSupported = soundManager.ok(); $log.debug('is supported: ' + isSupported); $rootScope.$broadcast('angularPlayer:ready', true); }); }, /** * To check if value is in array */ isInArray: function(array, value) { for(var i = 0; i < array.length; i++) { if(array[i].id === value) { return i; } } return false; }, /** * getIndexByValue used by this factory */ getIndexByValue: function(array, value) { for(var i = 0; i < array.length; i++) { if(array[i] === value) { return i; } } return false; }, /** * asyncLoop used by this factory */ asyncLoop: function(o) { var i = -1; var loop = function() { i++; if(i == o.length) { o.callback(); return; } o.functionToLoop(loop, i); }; loop(); //init }, setCurrentTrack: function(key) { currentTrack = key; }, getCurrentTrack: function() { return currentTrack; }, currentTrackData: function() { var trackId = this.getCurrentTrack(); var currentKey = this.isInArray(playlist, trackId); return playlist[currentKey]; }, getPlaylist: function(key) { if(typeof key === 'undefined') { return playlist; } else { return playlist[key]; } }, getTrack: function(trackId) { for (var i=0; i< playlist.length; i++) { if (playlist[i].id == trackId) { return playlist[i]; } } return null; }, addToPlaylist: function(track) { playlist.push(track); //broadcast playlist $rootScope.$broadcast('player:playlist', playlist); }, isTrackValid: function (track) { if (typeof track == 'undefined') { $log.debug('invalid track data'); return false; } if (track.url.indexOf("soundcloud") > -1) { //if soundcloud url if(typeof track.url == 'undefined') { $log.debug('invalid soundcloud track url'); return false; } } else { if(soundManager.canPlayURL(track.url) !== true) { $log.debug('invalid song url'); return false; } } }, addTrack: function(track) { //check if track itself is valid and if its url is playable // disable track valid check because request url without // proper extension name can be playable. // if (!this.isTrackValid) { // return null; // } //check if song already does not exists then add to playlist var inArrayKey = this.isInArray(this.getPlaylist(), track.id); if(inArrayKey === false) { //$log.debug('song does not exists in playlist'); //add to sound manager soundManager.createSound({ id: track.id, url: track.url }); shufflelist.push(track.id); //add to playlist this.addToPlaylist(track); } return track.id; }, addTrackArray: function(trackArray) { for(var i = 0; i < trackArray.length; i++) { var track = trackArray[i]; //check if track itself is valid and if its url is playable // if (!this.isTrackValid(track)) { // console.log('track invalid'); // continue; // } //check if song already does not exists then add to playlist var inArrayKey = this.isInArray(this.getPlaylist(), track.id); if(inArrayKey === false) { //$log.debug('song does not exists in playlist'); //add to sound manager soundManager.createSound({ id: track.id, url: track.url }); shufflelist.push(track.id); //add to playlist playlist.push(track); } } //broadcast playlist $rootScope.$broadcast('player:playlist', playlist); }, removeSong: function(song, index) { //if this song is playing stop it if(song === currentTrack) { this.stop(); } //unload from soundManager soundManager.destroySound(song); //remove from playlist playlist.splice(index, 1); //remove from shufflelist var removeIndex = this.getIndexByValue(shufflelist, song); shufflelist.splice(removeIndex, 1); if (removeIndex <= shuffleIndex) { shuffleIndex --; } if (removeIndex <= shuffleCount - 1 ) { shuffleCount --; } //once all done then broadcast $rootScope.$broadcast('player:playlist', playlist); }, initPlayTrack: function(trackId, isResume, isloadOnly, successCallback, failCallback) { if(isResume !== true) { //stop and unload currently playing track this.stop(); //set new track as current track this.setCurrentTrack(trackId); } if ((bootstrapTrack != null) && (isResume !== true)) { var angularPlayerObj = this; var sound = soundManager.getSoundById(trackId); sound.setVolume(volume); bootstrapTrack(sound, this.currentTrackData(), function(){ soundManager.play(trackId); $rootScope.$broadcast('track:id', trackId); //set as playing isPlaying = true; $rootScope.$broadcast('music:isPlaying', isPlaying); if (isloadOnly == true) { angularPlayerObj.pause(); } if(successCallback != undefined) { successCallback(); } }, function(){ if(failCallback != undefined) { failCallback(); } }); } else { soundManager.play(trackId); $rootScope.$broadcast('track:id', trackId); //set as playing isPlaying = true; $rootScope.$broadcast('music:isPlaying', isPlaying); } }, play: function() { var trackToPlay = null; //check if no track loaded, else play loaded track if(this.getCurrentTrack() === null) { if(soundManager.soundIDs.length === 0) { $log.debug('playlist is empty!'); return; } trackToPlay = soundManager.soundIDs[0]; this.initPlayTrack(trackToPlay); } else { trackToPlay = this.getCurrentTrack(); this.initPlayTrack(trackToPlay, true); } }, pause: function() { soundManager.pause(this.getCurrentTrack()); //set as not playing isPlaying = false; $rootScope.$broadcast('music:isPlaying', isPlaying); }, stop: function() { //first pause it this.pause(); this.resetProgress(); $rootScope.$broadcast('track:progress', trackProgress); $rootScope.$broadcast('currentTrack:position', 0); $rootScope.$broadcast('currentTrack:duration', 0); soundManager.stopAll(); soundManager.unload(this.getCurrentTrack()); }, loadTrack: function(trackId) { // play track and pause at beginning this.initPlayTrack(trackId, false, true); }, playTrack: function(trackId) { var player = this; this.initPlayTrack(trackId, false, false, undefined, function(){player.nextTrack()}); }, playTrackFailToPrev: function(trackId) { var player = this; this.initPlayTrack(trackId, false, false, undefined, function(){player.prevTrack()}); }, nextTrack: function() { if (shuffle) { if (shuffleCount == 0) { if (shufflelist.length == 0){ // initial shuffle related data shufflelist = soundManager.soundIDs.slice(); } // swap current song to first element var index = this.getIndexByValue(shufflelist, this.getCurrentTrack()); var temp = shufflelist[index]; shufflelist[index] = shufflelist[shuffleCount]; shufflelist[shuffleCount] = temp; shuffleIndex++; shuffleCount++; } if (shuffleIndex + 1 < shuffleCount) { shuffleIndex++; this.playTrack(shufflelist[shuffleIndex]); return; } // choose one song from [shuffleCount, shufflelist.length-1] if (shuffleCount == shufflelist.length) { shuffleCount = 0; shuffleIndex = -1; } var index = shuffleCount + Math.floor(Math.random() * (shufflelist.length-shuffleCount)); // swap shuffle count and index var temp = shufflelist[index]; shufflelist[index] = shufflelist[shuffleCount]; shufflelist[shuffleCount] = temp; shuffleIndex++; this.playTrack(shufflelist[shuffleIndex]); shuffleCount++; return; } if(this.getCurrentTrack() === null) { $log.debug("Please click on Play before this action"); return null; } var currentTrackKey = this.getIndexByValue(soundManager.soundIDs, this.getCurrentTrack()); var nextTrackKey = +currentTrackKey + 1; var nextTrackId = soundManager.soundIDs[nextTrackKey]; if(typeof nextTrackId !== 'undefined') { this.playTrack(nextTrackId); } else { //if no next track found if(repeat === true) { //start first track if repeat is on this.playTrack(soundManager.soundIDs[0]); } else { //breadcase not playing anything isPlaying = false; $rootScope.$broadcast('music:isPlaying', isPlaying); } } }, prevTrack: function() { if (shuffle) { if (shuffleIndex <= 0){ // no prev found return; } shuffleIndex--; this.playTrackFailToPrev(shufflelist[shuffleIndex]); return; } if(this.getCurrentTrack() === null) { $log.debug("Please click on Play before this action"); return null; } var currentTrackKey = this.getIndexByValue(soundManager.soundIDs, this.getCurrentTrack()); var prevTrackKey = +currentTrackKey - 1; var prevTrackId = soundManager.soundIDs[prevTrackKey]; if(typeof prevTrackId !== 'undefined') { this.playTrackFailToPrev(prevTrackId); } else { $log.debug('no prev track found!'); } }, mute: function() { if(soundManager.muted === true) { soundManager.unmute(); } else { soundManager.mute(); } $rootScope.$broadcast('music:mute', soundManager.muted); }, getMuteStatus: function() { return soundManager.muted; }, repeatToggle: function() { if(repeat === true) { repeat = false; } else { repeat = true; } $rootScope.$broadcast('music:repeat', repeat); }, getRepeatStatus: function() { return repeat; }, repeatOneToggle: function() { if(repeatOne === true) { repeatOne = false; } else { repeatOne = true; } }, getRepeatOneStatus: function() { return repeatOne; }, setRepeatOneStatus: function(value) { repeatOne = value ; }, getVolume: function() { return volume; }, adjustVolume: function(increase) { var changeVolume = function(volume) { for(var i = 0; i < soundManager.soundIDs.length; i++) { var mySound = soundManager.getSoundById(soundManager.soundIDs[i]); mySound.setVolume(volume); } $rootScope.$broadcast('music:volume', volume); }; if(increase === true) { if(volume < 100) { volume = volume + 10; changeVolume(volume); } } else { if(volume > 0) { volume = volume - 10; changeVolume(volume); } } }, adjustVolumeSlider: function(value) { var changeVolume = function(volume) { for(var i = 0; i < soundManager.soundIDs.length; i++) { var mySound = soundManager.getSoundById(soundManager.soundIDs[i]); mySound.setVolume(volume); } $rootScope.$broadcast('music:volume', volume); }; volume = value; changeVolume(value); }, clearPlaylist: function(callback) { $log.debug('clear playlist'); this.resetProgress(); this.clearShuffle(); //unload and destroy soundmanager sounds var smIdsLength = soundManager.soundIDs.length; this.asyncLoop({ length: smIdsLength, functionToLoop: function(loop, i) { setTimeout(function() { //custom code soundManager.destroySound(soundManager.soundIDs[0]); //custom code loop(); // accelerate remove speed reduce timeout to 0 }, 0); }, callback: function() { //callback custom code $log.debug('All done!'); //clear playlist playlist = []; $rootScope.$broadcast('player:playlist', playlist); callback(true); //callback custom code } }); }, resetProgress: function() { trackProgress = 0; }, isPlayingStatus: function() { return isPlaying; }, clearShuffle: function() { shufflelist = []; shuffleCount = 0; shuffleIndex = -1; }, getShuffle: function(){ return shuffle; }, toggleShuffle: function() { shuffle = !shuffle; this.clearShuffle(); }, setBootstrapTrack: function(fn){ bootstrapTrack = fn; } }; } ]); ngSoundManager.directive('soundManager', ['$filter', '$timeout', 'angularPlayer', function($filter, $timeout, angularPlayer) { return { restrict: "E", link: function(scope, element, attrs) { //init and load sound manager 2 angularPlayer.init(); scope.$on('track:progress', function(event, data) { $timeout(function() { scope.progress = data; }); }); scope.$on('track:id', function(event, data) { $timeout(function() { scope.currentPlaying = angularPlayer.currentTrackData(); }); }); scope.$on('currentTrack:position', function(event, data) { $timeout(function() { scope.currentPosition = $filter('humanTime')(data); }); }); scope.$on('currentTrack:duration', function(event, data) { $timeout(function() { scope.currentDuration = $filter('humanTime')(data); }); }); scope.isPlaying = false; scope.$on('music:isPlaying', function(event, data) { $timeout(function() { scope.isPlaying = data; }); }); scope.playlist = angularPlayer.getPlaylist(); //on load scope.$on('player:playlist', function(event, data) { $timeout(function() { scope.playlist = data; }); }); } }; } ]); ngSoundManager.directive('musicPlayer', ['angularPlayer', '$log', function(angularPlayer, $log) { return { restrict: "EA", scope: { song: "=addSong" }, link: function(scope, element, attrs) { var addToPlaylist = function() { var trackId = angularPlayer.addTrack(scope.song); //if request to play the track if(attrs.musicPlayer === 'play') { angularPlayer.playTrack(trackId); } }; element.bind('click', function() { $log.debug('adding song to playlist'); addToPlaylist(); }); } }; } ]); ngSoundManager.directive('playFromPlaylist', ['angularPlayer', function (angularPlayer) { return { restrict: "EA", scope: { song: "=playFromPlaylist" }, link: function (scope, element, attrs) { element.bind('click', function (event) { angularPlayer.playTrack(scope.song.id); }); } }; }]); ngSoundManager.directive('removeFromPlaylist', ['angularPlayer', function(angularPlayer) { return { restrict: "EA", scope: { song: "=removeFromPlaylist" }, link: function(scope, element, attrs) { element.bind('click', function(event) { angularPlayer.removeSong(scope.song.id, attrs.index); }); } }; } ]); ngSoundManager.directive('seekTrack', ['angularPlayer', '$log', function (angularPlayer, $log) { return { restrict: "EA", link: function (scope, element, attrs) { element.bind('click', function (event) { if (angularPlayer.getCurrentTrack() === null) { $log.debug('no track loaded'); return; } var sound = soundManager.getSoundById(angularPlayer.getCurrentTrack()); var getXOffset = function (event) { var x = 0, element = event.target; while (element && !isNaN(element.offsetLeft) && !isNaN(element.offsetTop)) { x += element.offsetLeft - element.scrollLeft; element = element.offsetParent; } return event.clientX - x; }; var x = event.offsetX || getXOffset(event), width = element[0].clientWidth, duration = sound.durationEstimate; sound.setPosition((x / width) * duration); }); } }; }]); ngSoundManager.directive('playMusic', ['angularPlayer', function (angularPlayer) { return { restrict: "EA", link: function (scope, element, attrs) { element.bind('click', function (event) { angularPlayer.play(); }); } }; }]); ngSoundManager.directive('pauseMusic', ['angularPlayer', function (angularPlayer) { return { restrict: "EA", link: function (scope, element, attrs) { element.bind('click', function (event) { angularPlayer.pause(); }); } }; }]); ngSoundManager.directive('stopMusic', ['angularPlayer', function (angularPlayer) { return { restrict: "EA", link: function (scope, element, attrs) { element.bind('click', function (event) { angularPlayer.stop(); }); } }; }]); ngSoundManager.directive('nextTrack', ['angularPlayer', function (angularPlayer) { return { restrict: "EA", link: function (scope, element, attrs) { element.bind('click', function (event) { angularPlayer.nextTrack(); }); } }; }]); ngSoundManager.directive('prevTrack', ['angularPlayer', function (angularPlayer) { return { restrict: "EA", link: function (scope, element, attrs) { element.bind('click', function (event) { angularPlayer.prevTrack(); }); } }; }]); ngSoundManager.directive('muteMusic', ['angularPlayer', function (angularPlayer) { return { restrict: "EA", link: function (scope, element, attrs) { element.bind('click', function (event) { angularPlayer.mute(); }); scope.mute = angularPlayer.getMuteStatus(); scope.$on('music:mute', function (event, data) { scope.$apply(function () { scope.mute = data; }); }); } }; }]); ngSoundManager.directive('repeatMusic', ['angularPlayer', function (angularPlayer) { return { restrict: "EA", link: function (scope, element, attrs) { element.bind('click', function (event) { angularPlayer.repeatToggle(); }); scope.repeat = angularPlayer.getRepeatStatus(); scope.$on('music:repeat', function (event, data) { scope.$apply(function () { scope.repeat = data; }); }); } }; }]); ngSoundManager.directive('musicVolume', ['angularPlayer', function(angularPlayer) { return { restrict: "EA", link: function(scope, element, attrs) { element.bind('click', function(event) { if(attrs.type === 'increase') { angularPlayer.adjustVolume(true); } else { angularPlayer.adjustVolume(false); } }); scope.volume = angularPlayer.getVolume(); scope.$on('music:volume', function(event, data) { scope.$apply(function() { scope.volume = data; }); }); } }; } ]); ngSoundManager.directive('clearPlaylist', ['angularPlayer', '$log', function(angularPlayer, $log) { return { restrict: "EA", link: function(scope, element, attrs) { element.bind('click', function(event) { //first stop any playing music angularPlayer.stop(); angularPlayer.setCurrentTrack(null); angularPlayer.clearPlaylist(function(data) { $log.debug('all clear!'); }); }); } }; } ]); ngSoundManager.directive('playAll', ['angularPlayer', '$log', function(angularPlayer, $log) { return { restrict: "EA", scope: { songs: '=playAll' }, link: function(scope, element, attrs) { element.bind('click', function(event) { //first clear the playlist angularPlayer.clearPlaylist(function(data) { $log.debug('cleared, ok now add to playlist'); //add songs to playlist for(var i = 0; i < scope.songs.length; i++) { angularPlayer.addTrack(scope.songs[i]); } if (attrs.play != 'false') { //play first song angularPlayer.play(); } }); }); } }; } ]); ngSoundManager.directive('volumeBar', ['angularPlayer', function(angularPlayer) { return { restrict: "EA", link: function(scope, element, attrs) { element.bind('click', function(event) { var getXOffset = function(event) { var x = 0, element = event.target; while(element && !isNaN(element.offsetLeft) && !isNaN(element.offsetTop)) { x += element.offsetLeft - element.scrollLeft; element = element.offsetParent; } return event.clientX - x; }; var x = event.offsetX || getXOffset(event), width = element[0].clientWidth, duration = 100; var volume = (x / width) * duration; angularPlayer.adjustVolumeSlider(volume); }); scope.volume = angularPlayer.getVolume(); scope.$on('music:volume', function(event, data) { scope.$apply(function() { scope.volume = data; }); }); } }; } ]); ngSoundManager.directive('playPauseToggle', ['angularPlayer', function(angularPlayer) { return { restrict: "EA", link: function(scope, element, attrs) { scope.$on('music:isPlaying', function(event, data) { //update html if (data) { if(typeof attrs.pause != 'undefined') { element.html(attrs.pause); } else { element.html('Pause'); } } else { if(typeof attrs.play != 'undefined') { element.html(attrs.play); } else { element.html('Play'); } } }); element.bind('click', function(event) { if(angularPlayer.isPlayingStatus()) { //if playing then pause angularPlayer.pause(); } else { //else play if not playing angularPlayer.play(); } }); } }; } ]);
1.28125
1
js/app/job/event-log-adder.js
hal-platform/hal
16
951
import 'jquery'; import { generateIcon } from '../util/icon'; import { formatTime } from '../util/time-formatter'; import { initEventLogLoader } from '../job/event-log-loader'; let logTableTarget = '.js-event-logs', logTarget = '[data-log]'; var $logTable = null, logs = {}; function initEventLogAdder() { // global state: logs, $logTable // stub event logs, dont need to be updated further $logTable = $(logTableTarget); if ($logTable.length <= 0) { return; } $logTable .find(logTarget) .each(function(index, item) { let id = $(item).data('log'); logs[id] = 'embedded'; }); } // Requires these properties: // - count // - _embedded.events // - _embedded.events[].id // - _embedded.events[].name // - _embedded.events[].message // - _embedded.events[].created function checkEventLogs($elem) { // global state: $logTable, logs if ($logTable === null) { return; } let id = $elem.data('build'), logsEndpoint = generateURL(id); $.getJSON(logsEndpoint, function(data) { if (data.count < 1) { return; } if (!data._embedded || !data._embedded.events) { return; } let logs = data._embedded.events, hasNewLogs = false; for(let index in logs) { let log = logs[index]; if (typeof logs[log.id] == 'undefined') { hasNewLogs = true; logs[log.id] = log.message; $logTable .append(renderEventRow(log)); } } if (hasNewLogs) { $logTable .find('.js-empty-row') .remove().end() .find('.js-thinking-row') .appendTo($logTable); } }); } function updateEventLogTable(jobStatus) { // global state: $logTable, logTarget if ($logTable === null) { return; } handleThinkingLogs($logTable, jobStatus); handleLogExpanding($logTable, logTarget, jobStatus); } // Handles the "Be patient, log messages are loading" message. function handleThinkingLogs($table, jobStatus) { if (jobStatus == 'pending' || jobStatus == 'running' || jobStatus == 'deploying') { var $thinking = $table.find('.js-thinking-row'); // If thinking row already exists, just move it to the bottom if ($thinking.length > 0) { $thinking.appendTo($table); } else { $thinking = $('<tbody class="js-thinking-row">') .append('<tr><td><span class="status-icon--thinking">Loading...</span></td></tr>') .appendTo($table); } } else { $table .find('.js-thinking-row') .remove(); } } // Attach event log loader once the job is finished. function handleLogExpanding($table, eventTarget, jobStatus) { // global state: $logTable, logTarget if ($table === null) { return; } // is finished if (jobStatus == 'success' || jobStatus == 'failure') { // wait 2 seconds so any remaining logs can be loaded window.setTimeout(() => { $table .find(eventTarget) .each((i, e) => { $(e).attr('data-log-loadable', '1'); }); initEventLogLoader(); }, 2000); } } function renderEventRow(event) { let event_name = formatEventName(event.name), event_time = formatTime(event.created), event_failure_class = event.status === 'failure' ? 'event-log--error' : ''; let event_block_class = 'status-block--info'; let event_icon = 'paragraph-justify-2'; if (event.status === 'success') { event_block_class = 'status-block--success'; event_icon = 'tick'; } if (event.status === 'failure') { event_block_class = 'status-block--error'; event_icon = 'spam-2'; } let event_icon_svg = generateIcon(event_icon); let template = ` <tbody data-log="${event.id}"> <tr class="${event_failure_class}"> <td> <span class="${event_block_class}"> ${event_icon_svg} ${event_name} </span> </td> <td> <time datetime="${event.created}" title="${event_time.absolute}">${event_time.relative}</time> </td> <td>${event.message}</td> <td class="tr js-event-logs-loader"></td> </tr> </tbody> `; return template; } function formatEventName(eventName) { let eventRegex = /^(build|release).([a-z]*)$/i, match = null, logName = ''; match = eventRegex.exec(eventName); if (match !== null && match.length > 0) { logName = match.pop(); } return logName.charAt(0).toUpperCase() + logName.slice(1); } function generateURL(buildID) { return '/api/builds/' + buildID + '/events?embed=events'; } export { initEventLogAdder, checkEventLogs, updateEventLogTable };
1.429688
1
src/lib/graphql-client.js
zexhan17/my-developer-portfolio
0
959
import { GraphQLClient } from 'graphql-request' const GRAPHQL_ENDPOINT = import.meta.env.VITE_GRAPHQL_API export const client = new GraphQLClient(GRAPHQL_ENDPOINT)
0.589844
1
packages/ui/src/components/common/APSelect/APGroupSelect.js
max-vorabhol-zipmex/express-app
0
967
import React from 'react'; import PropTypes from 'prop-types'; import { Field } from 'redux-form'; import classnames from 'classnames'; import { getBEMClasses } from '../../../helpers/cssClassesHelper'; import { Text } from 'design/typography'; import './APSelect.css'; export const GroupSelect = (props) => { const { input, meta, classModifiers, customClass, info, label, onSelect, showTriangles, optionGroups = [], placeholder, ...passedProps } = props; const baseClasses = getBEMClasses(['ap-select', customClass]); return ( <div className={`form-group ${baseClasses('select-wrapper', classModifiers)}`} > <label className={`ap--label ${baseClasses('select-label')}`}> <Text>{label}</Text> </label> {showTriangles ? ( <div className={baseClasses('triangles-container')}> <span className={'triangle-down'} /> </div> ) : ( '' )} <select className={classnames( `form-control ${baseClasses('select')}`, input && !input.value && baseClasses('select-unselected') )} {...input} {...passedProps} onChange={(e) => { if (onSelect) onSelect(e.target.value); input && input.onChange(e); }} > {placeholder && ( <option className={baseClasses('option-placeholder')} value="" disabled > {placeholder} </option> )} {optionGroups.map((i) => { return ( <optgroup key={i.label} label={i.label}> {i.options.map((j) => { return ( <option key={j.value} value={j.value}> {j.label} </option> ); })} </optgroup> ); })} </select> <small className={`form-text-muted ${baseClasses('select-info')}`}> {info} </small> {meta && meta.dirty && meta.error && ( <span className={baseClasses('select-error')}>{meta.error}</span> )} </div> ); }; const APGroupSelect = (props) => ( <Field name={props.name} component={GroupSelect} {...props} /> ); APGroupSelect.defaultProps = { name: '', label: '', classes: 'input', customClass: 'custom-select', classModifiers: '', info: '', autoFocus: '', disabled: false, multiple: false, required: false, }; APGroupSelect.propTypes = { name: PropTypes.string, label: PropTypes.string, classes: PropTypes.string, customClass: PropTypes.string, classModifiers: PropTypes.string, info: PropTypes.string, autoFocus: PropTypes.string, onSelect: PropTypes.func, disabled: PropTypes.bool, multiple: PropTypes.bool, required: PropTypes.bool, placeholder: PropTypes.string, }; export default APGroupSelect;
1.554688
2
word-consumer/index.js
Dunkelheit/word-platform
0
975
'use strict'; const kafka = require('kafka-node'); const log = require('./log'); const metrics = require('./metrics'); log.info('Starting up word-consumer'); const Producer = kafka.Producer; const Consumer = kafka.Consumer; const client = new kafka.Client('zookeeper:2181', 'word-consumer-client', { spinDelay: 1000, retries: 20 }); const producer = new Producer(client); const consumer = new Consumer(client, [{ topic: 'Words', partition: 0}], { autoCommit: false }); let producerReady = false; consumer.on('message', function (message) { metrics.increment('messages.received.word-consumer'); log.debug({ topic: message.topic, message: message.value }, 'Word consumer received a message'); const messageObject = JSON.parse(message.value); const points = messageObject.message.split(' ').length; const userId = messageObject.userId; log.debug({ points, userId }, 'Word consumer transforms the message into points'); if (!producerReady) { log.fatal('Producer is not ready yet!'); } const payloadMessage = JSON.stringify({ points, userId }); const payloads = [{ topic: 'Points', messages: [payloadMessage] }]; producer.send(payloads, function (err, data) { metrics.increment('messages.sent.word-consumer'); if (err) { log.error(err, 'An error has occurred!'); } log.debug({ data, payloadMessage }, 'Word consumer sent some transformed data'); }); }); producer.on('ready', function () { producerReady = true; log.info('Producer is ready'); });
1.914063
2
test/int/coin/bitcore/address.js
bookmoons/cashshufflejs
3
983
import test from 'ava' import Coin from 'coin/bitcore/main' import address from 'coin/bitcore/address' const publicKeyString = '<KEY>' const expectedAddress = 'bitcoincash:qp63uahgrxged4z5jswyt5dn5v3lzsem6cy4spdc2h' test.before(t => { Object.assign(Coin.prototype, { address }) }) test('correct', async t => { const coin = new Coin() const producedAddress = await coin.address(publicKeyString) t.is(producedAddress, expectedAddress) })
1.265625
1
src/server.js
islam-Attar/basic-api-server
0
991
'use strict'; const express = require('express'); const app = express(); const cors = require('cors'); app.use(express.json()); const logger = require('./middleware/logger.js') // const validator = require('./middleware/validator.js'); const notFound = require('./error-handlers/404.js'); const serverError = require('./error-handlers/500.js'); const clothesRouter = require('./routes/clothes'); const foodRouter = require('./routes/food'); app.use(cors()); app.use(logger); app.use(clothesRouter); app.use(foodRouter); app.get('/', (req, res) => { res.send('Home Route') }) app.use(notFound); app.use(serverError); function start(port) { app.listen(port,()=> { console.log(`running on PORT ${port}`); }) } module.exports = { app: app, start: start }
1.25
1
client/helpers/map-domain-description.js
samarabbas/temporal-web
0
999
export default function(d) { // eslint-disable-next-line no-param-reassign d.configuration = d.configuration || {}; // eslint-disable-next-line no-param-reassign d.replicationConfiguration = d.replicationConfiguration || { clusters: [] }; return { description: d.domainInfo.description, owner: d.domainInfo.ownerEmail, 'Global?': d.isGlobalDomain ? 'Yes' : 'No', 'Retention Period': `${d.configuration.workflowExecutionRetentionPeriodInDays} days`, 'Emit Metrics': d.configuration.emitMetric ? 'Yes' : 'No', 'Failover Version': d.failoverVersion, clusters: d.replicationConfiguration.clusters .map(c => c.clusterName === d.replicationConfiguration.activeClusterName ? `${c.clusterName} (active)` : c.clusterName ) .join(', '), }; }
0.820313
1
kliq-admin/src/views/components/accordion/AccordionHover.js
kliqadmin/kliq.club
0
1007
// ** React Imports import { useState } from 'react' // ** Reactstrap Imports import { Accordion, AccordionBody, AccordionHeader, AccordionItem } from 'reactstrap' const AccordionHover = () => { // ** State const [open, setOpen] = useState('') const toggle = id => { open === id ? setOpen() : setOpen(id) } return ( <Accordion open={open} toggle={toggle}> <AccordionItem onMouseEnter={() => toggle('1')} onMouseLeave={() => toggle('1')}> <AccordionHeader targetId='1'>Accordion Item 1</AccordionHeader> <AccordionBody accordionId='1'> Gummi bears toffee soufflé jelly carrot cake pudding sweet roll bear claw. Sweet roll gingerbread wafer liquorice cake tiramisu. Gummi bears caramels bonbon icing croissant lollipop topping lollipop danish. Marzipan tootsie roll bonbon toffee icing lollipop cotton candy pie gummies. Gingerbread bear claw chocolate cake bonbon. Liquorice marzipan cotton candy liquorice tootsie roll macaroon marzipan danish. </AccordionBody> </AccordionItem> <AccordionItem onMouseEnter={() => toggle('2')} onMouseLeave={() => toggle('2')}> <AccordionHeader targetId='2'>Accordion Item 2</AccordionHeader> <AccordionBody accordionId='2'> Soufflé sugar plum bonbon lemon drops candy canes icing brownie. Dessert tart dessert apple pie. Muffin wafer cookie. Soufflé fruitcake lollipop chocolate bar. Muffin gummi bears marzipan sesame snaps gummi bears topping toffee. Cupcake bonbon muffin. Cake caramels candy lollipop cheesecake bonbon soufflé apple pie cake. </AccordionBody> </AccordionItem> <AccordionItem onMouseEnter={() => toggle('3')} onMouseLeave={() => toggle('3')}> <AccordionHeader targetId='3'>Accordion Item 3</AccordionHeader> <AccordionBody accordionId='3'> Soufflé sugar plum bonbon lemon drops candy canes icing brownie. Dessert tart dessert apple pie. Muffin wafer cookie. Soufflé fruitcake lollipop chocolate bar. Muffin gummi bears marzipan sesame snaps gummi bears topping toffee. Cupcake bonbon muffin. Cake caramels candy lollipop cheesecake bonbon soufflé apple pie cake. </AccordionBody> </AccordionItem> <AccordionItem onMouseEnter={() => toggle('4')} onMouseLeave={() => toggle('4')}> <AccordionHeader targetId='4'>Accordion Item 4</AccordionHeader> <AccordionBody accordionId='4'> Marzipan candy apple pie icing. Sweet roll pudding dragée icing icing cookie pie fruitcake caramels. Bonbon candy canes candy canes. Dragée jelly beans chocolate bar dragée biscuit fruitcake gingerbread toffee apple pie. Gingerbread donut powder ice cream sesame snaps jelly beans oat cake. Candy wafer pudding dragée gummies. Carrot cake macaroon cake sesame snaps caramels. </AccordionBody> </AccordionItem> </Accordion> ) } export default AccordionHover
1.671875
2
atom/packages/atom-ide-ui/modules/atom-ide-ui/pkg/atom-ide-diagnostics-ui/lib/ui/SettingsModal.js
alexhope61/bootstrap
0
1015
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = SettingsModal; var React = _interopRequireWildcard(require("react")); function _BoundSettingsControl() { const data = _interopRequireDefault(require("../../../../../nuclide-commons-ui/BoundSettingsControl")); _BoundSettingsControl = function () { return data; }; return data; } function _HR() { const data = require("../../../../../nuclide-commons-ui/HR"); _HR = function () { return data; }; return data; } function _featureConfig() { const data = _interopRequireDefault(require("../../../../../nuclide-commons-atom/feature-config")); _featureConfig = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * * @format */ function SettingsModal(props) { const hasProviderSettings = props.config.some(config => config.settings.length > 0); return React.createElement("div", { className: "nuclide-diagnostics-ui-settings-modal settings-view" }, React.createElement("section", { className: "settings-panel" }, React.createElement(_BoundSettingsControl().default, { keyPath: _featureConfig().default.formatKeyPath('atom-ide-diagnostics-ui.showDirectoryColumn') }), React.createElement(_BoundSettingsControl().default, { keyPath: _featureConfig().default.formatKeyPath('atom-ide-diagnostics-ui.autoVisibility') })), hasProviderSettings ? React.createElement(_HR().HR, null) : null, props.config.map(p => React.createElement(SettingsSection, Object.assign({ key: p.providerName }, p)))); } function SettingsSection(props) { return React.createElement("section", { className: "settings-panel" }, React.createElement("h1", { className: "section-heading" }, props.providerName), props.settings.map(keyPath => React.createElement(_BoundSettingsControl().default, { key: keyPath, keyPath: keyPath }))); }
1.195313
1
src/pages/super/adminForgotPassword.js
Joblyn/ronzlsdesk
0
1023
import React, { useState, useEffect } from 'react'; import { Link, useHistory } from 'react-router-dom'; import { useDispatch, useSelector } from 'react-redux'; import logo from '../../assets/images/logo.png'; import bgImage from '../../assets/images/illustration.png'; //components import InputField from '../../components/InputField'; import Button from '../../components/button'; import { forgotPassword } from '../../actions/admin/authAction/Users'; import { adminForgotPassword } from '../../apiConstants/apiConstants'; const ForgotPasswordAdmin = () => { const [control, setControl] = useState({}); const dispatch = useDispatch(); const history = useHistory(); const adminForgotPass = useSelector(state => state.adminForgotPassword); const handleChange = event => { setControl({ ...control, [event.target.name]: event.target.value, }); }; useEffect(() => { if (adminForgotPass.isSuccessful) { history.push('/admin/login'); } }, [adminForgotPass]); const handleClick = event => { event.preventDefault(); dispatch(forgotPassword(adminForgotPassword, control)); }; return ( <div className="login"> <div className="container sm:px-10"> <div className="block xl:grid grid-cols-2 gap-4"> <div className="hidden xl:flex flex-col min-h-screen"> <div className="pt-3"> <Link to="/" className="-intro-x flex items-center"> <img alt="Ronzl Logo" className="w-48" src={logo} /> </Link> </div> <div className="my-auto"> <img alt="Ronzl background" className="-intro-x w-1/2 -mt-16" src={bgImage} /> <div className="-intro-x text-gray-700 font-medium text-4xl leading-tight mt-10"> {/* A few more clicks to <br /> */} Retrieve your account </div> {/* <div className="-intro-x mt-5 text-lg text-gray-700"> Manage all your e-commerce accounts in one place </div> */} </div> </div> <div className="h-screen xl:h-auto flex py-5 xl:py-0 xl:my-0"> <div className="my-auto mx-auto xl:ml-20 bg-white xl:bg-transparent px-5 sm:px-8 py-8 xl:p-0 rounded-md shadow-md xl:shadow-none w-full sm:w-3/4 lg:w-2/4 xl:w-auto"> <div className="lg:hidden"> <div className="pt-3"> <Link to="/" className="-intro-x flex items-center"> <img alt="Ronzl Logo" className="w-20" src={logo} /> </Link> </div> </div> <h2 className="intro-x font-bold text-2xl xl:text-3xl text-center xl:text-left">Header</h2> <div className="intro-x mt-2 text-gray-500 xl:hidden text-center"> Retrieve your account <br /> {/* Manage all your e-commerce accounts in one place */} </div> <div className="intro-x mt-8"> <InputField type="email" name="email" onChange={handleChange} className="intro-x login__input input input--lg border border-gray-300 block" placeholder="Email" /> {/* <InputField type="email" className="intro-x login__input input input--lg border border-gray-300 block mt-4" placeholder="Confirm Email" /> */} </div> <div className="intro-x mt-5 xl:mt-8 xl:text-left"> <Button type="button" onClick={handleClick} className="button button--lg w-full xl:w-40 text-white bg-theme-1 xl:mr-3" value="Confirm Email" /> </div> <div className="intro-x mt-6 xl:mt-10 text-lg text-gray-700 xl:text-left"> Already have an account? <Link to="/admin/login" className="text-green-500 font-semibold px-2 hover:underline" > Login </Link> </div> </div> </div> </div> </div> </div> ); }; export default ForgotPasswordAdmin;
1.523438
2
node_modules/@amcharts/amcharts4/.internal/core/Registry.js
Prosocial-Lab/hci-com
0
1031
import { EventDispatcher } from "./utils/EventDispatcher"; import { Dictionary } from "./utils/Dictionary"; import { cache } from "./utils/Cache"; import * as $type from "./utils/Type"; import * as $string from "./utils/String"; import * as $array from "./utils/Array"; /** * ============================================================================ * MAIN CLASS * ============================================================================ * @hidden */ /** * Registry is used to store miscellaneous system-wide information, like ids, * maps, themes, and registered classes. * * @ignore Exclude from docs */ var Registry = /** @class */ (function () { function Registry() { var _this = this; /** * Event dispacther. */ this.events = new EventDispatcher(); /** * All currently applied themes. All new chart instances created will * automatically inherit and retain System's themes. */ this.themes = []; /** * List of all loaded available themes. * * Whenever a theme loads, it registers itself in System's `loadedThemes` * collection. */ this.loadedThemes = {}; /** * An indeternal counter used to generate unique IDs. * * @ignore Exclude from docs */ this._uidCount = 0; /** * Keeps register of class references so that they can be instnatiated using * string key. * * @ignore Exclude from docs */ this.registeredClasses = {}; /** * Holds all generated placeholders. */ this._placeholders = {}; /** * A list of invalid(ated) [[Sprite]] objects that need to be re-validated * during next cycle. * * @ignore Exclude from docs */ this.invalidSprites = {}; /** * Components are added to this list when their data provider changes to * a new one or data is added/removed from their data provider. * * @ignore Exclude from docs */ this.invalidDatas = {}; /** * Components are added to this list when values of their raw data change. * Used when we want a smooth animation from one set of values to another. * * @ignore Exclude from docs */ this.invalidRawDatas = []; /** * Components are added to this list when values of their data changes * (but not data provider itself). * * @ignore Exclude from docs */ this.invalidDataItems = []; /** * Components are added to this list when their data range (selection) is * changed, e.g. zoomed. * * @ignore Exclude from docs */ this.invalidDataRange = []; /** * A list of [[Sprite]] objects that have invalid(ated) positions, that need * to be recalculated. * * @ignore Exclude from docs */ this.invalidPositions = {}; /** * A list of [[Container]] objects with invalid(ated) layouts. * * @ignore Exclude from docs */ this.invalidLayouts = {}; /** * An array holding all active (non-disposed) top level elemens. * * When, for example, a new chart is created, its instance will be added to * this array, and will be removed when the chart is disposed. */ this.baseSprites = []; /** * An UID-based map of base sprites (top-level charts). */ this.baseSpritesByUid = {}; /** * Queued charts (waiting for their turn) to initialize. * * @see {@link https://www.amcharts.com/docs/v4/concepts/performance/#Daisy_chaining_multiple_charts} for more information */ this.queue = []; /** * An array of deferred charts that haven't been created yet. * * @see {@link https://www.amcharts.com/docs/v4/concepts/performance/#Deferred_daisy_chained_instantiation} for more information * @since 4.10.0 */ this.deferred = []; this.uid = this.getUniqueId(); this.invalidSprites.noBase = []; this.invalidDatas.noBase = []; this.invalidLayouts.noBase = []; this.invalidPositions.noBase = []; // This is needed for Angular Universal SSR if (typeof addEventListener !== "undefined") { // This is needed to prevent charts from being cut off when printing addEventListener("beforeprint", function () { $array.each(_this.baseSprites, function (sprite) { var svg = sprite.paper.svg; svg.setAttribute("viewBox", "0 0 " + svg.clientWidth + " " + svg.clientHeight); }); }); addEventListener("afterprint", function () { $array.each(_this.baseSprites, function (sprite) { var svg = sprite.paper.svg; svg.removeAttribute("viewBox"); }); }); } } /** * Generates a unique chart system-wide ID. * * @return Generated ID */ Registry.prototype.getUniqueId = function () { var uid = this._uidCount; this._uidCount += 1; return "id-" + uid; }; Object.defineProperty(Registry.prototype, "map", { /** * Returns a universal collection for mapping ids with objects. * * @ignore Exclude from docs * @return Map collection */ get: function () { if (!this._map) { this._map = new Dictionary(); } return this._map; }, enumerable: true, configurable: true }); /** * Caches value in object's cache. * * @ignore Exclude from docs * @param key Key * @param value Value * @param ttl TTL in seconds */ Registry.prototype.setCache = function (key, value, ttl) { cache.set(this.uid, key, value, ttl); }; /** * Retrieves cached value. * * @ignore Exclude from docs * @param key Key * @param value Value to return if cache is not available * @return Value */ Registry.prototype.getCache = function (key, value) { if (value === void 0) { value = undefined; } return cache.get(this.uid, key, value); }; /** * Dispatches an event using own event dispatcher. Will automatically * populate event data object with event type and target (this element). * It also checks if there are any handlers registered for this sepecific * event. * * @param eventType Event type (name) * @param data Data to pass into event handler(s) */ Registry.prototype.dispatch = function (eventType, data) { // @todo Implement proper type check if (this.events.isEnabled(eventType)) { if (data) { data.type = eventType; data.target = data.target || this; this.events.dispatch(eventType, { type: eventType, target: this }); } else { this.events.dispatch(eventType, { type: eventType, target: this }); } } }; /** * Works like `dispatch`, except event is triggered immediately, without * waiting for the next frame cycle. * * @param eventType Event type (name) * @param data Data to pass into event handler(s) */ Registry.prototype.dispatchImmediately = function (eventType, data) { // @todo Implement proper type check if (this.events.isEnabled(eventType)) { if (data) { data.type = eventType; data.target = data.target || this; this.events.dispatchImmediately(eventType, data); } else { this.events.dispatchImmediately(eventType, { type: eventType, target: this }); } } }; /** * Returns a unique placeholder suitable for the key. * * @param key Key * @return Random string to be used as placeholder */ Registry.prototype.getPlaceholder = function (key) { if ($type.hasValue(this._placeholders[key])) { return this._placeholders[key]; } this._placeholders[key] = "__amcharts_" + key + "_" + $string.random(8) + "__"; return this._placeholders[key]; }; /** * @ignore */ Registry.prototype.addToInvalidComponents = function (component) { if (component.baseId) { $array.move(this.invalidDatas[component.baseId], component); } else { $array.move(this.invalidDatas["noBase"], component); } }; /** * @ignore */ Registry.prototype.removeFromInvalidComponents = function (component) { if (component.baseId) { $array.remove(this.invalidDatas[component.baseId], component); } $array.remove(this.invalidDatas["noBase"], component); }; /** * @ignore */ Registry.prototype.addToInvalidSprites = function (sprite) { if (sprite.baseId) { $array.add(this.invalidSprites[sprite.baseId], sprite); } else { $array.add(this.invalidSprites["noBase"], sprite); } }; /** * @ignore */ Registry.prototype.removeFromInvalidSprites = function (sprite) { if (sprite.baseId) { $array.remove(this.invalidSprites[sprite.baseId], sprite); } $array.remove(this.invalidSprites["noBase"], sprite); }; /** * @ignore */ Registry.prototype.addToInvalidPositions = function (sprite) { if (sprite.baseId) { $array.add(this.invalidPositions[sprite.baseId], sprite); } else { $array.add(this.invalidPositions["noBase"], sprite); } }; /** * @ignore */ Registry.prototype.removeFromInvalidPositions = function (sprite) { if (sprite.baseId) { $array.remove(this.invalidPositions[sprite.baseId], sprite); } $array.remove(this.invalidPositions["noBase"], sprite); }; /** * @ignore */ Registry.prototype.addToInvalidLayouts = function (sprite) { if (sprite.baseId) { $array.add(this.invalidLayouts[sprite.baseId], sprite); } else { $array.add(this.invalidLayouts["noBase"], sprite); } }; /** * @ignore */ Registry.prototype.removeFromInvalidLayouts = function (sprite) { if (sprite.baseId) { $array.remove(this.invalidLayouts[sprite.baseId], sprite); } $array.remove(this.invalidLayouts["noBase"], sprite); }; return Registry; }()); export { Registry }; /** * A singleton global instance of [[Registry]]. * * @ignore Exclude from docs */ export var registry = new Registry(); /** * Returns `true` if object is an instance of the class. It's the same as `instanceof` except it doesn't need to import the class. * * @param object Object * @param name Class name * @return Is instance of class */ export function is(object, name) { var x = registry.registeredClasses[name]; return x != null && object instanceof x; } //# sourceMappingURL=Registry.js.map
1.265625
1
src/store/actions/count.js
liyaxu123/react-juejin
0
1039
/* 该文件专门为Count组件生成action对象 */ import {INCREMENT, DECREMENT} from '../constant' //同步action,就是指action的值为Object类型的一般对象 export const increment = data => ({type: INCREMENT, data}) export const decrement = data => ({type: DECREMENT, data}) //异步action,就是指action的值为函数,异步action中一般都会调用同步action,异步action不是必须要用的。 export const incrementAsync = (data, time) => { return (dispatch) => { setTimeout(() => { dispatch(increment(data)) }, time) } }
1.421875
1
source/app/mywork/viewmodels/mywork2.js
realsungroup/MobileHrManage
0
1047
define(['durandal/system', 'durandal/app', 'knockout', 'plugins/router', 'plugins/dialog', 'myworkshell/viewmodels/mywork1', 'durandal/viewEngine', 'durandal/viewLocator', 'mobiscroll'], function (system, app, ko, router, dialog, mywork1, viewEngine, viewLocator, addSchool, mobiscroll) { var record = ko.observable({}); var allSchoolModelArr = []; var schoolModelArr = ko.observable([]), emptySchoolModelArr = []; var cerModelArr = ko.observable([]), emptyCerModelArr = []; var certificateArr = ['C3_464174073888', 'C3_464174102741', 'C3_464174124614', 'C3_464174135706', 'C3_464174225362'], lvArr = ['C3_464174245669', 'C3_464174263309', 'C3_464174274118', 'C3_464174314278', 'C3_464174325345'], organArr = ['C3_464174345857', 'C3_464174365244', 'C3_464174394548', 'C3_464174405591', 'C3_464174418555'], dataArr = ['C3_464174451732', 'C3_464174461446', 'C3_464174473180', 'C3_464174481889', 'C3_464174491548']; var schoolNameArr = ['C3_464173711606', 'C3_464173723045', 'C3_464173733523', 'C3_464173750564', 'C3_464173763887'], startTimeArr = ['C3_464173481804', 'C3_464173514735', 'C3_464173524810', 'C3_464173535280', 'C3_464173544689'], endTimeArr = ['C3_464173629942', 'C3_464173639392', 'C3_464173646851', 'C3_464173667723', 'C3_464173677006'], majorArr = ['C3_464173836290', 'C3_464173847918', 'C3_464173861459', 'C3_464173879808', 'C3_464173890490'], eduArr = ['C3_464173912562', 'C3_464173926575', 'C3_464173937460', 'C3_464173949368', 'C3_464173962533']; return { activate: function () { var a = mywork1.record(); var self = this; self.record(a); }, record: record, schoolModelArr: schoolModelArr, cerModelArr: cerModelArr, attached: function () { //学校预加载 var schoolModel = function (schoolName, startTime, endTime, major, edu, index) { this.schoolName = ko.observable(schoolName); this.startTime = ko.observable(startTime); this.endTime = ko.observable(endTime); this.major = ko.observable(major); this.edu = ko.observable(edu); this.index = index; } var tempArr = []; for (var i = 0; i < schoolNameArr.length; i++) { var tempM = new schoolModel(record()[schoolNameArr[i]], record()[startTimeArr[i]], record()[endTimeArr[i]], record()[majorArr[i]], record()[eduArr[i]], i); if (record()[schoolNameArr[i]] != null || record()[startTimeArr[i]] != null || record()[endTimeArr[i]] != null || record()[majorArr[i]] != null) { tempArr.push(tempM); } else { if (i == 0) tempArr.push(tempM); else emptySchoolModelArr.push(tempM); } allSchoolModelArr.push(tempM); } schoolModelArr(tempArr); //证书预加载 var cerModel = function (cer, lv, organ, data, index) { this.cer = ko.observable(cer); this.lv = ko.observable(lv); this.organ = ko.observable(organ); this.data = ko.observable(data); this.index = index; } var tempCerArr = []; for (var i = 0; i < certificateArr.length; i++) { var tempM = new cerModel(record()[certificateArr[i]], record()[lvArr[i]], record()[organArr[i]], record()[dataArr[i]], i); if (record()[certificateArr[i]] != null || record()[lvArr[i]] != null || record()[organArr[i]] != null || record()[dataArr[i]] != null) { tempCerArr.push(tempM); } else { if (i == 0) tempCerArr.push(tempM); else emptyCerModelArr.push(tempM); } } cerModelArr(tempCerArr); ko.computed(function () { // alert("1" + schoolModelArr()[0].schoolName() +'------'+record().C3_464173723045); for (var i = 0; i < schoolModelArr().concat(emptySchoolModelArr).length; i++) { var tempM = schoolModelArr().concat(emptySchoolModelArr)[i]; record()[schoolNameArr[tempM.index]] = tempM.schoolName(); record()[startTimeArr[tempM.index]] = tempM.startTime(); record()[endTimeArr[tempM.index]] = tempM.endTime(); record()[majorArr[tempM.index]] = tempM.major(); record()[eduArr[tempM.index]] = tempM.edu(); } }); ko.computed(function(){ for (var i = 0; i < cerModelArr().concat(emptyCerModelArr).length; i++) { var tempM = cerModelArr().concat(emptyCerModelArr)[i]; record()[certificateArr[tempM.index]] = tempM.cer(); record()[lvArr[tempM.index]] = tempM.lv(); record()[organArr[tempM.index]] = tempM.organ(); record()[dataArr[tempM.index]] = tempM.data(); console.log("------->" + record()[certificateArr[tempM.index]]); } }) var timeC = timeControl.createTimeControl(); timeC.record = record(); timeC.initTimeControl(); }, changeview: function (strID) { var self = this; if (strID == "btn1") {//添加证书 if (emptyCerModelArr.length) { var tempArr = cerModelArr(); tempArr.push(emptyCerModelArr[0]); cerModelArr(tempArr); emptyCerModelArr.splice(0, 1); } } else if (strID == "btn2") {//添加学校 if (emptySchoolModelArr.length) { var tempSchoolModelArr = schoolModelArr(); tempSchoolModelArr.push(emptySchoolModelArr[0]); schoolModelArr(tempSchoolModelArr); emptySchoolModelArr.splice(0, 1); } } var timeC = timeControl.createTimeControl(); timeC.record = record(); timeC.initTimeControl(); }, submitClickWork2: function () {//提交 mywork1.submitClick(); }, routeMyWork3: function () { var propertyArr = ['C3_464173711606', 'C3_464173481804', 'C3_464173629942', // 'C3_464173836290', 'C3_464173912562', 'C3_464174073888', 'C3_464174245669' ]; var propertyStrArr = [ "学校名称", "教育开始时间", "教育结束时间", // "专业", "学历", "证书名称", "等级" ]; var containArr = [propertyArr, propertyStrArr]; var emptyArr = mywork1.valiateForm(containArr); if (emptyArr.length == 0) { appConfig.app.myworkshell.router.navigate("#mywork/mywork3"); } else { dialog.showMessage(emptyArr + "不能为空"); } }, routeBack: function () { appConfig.app.myworkshell.router.navigateBack(); }, cellDelete: function (str, index, data, event) {//删除 if( mywork1.record().C3_471002935941 == "Y"){ dialog.showMessage("已提交数据不能删除"); return; } if (str == 'school') { var tempSchoolM = schoolModelArr()[index()]; emptySchoolModelArr.push(tempSchoolM); schoolModelArr().splice(index(), 1); tempSchoolM.schoolName(''); tempSchoolM.startTime(''); tempSchoolM.endTime(''); tempSchoolM.major(''); tempSchoolM.edu(''); schoolModelArr(schoolModelArr()); } else if (str == 'cer') { var tempSchoolM = cerModelArr()[index()]; emptyCerModelArr.push(tempSchoolM); cerModelArr().splice(index(), 1); tempSchoolM.cer(''); tempSchoolM.lv(''); tempSchoolM.organ(''); tempSchoolM.data(''); cerModelArr(cerModelArr()); } } }; });
0.796875
1
routes/http_user.js
garyhu1/koa-project
2
1055
const Router = require('koa-router'); const HttpServiceController = require("../controllers/http_req"); const router = new Router({ prefix: '/http' }); router.get("/user",HttpServiceController.getUser) module.exports = router;
0.847656
1
src/resources/3_0_1/profiles/devicemetric/query.js
michelekorell/graphql-fhir
2
1063
// Schemas const DeviceMetricSchema = require('../../schemas/devicemetric.schema'); const BundleSchema = require('../../schemas/bundle.schema'); // Arguments const DeviceMetricArgs = require('../../parameters/devicemetric.parameters'); const CommonArgs = require('../../parameters/common.parameters'); // Resolvers const { devicemetricResolver, devicemetricListResolver, devicemetricInstanceResolver, } = require('./resolver'); // Scope Utilities const { scopeInvariant } = require('../../../../utils/scope.utils'); let scopeOptions = { name: 'DeviceMetric', action: 'read', version: '3_0_1', }; /** * @name exports.DeviceMetricQuery * @summary DeviceMetric Query. */ module.exports.DeviceMetricQuery = { args: Object.assign({}, CommonArgs, DeviceMetricArgs), description: 'Query for a single DeviceMetric', resolve: scopeInvariant(scopeOptions, devicemetricResolver), type: DeviceMetricSchema, }; /** * @name exports.DeviceMetricListQuery * @summary DeviceMetricList Query. */ module.exports.DeviceMetricListQuery = { args: Object.assign({}, CommonArgs, DeviceMetricArgs), description: 'Query for multiple DeviceMetrics', resolve: scopeInvariant(scopeOptions, devicemetricListResolver), type: BundleSchema, }; /** * @name exports.DeviceMetricInstanceQuery * @summary DeviceMetricInstance Query. */ module.exports.DeviceMetricInstanceQuery = { description: 'Get information about a single DeviceMetric', resolve: scopeInvariant(scopeOptions, devicemetricInstanceResolver), type: DeviceMetricSchema, };
1.304688
1
src/constants/initial_state.js
yudinmaksym/ReactTestProject
0
1071
export const topSectionDefault = { id: 1, name: 'top', disabled: false, sectionOrder: null, content: { title: 'Lorem ipsum dolo', description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor', sold: '100000000', available: '100', from: 1513807200000, to: 1516658400000, bg: '../assets/images/top.png', problem: [ { description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor', }, { description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor', }, { description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor', }, ], key_benefits: [ { title: 'Lorem ipsum dolo', content: [ { img: '../assets/images/target.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', }, { img: '../assets/images/target.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', }, { img: '../assets/images/target.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', }, ], }, { title: 'Lorem ipsum dolo', content: [ { img: '../assets/images/target.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', }, { img: '../assets/images/target.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', }, ], }, { title: 'Lorem ipsum dolo', content: [ { img: '../assets/images/target.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', }, { img: '../assets/images/target.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', }, ], }, { title: 'Lorem ipsum dolo', content: [ { img: '../assets/images/target.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', }, { img: '../assets/images/target.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', }, ], }, ], white_paper: [ { img: '../assets/images/germany.png', }, { img: '../assets/images/germany.png', }, { img: '../assets/images/germany.png', }, ], token_eco: [ { disc: '../assets/images/bounty_el.png', text: 'Bitcoin Signature Campaign', }, { disc: '../assets/images/bounty_el.png', text: 'Bitcoin Signature Campaign', }, { disc: '../assets/images/bounty_el.png', text: 'Bitcoin Signature Campaign', }, { disc: '../assets/images/bounty_el.png', text: 'Bitcoin Signature Campaign', }, { disc: '../assets/images/bounty_el.png', text: 'Bitcoin Signature Campaign', }, ], media_top: [ { img: '../assets/images/m4.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor', }, { img: '../assets/images/m4.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor', }, { img: '../assets/images/m4.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor', }, ], media_bottom: [ { img: '../assets/images/m4.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor', }, { img: '../assets/images/m4.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor', }, { img: '../assets/images/m4.png', text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor', }, ], socials: [ { link: 'https://facebook.com', type: 'fb', img: '../assets/images/facebook.png', }, { link: 'https://www.instagram.com', type: 'insta', img: '../assets/images/insta.png', }, { link: 'https://twitter.com', type: 'tw', img: '../assets/images/twitter-.png', }, { link: 'https://telegram.org/', type: 'tel', img: '../assets/images/telegram.png', }, ], countDown: { title: 'Lorem ipsum dolor', description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', rates: 'US$0.05', acceptTitle: 'We accept', acceptLogo: '../assets/images/eth.png', acceptCrypt: 'ETH', }, navbar: [ { title: 'About', }, { title: 'ICO section', }, { title: 'Whitepaper', }, { title: 'Roadmap', }, { title: 'Team', }, { title: 'FAQ', }, ], }, }; export const INITIAL_STATE = { app: { type: '', locale: 'en', loaded: false, }, dialog: { params: {}, name: '', }, events: {}, user: { email: '', }, };
0.542969
1
lib/photoride.js
BeneathTheInk/photoride
0
1079
if (typeof Tap === "undefined") require("tapjs"); var _ = require("underscore"); var EventEmitter = require("events").EventEmitter; var Modernizr = require("./modernizr"); function Photoride(cont, options) { EventEmitter.call(this); var self = this; this.options = _.extend({ loop: true, showCount: true, showNav: true, resizeEvent: true, enableTouch: Modernizr.touch, enableArrowKeys: true }, options || {}); if (cont == null) cont = document.createElement("div"); if (typeof cont === "string") { cont = document.querySelector(cont); if (cont == null) throw new Error("Could not locate container element."); } this.container = cont; this.container.innerHTML = ""; this.container.classList.add("photoride"); this.container.classList[this.option("showNav") ? "remove" : "add"]("photoride-nav-disabled"); this.photoCount = document.createElement("div"); this.photoCount.style.display = this.option("showCount") ? "" : "none"; this.photoCount.classList.add("photoride-count"); this.container.appendChild(this.photoCount); this.scroll = document.createElement("div"); this.scroll.classList.add("photoride-scroll"); this.container.appendChild(this.scroll); this.nextBtn = document.createElement("a"); this.nextBtn.href = "#"; this.nextBtn.classList.add("photoride-btn", "photoride-btn-next"); this.nextBtn.addEventListener("tap", this.next.bind(this, null)); this.container.appendChild(this.nextBtn); this.prevBtn = document.createElement("a"); this.prevBtn.href = "#"; this.prevBtn.classList.add("photoride-btn", "photoride-btn-previous"); this.prevBtn.addEventListener("tap", this.previous.bind(this, null)); this.container.appendChild(this.prevBtn); this.current = 0; this.photos = []; this.refresh = _.debounce(this._refresh, 50); this.init(); } module.exports = Photoride; Photoride.Photo = Photo; Photoride.prototype = Object.create(EventEmitter.prototype); _.extend(Photoride.prototype, { init: function() { if (Modernizr.overflowscrolling) this._scrollDetect(); if (this.option("resizeEvent") !== false) { var onResize; window.addEventListener("resize", onResize = this.refresh.bind(this)); this.once("destroy", function() { window.removeEventListener("resize", onResize); }); } if (this.option("enableTouch") !== false) { var onTouch; this.container.addEventListener("touchstart", onTouch = this._onTouchStart.bind(this)); this.once("destroy", function() { this.container.removeEventListener("touchstart", onTouch); }); } if (this.option("enableArrowKeys") !== false) { var onKeypress; document.addEventListener("keyup", onKeypress = this._onArrowPress.bind(this)); this.once("destroy", function() { document.removeEventListener("keyup", onKeypress); }); } this.refresh(); }, option: function(prop) { var value = this.options == null ? void 0 : this.options[prop]; var args = Array.prototype.slice.call(arguments, 1); return _.isFunction(value) ? value.apply(this, args) : value; }, destroy: function() { this.scroll.innerHTML = ""; this.photos = []; this.current = 0; this.emit("destroy"); this.refresh(); return this; }, findBySource: function(src) { return _.find(this.photos, function(photo) { return photo.source === src; }); }, _refresh: function() { this.width = this.container.clientWidth; this.height = this.container.clientHeight; this.scroll.style.width = (this.photos.length * this.width) + "px"; _.each(this.photos, function(photo) { photo.container.style.width = this.width + "px"; photo.refresh(); }, this); var onAnimEnd; var left = (-1 * (this.current * this.width)) + "px"; var eleft = this.scroll.style.left; if (eleft && eleft !== "auto" && eleft !== left) { this.scroll.classList.add("photoride-scroll-transition"); addPrefixedEvent(this.scroll, "TransitionEnd", onAnimEnd = function(e) { removePrefixedEvent(this, "TransitionEnd", onAnimEnd); this.classList.remove("photoride-scroll-transition"); }); } this.photoCount.textContent = (this.current + 1) + " / " + this.photos.length; this.scroll.style.left = left; if (this.option("showNav")) { var enough = this.photos.length > 1; this.nextBtn.style.display = !enough ? "none" : ""; this.prevBtn.style.display = !enough ? "none" : ""; if (!this.option("loop")) { this.nextBtn.classList[this.current === (this.photos.length - 1) ? "add" : "remove"]("photoride-btn-disabled"); this.prevBtn.classList[this.current === 0 ? "add" : "remove"]("photoride-btn-disabled"); } } }, getCurrent: function() { return this.photos[this.current]; }, push: function(src, options) { return this.add(this.photos.length, src, options); }, add: function(index, src, options) { var photo = new Photo(src, _.extend({}, this.options, options)); var index = this.photos.length; this.photos.splice(index, 0, photo); this.scroll.appendChild(photo.container); this.refresh(); return photo; }, goto: function(n) { if (typeof n !== "number" || isNaN(n)) n = 0; this.current = Math.max(0, Math.min(this.photos.length - 1, n)); this.refresh(); return this; }, next: function(loop) { var n = this.current + 1; if (loop == null) loop = this.option("loop"); if (loop && n >= this.photos.length) n = 0; return this.goto(n); }, previous: function(loop) { var n = this.current - 1; if (loop == null) loop = this.option("loop"); if (loop && n < 0) n = this.photos.length - 1; return this.goto(n); }, _onTouchStart: function(e) { var touchMove, touchEnd; var touch = e.touches[0], ix = touch.pageX, iy = touch.pageY, horz = false, self = this, dx, dy, left; this.container.addEventListener("touchmove", touchMove = function(e) { if (horz) return; var touch = e.touches[0]; dx = ix - touch.pageX; dy = iy - touch.pageY; if (Math.abs(dy) >= 50) { horz = true; self.goto(self.current); } else if (Math.abs(dx) >= 10) { left = (self.current * self.width) + dx; self.scroll.style.left = (-1 * left) + "px"; } }); this.container.addEventListener("touchend", touchEnd = function(e) { this.removeEventListener("touchmove", touchMove); this.removeEventListener("touchend", touchEnd); var chg; if (!horz && dx != null && Math.abs(dx) > 10) { chg = dx >= 40 ? 1 : dx <= -40 ? -1 : 0; } else { chg = 0; } self.goto(self.current + chg); }); }, _onArrowPress: function(e) { if (e.keyCode !== 37 && e.keyCode !== 39) return; e.preventDefault(); this[e.keyCode === 37 ? "previous" : "next"](this.option("loop")); }, _scrollDetect: function() { if (this._scrollFix) return this; this.once("destroy", function() { if (this._scrollFix) { cancelAnimationFrame(this._scrollFix); delete this._scrollFix; } }); var refresh = _.bind(function() { var photo = this.getCurrent(); if (photo != null) photo.refresh(); next(); }, this); function next() { this._scrollFix = requestAnimationFrame(refresh); } next(); return this; } }); function Photo(src, options) { this.options = _.extend({ backgroundSize: "cover", backgroundColor: "black", scrollDuration: 300, maxFade: 0.75, gradientSize: 0.3 }, options || {}); this.container = document.createElement("div"); this.container.classList.add("photoride-image", "photoride-image-loading"); this.view = document.createElement("div"); this.view.classList.add("photoride-image-view"); this.view.style.backgroundSize = this.option("backgroundSize"); this.view.style.backgroundColor = this.option("backgroundColor"); this.container.appendChild(this.view); this.content = document.createElement("div"); this.content.classList.add("photoride-image-content"); this.content.addEventListener("scroll", _.throttle(this.refresh.bind(this), 16)); this.container.appendChild(this.content); this.inner = document.createElement("div"); this.inner.classList.add("photoride-image-inner"); this.content.appendChild(this.inner); this.paddingBox = document.createElement("div"); this.paddingBox.classList.add("photoride-image-padding"); this.inner.appendChild(this.paddingBox); this.title = document.createElement("div"); this.title.classList.add("photoride-image-title"); this.inner.appendChild(this.title); this.caption = document.createElement("div"); this.caption.classList.add("photoride-image-caption"); this.inner.appendChild(this.caption); this.moreBtn = document.createElement("a"); this.moreBtn.href = "#"; this.moreBtn.classList.add("photoride-btn", "photoride-btn-more"); this.moreBtn.addEventListener("tap", _.bind(function(e) { var contentHeight = this.getContentHeight() - this.title.offsetHeight; this.scrollTo(this.content.scrollTop > 20 ? 0 : Math.min(contentHeight, this.content.scrollHeight - contentHeight)); }, this)); this.container.appendChild(this.moreBtn); this.setSource(src); this.setTitle(this.option("title")); this.setCaption(this.option("caption")); } _.extend(Photo.prototype, { option: Photoride.prototype.option, setSource: function(src) { this.source = src; this.view.style.backgroundImage = "url('" + src + "')"; return this; }, setTitle: function(title) { if (!title) { this.title.textContent = ""; this.title.classList.add("photoride-image-title-empty"); } else { this.title.textContent = title; this.title.classList.remove("photoride-image-title-empty"); } return this; }, setCaption: function(content) { if (content == null) content = ""; if (typeof content === "string") { if (!content) this.caption.style.display = "none"; else { this.caption.style.display = ""; this.caption.innerHTML = content; } return this; } this.caption.innerHTML = ""; if (typeof content.nodeType === "number") { this.caption.appendChild(el); } else if (content.length) { _.each(content, function(el) { this.caption.appendChild(el); }, this); } return this; }, scrollTo: function(to) { if (this._scrollFrame) { cancelAnimationFrame(this._scrollFrame); delete this._scrollFrame; } var self = this; var scrollTop = this.content.scrollTop; var duration = this.option("scrollDuration"); // find difference between current scroll position(relative to document.body) and the bink element to which we are scrolling to var difference = to - scrollTop; // if target bink is within the upper part of window's view then don't scroll if (duration < 0 || !difference) return; // variable for holding time count var start; function runScroll() { // use time stamp to calculate time var t = new Date(); if (start == null) start = t; // difference in time var tDiff = t - start; // if difference in time is greater than our initially set duration, animation is complete if (tDiff >= duration){ self.content.scrollTop = to; delete self._scrollFrame; return; } // increment the scrollTop position self.content.scrollTop = scrollTop + ((tDiff/duration) * difference); // rerun function until animation is complete self._scrollFrame = requestAnimationFrame(runScroll); }; this._scrollFrame = requestAnimationFrame(runScroll); return this; }, getContentHeight: function() { var height = this.content.clientHeight; var contentStyle = getComputedStyle(this.content); var paddingTop = parseInt(contentStyle.paddingTop, 10); if (isNaN(paddingTop)) paddingTop = 0; var paddingBottom = parseInt(contentStyle.paddingBottom, 10); if (isNaN(paddingBottom)) paddingBottom = 0; return height - paddingTop - paddingBottom; }, refresh: function() { this.content.style.backgroundColor = ""; this.content.style.backgroundImage = ""; var hasCaption = this.caption.hasChildNodes(); var hasTitle = this.title.textContent !== ""; var contentHeight = this.getContentHeight(); var clientHeight = this.content.clientHeight; var scrollTop = this.content.scrollTop; var height = Math.min(this.content.scrollHeight - clientHeight, clientHeight * 0.6); var perc = scrollTop / height; perc = isNaN(perc) ? 0 : Math.min(1, perc); var fade = this.option("maxFade"); var lead = fade * perc; var css = this.content.style.cssText; var gradientSize = Math.min(100, Math.max(0, Math.round((1 - this.option("gradientSize")) * 100))); this.moreBtn.style.display = hasCaption ? "" : "none"; this.moreBtn.classList[!hasCaption || scrollTop < 20 ? "remove" : "add"]("photoride-btn-more-flipped"); this.paddingBox.style.height = (contentHeight - this.title.offsetHeight) + "px"; if (hasCaption || hasTitle) { if (fade !== lead) { var gradient = [ "rgba(0, 0, 0, " + lead + ") 0%", "rgba(0, 0, 0, " + lead + ") " + gradientSize + "%", "rgba(0, 0, 0, " + fade + ") 100%" ].join(", "); [ "-webkit-linear-gradient(top, ", "-moz-linear-gradient(top, ", "-o-linear-gradient(top, ", "linear-gradient(to bottom, " ].forEach(function(s) { css += " background-image: " + s + gradient + ");"; }); } else { css += " background-color: rgba(0, 0, 0, " + fade + ");"; } } this.content.style.cssText = css; this.container.classList.remove("photoride-image-loading"); } }); require("domready")(function() { _.each(document.querySelectorAll("[data-photoride]"), function(cont) { var options = autoCoerce(cont.dataset); var imgs = _.map(cont.querySelectorAll("img"), function(img) { var captionQuery = img.dataset.caption; var caption, captionel; if (captionQuery) { captionel = cont.querySelector(captionQuery); if (captionel != null) caption = _.toArray(captionel.childNodes); } var biggerWidth = img.naturalWidth >= cont.clientWidth; var biggerHeight = img.naturalHeight >= cont.clientHeight; var opts = _.extend({ backgroundSize: options.backgroundSize || ( biggerWidth && biggerHeight ? "cover" : biggerWidth || biggerHeight ? "contain" : "auto" ) }, autoCoerce(img.dataset), { title: img.getAttribute("title"), caption: caption }); return [ img.src, opts ]; }); var photoride = cont.photoride = new Photoride(cont, options); imgs.forEach(function(args) { photoride.push.apply(photoride, args); }); }); }); var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame || function (f) { return setTimeout(f, 16); }; var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.oCancelAnimationFrame || function (t) { return clearTimeout(t); }; var pfx = ["webkit", "moz", "MS", "o", ""]; function addPrefixedEvent(element, type, callback) { for (var p = 0; p < pfx.length; p++) { if (!pfx[p]) type = type.toLowerCase(); element.addEventListener(pfx[p]+type, callback, false); } } function removePrefixedEvent(element, type, callback) { for (var p = 0; p < pfx.length; p++) { if (!pfx[p]) type = type.toLowerCase(); element.removeEventListener(pfx[p]+type, callback, false); } } var numex = /^-?[0-9]*(?:\.[0-9]+)?$/, boolex = /^true|false$/i; function autoCoerce(v) { if (typeof v === "string") { var trimmed = v.trim(); if (numex.test(trimmed)) return parseFloat(v, 10); if (boolex.test(trimmed)) return trimmed === "true"; } if (typeof v === "object") { v = _.clone(v); _.each(v, function(val, key) { v[key] = autoCoerce(val); }); } return v; }
1.429688
1
packages/material-ui-icons/lib/esm/Pageview.js
good-gym/material-ui
51,124
1087
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M11.5 9C10.12 9 9 10.12 9 11.5s1.12 2.5 2.5 2.5 2.5-1.12 2.5-2.5S12.88 9 11.5 9zM20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-3.21 14.21-2.91-2.91c-.69.44-1.51.7-2.39.7C9.01 16 7 13.99 7 11.5S9.01 7 11.5 7 16 9.01 16 11.5c0 .88-.26 1.69-.7 2.39l2.91 2.9-1.42 1.42z" }), 'Pageview');
0.832031
1
test/reactor/expire-test.js
oroce/godot
62
1095
/* * expire-test.js: Tests for the Expire reactor stream. * * (C) 2012, Nodejitsu Inc. * */ var assert = require('assert'), vows = require('vows'), godot = require('../../lib/godot'), macros = require('../macros').reactor; vows.describe('godot/reactor/expire').addBatch({ "Godot aggregate": { "ttl 100ms": { "sent 200ms": macros.shouldExpireSync( godot .reactor() .expire(100), 'health', 200 ), "sent 50ms": macros.shouldNotExpireSync( godot .reactor() .expire(100), 'health', 50 ) } } }).export(module);
0.992188
1
src/MaterialUI/SVGIcon/Icon/FormatListBulletedOutlined.js
matoruru/purescript-react-material-ui-svgicon
0
1103
exports.formatListBulletedOutlinedImpl = require('@material-ui/icons/FormatListBulletedOutlined').default;
0.412109
0
test/serializer/abstract/ObjectAssign5.js
jeysal/prepack
0
1111
var obj = global.__abstract && global.__makePartial && global.__makeSimple ? __makeSimple(__makePartial(__abstract({}, "({foo:1})"))) : {foo:1}; var copyOfObj = Object.assign({}, obj); var copyOfCopyOfObj = Object.assign({}, copyOfObj); inspect = function() { return JSON.stringify(copyOfCopyOfObj); }
1.039063
1
tests/with-chatkit-one-to-one.test.js
pusher/chatkit-client-react
1
1119
import Chatkit from "@pusher/chatkit-client" import PropTypes from "prop-types" import React from "react" import TestRenderer from "react-test-renderer" import { withChatkitOneToOne, ChatkitProvider } from "../src" import { fakeAPI, makeOneToOneRoomId, User as FakeUser, Room as FakeRoom, ChatManager as FakeChatManager, CurrentUser as FakeCurrentUser, } from "./chatkit-fake" import { runInTestRenderer as helperRunInTestRenderer } from "./helpers" jest.mock("@pusher/chatkit-client") beforeEach(() => { fakeAPI.reset() fakeAPI.createUser({ id: "alice" }) fakeAPI.createUser({ id: "bob" }) fakeAPI.createUser({ id: "charlie" }) }) describe("withChatkitOneToOne higher-order-component", () => { Chatkit.ChatManager = FakeChatManager Chatkit.CurrentUser = FakeCurrentUser Chatkit.User = FakeUser Chatkit.Room = FakeRoom const instanceLocator = "v1:test:f83ad143-342f-4085-9639-9a809dc96466" const tokenProvider = new Chatkit.TokenProvider({ url: "https://customer-site.com/pusher-auth", }) const userId = "alice" const otherUserId = "bob" const roomId = makeOneToOneRoomId(userId, otherUserId) const runInTestRenderer = ({ resolveWhen, onLoad }) => helperRunInTestRenderer({ instanceLocator, tokenProvider, userId, higherOrderComponent: withChatkitOneToOne, resolveWhen, onLoad, wrappedComponentProps: { otherUserId, }, }) it("should inject a properly configured ChatManager", () => { return runInTestRenderer({ resolveWhen: props => props.chatkit.chatManager !== null, }).then(({ props }) => { const chatManager = props.chatkit.chatManager expect(chatManager).toBeInstanceOf(Chatkit.ChatManager) expect(chatManager.instanceLocator).toBe(instanceLocator) expect(chatManager.tokenProvider).toBe(tokenProvider) expect(chatManager.userId).toBe(userId) expect(chatManager.connected).toBe(true) }) }) it("should inject a properly configured CurrentUser", () => { return runInTestRenderer({ resolveWhen: props => props.chatkit.currentUser !== null, }).then(({ props }) => { const currentUser = props.chatkit.currentUser expect(currentUser).toBeInstanceOf(Chatkit.CurrentUser) expect(currentUser.id).toBe(userId) }) }) it("should inject isLoading and update appropriately", () => { return runInTestRenderer({ resolveWhen: props => !props.chatkit.isLoading, }).then(({ props, initialProps }) => { expect(initialProps.chatkit.isLoading).toBe(true) expect(props.chatkit.isLoading).toBe(false) expect(props.chatkit.currentUser).toBeInstanceOf(Chatkit.CurrentUser) expect(props.chatkit.otherUser).toBeInstanceOf(Chatkit.User) }) }) it("should have a readable display name", () => { class SomeComponent extends React.Component { render() { return null } } const WrappedComponent = withChatkitOneToOne(SomeComponent) expect(WrappedComponent.displayName).toBe( "WithChatkitOneToOne(SomeComponent)", ) }) it("should forward props to nested component", () => { const TestComponentWithProps = props => { return <div>{props.text}</div> } TestComponentWithProps.propTypes = { text: PropTypes.string, } const WrappedComponent = withChatkitOneToOne(TestComponentWithProps) const page = ( <ChatkitProvider instanceLocator={instanceLocator} tokenProvider={tokenProvider} userId={userId} > <WrappedComponent text={"some_value"} otherUserId={otherUserId} /> </ChatkitProvider> ) const renderer = TestRenderer.create(page) const result = renderer.toJSON() expect(result.children).toEqual(["some_value"]) }) it("should NOT forward config props for the HOC", () => { return runInTestRenderer({ resolveWhen: () => true, }).then(({ props }) => { expect(props.otherUserId).toBe(undefined) }) }) it("should inject otherUser via props", () => { return runInTestRenderer({ resolveWhen: props => props.chatkit.otherUser !== null, }).then(({ props }) => { const otherUser = props.chatkit.otherUser expect(otherUser).toBeInstanceOf(Chatkit.User) expect(otherUser.id).toBe(otherUserId) }) }) it("should start inject messages as empty array if there are no messages", () => { return runInTestRenderer({ resolveWhen: props => !props.chatkit.isLoading, }).then(({ initialProps, props }) => { expect(initialProps.chatkit.messages).toEqual([]) expect(props.chatkit.messages).toEqual([]) }) }) it("should update messages in props when a new message is received", () => { const messageParts = [ { type: "text/plain", content: "Hi!", }, ] return runInTestRenderer({ onLoad: () => { fakeAPI.createMessage({ roomId, senderId: otherUserId, parts: messageParts, }) }, resolveWhen: props => props.chatkit.messages.length !== 0, }).then(({ props }) => { expect(props.chatkit.messages).toHaveLength(1) const message = props.chatkit.messages[0] expect(message.parts).toEqual(messageParts) }) }) it("should inject a working sendSimpleMessage method", () => { return runInTestRenderer({ onLoad: props => { props.chatkit.sendSimpleMessage({ text: "MY_MESSAGE", }) }, resolveWhen: props => props.chatkit.messages.length > 0, }).then(() => { const room = fakeAPI.getRoom({ id: makeOneToOneRoomId(userId, otherUserId), }) expect(room.messages).toHaveLength(1) const message = room.messages[0] expect(message.parts).toEqual([ { type: "text/plain", content: "MY_MESSAGE", }, ]) }) }) it("should inject a working sendMultipartMessage method", () => { return runInTestRenderer({ onLoad: props => { props.chatkit.sendMultipartMessage({ parts: [ { type: "application/json", content: "2019", }, ], }) }, resolveWhen: props => props.chatkit.messages.length > 0, }).then(() => { const room = fakeAPI.getRoom({ id: makeOneToOneRoomId(userId, otherUserId), }) expect(room.messages).toHaveLength(1) const message = room.messages[0] expect(message.parts).toEqual([ { type: "application/json", content: "2019", }, ]) }) }) it("should set otherUser.isTyping to true on userStartedTyping", () => { return runInTestRenderer({ resolveWhen: props => !props.chatkit.isLoading, }) .then(({ props }) => { expect(props.chatkit.otherUser.isTyping).toEqual(false) }) .then(() => runInTestRenderer({ onLoad: () => { fakeAPI.sendTypingEvent({ roomId, userId: otherUserId }) }, resolveWhen: props => !props.chatkit.isLoading && props.chatkit.otherUser.isTyping != false, }), ) .then(({ props }) => { expect(props.chatkit.otherUser.isTyping).toEqual(true) }) }) it("should trigger a typing event when sendTypingEvent is called", () => { return new Promise(resolve => { class TestComponent extends React.Component { constructor() { super() this._onLoadHasRun = false } componentDidUpdate() { if (!this.props.chatkit.isLoading && !this._onLoadHasRun) { this.props.chatkit.sendTypingEvent() this._onLoadHasRun = true resolve() } } render() { return null } } TestComponent.propTypes = { chatkit: PropTypes.object, } const WrappedComponent = withChatkitOneToOne(TestComponent) const page = ( <ChatkitProvider instanceLocator={instanceLocator} tokenProvider={tokenProvider} userId={userId} > <WrappedComponent otherUserId={otherUserId} /> </ChatkitProvider> ) TestRenderer.create(page) }).then(() => { const typingEvents = fakeAPI.typingEvents expect(typingEvents).toHaveLength(1) expect(typingEvents[0].userId).toEqual(userId) expect(typingEvents[0].roomId).toEqual(roomId) }) }) it("should trigger a render when there is an incoming presence change", () => { return runInTestRenderer({ onLoad: () => { fakeAPI.sendPresenceEvent({ userId: otherUserId, newState: "online", }) }, resolveWhen: props => { return ( !props.chatkit.isLoading && props.chatkit.otherUser.presence.state === "online" ) }, }).then(({ props }) => { expect(props.chatkit.otherUser.presence.state).toEqual("online") }) }) it("should set otherUser.lastReadMessageId to the initial value on load", () => { const lastReadMessageId = 42 fakeAPI.createRoom({ id: roomId, userIds: [userId, otherUserId], }) fakeAPI.setCursor({ userId: otherUserId, roomId, position: lastReadMessageId, }) return runInTestRenderer({ resolveWhen: props => !props.chatkit.isLoading, }).then(({ props }) => { expect(props.chatkit.otherUser.lastReadMessageId).toEqual( lastReadMessageId, ) }) }) it("should set otherUser.lastReadMessageId to the latest value", () => { const lastReadMessageId = 42 return runInTestRenderer({ onLoad: () => { fakeAPI.setCursor({ userId: otherUserId, roomId, position: lastReadMessageId, }) }, resolveWhen: props => { return ( !props.chatkit.isLoading && props.chatkit.otherUser.lastReadMessageId !== undefined ) }, }).then(({ props }) => { expect(props.chatkit.otherUser.lastReadMessageId).toEqual( lastReadMessageId, ) }) }) it("should inject a working setReadCursor method", () => { let messageId = null return new Promise(resolve => { class TestComponent extends React.Component { constructor() { super() this._hasSentMessage = false this._hasSetReadCursor = false } componentDidUpdate() { if (this.props.chatkit.isLoading) { return } if (!this._hasSentMessage) { const message = fakeAPI.createMessage({ roomId, senderId: otherUserId, parts: [ { type: "text/plain", content: "Hi!", }, ], }) this._hasSentMessage = true messageId = message.id } if ( this.props.chatkit.messages.length > 0 && !this._hasSetReadCursor ) { this.props.chatkit.setReadCursor() this._hasSetReadCursor = true resolve() } } render() { return null } } TestComponent.propTypes = { chatkit: PropTypes.object, } const WrappedComponent = withChatkitOneToOne(TestComponent) const page = ( <ChatkitProvider instanceLocator={instanceLocator} tokenProvider={tokenProvider} userId={userId} > <WrappedComponent otherUserId={otherUserId} /> </ChatkitProvider> ) TestRenderer.create(page) }).then(() => { const cursor = fakeAPI.getCursor({ roomId, userId, }) expect(messageId).not.toEqual(null) expect(cursor).toEqual(messageId) }) }) it("should load the correct room when otherUserId changes", () => { return new Promise((resolve, reject) => { class TestComponent extends React.Component { constructor() { super() this._otherUserIdsSeen = new Set() } render() { if (this.props.chatkit.isLoading) { return null } this._otherUserIdsSeen.add(this.props.chatkit.otherUser.id) if (this._otherUserIdsSeen.size == 2) { if (!this._otherUserIdsSeen.has("bob")) { reject( new Error( "Exoected other user to have contained bob, but it didn't", ), ) } if (!this._otherUserIdsSeen.has("charlie")) { reject( new Error( "Exoected other user to have contained charlie, but it didn't", ), ) } resolve() } return null } } TestComponent.propTypes = { chatkit: PropTypes.object, } const WrappedComponent = withChatkitOneToOne(TestComponent) const firstOtherUserId = "bob" const secondOtherUserId = "charlie" class TopLevelComponent extends React.Component { constructor() { super() this.state = { otherUserId: firstOtherUserId, } } render() { setTimeout( () => this.setState({ otherUserId: secondOtherUserId }), 100, ) return ( <ChatkitProvider instanceLocator={instanceLocator} tokenProvider={tokenProvider} userId={userId} > <WrappedComponent otherUserId={this.state.otherUserId} /> </ChatkitProvider> ) } } TestRenderer.create(<TopLevelComponent />) }) }) })
1.65625
2
test/index.js
toniov/es-fixtures
17
1127
'use strict'; const esFixtures = require('../src'); const test = require('ava'); // use a different index for each test const indexes = ['bulk_index', 'clear_index', 'create_index', 'create_unexistent_index', 'mapping_index', 'load_random_index', 'load_incremental_index', 'clear_load_index', 'load_assigned_id_index']; const type = 'my_type'; test.before('delete indexes in case they exist', async () => { const client = esFixtures.bootstrap().client; const arrayOfPromsies = indexes.map(async (index) => { return client.indices.delete({ index: index, ignore: [404] }); }); await Promise.all(arrayOfPromsies); }); test('should use bulk properly', async (t) => { const loader = esFixtures.bootstrap('bulk_index', type); const data = [ { index: { _id: 1 } }, { name: 'Jotaro' }, { index: { _id: 2 } }, { name: 'Jolyne' }, ]; const result = await loader.bulk(data); t.false(result.errors); }); test('should clear all documents', async (t) => { const index = 'clear_index'; const loader = esFixtures.bootstrap(index, type); // insert mock data for (let i = 0; i < 100; i++) { await loader.client.create({ index: index, type: type, id: i, refresh: true, body: { title: `Inserted in ${i} place`, } }); } // count inserted number of documents const countBefore = await loader.client.count({ index: index, type: type }); t.is(countBefore.count, 100); // delete all inserted documents await loader.clear(); // count again deleting them const countAfter = await loader.client.count({ index: index, type: type }); t.is(countAfter.count, 0); }); test('should re-create existent index', async (t) => { const loader = esFixtures.bootstrap('create_index', type); await loader.client.indices.create({ index: 'create_index' }); const data = { mappings: { my_type_old: { properties: { name: { type: 'string' } } } } }; await loader.createIndex(data, { force: true }); t.notThrows(loader.client.indices.get({ index: 'create_index' })); }); test('should create index if it does not exist', async (t) => { const index = 'create_unexistent_index'; const loader = esFixtures.bootstrap(index, type); const data = { mappings: { [type]: { properties: { name: { type: 'string' } } } } }; await loader.createIndex(data); t.notThrows(loader.client.indices.get({ index: 'create_unexistent_index' })); }); test('should add mapping', async (t) => { const index = 'mapping_index'; const loader = esFixtures.bootstrap(index, type); await loader.client.indices.create({ index: index }); const data = { properties: { name: { type: 'string' } } }; await loader.addMapping(data); const mappingRes = await loader.client.indices.getMapping({ index: index, type: type }); t.truthy(mappingRes[index].mappings[type]); }); test('should add documents with random ids', async (t) => { const index = 'load_random_index'; const loader = esFixtures.bootstrap(index, type); const data = [{ name: 'Jotaro', standName: 'Star Platinum' }, { name: 'Jolyne', standName: 'Stone Free' }]; await loader.load(data); // check it was inserted correctly const searchResult = (await loader.client.search({ index: index })).hits.hits; const result1 = searchResult.some(result => result._source.name === 'Jotaro'); const result2 = searchResult.some(result => result._source.name === 'Jolyne'); t.is(searchResult.length, 2); t.true(result1); t.true(result2); }); test('should add documents with incremental ids', async (t) => { const index = 'load_incremental_index'; const loader = esFixtures.bootstrap(index, type); const data = [{ name: 'Jotaro', standName: 'Star Platinum' }, { name: 'Jolyne', standName: 'Stone Free' }]; const options = { incremental: true }; await loader.load(data, options); // check it was inserted correctly const searchResult = (await loader.client.search({ index: index })).hits.hits; const result1 = searchResult.find(result => result._id === '1'); const result2 = searchResult.find(result => result._id === '2'); t.is(result1._source.name, 'Jotaro'); t.is(result2._source.name, 'Jolyne'); }); test('should add documents with id specified inside doc', async (t) => { const index = 'load_assigned_id_index'; const loader = esFixtures.bootstrap(index, type); const data = [{ _id: 1, name: 'Jotaro', standName: 'Star Platinum' }, { _id: 2, name: 'Jolyne', standName: 'Stone Free' }]; await loader.load(data); // check it was inserted correctly const searchResult = (await loader.client.search({ index: index })).hits.hits; const result1 = searchResult.find(result => result._id === '1'); const result2 = searchResult.find(result => result._id === '2'); t.is(result1._source.name, 'Jotaro'); t.is(result2._source.name, 'Jolyne'); }); test('should clear and add documents with random ids', async (t) => { const loader = esFixtures.bootstrap('clear_load_index', type); // insert mock data for (let i = 0; i < 100; i++) { await loader.client.create({ index: 'clear_load_index', type: type, id: i, refresh: true, body: { title: `Inserted in ${i} place`, } }); } // count inserted number of documents const countBefore = await loader.client.count({ index: 'clear_load_index', type: type }); t.is(countBefore.count, 100); // delete all inserted documents and add new ones const data = [{ name: 'Jotaro', standName: 'Star Platinum' }, { name: 'Jolyne', standName: 'Stone Free' }]; await loader.clearAndLoad(data, { refresh: false }); // count again after clearing and loading them const countAfter = await loader.client.count({ index: 'clear_load_index', type: type }); t.is(countAfter.count, 2); }); test.after.always('remove created indexes', async () => { const client = esFixtures.bootstrap().client; const arrayOfPromises = indexes.map((index) => { return client.indices.delete({ index: index, ignore: [404] }); }); await Promise.all(arrayOfPromises); });
1.71875
2
lib/value_parsers.js
egils-consulting/wikibase-cli
110
1135
module.exports = { string: arg => arg.toString(), number: str => parseInt(str), boolean: value => { if (value === 'true') return true if (value === 'false') return false return value }, lang: str => str.split(/[\W_-]/)[0].toLowerCase(), object: obj => obj }
0.765625
1
renderer.js
pietrop/captioning-app
0
1143
// This file is required by the index.html file and will // be executed in the renderer process for that window. // All of the Node.js APIs are available in this process. "use strict"; //TODO: see if can move this code in main.js and if it still works when packaged. const fixPath = require('fix-path'); console.log(process.env.PATH); //=> '/usr/bin' fixPath(); const youtubedl = require('youtube-dl'); const fs = require('fs'); const path = require('path'); const electron = require('electron'); const exec = require('child_process').exec; const child = require('child_process').execFile; const spawn = require('child_process').spawn; const webvtt = require('node-webvtt-youtube'); const {dialog} = require('electron').remote; const tokenizer = require('sbd'); var currentWindow = electron.remote.getCurrentWindow(); var electronShell = require("electron").shell; var dataPath = currentWindow.dataPath.replace(/ /g,"\\ "); var desktopPath = currentWindow.desktopPath; var appPath = currentWindow.appPath; console.log("appPath",appPath); console.log("dataPath",dataPath); var alignBtnEl = document.getElementById('alignBtn'); var exportSrtBtnEl = document.getElementById('exportSrtBtn'); var selectFileBtnEl = document.getElementById('selectFileBtn'); var loadYoutubeUrlBtnEl = document.getElementById('loadYoutubeUrlBtn'); var videoYoutubeUrlInputEl = document.getElementById('videoYoutubeUrlInput'); var videoPreviewEl = document.getElementById('videoPreview'); var textBoxEl = document.getElementById('textBox'); var checkboxInputEl = document.getElementById('checkboxInput'); var saveBtnEl = document.getElementById('saveBtn'); var restoreLastSavedVersionBtnEl = document.getElementById('restoreLastSavedVersionBtn'); var selectCaptionFormatEl = document.getElementById('selectCaptionFormat'); var selectLanguageForAlignementEl = document.getElementById('selectLanguageForAlignement'); var navigateBtnEl = document.getElementById('navigateBtn'); var timeout = null; var resumeTiypingTimeInterval = 600; var startStopPlayingVideoOntyping = false; var isYoutubeVideo = false; var sourceVideoPath ="tempCaptionsMakerFile"; window.sourceVideoPath = sourceVideoPath; restoreLastSavedVersionBtnEl.onclick = function(e){ e.preventDefault(); restoreStateFromLocalStorage(); }; navigateBtnEl.onclick = function(e){ console.info("NAVIGATE BTN") e.preventDefault(); // var fileName = "tmpForJsonAlignment"; // var outPutSegmentedFile = dataPath+"/"+fileName+"._segmented"+".txt"; var fileName = path.basename(sourceVideoPath); var outPutSegmentedFile = dataPath+"/"+fileName+"._segmented"+".txt"; // var textFile = dataPath+"/"+fileName+"."+"json"; var textFile = createTextFileFromTextEditor(); var config={ language: getLanguageForAlignement(), captionFileFormat : "json", audio_file_head_length : 0,//eg 12.000 audio_file_tail_length : 0, //16.000 mediaFile : sourceVideoPath, outPutSegmentedFile : outPutSegmentedFile, textFile : textFile }; console.info("FLAG 1",outPutSegmentedFile, textFile); runAeneasComand(config, function(jsonFile){ // console.log("srtFilePath",srtFilePath); var aeneasJson = JSON.parse(fs.readFileSync(jsonFile,'utf8')); textBoxEl.innerHTML =parseAeneasJson(aeneasJson) textEditorContentEditable(false); makeLinesInteractive(); }); } saveBtnEl.onclick = function(e){ e.preventDefault(); saveToLocalStorage(); alert("saved"); // Then to repopulate on load if that is empty. }; function saveToLocalStorage(){ localStorage.captionsMakerState ={} //Horrible to save as HTML without serializing, but if save as TXT looses new line. //TODO: Welcome sudgestions on how to improve on this localStorage.captionsMakerStateText = textBoxEl.innerHTML; localStorage.captionsMakerStateVideoSrc = sourceVideoPath; } function restoreStateFromLocalStorage(){ //TODO: add notice, confirm, this will cancel the current session. do you want to continue? or relax, nothing happend. if(localStorage.captionsMakerState){ setTextBoxContent(localStorage.captionsMakerStateText); // makeSrtTimeCodesIntoLinks(); addLinksToSrtTimecodes(); // loadHtml5Video(localStorage.captionsMakerStateVideoSrc); isYoutubeVideo = false; sourceVideoPath = localStorage.captionsMakerStateVideoSrc; }else{ alert("No previously saved version was found."); } } checkboxInputEl.onclick = function(e){ // e.preventDefault(); if(startStopPlayingVideoOntyping == false){ startStopPlayingVideoOntyping = true; }else{ startStopPlayingVideoOntyping = false; } }; selectFileBtnEl.onclick = function(){ // e.preventDefault() isYoutubeVideo = false; dialog.showOpenDialog({properties: ['openFile']}, function(file){ console.log(file[0]); sourceVideoPath = file[0]; loadHtml5Video(sourceVideoPath); // loadEditorWithDummyText(); }); }; loadYoutubeUrlBtnEl.onclick = function(e){ e.preventDefault(); isYoutubeVideo = true; disableTextEditorProgressMessage(); var url = videoYoutubeUrlInputEl.value; //TODO: add validation to check it's a valid youtube URL. var youtubeId = youtubeUrlExtractId(url); populateYoutubePlayer(youtubeId); //TODO: can I use path .join here to add extension to name? // var destFileName = dataPath+"/"+ youtubeId+".mp4"; // sourceVideoPath = destFileName; downloadYoutubeVideo(url, function(destPath){ sourceVideoPath = destPath; loadHtml5Video(sourceVideoPath); isYoutubeVideo = false; console.log("sourceVideoPath+ ",sourceVideoPath) downloadCaptions(url, function(captionFiles){ if (captionFiles.length ==0){ alert("This video has no captions"); }else{ var captionFile = captionFiles[0]; console.log("1,openYoutubeVttFile"); openYoutubeVttFile(path.join(dataPath,captionFile)); // var captionsContent = openFile(captionFiles[0]); console.log(captionFile); } }); }); }; exportSrtBtnEl.onclick = function(){ //assumes allignment has been run, perhaps add a boolean flag to check that it is the case. //read content of textEditor. var fileName = path.basename(sourceVideoPath); //prompt user on where to save. add srt extension if possible. var newFilePath = desktopPath +"/"+ fileName+"."+getCaptionsFileFormat(); fs.writeFileSync(newFilePath, getContentFromTextEditor(), 'utf8'); // or just save to desktop. alert("your file has been saved on the desktop "+newFilePath); } function getCaptionsFileFormat(){ return selectCaptionFormatEl.value ; } function getLanguageForAlignement(){ return selectLanguageForAlignementEl.value; } alignBtnEl.onclick = function(){ //create text file of content of text box. in tmp folder. var textFile = createTextFileFromTextEditor(); var fileName = path.basename(sourceVideoPath); var outPutSegmentedFile = dataPath+"/"+fileName+"._segmented"+".txt"; // console.log("sourceVideoPath in alignBtnEl ", sourceVideoPath); // console.log('outPutSegmentedFile',outPutSegmentedFile); //should call perl scrip to prep on textfile to prep it for aeneas //TODO add: if(sourceVideoPath !="") var config={ language: getLanguageForAlignement(), captionFileFormat : getCaptionsFileFormat(), audio_file_head_length : 0,//eg 12.000 audio_file_tail_length : 0, //16.000 mediaFile : sourceVideoPath, outPutSegmentedFile : outPutSegmentedFile, textFile : textFile }; segmentTranscript(config, function(respSegmentedFileContent){ // console.log("LDLDL",fs.readFileSync(respSegmentedFileContent ).toString()); // config.outPutSegmentedFile = respSegmentedFilePath; config.outPutSegmentedFile = respSegmentedFileContent; console.log('config.outPutSegmentedFile',config.outPutSegmentedFile); console.log("LDLDL",fs.readFileSync(respSegmentedFileContent ).toString()); runAeneasComand(config, function(srtFilePath){ // console.log("srtFilePath",srtFilePath); textBoxEl.innerText =fs.readFileSync(srtFilePath,'utf8').toString('utf8'); //clear up // fs.unlinkSync(outPutSegmentedFile); // fs.unlinkSync(textFile); // fs.unlinkSync(srtFilePath); makeSrtTimeCodesIntoLinks(); addLinksToSrtTimecodes(); }); }) // }; //return path to file function createTextFileFromTextEditor(){ var fileName = path.basename(sourceVideoPath); // console.log('fileName',fileName); //TODO: add path. use path library var tmpTextFileName = dataPath+"/"+ fileName+".txt"; // console.log('tmpTextFileName',tmpTextFileName) fs.writeFileSync(tmpTextFileName, getContentFromTextEditor(),'utf8'); return tmpTextFileName; } function getContentFromTextEditor(){ //TODO: add sanitise step. return textBoxEl.innerText; } function loadHtml5Video(path){ videoPreviewEl.innerHTML = `<video width="100%" controls> <source src="${path}" type="video/mp4">`; initializeVideoPlayPuaseTypingPreferences(); } // TODO: you can't seem to be able to change this preference after having loaded the video. Needs fixing. // Use case, you are reviewing the text without emphasis on a speicific part. function initializeVideoPlayPuaseTypingPreferences(){ textBoxEl.onkeyup = function () { if(startStopPlayingVideoOntyping){ clearTimeout(timeout); pauseVideo(); //add timer logic to start playing after set interval. timeout = setTimeout(function () { // console.log('Input Value:', textInput.value); playVideo(); }, resumeTiypingTimeInterval); } }; }; // selectFileBtnEl.onclick = function(e){ // e.preventDefault(); // //TODO // }; function makeSrtTimeCodesIntoLinks () { // console.log(textBoxEl.innerHTML); //http://pietropassarelli.com/regex.html textBoxEl.innerHTML = textBoxEl.innerHTML.replace(/(\d{2}[:|.]\d{2}[:|.]\d{2}[.|,|:]\d{3})/ig , function replace(match) { //(?!<) return '<a class="timecodeLink">' + match + '</a>'; }); //TODO: Move curson back to it's possition after replacement editable //add event listener on class name. //https://stackoverflow.com/questions/19655189/javascript-click-event-listener-on-class }; function addLinksToSrtTimecodes(){ var timecodesEl = document.querySelectorAll('.timecodeLink'); timecodesEl.forEach(function(element, index){ element.onclick = function(){ setVideoCurrentTime(element.innerText); } }) } function setVideoCurrentTimeForNavigate(time){ // var time; // if(typeof timecode != "number"){ // //convert timecode // time = convertTimeCodeToSeconds(timecode); // }else{ // var time = timecode; // } // if(isYoutubeVideo){ // var iframe = document.querySelector('iframe'); // var innerDoc = iframe.contentDocument || iframe.contentWindow.document; // // innerDoc.querySelectorAll('video')[0].click(); // innerDoc.querySelectorAll('video')[0].currentTime = time; // playVideo(); // }else{ var video = document.querySelector('video'); video.currentTime = time ; playVideo(); // } } function openYoutubeVttFile(path){ // console.log("2,openYoutubeVttFile"); var vttFileContent = openFile(path); console.log(path,vttFileContent); //Do some parting var parsed = parseYoutubeVtt(vttFileContent); //add punctuation punctuatorPostRequest(parsed, function(respText){ // console.log('respText',JSON.stringify(respText,null,2)); setTextBoxContent(respText); textEditorContentEditable(true); }); } function parseYoutubeVtt(vtt){ var vttJSON =webvtt.parse(vtt); var result =""; vttJSON.cues.forEach(function(line, index){ result+= parseYoutubeVttTextLine(line.text)+" "; }) return result; } function parseYoutubeVttTextLine(textLine){ //used http://scriptular.com/ return textLine.replace(/<[A-z|.|0-9|:|/]*>/g,""); } function openFile(path){ return fs.readFileSync(path,'utf8').toString('utf-8'); } function loadEditorWithDummyText(){ textBoxEl.innerText = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed accumsan urna nec dui lacinia porttitor. Etiam eget rutrum quam, in hendrerit sapien. Etiam sed placerat lectus. Etiam viverra fermentum lacus non rhoncus. Fusce tristique lacus turpis, ac consequat lorem rhoncus a. Maecenas tempus massa sed ex ullamcorper ultrices. Nam eget pharetra risus, id ultrices sapien. Proin a euismod sem, sed dignissim dolor. Maecenas fringilla sem in ligula pellentesque venenatis. Sed eget ipsum tempus, euismod ex id, sollicitudin ipsum. Vestibulum pretium justo a dolor tincidunt, posuere ultrices nisl dapibus. Proin pretium ultricies posuere. Quisque faucibus arcu id dolor pulvinar congue. Aenean quis finibus magna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam dignissim vehicula volutpat. Vestibulum fermentum arcu nisl, placerat faucibus ex semper tempus. Aliquam mattis, sem sed accumsan fringilla, dolor mi sagittis nunc, quis suscipit dui turpis sed justo. Curabitur lacinia vulputate leo, et pharetra ipsum laoreet a. Nunc sagittis nulla mi, in dignissim ex molestie quis. Etiam hendrerit tincidunt diam, eget fringilla mauris ultrices et. Mauris quam mauris, dictum ut orci vitae, sodales ultrices arcu. Proin sed rhoncus ex. Ut pellentesque pellentesque justo, ac consectetur sapien. Praesent at tortor magna. Ut id ligula risus. Aliquam vestibulum nisi vel justo feugiat consequat. Mauris pellentesque orci at tellus porttitor, eu tempus urna sodales. Praesent et volutpat nisi. Vestibulum laoreet sollicitudin lacus, nec faucibus elit auctor in. Nunc malesuada orci quam, vel vulputate ante mollis viverra. Donec at velit dictum, lobortis massa vel, pharetra sapien. Praesent elementum magna eu orci gravida, in interdum tellus blandit. Quisque efficitur venenatis ex, eget laoreet erat facilisis eu. Praesent suscipit magna a neque dignissim iaculis. Curabitur pellente`; } function downloadCaptions(url,cb){ // console.log("downloadCaptions"); var options = { // Write automatic subtitle file (youtube only) auto: true, // Downloads all the available subtitles. all: false, // Languages of subtitles to download, separated by commas. lang: 'en', // format: 'srt/vtt', // The directory to save the downloaded files in. cwd: dataPath, }; youtubedl.getSubs(url, options, function(err, files) { if (err) throw err; if(cb){cb(files);} // setCaptionsStatus(subtitlesDownloadedMessage); console.info('subtitle files downloaded:', files); return files; }); } function downloadYoutubeVideo(url, cb){ //update user GUI on status of download // setStatusElement(downloadingMessage); // reset captions status // setCaptionsStatus('...'); var destFilePathName; //setup download with youtube-dl var video = youtubedl(url, // Optional arguments passed to youtube-dl. // see here for options https://github.com/rg3/youtube-dl/blob/master/README.md ['--format=best'], // Additional options can be given for calling `child_process.execFile()`. { cwd: dataPath, maxBuffer: Infinity }); //listener for video info, to get file name video.on('info', function(info) { // console.log("video-info",JSON.stringify(info,null,2)); destFilePathName = path.join(dataPath,info._filename.replace(/ /g,"_"));//info._filename); // console.log("destFilePathName-",destFilePathName); // update GUI with info on the file being downloaded // setInfoPanel('<div class="alert alert-dismissible alert-success"><strong>Filename: </strong>' + info._filename+'<br><strong>size: </strong>' + info.size+'<br>'+'<strong>Destination: </strong>'+destFilePathName+"</div>"); //TODO: sanilitse youtube file name so that it can be //save file locally var writeStream = fs.createWriteStream(destFilePathName); video.pipe(writeStream); }); video.on('end', function() { //TODO: replace with update Div symbol // setStatusElement(finishedDownloadingMessage); if(cb){cb(destFilePathName)}; }); } function youtubeUrlExtractId(url){ var urlParts = url.split("/"); var urlPartsLegth = urlParts.length; var youtubeId = urlParts[urlPartsLegth-1] return youtubeId; } function setTextBoxContent(text){ //todo: sanitise `text` textBoxEl.innerHTML = text; } function getTextBoxContent(){ // convert from html return textBoxEl.innerHTML; } function populateYoutubePlayer(id){ // console.log(id); //simple implementation var youtubeElement = `<iframe id="youtubeIframe" width='560' height='315' class='embed-responsive-item' src="https://www.youtube.com/embed/${id}" frameborder="0" allowfullscreen></iframe>`; // var youtubeElement = `<video width="640" height="360"><source type="video/youtube" src="http://www.youtube.com/watch?v=${id}" /></video>` videoPreviewEl.innerHTML = youtubeElement; // document.querySelector( 'video' ).addEventListener("playing", checkIfTypingPause, false); document.getElementById('youtubeIframe').onload= function() { var iframe = document.querySelector('iframe'); var innerDoc = iframe.contentDocument || iframe.contentWindow.document; //start video //TODO: decide whether to enable this or not. maybe make as an option? // innerDoc.querySelectorAll('video')[0].click(); initializeVideoPlayPuaseTypingPreferences(); }; } function playVideo(){ // console.log("play video "); // document.querySelector( 'video' ).play(); if(isYoutubeVideo){ var iframe = document.querySelector('iframe'); var innerDoc = iframe.contentDocument || iframe.contentWindow.document; if(innerDoc.querySelectorAll('video')[0].src ==""){ innerDoc.querySelectorAll('video')[0].click(); }else{ innerDoc.querySelectorAll('video')[0].play(); } }else{ var video = document.querySelector('video'); video.play(); } } function pauseVideo(){ if(isYoutubeVideo){ var iframe = document.querySelector('iframe'); var innerDoc = iframe.contentDocument || iframe.contentWindow.document; // document.querySelector( 'video' ).pause(); innerDoc.querySelectorAll('video')[0].pause(); }else{ var video = document.querySelector('video'); video.pause(); } } function populateVideoPlayer(url){ } function runAeneasComand(config,cb){ var mediaFile = config.mediaFile; var textFile = config.textFile; var language = config.language; var captionFileFormat = config.captionFileFormat; var audio_file_head_length = config.audio_file_head_length;//eg 12.000 var audio_file_tail_length = config.audio_file_tail_length; //16.000 // var tmpTextFileName = dataPath +"/"+ fileName; var fileName = path.basename(mediaFile); var outputCaptionFile = dataPath+"/"+fileName+"."+captionFileFormat; // console.log(JSON.stringify(config,null,2)); var outPutSegmentedFile = config.outPutSegmentedFile; console.log("Aeneas outPutSegmentedFile",outPutSegmentedFile); ///usr/local/bin/aeneas_execute_task///usr/local/bin/aeneas_execute_task //python -m aeneas.tools.execute_task var aeneasComandString = `/usr/local/bin/aeneas_execute_task "${mediaFile}" "${outPutSegmentedFile}" "task_language=${language}|os_task_file_format=${captionFileFormat}|is_text_type=subtitles|is_audio_file_head_length=${audio_file_head_length}|is_audio_file_tail_length=${audio_file_tail_length}|task_adjust_boundary_nonspeech_min=1.000|task_adjust_boundary_nonspeech_string=REMOVE|task_adjust_boundary_algorithm=percent|task_adjust_boundary_percent_value=75|is_text_file_ignore_regex=[*]" ${outputCaptionFile}`; // var productionEnv = Object.create(process.env); console.info("aeneasComandString", aeneasComandString); var aeneasPath = "/usr/local/bin/aeneas_execute_task"; var ffmpegPath = "/usr/local/bin/ffmpeg"; var ffprobePath = "/usr/local/bin/ffprobe"; var espeakPath = "/usr/local/bin/espeak"; var envVar = {'ffmpeg': ffmpegPath , 'ffprobe': ffprobePath, 'espeak':espeakPath, 'aeneas_execute_task': aeneasPath}; var options ={env: envVar, cwd: appPath} exec(aeneasComandString, function(error, stdout, stderr) { console.log('stdout runAeneasComand: ' + stdout); console.log('stderr runAeneasComand: ' + stderr); if(cb){cb(outputCaptionFile)}; if (error !== null) { console.log('exec error: ' + error); } }); } window.segmentTranscript = segmentTranscript; function segmentTranscript(config,cb){ var inputFile = config.textFile; var outPutSegmentedFile = config.outPutSegmentedFile; // var segmentTranscriptComand =`perl ${appPath}/sentence-boundary.pl -d ${appPath}/HONORIFICS -i ${inputFile} -o ${outPutSegmentedFile}`; sentenceBoundariesDetection(inputFile, outPutSegmentedFile, function(filePathSetencesWithLines){ if(cb){cb(filePathSetencesWithLines);} }); // TODO: refactor this } function sentenceBoundariesDetection(textFile,outPutSegmentedFile,cb){ var options = { "newline_boundaries" : true, "html_boundaries" : false, "sanitize" : false, "allowed_tags" : false, //TODO: Here could open HONORIFICS file and pass them in here I think "abbreviations" : null }; var text = fs.readFileSync(textFile).toString('utf8'); var sentences = tokenizer.sentences(text, options); // console.log("sentences",sentences); var sentencesWithLineSpaces=sentences.join("\n\n"); // console.log("sentencesWithLineSpaces",sentencesWithLineSpaces); fs.writeFileSync(outPutSegmentedFile,sentencesWithLineSpaces); //TODO: replace the system calls, unix fold, perl etc.. with js modules for segmentations. //TODO: extra manupulation of text //2. The 2nd line (pictured) takes each of sentences (now separated by an empty line) //and places a new line mark at the end of the word that exceeds > 35 characters //(if the sentence exceeds that number) //# Break each line at 35 characters //fold -w 35 -s test2.txt > test3.txt var outPutSegmentedFile2 = outPutSegmentedFile+"2.txt"; exec(`fold -w 35 -s ${outPutSegmentedFile} > ${outPutSegmentedFile2}`, function(error, stdout, stderr) { // if(cb){cb(outPutSegmentedFile);} console.log('stdout Segmented Script: ' + stdout); console.log('stderr Segmented Script: ' + stderr); if (error !== null) { console.log('exec error Perl Script: ' + error); } // fs.read // fs.writeFileSync(outPutSegmentedFile2,sentencesWithLineSpaces ); // if(cb){cb(sourceVideoPath)}; //3. Then the Perl command (3rd line pictured) will take these new chunks //and separate them further so that there are no more than two consecutive lines before an empty line. //# Insert new line for every two lines, preserving paragraphs // perl -00 -ple 's/.*\n.*\n/$&\n/mg' test3.txt > "$f" var outPutSegmentedFile3 = outPutSegmentedFile+"3.txt"; exec(`perl -00 -ple 's/.*\n.*\n/$&\n/mg' ${outPutSegmentedFile2} > ${outPutSegmentedFile3}`, function(error, stdout, stderr) { console.log('stdout Segmented Script: ' + stdout); console.log('stderr Segmented Script: ' + stderr); if (error !== null) { console.log('exec error Perl Script: ' + error); } console.log("outPutSegmentedFile3", outPutSegmentedFile3); if(cb){cb(outPutSegmentedFile3)}; }); }); } function convertTimeCodeToSeconds(timeString){ var timeArray = timeString.split(":"); var hours = parseFloat(timeArray[0]) * 60 * 60; var minutes = parseFloat(timeArray[1]) * 60; var seconds = parseFloat(timeArray[2].replace(",",".")); // var frames = parseInt(timeArray[3].split(",")[1])*(1/framerate); // var str = "h:" + hours + "\nm:" + minutes + "\ns:" + seconds + "\nf:" + frames; // console.log(str); var totalTime = hours + minutes + seconds// + frames; //alert(timeString + " = " + totalTime) return totalTime; } // window.punctuatorPostRequest = punctuatorPostRequest; //TODO: this could be refactored into function punctuatorPostRequest(content, cb){ var tmpPunctuationFile =sourceVideoPath+".punctuation.txt"; //"~/Desktop/textTEST.txt" var comand = `curl -d "text=${content}" http://bark.phon.ioc.ee/punctuator > ${tmpPunctuationFile}` exec(comand, function(error, stdout, stderr) { var resultTextWithPunctuation = openFile(tmpPunctuationFile); if(cb){cb(resultTextWithPunctuation)} console.log('stdout punctuatorPostRequest: ' + stdout); console.log('stderr punctuatorPostRequest: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } }); } function disableTextEditorProgressMessage(){ textEditorContentEditable(false, "<i>Transcription in progress...</i>") } function textEditorContentEditable(editable, message){ if(message){ textBoxEl.innerHTML = message; } textBoxEl.contentEditable = editable; } //TODO: add a button and onclick listener that points to this function function resetPunctuation(){ var text = textBoxEl.innerText; // confirm("warning this removes timecodes and current puctuation"). //remove any timecode // remove any pucntuation . , ! ? //call punctuator and reset punctuation //add to text box } ///Credentials // var passwordInput = document.getElementById('password'); // var usernameInput = document.getElementById('username'); // var saveCredentialsBtnEl = document.getElementById('saveCredentialsBtn'); // function getPassword(){ // return passwordInput.value ; // } // function getUsername(){ // return usernameInput.value; // } // function saveCredentials(){ // alert("saved"); // localStorage.username = getUsername(); // localStorage.password = <PASSWORD>() // } // function populateCredentials(){ // passwordInput.value = window.credentials.password; // usernameInput.value = window.credentials.username; // } // function loadCredentials(){ // if(localStorage.username && localStorage.password){ // window.credentials = {username: localStorage.username, password: localStorage.password}; // }else{ // // alert("add credentials for "); // document.getElementById('settingsModalBtnTrigger').click() // } // } // loadCredentials(); // populateCredentials(); // saveCredentialsBtnEl.onclick = function(e){ // e.preventDefault(); // saveCredentials(); // }; // addEventListener("click", saveCredentials); // function parseAeneasJson(aeneasJson){ var result = ""; var fragments = aeneasJson.fragments; fragments.forEach(function(frag){ console.info('frag.begin', frag.begin); result += `<span class="alignedline" data-start=${frag.begin} data-end=${frag.end}>${frag.lines} </span>` }) return result; } function makeLinesInteractive(){ //declaring counter for loop here so that it is visible in scope of on click ananonimous function; // var i; var lines = document.getElementsByClassName('alignedline'); for(var i=0; i< (lines.length -1) ; i++){ console.log(i, lines.length); // var line = lines[i]; // lines.forEach(function(line){ lines[i].addEventListener("click", function(ev){ console.log(ev, ev.target)//; console.log(lines[i], lines[i].dataset.start, lines[i], ev.target.dataset.start); setVideoCurrentTimeForNavigate(parseInt(ev.target.dataset.start)); // setVideoForClickLine(line); }); // }); } } function setVideoCurrentTime(timecode){ var time; if(typeof timecode != "number"){ //convert timecode time = convertTimeCodeToSeconds(timecode); }else{ time = timecode; } if(isYoutubeVideo){ var iframe = document.querySelector('iframe'); var innerDoc = iframe.contentDocument || iframe.contentWindow.document; // innerDoc.querySelectorAll('video')[0].click(); innerDoc.querySelectorAll('video')[0].currentTime = time; playVideo(); }else{ var video = document.querySelector('video'); video.currentTime = time ; playVideo(); } } // function setVideoForClickLine(line){ // setVideoCurrentTime(parseInt(line.dataset.start)); // } ///progress line /// // var sideLine = document.getElementById('progressLineEditor'); // sideLine.onclick = function(e){ // var sideLinePosition = sideLine.getBoundingClientRect() // console.log("sideLinePosition",sideLinePosition) // console.log( "sideLinePosition.bottom", sideLinePosition.bottom ," sideLinePosition.top", sideLinePosition.top) // var sideLineLength = sideLinePosition.bottom - sideLinePosition.top; // var mousePositionOnLine = e.clientY - sideLinePosition.top; // console.log("e.clientY",e.clientY); // console.log("sideLineLength",sideLineLength,"mousePositionOnLine",mousePositionOnLine) // } //TODO: disable while speech to text //textBoxEl.innerHTML = "<i>Transcription in progress...</i>" //textBoxEl.contentEditable = false //textBoxEl.contentEditable = true //to add captions dynamically - Might not be needed as a requiremen // maybe add button, update captions preview. or auto trigger. // might need to write the `vtt` file. and then code below to update on video. // altho it better if video was bigger. // document.querySelector("video").innerHTML = '<track label="English Captions" srclang="en" kind="captions" src="/Users/pietropassarelli/Dropbox/CODE/NODE/webVideoTextCrawler/test/results.vtt" type="text/vtt" default />'
1.328125
1
core/assets/js/event-card.js
LorenzSelv/pinned
1
1151
// Blur other cards when hovering over one and remove blurring after leaving it $(".event-card").mouseover(function() { $(".event-card").not(this).each(function() { $(this).addClass("card-blurred") }) }).mouseout(function() { $(".event-card").not(this).each(function() { $(this).removeClass("card-blurred") }) })
1.132813
1
app/scripts/modules/openstack/src/region/regionSelectField.directive.js
scopely/deck
0
1159
'use strict'; const angular = require('angular'); import _ from 'lodash'; import { ACCOUNT_SERVICE } from '@spinnaker/core'; module.exports = angular .module('spinnaker.openstack.region.regionSelectField.directive', [ ACCOUNT_SERVICE, require('../common/selectField.component.js').name, ]) .directive('osRegionSelectField', function(accountService) { return { restrict: 'E', templateUrl: require('../common/cacheBackedSelectField.template.html'), scope: { label: '@', labelColumnSize: '@', helpKey: '@', model: '=', filter: '=', account: '<', onChange: '&', readOnly: '<', allowNoSelection: '=', noOptionsMessage: '@', noSelectionMessage: '@', }, link: function(scope) { _.defaults(scope, { label: 'Region', labelColumnSize: 3, valueColumnSize: 7, options: [{ label: scope.model, value: scope.model }], filter: {}, backingCache: 'regions', updateOptions: function() { return accountService.getRegionsForAccount(scope.account).then(function(regions) { scope.options = _.chain(regions) .map(r => ({ label: r, value: r })) .sortBy('label') .value(); return scope.options; }); }, onValueChanged: function(newValue) { scope.model = newValue; if (scope.onChange) { scope.onChange({ region: newValue }); } }, }); scope.$watch('account', function() { scope.$broadcast('updateOptions'); }); }, }; });
1.148438
1
js-test-suite/testsuite/b76e30b93908fa9967f494d367c8af6b.js
hao-wang/Montage
16
1167
load("bf4b12814bc95f34eeb130127d8438ab.js"); load("93fae755edd261212639eed30afa2ca4.js"); load("6b78370695c49b6074ed4ac9ff090dbd.js"); // Copyright (C) 2016 ecmascript_simd authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: simd-store-in-tarray description: Tests Simdstore functions. includes: [simdUtilities.js] ---*/ function testStore(type, name, count) { var storeFn = type.fn[name]; assert.sameValue('function', typeof storeFn); var bufLanes = 2 * type.lanes; // Test all alignments. var bufSize = bufLanes * type.laneSize + 8; // Extra for over-alignment test. var ab = new ArrayBuffer(bufSize); var buf = new type.view(ab); var a = createTestValue(type); // Value containing 0, 1, 2, 3 ... function checkBuffer(offset) { for (var i = 0; i < count; i++) if (buf[offset + i] != i) return false; return true; } // Test aligned stores. for (var i = 0; i < type.lanes; i++) { assert.sameValue(storeFn(buf, i, a), a); assert(checkBuffer(i)); } // Test the 2 over-alignments. var f64 = new Float64Array(ab); var stride = 8 / type.laneSize; for (var i = 0; i < 1; i++) { assert.sameValue(storeFn(f64, i, a), a); assert(checkBuffer(stride * i)); } // Test the 7 mis-alignments. var i8 = new Int8Array(ab); for (var misalignment = 1; misalignment < 8; misalignment++) { assert.sameValue(storeFn(i8, misalignment, a), a); // Shift the buffer down by misalignment. for (var i = 0; i < i8.length - misalignment; i++) i8[i] = i8[i + misalignment]; assert(checkBuffer(0)); } //Test index coercions storeFn(buf, "0", a); assert(checkBuffer(0)); storeFn(buf, "01", a); assert(checkBuffer(1)); storeFn(buf, " -0.0 ", a); assert(checkBuffer(0)); storeFn(buf, " +1e0", a); assert(checkBuffer(1)); storeFn(buf, false, a); assert(checkBuffer(0)); storeFn(buf, true, a); assert(checkBuffer(1)); storeFn(buf, null, a); assert(checkBuffer(0)); function testIndexCheck(buf, index, err) { assert.throws(err, function () { storeFn(buf, index, type.fn()); }); } testIndexCheck(buf, -1, RangeError); testIndexCheck(buf, bufSize / type.laneSize - count + 1, RangeError); testIndexCheck(buf.buffer, 1, TypeError); testIndexCheck(buf, "a", RangeError); } simdTypes.filter(isNumerical).forEach(function(type) { testSimdFunction(type.name + ' store', function() { testStore(type, 'store', type.lanes); }); }); simdTypes.filter(hasLoadStore123).forEach(function(type) { testSimdFunction(type.name + ' store1', function() { testStore(type, 'store1', 1); }); testSimdFunction(type.name + ' store1', function() { testStore(type, 'store2', 2); }); testSimdFunction(type.name + ' store3', function() { testStore(type, 'store3', 3); }); });
1.703125
2
public/assets/script/scripts.js
Adeyemi-Timilehin/communityforum-juke4devs-
0
1175
/*! * Start Bootstrap - Simple Sidebar v6.0.1 (https://startbootstrap.com/template/simple-sidebar) * Copyright 2013-2021 Start Bootstrap * Licensed under MIT (https://github.com/StartBootstrap/startbootstrap-simple-sidebar/blob/master/LICENSE) */ // // Scripts // window.addEventListener('DOMContentLoaded', event => { // Toggle the side navigation const sidebarToggle = document.body.querySelector('#sidebarToggle'); if (sidebarToggle) { // Uncomment Below to persist sidebar toggle between refreshes // if (localStorage.getItem('sb|sidebar-toggle') === 'true') { // document.body.classList.toggle('sb-sidenav-toggled'); // } sidebarToggle.addEventListener('click', event => { event.preventDefault(); document.body.classList.toggle('sb-sidenav-toggled'); localStorage.setItem('sb|sidebar-toggle', document.body.classList.contains('sb-sidenav-toggled')); }); } }); $(document).ready(function(){ $("#post").click(function(){ $('#re').removeClass('post'); }) $("#user").click(function(){ $("#page-content-wrapper").removeClass('user'); $("#up").addClass("uprofile"); }); $("#profile").click(function(){ $("#page-content-wrapper").addClass('user'); $("#up").removeClass("uprofile"); }) })
1.390625
1
src/utils/setupTests.js
mattcolman/react-prebid
0
1183
import chai from 'chai'; import sinonChai from 'sinon-chai'; import chaiEnzyme from 'chai-enzyme'; import { configure } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import 'regenerator-runtime/runtime'; configure({ adapter: new Adapter() }); chai.should(); chai.use(sinonChai); chai.use(chaiEnzyme()); // Make sure chai and jasmine ".not" play nice together const originalNot = Object.getOwnPropertyDescriptor(chai.Assertion.prototype, 'not').get; Object.defineProperty(chai.Assertion.prototype, 'not', { get() { Object.assign(this, this.assignedNot); return originalNot.apply(this); }, set(newNot) { this.assignedNot = newNot; return newNot; } }); // Combine both jest and chai matchers on expect const jestExpect = global.expect; global.expect = actual => { const originalMatchers = jestExpect(actual); const chaiMatchers = chai.expect(actual); return Object.assign(chaiMatchers, originalMatchers); }; // Fix error message “A "describe" callback must not return a value.” // https://stackoverflow.com/a/55211488/1253156 const realDescribe = global.describe; global.describe = (name, fn) => { realDescribe(name, () => { fn(); }); };
1.445313
1
themes/gatsby-theme-ripperoni-account/src/components/OrderLineItems/index.js
packdigital/ripperoni
0
1191
export { OrderLineItems } from './OrderLineItems';
-0.135742
0
plots.js
dhoebbel/bButton_Biodiversity
0
1199
// Getting references var selDataset = document.getElementById("selDataset"); var PANEL = document.getElementById("sample-metadata"); var PIE = document.getElementById("pie"); var BUBBLE = document.getElementById("bubble"); var Gauge = document.getElementById("gauge"); function updateMetaData(data) { // Reference to Panel element for sample metadata var PANEL = document.getElementById("sample-metadata"); // Clear any existing metadata PANEL.innerHTML = ''; // Loop through all of the keys in the json response and // create new metadata tags for(var key in data) { h6tag = document.createElement("h6"); h6Text = document.createTextNode(`${key}: ${data[key]}`); h6tag.append(h6Text); PANEL.appendChild(h6tag); } } function buildCharts(sampleData, otuData) { // Loop through sample data and find the OTU Taxonomic Name var labels = sampleData[0]['otu_ids'].map(function(item) { return otuData[item] }); // Build Bubble Chart var bubbleLayout = { margin: { t: 0 }, hovermode: 'closest', xaxis: { title: 'OTU ID' } }; var bubbleData = [{ x: sampleData[0]['otu_ids'], y: sampleData[0]['sample_values'], text: labels, mode: 'markers', marker: { size: sampleData[0]['sample_values'], color: sampleData[0]['otu_ids'], colorscale: "Earth", } }]; var BUBBLE = document.getElementById('bubble'); Plotly.plot(BUBBLE, bubbleData, bubbleLayout); // Build Pie Chart console.log(sampleData[0]['sample_values'].slice(0, 10)) var pieData = [{ values: sampleData[0]['sample_values'].slice(0, 10), labels: sampleData[0]['otu_ids'].slice(0, 10), hovertext: labels.slice(0, 10), hoverinfo: 'hovertext', type: 'pie' }]; var pieLayout = { margin: { t: 0, l: 0 } }; var PIE = document.getElementById('pie'); Plotly.plot(PIE, pieData, pieLayout); }; function updateCharts(sampleData, otuData) { var sampleValues = sampleData[0]['sample_values']; var otuIDs = sampleData[0]['otu_ids']; // Return the OTU Description for each otuID in the dataset var labels = otuIDs.map(function(item) { return otuData[item] }); // Update the Bubble Chart with the new data var BUBBLE = document.getElementById('bubble'); Plotly.restyle(BUBBLE, 'x', [otuIDs]); Plotly.restyle(BUBBLE, 'y', [sampleValues]); Plotly.restyle(BUBBLE, 'text', [labels]); Plotly.restyle(BUBBLE, 'marker.size', [sampleValues]); Plotly.restyle(BUBBLE, 'marker.color', [otuIDs]); // Update the Pie Chart with the new data // Use slice to select only the top 10 OTUs for the pie chart var PIE = document.getElementById('pie'); var pieUpdate = { values: [sampleValues.slice(0, 10)], labels: [otuIDs.slice(0, 10)], hovertext: [labels.slice(0, 10)], hoverinfo: 'hovertext', type: 'pie' }; Plotly.restyle(PIE, pieUpdate); } function getData(sample, callback) { // Use a request to grab the json data needed for all charts Plotly.d3.json(`/samples/${sample}`, function(error, sampleData) { if (error) return console.warn(error); Plotly.d3.json('/otu', function(error, otuData) { if (error) return console.warn(error); callback(sampleData, otuData); }); }); Plotly.d3.json(`/metadata/${sample}`, function(error, metaData) { if (error) return console.warn(error); updateMetaData(metaData); }) // BONUS - Build the Gauge Chart buildGauge(sample); } function getOptions() { // Grab a reference to the dropdown select element var selector = document.getElementById('selDataset'); // Use the list of sample names to populate the select options Plotly.d3.json('/names', function(error, sampleNames) { for (var i = 0; i < sampleNames.length; i++) { var currentOption = document.createElement('option'); currentOption.text = sampleNames[i]; currentOption.value = sampleNames[i] selector.appendChild(currentOption); } getData(sampleNames[0], buildCharts); }) } function optionChanged(newSample) { // Fetch new data each time a new sample is selected getData(newSample, updateCharts); } function init() { getOptions(); } // Initialize the dashboard init();
1.78125
2
src/main/resources/static/js/sensor.js
adriancierpka/ChillImport-1
0
1207
/*global addToLog, closeModal*/ function initSensor() { var data = [ { id : "", text : "" }, { id : "application/pdf", text : "application/pdf" }, { id : "application/json", text : "application/json" }, { id : "text", text : "text" } ]; $("#senEncTypes").select2({ data : data, placeholder : "Choose an encoding type", width : "style", dropdownAutoWidth : true }); } function createSensor() { var name = $("#senname").val(); var desc = $("#sendescription").val(); var encType = $("#senEncTypes").val(); if (!encType || encType === "") { alert("Choose an encryption type."); return false; } var meta = $("#senmeta").val(); var mySensor = { name : name, description : desc, encoding_TYPE : encType, metadata : meta }; var url = document.getElementById("serverurlbox").innerText; var mydata = { entity : mySensor, string : url }; $ .ajax({ type : "POST", url : "sensor/create", datatype : "json", contentType : "application/json", data : JSON.stringify(mydata), error : function(e) { $ .notify( { message : "Sensor could not be created, check the Log for errors" }, { allow_dismiss : true, type : "danger", placement : { from : "top", align : "left" }, animate : { enter : "animated fadeInDown", exit : "animated fadeOutUp" }, z_index : 9000 }); addToLog(e.responseText); }, success : function(e) { $.notify({ message : "Sensor created." }, { allow_dismiss : true, type : "info", placement : { from : "top", align : "left" }, animate : { enter : "animated fadeInDown", exit : "animated fadeOutUp" }, z_index : 9000 }); addToLog("Sensor created."); closeModal("dsdialog"); var text = e.name + " (" + e.frostId + ")"; var option = new Option(text, text, null, null); option.setAttribute("data-value", JSON .stringify(e, null, 4)); var sensors = $("#streamsensors"); sensors.append(option).trigger("change"); sensors.val(text); } }); }
1.351563
1
client/src/components/MarketValue.js
AnshuJalan/newton
2
1215
import React, { Component } from 'react'; import getWeb3 from '../getWeb3'; import UsingPriceFeed from '../contracts/UsingPriceFeed.json'; class MarketValue extends Component { state = { web3: null, eth: 235.25, ethColor: '', ethSign: '', dai: 1.0025, daiSign: '', daiColor: '', ethdai: 235.14, ethdaiSign: '', ethDiff: 1.2, ethdaiColor: '', daiDiff: 0.005, ethdaiDiff: 1.3, }; componentDidMount = async () => { const web3 = this.props.web3; const networkId = this.props.networkId; const address = UsingPriceFeed.networks[networkId].address; const instance = new web3.eth.Contract(UsingPriceFeed.abi, address); this.setState({ web3, contract: instance }, () => { this.updateData(); setInterval(this.updateData, 30000); }); }; updateData = async () => { const ethList = await this.state.contract.methods.getEthRange().call(); let eth = ethList[1] / 1000000; let ethDiff = ((ethList[1] - ethList[0]) / 1000000).toFixed(1); let ethSign; let ethColor; if (ethDiff >= 0) { ethSign = 'fa fa-caret-up'; ethColor = 'text-success'; } else { ethSign = 'fa fa-caret-down'; ethColor = 'text-danger'; } ethDiff = Math.abs(ethDiff); const daiList = await this.state.contract.methods.getDaiRange().call(); let dai = daiList[1] / 1000000; let daiDiff = ((daiList[1] - daiList[0]) / 1000000).toFixed(6); let daiSign; let daiColor; if (daiDiff >= 0) { daiSign = 'fa fa-caret-up'; daiColor = 'text-success'; } else { daiSign = 'fa fa-caret-down'; daiColor = 'text-danger'; } daiDiff = Math.abs(daiDiff); let ethdai = ethList[1] / daiList[1]; let ethdaiDiff = (ethdai - ethList[0] / daiList[0]).toFixed(6); let ethdaiSign; let ethdaiColor; if (ethdaiDiff >= 0) { ethdaiSign = 'fa fa-caret-up'; ethdaiColor = 'text-success'; } else { ethdaiSign = 'fa fa-caret-down'; ethdaiColor = 'text-danger'; } ethdaiDiff = Math.abs(ethdaiDiff); eth = eth.toFixed(2); dai = dai.toFixed(3); ethdai = ethdai.toFixed(2); this.setState({ eth, dai, ethDiff, daiDiff, ethdai, daiSign, ethSign, ethdaiSign, ethColor, daiColor, ethdaiColor, }); }; render() { return ( <div className='sec-bg market-val'> <table className='text-center text-white' style={{ width: '100%' }}> <tbody> <tr> <td> <img className='mr-2' src={require('../images/eth.png')} width='36' /> <span className='font-weight-bold ml-2 text-secondary'> ETH/USD </span> </td> <td> <span>$ {this.state.eth}</span> <span className={'ml-2 ' + this.state.ethColor}> <i className={this.state.ethSign}></i> {this.state.ethDiff} </span> </td> </tr> <tr> <td> <img className='mr-2' src={require('../images/dai.png')} width='36' /> <span className='font-weight-bold ml-2 text-secondary'> DAI/USD </span> </td> <td> <span>$ {this.state.dai}</span> <span className={'ml-2 ' + this.state.daiColor}> <i className={this.state.daiSign}></i> {this.state.daiDiff} </span> </td> </tr> <tr> <td> <img className='mr-2' src={require('../images/ethdai.png')} width='36' /> <span className='font-weight-bold ml-2 text-secondary'> ETH/DAI </span> </td> <td> <span>DAI {this.state.ethdai}</span> <span className={'ml-2 ' + this.state.ethdaiColor}> <i className={this.state.ethdaiSign}></i>{' '} {this.state.ethdaiDiff} </span> </td> </tr> </tbody> </table> </div> ); } } export default MarketValue;
1.898438
2
appcms/areanet/PIM-UI/default/assets/scripts/services/token.service.js
appcms/server
3
1223
(function() { 'use strict'; angular .module('app') .factory('TokenService', TokenService); function TokenService(localStorageService, $http){ return{ delete: doDelete, add: add, generate: generate, list: list } ////////////////////////////////////////////////////// function list(id){ return $http({ method: 'POST', url: '/system/do', data: { method: 'listTokens' } }); } function doDelete(id){ return $http({ method: 'POST', url: '/system/do', data: { method: 'deleteToken', id: id } }); } function add(referrer, token, user){ return $http({ method: 'POST', url: '/system/do', data: { method: 'addToken', referrer: referrer, user: user, token: token } }); } function generate(){ return $http({ method: 'POST', url: '/system/do', data: { method: 'generateToken' } }); } } })();
1.125
1
dist/js/app.js
vipulism/gulphtml
0
1231
"use strict"; function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } console.log('5ppp5'); var p = ["lo0", "kjh"]; p = _toConsumableArray(p).concat(["ko"]); hukoo(); //# sourceMappingURL=data:application/json;charset=utf8;base64,<KEY>
1.851563
2
browser/store.js
snickers495/foodie
0
1239
import { createStore, applyMiddleware } from 'redux'; import loggerMiddleware from 'redux-logger'; import thunkMiddleware from 'redux-thunk'; import { composeWithDevTools } from 'redux-devtools-extension'; import rootReducer from './redux'; export default createStore( rootReducer, composeWithDevTools(applyMiddleware(thunkMiddleware, loggerMiddleware)) );
0.8125
1
src/promise/tests/cli/assets/aplus.js
maniekmankowski/yui3
1,958
1247
YUI.add('aplus-tests', function(Y) { var Assert = Y.Assert; var adapter = { fulfilled: function (value) { return new Y.Promise(function (fulfill) { fulfill(value); }); }, rejected: function (value) { return new Y.Promise(function (fulfill, reject) { reject(value); }); }, pending: function () { var fulfill, reject, promise; promise = new Y.Promise(function (f, r) { fulfill = f; reject = r; }); return { promise: promise, fulfill: fulfill, reject: reject }; } }; var promisesAplusTests = require("promises-aplus-tests"); var suite = new Y.Test.Suite('Promise Aplus'); suite.add(new Y.Test.Case({ name: "Promise Aplus", 'should run the full test suite': function() { var test = this; promisesAplusTests(adapter, {reporter: 'dot'}, function (err) { test.resume(function() { Assert.isNull(err, 'All promises tests should pass'); }); }); test.wait(9999999); } })); Y.Test.Runner.add(suite); });
1.320313
1
src/commands/Music/LyricsCommand.js
DaanGamesDG/discordjs-music-bot
0
1255
const BaseCommand = require('../../utils/structures/BaseCommand'); const lryicsfinder = require('lyrics-finder'); const { MessageEmbed } = require('discord.js'); module.exports = class LyricsCommand extends BaseCommand { constructor() { super('lyrics', 'Music', ['lyr', 'l'], 'Gives the lyrics the song playing in the guild'); } async run(client, message, args) { const queue = client.queue.get(message.guild.id); if (!queue || !queue.songs[0]) return message.channel.send(`> ${client.emojis.cache.find(m => m.name === 'redtick').toString()} This server doesnt have a queue!`); let songTitle = queue.songs[0].title .toLowerCase() .replace('(official video)', '') .replace('lyrics', '') .replace('(video)', '') await lryicsfinder(songTitle, '').then(lyrics => { if (!lyrics) return message.channel.send(`> 📑 No lyrics for **${queue.songs[0].title}** found!`); const embed = new MessageEmbed() .setAuthor(`Lyrics for ${queue.songs[0].title}`, queue.playing ? 'https://emoji.gg/assets/emoji/6935_Plak_Emoji.gif' : 'https://imgur.com/Y9XRC6N.png') .setDescription(lyrics) .setColor(message.member.displayHexColor || 'BLUE') if (embed.description.length >= 2048) embed.description = `${embed.description.substr(0, 2045)}...`; return message.channel.send(embed).catch(console.error); }) } }
1.835938
2
src/components/ResultsTable.js
jonnyi/leaderboard-app
1
1263
import React from 'react'; import RowSelector from './RowSelector'; import ResultsRow from './ResultsRow'; class ResultsTable extends React.PureComponent { constructor(props) { super(props); this.sortBy = this.sortBy.bind(this); this.state = { tableSortedBy: 'recent' }; } componentDidMount() { this.props.updateTableData('recent'); } sortBy(sortByValue) { this.props.updateLoadingFlag(true); this.props.updateTableData(sortByValue); this.props.updateTitle( sortByValue == 'recent' ? 'Top scores in the last 30 days!' : 'Top scores of all time!' ); this.setState({ tableSortedBy: sortByValue }); } render() { const { updateRowCount, rowCount, scoreData, loadingFlag } = this.props; const { tableSortedBy } = this.state; const scoreDataTrimmed = scoreData.slice(0, rowCount); const isSortedByRecent = tableSortedBy == 'recent' ? true : false; if (loadingFlag) { return <h2>Loading...</h2>; } else { return ( <div id="results-table"> {loadingFlag} <RowSelector updateRowCount={updateRowCount} rowCount={rowCount} /> <div className="table-responsive"> <table className="table table-sm table-striped"> <thead> <tr> <th>#</th> <th>Name</th> <th id="recent-selector" className={isSortedByRecent ? 'selected thCta' : 'thCta'} onClick={() => this.sortBy('recent')} > Last 30 Days </th> <th id="alltime-selector" className={!isSortedByRecent ? 'selected thCta' : 'thCta'} onClick={() => this.sortBy('alltime')} > All time score </th> </tr> </thead> <tbody> {scoreDataTrimmed.map((row, i) => ( <ResultsRow key={i} rowData={row} rowNumber={i + 1} /> ))} </tbody> </table> </div> </div> ); } } } export default ResultsTable;
2.015625
2
src/renderer/components/Content/index.js
rubenandre/simulator
66
1271
import React from 'react' import styled from 'styled-components' import Exams from './Main/Exams' import History from './Main/History' import Sessions from './Main/Sessions' import Cover from './Cover' import Exam from './Exam' import Review from './Review' import Options from './Options' import AddRemoteExam from './AddRemoteExam' const ContentStyles = styled.div` display: grid; justify-items: center; align-items: center; padding: 2rem; padding-right: ${props => (props.open ? '28rem' : '7rem')}; transition: 0.3s; ` export default class Content extends React.Component { renderContent = () => { const p = this.props if (p.mode === 0) { if (p.mainMode === 0) { return ( <Exams exams={p.exams} setIndexExam={p.setIndexExam} initExam={p.initExam} setConfirmDeleteExam={p.setConfirmDeleteExam} /> ) } else if (p.mainMode === 1) { return ( <History history={p.history} setIndexHistory={p.setIndexHistory} setConfirmReviewExam={p.setConfirmReviewExam} setConfirmDeleteHistory={p.setConfirmDeleteHistory} /> ) } else if (p.mainMode === 2) { return ( <Sessions sessions={p.sessions} setIndexSession={p.setIndexSession} setConfirmStartSession={p.setConfirmStartSession} setConfirmDeleteSession={p.setConfirmDeleteSession} /> ) } else if (p.mainMode === 3) { return <Options options={p.options} /> } else if (p.mainMode === 4) { return <AddRemoteExam loadRemoteExam={p.loadRemoteExam} /> } } else if (p.mode === 1) { return <Cover cover={p.exam.cover} /> } else if (p.mode === 2) { return ( <Exam explanationRef={p.explanationRef} explanation={p.explanation} examMode={p.examMode} exam={p.exam} question={p.question} answers={p.answers} fillIns={p.fillIns} orders={p.orders} intervals={p.intervals} marked={p.marked} confirmPauseTimer={p.confirmPauseTimer} onBookmarkQuestion={p.onBookmarkQuestion} onMultipleChoice={p.onMultipleChoice} onMultipleAnswer={p.onMultipleAnswer} onFillIn={p.onFillIn} onListOrder={p.onListOrder} setIntervals={p.setIntervals} /> ) } else if (p.mode === 3) { return ( <Review exam={p.exam} reviewMode={p.reviewMode} reviewType={p.reviewType} reviewQuestion={p.reviewQuestion} report={p.report} /> ) } else { return null } } render() { const { props: { open } } = this return <ContentStyles open={open}>{this.renderContent()}</ContentStyles> } }
1.34375
1
src/platforms/mp-xhs/runtime/wrapper/util.js
Songllgons/uni-app
0
1279
import { isFn, hasOwn } from 'uni-shared' export const isComponent2 = xhs.canIUse('component2') export const mocks = ['$id'] export function initSpecialMethods (mpInstance) { if (!mpInstance.$vm) { return } let path = mpInstance.is || mpInstance.route if (!path) { return } if (path.indexOf('/') === 0) { path = path.substr(1) } const specialMethods = xhs.specialMethods && xhs.specialMethods[path] if (specialMethods) { specialMethods.forEach(method => { if (isFn(mpInstance.$vm[method])) { mpInstance[method] = function (event) { if (hasOwn(event, 'markerId')) { event.detail = typeof event.detail === 'object' ? event.detail : {} event.detail.markerId = event.markerId } // TODO normalizeEvent mpInstance.$vm[method](event) } } }) } } export const handleWrap = function (mp, destory) { const vueId = mp.props.vueId const list = mp.props['data-event-list'].split(',') list.forEach(eventName => { const key = `${eventName}${vueId}` if (destory) { delete this[key] } else { // TODO remove handleRef this[key] = function () { mp.props[eventName].apply(this, arguments) } } }) }
1.398438
1
src/js_src/containers/about/test.js
ClinGen/python_react_programming_starter
1
1287
import assert from 'assert'; import React from 'react'; import { renderToString } from 'react-dom/server'; import Component from './index'; describe('About', () => { it('should be able to render to an HTML string', () => { let htmlString = renderToString(<Component />); assert.equal(typeof htmlString, 'string'); }); });
1.304688
1
src/events/guildUnavailable.js
Skario37/victini2.0
0
1295
module.exports = (client, guild) => {}
-0.091797
0
public/js/judge-cookie.js
hongxuepeng/ulzz
0
1303
function language() { $("#language-switch>li").click(function () { var lan = $.session.get('lan'); var type = $(this).attr("type"); if(lan != type){ $.session.set('lan',type); location.reload(); } }) } language();
0.570313
1
src/components/_globals.js
mfeyx/vue-enterprise-boilerplate
5
1311
// Globally register all base components for convenience, because they // will be used very frequently. Components are registered using the // PascalCased version of their file name. import Vue from 'vue' import upperFirst from 'lodash/upperFirst' import camelCase from 'lodash/camelCase' // https://webpack.js.org/guides/dependency-management/#require-context const requireComponent = require.context( // Look for files in the current directory '.', // Do not look in subdirectories false, // Only include "_base-" prefixed .vue files /_base-[\w-]+\.vue$/ ) // For each matching file name... requireComponent.keys().forEach((fileName) => { // Get the component config const componentConfig = requireComponent(fileName) // Get the PascalCase version of the component name const componentName = upperFirst( camelCase( fileName // Remove the "./_" from the beginning .replace(/^\.\/_/, '') // Remove the file extension from the end .replace(/\.\w+$/, '') ) ) // Globally register the component Vue.component(componentName, componentConfig.default || componentConfig) })
1.546875
2
src/styles/contactStyle.js
agielasyari1/personal-website-react
59
1319
import styled from "styled-components"; export const ContactWrapper = styled.div` margin: 10% auto; @media (max-width: 700px) { margin: 15% auto; } `; export const ContactHeader = styled.h1` text-align: CENTER; color: #7fa1e8; margin-bottom: 5%; font-weight: 300; `; export const ContactDetails = styled.div` display: flex; align-items: baseline; justify-content: center; @media (max-width: 700px) { flex-direction: column; align-items: center; } `; export const ContactBox = styled.div` display: flex; align-items: center; flex-direction: column; font-weight: 300; @media (max-width: 700px) { flex-direction: column; } `;
0.769531
1
packages/material-ui-icons/src/RemoveDone.js
silver-snoopy/material-ui
8
1327
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M1.79 12l5.58 5.59L5.96 19 .37 13.41 1.79 12zm.45-7.78L12.9 14.89l-1.28 1.28L7.44 12l-1.41 1.41L11.62 19l2.69-2.69 4.89 4.89 1.41-1.41L3.65 2.81 2.24 4.22zm14.9 9.27L23.62 7 22.2 5.59l-6.48 6.48 1.42 1.42zM17.96 7l-1.41-1.41-3.65 3.66 1.41 1.41L17.96 7z" /> , 'RemoveDone');
0.546875
1
community-edition/getColumnState/updateWithShowingColumns.js
fattynoparents/reactdatagrid
0
1335
/** * Copyright (c) INOVUA SOFTWARE TECHNOLOGIES. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import assign from 'object-assign'; import getShowingColumns from '../getShowingColumns'; export default (columns, props, state, context) => { context = context || {}; const showingColumnsMap = assign( context.showingColumnsMap, getShowingColumns(columns, state.columnsMap) ); const showingKeys = Object.keys(showingColumnsMap); if (showingKeys.length) { const showingColumn = showingColumnsMap[showingKeys[0]]; const duration = showingColumn.showTransitionDuration !== undefined ? showingColumn.showTransitionDuration : showingColumn.visibilityTransitionDuration; columns = columns.map(c => { const id = c.id || c.name; c.inTransition = !!context.inTransition; if (c.inTransition) { c.inShowTransition = true; } if (!c.inTransition && showingColumnsMap[id]) { c.width = 0; c.minWidth = 0; c.maxWidth = 0; } c.showTransitionDuration = duration; c.visibilityTransitionDuration = duration; return c; }); } return columns; };
1.445313
1
public/vue/vue-app.js
markgeek95/Dashpayroll
0
1343
var vue_app = new Vue({ el: '#vue-app', data: { errors: [], // for viewing of errors password_user: 'password', employee_list: [], // for philhealth modal range_value: '', // for philhealth maintenace module addition amount_value: '', // for philhealth maintenace module addition rate_value: '', // for philhealth maintenace module addition employer_value: '', // for philhealth maintenace module addition employee_value: '', // for philhealth maintenace module addition ec_value: '', // for sss maintenace module edit percentage_value: '', // for sss maintenace module edit philhealth_id: '', // for philhealth maintenace module addition sss_id: '', // for philhealth maintenace module addition withholding_tax_id: '', // for update of witholding tax frequency_id: '', // for update of witholding tax frequency: {}, // holder of frequency table witholding_tax_delete_id: '', annual_tax_id: '', fixed_rate_value: '', tax_rate_value: '', global_delete_id: '', global_delete_name: '', amount_money: '324', leave_array: [], holiday_types_array: {}, shifts_array: {}, // store shifts array here bank: {}, // for updating banks ot_nightdifferential: {}, // OT statutory_array: {}, // for editing statutory }, methods: { // toggle password on user password_toggle: function () { if (this.password_user == 'password'){ this.password_user = '<PASSWORD>'; } else{ this.password_user = 'password'; } }, full_loader: function() { $('#loader-modal').modal({ backdrop: 'static', keyboard: false }); }, decrypt_encrypt: function (event) { var input = $(event.target).closest('div').find('input.password_holder'); var type = $(input).attr('type'); if (type == 'text'){ $(input).attr('type','password'); } else{ $(input).attr('type','text'); } }, philhealth_get_all_employees: function ($element) { var root_element = this; // the parent element request = $.ajax({ url: baseUrl+'/get_all_employees', type: "post", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); root_element.employee_list = response; }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#'+$element+' .loaderRefresh').fadeOut('fast'); }); }, philhealth_maintenance: function () { $('#add_philheatlh_modal').find('.loaderRefresh').fadeIn(0); $('#add_philheatlh_modal').modal(); this.philhealth_get_all_employees('add_philheatlh_modal'); }, philhealth_maintenance_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#add_philheatlh_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/philhealth', type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Philhealth Maintenance Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#add_philheatlh_modal .loaderRefresh').fadeOut('fast'); }); }, philhealth_maintenance_edit: function (event, $id) { var root_element = this; // the parent element $('#edit_philheatlh_modal').find('.loaderRefresh').fadeIn(0); $('#edit_philheatlh_modal').modal(); request = $.ajax({ url: baseUrl+'/philhealth/'+$id+'/edit', type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); root_element.philhealth_id = response.id; root_element.range_value = response.ranges; root_element.amount_value = response.amount; root_element.rate_value = response.rate; root_element.employer_value = response.employer; root_element.employee_value = response.employee_id; root_element.philhealth_get_all_employees('edit_philheatlh_modal'); root_element.check_employee_id(); }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ // $('#edit_philheatlh_modal').find('.loaderRefresh').fadeOut('fast'); }); }, check_employee_id: function($employee_id) { return ($employee_id == this.employee_value)? true : false; }, philhealth_maintenance_edit_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#edit_philheatlh_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/philhealth/'+root_element.philhealth_id, type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Philhealth Maintenance Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#edit_philheatlh_modal .loaderRefresh').fadeOut('fast'); }); }, philhealth_maintenance_delete: function ($id) { var ans = confirm('Do you really want to delete this data?'); if (ans) { this.full_loader(); // show window loader var root_element = this; // the parent element request = $.ajax({ url: baseUrl+'/philhealth_delete/'+$id, type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, }); request.done(function (response, textStatus, jqXHR) { console.log(response); toaster('info', 'Philhealth Maintenance Has Been Deleted.'); location.reload(); }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ // $('#edit_philheatlh_modal .loaderRefresh').fadeOut('fast'); }); } }, // SSS MODULE sss_add: function() { $('#sss_add_modal').find('.loaderRefresh').fadeIn(0); $('#sss_add_modal').modal(); this.philhealth_get_all_employees('sss_add_modal'); }, sss_submit_form: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#sss_add_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/sss', type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'SSS Maintenance Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#sss_add_modal .loaderRefresh').fadeOut('fast'); }); }, sss_maintenance_edit: function (event, $id) { var root_element = this; // the parent element $('#sss_edit_modal').find('.loaderRefresh').fadeIn(0); $('#sss_edit_modal').modal(); request = $.ajax({ url: baseUrl+'/sss/'+$id+'/edit', type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); root_element.sss_id = response.id; root_element.range_value = response.ranges; root_element.employer_value = response.employer; root_element.employee_value = response.employee_id; root_element.ec_value = response.ec; root_element.philhealth_get_all_employees('sss_edit_modal'); // root_element.check_employee_id(); }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#sss_edit_modal').find('.loaderRefresh').fadeOut('fast'); }); }, sss_edit_submit_form: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#sss_edit_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/sss/'+root_element.sss_id, type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'SSS Maintenance Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#sss_edit_modal .loaderRefresh').fadeOut('fast'); }); }, sss_maintenance_delete: function ($id) { var ans = confirm('Do you really want to delete this data?'); if (ans) { this.full_loader(); // show window loader var root_element = this; // the parent element request = $.ajax({ url: baseUrl+'/sss_delete/'+$id, type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, }); request.done(function (response, textStatus, jqXHR) { console.log(response); toaster('info', 'SSS Maintenance Has Been Deleted.'); location.reload(); }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ // $('#edit_philheatlh_modal .loaderRefresh').fadeOut('fast'); }); } }, get_frequency: function () { var root_element = this; // the parent element request = $.ajax({ url: baseUrl+'/get_frequency', type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { root_element.frequency = response; }); }, withholding_tax_new: function() { var root_element = this; // the parent element $('#withholding_tax_modal').find('.loaderRefresh').fadeIn(0); $('#withholding_tax_modal').modal(); request = $.ajax({ url: baseUrl+'/get_frequency', type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { root_element.frequency = response; }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#withholding_tax_modal .loaderRefresh').fadeOut('fast'); }); }, witholding_tax_submit: function(event){ var root_element = this; // the parent element var data = $(event.target).serialize(); $('#withholding_tax_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/withholding_tax', type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Withholding Tax Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#withholding_tax_modal .loaderRefresh').fadeOut('fast'); }); }, witholding_tax_edit: function (event, $id) { var root_element = this; // the parent element var data = $(event.target).serialize(); this.get_frequency(); $('#withholding_tax_edit').find('.loaderRefresh').fadeIn(0); $('#withholding_tax_edit').modal(); request = $.ajax({ url: baseUrl+'/withholding_tax/'+$id+'/edit', type: "get", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); root_element.withholding_tax_id = response.id; root_element.frequency_id = response.frequency_id; root_element.range_value = response.ranges; root_element.percentage_value = response.percentage; root_element.amount_value = response.amount; }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#withholding_tax_edit .loaderRefresh').fadeOut('fast'); }); }, check_frequency_id: function($frequency_id) { return ($frequency_id == this.frequency_id)? true : false; }, witholding_tax_edit_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#withholding_tax_edit').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/withholding_tax/'+root_element.withholding_tax_id, type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Withholding Tax Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#withholding_tax_edit').find('.loaderRefresh').fadeOut('fast'); }); }, witholding_tax_delete_modal: function ($id) { this.witholding_tax_delete_id = $id; $('#withholding_tax_delete').modal(); }, witholding_tax_delete: function () { var root_element = this; // the parent element $('#withholding_tax_delete').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/withholding_tax_delete/'+root_element.witholding_tax_delete_id, type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, }); request.done(function (response, textStatus, jqXHR) { console.log(response); toaster('info', response.info); location.reload(); }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#withholding_tax_delete').find('.loaderRefresh').fadeOut('fast'); }); }, // annual tax annual_tax_new: function () { $('#annualtax_new').modal(); }, annualtax_new_submit: function(event){ var root_element = this; // the parent element var data = $(event.target).serialize(); $('#annualtax_new').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/annual_tax', type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Annual Tax Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#annualtax_new').find('.loaderRefresh').fadeOut('fast'); }); }, annual_tax_edit: function ($id) { var root_element = this; // the parent element $('#annualtax_edit').find('.loaderRefresh').fadeIn(0); $('#annualtax_edit').modal(); request = $.ajax({ url: baseUrl+'/annual_tax/'+$id+'/edit', type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); root_element.annual_tax_id = response.id; root_element.range_value = response.ranges; root_element.fixed_rate_value = response.fixed_rate; root_element.tax_rate_value = response.tax_rate; }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#annualtax_edit .loaderRefresh').fadeOut('fast'); }); }, annualtax_edit_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#annualtax_edit').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/annual_tax/'+root_element.annual_tax_id, type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Annual Tax Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#annualtax_edit').find('.loaderRefresh').fadeOut('fast'); }); }, global_delete: function($id, $name) { this.global_delete_id = $id; this.global_delete_name = $name; $('#delete_modal').modal(); }, delete_yes: function () { var delName = this.global_delete_name; if (delName == 'annual_tax_delete') { this.annual_tax_delete(); }else if (delName == 'leave_delete') { this.leave_delete(); }else if (delName == 'bank_delete') { this.bank_delete(); }else if (delName == 'statutory_delete') { this.statutory_delete(); } }, annual_tax_delete: function (){ var root_element = this; // the parent element $('#delete_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/annual_tax_delete/'+root_element.global_delete_id, type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, }); request.done(function (response, textStatus, jqXHR) { console.log(response); toaster('info', 'Annual Tax Has Been Deleted.'); location.reload(); }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ }); }, /* leave tables */ leave_new_open: function () { $('#leave_new_modal').modal(); }, leave_new_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#leave_new_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/leave', type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Leave Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#leave_new_modal').find('.loaderRefresh').fadeOut('fast'); }); }, leave_edit: function ($id) { var root_element = this; // the parent element $('#leave_edit_modal').find('.loaderRefresh').fadeIn(0); $('#leave_edit_modal').modal(); request = $.ajax({ url: baseUrl+'/leave/'+$id+'/edit', type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); root_element.leave_array = response; console.log(root_element.leave_array); }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#leave_edit_modal .loaderRefresh').fadeOut('fast'); }); }, cash_convertible_check: function (status) { return (status == 'Y')? true : false; }, carry_over_check: function (status) { return (status == 'Y')? true : false; }, leave_edit_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#leave_edit_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/leave/'+root_element.leave_array.id, type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Leave Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#leave_edit_modal').find('.loaderRefresh').fadeOut('fast'); }); }, leave_delete: function (){ var root_element = this; // the parent element $('#delete_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/leave_delete/'+root_element.global_delete_id, type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, }); request.done(function (response, textStatus, jqXHR) { console.log(response); toaster('info', 'Leave Has Been Deleted.'); location.reload(); }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); }, /* holiday */ holiday_new: function () { var root_element = this; // the parent element $('#holiday_new_modal').modal(); $('#holiday_new_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/holiday_types', type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { root_element.holiday_types_array = response; }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#holiday_new_modal').find('.loaderRefresh').fadeOut('fast'); }); }, holiday_new_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#holiday_new_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/holiday', type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Leave Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#holiday_new_modal').find('.loaderRefresh').fadeOut('fast'); }); }, rest_day_new: function () { var root_element = this; // the parent element $('#rest_day_new_modal').modal(); $('#rest_day_new_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/shifts', type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { root_element.shifts_array = response; }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#rest_day_new_modal').find('.loaderRefresh').fadeOut('fast'); }); }, rest_day_new_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#rest_day_new_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/rest_day', type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Leave Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#rest_day_new_modal').find('.loaderRefresh').fadeOut('fast'); }); }, // for editing of banks banks_edit: function ($id) { var root_element = this; // the parent element $('#banks_edit_modal').modal(); var data = $(event.target).serialize(); $('#banks_edit_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/banks/'+$id+'/edit', type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); root_element.bank = response; }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#banks_edit_modal').find('.loaderRefresh').fadeOut('fast'); }); }, bank_edit_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#banks_edit_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/banks/'+root_element.bank.id, type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Leave Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#banks_edit_modal').find('.loaderRefresh').fadeOut('fast'); }); }, bank_delete: function (){ var root_element = this; // the parent element $('#delete_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/bank_delete/'+root_element.global_delete_id, type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, }); request.done(function (response, textStatus, jqXHR) { console.log(response); toaster('info', 'Bank Has Been Deleted.'); location.reload(); }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); }, departments_new_open_modal: function () { $('#department_modal').modal(); }, department_new_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#department_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/departments', type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Department Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#department_modal').find('.loaderRefresh').fadeOut('fast'); }); }, position_new_open_modal: function () { $('#position_modal').modal(); }, position_new_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#position_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/positions', type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Position Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#position_modal').find('.loaderRefresh').fadeOut('fast'); }); }, cost_center_new_open_modal: function () { $('#cost_center_modal').modal(); }, cost_center_new_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#cost_center_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/cost_center', type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Cost Center Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#cost_center_modal').find('.loaderRefresh').fadeOut('fast'); }); }, open_employee_status_new_modal: function () { $('#employee_status_new_modal').modal(); }, employee_status_new_submit: function () { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#employee_status_new_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/employee_status', type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Cost Center Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#employee_status_new_modal').find('.loaderRefresh').fadeOut('fast'); }); }, open_night_differential_modal: function () { $('#overtime_nightdifferential_new_modal').modal(); }, overtime_nightdifferential_new_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#overtime_nightdifferential_new_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/overtime_nightdifferential', type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Overtime Night Differential Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#overtime_nightdifferential_new_modal').find('.loaderRefresh').fadeOut('fast'); }); }, overtime_nightdifferential_edit: function ($id) { var root_element = this; // the parent element $('#overtime_nightdifferential_edit_modal').modal(); var data = $(event.target).serialize(); $('#overtime_nightdifferential_edit_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/overtime_nightdifferential/'+$id+'/edit', type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); root_element.ot_nightdifferential = response; }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#overtime_nightdifferential_edit_modal').find('.loaderRefresh').fadeOut('fast'); }); }, overtime_nightdifferential_edit_submit: function (event) { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#overtime_nightdifferential_edit_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/overtime_nightdifferential/'+root_element.ot_nightdifferential.id, type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Overtime Night Differential Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#overtime_nightdifferential_edit_modal').find('.loaderRefresh').fadeOut('fast'); }); }, statutory_add_modal: function () { var root_element = this; // the parent element $('#statutorydeduction_add').modal(); $('#statutorydeduction_add').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/get_frequency', type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); root_element.frequency = response; }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#statutorydeduction_add').find('.loaderRefresh').fadeOut('fast'); }); }, statutory_deduction_submit: function () { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#statutorydeduction_add').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/statutory_deduction_schedule', type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Statutory Deduction Schedule Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#statutorydeduction_add').find('.loaderRefresh').fadeOut('fast'); }); }, statutory_edit: function ($id) { var root_element = this; // the parent element $('#statutorydeduction_edit').modal(); $('#statutorydeduction_edit').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/statutory_deduction_schedule/'+$id+'/edit', type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); root_element.statutory_array = response; }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ root_element.get_frequency(); // get all frequency $('#statutorydeduction_edit').find('.loaderRefresh').fadeOut('fast'); }); }, deduction_count_if: function ($i) { return ($i == this.statutory_array.deduction_count)? true : false; }, days_deduction_if: function ($i) { return ($i == this.statutory_array.days_of_deduction)? true : false; }, frequency_select: function ($id) { return ($id == this.statutory_array.frequency_id)? true : false; }, statutory_edit_submit: function () { var root_element = this; // the parent element var data = $(event.target).serialize(); $('#statutorydeduction_edit').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/statutory_deduction_schedule/'+root_element.statutory_array.id, type: "post", data: data, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, dataType: 'json' }); request.done(function (response, textStatus, jqXHR) { console.log(response); if ($.isEmptyObject(response.errors)) { toaster('success', response.success); location.reload(); }else{ toaster('error', 'Statutory Deduction Schedule Not Saved.'); root_element.errors = response.errors; } }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); request.always(function(){ $('#statutorydeduction_edit').find('.loaderRefresh').fadeOut('fast'); }); }, statutory_delete: function (){ var root_element = this; // the parent element $('#delete_modal').find('.loaderRefresh').fadeIn(0); request = $.ajax({ url: baseUrl+'/statutory_delete/'+root_element.global_delete_id, type: "get", headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, }); request.done(function (response, textStatus, jqXHR) { console.log(response); toaster('info', 'Statutory Deduction Schedule Been Deleted.'); location.reload(); }); request.fail(function (jqXHR, textStatus, errorThrown){ console.log("The following error occured: "+ jqXHR, textStatus, errorThrown); }); }, }, // end of method computed: { }, filters: { textuppercase: function (value){ if (!value) return ''; return value.toString().toUpperCase(); }, formatMoney: function (n, c, d, t) { var c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }, } })
1.039063
1
overlays/holo-nixpkgs/hpos-holochain-api/src/utils.js
pjkundert/holo-nixpkgs
0
1351
const tmp = require('tmp') const request = require('request') const fs = require('fs') // Download from url to tmp file // return tmp file path const downloadFile = async (downloadUrl) => { console.log('Downloading url: ', downloadUrl) const fileName = tmp.tmpNameSync() const file = fs.createWriteStream(fileName) // Clean up url const urlObj = new URL(downloadUrl) urlObj.protocol = 'https' downloadUrl = urlObj.toString() return new Promise((resolve, reject) => { request({ uri: downloadUrl }) .pipe(file) .on('finish', () => { // console.log(`Downloaded file from ${downloadUrl} to ${fileName}`); resolve(fileName) }) .on('error', (error) => { reject(error) }) }) } const parsePreferences = (p, key) => { const mtbi = typeof p.max_time_before_invoice === 'string' ? JSON.parse(p.max_time_before_invoice) : p.max_time_before_invoice return { max_fuel_before_invoice: toInt(p.max_fuel_before_invoice), max_time_before_invoice: [toInt(mtbi[0]), toInt(mtbi[1])], price_compute: toInt(p.price_compute), price_storage: toInt(p.price_storage), price_bandwidth: toInt(p.price_bandwidth), provider_pubkey: key } } const formatBytesByUnit = (bytes, decimals = 2) => { if (bytes === 0) return { size: 0, unit: 'Bytes' } const units = ['Bytes', 'KB', 'MB', 'GB'] const dm = decimals < 0 ? 0 : decimals const i = Math.floor(Math.log(bytes) / Math.log(1024)) return { size: parseFloat((bytes / Math.pow(1024, i)).toFixed(dm)), unit: units[i] } } const toInt = i => { if (typeof i === 'string') return parseInt(i) else return i } const isusageTimeInterval = value => { if (value === null) return false const keys = Object.keys(value) return keys.includes('duration_unit') && keys.includes('amount') } module.exports = { parsePreferences, formatBytesByUnit, downloadFile, isusageTimeInterval }
1.914063
2
samples/core/com/zoho/crm/api/sample/threading/multi_thread.js
zoho/zohocrm-typescript-sdk-2.0
0
1359
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const user_signature_1 = require("@zohocrm/typescript-sdk-2.0/routes/user_signature"); const sdk_config_builder_1 = require("@zohocrm/typescript-sdk-2.0/routes/sdk_config_builder"); const file_store_1 = require("@zohocrm/typescript-sdk-2.0/models/authenticator/store/file_store"); const logger_1 = require("@zohocrm/typescript-sdk-2.0/routes/logger/logger"); const log_builder_1 = require("@zohocrm/typescript-sdk-2.0/routes/logger/log_builder"); const us_data_center_1 = require("@zohocrm/typescript-sdk-2.0/routes/dc/us_data_center"); const oauth_builder_1 = require("@zohocrm/typescript-sdk-2.0/models/authenticator/oauth_builder"); const initialize_builder_1 = require("@zohocrm/typescript-sdk-2.0/routes/initialize_builder"); const record_operations_1 = require("@zohocrm/typescript-sdk-2.0/core/com/zoho/crm/api/record/record_operations"); const response_wrapper_1 = require("@zohocrm/typescript-sdk-2.0/core/com/zoho/crm/api/record/response_wrapper"); const parameter_map_1 = require("@zohocrm/typescript-sdk-2.0/routes/parameter_map"); const header_map_1 = require("@zohocrm/typescript-sdk-2.0/routes/header_map"); class SampleRecord { static async call() { /* * Create an instance of Logger Class that takes two parameters * level -> Level of the log messages to be logged. Can be configured by typing Levels "." and choose any level from the list displayed. * filePath -> Absolute file path, where messages need to be logged. */ let logger = new log_builder_1.LogBuilder() .level(logger_1.Levels.INFO) .filePath("/Users/username/Documents/final-logs.log") .build(); /* * Create an UserSignature instance that takes user Email as parameter */ let user1 = new user_signature_1.UserSignature("<EMAIL>"); /* * Configure the environment * which is of the pattern Domain.Environment * Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter * Available Environments: PRODUCTION(), DEVELOPER(), SANDBOX() */ let environment1 = us_data_center_1.USDataCenter.PRODUCTION(); /* * Create a Token instance * clientId -> OAuth client id. * clientSecret -> OAuth client secret. * grantToken -> OAuth Grant Token. * refreshToken -> OAuth Refresh Token token. * redirectURL -> OAuth Redirect URL. */ let token1 = new oauth_builder_1.OAuthBuilder() .clientId("clientId") .clientSecret("clientSecret") .refreshToken("<PASSWORD>Token") .redirectURL("redirectURL") .build(); /* * Create an instance of TokenStore. * host -> DataBase host name. Default "localhost" * databaseName -> DataBase name. Default "zohooauth" * userName -> DataBase user name. Default "root" * password -> DataBase password. Default "" * portNumber -> DataBase port number. Default "3306" * tableName -> DataBase table name. Default "oauthtoken" */ // let tokenstore: DBStore = new DBBuilder() // .host("hostName") // .databaseName("databaseName") // .userName("userName") // .portNumber(3306) // .tableName("tableName") // .password("password") // .build(); /* * Create an instance of FileStore that takes absolute file path as parameter */ let store = new file_store_1.FileStore("/Users/username/ts_sdk_tokens.txt"); /* * autoRefreshFields * if true - all the modules' fields will be auto-refreshed in the background, every hour. * if false - the fields will not be auto-refreshed in the background. The user can manually delete the file(s) or refresh the fields using methods from ModuleFieldsHandler(utils/util/module_fields_handler.js) * * pickListValidation * A boolean field that validates user input for a pick list field and allows or disallows the addition of a new value to the list. * True - the SDK validates the input. If the value does not exist in the pick list, the SDK throws an error. * False - the SDK does not validate the input and makes the API request with the user’s input to the pick list */ let sdkConfig = new sdk_config_builder_1.SDKConfigBuilder().pickListValidation(false).autoRefreshFields(true).build(); /* * The path containing the absolute directory path to store user specific JSON files containing module fields information. */ let resourcePath = "/Users/user_name/Documents/ts-app"; /* * Call the static initialize method of Initializer class that takes the following arguments * user -> UserSignature instance * environment -> Environment instance * token -> Token instance * store -> TokenStore instance * SDKConfig -> SDKConfig instance * resourcePath -> resourcePath * logger -> Logger instance */ try { (await new initialize_builder_1.InitializeBuilder()) .user(user1) .environment(environment1) .token(token1) .store(store) .SDKConfig(sdkConfig) .resourcePath(resourcePath) .logger(logger) .initialize(); } catch (error) { console.log(error); } await SampleRecord.getRecords("leads"); // await Initializer.removeUserConfiguration(user1, environment1); // let user2: UserSignature = new UserSignature("<EMAIL>"); // let environment2: Environment = EUDataCenter.SANDBOX(); // let token2: OAuthToken = new OAuthBuilder() // .clientId("clientId") // .clientSecret("clientSecret") // .grantToken("grantToken") // .refreshToken("refreshToken") // .redirectURL("https://www.zoho.com") // .build(); // let sdkConfig2: SDKConfig = new SDKConfigBuilder() // .pickListValidation(true) // .autoRefreshFields(true) // .build(); // (await new InitializeBuilder()) // .user(user2) // .environment(environment2) // .token(token2) // .SDKConfig(sdkConfig2) // // .requestProxy(requestProxy) // .switchUser(); // await SampleRecord.getRecords("Leads"); } static async getRecords(moduleAPIName) { try { let moduleAPIName = "Leads"; //Get instance of RecordOperations Class let recordOperations = new record_operations_1.RecordOperations(); let paramInstance = new parameter_map_1.ParameterMap(); await paramInstance.add(record_operations_1.GetRecordsParam.APPROVED, "both"); let headerInstance = new header_map_1.HeaderMap(); await headerInstance.add(record_operations_1.GetRecordsHeader.IF_MODIFIED_SINCE, new Date("2020-01-01T00:00:00+05:30")); //Call getRecords method that takes paramInstance, headerInstance and moduleAPIName as parameters let response = await recordOperations.getRecords(moduleAPIName, paramInstance, headerInstance); if (response != null) { //Get the status code from response console.log("Status Code: " + response.getStatusCode()); if ([204, 304].includes(response.getStatusCode())) { console.log(response.getStatusCode() == 204 ? "No Content" : "Not Modified"); return; } //Get the object from response let responseObject = response.getObject(); if (responseObject != null) { //Check if expected ResponseWrapper instance is received if (responseObject instanceof response_wrapper_1.ResponseWrapper) { //Get the array of obtained Record instances let records = responseObject.getData(); for (let record of records) { //Get the ID of each Record console.log("Record ID: " + record.getId()); //Get the createdBy User instance of each Record let createdBy = record.getCreatedBy(); //Check if createdBy is not null if (createdBy != null) { //Get the ID of the createdBy User console.log("Record Created By User-ID: " + createdBy.getId()); //Get the name of the createdBy User console.log("Record Created By User-Name: " + createdBy.getName()); //Get the Email of the createdBy User console.log("Record Created By User-Email: " + createdBy.getEmail()); } //Get the CreatedTime of each Record console.log("Record CreatedTime: " + record.getCreatedTime()); //Get the modifiedBy User instance of each Record let modifiedBy = record.getModifiedBy(); //Check if modifiedBy is not null if (modifiedBy != null) { //Get the ID of the modifiedBy User console.log("Record Modified By User-ID: " + modifiedBy.getId()); //Get the name of the modifiedBy User console.log("Record Modified By User-Name: " + modifiedBy.getName()); //Get the Email of the modifiedBy User console.log("Record Modified By User-Email: " + modifiedBy.getEmail()); } //Get the ModifiedTime of each Record console.log("Record ModifiedTime: " + record.getModifiedTime()); //Get the list of Tag instance each Record let tags = record.getTag(); //Check if tags is not null if (tags != null) { tags.forEach(tag => { //Get the Name of each Tag console.log("Record Tag Name: " + tag.getName()); //Get the Id of each Tag console.log("Record Tag ID: " + tag.getId()); }); } //To get particular field value console.log("Record Field Value: " + record.getKeyValue("Last_Name")); // FieldApiName console.log("Record KeyValues: "); let keyValues = record.getKeyValues(); let keyArray = Array.from(keyValues.keys()); for (let keyName of keyArray) { let value = keyValues.get(keyName); console.log(keyName + " : " + value); } } } } } } catch (error) { console.log(error); } } } SampleRecord.call(); //# sourceMappingURL=multi_thread.js.map
0.984375
1
dist/esm/internal/operators/take.js
openforis/rxjs
0
1367
import { Subscriber } from '../Subscriber'; import { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError'; import { EMPTY } from '../observable/empty'; export function take(count) { if (isNaN(count)) { throw new TypeError(`'count' is not a number`); } if (count < 0) { throw new ArgumentOutOfRangeError; } return (source) => (count === 0) ? EMPTY : source.lift(new TakeOperator(count)); } class TakeOperator { constructor(count) { this.count = count; } call(subscriber, source) { return source.subscribe(new TakeSubscriber(subscriber, this.count)); } } class TakeSubscriber extends Subscriber { constructor(destination, count) { super(destination); this.count = count; this._valueCount = 0; } _next(value) { const total = this.count; const count = ++this._valueCount; if (count <= total) { this.destination.next(value); if (count === total) { this.destination.complete(); this.unsubscribe(); } } } } //# sourceMappingURL=take.js.map
1.46875
1
public/js/script.js
Viva10/Otimetable
0
1375
window.onload = function(){ $("#accordion").accordion(); };
0.455078
0
misc/deprecated/deprecate-ext-react/src/ExtMenu.js
msgimanila/EXT-React-MSG
94
1383
import reactize from './reactize.js'; import EWCMenu from '@sencha/ext-web-components/src/ext-menu.component.js'; export default reactize(EWCMenu);
0.550781
1
src/services/patientService.js
lf-achyutpkl/patient-info-api
0
1391
import Patient from '../models/patient'; import Annotation from '../models/annotation'; import Tags from '../models/tags'; import AnnotationTags from '../models/annotationsTags'; import AnnotationBatches from '../models/annotationsBatches'; import Batches from '../models/batches'; import fs from 'fs'; import queue from 'async/queue'; export function createPatient(patient) { let annotations = patient.annotations; return new Patient({ firstName: patient.firstName, lastName: patient.lastName, gender: patient.gender, age: patient.age, address: patient.address }) .save() .then(patient => { patient.refresh(); for (let i = 0; i < annotations.length; i++) { new Annotation({ patientId: patient.id, imageName: annotations[i].imageName, annotationInfo: annotations[i].annotationInfo }) .save() .then(annotation => { annotation.refresh(); patient.images.push(annotation); }); } return patient; }); } export function getAllPatients(queryParams) { return Patient.fetchPage({ pageSize: queryParams.pageSize, page: queryParams.page, withRelated: ['annotations'] }); } /** * { * tags: [], * annotations: [ * { * imageName: ..., * annotationInfo: ..., * fileInfo: {originalName: 54_right.png} * } * ] * } * */ export async function saveBatchUpload() { // return; // REMOVE THIS, only to aviod accidently uploading file let files = []; let batchLimit = 350; let count = 0; let q = queue(async (file, cb) => { let [dummyPatientName, tag] = file.split('_'); tag = tag.split('.')[0]; let patient = await new Patient({ firstName: dummyPatientName }).fetch(); if (!patient) { patient = await new Patient({ firstName: dummyPatientName.trim(), lastName: dummyPatientName, gender: 'female' }) .save() .then(patient => { patient.refresh(); return patient; }); } let tagObj = await new Tags({ tagName: tag }).fetch(); if (!tagObj) { tagObj = await new Tags({ tagName: tag.trim() }) .save() .then(tag => { tag.refresh(); return tag; }); } let batchName = 'Kaggle Batch - ' + Math.ceil((count + 1) / batchLimit); let batchesObj = await new Batches({ batchName: batchName.trim() }).fetch(); if (!batchesObj) { batchesObj = await new Batches({ batchName: batchName, isCompleted: false }) .save() .then(branch => { branch.refresh(); return branch; }); } let annotation = await new Annotation({ patientId: patient.id, imageName: file, remarks: tag }) .save() .then(annotation => { annotation.refresh(); return annotation; }); await new AnnotationTags({ tagId: tagObj.id, annotationId: annotation.id }).save(); await new AnnotationBatches({ batchId: batchesObj.id, annotationId: annotation.id }).save(); // console.log('finished processing ', file); count++; cb(); }, 1); fs.readdirSync('./uploads').forEach(file => { if (file.includes('_')) { files.push(file); } }); q.push(files); q.drain = function() { // console.log('all images uploaded'); }; return; }
1.46875
1
tests/en/level1.js
nicompte/edtfy
9
1399
var should = require('chai').should(), edtfy = require('../../dist/edtfy'); describe('EN - Level 1', function () { beforeEach(function() { edtfy.locale('en'); }); describe('uncertain/approximate: the parser', function() { it('should parse year uncertain', function() { edtfy('1988?').should.equal('1988?'); }); it('should parse season uncertain', function() { edtfy('winter 1988?').should.equal('1988-24?'); edtfy('autumn 1988?').should.equal('1988-23?'); }); it('should parse month uncertain', function() { edtfy('03/1988?').should.equal('1988-03?'); edtfy('3/1988?').should.equal('1988-03?'); edtfy('march 1988?').should.equal('1988-03?'); edtfy('mar 1988?').should.equal('1988-03?'); }); it('should parse day uncertain', function() { edtfy('03/29/1988?').should.equal('1988-03-29?'); edtfy('03/29/1988 ?').should.equal('1988-03-29?'); edtfy('the 03/29/1988?').should.equal('1988-03-29?'); edtfy('3/29/1988?').should.equal('1988-03-29?'); edtfy('march 29 1988?').should.equal('1988-03-29?'); edtfy('march 29th 1988?').should.equal('1988-03-29?'); edtfy('mar 29 1988?').should.equal('1988-03-29?'); edtfy('june 2003 ?').should.equal('2003-06?'); }); it('should parse year approximate', function() { edtfy('around 1988').should.equal('1988~'); edtfy('about 1988').should.equal('1988~'); edtfy('circa 1988').should.equal('1988~'); edtfy('ca 1988').should.equal('1988~'); edtfy('c. 1988').should.equal('1988~'); edtfy('1988~').should.equal('1988~'); }); it('should parse season approximate', function() { edtfy('around winter 1988').should.equal('1988-24~'); edtfy('about autumn 1988').should.equal('1988-23~'); edtfy('autumn 1988~').should.equal('1988-23~'); }); it('should parse month approximate', function() { edtfy('around 03/1988').should.equal('1988-03~'); edtfy('around 3/1988').should.equal('1988-03~'); edtfy('around march 1988').should.equal('1988-03~'); edtfy('around mar 1988').should.equal('1988-03~'); edtfy('mar 1988~').should.equal('1988-03~'); }); it('should parse day approximate', function() { edtfy('about 03/29/1988').should.equal('1988-03-29~'); edtfy('about 03/29/1988').should.equal('1988-03-29~'); edtfy('about 3/29/1988').should.equal('1988-03-29~'); edtfy('about march the 29th 1988').should.equal('1988-03-29~'); edtfy('about march 29 1988').should.equal('1988-03-29~'); edtfy('abt mar 29 1988').should.equal('1988-03-29~'); edtfy('mar 29 1988~').should.equal('1988-03-29~'); }); it('should parse year approximate and uncertain', function() { edtfy('around 1988?').should.equal('1988?~'); edtfy('about 1988?').should.equal('1988?~'); edtfy('1988?~').should.equal('1988?~'); }); it('should parse season approximate and uncertain', function() { edtfy('around winter 1988?').should.equal('1988-24?~'); edtfy('around autumn 1988?').should.equal('1988-23?~'); edtfy('autumn 1988?~').should.equal('1988-23?~'); }); it('should parse month approximate and uncertain', function() { edtfy('around 03/1988?').should.equal('1988-03?~'); edtfy('around 3/1988?').should.equal('1988-03?~'); edtfy('around march 1988?').should.equal('1988-03?~'); edtfy('mar 1988?~').should.equal('1988-03?~'); }); it('should parse day approximate and uncertain', function() { edtfy('around 03/29/1988?').should.equal('1988-03-29?~'); edtfy('around the 03/29/1988?').should.equal('1988-03-29?~'); edtfy('around 3/29/1988?').should.equal('1988-03-29?~'); edtfy('around march 29 1988?').should.equal('1988-03-29?~'); edtfy('around march the 29 1988?').should.equal('1988-03-29?~'); edtfy('mar 29 1988?~').should.equal('1988-03-29?~'); }); }); describe('unspecified: the parser', function() { it('should parse year unspecified', function() { edtfy('198u').should.equal('198u'); edtfy('19uu').should.equal('19uu'); edtfy('198*').should.equal('198u'); edtfy('19**').should.equal('19uu'); }); it('should parse month unspecified', function() { edtfy('1u/1988').should.equal('1988-1u'); edtfy('uu/1988').should.equal('1988-uu'); edtfy('u/1988').should.equal('1988-uu'); edtfy('1*/1988').should.equal('1988-1u'); edtfy('**/1988').should.equal('1988-uu'); edtfy('*/1988').should.equal('1988-uu'); }); it('should parse day unspecified', function() { edtfy('01/1u/1988').should.equal('1988-01-1u'); edtfy('1/1u/1988').should.equal('1988-01-1u'); edtfy('01/uu/1988').should.equal('1988-01-uu'); edtfy('01/1*/1988').should.equal('1988-01-1u'); edtfy('1/1*/1988').should.equal('1988-01-1u'); edtfy('01/**/1988').should.equal('1988-01-uu'); }); }); describe('L1 extended interval: the parser', function() { it('should parse intervals with unknown dates', function() { edtfy('unknown - 1988').should.equal('unknown/1988'); edtfy('1988 - unknown').should.equal('1988/unknown'); }); it('should parse intervals with open dates', function() { edtfy('1988 - open').should.equal('1988/open'); }); it('should parse various intervals', function() { edtfy('uu/1988 - around 2005').should.equal('1988-uu/2005~'); edtfy('march 1988 - winter 2005?').should.equal('1988-03/2005-24?'); edtfy('from around sep 10 1988? to unknown').should.equal('1988-09-10?~/unknown'); edtfy('around sep 10 1988? - unknown').should.equal('1988-09-10?~/unknown'); }); }); describe('year exceeding four digits: the parser', function() { it('should handthe them', function() { edtfy('21988').should.equal('y21988'); edtfy('-21988').should.equal('y-21988'); edtfy('march 3 -21988').should.equal('y-21988-03-03'); edtfy('2/-21988').should.equal('y-21988-02'); edtfy('11/10/21988').should.equal('y21988-11-10'); edtfy('march 3 -21988').should.equal('y-21988-03-03'); }); }); describe('season: the parser', function() { it('should parse seasons', function() { edtfy('spring 1988').should.equal('1988-21'); edtfy('summer 1988').should.equal('1988-22'); edtfy('autumn 1988').should.equal('1988-23'); edtfy('fall 1988').should.equal('1988-23'); edtfy('winter 1988').should.equal('1988-24'); }); }); });
1.414063
1
test/test.0001.js
g-stefan/quantum-script-extension-example
0
1407
// Public domain // http://unlicense.org/ Script.requireExtension("Console"); Script.requireExtension("Example"); Script.requireExtension("JSON"); Example.print(Example.process(function(x) { return x + " world!\r\n"; })); Console.writeLn(JSON.encodeWithIndentation(Script.getExtensionList())); Console.writeLn("-> test 0001 ok");
1.28125
1
wildfire-tracker/src/components/Header.js
LightLordYT/Traversy-Courses
1
1415
import { Icon } from '@iconify/react'; import locationIcon from '@iconify/icons-mdi/fire-alert'; const Header = () => { return ( <header className='header'> <h1> <Icon icon={locationIcon} /> Wildfire Tracker (Powered By NASA) </h1> </header> ); }; export default Header;
0.820313
1
packages/material-ui/src/MenuItem/MenuItem.test.js
MichaelDuo/material-ui
0
1423
// @ts-check import * as React from 'react'; import { expect } from 'chai'; import { spy } from 'sinon'; import { createMount, describeConformanceV5, createClientRender, fireEvent, screen, } from 'test/utils'; import MenuItem, { menuItemClasses as classes } from '@material-ui/core/MenuItem'; import ListItem from '@material-ui/core/ListItem'; import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction'; describe('<MenuItem />', () => { const mount = createMount(); const render = createClientRender(); describeConformanceV5(<MenuItem />, () => ({ classes, inheritComponent: ListItem, mount, refInstanceof: window.HTMLLIElement, testComponentPropWith: 'a', muiName: 'MuiMenuItem', testVariantProps: { disableGutters: true }, skip: ['componentsProp'], })); it('should render a focusable menuitem', () => { render(<MenuItem />); const menuitem = screen.getByRole('menuitem'); expect(menuitem).to.have.property('tabIndex', -1); }); it('has a ripple when clicked', () => { render(<MenuItem TouchRippleProps={{ classes: { rippleVisible: 'ripple-visible' } }} />); const menuitem = screen.getByRole('menuitem'); // ripple starts on mousedown fireEvent.mouseDown(menuitem); expect(menuitem.querySelectorAll('.ripple-visible')).to.have.length(1); }); it('should render with the selected class but not aria-selected when `selected`', () => { render(<MenuItem selected />); const menuitem = screen.getByRole('menuitem'); expect(menuitem).to.have.class(classes.selected); expect(menuitem).not.to.have.attribute('aria-selected'); }); it('can have a role of option', () => { render(<MenuItem role="option" aria-selected={false} />); expect(screen.queryByRole('option')).not.to.equal(null); }); describe('event callbacks', () => { /** * @type {Array<keyof typeof fireEvent>} */ const events = ['click', 'mouseDown', 'mouseEnter', 'mouseLeave', 'mouseUp', 'touchEnd']; events.forEach((eventName) => { it(`should fire ${eventName}`, () => { const handlerName = `on${eventName[0].toUpperCase()}${eventName.slice(1)}`; const handler = spy(); render(<MenuItem {...{ [handlerName]: handler }} />); fireEvent[eventName](screen.getByRole('menuitem')); expect(handler.callCount).to.equal(1); }); }); it(`should fire focus, keydown, keyup and blur`, () => { const handleFocus = spy(); const handleKeyDown = spy(); const handleKeyUp = spy(); const handleBlur = spy(); render( <MenuItem onFocus={handleFocus} onKeyDown={handleKeyDown} onKeyUp={handleKeyUp} onBlur={handleBlur} />, ); const menuitem = screen.getByRole('menuitem'); menuitem.focus(); expect(handleFocus.callCount).to.equal(1); fireEvent.keyDown(menuitem); expect(handleKeyDown.callCount).to.equal(1); fireEvent.keyUp(menuitem); expect(handleKeyUp.callCount).to.equal(1); menuitem.blur(); expect(handleKeyDown.callCount).to.equal(1); }); it('should fire onTouchStart', function touchStartTest() { // only run in supported browsers if (typeof Touch === 'undefined') { this.skip(); } const handleTouchStart = spy(); render(<MenuItem onTouchStart={handleTouchStart} />); const menuitem = screen.getByRole('menuitem'); const touch = new Touch({ identifier: 0, target: menuitem, clientX: 0, clientY: 0 }); fireEvent.touchStart(menuitem, { touches: [touch] }); expect(handleTouchStart.callCount).to.equal(1); }); }); // Regression test for #10452. // Kept for backwards compatibility. // In the future we should have a better pattern for this UI. it('should not fail with a li > li error message', () => { const { rerender } = render( <MenuItem> <ListItemSecondaryAction> <div /> </ListItemSecondaryAction> </MenuItem>, ); expect(document.querySelectorAll('li')).to.have.length(1); rerender( <MenuItem button={false}> <ListItemSecondaryAction> <div /> </ListItemSecondaryAction> </MenuItem>, ); expect(document.querySelectorAll('li')).to.have.length(1); }); it('can be disabled', () => { render(<MenuItem disabled />); const menuitem = screen.getByRole('menuitem'); expect(menuitem).to.have.attribute('aria-disabled', 'true'); }); describe('prop: ListItemClasses', () => { it('should be able to change the style of ListItem', () => { render(<MenuItem ListItemClasses={{ disabled: 'bar' }} disabled />); const menuitem = screen.getByRole('menuitem'); expect(menuitem).to.have.class('bar'); }); }); });
1.46875
1
app-frontend/src/pages/homepage/homepage.test.js
Tanvir-rahman/phone-catalog-app
0
1431
import React from 'react'; import { shallow } from 'enzyme'; import { HomePage } from './homepage.component'; describe('Homepage component', () => { let wrapper; let mockfetchPhoneList; beforeEach(() => { mockfetchPhoneList= jest.fn(); const mockProps = { fetchPhoneList: mockfetchPhoneList }; wrapper = shallow(<HomePage {...mockProps} />); }); it('should render Homepage component', () => { expect(wrapper).toMatchSnapshot(); }); it('should render title in Title Container', () => { expect(wrapper.find('.title').text()).toBe(' Phone Catalog App '); }); });
1.25
1
assets/js/0-plugins/maintain-animation.js
cedric-91/Audify-Landing-Page
0
1439
(function (lib, img, cjs, ss, an) { var p; // shortcut to reference prototypes lib.webFontTxtInst = {}; var loadedTypekitCount = 0; var loadedGoogleCount = 0; var gFontsUpdateCacheList = []; var tFontsUpdateCacheList = []; lib.ssMetadata = []; lib.updateListCache = function (cacheList) { for(var i = 0; i < cacheList.length; i++) { if(cacheList[i].cacheCanvas) cacheList[i].updateCache(); } }; lib.addElementsToCache = function (textInst, cacheList) { var cur = textInst; while(cur != exportRoot) { if(cacheList.indexOf(cur) != -1) break; cur = cur.parent; } if(cur != exportRoot) { var cur2 = textInst; var index = cacheList.indexOf(cur); while(cur2 != cur) { cacheList.splice(index, 0, cur2); cur2 = cur2.parent; index++; } } else { cur = textInst; while(cur != exportRoot) { cacheList.push(cur); cur = cur.parent; } } }; lib.gfontAvailable = function(family, totalGoogleCount) { lib.properties.webfonts[family] = true; var txtInst = lib.webFontTxtInst && lib.webFontTxtInst[family] || []; for(var f = 0; f < txtInst.length; ++f) lib.addElementsToCache(txtInst[f], gFontsUpdateCacheList); loadedGoogleCount++; if(loadedGoogleCount == totalGoogleCount) { lib.updateListCache(gFontsUpdateCacheList); } }; lib.tfontAvailable = function(family, totalTypekitCount) { lib.properties.webfonts[family] = true; var txtInst = lib.webFontTxtInst && lib.webFontTxtInst[family] || []; for(var f = 0; f < txtInst.length; ++f) lib.addElementsToCache(txtInst[f], tFontsUpdateCacheList); loadedTypekitCount++; if(loadedTypekitCount == totalTypekitCount) { lib.updateListCache(tFontsUpdateCacheList); } }; // symbols: // helper functions: function mc_symbol_clone() { var clone = this._cloneProps(new this.constructor(this.mode, this.startPosition, this.loop)); clone.gotoAndStop(this.currentFrame); clone.paused = this.paused; clone.framerate = this.framerate; return clone; } function getMCSymbolPrototype(symbol, nominalBounds, frameBounds) { var prototype = cjs.extend(symbol, cjs.MovieClip); prototype.clone = mc_symbol_clone; prototype.nominalBounds = nominalBounds; prototype.frameBounds = frameBounds; return prototype; } (lib.Tween5 = function(mode,startPosition,loop) { this.initialize(mode,startPosition,loop,{}); // Layer 1 this.shape = new cjs.Shape(); this.shape.graphics.f().s("#FFFFFC").ss(2).p("AhjhjIDHDH"); this.shape.setTransform(26.8,29.2); this.shape_1 = new cjs.Shape(); this.shape_1.graphics.f().s("#C7CF43").ss(2).p("Ai8hGIB1h2IA7AMIAABGIC8C8QAOAOAAAVQAAAVgOAOIgYAYQgOAOgVAAQgVAAgOgOIi8i8IhHAAg"); this.shape_1.setTransform(23.9,26.3); this.shape_2 = new cjs.Shape(); this.shape_2.graphics.f().s("#C7CF43").ss(2).p("ACRDAIixiyIg7gLIheiNIAvgvICMBeIAMA7ICyCx"); this.shape_2.setTransform(-23.5,-21.2); this.shape_3 = new cjs.Shape(); this.shape_3.graphics.f().s("#C7CF43").ss(2).p("AgUhDIBRBRIgwAvIhQhR"); this.shape_3.setTransform(7.2,9.5); this.shape_4 = new cjs.Shape(); this.shape_4.graphics.f().s("#FFFFFC").ss(2).p("ADyjxIniHi"); this.shape_4.setTransform(-8.5,6.7); this.shape_5 = new cjs.Shape(); this.shape_5.graphics.f().s("#FFFFFC").ss(2).p("AALAMIgWgX"); this.shape_5.setTransform(-36.2,34.4); this.shape_6 = new cjs.Shape(); this.shape_6.graphics.f().s("#C7CF43").ss(2).p("AGflBIheBeQgFAFgHAAQgHAAgFgFIhGhHQgFgFAAgGQAAgHAFgFIBeheQgtgYgrAGQgqAHgjAiIgjAkQgyAxAnBpIoRIRQgPAOAAAVQAAAVAPAOIAXAYQAPAOAVAAQAUAAAPgOIIRoRQBlAmAzgzIAkgjQAigjAHgpQAHgsgZgtg"); this.shape_6.setTransform(0,-1.7); this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.shape_6},{t:this.shape_5},{t:this.shape_4},{t:this.shape_3},{t:this.shape_2},{t:this.shape_1},{t:this.shape}]}).wait(1)); }).prototype = p = new cjs.MovieClip(); p.nominalBounds = new cjs.Rectangle(-44.4,-48.7,93.6,95.1); (lib.maintainicon2 = function(mode,startPosition,loop) { this.initialize(mode,startPosition,loop,{}); // Layer 1 this.instance = new lib.Tween5("synched",0); this.instance.parent = this; this.timeline.addTween(cjs.Tween.get(this.instance).wait(1)); }).prototype = getMCSymbolPrototype(lib.maintainicon2, new cjs.Rectangle(-44.4,-48.7,93.6,95.1), null); // stage content: (lib.maintainanimation = function(mode,startPosition,loop) { if (loop == null) { loop = false; } this.initialize(mode,startPosition,loop,{}); // FlashAICB this.instance = new lib.maintainicon2(); this.instance.parent = this; this.instance.setTransform(67.3,63.8,1,1,0,0,0,2.3,-1.2); this.timeline.addTween(cjs.Tween.get(this.instance).to({regX:0,regY:0,rotation:360,x:65,y:65},24,cjs.Ease.get(-0.9)).wait(1)); }).prototype = p = new cjs.MovieClip(); p.nominalBounds = new cjs.Rectangle(85.6,81.3,93.6,95.1); // library properties: lib.properties = { width: 130, height: 130, fps: 24, color: "#CC00FF", opacity: 0.00, webfonts: {}, manifest: [], preloads: [] }; })(lib = lib||{}, images = images||{}, createjs = createjs||{}, ss = ss||{}, AdobeAn = AdobeAn||{}); var lib, images, createjs, ss, AdobeAn;
1.210938
1
docs/cpp_algorithms/search/functions_f.js
matbesancon/or-tools
1
1447
var searchData= [ ['to_265',['to',['../classoperations__research_1_1_knapsack_search_path.html#af020a457732b35e71f0bce09433ba4f2',1,'operations_research::KnapsackSearchPath']]] ];
-0.388672
0
frontend/src/comment.js
ph3nomforko/book_review
1
1455
class Comment { constructor(comment) { this.id = comment.id this.content = comment.attributes.content this.username = comment.attributes.username this.book = comment.attributes.book Comment.all.push(this) } } Comment.all = []
1.148438
1
load-test/src/index.js
SerayaEryn/nodejs-sensor
0
1463
/* eslint-disable no-console */ 'use strict'; var config = require('./config'); var cluster = require('cluster'); if (config.sensor.enabled) { require('instana-nodejs-sensor')({ level: 'info', agentPort: config.sensor.agentPort, tracing: { enabled: config.sensor.tracing, stackTraceLength: config.sensor.stackTraceLength } }); } require('heapdump'); if (cluster.isMaster && config.app.workers > 1) { initMaster(); } else { initWorker(); } function initMaster() { console.log('Master ' + process.pid + ' is running'); for (var i = 0; i < config.app.workers; i++) { cluster.fork(); } cluster.on('exit', function(worker) { console.log('worker ' + worker.process.pid + ' died'); }); } function initWorker() { console.log('Starting worker ' + process.pid); require('./app').init(function() { console.log('Worker ' + process.pid + ' started'); }); }
1.15625
1
spec/quick_latex-to-ast.spec.js
Conway/math-expressions
47
1471
import latexToAst from '../lib/converters/latex-to-ast'; import { ParseError } from '../lib/converters/error'; var converter = new latexToAst(); var trees = { '\\frac{1}{2} x': ['*',['/',1,2],'x'], '1+x+3': ['+',1,'x',3], '1-x-3': ['+',1,['-','x'],['-',3]], "1 + - x": ['+',1,['-','x']], "1 - - x": ['+',1,['-',['-','x']]], '1.+x+3.0': ['+',1,'x',3], 'x^2': ['^', 'x', 2], '\\log x': ['apply', 'log', 'x'], '\\ln x': ['apply', 'ln', 'x'], '-x^2': ['-',['^', 'x', 2]], '|x|': ['apply', 'abs','x'], '|\\sin|x||': ['apply', 'abs', ['apply', 'sin', ['apply', 'abs', 'x']]], 'x^47': ['^', 'x', 47], 'x^ab': ['*', ['^', 'x', 'a'], 'b'], 'x^a!': ['^', 'x', ['apply', 'factorial', 'a']], 'xyz': ['*','x','y','z'], 'c(a+b)': ['*', 'c', ['+', 'a', 'b']], '(a+b)c': ['*', ['+', 'a', 'b'], 'c'], 'a!': ['apply', 'factorial','a'], '\\theta': 'theta', 'theta': ['*', 't', 'h', 'e', 't', 'a'], '\\cos(\\theta)': ['apply', 'cos','theta'], 'cos(x)': ['*', 'c', 'o', 's', 'x'], '|\\sin(|x|)|': ['apply', 'abs', ['apply', 'sin', ['apply', 'abs', 'x']]], '\\var{blah}(x)': ['*', 'blah', 'x'], '|x+3=2|': ['apply', 'abs', ['=', ['+', 'x', 3], 2]], 'x_y_z': ['_', 'x', ['_','y','z']], 'x_{y_z}': ['_', 'x', ['_','y','z']], '{x_y}_z': ['_', ['_', 'x', 'y'],'z'], 'x^y^z': ['^', 'x', ['^','y','z']], 'x^{y^z}': ['^', 'x', ['^','y','z']], '{x^y}^z': ['^', ['^', 'x', 'y'],'z'], 'x^y_z': ['^', 'x', ['_','y','z']], 'x_y^z': ['^', ['_','x','y'],'z'], 'xyz!': ['*','x','y', ['apply', 'factorial', 'z']], 'x': 'x', 'f': 'f', 'fg': ['*', 'f','g'], 'f+g': ['+', 'f', 'g'], 'f(x)': ['apply', 'f', 'x'], 'f(x,y,z)': ['apply', 'f', ['tuple', 'x', 'y', 'z']], 'fg(x)': ['*', 'f', ['apply', 'g', 'x']], 'fp(x)': ['*', 'f', 'p', 'x'], 'fx': ['*', 'f', 'x'], 'f\'': ['prime', 'f'], 'fg\'': ['*', 'f', ['prime', 'g']], 'f\'g': ['*', ['prime', 'f'], 'g'], 'f\'g\'\'': ['*', ['prime', 'f'], ['prime', ['prime', 'g']]], 'x\'': ['prime', 'x'], 'f\'(x)' : ['apply', ['prime', 'f'], 'x'], 'f(x)\'' : ['prime', ['apply', 'f', 'x']], '\\sin(x)\'': ['prime', ['apply', 'sin', 'x']], '\\sin\'(x)': ['apply', ['prime', 'sin'], 'x'], 'f\'\'(x)': ['apply', ['prime', ['prime', 'f']],'x'], '\\sin(x)\'\'': ['prime', ['prime', ['apply','sin','x']]], 'f(x)^t_y': ['^', ['apply', 'f','x'], ['_','t','y']], 'f_t(x)': ['apply', ['_', 'f', 't'], 'x'], 'f(x)_t': ['_', ['apply', 'f', 'x'], 't'], 'f^2(x)': ['apply', ['^', 'f', 2], 'x'], 'f(x)^2': ['^', ['apply', 'f', 'x'],2], 'f\'^a(x)': ['apply', ['^', ['prime', 'f'], 'a'], 'x'], 'f^a\'(x)': ['apply', ['^', 'f', ['prime', 'a']], 'x'], 'f_a^b\'(x)': ['apply', ['^', ['_', 'f', 'a'], ['prime', 'b']],'x'], 'f_a\'^b(x)': ['apply', ['^', ['prime', ['_', 'f','a']],'b'],'x'], '\\sin x': ['apply', 'sin', 'x'], 'f x': ['*', 'f', 'x'], '\\sin^xyz': ['*', ['apply', ['^', 'sin', 'x'], 'y'], 'z'], '\\sin xy': ['*', ['apply', 'sin', 'x'], 'y'], '\\sin^2(x)': ['apply', ['^', 'sin', 2], 'x'], '\\exp(x)': ['apply', 'exp', 'x'], 'e^x': ['^', 'e', 'x'], 'x^2!': ['^', 'x', ['apply', 'factorial', 2]], 'x^2!!': ['^', 'x', ['apply', 'factorial', ['apply', 'factorial', 2]]], 'x_t^2': ['^', ['_', 'x', 't'], 2], 'x_f^2': ['_', 'x', ['^', 'f', 2]], 'x_t\'': ['prime', ['_', 'x', 't']], 'x_f\'': ['_', 'x', ['prime', 'f']], '(x,y,z)': ['tuple', 'x', 'y', 'z'], '(x,y)-[x,y]': ['+', ['tuple','x','y'], ['-', ['array','x','y']]], '2[z-(x+1)]': ['*', 2, ['+', 'z', ['-', ['+', 'x', 1]]]], '\\{1,2,x\\}': ['set', 1, 2, 'x'], '\\{x, x\\}': ['set', 'x', 'x'], '\\{x\\}': ['set', 'x'], '\\{-x\\}': ['set', ['-','x']], '(1,2]': ['interval', ['tuple', 1, 2], ['tuple', false, true]], '[1,2)': ['interval', ['tuple', 1, 2], ['tuple', true, false]], '[1,2]': ['array', 1, 2 ], '(1,2)': ['tuple', 1, 2 ], '1,2,3': ['list', 1, 2, 3], 'x=a': ['=', 'x', 'a'], 'x=y=1': ['=', 'x', 'y', 1], 'x=(y=1)': ['=', 'x', ['=', 'y', 1]], '(x=y)=1': ['=', ['=','x', 'y'], 1], '7 \\ne 2': ['ne', 7, 2], '7 \\neq 2': ['ne', 7, 2], '\\lnot x=y': ['not', ['=', 'x', 'y']], '\\lnot (x=y)': ['not', ['=', 'x', 'y']], 'x>y': ['>', 'x','y'], 'x \\gt y': ['>', 'x','y'], 'x \\ge y': ['ge', 'x','y'], 'x \\geq y': ['ge', 'x','y'], 'x>y>z': ['gts', ['tuple', 'x', 'y','z'], ['tuple', true, true]], 'x>y \\ge z': ['gts', ['tuple', 'x', 'y','z'], ['tuple', true, false]], 'x \\ge y>z': ['gts', ['tuple', 'x', 'y','z'], ['tuple', false, true]], 'x \\ge y \\ge z': ['gts', ['tuple', 'x', 'y','z'], ['tuple', false, false]], 'x<y': ['<', 'x','y'], 'x \\lt y': ['<', 'x','y'], 'x \\le y': ['le', 'x','y'], 'x \\leq y': ['le', 'x','y'], 'x<y<z': ['lts', ['tuple', 'x', 'y','z'], ['tuple', true, true]], 'x<y \\le z': ['lts', ['tuple', 'x', 'y','z'], ['tuple', true, false]], 'x \\le y<z': ['lts', ['tuple', 'x', 'y', 'z'], ['tuple', false, true]], 'x \\le y \\le z': ['lts', ['tuple', 'x', 'y', 'z'], ['tuple', false, false]], 'x<y>z': ['>', ['<', 'x', 'y'], 'z'], 'A \\subset B': ['subset', 'A', 'B'], 'A \\not\\subset B': ['notsubset', 'A', 'B'], 'A \\supset B': ['superset', 'A', 'B'], 'A \\not\\supset B': ['notsuperset', 'A', 'B'], 'x \\in A': ['in', 'x', 'A'], 'x \\notin A': ['notin', 'x', 'A'], 'x \\not\\in A': ['notin', 'x', 'A'], 'A \\ni x': ['ni', 'A', 'x'], 'A \\not\\ni x': ['notni', 'A', 'x'], 'A \\cup B': ['union', 'A', 'B'], 'A \\cap B': ['intersect', 'A', 'B'], 'A \\land B': ['and', 'A', 'B'], 'A \\wedge B': ['and', 'A', 'B'], 'A \\lor B': ['or', 'A', 'B'], 'A \\vee B': ['or', 'A', 'B'], 'A \\land B \\lor C': ['and', 'A', 'B', 'C'], 'A \\lor B \\lor C': ['or', 'A', 'B', 'C'], 'A \\land B \\lor C': ['or', ['and', 'A', 'B'], 'C'], 'A \\lor B \\land C': ['or', 'A', ['and', 'B', 'C']], '\\lnot x=1': ['not', ['=', 'x', 1]], '\\lnot(x=1)': ['not', ['=', 'x', 1]], '\\lnot(x=y) \\lor z \\ne w': ['or', ['not', ['=','x','y']], ['ne','z','w']], '1.2E3': 1200, '1.2E+3 ': 1200, '3.1E-3 ': 0.0031, '3.1E- 3 ': ['+', ['*', 3.1, 'E'], ['-', 3]], '3.1E -3 ': ['+', ['*', 3.1, 'E'], ['-', 3]], '3.1E - 3 ': ['+', ['*', 3.1, 'E'], ['-', 3]], '3.1E-3 + 2 ': ['+', ['*', 3.1, 'E'], ['-', 3], 2], '(3.1E-3 ) + 2': ['+', 0.0031, 2], '\\sin((3.1E-3)x)': ['apply', 'sin', ['*', 0.0031, 'x']], '\\sin( 3.1E-3 x)': ['apply', 'sin', ['+', ['*', 3.1, 'E'], ['-', ['*', 3, 'x']]]], '\\frac{3.1E-3 }{x}': ['/', 0.0031, 'x'], '|3.1E-3|': ['apply', 'abs', 0.0031], '|3.1E-3|': ['apply', 'abs', 0.0031], '(3.1E-3, 1E2)': ['tuple', 0.0031, 100], '(3.1E-3, 1E2]': ["interval", ["tuple", 0.0031, 100], ["tuple", false, true]], '\\{ 3.1E-3, 1E2 \\}': ['set', 0.0031, 100], '\\begin{matrix} 1E-3 & 3E-12 \\\\ 6E+3& 7E5\\end{matrix}': [ 'matrix', [ 'tuple', 2, 2 ], [ 'tuple', [ 'tuple', 0.001, 3e-12 ], [ 'tuple', 6000, 700000 ] ] ], '1.2e-3': ['+', ['*', 1.2, 'e'], ['-', 3]], '+2': 2, '\\infty': Infinity, '+\\infty': Infinity, 'a b\\,c\\!d\\ e\\>f\\;g\\>h\\quad i \\qquad j': ['*','a','b','c','d','e','f','g','h','i','j'], '\\begin{bmatrix}a & b\\\\ c&d\\end{bmatrix}': ['matrix', ['tuple', 2, 2], ['tuple', ['tuple', 'a', 'b'], ['tuple', 'c', 'd']]], '\\begin{pmatrix}a & b\\\\ c\\end{pmatrix}': ['matrix', ['tuple', 2, 2], ['tuple', ['tuple', 'a', 'b'], ['tuple', 'c', 0]]], '\\begin{matrix}a & b\\\\ &d\\end{matrix}': ['matrix', ['tuple', 2, 2], ['tuple', ['tuple', 'a', 'b'], ['tuple', 0, 'd']]], '\\begin{pmatrix}a + 3y & 2\\sin(\\theta)\\end{pmatrix}': ['matrix', ['tuple', 1, 2], ['tuple', ['tuple', ['+', 'a', ['*', 3, 'y']], ['*', 2, ['apply', 'sin', 'theta']]]]], '\\begin{bmatrix}3\\\\ \\\\ 4 & 5\\end{bmatrix}': ['matrix', ['tuple', 3, 2], ['tuple', ['tuple', 3, 0], ['tuple', 0, 0], ['tuple', 4, 5]]], '\\begin{matrix}8\\\\1&2&3\\end{matrix}': ['matrix', ['tuple', 2, 3], ['tuple', ['tuple', 8, 0, 0], ['tuple', 1, 2, 3]]], '\\frac{dx}{dt}=q': ['=', ['derivative_leibniz', 'x', ['tuple', 't']], 'q'], '\\frac { dx } { dt } = q': ['=', ['derivative_leibniz', 'x', ['tuple', 't']], 'q'], '\\frac{d x}{dt}': ['derivative_leibniz', 'x', ['tuple', 't']], '\\frac{dx}{d t}': ['derivative_leibniz', 'x', ['tuple', 't']], '\\frac{dx_2}{dt}': ["/", ["*", "d", ["_", "x", 2]], ["*", "d", "t"]], '\\frac{dxy}{dt}': ["/", ["*", "d", "x", "y"], ["*", "d", "t"]], '\\frac{d^2x}{dt^2}': ['derivative_leibniz', ['tuple', 'x', 2], ['tuple', ['tuple', 't', 2]]], '\\frac{d^{2}x}{dt^{ 2 }}': ['derivative_leibniz', ['tuple', 'x', 2], ['tuple', ['tuple', 't', 2]]], '\\frac{d^2x}{dt^3}': ["/", ["*", ["^", "d", 2], "x"], ["*", "d", ["^", "t", 3]]], '\\frac{d^2x}{dsdt}': ['derivative_leibniz', ['tuple', 'x', 2], ['tuple', 's', 't']], '\\frac{d^2x}{dsdta}': ["/", ["*", ["^", "d", 2], "x"], ["*", "d", "s", "d", "t", "a"]], '\\frac{d^3x}{ds^2dt}': ['derivative_leibniz', ['tuple', 'x', 3], ['tuple', ['tuple', 's', 2], 't']], '\\frac{d^{ 3 }x}{ds^{2}dt}': ['derivative_leibniz', ['tuple', 'x', 3], ['tuple', ['tuple', 's', 2], 't']], '\\frac{d^3x}{dsdt^2}': ['derivative_leibniz', ['tuple', 'x', 3], ['tuple', 's', ['tuple', 't', 2]]], '\\frac{d^{3}x}{dsdt^{ 2 }}': ['derivative_leibniz', ['tuple', 'x', 3], ['tuple', 's', ['tuple', 't', 2]]], '\\frac{d\\theta}{d\\pi}': ['derivative_leibniz', 'theta', ['tuple', 'pi']], '\\frac{d\\var{hello}}{d\\var{bye}}': ['derivative_leibniz', 'hello', ['tuple', 'bye']], '\\frac{d^2\\theta}{d\\pi^2}': ['derivative_leibniz', ['tuple', 'theta', 2], ['tuple', ['tuple', 'pi', 2]]], '\\frac{d^2\\var{hello}}{d\\var{bye}^2}': ['derivative_leibniz', ['tuple', 'hello', 2], ['tuple', ['tuple', 'bye', 2]]], '\\frac{d^{2}\\theta}{d\\pi^{ 2 }}': ['derivative_leibniz', ['tuple', 'theta', 2], ['tuple', ['tuple', 'pi', 2]]], '\\frac{d^{ 2 }\\var{hello}}{d\\var{bye}^{2}}': ['derivative_leibniz', ['tuple', 'hello', 2], ['tuple', ['tuple', 'bye', 2]]], '\\frac{\\partial x}{\\partial t}': ['partial_derivative_leibniz', 'x', ['tuple', 't']], '\\frac { \\partial x } { \\partial t } = q': ['=', ['partial_derivative_leibniz', 'x', ['tuple', 't']], 'q'], '\\frac{\\partial x_2}{\\partial t}': ["/", ["*", "partial", ["_", "x", 2]], ["*", "partial", "t"]], '\\frac{\\partial xy}{\\partial t}': ["/", ["*", "partial", "x", "y"], ["*", "partial", "t"]], '\\frac{\\partial^2x}{\\partial t^2}': ['partial_derivative_leibniz', ['tuple', 'x', 2], ['tuple', ['tuple', 't', 2]]], '\\frac{\\partial^{2}x}{\\partial t^{ 2 }}': ['partial_derivative_leibniz', ['tuple', 'x', 2], ['tuple', ['tuple', 't', 2]]], '\\frac{\\partial ^2x}{\\partial t^3}': ["/", ["*", ["^", "partial", 2], "x"], ["*", "partial", ["^", "t", 3]]], '\\frac{\\partial ^2x}{\\partial s\\partial t}': ['partial_derivative_leibniz', ['tuple', 'x', 2], ['tuple', 's', 't']], '\\frac{\\partial ^2x}{\\partial s\\partial ta}': ["/", ["*", ["^", "partial", 2], "x"], ["*", "partial", "s", "partial", "t", "a"]], '\\frac{\\partial ^3x}{\\partial s^2\\partial t}': ['partial_derivative_leibniz', ['tuple', 'x', 3], ['tuple', ['tuple', 's', 2], 't']], '\\frac{\\partial ^{ 3 }x}{\\partial s^{2}\\partial t}': ['partial_derivative_leibniz', ['tuple', 'x', 3], ['tuple', ['tuple', 's', 2], 't']], '\\frac{\\partial ^3x}{\\partial s\\partial t^2}': ['partial_derivative_leibniz', ['tuple', 'x', 3], ['tuple', 's', ['tuple', 't', 2]]], '\\frac{\\partial ^{3}x}{\\partial s\\partial t^{ 2 }}': ['partial_derivative_leibniz', ['tuple', 'x', 3], ['tuple', 's', ['tuple', 't', 2]]], '\\frac{\\partial \\theta}{\\partial \\pi}': ['partial_derivative_leibniz', 'theta', ['tuple', 'pi']], '\\frac{\\partial \\var{hello}}{\\partial \\var{bye}}': ['partial_derivative_leibniz', 'hello', ['tuple', 'bye']], '\\frac{\\partial ^2\\theta}{\\partial \\pi^2}': ['partial_derivative_leibniz', ['tuple', 'theta', 2], ['tuple', ['tuple', 'pi', 2]]], '\\frac{\\partial ^2\\var{hello}}{\\partial \\var{bye}^2}': ['partial_derivative_leibniz', ['tuple', 'hello', 2], ['tuple', ['tuple', 'bye', 2]]], '\\frac{\\partial ^{2}\\theta}{\\partial \\pi^{ 2 }}': ['partial_derivative_leibniz', ['tuple', 'theta', 2], ['tuple', ['tuple', 'pi', 2]]], '\\frac{\\partial ^{ 2 }\\var{hello}}{\\partial \\var{bye}^{2}}': ['partial_derivative_leibniz', ['tuple', 'hello', 2], ['tuple', ['tuple', 'bye', 2]]], '2 \\cdot 3': ['*', 2, 3], '2\\cdot3': ['*', 2, 3], '2 \\times 3': ['*', 2, 3], '2\\times3': ['*', 2, 3], '3 \\div 1': ['/', 3, 1], '3\\div1': ['/', 3, 1], '\\sin2': ['apply', 'sin', 2], '3|x|': ['*', 3, ['apply', 'abs', 'x']], '|a|b|c|': ['*',['apply', 'abs', 'a'], 'b', ['apply', 'abs', 'c']], '|a|*b*|c|': ['*',['apply', 'abs', 'a'], 'b', ['apply', 'abs', 'c']], '|a*|b|*c|': ['apply', 'abs', ['*', 'a', ['apply', 'abs', 'b'], 'c']], '\\left|a\\left|b\\right|c\\right|': ['apply', 'abs', ['*', 'a', ['apply', 'abs', 'b'], 'c']], '|a(q|b|r)c|': ['apply', 'abs', ['*', 'a', 'q', ['apply', 'abs', 'b'], 'r', 'c']], 'r=1|x': ['|', ['=', 'r', 1], 'x'], '\\{ x | x > 0 \\}': ['set', ['|', 'x', ['>', 'x', 0]]], 'r=1 \\mid x': ['|', ['=', 'r', 1], 'x'], '\\{ x \\mid x > 0 \\}': ['set', ['|', 'x', ['>', 'x', 0]]], 'r=1:x': [':', ['=', 'r', 1], 'x'], '\\{ x : x > 0 \\}': ['set', [':', 'x', ['>', 'x', 0]]], '\\ldots': ['ldots'], '1,2,3,\\ldots': ['list', 1, 2, 3, ['ldots']], '(1,2,3,\\ldots)': ['tuple', 1, 2, 3, ['ldots']], 'a-2b': ['+', 'a', ['-', ['*', 2, 'b']]], 'a+-2b': ['+', 'a', ['-', ['*', 2, 'b']]], 'a+(-2b)': ['+', 'a', ['-', ['*', 2, 'b']]], }; Object.keys(trees).forEach(function(string) { test("parses " + string, () => { expect(converter.convert(string)).toEqual(trees[string]); }); }); // inputs that should throw an error var bad_inputs = { '1++1': "Invalid location of '+'", ')1++1': "Invalid location of ')'", '(1+1': "Expecting )", 'x-y-': "Unexpected end of input", '|x_|': "Unexpected end of input", '_x': "Invalid location of _", 'x_': "Unexpected end of input", 'x@2': "Invalid symbol '@'", '|y/v': "Expecting |", 'x+^2': "Invalid location of ^", 'x/\'y': "Invalid location of '", '[1,2,3)': "Expecting ]", '(1,2,3]': "Expecting )", '[x)': "Expecting ]", '(x]': "Expecting )", '\\sin': "Unexpected end of input", '\\sin+\\cos': "Invalid location of '+'", } Object.keys(bad_inputs).forEach(function(string) { test("throws " + string, function() { expect(() => {converter.convert(string)}).toThrow(bad_inputs[string]); }); }); test("function symbols", function () { let converter = new latexToAst({functionSymbols: []}); expect(converter.convert('f(x)+h(y)')).toEqual( ['+',['*', 'f', 'x'], ['*', 'h', 'y']]); converter = new latexToAst({functionSymbols: ['f']}); expect(converter.convert('f(x)+h(y)')).toEqual( ['+',['apply', 'f', 'x'], ['*', 'h', 'y']]); converter = new latexToAst({functionSymbols: ['f', 'h']}); expect(converter.convert('f(x)+h(y)')).toEqual( ['+',['apply', 'f', 'x'], ['apply', 'h', 'y']]); converter = new latexToAst({functionSymbols: ['f', 'h', 'x']}); expect(converter.convert('f(x)+h(y)')).toEqual( ['+',['apply', 'f', 'x'], ['apply', 'h', 'y']]); }); test("applied function symbols", function () { let converter = new latexToAst({appliedFunctionSymbols: [], allowedLatexSymbols: ['custom', 'sin']}); expect(converter.convert('\\sin(x) + \\custom(y)')).toEqual( ['+', ['*', 'sin', 'x'], ['*', 'custom', 'y']]); expect(converter.convert('\\sin x + \\custom y')).toEqual( ['+', ['*', 'sin', 'x'], ['*', 'custom', 'y']]); converter = new latexToAst({appliedFunctionSymbols: ['custom'], allowedLatexSymbols: ['custom', 'sin']}); expect(converter.convert('\\sin(x) + \\custom(y)')).toEqual( ['+', ['*', 'sin', 'x'], ['apply', 'custom', 'y']]); expect(converter.convert('\\sin x + \\custom y')).toEqual( ['+', ['*', 'sin', 'x'], ['apply', 'custom', 'y']]); converter = new latexToAst({appliedFunctionSymbols: ['custom', 'sin'], allowedLatexSymbols: ['custom', 'sin']}); expect(converter.convert('\\sin(x) + \\custom(y)')).toEqual( ['+', ['apply', 'sin', 'x'], ['apply', 'custom', 'y']]); expect(converter.convert('\\sin x + \\custom y')).toEqual( ['+', ['apply', 'sin', 'x'], ['apply', 'custom', 'y']]); }); test("allow simplified function application", function () { let converter = new latexToAst(); expect(converter.convert('\\sin x')).toEqual( ['apply', 'sin', 'x']); converter = new latexToAst({allowSimplifiedFunctionApplication: false}); expect(() => {converter.convert('\\sin x')}).toThrow( "Expecting ( after function"); converter = new latexToAst({allowSimplifiedFunctionApplication: true}); expect(converter.convert('\\sin x')).toEqual( ['apply', 'sin', 'x']); }); test("parse Leibniz notation", function () { let converter = new latexToAst(); expect(converter.convert('\\frac{dy}{dx}')).toEqual( ['derivative_leibniz', 'y', ['tuple', 'x']]); converter = new latexToAst({parseLeibnizNotation: false}); expect(converter.convert('\\frac{dy}{dx}')).toEqual( ['/', ['*', 'd', 'y'], ['*', 'd', 'x']]); converter = new latexToAst({parseLeibnizNotation: true}); expect(converter.convert('\\frac{dy}{dx}')).toEqual( ['derivative_leibniz', 'y', ['tuple', 'x']]); }); test("conditional probability", function () { let converter = new latexToAst({functionSymbols: ["P"]}); expect(converter.convert("P(A|B)")).toEqual( ['apply', 'P', ['|', 'A', 'B']]); expect(converter.convert("P(A:B)")).toEqual( ['apply', 'P', [':', 'A', 'B']]); expect(converter.convert("P(R=1|X>2)")).toEqual( ['apply', 'P', ['|', ['=', 'R', 1], ['>', 'X', 2]]]); expect(converter.convert("P(R=1:X>2)")).toEqual( ['apply', 'P', [':', ['=', 'R', 1], ['>', 'X', 2]]]); expect(converter.convert("P( A \\land B | C \\lor D )")).toEqual( ['apply', 'P', ['|', ['and', 'A', 'B'], ['or', 'C', 'D']]]); expect(converter.convert("P( A \\land B : C \\lor D )")).toEqual( ['apply', 'P', [':', ['and', 'A', 'B'], ['or', 'C', 'D']]]); });
1.359375
1
sources/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl.js
Itee/three-full
135
1479
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // WARNING: This file was auto-generated, any change will be overridden in next release. Please use configs/es6.conf.js then run "npm run convert". // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// export default ` vec4 LinearToLinear( in vec4 value ) { return value; } vec4 GammaToLinear( in vec4 value, in float gammaFactor ) { return vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a ); } vec4 LinearToGamma( in vec4 value, in float gammaFactor ) { return vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a ); } vec4 sRGBToLinear( in vec4 value ) { return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); } vec4 LinearTosRGB( in vec4 value ) { return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); } vec4 RGBEToLinear( in vec4 value ) { return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 ); } vec4 LinearToRGBE( in vec4 value ) { float maxComponent = max( max( value.r, value.g ), value.b ); float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 ); return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 ); } vec4 RGBMToLinear( in vec4 value, in float maxRange ) { return vec4( value.rgb * value.a * maxRange, 1.0 ); } vec4 LinearToRGBM( in vec4 value, in float maxRange ) { float maxRGB = max( value.r, max( value.g, value.b ) ); float M = clamp( maxRGB / maxRange, 0.0, 1.0 ); M = ceil( M * 255.0 ) / 255.0; return vec4( value.rgb / ( M * maxRange ), M ); } vec4 RGBDToLinear( in vec4 value, in float maxRange ) { return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 ); } vec4 LinearToRGBD( in vec4 value, in float maxRange ) { float maxRGB = max( value.r, max( value.g, value.b ) ); float D = max( maxRange / maxRGB, 1.0 ); D = clamp( floor( D ) / 255.0, 0.0, 1.0 ); return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D ); } const mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 ); vec4 LinearToLogLuv( in vec4 value ) { vec3 Xp_Y_XYZp = cLogLuvM * value.rgb; Xp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) ); vec4 vResult; vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z; float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0; vResult.w = fract( Le ); vResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0; return vResult; } const mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 ); vec4 LogLuvToLinear( in vec4 value ) { float Le = value.z * 255.0 + value.w; vec3 Xp_Y_XYZp; Xp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 ); Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y; Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z; vec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb; return vec4( max( vRGB, 0.0 ), 1.0 ); } `;
1.203125
1
src/plugins/enter_key_submit/plugin.js
DefenseStorm/selectize.js
0
1487
/* // Include this in $('#yourSelector').selectize({ plugins: ['enter_key_submit'], onInitialize: function () { this.on('submit', function () { this.$input.closest('form').submit(); }, this); }, */ Selectize.define('enter_key_submit', function (options) { var self = this; this.onKeyDown = (function (e) { var original = self.onKeyDown; return function (e) { // this.items.length MIGHT change after event propagation. // We need the initial value as well. See next comment. var initialSelection = this.items.length; original.apply(this, arguments); if (e.keyCode === 13 // Necessary because we don't want this to be triggered when an option is selected with Enter after pressing DOWN key to trigger the dropdown options && initialSelection && initialSelection === this.items.length && this.$control_input.val() === '') { self.trigger('submit'); } }; })(); });
1.328125
1
webpack.config.js
juju4/mitaka
3
1495
const { version } = require("./package.json"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const ExtensionReloader = require("webpack-extension-reloader"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const path = require("path"); const config = { mode: process.env.NODE_ENV, context: path.join(__dirname, "/src"), entry: { background: "./background.ts", content: "./content.ts", options: "./options.ts", }, output: { filename: "[name].js", path: path.join(__dirname, "dist/"), }, module: { rules: [ { test: /\.tsx?$/, loader: "ts-loader", }, { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, { loader: "css-loader", }, { loader: "sass-loader", }, ], }, ], }, resolve: { extensions: [".ts", ".tsx", ".js"], }, optimization: { splitChunks: { name: "vendor", chunks: "all", }, }, plugins: [ new CopyWebpackPlugin({ patterns: [ { from: "icons", to: "icons" }, { from: "options/options.html", to: "options/options.html" }, { from: "manifest.json", to: "manifest.json", transform: (content) => { const jsonContent = JSON.parse(content); jsonContent.version = version; return JSON.stringify(jsonContent, null, 2); }, }, ], }), new MiniCssExtractPlugin({ filename: "options/css/bulma.css", }), new CleanWebpackPlugin(), ], performance: { assetFilter: function (assetFilename) { return assetFilename.endsWith(".js"); }, }, }; if (process.env.HMR === "true") { config.plugins = (config.plugins || []).concat([ new ExtensionReloader({ manifest: path.join(__dirname, "/src/manifest.json"), }), ]); } module.exports = config;
1.140625
1
ai/DQ/mongo/monsterData.js
TouhouFishClub/baibaibot
17
1503
const MongoClient = require('mongodb').MongoClient; const config = require('../config') MongoClient.connect(`${config.MONGO_URL}/${config.MONGO_DATABASE}`, (db, err) => { }) const AllMonster = [ { name: '史莱姆', atk: 1, def: 0, hp: 4, minlv: 1, maxlv: 4, } ]
1.085938
1
vendors/lightgallery/lib/plugins/pager/lg-pager.js
scpedicini/imageserver
0
1511
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); var lg_events_1 = require("../../lg-events"); var lg_pager_settings_1 = require("./lg-pager-settings"); var Pager = /** @class */ (function () { function Pager(instance, $LG) { // get lightGallery core plugin instance this.core = instance; this.$LG = $LG; // extend module default settings with lightGallery core settings this.settings = __assign(__assign({}, lg_pager_settings_1.pagerSettings), this.core.settings); return this; } Pager.prototype.getPagerHtml = function (items) { var pagerList = ''; for (var i = 0; i < items.length; i++) { pagerList += "<span data-lg-item-id=\"" + i + "\" class=\"lg-pager-cont\"> \n <span data-lg-item-id=\"" + i + "\" class=\"lg-pager\"></span>\n <div class=\"lg-pager-thumb-cont\"><span class=\"lg-caret\"></span> <img src=\"" + items[i].thumb + "\" /></div>\n </span>"; } return pagerList; }; Pager.prototype.init = function () { var _this = this; if (!this.settings.pager) { return; } var timeout; this.core.$lgComponents.prepend('<div class="lg-pager-outer"></div>'); var $pagerOuter = this.core.outer.find('.lg-pager-outer'); $pagerOuter.html(this.getPagerHtml(this.core.galleryItems)); // @todo enable click $pagerOuter.first().on('click.lg touchend.lg', function (event) { var $target = _this.$LG(event.target); if (!$target.hasAttribute('data-lg-item-id')) { return; } var index = parseInt($target.attr('data-lg-item-id')); _this.core.slide(index, false, true, false); }); $pagerOuter.first().on('mouseover.lg', function () { clearTimeout(timeout); $pagerOuter.addClass('lg-pager-hover'); }); $pagerOuter.first().on('mouseout.lg', function () { timeout = setTimeout(function () { $pagerOuter.removeClass('lg-pager-hover'); }); }); this.core.LGel.on(lg_events_1.lGEvents.beforeSlide + ".pager", function (event) { var index = event.detail.index; _this.manageActiveClass.call(_this, index); }); this.core.LGel.on(lg_events_1.lGEvents.updateSlides + ".pager", function () { $pagerOuter.empty(); $pagerOuter.html(_this.getPagerHtml(_this.core.galleryItems)); _this.manageActiveClass(_this.core.index); }); }; Pager.prototype.manageActiveClass = function (index) { var $pagerCont = this.core.outer.find('.lg-pager-cont'); $pagerCont.removeClass('lg-pager-active'); $pagerCont.eq(index).addClass('lg-pager-active'); }; Pager.prototype.destroy = function () { this.core.outer.find('.lg-pager-outer').remove(); this.core.LGel.off('.lg.pager'); this.core.LGel.off('.pager'); }; return Pager; }()); exports.default = Pager; //# sourceMappingURL=lg-pager.js.map
1.492188
1
index.js
eladnava/cachet-ap
15
1519
var util = require('util'); var request = require('request'); var Promise = require('bluebird'); var statusCodes = require('./util/statusCodes'); // Internal package configuration var config = { // Supported Cachet API version apiVersion: 1, // Default timeout of 5 seconds for each request to the Cachet API timeout: 5000 }; // Package constructor function CachetAPI(options) { // Make sure the developer provided the status page URL if (!options.url) { throw new Error('Please provide your Cachet API endpoint URL to use this package.'); } // Make sure the developer provided the Cachet API key if (!options.apiKey) { throw new Error('Please provide your API key to use this package.'); } // Add trailing slash if ommitted in status page URL if (options.url.substr(-1) !== '/') { options.url += '/'; } // Append api/v1 to the URL options.url += 'api/v' + config.apiVersion; // Keep track of URL for later this.url = options.url; // Prepare extra headers to be sent with all API requests this.headers = { // Cachet API authentication header 'X-Cachet-Token': options.apiKey }; // Set timeout to value passed in or default to config.timeout this.timeout = options.timeout || config.timeout; // Use ca certificate if one is provided this.ca = options.ca || null; } CachetAPI.prototype.publishMetricPoint = function (metricPoint) { // Dirty hack var that = this; // Return a promise return new Promise(function (resolve, reject) { // No metric point provided? if (!metricPoint) { return reject(new Error('Please provide the metric point to publish.')); } // Point must be an object if (typeof metricPoint !== 'object') { return reject(new Error('Please provide the metric point as an object.')); } // Check for missing metric ID if (!metricPoint.id) { return reject(new Error('Please provide the metric ID.')); } // Check for missing metric value if (metricPoint.value === null) { return reject(new Error('Please provide the metric point value.')); } // Prepare API request var req = { method: 'POST', timeout: that.timeout, json: metricPoint, headers: that.headers, url: that.url + '/metrics/' + metricPoint.id + '/points', ca: that.ca }; // Execute request request(req, function (err, res, body) { // Handle the response accordingly handleResponse(err, res, body, reject, resolve); }); }); }; CachetAPI.prototype.reportIncident = function (incident) { // Dirty hack var that = this; // Return a promise return new Promise(function (resolve, reject) { // No incident provided? if (!incident) { return reject(new Error('Please provide the incident to report.')); } // Incident must be an object if (typeof incident !== 'object') { return reject(new Error('Please provide the incident as an object.')); } // Check for required parameters if (!incident.name || !incident.message || !incident.status || incident.visible === undefined) { return reject(new Error('Please provide the incident name, message, status, and visibility.')); } // Convert boolean values to integers incident.notify = incident.notify ? 1 : 0; incident.visible = incident.visible ? 1 : 0; try { // Attempt to convert incident status name to code incident.status = statusCodes.getIncidentStatusCode(incident.status); // Incident status provided? if (incident.component_status) { // Attempt to convert component status name to code incident.component_status = statusCodes.getComponentStatusCode(incident.component_status); } } catch (err) { // Bad status provided return reject(err); } // Prepare API request var req = { method: 'POST', timeout: that.timeout, json: incident, headers: that.headers, url: that.url + '/incidents', ca: that.ca }; // Execute request request(req, function (err, res, body) { // Handle the response accordingly handleResponse(err, res, body, reject, resolve); }); }); }; CachetAPI.prototype.deleteIncidentById = function (id) { // Dirty hack var that = this; // Return a promise return new Promise(function (resolve, reject) { // No incident id provided? if (!id) { return reject(new Error('Please provide the id of the incident to delete.')); } // Prepare API request var req = { method: 'DELETE', timeout: that.timeout, headers: that.headers, url: that.url + '/incidents/' + id, ca: that.ca }; // Execute request request(req, function (err, res, body) { // Handle the response accordingly handleResponse(err, res, body, reject, resolve); }); }); }; CachetAPI.prototype.getIncidentsByComponentId = function (id) { // Dirty hack var that = this; // Return a promise return new Promise(function (resolve, reject) { // No component ID provided? if (!id) { return reject(new Error('Please provide the component ID of the incidents to fetch.')); } // Prepare API request var req = { method: 'GET', json: true, timeout: that.timeout, headers: that.headers, url: that.url + '/incidents?component_id=' + id, ca: that.ca }; // Execute request request(req, function (err, res, body) { // Extract data object from body if it exists body = (body && body.data) ? body.data : body; // Handle the response accordingly handleResponse(err, res, body, reject, resolve); }); }); }; CachetAPI.prototype.getComponentById = function (id) { // Dirty hack var that = this; // Return a promise return new Promise(function (resolve, reject) { // No component ID provided? if (!id) { return reject(new Error('Please provide the component ID to fetch.')); } // Prepare API request var req = { method: 'GET', json: true, timeout: that.timeout, headers: that.headers, url: that.url + '/components/' + id, ca: that.ca }; // Execute request request(req, function (err, res, body) { // Extract data object from body if it exists body = (body && body.data) ? body.data : body; // Handle the response accordingly handleResponse(err, res, body, reject, resolve); }); }); }; function handleResponse(err, res, body, reject, resolve) { // Handle errors by rejecting the promise if (err) { return reject(err); } // Error(s) returned? if (body.errors) { // Stringify and reject promise return reject(new Error(util.inspect(body.errors))); } // Require 200 OK for success if (res.statusCode != 200 && res.statusCode != 204) { // Throw generic error return reject(new Error('An invalid response code was returned from the API: ' + res.statusCode)); } // Resolve promise with request body resolve(body); } // Expose the class object module.exports = CachetAPI;
1.265625
1
src/common/interceptors/loadingHandler/loadingHandler.js
amobbs/plog
0
1527
/** * Loading Handler * Count requests/responses. When there are active requests, start a timer. * If the timer goes above X seconds, send a broadcast for (loadingHandler.loading", true) (show dialog) * When the requests are completed, wait X milliseconds. * After X milliseconds, if there are no more requests, send a broadcast for (loadingHandler.loading", false) (close dialog) */ angular.module('loadingHandler', []) /** * LOADING_MIN_THRESHOLD: Minimum duration that must pass before the loading message is displayed * LOADING_MIN_DISPLAY_DURATION: Minimum time the loading message must be shown for. Prevents "flashes" of the loading screen. * LOADING_EXIT_GRACE: Grace period for Loading dialog dismissal. Prevents sequential requests resulting in the dialog being cleared. * * @integer - milliseconds */ .constant('LOADING_ENTRY_GRACE', 1000) // 1s .constant('LOADING_MIN_DISPLAY_DURATION', 1000) // 1s .constant('LOADING_EXIT_GRACE', 100)// 0.2s /** * Request handler */ .config(function($httpProvider, LOADING_ENTRY_GRACE, LOADING_MIN_DISPLAY_DURATION, LOADING_EXIT_GRACE) { var loading = false, // Loading process active? loadingDisplayed = false, // Loading panel visible? loadingGrace = false, // Grace period for dialog still active? numberOfRequests = 0, // Request # tracker entryTimer, // Timer for pending display graceTimer, // Timer for grace period; loader must be open for this period exitTimer, // Timer for pending hide /** * Increst requests * @param $rootScope * @param $timeout */ increaseRequest = function($rootScope, $timeout) { numberOfRequests++; // Only instigate the timer if if (!loading) { loading = true; // If visible if (!loadingDisplayed) { // Timer for entry activity entryTimer = $timeout(function() { // Mark as displayed, and grace period active. loadingDisplayed = true; loadingGrace = true; // Broadcast $rootScope.$broadcast('loadingHandler.loading', loading); // Instigate Exit Timer // Hide the dialog after grace period, if no longer loading. graceTimer = $timeout(function() { // Clear this timer loadingGrace = false; // If the dialog should be cleared (no load pending) if (!loading) { hideLoadingDialog($rootScope, $timeout); } }, LOADING_MIN_DISPLAY_DURATION); }, LOADING_ENTRY_GRACE); } } }, /** * Decrease requests until empty. * @param $rootScope * @param $timeout */ decreaseRequest = function($rootScope, $timeout) { if (loading) { numberOfRequests--; if (numberOfRequests === 0) { // cancel loader loading = false; // Clear loading timer if present $timeout.cancel(entryTimer); // If the dialog is still visible if (loadingDisplayed) { // If the grace period has passed already if (!loadingGrace) { // Clear loader hideLoadingDialog($rootScope, $timeout); } } } } }; /** * Hide the loading dialog * - Instigates a timer with a grace period. When grace passes, loader will be cleared. * @param $rootScope * @param $timeout */ hideLoadingDialog = function( $rootScope, $timeout ) { // Restart the timer $timeout.cancel(exitTimer); // Create timer exitTimer = $timeout(function() { // If the dialog should be cleared (no load pending) if (!loading) { // Hide display loadingDisplayed = false; $rootScope.$broadcast('loadingHandler.loading', loading); } }, LOADING_EXIT_GRACE); }; /** * Test for if the Loader should be executed for this url * Specify regex here for URLS you wish to exclude from the global loader. */ allowRequest = function (url) { var found = 0; found += RegExp('dashboards/[a-zA-Z0-9]+/widgets/[a-zA-Z0-9]+$').test(url); found += RegExp('search$').test(url); return !found; }; /** * HTTP Interceptor * - Add count of HTTP activity when a request is commenced * - Remove count of HTTP activity when a request completes or fails. * Note: $timeout is passed as it's unavailable where the functions are defined. */ $httpProvider.interceptors.push(['$q', '$rootScope', '$timeout', function($q, $rootScope, $timeout) { return { 'request': function(config) { if (allowRequest(config.url)) { increaseRequest($rootScope, $timeout); } return config || $q.when(config); }, 'requestError': function(rejection) { if (allowRequest(rejection.url)) { decreaseRequest($rootScope, $timeout); } return $q.reject(rejection); }, 'response': function(response) { if (allowRequest(response.url)) { decreaseRequest($rootScope, $timeout); } return response || $q.when(response); }, 'responseError': function(rejection) { if (allowRequest(rejection.url)) { decreaseRequest($rootScope, $timeout); } return $q.reject(rejection); } }; }]); }) ;
1.789063
2
test/bjorlingIntegration.js
bmavity/bjorling-nedb-storage
0
1535
var storage = require('../') , bjorling = require('bjorling') , fs = require('fs') , dbPath = './testdb/bjorlingIntegration.db' , eb = require('./eb') describe('bjorling storage integration, when retrieving projection state by id', function() { var state before(function(done) { var s = storage(dbPath + '1') , b = bjorling(__filename, { storage: s , key: 'storageId' }) b.when({ '$new': function(e) { return { storageId: e.storageId , count: 0 , ids: [] } } , 'FirstEvent': function(s, e) { s.count += 1 s.ids.push(e.eventId) } , 'SecondEvent': function(s, e) { s.count += 2 s.ids.push(e.eventId) } }) function getEntry() { b.get('abcdef', function(err, val) { if(err) return done(err) state = val done() }) } function addEvent(evt, cb) { b.processEvent(evt, cb) } setImmediate(function() { addEvent({ __type: 'SecondEvent' , data: { storageId: 'abcdef' , eventId: 1 } }, function() { addEvent({ __type: 'FirstEvent' , data: { storageId: 'abcdef' , eventId: 3 } }, getEntry) }) }) }) after(function(done) { fs.unlink(dbPath + '1', done) }) it('should have the proper count', function() { state.count.should.equal(3) }) it('should contain the first event id', function() { state.ids.should.include(3) }) it('should contain the second event id', function() { state.ids.should.include(1) }) }) describe('bjorling storage integration, when retrieving projection state by an index', function() { var state before(function(done) { var s = storage(dbPath + '2') , b = bjorling(__filename, { storage: s , key: 'storageId' }) b.addIndex('lockerId') b.when({ '$new': function(e) { return { storageId: e.storageId , count: 0 , ids: [] } } , 'FirstEvent': function(s, e) { s.count += 1 s.ids.push(e.eventId) } , 'SecondEvent': function(s, e) { s.count += 2 s.lockerId = e.lockerId s.ids.push(e.eventId) } , 'ThirdEvent': function(s, e) { s.count += 3 s.ids = [] } }) function getEntry() { b.get({ lockerId: 178 }, function(err, val) { if(err) return done(err) state = val done() }) } function addEvent(evt, cb) { b.processEvent(evt, cb) } setImmediate(function() { var e1 = { __type: 'FirstEvent' , data: { storageId: 'abcdef' , eventId: 3 } } , e2 = { __type: 'SecondEvent' , data: { storageId: 'abcdef' , lockerId: 178 , eventId: 1 } } , e3 = { __type: 'ThirdEvent' , data: { lockerId: 178 } } addEvent(e1, function() { addEvent(e2, function() { addEvent(e3, getEntry) }) }) }) }) after(function(done) { fs.unlink(dbPath + '2', done) }) it('should have the proper count', function() { state.count.should.equal(6) }) it('should not contain the first event id', function() { state.ids.should.not.include(3) }) it('should contain the second event id', function() { state.ids.should.not.include(1) }) })
1.796875
2
types/modelStatusTypes.js
measurify/model-registry
1
1543
const ModelStatusTypes = Object.freeze({ training: 'training', test: 'test', production: 'production' }); module.exports = ModelStatusTypes;
0.466797
0
backend/_lib/index.js
josiahakinloye/Latest-harchive
0
1551
//session management const session = require('express-session'); const MongoDBStore = require('connect-mongodb-session')(session); // express server setup const express = require('express'); const app = express(); const bodyParser = require('body-parser') const cors = require('cors'); const multer = require('multer'); var upload_profile_picture = multer({ dest: 'uploads/profile-picture'}); var upload_real_assets = multer({ dest: 'uploads/real-assets'}); // security package const helmet = require('helmet') // import from different files const wallet = require('./modules/wallet'); const user = require('./modules/registration'); const uniqueUser = require('./modules/uniqueUsername'); const asset = require('./modules/assets'); const friend = require('./modules/friends'); const email = require('./modules/email'); const blockchain = require('./modules/blockchain'); const autoAssetTransfer = require('./modules/autoAssetTransfer'); // initialisaction of session management and session store. var store = new MongoDBStore({ uri: 'mongodb://localhost:27017/will-management-system-test', collection: 'users_sessions_test' }); store.on('connected', function() { console.log('connected to session store'); // console.log(store.client); // The underlying MongoClient object from the MongoDB driver }); // Catch errors store.on('error', function(error) { console.log('error while connecting to session store.'); }); // cors enable app.use(cors()); // security app.use(helmet()); // parse application/json app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })); app.use(require('express-session')({ secret: 'will-management-system-key', cookie: { maxAge: 1000 * 60 * 60 * 24 // 1 day }, store: store, // Boilerplate options, see: // * https://www.npmjs.com/package/express-session#resave // * https://www.npmjs.com/package/express-session#saveuninitialized resave: false, saveUninitialized: false })); // ************* API CREATION ************ // // app.get('/', function(req, res) { // // console.log(req); // console.log(req.session); // // res.send('Hello ' + JSON.stringify(req.session)); // }); // REGISTRATION MODULE. app.post('/checkUniqueUser',function(req,res){ let username = req.body.username; let emailAddress = req.body.email; uniqueUser.checkUniqueness(username,emailAddress).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error"}); } }) }); app.post('/registerUser',upload_profile_picture.single('profile_picture'),(req,res) => { let userDetails = { image:req.file, other:req.body }; user.createUser(userDetails).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }); }) app.get('/verifyEmailAddress',(req,res)=>{ let user_id = req.query.id; let user_email = req.query.email; email.verifyEmailAddress(user_email,user_id).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }); }) app.get('/addNewDevice',(req,res)=>{ let user = req.query.username; let user_mac_address = req.query.mac_address; email.addNewDevice(user,user_mac_address).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }); }) app.post('/login',(req,res)=>{ let username = req.body.username; let password = <PASSWORD>; let macAddress = req.body.mac_address; user.userLogin(username,password,macAddress).then(function(response){ if(response.status == "success"){ // if(Object.prototype.hasOwnProperty.call(req.session,'users')){ // req.session.users.push({username:username}); // }else{ // req.session.users = []; // req.session.users.push({username:username}); // } res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }); }) app.post('/logout',(req,res)=>{ let username = req.body.username; user.checkAccountStatus(user).then(function(account_status_response){ if(account_status_response.status == "success"){ user.userLogout(username).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }); }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) // get user profile can be used multiple ways so no need to check for login and etc. app.post('/getUserProfile',(req,res)=>{ let username = req.body.username; user.getUserProfile(username).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }) app.post('/updateUserProfile',upload_profile_picture.single('profile_picture'),(req,res)=>{ let userDetails = { image:req.file, other:req.body }; user.checkAccountStatus(userDetails.other.username).then(function(account_status_response){ if(account_status_response.status == "success"){ user.updateProfile(userDetails).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.post('/deleteAccount',(req,res)=>{ let username = req.body.username; let accountStatus = req.body.accountStatus; user.checkAccountStatus(username).then(function(account_status_response){ if(account_status_response.status == "success"){ user.deleteAccount(username,accountStatus).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) // WALLET MODULE. app.post('/createWallet',function(req,res){ let username = req.body.username; user.checkAccountStatus(username).then(function(account_status_response){ if(account_status_response.status == "success"){ wallet.createWallet(username).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error"}); } }); }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }); // BLOCKCHAIN MODULE app.post('/getEtherBalance',function(req,res){ let username = req.body.username; let walletAddress = req.body.wallet_address; user.checkAccountStatus(username).then(function(account_status_response){ if(account_status_response.status == "success"){ blockchain.getEtherBalance(username,walletAddress).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.post('/createAssetInBlockchain',(req,res)=>{ let assetDetails = req.body; user.checkAccountStatus(assetDetails.username).then(function(account_status_response){ if(account_status_response.status == "success"){ blockchain.createAssetContract(assetDetails).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.post('/setContractData',(req,res)=>{ let assetDetails = req.body; user.checkAccountStatus(assetDetails.username).then(function(account_status_response){ if(account_status_response.status == "success"){ blockchain.setContractData(assetDetails).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.post('/getContractData',(req,res)=>{ let assetDetails = req.body; user.checkAccountStatus(assetDetails.username).then(function(account_status_response){ if(account_status_response.status == "success"){ blockchain.getContractData(assetDetails).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.post('/transferOwner',(req,res)=>{ let assetDetails = req.body; user.checkAccountStatus(assetDetails.username).then(function(account_status_response){ if(account_status_response.status == "success"){ blockchain.transferOwner(assetDetails).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) // ASSET MODULE. app.get('/autoAssetTransfer',(req,res)=>{ autoAssetTransfer.transfer().then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }) app.post('/createRealAsset',upload_real_assets.array('asset_images'),(req,res)=>{ let assetDetails = { asset_images:req.files, other_form_fields:req.body }; user.checkAccountStatus(assetDetails.other_form_fields.username).then(function(account_status_response){ if(account_status_response.status == "success"){ asset.createRealAssets(assetDetails).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.post('/updateRealAsset',upload_real_assets.array('asset_images'),(req,res)=>{ let assetDetails = { asset_images:req.files, other_form_fields:req.body }; user.checkAccountStatus(assetDetails.other_form_fields.username).then(function(account_status_response){ if(account_status_response.status == "success"){ asset.updateRealAsset(assetDetails).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.post('/createDigitalAsset',(req,res)=>{ let assetDetails = req.body; user.checkAccountStatus(assetDetails.username).then(function(account_status_response){ if(account_status_response.status == "success"){ asset.createDigitalAsset(assetDetails).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.post('/updateDigitalAsset',(req,res)=>{ let assetObject = req.body; user.checkAccountStatus(assetObject.username).then(function(account_status_response){ if(account_status_response.status == "success"){ asset.updateDigitalAsset(assetObject).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.post('/deleteAsset',(req,res)=>{ let username = req.body.username; let assetId = req.body.assetId; user.checkAccountStatus(username).then(function(account_status_response){ if(account_status_response.status == "success"){ asset.deleteAsset(username,assetId).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.post('/transferAsset',(req,res)=>{ let username = req.body.username; let assetId = req.body.asset_id; user.checkAccountStatus(username).then(function(account_status_response){ if(account_status_response.status == "success"){ asset.transferAsset(username,assetId).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.post('/addBeneficiary',(req,res)=>{ let beneficiaryDetails = req.body; user.checkAccountStatus(beneficiaryDetails.username).then(function(account_status_response){ if(account_status_response.status == "success"){ asset.addBeneficiary(beneficiaryDetails).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) // beneficiary or friend request module app.post('/addFriend',(req,res)=>{ let username = req.body.username; let friends_username = req.body.friend_username; user.checkAccountStatus(username).then(function(account_status_response){ if(account_status_response.status == "success"){ friend.addFriend(username,friends_username).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.post('/acceptFriendRequest',(req,res)=>{ let username = req.body.username; let friends_username = req.body.friend_username; user.checkAccountStatus(username).then(function(account_status_response){ if(account_status_response.status == "success"){ friend.acceptFriendRequest(username,friends_username).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.post('/removeFriend',(req,res)=>{ let username = req.body.username; let friends_username = req.body.friend_username; user.checkAccountStatus(username).then(function(account_status_response){ if(account_status_response.status == "success"){ friend.removeFriend(username,friends_username).then(function(response){ if(response.status == "success"){ res.status(200).send({status: "success",data:response.payload}); }else{ res.status(200).send({status: "error",data:response.payload}); } }) }else{ res.status(200).send({status: "error",data:account_status_response.payload}); } }) }) app.listen(9000,function(){ console.log("connection to server successfull"); });
1.375
1
test/test.js
mugetsu/ash
3
1559
var assert = require('assert'); describe('Find the One', function() { var person = 'Efrelyn'; var people = ['Randell', 'Efrelyn', 'Elise']; describe('Find ' + person, function() { it('should return 1 when ' + person + ' is the one', function() { assert.equal(1, ['Randell', 'Efrelyn', 'Elise'].indexOf(person)); }); }); });
1.375
1
Libraries/Utilities/differ/__tests__/deepDiffer-test.js
Buddhalow/react-native-astral
25
1567
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+react_native */ 'use strict'; var deepDiffer = require('deepDiffer'); describe('deepDiffer', function() { it('should diff primitives of the same type', () => { expect(deepDiffer(1, 2)).toBe(true); expect(deepDiffer(42, 42)).toBe(false); expect(deepDiffer('foo', 'bar')).toBe(true); expect(deepDiffer('foo', 'foo')).toBe(false); expect(deepDiffer(true, false)).toBe(true); expect(deepDiffer(false, true)).toBe(true); expect(deepDiffer(true, true)).toBe(false); expect(deepDiffer(false, false)).toBe(false); expect(deepDiffer(null, null)).toBe(false); expect(deepDiffer(undefined, undefined)).toBe(false); }); it('should diff primitives of different types', () => { expect(deepDiffer(1, '1')).toBe(true); expect(deepDiffer(true, 'true')).toBe(true); expect(deepDiffer(true, 1)).toBe(true); expect(deepDiffer(false, 0)).toBe(true); expect(deepDiffer(null, undefined)).toBe(true); expect(deepDiffer(null, 0)).toBe(true); expect(deepDiffer(null, false)).toBe(true); expect(deepDiffer(null, '')).toBe(true); expect(deepDiffer(undefined, 0)).toBe(true); expect(deepDiffer(undefined, false)).toBe(true); expect(deepDiffer(undefined, '')).toBe(true); }); it('should diff Objects', () => { expect(deepDiffer({}, {})).toBe(false); expect(deepDiffer({}, null)).toBe(true); expect(deepDiffer(null, {})).toBe(true); expect(deepDiffer({a: 1}, {a: 1})).toBe(false); expect(deepDiffer({a: 1}, {a: 2})).toBe(true); expect(deepDiffer({a: 1}, {a: 1, b: null})).toBe(true); expect(deepDiffer({a: 1}, {a: 1, b: 1})).toBe(true); expect(deepDiffer({a: 1, b: 1}, {a: 1})).toBe(true); expect(deepDiffer({a: {A: 1}, b: 1}, {a: {A: 1}, b: 1})).toBe(false); expect(deepDiffer({a: {A: 1}, b: 1}, {a: {A: 2}, b: 1})).toBe(true); expect(deepDiffer( {a: {A: {aA: 1, bB: 1}}, b: 1}, {a: {A: {aA: 1, bB: 1}}, b: 1} )).toBe(false); expect(deepDiffer( {a: {A: {aA: 1, bB: 1}}, b: 1}, {a: {A: {aA: 1, cC: 1}}, b: 1} )).toBe(true); }); it('should diff Arrays', () => { expect(deepDiffer([], [])).toBe(false); expect(deepDiffer([], null)).toBe(true); expect(deepDiffer(null, [])).toBe(true); expect(deepDiffer([42], [42])).toBe(false); expect(deepDiffer([1], [2])).toBe(true); expect(deepDiffer([1, 2, 3], [1, 2, 3])).toBe(false); expect(deepDiffer([1, 2, 3], [1, 2, 4])).toBe(true); expect(deepDiffer([1, 2, 3], [1, 4, 3])).toBe(true); expect(deepDiffer([1, 2, 3, 4], [1, 2, 3])).toBe(true); expect(deepDiffer([1, 2, 3], [1, 2, 3, 4])).toBe(true); expect(deepDiffer([0, null, false, ''], [0, null, false, ''])).toBe(false); expect(deepDiffer([0, null, false, ''], ['', false, null, 0])).toBe(true); }); it('should diff mixed types', () => { expect(deepDiffer({}, [])).toBe(true); expect(deepDiffer([], {})).toBe(true); expect(deepDiffer( {a: [{A: {aA: 1, bB: 1}}, 'bar'], c: [1, [false]]}, {a: [{A: {aA: 1, bB: 1}}, 'bar'], c: [1, [false]]} )).toBe(false); expect(deepDiffer( {a: [{A: {aA: 1, bB: 1}}, 'bar'], c: [1, [false]]}, {a: [{A: {aA: 1, bB: 2}}, 'bar'], c: [1, [false]]} )).toBe(true); expect(deepDiffer( {a: [{A: {aA: 1, bB: 1}}, 'bar'], c: [1, [false]]}, {a: [{A: {aA: 1, bB: 1}}, 'bar'], c: [1, [false], null]} )).toBe(true); expect(deepDiffer( {a: [{A: {aA: 1, bB: 1}}, 'bar'], c: [1, [false]]}, {a: [{A: {aA: 1, bB: 1}}, ['bar']], c: [1, [false]]} )).toBe(true); }); it('should distinguish between proper Array and Object', () => { expect(deepDiffer(['a', 'b'], {0: 'a', 1: 'b', length: 2})).toBe(true); expect(deepDiffer(['a', 'b'], {length: 2, 0: 'a', 1: 'b'})).toBe(true); }); it('should diff same object', () => { var obj = [1,[2,3]]; expect(deepDiffer(obj, obj)).toBe(false); }); });
1.414063
1
ddp-redux/src/DDPError.js
apendua/ddp
7
1575
// Based on Meteor's EJSON implementation: https://github.com/meteor/meteor // // packages/meteor/errors.js // 2017-08-10 // // The MIT License (MIT) // // Copyright (c) 2011 - 2017 Meteor Development Group, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. class DDPError extends Error { constructor(error, reason, details) { super(); // Ensure we get a proper stack trace in most Javascript environments if (Error.captureStackTrace) { // V8 environments (Chrome and Node.js) Error.captureStackTrace(this, DDPError); } else { // Borrow the .stack property of a native Error object. this.stack = new Error().stack; } // Safari magically works. // Newer versions of DDP use this property to signify that an error // can be sent back and reconstructed on the calling client. this.isClientSafe = true; // String code uniquely identifying this kind of error. this.error = error; // Optional: A short human-readable summary of the error. Not // intended to be shown to end users, just developers. ("Not Found", // "Internal Server Error") this.reason = reason; // Optional: Additional information about the error, say for // debugging. It might be a (textual) stack trace if the server is // willing to provide one. The corresponding thing in HTTP would be // the body of a 404 or 500 response. (The difference is that we // never expect this to be shown to end users, only developers, so // it doesn't need to be pretty.) this.details = details; // This is what gets displayed at the top of a stack trace. Current // format is "[404]" (if no reason is set) or "File not found [404]" if (this.reason) { this.message = `${this.reason} [${this.error}]`; } else { this.message = `[${this.error}]`; } this.errorType = 'Meteor.Error'; } // Meteor.Error is basically data and is sent over DDP, so you should be able to // properly EJSON-clone it. This is especially important because if a // Meteor.Error is thrown through a Future, the error, reason, and details // properties become non-enumerable so a standard Object clone won't preserve // them and they will be lost from DDP. clone() { return new DDPError(this.error, this.reason, this.details); } } DDPError.ERROR_CONNECTION = 'ErrorConnection'; DDPError.ERROR_BAD_MESSAGE = 'ErrorBadMessage'; export default DDPError;
1.460938
1
build/task/build/config/webpack.test.conf.js
linmingdao/v-bonjure
9
1583
const path = require('path'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const OptimizeCssnanoPlugin = require('@intervolga/optimize-cssnano-plugin'); function base(commonBase) { return { // 公共的配置信息 ...commonBase, // 启用source-map devtool: 'cheap-eval-source-map' }; } function output(pathInfo) { return { path: pathInfo['app_dist'], filename: 'js/index.bundle.[chunkhash].js', // 上线该配置需要配置成线上地址 publicPath: '/' }; } function plugins(pathInfo, commonPlugins, env) { return [ new CleanWebpackPlugin([env], { root: path.resolve(pathInfo['app_dist'], '..'), verbose: true, dry: false }), // 公共插件配置 ...commonPlugins, new OptimizeCssnanoPlugin({ sourceMap: true, compress: { warnings: false, drop_console: true }, cssnanoOptions: { preset: [ 'default', { discardComments: { removeAll: true } } ] } }) ]; } function rules(commonRules) { return [ // 公共规则配置 ...commonRules ]; } /** * 测试环境应用打包构建配置文件 */ module.exports = { /** * 获取对应环境的webpack编译打包配置信息 * @param {Object} env * @param {Object} appInfo * @param {Object} pathInfo * @param {String} analyzer */ getConfig({ env, appInfo, pathInfo, analyzer }) { // 获取webpack公共配置 const baseConfig = require('./webpack.base.conf').getConfig({ appInfo, pathInfo, analyzer }); return { // 基础配置 ...base(baseConfig.base), // 应用打包出口 output: output(pathInfo), // 插件配置 plugins: plugins(pathInfo, baseConfig.plugins, env), module: { // 规则配置 rules: rules(baseConfig.rules) } }; } };
1.40625
1
frontend/lost/src/coreui_containers/TheLayout.js
JonasGoebel/lost
490
1591
import React, { useEffect, useState, useRef } from 'react' import { useDispatch } from 'react-redux' import jwtDecode from 'jwt-decode' import { useHistory } from 'react-router-dom' import { useTranslation } from 'react-i18next' import axios from 'axios' import TheContent from './TheContent' import TheSidebar from './TheSidebar' import TheFooter from './TheFooter' import TheHeader from './TheHeader' import guiSetup from '../guiSetup' import actions from '../actions' const TheLayout = () => { const role = useRef() const history = useHistory() const dispatch = useDispatch() const [navItems, setNavItems] = useState([]) const [routes, setRoutes] = useState([]) const { i18n } = useTranslation() useEffect(() => { const token = localStorage.getItem('token') if (token) { axios.defaults.headers.common.Authorization = `Bearer ${localStorage.getItem('token')}` const { roles } = jwtDecode(token).user_claims role.current = roles[0] if (!guiSetup[role.current]) { throw new Error(`Role ${role.current} not found in Gui Setup`) } else { const roles = Object.keys(guiSetup).filter((e) => e !== 'additionalRoutes') dispatch(actions.setRoles(roles)) const newRoutes1 = guiSetup[role.current].navItems.map((navItem) => ({ path: navItem.to, name: navItem, component: navItem.component, })) let newRoutes2 = [] if (guiSetup.additionalRoutes) { newRoutes2 = guiSetup.additionalRoutes.map((route) => ({ path: route.path, name: route.path, exact: route.exact, component: route.component, })) } const newRoutes = [...newRoutes1, ...newRoutes2] setRoutes(newRoutes) dispatch(actions.setOwnUser()) dispatch(actions.getVersion()) if(history.location.pathname === '/'){ history.push(guiSetup[role.current].redirect) } } } else { history.push('/login') } }, []) useEffect(() => { const token = localStorage.getItem('token') if (token) { // ??? const navItemsFiltered = guiSetup[role.current].navItems.map( ({ component, ...navItem }) => { const name = i18n.language === 'de' && navItem.de_name ? navItem.de_name : navItem.name if (navItem.title) { return { _tag: 'CSidebarNavTitle', _children: [name], } } return { _tag: 'CSidebarNavItem', ...navItem, name, } }, ) setNavItems(navItemsFiltered) } }, [i18n.language]) return ( <div className="c-app c-default-layout"> <TheSidebar navItems={navItems} /> <div className="c-wrapper"> <TheHeader numNavItems={navItems.length}/> <div className="c-body"> <TheContent routes={routes} /> </div> <TheFooter /> </div> </div> ) } export default TheLayout
1.546875
2
resources/viewer.js
isaac-utilizecore/Compliancy
0
1599
function createViewer(story, files) { return { highlightLinks: story.highlightLinks, prevPageIndex: -1, lastRegularPage: -1, currentPage : -1, currentPageOverlay : false, prevPageOverlayIndex : -1, backStack: [], cache: [], urlLastIndex: -1, files: files, initialize: function() { this.createImageMaps(); this.addHotkeys(); this.initializeHighDensitySupport(); }, initializeHighDensitySupport: function() { if (window.matchMedia) { this.hdMediaQuery = window .matchMedia("only screen and (min--moz-device-pixel-ratio: 1.1), only screen and (-o-min-device-pixel-ratio: 2.2/2), only screen and (-webkit-min-device-pixel-ratio: 1.1), only screen and (min-device-pixel-ratio: 1.1), only screen and (min-resolution: 1.1dppx)"); var v = this; this.hdMediaQuery.addListener(function(e) { v.refresh(); }); } }, isHighDensityDisplay: function() { return (this.hdMediaQuery && this.hdMediaQuery.matches || (window.devicePixelRatio && window.devicePixelRatio > 1)); }, createImageMaps: function() { var div = $('<div/>', { 'class': 'hidden' }); var pages = story.pages; for(var i = 0; i < pages.length; i ++) { var page = pages[i]; var name = 'map' + i; var map = $('<map/>', { id: name, type: "'"+page.type+"'", name: name }); for(var j = page.links.length - 1; j >= 0; j --) { var link = page.links[j]; var title, href, target; if(link.page != null) { title = story.pages[link.page].title; href = 'javascript:viewer.goTo(' + link.page + ')'; target = null; } else if(link.action != null && link.action == 'back') { title = "Go Back"; href = 'javascript:viewer.goBack()'; target = null; } else if(link.url != null){ title = link.url; href = link.url; target = link.target!=null?link.target:null; } $('<area/>', { shape: 'rect', coords: link.rect.join(','), href: href, alt: title, title: title, target: target }).appendTo(map); } map.appendTo(div); } div.appendTo('body'); }, addHotkeys: function() { var v = this; $(document).bind('keydown', 'right space return', function() { v.next(); }); $(document).bind('keydown', 'left backspace', function() { v.previous(); }); $(document).bind('keydown', 'shift', function() { v.toggleLinks(); }); $(document).bind('keydown', 'g', function() { gallery.toogle(); }); $(document).bind('keydown', 's', function() { v.goToPage(0); }); }, getPageHash: function(index) { var image = story.pages[index].image; return image.substring(0, image.length - 4); // strip .png suffix }, getPageHashes: function() { if(this.pageHashes == null) { var hashes = {}; var pages = story.pages; for(var i = 0; i < pages.length; i ++) { hashes[this.getPageHash(i)] = i; } this.pageHashes = hashes; } return this.pageHashes; }, getOverlayFirstParentPageIndex: function(overlayIndex){ var page = null; var link = null; for(var i=story.pages.length-1; i>=0 ;i --) { page = story.pages[i]; if(page.type==='overlay') continue; for(var li = 0; li < page.links.length; li ++) { link = page.links[li]; if(link.page!=null && link.page==overlayIndex){ // return the page index which has link to overlay return i; } } } // return first prototype page return 0; }, getPageIndex: function(page) { var index; if (typeof page === "number") { index = page; } else if (page === "") { index = 0; } else { index = this.getPageHashes()[page]; if (index==undefined) { var pageNumber = parseInt(page); if (isNaN(pageNumber)) index = 0; else index = pageNumber - 1; } } return index; }, goBack: function() { if(this.backStack.length>0){ this.goTo(this.backStack[this.backStack.length-1]); this.backStack.shift(); }else{ window.history.back(); } }, goToPage : function(page) { this.clear_context(); this.goTo(page); }, goTo : function(page,refreshURL=true) { var index = this.getPageIndex(page); if(!this.currentPageOverlay && this.currentPage>=0){ this.backStack.push(this.currentPage); } this.currentPageOverlay = false; this.prevPageOverlayIndex = -1; if(index <0 || index == this.currentPage || index >= story.pages.length) return; var newPage = story.pages[index]; if(newPage.type==="overlay"){ // no any page to overlay, need to find something if(this.currentPage==-1){ parentIndex = this.getOverlayFirstParentPageIndex(index); this.goTo(parentIndex); this.prevPageOverlayIndex = parentIndex; }else{ this.prevPageOverlayIndex = this.currentPage; } this.currentPageOverlay = true; }else{ this.currentPageOverlay = false; } this.prevPageIndex = this.currentPage; this.refresh_adjust_content_layer(index); this.refresh_show_or_create_img(index,true); this.refresh_switch_overlay_layer(index); this.refresh_update_navbar(index); if(refreshURL) this.refresh_url(index) this.currentPage = index; if(story.pages[index].type!="overlay"){ this.lastRegularPage = index; } }, refresh_update_navbar: function(pageIndex) { var page = story.pages[pageIndex]; $('#nav .title').html((pageIndex+1) + '/' + story.pages.length + ' - ' + page.title); $('#nav-left-prev').toggleClass('disabled', !this.hasPrevious(pageIndex)); $('#nav-left-next').toggleClass('disabled', !this.hasNext(pageIndex)); if(this.hasPrevious(pageIndex)) { $('#nav-left-prev a').attr('title', story.pages[pageIndex - 1].title); } else { $('#nav-left-prev a').removeAttr('title'); } if(this.hasNext(pageIndex)) { $('#nav-left-next a').attr('title', story.pages[pageIndex + 1].title); } else { $('#nav-left-next a').removeAttr('title'); } $('#nav-right-hints').toggleClass('disabled', page.annotations==undefined); this.refresh_update_links_toggler(pageIndex); }, refresh_url: function(pageIndex) { var page = story.pages[pageIndex]; this.urlLastIndex = pageIndex $(document).attr('title', story.title + ': ' + page.title) location.hash = '#' + encodeURIComponent(this.getPageHash(pageIndex)) }, refresh_update_links_toggler: function(pageIndex) { var page = story.pages[pageIndex]; $('#nav-right-links').toggleClass('active', this.highlightLinks); $('#nav-right-links').toggleClass('disabled', page.links.length == 0); }, refresh_hide_last_image: function(pageIndex){ var page = story.pages[pageIndex]; var content = $('#content'); var contentOverlay = $('#content-overlay'); var isOverlay = page.type==="overlay"; // hide last regular page to show a new regular after ovelay if(!isOverlay && this.lastRegularPage>=0 && this.lastRegularPage!=pageIndex){ var lastPage = $('#img_'+this.lastRegularPage); if(lastPage.length) lastPage.parent().addClass('hidden'); } // hide last overlay var prevPageWasOverlay = this.prevPageIndex>=0 && story.pages[this.prevPageIndex].type==="overlay"; if(prevPageWasOverlay){ var prevImg = $('#img_'+this.prevPageIndex); if(prevImg.length){ prevImg.parent().addClass('hidden'); } } }, refresh_adjust_content_layer: function(pageIndex){ var page = story.pages[pageIndex]; if(page.type=="overlay") return; var contentShadow = $('#content-shadow'); var contentOverlay = $('#content-overlay'); var content = $('#content'); var prevPageWasOverlay = this.prevPageIndex>=0 && story.pages[this.prevPageIndex].type==="overlay"; if(prevPageWasOverlay){ contentShadow.addClass('hidden'); contentOverlay.addClass('hidden'); } content.width(page.width); content.height(page.height); contentShadow.width(page.width); contentShadow.height(page.height); contentOverlay.width(page.width); //contentOverlay.height(page.height) }, refresh_switch_overlay_layer: function(pageIndex){ var page = story.pages[pageIndex]; var lastMainPage = story.pages[this.lastRegularPage]; if(page.type!="overlay") return; var isOverlayShadow = page.overlayShadow==1; var contentOverlay = $('#content-overlay'); var contentShadow = $('#content-shadow'); if(isOverlayShadow){ contentShadow.removeClass('no-shadow'); contentShadow.addClass('shadow'); contentShadow.removeClass('hidden'); }else{ contentOverlay.addClass('hidden'); } contentOverlay.removeClass('hidden'); }, refresh_show_or_create_img: function(pageIndex,hideLast=false){ var img = $('#img_'+pageIndex); var page = story.pages[pageIndex]; var isOverlay = page.type==="overlay"; if(isOverlay){ var contentOverlay = $('#content-overlay'); contentOverlay.width(page.width); } if(img.length){ if(hideLast) this.refresh_hide_last_image(pageIndex); img.parent().removeClass('hidden'); }else{ this.refresh_recreate_img(pageIndex,hideLast); } }, clear_context_hide_all_images: function(){ var page = story.pages[this.currentPage]; var content = $('#content'); var contentOverlay = $('#content-overlay'); var contentShadow = $('#content-shadow'); var isOverlay = page.type==="overlay"; contentShadow.addClass('hidden'); contentOverlay.addClass('hidden'); // hide last regular page if(this.lastRegularPage>=0){ var lastPage = $('#img_'+this.lastRegularPage); if(lastPage.length) lastPage.parent().addClass('hidden'); } // hide current overlay if(isOverlay){ var overlayImg = $('#img_'+this.currentPage); if(overlayImg.length) overlayImg.parent().addClass('hidden'); } }, clear_context: function(){ this.clear_context_hide_all_images() this.prevPageIndex = -1 this.lastRegularPage = -1 this.currentPage = -1 this.currentPageOverlay = false this.prevPageOverlayIndex = -1 this.backStack = [] }, refresh: function(){ this.refresh_recreate_img(this.currentPage); }, refresh_recreate_img: function(pageIndex,hideLast=false){ var page = story.pages[pageIndex]; // remove old var img = $('#img_' + pageIndex); if(img.length){ img.parent().remove(); img = null; } // create new img var hasRetinaImages = $.inArray(2, story.resolutions) != -1; var imageURI = hasRetinaImages && this.isHighDensityDisplay() ? page.image2x : page.image; var isOverlay = page.type==="overlay"; var content = $('#content'); var contentOverlay = $('#content-overlay'); var highlight = this.highlightLinks; var viewer = this; img = $('<img/>', { id : "img_"+pageIndex, src : encodeURIComponent(files) + '/' + encodeURIComponent(imageURI), usemap: '#map' + pageIndex, }).attr('width', page.width).attr('height', page.height); img.one('load', function() { if(hideLast) viewer.refresh_hide_last_image(pageIndex); img.appendTo(isOverlay?contentOverlay:content); img.maphilight({ alwaysOn: highlight, stroke: false, fillColor: 'FFC400', fillOpacity: 100.0/255 }); }).each(function() { $(this).trigger('load'); }); }, next : function() { if (this.hasNext(this.currentPage)){ const index = this.currentPage + 1; this.goToPage(index); } }, previous : function() { if (this.hasPrevious(this.currentPage)){ const index = this.currentPage - 1; this.goToPage(index); } }, hasNext : function(pageIndex) { return pageIndex < story.pages.length - 1; }, hasPrevious : function(pageIndex) { return pageIndex > 0; }, toggleLinks : function() { this.highlightLinks = !this.highlightLinks; this.refresh_update_links_toggler(this.currentPage); this.refresh_recreate_img(this.currentPage); }, showHints : function(){ var text = story.pages[this.currentPage].annotations; if(text==undefined) return; alert(text); }, hideNavbar : function() { $('#nav').slideToggle('fast', function() { $('#nav-hide').slideToggle('fast').removeClass('hidden'); }); }, showNavbar : function() { $('#nav-hide').slideToggle('fast', function() { $('#nav').slideToggle('fast'); }).addClass('hidden'); } }; } // ADD | REMOVE CLASS // mode ID - getELementByID // mode CLASS - getELementByClassName function addRemoveClass(mode, el, cls) { var el; switch(mode) { case 'class': el = document.getElementsByClassName(el)[0]; break; case 'id': el = document.getElementById(el); break; } if (el.classList.contains(cls)) { el.classList.remove(cls) } else { el.classList.add(cls); } } $(document).ready(function() { viewer.initialize(); gallery.initialize(); if(!!('ontouchstart' in window) || !!('onmsgesturechange' in window)) { $('body').removeClass('screen'); } var hash = location.hash; if(hash == null || hash.length == 0) hash = '#'; hash = '#' + hash.replace( /^[^#]*#?(.*)$/, '$1' ); var page = decodeURIComponent(hash.substring(1)); viewer.goTo(page); $(window).hashchange(function(e) { var hash = location.hash; if(hash == null || hash.length == 0) hash = '#'; hash = '#' + hash.replace( /^[^#]*#?(.*)$/, '$1' ); var page = decodeURIComponent(hash.substring(1)); var pageIndex = viewer.getPageIndex(page); if(viewer.urlLastIndex==pageIndex){ return } viewer.clear_context(); viewer.goTo(page,false); viewer.urlLastIndex= pageIndex }); $(window).hashchange(); });
1.554688
2
CSS Advanced/lazy/lazy/gulpfile.js
MartinValchevv/Front-End-Development-2018
0
1607
var gulp = require('gulp'); var browserSync = require('browser-sync').create(); var $ = require('gulp-load-plugins')(); var path = { SCSS_SRC : './scss/**/*.scss', SCSS_DST : './css', CSS_JKDST : './docs/css', HTML_SRC : ['./*.html','./_post/*.*','./_layouts/*.*', './_includes/*.*'], } gulp.task('scss', function () { gulp.src( path.SCSS_SRC ) .pipe($.sourcemaps.init()) .pipe($.sass()) .pipe($.autoprefixer({ browsers: ['last 2 versions'], cascade: false })) .pipe($.size({ showFiles: true })) .pipe($.csso()) .pipe($.size({ showFiles: true })) .pipe($.sourcemaps.write('map')) .pipe(gulp.dest( path.SCSS_DST )) .pipe(gulp.dest( path.CSS_JKDST )) .pipe(browserSync.stream({ match: '**/*.css' })) ; }); gulp.task('jekyll', function () { require('child_process').exec('jekyll build --baseurl=', {stdio: 'inherit'}, function(){ browserSync.reload(); }); }); gulp.task('serve', function() { // browserSync.init({ // proxy: { // target: "http://127.0.0.1:4000/" // } // }); //browserSync.init({ //server: { //baseDir: "./docs/" //} //}); gulp.watch(path.SCSS_SRC, ['scss']); // gulp.watch(path.HTML_SRC, ['jekyll']); gulp.watch(path.HTML_SRC).on('change', browserSync.reload); }); gulp.task('default', ['scss','jekyll','serve']);
1.226563
1