hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
529e412082402419b1876c2637ca39bedc9387ef
3,951
js
JavaScript
packages/cli/core/plugins/parser/component.js
dev-itsheng/wepy
b8e43f6dd2d25f324443b592a3e42521562ff2d1
[ "BSD-3-Clause" ]
20,287
2017-11-29T11:56:49.000Z
2022-03-31T09:08:18.000Z
packages/cli/core/plugins/parser/component.js
dev-itsheng/wepy
b8e43f6dd2d25f324443b592a3e42521562ff2d1
[ "BSD-3-Clause" ]
2,153
2017-11-29T14:30:55.000Z
2022-03-31T09:05:44.000Z
packages/cli/core/plugins/parser/component.js
dev-itsheng/wepy
b8e43f6dd2d25f324443b592a3e42521562ff2d1
[ "BSD-3-Clause" ]
3,194
2017-11-29T11:07:26.000Z
2022-03-31T04:27:35.000Z
/** * Tencent is pleased to support the open source community by making WePY available. * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ const fs = require('fs'); const path = require('path'); const CONST = require('../../util/const'); const wxmlAst = require('../../ast/wxml'); const readFile = (file, defaultValue = '') => { if (fs.existsSync(file)) { return fs.readFileSync(file, 'utf-8'); } return defaultValue; }; exports = module.exports = function() { this.register('wepy-parser-component', function(comp) { let parsedPath = path.parse(comp.path); let file = path.join(parsedPath.dir, parsedPath.name); let sfc = { styles: [], script: {}, template: {} }; let context = { sfc: sfc, file: file, npm: comp.npm, component: true, type: 'weapp' // This is a weapp original component }; let weappCacheKey = file + CONST.WEAPP_EXT; if (!this.compiled[weappCacheKey]) { this.compiled[weappCacheKey] = comp; } this.fileDep.addDeps(weappCacheKey); sfc.styles[0] = { content: readFile(file + '.wxss'), type: 'style', lang: 'wxss' }; sfc.template = { content: readFile(file + '.wxml'), type: 'template', lang: 'wxml' }; // JS file should be there. sfc.script = { content: readFile(file + '.js', 'Page({})'), type: 'script', lang: 'babel' }; sfc.config = { content: readFile(file + '.json', '{}'), type: 'config', lang: 'json' }; let flow = Promise.resolve(true); let templateContent = sfc.template.content; if (templateContent.indexOf('<wxs ') > -1) { // wxs tag inside let templateAst = wxmlAst(sfc.template.content); sfc.wxs = []; flow = templateAst.then(ast => { let checkSrc = false; wxmlAst.walk(ast, { name: { wxs(item) { if (item.type === 'tag' && item.name === 'wxs') { if (item.attribs.src) { checkSrc = true; } sfc.wxs.push({ attrs: item.attribs, src: checkSrc ? item.attribs.src : '', lang: 'js', type: 'wxs', content: wxmlAst.generate(item.children) }); // Remove node; item.data = ''; item.children = []; item.type = 'text'; } } } }); if (checkSrc) { // has wxs with src, reset wxml sfc.template.content = wxmlAst.generate(ast); } return checkSrc ? this.hookAsyncSeq('parse-sfc-src', context) : true; }); } return flow .then(() => { if (sfc.wxs) { return Promise.all( sfc.wxs.map(wxs => { return this.applyCompiler(wxs, context); }) ); } }) .then(() => { return this.applyCompiler(sfc.config, context); }) .then(() => { return this.applyCompiler(sfc.template, context); }) .then(() => { return this.applyCompiler(sfc.script, context); }) .then(parsed => { sfc.script.parsed = parsed; return this.applyCompiler(sfc.styles[0], context); }) .then(() => context); }); };
28.630435
308
0.537839
529fa0d124395c6eaf673292815e7ecc2ffccbfc
27
js
JavaScript
app/Views/home/home.module.js
christopher-alba/angularjs-todolist-client
e7b92ca76a1b06f98e03ae1bc0a7b1ace49df99d
[ "MIT" ]
null
null
null
app/Views/home/home.module.js
christopher-alba/angularjs-todolist-client
e7b92ca76a1b06f98e03ae1bc0a7b1ace49df99d
[ "MIT" ]
null
null
null
app/Views/home/home.module.js
christopher-alba/angularjs-todolist-client
e7b92ca76a1b06f98e03ae1bc0a7b1ace49df99d
[ "MIT" ]
null
null
null
angular.module("home", []);
27
27
0.62963
529fa5530bab394ab9e421a6d6214fc3faf15f5e
12,619
js
JavaScript
functions/webhooks/cashfree.js
amarjeet045/backend-cloud-functions
399f936b6da60b26a128097270ffee603b4ef8a7
[ "MIT" ]
null
null
null
functions/webhooks/cashfree.js
amarjeet045/backend-cloud-functions
399f936b6da60b26a128097270ffee603b4ef8a7
[ "MIT" ]
null
null
null
functions/webhooks/cashfree.js
amarjeet045/backend-cloud-functions
399f936b6da60b26a128097270ffee603b4ef8a7
[ "MIT" ]
null
null
null
/** * Copyright (c) 2018 GrowthFile * * 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. * */ 'use strict'; const { rootCollections, db } = require('../admin/admin'); const { subcollectionNames, addendumTypes } = require('../admin/constants'); const { handleError, sendJSON, maskLastDigits } = require('../admin/utils'); const { requestBatchTransfer } = require('../cash-free/payout'); const currencyJs = require('currency.js'); const crypto = require('crypto'); const momentTz = require('moment-timezone'); const env = require('../admin/env'); const depositEvents = new Set([ 'AMOUNT_SETTLED', 'AMOUNT_COLLECTED', 'TRANSFER_REJECTED', ]); const paymentEvents = new Set([ 'TRANSFER_FAILED', 'TRANSFER_SUCCESS', 'TRANSFER_REVERSED', 'LOW_BALANCE_ALERT', 'CREDIT_CONFIRMATION', 'TRANSFER_ACKNOWLEDGED', 'INVALID_BENEFICIARY_ACCOUNT', ]); const paymentTypes = { SALARY: 'SALARY', REIMBURSEMENT: 'REIMBURSEMENT' }; const getClientSecret = isPaymentEvent => { if (isPaymentEvent) { return env.cashFree.payout.clientSecret; } return env.cashFree.autocollect.clientSecret; }; const verifyWebhookPost = webhookData => { let concatenatedValues = ''; const { signature: receivedSignature, event } = webhookData; const isPaymentEvent = paymentEvents.has(event); delete webhookData.signature; Object.keys(webhookData) .sort() .forEach(key => (concatenatedValues += `${webhookData[key]}`)); const calculatedSignature = crypto .createHmac('sha256', getClientSecret(isPaymentEvent)) .update(concatenatedValues) .digest('base64'); return calculatedSignature === receivedSignature; }; const getPaymentObjectForUpdates = ({ payment, id }) => { const { createdAt, office, officeId, amount, cycleStart, cycleEnd, ifsc, account, // last 4 digits // status, paymentType, utr = null, } = payment; const { date, months: month, years: year } = momentTz(createdAt).toObject(); const getPaymentStatus = () => { return ''; }; return { date, month, year, office, officeId, key: momentTz() .date(date) .month(month) .year(year) .startOf('date') .valueOf(), id: `${date}${month}${year}${id}`, timestamp: Date.now(), _type: addendumTypes.PAYMENT, currency: 'INR', details: { utr, ifsc, amount, cycleStart, cycleEnd, status: getPaymentStatus(), account: maskLastDigits(account, 4, 'X'), type: paymentType, // salary/attendance }, }; }; const handlePayment = async requestBody => { // payment // 'TRANSFER_FAILED', // 'TRANSFER_SUCCESS', // 'TRANSFER_REVERSED', // 'LOW_BALANCE_ALERT', // 'CREDIT_CONFIRMATION', // 'TRANSFER_ACKNOWLEDGED', /** * Send flag to user in `/now`. * Delete bank account in `Updates/{uid}` of this user. * Create doc in Updates/{uid}/Addendum/{autoId} with _type = "payment" * last 4 digits of bankAccount in `Payroll`. */ const { event, // The `transferId` is the same as the `voucherId` transferId, signature, } = requestBody; const batch = db.batch(); /** * PaymentDoc will always exist because we are creating it when * during the deposit webhook flow. */ const paymentDoc = await rootCollections.payments.doc(transferId).get(); const paymentData = paymentDoc.data(); paymentData.events = paymentData.events || []; /** * Test the duplication before pushing the current event into the events array. */ const isRepeatedEvent = paymentData.events.findIndex( ({ signature: payloadSignature }) => payloadSignature === signature, ) > -1; paymentData.events.push(requestBody); if (isRepeatedEvent) { batch.set(paymentDoc.ref, paymentData, { merge: true }); return batch.commit(); } // transfer completed successfully. const { officeId } = paymentDoc.data(); const voucherDoc = await rootCollections.offices .doc(officeId) .collection(subcollectionNames.VOUCHERS) .doc(transferId) .get(); batch.set( paymentDoc.ref, Object.assign({}, paymentData, { cycleStart: voucherDoc.get('cycleStart'), cycleEnd: voucherDoc.get('cycleEnd'), updatedAt: Date.now(), }), { merge: true }, ); // Voucher update with status batch.set( voucherDoc.ref, Object.assign({}, voucherDoc.data(), { status: event, updatedAt: Date.now(), }), { merge: true }, ); const { beneficiaryId } = voucherDoc.data(); const updatesRef = rootCollections.updates .doc(beneficiaryId) .collection(subcollectionNames.ADDENDUM) .doc(); batch.set( updatesRef, getPaymentObjectForUpdates({ payment: paymentData, id: paymentDoc.id }), ); return batch.commit(); }; const handleDeposit = async requestBody => { const batch = db.batch(); const { vAccountId, signature, // event, amount: amountInWebhook, } = requestBody; const { docs: [batchDoc], } = await rootCollections.batches .where('batchId', '==', vAccountId) .limit(1) .get(); const { office, officeId, linkedDeposits = [], linkedVouchers = [], } = batchDoc.data(); const bankDetailsMap = new Map().set(env.mainOffice.officeId, env.mainOffice); const expectedAmount = currencyJs(batchDoc.get('amount')); const currentlyReceivedAmount = currencyJs(amountInWebhook); const usersWithoutPaymentAccount = []; const { docs: [depositDoc], } = await rootCollections.deposits .where('vAccountId', '==', vAccountId) .where('officeId', '==', officeId) .limit(1) .get(); const depositDocRef = depositDoc ? depositDoc.ref : rootCollections.deposits.doc(); const depositData = depositDoc ? depositDoc.data() : {}; depositData.events = depositData.events || []; const isRepeatedEvent = depositData.events.findIndex( ({ signature: payloadSignature }) => payloadSignature === signature, ) > -1; depositData.events.push(requestBody); linkedDeposits.push(depositDocRef.id); batch.set( depositDocRef, Object.assign({}, depositData, { vAccountId, office, officeId, createdAt: depositData.createdAt || Date.now(), updatedAt: Date.now(), }), { merge: true }, ); if (isRepeatedEvent) { return batch.commit(); } const { value: receivedAmount } = currencyJs( batchDoc.get('receivedAmount') || 0, ).add(amountInWebhook); let amountThisInstance = currencyJs(currentlyReceivedAmount); if (currentlyReceivedAmount.value < expectedAmount.value) { // fetch other deposits with same batchId // add their sum. // if that sum is at least equal to the expected amount // start payments // else // exit const deposits = await rootCollections.deposits .where('vAccountId', '==', vAccountId) .where('officeId', '==', officeId) .get(); deposits.forEach(deposit => { amountThisInstance = amountThisInstance.add(deposit.get('amount')); }); } // Amount received during this instance + amount received // during all previous deposits during this payment flow // is less than what was expected, then we wait for // another deposit and run this flow again. // As soon as the money received is at least the expected value // we create payments and payment docs in `Payments/{voucherId}`. const isInsufficientAmount = amountThisInstance.value < expectedAmount.value; if (isInsufficientAmount) { console.log('amt less'); return batch.commit(); } // start with payments here. // `amountThisInstance` <== this amount is now at least // what we were expecting when compared to the amount in // batch. // We can proceed with the payments flow. const voucherDocs = await db.getAll( /** * Linked vouchers will never be `undefined` or an empty array. */ ...linkedVouchers.map(voucherId => rootCollections.offices .doc(officeId) .collection(subcollectionNames.VOUCHERS) .doc(voucherId), ), ); const updateCollectionRefs = await db.getAll( ...voucherDocs.map(voucher => { const { beneficiaryId } = voucher.data(); return rootCollections.updates.doc(beneficiaryId); }), ); updateCollectionRefs.forEach(updatesDoc => { const { id: uid } = updatesDoc; const { linkedAccounts = [] } = updatesDoc.data(); const [{ bankAccount, ifsc } = {}] = linkedAccounts; bankDetailsMap.set(uid, { bankAccount, ifsc }); }); const bulkTransferApiRequestBody = { batchTransferId: batchDoc.id, batchFormat: 'BANK_ACCOUNT', batch: [], }; voucherDocs.forEach(voucher => { const { email, amount, phoneNumber, displayName, type, beneficiaryId, } = voucher.data(); const { id: transferId } = voucher; const { bankAccount, ifsc } = bankDetailsMap.get(beneficiaryId) || {}; if (!bankAccount || !ifsc) { // Money can't be transferred to users without `bankAccount`. usersWithoutPaymentAccount.push(beneficiaryId); return; } // Payment is created when a deposit is done from a user batch.set(rootCollections.payments.doc(transferId), { office, officeId, amount, paymentType: type === 'attendance' ? paymentTypes.SALARY : paymentTypes.REIMBURSEMENT, createdAt: Date.now(), updatedAt: Date.now(), }); bulkTransferApiRequestBody.batch.push({ ifsc, email, amount, transferId, bankAccount, phone: phoneNumber, name: displayName, }); }); batch.set( batchDoc.ref, Object.assign({}, batchDoc.data(), { receivedAmount, linkedDeposits, updatedAt: Date.now(), }), { merge: true }, ); // Handle case where `bulkTransferApiRequestBody.batch.length` is 0 // This would be possible in the case where all the beneficiaries // haven't added their bank account. if (bulkTransferApiRequestBody.batch.length > 0) { const batchTransferResponse = await requestBatchTransfer({ batch: bulkTransferApiRequestBody.batch, batchTransferId: bulkTransferApiRequestBody.batchTransferId, }); console.log('batchTransferResponse =>', batchTransferResponse); } return batch.commit(); }; const cashfreeWebhookHandler = async conn => { console.log('cashfree webhook', conn.req.body); const { signature, event } = conn.req.body; // Invalid request sent to the API if (typeof signature !== 'string') { return sendJSON(conn, ''); } // This is a simple object with key and value (strings). // While verifying the signature of the request, we are // modifying the request body by removing the field // `signature`. // To avoid missing any field value during data processing, we can simply const isValidRequest = verifyWebhookPost(Object.assign({}, conn.req.body)); const logBatch = db.batch(); if (!isValidRequest) { logBatch.set(rootCollections.instant.doc(), { subject: 'Invalid Signature in Cashfree webhook', messageBody: JSON.stringify(conn.req.body, ' ', 2), }); } await logBatch.commit(); if (paymentEvents.has(event)) { await handlePayment(conn.req.body); } if (depositEvents.has(event)) { await handleDeposit(conn.req.body); } return sendJSON(conn, {}); }; module.exports = async conn => { try { return cashfreeWebhookHandler(conn); } catch (error) { return handleError(conn, error); } };
27.021413
81
0.661542
529fbe1083c96b0f1ad4dc2dce08a82fcf0d4752
4,276
js
JavaScript
src/components/Search/index.js
Jdbain67/react-mybooks
5a27b8e7b6b609e3ab91b69d8b780802ecc493f7
[ "MIT" ]
15
2017-07-23T06:11:08.000Z
2019-03-10T13:24:02.000Z
src/components/Search/index.js
Jdbain67/react-mybooks
5a27b8e7b6b609e3ab91b69d8b780802ecc493f7
[ "MIT" ]
null
null
null
src/components/Search/index.js
Jdbain67/react-mybooks
5a27b8e7b6b609e3ab91b69d8b780802ecc493f7
[ "MIT" ]
5
2017-07-21T05:45:48.000Z
2021-07-27T19:22:12.000Z
// External Dependencies import React, { Component } from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; // Our Dependencies import { track } from '../../util/analytics'; import * as BooksAPI from '../../BooksAPI'; import { getSuggetions } from '../../util/search'; // Our Components import BookList from '../BookList'; export default class Search extends Component { static propTypes = { onBackClick: PropTypes.func.isRequired, isFetching: PropTypes.bool.isRequired, onShelfChange: PropTypes.func.isRequired, books: PropTypes.array.isRequired, onBookClick: PropTypes.func.isRequired, } state = { query: '', isSearching: false, results: [], } // istanbul ignore next componentDidMount() { const { lastQuery } = localStorage; if (lastQuery) { this.updateQuery(lastQuery); } track(window); } componentWillReceiveProps =({ books }) => { const clonedResults = _.cloneDeep(this.state.results); books.forEach(b => { clonedResults.forEach((r, i, arr) => { if (r.id === b.id) { arr[i].shelf = b.shelf; } }) }); this.setState({ results: clonedResults }); } updateQuery = (query) => { this.setState({ query }); // Store query so it can be retrieved // when the back arrow is clicked // from the BookDetail screen localStorage.lastQuery = query; // If query is empty do // not send an API request if (query.trim().length > 0) { this.setState({ isSearching: true }); BooksAPI.search(query).then(resp => { let results = []; // Only set state if resp is an array // since the endpoint returns undefined // and an error object as well if (Array.isArray(resp)) { const { books } = this.props; // istanbul ignore next books.forEach(b => { resp.forEach((r, i, arr) => { if (r.id === b.id) { arr[i].shelf = b.shelf; } }) }); results = resp; } this.setState({ results, isSearching: false }); }) } else { this.setState({ results: [] }); } } render() { const { query, results, isSearching } = this.state; const { onBackClick, onShelfChange, isFetching, onBookClick } = this.props; const suggestions = getSuggetions(); return ( <div> <div className="search-books"> <div className="search-books-bar"> <a className="close-search" onClick={() => onBackClick()}>Close</a> <div className={isSearching ? "animated loading-bar" : ""}></div> <div className="search-books-input-wrapper"> <input type="text" placeholder="Search by Title or Author" value={query} onChange={(e) => this.updateQuery(e.target.value)} /> </div> </div> <div className="search-books-results"> {/* If results were returned and something was searched for show the following */} { !!results.length && !!query.length && ( <ol className="books-grid"> <BookList onShelfChange={onShelfChange} books={results} isFetching={isFetching} onBookClick={onBookClick} /> </ol> )} {/* If no results were returned, we are not currently searching and text has been typed in the search box then display the following */} { !results.length && !isSearching && !!query.length && ( <div className="search-not-found"> <h2>Could not find anything 😣</h2> <div>Try search for <strong> {suggestions[0]} </strong> or <strong> {suggestions[1]} </strong> </div> </div> )} </div> </div> </div> ) } }
28.506667
79
0.510056
529fcf6d32c9c1ffd2d6248d0fa2f8fbe7395188
2,170
js
JavaScript
eg/timeit/lib/maria/maria.js
OldManLink/maria
a13f0367247bb850da38f11bbc7906302e939954
[ "BSD-2-Clause" ]
271
2015-01-02T10:55:20.000Z
2022-03-11T13:45:06.000Z
eg/timeit/lib/maria/maria.js
OldManLink/maria
a13f0367247bb850da38f11bbc7906302e939954
[ "BSD-2-Clause" ]
11
2015-01-06T03:34:58.000Z
2016-01-29T16:30:59.000Z
eg/timeit/lib/maria/maria.js
OldManLink/maria
a13f0367247bb850da38f11bbc7906302e939954
[ "BSD-2-Clause" ]
36
2015-01-06T03:29:37.000Z
2021-11-02T13:01:40.000Z
// The contents of this file would normally be the built maria.js file. // To make development of Maria easier, we use document.write so that // the examples are always using the latest Maria code and we don't // need a build step while developing Maria. document.write('<script src="../../../lib/evento/evento.js"></script>'); document.write('<script src="../../../lib/hijos/hijos.js"></script>'); document.write('<script src="../../../lib/arbutus/arbutus.js"></script>'); document.write('<script src="../../../lib/grail/grail.js"></script>'); document.write('<script src="../../../lib/hormigas/hormigas.js"></script>'); document.write('<script src="../../../src/namespace.js"></script>'); document.write('<script src="../../../src/capitalize.js"></script>'); document.write('<script src="../../../src/trim.js"></script>'); document.write('<script src="../../../src/some.js"></script>'); document.write('<script src="../../../src/borrow.js"></script>'); document.write('<script src="../../../src/borrowEvento.js"></script>'); document.write('<script src="../../../src/borrowHijos.js"></script>'); document.write('<script src="../../../src/borrowGrail.js"></script>'); document.write('<script src="../../../src/create.js"></script>'); document.write('<script src="../../../src/subclass.js"></script>'); document.write('<script src="../../../src/Model.js"></script>'); document.write('<script src="../../../src/SetModel.js"></script>'); document.write('<script src="../../../src/View.js"></script>'); document.write('<script src="../../../src/ElementView.js"></script>'); document.write('<script src="../../../src/SetView.js"></script>'); document.write('<script src="../../../src/Controller.js"></script>'); document.write('<script src="../../../src/Model.subclass.js"></script>'); document.write('<script src="../../../src/SetModel.subclass.js"></script>'); document.write('<script src="../../../src/View.subclass.js"></script>'); document.write('<script src="../../../src/ElementView.subclass.js"></script>'); document.write('<script src="../../../src/SetView.subclass.js"></script>'); document.write('<script src="../../../src/Controller.subclass.js"></script>');
62
79
0.629954
52a2ce89b60d435d5df7af87828bde56f14c696d
4,949
js
JavaScript
js/noms/src/http-batch-store.js
bowlofstew/noms
f22646b8c2ca91827c417b158cb8df74ad621758
[ "Apache-2.0" ]
null
null
null
js/noms/src/http-batch-store.js
bowlofstew/noms
f22646b8c2ca91827c417b158cb8df74ad621758
[ "Apache-2.0" ]
null
null
null
js/noms/src/http-batch-store.js
bowlofstew/noms
f22646b8c2ca91827c417b158cb8df74ad621758
[ "Apache-2.0" ]
null
null
null
// @flow // Copyright 2016 Attic Labs, Inc. All rights reserved. // Licensed under the Apache License, version 2.0: // http://www.apache.org/licenses/LICENSE-2.0 import Hash from './hash.js'; import RemoteBatchStore from './remote-batch-store.js'; import type {UnsentReadMap} from './remote-batch-store.js'; import type {FetchOptions} from './fetch.js'; import type {ChunkStream} from './chunk-serializer.js'; import {serialize, deserializeChunks} from './chunk-serializer.js'; import {emptyChunk} from './chunk.js'; import { fetchUint8Array as fetchUint8ArrayWithoutVersion, fetchText as fetchTextWithoutVersion, HTTPError, } from './fetch.js'; import {notNull} from './assert.js'; import nomsVersion from './version.js'; const HTTP_STATUS_CONFLICT = 409; const versionHeader = 'x-noms-vers'; type RpcStrings = { getRefs: string, root: string, writeValue: string, }; const versionOptions = { headers: { [versionHeader]: nomsVersion, }, }; function fetchText(url: string, options: FetchOptions) { return fetchTextWithoutVersion(url, mergeOptions(options, versionOptions)); } function fetchUint8Array(url: string, options: FetchOptions) { return fetchUint8ArrayWithoutVersion(url, mergeOptions(options, versionOptions)); } const readBatchOptions = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }; export default class HttpBatchStore extends RemoteBatchStore { _rpc: RpcStrings; constructor(urlparam: string, maxReads: number = 5, fetchOptions: FetchOptions = {}) { const [url, params] = separateParams(urlparam); const rpc = { getRefs: url + '/getRefs/' + params, root: url + '/root/' + params, writeValue: url + '/writeValue/' + params, }; super(maxReads, new Delegate(rpc, fetchOptions)); this._rpc = rpc; } } function separateParams(url: string): [string, string] { let u = url; let params = ''; const m = url.match(/^(.+?)(\?.+)?$/); if (!m) { throw new Error('Could not parse url: ' + url); } if (m[2]) { [, u, params] = m; } u = u.replace(/\/*$/, ''); return [u, params]; } function mergeOptions(baseOpts: FetchOptions, opts: FetchOptions): FetchOptions { const hdrs = Object.assign({}, opts.headers, baseOpts.headers); return Object.assign({}, opts, baseOpts, {headers: hdrs}); } export class Delegate { _rpc: RpcStrings; _readBatchOptions: FetchOptions; _rootOptions: FetchOptions; _body: ArrayBuffer; constructor(rpc: RpcStrings, fetchOptions: FetchOptions) { this._rpc = rpc; this._rootOptions = fetchOptions; this._readBatchOptions = mergeOptions(readBatchOptions, fetchOptions); this._body = new ArrayBuffer(0); } async readBatch(reqs: UnsentReadMap): Promise<void> { const hashStrs = Object.keys(reqs); const body = hashStrs.map(r => 'ref=' + r).join('&'); const opts = Object.assign(this._readBatchOptions, {body: body}); const {headers, buf} = await fetchUint8Array(this._rpc.getRefs, opts); const versionErr = checkVersion(headers); if (versionErr) { return Promise.reject(versionErr); } const chunks = deserializeChunks(buf); // Return success chunks.forEach(chunk => { const hashStr = chunk.hash.toString(); reqs[hashStr](chunk); delete reqs[hashStr]; }); // Report failure Object.keys(reqs).forEach(hashStr => reqs[hashStr](emptyChunk)); } writeBatch(hints: Set<Hash>, chunkStream: ChunkStream): Promise<void> { return serialize(hints, chunkStream) .then(body => fetchText(this._rpc.writeValue, {method: 'POST', body})) .then(({headers}) => { const versionErr = checkVersion(headers); if (versionErr) { return Promise.reject(versionErr); } }); } async getRoot(): Promise<Hash> { const {headers, buf} = await fetchText(this._rpc.root, this._rootOptions); const versionErr = checkVersion(headers); if (versionErr) { return Promise.reject(versionErr); } return notNull(Hash.parse(buf)); } async updateRoot(current: Hash, last: Hash): Promise<boolean> { const ch = this._rpc.root.indexOf('?') >= 0 ? '&' : '?'; const params = `${ch}current=${current.toString()}&last=${last.toString()}`; try { const {headers} = await fetchText(this._rpc.root + params, {method: 'POST'}); const versionErr = checkVersion(headers); if (versionErr) { return Promise.reject(versionErr); } return true; } catch (ex) { if (ex instanceof HTTPError && ex.status === HTTP_STATUS_CONFLICT) { return false; } throw ex; } } } function checkVersion(headers: Map<string, string>): ?Error { const version = headers.get(versionHeader); if (version !== nomsVersion) { return new Error( `SDK version ${nomsVersion} is not compatible with data of version ${String(version)}.`); } return null; }
28.94152
95
0.662356
52a30633c8435999a001e46f6c2fa77736c1a584
1,117
js
JavaScript
HereNow.js
kkennis/HereNow
1b193f52aff87836f91c5ff90629ffe43ea91f4e
[ "MIT" ]
null
null
null
HereNow.js
kkennis/HereNow
1b193f52aff87836f91c5ff90629ffe43ea91f4e
[ "MIT" ]
null
null
null
HereNow.js
kkennis/HereNow
1b193f52aff87836f91c5ff90629ffe43ea91f4e
[ "MIT" ]
null
null
null
Tasks = new Mongo.Collection("tasks"); if (Meteor.isClient) { // This code only runs on the client Template.body.helpers({ tasks: function () { // Show newest tasks at the top return Tasks.find({}, {sort: {createdAt: -1}}); } }); Template.body.events({ "submit .new-task": function (event) { // Prevent default browser form submit event.preventDefault(); // Get value from form element var text = event.target.text.value; // Insert a task into the collection Tasks.insert({ text: text, createdAt: new Date() // current time }); // Clear form event.target.text.value = ""; }, "change .hide-completed input": function (event) { Session.set("hideCompleted", event.target.checked); } }); Template.task.events({ "click .toggle-checked": function () { // Set the checked property to the opposite of its current value Tasks.update(this._id, { $set: {checked: ! this.checked} }); }, "click .delete": function () { Tasks.remove(this._id); } }); }
24.822222
70
0.582811
52a32f244522b4d2b419872d9a93086a68d99c4a
741
js
JavaScript
test/spec/desktop/getTabIds.js
jonathan-fielding/webdriverio
4449e827f041dd9613e2a0f07d08d29a78b88f71
[ "MIT" ]
null
null
null
test/spec/desktop/getTabIds.js
jonathan-fielding/webdriverio
4449e827f041dd9613e2a0f07d08d29a78b88f71
[ "MIT" ]
null
null
null
test/spec/desktop/getTabIds.js
jonathan-fielding/webdriverio
4449e827f041dd9613e2a0f07d08d29a78b88f71
[ "MIT" ]
2
2017-05-25T06:36:11.000Z
2021-01-21T18:04:18.000Z
/** * `newWindow` will also been tested here */ describe('getTabIds', function() { before(h.setup()); it('should return a single tab id', function() { return this.client.getTabIds().then(function(tabs) { tabs.should.be.an.instanceOf(Array); tabs.should.have.length(1); }); }); it('should return two tab ids after openening a new window', function() { var tabsIds; return this.client.newWindow(conf.testPage.subPage).getTabIds().then(function(tabs) { tabsIds = tabs; tabs.should.be.an.instanceOf(Array); tabs.should.have.length(2); }).call(function() { return this.close(tabsIds[0]); }); }); });
27.444444
93
0.57085
52a39634928c2bd5e8b2ee4f82a384521b2f1666
102,614
js
JavaScript
test/test.js
mpj/highland
bc5916498582482b7cce3936e85ca81b2d332411
[ "Apache-2.0" ]
null
null
null
test/test.js
mpj/highland
bc5916498582482b7cce3936e85ca81b2d332411
[ "Apache-2.0" ]
null
null
null
test/test.js
mpj/highland
bc5916498582482b7cce3936e85ca81b2d332411
[ "Apache-2.0" ]
null
null
null
var EventEmitter = require('events').EventEmitter, through = require('through'), sinon = require('sinon'), Stream = require('stream'), streamify = require('stream-array'), concat = require('concat-stream'), Promise = require('es6-promise').Promise, _ = require('../lib/index'); /** * Useful function to use in tests. */ function valueEquals(test, expected) { return function (err, x) { if (err) { test.equal(err, null, 'Expected a value to be emitted.'); } else { test.equal(x, expected, 'Incorrect value emitted.'); } }; } function errorEquals(test, expectedMsg) { return function (err, x) { if (err) { test.equal( err.message, expectedMsg, 'Error emitted with incorrect message.' ); } else { test.notEqual(err, null, 'No error emitted.'); } }; } function anyError(test) { return function (err, x) { test.notEqual(err, null, 'No error emitted.'); }; } exports['ratelimit'] = { setUp: function (callback) { this.clock = sinon.useFakeTimers(); callback(); }, tearDown: function (callback) { this.clock.restore(); callback(); }, 'invalid num per ms': function (test) { test.throws(function () { _([1,2,3]).ratelimit(-10, 0); }); test.throws(function () { _([1,2,3]).ratelimit(0, 0); }); test.done(); }, 'async generator': function (test) { function delay(push, ms, x) { setTimeout(function () { push(null, x); }, ms); } var source = _(function (push, next) { delay(push, 10, 1); delay(push, 20, 2); delay(push, 30, 3); delay(push, 40, 4); delay(push, 50, 5); delay(push, 60, _.nil); }) var results = []; source.ratelimit(2, 100).each(function (x) { results.push(x); }); this.clock.tick(10); test.same(results, [1]); this.clock.tick(89); test.same(results, [1, 2]); this.clock.tick(51); test.same(results, [1, 2, 3, 4]); this.clock.tick(1000); test.same(results, [1, 2, 3, 4, 5]); test.done(); }, 'toplevel - async generator': function (test) { function delay(push, ms, x) { setTimeout(function () { push(null, x); }, ms); } var source = _(function (push, next) { delay(push, 10, 1); delay(push, 20, 2); delay(push, 30, 3); delay(push, 40, 4); delay(push, 50, 5); delay(push, 60, _.nil); }) var results = []; _.ratelimit(2, 100, source).each(function (x) { results.push(x); }); this.clock.tick(10); test.same(results, [1]); this.clock.tick(89); test.same(results, [1, 2]); this.clock.tick(51); test.same(results, [1, 2, 3, 4]); this.clock.tick(1000); test.same(results, [1, 2, 3, 4, 5]); test.done(); }, 'toplevel - partial application, async generator': function (test) { function delay(push, ms, x) { setTimeout(function () { push(null, x); }, ms); } var source = _(function (push, next) { delay(push, 10, 1); delay(push, 20, 2); delay(push, 30, 3); delay(push, 40, 4); delay(push, 50, 5); delay(push, 60, _.nil); }) var results = []; _.ratelimit(2)(100)(source).each(function (x) { results.push(x); }); this.clock.tick(10); test.same(results, [1]); this.clock.tick(89); test.same(results, [1, 2]); this.clock.tick(51); test.same(results, [1, 2, 3, 4]); this.clock.tick(1000); test.same(results, [1, 2, 3, 4, 5]); test.done(); } }; exports['curry'] = function (test) { var fn = _.curry(function (a, b, c, d) { return a + b + c + d; }); test.equal(fn(1,2,3,4), fn(1,2)(3,4)); test.equal(fn(1,2,3,4), fn(1)(2)(3)(4)); var fn2 = function (a, b, c, d) { return a + b + c + d; }; test.equal(_.curry(fn2)(1,2,3,4), _.curry(fn2,1,2,3,4)); test.equal(_.curry(fn2)(1,2,3,4), _.curry(fn2,1,2)(3,4)); test.done(); }; exports['ncurry'] = function (test) { var fn = _.ncurry(3, function (a, b, c, d) { return a + b + c + (d || 0); }); test.equal(fn(1,2,3,4), 6); test.equal(fn(1,2,3,4), fn(1,2)(3)); test.equal(fn(1,2,3,4), fn(1)(2)(3)); var fn2 = function () { var args = Array.prototype.slice(arguments); return args.reduce(function (a, b) { return a + b; }, 0); }; test.equal(_.ncurry(3,fn2)(1,2,3,4), _.ncurry(3,fn2,1,2,3,4)); test.equal(_.ncurry(3,fn2)(1,2,3,4), _.ncurry(3,fn2,1,2)(3,4)); test.done(); }; exports['compose'] = function (test) { function append(x) { return function (str) { return str + x; }; } var fn1 = append(':one'); var fn2 = append(':two'); var fn = _.compose(fn2, fn1); test.equal(fn('zero'), 'zero:one:two'); fn = _.compose(fn1, fn2, fn1); test.equal(fn('zero'), 'zero:one:two:one'); test.done(); }; exports['partial'] = function (test) { var addAll = function () { var args = Array.prototype.slice.call(arguments); return args.reduce(function (a, b) { return a + b; }, 0); }; var f = _.partial(addAll, 1, 2); test.equal(f(3, 4), 10); test.done(); }; exports['flip'] = function (test) { var subtract = function (a, b) { return a - b; }; test.equal(subtract(4,2), 2); test.equal(_.flip(subtract)(4,2), -2); test.equal(_.flip(subtract, 4)(2), -2); test.equal(_.flip(subtract, 4, 2), -2); test.done(); }; exports['seq'] = function (test) { function append(x) { return function (str) { return str + x; }; } var fn1 = append(':one'); var fn2 = append(':two'); var fn = _.seq(fn1, fn2); test.equal(fn('zero'), 'zero:one:two'); // more than two args test.equal(_.seq(fn1, fn2, fn1)('zero'), 'zero:one:two:one'); test.done(); } exports['isStream'] = function (test) { test.ok(!_.isStream()); test.ok(!_.isStream(undefined)); test.ok(!_.isStream(null)); test.ok(!_.isStream(123)); test.ok(!_.isStream({})); test.ok(!_.isStream([])); test.ok(!_.isStream('foo')); test.ok(_.isStream(_())); test.ok(_.isStream(_().map(_.get('foo')))); test.done(); }; exports['nil defines end'] = function (test) { _([1,_.nil,3]).toArray(function (xs) { test.same(xs, [1]); test.done(); }); }; exports['nil should not equate to any empty object'] = function (test) { var s = [1,{},3]; _(s).toArray(function (xs) { test.same(xs, s); test.done(); }); }; exports['async consume'] = function (test) { _([1,2,3,4]).consume(function (err, x, push, next) { if (x === _.nil) { push(null, _.nil); } else { setTimeout(function(){ push(null, x*10); next(); }, 10); } }) .toArray(function (xs) { test.same(xs, [10, 20, 30, 40]); test.done(); }); }; exports['passing Stream to constructor returns original'] = function (test) { var s = _([1,2,3]); test.strictEqual(s, _(s)); test.done(); }; exports['constructor from promise'] = function (test) { _(Promise.resolve(3)).toArray(function (xs) { test.same(xs, [3]); test.done(); }); }; exports['constructor from promise - errors'] = function (test) { var errs = []; _(Promise.reject(new Error('boom'))) .errors(function (err) { errs.push(err); }) .toArray(function (xs) { test.equal(errs[0].message, 'boom'); test.equal(errs.length, 1); test.same(xs, []); test.done(); }); }; exports['if no consumers, buffer data'] = function (test) { var s = _(); test.equal(s.paused, true); s.write(1); s.write(2); s.toArray(function (xs) { test.same(xs, [1,2,3]); test.done(); }); s.write(3); s.write(_.nil); }; exports['if consumer paused, buffer data'] = function (test) { var map_calls = []; function doubled(x) { map_calls.push(x); return x * 2; } var s = _(); var s2 = s.map(doubled); test.equal(s.paused, true); test.equal(s2.paused, true); s.write(1); s.write(2); test.same(map_calls, []); s2.toArray(function (xs) { test.same(xs, [2, 4, 6]); test.same(map_calls, [1, 2, 3]); test.done(); }); s.write(3); s.write(_.nil); }; exports['write when paused adds to incoming buffer'] = function (test) { var s = _(); test.ok(s.paused); test.same(s._incoming, []); test.strictEqual(s.write(1), false); test.same(s._incoming, [1]); test.strictEqual(s.write(2), false); test.same(s._incoming, [1,2]); test.done(); }; exports['write when not paused sends to consumer'] = function (test) { var vals = []; var s1 = _(); var s2 = s1.consume(function (err, x, push, next) { vals.push(x); next(); }); test.ok(s1.paused); test.ok(s2.paused); test.same(s1._incoming, []); test.same(s2._incoming, []); s2.resume(); test.ok(!s1.paused); test.ok(!s2.paused); test.strictEqual(s1.write(1), true); test.strictEqual(s1.write(2), true); test.same(s1._incoming, []); test.same(s2._incoming, []); test.same(vals, [1,2]); test.done(); }; exports['buffered incoming data released on resume'] = function (test) { var vals = []; var s1 = _(); var s2 = s1.consume(function (err, x, push, next) { vals.push(x); next(); }); test.strictEqual(s1.write(1), false); test.same(s1._incoming, [1]); test.same(s2._incoming, []); s2.resume(); test.same(vals, [1]); test.same(s1._incoming, []); test.same(s2._incoming, []); test.strictEqual(s1.write(2), true); test.same(vals, [1,2]); test.done(); }; exports['restart buffering incoming data on pause'] = function (test) { var vals = []; var s1 = _(); var s2 = s1.consume(function (err, x, push, next) { vals.push(x); next(); }); s2.resume(); test.strictEqual(s1.write(1), true); test.strictEqual(s1.write(2), true); test.same(s1._incoming, []); test.same(s2._incoming, []); test.same(vals, [1,2]); s2.pause(); test.strictEqual(s1.write(3), false); test.strictEqual(s1.write(4), false); test.same(s1._incoming, [3,4]); test.same(s2._incoming, []); test.same(vals, [1,2]); s2.resume(); test.same(s1._incoming, []); test.same(s2._incoming, []); test.same(vals, [1,2,3,4]); test.done(); }; exports['redirect from consumer'] = function (test) { var s = _([1,2,3]); var s2 = s.consume(function (err, x, push, next) { next(_([4, 5, 6])); }); s2.toArray(function (xs) { test.same(xs, [4, 5, 6]); test.done(); }); }; exports['async next from consumer'] = function (test) { test.expect(5); var calls = 0; var s = _(function (push, next) { calls++; setTimeout(function () { push(null, calls); next(); }, 10); }); s.id = 's'; var s2 = s.consume(function (err, x, push, next) { if (x <= 3) { setTimeout(function () { // no further values should have been read test.equal(calls, x); next(); }, 50); } else { push(null, _.nil); } }); s2.id = 's2'; s2.toArray(function (xs) { test.same(xs, []); test.equal(calls, 4); test.done(); }); }; exports['errors'] = function (test) { var errs = []; var err1 = new Error('one'); var err2 = new Error('two'); var s = _(function (push, next) { push(err1); push(null, 1); push(err2); push(null, 2); push(null, _.nil); }); var f = function (err, rethrow) { errs.push(err); }; _.errors(f, s).toArray(function (xs) { test.same(xs, [1, 2]); test.same(errs, [err1, err2]); test.done(); }); }; exports['errors - rethrow'] = function (test) { var errs = []; var err1 = new Error('one'); var err2 = new Error('two'); var s = _(function (push, next) { push(err1); push(null, 1); push(err2); push(null, 2); push(null, _.nil); }); var f = function (err, rethrow) { errs.push(err); if (err.message === 'two') { rethrow(err); } }; test.throws(function () { _.errors(f)(s).toArray(function () { test.ok(false, 'should not be called'); }); }, 'two'); test.done(); }; exports['errors - rethrows + forwarding different stream'] = function (test) { test.expect(1); var err1 = new Error('one'); var s = _(function (push, next) { push(err1); push(null, _.nil); }).errors(function (err, push) { push(err); }); var s2 = _(function (push, next) { s.pull(function (err, val) { push(err, val); if (val !== _.nil) next(); }); }); test.throws(function () { s2.toArray(function () { test.ok(false, 'should not be called'); }); }, 'one'); test.done(); }; exports['errors - ArrayStream'] = function (test) { var errs = []; var f = function (err, rethrow) { errs.push(err); }; // kinda pointless _([1,2]).errors(f).toArray(function (xs) { test.same(xs, [1, 2]); test.same(errs, []); test.done(); }); }; exports['errors - GeneratorStream'] = function (test) { var errs = []; var err1 = new Error('one'); var err2 = new Error('two'); var s = _(function (push, next) { push(err1); push(null, 1); setTimeout(function () { push(err2); push(null, 2); push(null, _.nil); }, 10); }); var f = function (err, rethrow) { errs.push(err); }; s.errors(f).toArray(function (xs) { test.same(xs, [1, 2]); test.same(errs, [err1, err2]); test.done(); }); }; exports['stopOnError'] = function (test) { var errs = []; var err1 = new Error('one'); var err2 = new Error('two'); var s = _(function (push, next) { push(null, 1); push(err1); push(null, 2); push(err2); push(null, _.nil); }); var f = function (err, rethrow) { errs.push(err); }; _.stopOnError(f, s).toArray(function (xs) { test.same(xs, [1]); test.same(errs, [err1]); test.done(); }); }; exports['stopOnError - rethrows + forwarding different stream'] = function (test) { test.expect(1); var err1 = new Error('one'); var s = _(function (push, next) { push(err1); push(null, _.nil); }).stopOnError(function (err, push) { push(err); }); var s2 = _(function (push, next) { s.pull(function (err, val) { push(err, val); if (val !== _.nil) next(); }); }); test.throws(function () { s2.toArray(function () { test.ok(false, 'should not be called'); }); }, 'one'); test.done(); }; exports['stopOnError - ArrayStream'] = function (test) { var errs = []; var f = function (err, rethrow) { errs.push(err); }; _([1,2,3,4]).stopOnError(f).toArray(function (xs) { test.same(xs, [1,2,3,4]); test.same(errs, []); test.done(); }); }; exports['stopOnError - GeneratorStream'] = function (test) { var errs = []; var err1 = new Error('one'); var err2 = new Error('two'); var s = _(function (push, next) { push(null, 1); setTimeout(function () { push(err1); push(null, 2); push(err2); push(null, _.nil); }, 10); }); var f = function (err, rethrow) { errs.push(err); }; s.stopOnError(f).toArray(function (xs) { test.same(xs, [1]); test.same(errs, [err1]); test.done(); }); }; exports['apply'] = function (test) { test.expect(8); var fn = function (a, b, c) { test.equal(arguments.length, 3); test.equal(a, 1); test.equal(b, 2); test.equal(c, 3); }; _.apply(fn, [1, 2, 3]); // partial application _.apply(fn)([1, 2, 3]); test.done(); }; exports['apply - ArrayStream'] = function (test) { _([1,2,3]).apply(function (a, b, c) { test.equal(arguments.length, 3); test.equal(a, 1); test.equal(b, 2); test.equal(c, 3); test.done(); }); }; exports['apply - GeneratorStream'] = function (test) { var s = _(function (push, next) { push(null, 1); setTimeout(function () { push(null, 2); push(null, 3); push(null, _.nil); }, 10); }); s.apply(function (a, b, c) { test.equal(arguments.length, 3); test.equal(a, 1); test.equal(b, 2); test.equal(c, 3); test.done(); }); }; exports['take'] = function (test) { test.expect(3); var s = _([1,2,3,4]).take(2); s.pull(function (err, x) { test.equal(x, 1); }); s.pull(function (err, x) { test.equal(x, 2); }); s.pull(function (err, x) { test.equal(x, _.nil); }); test.done(); }; exports['take - errors'] = function (test) { test.expect(4); var s = _(function (push, next) { push(null, 1), push(new Error('error'), 2), push(null, 3), push(null, 4), push(null, _.nil) }); var f = s.take(2); f.pull(function (err, x) { test.equal(x, 1); }); f.pull(function (err, x) { test.equal(err.message, 'error'); }); f.pull(function (err, x) { test.equal(x, 3); }); f.pull(function (err, x) { test.equal(x, _.nil); }); test.done(); }; exports['take 1'] = function (test) { test.expect(2); var s = _([1]).take(1); s.pull(function (err, x) { test.equal(x, 1); }); s.pull(function (err, x) { test.equal(x, _.nil); }); test.done(); }; exports['head'] = function (test) { test.expect(2); var s = _([2, 1]).head(); s.pull(function (err, x) { test.equal(2, x); }); s.pull(function (err, x) { test.equal(x, _.nil); }); test.done(); }; exports['each'] = function (test) { var calls = []; _.each(function (x) { calls.push(x); }, [1,2,3]); test.same(calls, [1,2,3]); // partial application _.each(function (x) { calls.push(x); })([1,2,3]); test.same(calls, [1,2,3,1,2,3]); test.done(); }; exports['each - ArrayStream'] = function (test) { var calls = []; _([1,2,3]).each(function (x) { calls.push(x); }); test.same(calls, [1,2,3]); test.done(); }; exports['each - GeneratorStream'] = function (test) { var s = _(function (push, next) { push(null, 1); push(null, 2); push(null, 3); push(null, _.nil); }); var calls = []; s.each(function (x) { calls.push(x); }); test.same(calls, [1,2,3]); test.done(); }; exports['each - throw error if consumed'] = function (test) { var e = new Error('broken'); var s = _(function (push, next) { push(null, 1); push(e); push(null, 2); push(null, _.nil); }); test.throws(function () { s.each(function (x) { // do nothing }); }); test.done(); }; exports['calls generator on read'] = function (test) { var gen_calls = 0; var s = _(function (push, next) { gen_calls++; push(null, 1); push(null, _.nil); }); test.equal(gen_calls, 0); s.take(1).toArray(function (xs) { test.equal(gen_calls, 1); test.same(xs, [1]); s.take(1).toArray(function (ys) { test.equal(gen_calls, 1); test.same(ys, []); test.done(); }); }); }; exports['generator consumers are sent values eagerly until pause'] = function (test) { var s = _(function (push, next) { push(null, 1); push(null, 2); push(null, 3); push(null, _.nil); }); var calls = []; var consumer = s.consume(function (err, x, push, next) { calls.push(x); if (x !== 2) { next(); } }); consumer.resume(); test.same(JSON.stringify(calls), JSON.stringify([1,2])); consumer.resume(); test.same(calls, [1,2,3,_.nil]); test.done(); }; exports['check generator loops on next call without push'] = function (test) { var count = 0; var s = _(function (push, next) { count++; if (count < 5) { next(); } else { push(null, count); push(null, _.nil); } }); s.toArray(function (xs) { test.equal(count, 5); test.same(xs, [5]); test.done(); }); }; exports['calls generator multiple times if paused by next'] = function (test) { var gen_calls = 0; var vals = [1, 2]; var s = _(function (push, next) { gen_calls++; if (vals.length) { push(null, vals.shift()); next(); } else { push(null, _.nil); } }); test.equal(gen_calls, 0); s.take(1).toArray(function (xs) { test.equal(gen_calls, 1); test.same(xs, [1]); s.take(1).toArray(function (xs) { test.equal(gen_calls, 2); test.same(xs, [2]); s.take(1).toArray(function (xs) { test.equal(gen_calls, 3); test.same(xs, []); test.done(); }); }); }); }; exports['adding multiple consumers should error'] = function (test) { var s = _([1,2,3,4]); s.consume(function () {}); test.throws(function () { s.consume(function () {}); }); test.done(); }; exports['switch to alternate stream using next'] = function (test) { var s2_gen_calls = 0; var s2 = _(function (push, next) { s2_gen_calls++; push(null, 2); push(null, _.nil); }); s2.id = 's2'; var s1_gen_calls = 0; var s1 = _(function (push, next) { s1_gen_calls++; push(null, 1); next(s2); }); s1.id = 's1'; test.equal(s1_gen_calls, 0); test.equal(s2_gen_calls, 0); s1.take(1).toArray(function (xs) { test.equal(s1_gen_calls, 1); test.equal(s2_gen_calls, 0); test.same(xs, [1]); s1.take(1).toArray(function (xs) { test.equal(s1_gen_calls, 1); test.equal(s2_gen_calls, 1); test.same(xs, [2]); s1.take(1).toArray(function (xs) { test.equal(s1_gen_calls, 1); test.equal(s2_gen_calls, 1); test.same(xs, []); test.done(); }); }); }); }; exports['switch to alternate stream using next (async)'] = function (test) { var s2_gen_calls = 0; var s2 = _(function (push, next) { s2_gen_calls++; setTimeout(function () { push(null, 2); push(null, _.nil); }, 10); }); s2.id = 's2'; var s1_gen_calls = 0; var s1 = _(function (push, next) { s1_gen_calls++; setTimeout(function () { push(null, 1); next(s2); }, 10); }); s1.id = 's1'; test.equal(s1_gen_calls, 0); test.equal(s2_gen_calls, 0); s1.take(1).toArray(function (xs) { test.equal(s1_gen_calls, 1); test.equal(s2_gen_calls, 0); test.same(xs, [1]); s1.take(1).toArray(function (xs) { test.equal(s1_gen_calls, 1); test.equal(s2_gen_calls, 1); test.same(xs, [2]); s1.take(1).toArray(function (xs) { test.equal(s1_gen_calls, 1); test.equal(s2_gen_calls, 1); test.same(xs, []); test.done(); }); }); }); }; exports['lazily evalute stream'] = function (test) { test.expect(2); var map_calls = []; function doubled(x) { map_calls.push(x); return x * 2; } var s = _([1, 2, 3, 4]); s.id = 's'; s.map(doubled).take(2).toArray(function (xs) { test.same(xs, [2, 4]); }); test.same(JSON.stringify(map_calls), JSON.stringify([1, 2])); test.done(); }; exports['pipe old-style node stream to highland stream'] = function (test) { var xs = []; var src = streamify([1,2,3,4]); var s1 = _(); var s2 = s1.consume(function (err, x, push, next) { xs.push(x); next(); }); Stream.prototype.pipe.call(src, s1); setTimeout(function () { test.same(s1._incoming, [1]); test.same(s2._incoming, []); test.same(xs, []); s2.resume(); setTimeout(function () { test.same(s1._incoming, []); test.same(s2._incoming, []); test.same(xs, [1,2,3,4,_.nil]); test.done(); }, 100); }, 100); }; exports['pipe node stream to highland stream'] = function (test) { var xs = []; var src = streamify([1,2,3,4]); var s1 = _(); var s2 = s1.consume(function (err, x, push, next) { xs.push(x); next(); }); src.pipe(s1); setTimeout(function () { test.same(s1._incoming, [1]); test.same(s2._incoming, []); test.same(xs, []); s2.resume(); setTimeout(function () { test.same(s1._incoming, []); test.same(s2._incoming, []); test.same(xs, [1,2,3,4,_.nil]); test.done(); }, 100); }, 100); }; exports['pipe highland stream to node stream'] = function (test) { var src = _(['a','b','c']); var dest = concat(function (data) { test.same(data, 'abc'); test.done(); }); src.pipe(dest); }; exports['pipe to node stream with backpressure'] = function (test) { test.expect(3); var src = _([1,2,3,4]); var xs = []; var dest = new EventEmitter(); dest.writable = true; dest.write = function (x) { xs.push(x); if (xs.length === 2) { _.setImmediate(function () { test.same(xs, [1,2]); test.ok(src.paused); dest.emit('drain'); }); return false; } }; dest.end = function () { test.same(xs, [1,2,3,4]); test.done(); }; src.pipe(dest); }; exports['wrap node stream and pipe'] = function (test) { test.expect(7); function doubled(x) { return x * 2; } var xs = []; var readable = streamify([1,2,3,4]); var ys = _(readable).map(doubled); var dest = new EventEmitter(); dest.writable = true; dest.write = function (x) { xs.push(x); if (xs.length === 2) { _.setImmediate(function () { test.same(xs, [2,4]); test.ok(ys.source.paused); test.equal(readable._readableState.readingMore, false); dest.emit('drain'); }); return false; } }; dest.end = function () { test.same(xs, [2,4,6,8]); test.done(); }; // make sure nothing starts until we pipe test.same(xs, []); test.same(ys._incoming, []); test.same(ys.source._incoming, []); ys.pipe(dest); }; exports['wrap node stream with error'] = function (test) { test.expect(1); var readable = streamify([1,2,3,4]); var err = new Error('nope'); var xs = _(readable); readable.emit('error', err); xs.stopOnError(function (e) { test.strictEqual(err, e); test.done(); }).each(function () {}); }; // ignore these tests in non-node.js environments if (typeof process !== 'undefined' && process.stdout) { exports['pipe highland stream to stdout'] = function (test) { test.expect(1) var src = _(['']); test.doesNotThrow(function () { src.pipe(process.stdout); }) test.done() } } // ignore these tests in non-node.js environments if (typeof process !== 'undefined' && process.stderr) { exports['pipe highland stream to stderr'] = function (test) { test.expect(1) var src = _(['']); test.doesNotThrow(function () { src.pipe(process.stderr); }) test.done() } } exports['attach data event handler'] = function (test) { var s = _([1,2,3,4]); var xs = []; s.on('data', function (x) { xs.push(x); }); s.on('end', function () { test.same(xs, [1,2,3,4]); test.done(); }); }; exports['multiple pull calls on async generator'] = function (test) { var calls = 0; function countdown(n) { var s = _(function (push, next) { calls++; if (n === 0) { push(null, _.nil); } else { setTimeout(function () { push(null, n); next(countdown(n - 1)); }, 10); } }); s.id = 'countdown:' + n; return s; } var s = countdown(3); var s2 = _(function (push, next) { s.pull(function (err, x) { if (err || x !== _.nil) { push(err, x); next(); } else { push(null, _.nil); } }); }); s2.id = 's2'; s2.toArray(function (xs) { test.same(xs, [3,2,1]); test.same(calls, 4); test.done(); }); }; exports['wrap EventEmitter (or jQuery) on handler'] = function (test) { var calls = []; var ee = { on: function (name, f) { test.same(name, 'myevent'); f(1); f(2); setTimeout(function () { f(3); test.same(calls, [1, 2, 3]); test.done(); }, 10); } }; _('myevent', ee).each(function (x) { calls.push(x); }); }; exports['wrap EventEmitter (or jQuery) on handler with args wrapping by function'] = function (test) { var ee = { on: function (name, f) { test.same(name, 'myevent'); f(1, 2, 3); } }; function mapper(){ return Array.prototype.slice.call(arguments); } _('myevent', ee, mapper).each(function (x) { test.same(x, [1, 2, 3]); test.done(); }); }; exports['wrap EventEmitter (or jQuery) on handler with args wrapping by number'] = function (test) { var ee = { on: function (name, f) { test.same(name, 'myevent'); f(1, 2, 3); } }; _('myevent', ee, 2).each(function (x) { test.same(x, [1, 2]); test.done(); }); }; exports['wrap EventEmitter (or jQuery) on handler with args wrapping by array'] = function (test) { var ee = { on: function (name, f) { test.same(name, 'myevent'); f(1, 2, 3); } }; _('myevent', ee, ['one', 'two', 'three']).each(function (x) { test.same(x, {'one': 1, 'two': 2, 'three': 3}); test.done() }); }; exports['sequence'] = function (test) { _.sequence([[1,2], [3], [[4],5]]).toArray(function (xs) { test.same(xs, [1,2,3,[4],5]); }); test.done(); }; exports['sequence - ArrayStream'] = function (test) { _([[1,2], [3], [[4],5]]).sequence().toArray(function (xs) { test.same(xs, [1,2,3,[4],5]); test.done(); }); }; exports['sequence - GeneratorStream'] = function (test) { var calls = []; function countdown(name, n) { var s = _(function (push, next) { calls.push(name); if (n === 0) { push(null, _.nil); } else { setTimeout(function () { push(null, n); next(countdown(name, n - 1)); }, 10); } }); s.id = 'countdown:' + name + ':' + n; return s; } var s1 = countdown('one', 3); var s2 = countdown('two', 3); var s3 = countdown('three', 3); _([s1, s2, s3]).sequence().take(8).toArray(function (xs) { test.same(xs, [3,2,1,3,2,1,3,2]); test.same(calls, [ 'one', 'one', 'one', 'one', 'two', 'two', 'two', 'two', 'three', 'three' // last call missed off due to take(8) ]); test.done(); }); }; exports['sequence - nested GeneratorStreams'] = function (test) { var s2 = _(function (push, next) { push(null, 2); push(null, _.nil); }); var s1 = _(function (push, next) { push(null, 1); push(null, s2); push(null, _.nil); }); _([s1]).sequence().toArray(function (xs) { test.same(xs, [1, s2]); test.done(); }); }; exports['sequence - series alias'] = function (test) { test.equal(_.sequence, _.series); var s1 = _([1,2,3]); var s2 = _(function (push, next) {}); test.equal(s1.sequence, s1.series); test.equal(s2.sequence, s2.series); test.done(); }; exports['sequence - Streams of Streams of Arrays'] = function (test) { _([ _([1,2]), _([3]), _([[4],5]) ]).sequence().toArray(function (xs) { test.same(xs, [1,2,3,[4],5]); test.done(); }); } exports['fork'] = function (test) { var s = _([1,2,3,4]); s.id = 's'; var s2 = s.map(function (x) { return x * 2; }); s2.id = 's2'; var s3 = s.fork().map(function (x) { return x * 3; }); s3.id = 's3'; var s2_data = []; var s3_data = []; s2.take(1).each(function (x) { s2_data.push(x); }); // don't start until both consumers resume test.same(s2_data, []); s3.take(2).each(function (x) { s3_data.push(x); }); test.same(s2_data, [2]); test.same(s3_data, [3]); s2.take(1).each(function (x) { s2_data.push(x); }); test.same(s2_data, [2,4]); test.same(s3_data, [3,6]); s3.take(2).each(function (x) { s3_data.push(x); }); test.same(s2_data, [2,4]); test.same(s3_data, [3,6]); s2.take(2).each(function (x) { s2_data.push(x); }); test.same(s2_data, [2,4,6,8]); test.same(s3_data, [3,6,9,12]); test.done(); }; exports['observe'] = function (test) { var s = _([1,2,3,4]); s.id = 's'; var s2 = s.map(function (x) { return x * 2; }); s2.id = 's2'; var s3 = s.observe().map(function (x) { return x * 3; }); s3.id = 's3'; var s2_data = []; var s3_data = []; s2.take(1).each(function (x) { s2_data.push(x); }); test.same(s2_data, [2]); test.same(s3_data, []); test.same(s3.source._incoming, [1]); s3.take(2).each(function (x) { s3_data.push(x); }); test.same(s2_data, [2]); test.same(s3_data, [3]); s2.take(1).each(function (x) { s2_data.push(x); }); test.same(s2_data, [2,4]); test.same(s3_data, [3,6]); s3.take(2).each(function (x) { s3_data.push(x); }); test.same(s2_data, [2,4]); test.same(s3_data, [3,6]); s2.take(2).each(function (x) { s2_data.push(x); }); test.same(s2_data, [2,4,6,8]); test.same(s3_data, [3,6,9,12]); test.done(); }; // TODO: test redirect after fork, forked streams should transfer over // TODO: test redirect after observe, observed streams should transfer over exports['flatten'] = function (test) { _.flatten([1, [2, [3, 4], 5], [6]]).toArray(function (xs) { test.same(xs, [1,2,3,4,5,6]); test.done(); }); }; exports['flatten - ArrayStream'] = function (test) { _([1, [2, [3, 4], 5], [6]]).flatten().toArray(function (xs) { test.same(xs, [1,2,3,4,5,6]); test.done(); }); }; exports['flatten - GeneratorStream'] = function (test) { var s3 = _(function (push, next) { setTimeout(function () { push(null, 3); push(null, 4); push(null, _.nil); }, 200); }); var s2 = _(function (push, next) { setTimeout(function () { push(null, 2); push(null, s3); push(null, 5); push(null, _.nil); }, 50); }); var s1 = _(function (push, next) { push(null, 1); push(null, s2); push(null, [6]); push(null, _.nil); }); s1.flatten().toArray(function (xs) { test.same(xs, [1,2,3,4,5,6]); test.done(); }); }; exports['flatten - nested GeneratorStreams'] = function (test) { var s2 = _(function (push, next) { push(null, 2); push(null, _.nil); }); var s1 = _(function (push, next) { push(null, 1); push(null, s2); push(null, _.nil); }); s1.flatten().toArray(function (xs) { test.same(xs, [1, 2]); test.done(); }); }; exports['otherwise'] = function (test) { test.expect(5); _.otherwise(_([4,5,6]), _([1,2,3])).toArray(function (xs) { test.same(xs, [1,2,3]); }); _.otherwise(_([4,5,6]), _([])).toArray(function (xs) { test.same(xs, [4,5,6]); }); _.otherwise(_([]), _([1,2,3])).toArray(function (xs) { test.same(xs, [1,2,3]); }); _.otherwise(_([]), _([])).toArray(function (xs) { test.same(xs, []); }); // partial application _.otherwise(_([4,5,6]))(_([1,2,3])).toArray(function (xs) { test.same(xs, [1,2,3]); }); test.done(); }; exports['otherwise - ArrayStream'] = function (test) { test.expect(5); _([1,2,3]).otherwise([4,5,6]).toArray(function (xs) { test.same(xs, [1,2,3]); }); _([]).otherwise([4,5,6]).toArray(function (xs) { test.same(xs, [4,5,6]); }); _([4,5,6]).otherwise([]).otherwise([]).toArray(function (xs) { test.same(xs, [4,5,6]); }); _([]).otherwise([4,5,6]).otherwise([]).toArray(function (xs) { test.same(xs, [4,5,6]); }); _([]).otherwise([]).otherwise([4,5,6]).toArray(function (xs) { test.same(xs, [4,5,6]); }); test.done(); }; exports['otherwise - Redirect'] = function(test) { test.expect(3); _(function (push, next) { next(_([1,2,3])); }).otherwise([]).toArray(function (xs) { test.same(xs, [1,2,3]); }); _(function (push, next) { next(_([1,2,3])); }).otherwise([4,5,6]).toArray(function (xs) { test.same(xs, [1,2,3]); }); _(function (push, next) { next(_([])); }).otherwise([4,5,6]).toArray(function (xs) { test.same(xs, [4,5,6]); }); test.done(); }; exports['otherwise - GeneratorStream'] = function (test) { test.expect(2); var empty = _(function (push, next) { setTimeout(function () { push(null, _.nil); }, 10); }); var xs = _(function (push, next) { setTimeout(function () { push(null, 1); push(null, _.nil); }, 10); }); var ys = _(function (push, next) { setTimeout(function () { push(null, 2); push(null, _.nil); }, 10); }); xs.otherwise(ys).toArray(function (zs) { test.same(zs, [1]); empty.otherwise(ys).toArray(function (zs) { test.same(zs, [2]); test.done(); }); }); }; exports['append'] = function (test) { test.expect(2); _.append(4, [1,2,3]).toArray(function (xs) { test.same(xs, [1,2,3,4]); }); // partial application _.append(4)([1,2,3]).toArray(function (xs) { test.same(xs, [1,2,3,4]); }); test.done(); }; exports['append - ArrayStream'] = function (test) { _([1,2,3]).append(4).toArray(function (xs) { test.same(xs, [1,2,3,4]); test.done(); }); }; exports['append - GeneratorStream'] = function (test) { var s = _(function (push, next) { push(null, 1); push(null, 2); push(null, 3); push(null, _.nil); }); s.append(4).toArray(function (xs) { test.same(xs, [1,2,3,4]); test.done(); }); }; exports['reduce'] = function (test) { test.expect(3); function add(a, b) { return a + b; } _.reduce(10, add, [1,2,3,4]).toArray(function (xs) { test.same(xs, [20]); }); // partial application _.reduce(10, add)([1,2,3,4]).toArray(function (xs) { test.same(xs, [20]); }); _.reduce(10)(add)([1,2,3,4]).toArray(function (xs) { test.same(xs, [20]); }); test.done(); }; exports['reduce - argument function throws'] = function (test) { test.expect(2); var err = new Error('error'); var s = _([1,2,3,4,5]).reduce(0, function (memo, x) { if (x === 3) throw err; return memo + x; }); s.pull(errorEquals(test, 'error')); s.pull(valueEquals(test, _.nil)); test.done(); }; exports['reduce - ArrayStream'] = function (test) { function add(a, b) { return a + b; } _([1,2,3,4]).reduce(10, add).toArray(function (xs) { test.same(xs, [20]); test.done(); }); }; exports['reduce - GeneratorStream'] = function (test) { function add(a, b) { return a + b; } var s = _(function (push, next) { setTimeout(function () { push(null, 1); push(null, 2); push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s.reduce(10, add).toArray(function (xs) { test.same(xs, [20]); test.done(); }); }; exports['reduce1'] = function (test) { test.expect(4); function add(a, b) { return a + b; } _.reduce1(add, [1,2,3,4]).toArray(function (xs) { test.same(xs, [10]); }); // partial application _.reduce1(add)([1,2,3,4]).toArray(function (xs) { test.same(xs, [10]); }); _.reduce1(add)([1,2,3,4]).toArray(function (xs) { test.same(xs, [10]); }); // single argument _.reduce1(add, [1]).toArray(function (xs) { test.same(xs, [1]); }); test.done(); }; exports['reduce1 - argument function throws'] = function (test) { test.expect(2); var err = new Error('error'); var s = _([1,2,3,4,5]).reduce1(function (memo, x) { if (x === 3) throw err; return memo + x; }); s.pull(errorEquals(test, 'error')); s.pull(valueEquals(test, _.nil)); test.done(); }; exports['reduce1 - ArrayStream'] = function (test) { function add(a, b) { return a + b; } _([1,2,3,4]).reduce1(add).toArray(function (xs) { test.same(xs, [10]); test.done(); }); }; exports['reduce1 - GeneratorStream'] = function (test) { function add(a, b) { return a + b; } var s = _(function (push, next) { setTimeout(function () { push(null, 1); push(null, 2); push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s.reduce1(add).toArray(function (xs) { test.same(xs, [10]); test.done(); }); }; exports['scan'] = function (test) { test.expect(3); function add(a, b) { return a + b; } _.scan(10, add, [1,2,3,4]).toArray(function (xs) { test.same(xs, [10, 11, 13, 16, 20]); }); // partial application _.scan(10, add)([1,2,3,4]).toArray(function (xs) { test.same(xs, [10, 11, 13, 16, 20]); }); _.scan(10)(add)([1,2,3,4]).toArray(function (xs) { test.same(xs, [10, 11, 13, 16, 20]); }); test.done(); }; exports['scan - argument function throws'] = function (test) { test.expect(5); var err = new Error('error'); var s = _([1,2,3,4,5]).scan(0, function (memo, x) { if (x === 3) throw err; return memo + x; }); s.pull(valueEquals(test, 0)); s.pull(valueEquals(test, 1)); s.pull(valueEquals(test, 3)); s.pull(errorEquals(test, 'error')); s.pull(valueEquals(test, _.nil)); test.done(); }; exports['scan - ArrayStream'] = function (test) { function add(a, b) { return a + b; } _([1,2,3,4]).scan(10, add).toArray(function (xs) { test.same(xs, [10, 11, 13, 16, 20]); test.done(); }); }; exports['scan - GeneratorStream'] = function (test) { function add(a, b) { return a + b; } var s = _(function (push, next) { setTimeout(function () { push(null, 1); push(null, 2); push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s.scan(10, add).toArray(function (xs) { test.same(xs, [10, 11, 13, 16, 20]); test.done(); }); }; exports['scan - GeneratorStream lazy'] = function (test) { var calls = []; function add(a, b) { calls.push([a, b]); return a + b; } var s = _(function (push, next) { setTimeout(function () { push(null, 1); push(null, 2); push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s.scan(10, add).take(3).toArray(function (xs) { test.same(calls, [ [10, 1], [11, 2] ]); test.same(xs, [10, 11, 13]); test.done(); }); }; exports['scan1'] = function (test) { test.expect(4); function add(a, b) { return a + b; } _.scan1(add, [1,2,3,4]).toArray(function (xs) { test.same(xs, [1, 3, 6, 10]); }); // partial application _.scan1(add)([1,2,3,4]).toArray(function (xs) { test.same(xs, [1, 3, 6, 10]); }); _.scan1(add)([1,2,3,4]).toArray(function (xs) { test.same(xs, [1, 3, 6, 10]); }); // single argument _.scan1(add, [1]).toArray(function (xs) { test.same(xs, [1]); }); test.done(); }; exports['scan1 - argument function throws'] = function (test) { test.expect(4); var err = new Error('error'); var s = _([1,2,3,4,5]).scan1(function (memo, x) { if (x === 3) throw err; return memo + x; }); s.pull(valueEquals(test, 1)); s.pull(valueEquals(test, 3)); s.pull(errorEquals(test, 'error')); s.pull(valueEquals(test, _.nil)); test.done(); }; exports['scan1 - ArrayStream'] = function (test) { function add(a, b) { return a + b; } _([1,2,3,4]).scan1(add).toArray(function (xs) { test.same(xs, [1, 3, 6, 10]); test.done(); }); }; exports['scan1 - GeneratorStream'] = function (test) { function add(a, b) { return a + b; } var s = _(function (push, next) { setTimeout(function () { push(null, 1); push(null, 2); push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s.scan1(add).toArray(function (xs) { test.same(xs, [1, 3, 6, 10]); test.done(); }); }; exports['scan1 - GeneratorStream lazy'] = function (test) { var calls = []; function add(a, b) { calls.push([a, b]); return a + b; } var s = _(function (push, next) { setTimeout(function () { push(null, 1); push(null, 2); push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s.scan1(add).take(3).toArray(function (xs) { test.same(calls, [ [1, 2], [3, 3] ]); test.same(xs, [1, 3, 6]); test.done(); }); }; exports['collect'] = function (test) { _.collect([1,2,3,4]).toArray(function (xs) { test.same(xs, [[1,2,3,4]]); test.done(); }); }; exports['collect - ArrayStream'] = function (test) { _([1,2,3,4]).collect().toArray(function (xs) { test.same(xs, [[1,2,3,4]]); test.done(); }); }; exports['collect - GeneratorStream'] = function (test) { var s = _(function (push, next) { setTimeout(function () { push(null, 1); push(null, 2); push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s.collect().toArray(function (xs) { test.same(xs, [[1,2,3,4]]); test.done(); }); }; exports['concat'] = function (test) { test.expect(2); _.concat([3,4], [1,2]).toArray(function (xs) { test.same(xs, [1,2,3,4]) }); // partial application _.concat([3,4])([1,2]).toArray(function (xs) { test.same(xs, [1,2,3,4]) }); test.done(); }; exports['concat - ArrayStream'] = function (test) { _([1,2]).concat([3,4]).toArray(function (xs) { test.same(xs, [1,2,3,4]); test.done(); }); }; exports['concat - piped ArrayStream'] = function (test) { _.concat(streamify([3,4]).pipe(through()), streamify([1,2])).toArray(function (xs) { test.same(xs, [1,2,3,4]); test.done(); }); }; exports['concat - piped ArrayStream - paused'] = function (test) { var s1 = streamify([1,2]); var s2 = streamify([3,4]); s2.pause(); s1.pause(); test.strictEqual(s1._readableState.buffer.length, 0); test.strictEqual(s1._readableState.reading, false); test.strictEqual(s2._readableState.buffer.length, 0); test.strictEqual(s2._readableState.reading, false); var s3 = _.concat(s2, s1); test.ok( s1._readableState.buffer[0] === 1 || // node 0.11.x s1._readableState.buffer.length === 0 // node 0.10.x ); test.strictEqual(s1._readableState.reading, false); test.ok( s2._readableState.buffer[0] === 3 || // node 0.11.x s2._readableState.buffer.length === 0 // node 0.10.x ); test.strictEqual(s2._readableState.reading, false); s3.toArray(function (xs) { test.same(xs, [1,2,3,4]); test.done(); }); }; exports['concat - GeneratorStream'] = function (test) { var s1 = _(function (push, next) { setTimeout(function () { push(null, 1); push(null, 2); push(null, _.nil); }, 10); }); var s2 = _(function (push, next) { setTimeout(function () { push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s1.concat(s2).toArray(function (xs) { test.same(xs, [1,2,3,4]); test.done(); }); }; exports['merge'] = { setUp: function (callback) { this.clock = sinon.useFakeTimers(); callback(); }, tearDown: function (callback) { this.clock.restore(); callback(); }, 'top-level': function (test) { var s1 = _(function (push, next) { push(null, 1); setTimeout(function () { push(null, 2); }, 20); setTimeout(function () { push(null, 3); push(null, _.nil); }, 40); }); var s2 = _(function (push, next) { setTimeout(function () { push(null, 4); }, 10); setTimeout(function () { push(null, 5); }, 30); setTimeout(function () { push(null, 6); push(null, _.nil); }, 50); }); _.merge([s1, s2]).toArray(function (xs) { test.same(xs, [1,4,2,5,3,6]); test.done(); }); this.clock.tick(100); }, 'ArrayStream': function (test) { var s1 = _(function (push, next) { push(null, 1); setTimeout(function () { push(null, 2); }, 20); setTimeout(function () { push(null, 3); push(null, _.nil); }, 40); }); var s2 = _(function (push, next) { setTimeout(function () { push(null, 4); }, 10); setTimeout(function () { push(null, 5); }, 30); setTimeout(function () { push(null, 6); push(null, _.nil); }, 50); }); _([s1, s2]).merge().toArray(function (xs) { test.same(xs, [1,4,2,5,3,6]); test.done(); }); this.clock.tick(100); }, 'GeneratorStream': function (test) { var s1 = _(function (push, next) { push(null, 1); setTimeout(function () { push(null, 2); }, 20); setTimeout(function () { push(null, 3); push(null, _.nil); }, 40); }); var s2 = _(function (push, next) { setTimeout(function () { push(null, 4); }, 10); setTimeout(function () { push(null, 5); }, 30); setTimeout(function () { push(null, 6); push(null, _.nil); }, 50); }); var s = _(function (push, next) { push(null, s1); setTimeout(function() { push(null, s2); push(null, _.nil); }, 5); }); s.merge().toArray(function (xs) { test.same(xs, [1,4,2,5,3,6]); test.done(); }); this.clock.tick(100); }, 'pull from all streams in parallel': function (test) { var s1 = _(function (push, next) { setTimeout(function () { push(null, 1); }, 40); setTimeout(function () { push(null, 2); push(null, _.nil); }, 80); }); var s2 = _(function (push, next) { setTimeout(function () { push(null, 3); }, 10); setTimeout(function () { push(null, 4); }, 20); setTimeout(function () { push(null, 5); push(null, _.nil); }, 30); }); _([s1, s2]).merge().toArray(function (xs) { test.same(xs, [3,4,5,1,2]); test.done(); }); this.clock.tick(100); }, 'consume lazily': function (test) { var counter1 = 0; var s1 = _(function (push, next) { counter1++; setTimeout(function () { push(null, counter1); next(); }, 100); }); var counter2 = 0; var s2 = _(function (push, next) { counter2++; setTimeout(function () { push(null, counter2); next(); }, 240); }); var self = this; _([s1, s2]).merge().take(4).toArray(function (xs) { test.same(xs, [1, 2, 1, 3]); setTimeout(function () { test.equal(counter1, 3); test.equal(counter2, 2); test.done(); }, 1000); }); this.clock.tick(2000); }, /* 'read from sources as soon as they are available': function (test) { test.expect(2); var s1 = _([1, 2, 3]); var s2 = _([4, 5, 6]); var srcs = _(function (push, next) { setTimeout(function () { push(null, s1); }, 100); setTimeout(function () { push(null, s2); }, 200); setTimeout(function () { push(null, _.nil); }, 300); }); var xs = []; srcs.merge().each(function (x) { xs.push(x); }); setTimeout(function () { test.same(xs.slice(), [1, 2, 3]); }, 150); setTimeout(function () { test.same(xs.slice(), [1, 2, 3, 4, 5, 6]); test.done(); }, 400); this.clock.tick(400); }, */ 'github issue #124: detect late end of stream': function(test) { var s = _([1,2,3]) .map(function(x) { return _([x]) }) .merge() s.toArray(function(xs) { test.same(xs, [1,2,3]); test.done(); }) }, 'handle backpressure': function (test) { var s1 = _([1,2,3,4]); var s2 = _([5,6,7,8]); var s = _.merge([s1, s2]); s.take(5).toArray(function (xs) { test.same(xs, [1,5,2,6,3]); setImmediate(function () { test.equal(s._outgoing.length, 0); test.equal(s._incoming.length, 1); test.equal(s1._incoming.length, 2); test.equal(s2._incoming.length, 2); test.done(); }); }); this.clock.tick(100); }, 'fairer merge algorithm': function (test) { // make sure one stream with many buffered values doesn't crowd // out another stream being merged var s1 = _([1,2,3,4]); s1.id = 's1'; var s2 = _(function (push, next) { setTimeout(function () { push(null, 5); push(null, 6); setTimeout(function () { push(null, 7); push(null, 8); push(null, _.nil); }, 100); }, 100); }); s2.id = 's2'; var s = _([s1, s2]).merge(); s.id = 's'; s.take(1).toArray(function (xs) { test.same(xs, [1]); setTimeout(function () { s.take(4).toArray(function (xs) { test.same(xs, [5,2,6,3]); s.toArray(function (xs) { test.same(xs, [4,7,8]); test.done(); }); }); }, 150); }); this.clock.tick(400); } }; exports['invoke'] = function (test) { test.expect(2); _.invoke('toString', [], [1,2,3,4]).toArray(function (xs) { test.same(xs, ['1', '2', '3', '4']); }); // partial application _.invoke('toString')([])([1,2,3,4]).toArray(function (xs) { test.same(xs, ['1', '2', '3', '4']); }); test.done(); }; exports['invoke - ArrayStream'] = function (test) { _([1,2,3,4]).invoke('toString', []).toArray(function (xs) { test.same(xs, ['1','2','3','4']); test.done(); }); }; exports['invoke - GeneratorStream'] = function (test) { var s = _(function (push, next) { push(null, 1); push(null, 2); setTimeout(function () { push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s.invoke('toString', []).toArray(function (xs) { test.same(xs, ['1','2','3','4']); test.done(); }); }; exports['map'] = function (test) { test.expect(2); function doubled(x) { return x * 2; } _.map(doubled, [1, 2, 3, 4]).toArray(function (xs) { test.same(xs, [2, 4, 6, 8]); }); // partial application _.map(doubled)([1, 2, 3, 4]).toArray(function (xs) { test.same(xs, [2, 4, 6, 8]); }); test.done(); }; exports['map - argument function throws'] = function (test) { test.expect(6); var err = new Error('error'); var s = _([1,2,3,4,5]).map(function (x) { if (x === 3) throw err; return x + 1; }); s.pull(valueEquals(test, 2)); s.pull(valueEquals(test, 3)); s.pull(errorEquals(test, 'error')); s.pull(valueEquals(test, 5)); s.pull(valueEquals(test, 6)); s.pull(valueEquals(test, _.nil)); test.done(); }; exports['map - ArrayStream'] = function (test) { function doubled(x) { return x * 2; } _([1, 2, 3, 4]).map(doubled).toArray(function (xs) { test.same(xs, [2, 4, 6, 8]); test.done(); }); }; exports['map - GeneratorStream'] = function (test) { function doubled(x) { return x * 2; } var s = _(function (push, next) { push(null, 1); push(null, 2); setTimeout(function () { push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s.map(doubled).toArray(function (xs) { test.same(xs, [2, 4, 6, 8]); test.done(); }); }; exports['map to value'] = function (test) { test.expect(2); _.map('foo', [1, 2]).toArray(function (xs) { test.same(xs, ['foo', 'foo']); }); _([1, 2, 3]).map(1).toArray(function (xs) { test.same(xs, [1,1,1]); }); test.done(); }; exports['doto'] = function (test) { test.expect(4); var seen; function record(x) { seen.push(x * 2); } seen = []; _.doto(record, [1, 2, 3, 4]).toArray(function (xs) { test.same(xs, [1, 2, 3, 4]); test.same(seen, [2, 4, 6, 8]); }); // partial application seen = []; _.doto(record)([1, 2, 3, 4]).toArray(function (xs) { test.same(xs, [1, 2, 3, 4]); test.same(seen, [2, 4, 6, 8]); }); test.done(); }; exports['flatMap'] = function (test) { var f = function (x) { return _(function (push, next) { setTimeout(function () { push(null, x * 2); push(null, _.nil); }, 10); }); }; _.flatMap(f, [1,2,3,4]).toArray(function (xs) { test.same(xs, [2,4,6,8]); test.done(); }); }; exports['flatMap - argument function throws'] = function (test) { test.expect(4); var err = new Error('error'); var s = _([1,2,3,4]).flatMap(function (x) { if (x === 1) return _([x]); if (x === 2) throw err; if (x === 3) return _([]); return true; }); s.pull(valueEquals(test, 1)); s.pull(errorEquals(test, 'error')); s.pull(anyError(test)); s.pull(valueEquals(test, _.nil)); test.done(); }; exports['flatMap - ArrayStream'] = function (test) { var f = function (x) { return _(function (push, next) { setTimeout(function () { push(null, x * 2); push(null, _.nil); }, 10); }); }; _([1,2,3,4]).flatMap(f).toArray(function (xs) { test.same(xs, [2,4,6,8]); test.done(); }); }; exports['flatMap - GeneratorStream'] = function (test) { var f = function (x) { return _(function (push, next) { setTimeout(function () { push(null, x * 2); push(null, _.nil); }, 10); }); }; var s = _(function (push, next) { push(null, 1); push(null, 2); setTimeout(function () { push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s.flatMap(f).toArray(function (xs) { test.same(xs, [2,4,6,8]); test.done(); }); }; exports['flatMap - map to Stream of Array'] = function (test) { test.expect(1); var f = function (x) { return _([[x]]); }; var s = _([1,2,3,4]).flatMap(f).toArray(function (xs) { test.same(xs, [[1],[2],[3],[4]]); test.done(); }); }; exports['pluck'] = function (test) { var a = _([ {type: 'blogpost', title: 'foo'}, {type: 'blogpost', title: 'bar'}, {type: 'asdf', title: 'baz'} ]); a.pluck('title').toArray(function (xs) { test.same(xs, ['foo', 'bar', 'baz']); test.done(); }); }; exports['pluck - non-object argument'] = function (test) { var a = _([1, {type: 'blogpost', title: 'foo'}]); test.throws(function () { a.pluck('title').toArray(function (xs) { test.ok(false, "shouldn't be called"); }); }, 'Expected Object, got array'); test.done(); }; exports['filter'] = function (test) { test.expect(2); function isEven(x) { return x % 2 === 0; } _.filter(isEven, [1, 2, 3, 4]).toArray(function (xs) { test.same(xs, [2, 4]); }); // partial application _.filter(isEven)([1, 2, 3, 4]).toArray(function (xs) { test.same(xs, [2, 4]); }); test.done(); }; exports['filter - argument function throws'] = function (test) { test.expect(3); var err = new Error('error'); var s = _([1,2,3]).filter(function (x) { if (x === 2) throw err; if (x === 3) return false; return true; }); s.pull(valueEquals(test, 1)); s.pull(errorEquals(test, 'error')); s.pull(valueEquals(test, _.nil)); test.done(); }; exports['filter - ArrayStream'] = function (test) { function isEven(x) { return x % 2 === 0; } _([1, 2, 3, 4]).filter(isEven).toArray(function (xs) { test.same(xs, [2, 4]); test.done(); }); }; exports['filter - GeneratorStream'] = function (test) { function isEven(x) { return x % 2 === 0; } var s = _(function (push, next) { push(null, 1); push(null, 2); setTimeout(function () { push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s.filter(isEven).toArray(function (xs) { test.same(xs, [2, 4]); test.done(); }); }; exports['flatFilter'] = function (test) { var f = function (x) { return _([x % 2 === 0]); }; _.flatFilter(f, [1,2,3,4]).toArray(function (xs) { test.same(xs, [2,4]); test.done(); }); }; exports['flatFilter - argument function throws'] = function (test) { test.expect(4); var err = new Error('error'); var s = _([1,2,3,4]).flatFilter(function (x) { if (x === 1) return _([false]); if (x === 2) throw err; if (x === 3) return _([]); return true; }); s.pull(errorEquals(test, 'error')); s.pull(anyError(test)); s.pull(anyError(test)); s.pull(valueEquals(test, _.nil)); test.done(); }; exports['flatFilter - ArrayStream'] = function (test) { var f = function (x) { return _(function (push, next) { setTimeout(function () { push(null, x % 2 === 0); push(null, _.nil); }, 10); }); }; _([1,2,3,4]).flatFilter(f).toArray(function (xs) { test.same(xs, [2,4]); test.done(); }); }; exports['flatFilter - GeneratorStream'] = function (test) { var f = function (x) { return _(function (push, next) { setTimeout(function () { push(null, x % 2 === 0); push(null, _.nil); }, 10); }); }; var s = _(function (push, next) { push(null, 1); setTimeout(function () { push(null, 2); push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s.flatFilter(f).toArray(function (xs) { test.same(xs, [2,4]); test.done(); }); }; exports['reject'] = function (test) { test.expect(2); function isEven(x) { return x % 2 === 0; } _.reject(isEven, [1, 2, 3, 4]).toArray(function (xs) { test.same(xs, [1, 3]); }); // partial application _.reject(isEven)([1, 2, 3, 4]).toArray(function (xs) { test.same(xs, [1, 3]); }); test.done(); }; exports['reject - ArrayStream'] = function (test) { function isEven(x) { return x % 2 === 0; } _([1, 2, 3, 4]).reject(isEven).toArray(function (xs) { test.same(xs, [1, 3]); test.done(); }); }; exports['reject - GeneratorStream'] = function (test) { function isEven(x) { return x % 2 === 0; } var s = _(function (push, next) { push(null, 1); push(null, 2); setTimeout(function () { push(null, 3); push(null, 4); push(null, _.nil); }, 10); }); s.reject(isEven).toArray(function (xs) { test.same(xs, [1, 3]); test.done(); }); }; exports['find'] = function (test) { test.expect(2); var xs = [ {type: 'foo', name: 'wibble'}, {type: 'foo', name: 'wobble'}, {type: 'bar', name: '123'}, {type: 'bar', name: 'asdf'}, {type: 'baz', name: 'asdf'} ]; var f = function (x) { return x.type == 'bar'; }; _.find(f, xs).toArray(function (xs) { test.same(xs, [{type: 'bar', name: '123'}]); }); // partial application _.find(f)(xs).toArray(function (xs) { test.same(xs, [{type: 'bar', name: '123'}]); }); test.done(); }; exports['find - argument function throws'] = function (test) { test.expect(4); var err = new Error('error'); var s = _([1,2,3,4,5]).find(function (x) { if (x < 3) throw err; return true; }); s.pull(errorEquals(test, 'error')); s.pull(errorEquals(test, 'error')); s.pull(valueEquals(test, 3)); s.pull(valueEquals(test, _.nil)); test.done(); }; exports['find - ArrayStream'] = function (test) { test.expect(2); var xs = [ {type: 'foo', name: 'wibble'}, {type: 'foo', name: 'wobble'}, {type: 'bar', name: '123'}, {type: 'bar', name: 'asdf'}, {type: 'baz', name: 'asdf'} ]; var f = function (x) { return x.type == 'bar'; }; _(xs).find(f).toArray(function (xs) { test.same(xs, [{type: 'bar', name: '123'}]); }); // partial application _(xs).find(f).toArray(function (xs) { test.same(xs, [{type: 'bar', name: '123'}]); }); test.done(); }; exports['find - GeneratorStream'] = function (test) { var xs = _(function (push, next) { push(null, {type: 'foo', name: 'wibble'}); push(null, {type: 'foo', name: 'wobble'}); setTimeout(function () { push(null, {type: 'bar', name: '123'}); push(null, {type: 'bar', name: 'asdf'}); push(null, {type: 'baz', name: 'asdf'}); push(null, _.nil); }, 10); }); var f = function (x) { return x.type == 'baz'; }; _(xs).find(f).toArray(function (xs) { test.same(xs, [{type: 'baz', name: 'asdf'}]); test.done(); }); }; (function (exports) { var xs = [ {type: 'foo', name: 'wibble'}, {type: 'foo', name: 'wobble'}, {type: 'bar', name: '123'}, {type: 'bar', name: 'asdf'}, {type: 'baz', name: 'asdf'} ]; var expected = { 'foo': [{type: 'foo', name: 'wibble'}, {type: 'foo', name: 'wobble'}], 'bar': [{type: 'bar', name: '123'}, {type: 'bar', name: 'asdf'}], 'baz': [{type: 'baz', name: 'asdf'}] }; var primatives = [1,2,3,'cat']; var pexpected = {1: [1], 2: [2], 3: [3], 'cat': ['cat']}; var pexpectedUndefined = { 'undefined': [ 1, 2, 3, 'cat' ] }; var f = function (x) { return x.type; }; var pf = function (o) { return o }; var s = 'type'; exports['group'] = function (test) { test.expect(4); _.group(f, xs).toArray(function (xs) { test.same(xs, [expected]); }); _.group(s, xs).toArray(function (xs) { test.same(xs, [expected]); }); // partial application _.group(f)(xs).toArray(function (xs) { test.same(xs, [expected]); }); _.group(s)(xs).toArray(function (xs) { test.same(xs, [expected]); }); test.done(); }; exports['group - primatives'] = function (test) { test.expect(5); _.group(pf, primatives).toArray(function (xs) { test.same(xs, [pexpected]); }); _.group(s, primatives).toArray(function (xs){ test.same(xs, [pexpectedUndefined]); }); test.throws(function () { _.group(null, primatives).toArray(_.log); }); // partial application _.group(pf)(primatives).toArray(function (xs) { test.same(xs, [pexpected]); }); test.throws(function () { _.group(null)(primatives).toArray(_.log); }); test.done(); }; exports['group - argument function throws'] = function (test) { test.expect(2); var err = new Error('error'); var s = _([1,2,3,4,5]).group(function (x) { if (x === 5) throw err return x % 2 == 0 ? 'even' : 'odd'; }); s.pull(errorEquals(test, 'error')); s.pull(valueEquals(test, _.nil)); test.done(); }; exports['group - ArrayStream'] = function (test) { test.expect(4); _(xs).group(f).toArray(function (xs) { test.same(xs, [expected]); }); _(xs).group(s).toArray(function (xs) { test.same(xs, [expected]); }); // partial application _(xs).group(f).toArray(function (xs) { test.same(xs, [expected]); }); _(xs).group(s).toArray(function (xs) { test.same(xs, [expected]); }); test.done(); }; exports['group - GeneratorStream'] = function (test) { var generator = _(function (push, next) { push(null, xs[0]); push(null, xs[1]); setTimeout(function () { push(null, xs[2]); push(null, xs[3]); push(null, xs[4]); push(null, _.nil); }, 10); }); _(generator).group(f).toArray(function (result) { test.same(result, [expected]); test.done(); }); }; }(exports)); exports['compact'] = function (test) { test.expect(1); _.compact([0, 1, false, 3, undefined, null, 6]).toArray(function (xs) { test.same(xs, [1, 3, 6]); }); test.done(); }; exports['compact - ArrayStream'] = function (test) { _([0, 1, false, 3, undefined, null, 6]).compact().toArray(function (xs) { test.same(xs, [1, 3, 6]); test.done(); }); }; exports['where'] = function (test) { test.expect(2); var xs = [ {type: 'foo', name: 'wibble'}, {type: 'foo', name: 'wobble'}, {type: 'bar', name: '123'}, {type: 'bar', name: 'asdf'}, {type: 'baz', name: 'asdf'} ]; _.where({type: 'foo'}, xs).toArray(function (xs) { test.same(xs, [ {type: 'foo', name: 'wibble'}, {type: 'foo', name: 'wobble'} ]); }); // partial application _.where({type: 'bar', name: 'asdf'})(xs).toArray(function (xs) { test.same(xs, [ {type: 'bar', name: 'asdf'} ]); }); test.done(); }; exports['where - ArrayStream'] = function (test) { test.expect(2); var xs = [ {type: 'foo', name: 'wibble'}, {type: 'foo', name: 'wobble'}, {type: 'bar', name: '123'}, {type: 'bar', name: 'asdf'}, {type: 'baz', name: 'asdf'} ]; _(xs).where({type: 'foo'}).toArray(function (xs) { test.same(xs, [ {type: 'foo', name: 'wibble'}, {type: 'foo', name: 'wobble'} ]); }); // partial application _(xs).where({type: 'bar', name: 'asdf'}).toArray(function (xs) { test.same(xs, [ {type: 'bar', name: 'asdf'} ]); }); test.done(); }; exports['where - GeneratorStream'] = function (test) { var xs = _(function (push, next) { push(null, {type: 'foo', name: 'wibble'}); push(null, {type: 'foo', name: 'wobble'}); setTimeout(function () { push(null, {type: 'bar', name: '123'}); push(null, {type: 'bar', name: 'asdf'}); push(null, {type: 'baz', name: 'asdf'}); push(null, _.nil); }, 10); }); _(xs).where({name: 'asdf'}).toArray(function (xs) { test.same(xs, [ {type: 'bar', name: 'asdf'}, {type: 'baz', name: 'asdf'} ]); test.done(); }); }; exports['zip'] = function (test) { test.expect(2); _.zip([1,2,3], ['a', 'b', 'c']).toArray(function (xs) { test.same(xs, [['a',1], ['b',2], ['c',3]]); }); // partial application _.zip([1,2,3,4,5])(['a', 'b', 'c']).toArray(function (xs) { test.same(xs, [['a',1], ['b',2], ['c',3]]); }); test.done(); }; exports['zip - source emits error'] = function (test) { test.expect(4); var err = new Error('error'); var s1 = _([1,2]); var s2 = _(function (push) { push(null, 'a'); push(err); push(null, 'b'); push(null, _.nil); }); var s = s1.zip(s2); s.pull(function (err, x) { test.deepEqual(x, [1, 'a']); }); s.pull(function (err, x) { test.equal(err.message, 'error'); }); s.pull(function (err, x) { test.deepEqual(x, [2, 'b']); }); s.pull(function (err, x) { test.equal(x, _.nil); }); test.done(); }; exports['zip - ArrayStream'] = function (test) { _(['a', 'b', 'c']).zip([1,2,3]).toArray(function (xs) { test.same(xs, [['a',1], ['b',2], ['c',3]]); test.done(); }); }; exports['zip - GeneratorStream'] = function (test) { var s1 = _(function (push, next) { push(null, 'a'); setTimeout(function () { push(null, 'b'); setTimeout(function () { push(null, 'c'); push(null, _.nil); }, 10); }, 10); }); var s2 = _(function (push, next) { setTimeout(function () { push(null, 1); push(null, 2); setTimeout(function () { push(null, 3); push(null, _.nil); }, 50); }, 50); }); s1.zip(s2).toArray(function (xs) { test.same(xs, [['a',1], ['b',2], ['c',3]]); test.done(); }); }; exports['batch'] = function (test) { test.expect(5); _.batch(3, [1,2,3,4,5,6,7,8,9,0]).toArray(function (xs) { test.same(xs, [[1,2,3], [4,5,6], [7,8,9], [0]]); }); _.batch(3, [1,2,3]).toArray(function (xs) { test.same(xs, [[1,2,3]]); }); _.batch(2, [1,2,3]).toArray(function (xs) { test.same(xs, [[1,2],[3]]); }); _.batch(1, [1,2,3]).toArray(function (xs) { test.same(xs, [[1],[2],[3]]); }); _.batch(0, [1,2,3]).toArray(function (xs) { test.same(xs, [[1,2,3]]); }); test.done(); }; exports['batch - ArrayStream'] = function (test) { test.expect(5); _([1,2,3,4,5,6,7,8,9,0]).batch(3).toArray(function (xs) { test.same(xs, [[1,2,3], [4,5,6], [7,8,9], [0]]); }); _([1,2,3]).batch(4).toArray(function (xs) { test.same(xs, [[1,2,3]]); }); _([1,2,3]).batch(2).toArray(function (xs) { test.same(xs, [[1,2],[3]]); }); _([1,2,3]).batch(1).toArray(function (xs) { test.same(xs, [[1],[2],[3]]); }); _([1,2,3]).batch(0).toArray(function (xs) { test.same(xs, [[1,2,3]]); }); test.done(); }; exports['batch - GeneratorStream'] = function (test) { var s1 = _(function (push, next) { push(null, 1); setTimeout(function () { push(null, 2); setTimeout(function () { push(null, 3); push(null, _.nil); }, 10); }, 10); }); s1.batch(1).toArray(function (xs) { test.same(xs, [[1], [2], [3]]); test.done(); }); } exports['parallel'] = function (test) { var calls = []; var s1 = _(function (push, next) { setTimeout(function () { calls.push(1); push(null, 1); push(null, _.nil); }, 150); }); var s2 = _(function (push, next) { setTimeout(function () { calls.push(2); push(null, 2); push(null, _.nil); }, 50); }); var s3 = _(function (push, next) { setTimeout(function () { calls.push(3); push(null, 3); push(null, _.nil); }, 100); }); _.parallel(4, [s1, s2, s3]).toArray(function (xs) { test.same(calls, [2, 3, 1]); test.same(xs, [1, 2, 3]); test.done(); }); }; exports['parallel - partial application'] = function (test) { var calls = []; var s1 = _(function (push, next) { setTimeout(function () { calls.push(1); push(null, 1); push(null, _.nil); }, 100); }); var s2 = _(function (push, next) { setTimeout(function () { calls.push(2); push(null, 2); push(null, _.nil); }, 50); }); var s3 = _(function (push, next) { setTimeout(function () { calls.push(3); push(null, 3); push(null, _.nil); }, 150); }); _.parallel(4)([s1, s2, s3]).toArray(function (xs) { test.same(calls, [2, 1, 3]); test.same(xs, [1, 2, 3]); test.done(); }); }; exports['parallel - n === 1'] = function (test) { var calls = []; var s1 = _(function (push, next) { setTimeout(function () { calls.push(1); push(null, 1); push(null, _.nil); }, 100); }); var s2 = _(function (push, next) { setTimeout(function () { calls.push(2); push(null, 2); push(null, _.nil); }, 50); }); var s3 = _(function (push, next) { setTimeout(function () { calls.push(3); push(null, 3); push(null, _.nil); }, 150); }); _.parallel(1, [s1, s2, s3]).toArray(function (xs) { test.same(calls, [1, 2, 3]); test.same(xs, [1, 2, 3]); test.done(); }); }; exports['parallel - n === 2'] = function (test) { var calls = []; var s1 = _(function (push, next) { setTimeout(function () { calls.push(1); push(null, 1); push(null, _.nil); }, 150); }); var s2 = _(function (push, next) { setTimeout(function () { calls.push(2); push(null, 2); push(null, _.nil); }, 100); }); var s3 = _(function (push, next) { setTimeout(function () { calls.push(3); push(null, 3); push(null, _.nil); }, 50); }); _.parallel(2, [s1, s2, s3]).toArray(function (xs) { test.same(calls, [2, 1, 3]); test.same(xs, [1, 2, 3]); test.done(); }); }; exports['parallel - ArrayStream'] = function (test) { var calls = []; var s1 = _(function (push, next) { setTimeout(function () { calls.push(1); push(null, 1); push(null, _.nil); }, 150); }); var s2 = _(function (push, next) { setTimeout(function () { calls.push(2); push(null, 2); push(null, _.nil); }, 100); }); var s3 = _(function (push, next) { setTimeout(function () { calls.push(3); push(null, 3); push(null, _.nil); }, 50); }); _([s1, s2, s3]).parallel(2).toArray(function (xs) { test.same(calls, [2, 1, 3]); test.same(xs, [1, 2, 3]); test.done(); }); }; exports['parallel - GeneratorStream'] = function (test) { var calls = []; var s1 = _(function (push, next) { setTimeout(function () { calls.push(1); push(null, 1); push(null, _.nil); }, 150); }); var s2 = _(function (push, next) { setTimeout(function () { calls.push(2); push(null, 2); push(null, _.nil); }, 100); }); var s3 = _(function (push, next) { setTimeout(function () { calls.push(3); push(null, 3); push(null, _.nil); }, 50); }); var s = _(function (push, next) { push(null, s1); setTimeout(function () { push(null, s2); push(null, s3); push(null, _.nil); }, 10); }); s.parallel(2).toArray(function (xs) { test.same(calls, [2, 1, 3]); test.same(xs, [1, 2, 3]); test.done(); }); }; exports['parallel consume from async generator'] = function (test) { function delay(push, ms, x) { setTimeout(function () { push(null, x); }, ms); } var source = _(function (push, next) { //console.log('source read'); delay(push, 100, 1); delay(push, 200, 2); delay(push, 300, 3); delay(push, 400, 4); delay(push, 500, 5); delay(push, 600, _.nil); }); var doubler = function (x) { //console.log(['doubler call', x]); return _(function (push, next) { //console.log('doubler read'); delay(push, 50, x * 2); delay(push, 100, _.nil); }); }; source.map(doubler).parallel(3).toArray(function (xs) { test.same(xs, [2, 4, 6, 8, 10]); test.done(); }); }; exports['throttle'] = { setUp: function (callback) { this.clock = sinon.useFakeTimers(); callback(); }, tearDown: function (callback) { this.clock.restore(); callback(); }, 'top-level': function (test) { function delay(push, ms, x) { setTimeout(function () { push(null, x); }, ms); } var s = _(function (push, next) { delay(push, 10, 1); delay(push, 20, 1); delay(push, 30, 1); delay(push, 40, 1); delay(push, 50, 1); delay(push, 60, 1); delay(push, 70, 1); delay(push, 80, 1); delay(push, 90, _.nil); }); _.throttle(50, s).toArray(function (xs) { test.same(xs, [1, 1]); test.done(); }); this.clock.tick(90); }, 'let errors through regardless': function (test) { function delay(push, ms, err, x) { setTimeout(function () { push(err, x); }, ms); } var s = _(function (push, next) { delay(push, 10, null, 1); delay(push, 20, null, 1); delay(push, 30, null, 1); delay(push, 30, 'foo'); delay(push, 30, 'bar'); delay(push, 40, null, 1); delay(push, 50, null, 1); delay(push, 60, null, 1); delay(push, 70, null, 1); delay(push, 80, null, 1); delay(push, 90, null, _.nil); }); var errs = []; s.throttle(50).errors(function (err) { errs.push(err); }).toArray(function (xs) { test.same(xs, [1, 1]); test.same(errs, ['foo', 'bar']); test.done(); }); this.clock.tick(90); }, 'GeneratorStream': function (test) { function delay(push, ms, x) { setTimeout(function () { push(null, x); }, ms); } var s = _(function (push, next) { delay(push, 10, 1); delay(push, 20, 1); delay(push, 30, 1); delay(push, 40, 1); delay(push, 50, 1); delay(push, 60, 1); delay(push, 70, 1); delay(push, 80, 1); delay(push, 90, _.nil); }); s.throttle(30).toArray(function (xs) { test.same(xs, [1, 1, 1]); test.done(); }); this.clock.tick(90); } }; exports['debounce'] = { setUp: function (callback) { this.clock = sinon.useFakeTimers(); callback(); }, tearDown: function (callback) { this.clock.restore(); callback(); }, 'top-level': function (test) { function delay(push, ms, x) { setTimeout(function () { push(null, x); }, ms); } var s = _(function (push, next) { delay(push, 10, 1); delay(push, 20, 1); delay(push, 30, 1); delay(push, 40, 1); delay(push, 150, 1); delay(push, 160, 1); delay(push, 170, 1); delay(push, 180, 'last'); delay(push, 190, _.nil); }); _.debounce(100, s).toArray(function (xs) { test.same(xs, [1, 'last']); test.done(); }); this.clock.tick(200); }, 'GeneratorStream': function (test) { function delay(push, ms, x) { setTimeout(function () { push(null, x); }, ms); } var s = _(function (push, next) { delay(push, 10, 1); delay(push, 20, 1); delay(push, 30, 1); delay(push, 40, 1); delay(push, 150, 1); delay(push, 160, 1); delay(push, 170, 1); delay(push, 180, 'last'); delay(push, 190, _.nil); }); s.debounce(100).toArray(function (xs) { test.same(xs, [1, 'last']); test.done(); }); this.clock.tick(200); }, 'let errors through regardless': function (test) { function delay(push, ms, err, x) { setTimeout(function () { push(err, x); }, ms); } var s = _(function (push, next) { delay(push, 10, null, 1); delay(push, 20, null, 1); delay(push, 30, null, 1); delay(push, 30, 'foo'); delay(push, 30, 'bar'); delay(push, 40, null, 1); delay(push, 150, null, 1); delay(push, 260, null, 1); delay(push, 270, null, 1); delay(push, 280, null, 'last'); delay(push, 290, null, _.nil); }); var errs = []; s.debounce(100).errors(function (err) { errs.push(err); }).toArray(function (xs) { test.same(xs, [1, 1, 'last']); test.same(errs, ['foo', 'bar']); test.done(); }); this.clock.tick(300); } }; exports['latest'] = { setUp: function (callback) { this.clock = sinon.useFakeTimers(); callback(); }, tearDown: function (callback) { this.clock.restore(); callback(); }, 'top-level': function (test) { test.expect(1); function delay(push, ms, x) { setTimeout(function () { push(null, x); }, ms); } var s = _(function (push, next) { delay(push, 10, 1); delay(push, 20, 1); delay(push, 30, 1); delay(push, 40, 1); delay(push, 50, 1); delay(push, 60, 1); delay(push, 70, 1); delay(push, 80, 'last'); delay(push, 90, _.nil); }); var s2 = _.latest(s); var s3 = s2.consume(function (err, x, push, next) { push(err, x); setTimeout(next, 60); }); s3.toArray(function (xs) { // values at 0s, 60s, 120s test.same(xs, [1, 1, 'last']); test.done(); }); this.clock.tick(1000); }, 'GeneratorStream': function (test) { test.expect(1); function delay(push, ms, x) { setTimeout(function () { push(null, x); }, ms); } var s = _(function (push, next) { delay(push, 10, 1); delay(push, 20, 1); delay(push, 30, 1); delay(push, 40, 1); delay(push, 50, 1); delay(push, 60, 1); delay(push, 70, 1); delay(push, 80, 'last'); delay(push, 90, _.nil); }); var s2 = s.latest(); var s3 = s2.consume(function (err, x, push, next) { push(err, x); setTimeout(next, 60); }); s3.toArray(function (xs) { // values at 0s, 60s, 120s test.same(xs, [1, 1, 'last']); test.done(); }); this.clock.tick(1000); }, 'let errors pass through': function (test) { test.expect(2); function delay(push, ms, err, x) { setTimeout(function () { push(err, x); }, ms); } var s = _(function (push, next) { delay(push, 10, null, 1); delay(push, 20, null, 1); delay(push, 30, null, 1); delay(push, 30, 'foo', 1); delay(push, 30, 'bar', 1); delay(push, 40, null, 1); delay(push, 50, null, 1); delay(push, 60, null, 1); delay(push, 70, null, 1); delay(push, 80, null, 'last'); delay(push, 90, null, _.nil); }); var errs = []; var s2 = s.latest().errors(function (err) { errs.push(err); }); var s3 = s2.consume(function (err, x, push, next) { push(err, x); setTimeout(next, 60); }); s3.toArray(function (xs) { // values at 0s, 60s, 120s test.same(xs, [1, 1, 'last']); test.same(errs, ['foo', 'bar']); test.done(); }); this.clock.tick(1000); } }; exports['last'] = function (test) { test.expect(3); _([1,2,3,4]).last().toArray(function (xs) { test.same(xs, [4]); }); _.last([1,2,3,4]).toArray(function (xs) { test.same(xs, [4]); }); _.last([]).toArray(function (xs) { test.same(xs, []); }); test.done(); }; exports['through - function'] = function (test) { var s = _.through(function (s) { return s .filter(function (x) { return x % 2; }) .map(function (x) { return x * 2; }); }, [1,2,3,4]); s.toArray(function (xs) { test.same(xs, [2, 6]); test.done(); }); }; exports['through - function - ArrayStream'] = function (test) { var s = _([1,2,3,4]).through(function (s) { return s .filter(function (x) { return x % 2; }) .map(function (x) { return x * 2; }); }) .through(function (s) { return s.map(function (x) { return x + 1; }); }); s.toArray(function (xs) { test.same(xs, [3, 7]); test.done(); }); }; exports['through - stream'] = function (test) { var parser = through( function (data) { this.queue(JSON.parse(data)); }, function () { this.queue(null); } ); var s = _.through(parser, ['1','2','3','4']); s.toArray(function (xs) { test.same(xs, [1,2,3,4]); test.done(); }); }; exports['through - stream - ArrayStream'] = function (test) { var parser = through(function (data) { this.queue(JSON.parse(data)); }); var s = _(['1','2','3','4']).through(parser); s.toArray(function (xs) { test.same(xs, [1,2,3,4]); test.done(); }); }; exports['through - stream and function'] = function (test) { var parser = through( function (data) { this.queue(JSON.parse(data)); }, function () { this.queue(null); } ); var s = _(['1','2','3','4']) .through(parser) .through(function (s) { return s.map(function (x) { return x * 2; }); }); s.toArray(function (xs) { test.same(xs, [2,4,6,8]); test.done(); }); }; exports['pipeline'] = function (test) { var parser = through( function (data) { this.queue(JSON.parse(data)); }, function () { this.queue(null); } ); var doubler = _.map(function (x) { return x * 2; }); var parseDouble = _.pipeline(parser, doubler); var s = _(function (push, next) { push(null, 1); setTimeout(function () { push(null, 2); }, 10); setTimeout(function () { push(null, 3); }, 20); setTimeout(function () { push(null, 4); }, 30); setTimeout(function () { push(null, _.nil); }, 40); }); s.pipe(parseDouble).toArray(function (xs) { test.same(xs, [2,4,6,8]); test.done(); }); }; exports['pipeline - single through function'] = function (test) { var src = streamify([1,2,3,4]); var through = _.pipeline(function (s) { return s .filter(function (x) { return x % 2; }) .map(function (x) { return x * 2; }) .map(function (x) { return x + 10; }); }); src.pipe(through).toArray(function (xs) { test.same(xs, [12, 16]); test.done(); }); }; exports['pipeline - no arguments'] = function (test) { var src = streamify([1,2,3,4]); var through = _.pipeline(); src.pipe(through).toArray(function (xs) { test.same(xs, [1,2,3,4]); test.done(); }); }; // TODO: test lazy getting of values from obj keys (test using getters?) exports['values'] = function (test) { var obj = { foo: 1, bar: 2, baz: 3 }; _.values(obj).toArray(function (xs) { test.same(xs, [1, 2, 3]); test.done(); }); }; exports['values - lazy property access'] = function (test) { var calls = []; var obj = { get foo() { calls.push('foo'); return 1; }, get bar() { calls.push('bar'); return 2; }, get baz() { calls.push('baz'); return 3; } }; _.values(obj).take(2).toArray(function (xs) { test.same(calls, ['foo', 'bar']); test.same(xs, [1, 2]); test.done(); }); }; exports['keys'] = function (test) { var obj = { foo: 1, bar: 2, baz: 3 }; _.keys(obj).toArray(function (xs) { test.same(xs, ['foo', 'bar', 'baz']); test.done(); }); }; exports['pairs'] = function (test) { var obj = { foo: 1, bar: 2, baz: {qux: 3} }; _.pairs(obj).toArray(function (xs) { test.same(xs, [ ['foo', 1], ['bar', 2], ['baz', {qux: 3}] ]); test.done(); }); }; exports['pairs - lazy property access'] = function (test) { var calls = []; var obj = { get foo() { calls.push('foo'); return 1; }, get bar() { calls.push('bar'); return 2; }, get baz() { calls.push('baz'); return {qux: 3}; } }; _.pairs(obj).take(2).toArray(function (xs) { test.same(calls, ['foo', 'bar']); test.same(xs, [ ['foo', 1], ['bar', 2] ]); test.done(); }); }; exports['extend'] = function (test) { var a = {a: 1, b: {num: 2, test: 'test'}}; test.equal(a, _.extend({b: {num: 'foo'}, c: 3}, a)); test.same(a, {a: 1, b: {num: 'foo'}, c: 3}); // partial application test.equal(a, _.extend({b: 'baz'})(a)); test.same(a, {a: 1, b: 'baz', c: 3}); test.done(); }; exports['get'] = function (test) { var a = {foo: 'bar', baz: 123}; test.equal(_.get('foo', a), 'bar'); test.equal(_.get('baz')(a), 123); test.done(); }; exports['set'] = function (test) { var a = {foo: 'bar', baz: 123}; test.equal(_.set('foo', 'asdf', a), a); test.equal(a.foo, 'asdf'); test.equal(_.set('wibble', 'wobble')(a), a); test.equal(a.wibble, 'wobble'); test.same(a, {foo: 'asdf', baz: 123, wibble: 'wobble'}); test.done(); }; // TODO: failing case in another program - consume stream and switch to // new async source using next, then follow the consume with flatten() // // in fact, a simple .consume().flatten() failed with async sub-source to be // flattened, but curiously, it worked by doing .consume().map().flatten() // where the map() was just map(function (x) { return x; }) exports['log'] = function (test) { var calls = []; var _log = console.log; console.log = function (x) { calls.push(x); }; _.log('foo'); _.log('bar'); test.same(calls, ['foo', 'bar']); console.log = _log; test.done(); }; exports['wrapCallback'] = function (test) { var f = function (a, b, cb) { setTimeout(function () { cb(null, a + b); }, 10); }; _.wrapCallback(f)(1, 2).toArray(function (xs) { test.same(xs, [3]); test.done(); }); }; exports['wrapCallback - errors'] = function (test) { var f = function (a, b, cb) { cb(new Error('boom')); }; test.throws(function () { _.wrapCallback(f)(1, 2).toArray(function () { test.ok(false, "this shouldn't be called"); }); }); test.done(); }; exports['add'] = function (test) { test.equal(_.add(1, 2), 3); test.equal(_.add(3)(2), 5); return test.done(); }; exports['not'] = function (test) { test.equal(_.not(true), false); test.equal(_.not(123), false); test.equal(_.not("asdf"), false); test.equal(_.not(false), true); test.equal(_.not(0), true); test.equal(_.not(""), true); test.equal(_.not(null), true); test.equal(_.not(undefined), true); return test.done(); };
26.284324
102
0.465706
52a3f9de369c463b3b376951338d229223250717
488
js
JavaScript
test/kalos_test.js
kalos-framework/kalos
8e49ee1d17a2c9fbcae4dd49011d32bb306a23ea
[ "MIT" ]
1
2019-08-08T05:19:28.000Z
2019-08-08T05:19:28.000Z
test/kalos_test.js
kalos-framework/kalos
8e49ee1d17a2c9fbcae4dd49011d32bb306a23ea
[ "MIT" ]
4
2019-08-08T02:57:55.000Z
2019-08-10T20:03:40.000Z
test/kalos_test.js
kalos-framework/kalos
8e49ee1d17a2c9fbcae4dd49011d32bb306a23ea
[ "MIT" ]
null
null
null
import Kalos from '../index'; import cookieParser from 'cookie-parser'; const server = new Kalos.Server() .use(cookieParser()) .get('/', (req, res) => { res.end('Home'); }) .get('/hello/:name', (req, res) => { res.end('Hello ' + req.params.name); }) .get('/cookies', (req, res) => { console.log(req.cookies); res.end('Cookie'); }) .start((ip, port) => { console.log('Server started a: ' + ip + ':' + port); });
25.684211
60
0.5
52a4e60ffc8a3ec80631d4b71196c9f20e6ca9e0
1,312
js
JavaScript
blueprints/redux/files/src/redux/__name__.js
nslobodian/react-admin-generator
487b68621bdedbb86874419be2471dcb64c35ef2
[ "MIT" ]
3
2019-03-14T10:31:37.000Z
2020-02-16T13:47:35.000Z
blueprints/redux/files/src/redux/__name__.js
nslobodian/react-admin-generator
487b68621bdedbb86874419be2471dcb64c35ef2
[ "MIT" ]
null
null
null
blueprints/redux/files/src/redux/__name__.js
nslobodian/react-admin-generator
487b68621bdedbb86874419be2471dcb64c35ef2
[ "MIT" ]
1
2019-06-18T12:50:34.000Z
2019-06-18T12:50:34.000Z
import createReducer from 'utils/createReducer' import { actionCreator, reducerHelper } from 'store/helpers' // ------------------------------------ // Constants // ------------------------------------ export const GET_<%= pascalEntityName.toUpperCase() %>_ATTEMPT = '<%= pascalEntityName.toUpperCase() %>.GET_<%= pascalEntityName.toUpperCase() %>_ATTEMPT' export const GET_<%= pascalEntityName.toUpperCase() %>_SUCCESSFULLY = '<%= pascalEntityName.toUpperCase() %>.GET_<%= pascalEntityName.toUpperCase() %>_SUCCESSFULLY' export const GET_<%= pascalEntityName.toUpperCase() %>_FAILURE = '<%= pascalEntityName.toUpperCase() %>.GET_<%= pascalEntityName.toUpperCase() %>_FAILURE' // ------------------------------------ // Actions // ------------------------------------ export const get<%= pascalEntityName %>Attempt = actionCreator(GET_<%= pascalEntityName.toUpperCase() %>_ATTEMPT) // ------------------------------------ // Reducer // ------------------------------------ const initialState = { get<%= pascalEntityName.toUpperCase() %>: false } const reducers = reducerHelper([ GET_<%= pascalEntityName.toUpperCase() %>_ATTEMPT, GET_<%= pascalEntityName.toUpperCase() %>_SUCCESSFULLY, GET_<%= pascalEntityName.toUpperCase() %>_FAILURE ]) export default createReducer(initialState, { ...reducers, })
38.588235
164
0.613567
52a565b40c0df0a0d31260881f2e2702e88106ab
3,917
js
JavaScript
awx/ui/client/src/inventories-hosts/hosts/list/host-list.controller.js
doziya/ansible
96f7371493043e2ae596d059f2ca990bd0a28ad5
[ "Apache-2.0" ]
1
2021-01-24T09:08:10.000Z
2021-01-24T09:08:10.000Z
awx/ui/client/src/inventories-hosts/hosts/list/host-list.controller.js
doziya/ansible
96f7371493043e2ae596d059f2ca990bd0a28ad5
[ "Apache-2.0" ]
4
2020-04-29T23:03:16.000Z
2022-03-01T23:56:09.000Z
awx/ui/client/src/inventories-hosts/hosts/list/host-list.controller.js
doziya/ansible
96f7371493043e2ae596d059f2ca990bd0a28ad5
[ "Apache-2.0" ]
1
2018-06-06T08:47:22.000Z
2018-06-06T08:47:22.000Z
/************************************************* * Copyright (c) 2017 Ansible, Inc. * * All Rights Reserved *************************************************/ function HostsList($scope, HostsList, $rootScope, GetBasePath, rbacUiControlService, Dataset, $state, $filter, Prompt, Wait, HostsService, SetStatus, canAdd) { let list = HostsList; init(); function init(){ $scope.canAdd = canAdd; $scope.enableSmartInventoryButton = false; // Search init $scope.list = list; $scope[`${list.iterator}_dataset`] = Dataset.data; $scope[list.name] = $scope[`${list.iterator}_dataset`].results; $rootScope.flashMessage = null; $scope.$watchCollection(list.name, function() { $scope[list.name] = _.map($scope.hosts, function(value) { value.inventory_name = value.summary_fields.inventory.name; value.inventory_id = value.summary_fields.inventory.id; return value; }); setJobStatus(); }); $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams) { if(toParams && toParams.host_search) { let hasMoreThanDefaultKeys = false; angular.forEach(toParams.host_search, function(value, key) { if(key !== 'order_by' && key !== 'page_size') { hasMoreThanDefaultKeys = true; } }); $scope.enableSmartInventoryButton = hasMoreThanDefaultKeys ? true : false; } else { $scope.enableSmartInventoryButton = false; } }); } function setJobStatus(){ _.forEach($scope.hosts, function(value) { SetStatus({ scope: $scope, host: value }); }); } $scope.createHost = function(){ $state.go('hosts.add'); }; $scope.editHost = function(id){ $state.go('hosts.edit', {host_id: id}); }; $scope.goToInsights = function(id){ $state.go('hosts.edit.insights', {host_id:id}); }; $scope.toggleHost = function(event, host) { try { $(event.target).tooltip('hide'); } catch (e) { // ignore } host.enabled = !host.enabled; HostsService.put(host).then(function(){ $state.go($state.current, null, {reload: true}); }); }; $scope.smartInventory = function() { // Gather up search terms and pass them to the add smart inventory form let stateParamsCopy = angular.copy($state.params.host_search); let defaults = _.find($state.$current.path, (step) => { if(step && step.params && step.params.hasOwnProperty(`host_search`)){ return step.params.hasOwnProperty(`host_search`); } }).params[`host_search`].config.value; // Strip defaults out of the state params copy angular.forEach(Object.keys(defaults), function(value) { delete stateParamsCopy[value]; }); $state.go('inventories.addSmartInventory', {hostfilter: JSON.stringify(stateParamsCopy)}); }; $scope.editInventory = function(host) { if(host.summary_fields && host.summary_fields.inventory) { if(host.summary_fields.inventory.kind && host.summary_fields.inventory.kind === 'smart') { $state.go('inventories.editSmartInventory', {smartinventory_id: host.inventory}); } else { $state.go('inventories.edit', {inventory_id: host.inventory}); } } }; } export default ['$scope', 'HostsList', '$rootScope', 'GetBasePath', 'rbacUiControlService', 'Dataset', '$state', '$filter', 'Prompt', 'Wait', 'HostsService', 'SetStatus', 'canAdd', HostsList ];
32.915966
102
0.546336
52a587c5f1cd623c715b21aeafa47c952b55dbd6
3,008
js
JavaScript
src/logic.js
sridhar-5/battle-snake-workshop
40bef5a0603b8e848ecd5afcf62dfd261d418237
[ "MIT" ]
2
2022-01-22T17:04:51.000Z
2022-01-23T13:00:08.000Z
src/logic.js
sridhar-5/battle-snake-workshop
40bef5a0603b8e848ecd5afcf62dfd261d418237
[ "MIT" ]
null
null
null
src/logic.js
sridhar-5/battle-snake-workshop
40bef5a0603b8e848ecd5afcf62dfd261d418237
[ "MIT" ]
null
null
null
function info() { console.log("INFO"); const response = { apiversion: "1", author: "", color: "#888888", head: "default", tail: "default", }; return response; } function start(gameState) { console.log(`${gameState.game.id} START`); } function end(gameState) { console.log(`${gameState.game.id} END\n`); } function move(gameState) { const possibleMoves = ["up", "down", "left", "right"]; var SafeMoves = GetSafeMoves(gameState, possibleMoves); console.log(SafeMoves); //if the no of safe moves are greater than 1 if (SafeMoves) { var moveChoosen = SafeMoves[Math.floor(Math.random() * SafeMoves.length())]; } else { // if there are no other safe moves moveChoosen = possibleMoves[Math.floor(Math.random() * possibleMoves.length())]; } //preparing the response var response = { move: moveChoosen, }; //log the choosen move to make debuggin easier if you have to console.log(`${gameState.game.id} MOVE ${gameState.turn}: ${response.move}`); return response; } function GetSafeMoves(gameState, possibleMoves) { var SafeMoves = []; //this is the snake body const OurSnakeBody = gameState["you"]["body"]; //checker head details const SnakeHead = gameState["you"]["head"]; const getBoardDetails = gameState["board"]; //wall of the snake is at x != 11 or y != 11 // x !< 0 y !< 0 // its a fact that head is what is leading the snake to any direction so head.x < 11 and head.y < 11 shoul;d d0 possibleMoves.forEach((move) => { var GetCoordinates = getNextCoordinatesOfTheMove(SnakeHead, move); var SnakeTail = OurSnakeBody[OurSnakeBody.length - 1]; var SnakeBodyExceptTail = OurSnakeBody.slice(0, OurSnakeBody.length - 2); //analyze the board and other snakes if ( avoidHittingTheWalls( GetCoordinates, getBoardDetails["height"], getBoardDetails["width"] ) ) { SafeMoves.push(move); } else if ( OurSnakeBody.length > 1 && JSON.stringify(GetCoordinates) == JSON.stringify(SnakeTail) && CheckSnakeHeadNotInBody(GetCoordinates, SnakeBodyExceptTail) ) { SafeMoves.push(move); } }); return SafeMoves; } function avoidHittingTheWalls(HeadCoordinates, height, width) { var result = true; if ( HeadCoordinates.x < 0 || HeadCoordinates.y < 0 || HeadCoordinates.x >= width || HeadCoordinates.y >= height ) { result = false; } else { result = true; } return result; } function getNextCoordinatesOfTheMove(SnakeHead, move) { var futureHeadOfSnake = Object.assign({}, SnakeHead); if (move == "up") { futureHeadOfSnake.y = SnakeHead.y + 1; } if (move == "down") { futureHeadOfSnake.y = SnakeHead.y - 1; } if (move == "left") { futureHeadOfSnake.x = SnakeHead.x - 1; } if (move == "right") { futureHeadOfSnake.x = SnakeHead.x + 1; } return futureHeadOfSnake; } module.exports = { info: info, start: start, move: move, end: end, };
24.655738
113
0.644282
52a6829ca2efd256ad3f259f746126459248a6fe
156
js
JavaScript
src/components/js/app.js
i-dc/i-dc.github.io
36d802295c44e81c22f4eb9d3262285af04ca64e
[ "MIT" ]
null
null
null
src/components/js/app.js
i-dc/i-dc.github.io
36d802295c44e81c22f4eb9d3262285af04ca64e
[ "MIT" ]
null
null
null
src/components/js/app.js
i-dc/i-dc.github.io
36d802295c44e81c22f4eb9d3262285af04ca64e
[ "MIT" ]
null
null
null
export default { name: "VcardApp", data: () => ({ ready: false }), methods: {}, mounted() { this.ready = true; } };
14.181818
26
0.423077
52a723de12790842a6ef507ad54338263b670b49
898
js
JavaScript
__test__/server.test.js
roukia-401-advanced-javascript/api-server
cccf46d222de7c308048514845258dbe7a56ff39
[ "MIT" ]
null
null
null
__test__/server.test.js
roukia-401-advanced-javascript/api-server
cccf46d222de7c308048514845258dbe7a56ff39
[ "MIT" ]
null
null
null
__test__/server.test.js
roukia-401-advanced-javascript/api-server
cccf46d222de7c308048514845258dbe7a56ff39
[ "MIT" ]
1
2020-09-13T17:59:32.000Z
2020-09-13T17:59:32.000Z
'use strict'; // take the whole obj const { server } = require('../lib/server.js'); const supertest = require('supertest'); const mockRequest = supertest(server); // mock server describe('web server', () => { it('should respond with 404 for not found routes', () => { return mockRequest.get('/anythingElseMyRoutes').then(result => { expect(result.status).toBe(404); }).catch(err => { console.log(err); }); }); // it('should respond with 200 for good routes', () => { // return mockRequest.get('/products').then(result => { // expect(result.status).toBe(200); // }).catch(err => { // console.log(err); // }); // }); it('should respond with 500 for bad routes', ()=>{ return mockRequest.get('/bad').then(result=>{ expect(result.status).toBe(500); }).catch(err=> { console.log(err); }); }); });
24.944444
68
0.565702
52a77ba989fdf50d492eb1ae5246226c2c07faf4
2,999
js
JavaScript
src/elements/basicelement.js
pratyushcrd/canvaslitejs
41ad6d2c1fa5ca070dbd7e138e69fa1f9a0d3879
[ "MIT" ]
1
2019-07-03T15:13:25.000Z
2019-07-03T15:13:25.000Z
src/elements/basicelement.js
pratyushcrd/canvaslitejs
41ad6d2c1fa5ca070dbd7e138e69fa1f9a0d3879
[ "MIT" ]
null
null
null
src/elements/basicelement.js
pratyushcrd/canvaslitejs
41ad6d2c1fa5ca070dbd7e138e69fa1f9a0d3879
[ "MIT" ]
null
null
null
const consts = require('../utils/constants'), errors = require('../utils/error'), availableTypes = consts.availableTypes, has = consts.has, libName = consts.name let addAttrToConfig = function (configOb, attrsOb) { let key, val if (typeof configOb !== 'object') { return } // validating availableAttrs types and putting // then on the config's available attrs for (key in attrsOb) { val = attrsOb[key] if (attrsOb[has](key) && availableTypes[val]) { configOb[key] = attrsOb[key]; } } }, setAttr = function (ob, attrs, defAttrs) { let key, value if (!ob) { return } for (key in ob) { value = ob[key]; if (ob[has](key) && defAttrs[key]) { attrs[key] = value } } } // Exporting a function so that basicelement // can be registered to constructor module.exports = function (CanvasLite) { let sanityCheck = function (canvas, group) { if (!(canvas instanceof CanvasLite)) { errors.notAnInstance('canvas', libName) } } class BasicElement { constructor (canvasInstance, group, attrsDef, defValues) { let config, key = '', availableAttrs sanityCheck(canvasInstance, group) // Defining a configuration on the instance config = this.config = {} // Defining available attrs list availableAttrs = config.attrs = {} addAttrToConfig(availableAttrs, attrsDef) // Saving instance of canvas config.canvas = canvasInstance // saving blank attrs to object this.attrs = {} // If group provide add this element to group group && group.addChild(this) // Applying default values this.attr(defValues); } attr (ob) { let element = this, key = '', value, attrs = element.attrs, config = element.config, defAttrs = config.attrs // this function will behave both // as getter and setter if (typeof ob === 'string') { return attrs[ob] } setAttr(ob, attrs, defAttrs) return element } // Internal function // Set a parent __setParent (group) { let config = this.config // Remove self from previous parent config.parent && config.parent.removeChild(this) config.parent = group; return this } // Ask parent group to bring this // element to front bringToFront () { let parent = this.config.parent parent && parent.__bringToFront(this) return this } // Ask parent group to bring this // element to front sendToBack () { let parent = this.config.parent parent && parent.__sendToBack(this) return this } // inner paint function to be extended by // other elements to draw itself __paint (ctx) { } } CanvasLite.registerComponent('BasicElement', BasicElement) }
27.018018
61
0.58853
52a7b20b695aecc251c6d912e4bc09ad9a306b5e
736
js
JavaScript
models/market.js
AltCoinBuilders/xrp-telegram-bot
831da4626edc60af69cb2c35ca8c42c7e54f7ddc
[ "Apache-2.0" ]
12
2019-02-15T17:25:01.000Z
2021-12-12T09:46:34.000Z
models/market.js
AltCoinBuilders/xrp-telegram-bot
831da4626edc60af69cb2c35ca8c42c7e54f7ddc
[ "Apache-2.0" ]
4
2019-10-16T21:17:02.000Z
2022-01-22T03:57:39.000Z
models/market.js
AltCoinBuilders/xrp-telegram-bot
831da4626edc60af69cb2c35ca8c42c7e54f7ddc
[ "Apache-2.0" ]
12
2019-09-22T16:12:40.000Z
2021-12-07T22:59:24.000Z
'use strict'; module.exports = function(sequelize, DataTypes) { const Market = sequelize.define('Market', { pair: { type: DataTypes.STRING(), allowNull: false, }, ticker: { type: DataTypes.JSON(), allowNull: false, }, source: { type: DataTypes.STRING(), allowNull: false, }, }); Market.prototype.calculate = function(amount, pair) { return Market.findOne({ where: { pair, }, }).then(m => { const ticker = JSON.parse(m.ticker); return Math.round(amount * ticker.price * 100) / 100; }); }; return Market; };
23.741935
65
0.46875
52a87c9274ae6a1827606ec83974cfd0e2ad56e8
3,845
js
JavaScript
packages/core/addon/utils/chart-data.js
Ruiqian1/navi
2348ea4f6ff8c1683f597fdb83a25a5c3c3f65c2
[ "MIT" ]
null
null
null
packages/core/addon/utils/chart-data.js
Ruiqian1/navi
2348ea4f6ff8c1683f597fdb83a25a5c3c3f65c2
[ "MIT" ]
null
null
null
packages/core/addon/utils/chart-data.js
Ruiqian1/navi
2348ea4f6ff8c1683f597fdb83a25a5c3c3f65c2
[ "MIT" ]
null
null
null
/** * Copyright 2018, Yahoo Holdings Inc. * Licensed under the terms of the MIT license. See accompanying LICENSE.md file for terms. */ import { A as arr } from '@ember/array'; import { get } from '@ember/object'; import DataGroup from 'navi-core/utils/classes/data-group'; import objectValues from 'lodash/values'; export const METRIC_SERIES = 'metric'; export const DIMENSION_SERIES = 'dimension'; export const DATE_TIME_SERIES = 'dateTime'; /** * Group data by dimensions * * @method groupDataByDimensions * @param {Array} rows - rows from bard response * @param {Array} config.dimensions - list of dimensions to chart * @returns {DataGroup} rows grouped by composite key */ export function groupDataByDimensions(rows, config) { let dimensionOrder = config.dimensionOrder, byDimensions = new DataGroup(rows, row => dimensionOrder.map(dimension => row[`${dimension}|id`]).join('|')); return byDimensions; } /** * Build series key * * @method buildSeriesKey * @param {Array} config.dimensions - list of dimensions to chart * @returns {series} the built series */ export function buildSeriesKey(config) { let dimensionOrder = config.dimensionOrder, series = config.dimensions; return series.map(s => dimensionOrder.map(dimension => s.values[dimension]).join('|')); } /** * Get series name * * @method getSeriesName * @param {Array} config.dimensions - list of dimensions to chart * @returns {seriesName} series Name */ export function getSeriesName(config) { let series = config.dimensions; // Return the series name in an array return series.map(s => s.name); } /** * Determine chart type based on request * * @function chartTypeForRequest * @param {Object} request - request object * @returns {Boolean} */ export function chartTypeForRequest(request) { let dimensionCount = get(request, 'dimensions.length'); if (dimensionCount > 0) { return DIMENSION_SERIES; } let metricCount = get(request, 'metrics.length'), timeGrain = get(request, 'logicalTable.timeGrain.name'), interval = get(request, 'intervals.firstObject.interval'), monthPeriod = interval.diffForTimePeriod('month'), applicableTimeGrain = ['day', 'week', 'month'].includes(timeGrain); if (metricCount === 1 && monthPeriod > 12 && applicableTimeGrain) { return DATE_TIME_SERIES; } return METRIC_SERIES; } /** * Returns a list of metric names from the request * * @function getRequestMetrics * @param {Object} request - request object * @returns {Array} - list of metric JSON objects */ export function getRequestMetrics(request) { return get(request, 'metrics').map(metric => metric.toJSON()); } /** * Returns a list of dimensions names from the request * * @function getRequestDimensions * @param {Object} request - request object * @returns {Array} - list of dimension names */ export function getRequestDimensions(request) { return arr(get(request, 'dimensions')).mapBy('dimension.name'); } /** * Returns an object for the dimension series values * * @function buildDimensionSeriesValues * @param {Object} request - request object * @param {Array} rows - response rows * @returns {Object} - config series values object */ export function buildDimensionSeriesValues(request, rows) { let series = {}; let requestDimensions = getRequestDimensions(request); rows.forEach(row => { let values = {}, dimensionLabels = []; requestDimensions.forEach(dimension => { let id = get(row, `${dimension}|id`), desc = get(row, `${dimension}|desc`); values[dimension] = id; dimensionLabels.push(desc || id); }); //Use object key to dedup dimension value combinations series[objectValues(values).join('|')] = { name: dimensionLabels.join(','), values }; }); return objectValues(series); }
27.862319
113
0.698309
52a8c299a53347320a99a74cd8c09b081e37c004
2,310
js
JavaScript
modules/irc.js
DavidJoacaRo/lambdapse
6742e72ad25ab449a7cccd7770f646c1b7ac148a
[ "MIT" ]
null
null
null
modules/irc.js
DavidJoacaRo/lambdapse
6742e72ad25ab449a7cccd7770f646c1b7ac148a
[ "MIT" ]
null
null
null
modules/irc.js
DavidJoacaRo/lambdapse
6742e72ad25ab449a7cccd7770f646c1b7ac148a
[ "MIT" ]
null
null
null
module.exports.name = 'Discord-IRC Integration'; // Lambdapse Discord-IRC Integration // If you want to link other channels on both ends, make a copy of this file, and make sure to change the Discord channel ID // Discord-related stuff // Channel ID. Where will the bot send messages and listen for messages const discordchannel = '837435373239795744'; // How will the message show up on Discord // Example: // donkeykong50 => #forest: Oh, these are pretty cool bananas const ircmsgformat = '`**(NAME)** => **(CHANNEL):** (MESSAGE)`'; // IRC-related stuff // What server will the bot connect to? const server = 'irc.freenode.net'; // The bot's nickname in the IRC server const nick = require('../messages.json').bot_name; // Which channel should it connect to const ircchannel = '#freenode'; // How will the message show up on IRC // Example: // donkeykong#6969: Oh, these are pretty cool bananas const discordmsgformat = '`(TAG): (MESSAGE)`'; // Is this module enabled? // If this is set to false, the module will do nothing // If set to true, the module will listen for messages in both IRC and Discord. Useful if you have an IRC server/channel on freenode const enabled = false; // Code for the module if (enabled == true) { const colors = require('colors'); console.log('[INFO]'.blue + ' IRC module is ' + 'ENABLED'.green); const irc = require('irc'); const discordclient = require('../shard.js').client; const ircclient = new irc.Client(server, nick, { channels: channel, }); ircclient.addListener('message', function (from, to, message) { const configchannel = discordclient.channels.cache.get(discordchannel); configchannel.send(ircmsgformat.replace('(NAME)', from).replace('(CHANNEL)', to).replace('(MESSAGE)', message).replace(/@everyone/g, '(a)everyone').replace(/@here/g, '(a)here')); }); discordclient.on(message, async (message) => { if (message.channel.id !== discordchannel || message.author.bot) return; ircclient.say(ircchannel, discordmsgformat.replace('(TAG)', message.author.tag).replace('(MESSAGE)', message.content)); }) process.on('SIGTERM', () => { client.part(ircchannel); console.log('[STATUS]'.green + ` Left channel ${ircchannel}`); }) } else { console.log('[INFO]'.blue + ' IRC module is ' + 'DISABLED'.red); }
37.258065
184
0.693074
52aab3b89d643a57c997b643b8c1f4c4623c3d19
629
js
JavaScript
src/templates/BasicPage.js
ramojej/100-days-of-gatsby
fb53d18f3893a410968be5861cae34d32b4b3901
[ "RSA-MD" ]
null
null
null
src/templates/BasicPage.js
ramojej/100-days-of-gatsby
fb53d18f3893a410968be5861cae34d32b4b3901
[ "RSA-MD" ]
null
null
null
src/templates/BasicPage.js
ramojej/100-days-of-gatsby
fb53d18f3893a410968be5861cae34d32b4b3901
[ "RSA-MD" ]
null
null
null
import { graphql } from "gatsby" import React from "react" import Layout from "../components/layout" const BasicPage = ({ data: { wpPage: { title, content }, }, }) => { return ( <Layout> <div className="container px-4 mx-auto mt-8 h-screen"> <h2 className="text-2xl font-semibold">{title}</h2> <div dangerouslySetInnerHTML={{ __html: content }} className="content mt-4" /> </div> </Layout> ) } export const query = graphql` query($id: String!) { wpPage(id: { eq: $id }) { id title content } } ` export default BasicPage
18.5
60
0.558029
52ab33379c199ccca2cd2cd7d5080c5e9ac11a6e
2,114
js
JavaScript
apps/bare-expo/e2e/TestSuite-test.web.js
Cofit/expo
02b6d9ef4b70b1e970b40f3f3e0364bb2c68fc63
[ "Apache-2.0", "MIT" ]
null
null
null
apps/bare-expo/e2e/TestSuite-test.web.js
Cofit/expo
02b6d9ef4b70b1e970b40f3f3e0364bb2c68fc63
[ "Apache-2.0", "MIT" ]
null
null
null
apps/bare-expo/e2e/TestSuite-test.web.js
Cofit/expo
02b6d9ef4b70b1e970b40f3f3e0364bb2c68fc63
[ "Apache-2.0", "MIT" ]
null
null
null
/* global page */ import { setDefaultOptions } from 'expect-puppeteer'; import config from '../jest-puppeteer.config'; import { expectResults } from './utils/report'; import { runTestsAsync } from './Utils'; const TESTS = [ { name: 'Sanity', tests: ['Basic'], }, { name: 'Core', tests: ['Asset', 'Constants', 'FileSystem', 'Font', 'Permissions'], }, { name: 'API', tests: ['Localization', 'SecureStore', 'Contacts', 'Random', 'Crypto'], }, // { // name: 'Components', // tests: [ // 'GLView', // ] // }, // { // name: 'Third-Party', // tests: [ // 'Segment', // ] // } ]; // This is how long we allocate for the actual tests to be run after the test screen has mounted. const MIN_TIME = 50000; const RENDER_MOUNTING_TIMEOUT = 500; setDefaultOptions({ timeout: MIN_TIME * 1.5, }); function matchID(id, ...props) { return expect(page).toMatchElement(`div[data-testid="${id}"]`, ...props); } // Add some extra time for page content loading (page.goto) and parsing the DOM runTestsAsync(TESTS, (MIN_TIME + RENDER_MOUNTING_TIMEOUT) * 1.2, async ({ testName }) => { /// Pause the timeout await page.goto(`${config.url}/test-suite/select/${testName}`); // await jestPuppeteer.debug(); // console.log(testName); // Ensure the app linked to the testing screen (give it 100ms for navigation mounting) await matchID('test_suite_container', { visible: true, timeout: RENDER_MOUNTING_TIMEOUT }); // Wait for the final result to be rendered. This means all the tests have finished. await matchID('test_suite_final_results', { visible: true, timeout: MIN_TIME }); // Get the DOM element matching the testID prop. // This text will contain the final results (parity with native) const element = await page.$(`div[data-testid="test_suite_final_results"]`); // Read the text contents and parse them as JSON const input = await (await element.getProperty('textContent')).jsonValue(); console.log(input); // Parse, expect, and print the results of our tests expectResults({ testName, input, }); });
29.361111
97
0.653264
52ab90cdddfc84a70bd09ce25e6532a9216a7f76
3,355
js
JavaScript
src/webui/components/AutoComplete/index.js
willsmythe/verdaccio
56e1d4becf3d297a8abed39ec565f4db6b2005e8
[ "MIT" ]
2
2019-05-03T14:35:44.000Z
2019-10-16T00:18:00.000Z
src/webui/components/AutoComplete/index.js
willsmythe/verdaccio
56e1d4becf3d297a8abed39ec565f4db6b2005e8
[ "MIT" ]
null
null
null
src/webui/components/AutoComplete/index.js
willsmythe/verdaccio
56e1d4becf3d297a8abed39ec565f4db6b2005e8
[ "MIT" ]
null
null
null
/** * @prettier * @flow */ import React from 'react'; import type { Node } from 'react'; import Autosuggest from 'react-autosuggest'; import match from 'autosuggest-highlight/match'; import parse from 'autosuggest-highlight/parse'; import Paper from '@material-ui/core/Paper'; import MenuItem from '@material-ui/core/MenuItem'; import { fontWeight } from '../../utils/styles/sizes'; import { Wrapper, InputField } from './styles'; import { IProps } from './types'; const renderInputComponent = (inputProps): Node => { const { ref, startAdornment, disableUnderline, onKeyDown, ...others } = inputProps; return ( <InputField InputProps={{ inputRef: node => { ref(node); }, startAdornment, disableUnderline, onKeyDown, }} fullWidth={true} {...others} /> ); }; const getSuggestionValue = (suggestion): string => suggestion.name; const renderSuggestion = (suggestion, { query, isHighlighted }): Node => { const matches = match(suggestion.name, query); const parts = parse(suggestion.name, matches); return ( <MenuItem component={'div'} selected={isHighlighted}> <div> {parts.map((part, index) => { return part.highlight ? ( <span href={suggestion.link} key={String(index)} style={{ fontWeight: fontWeight.semiBold }}> {part.text} </span> ) : ( <span href={suggestion.link} key={String(index)} style={{ fontWeight: fontWeight.light }}> {part.text} </span> ); })} </div> </MenuItem> ); }; const renderMessage = (message): Node => { return ( <MenuItem component={'div'} selected={false}> <div>{message}</div> </MenuItem> ); }; const SUGGESTIONS_RESPONSE = { LOADING: 'Loading...', FAILURE: 'Something went wrong.', NO_RESULT: 'No results found.', }; const AutoComplete = ({ suggestions, startAdornment, onChange, onSuggestionsFetch, onCleanSuggestions, value = '', placeholder = '', disableUnderline = false, color, onClick, onKeyDown, onBlur, suggestionsLoading = false, suggestionsLoaded = false, suggestionsError = false, }: IProps): Node => { const autosuggestProps = { renderInputComponent, suggestions, getSuggestionValue, renderSuggestion, onSuggestionsFetchRequested: onSuggestionsFetch, onSuggestionsClearRequested: onCleanSuggestions, }; const inputProps = { value, onChange, placeholder, startAdornment, disableUnderline, color, onKeyDown, onBlur, }; // this format avoid arrow function eslint rule function renderSuggestionsContainer({ containerProps, children, query }) { return ( <Paper {...containerProps} square={true}> {suggestionsLoaded && children === null && query && renderMessage(SUGGESTIONS_RESPONSE.NO_RESULT)} {suggestionsLoading && query && renderMessage(SUGGESTIONS_RESPONSE.LOADING)} {suggestionsError && renderMessage(SUGGESTIONS_RESPONSE.FAILURE)} {children} </Paper> ); } return ( <Wrapper> <Autosuggest {...autosuggestProps} inputProps={inputProps} onSuggestionSelected={onClick} renderSuggestionsContainer={renderSuggestionsContainer} /> </Wrapper> ); }; export default AutoComplete;
25.807692
154
0.642325
52aba6d241049f0b70c12f3c2bba6e3377af13cf
680
js
JavaScript
example/src/scenes/Slider/Vertical.js
TuyaInc/tuya-panel-kit-
fd129685a5c1e2079533d42a558d23dd8a5b2997
[ "MIT" ]
20
2018-12-21T10:01:43.000Z
2022-01-24T01:55:54.000Z
example/src/scenes/Slider/Vertical.js
TuyaInc/tuya-panel-kit-
fd129685a5c1e2079533d42a558d23dd8a5b2997
[ "MIT" ]
23
2019-05-10T01:24:39.000Z
2021-09-22T03:46:29.000Z
example/src/scenes/Slider/Vertical.js
TuyaInc/tuya-panel-kit-
fd129685a5c1e2079533d42a558d23dd8a5b2997
[ "MIT" ]
9
2020-07-17T08:16:15.000Z
2021-09-18T07:23:00.000Z
import React, { Component } from 'react'; import { View } from 'react-native'; import { Slider } from 'tuya-panel-kit'; export default class SliderVerticalScene extends Component { state = { value: 24, }; _handleComplete = value => { this.setState({ value: Math.round(value) }); }; render() { return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Slider.Vertical style={{ height: 200 }} value={this.state.value} minimumValue={0} maximumValue={100} minimumTrackTintColor="#ff0000" maximumTrackTintColor="#ff00ff" /> </View> ); } }
23.448276
80
0.577941
52ac5ab5e466b7e27f79300e3bd29c50a5af72db
23,462
js
JavaScript
node_modules/@react-md/theme/dist/scssVariables.js
yashpal64/Nayi-Website
57454390ff2bfd0ef67fb02ab30f406864aa87cd
[ "MIT" ]
null
null
null
node_modules/@react-md/theme/dist/scssVariables.js
yashpal64/Nayi-Website
57454390ff2bfd0ef67fb02ab30f406864aa87cd
[ "MIT" ]
null
null
null
node_modules/@react-md/theme/dist/scssVariables.js
yashpal64/Nayi-Website
57454390ff2bfd0ef67fb02ab30f406864aa87cd
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** this is an auto-generated file from @react-md/dev-utils */ exports.default = { "rmd-theme-default-contrast-ratio": 3, "rmd-red-50": "#ffebee", "rmd-red-100": "#ffcdd2", "rmd-red-200": "#ef9a9a", "rmd-red-300": "#e57373", "rmd-red-400": "#ef5350", "rmd-red-500": "#f44336", "rmd-red-600": "#e53935", "rmd-red-700": "#d32f2f", "rmd-red-800": "#c62828", "rmd-red-900": "#b71c1c", "rmd-red-a-100": "#ff8a80", "rmd-red-a-200": "#ff5252", "rmd-red-a-400": "#ff1744", "rmd-red-a-700": "#d50000", "rmd-pink-50": "#fce4ec", "rmd-pink-100": "#f8bbd0", "rmd-pink-200": "#f48fb1", "rmd-pink-300": "#f06292", "rmd-pink-400": "#ec407a", "rmd-pink-500": "#e91e63", "rmd-pink-600": "#d81b60", "rmd-pink-700": "#c2185b", "rmd-pink-800": "#ad1457", "rmd-pink-900": "#880e4f", "rmd-pink-a-100": "#ff80ab", "rmd-pink-a-200": "#ff4081", "rmd-pink-a-400": "#f50057", "rmd-pink-a-700": "#c51162", "rmd-purple-50": "#f3e5f5", "rmd-purple-100": "#e1bee7", "rmd-purple-200": "#ce93d8", "rmd-purple-300": "#ba68c8", "rmd-purple-400": "#ab47bc", "rmd-purple-500": "#9c27b0", "rmd-purple-600": "#8e24aa", "rmd-purple-700": "#7b1fa2", "rmd-purple-800": "#6a1b9a", "rmd-purple-900": "#4a148c", "rmd-purple-a-100": "#ea80fc", "rmd-purple-a-200": "#e040fb", "rmd-purple-a-400": "#d500f9", "rmd-purple-a-700": "#a0f", "rmd-deep-purple-50": "#ede7f6", "rmd-deep-purple-100": "#d1c4e9", "rmd-deep-purple-200": "#b39ddb", "rmd-deep-purple-300": "#9575cd", "rmd-deep-purple-400": "#7e57c2", "rmd-deep-purple-500": "#673ab7", "rmd-deep-purple-600": "#5e35b1", "rmd-deep-purple-700": "#512da8", "rmd-deep-purple-800": "#4527a0", "rmd-deep-purple-900": "#311b92", "rmd-deep-purple-a-100": "#b388ff", "rmd-deep-purple-a-200": "#7c4dff", "rmd-deep-purple-a-400": "#651fff", "rmd-deep-purple-a-700": "#6200ea", "rmd-indigo-50": "#e8eaf6", "rmd-indigo-100": "#c5cae9", "rmd-indigo-200": "#9fa8da", "rmd-indigo-300": "#7986cb", "rmd-indigo-400": "#5c6bc0", "rmd-indigo-500": "#3f51b5", "rmd-indigo-600": "#3949ab", "rmd-indigo-700": "#303f9f", "rmd-indigo-800": "#283593", "rmd-indigo-900": "#1a237e", "rmd-indigo-a-100": "#8c9eff", "rmd-indigo-a-200": "#536dfe", "rmd-indigo-a-400": "#3d5afe", "rmd-indigo-a-700": "#304ffe", "rmd-blue-50": "#e3f2fd", "rmd-blue-100": "#bbdefb", "rmd-blue-200": "#90caf9", "rmd-blue-300": "#64b5f6", "rmd-blue-400": "#42a5f5", "rmd-blue-500": "#2196f3", "rmd-blue-600": "#1e88e5", "rmd-blue-700": "#1976d2", "rmd-blue-800": "#1565c0", "rmd-blue-900": "#0d47a1", "rmd-blue-a-100": "#82b1ff", "rmd-blue-a-200": "#448aff", "rmd-blue-a-400": "#2979ff", "rmd-blue-a-700": "#2962ff", "rmd-light-blue-50": "#e1f5fe", "rmd-light-blue-100": "#b3e5fc", "rmd-light-blue-200": "#81d4fa", "rmd-light-blue-300": "#4fc3f7", "rmd-light-blue-400": "#29b6f6", "rmd-light-blue-500": "#03a9f4", "rmd-light-blue-600": "#039be5", "rmd-light-blue-700": "#0288d1", "rmd-light-blue-800": "#0277bd", "rmd-light-blue-900": "#01579b", "rmd-light-blue-a-100": "#80d8ff", "rmd-light-blue-a-200": "#40c4ff", "rmd-light-blue-a-400": "#00b0ff", "rmd-light-blue-a-700": "#0091ea", "rmd-cyan-50": "#e0f7fa", "rmd-cyan-100": "#b2ebf2", "rmd-cyan-200": "#80deea", "rmd-cyan-300": "#4dd0e1", "rmd-cyan-400": "#26c6da", "rmd-cyan-500": "#00bcd4", "rmd-cyan-600": "#00acc1", "rmd-cyan-700": "#0097a7", "rmd-cyan-800": "#00838f", "rmd-cyan-900": "#006064", "rmd-cyan-a-100": "#84ffff", "rmd-cyan-a-200": "#18ffff", "rmd-cyan-a-400": "#00e5ff", "rmd-cyan-a-700": "#00b8d4", "rmd-teal-50": "#e0f2f1", "rmd-teal-100": "#b2dfdb", "rmd-teal-200": "#80cbc4", "rmd-teal-300": "#4db6ac", "rmd-teal-400": "#26a69a", "rmd-teal-500": "#009688", "rmd-teal-600": "#00897b", "rmd-teal-700": "#00796b", "rmd-teal-800": "#00695c", "rmd-teal-900": "#004d40", "rmd-teal-a-100": "#a7ffeb", "rmd-teal-a-200": "#64ffda", "rmd-teal-a-400": "#1de9b6", "rmd-teal-a-700": "#00bfa5", "rmd-green-50": "#e8f5e9", "rmd-green-100": "#c8e6c9", "rmd-green-200": "#a5d6a7", "rmd-green-300": "#81c784", "rmd-green-400": "#66bb6a", "rmd-green-500": "#4caf50", "rmd-green-600": "#43a047", "rmd-green-700": "#388e3c", "rmd-green-800": "#2e7d32", "rmd-green-900": "#1b5e20", "rmd-green-a-100": "#b9f6ca", "rmd-green-a-200": "#69f0ae", "rmd-green-a-400": "#00e676", "rmd-green-a-700": "#00c853", "rmd-light-green-50": "#f1f8e9", "rmd-light-green-100": "#dcedc8", "rmd-light-green-200": "#c5e1a5", "rmd-light-green-300": "#aed581", "rmd-light-green-400": "#9ccc65", "rmd-light-green-500": "#8bc34a", "rmd-light-green-600": "#7cb342", "rmd-light-green-700": "#689f38", "rmd-light-green-800": "#558b2f", "rmd-light-green-900": "#33691e", "rmd-light-green-a-100": "#ccff90", "rmd-light-green-a-200": "#b2ff59", "rmd-light-green-a-400": "#76ff03", "rmd-light-green-a-700": "#64dd17", "rmd-lime-50": "#f9fbe7", "rmd-lime-100": "#f0f4c3", "rmd-lime-200": "#e6ee9c", "rmd-lime-300": "#dce775", "rmd-lime-400": "#d4e157", "rmd-lime-500": "#cddc39", "rmd-lime-600": "#c0ca33", "rmd-lime-700": "#afb42b", "rmd-lime-800": "#9e9d24", "rmd-lime-900": "#827717", "rmd-lime-a-100": "#f4ff81", "rmd-lime-a-200": "#eeff41", "rmd-lime-a-400": "#c6ff00", "rmd-lime-a-700": "#aeea00", "rmd-yellow-50": "#fffde7", "rmd-yellow-100": "#fff9c4", "rmd-yellow-200": "#fff59d", "rmd-yellow-300": "#fff176", "rmd-yellow-400": "#ffee58", "rmd-yellow-500": "#ffeb3b", "rmd-yellow-600": "#fdd835", "rmd-yellow-700": "#fbc02d", "rmd-yellow-800": "#f9a825", "rmd-yellow-900": "#f57f17", "rmd-yellow-a-100": "#ffff8d", "rmd-yellow-a-200": "#ff0", "rmd-yellow-a-400": "#ffea00", "rmd-yellow-a-700": "#ffd600", "rmd-amber-50": "#fff8e1", "rmd-amber-100": "#ffecb3", "rmd-amber-200": "#ffe082", "rmd-amber-300": "#ffd54f", "rmd-amber-400": "#ffca28", "rmd-amber-500": "#ffc107", "rmd-amber-600": "#ffb300", "rmd-amber-700": "#ffa000", "rmd-amber-800": "#ff8f00", "rmd-amber-900": "#ff6f00", "rmd-amber-a-100": "#ffe57f", "rmd-amber-a-200": "#ffd740", "rmd-amber-a-400": "#ffc400", "rmd-amber-a-700": "#ffab00", "rmd-orange-50": "#fff3e0", "rmd-orange-100": "#fff0b2", "rmd-orange-200": "#ffcc80", "rmd-orange-300": "#ffb74d", "rmd-orange-400": "#ffa726", "rmd-orange-500": "#ff9800", "rmd-orange-600": "#fb8c00", "rmd-orange-700": "#f57c00", "rmd-orange-800": "#ef6c00", "rmd-orange-900": "#e65100", "rmd-orange-a-100": "#ffd180", "rmd-orange-a-200": "#ffab40", "rmd-orange-a-400": "#ff9100", "rmd-orange-a-700": "#ff6d00", "rmd-deep-orange-50": "#fbe9e7", "rmd-deep-orange-100": "#ffccbc", "rmd-deep-orange-200": "#ffab91", "rmd-deep-orange-300": "#ff8a65", "rmd-deep-orange-400": "#ff7043", "rmd-deep-orange-500": "#ff5722", "rmd-deep-orange-600": "#f4511e", "rmd-deep-orange-700": "#e64a19", "rmd-deep-orange-800": "#d84315", "rmd-deep-orange-900": "#bf360c", "rmd-deep-orange-a-100": "#ff9e80", "rmd-deep-orange-a-200": "#ff6e40", "rmd-deep-orange-a-400": "#ff3d00", "rmd-deep-orange-a-700": "#dd2c00", "rmd-brown-50": "#efebe9", "rmd-brown-100": "#d7ccc8", "rmd-brown-200": "#bcaaa4", "rmd-brown-300": "#a1887f", "rmd-brown-400": "#8d6e63", "rmd-brown-500": "#795548", "rmd-brown-600": "#6d4c41", "rmd-brown-700": "#5d4037", "rmd-brown-800": "#4e342e", "rmd-brown-900": "#3e2723", "rmd-grey-50": "#fafafa", "rmd-grey-100": "#f5f5f5", "rmd-grey-200": "#eee", "rmd-grey-300": "#e0e0e0", "rmd-grey-400": "#bdbdbd", "rmd-grey-500": "#9e9e9e", "rmd-grey-600": "#757575", "rmd-grey-700": "#616161", "rmd-grey-800": "#424242", "rmd-grey-900": "#212121", "rmd-blue-grey-50": "#eceff1", "rmd-blue-grey-100": "#cfd8dc", "rmd-blue-grey-200": "#b0bec5", "rmd-blue-grey-300": "#90a4ae", "rmd-blue-grey-400": "#78909c", "rmd-blue-grey-500": "#607d8b", "rmd-blue-grey-600": "#546e7a", "rmd-blue-grey-700": "#455a64", "rmd-blue-grey-800": "#37474f", "rmd-blue-grey-900": "#263238", "rmd-black-base": "#000", "rmd-white-base": "#fff", "rmd-theme-color-map": { "rmd-red-50": "#ffebee", "rmd-red-100": "#ffcdd2", "rmd-red-200": "#ef9a9a", "rmd-red-300": "#e57373", "rmd-red-400": "#ef5350", "rmd-red-500": "#f44336", "rmd-red-600": "#e53935", "rmd-red-700": "#d32f2f", "rmd-red-800": "#c62828", "rmd-red-900": "#b71c1c", "rmd-red-a-100": "#ff8a80", "rmd-red-a-200": "#ff5252", "rmd-red-a-400": "#ff1744", "rmd-red-a-700": "#d50000", "rmd-pink-50": "#fce4ec", "rmd-pink-100": "#f8bbd0", "rmd-pink-200": "#f48fb1", "rmd-pink-300": "#f06292", "rmd-pink-400": "#ec407a", "rmd-pink-500": "#e91e63", "rmd-pink-600": "#d81b60", "rmd-pink-700": "#c2185b", "rmd-pink-800": "#ad1457", "rmd-pink-900": "#880e4f", "rmd-pink-a-100": "#ff80ab", "rmd-pink-a-200": "#ff4081", "rmd-pink-a-400": "#f50057", "rmd-pink-a-700": "#c51162", "rmd-purple-50": "#f3e5f5", "rmd-purple-100": "#e1bee7", "rmd-purple-200": "#ce93d8", "rmd-purple-300": "#ba68c8", "rmd-purple-400": "#ab47bc", "rmd-purple-500": "#9c27b0", "rmd-purple-600": "#8e24aa", "rmd-purple-700": "#7b1fa2", "rmd-purple-800": "#6a1b9a", "rmd-purple-900": "#4a148c", "rmd-purple-a-100": "#ea80fc", "rmd-purple-a-200": "#e040fb", "rmd-purple-a-400": "#d500f9", "rmd-purple-a-700": "#a0f", "rmd-deep-purple-50": "#ede7f6", "rmd-deep-purple-100": "#d1c4e9", "rmd-deep-purple-200": "#b39ddb", "rmd-deep-purple-300": "#9575cd", "rmd-deep-purple-400": "#7e57c2", "rmd-deep-purple-500": "#673ab7", "rmd-deep-purple-600": "#5e35b1", "rmd-deep-purple-700": "#512da8", "rmd-deep-purple-800": "#4527a0", "rmd-deep-purple-900": "#311b92", "rmd-deep-purple-a-100": "#b388ff", "rmd-deep-purple-a-200": "#7c4dff", "rmd-deep-purple-a-400": "#651fff", "rmd-deep-purple-a-700": "#6200ea", "rmd-indigo-50": "#e8eaf6", "rmd-indigo-100": "#c5cae9", "rmd-indigo-200": "#9fa8da", "rmd-indigo-300": "#7986cb", "rmd-indigo-400": "#5c6bc0", "rmd-indigo-500": "#3f51b5", "rmd-indigo-600": "#3949ab", "rmd-indigo-700": "#303f9f", "rmd-indigo-800": "#283593", "rmd-indigo-900": "#1a237e", "rmd-indigo-a-100": "#8c9eff", "rmd-indigo-a-200": "#536dfe", "rmd-indigo-a-400": "#3d5afe", "rmd-indigo-a-700": "#304ffe", "rmd-blue-50": "#e3f2fd", "rmd-blue-100": "#bbdefb", "rmd-blue-200": "#90caf9", "rmd-blue-300": "#64b5f6", "rmd-blue-400": "#42a5f5", "rmd-blue-500": "#2196f3", "rmd-blue-600": "#1e88e5", "rmd-blue-700": "#1976d2", "rmd-blue-800": "#1565c0", "rmd-blue-900": "#0d47a1", "rmd-blue-a-100": "#82b1ff", "rmd-blue-a-200": "#448aff", "rmd-blue-a-400": "#2979ff", "rmd-blue-a-700": "#2962ff", "rmd-light-blue-50": "#e1f5fe", "rmd-light-blue-100": "#b3e5fc", "rmd-light-blue-200": "#81d4fa", "rmd-light-blue-300": "#4fc3f7", "rmd-light-blue-400": "#29b6f6", "rmd-light-blue-500": "#03a9f4", "rmd-light-blue-600": "#039be5", "rmd-light-blue-700": "#0288d1", "rmd-light-blue-800": "#0277bd", "rmd-light-blue-900": "#01579b", "rmd-light-blue-a-100": "#80d8ff", "rmd-light-blue-a-200": "#40c4ff", "rmd-light-blue-a-400": "#00b0ff", "rmd-light-blue-a-700": "#0091ea", "rmd-cyan-50": "#e0f7fa", "rmd-cyan-100": "#b2ebf2", "rmd-cyan-200": "#80deea", "rmd-cyan-300": "#4dd0e1", "rmd-cyan-400": "#26c6da", "rmd-cyan-500": "#00bcd4", "rmd-cyan-600": "#00acc1", "rmd-cyan-700": "#0097a7", "rmd-cyan-800": "#00838f", "rmd-cyan-900": "#006064", "rmd-cyan-a-100": "#84ffff", "rmd-cyan-a-200": "#18ffff", "rmd-cyan-a-400": "#00e5ff", "rmd-cyan-a-700": "#00b8d4", "rmd-teal-50": "#e0f2f1", "rmd-teal-100": "#b2dfdb", "rmd-teal-200": "#80cbc4", "rmd-teal-300": "#4db6ac", "rmd-teal-400": "#26a69a", "rmd-teal-500": "#009688", "rmd-teal-600": "#00897b", "rmd-teal-700": "#00796b", "rmd-teal-800": "#00695c", "rmd-teal-900": "#004d40", "rmd-teal-a-100": "#a7ffeb", "rmd-teal-a-200": "#64ffda", "rmd-teal-a-400": "#1de9b6", "rmd-teal-a-700": "#00bfa5", "rmd-green-50": "#e8f5e9", "rmd-green-100": "#c8e6c9", "rmd-green-200": "#a5d6a7", "rmd-green-300": "#81c784", "rmd-green-400": "#66bb6a", "rmd-green-500": "#4caf50", "rmd-green-600": "#43a047", "rmd-green-700": "#388e3c", "rmd-green-800": "#2e7d32", "rmd-green-900": "#1b5e20", "rmd-green-a-100": "#b9f6ca", "rmd-green-a-200": "#69f0ae", "rmd-green-a-400": "#00e676", "rmd-green-a-700": "#00c853", "rmd-light-green-50": "#f1f8e9", "rmd-light-green-100": "#dcedc8", "rmd-light-green-200": "#c5e1a5", "rmd-light-green-300": "#aed581", "rmd-light-green-400": "#9ccc65", "rmd-light-green-500": "#8bc34a", "rmd-light-green-600": "#7cb342", "rmd-light-green-700": "#689f38", "rmd-light-green-800": "#558b2f", "rmd-light-green-900": "#33691e", "rmd-light-green-a-100": "#ccff90", "rmd-light-green-a-200": "#b2ff59", "rmd-light-green-a-400": "#76ff03", "rmd-light-green-a-700": "#64dd17", "rmd-lime-50": "#f9fbe7", "rmd-lime-100": "#f0f4c3", "rmd-lime-200": "#e6ee9c", "rmd-lime-300": "#dce775", "rmd-lime-400": "#d4e157", "rmd-lime-500": "#cddc39", "rmd-lime-600": "#c0ca33", "rmd-lime-700": "#afb42b", "rmd-lime-800": "#9e9d24", "rmd-lime-900": "#827717", "rmd-lime-a-100": "#f4ff81", "rmd-lime-a-200": "#eeff41", "rmd-lime-a-400": "#c6ff00", "rmd-lime-a-700": "#aeea00", "rmd-yellow-50": "#fffde7", "rmd-yellow-100": "#fff9c4", "rmd-yellow-200": "#fff59d", "rmd-yellow-300": "#fff176", "rmd-yellow-400": "#ffee58", "rmd-yellow-500": "#ffeb3b", "rmd-yellow-600": "#fdd835", "rmd-yellow-700": "#fbc02d", "rmd-yellow-800": "#f9a825", "rmd-yellow-900": "#f57f17", "rmd-yellow-a-100": "#ffff8d", "rmd-yellow-a-200": "#ff0", "rmd-yellow-a-400": "#ffea00", "rmd-yellow-a-700": "#ffd600", "rmd-amber-50": "#fff8e1", "rmd-amber-100": "#ffecb3", "rmd-amber-200": "#ffe082", "rmd-amber-300": "#ffd54f", "rmd-amber-400": "#ffca28", "rmd-amber-500": "#ffc107", "rmd-amber-600": "#ffb300", "rmd-amber-700": "#ffa000", "rmd-amber-800": "#ff8f00", "rmd-amber-900": "#ff6f00", "rmd-amber-a-100": "#ffe57f", "rmd-amber-a-200": "#ffd740", "rmd-amber-a-400": "#ffc400", "rmd-amber-a-700": "#ffab00", "rmd-orange-50": "#fff3e0", "rmd-orange-100": "#fff0b2", "rmd-orange-200": "#ffcc80", "rmd-orange-300": "#ffb74d", "rmd-orange-400": "#ffa726", "rmd-orange-500": "#ff9800", "rmd-orange-600": "#fb8c00", "rmd-orange-700": "#f57c00", "rmd-orange-800": "#ef6c00", "rmd-orange-900": "#e65100", "rmd-orange-a-100": "#ffd180", "rmd-orange-a-200": "#ffab40", "rmd-orange-a-400": "#ff9100", "rmd-orange-a-700": "#ff6d00", "rmd-deep-orange-50": "#fbe9e7", "rmd-deep-orange-100": "#ffccbc", "rmd-deep-orange-200": "#ffab91", "rmd-deep-orange-300": "#ff8a65", "rmd-deep-orange-400": "#ff7043", "rmd-deep-orange-500": "#ff5722", "rmd-deep-orange-600": "#f4511e", "rmd-deep-orange-700": "#e64a19", "rmd-deep-orange-800": "#d84315", "rmd-deep-orange-900": "#bf360c", "rmd-deep-orange-a-100": "#ff9e80", "rmd-deep-orange-a-200": "#ff6e40", "rmd-deep-orange-a-400": "#ff3d00", "rmd-deep-orange-a-700": "#dd2c00", "rmd-brown-50": "#efebe9", "rmd-brown-100": "#d7ccc8", "rmd-brown-200": "#bcaaa4", "rmd-brown-300": "#a1887f", "rmd-brown-400": "#8d6e63", "rmd-brown-500": "#795548", "rmd-brown-600": "#6d4c41", "rmd-brown-700": "#5d4037", "rmd-brown-800": "#4e342e", "rmd-brown-900": "#3e2723", "rmd-grey-50": "#fafafa", "rmd-grey-100": "#f5f5f5", "rmd-grey-200": "#eee", "rmd-grey-300": "#e0e0e0", "rmd-grey-400": "#bdbdbd", "rmd-grey-500": "#9e9e9e", "rmd-grey-600": "#757575", "rmd-grey-700": "#616161", "rmd-grey-800": "#424242", "rmd-grey-900": "#212121", "rmd-blue-grey-50": "#eceff1", "rmd-blue-grey-100": "#cfd8dc", "rmd-blue-grey-200": "#b0bec5", "rmd-blue-grey-300": "#90a4ae", "rmd-blue-grey-400": "#78909c", "rmd-blue-grey-500": "#607d8b", "rmd-blue-grey-600": "#546e7a", "rmd-blue-grey-700": "#455a64", "rmd-blue-grey-800": "#37474f", "rmd-blue-grey-900": "#263238", "rmd-black-base": "#000", "rmd-white-base": "#fff", }, "rmd-theme-primary-suffixes": [ 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, ], "rmd-theme-accent-suffixes": [100, 200, 400, 700], "rmd-theme-colors": [ "red", "pink", "purple", "deep-purple", "indigo", "blue", "light-blue", "cyan", "teal", "green", "light-green", "lime", "yellow", "amber", "orange", "deep-orange", "brown", "grey", "blue-grey", ], "rmd-theme-no-css-variables-fallback": true, "rmd-theme-define-colors-with-rgba": false, "rmd-theme-dark-elevation": false, "rmd-theme-light": true, "rmd-theme-primary": "#9c27b0", "rmd-theme-on-primary": "#000", "rmd-theme-secondary": "#f50057", "rmd-theme-on-secondary": "#000", "rmd-theme-warning": "#ff6e40", "rmd-theme-on-warning": "#fff", "rmd-theme-error": "#f44336", "rmd-theme-on-error": "#000", "rmd-theme-success": "#00c853", "rmd-theme-on-success": "#fff", "rmd-theme-light-background": "#fafafa", "rmd-theme-light-surface": "#fff", "rmd-theme-dark-background": "#303030", "rmd-theme-dark-surface": "#424242", "rmd-theme-dark-class": ".dark-theme", "rmd-theme-background": "#fafafa", "rmd-theme-surface": "#fff", "rmd-theme-on-surface": "#000", "rmd-theme-light-primary-text-color": "#212121", "rmd-theme-light-secondary-text-color": "#757575", "rmd-theme-light-hint-text-color": "#a8a8a8", "rmd-theme-light-disabled-text-color": "#9e9e9e", "rmd-theme-light-icon-color": "#757575", "rmd-theme-dark-primary-text-color": "#d9d9d9", "rmd-theme-dark-secondary-text-color": "#b3b3b3", "rmd-theme-dark-hint-text-color": "gray", "rmd-theme-dark-disabled-text-color": "gray", "rmd-theme-dark-icon-color": "#b3b3b3", "rmd-theme-light-text-colors": { primary: "#212121", secondary: "#757575", hint: "#a8a8a8", disabled: "#9e9e9e", icon: "#757575", }, "rmd-theme-dark-text-colors": { primary: "#d9d9d9", secondary: "#b3b3b3", hint: "gray", disabled: "gray", icon: "#b3b3b3", }, "rmd-theme-primary-text-on-background-color": "#212121", "rmd-theme-secondary-text-on-background-color": "#757575", "rmd-theme-hint-text-on-background-color": "#a8a8a8", "rmd-theme-disabled-text-on-background-color": "#9e9e9e", "rmd-theme-icon-on-background-color": "#757575", "rmd-theme-primary-text-on-light-color": "#212121", "rmd-theme-secondary-text-on-light-color": "#757575", "rmd-theme-hint-text-on-light-color": "#a8a8a8", "rmd-theme-disabled-text-on-light-color": "#9e9e9e", "rmd-theme-icon-on-light-color": "#757575", "rmd-theme-primary-text-on-dark-color": "#d9d9d9", "rmd-theme-secondary-text-on-dark-color": "#b3b3b3", "rmd-theme-hint-text-on-dark-color": "gray", "rmd-theme-disabled-text-on-dark-color": "gray", "rmd-theme-icon-on-dark-color": "#b3b3b3", "rmd-theme-dark-elevation-colors": { 0: "#303030", 1: "#1f1f1f", 2: "#242424", 3: "#262626", 4: "#282828", 5: "#282828", 6: "#2c2c2c", 7: "#2c2c2c", 8: "#2f2f2f", 9: "#2f2f2f", 10: "#2f2f2f", 11: "#2f2f2f", 12: "#333", 13: "#333", 14: "#333", 15: "#333", 16: "#353535", 17: "#353535", 18: "#353535", 19: "#353535", 20: "#353535", 21: "#353535", 22: "#353535", 23: "#353535", 24: "#383838", }, "rmd-theme-values": { background: "#fafafa", primary: "#9c27b0", "on-primary": "#000", secondary: "#f50057", "on-secondary": "#000", surface: "#fff", "on-surface": "#000", warning: "#ff6e40", "on-warning": "#fff", error: "#f44336", "on-error": "#000", success: "#00c853", "on-success": "#fff", "text-primary-on-background": "#212121", "text-secondary-on-background": "#757575", "text-hint-on-background": "#a8a8a8", "text-disabled-on-background": "#9e9e9e", "text-icon-on-background": "#757575", "light-background": "#fafafa", "light-surface": "#fff", "dark-background": "#303030", "dark-surface": "#424242", "text-primary-on-light": "#212121", "text-secondary-on-light": "#757575", "text-hint-on-light": "#a8a8a8", "text-disabled-on-light": "#9e9e9e", "text-icon-on-light": "#757575", "text-primary-on-dark": "#d9d9d9", "text-secondary-on-dark": "#b3b3b3", "text-hint-on-dark": "gray", "text-disabled-on-dark": "gray", "text-icon-on-dark": "#b3b3b3", }, }; //# sourceMappingURL=scssVariables.js.map
34.655835
62
0.512872
52ad5f7714fd42d6860bd30989987d9549f3b9d4
720
js
JavaScript
react-frontend/src/contexts/useGlobalState.js
isystematics/SoarCast
6ba8d7db76e2ba1ad5fd1ab3636dd202b11450b0
[ "Apache-2.0" ]
2
2021-06-08T16:35:30.000Z
2022-03-18T16:04:48.000Z
react-frontend/src/contexts/useGlobalState.js
isystematics/SoarCast
6ba8d7db76e2ba1ad5fd1ab3636dd202b11450b0
[ "Apache-2.0" ]
4
2022-02-22T18:43:07.000Z
2022-02-22T18:45:25.000Z
react-frontend/src/contexts/useGlobalState.js
isystematics/SoarCast
6ba8d7db76e2ba1ad5fd1ab3636dd202b11450b0
[ "Apache-2.0" ]
null
null
null
import {useReducer} from 'react' const reducer = (state, action) => { switch (action.type) { case "LOGIN": sessionStorage.setItem('loggedIn', 'true') return { isLoggedIn: true } case "LOGOUT": sessionStorage.removeItem('loggedIn') sessionStorage.removeItem('token') return { isLoggedIn: false } default: return { state } } } const UseGlobalState = () => { const [globalState, globalDispatch] = useReducer(reducer, { isLoggedIn: false }) return {globalState, globalDispatch}; } export default UseGlobalState;
22.5
63
0.520833
52ad8fbf693cf707d5850f5f1718caaf927ac151
862
js
JavaScript
app/data/api.js
ViniciusSossela/tonialsge-frontend
7fa6b82d68b3763aa002539b2e76a7b1a2354fc4
[ "MIT" ]
null
null
null
app/data/api.js
ViniciusSossela/tonialsge-frontend
7fa6b82d68b3763aa002539b2e76a7b1a2354fc4
[ "MIT" ]
null
null
null
app/data/api.js
ViniciusSossela/tonialsge-frontend
7fa6b82d68b3763aa002539b2e76a7b1a2354fc4
[ "MIT" ]
null
null
null
'use strict'; angular.module('myApp.API', []) .service('API', function () { // var server = "http://localhost:8080/"; var server = "http://52.207.215.106:8080/"; this.loginURL = server + "usuario/login"; this.clienteAddURL = server + "cliente/"; this.clienteAllURL = server + "cliente/all"; this.clienteAllByRotaURL = server + "cliente/rota/"; this.rotaAllUrl = server + "rota/all"; this.rotaAddUrl = server + "rota/"; this.tabelaPrecoAllUrl = server + "tabelapreco/all"; this.tabelaPrecoAddUrl = server + "tabelapreco/"; this.produtoAddURL = server + "produto/"; this.produtoAllURL = server + "produto/all"; this.produtoTabelaPrecoURL = function (produtoId) { return server + "produto/" + produtoId + "/tabelapreco" } });
31.925926
67
0.590487
52ae0a238ef6dc64d82fa8f9dcf9f8934b4e14e0
2,108
js
JavaScript
!EXO/OBJETS-JS/Pokemon/assets/js/pokemonGenerator.js
MokkaCobain/dwwmb
db230e917ac52713215e261af036c768042c05a9
[ "MIT" ]
null
null
null
!EXO/OBJETS-JS/Pokemon/assets/js/pokemonGenerator.js
MokkaCobain/dwwmb
db230e917ac52713215e261af036c768042c05a9
[ "MIT" ]
null
null
null
!EXO/OBJETS-JS/Pokemon/assets/js/pokemonGenerator.js
MokkaCobain/dwwmb
db230e917ac52713215e261af036c768042c05a9
[ "MIT" ]
null
null
null
// EXERCICE 13 : POO // PARTIE 1 : POKEMON // Pokémon sportif : // ▪ "Je suis le Pokémon Pikachu mon poids est de 18 kg, ma vitesse est de 5,1 km/h j'ai 2 pattes, ma taille est de 0,85m ma fréquence cardiaque est de 120 pulsations à la minute." // Pokémon casanier : // ▪ "Je suis le pokémon Salameche mon poids est de 12 kg, ma vitesse est de 3,9 km/h j'ai 2 pattes, ma taille est de 0,65m je regarde la télé 8h par jour." // Pokémon des mers : // ▪ "Je suis le Pokémon Rondoudou mon poids est de 45 kg, ma vitesse est de 3,6 km/h j'ai 2 nageoires." // Pokémon de croisière : // ▪ "Je suis le Pokémon Bulbizarre mon poids est de 15 kg, ma vitesse est de 0,9 km/h j'ai 3 nageoires." import {PokemonSportif} from "./classes/PokemonSportif.js"; import {PokemonCasanier} from "./classes/PokemonCasanier.js"; import {PokemonDesMers} from "./classes/PokemonDesMers.js"; import {PokemonDeCroisiere} from "./classes/PokemonDeCroisiere.js"; // Attributs de PokemonSportif // (nom, poids, taille, nbPatte, cardiaque) const pikachu = new PokemonSportif(`Pikachu`, 18, 0.85, 2, 120); console.log(pikachu.toString()); // Attributs de PokemonCasanier // (nom, poids, taille, nbPatte, tv) const salameche = new PokemonCasanier(`Salameche`, 12, 0.65, 2, 8); console.log(salameche.toString()); // Attributs de PokemonDeCroisiere && PokemonDesMers // (nom, poids, nbNageoire) const rondoudou = new PokemonDesMers(`Rondoudou`, 45, 2); console.log(rondoudou.toString()); const bulbizarre = new PokemonDeCroisiere(`Bulbizarre`, 15, 3); console.log(bulbizarre.toString()); // ********* PLACER LES POKEMON ********* // //Sportif let sportif = document.getElementById(`PokemonSportif`); sportif.innerText += `${pikachu.toString()}`; //Casanier let casanier = document.getElementById(`PokemonCasanier`); casanier.innerText += `${salameche.toString()}`; //DesMers let desMers = document.getElementById(`PokemonDesMers`); desMers.innerText += `${rondoudou.toString()}`; //DeCroisiere let deCroisiere = document.getElementById(`PokemonDeCroisiere`); deCroisiere.innerText += `${bulbizarre.toString()}`;
31.462687
180
0.717268
52ae646ef37cafdcc3828e22ad902477e56a4db4
2,421
js
JavaScript
server/routes/people.route.test.js
uk-gov-mirror/defra.ivory-services
c743c7ed3c8e3202a0b022a9b7ca2b5689bca93b
[ "Unlicense" ]
null
null
null
server/routes/people.route.test.js
uk-gov-mirror/defra.ivory-services
c743c7ed3c8e3202a0b022a9b7ca2b5689bca93b
[ "Unlicense" ]
84
2019-08-05T14:41:37.000Z
2021-07-19T05:52:45.000Z
server/routes/people.route.test.js
uk-gov-mirror/defra.ivory-services
c743c7ed3c8e3202a0b022a9b7ca2b5689bca93b
[ "Unlicense" ]
1
2021-04-10T21:32:47.000Z
2021-04-10T21:32:47.000Z
const Lab = require('@hapi/lab') const lab = exports.lab = Lab.script() const Boom = require('@hapi/boom') const TestHelper = require('../../test-helper') const path = '/people' const { Person } = require('../models') const INVALID_GUID = 'INVALID-GUID' const INVALID_EMAIL = 'INVALID-EMAIL' const { invalidGuidMessage, invalidEmailMessage, emptyMessage } = TestHelper lab.experiment(TestHelper.getFile(__filename), () => { const routesHelper = TestHelper.createRoutesHelper(lab, __filename, { mocks: { id: 'a5754ea4-aee8-40d3-a0d7-e7681ed8ef3a', model: new Person({ fullName: 'James Bond', email: 'james.bond@defra.test.gov.uk', addressId: '20f219ce-fcc5-4ee0-8d53-6e4476daf47a' }) } }) /** *********************** GET All *************************** **/ routesHelper.getRequestTests({ lab, Model: Person, url: path }) /** ********************** GET By Id ************************** **/ routesHelper.getByIdRequestTests({ lab, Model: Person, url: path }) /** ************************* POST **************************** **/ routesHelper.postRequestTests({ lab, Model: Person, url: path }, () => { lab.test('responds with "Bad Data" when invalid data is posted', async ({ context }) => { const { request, server } = context const message = `${emptyMessage('fullName')}. ${invalidEmailMessage('email')}. ${invalidGuidMessage('addressId')}` const expectedResponse = Boom.badData(message).output TestHelper.testResponse(await server.inject(request({ fullName: '', email: INVALID_EMAIL, addressId: INVALID_GUID })), expectedResponse) }) }) /** ************************ PATCH **************************** **/ routesHelper.patchRequestTests({ lab, Model: Person, url: path }, () => { lab.test('responds with "Bad Data" when invalid data is patched', async ({ context }) => { const { mocks, request, server } = context const message = `${emptyMessage('fullName')}. ${invalidEmailMessage('email')}. ${invalidGuidMessage('addressId')}` const expectedResponse = Boom.badData(message).output TestHelper.testResponse(await server.inject(request(mocks.id, { fullName: '', email: INVALID_EMAIL, addressId: INVALID_GUID })), expectedResponse) }) }) /** ************************ DELETE *************************** **/ routesHelper.deleteRequestTests({ lab, Model: Person, url: path }) })
44.833333
152
0.594796
52aed2573c9bba6a2fefb734e8f4a949e8b53130
590
js
JavaScript
src/web-api/routes/index.route.js
Dakad/mean-octotrails-starter
79e74255a7077bc0a98ba1809b64d5b75d367cb9
[ "MIT" ]
null
null
null
src/web-api/routes/index.route.js
Dakad/mean-octotrails-starter
79e74255a7077bc0a98ba1809b64d5b75d367cb9
[ "MIT" ]
null
null
null
src/web-api/routes/index.route.js
Dakad/mean-octotrails-starter
79e74255a7077bc0a98ba1809b64d5b75d367cb9
[ "MIT" ]
null
null
null
import express from 'express'; import authRoutes from './auth.route'; import postsRoutes from './posts.route'; import heroesRoutes from './heroes.route'; const router = express.Router(); // eslint-disable-line new-cap /** GET /health-check - Check service health */ router.get(['/', '/health-check'], (req, res) => { //res.header(); res.send('Yello'); }); // mount auth routes at /auth router.use('/auth', authRoutes); // mount heroes routes at /heroes router.use('/heroes', heroesRoutes); // mount posts routes at /posts router.use('/posts', postsRoutes); export default router;
24.583333
63
0.688136
52af5fd906abf3d18f46487d27d5a4696785b989
11,851
js
JavaScript
packages/@react-spectrum/searchfield/test/SearchField.test.js
watheia/designx
3489584b6301e2c795c2c82783602ea8420886e7
[ "Apache-2.0" ]
1
2021-08-31T03:29:23.000Z
2021-08-31T03:29:23.000Z
packages/@react-spectrum/searchfield/test/SearchField.test.js
watheia/designx
3489584b6301e2c795c2c82783602ea8420886e7
[ "Apache-2.0" ]
1
2021-08-15T04:59:57.000Z
2021-08-15T04:59:57.000Z
packages/@react-spectrum/searchfield/test/SearchField.test.js
watheia/spectrum
3489584b6301e2c795c2c82783602ea8420886e7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Adobe. All rights reserved. * This file is licensed to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ import {act, fireEvent, render, within} from "@testing-library/react"; import Checkmark from "@spectrum-icons/workflow/Checkmark"; import React from "react"; import {SearchField} from "../"; import {triggerPress} from "@react-spectrum/test-utils"; import userEvent from "@testing-library/user-event"; import V2SearchField from "@react/react-spectrum/Search"; let testId = "test-id"; let inputText = "blah"; function renderComponent(Component, props) { return render(<Component aria-label="the label" {...props} data-testid={testId} />); } // Note: Running this test suite will result in some warnings of the following class: // 1. "Textfield contains an input of type search with both value and defaultValue props. This is a v2 SearchField issue // 2. "An update to ForwardRef inside a test was not wrapped in act(...)". See https://github.com/testing-library/react-testing-library/issues/281 // 3. Various warnings about componentWillReceiveProps and componentDidUpdate. Prob a TODO to update v2 components so we don't use these renamed/deprecated lifecycle methods describe("Search", () => { let onChange = jest.fn(); let onFocus = jest.fn(); let onSubmit = jest.fn(); let onClear = jest.fn(); afterEach(() => { onChange.mockClear(); onFocus.mockClear(); onSubmit.mockClear(); onClear.mockClear(); }); it.each` Name | Component ${"v3 SearchField"} | ${SearchField} ${"v2 SearchField"} | ${V2SearchField} `("$Name default behavior check", ({Component}) => { let tree = renderComponent(Component); let outerDiv = tree.container; expect(outerDiv).toBeTruthy(); let input = within(outerDiv).getByTestId(testId); expect(input).toHaveAttribute("type", "search"); let clearButton = within(outerDiv).queryByRole("button"); expect(clearButton).toBeNull(); }); // omitting v2 because the v3 icon we use doesn't accept className, only UNSAFE_className it.each` Name | Component ${"v3 SearchField"} | ${SearchField} `("$Name should support custom icons", ({Component}) => { let icon = <Checkmark data-testid="testicon" />; let tree = renderComponent(Component, {icon}); expect(tree.getByTestId("testicon")).toBeTruthy(); }); it.each` Name | Component ${"v3 SearchField"} | ${SearchField} ${"v2 SearchField"} | ${V2SearchField} `("$Name should support no icons", ({Component}) => { let tree = renderComponent(Component, {icon: ""}); expect(tree.queryByTestId("searchicon")).toBeNull(); }); it.each` Name | Component ${"v3 SearchField"} | ${SearchField} `("$Name should display the clear button icon only if text is present", ({Component}) => { let tree = renderComponent(Component, {defaultValue: inputText}); let clearButton = tree.getByLabelText("Clear search"); expect(clearButton).toBeTruthy(); let input = tree.getByTestId(testId); fireEvent.change(input, {target: {value: ""}}); clearButton = tree.queryByLabelText("Clear search"); expect(clearButton).toBeNull(); userEvent.type(input, "bleh"); clearButton = tree.queryByLabelText("Clear search"); expect(clearButton).toBeTruthy(); }); // Omitting v2 searchfield because fireEvent.keyDown seems bugged, doesn't actually propagate the key code // which v2 searchfield handleTextKeyDown relies on it.each` Name | Component ${"v3 SearchField"} | ${SearchField} `("$Name submits the textfield value when enter is pressed", ({Component}) => { let tree = renderComponent(Component, {defaultValue: inputText, onSubmit}); let input = tree.getByTestId(testId); fireEvent.keyDown(input, {key: "Enter", code: 13, charCode: 13}); expect(onSubmit).toBeCalledTimes(1); expect(onSubmit).toHaveBeenLastCalledWith(inputText); act(() => { fireEvent.change(input, {target: {value: ""}}); }); act(() => { fireEvent.keyDown(input, {key: "Enter", code: 13, charCode: 13}); }); expect(onSubmit).toBeCalledTimes(2); expect(onSubmit).toHaveBeenLastCalledWith(""); }); // Omitting v2 searchfield because fireEvent.keyDown seems bugged, doesn't actually propagate the key code // which v2 searchfield handleTextKeyDown relies on it.each` Name | Component | props ${"v3 SearchField"} | ${SearchField} | ${{isDisabled: true}} `("$Name doesn't submit the textfield value when enter is pressed but field is disabled", ({Component, props}) => { let tree = renderComponent(Component, {defaultValue: inputText, onSubmit, ...props}); let input = tree.getByTestId(testId); fireEvent.keyDown(input, {key: "Enter", code: 13, charCode: 13}); expect(onSubmit).toBeCalledTimes(0); }); // Omitting v2 searchfield because fireEvent.keyDown seems bugged, doesn't actually propagate the key code // which v2 searchfield handleTextKeyDown relies on it.each` Name | Component ${"v3 SearchField"} | ${SearchField} `("$Name clears the input field if the escape key is pressed and the field is uncontrolled", ({Component}) => { let tree = renderComponent(Component, {defaultValue: inputText, onChange, onClear}); let input = tree.getByTestId(testId); expect(input.value).toBe(inputText); fireEvent.keyDown(input, {key: "Escape", code: 27, charCode: 27}); expect(onChange).toBeCalledTimes(1); expect(onChange).toHaveBeenLastCalledWith(""); expect(input.value).toBe(""); expect(document.activeElement).toBe(document.body); // onClear was added in v3 if (Component === SearchField) { expect(onClear).toBeCalledTimes(1); expect(onChange).toHaveBeenLastCalledWith(expect.anything()); } }); // Omitting v2 searchfield because fireEvent.keyDown seems bugged, doesn't actually propagate the key code // which v2 searchfield handleTextKeyDown relies on it.each` Name | Component ${"v3 SearchField"} | ${SearchField} `("$Name doesn't clear the input field if the escape key is pressed and the field is controlled", ({Component}) => { let tree = renderComponent(Component, {value: inputText, onChange, onClear}); let input = tree.getByTestId(testId); expect(input.value).toBe(inputText); fireEvent.keyDown(input, {key: "Escape", code: 27, charCode: 27}); expect(onChange).toBeCalledTimes(1); expect(onChange).toHaveBeenLastCalledWith(""); expect(input.value).toBe(inputText); expect(document.activeElement).toBe(document.body); // onClear was added in v3 expect(onClear).toBeCalledTimes(1); expect(onChange).toHaveBeenLastCalledWith(expect.anything()); }); // Omitting v2 searchfield because fireEvent.keyDown seems bugged, doesn't actually propagate the key code // which v2 searchfield handleTextKeyDown relies on it.each` Name | Component | props ${"v3 SearchField"} | ${SearchField} | ${{isDisabled: true}} `("$Name doesn't clear the input field if the escape key is pressed and the field is disabled", ({Component, props}) => { let tree = renderComponent(Component, {defaultValue: inputText, onChange, onClear, ...props}); let input = tree.getByTestId(testId); expect(input.value).toBe(inputText); fireEvent.keyDown(input, {key: "Escape", code: 27, charCode: 27}); expect(onChange).toBeCalledTimes(0); expect(input.value).toBe(inputText); // onClear was added in v3 expect(onClear).toBeCalledTimes(0); }); it.each` Name | Component ${"v3 SearchField"} | ${SearchField} `("$Name clears the input field if the clear button is pressed and the field is uncontrolled", ({Component}) => { let tree = renderComponent(Component, {defaultValue: inputText, onChange, onClear}); let input = tree.getByTestId(testId); let clearButton = tree.getByLabelText("Clear search"); expect(input.value).toBe(inputText); triggerPress(clearButton); expect(onChange).toBeCalledTimes(1); if (Component === SearchField) { expect(onChange).toHaveBeenLastCalledWith(""); } else { expect(onChange).toHaveBeenLastCalledWith("", expect.anything(), {"from": "clearButton"}); } expect(input.value).toBe(""); expect(document.activeElement).toBe(input); // onClear was added in v3 if (Component === SearchField) { expect(onClear).toBeCalledTimes(1); expect(onChange).toHaveBeenLastCalledWith(expect.anything()); } }); it.each` Name | Component ${"v3 SearchField"} | ${SearchField} ${"v2 SearchField"} | ${V2SearchField} `("$Name doesn't clear the input field if the clear button is pressed and the field is controlled", ({Component}) => { let tree = renderComponent(Component, {value: inputText, onChange, onClear}); let input = tree.getByTestId(testId); let clearButton = tree.getByLabelText("Clear search"); expect(input.value).toBe(inputText); userEvent.click(clearButton); expect(onChange).toBeCalledTimes(1); if (Component === SearchField) { expect(onChange).toHaveBeenLastCalledWith(""); } else { expect(onChange).toHaveBeenLastCalledWith("", expect.anything(), {"from": "clearButton"}); } expect(input.value).toBe(inputText); expect(document.activeElement).toBe(input); // onClear was added in v3 if (Component === SearchField) { expect(onClear).toBeCalledTimes(1); expect(onChange).toHaveBeenLastCalledWith(expect.anything()); } }); it.each` Name | Component | props ${"v3 SearchField"} | ${SearchField} | ${{isDisabled: true}} `("$Name doesn't clear the input field if the clear button is pressed and the field is disabled", ({Component, props}) => { let tree = renderComponent(Component, {defaultValue: inputText, onChange, onClear, ...props}); let input = tree.getByTestId(testId); let clearButton = tree.getByLabelText("Clear search"); expect(input.value).toBe(inputText); userEvent.click(clearButton); expect(onChange).toBeCalledTimes(0); expect(input.value).toBe(inputText); // onClear was added in v3 if (Component === SearchField) { expect(onClear).toBeCalledTimes(0); } }); it("SearchField doesn't show clear button if isReadOnly is true", () => { let tree = renderComponent(SearchField, {isReadOnly: true, value: "puppy"}); let clearButton = tree.queryByLabelText("Clear search"); expect(clearButton).toBe(null); }); it.each` Name | Component ${"v3 SearchField"} | ${SearchField} ${"v2 SearchField"} | ${V2SearchField} `("$Name should support aria-label", ({Component}) => { let tree = renderComponent(Component, {"aria-label": "Test"}); expect(tree.getByRole("searchbox")).toHaveAttribute("aria-label", "Test"); }); it.each` Name | Component ${"v3 SearchField"} | ${SearchField} `("$Name should support excludeFromTabOrder", ({Component}) => { let tree = renderComponent(Component, {excludeFromTabOrder: true}); expect(tree.getByRole("searchbox")).toHaveAttribute("tabIndex", "-1"); }); });
41.149306
173
0.674036
52af92c3e3453dc15918c8de74fe7fd6d9f8793c
4,310
js
JavaScript
doc/jsduck/template/extjs/src/PluginManager.js
prime-solutions/prime-commonjs
4c1db30d4dac4bf44a807feda1a2d00eb8f71ad3
[ "MIT" ]
1
2019-07-29T02:04:31.000Z
2019-07-29T02:04:31.000Z
doc/jsduck/template/extjs/src/PluginManager.js
org-victorinox/prime-commonjs
4c1db30d4dac4bf44a807feda1a2d00eb8f71ad3
[ "MIT" ]
3
2018-04-30T16:51:50.000Z
2018-06-06T06:18:31.000Z
doc/jsduck/template/extjs/src/PluginManager.js
org-victorinox/prime-commonjs
4c1db30d4dac4bf44a807feda1a2d00eb8f71ad3
[ "MIT" ]
null
null
null
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Sencha. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314) */ /** * Provides a registry of available Plugin classes indexed by a mnemonic code known as the Plugin's ptype. * * A plugin may be specified simply as a *config object* as long as the correct `ptype` is specified: * * { * ptype: 'gridviewdragdrop', * dragText: 'Drag and drop to reorganize' * } * * Or just use the ptype on its own: * * 'gridviewdragdrop' * * Alternatively you can instantiate the plugin with Ext.create: * * Ext.create('Ext.grid.plugin.DragDrop', { * dragText: 'Drag and drop to reorganize' * }) */ Ext.define('Ext.PluginManager', { extend: 'Ext.AbstractManager', alternateClassName: 'Ext.PluginMgr', singleton: true, typeName: 'ptype', /** * Creates a new Plugin from the specified config object using the config object's ptype to determine the class to * instantiate. * @param {Object} config A configuration object for the Plugin you wish to create. * @param {Function} defaultType (optional) The constructor to provide the default Plugin type if the config object does not * contain a `ptype`. (Optional if the config contains a `ptype`). * @return {Ext.Component} The newly instantiated Plugin. */ create : function(config, defaultType, host) { var result; if (config.init) { result = config; } else { // Inject the host into the config is we know the host if (host) { config = Ext.apply({}, config); // copy since we are going to modify config.cmp = host; } // Grab the host ref if it was configured in else { host = config.cmp; } if (config.xclass) { result = Ext.create(config); } else { // Lookup the class from the ptype and instantiate unless its a singleton result = Ext.ClassManager.getByAlias(('plugin.' + (config.ptype || defaultType))); if (typeof result === 'function') { result = new result(config); } } } // If we come out with a non-null plugin, ensure that any setCmp is called once. if (result && host && result.setCmp && !result.setCmpCalled) { result.setCmp(host); result.setCmpCalled = true; } return result; }, /** * Returns all plugins registered with the given type. Here, 'type' refers to the type of plugin, not its ptype. * @param {String} type The type to search for * @param {Boolean} defaultsOnly True to only return plugins of this type where the plugin's isDefault property is * truthy * @return {Ext.AbstractPlugin[]} All matching plugins */ findByType: function(type, defaultsOnly) { var matches = [], types = this.types, name, item; for (name in types) { if (!types.hasOwnProperty(name)) { continue; } item = types[name]; if (item.type == type && (!defaultsOnly || (defaultsOnly === true && item.isDefault))) { matches.push(item); } } return matches; } }, function() { /** * Shorthand for {@link Ext.PluginManager#registerType} * @param {String} ptype The ptype mnemonic string by which the Plugin class * may be looked up. * @param {Function} cls The new Plugin class. * @member Ext * @method preg */ Ext.preg = function() { return Ext.PluginManager.registerType.apply(Ext.PluginManager, arguments); }; });
33.937008
128
0.604872
52b0b7722d72f97af57b09ac70adb456654d6666
1,684
js
JavaScript
docs/_nuxt/1e901c557d9e329f1946.js
byu-oit/sim-vue-lib
fc88bd67f162dfdf5f061114a6b49aaae7ba69ce
[ "Apache-2.0" ]
null
null
null
docs/_nuxt/1e901c557d9e329f1946.js
byu-oit/sim-vue-lib
fc88bd67f162dfdf5f061114a6b49aaae7ba69ce
[ "Apache-2.0" ]
147
2019-12-09T21:37:33.000Z
2021-08-03T20:10:38.000Z
docs/_nuxt/1e901c557d9e329f1946.js
byu-oit/sim-vue-lib
fc88bd67f162dfdf5f061114a6b49aaae7ba69ce
[ "Apache-2.0" ]
null
null
null
(window.webpackJsonp=window.webpackJsonp||[]).push([[2],{285:function(e,t,n){"use strict";n.r(t);var c=n(18),r=n(22),l=n(27),o=n(28),f=n(19),h=n(108),j=function(e,t,n,desc){var c,r=arguments.length,l=r<3?t:null===desc?desc=Object.getOwnPropertyDescriptor(t,n):desc;if("object"===("undefined"==typeof Reflect?"undefined":Object(f.a)(Reflect))&&"function"==typeof Reflect.decorate)l=Reflect.decorate(e,t,n,desc);else for(var i=e.length-1;i>=0;i--)(c=e[i])&&(l=(r<3?c(l):r>3?c(t,n,l):c(t,n))||l);return r>3&&l&&Object.defineProperty(t,n,l),l},O=function(e){function t(){var e;return Object(c.a)(this,t),(e=Object(r.a)(this,Object(l.a)(t).apply(this,arguments))).title="Hello World",e}return Object(o.a)(t,e),t}(h.Vue),d=O=j([h.Component],O),y=n(56),v=Object(y.a)(d,(function(){var e=this.$createElement;return(this._self._c||e)("h1",{staticClass:"text-primary"},[this._v(this._s(this.title))])}),[],!1,null,null,null).exports,m=function(e,t,n,desc){var c,r=arguments.length,l=r<3?t:null===desc?desc=Object.getOwnPropertyDescriptor(t,n):desc;if("object"===("undefined"==typeof Reflect?"undefined":Object(f.a)(Reflect))&&"function"==typeof Reflect.decorate)l=Reflect.decorate(e,t,n,desc);else for(var i=e.length-1;i>=0;i--)(c=e[i])&&(l=(r<3?c(l):r>3?c(t,n,l):c(t,n))||l);return r>3&&l&&Object.defineProperty(t,n,l),l},w=function(e){function t(){var e;return Object(c.a)(this,t),(e=Object(r.a)(this,Object(l.a)(t).apply(this,arguments))).title="Example Page",e}return Object(o.a)(t,e),t}(h.Vue),R=w=m([Object(h.Component)({components:{Example:v}})],w),x=Object(y.a)(R,(function(){var e=this.$createElement;return(this._self._c||e)("example")}),[],!1,null,null,null);t.default=x.exports}}]);
1,684
1,684
0.676366
52b0e785fc8b8140117f014301d16486fff7922d
267
js
JavaScript
e2e/protractor.conf.js
em3ndez/mesh-ui
7cae402af37d4b7e6981e16bdd653c980ed84175
[ "Apache-2.0" ]
null
null
null
e2e/protractor.conf.js
em3ndez/mesh-ui
7cae402af37d4b7e6981e16bdd653c980ed84175
[ "Apache-2.0" ]
null
null
null
e2e/protractor.conf.js
em3ndez/mesh-ui
7cae402af37d4b7e6981e16bdd653c980ed84175
[ "Apache-2.0" ]
null
null
null
// Protrator end-to-end testing framework. // For config options see https://github.com/angular/protractor/blob/master/docs/referenceConf.js exports.config = { seleniumAddress: 'http://localhost:4444/wd/hub', specs: ['**/*.e2e.js'], rootElement: 'html' };
38.142857
97
0.700375
52b13a15527e2c79ac78fb0c1ea5fbe052d16167
2,376
js
JavaScript
aggregation_framework/pipeline.js
vmilkovic/master-mongodb
527d88461b1271d632fd0b0092e4945ff3550dba
[ "MIT" ]
null
null
null
aggregation_framework/pipeline.js
vmilkovic/master-mongodb
527d88461b1271d632fd0b0092e4945ff3550dba
[ "MIT" ]
null
null
null
aggregation_framework/pipeline.js
vmilkovic/master-mongodb
527d88461b1271d632fd0b0092e4945ff3550dba
[ "MIT" ]
null
null
null
db.persons.aggregate([ { $project: { _id: 0, name: 1, email: 1, birthdate: { $toDate: '$dob.date', }, age: '$dob.age', location: { type: 'Point', coordinates: [ { $convert: { input: '$location.coordinates.longitude', to: 'decimal', onError: 0.0, onNull: 0.0, }, }, { $convert: { input: '$location.coordinates.latitude', to: 'decimal', onError: 0.0, onNull: 0.0, }, }, ], }, }, }, { $project: { _id: 0, gender: 1, email: 1, location: 1, birthdate: 1, age: 1, fullName: { $concat: [ { $toUpper: { $substrCP: ['$name.first', 0, 1], }, }, { $substrCP: [ '$name.first', 1, { $subtract: [ { $strLenCP: '$name.first', }, 1, ], }, ], }, ' ', { $toUpper: { $substrCP: ['$name.last', 0, 1], }, }, { $substrCP: [ '$name.last', 1, { $subtract: [ { $strLenCP: '$name.last', }, 1, ], }, ], }, ], }, }, }, // { // $group: { // _id: { // birthYear: { // $isoWeekYear: '$birthdate', // }, // }, // numPersons: { // $sum: 1, // }, // }, // }, { $sort: { numPersons: -1, }, }, { $out: 'transformedPersons', }, ]); db.transformedPersons.find(); db.transformedPersons.createIndex({ location: '2dsphere', }); db.transformedPersons.aggregate([ { $geoNear: { near: { type: 'Point', coordinates: [-18.4, 42.8], }, maxDistance: 1000000, query: { age: { $gt: 30, }, }, distanceField: 'distance', }, }, ]);
18
55
0.295875
52b2147f04e6324443adea867487f26dd14f25eb
2,663
js
JavaScript
lib/staleBuildChecks.js
Ketan1502/oppiabot
a1e142d0552d9a8626a73773323e8820be63a026
[ "Apache-2.0" ]
17
2019-05-08T17:49:58.000Z
2021-11-30T09:06:44.000Z
lib/staleBuildChecks.js
Ketan1502/oppiabot
a1e142d0552d9a8626a73773323e8820be63a026
[ "Apache-2.0" ]
246
2018-06-21T21:02:45.000Z
2022-03-31T11:39:53.000Z
lib/staleBuildChecks.js
Ketan1502/oppiabot
a1e142d0552d9a8626a73773323e8820be63a026
[ "Apache-2.0" ]
63
2018-04-27T10:30:10.000Z
2022-02-01T06:50:23.000Z
const utils = require('./utils'); /** * This function comments on and tags pull requests in which the last * commit was created 2 days ago * @param {import('probot').Context} context */ const checkAndTagPRsWithOldBuilds = async (context) => { const allOpenPullRequests = await utils.getAllOpenPullRequests( context ); allOpenPullRequests.forEach(async (pullRequest) => { const containsOldBuildLabel = pullRequest.labels.some( label => label.name === utils.OLD_BUILD_LABEL ); // If label has already been added, do nothing. if (containsOldBuildLabel) { return; } const {data: lastCommit} = await context.github.repos.getCommit( context.repo({ ref: pullRequest.head.sha }) ); const lastCommitDate = new Date(lastCommit.commit.author.date); // Commit is older than 2 days if (utils.MIN_BUILD_DATE > lastCommitDate) { const labelParams = context.repo({ issue_number: pullRequest.number, labels: [utils.OLD_BUILD_LABEL], }); context.github.issues.addLabels(labelParams); // Ping PR author. const commentParams = context.repo({ issue_number: pullRequest.number, body: 'Hi @' + pullRequest.user.login + ', the build of this PR is ' + 'stale and this could result in tests failing in develop. Please ' + 'update this pull request with the latest changes from develop. ' + 'Thanks!', }); context.github.issues.createComment(commentParams); } } ); }; /** * This function removes the old build label when a PR has a new commit. * @param {import('probot').Context} context */ const removeOldBuildLabel = async (context) => { const pullRequest = context.payload.pull_request; const containsOldBuildLabel = pullRequest.labels.some( label => label.name === utils.OLD_BUILD_LABEL ); if (!containsOldBuildLabel) { return; } // Get last commit for pull request. const {data: lastCommit} = await context.github.repos.getCommit( context.repo({ ref: pullRequest.head.sha }) ); const lastCommitDate = new Date(lastCommit.commit.author.date); // Commit is older than 2 days, this can happen when 'synchronize' event // got triggered as a result of a merge to the main branch. In this case // we don't want to remove the label. if (utils.MIN_BUILD_DATE > lastCommitDate) { return; } context.github.issues.removeLabel( context.repo({ issue_number: pullRequest.number, name: utils.OLD_BUILD_LABEL, }) ); }; module.exports = { checkAndTagPRsWithOldBuilds, removeOldBuildLabel };
28.945652
80
0.66579
52b248dcd24ac001f299955fdaf8e13e6ec704a2
1,323
js
JavaScript
data/js/00/16/22/00/00/00.24.js
hdm/mac-tracker
69f0c4efaa3d60111001d40f7a33886cc507e742
[ "CC-BY-4.0", "MIT" ]
20
2018-12-26T17:06:05.000Z
2021-08-05T07:47:31.000Z
data/js/00/16/22/00/00/00.24.js
hdm/mac-tracker
69f0c4efaa3d60111001d40f7a33886cc507e742
[ "CC-BY-4.0", "MIT" ]
1
2021-06-03T12:20:55.000Z
2021-06-03T16:36:26.000Z
data/js/00/16/22/00/00/00.24.js
hdm/mac-tracker
69f0c4efaa3d60111001d40f7a33886cc507e742
[ "CC-BY-4.0", "MIT" ]
8
2018-12-27T05:07:48.000Z
2021-01-26T00:41:17.000Z
macDetailCallback("001622000000/24",[{"d":"2005-10-13","t":"add","a":"Böttgerstrasse 40\nWeiden i.d.OPf. Bayern 92637\n\n","c":"GERMANY","o":"BBH SYSTEMS GMBH"},{"d":"2009-11-07","t":"change","a":"Böttgerstrasse 40\nWeiden i.d.OPf. Bayern 92637\n\n","c":"GERMANY","o":"BBH SYSTEMS GMBH"},{"d":"2010-02-06","t":"change","a":"Böttgerstrasse 40\nWeiden i.d.OPf. Bayern 92637\n\n","c":"GERMANY","o":"BBH SYSTEMS GMBH"},{"d":"2010-08-24","t":"change","a":"Böttgerstrasse 40\nWeiden i.d.OPf. Bayern 92637\n\n","c":"GERMANY","o":"BBH SYSTEMS GMBH"},{"d":"2010-08-25","t":"change","a":"Böttgerstrasse 40\nWeiden i.d.OPf. Bayern 92637\n\n","c":"GERMANY","o":"BBH SYSTEMS GMBH"},{"d":"2011-11-17","t":"change","a":"Böttgerstrasse 40\nWeiden i.d.OPf. Bayern 92637\n\n","c":"GERMANY","o":"BBH SYSTEMS GMBH"},{"d":"2011-11-18","t":"change","a":"Böttgerstrasse 40\nWeiden i.d.OPf. Bayern 92637\n\n","c":"GERMANY","o":"BBH SYSTEMS GMBH"},{"d":"2012-09-17","t":"change","a":"Böttgerstrasse 40\nWeiden i.d.OPf. Bayern 92637\n\n","c":"GERMANY","o":"BBH SYSTEMS GMBH"},{"d":"2012-11-29","t":"change","a":"Böttgerstraße 40\nWeiden i.d.OPf. Bayern 92637\n\n","c":"GERMANY","o":"BBH SYSTEMS GMBH"},{"d":"2015-08-27","t":"change","a":"Böttgerstraße 40 Weiden i.d.OPf. Bayern DE 92637","c":"DE","o":"BBH SYSTEMS GMBH"}]);
661.5
1,322
0.634165
52b2c44abf1e3ef4d618f718f209aa9b61e6440e
4,708
js
JavaScript
frontend/src/_services/api.service.js
magrandera/SPaaS
b3ced24259817cffcfd436d4d4f6de0a2422b63e
[ "MIT" ]
15
2018-12-08T21:20:40.000Z
2022-01-04T13:56:29.000Z
frontend/src/_services/api.service.js
magrandera/PiaaS
b3ced24259817cffcfd436d4d4f6de0a2422b63e
[ "Apache-2.0" ]
31
2017-07-15T21:54:19.000Z
2018-08-23T21:44:07.000Z
frontend/src/_services/api.service.js
magrandera/SPaaS
b3ced24259817cffcfd436d4d4f6de0a2422b63e
[ "MIT" ]
2
2020-11-19T20:32:28.000Z
2021-01-07T16:46:22.000Z
import { authHeader } from "../_helpers"; import { userService } from "../_services"; export const apiService = { getAll, createApp, inspectApp, deployApp, stopApp, startApp, logs, deleteApp }; function getAll() { const requestOptions = { method: "GET", headers: authHeader() }; return fetch(`/api/app`, requestOptions) .then(response => { if (!response.ok) { if (response.status === 401) { // auto logout if 401 response returned from api logout(); location.reload(true); } const error = (data && data.message) || response.statusText; return Promise.reject(error); } return response.text(); }) .then(text => { const apps = []; const responseObjects = text.split("\n"); responseObjects .filter(value => { return value != ""; }) .forEach(value => { apps.push(JSON.parse(value)["message"]); }); return apps; }); } function createApp(name) { const requestOptions = { method: "POST", headers: authHeader() }; return fetch(`/api/app/${name}`, requestOptions) .then(response => { if (!response.ok) { if (response.status === 401) { // auto logout if 401 response returned from api logout(); location.reload(true); } const error = (data && data.message) || response.statusText; return Promise.reject(error); } return response.body; }) .then(body => { return body.getReader(); }); } function inspectApp(name) { const requestOptions = { method: "GET", headers: authHeader() }; return fetch( `/api/app/${name}`, requestOptions ).then(response => { if (!response.ok) { if (response.status === 401) { // auto logout if 401 response returned from api logout(); location.reload(true); } const error = (data && data.message) || response.statusText; return Promise.reject(error); } return response.text(); }); } function deployApp(name) { const requestOptions = { method: "POST", headers: authHeader() }; return fetch( `/api/app/${name}/deploy`, requestOptions ).then(response => { if (!response.ok) { if (response.status === 401) { // auto logout if 401 response returned from api logout(); location.reload(true); } const error = (data && data.message) || response.statusText; return Promise.reject(error); } return response.text(); }); } function stopApp(name) { const requestOptions = { method: "POST", headers: authHeader() }; return fetch( `/api/app/${name}/stop`, requestOptions ) .then(response => { if (!response.ok) { if (response.status === 401) { // auto logout if 401 response returned from api logout(); location.reload(true); } const error = (data && data.message) || response.statusText; return Promise.reject(error); } return response.text(); }); } function startApp(name) { const requestOptions = { method: "POST", headers: authHeader() }; return fetch( `/api/app/${name}/start`, requestOptions ) .then(response => { if (!response.ok) { if (response.status === 401) { // auto logout if 401 response returned from api logout(); location.reload(true); } const error = (data && data.message) || response.statusText; return Promise.reject(error); } return response.text(); }); } function logs(name) { const requestOptions = { method: "GET", headers: authHeader() }; return fetch(`/api/app/${name}/logs`, requestOptions) .then(response => { if (!response.ok) { if (response.status === 401) { // auto logout if 401 response returned from api logout(); location.reload(true); } const error = (data && data.message) || response.statusText; return Promise.reject(error); } return response.body; }) .then(body => { return body.getReader(); }); } function deleteApp(name) { const requestOptions = { method: "DELETE", headers: authHeader() }; return fetch( `/api/app/${name}`, requestOptions ) .then(response => { if (!response.ok) { if (response.status === 401) { // auto logout if 401 response returned from api logout(); location.reload(true); } const error = (data && data.message) || response.statusText; return Promise.reject(error); } return response.text(); }); }
23.078431
68
0.56627
52b434459e26ff4d3a00d81e655a7d9ddde47265
18,356
js
JavaScript
src/application.js
kalisio/kCore
573a4ba35d2decab2c0010a9dc9a2c58bb995ea3
[ "MIT" ]
5
2018-07-07T13:37:28.000Z
2019-05-16T19:24:54.000Z
src/application.js
kaelia-tech/kCore
573a4ba35d2decab2c0010a9dc9a2c58bb995ea3
[ "MIT" ]
144
2017-08-24T10:09:34.000Z
2021-05-08T06:25:05.000Z
src/application.js
kaelia-tech/kCore
573a4ba35d2decab2c0010a9dc9a2c58bb995ea3
[ "MIT" ]
3
2019-01-22T06:41:31.000Z
2019-07-14T11:52:45.000Z
import path from 'path' import makeDebug from 'debug' import logger from 'winston' import _ from 'lodash' import sift from 'sift' import 'winston-daily-rotate-file' import compress from 'compression' import cors from 'cors' import helmet from 'helmet' import bodyParser from 'body-parser' import { RateLimiter as SocketLimiter } from 'limiter' import HttpLimiter from 'express-rate-limit' import feathers from '@feathersjs/feathers' import configuration from '@feathersjs/configuration' import { TooManyRequests, Forbidden, BadRequest } from '@feathersjs/errors' import express from '@feathersjs/express' import rest from '@feathersjs/express/rest' import socketio from '@feathersjs/socketio' import memory from 'feathers-memory' import { ObjectID } from 'mongodb' import { Database, idToString } from './db' import auth, { authSocket } from './authentication' const debug = makeDebug('kalisio:kCore:application') const debugLimiter = makeDebug('kalisio:kCore:application:limiter') function tooManyRequests (socket, message, key) { debug(message) const error = new TooManyRequests(message, { translation: { key } }) socket.emit('rate-limit', error) // Add a timeout so that error message is correctly handled setTimeout(() => socket.disconnect(true), 3000) } export function declareService (path, app, service, middlewares = {}) { const feathersPath = app.get('apiPath') + '/' + path const feathersService = app.service(feathersPath) // Some internal Feathers service might internally declare the service if (feathersService) { return feathersService } // Initialize our service by providing any middleware as well let args = [feathersPath] if (middlewares.before) args = args.concat(middlewares.before) args.push(service) if (middlewares.after) args = args.concat(middlewares.after) app.use.apply(app, args) debug('Service declared on path ' + feathersPath) // Return the Feathers service, ie base service + Feathers' internals return app.service(feathersPath) } export function configureService (name, service, servicesPath) { try { const hooks = require(path.join(servicesPath, name, name + '.hooks')) service.hooks(hooks) debug(name + ' service hooks configured on path ' + servicesPath) } catch (error) { debug('No ' + name + ' service hooks configured on path ' + servicesPath) if (error.code !== 'MODULE_NOT_FOUND') { // Log error in this case as this might be linked to a syntax error in required file debug(error) } // As this is optionnal this require has to fail silently } try { const channels = require(path.join(servicesPath, name, name + '.channels')) _.forOwn(channels, (publisher, event) => { if (event === 'all') service.publish(publisher) else service.publish(event, publisher) }) debug(name + ' service channels configured on path ' + servicesPath) } catch (error) { debug('No ' + name + ' service channels configured on path ' + servicesPath) if (error.code !== 'MODULE_NOT_FOUND') { // Log error in this case as this might be linked to a syntax error in required file debug(error) } // As this is optionnal this require has to fail silently } return service } export function createProxyService (options) { const targetService = options.service function proxyParams (params) { if (options.params) { let proxiedParams if (typeof options.params === 'function') { proxiedParams = options.params(params) } else { proxiedParams = _.merge(params, options.params) } return proxiedParams } else return params } function proxyId (id) { if (options.id) return options.id(id) else return id } function proxyData (data) { if (options.data) return options.data(data) else return data } function proxyResult (data) { if (options.result) return options.result(data) else return data } return { async find (params) { return proxyResult(await targetService.find(proxyParams(params))) }, async get (id, params) { return proxyResult(await targetService.get(proxyId(id), proxyParams(params))) }, async create (data, params) { return proxyResult(await targetService.create(proxyData(data), proxyParams(params))) }, async update (id, data, params) { return proxyResult(await targetService.update(proxyId(id), proxyData(data), proxyParams(params))) }, async patch (id, data, params) { return proxyResult(await targetService.patch(proxyId(id), proxyData(data), proxyParams(params))) }, async remove (id, params) { return proxyResult(await targetService.remove(proxyId(id), proxyParams(params))) } } } export function createService (name, app, options = {}) { const createFeathersService = require('feathers-' + app.db.adapter) const paginate = app.get('paginate') const serviceOptions = Object.assign({ name: name, paginate }, options) if (serviceOptions.disabled) return undefined // For DB services a model has to be provided const fileName = serviceOptions.fileName || name let dbService = false try { if (serviceOptions.modelsPath) { const configureModel = require(path.join(serviceOptions.modelsPath, fileName + '.model.' + app.db.adapter)) configureModel(app, serviceOptions) dbService = true } } catch (error) { debug('No ' + fileName + ' service model configured on path ' + serviceOptions.modelsPath) if (error.code !== 'MODULE_NOT_FOUND') { // Log error in this case as this might be linked to a syntax error in required file debug(error) } // As this is optionnal this require has to fail silently } // Initialize our service with any options it requires let service if (serviceOptions.memory) { service = memory(serviceOptions.memory) } if (dbService) { service = createFeathersService(serviceOptions) dbService = service } else if (serviceOptions.proxy) { service = createProxyService(serviceOptions.proxy) } else { // Otherwise we expect the service to be provided as a Feathers service interface service = require(path.join(serviceOptions.servicesPath, fileName, fileName + '.service')) // If we get a function try to call it assuming it will return the service object if (typeof service === 'function') { service = service(name, app, serviceOptions) } // Need to set this manually for services not using class inheritance or default adapters if (serviceOptions.events) service.events = serviceOptions.events } // Get our initialized service so that we can register hooks and filters let servicePath = serviceOptions.path || name let contextId if (serviceOptions.context) { contextId = idToString(serviceOptions.context) servicePath = contextId + '/' + servicePath } service = declareService(servicePath, app, service, serviceOptions.middlewares) // Register hooks and event filters service = configureService(fileName, service, serviceOptions.servicesPath) // Optionnally a specific service mixin can be provided, apply it if (dbService && serviceOptions.servicesPath) { try { let serviceMixin = require(path.join(serviceOptions.servicesPath, fileName, fileName + '.service')) // If we get a function try to call it assuming it will return the mixin object if (typeof serviceMixin === 'function') { serviceMixin = serviceMixin.bind(dbService)(fileName, app, serviceOptions) } service.mixin(serviceMixin) } catch (error) { debug('No ' + fileName + ' service mixin configured on path ' + serviceOptions.servicesPath) if (error.code !== 'MODULE_NOT_FOUND') { // Log error in this case as this might be linked to a syntax error in required file debug(error) } // As this is optionnal this require has to fail silently } } // Then configuration service.name = name service.app = app service.options = serviceOptions service.path = servicePath service.context = serviceOptions.context // Add some utility functions service.getPath = function (withApiPrefix) { let path = service.path if (withApiPrefix) { path = app.get('apiPath') + '/' + path } return path } service.getContextId = function () { return contextId // As string } debug(service.name + ' service registration completed') app.emit('service', service) return service } export function createWebhook (path, app, options = {}) { let webhookPath = path if (options.context) { webhookPath = idToString(options.context) + '/' + webhookPath } const isAllowed = (payload) => { // Default is to expose all services/operations if (!options.filter) return true const result = [payload].filter(sift(options.filter)) return result.length > 0 } app.post(app.get('apiPath') + '/webhooks/' + webhookPath, async (req, res, next) => { const payload = req.body const headers = req.headers const config = app.get('authentication') res.set('Content-Type', 'application/json') let params = {} try { // Authenticate when required if (config) { try { const tokenPayload = await app.passport.verifyJWT(payload.accessToken, config) if (tokenPayload.userId) { params.user = await app.getService('users').get(tokenPayload.userId) params.checkAuthorisation = true } } catch (error) { throw new Forbidden('Could not verify webhook') } } if (!isAllowed(payload)) throw new Forbidden('Service not allowed for webhook') const service = app.getService(payload.service, payload.context) if (!service) throw new BadRequest('Service could not be found') let args = [] // Update/Patch/Remove if (_.has(payload, 'id')) args.push(_.get(payload, 'id')) // Create/Update/Patch if (_.has(payload, 'data')) args.push(_.get(payload, 'data')) // Params args.push(params) try { let result = await service[payload.operation].apply(service, args) // Send back result res.json(result) } catch (error) { throw new BadRequest('Service operation could not be performed') } } catch (error) { // Send back error res.status(error.code).json(error.toJSON()) } }) debug(`Webhook ${webhookPath} registration completed`) } function setupLogger (app) { debug('Setup application loggers') const logsConfig = app.get('logs') // Use winston default logger app.logger = logger // Remove winston defaults try { logger.clear() } catch (error) { // Logger might be down, use console console.error('Could not remove default logger transport(s)', error) } // We have one entry per log type const logsTypes = logsConfig ? Object.getOwnPropertyNames(logsConfig) : [] // Create corresponding winston transports with options logsTypes.forEach(logType => { const options = logsConfig[logType] // Setup default log level if not defined if (!options.level) { options.level = (process.env.NODE_ENV === 'development' ? 'debug' : 'info') } try { logger.add(new logger.transports[logType](options)) } catch (error) { // Logger might be down, use console console.error('Could not setup default log levels', error) } }) } function setupSockets (app) { const apiLimiter = app.get('apiLimiter') const connections = {} let nbConnections = 0 return io => { // By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. // The value can be set to Infinity (or 0) to indicate an unlimited number of listeners. io.sockets.setMaxListeners(0) const maxConnections = _.get(apiLimiter, 'websocket.maxConcurrency', 0) const maxIpConnections = _.get(apiLimiter, 'websocket.concurrency', 0) io.on('connection', socket => { nbConnections++ debug(`New socket connection on server with pid ${process.pid}`, socket.id, socket.conn.remoteAddress, nbConnections) // Setup disconnect handler first socket.on('disconnect', () => { nbConnections-- debug(`Socket disconnection on server with pid ${process.pid}`, socket.id, socket.conn.remoteAddress, nbConnections) if (maxIpConnections > 0) { const nbIpConnections = _.get(connections, socket.conn.remoteAddress) - 1 debug('Total number of connections for', socket.id, socket.conn.remoteAddress, nbIpConnections) _.set(connections, socket.conn.remoteAddress, nbIpConnections) } }) if (maxConnections > 0) { if (nbConnections > maxConnections) { tooManyRequests(socket, 'Too many concurrent connections (rate limiting)', 'RATE_LIMITING_CONCURRENCY') return } } if (maxIpConnections > 0) { if (_.has(connections, socket.conn.remoteAddress)) { const nbIpConnections = _.get(connections, socket.conn.remoteAddress) + 1 debug('Total number of connections for', socket.id, socket.conn.remoteAddress, nbConnections) _.set(connections, socket.conn.remoteAddress, nbIpConnections) if (nbIpConnections > maxIpConnections) { tooManyRequests(socket, 'Too many concurrent connections (rate limiting)', 'RATE_LIMITING_CONCURRENCY') return } } else { _.set(connections, socket.conn.remoteAddress, 1) } } /* For debug purpose: trace all data received socket.use((packet, next) => { console.log(packet) next() }) */ if (apiLimiter && apiLimiter.websocket) { const { tokensPerInterval, interval } = apiLimiter.websocket socket.socketLimiter = new SocketLimiter(tokensPerInterval, interval) socket.use((packet, next) => { if (packet.length > 0) { // Message are formatted like this 'service_path::service_method' const pathAndMethod = packet[0].split('::') if (pathAndMethod.length > 0) { // const servicePath = pathAndMethod[0] debugLimiter(socket.socketLimiter.getTokensRemaining() + ' remaining API token for socket', socket.id, socket.conn.remoteAddress) if (!socket.socketLimiter.tryRemoveTokens(1)) { // if exceeded tooManyRequests(socket, 'Too many requests in a given amount of time (rate limiting)', 'RATE_LIMITING') // FIXME: calling this causes a client timeout // next(error) // Need to normalize the error object as JSON // let result = {} // Object.getOwnPropertyNames(error).forEach(key => (result[key] = error[key])) // Trying to send error like in https://github.com/feathersjs/transport-commons/blob/auk/src/events.js#L103 // does not work either (also generates a client timeout) // socket.emit(`${servicePath} error`, result) // socket.emit(result) return } } } next() }) } authSocket(app, socket) }) } } export function kalisio () { const app = express(feathers()) // By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. // The value can be set to Infinity (or 0) to indicate an unlimited number of listeners. app.setMaxListeners(0) // Load app configuration first app.configure(configuration()) // Then setup logger setupLogger(app) // This retrieve corresponding service options from app config if any app.getServiceOptions = function (name) { const services = app.get('services') if (!services) return {} return _.get(services, name, {}) } // This avoid managing the API path before each service name app.getService = function (path, context) { // Context is given as string ID if (context && typeof context === 'string') { return app.service(app.get('apiPath') + '/' + context + '/' + path) } else if (context && typeof context === 'object') { // Could be Object ID or raw object if (ObjectID.isValid(context)) return app.service(app.get('apiPath') + '/' + context.toString() + '/' + path) else return app.service(app.get('apiPath') + '/' + context._id.toString() + '/' + path) } else { return app.service(app.get('apiPath') + '/' + path) } } // This is used to add hooks/filters to services app.configureService = function (name, service, servicesPath) { return configureService(name, service, servicesPath) } // This is used to create standard services app.createService = function (name, options) { return createService(name, app, options) } // This is used to create webhooks app.createWebhook = function (path, options) { return createWebhook(path, app, options) } // Override Feathers configure that do not manage async operations, // here we also simply call the function given as parameter but await for it app.configure = async function (fn) { await fn.call(this, this) return this } const apiLimiter = app.get('apiLimiter') if (apiLimiter && apiLimiter.http) { app.use(app.get('apiPath'), new HttpLimiter(apiLimiter.http)) } // Enable CORS, security, compression, and body parsing app.use(cors(app.get('cors'))) app.use(helmet(app.get('helmet'))) app.use(compress(app.get('compression'))) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) // Set up plugins and providers app.configure(rest()) app.configure(socketio({ path: app.get('apiPath') + 'ws' }, setupSockets(app))) app.configure(auth) // Initialize DB app.db = Database.create(app) return app }
39.731602
144
0.654881
52b443ef1be4edbd7f6131e8fd89ad7ec8a681b7
445
js
JavaScript
addon/components/masked-input.js
systembugtj/ember-maskinput
0e237b6ef68311f674e0712fe25c00f1eb83baf2
[ "MIT" ]
null
null
null
addon/components/masked-input.js
systembugtj/ember-maskinput
0e237b6ef68311f674e0712fe25c00f1eb83baf2
[ "MIT" ]
null
null
null
addon/components/masked-input.js
systembugtj/ember-maskinput
0e237b6ef68311f674e0712fe25c00f1eb83baf2
[ "MIT" ]
null
null
null
import Ember from 'ember'; export default Ember.TextField.extend({ mask: "9999 9999", tagName: "input", maskholder: "-", autoclear: false, didInsertElement() { this._super(...arguments); this.$().mask(this.get("mask"), { placeholder: this.get("maskholder"), autoclear: this.get("autoclear"), completed: this.completed.bind(this) }); }, completed() { this.sendAction("inputReady"); } });
20.227273
42
0.608989
52b4907a710a1c346957fca6350602265740b879
1,542
js
JavaScript
resources/assets/frontend/js/config/socket.js
zhouhang4200/fadan
df7a6a151dddefdb907b4cc0f67a78f9332f26e2
[ "MIT" ]
null
null
null
resources/assets/frontend/js/config/socket.js
zhouhang4200/fadan
df7a6a151dddefdb907b4cc0f67a78f9332f26e2
[ "MIT" ]
4
2020-02-15T00:02:01.000Z
2022-02-26T15:24:34.000Z
resources/assets/frontend/js/config/socket.js
zhouhang4200/fadan
df7a6a151dddefdb907b4cc0f67a78f9332f26e2
[ "MIT" ]
null
null
null
var webSocket = null; var global_callback = null; var serverPort = '5000'; //webSocket连接端口 function getWebIP(){ // let serverIp = window.location.hostname; return window.location.hostname; } function initWebSocket(){ //初始化weosocket //ws地址 let wsUri = "ws://" +getWebIP()+ ":" + serverPort; webSocket = new WebSocket(wsUri); webSocket.onmessage = function(e){ webSocketOnMessage(e); }; webSocket.onclose = function(e){ webSocketClose(e); }; webSocket.onopen = function () { webSocketOpen(); }; //连接发生错误的回调方法 webSocket.onerror = function () { console.log("WebSocket连接发生错误"); }; } // 实际调用的方法 function sendSock(agentData,callback){ global_callback = callback; if (webSocket.readyState === webSocket.OPEN) { //若是ws开启状态 webSocketSend(agentData); }else if (webSocket.readyState === webSocket.CONNECTING) { // 若是 正在开启状态,则等待1s后重新调用 setTimeout(function () { sendSock(agentData,callback); }, 1000); }else { // 若未开启 ,则等待1s后重新调用 setTimeout(function () { sendSock(agentData,callback); }, 1000); } } //数据接收 function webSocketOnMessage(e){ global_callback(JSON.parse(e.data)); } //数据发送 function webSocketSend(agentData){ webSocket.send(JSON.stringify(agentData)); } //关闭 function webSocketClose(e){ console.log("connection closed (" + e.code + ")"); } function webSocketOpen(e){ console.log("连接成功"); } initWebSocket(); export{sendSock};
22.028571
62
0.627108
52b4ac12233bf25229355062792c239ba0d91d30
828
js
JavaScript
src/components/icon-link.js
samjam48/js-jabber-clone
0fb786d20064e66bfb63897f569b83ac397381d3
[ "MIT" ]
133
2015-11-21T15:52:37.000Z
2021-12-22T21:57:39.000Z
src/components/icon-link.js
samjam48/js-jabber-clone
0fb786d20064e66bfb63897f569b83ac397381d3
[ "MIT" ]
167
2015-11-20T18:12:11.000Z
2020-10-01T19:52:17.000Z
src/components/icon-link.js
samjam48/js-jabber-clone
0fb786d20064e66bfb63897f569b83ac397381d3
[ "MIT" ]
69
2015-12-21T21:18:09.000Z
2022-03-27T13:53:27.000Z
import {PropTypes} from 'react' import {StyleSheet, css} from 'aphrodite' import {linkColor, linkHoverColor} from '<styles>/variables' import classNames from 'classnames' import Icon from './icon' export default IconLink function IconLink(props) { const {black, ...remaining} = props // eslint-disable-line const {styles} = IconLink const iconClassName = css(black ? styles.blackIcon : styles.icon) return ( <a {...remaining} className={null}> <Icon {...remaining} className={classNames(iconClassName, props.className)} /> </a> ) } IconLink.propTypes = { className: PropTypes.string, black: PropTypes.bool, } IconLink.styles = StyleSheet.create({ icon: { fill: linkColor, ':hover': {fill: linkHoverColor}, }, blackIcon: { fill: 'black', ':hover': {fill: '#2B2B2B'}, }, })
23.657143
84
0.671498
52b5f894ed2b019ee2f95e7e3f0179366005daea
524
js
JavaScript
docs/doc/implementors/core/marker/trait.StructuralEq.js
DanielIrons/ledge_engine
82b9b6b63796de04cf8bdaab9a397086e8dfe1db
[ "MIT" ]
2
2021-12-28T12:34:22.000Z
2022-02-03T16:26:41.000Z
docs/doc/implementors/core/marker/trait.StructuralEq.js
DanielIrons/ledge_engine
82b9b6b63796de04cf8bdaab9a397086e8dfe1db
[ "MIT" ]
null
null
null
docs/doc/implementors/core/marker/trait.StructuralEq.js
DanielIrons/ledge_engine
82b9b6b63796de04cf8bdaab9a397086e8dfe1db
[ "MIT" ]
1
2021-12-28T12:34:31.000Z
2021-12-28T12:34:31.000Z
(function() {var implementors = {}; implementors["ledge_engine"] = [{"text":"impl StructuralEq for BlendMode","synthetic":false,"types":[]},{"text":"impl&lt;A&gt; StructuralEq for Handle&lt;A&gt; <span class=\"where fmt-newline\">where<br>&nbsp;&nbsp;&nbsp;&nbsp;A: Asset,&nbsp;</span>","synthetic":false,"types":[]},{"text":"impl StructuralEq for HandleId","synthetic":false,"types":[]}]; if (window.register_implementors) {window.register_implementors(implementors);} else {window.pending_implementors = implementors;}})()
174.666667
353
0.719466
52b6364c1be86f692cae1fcc1d2a71fa2e06e72f
3,943
js
JavaScript
packages/api/tests/lambdas/test-sns-consumer.js
schwabm/cumulus
e679c0b75836197ebf7262858f45e6710cdfb860
[ "Apache-2.0" ]
null
null
null
packages/api/tests/lambdas/test-sns-consumer.js
schwabm/cumulus
e679c0b75836197ebf7262858f45e6710cdfb860
[ "Apache-2.0" ]
null
null
null
packages/api/tests/lambdas/test-sns-consumer.js
schwabm/cumulus
e679c0b75836197ebf7262858f45e6710cdfb860
[ "Apache-2.0" ]
null
null
null
'use strict'; const get = require('lodash/get'); const sinon = require('sinon'); const test = require('ava'); const SQS = require('@cumulus/aws-client/SQS'); const { randomString } = require('@cumulus/common/test-utils'); const { handler } = require('../../lambdas/message-consumer'); const Collection = require('../../models/collections'); const Rule = require('../../models/rules'); const Provider = require('../../models/providers'); const testCollectionName = 'test-collection'; /** * Callback used for testing * * @param {*} err - error * @param {Object} object - object * @returns {Object} object, if no error is thrown */ function testCallback(err, object) { if (err) throw err; return object; } const snsArn = 'test-SnsArn'; const messageBody = '{"Data":{}}'; const event = { Records: [ { EventSource: 'aws:sns', EventVersion: '1.0', EventSubscriptionArn: 'arn:aws:sns:us-east-1:00000000000:gdelt-csv:111111-111', Sns: { Type: 'Notification', MessageId: '4f411981', TopicArn: snsArn, Subject: 'Amazon S3 Notification', Message: messageBody, MessageAttributes: {} } } ] }; const collection = { name: testCollectionName, version: '0.0.0' }; const provider = { id: 'PROV1' }; const stubQueueUrl = 'stubQueueUrl'; let ruleModel; let sandbox; let sfSchedulerSpy; test.before(async () => { process.env.CollectionsTable = randomString(); process.env.ProvidersTable = randomString(); process.env.RulesTable = randomString(); process.env.stackName = randomString(); process.env.system_bucket = randomString(); process.env.messageConsumer = randomString(); ruleModel = new Rule(); await ruleModel.createTable(); sandbox = sinon.createSandbox(); sandbox.stub(ruleModel, 'addSnsTrigger'); sandbox.stub(ruleModel, 'deleteSnsTrigger'); }); test.beforeEach(async (t) => { t.context.templateBucket = randomString(); t.context.workflow = randomString(); t.context.stateMachineArn = randomString(); t.context.messageTemplate = { meta: { queues: { startSF: stubQueueUrl } } }; const workflowDefinition = { name: t.context.workflow, arn: t.context.stateMachineArn }; sfSchedulerSpy = sandbox.stub(SQS, 'sendSQSMessage').returns(true); sandbox.stub(Rule, 'buildPayload').callsFake((item) => Promise.resolve({ template: t.context.messageTemplate, provider: item.provider, collection: item.collection, meta: get(item, 'meta', {}), payload: get(item, 'payload', {}), definition: workflowDefinition })); sandbox.stub(Provider.prototype, 'get').resolves(provider); sandbox.stub(Collection.prototype, 'get').resolves(collection); }); test.afterEach.always(async () => { sfSchedulerSpy.resetHistory(); }); test.after.always(async () => { await ruleModel.deleteTable(); sandbox.restore(); }); // handler tests test.serial('it should enqueue a message for each associated workflow', async (t) => { const rule1 = { name: 'testRule1', collection, provider: provider.id, rule: { type: 'sns', value: snsArn }, state: 'ENABLED', workflow: 'test-workflow-1' }; await ruleModel.create(rule1); await handler(event, {}, testCallback); const actualQueueUrl = sfSchedulerSpy.getCall(0).args[0]; t.is(actualQueueUrl, stubQueueUrl); const actualMessage = sfSchedulerSpy.getCall(0).args[1]; const expectedMessage = { cumulus_meta: { state_machine: t.context.stateMachineArn }, meta: { queues: { startSF: stubQueueUrl }, provider, collection, snsSourceArn: snsArn, workflow_name: t.context.workflow }, payload: JSON.parse(messageBody) }; t.is(actualMessage.cumulus_meta.state_machine, expectedMessage.cumulus_meta.state_machine); t.deepEqual(actualMessage.meta, expectedMessage.meta); t.deepEqual(actualMessage.payload, expectedMessage.payload); });
26.823129
93
0.673345
52b63c3f99e8bf691fafc9a6f788c18aa50a112f
5,307
js
JavaScript
web/cypress/integration/service/create-edit-delete-service.spec.js
zzzdong/apisix-dashboard
846f2c14d2343d9aa79dbe332e699850c92fe161
[ "Apache-2.0", "MIT" ]
1
2021-07-07T06:32:30.000Z
2021-07-07T06:32:30.000Z
web/cypress/integration/service/create-edit-delete-service.spec.js
zzzdong/apisix-dashboard
846f2c14d2343d9aa79dbe332e699850c92fe161
[ "Apache-2.0", "MIT" ]
null
null
null
web/cypress/integration/service/create-edit-delete-service.spec.js
zzzdong/apisix-dashboard
846f2c14d2343d9aa79dbe332e699850c92fe161
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable no-undef */ context('Create and Delete Service ', () => { const timeout = 5000; beforeEach(() => { cy.login(); cy.fixture('selector.json').as('domSelector'); cy.fixture('data.json').as('data'); }); it('should create service', function () { cy.visit('/'); cy.contains('Service').click(); cy.contains('Create').click(); cy.get(this.domSelector.name).type(this.data.serviceName); cy.get(this.domSelector.description).type(this.data.description); cy.get(this.domSelector.nodes_0_host).click(); cy.get(this.domSelector.nodes_0_host).type(this.data.ip1); cy.contains('Next').click(); cy.contains(this.data.basicAuthPlugin).parents(this.domSelector.pluginCardBordered).within(() => { cy.get('button').click({ force: true }); }); cy.get(this.domSelector.drawer).should('be.visible').within(() => { cy.get(this.domSelector.disabledSwitcher).click(); cy.get(this.domSelector.checkedSwitcher).should('exist'); }); cy.contains('button', 'Submit').click(); cy.get(this.domSelector.drawer, { timeout }).should('not.exist'); cy.contains(this.data.basicAuthPlugin).parents(this.domSelector.pluginCardBordered).within(() => { cy.get('button').click({ force: true }); }); cy.get(this.domSelector.drawerFooter).contains('button', 'Delete').click({ force: true }); cy.contains('button', 'Confirm').click({ force: true }); cy.contains(this.data.basicAuthPlugin).parents(this.domSelector.pluginCardBordered).within(() => { cy.get('button').click({ force: true }); }); cy.get(this.domSelector.drawerFooter).contains('button', 'Delete').should('not.exist'); cy.contains('button', 'Cancel').click({ force: true }); cy.contains('Next').click(); cy.contains('Submit').click(); cy.get(this.domSelector.notification).should('contain', this.data.createServiceSuccess); }); it('should view the service', function () { cy.visit('/'); cy.contains('Service').click(); cy.get(this.domSelector.nameSelector).type(this.data.serviceName); cy.contains('Search').click(); cy.contains(this.data.serviceName).siblings().contains('View').click(); cy.get(this.domSelector.drawer).should('be.visible'); cy.get(this.domSelector.codemirrorScroll).within(() => { cy.contains('upstream').should('exist'); cy.contains(this.data.serviceName).should('exist'); }); }); it('should edit the service', function () { cy.visit('/'); cy.contains('Service').click(); cy.get(this.domSelector.nameSelector).type(this.data.serviceName); cy.contains('Search').click(); cy.contains(this.data.serviceName).siblings().contains('Configure').click(); // Confirm whether the created data is saved. cy.get(this.domSelector.nodes_0_host).should('value', this.data.ip1); cy.get(this.domSelector.description).should('value', this.data.description); cy.get(this.domSelector.name).clear().type(this.data.serviceName2); cy.get(this.domSelector.description).clear().type(this.data.description2); cy.get(this.domSelector.nodes_0_host).click(); cy.get(this.domSelector.nodes_0_host).clear().type(this.data.ip2); cy.contains('Next').click(); cy.contains('Next').click(); cy.contains('Submit').click(); cy.get(this.domSelector.notification).should('contain', this.data.editServiceSuccess); // test view cy.contains(this.data.serviceName2).siblings().contains('View').click(); cy.get(this.domSelector.drawer).should('be.visible'); cy.get(this.domSelector.codemirrorScroll).within(() => { cy.contains('upstream').should('exist'); cy.contains(this.data.serviceName2).should('exist'); }); }); it('should delete the service', function () { // Confirm whether the edited data is saved. cy.visit('/service/list'); cy.get(this.domSelector.nameSelector).type(this.data.serviceName2); cy.contains('Search').click(); cy.contains(this.data.serviceName2).siblings().contains('Configure').click(); cy.get(this.domSelector.nodes_0_host).should('value', this.data.ip2); cy.get(this.domSelector.description).should('value', this.data.description2); cy.visit('/'); cy.contains('Service').click(); cy.contains(this.data.serviceName2).siblings().contains('Delete').click(); cy.contains('button', 'Confirm').click(); cy.get(this.domSelector.notification).should('contain', this.data.deleteServiceSuccess); }); });
39.902256
102
0.682872
52b7f22c60056bf98f4600ea058857f4098eff21
1,227
js
JavaScript
node_modules/just-handlebars-helpers/lib/helpers/math.js
klorenz/markdown-spreadsheet
5602eb218d8de95117cbe4c283511c8b0921c8b2
[ "MIT" ]
5
2016-08-31T11:11:53.000Z
2022-03-08T19:43:43.000Z
node_modules/just-handlebars-helpers/lib/helpers/math.js
klorenz/markdown-spreadsheet
5602eb218d8de95117cbe4c283511c8b0921c8b2
[ "MIT" ]
1
2019-10-04T09:02:44.000Z
2019-10-04T09:02:44.000Z
node_modules/just-handlebars-helpers/lib/helpers/math.js
klorenz/markdown-spreadsheet
5602eb218d8de95117cbe4c283511c8b0921c8b2
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { /** * A sum helper calculating the sum of two numbers. * @example * {{sum 1 2}} => 3 * * @param value1 * @param value2 * @returns number */ sum: function sum(value1, value2) { return Number(value1) + Number(value2); }, /** * A difference helper calculating the difference of two numbers. * @example * {{difference 5 2}} => 3 * * @param value1 * @param value2 * @returns number */ difference: function difference(value1, value2) { return Number(value1) - Number(value2); }, /** * A ceil helper to find the ceil value of the number. * @example * {{ceil 5.6}} => 6 * * @param value * @returns number */ ceil: function ceil(value) { return Math.ceil(Number(value)); }, /** * A floor helper to find the floor value of the number. * @example * {{floor 5.6}} => 5 * * @param value * @returns number */ floor: function floor(value) { return Math.floor(Number(value)); } };
21.910714
69
0.523227
52b878ecbeb4ffa9ab2c765757d403473c43abaa
2,105
js
JavaScript
test/built-ins/Atomics/wake/wake-all-on-loc.js
apaprocki/test262
5d6899522ad913003f83e1127f84f5d068112460
[ "BSD-3-Clause" ]
null
null
null
test/built-ins/Atomics/wake/wake-all-on-loc.js
apaprocki/test262
5d6899522ad913003f83e1127f84f5d068112460
[ "BSD-3-Clause" ]
null
null
null
test/built-ins/Atomics/wake/wake-all-on-loc.js
apaprocki/test262
5d6899522ad913003f83e1127f84f5d068112460
[ "BSD-3-Clause" ]
null
null
null
// Copyright (C) 2017 Mozilla Corporation. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-atomics.wake description: > Test that Atomics.wake wakes all waiters on a location, but does not wake waiters on other locations. features: [Atomics] ---*/ var WAKEUP = 0; // Waiters on this will be woken var DUMMY = 1; // Waiters on this will not be woken var RUNNING = 2; // Accounting of live agents var NUMELEM = 3; var NUMAGENT = 3; for (var i=0; i < NUMAGENT; i++) { $262.agent.start( ` $262.agent.receiveBroadcast(function (sab) { var ia = new Int32Array(sab); Atomics.add(ia, ${RUNNING}, 1); $262.agent.report("A " + Atomics.wait(ia, ${WAKEUP}, 0)); $262.agent.leaving(); }) `); } $262.agent.start( ` $262.agent.receiveBroadcast(function (sab) { var ia = new Int32Array(sab); Atomics.add(ia, ${RUNNING}, 1); // This will always time out. $262.agent.report("B " + Atomics.wait(ia, ${DUMMY}, 0, 1000)); $262.agent.leaving(); }) `); var ia = new Int32Array(new SharedArrayBuffer(NUMELEM * Int32Array.BYTES_PER_ELEMENT)); $262.agent.broadcast(ia.buffer); // Wait for agents to be running. waitUntil(ia, RUNNING, NUMAGENT + 1); // Then wait some more to give the agents a fair chance to wait. If we don't, // we risk sending the wakeup before agents are sleeping, and we hang. $262.agent.sleep(500); // Wake all waiting on WAKEUP, should be 3 always, they won't time out. assert.sameValue(Atomics.wake(ia, WAKEUP), NUMAGENT); var rs = []; for (var i = 0; i < NUMAGENT + 1; i++) rs.push(getReport()); rs.sort(); for (var i = 0; i < NUMAGENT; i++) assert.sameValue(rs[i], "A ok"); assert.sameValue(rs[NUMAGENT], "B timed-out"); function getReport() { var r; while ((r = $262.agent.getReport()) == null) $262.agent.sleep(100); return r; } function waitUntil(ia, k, value) { var i = 0; while (Atomics.load(ia, k) !== value && i < 15) { $262.agent.sleep(100); i++; } assert.sameValue(Atomics.load(ia, k), value, "All agents are running"); }
26.64557
87
0.645606
52b9a9ab2f21d906e8b3ee1ee7aecaf77ea2f607
1,859
js
JavaScript
workout/static/js/sw.js
Yaasha/interactive-cheat-sheet
7401fc492a06480d042725016cd94e9626ef1734
[ "MIT" ]
1
2018-08-26T14:16:04.000Z
2018-08-26T14:16:04.000Z
workout/static/js/sw.js
Yaasha/interactive-cheat-sheet
7401fc492a06480d042725016cd94e9626ef1734
[ "MIT" ]
null
null
null
workout/static/js/sw.js
Yaasha/interactive-cheat-sheet
7401fc492a06480d042725016cd94e9626ef1734
[ "MIT" ]
null
null
null
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.4.1/workbox-sw.js'); workbox.routing.registerRoute( /\.(?:png|gif|jpg|jpeg|json|js|css)$/, workbox.strategies.staleWhileRevalidate({ cacheName: 'static', }) ); workbox.routing.registerRoute( /^https:\/\/storage\.googleapis\.com/, workbox.strategies.staleWhileRevalidate({ cacheName: 'static', }), ); workbox.routing.registerRoute( /^https:\/\/fonts\.googleapis\.com/, workbox.strategies.staleWhileRevalidate({ cacheName: 'google-fonts-stylesheets', }), ); workbox.routing.registerRoute( /^https:\/\/cdnjs\.cloudflare\.com/, workbox.strategies.staleWhileRevalidate({ cacheName: 'cloudflare', }), ); workbox.routing.registerRoute( /^https:\/\/code\.jquery\.com/, workbox.strategies.staleWhileRevalidate({ cacheName: 'jquery', }), ); workbox.routing.registerRoute( /^https:\/\/cdn\.jsdelivr\.net/, workbox.strategies.staleWhileRevalidate({ cacheName: 'jsdelivr', }), ); workbox.routing.registerRoute( /^https:\/\/www\.googletagmanager\.com/, workbox.strategies.staleWhileRevalidate({ cacheName: 'googletagmanager', }), ); workbox.routing.registerRoute( /^https:\/\/soundjay\.com/, workbox.strategies.staleWhileRevalidate({ cacheName: 'soundjay', }), ); workbox.routing.registerRoute( '/', workbox.strategies.staleWhileRevalidate({ cacheName: 'content', }) ); workbox.routing.registerRoute( '/recommended-routine/', workbox.strategies.staleWhileRevalidate({ cacheName: 'content', }) ); workbox.routing.registerRoute( '/skill-day/', workbox.strategies.staleWhileRevalidate({ cacheName: 'content', }) ); workbox.routing.registerRoute( /show_details\?.*$/, workbox.strategies.staleWhileRevalidate({ cacheName: 'content', }) ); workbox.googleAnalytics.initialize();
21.367816
89
0.698763
52baf7226746856f3cd3c8bfe55a1d6bbd408281
480
js
JavaScript
catparty/src/catDancer.js
stefanruijsenaars/stefanruijsenaars.github.io
6f8a74127b3fb1ebc8bf6211bf8e86114f07cd73
[ "MIT" ]
null
null
null
catparty/src/catDancer.js
stefanruijsenaars/stefanruijsenaars.github.io
6f8a74127b3fb1ebc8bf6211bf8e86114f07cd73
[ "MIT" ]
null
null
null
catparty/src/catDancer.js
stefanruijsenaars/stefanruijsenaars.github.io
6f8a74127b3fb1ebc8bf6211bf8e86114f07cd73
[ "MIT" ]
null
null
null
var CatDancer = function(top, left, timeBetweenSteps) { this.gifs = [ // second argument is the BPMs. ['assets/images/cat1.gif', 2], ['assets/images/cat2.gif', 2], ['assets/images/cat3.gif', 4], ['assets/images/cat4.gif', 2], ['assets/images/cat5.gif', 2], ['assets/images/cat6.gif', 2], ]; GifDancer.call(this, top, left, timeBetweenSteps); }; CatDancer.prototype = Object.create(Dancer.prototype); CatDancer.prototype.constructor = CatDancer;
30
55
0.660417
52bc104d1ec823936f5e92df99ac2a6e8816e0fa
3,261
js
JavaScript
projects/clairvoyance/assets/js/register.js
daviruiz3/miniature-bear
7e8fd7cd2ade1291509161d280f730347af2b0a5
[ "CC-BY-3.0" ]
null
null
null
projects/clairvoyance/assets/js/register.js
daviruiz3/miniature-bear
7e8fd7cd2ade1291509161d280f730347af2b0a5
[ "CC-BY-3.0" ]
null
null
null
projects/clairvoyance/assets/js/register.js
daviruiz3/miniature-bear
7e8fd7cd2ade1291509161d280f730347af2b0a5
[ "CC-BY-3.0" ]
null
null
null
$(window).load(function() { $('.controls input').change(validateForm); $('#psychform').submit(function(e){ //alert("it worked"); e.preventDefault(); //ajaxCall(); ajaxCall(); return false; }); $('#clear').bind("click", clearform); }); //need to connect to database... pass ajaxdata to webservice or something that can connect to DB // function ajaxCall() { //alert("ajaxCall"); dataString = $('#psychform').serialize(); $.post("psychicregisterhelper.php", dataString, function(data){ if(data.email_check == 'invalid'){ $("#errors").html("<div class='errorMessage'>Sorry " + data.firstName + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>"); } else { $("#errors").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.firstName + ".</div>"); } console.log(data.insertResult); }, "json").fail(function() {alert("FAILURE!")}); } function validateForm() { console.log("entering validateForm() function"); var fName = $('#firstName').val(); var lName = $('#lastName').val(); var user = $('#userName').val(); var email = $('#inputEmail').val(); var pass = $('#pass').val(); var cPass = $('#confirmPass').val(); if (fName != "" && lName != "" && user != "" && email != "" && pass != "" && cPass != "") { var namePatt = /^[a-zA-Z]+$/g; if (!namePatt.test(fName) && fName != "") { console.log("invalid first name"); //print invalid first name or last name var div = document.createElement("div"); div.innerHTML = "Invalid first name."; var errors = document.getElementById('errors'); div.setAttribute("id", "errorfName"); errors.appendChild(div); } else { if ($('#errorfName').length != 0) { $('#errorfName').remove(); } } if (!namePatt.test(lName) && lName != "") { console.log("invalid last name"); //print invalid first name or last name var div = document.createElement("div"); div.innerHTML = "Invalid last name."; var errors = document.getElementById('errors'); div.setAttribute("id", "errorlName"); errors.appendChild(div); } else { if ($('#errorlName').length != 0) { $('#errorlName').remove(); } } var emailPatt = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; if (!emailPatt.test(email) && email != "") { console.log("invalid email"); var div = document.createElement("div"); div.innerHTML = "Invalid Email."; var errors = document.getElementById('errors'); errors.appendChild(div); } /* if (pass.length == 0 || cPass.length == 0) { console.log("mismatch passwords"); //print passwords do not match var div = document.createElement("div"); div.innerHTML = "Passwords do not match."; var errors = document.getElementById('errors'); errors.appendChild(div); } */ if (pass != cPass) { console.log("mismatch passwords"); //print passwords do not match var div = document.createElement("div"); div.innerHTML = "Passwords do not match."; var errors = document.getElementById('errors'); errors.appendChild(div); } } } function clearform() { $('.controls input').innerHTML = ""; $('#errors').innerHTML = ""; }
31.660194
164
0.596443
52bc13dac6d69ffade28b3f321170e5e47666c9c
1,265
js
JavaScript
src/js/app.js
lewandy/Vanilla-Blog
263c33234331ca3ce89d0cd6cd3c280fbaefb9d6
[ "MIT" ]
1
2021-01-18T12:26:11.000Z
2021-01-18T12:26:11.000Z
src/js/app.js
lewandy/Vanilla-Blog
263c33234331ca3ce89d0cd6cd3c280fbaefb9d6
[ "MIT" ]
1
2022-02-18T12:49:20.000Z
2022-02-18T12:49:20.000Z
src/js/app.js
lewandy/Vanilla-Blog
263c33234331ca3ce89d0cd6cd3c280fbaefb9d6
[ "MIT" ]
null
null
null
import App from "../core/app"; import Router from "../core/router"; import routes from "./routes/routes" import { TheAsideComponent, TheFooterComponent, TheHeaderComponent } from "./components/layout" import PostsComponent from "./components/PostsComponent"; import CommentsComponent from "./components/CommentsComponent"; //Services to be injected import PostService from "./services/postService"; import AuthService from "./services/authService" import UserService from "./services/userService" export default class BlogApp extends App { router = null; constructor() { super( TheFooterComponent, TheHeaderComponent, TheAsideComponent, PostsComponent, CommentsComponent ); this.router = new Router({ routes }); this.configureServices(); window.blog = this; } /** * App services */ get services() { return this.serviceContainer.services; } /** * Register services to the service container to be use globally */ configureServices() { this.serviceContainer.register("Post", new PostService()); this.serviceContainer.register("Auth", new AuthService()); this.serviceContainer.register("User", new UserService()); } }
26.354167
95
0.682213
52bccbc1cac69411c477e144adfa842d35dc27a7
423
js
JavaScript
packages/core/src/scripts/components/marks/index.js
NoBey/re-editor
a4bdc16b34632b9c56ea72861528e3d6deecab63
[ "MIT" ]
448
2019-03-17T15:14:37.000Z
2022-03-09T18:11:35.000Z
packages/core/src/scripts/components/marks/index.js
galaxy-book/galaxy-editor
fd9c57a4e8012c8152ce6e8848d2163f22395fc4
[ "MIT" ]
86
2019-03-18T02:20:13.000Z
2022-02-26T10:06:09.000Z
packages/core/src/scripts/components/marks/index.js
galaxy-book/galaxy-editor
fd9c57a4e8012c8152ce6e8848d2163f22395fc4
[ "MIT" ]
40
2019-03-18T02:49:24.000Z
2022-03-24T07:03:59.000Z
import { generateElementComponents } from '~/utils/utils'; import code from './code'; export const basicMarks = { bold: { name: 'strong' }, italic: { name: 'em' }, span: { name: 'span' }, underline: { name: 'u' }, superscript: { name: 'sup' }, subscript: { name: 'sub' }, strikethrough: { name: 'del' } }; export default { ...generateElementComponents(basicMarks), ...generateElementComponents(code) };
23.5
58
0.631206
52bd0a8b53d31a89814cfed299469c93fb47d5a2
4,734
js
JavaScript
src/store/modules/cart.js
soyojoearth/nxtframework_ucenter
64f0b7ebf74ac1557966ab3c4ca19d7f52f021f1
[ "Apache-2.0" ]
4
2021-02-24T01:39:23.000Z
2021-11-20T06:06:55.000Z
src/store/modules/cart.js
soyojoearth/nxtframework_ucenter
64f0b7ebf74ac1557966ab3c4ca19d7f52f021f1
[ "Apache-2.0" ]
null
null
null
src/store/modules/cart.js
soyojoearth/nxtframework_ucenter
64f0b7ebf74ac1557966ab3c4ca19d7f52f021f1
[ "Apache-2.0" ]
9
2021-02-25T09:17:17.000Z
2022-01-14T03:38:24.000Z
import { detail, addProduct, delProduct, selectProduct ,info} from '@/api/cart' import { getGuestToken, setGuestToken } from '@/utils/auth' const state = { productList:[], cartProductList:[], guestToken:getGuestToken(), deliveryPerson:'', deliveryProvince:'', deliveryCity:'', deliveryAddress: '', deliveryPhone:'', deliveryConfigId:1, deliveryConfig:'', dealPlatform:1, deliveryRemark:'', deliveryCountry:'', countAll:0 } const mutations = { SET_PRODUCT_LIST: (state, data) => { state.productList = data }, SET_PRODUCT_NUM: (state, data) => { state.productList.map(element => { if(element.id == data.id) { element.quantity = data.num } }); }, DEl_PRODUCT:(state, data) =>{ let arr = []; state.productList.map(element => { if(element.id != data.id) { arr.push(element) } }); state.productList = arr }, CHECK_PRODUCT: (state, data) =>{ let arr = []; state.productList.map(element => { if(element.id == data.id) { if(element.checkout) element.checkout = false else element.checkout = true } arr.push(element) }); state.productList = arr }, CHECK_ALL: (state, data) => { let arr = []; state.productList.map(element => { if(!element.invalid){ element.checkout = data arr.push(element) } }); state.productList = arr }, SET_ADDRESS: (state, data) =>{ const {deliveryPerson,deliveryProvince,deliveryCity, deliveryAddress,deliveryPhone,deliveryConfigId, deliveryConfig,dealPlatform,deliveryRemark,deliveryCountry} = data; state.deliveryPerson = deliveryPerson state.deliveryProvince = deliveryProvince state.deliveryCity = deliveryCity state.deliveryAddress = deliveryAddress state.deliveryPhone = deliveryPhone state.deliveryConfigId = deliveryConfigId state.deliveryConfig = deliveryConfig state.dealPlatform = dealPlatform state.deliveryRemark = deliveryRemark state.deliveryCountry = deliveryCountry }, BUY_PRODUCT:(state, data) =>{ state.cartProductList = data }, SET_GUESTTOKEN:(state, data) => { state.guestToken = data }, SET_COUNT: (state, data) => { state.countAll = data } } const actions = { detail({ state,commit }, data ={}) { return new Promise((resolve, reject) => { detail({ guestToken:state.guestToken,...data }).then(response => { const { itemList, guestToken} = response.result itemList.map(item =>{ if(!item.invalid){ item.checkout = item.selected }else{ item.checkout = false } }) if(guestToken != state.getGuestToken) { setGuestToken(guestToken) commit('SET_GUESTTOKEN', guestToken) } commit('SET_PRODUCT_LIST', itemList) resolve() }).catch(error => { reject(error) }) }) }, // eslint-disable-next-line no-empty-pattern addProduct({ }, data) { const { product } = data; return new Promise((resolve, reject) => { addProduct({ product:product,guestToken:state.guestToken}).then(() => { resolve() }).catch(error => { reject(error) }) }) }, delProduct({state}, data) { return new Promise((resolve, reject) => { delProduct({guestToken:state.guestToken,product:data}).then(() => { // commit('DEl_PRODUCT', {id:data.id}) resolve() }).catch(error => { reject(error) }) }) }, selectProduct({state, commit}, data) { return new Promise((resolve, reject) => { selectProduct({guestToken: state.guestToken, product: data}).then(() => { commit('CHECK_PRODUCT', data) resolve() }).catch(error => { reject(error) }) }) }, // eslint-disable-next-line no-empty-pattern info({ commit, state }) { return new Promise((resolve, reject) => { info({ guestToken:state.guestToken }).then((res) => { commit('SET_COUNT',res.result.countAll) // console.log(res) resolve() }).catch(error => { reject(error) }) }) } } export default { namespaced: true, state, mutations, actions }
29.042945
85
0.539501
52bd13d8df175e854078ebe02aa6c15b8bc27a58
13,743
js
JavaScript
backend/node_modules/pm2/lib/API/Modules/Modularizer.js
diegohfacchinetti/ExemploReactRedux
da1c5ef98d076ce206871fd2d3b5c7362fe4b03c
[ "MIT" ]
3
2018-05-30T10:08:53.000Z
2020-05-19T16:44:54.000Z
backend/node_modules/pm2/lib/API/Modules/Modularizer.js
diegohfacchinetti/ExemploReactRedux
da1c5ef98d076ce206871fd2d3b5c7362fe4b03c
[ "MIT" ]
null
null
null
backend/node_modules/pm2/lib/API/Modules/Modularizer.js
diegohfacchinetti/ExemploReactRedux
da1c5ef98d076ce206871fd2d3b5c7362fe4b03c
[ "MIT" ]
null
null
null
/** * Copyright 2013 the PM2 project authors. All rights reserved. * Use of this source code is governed by a license that * can be found in the LICENSE file. */ var shelljs = require('shelljs'); var path = require('path'); var fs = require('fs'); var async = require('async'); var p = path; var readline = require('readline'); var spawn = require('child_process').spawn; var chalk = require('chalk'); var Configuration = require('../../Configuration.js'); var cst = require('../../../constants.js'); var Common = require('../../Common'); var UX = require('../CliUx.js'); var Utility = require('../../Utility.js'); var Modularizer = module.exports = {}; var MODULE_CONF_PREFIX = 'module-db'; function startModule(CLI, opts, cb) { /** SCRIPT * Open file and make the script detection smart */ if (!opts.cmd) throw new Error('module package.json not defined'); if (!opts.development_mode) opts.development_mode = false; var package_json = require(opts.cmd); /** * Script file detection * 1- *apps* field (default pm2 json configuration) * 2- *bin* field * 3- *main* field */ if (!package_json.apps) { package_json.apps = {}; if (package_json.bin) { var bin = Object.keys(package_json.bin)[0]; package_json.apps.script = package_json.bin[bin]; } else if (package_json.main) { package_json.apps.script = package_json.main; } } /** * Verify that the module is valid * If not, delete */ if (isValidModule(package_json) === false) { if (!opts.development_mode) shelljs.rm('-rf', opts.proc_pabth); Common.printError(cst.PREFIX_MSG_MOD + 'Module uninstalled'); return cb(new Error('Invalid module (script is missing)')); } // Start the module CLI.start(package_json, { cwd : opts.proc_path, watch : opts.development_mode, force_name : package_json.name, started_as_module : true }, function(err, data) { if (err) return cb(err); return cb(null, data); }); }; function installModule(CLI, module_name, cb) { var proc_path = '', cmd = '', conf = {}, development_mode = false; if (module_name == '.') { /** * Development mode */ Common.printOut(cst.PREFIX_MSG_MOD + 'Installing local module in DEVELOPMENT MODE with WATCH auto restart'); development_mode = true; proc_path = process.cwd(); cmd = p.join(proc_path, cst.DEFAULT_MODULE_JSON); startModule(CLI, { cmd : cmd, development_mode : development_mode, proc_path : proc_path }, function(err, dt) { if (err) return cb(err); Common.printOut(cst.PREFIX_MSG_MOD + 'Module successfully installed and launched'); return cb(null, dt); }); } else { /** * Production mode */ //UX.processing.start('Downloading module'); Common.printOut(cst.PREFIX_MSG_MOD + 'Calling ' + chalk.bold.red('[NPM]') + ' registry...'); var install_instance; install_instance = spawn(cst.IS_WINDOWS ? 'npm.cmd' : 'npm', [ 'install', module_name, '--prefix', cst.PM2_ROOT_PATH, '--loglevel=error' ],{ stdio : 'inherit', env: process.env, shell : true }); install_instance.on('close', finalize); install_instance.on('error', function (err) { console.error(err.stack || err); }); function finalize(code) { if (code != 0) { return cb(new Error("Installation failed")); } Common.printOut(cst.PREFIX_MSG_MOD + 'Module downloaded'); if (module_name.match(/\.tgz($|\?)/)) { module_name = Utility.packageNameToModuleName(module_name); } else if (module_name.indexOf('/') != -1) module_name = module_name.split('/')[1]; //pm2 install module@2.1.0-beta if(module_name.indexOf('@') != -1) module_name = module_name.split('@')[0] proc_path = p.join(cst.PM2_ROOT_PATH, 'node_modules', module_name); cmd = p.join(proc_path, cst.DEFAULT_MODULE_JSON); Configuration.set(MODULE_CONF_PREFIX + ':' + module_name, 'true', function(err, data) { startModule(CLI, { cmd : cmd, development_mode : development_mode, proc_path : proc_path }, function(err, dt) { if (err) return cb(err); Common.printOut(cst.PREFIX_MSG_MOD + 'Module successfully installed and launched'); Common.printOut(cst.PREFIX_MSG_MOD + ': To configure module do'); Common.printOut(cst.PREFIX_MSG_MOD + ': $ pm2 conf <key> <value>'); return cb(null, dt); }); }); } } } function uninstallModule(CLI, module_name, cb) { var proc_path = p.join(cst.PM2_ROOT_PATH, 'node_modules', module_name); Configuration.unsetSync(MODULE_CONF_PREFIX + ':' + module_name); CLI.deleteModule(module_name, function(err, data) { if (err) { Common.printError(err); if (module_name != '.') { console.log(proc_path); shelljs.rm('-r', proc_path); } return cb(err); } if (module_name != '.') { shelljs.rm('-r', proc_path); } return cb(null, data); }); } function installLangModule(module_name, cb) { var node_module_path = path.join(__dirname, '../../..'); var install_instance = spawn(cst.IS_WINDOWS ? 'npm.cmd' : 'npm', [ 'install', module_name, '--prefix', node_module_path, '--loglevel=error' ],{ stdio : 'inherit', env: process.env, shell : true }); install_instance.on('close', function done() { cb(null); }); install_instance.on('error', function (err) { console.error(err.stack || err); }); }; /** * List modules on the old way */ var listModules = function() { var module_folder = p.join(cst.PM2_ROOT_PATH, 'node_modules'); var ret = []; shelljs.config.silent = true; var modules = shelljs.ls(module_folder); shelljs.config.silent = false; modules.forEach(function(module_name) { if (module_name.indexOf('pm2-') > -1) ret.push(module_name); }); return ret; }; /** * List modules based on internal database */ var listModulesV2 = Modularizer.listModules = function() { var config = Configuration.getSync(MODULE_CONF_PREFIX); if (!config) { var modules_already_installed = listModules(); modules_already_installed.forEach(function(module_name) { Configuration.setSync(MODULE_CONF_PREFIX + ':' + module_name, true); }); return modules_already_installed; } return Object.keys(config); }; Modularizer.getAdditionalConf = function(app_name) { if (!app_name) throw new Error('No app_name defined'); var module_conf = Configuration.getAllSync(); var additional_env = {}; if (!module_conf[app_name]) { additional_env = {}; additional_env[app_name] = {}; } else { additional_env = Common.clone(module_conf[app_name]); additional_env[app_name] = JSON.stringify(module_conf[app_name]); } return additional_env; }; Modularizer.launchAll = function(CLI, cb) { var module_folder = p.join(cst.PM2_ROOT_PATH, 'node_modules'); var modules = listModulesV2(); async.eachLimit(modules, 1, function(module, next) { var pmod = p.join(module_folder, module, cst.DEFAULT_MODULE_JSON); Common.printOut(cst.PREFIX_MSG_MOD + 'Starting module ' + module); startModule(CLI, { cmd : pmod, development_mode : false, proc_path : p.join(module_folder, module) }, function(err, dt) { if (err) console.error(err); return next(); }); }, function() { return cb ? cb(null) : false; }); }; Modularizer.install = function(CLI, module_name, cb) { Common.printOut(cst.PREFIX_MSG_MOD + 'Installing module ' + module_name); var canonic_module_name = Utility.packageNameToModuleName(module_name); if (module_name == 'typescript') { // Special dependency install installLangModule('typescript', function(e) { installLangModule('ts-node@latest', function(e) { Common.printOut(cst.PREFIX_MSG + chalk.bold.green('Typescript support enabled')); return cb(); }); }); return false; } if (module_name == 'livescript') { installLangModule('livescript', function(e) { Common.printOut(cst.PREFIX_MSG + chalk.bold.green('Livescript support enabled')); return cb(); }); return false; } if (module_name == 'coffeescript') { installLangModule('coffee-script', function(e) { Common.printOut(cst.PREFIX_MSG + chalk.bold.green('Coffeescript support enabled')); return cb(); }); return false; } if (moduleExist(canonic_module_name) === true) { /** * Update */ Common.printOut(cst.PREFIX_MSG_MOD + 'Module already installed. Updating.'); uninstallModule(CLI, canonic_module_name, function(err) { return installModule(CLI, module_name, cb); }); return false; } /** * Install */ installModule(CLI, module_name, cb); }; /** * Uninstall module */ Modularizer.uninstall = function(CLI, module_name, cb) { Common.printOut(cst.PREFIX_MSG_MOD + 'Uninstalling module ' + module_name); //if (moduleExist(module_name) === false && module_name != '.') { //Common.printError(cst.PREFIX_MSG_MOD_ERR + 'Module unknown.'); //return cb({msg:'Module unknown'}); //} if (module_name == 'all') { var modules = listModulesV2(); async.forEachLimit(modules, 1, function(module, next) { uninstallModule(CLI, module, next); }, cb); return false; } uninstallModule(CLI, module_name, cb); }; /** * Publish a module */ Modularizer.publish = function(cb) { var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); var semver = require('semver'); var package_file = p.join(process.cwd(), 'package.json'); var package_json = require(package_file); package_json.version = semver.inc(package_json.version, 'minor'); Common.printOut(cst.PREFIX_MSG_MOD + 'Incrementing module to: %s@%s', package_json.name, package_json.version); rl.question("Write & Publish? [Y/N]", function(answer) { if (answer != "Y") return cb(); fs.writeFile(package_file, JSON.stringify(package_json, null, 2), function(err, data) { if (err) return cb(err); Common.printOut(cst.PREFIX_MSG_MOD + 'Publishing module - %s@%s', package_json.name, package_json.version); shelljs.exec('npm publish', function(code) { Common.printOut(cst.PREFIX_MSG_MOD + 'Module - %s@%s successfully published', package_json.name, package_json.version); Common.printOut(cst.PREFIX_MSG_MOD + 'Pushing module on Git'); shelljs.exec('git add . ; git commit -m "' + package_json.version + '"; git push origin master', function(code) { Common.printOut(cst.PREFIX_MSG_MOD + 'Installable with pm2 install %s', package_json.name); return cb(null, package_json); }); }); }); }); }; Modularizer.generateSample = function(app_name, cb) { var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); function samplize(module_name) { var cmd1 = 'git clone https://github.com/pm2-hive/sample-module.git ' + module_name + '; cd ' + module_name + '; rm -rf .git'; var cmd2 = 'cd ' + module_name + ' ; sed -i "s:sample-module:'+ module_name +':g" package.json'; var cmd3 = 'cd ' + module_name + ' ; npm install'; Common.printOut(cst.PREFIX_MSG_MOD + 'Getting sample app'); shelljs.exec(cmd1, function(err) { if (err) Common.printError(cst.PREFIX_MSG_MOD_ERR + err.message); shelljs.exec(cmd2, function(err) { console.log(''); shelljs.exec(cmd3, function(err) { console.log(''); Common.printOut(cst.PREFIX_MSG_MOD + 'Module sample created in folder: ', path.join(process.cwd(), module_name)); console.log(''); Common.printOut('Start module in development mode:'); Common.printOut('$ cd ' + module_name + '/'); Common.printOut('$ pm2 install . '); console.log(''); Common.printOut('Module Log: '); Common.printOut('$ pm2 logs ' + module_name); console.log(''); Common.printOut('Uninstall module: '); Common.printOut('$ pm2 uninstall ' + module_name); console.log(''); Common.printOut('Force restart: '); Common.printOut('$ pm2 restart ' + module_name); return cb ? cb() : false; }); }); }); } if (app_name) return samplize(app_name); rl.question(cst.PREFIX_MSG_MOD + "Module name: ", function(module_name) { samplize(module_name); }); }; function isValidModule(conf) { var valid = true; if (!conf.apps) { Common.printError(cst.PREFIX_MSG_MOD_ERR + 'apps attribute indicating the script to launch is not defined in the package.json'); return false; } if (Array.isArray(conf.apps)) { conf.apps.forEach(function(app) { if (!app.script) valid = false; }); } else { if (!conf.apps.script) valid = false; } return valid; }; function moduleExist(module_name) { var modules = getModuleInstalled(); if (module_name.indexOf('/') > -1) module_name = module_name.split('/')[1]; return modules.indexOf(module_name) > -1 ? true : false; }; function getModuleInstalled() { shelljs.config.silent = true; var module_folder = p.join(cst.PM2_ROOT_PATH, 'node_modules'); var modules = shelljs.ls('-A', module_folder); shelljs.config.silent = false; return modules; }
27.819838
132
0.6249
52bd43459507d189fa4ffcf7c01f0b906abe57e3
460
js
JavaScript
src/reducers/sidebar.js
Kkknight-12/HT-DT-Project
8d750217bcce1d55bec3172898cb814f7c7922ac
[ "MIT" ]
null
null
null
src/reducers/sidebar.js
Kkknight-12/HT-DT-Project
8d750217bcce1d55bec3172898cb814f7c7922ac
[ "MIT" ]
null
null
null
src/reducers/sidebar.js
Kkknight-12/HT-DT-Project
8d750217bcce1d55bec3172898cb814f7c7922ac
[ "MIT" ]
null
null
null
const initialState = { sidebarShow: true, sidebarUnfoldable: false, } const sideBarReducer = (state = initialState, action) => { console.log(action) switch (action.type) { case 'setSideBar': // console.log('changeState', state) return { ...state, sidebarShow: action.payload } case 'setUnfoldable': return { ...state, sidebarUnfoldable: action.payload } default: return state } } export default sideBarReducer
23
60
0.665217
52be78c9fe1d4cee1f24e08db4d50010413daa7c
10,214
js
JavaScript
public/app.js
davideicardi/device-orientation
af3036ddabc0892f2dda9928e241b180372a6f15
[ "MIT" ]
1
2016-06-29T08:03:42.000Z
2016-06-29T08:03:42.000Z
public/app.js
davideicardi/device-orientation
af3036ddabc0892f2dda9928e241b180372a6f15
[ "MIT" ]
null
null
null
public/app.js
davideicardi/device-orientation
af3036ddabc0892f2dda9928e241b180372a6f15
[ "MIT" ]
null
null
null
// just to keep the IDE happy var io = io || null; var angular = angular || null; var THREE = THREE || null; var app = angular.module('deviceOrientationApp', [ 'ngRoute', 'monospaced.qrcode' ]); app.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/', { templateUrl: 'partials/_home.html', controller: 'HomeCtrl' }). when('/rooms/:roomId', { templateUrl: 'partials/_room.html', controller: 'RoomCtrl' }). when('/remote/:roomId', { templateUrl: 'partials/_remote.html', controller: 'RemoteCtrl' }). otherwise({ redirectTo: '/' }); } ]); // socket.io wrapper function socketIOConnection(namespace) { this.namespace = namespace || '/'; this.socket = io(namespace, {multiplex : false}); // multiplex=false is needed because I close and reopen the connection based on the angular navigation this.disconnect = function() { this.socket.disconnect(); this.socket = null; }; this.emit = function(eventId, data) { this.socket.emit(eventId, data); }; this.on = function(eventId, listener) { this.socket.on(eventId, listener); }; } app.value('socketIOService', { connect : function(namespace){ return new socketIOConnection(namespace); } }); app.controller('HomeCtrl', ['$scope', '$routeParams', '$location', '$http', function($scope, $routeParams, $location, $http) { $scope.reservedRooms = null; $http.get('/api/rooms'). success(function(data, status, headers, config) { $scope.reservedRooms = data.count; }); $scope.startRoom = function() { $http.put('/api/reserveRoom'). success(function(data, status, headers, config) { $location.path('/rooms/' + data.roomId); }); }; } ]); app.controller('RoomCtrl', ['$scope', '$routeParams', 'socketIOService', function($scope, $routeParams, socketIOService) { $scope.roomId = $routeParams.roomId; $scope.remote = null; $scope.device = { orientation : { gamma: 0, beta: 0, alpha: 0, isFaceDown:false } }; function loadModel() { var onProgress = function ( xhr ) { if ( xhr.lengthComputable ) { var percentComplete = xhr.loaded / xhr.total * 100; console.log( Math.round(percentComplete, 2) + '% downloaded' ); } }; var onError = function ( xhr ) { }; var loader = new THREE.OBJMTLLoader(); loader.load( '/models/s4.obj', '/models/s4.mtl', function ( object ) { $scope.device3DModel = object; $scope.$digest(); }, onProgress, onError ); } loadModel(); function onRemoteConnected(data) { $scope.remote = data; $scope.$digest(); } function onRemoteDisconnected() { $scope.remote = null; $scope.$digest(); } function onDeviceOrientation(orientation){ var isFaceDown = Math.abs(orientation.beta) >= 90; // show debug info $scope.device.orientation = orientation; $scope.device.orientation.isFaceDown = isFaceDown; $scope.$digest(); // rotate 3D model applying a correction when the device is face down var x = isFaceDown ? 180 + orientation.beta : orientation.beta; // beta var y = isFaceDown ? 180 + orientation.alpha : orientation.alpha; // alpha var z = isFaceDown ? 180 + orientation.gamma : orientation.gamma; // gamma if ($scope.device3DModel) { $scope.device3DModel.rotation.x = THREE.Math.degToRad(x); $scope.device3DModel.rotation.y = THREE.Math.degToRad(-y); // fix rotation, not sure why... $scope.device3DModel.rotation.z = THREE.Math.degToRad(-z); // fix rotation, not sure why... } } var socket = socketIOService.connect(); socket.on('connect', function(){ socket.emit('initRoom', { roomId: $scope.roomId }); }); socket.on('remote-connected', onRemoteConnected); socket.on('remote-disconnected', onRemoteDisconnected); socket.on('remote-orientation', onDeviceOrientation); $scope.$on("$destroy", function() { //socketIOService.removeListener('test-orientation', onDeviceOrientation); socket.disconnect(); }); } ]); app.controller('RemoteCtrl', ['$scope', '$routeParams', '$window', 'socketIOService', function($scope, $routeParams, $window, socketIOService) { $scope.roomId = $routeParams.roomId; $scope.threshold = 1.0; $scope.connected = false; $scope.errors = []; var lastOrientation = { gamma: 0, beta: 0, alpha: 0 }; var initialAlpha = null; var socket = socketIOService.connect(); socket.on('connect', function(){ socket.emit('initRemote', { roomId: $scope.roomId }); }); function onRoomConnected(){ $scope.connected = true; $scope.$digest(); } function onRoomDisconnected(){ $scope.connected = false; $scope.$digest(); } function onRoomError(msg){ $scope.errors.push(msg); $scope.$digest(); } socket.on('room-connected', onRoomConnected); socket.on('room-disconnected', onRoomDisconnected); socket.on('room-error', onRoomError); function isChanged(orientation) { var threshold = $scope.threshold; var c = false; if (Math.abs(lastOrientation.gamma - orientation.gamma) > threshold || Math.abs(lastOrientation.beta - orientation.beta) > threshold || Math.abs(lastOrientation.alpha - orientation.alpha) > threshold) { c = true; lastOrientation = orientation; } return c; } function onDeviceOrientation(eventData) { if (!initialAlpha) { initialAlpha = eventData.alpha; } var orientation = { // gamma is the left-to-right tilt in degrees, where right is positive. // Represents the motion of the device around the y axis, // represented in degrees with values ranging from -90 to 90. This represents a left to right motion of the device. gamma: eventData.gamma, // beta is the front-to-back tilt in degrees, where front is positive. // Represents the motion of the device around the x axis, // represented in degrees with values ranging from -180 to 180. This represents a front to back motion of the device. beta: eventData.beta, // alpha is the compass direction the device is facing in degrees. // Represents the motion of the device around the z axis, // represented in degrees with values ranging from 0 to 360. alpha: eventData.alpha }; // fix the alpha so that it correspond to the difference between the current degrees and the initial degrees // otherwise it usually represents just the orientation relative to the NORTH orientation.alpha = initialAlpha - orientation.alpha; if (isChanged(orientation)) { socket.emit('remote-orientation', orientation); } } if ($window.DeviceOrientationEvent) { $window.addEventListener('deviceorientation', onDeviceOrientation, false); } else { $scope.errors.push("deviceorientation not supported on your device or browser. Sorry."); } $scope.resetAlpha = function(){ initialAlpha = null; }; $scope.$on("$destroy", function() { $window.removeEventListener('deviceorientation', onDeviceOrientation, false); socket.disconnect(); }); } ]); app.directive('diThreeJsViewer', [function() { function createThreeJsCanvas(parentElement, object) { var width = 400; var height = 400; var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(35, width / height, 2.109, 213.014); var renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); renderer.setSize(width, height); renderer.setClearColor( 0xffffff, 1); parentElement.append(renderer.domElement); camera.position.x = 0; camera.position.y = 0; camera.position.z = 20; //camera.up = new THREE.Vector3(0, 0, 1); camera.lookAt(new THREE.Vector3(0.000, 0.000, 0.000)); // look at the center var light = new THREE.PointLight(0x404040, 2); light.position.set(20, 20, 0); scene.add(light); light = new THREE.PointLight(0x404040, 2); light.position.set(20, 0, 20); scene.add(light); light = new THREE.PointLight(0x404040, 2); light.position.set(0, 20, 20); scene.add(light); light = new THREE.AmbientLight(0x404040); scene.add(light); // add object scene.add(object); var render = function() { requestAnimationFrame(render); //model.rotation.y += 0.01; renderer.render(scene, camera); }; render(); } function link(scope, element, attrs) { scope.$watch("threeJsObject", function(){ if (scope.threeJsObject) { createThreeJsCanvas(element, scope.threeJsObject); } }, false); } return { restrict: 'E', scope: { threeJsObject: '=' }, link: link }; }]);
32.018809
157
0.556883
52bf0ab46b61b3e873aeea77db2b4a18b83a1260
1,721
js
JavaScript
assets/bower_components/ckeditor/plugins/panelbutton/plugin-MazHep.js
dicky54putra/ycpt
f2c23ad2f4021ab716a597e138144312d6352536
[ "MIT" ]
null
null
null
assets/bower_components/ckeditor/plugins/panelbutton/plugin-MazHep.js
dicky54putra/ycpt
f2c23ad2f4021ab716a597e138144312d6352536
[ "MIT" ]
null
null
null
assets/bower_components/ckeditor/plugins/panelbutton/plugin-MazHep.js
dicky54putra/ycpt
f2c23ad2f4021ab716a597e138144312d6352536
[ "MIT" ]
1
2020-12-17T11:39:37.000Z
2020-12-17T11:39:37.000Z
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.add("panelbutton",{requires:"button",onLoad:function(){function e(c){var a=this._;a.state!=CKEDITOR.TRISTATE_DISABLED&&(this.createPanel(c),a.on?a.panel.hide():a.panel.showBlock(this._.id,this.document.getById(this._.id),4))}CKEDITOR.ui.panelButton=CKEDITOR.tools.createClass({base:CKEDITOR.ui.button,$:function(c){var a=c.panel||{};delete c.panel;this.base(c);this.document=a.parent&&a.parent.getDocument()||CKEDITOR.document;a.block={attributes:a.attributes};this.hasArrow=a.toolbarRelated= !0;this.click=e;this._={panelDefinition:a}},statics:{handler:{create:function(c){return new CKEDITOR.ui.panelButton(c)}}},proto:{createPanel:function(c){var a=this._;if(!a.panel){var f=this._.panelDefinition,e=this._.panelDefinition.block,g=f.parent||CKEDITOR.document.getBody(),d=this._.panel=new CKEDITOR.ui.floatPanel(c,g,f),f=d.addBlock(a.id,e),b=this;d.onShow=function(){b.className&&this.element.addClass(b.className+"_panel");b.setState(CKEDITOR.TRISTATE_ON);a.on=1;b.editorFocus&&c.focus();if(b.onOpen)b.onOpen()}; d.onHide=function(d){b.className&&this.element.getFirst().removeClass(b.className+"_panel");b.setState(b.modes&&b.modes[c.mode]?CKEDITOR.TRISTATE_OFF:CKEDITOR.TRISTATE_DISABLED);a.on=0;if(!d&&b.onClose)b.onClose()};d.onEscape=function(){d.hide(1);b.document.getById(a.id).focus()};if(this.onBlock)this.onBlock(d,f);f.onHide=function(){a.on=0;b.setState(CKEDITOR.TRISTATE_OFF)}}}}})},beforeInit:function(e){e.ui.addHandler(CKEDITOR.UI_PANELBUTTON,CKEDITOR.ui.panelButton.handler)}}); CKEDITOR.UI_PANELBUTTON="panelbutton";
215.125
525
0.757118
52c01ddf5d59fdce0ded15601977caf2cc0ea2c9
550
js
JavaScript
lib/elements/Stepper/Stepper.stories.js
nadalfederer/react-shapebase
5a5821c7c36d5f588371bd2e721d982604d7fa56
[ "MIT" ]
10
2018-02-24T13:01:47.000Z
2018-09-14T10:54:53.000Z
lib/elements/Stepper/Stepper.stories.js
nadalfederer/react-shapebase
5a5821c7c36d5f588371bd2e721d982604d7fa56
[ "MIT" ]
29
2018-02-24T12:32:17.000Z
2018-06-24T15:14:12.000Z
lib/elements/Stepper/Stepper.stories.js
nadalfederer/react-shapebase
5a5821c7c36d5f588371bd2e721d982604d7fa56
[ "MIT" ]
7
2018-03-04T04:09:29.000Z
2018-04-16T15:11:50.000Z
import React from 'react'; import { storiesOf, action } from '@storybook/react'; import Stepper from './Stepper'; import Grid from '../Grid/Grid'; storiesOf('Stepper', module) .add('Stepper', () => ( <Grid> <Stepper activeStep={2}> <Stepper.Step> <p> Yo One </p> </Stepper.Step> <Stepper.Step> <p> Yo Two </p> </Stepper.Step> <Stepper.Step> <p> Yo Three </p> </Stepper.Step> </Stepper> </Grid> ));
23.913043
53
0.470909
52c048dbb9d13b64fcf583a97426a3d2e04fcb55
350
js
JavaScript
src/index.js
whinc/xConsole
36134793fc1f3ae8b3e4600a4ac7c6db10ed0da9
[ "MIT" ]
null
null
null
src/index.js
whinc/xConsole
36134793fc1f3ae8b3e4600a4ac7c6db10ed0da9
[ "MIT" ]
null
null
null
src/index.js
whinc/xConsole
36134793fc1f3ae8b3e4600a4ac7c6db10ed0da9
[ "MIT" ]
null
null
null
import React from 'react' import ReactDOM from 'react-dom' import xConsole from './core/XConsole' import 'font-awesome/css/font-awesome.min.css' import './index.css' if (!window.xConsole) { window.xConsole = xConsole } if (!window.React) { window.React = React } if (!window.ReactDOM) { window.ReactDOM = ReactDOM } export default xConsole
17.5
46
0.722857
52c0da839b30954ddc12217744b7010bf01d46c5
455
js
JavaScript
packages/query-graphql/dist/src/resolvers/federation/federation.resolver.js
Yiin/nestjs-query
498f2582ccf5e18495757127957b9ca7c6fe548d
[ "MIT" ]
null
null
null
packages/query-graphql/dist/src/resolvers/federation/federation.resolver.js
Yiin/nestjs-query
498f2582ccf5e18495757127957b9ca7c6fe548d
[ "MIT" ]
null
null
null
packages/query-graphql/dist/src/resolvers/federation/federation.resolver.js
Yiin/nestjs-query
498f2582ccf5e18495757127957b9ca7c6fe548d
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FederationResolver = void 0; const relations_1 = require("../relations"); const decorators_1 = require("../../decorators"); const FederationResolver = (DTOClass, opts = {}) => (0, relations_1.ReadRelationsResolver)(DTOClass, (0, decorators_1.getRelations)(DTOClass, opts)); exports.FederationResolver = FederationResolver; //# sourceMappingURL=federation.resolver.js.map
56.875
149
0.76044
52c0efd196b9221c034ac6b7f4cd4f7978b5f829
209
js
JavaScript
lib/controllers/index.js
chrisharrington/twitter-followers-server
e3fc6a5c168a9af922bf41244ea81ec19bd63a71
[ "MIT" ]
1
2015-12-15T19:48:36.000Z
2015-12-15T19:48:36.000Z
lib/controllers/index.js
chrisharrington/twitter-followers-server
e3fc6a5c168a9af922bf41244ea81ec19bd63a71
[ "MIT" ]
null
null
null
lib/controllers/index.js
chrisharrington/twitter-followers-server
e3fc6a5c168a9af922bf41244ea81ec19bd63a71
[ "MIT" ]
null
null
null
"use strict"; var _ = require("lodash"); module.exports = function(app) { _.each([ "./sign-in", "./user-info", "./favourites", "./log" ], function(controller) { require(controller)(app); }); };
13.933333
32
0.574163
52c125491808599332455b19ca4d51acc18b20ce
2,532
js
JavaScript
eth/tests/sloth-verifiable-delay.js
circle-free/verifiable-delay-functions
813c00ccee86ebfb270feeee8d1e0cd8a843837f
[ "MIT" ]
3
2021-02-24T22:06:48.000Z
2022-01-22T19:40:52.000Z
eth/tests/sloth-verifiable-delay.js
circle-free/verifiable-delay-functions
813c00ccee86ebfb270feeee8d1e0cd8a843837f
[ "MIT" ]
null
null
null
eth/tests/sloth-verifiable-delay.js
circle-free/verifiable-delay-functions
813c00ccee86ebfb270feeee8d1e0cd8a843837f
[ "MIT" ]
null
null
null
const chai = require('chai'); chai.use(require('chai-as-promised')); const { expect } = chai; const Sloth_Test_Harness = artifacts.require('Sloth_Test_Harness'); const fixtures = require('./fixtures/vdfs.json'); let contractInstance = null; contract('Test Harness', async (accounts) => { before(async () => { contractInstance = await Sloth_Test_Harness.deployed(); }); afterEach(() => contractInstance.set('0')); describe('Stateful', () => { fixtures.stateful.compute.forEach(({ x, p, t, y, computeGasUsed }) => { it('should compute sloth modular root y and store it.', async () => { const { receipt } = await contractInstance.compute_and_store(x, p, t); expect((await contractInstance.y()).toString(10)).to.equal(y); expect(receipt.gasUsed.toString()).to.equal(computeGasUsed); }); }); fixtures.stateful.verify.forEach(({ x, p, t, y, verifyGasUsed }) => { it('should verify a 10000-t vdf and store bool.', async () => { await contractInstance.set(y); const { receipt } = await contractInstance.verify_and_store(x, p, t); expect(await contractInstance.valid()).to.be.true; expect(receipt.gasUsed.toString()).to.equal(verifyGasUsed); }); }); }); describe('Stateless', () => { fixtures.stateless.compute.forEach(({ x, p, t, y }) => { it('should compute sloth modular root y.', async () => { expect((await contractInstance.compute(x, p, t)).toString(10)).to.equal(y); }); }); fixtures.stateless.verify.forEach(({ x, p, t, y, valid }) => { it('should verify sloth modular root y.', async () => { expect(await contractInstance.verify(y, x, p, t)).to.equal(valid); }); }); }); describe('Intermediated Stateless', () => { fixtures.intermediates.compute.forEach(({ x, p, t, size, y }) => { it('should compute intermediate sloth modular roots y[].', async () => { let seed = x; for (let i = 0; i < size; i++) { expect((await contractInstance.compute(seed, p, t / size)).toString(10)).to.equal(y[i]); seed = y[i]; } }); }); fixtures.intermediates.verify.forEach(({ x, p, t, size, y, valid }) => { it('should verify intermediate sloth modular roots y[].', async () => { let seed = x; for (let i = 0; i < size; i++) { expect(await contractInstance.verify(y[i], seed, p, t / size)).to.equal(valid); seed = y[i]; } }); }); }); });
33.76
98
0.581359
52c1d1c59a601831f463745be4d64f30a19fec80
4,657
js
JavaScript
dist/es/plugins/backup/file-util.js
SuperKirik/rxdb
0199fc0e6bfd67a94863c588d228162c8531d355
[ "Apache-2.0" ]
null
null
null
dist/es/plugins/backup/file-util.js
SuperKirik/rxdb
0199fc0e6bfd67a94863c588d228162c8531d355
[ "Apache-2.0" ]
null
null
null
dist/es/plugins/backup/file-util.js
SuperKirik/rxdb
0199fc0e6bfd67a94863c588d228162c8531d355
[ "Apache-2.0" ]
null
null
null
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _regeneratorRuntime from "@babel/runtime/regenerator"; import * as fs from 'fs'; import * as path from 'path'; import { now } from '../../util'; /** * ensure that the given folder exists */ export function ensureFolderExists(folderPath) { if (!fs.existsSync(folderPath)) { fs.mkdirSync(folderPath, { recursive: true }); } } /** * deletes and recreates the folder */ export function clearFolder(folderPath) { deleteFolder(folderPath); ensureFolderExists(folderPath); } export function deleteFolder(folderPath) { // only remove if exists to not raise warning if (fs.existsSync(folderPath)) { fs.rmdirSync(folderPath, { recursive: true }); } } export function prepareFolders(database, options) { ensureFolderExists(options.directory); var metaLoc = metaFileLocation(options); if (!fs.existsSync(metaLoc)) { var currentTime = now(); var metaData = { createdAt: currentTime, updatedAt: currentTime, collectionStates: {} }; fs.writeFileSync(metaLoc, JSON.stringify(metaData), 'utf-8'); } Object.keys(database.collections).forEach(function (collectionName) { ensureFolderExists(path.join(options.directory, collectionName)); }); } export function writeToFile(_x, _x2) { return _writeToFile.apply(this, arguments); } function _writeToFile() { _writeToFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(location, data) { return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", new Promise(function (res, rej) { fs.writeFile(location, data, 'utf-8', function (err) { if (err) { rej(err); } else { res(); } }); })); case 1: case "end": return _context.stop(); } } }, _callee); })); return _writeToFile.apply(this, arguments); } export function writeJsonToFile(_x3, _x4) { return _writeJsonToFile.apply(this, arguments); } function _writeJsonToFile() { _writeJsonToFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(location, data) { return _regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: return _context2.abrupt("return", writeToFile(location, JSON.stringify(data))); case 1: case "end": return _context2.stop(); } } }, _callee2); })); return _writeJsonToFile.apply(this, arguments); } export function metaFileLocation(options) { return path.join(options.directory, 'backup_meta.json'); } export function getMeta(_x5) { return _getMeta.apply(this, arguments); } function _getMeta() { _getMeta = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(options) { var loc; return _regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: loc = metaFileLocation(options); return _context3.abrupt("return", new Promise(function (res, rej) { fs.readFile(loc, 'utf-8', function (err, data) { if (err) { rej(err); } else { var metaContent = JSON.parse(data); res(metaContent); } }); })); case 2: case "end": return _context3.stop(); } } }, _callee3); })); return _getMeta.apply(this, arguments); } export function setMeta(_x6, _x7) { return _setMeta.apply(this, arguments); } function _setMeta() { _setMeta = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(options, meta) { var loc; return _regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: loc = metaFileLocation(options); return _context4.abrupt("return", writeJsonToFile(loc, meta)); case 2: case "end": return _context4.stop(); } } }, _callee4); })); return _setMeta.apply(this, arguments); } export function documentFolder(options, docId) { return path.join(options.directory, docId); } //# sourceMappingURL=file-util.js.map
28.054217
113
0.616921
52c2e17ee46f4eee259c7431f2f3bf7d418e9185
1,520
js
JavaScript
src/vigenere-cipher.js
Helen-JS/basic-js
bab03ce2ef20b9d77d13687e9f3356cc964e1e39
[ "MIT" ]
null
null
null
src/vigenere-cipher.js
Helen-JS/basic-js
bab03ce2ef20b9d77d13687e9f3356cc964e1e39
[ "MIT" ]
null
null
null
src/vigenere-cipher.js
Helen-JS/basic-js
bab03ce2ef20b9d77d13687e9f3356cc964e1e39
[ "MIT" ]
null
null
null
import { NotImplementedError } from '../extensions/index.js'; /** * Implement class VigenereCipheringMachine that allows us to create * direct and reverse ciphering machines according to task description * * @example * * const directMachine = new VigenereCipheringMachine(); * * const reverseMachine = new VigenereCipheringMachine(false); * * directMachine.encrypt('attack at dawn!', 'alphonse') => 'AEIHQX SX DLLU!' * * directMachine.decrypt('AEIHQX SX DLLU!', 'alphonse') => 'ATTACK AT DAWN!' * * reverseMachine.encrypt('attack at dawn!', 'alphonse') => '!ULLD XS XQHIEA' * * reverseMachine.decrypt('AEIHQX SX DLLU!', 'alphonse') => '!NWAD TA KCATTA' * */ export default class VigenereCipheringMachine { encrypt(message, key) { let alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.!?,:;'/ "; let encryptWord = ""; for (let i = 0;i < message.length;i++) { encryptWord += alphabet.charAt((alphabet.indexOf(message.charAt(i)) + alphabet.indexOf(key.charAt(i % key.length))) % alphabet.length); } return encryptWord; } decrypt(encryptedMessage, key) { let alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.!?,:;'/ "; let decryptWord = ""; for (let i = 0;i < encryptedMessage.length;i++) { decryptWord += alphabet.charAt(((alphabet.indexOf(encryptedMessage.charAt(i)) + alphabet.length) - alphabet.indexOf(key.charAt(i % key.length))) % alphabet.length); } return decryptWord; } }
34.545455
170
0.691447
52c35af58cf18b7c13b1c27170445606cc6241cd
1,592
js
JavaScript
lib/loaders/FileMeta.js
arjunvegda/preloader
13f63b2bd8ced5aa58fe06e83a5d5ff08840699f
[ "MIT" ]
78
2015-10-01T01:28:13.000Z
2022-01-26T21:31:33.000Z
lib/loaders/FileMeta.js
arjunvegda/preloader
13f63b2bd8ced5aa58fe06e83a5d5ff08840699f
[ "MIT" ]
13
2016-07-04T18:35:22.000Z
2020-01-02T09:19:18.000Z
lib/loaders/FileMeta.js
arjunvegda/preloader
13f63b2bd8ced5aa58fe06e83a5d5ff08840699f
[ "MIT" ]
20
2015-09-14T21:07:06.000Z
2022-01-14T22:56:34.000Z
var parseHTTPHeader = require('../util/parseHTTPHeader'); /** * FileMeta is a class which will hold file meta data. Each LoaderBase contains a FileMeta object * that you can use to query. * * @class FileMeta * @constructor * @param {String} header HTTP Header sent when loading this file */ var FileMeta = function (header) { /** * This property is the mimetype for the file * * @property mime * @type {String} */ this.mime = null; /** * This is the file size in bytes * * @type {Number} */ this.size = null; /** * This is a Date object which represents the last time this file was modified * * @type {Date} */ this.lastModified = null; /** * This is the HTTP header as an Object for the file. * * @type {Object} */ this.httpHeader = null; if (header) this.setFromHTTPHeader(header); }; FileMeta.prototype = { /** * This function will be called in the constructor of FileMeta. It will parse the HTTP * headers returned by a server and save useful information for development. * * @method setFromHTTPHeader * @param {String} header HTTP header returned by the server */ setFromHTTPHeader: function (header) { this.httpHeader = parseHTTPHeader(header); if (this.httpHeader[ 'content-length' ]) this.size = this.httpHeader[ 'content-length' ]; if (this.httpHeader[ 'content-type' ]) this.mime = this.httpHeader[ 'content-type' ]; if (this.httpHeader[ 'last-modified' ]) this.lastModified = new Date(this.httpHeader[ 'last-modified' ]); } }; module.exports = FileMeta;
24.492308
109
0.660804
52c3ade0cc7d81dd3f1c5dedc9ecdfbbea088b2b
913
js
JavaScript
src/components/charts/Tooltip/index.js
thiagokpelo/loft-science
ff105f5142518d845ed26210f45ad7fa928966f3
[ "MIT" ]
9
2020-04-22T15:02:08.000Z
2021-07-31T21:35:15.000Z
src/components/charts/Tooltip/index.js
loft-br/covid-19
8f8b69ecfa153d071a1136a24b65c57b52a1150b
[ "MIT" ]
7
2020-09-13T16:36:58.000Z
2022-02-27T03:23:27.000Z
src/components/charts/Tooltip/index.js
loft-br/covid-19
8f8b69ecfa153d071a1136a24b65c57b52a1150b
[ "MIT" ]
4
2020-04-27T10:27:58.000Z
2020-10-14T21:57:51.000Z
import React from 'react'; import { Typography, Paper } from '@material-ui/core'; import Rt from 'components/Rt'; import Thumb from 'components/Thumb'; import useStyles from './Tooltip.styles'; const RED = '#f9e7e7'; const GREEN = '#c3f5c3'; const Tooltip = ({ children, data = {} }) => { const classes = useStyles(); const getColor = (number) => (number < 1 ? GREEN : RED); return ( <Paper variant="outlined" elevation={3} className={classes.root}> {children} <br /> <Typography variant="caption"> <Rt />: {data?.formattedY || data?.y} </Typography> <br /> <Typography variant="caption"> High: <Thumb color={getColor(data?.high)} /> {data?.high} </Typography> <br /> <Typography variant="caption"> Low: <Thumb color={getColor(data?.low)} /> {data?.low} </Typography> </Paper> ); }; export default Tooltip;
25.361111
69
0.596933
52c3d9f8e4112cb2cb77f111284116d0c3a65ef8
2,525
js
JavaScript
structures/ThreadMember.js
Cannicide/node-elisif
8b55a2d5ae06d5108946a082605cdfcb7277272b
[ "MIT" ]
7
2021-02-25T15:01:11.000Z
2022-03-31T18:13:47.000Z
structures/ThreadMember.js
Cannicide/node-elisif
8b55a2d5ae06d5108946a082605cdfcb7277272b
[ "MIT" ]
null
null
null
structures/ThreadMember.js
Cannicide/node-elisif
8b55a2d5ae06d5108946a082605cdfcb7277272b
[ "MIT" ]
null
null
null
// Represents a Thread Member // Based on unstable discord.js v13 code, but adapted to work with discord.js v12 // Note: though Elisif supports managing and manipulating threads, it does not support events in threads due to API version differences. const { Base, BitField } = require("discord.js"); /** * Represents flags for a ThreadMember */ class MemberFlags extends BitField { constructor(bits) { super(bits); this.FLAGS = {}; } } /** * Represents a Member for a Thread. * @extends {Base} */ class ThreadMember extends Base { /** * @param {ThreadChannel} thread The thread that this member is associated with * @param {APIThreadMember} data The data for the thread member */ constructor(thread, data) { super(thread.client); /** * The thread that this member is a part of * @type {ThreadChannel} */ this.thread = thread; /** * The timestamp the member last joined the thread at * @type {?number} */ this.joinedTimestamp = null; /** * The id of the thread member * @type {Snowflake} */ this.id = data.user_id; this._patch(data); } _patch(data) { this.joinedTimestamp = new Date(data.join_timestamp).getTime(); /** * The flags for this thread member * @type {ThreadMemberFlags} */ this.flags = new MemberFlags(data.flags).freeze(); } /** * The guild member associated with this thread member * @type {?GuildMember} * @readonly */ get guildMember() { return this.thread.guild.members.resolve(this.id); } /** * The last time this member joined the thread * @type {?Date} * @readonly */ get joinedAt() { return this.joinedTimestamp ? new Date(this.joinedTimestamp) : null; } /** * The user associated with this thread member * @type {?User} * @readonly */ get user() { return this.client.users.resolve(this.id); } /** * Whether the client user can manage this thread member * @type {boolean} * @readonly */ get manageable() { return !this.thread.archived && this.thread.editable; } /** * Removes this member from the thread. * @param {string} [reason] Reason for removing the member * @returns {ThreadMember} */ remove(reason) { return this.thread.members.remove(this.id, reason).then(() => this); } } module.exports = ThreadMember; /** * @external APIThreadMember * @see {@link https://discord.com/developers/docs/resources/channel#thread-member-object} */
22.747748
136
0.640792
52c47369630952cc9e0d6d818b264e353aee119e
3,690
js
JavaScript
test/test.objects.js
ellipticaljs/Object.observe
6ad3b5604525ad12336ea748fbc35d12c87fe100
[ "Unlicense" ]
93
2015-01-07T07:30:51.000Z
2019-04-29T15:09:08.000Z
test/test.objects.js
ellipticaljs/Object.observe
6ad3b5604525ad12336ea748fbc35d12c87fe100
[ "Unlicense" ]
5
2015-01-02T20:30:22.000Z
2015-11-30T22:43:05.000Z
test/test.objects.js
ellipticaljs/Object.observe
6ad3b5604525ad12336ea748fbc35d12c87fe100
[ "Unlicense" ]
19
2015-01-03T16:38:36.000Z
2019-03-24T08:38:42.000Z
'use strict'; describe('single', function() { beforeEach(function() { sinon.spy(Object, 'observe'); sinon.spy(Object, 'unobserve'); }); afterEach(function() { Object.observe.restore(); Object.unobserve.restore(); }); it('should call the handler when an object property is added', function(done) { var subject = {}, handler = sinon.stub(); Object.observe(subject, handler); subject.foobar = 123; setTimeout(function() { sinon.assert.calledOnce(handler); sinon.assert.calledWithMatch(handler, numberOfChangesMatching(1)); sinon.assert.calledWithMatch(handler, aChangeMatching('add', 'foobar', 123)); done(); }, 100); }); it('should not call the handler when an object property is added to the prototype', function(done) { var subject = new Subject(), handler = sinon.stub(); function Subject() {} Object.observe(subject, handler); Subject.prototype.foobar = 123; setTimeout(function() { assert.property(subject, 'foobar'); assert.propertyVal(subject, 'foobar', 123); sinon.assert.notCalled(handler); done(); }, 100); }); it('should call the handler when an object property is updated', function(done) { var subject = {}, handler = sinon.stub(); subject.foo = 'bar'; Object.observe(subject, handler); subject.foo = 'barbar'; setTimeout(function() { sinon.assert.calledOnce(handler); sinon.assert.calledWithMatch(handler, numberOfChangesMatching(1)); sinon.assert.calledWithMatch(handler, aChangeMatching('update', 'foo', 'barbar', 'bar')); done(); }, 100); }); it('should not call the handler when an object property is updated on the prototype', function(done) { var subject = new Subject(), handler = sinon.stub(); function Subject() {} Subject.prototype.foo = 'bar'; assert.property(subject, 'foo'); assert.propertyVal(subject, 'foo', 'bar'); Object.observe(subject, handler); Subject.prototype.foo = 'barbar'; setTimeout(function() { assert.property(subject, 'foo'); assert.propertyVal(subject, 'foo', 'barbar'); sinon.assert.notCalled(handler); done(); }, 100); }); it('should call the handler when an object property is deleted', function(done) { var subject = {}, handler = sinon.stub(); subject.foo = undefined; Object.observe(subject, handler); delete subject.foo; setTimeout(function() { sinon.assert.calledOnce(handler); sinon.assert.calledWithMatch(handler, numberOfChangesMatching(1)); sinon.assert.calledWithMatch(handler, aChangeMatching('delete', 'foo', undefined, undefined)); done(); }, 100); }); it('should not call the handler when an object property is deleted on the prototype', function(done) { var subject = new Subject(), handler = sinon.stub(); function Subject() {} Subject.prototype.foo = 123; assert.property(subject, 'foo'); assert.propertyVal(subject, 'foo', 123); Object.observe(subject, handler); delete Subject.prototype.foo; setTimeout(function() { assert.notProperty(subject, 'foo'); sinon.assert.notCalled(handler); done(); }, 100); }); });
26.934307
106
0.571274
52c6e0c9f2f654fe4b4e6b6bf4de9166a17ad690
1,965
js
JavaScript
src/components/NavigationBar/index.js
antonyoneill/nhs-virtual-visit
f60fd2cd62180f4553f6baf47bf64f74d96eb6fd
[ "MIT" ]
null
null
null
src/components/NavigationBar/index.js
antonyoneill/nhs-virtual-visit
f60fd2cd62180f4553f6baf47bf64f74d96eb6fd
[ "MIT" ]
null
null
null
src/components/NavigationBar/index.js
antonyoneill/nhs-virtual-visit
f60fd2cd62180f4553f6baf47bf64f74d96eb6fd
[ "MIT" ]
null
null
null
import React from "react"; import Link from "next/link"; const NavigationBar = ({ links, testId }) => ( <nav className="nhsuk-header__navigation" id="header-navigation" role="navigation" aria-label="Primary navigation" aria-labelledby="label-navigation" data-testid={testId} > <div className="nhsuk-width-container"> <p className="nhsuk-header__navigation-title"> <span id="label-navigation">Menu</span> <button className="nhsuk-header__navigation-close" id="close-menu"> <svg className="nhsuk-icon nhsuk-icon__close" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true" focusable="false" > <path d="M13.41 12l5.3-5.29a1 1 0 1 0-1.42-1.42L12 10.59l-5.29-5.3a1 1 0 0 0-1.42 1.42l5.3 5.29-5.3 5.29a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l5.29-5.3 5.29 5.3a1 1 0 0 0 1.42 0 1 1 0 0 0 0-1.42z"></path> </svg> <span className="nhsuk-u-visually-hidden">Close menu</span> </button> </p> <ul className="nhsuk-header__navigation-list"> {links.map((link) => ( <li className="nhsuk-header__navigation-item" key={link.text}> <Link href={link.href}> <a className="nhsuk-header__navigation-link" onClick={link?.onClick} > {link.text} <svg className="nhsuk-icon nhsuk-icon__chevron-right" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true" > <path d="M15.5 12a1 1 0 0 1-.29.71l-5 5a1 1 0 0 1-1.42-1.42l4.3-4.29-4.3-4.29a1 1 0 0 1 1.42-1.42l5 5a1 1 0 0 1 .29.71z"></path> </svg> </a> </Link> </li> ))} </ul> </div> </nav> ); export default NavigationBar;
35.089286
212
0.5257
52c88c53495082155a202015f712bcbe968c1338
3,566
js
JavaScript
routes/routes.js
fieldlinguist/AuthenticationWebService
5e4df6defcb7e8650a5d1ef275704a8ba6fd7890
[ "MIT" ]
null
null
null
routes/routes.js
fieldlinguist/AuthenticationWebService
5e4df6defcb7e8650a5d1ef275704a8ba6fd7890
[ "MIT" ]
null
null
null
routes/routes.js
fieldlinguist/AuthenticationWebService
5e4df6defcb7e8650a5d1ef275704a8ba6fd7890
[ "MIT" ]
null
null
null
/* Load modules provided by $ npm install, see package.json for details */ var swagger = require('swagger-node-express'); var config = require('config'); /* Load modules provided by this codebase */ var userRoutes = require('./user'); var authenticationRoutes = require('./authentication'); var oauthRoutes = require('./oauth2'); var corporaRoutes = require('./corpora'); var errorHandler = require('../middleware/error-handler').errorHandler; var utterancesRoutes = require('./utterances'); var filesRoutes = require('./files'); var dataRoutes = require('./data'); var eLanguagesRoutes = require('./elanguages'); var morphologicalParsesRoutes = require('./morphologicalparses'); var setup = function setup(api, apiVersion) { swagger.configureSwaggerPaths('', '/api', ''); swagger.setErrorHandler(function (req, res, error) { return errorHandler(error, req, res); }); swagger.setAppHandler(api); /* Prepare models for the API Schema info using the info the routes provide */ var APIModelShema = {}; APIModelShema.models = { User: userRoutes.UserSchema, Connection: userRoutes.ConnectionSchema }; swagger.addModels(APIModelShema); /* Declare available APIs */ swagger.addGet({ spec: { path: '/v1/healthcheck', description: 'Operations about healthcheck', notes: 'Requests healthcheck', summary: 'Retrieves healthcheck', method: 'GET', parameters: [], responseClass: 'User', errorResponses: [], nickname: 'getHealthcheck' }, action: function getHealthcheck(req, res) { res.json({ ok: true }); } }); swagger.addPost(authenticationRoutes.postLogin); swagger.addGet(authenticationRoutes.getLogout); swagger.addPost(authenticationRoutes.postRegister); swagger.addGet(oauthRoutes.getAuthorize); swagger.addPost(oauthRoutes.postToken); swagger.addGet(userRoutes.getUser); swagger.addGet(userRoutes.getCurrentUser); swagger.addGet(userRoutes.getList); swagger.addPost(userRoutes.postUsers); swagger.addPut(userRoutes.putUser); swagger.addDelete(userRoutes.deleteUsers); swagger.addGet(corporaRoutes.getCorpora); swagger.addPost(corporaRoutes.postCorpora); swagger.addPut(corporaRoutes.putCorpora); swagger.addDelete(corporaRoutes.deleteCorpora); swagger.addSearch(corporaRoutes.searchCorpora); // api.delete('/corpus/:corpusid', corporaRoutes.deleteCorpora.action); swagger.addGet(dataRoutes.getData); swagger.addPost(dataRoutes.postData); swagger.addPut(dataRoutes.putData); swagger.addDelete(dataRoutes.deleteData); swagger.addGet(utterancesRoutes.getUtterances); swagger.addPost(utterancesRoutes.postUtterances); swagger.addPut(utterancesRoutes.putUtterances); swagger.addDelete(utterancesRoutes.deleteUtterances); swagger.addGet(filesRoutes.getFiles); swagger.addPost(filesRoutes.postFiles); swagger.addPut(filesRoutes.putFiles); swagger.addDelete(filesRoutes.deleteFiles); swagger.addGet(eLanguagesRoutes.getELanguages); swagger.addPost(eLanguagesRoutes.postELanguages); swagger.addPut(eLanguagesRoutes.putELanguages); swagger.addDelete(eLanguagesRoutes.deleteELanguages); swagger.addGet(morphologicalParsesRoutes.getMorphologicalParses); swagger.addPost(morphologicalParsesRoutes.postMorphologicalParses); swagger.addPut(morphologicalParsesRoutes.putMorphologicalParses); swagger.addDelete(morphologicalParsesRoutes.deleteMorphologicalParses); swagger.configure(config.externalOrigin);// + '/' + apiVersion, apiVersion.replace('v', '')); }; exports.setup = setup;
39.622222
95
0.75631
52c9cc5706cbe4d303199117273ba65f62e54e9b
1,448
js
JavaScript
src/get-package-name/__tests__/create-package.test.js
kira0x1/github-npm-stats
ee07d2ed2922410f7b7311fbf97a54771f1322d0
[ "MIT" ]
52
2017-09-25T08:10:44.000Z
2021-12-15T16:37:33.000Z
src/get-package-name/__tests__/create-package.test.js
kira0x1/github-npm-stats
ee07d2ed2922410f7b7311fbf97a54771f1322d0
[ "MIT" ]
15
2017-10-11T13:28:31.000Z
2020-09-16T19:49:12.000Z
src/get-package-name/__tests__/create-package.test.js
kira0x1/github-npm-stats
ee07d2ed2922410f7b7311fbf97a54771f1322d0
[ "MIT" ]
8
2017-10-15T11:31:49.000Z
2020-12-30T07:43:34.000Z
import createPackage from '../create-package' jest.mock('../fetch-package-name') import fetchPackageNameMock from '../fetch-package-name' const now = Date.now() const nowFunc = Date.now.bind(Date) beforeAll(() => { Date.now = jest.fn(() => now) }) afterAll(() => { Date.now = nowFunc }) afterEach(() => { fetchPackageNameMock.mockReset() chrome.storage.local.set.mockReset() }) describe('createPackage', () => { it('returns package that consist of name and timestamp', async () => { fetchPackageNameMock.mockReturnValue(Promise.resolve('vue')) const pkg = await createPackage('cache-key', 'vuejs', 'vue') expect(fetchPackageNameMock).toHaveBeenCalledWith('vuejs', 'vue') expect(pkg).toEqual({ name: 'vue', timeCreated: now }) }) it('caches package in storage', async () => { fetchPackageNameMock.mockReturnValue(Promise.resolve('vue')) chrome.storage.local.set.mockImplementation((object, callback) => { expect(object['cache-key']).toEqual({ name: 'vue', timeCreated: now }) callback() }) const pkg = await createPackage('cache-key', 'vuejs', 'vue') }) it('returns null if package name is null', async () => { fetchPackageNameMock.mockReturnValue(Promise.resolve(null)) const pkg = await createPackage('cache-key', 'vuejs', 'vue') expect(pkg).toBeNull() expect(chrome.storage.local.set).not.toHaveBeenCalled() }) })
24.965517
72
0.653315
52ca296a4fc2f370b88988313ea8fcde1d6a8ab9
1,459
js
JavaScript
build/lib/Devices/VendorTypeVersion/zhimi.fan.v2.js
sergeyksv/ioBroker.miio
afdc8315d8814252cc6a09f8caed1ef99f4c33f7
[ "MIT" ]
1
2022-01-14T13:36:06.000Z
2022-01-14T13:36:06.000Z
build/lib/Devices/VendorTypeVersion/zhimi.fan.v2.js
sergeyksv/ioBroker.miio
afdc8315d8814252cc6a09f8caed1ef99f4c33f7
[ "MIT" ]
null
null
null
build/lib/Devices/VendorTypeVersion/zhimi.fan.v2.js
sergeyksv/ioBroker.miio
afdc8315d8814252cc6a09f8caed1ef99f4c33f7
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DeviceClass = void 0; const Fan = require("../Type/fan"); const tools_1 = require("../../tools"); const command_1 = require("../../Commands/command"); const property_1 = require("../../Properties/property"); class DeviceClass extends Fan.DeviceClass { get deviceName() { return "zhimi.fan.v2"; } get deviceType() { return "VendorTypeVersionDevice"; } get rwState() { return (0, tools_1.objectExtend)(super.rwState, { led: { command: new command_1.SetLed(), property: new property_1.Led(), } }); } get roState() { return (0, tools_1.objectExtend)(super.roState, { humidity: { property: new property_1.Humidity(), }, temperature: { property: new property_1.TempDec(), }, battery: { property: new property_1.Battery(), }, ChargeState: { property: new property_1.BatCharge(), }, LastPressedButton: { property: new property_1.ButtonPressed(), }, batteryState: { property: new property_1.BatState(), } }); } constructor(miioDev) { super(miioDev); } } exports.DeviceClass = DeviceClass; ;
28.607843
62
0.520219
52ca41b256a721422f302ffc0306c74cc021d297
4,300
js
JavaScript
config/helpers.js
illimitable-in/Sails-Template-App
cd9ce08cba6881819d44bc35500c4398fa3d9a91
[ "MIT" ]
null
null
null
config/helpers.js
illimitable-in/Sails-Template-App
cd9ce08cba6881819d44bc35500c4398fa3d9a91
[ "MIT" ]
null
null
null
config/helpers.js
illimitable-in/Sails-Template-App
cd9ce08cba6881819d44bc35500c4398fa3d9a91
[ "MIT" ]
null
null
null
var Handlebars = require('handlebars'); Handlebars.registerHelper('_initVariable', function (varName, data) { if (varName) { return 'var ' + varName + ' = ' + ((typeof data == 'object') ? JSON.stringify(data) : ((typeof data == 'string') ? ('\'' + data + '\'') : data)) + ';'; } }); Handlebars.registerHelper('_pageTitle', function (title) { return title ? title : sails.config.appDisplayName; }); Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) { switch (operator) { case '==': return (v1 == v2) ? options.fn(this) : options.inverse(this); case '===': return (v1 === v2) ? options.fn(this) : options.inverse(this); case '!=': return (v1 != v2) ? options.fn(this) : options.inverse(this); case '!==': return (v1 !== v2) ? options.fn(this) : options.inverse(this); case '<': return (v1 < v2) ? options.fn(this) : options.inverse(this); case '<=': return (v1 <= v2) ? options.fn(this) : options.inverse(this); case '>': return (v1 > v2) ? options.fn(this) : options.inverse(this); case '>=': return (v1 >= v2) ? options.fn(this) : options.inverse(this); case '&&': return (v1 && v2) ? options.fn(this) : options.inverse(this); case '||': return (v1 || v2) ? options.fn(this) : options.inverse(this); default: return options.inverse(this); } }); Handlebars.registerHelper('arrayContains', function (arrayObj, arg) { try { if (arrayObj.indexOf(arg) >= 0) { return true; } } catch (e) { } return false; }); Handlebars.registerHelper('conditionalPrint', function (v1, operator, v2, option) { switch (operator) { case '==': return (v1 == v2) ? option : ''; case '===': return (v1 === v2) ? option : ''; case '!=': return (v1 != v2) ? option : ''; case '!==': return (v1 !== v2) ? option : ''; case '<': return (v1 < v2) ? option : ''; case '<=': return (v1 <= v2) ? option : ''; case '>': return (v1 > v2) ? option : ''; case '>=': return (v1 >= v2) ? option : ''; case '&&': return (v1 && v2) ? option : ''; case '||': return (v1 || v2) ? option : ''; case 'in': try{ v2 = v2.split(","); if(v2.indexOf(v1)>= 0){ return option; }else{ return ''; } }catch(ex){ return ''; } default: return ''; } }); Handlebars.registerHelper('ternaryPrint', function (v1, operator, v2, successoption,failureoption) { switch (operator) { case '==': return (v1 == v2) ? successoption : failureoption; case '===': return (v1 === v2) ? successoption : failureoption; case '!=': return (v1 != v2) ? successoption : failureoption; case '!==': return (v1 !== v2) ? successoption : failureoption; case '<': return (v1 < v2) ? successoption : failureoption; case '<=': return (v1 <= v2) ? successoption : failureoption; case '>': return (v1 > v2) ? successoption : failureoption; case '>=': return (v1 >= v2) ? successoption : failureoption; case '&&': return (v1 && v2) ? successoption : failureoption; case '||': return (v1 || v2) ? successoption : failureoption; case 'in': try{ v2 = v2.split(","); if(v2.indexOf(v1)>= 0){ return successoption; }else{ return failureoption; } }catch(ex){ return failureoption; } default: return failureoption; } }); module.exports = Handlebars.helpers;
33.59375
160
0.44814
52ca7425b8312927a9c3111d263ef9ae0ec06437
4,056
js
JavaScript
app/static/scripts/xdataht/modules/util/kmeans.js
giantoak/OpenAds-Flask
ab51b3e44056accbc43bed4c568dcf41c9678a29
[ "MIT" ]
null
null
null
app/static/scripts/xdataht/modules/util/kmeans.js
giantoak/OpenAds-Flask
ab51b3e44056accbc43bed4c568dcf41c9678a29
[ "MIT" ]
null
null
null
app/static/scripts/xdataht/modules/util/kmeans.js
giantoak/OpenAds-Flask
ab51b3e44056accbc43bed4c568dcf41c9678a29
[ "MIT" ]
null
null
null
/** * Copyright (c) 2013 Oculus Info Inc. * http://www.oculusinfo.com/ * * Released under the MIT License. * * 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. */ define(['jquery'], function($) { var getRange = function(data) { var result = { minX:null, maxX:null, minY:null, maxY:null }; for (var i=0; i<data.length; i++) { var datum = data[i]; if (result.minX==null || result.minX>datum.lon) result.minX = datum.lon; if (result.maxX==null || result.maxX<datum.lon) result.maxX = datum.lon; if (result.minY==null || result.minY>datum.lat) result.minY = datum.lat; if (result.maxY==null || result.maxY<datum.lat) result.maxY = datum.lat; } return result; }; var initKmeans = function(data,k) { var range = getRange(data); var xsteps = Math.ceil(Math.sqrt(k)); var xstep = (range.maxX-range.minX)/xsteps; var ysteps = Math.ceil(k/xsteps); var ystep = (range.maxY-range.minY)/ysteps; var clusters = []; var curX = 0, curY = 0; for (var i=0; i<k; i++) { curX = Math.floor(i/ysteps); curY = i-curX*ysteps; clusters.push({lon:range.minX+xstep*curX,lat:range.minY+ystep*curY,members:[]}); } return clusters; }; var assignClusters = function(data, clusters) { var anyChanges = false; for (var i=0; i<data.length; i++) { var datum = data[i]; var bestMatch = null; var bestDistance = null; for (var j=0; j<clusters.length; j++) { var cluster = clusters[j]; var distance = Math.pow(cluster.lon-datum.lon,2)+Math.pow(cluster.lat-datum.lat,2); if (bestDistance==null || distance<bestDistance) { bestMatch = j; bestDistance = distance; } } if ((!datum.cluster)||(datum.cluster!=bestMatch)) { anyChanges = true; datum.cluster = bestMatch; } clusters[bestMatch].members.push(datum); } return anyChanges; }; var computeCentroids = function(clusters) { for (var i=0; i<clusters.length; i++) { var cluster = clusters[i]; var sumX = 0, sumY = 0; for (var j=0; j<cluster.members.length; j++) { sumX += cluster.members[j].lon; sumY += cluster.members[j].lat; } if (cluster.members.length!=0) { cluster.lon = sumX/cluster.members.length; cluster.lat = sumY/cluster.members.length; } } }; var clearClusters = function(clusters) { for (var i=0; i<clusters.length; i++) { clusters[i].members.length = 0; } }; var kmeans = function(data, k) { var clusters = initKmeans(data,k); assignClusters(data, clusters); var anyChanges = true; var iteration = 0; while (anyChanges && iteration<100) { computeCentroids(clusters); clearClusters(clusters); anyChanges = assignClusters(data, clusters); iteration++; } var result = []; for (var i=0; i<clusters.length; i++) { var cluster = clusters[i]; if (cluster.members.length>0) result.push(cluster); } return result; }; return { kmeans:kmeans } });
31.937008
88
0.649655
52cad0d6604bf269a8294f031c5946e41dd04298
1,016
js
JavaScript
RANDOM-USER-GEN/app.js
ozgurtezel89/vuejs-study
e0fcbaee1a422ad020824d7c501f3d2d184ce4a3
[ "MIT" ]
null
null
null
RANDOM-USER-GEN/app.js
ozgurtezel89/vuejs-study
e0fcbaee1a422ad020824d7c501f3d2d184ce4a3
[ "MIT" ]
null
null
null
RANDOM-USER-GEN/app.js
ozgurtezel89/vuejs-study
e0fcbaee1a422ad020824d7c501f3d2d184ce4a3
[ "MIT" ]
null
null
null
const app = Vue.createApp({ data(){ return { firstname: 'Ozgur', lastname: 'Tezel', email: 'ozgurtezel89@gmail.com', gender: 'male', picture: 'https://randomuser.me/api/portraits/lego/1.jpg' } }, methods: { changeUser() { this.firstname = 'Tilly'; this.lastname = 'Tezel'; this.email = 'tillytezel89@gmail.com'; this.gender = 'female'; this.picture = 'https://randomuser.me/api/portraits/lego/9.jpg' }, async getRandomUser(){ const res = await fetch('https://randomuser.me/api') const { results } = await res.json(); const result = results[0]; this.firstname = result.name.first; this.lastname = result.name.last; this.email = result.email; this.gender = result.gender; this.picture = result.picture.large } } }) app.mount('#app')
29.882353
75
0.507874
52cb29ab2a7afa0ec9ac4fe95195cbf10dfc8aca
1,790
js
JavaScript
Develop/index.js
bronsonsoda/readme-gen
daf97de5a7fc98983d31a1eceb7e957c21c34dff
[ "Info-ZIP" ]
null
null
null
Develop/index.js
bronsonsoda/readme-gen
daf97de5a7fc98983d31a1eceb7e957c21c34dff
[ "Info-ZIP" ]
null
null
null
Develop/index.js
bronsonsoda/readme-gen
daf97de5a7fc98983d31a1eceb7e957c21c34dff
[ "Info-ZIP" ]
null
null
null
const inquirer = require("inquirer"); const fs = require('fs'); const axios = require("axios"); const generate = require('./utils/generateMarkdown'); // array of questions for user const questions = [ { type: "input", name: "title", message: "Title of project" }, { type: "input", name: "badge", message: "Badge link" }, { type: "input", name: "description", message: "Enter description" }, { type: "input", name: "contents", message: "Table of contents" }, { type: "input", name: "installation", message: "Installation instructions" }, { type: "input", name: "usage", message: "Project usage" }, { type: "input", name: "licence", message: "Project license" }, { type: "input", name: "contributing", message: "Contributing" }, { type: "input", name: "test", message: "Project tests" }, { type: "input", name: "username", message: "What is your github username?" }, { type: "input", name: "repo", message: "What is the repo link?" }, { type: "input", name: "email", message: "What is your email?" }, ]; inquirer .prompt(questions) .then(function (data) { const queryUrl = `https://api.github.com/users/${data.username}`; axios.get(queryUrl).then(function (res) { const githubInfo = { githubImage: res.data.avatar_url, email: res.data.email, profile: res.data.html_url, name: res.data.name }; fs.writeFile("README.md", generate(data, githubInfo), function (err) { if (err) { throw err; }; console.log("New README file created with success!"); }); }); }); function init() { } init();
18.080808
76
0.553073
52cb7595f9613fc9b2b888954d1accd499370044
221
js
JavaScript
03. JS Syntax/6. Figure Area.js
dimitar-v/JS-Fundamentals
de5c2cdc4924b37334ecb53139bfd2a1b05b1f83
[ "MIT" ]
null
null
null
03. JS Syntax/6. Figure Area.js
dimitar-v/JS-Fundamentals
de5c2cdc4924b37334ecb53139bfd2a1b05b1f83
[ "MIT" ]
null
null
null
03. JS Syntax/6. Figure Area.js
dimitar-v/JS-Fundamentals
de5c2cdc4924b37334ecb53139bfd2a1b05b1f83
[ "MIT" ]
null
null
null
function figureArea(w1, h1, w2, h2) { let s1 = w1 * h1; let s2 = w2 * h2; let s3 = Math.min(w1, w2) * Math.min(h1, h2); console.log(s1 + s2 - s3); } //figureArea(2, 4, 5, 3); //figureArea(13, 2, 5, 8);
18.416667
49
0.524887
52cbff50ef10cbcd44564023d9eec225aab528d8
675
js
JavaScript
test/index.js
Mattlk13/nodegit
f75d7388958f9a8f53aaa0cc06137099c1fcd161
[ "MIT" ]
1
2017-10-02T15:07:39.000Z
2017-10-02T15:07:39.000Z
test/index.js
atf1999/nodegit
269a324acc51e5859b491c5982c216783a11c114
[ "MIT" ]
null
null
null
test/index.js
atf1999/nodegit
269a324acc51e5859b491c5982c216783a11c114
[ "MIT" ]
1
2021-07-02T00:10:25.000Z
2021-07-02T00:10:25.000Z
var fork = require("child_process").fork; var path = require("path"); var bin = "./node_modules/.bin/istanbul"; var cov = "cover --report=lcov --dir=test/coverage/js _mocha --".split(" "); if (process.platform === 'win32') { bin = "./node_modules/mocha/bin/mocha"; cov = []; } var args = cov.concat([ "test/runner", "test/tests", "--expose-gc", "--timeout", "15000" ]); if (!process.env.APPVEYOR && !process.env.TRAVIS) { var local = path.join.bind(path, __dirname); var dummyPath = local("home"); process.env.HOME = dummyPath; process.env.USERPROFILE = dummyPath; } fork(bin, args, { cwd: path.join(__dirname, "../") }).on("close", process.exit);
24.107143
80
0.632593
52cc31cfebb05b53535619b745a19592610beca2
12,584
js
JavaScript
apollo-portal/src/main/resources/static/scripts/directive/directive.js
Hans-Kl/apollo
311e8e6cf867a33e8e4a64d85a13a18e30074ac6
[ "Apache-2.0" ]
2
2021-02-22T02:32:41.000Z
2021-02-22T02:35:30.000Z
apollo-portal/src/main/resources/static/scripts/directive/directive.js
Dmsansan/apollo
5c5deb7e42b367fae579cccf8a2212b29d935195
[ "Apache-2.0" ]
23
2019-01-31T13:03:33.000Z
2021-03-28T15:36:36.000Z
apollo-portal/src/main/resources/static/scripts/directive/directive.js
Dmsansan/apollo
5c5deb7e42b367fae579cccf8a2212b29d935195
[ "Apache-2.0" ]
2
2017-09-23T12:56:22.000Z
2018-09-17T08:04:55.000Z
/** navbar */ directive_module.directive('apollonav', function ($compile, $window, $translate, toastr, AppUtil, AppService, EnvService, UserService, CommonService, PermissionService) { return { restrict: 'E', templateUrl: AppUtil.prefixPath() + '/views/common/nav.html', transclude: true, replace: true, link: function (scope, element, attrs) { CommonService.getPageSetting().then(function (setting) { scope.pageSetting = setting; }); // Looks like a trick to make xml/yml/json namespaces display right, but why? $(document).on('click', function () { scope.$apply(function () {}); }); $translate('ApolloConfirmDialog.SearchPlaceHolder').then(function(placeholderLabel) { $('#app-search-list').select2({ placeholder: placeholderLabel, ajax: { url: AppUtil.prefixPath() + "/apps/search/by-appid-or-name", dataType: 'json', delay: 400, data: function (params) { return { query: params.term || '', page: params.page ? params.page - 1 : 0, size: 20 }; }, processResults: function (data) { if (data && data.content) { var hasMore = data.content.length === data.size; var result = []; data.content.forEach(function (app) { result.push({ id: app.appId, text: app.appId + ' / ' + app.name }) }); return { results: result, pagination: { more: hasMore } }; } else { return { results: [], pagination: { more: false } }; } } } }); $('#app-search-list').on('select2:select', function () { var selected = $('#app-search-list').select2('data'); if (selected && selected.length) { jumpToConfigPage(selected[0].id) } }); }); function jumpToConfigPage(selectedAppId) { if ($window.location.href.indexOf("config.html") > -1) { $window.location.hash = "appid=" + selectedAppId; $window.location.reload(); } else { $window.location.href = AppUtil.prefixPath() + '/config.html?#appid=' + selectedAppId; } }; UserService.load_user().then(function (result) { scope.userName = result.userId; }, function (result) { }); PermissionService.has_root_permission().then(function (result) { scope.hasRootPermission = result.hasPermission; }) scope.changeLanguage = function (lang) { $translate.use(lang) } } } }); /** env cluster selector*/ directive_module.directive('apolloclusterselector', function ($compile, $window, AppService, AppUtil, toastr) { return { restrict: 'E', templateUrl: AppUtil.prefixPath() + '/views/component/env-selector.html', transclude: true, replace: true, scope: { appId: '=apolloAppId', defaultAllChecked: '=apolloDefaultAllChecked', select: '=apolloSelect', defaultCheckedEnv: '=apolloDefaultCheckedEnv', defaultCheckedCluster: '=apolloDefaultCheckedCluster', notCheckedEnv: '=apolloNotCheckedEnv', notCheckedCluster: '=apolloNotCheckedCluster' }, link: function (scope, element, attrs) { scope.$watch("defaultCheckedEnv", refreshClusterList); scope.$watch("defaultCheckedCluster", refreshClusterList); refreshClusterList(); function refreshClusterList() { AppService.load_nav_tree(scope.appId).then(function (result) { scope.clusters = []; var envClusterInfo = AppUtil.collectData(result); envClusterInfo.forEach(function (node) { var env = node.env; node.clusters.forEach(function (cluster) { cluster.env = env; //default checked cluster.checked = scope.defaultAllChecked || (cluster.env == scope.defaultCheckedEnv && cluster.name == scope.defaultCheckedCluster); //not checked if (cluster.env == scope.notCheckedEnv && cluster.name == scope.notCheckedCluster) { cluster.checked = false; } scope.clusters.push(cluster); }) }); scope.select(collectSelectedClusters()); }); } scope.envAllSelected = scope.defaultAllChecked; scope.toggleEnvsCheckedStatus = function () { scope.envAllSelected = !scope.envAllSelected; scope.clusters.forEach(function (cluster) { cluster.checked = scope.envAllSelected; }); scope.select(collectSelectedClusters()); }; scope.switchSelect = function (o, $event) { o.checked = !o.checked; $event.stopPropagation(); scope.select(collectSelectedClusters()); }; scope.toggleClusterCheckedStatus = function (cluster) { cluster.checked = !cluster.checked; scope.select(collectSelectedClusters()); }; function collectSelectedClusters() { var selectedClusters = []; scope.clusters.forEach(function (cluster) { if (cluster.checked) { cluster.clusterName = cluster.name; selectedClusters.push(cluster); } }); return selectedClusters; } } } }); /** 必填项*/ directive_module.directive('apollorequiredfield', function ($compile, $window) { return { restrict: 'E', template: '<strong style="color: red">*</strong>', transclude: true, replace: true } }); /** 确认框 */ directive_module.directive('apolloconfirmdialog', function ($compile, $window, $sce,$translate,AppUtil) { return { restrict: 'E', templateUrl: AppUtil.prefixPath() + '/views/component/confirm-dialog.html', transclude: true, replace: true, scope: { dialogId: '=apolloDialogId', title: '=apolloTitle', detail: '=apolloDetail', showCancelBtn: '=apolloShowCancelBtn', doConfirm: '=apolloConfirm', extraClass: '=apolloExtraClass', confirmBtnText: '=?', cancel: '=' }, link: function (scope, element, attrs) { scope.$watch("detail", function () { scope.detailAsHtml = $sce.trustAsHtml(scope.detail); }); if (!scope.confirmBtnText) { scope.confirmBtnText = $translate.instant('ApolloConfirmDialog.DefaultConfirmBtnName'); } scope.confirm = function () { if (scope.doConfirm) { scope.doConfirm(); } }; } } }); /** entrance */ directive_module.directive('apolloentrance', function ($compile, $window,AppUtil) { return { restrict: 'E', templateUrl: AppUtil.prefixPath() + '/views/component/entrance.html', transclude: true, replace: true, scope: { imgSrc: '=apolloImgSrc', title: '=apolloTitle', href: '=apolloHref' }, link: function (scope, element, attrs) { } } }); /** entrance */ directive_module.directive('apollouserselector', function ($compile, $window,AppUtil) { return { restrict: 'E', templateUrl: AppUtil.prefixPath() + '/views/component/user-selector.html', transclude: true, replace: true, scope: { id: '=apolloId', disabled: '=' }, link: function (scope, element, attrs) { scope.$watch("id", initSelect2); var select2Options = { ajax: { url: AppUtil.prefixPath() + '/users', dataType: 'json', delay: 250, data: function (params) { return { keyword: params.term ? params.term : '', limit: 100 } }, processResults: function (data, params) { var users = []; data.forEach(function (user) { users.push({ id: user.userId, text: user.userId + " | " + user.name }) }); return { results: users } }, cache: true, minimumInputLength: 5 } }; function initSelect2() { $('.' + scope.id).select2(select2Options); } } } }); directive_module.directive('apollomultipleuserselector', function ($compile, $window,AppUtil) { return { restrict: 'E', templateUrl: AppUtil.prefixPath() + '/views/component/multiple-user-selector.html', transclude: true, replace: true, scope: { id: '=apolloId' }, link: function (scope, element, attrs) { scope.$watch("id", initSelect2); var searchUsersAjax = { ajax: { url: AppUtil.prefixPath() + '/users', dataType: 'json', delay: 250, data: function (params) { return { keyword: params.term ? params.term : '', limit: 100 } }, processResults: function (data, params) { var users = []; data.forEach(function (user) { users.push({ id: user.userId, text: user.userId + " | " + user.name }) }); return { results: users } }, cache: true, minimumInputLength: 5 } }; function initSelect2() { $('.' + scope.id).select2(searchUsersAjax); } } } });
35.648725
112
0.419024
52cedcb6eff54977c07b0eb2b1b622011de29aff
378
js
JavaScript
node_modules/@iconify/icons-radix-icons/minus-circled.js
skyriver228/Learn-ON
2eea03bdc040b2e9be7a267a65a699e7bfce455e
[ "MIT" ]
1
2021-02-25T07:20:19.000Z
2021-02-25T07:20:19.000Z
node_modules/@iconify/icons-radix-icons/minus-circled.js
skyriver228/Learn-ON
2eea03bdc040b2e9be7a267a65a699e7bfce455e
[ "MIT" ]
19
2021-02-11T12:39:34.000Z
2021-02-25T01:55:05.000Z
node_modules/@iconify/icons-radix-icons/minus-circled.js
skyriver228/Learn-ON
2eea03bdc040b2e9be7a267a65a699e7bfce455e
[ "MIT" ]
8
2021-02-05T05:13:06.000Z
2022-02-18T05:54:44.000Z
var data = { "body": "<g fill=\"none\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M7.5.877a6.623 6.623 0 1 0 0 13.246A6.623 6.623 0 0 0 7.5.877zM1.827 7.5a5.673 5.673 0 1 1 11.346 0a5.673 5.673 0 0 1-11.346 0zM4.5 7a.5.5 0 0 0 0 1h6a.5.5 0 1 0 0-1h-6z\" fill=\"currentColor\"/></g>", "width": 15, "height": 15 }; exports.__esModule = true; exports.default = data;
47.25
282
0.626984
52cf5ce0dfc8e3a74674ea7eadb608ebafa4d286
1,145
js
JavaScript
gulpfile.js
simmsa/dark-mode
a1925dd72280adde6274c9171969262a5c479bda
[ "MIT" ]
null
null
null
gulpfile.js
simmsa/dark-mode
a1925dd72280adde6274c9171969262a5c479bda
[ "MIT" ]
null
null
null
gulpfile.js
simmsa/dark-mode
a1925dd72280adde6274c9171969262a5c479bda
[ "MIT" ]
null
null
null
var gulp = require("gulp"); var exec = require("gulp-exec"); var rename = require("gulp-rename"); var less = require("gulp-less"); var cssLint = require("gulp-csslint"); var runSequence = require("run-sequence"); gulp.task("staticCss", function(){ var options = { continueOnError: false, pipeStdout: true }; gulp.src("build/CssBuilder.js") .pipe(exec("node <%= file.path %>", options)) .pipe(rename("dark-mode.css")) .pipe(gulp.dest("styles/css")); }); gulp.task("less", function(){ return gulp.src("styles/less/*.less") .pipe(less({})) .pipe(gulp.dest("styles/css")); }); gulp.task("lintCss", function(){ gulp.src("styles/css/dark-mode.css") .pipe(cssLint({ "important": false, "universal-selector": false, "unqualified-attributes": false, "regex-selectors": false })) .pipe(cssLint.reporter()); }); // Use run sequence to explicitly build the css then run the linter gulp.task("buildStaticCssThenLint", function(){ runSequence("staticCss", "lintCss"); }); gulp.task("default", ["less", "buildStaticCssThenLint"]);
27.261905
67
0.616594
52cfc2f029cbc831a8092fd59d4a5be9647d62a4
1,944
js
JavaScript
src/utils/helper.js
simon300000/github-annual-report
dd8864e05ba436b55941fe6ffc44622fc083fb29
[ "MIT" ]
1
2020-01-12T18:00:35.000Z
2020-01-12T18:00:35.000Z
src/utils/helper.js
liupengzhouyi/github-annual-report
bbdca44849b0fd39eef3bdb0581e047116c3b427
[ "MIT" ]
null
null
null
src/utils/helper.js
liupengzhouyi/github-annual-report
bbdca44849b0fd39eef3bdb0581e047116c3b427
[ "MIT" ]
null
null
null
import axios from 'axios' import { TIMEOUT } from './constant' export const utf8ToB64 = (str) => { return window.btoa(unescape(encodeURIComponent(str))) } export const b64ToUtf8 = (str) => { return decodeURIComponent(escape(window.atob(str))) } export const queryParse = (search = window.location.search) => { if (!search) return {} const queryString = search[0] === '?' ? search.substring(1) : search const query = {} queryString .split('&') .forEach(queryStr => { const [key, value] = queryStr.split('=') /* istanbul ignore else */ if (key) query[decodeURIComponent(key)] = decodeURIComponent(value) }) return query } export const axiosJSON = axios.create({ headers: { 'Accept': 'application/json' } }) export const axiosGithub = axios.create({ baseURL: 'https://api.github.com', headers: { 'Accept': 'application/json' } }) // 只有23:00 - 4:00的时间可以进入,保证不为空 export const compareLate = (latest, current) => { // 分别比较时分秒 const currentHours = current.getHours() === 23 ? -1 : current.getHours(); const latestHours = latest.getHours() === 23 ? -1 : latest.getHours(); if (currentHours > latestHours) { return current; } else if (currentHours === latestHours) { const currentMinutes = current.getMinutes(); const latestMinutes = latest.getMinutes(); if (currentMinutes > latestMinutes) { return current; } else if (currentMinutes === latestMinutes) { const currentSeconds = current.getSeconds(); const latestSeconds = latest.getSeconds(); if (currentSeconds > latestSeconds) { return current; } } } return latest; }; // 对每个API请求增加超时机制 export const timeout = (octokitPromise) => { return Promise.race([ octokitPromise, new Promise(function(resolve, reject) { setTimeout(() => reject(new Error('request timeout')), TIMEOUT); }), ]).catch((e)=>{ console.log(octokitPromise) }); }
27
75
0.647119
52d03f1867d983a91a69a2528e42dcfd57d74be4
209
js
JavaScript
node_modules/fibers/test/stack-overflow.js
josearmandojacq/x-chess-queen
b51baacbb2d7e8b12ad2c3d556d77dfc1a83dc0e
[ "MIT" ]
2,212
2015-01-03T06:42:16.000Z
2022-03-31T12:51:49.000Z
node_modules/fibers/test/stack-overflow.js
josearmandojacq/x-chess-queen
b51baacbb2d7e8b12ad2c3d556d77dfc1a83dc0e
[ "MIT" ]
273
2015-01-01T03:01:16.000Z
2022-02-07T11:04:18.000Z
node_modules/fibers/test/stack-overflow.js
Oliverhiggins93/macrophotographyworkshop
dd66b8e75a1e8d9ccd12216b1711dae8032d601e
[ "CC-BY-3.0" ]
191
2015-01-06T09:43:52.000Z
2021-12-09T17:28:13.000Z
var Fiber = require('fibers'); try { Fiber(function() { function foo() { var hello = Math.random(); foo(); } foo(); }).run(); } catch (err) { err.name === 'RangeError' && console.log('pass'); }
16.076923
50
0.545455
52d04d5ba0dbbdd5f0ef6b3ff1df370ca8eb8ee0
5,044
js
JavaScript
client/src/components/schema/PredicatePropertiesPanel.js
fenos/ratel
17b167b96159e0decf0cfe1e301acff53efa1d92
[ "Apache-2.0" ]
92
2018-11-30T01:34:40.000Z
2022-03-10T03:28:02.000Z
client/src/components/schema/PredicatePropertiesPanel.js
fenos/ratel
17b167b96159e0decf0cfe1e301acff53efa1d92
[ "Apache-2.0" ]
179
2018-12-10T17:49:17.000Z
2022-02-11T04:08:55.000Z
client/src/components/schema/PredicatePropertiesPanel.js
fenos/ratel
17b167b96159e0decf0cfe1e301acff53efa1d92
[ "Apache-2.0" ]
46
2018-12-02T16:59:45.000Z
2022-03-07T20:02:17.000Z
// Copyright 2017-2021 Dgraph Labs, Inc. and Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import React from "react"; import Button from "react-bootstrap/Button"; import { getPredicateQuery } from "lib/dgraph-syntax"; import SchemaPredicateForm from "./SchemaPredicateForm"; export default class PredicatePropertiesPanel extends React.Component { predicateForm = React.createRef(); state = { updating: false, deleting: false, errorMsg: "", predicateQuery: null, }; async handleUpdatePredicate() { const { executeQuery, onAfterUpdate } = this.props; this.setState({ errorMsg: "", updating: true, }); try { await executeQuery(this.state.predicateQuery, "alter"); onAfterUpdate(); } catch (errorMessage) { this.setState({ errorMsg: `Could not alter predicate: ${errorMessage}`, }); } finally { this.setState({ updating: false }); } } async handleDropPredicate() { const { executeQuery, onAfterDrop, predicate } = this.props; if (!window.confirm("Are you sure?\nThis action will destroy data!")) { return; } if ( !window.confirm( `Please confirm you *really* want to DROP\n"${predicate.predicate}".\nThis cannot be undone!`, ) ) { return; } this.setState({ errorMsg: "", deleting: true, }); try { await executeQuery( JSON.stringify({ drop_attr: predicate.predicate }), "alter", ); onAfterDrop(); } catch (errorMessage) { this.setState({ errorMsg: `Could not drop predicate: ${errorMessage}`, }); } finally { this.setState({ deleting: false }); } } render() { const { deleting, errorMsg, predicateQuery, updating } = this.state; const { predicate } = this.props; const predicateForm = this.predicateForm.current; const canUpdate = predicateForm && getPredicateQuery(predicate) !== predicateQuery && !predicateForm.hasErrors(); return ( <div> <div className="col-sm-12 mt-2"> <SchemaPredicateForm createMode={false} clickedSubmit={true} ref={this.predicateForm} predicate={predicate} onChangeQuery={predicateQuery => this.setState({ predicateQuery }) } /> {!errorMsg ? null : ( <div className="alert alert-danger">{errorMsg}</div> )} {!predicateQuery ? null : ( <div className="form-group"> <div className="col-sm-12" style={{ color: "#666" }} > New schema string:&nbsp; <span style={{ fontStyle: "italic" }}> {predicateQuery} </span> </div> </div> )} </div> <div className="col-sm-12 btn-toolbar justify-content-between" role="toolbar" aria-label="Operations on the selected predicate" > <Button variant="danger" onClick={() => this.handleDropPredicate()} disabled={updating || deleting} > {deleting ? "Dropping..." : "Drop"} </Button>{" "} <Button variant="primary" className="float-right" onClick={() => this.handleUpdatePredicate()} disabled={!canUpdate || updating || deleting} > {updating ? "Updating..." : "Update"} </Button> </div> </div> ); } }
33.626667
110
0.467684
52d0b1408c0d717c37113c2a1fdc7e42f0c4aaa5
2,530
js
JavaScript
vendor/angular/compiler/esm/src/view_compiler/view_compiler.js
mgechev/closure-compiler-angular-bundling
0887631ec6bf8423ecc245e523b023f06bb6d7ee
[ "MIT" ]
9
2016-08-22T21:16:00.000Z
2018-11-27T20:09:49.000Z
vendor/angular/compiler/esm/src/view_compiler/view_compiler.js
mgechev/closure-compiler-angular-bundling
0887631ec6bf8423ecc245e523b023f06bb6d7ee
[ "MIT" ]
null
null
null
vendor/angular/compiler/esm/src/view_compiler/view_compiler.js
mgechev/closure-compiler-angular-bundling
0887631ec6bf8423ecc245e523b023f06bb6d7ee
[ "MIT" ]
7
2016-08-22T21:16:03.000Z
2020-05-15T11:49:31.000Z
goog.module('_angular$compiler$src$view__compiler$view__compiler'); var core_1 = goog.require('_angular$core'); var compile_element_1 = goog.require('_angular$compiler$src$view__compiler$compile__element'); var compile_view_1 = goog.require('_angular$compiler$src$view__compiler$compile__view'); var view_builder_1 = goog.require('_angular$compiler$src$view__compiler$view__builder'); var view_binder_1 = goog.require('_angular$compiler$src$view__compiler$view__binder'); var config_1 = goog.require('_angular$compiler$src$config'); class ViewCompileResult { /** * @param {?} statements * @param {?} viewFactoryVar * @param {?} dependencies */ constructor(statements, viewFactoryVar, dependencies) { this.statements = statements; this.viewFactoryVar = viewFactoryVar; this.dependencies = dependencies; } static _tsickle_typeAnnotationsHelper() { /** @type {?} */ ViewCompileResult.prototype.statements; /** @type {?} */ ViewCompileResult.prototype.viewFactoryVar; /** @type {?} */ ViewCompileResult.prototype.dependencies; } } exports.ViewCompileResult = ViewCompileResult; class ViewCompiler { /** * @param {?} _genConfig */ constructor(_genConfig) { this._genConfig = _genConfig; } /** * @param {?} component * @param {?} template * @param {?} styles * @param {?} pipes * @return {?} */ compileComponent(component, template, styles, pipes) { var /** @type {?} */ statements = []; var /** @type {?} */ dependencies = []; var /** @type {?} */ view = new compile_view_1.CompileView(component, this._genConfig, pipes, styles, 0, compile_element_1.CompileElement.createNull(), []); view_builder_1.buildView(view, template, dependencies); // Need to separate binding from creation to be able to refer to // variables that have been declared after usage. view_binder_1.bindView(view, template); view_builder_1.finishView(view, statements); return new ViewCompileResult(statements, view.viewFactory.name, dependencies); } static _tsickle_typeAnnotationsHelper() { /** @type {?} */ ViewCompiler.prototype._genConfig; } } ViewCompiler.decorators = [ { type: core_1.Injectable }, ]; /** @nocollapse */ ViewCompiler.ctorParameters = [ { type: config_1.CompilerConfig, }, ]; exports.ViewCompiler = ViewCompiler; //# sourceMappingURL=view_compiler.js.map
38.333333
164
0.665217
52d1354a8de85cd82030e5082ac16d865e3825bc
44
js
JavaScript
index.js
allain/bench-csv
a7adfd56ac4e31aea9ecf31eb42398aaf779dbe6
[ "ISC" ]
null
null
null
index.js
allain/bench-csv
a7adfd56ac4e31aea9ecf31eb42398aaf779dbe6
[ "ISC" ]
1
2018-06-02T01:06:07.000Z
2018-06-02T02:12:31.000Z
index.js
allain/bench-csv
a7adfd56ac4e31aea9ecf31eb42398aaf779dbe6
[ "ISC" ]
null
null
null
module.exports = require('./src/benchmark')
22
43
0.727273
52d14b6f1acad74892e8bf56c92d2d7c22c21e90
21,185
js
JavaScript
node_modules/googleapis/apis/youtubeAnalytics/v1.js
fahamk/writersblock
d2c24c902a7262e2318cea3b55da4218a3c7b651
[ "Apache-2.0" ]
null
null
null
node_modules/googleapis/apis/youtubeAnalytics/v1.js
fahamk/writersblock
d2c24c902a7262e2318cea3b55da4218a3c7b651
[ "Apache-2.0" ]
5
2017-08-29T05:55:57.000Z
2017-09-05T04:29:16.000Z
node_modules/googleapis/apis/youtubeAnalytics/v1.js
fahamk/writersblock
d2c24c902a7262e2318cea3b55da4218a3c7b651
[ "Apache-2.0" ]
null
null
null
"use strict"; /** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* jshint maxlen: false */ const apirequest_1 = require("../../lib/apirequest"); /** * YouTube Analytics API * * Retrieves your YouTube Analytics data. * * @example * const google = require('googleapis'); * const youtubeAnalytics = google.youtubeAnalytics('v1'); * * @namespace youtubeAnalytics * @type {Function} * @version v1 * @variation v1 * @param {object=} options Options for Youtubeanalytics */ function Youtubeanalytics(options) { const self = this; self._options = options || {}; self.groupItems = { /** * youtubeAnalytics.groupItems.delete * * @desc Removes an item from a group. * * @alias youtubeAnalytics.groupItems.delete * @memberOf! youtubeAnalytics(v1) * * @param {object} params Parameters for request * @param {string} params.id The id parameter specifies the YouTube group item ID for the group that is being deleted. * @param {string=} params.onBehalfOfContentOwner Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/youtube/analytics/v1/groupItems').replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE' }, options), params: params, requiredParams: ['id'], pathParams: [], context: self }; return apirequest_1.default(parameters, callback); }, /** * youtubeAnalytics.groupItems.insert * * @desc Creates a group item. * * @alias youtubeAnalytics.groupItems.insert * @memberOf! youtubeAnalytics(v1) * * @param {object} params Parameters for request * @param {string=} params.onBehalfOfContentOwner Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {youtubeAnalytics(v1).GroupItem} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/youtube/analytics/v1/groupItems').replace(/([^:]\/)\/+/g, '$1'), method: 'POST' }, options), params: params, requiredParams: [], pathParams: [], context: self }; return apirequest_1.default(parameters, callback); }, /** * youtubeAnalytics.groupItems.list * * @desc Returns a collection of group items that match the API request parameters. * * @alias youtubeAnalytics.groupItems.list * @memberOf! youtubeAnalytics(v1) * * @param {object} params Parameters for request * @param {string} params.groupId The id parameter specifies the unique ID of the group for which you want to retrieve group items. * @param {string=} params.onBehalfOfContentOwner Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/youtube/analytics/v1/groupItems').replace(/([^:]\/)\/+/g, '$1'), method: 'GET' }, options), params: params, requiredParams: ['groupId'], pathParams: [], context: self }; return apirequest_1.default(parameters, callback); } }; self.groups = { /** * youtubeAnalytics.groups.delete * * @desc Deletes a group. * * @alias youtubeAnalytics.groups.delete * @memberOf! youtubeAnalytics(v1) * * @param {object} params Parameters for request * @param {string} params.id The id parameter specifies the YouTube group ID for the group that is being deleted. * @param {string=} params.onBehalfOfContentOwner Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/youtube/analytics/v1/groups').replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE' }, options), params: params, requiredParams: ['id'], pathParams: [], context: self }; return apirequest_1.default(parameters, callback); }, /** * youtubeAnalytics.groups.insert * * @desc Creates a group. * * @alias youtubeAnalytics.groups.insert * @memberOf! youtubeAnalytics(v1) * * @param {object} params Parameters for request * @param {string=} params.onBehalfOfContentOwner Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {youtubeAnalytics(v1).Group} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/youtube/analytics/v1/groups').replace(/([^:]\/)\/+/g, '$1'), method: 'POST' }, options), params: params, requiredParams: [], pathParams: [], context: self }; return apirequest_1.default(parameters, callback); }, /** * youtubeAnalytics.groups.list * * @desc Returns a collection of groups that match the API request parameters. For example, you can retrieve all groups that the authenticated user owns, or you can retrieve one or more groups by their unique IDs. * * @alias youtubeAnalytics.groups.list * @memberOf! youtubeAnalytics(v1) * * @param {object=} params Parameters for request * @param {string=} params.id The id parameter specifies a comma-separated list of the YouTube group ID(s) for the resource(s) that are being retrieved. In a group resource, the id property specifies the group's YouTube group ID. * @param {boolean=} params.mine Set this parameter's value to true to instruct the API to only return groups owned by the authenticated user. * @param {string=} params.onBehalfOfContentOwner Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {string=} params.pageToken The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken property identifies the next page that can be retrieved. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/youtube/analytics/v1/groups').replace(/([^:]\/)\/+/g, '$1'), method: 'GET' }, options), params: params, requiredParams: [], pathParams: [], context: self }; return apirequest_1.default(parameters, callback); }, /** * youtubeAnalytics.groups.update * * @desc Modifies a group. For example, you could change a group's title. * * @alias youtubeAnalytics.groups.update * @memberOf! youtubeAnalytics(v1) * * @param {object} params Parameters for request * @param {string=} params.onBehalfOfContentOwner Note: This parameter is intended exclusively for YouTube content partners. The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner. * @param {youtubeAnalytics(v1).Group} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/youtube/analytics/v1/groups').replace(/([^:]\/)\/+/g, '$1'), method: 'PUT' }, options), params: params, requiredParams: [], pathParams: [], context: self }; return apirequest_1.default(parameters, callback); } }; self.reports = { /** * youtubeAnalytics.reports.query * * @desc Retrieve your YouTube Analytics reports. * * @alias youtubeAnalytics.reports.query * @memberOf! youtubeAnalytics(v1) * * @param {object} params Parameters for request * @param {string=} params.currency The currency to which financial metrics should be converted. The default is US Dollar (USD). If the result contains no financial metrics, this flag will be ignored. Responds with an error if the specified currency is not recognized. * @param {string=} params.dimensions A comma-separated list of YouTube Analytics dimensions, such as views or ageGroup,gender. See the Available Reports document for a list of the reports that you can retrieve and the dimensions used for those reports. Also see the Dimensions document for definitions of those dimensions. * @param {string} params.end-date The end date for fetching YouTube Analytics data. The value should be in YYYY-MM-DD format. * @param {string=} params.filters A list of filters that should be applied when retrieving YouTube Analytics data. The Available Reports document identifies the dimensions that can be used to filter each report, and the Dimensions document defines those dimensions. If a request uses multiple filters, join them together with a semicolon (;), and the returned result table will satisfy both filters. For example, a filters parameter value of video==dMH0bHeiRNg;country==IT restricts the result set to include data for the given video in Italy. * @param {string} params.ids Identifies the YouTube channel or content owner for which you are retrieving YouTube Analytics data. - To request data for a YouTube user, set the ids parameter value to channel==CHANNEL_ID, where CHANNEL_ID specifies the unique YouTube channel ID. - To request data for a YouTube CMS content owner, set the ids parameter value to contentOwner==OWNER_NAME, where OWNER_NAME is the CMS name of the content owner. * @param {boolean=} params.include-historical-channel-data If set to true historical data (i.e. channel data from before the linking of the channel to the content owner) will be retrieved. * @param {integer=} params.max-results The maximum number of rows to include in the response. * @param {string} params.metrics A comma-separated list of YouTube Analytics metrics, such as views or likes,dislikes. See the Available Reports document for a list of the reports that you can retrieve and the metrics available in each report, and see the Metrics document for definitions of those metrics. * @param {string=} params.sort A comma-separated list of dimensions or metrics that determine the sort order for YouTube Analytics data. By default the sort order is ascending. The '-' prefix causes descending sort order. * @param {string} params.start-date The start date for fetching YouTube Analytics data. The value should be in YYYY-MM-DD format. * @param {integer=} params.start-index An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter (one-based, inclusive). * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ query: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/youtube/analytics/v1/reports').replace(/([^:]\/)\/+/g, '$1'), method: 'GET' }, options), params: params, requiredParams: ['ids', 'start-date', 'end-date', 'metrics'], pathParams: [], context: self }; return apirequest_1.default(parameters, callback); } }; } module.exports = Youtubeanalytics; //# sourceMappingURL=v1.js.map
64.588415
725
0.641586
52d192f5f42be7cf8ebe265b02d905381c5de54c
3,308
js
JavaScript
source/background.js
agustinroldan/virus-link-scanner
3874cb16e52a6619dbd3678b9c3d04355a7bcf0f
[ "MIT" ]
3
2015-08-13T08:48:56.000Z
2018-06-17T20:38:53.000Z
source/background.js
agustinroldan/virus-link-scanner
3874cb16e52a6619dbd3678b9c3d04355a7bcf0f
[ "MIT" ]
null
null
null
source/background.js
agustinroldan/virus-link-scanner
3874cb16e52a6619dbd3678b9c3d04355a7bcf0f
[ "MIT" ]
2
2015-09-17T15:08:41.000Z
2018-08-26T19:31:20.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. var url_link = ''; /* function getOpeningIds() { var ids = []; try { ids = JSON.parse(localStorage.openWhenComplete); } catch (e) { localStorage.openWhenComplete = JSON.stringify(ids); } return ids; } function setOpeningIds(ids) { localStorage.openWhenComplete = JSON.stringify(ids); } chrome.downloads.onChanged.addListener(function (delta) { if (!delta.state || (delta.state.current != 'complete')) { return; } var ids = getOpeningIds(); if (ids.indexOf(delta.id) < 0) { return; } chrome.downloads.open(delta.id); ids.splice(ids.indexOf(delta.id), 1); setOpeningIds(ids); }); */ chrome.contextMenus.onClicked.addListener(function (info, tab) { /// begin doing my testing for virus detection. /// Use Alerts at the moment. url_link = info.linkUrl; // check for api key value pair var apikey = localStorage['apikey']; if (undefined == apikey) { chrome.tabs.executeScript(null, { code: 'alert("No valid API Key Found. Please Add one using the extension popup above.")' }); } /// Try doing your analysis. else { data_download(url_link); } }); chrome.contextMenus.create({ id: 'open', title: 'Scan link with Metascan Online', contexts: ['link'], }); chrome.downloads.onCreated.addListener(function(downloadItem){ if(localStorage['auto'] === '1'){ //chrome.downloads.pause(downloadItem.id); url_link = downloadItem.url; data_download(url_link); console.log("auto scanning started"); } console.log(downloadItem.id); //chrome.downloads.resume(integer downloadId, function callback) });
36.351648
91
0.704655
52d1eaf1d92bd329c580b019452879043390ace1
327
js
JavaScript
app/modules/job-list/controllers/job-list.ctrl.js
stackdot/cuid
802937a05b028ab5b4bbc2341f9f165c9e348d49
[ "MIT" ]
null
null
null
app/modules/job-list/controllers/job-list.ctrl.js
stackdot/cuid
802937a05b028ab5b4bbc2341f9f165c9e348d49
[ "MIT" ]
null
null
null
app/modules/job-list/controllers/job-list.ctrl.js
stackdot/cuid
802937a05b028ab5b4bbc2341f9f165c9e348d49
[ "MIT" ]
null
null
null
// job-list controller: module.exports = ( $scope, jobListService, sidebarService ) => { console.log('constr') var self = this $scope.data = jobListService.data $scope.sidebar = () => { console.log('sidebar') sidebarService.close() } $scope.itemClick = ( e ) => { console.log('item click') return false } }
16.35
64
0.642202
52d250aeadee79c37089a0bec33d98cad168b1e4
1,245
js
JavaScript
modules/HTML/Panel.js
web-part/stat
06f3a2e1545d3ef60c30259f9eae8b7db166811b
[ "MIT" ]
null
null
null
modules/HTML/Panel.js
web-part/stat
06f3a2e1545d3ef60c30259f9eae8b7db166811b
[ "MIT" ]
null
null
null
modules/HTML/Panel.js
web-part/stat
06f3a2e1545d3ef60c30259f9eae8b7db166811b
[ "MIT" ]
null
null
null
const cheerio = require('cheerio'); const MD5 = require('@definejs/md5'); const Lines = require('@definejs/lines'); module.exports = { parse(content, selectors) { let $ = cheerio.load(content); let list = $(selectors.join(',')); list = Array.from(list).map((item) => { let { attribs, } = item; let content = $.html(item); let lines = Lines.split(content); let md5 = MD5.get(content); let id = ''; let method = ''; ['view', 'panel', ].some((key) => { let value = attribs[`data-${key}`]; if (!value) { return; } id = value; method = key; return true; }); return { 'id': id, 'method': method, 'factory': { 'type': item.name, //标签名,如 `div`。 'content': content, 'md5': md5, 'lines': lines.length, 'attribs': { ...item.attribs, }, }, }; }); return list; }, };
21.465517
53
0.369478
52d2d89b61096efc3c9b282847c7253d2d7c4025
4,887
js
JavaScript
transport/ipcc/europe/default.js
mamhoff/datasets
b33b25ba5a27abd354c110520eaa969bffddd4a6
[ "MIT" ]
7
2019-07-23T07:19:36.000Z
2020-03-08T15:23:25.000Z
transport/ipcc/europe/default.js
mamhoff/datasets
b33b25ba5a27abd354c110520eaa969bffddd4a6
[ "MIT" ]
14
2019-07-22T18:36:37.000Z
2019-09-09T11:45:00.000Z
transport/ipcc/europe/default.js
mamhoff/datasets
b33b25ba5a27abd354c110520eaa969bffddd4a6
[ "MIT" ]
3
2017-07-21T11:47:23.000Z
2019-09-15T14:04:35.000Z
// establish which profile item values set try{ var fC = fuelConsumed; } catch(error) { fuelConsumed = null; } try { var d = distance; } catch(error) { distance = null; returnValues.addNote('comment', 'Distance not specified. Cannot calculate CH4 and N2O emissions'); } try{ var fE = fuelEfficiency; } catch(error) { fuelEfficiency = null; } // check if driving style parameters total to 1 var drivingParameters = urbanCold + urbanhot + highway + rural; if (drivingParameters != 1) { returnValues.addNote('comment', 'Driving style parameters do not total 1. Cannot calculate CH4 and N2O emissions'); } // ############### CO2 EMISSIONS ################## // translate fuel to name used in lookup category var ipccSynonym; var defraSynonym; if (fuel == "gasoline") { ipccSynonym = "motor gasoline"; defraSynonym = "petrol"; } else if(fuel == "diesel") { ipccSynonym = "gas/diesel oil"; defraSynonym = "diesel"; } else if(fuel == "lpg") { ipccSynonym = "liquefied petroleum gases"; defraSynonym = "lpg"; } else if(fuel == "cng") { ipccSynonym = "compressed natural gas"; defraSynonym = "cng"; } // get fuel property data var massCO2PerEnergy = dataFinder.getDataItemValue('transport/ipcc/fuel','fuel='+ipccSynonym,'massCO2PerEnergy'); var energyPerMass = dataFinder.getDataItemValue('transport/ipcc/fuel','fuel='+ipccSynonym,'netEnergyPerMass'); try { // if density specified, convert to litres per tonne var d = density; } catch(error) { // if no density specified, use DEFRA data var volumePerMass = dataFinder.getDataItemValue('business/energy/stationaryCombustion/defra/fuelproperties','fuel='+defraSynonym,'volumePerMass'); density = 1000 / volumePerMass; // convert DEFRA litres-per-tonne into kg per L } // establish volumetric emissions factor for CO2 using fuel properties var CO2VolumeFactor = (massCO2PerEnergy * energyPerMass / 1000000) * density; // 1000000 factor is conversion from per Gg to per kg // calculate if (fuelConsumed == null) { if (distance == null || fuelEfficiency == null){ //CO2 only, fuel-based calcualtion co2Emissions = 0; returnValues.addNote('comment', 'Cannot calculate CO2 emissions. Either fuel consumed OR distance AND fuel efficiency must be specified'); } else { co2Emissions = (distance * (CO2VolumeFactor / fuelEfficiency))/occupancy; } } else { co2Emissions = (CO2VolumeFactor * fuelConsumed)/occupancy; } // ############### N2O EMISSIONS ################## // establish N2O emissions factor var n2oDistanceFactor; try { if (distance == null) { throw "error"; } var n2oUrbanCold = massN2OPerDistanceUrbanCold*urbanCold; var n2oUrbanHot = massN2OPerDistanceUrbanHot*urbanhot; var n2oHighway = massN2OPerDistanceHighway*highway; var n2oRural = massN2OPerDistanceRural*rural; n2oDistanceFactor = (n2oUrbanCold +n2oUrbanHot + n2oHighway + n2oRural)/1000000; n2oGWP = parseFloat(dataFinder.getDataItemValue('planet/greenhousegases/gwp','gas=N2O','GWP')); //global warming potential for N2O returnValues.addNote('comment', 'N2O emissions converted to CO2e using a global warming potential of '+n2oGWP); } catch(error) { // if no data (i.e. cng buses and trucks) set to zero n2oDistanceFactor = 0; n2oGWP = 0; } if(distance == null){ //CO2 only, fuel-based calculation n2oEmissions = 0; } else if (drivingParameters != 1) { n2oEmissions = 0; } else { n2oEmissions = distance * n2oDistanceFactor / occupancy; } // ############### CH4 EMISSIONS ################## // establish CH4 emissions factor var ch4DistanceFactor; try { if (distance == null) { throw "error"; } var ch4UrbanCold = massCH4PerDistanceUrbanCold*urbanCold; var ch4UrbanHot = massCH4PerDistanceUrbanHot*urbanhot; var ch4Highway = massCH4PerDistanceHighway*highway; var ch4Rural = massCH4PerDistanceRural*rural; ch4DistanceFactor = (ch4UrbanCold +ch4UrbanHot + ch4Highway + ch4Rural)/1000000; ch4GWP = parseFloat(dataFinder.getDataItemValue('planet/greenhousegases/gwp','gas=CH4','GWP')); //global warming potential for CH4 returnValues.addNote('comment', 'CH4 emissions converted to CO2e using a global warming potential of '+ch4GWP); } catch(error) { // if no data (i.e. cng buses and trucks) set to zero ch4DistanceFactor = 0; ch4GWP = 0; } if(distance == null){ //CO2 only, fuel-based calculation ch4Emissions = 0; } else if (drivingParameters != 1) { ch4Emissions = 0; } else { ch4Emissions = distance * ch4DistanceFactor / occupancy; } // ############### Return values ################## returnValues.putValue('CO2', 'kg',null, co2Emissions); returnValues.putValue('CH4', 'kg',null, ch4Emissions); returnValues.putValue('N2O', 'kg',null, n2oEmissions); co2eEmissions = co2Emissions + (ch4Emissions * ch4GWP) + (n2oEmissions * n2oGWP); returnValues.putValue('CO2e', 'kg',null, co2eEmissions); returnValues.setDefaultType('CO2e');
36.744361
148
0.710661
52d3038e47e7c116a96789c3901af60648f9f1fc
5,214
js
JavaScript
packages/web-app/src/Accounts.js
YDB-stack/ydb-nwmrentals
e85178644a29313afb03df64e22bce38ad1ad408
[ "Apache-2.0" ]
null
null
null
packages/web-app/src/Accounts.js
YDB-stack/ydb-nwmrentals
e85178644a29313afb03df64e22bce38ad1ad408
[ "Apache-2.0" ]
null
null
null
packages/web-app/src/Accounts.js
YDB-stack/ydb-nwmrentals
e85178644a29313afb03df64e22bce38ad1ad408
[ "Apache-2.0" ]
null
null
null
import React, { useEffect } from 'react' import { useDispatch, useSelector } from 'react-redux' import { getAccountList, getAccountById, getAccountBalances, getAccountTransactions, getAccountDirectDebits, getAccountProducts, getAccountStandingOrders, } from '@openbanking/ui-data/lib/services/account-service' import InfoDisplay from '@openbanking/ui-common/lib/InfoDisplay' import './Accounts.css' import { Menu } from './Menu' import Button from '@material-ui/core/Button' import { makeStyles } from '@material-ui/core/styles' const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(7), display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(3), }, submit: { margin: theme.spacing(3, 0, 2), }, textField: { marginLeft: theme.spacing(1), marginRight: theme.spacing(1), width: '100%', }, })) //accounts api list const Accounts = () => { const classes = useStyles() console.log('11') const data = useSelector((state) => state.app.data) const accountId = useSelector((state) => state.account.accountId) console.log('dispatch') const dispatch = useDispatch() useEffect(() => getAccountList(dispatch), []) return ( <div className="mainContainer"> <h2 className="pageTitle"> Your account has been successfully added <br /> <br /> {data ? data.Data.Account.map((item) => { return ( <> <br /> <strong>{item.Nickname}</strong> <br /> </> ) }) : console.log('null from Account component')} </h2> <a href="/menu"> <Button // type="submit" fullWidth variant="contained" color="primary" preventDefault className={classes.submit} //onClick={Card} > Back to menu </Button> </a> <div className="apiContainer"> <div className="btnContainer"> {/* <button className="buttonLinks" onClick={() => { console.log('Acc List') getAccountList(dispatch) }} > Get Account List </button> <button className="buttonLinks" onClick={() => getAccountById(dispatch, accountId)} > Get Account By Id </button> <button className="buttonLinks" onClick={() => { console.log('Ba1ance ') getAccountBalances(dispatch, accountId) }} > Get Account Balances </button> {/* <button className="buttonLinks" onClick={() => getAccountDirectDebits(dispatch, accountId) } > Get Account Direct Debits </button> */} {/* <button className="buttonLinks" onClick={() => getAccountTransactions(dispatch, accountId) } > Get Account Transactions </button> {/* <button className="buttonLinks" onClick={() => getAccountProducts(dispatch, accountId)} > Get Account Products </button> <button className="buttonLinks" onClick={() => getAccountStandingOrders(dispatch, accountId) } > Get Account Standing Orders </button> */} </div> <div className="displayInfo"> <InfoDisplay data={data} /> {console.log('DATA after InfoDisplay')} {console.log(data)} </div> </div> </div> ) } export default Accounts
33
79
0.403913
52d397370a3804a2da2781141cb39448502d7c30
245
js
JavaScript
owtf/webapp/src/sagas.js
samhaxr/owtf
5d24be34a8303bb7234e0154a91d0755c90533d2
[ "BSD-3-Clause" ]
1
2018-11-22T15:15:50.000Z
2018-11-22T15:15:50.000Z
owtf/webapp/src/sagas.js
samhaxr/owtf
5d24be34a8303bb7234e0154a91d0755c90533d2
[ "BSD-3-Clause" ]
null
null
null
owtf/webapp/src/sagas.js
samhaxr/owtf
5d24be34a8303bb7234e0154a91d0755c90533d2
[ "BSD-3-Clause" ]
null
null
null
/** * Combine all sags in this file and export the combined sagas. */ import { all } from 'redux-saga/effects'; import sessionSaga from 'containers/Sessions/saga'; export default function* rootSaga() { yield all([ sessionSaga() ]) }
18.846154
63
0.689796
52d39a95d54fc839f08abbb9bfc39deee3e40b87
2,940
js
JavaScript
style/js/telerik2014.1.416/kendo.dataviz.sparkline.min.js
murderkillgamers/Dev
148d3b58269096b3d2cab98cdd56bbc4a2e4ab63
[ "MIT" ]
1
2020-07-23T06:11:12.000Z
2020-07-23T06:11:12.000Z
style/js/telerik2014.1.416/kendo.dataviz.sparkline.min.js
murderkillgamers/Dev
148d3b58269096b3d2cab98cdd56bbc4a2e4ab63
[ "MIT" ]
null
null
null
style/js/telerik2014.1.416/kendo.dataviz.sparkline.min.js
murderkillgamers/Dev
148d3b58269096b3d2cab98cdd56bbc4a2e4ab63
[ "MIT" ]
1
2021-05-03T14:46:31.000Z
2021-05-03T14:46:31.000Z
/* * Kendo UI v2014.1.416 (http://www.telerik.com/kendo-ui) * Copyright 2014 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ !function(e,define){define(["./kendo.dataviz.chart.min"],e)}(function(){return function(e){function t(e){return"number"==typeof e?[e]:e}var n=window.kendo,i=n.dataviz,r=i.ui.Chart,o=n.data.ObservableArray,a=i.SharedTooltip,s=n.deepExtend,l=e.isArray,d=i.inArray,c=Math,u="k-",p=150,f=150,h="bar",g="bullet",m="pie",v=[h,g],_=r.extend({init:function(n,i){var a=this,p=a.stage=e("<span />"),f=i||{};n=e(n).addClass(u+"sparkline").empty().append(p),a._initialWidth=c.floor(n.width()),f=t(f),(l(f)||f instanceof o)&&(f={seriesDefaults:{data:f}}),f.series||(f.series=[{data:t(f.data)}]),s(f,{seriesDefaults:{type:f.type}}),(d(f.series[0].type,v)||d(f.seriesDefaults.type,v))&&(f=s({},{categoryAxis:{crosshair:{visible:!1}}},f)),r.fn.init.call(a,n,f)},options:{name:"Sparkline",chartArea:{margin:2},axisDefaults:{visible:!1,majorGridLines:{visible:!1},valueAxis:{narrowRange:!0}},seriesDefaults:{type:"line",area:{line:{width:.5}},bar:{stack:!0},padding:2,width:.5,overlay:{gradient:null},highlight:{visible:!1},border:{width:0},markers:{size:2,visible:!1}},tooltip:{visible:!0,shared:!0},categoryAxis:{crosshair:{visible:!0,tooltip:{visible:!1}}},legend:{visible:!1},transitions:!1,pointWidth:5,panes:[{clip:!1}]},_applyDefaults:function(e){var t=this,n=i.ViewFactory.current.create({},e.renderAs);i.CanvasView&&n instanceof i.CanvasView&&s(e,{categoryAxis:{crosshair:{visible:!1}}}),r.fn._applyDefaults.apply(t,arguments)},_modelOptions:function(){var e,t=this,n=t.options,i=t._initialWidth,r=t.stage;return t.stage[0].innerHTML="&nbsp;",e=s({width:i?i:t._autoWidth(),height:r.height(),transitions:n.transitions},n.chartArea,{inline:!0,align:!1}),r.css({width:e.width,height:e.height}),e},_createTooltip:function(){var e,t=this,n=t.options,i=t.element;return e=t._sharedTooltip()?new k(i,t._plotArea,n.tooltip):r.fn._createTooltip.call(t)},_renderView:function(){var e=this;return e.element.empty().append(e.stage),e._view.renderTo(e.stage[0])},_autoWidth:function(){var e,t,n,r=this,o=r.options,a=i.getSpacing(o.chartArea.margin),s=o.series,l=r.dataSource.total(),d=0;for(t=0;s.length>t;t++){if(n=s[t],n.type===h)return p;if(n.type===g)return f;if(n.type===m)return r.stage.height();n.data&&(d=c.max(d,n.data.length))}return e=c.max(l,d)*o.pointWidth,e>0&&(e+=a.left+a.right),e}}),k=a.extend({options:{animation:{duration:0}},_anchor:function(e,t){var n=a.fn._anchor.call(this,e,t);return n.y=-this.element.height()-this.options.offset,n},_hideElement:function(){this.element.hide()}});i.ui.plugin(_),s(i,{})}(window.kendo.jQuery),window.kendo},"function"==typeof define&&define.amd?define:function(e,t){t()});
326.666667
2,607
0.715986
52d3c1dc5a1acfeca6d60ecb0ef869a0b2907677
3,216
js
JavaScript
components/Directions.js
sasham43/deco-cocktails
07f97f08ce0ef9d62d45a63232d40b9819e6248c
[ "MIT" ]
null
null
null
components/Directions.js
sasham43/deco-cocktails
07f97f08ce0ef9d62d45a63232d40b9819e6248c
[ "MIT" ]
null
null
null
components/Directions.js
sasham43/deco-cocktails
07f97f08ce0ef9d62d45a63232d40b9819e6248c
[ "MIT" ]
null
null
null
import React, { useState, useEffect } from 'react' import { StyleSheet, View, TextInput } from 'react-native' import AppText from './AppText' import CornerIcon from '../assets/corner' export function Directions(props){ const [directions, setDirections] = useState(props.directions ? props.directions : '') // console.log('dir', directions, props.directions) useEffect(()=>{ setDirections(props.directions) }, [props.directions]) if(directions && directions.split('\n').length > 4){ setDirections(directions.replace(/\n/g, ' ')) } return ( <View style={[styles.directions, props.style]}> <AppText style={[styles.directions_text, props.style]}>{directions}</AppText> </View> ) } export function DirectionsInput(props){ var icon_size = 15 return ( <View style={styles.directions_input_container}> <View> <CornerIcon fill={props.ui.current_theme.color} style={[styles.corner_icon, styles.top_right]} width={icon_size} height={icon_size} /> <CornerIcon fill={props.ui.current_theme.color} style={[styles.corner_icon, styles.top_left]} width={icon_size} height={icon_size} /> <CornerIcon fill={props.ui.current_theme.color} style={[styles.corner_icon, styles.bottom_right]} width={icon_size} height={icon_size} /> <CornerIcon fill={props.ui.current_theme.color} style={[styles.corner_icon, styles.bottom_left]} width={icon_size} height={icon_size} /> <TextInput style={[styles.directions_input, props.ui.current_theme]} multiline={true} numberOfLines={10} onChangeText={(text) => props.setText(text)} value={props.text} placeholder={"Directions..."} placeholderTextColor={"grey"} maxLength={220} /> </View> <View style={{ flexDirection: 'row', justifyContent: 'flex-end', flex: 1 }}> <AppText style={{ color: 'grey' }}> {props.text.length} / 220 letters </AppText> </View><AppText></AppText> </View> ) } var icon_distance = 0 const styles = StyleSheet.create({ directions_input_container: { marginTop: 25 }, directions_input: { fontFamily: 'PoiretOne_400Regular', paddingTop: 10, paddingBottom: 10, paddingLeft: 10, paddingRight: 10, borderWidth: 1, height: 150, flex: 1, alignItems: 'stretch', fontSize: 17 }, directions: { padding: 20 }, directions_text: { fontSize: 17 }, corner_icon: { zIndex: 10, position: 'absolute' }, top_right: { top: icon_distance, right: icon_distance }, top_left: { top: icon_distance, left: icon_distance, transform: [{ rotate: '-90deg' }] }, bottom_right: { bottom: icon_distance, right: icon_distance, transform: [{ rotate: '90deg' }] }, bottom_left: { bottom: icon_distance, left: icon_distance, transform: [{ rotate: '180deg' }] } })
37.395349
153
0.587065
52d4e22a05de18d6567b53d7776d94022bf28578
1,282
js
JavaScript
src/utils/Globals.js
jicksonp/TwitterSearch
c9a39ed3a410dd0476f7846d0a4b0ff0576f724b
[ "Apache-2.0" ]
null
null
null
src/utils/Globals.js
jicksonp/TwitterSearch
c9a39ed3a410dd0476f7846d0a4b0ff0576f724b
[ "Apache-2.0" ]
null
null
null
src/utils/Globals.js
jicksonp/TwitterSearch
c9a39ed3a410dd0476f7846d0a4b0ff0576f724b
[ "Apache-2.0" ]
null
null
null
// @flow module.exports = { SCREEN_TITLE: { HOME: 'Twitter Search', }, COLOR: { PRIMARY: '#0F303E', DARK_PRIMARY: 'rgb(102,119,133)', APP_BACKGROUND: '#F5FCFF', BLACK_75: 'rgba(0,0,0,0.75)', GREYISH_BROWN: '#565656', PALE_GREY_33: 'rgba(231,235,237,0.33)', LIGHT_GREY: '#cecece', GREY: '#aaaaaa', TEXT_ICON: '#FFFFFF', ACCENT: '#4CAF50', PRIMARY_TEXT: '#212121', SECONDARY_TEXT: '#727272', DIVIDER: '#B6B6B6', BACKGROUND: '#0E3753', LIBRARY_PRIMARY: 'paperBlue', WHITE: '#FFFFFF', LOGIN_GREY_CARD: 'rgba(255,255,255,0.64)', PRIMARY_GREEN: '#38ab57', BLACK_87: 'rgba(0, 0, 0, 0.87)', BLACK_54: 'rgba(0,0,0,0.54)', BLACK_27: 'rgba(0,0,0,0.27)', GRE_98: '#FAFAFA', CHETWODE_BLUE: '#58A2C2', LOADER_TRANSPARENT_BACKGROUND: 'rgba(0, 0, 0, 0.3)', DARK_TEXT: '#032250', LIGHT_TEXT: '#7F91A7', }, STRINGS: { HINT_SEARCH: 'Please enter hashtag to search', NETWORK_ERROR_TITLE: 'Slow or no internet connection', NETWORK_ERROR_MESSAGE: 'Please wait & try again after a moment', SEARCH_ERROR: 'Failed to get Tweet', }, };
31.268293
72
0.546022
52d4ec8507b112b29c0d21b7fb210303568756b9
711
js
JavaScript
src/Topxia/WebBundle/Resources/public/js/controller/my/notebook-show.js
smeagonline-developers/OnlineEducationPlatform---SMEAGonline
dce7114bde92d6ca9f4daed880b8163df4e6a1b2
[ "MIT" ]
null
null
null
src/Topxia/WebBundle/Resources/public/js/controller/my/notebook-show.js
smeagonline-developers/OnlineEducationPlatform---SMEAGonline
dce7114bde92d6ca9f4daed880b8163df4e6a1b2
[ "MIT" ]
null
null
null
src/Topxia/WebBundle/Resources/public/js/controller/my/notebook-show.js
smeagonline-developers/OnlineEducationPlatform---SMEAGonline
dce7114bde92d6ca9f4daed880b8163df4e6a1b2
[ "MIT" ]
null
null
null
define(function(require, exports, module) { exports.run = function() { $('#notebook').on('click', '.notebook-note-collapsed', function(){ $(this).removeClass('notebook-note-collapsed'); }); $('#notebook').on('click', '.notebook-note-collapse-bar', function(){ $(this).parents('.notebook-note').addClass('notebook-note-collapsed'); }); $('#notebook').on('click', '.notebook-note-delete', function(){ var $btn = $(this); if (!confirm('真的要删除该笔记吗?')) { return false; } $.post($btn.data('url'), function(){ $btn.parents('.notebook-note').remove(); }); }); }; });
28.44
82
0.506329
52d6686da987acef89bddf786eddde324ab4a6b3
601
js
JavaScript
3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/GeneratorFunction/invoked-as-function-no-arguments.js
mikestaub/arangodb
1bdf414de29b31bcaf80769a095933f66f8256ce
[ "ICU", "BSL-1.0", "Zlib", "Apache-2.0" ]
11
2016-03-29T16:34:24.000Z
2020-04-23T14:49:33.000Z
3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/GeneratorFunction/invoked-as-function-no-arguments.js
mikestaub/arangodb
1bdf414de29b31bcaf80769a095933f66f8256ce
[ "ICU", "BSL-1.0", "Zlib", "Apache-2.0" ]
2
2016-02-08T18:26:26.000Z
2018-06-30T20:56:39.000Z
test/built-ins/GeneratorFunction/invoked-as-function-no-arguments.js
LaudateCorpus1/test262
9c45e2ac684bae64614d8eb55789cae97323a7e7
[ "BSD-3-Clause" ]
7
2018-05-30T05:05:57.000Z
2022-03-27T17:59:46.000Z
// Copyright (C) 2013 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es6id: 25.2 description: > When invoked via the function invocation pattern without arguments, the GeneratorFunction intrinsic returns a valid generator with an empty body. ---*/ var GeneratorFunction = Object.getPrototypeOf(function* () {}).constructor; var g = GeneratorFunction(); var iter = g(); var result = iter.next(); assert.sameValue(result.value, undefined, 'Result `value`'); assert.sameValue(result.done, true, 'Result `done` flag');
33.388889
77
0.733777
52d6bd94befdafc462271f25c655f02b57d4ed62
2,294
js
JavaScript
docs/can-guides/commitment/recipes/credit-card-simple/6-validate-form.js
gsmeets/canjs
b72caa80dd5dfc3e65832dff18aee4d8c4327c61
[ "MIT" ]
null
null
null
docs/can-guides/commitment/recipes/credit-card-simple/6-validate-form.js
gsmeets/canjs
b72caa80dd5dfc3e65832dff18aee4d8c4327c61
[ "MIT" ]
null
null
null
docs/can-guides/commitment/recipes/credit-card-simple/6-validate-form.js
gsmeets/canjs
b72caa80dd5dfc3e65832dff18aee4d8c4327c61
[ "MIT" ]
null
null
null
Stripe.setPublishableKey('pk_test_zCC2JrO3KSMeh7BB5x9OUe2U'); var PaymentVM = can.DefineMap.extend({ amount: {value: 9.99}, userCardNumber: "string", get cardNumber(){ return this.userCardNumber ? this.userCardNumber.replace(/-/g,""): null; }, get cardError() { if( this.cardNumber && !Stripe.card.validateCardNumber(this.cardNumber) ) { return "Invalid card number (ex: 4242-4242-4242)."; } }, userExpiry: "string", get expiryParts() { if(this.userExpiry) { return this.userExpiry.split("-").map(function(p){ return parseInt(p,10); }); } }, get expiryMonth() { return this.expiryParts && this.expiryParts[0]; }, get expiryYear() { return this.expiryParts && this.expiryParts[1]; }, get expiryError() { if( (this.expiryMonth || this.expiryYear) && !Stripe.card.validateExpiry(this.expiryMonth, this.expiryYear) ) { return "Invalid expiration date (ex: 01-22)."; } }, userCVC: "string", get cvc(){ return this.userCVC ? parseInt(this.userCVC,10) : null; }, get cvcError() { if(this.cvc && !Stripe.card.validateCVC(this.cvc)) { return "Invalid CVC (ex: 123)."; } }, pay: function(event){ event.preventDefault(); Stripe.card.createToken({ number: this.cardNumber, cvc: this.cvc, exp_month: this.expiryMonth, exp_year: this.expiryYear }, function(status, response){ if(status === 200) { alert("Token: "+response.id); // stripe.charges.create({ // amount: this.amount, // currency: "usd", // description: "Example charge", // source: response.id, // }) } else { alert("Error: "+response.error.message); } }); }, get isCardValid(){ return Stripe.card.validateCardNumber(this.cardNumber) && Stripe.card.validateExpiry(this.expiryMonth, this.expiryYear) && Stripe.card.validateCVC(this.cvc); }, get isCardInvalid(){ return !this.isCardValid; }, get errorMessage(){ return this.cardError || this.expiryError || this.cvcError; } }); var viewModel = new PaymentVM(); var paymentView = can.stache.from("payment-view"); var frag = paymentView( viewModel ); document.body.appendChild( frag );
25.775281
79
0.617698
52d7ebe663c9222278a41dab2024dbbb18509a85
783
js
JavaScript
theme/utils/propToStyle.js
rafedweb/instalura-base2
ab33992665dc9fa1b076a18a6eeafcb00950255f
[ "MIT" ]
null
null
null
theme/utils/propToStyle.js
rafedweb/instalura-base2
ab33992665dc9fa1b076a18a6eeafcb00950255f
[ "MIT" ]
null
null
null
theme/utils/propToStyle.js
rafedweb/instalura-base2
ab33992665dc9fa1b076a18a6eeafcb00950255f
[ "MIT" ]
null
null
null
import { breakpointsMedia } from './breakpointsMedia'; // eslint-disable-next-line import/prefer-default-export export function propToStyle(propName) { return function(props) { const propValue = props[propName]; if(typeof propValue === 'string' || typeof propValue === 'number') { return { // textAlign: props.textAlign [propName]: propValue } } if(typeof propValue === 'object') { return breakpointsMedia({ xs: { [propName]: propValue.xs }, sm: { [propName]: propValue.sm }, md: { [propName]: propValue.md }, lg: { [propName]: propValue.lg }, xl: { [propName]: propValue.xl }, }) } } }
22.371429
72
0.519796
52d7f3cdc843555004d56ce8eb86fba47d676faa
20,621
js
JavaScript
static/index.js
Fpskkk/getanemeng
40c587a9ddedc01cf95fb5beccfbd218b8037529
[ "MIT" ]
null
null
null
static/index.js
Fpskkk/getanemeng
40c587a9ddedc01cf95fb5beccfbd218b8037529
[ "MIT" ]
null
null
null
static/index.js
Fpskkk/getanemeng
40c587a9ddedc01cf95fb5beccfbd218b8037529
[ "MIT" ]
null
null
null
const MODE_NORMAL = 1, MODE_ENDLESS = 2, MODE_PRACTICE = 3; (function(w) { let isDesktop = !navigator['userAgent'].match(/(ipad|iphone|ipod|android|windows phone)/i); let fontunit = isDesktop ? 20 : ((window.innerWidth > window.innerHeight ? window.innerHeight : window.innerWidth) / 320) * 10; document.write('<style type="text/css">' + 'html,body {font-size:' + (fontunit < 30 ? fontunit : '30') + 'px;}' + (isDesktop ? '#welcome,#GameTimeLayer,#GameLayerBG,#GameScoreLayer.SHADE{position: absolute;}' : '#welcome,#GameTimeLayer,#GameLayerBG,#GameScoreLayer.SHADE{position:fixed;}@media screen and (orientation:landscape) {#landscape {display: box; display: -webkit-box; display: -moz-box; display: -ms-flexbox;}}') + '</style>'); let map = {'d': 1, 'f': 2, 'j': 3, 'k': 4}; if (isDesktop) { document.write('<div id="gameBody">'); document.onkeydown = function (e) { let key = e.key.toLowerCase(); if (Object.keys(map).indexOf(key) !== -1) { click(map[key]) } } } let body, blockSize, GameLayer = [], GameLayerBG, touchArea = [], GameTimeLayer; let transform, transitionDuration, welcomeLayerClosed; let mode = getMode(); w.init = function() { showWelcomeLayer(); body = document.getElementById('gameBody') || document.body; body.style.height = window.innerHeight + 'px'; transform = typeof (body.style.webkitTransform) != 'undefined' ? 'webkitTransform' : (typeof (body.style.msTransform) != 'undefined' ? 'msTransform' : 'transform'); transitionDuration = transform.replace(/ransform/g, 'ransitionDuration'); GameTimeLayer = document.getElementById('GameTimeLayer'); GameLayer.push(document.getElementById('GameLayer1')); GameLayer[0].children = GameLayer[0].querySelectorAll('div'); GameLayer.push(document.getElementById('GameLayer2')); GameLayer[1].children = GameLayer[1].querySelectorAll('div'); GameLayerBG = document.getElementById('GameLayerBG'); if (GameLayerBG.ontouchstart === null) { GameLayerBG.ontouchstart = gameTapEvent; } else { GameLayerBG.onmousedown = gameTapEvent; } gameInit(); initSetting(); window.addEventListener('resize', refreshSize, false); } function getMode() { //有cookie优先返回cookie记录的,没有再返回normal return cookie('gameMode') ? parseInt(cookie('gameMode')) : MODE_NORMAL; } function modeToString(m) { return m === MODE_NORMAL ? "普通模式" : (m === MODE_ENDLESS ? "无尽模式" : "练习模式"); } w.changeMode = function(m) { mode = m; cookie('gameMode', m); $('#mode').text(modeToString(m)); } w.readyBtn = function() { closeWelcomeLayer(); updatePanel(); } w.winOpen = function() { window.open(location.href + '?r=' + Math.random(), 'nWin', 'height=500,width=320,toolbar=no,menubar=no,scrollbars=no'); let opened = window.open('about:blank', '_self'); opened.opener = null; opened.close(); } let refreshSizeTime; function refreshSize() { clearTimeout(refreshSizeTime); refreshSizeTime = setTimeout(_refreshSize, 200); } function _refreshSize() { countBlockSize(); for (let i = 0; i < GameLayer.length; i++) { let box = GameLayer[i]; for (let j = 0; j < box.children.length; j++) { let r = box.children[j], rstyle = r.style; rstyle.left = (j % 4) * blockSize + 'px'; rstyle.bottom = Math.floor(j / 4) * blockSize + 'px'; rstyle.width = blockSize + 'px'; rstyle.height = blockSize + 'px'; } } let f, a; if (GameLayer[0].y > GameLayer[1].y) { f = GameLayer[0]; a = GameLayer[1]; } else { f = GameLayer[1]; a = GameLayer[0]; } let y = ((_gameBBListIndex) % 10) * blockSize; f.y = y; f.style[transform] = 'translate3D(0,' + f.y + 'px,0)'; a.y = -blockSize * Math.floor(f.children.length / 4) + y; a.style[transform] = 'translate3D(0,' + a.y + 'px,0)'; } function countBlockSize() { blockSize = body.offsetWidth / 4; body.style.height = window.innerHeight + 'px'; GameLayerBG.style.height = window.innerHeight + 'px'; touchArea[0] = window.innerHeight; touchArea[1] = window.innerHeight - blockSize * 3; } let _gameBBList = [], _gameBBListIndex = 0, _gameOver = false, _gameStart = false, _gameSettingNum=20, _gameTime, _gameTimeNum, _gameScore, _date1, deviationTime; let _gameStartTime, _gameStartDatetime; function gameInit() { createjs.Sound.registerSound({ src: "./static/music/err.mp3", id: "err" }); createjs.Sound.registerSound({ src: "./static/music/end.mp3", id: "end" }); createjs.Sound.registerSound({ src: "./static/music/tap.mp3", id: "tap" }); gameRestart(); } function gameRestart() { _gameBBList = []; _gameBBListIndex = 0; _gameScore = 0; _gameOver = false; _gameStart = false; _gameTimeNum = _gameSettingNum; _gameStartTime = 0; countBlockSize(); refreshGameLayer(GameLayer[0]); refreshGameLayer(GameLayer[1], 1); updatePanel(); } function gameStart() { _date1 = new Date(); _gameStartDatetime = _date1.getTime(); _gameStart = true; _gameTime = setInterval(timer, 1000); } function getCPS() { let cps = _gameScore / ((new Date().getTime() - _gameStartDatetime) / 1000); if (isNaN(cps) || cps === Infinity || _gameStartTime < 2) { cps = 0; } return cps; } function timer() { _gameTimeNum--; _gameStartTime++; if (mode === MODE_NORMAL && _gameTimeNum <= 0) { GameTimeLayer.innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;时间到!'; gameOver(); GameLayerBG.className += ' flash'; createjs.Sound.play("end"); } updatePanel(); } function updatePanel() { if (mode === MODE_NORMAL) { if (!_gameOver) { GameTimeLayer.innerHTML = createTimeText(_gameTimeNum); } } else if (mode === MODE_ENDLESS) { let cps = getCPS(); let text = (cps === 0 ? '计算中' : cps.toFixed(2)); GameTimeLayer.innerHTML = `CPS:${text}`; } else { GameTimeLayer.innerHTML = `SCORE:${_gameScore}`; } } //使重试按钮获得焦点 function foucusOnReplay(){ $('#replay').focus() } function gameOver() { _gameOver = true; clearInterval(_gameTime); let cps = getCPS(); updatePanel(); setTimeout(function () { GameLayerBG.className = ''; showGameScoreLayer(cps); foucusOnReplay(); }, 1500); } function encrypt(text) { let encrypt = new JSEncrypt(); encrypt.setPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDTzGwX6FVKc7rDiyF3H+jKpBlRCV4jOiJ4JR33qZPVXx8ahW6brdBF9H1vdHBAyO6AeYBumKIyunXP9xzvs1qJdRNhNoVwHCwGDu7TA+U4M7G9FArDG0Y6k4LbS0Ks9zeRBMiWkW53yQlPshhtOxXCuZZOMLqk1vEvTCODYYqX5QIDAQAB"); return encrypt.encrypt(text); } function SubmitResults() { let system = "其他操作系统"; let area = "异世界"; if ($("#username").val() && _gameSettingNum === 20) { const systems = [ ['Win', 'Windows'], ['like Mac', 'iOS'], ['Mac', 'Macintosh'], ['Android', 'Android'], ['Linux', 'Linux'], ]; for (let sys of systems) { if (navigator.appVersion.indexOf(sys[0]) !== -1) { system = sys[1]; break; } } if (returnCitySN && returnCitySN['cname']) { area = returnCitySN['cname'] } let httpRequest = new XMLHttpRequest(); httpRequest.open('POST', './SubmitResults.php', true); httpRequest.setRequestHeader("Content-type", "application/json"); let name = $("#username").val(); let message = $("#message").val(); let test = "|_|"; httpRequest.send(encrypt(_gameScore + test + name + test + tj + test + system + test + area + test + message)); } } function createTimeText(n) { return '&nbsp;TIME:' + Math.ceil(n); } let _ttreg = / t{1,2}(\d+)/, _clearttClsReg = / t{1,2}\d+| bad/; function refreshGameLayer(box, loop, offset) { let i = Math.floor(Math.random() * 1000) % 4 + (loop ? 0 : 4); for (let j = 0; j < box.children.length; j++) { let r = box.children[j], rstyle = r.style; rstyle.left = (j % 4) * blockSize + 'px'; rstyle.bottom = Math.floor(j / 4) * blockSize + 'px'; rstyle.width = blockSize + 'px'; rstyle.height = blockSize + 'px'; r.className = r.className.replace(_clearttClsReg, ''); if (i === j) { _gameBBList.push({ cell: i % 4, id: r.id }); r.className += ' t' + (Math.floor(Math.random() * 1000) % 5 + 1); r.notEmpty = true; i = (Math.floor(j / 4) + 1) * 4 + Math.floor(Math.random() * 1000) % 4; } else { r.notEmpty = false; } } if (loop) { box.style.webkitTransitionDuration = '0ms'; box.style.display = 'none'; box.y = -blockSize * (Math.floor(box.children.length / 4) + (offset || 0)) * loop; setTimeout(function () { box.style[transform] = 'translate3D(0,' + box.y + 'px,0)'; setTimeout(function () { box.style.display = 'block'; }, 100); }, 200); } else { box.y = 0; box.style[transform] = 'translate3D(0,' + box.y + 'px,0)'; } box.style[transitionDuration] = '150ms'; } function gameLayerMoveNextRow() { for (let i = 0; i < GameLayer.length; i++) { let g = GameLayer[i]; g.y += blockSize; if (g.y > blockSize * (Math.floor(g.children.length / 4))) { refreshGameLayer(g, 1, -1); } else { g.style[transform] = 'translate3D(0,' + g.y + 'px,0)'; } } } function gameTapEvent(e) { if (_gameOver) { return false; } let tar = e.target; let y = e.clientY || e.targetTouches[0].clientY, x = (e.clientX || e.targetTouches[0].clientX) - body.offsetLeft, p = _gameBBList[_gameBBListIndex]; if (y > touchArea[0] || y < touchArea[1]) { return false; } if ((p.id === tar.id && tar.notEmpty) || (p.cell === 0 && x < blockSize) || (p.cell === 1 && x > blockSize && x < 2 * blockSize) || (p.cell === 2 && x > 2 * blockSize && x < 3 * blockSize) || (p.cell === 3 && x > 3 * blockSize)) { if (!_gameStart) { gameStart(); } createjs.Sound.play("tap"); tar = document.getElementById(p.id); tar.className = tar.className.replace(_ttreg, ' tt$1'); _gameBBListIndex++; _gameScore++; updatePanel(); gameLayerMoveNextRow(); } else if (_gameStart && !tar.notEmpty) { createjs.Sound.play("err"); tar.classList.add('bad'); if (mode === MODE_PRACTICE) { setTimeout(() => { tar.classList.remove('bad'); }, 500); } else { gameOver(); } } return false; } function createGameLayer() { let html = '<div id="GameLayerBG">'; for (let i = 1; i <= 2; i++) { let id = 'GameLayer' + i; html += '<div id="' + id + '" class="GameLayer">'; for (let j = 0; j < 10; j++) { for (let k = 0; k < 4; k++) { html += '<div id="' + id + '-' + (k + j * 4) + '" num="' + (k + j * 4) + '" class="block' + (k ? ' bl' : '') + '"></div>'; } } html += '</div>'; } html += '</div>'; html += '<div id="GameTimeLayer"></div>'; return html; } function closeWelcomeLayer() { welcomeLayerClosed = true; $('#welcome').css('display', 'none'); updatePanel(); } function showWelcomeLayer() { welcomeLayerClosed = false; $('#mode').text(modeToString(mode)); $('#welcome').css('display', 'block'); } function getBestScore(score) { // 练习模式不会进入算分界面 let cookieName = (mode === MODE_NORMAL ? 'bast-score' : 'endless-best-score'); let best = cookie(cookieName) ? Math.max(parseFloat(cookie(cookieName)), score) : score; cookie(cookieName, best.toFixed(2), 100); return best; } function scoreToString(score) { return mode === MODE_ENDLESS ? score.toFixed(2) : score.toString(); } function legalDeviationTime() { return deviationTime < (_gameSettingNum + 3) * 1000; } function showGameScoreLayer(cps) { let l = $('#GameScoreLayer'); let c = $(`#${_gameBBList[_gameBBListIndex - 1].id}`).attr('class').match(_ttreg)[1]; let score = (mode === MODE_ENDLESS ? cps : _gameScore); let best = getBestScore(score); l.attr('class', l.attr('class').replace(/bgc\d/, 'bgc' + c)); $('#GameScoreLayer-text').html(shareText(cps)); let normalCond = legalDeviationTime() || mode !== MODE_NORMAL; //显示CPS $('#GameScoreLayer-CPS').html('CPS&nbsp;' + cps.toFixed(2)); //获取CPS $('#GameScoreLayer-score').css('display', mode === MODE_ENDLESS ? 'none' : '') .html('得分&nbsp;' + (normalCond ? score : "<span style='color:red;'>" + score + "</span>")); $('#GameScoreLayer-bast').html('最佳&nbsp;' + scoreToString(best)); l.css('display', 'block'); } function hideGameScoreLayer() { $('#GameScoreLayer').css('display', 'none'); } w.replayBtn = function() { gameRestart(); hideGameScoreLayer(); } w.backBtn = function() { gameRestart(); hideGameScoreLayer(); showWelcomeLayer(); } function shareText(cps) { if (mode === MODE_NORMAL) { let date2 = new Date(); deviationTime = (date2.getTime() - _date1.getTime()) if (!legalDeviationTime()) { return '倒计时多了' + ((deviationTime / 1000) - 20).toFixed(2) + "s"; } SubmitResults(); } if (cps <= 3) return '逊呐'; if (cps <= 5) return '试着好好练一下'; if (cps <= 8) return '你是一个一个一个'; if (cps <= 15) return '您'; return '人?'; } function toStr(obj) { if (typeof obj === 'object') { return JSON.stringify(obj); } else { return obj; } } function cookie(name, value, time) { if (name) { if (value) { if (time) { let date = new Date(); date.setTime(date.getTime() + 864e5 * time), time = date.toGMTString(); } return document.cookie = name + "=" + escape(toStr(value)) + (time ? "; expires=" + time + (arguments[3] ? "; domain=" + arguments[3] + (arguments[4] ? "; path=" + arguments[4] + (arguments[5] ? "; secure" : "") : "") : "") : ""), !0; } return value = document.cookie.match("(?:^|;)\\s*" + name.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1") + "=([^;]*)"), value = value && "string" == typeof value[1] ? unescape(value[1]) : !1, (/^(\{|\[).+\}|\]$/.test(value) || /^[0-9]+$/g.test(value)) && eval("value=" + value), value; } let data = {}; value = document.cookie.replace(/\s/g, "").split(";"); for (let i = 0; value.length > i; i++) name = value[i].split("="), name[1] && (data[name[0]] = unescape(name[1])); return data; } document.write(createGameLayer()); function initSetting() { $("#username").val(cookie("username") ? cookie("username") : ""); $("#message").val(cookie("message") ? cookie("message") : ""); if (cookie("title")) { $('title').text(cookie('title')); } let keyboard = cookie('keyboard'); if (keyboard) { keyboard = keyboard.toString().toLowerCase(); $("#keyboard").val(keyboard); map = {} map[keyboard.charAt(0)] = 1; map[keyboard.charAt(1)] = 2; map[keyboard.charAt(2)] = 3; map[keyboard.charAt(3)] = 4; } if (cookie('gameTime')) { document.getElementById('gameTime').value = cookie('gameTime'); _gameSettingNum = parseInt(cookie('gameTime')); gameRestart(); } } w.show_btn = function() { $("#btn_group,#desc").css('display', 'block') $('#setting').css('display', 'none') } w.show_setting = function() { $('#btn_group,#desc').css('display', 'none') $('#setting').css('display', 'block') } w.save_cookie = function() { const settings = ['username', 'message', 'keyboard', 'title', 'gameTime']; for (let s of settings) { cookie(s, $(`#${s}`).val().toString(), 100); } initSetting(); } function isnull(val) { let str = val.replace(/(^\s*)|(\s*$)/g, ''); return str === '' || str === undefined || str == null; } w.goRank = function() { let name = $("#username").val(); let link = './rank.php'; if (!isnull(name)) { link += "?name=" + name; } window.location.href = link; } function click(index) { if (!welcomeLayerClosed) { return; } let p = _gameBBList[_gameBBListIndex]; let base = parseInt($(`#${p.id}`).attr("num")) - p.cell; let num = base + index - 1; let id = p.id.substring(0, 11) + num; let fakeEvent = { clientX: ((index - 1) * blockSize + index * blockSize) / 2 + body.offsetLeft, // Make sure that it is in the area clientY: (touchArea[0] + touchArea[1]) / 2, target: document.getElementById(id), }; gameTapEvent(fakeEvent); } const clickBeforeStyle = $('<style></style>'); const clickAfterStyle = $('<style></style>'); clickBeforeStyle.appendTo($(document.head)); clickAfterStyle.appendTo($(document.head)); function saveImage(dom, callback) { if (dom.files && dom.files[0]) { let reader = new FileReader(); reader.onload = function() { callback(this.result); } reader.readAsDataURL(dom.files[0]); } } w.getClickBeforeImage = function() { $('#click-before-image').click(); } w.saveClickBeforeImage = function() { const img = document.getElementById('click-before-image'); saveImage(img, r => { clickBeforeStyle.html(` .t1, .t2, .t3, .t4, .t5 { background-size: auto 100%; background-image: url(${r}); }`); }) } w.getClickAfterImage = function() { $('#click-after-image').click(); } w.saveClickAfterImage = function() { const img = document.getElementById('click-after-image'); saveImage(img, r => { clickAfterStyle.html(` .tt1, .tt2, .tt3, .tt4, .tt5 { background-size: auto 86%; background-image: url(${r}); }`); }) } }) (window);
34.254153
249
0.502934