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
28f0bc43deec1e7de2deb271015f5f88e2f0975e
1,622
js
JavaScript
node_modules/ts-morph/dist/structurePrinters/interface/ConstructSignatureDeclarationStructurePrinter.js
melanieph/mooody-test
0c515581bd0baad75e4fb9da7c9b19a73788b6ec
[ "MIT" ]
1
2021-12-28T01:54:21.000Z
2021-12-28T01:54:21.000Z
node_modules/ts-morph/dist/structurePrinters/interface/ConstructSignatureDeclarationStructurePrinter.js
melanieph/mooody-test
0c515581bd0baad75e4fb9da7c9b19a73788b6ec
[ "MIT" ]
7
2019-08-13T01:47:10.000Z
2021-11-02T15:46:32.000Z
node_modules/ts-simple-ast/dist/structurePrinters/interface/ConstructSignatureDeclarationStructurePrinter.js
udistrital/oas_cliente
ae87414eebfda72dc626d8e18c5cfe3311b007ee
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var FactoryStructurePrinter_1 = require("../FactoryStructurePrinter"); var formatting_1 = require("../formatting"); var ConstructSignatureDeclarationStructurePrinter = /** @class */ (function (_super) { tslib_1.__extends(ConstructSignatureDeclarationStructurePrinter, _super); function ConstructSignatureDeclarationStructurePrinter() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.multipleWriter = new formatting_1.NewLineFormattingStructuresPrinter(_this); return _this; } ConstructSignatureDeclarationStructurePrinter.prototype.printTexts = function (writer, structures) { this.multipleWriter.printText(writer, structures); }; ConstructSignatureDeclarationStructurePrinter.prototype.printText = function (writer, structure) { this.factory.forJSDoc().printDocs(writer, structure.docs); writer.write("new"); this.factory.forTypeParameterDeclaration().printTextsWithBrackets(writer, structure.typeParameters); writer.write("("); this.factory.forParameterDeclaration().printTexts(writer, structure.parameters); writer.write(")"); this.factory.forReturnTypedNode().printText(writer, structure); writer.write(";"); }; return ConstructSignatureDeclarationStructurePrinter; }(FactoryStructurePrinter_1.FactoryStructurePrinter)); exports.ConstructSignatureDeclarationStructurePrinter = ConstructSignatureDeclarationStructurePrinter;
55.931034
109
0.74106
28f126474f76c1aa1beed298d55909c6966920f4
644
js
JavaScript
web-client/src/presenter/actions/CourtIssuedDocketEntry/clearCourtIssuedDocketEntryFormValuesAction.js
cogentcloud/ef-cms
d6f8105bbc4e552c4764f7f2cdfbf9fb75f9594f
[ "CC0-1.0" ]
null
null
null
web-client/src/presenter/actions/CourtIssuedDocketEntry/clearCourtIssuedDocketEntryFormValuesAction.js
cogentcloud/ef-cms
d6f8105bbc4e552c4764f7f2cdfbf9fb75f9594f
[ "CC0-1.0" ]
null
null
null
web-client/src/presenter/actions/CourtIssuedDocketEntry/clearCourtIssuedDocketEntryFormValuesAction.js
cogentcloud/ef-cms
d6f8105bbc4e552c4764f7f2cdfbf9fb75f9594f
[ "CC0-1.0" ]
1
2020-04-04T10:31:46.000Z
2020-04-04T10:31:46.000Z
import { state } from 'cerebral'; /** * clears values on the court-issued docket entry form if the event code was changed * * @param {object} providers the providers object * @param {object} providers.store the cerebral store * @param {object} providers.props the cerebral props object */ export const clearCourtIssuedDocketEntryFormValuesAction = ({ props, store, }) => { if (props.key === 'eventCode') { store.unset(state.form.freeText); store.unset(state.form.judge); store.unset(state.form.docketNumbers); store.unset(state.form.month); store.unset(state.form.day); store.unset(state.form.year); } };
28
84
0.700311
28f13171aeeb072664998ca70afe3b1785bbe6da
4,885
js
JavaScript
node_modules/react-solr-connector/lib/react-solr-connector.js
SerendpityZOEY/SolrProject
a75f5ac492ffc5f8b474a3e9acdebc8f74f5bc9a
[ "Apache-2.0" ]
1
2016-08-17T16:37:08.000Z
2016-08-17T16:37:08.000Z
node_modules/react-solr-connector/lib/react-solr-connector.js
SerendpityZOEY/SolrProject
a75f5ac492ffc5f8b474a3e9acdebc8f74f5bc9a
[ "Apache-2.0" ]
null
null
null
node_modules/react-solr-connector/lib/react-solr-connector.js
SerendpityZOEY/SolrProject
a75f5ac492ffc5f8b474a3e9acdebc8f74f5bc9a
[ "Apache-2.0" ]
null
null
null
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var SolrConnector = function (_React$Component) { _inherits(SolrConnector, _React$Component); function SolrConnector(props) { _classCallCheck(this, SolrConnector); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(SolrConnector).call(this, props)); _this.state = { searchParams: props.searchParams, busy: false, error: null, response: null }; return _this; } /* * When the component mounts, do an initial search. */ _createClass(SolrConnector, [{ key: 'componentDidMount', value: function componentDidMount() { if (this.props.searchParams) { this.doSearch(this.props.searchParams); } } /* * something has changed. Update the search results. */ }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(newProps) { if (newProps.searchParams) { this.doSearch(newProps.searchParams); } } }, { key: 'doSearch', value: function doSearch(searchParams) { var _this2 = this; if (searchParams.query) { this.setState({ busy: true, error: null, searchParams: searchParams }); var params = Object.assign({ wt: "json" }, searchParams.highlightParams); var solrParams = { offset: searchParams.offset, limit: searchParams.limit, query: searchParams.query, filter: searchParams.filter, fields: searchParams.fetchFields, facet: searchParams.facet, params: params }; var reqBody = JSON.stringify(solrParams); // do the search. 'post' is required with a fetch() body. Solr doesn't mind fetch(searchParams.solrSearchUrl, { method: 'post', body: reqBody, headers: new Headers({ 'Content-Type': 'application/json' }) }).then(function (response) { if (response.ok) { return response.json(); } else { throw response.status + " " + response.statusText; } }).then(function (response) { _this2.setState({ busy: false, error: null, response: response }); }).catch(function (error) { _this2.setState({ busy: false, error: "" + error, response: null }); }); } else { // no search to perform this.setState({ busy: false, error: null, response: null }); } } }, { key: 'render', value: function render() { var solrConnector = { searchParams: this.state.searchParams, busy: this.state.busy, error: this.state.error, response: this.state.response }; var clones = _react2.default.Children.map(this.props.children, function (child) { return _react2.default.cloneElement(child, { solrConnector: solrConnector }); }); return _react2.default.createElement( 'div', null, clones ); } }]); return SolrConnector; }(_react2.default.Component); SolrConnector.propTypes = { searchParams: _react2.default.PropTypes.object }; exports.default = SolrConnector;
36.455224
564
0.648311
28f3a6b02ca518934912a953f379d765bd3499cc
7,703
js
JavaScript
src/server/config.js
surinder83singh/example-tictactoe
7b8ce809be723ce860088715f8e8baddf3a317e3
[ "MIT" ]
null
null
null
src/server/config.js
surinder83singh/example-tictactoe
7b8ce809be723ce860088715f8e8baddf3a317e3
[ "MIT" ]
null
null
null
src/server/config.js
surinder83singh/example-tictactoe
7b8ce809be723ce860088715f8e8baddf3a317e3
[ "MIT" ]
null
null
null
// @flow import {BpfLoader, Connection, Account, PublicKey, Keypair} from '@solana/web3.js'; import fs from 'mz/fs'; import path from 'path'; import semver from 'semver'; import {url, urlTls} from '../../url'; import {Store} from './store'; import {TicTacToeDashboard} from '../program/tic-tac-toe-dashboard'; import {newSystemAccountWithAirdrop} from '../util/new-system-account-with-airdrop'; const NUM_RETRIES = 500; /* allow some number of retries */ let connection; let commitment; let payer; let GREETING_SIZE; const PROGRAM_PATH = path.resolve(__dirname, '../../dist/program'); const PROGRAM_KEYPAIR_PATH = path.join(PROGRAM_PATH, 'tictactoe-keypair.json'); async function getConnection(): Promise<Object> { if (connection) return {connection, commitment}; let newConnection = new Connection(url); const version = await newConnection.getVersion(); // commitment params are only supported >= 0.21.0 const solanaCoreVersion = version['solana-core'].split(' ')[0]; if (semver.gte(solanaCoreVersion, '0.21.0')) { commitment = 'recent'; newConnection = new Connection(url, commitment); } // eslint-disable-next-line require-atomic-updates connection = newConnection; console.log('Connection to cluster established:', url, version); return {connection, commitment}; } /** * Obtain the Dashboard singleton object */ export async function findDashboard(): Promise<Object> { const store = new Store(); const {connection, commitment} = await getConnection(); const config = await store.load('../../../dist/config.json'); const dashboard = await TicTacToeDashboard.connect( connection, new Account(Buffer.from(config.secretKey, 'hex')), ); return {dashboard, connection, commitment}; } /** * Load and parse the Solana CLI config file to determine which payer to use */ export async function getPayer(): Promise<Keypair> { try { const config = await getConfig(); if (!config.keypair_path) throw new Error('Missing keypair path'); return await createKeypairFromFile(config.keypair_path); } catch (err) { console.warn( 'Failed to create keypair from CLI config file, falling back to new random keypair', ); return Keypair.generate(); } } export async function establishPayer(): Promise<void> { let fees = 0; if (!payer) { const {feeCalculator} = await connection.getRecentBlockhash(); let elf; try { elf = await fs.readFile( path.join(__dirname, '..', '..', 'dist', 'program', 'tictactoe.so'), ); } catch (err) { console.error(err); process.exit(1); return; } const balanceNeeded = feeCalculator.lamportsPerSignature * (BpfLoader.getMinNumSignatures(elf.length) + NUM_RETRIES) + (await connection.getMinimumBalanceForRentExemption(elf.length)); GREETING_SIZE = elf.length; // Calculate the cost to fund the greeter account fees += await connection.getMinimumBalanceForRentExemption(GREETING_SIZE); // Calculate the cost of sending transactions fees += feeCalculator.lamportsPerSignature * 100; // wag payer = await getPayer(); } let lamports = await connection.getBalance(payer.publicKey); if (lamports < fees) { // If current balance is not enough to pay for fees, request an airdrop const sig = await connection.requestAirdrop( payer.publicKey, fees - lamports, ); await connection.confirmTransaction(sig); lamports = await connection.getBalance(payer.publicKey); } console.log( 'Using account', payer.publicKey.toBase58(), 'containing', lamports / LAMPORTS_PER_SOL, 'SOL to pay for fees', 'LAMPORTS_PER_SOL:', LAMPORTS_PER_SOL ); } export async function createKeypairFromFile( filePath: string, ): Promise<Keypair> { const secretKeyString = await fs.readFile(filePath, {encoding: 'utf8'}); const secretKey = Uint8Array.from(JSON.parse(secretKeyString)); return Keypair.fromSecretKey(secretKey); } /** * Load the TTT program and then create the Dashboard singleton object */ export async function createDashboard(): Promise<Object> { //await establishPayer(); const store = new Store(); const {connection, commitment} = await getConnection(); /* // Derive the address (public key) of a greeting account from the program so that it's easy to find later. const GREETING_SEED = 'hello'; greetedPubkey = await PublicKey.createWithSeed( payer.publicKey, GREETING_SEED, programId, ); // Check if the greeting account has already been created const greetedAccount = await connection.getAccountInfo(greetedPubkey); if (greetedAccount === null) { console.log( 'Creating account', greetedPubkey.toBase58(), 'to say hello to', ); const lamports = await connection.getMinimumBalanceForRentExemption( GREETING_SIZE, ); const transaction = new Transaction().add( SystemProgram.createAccountWithSeed({ fromPubkey: payer.publicKey, basePubkey: payer.publicKey, seed: GREETING_SEED, newAccountPubkey: greetedPubkey, lamports, space: GREETING_SIZE, programId, }), ); await sendAndConfirmTransaction(connection, transaction, [payer]); } /* const loaderAccount = await newSystemAccountWithAirdrop( connection, balanceNeeded, ); */ //let program = new Account(); /* let attempts = 5; while (attempts > 0) { try { console.log('Loading BPF program...'); await BpfLoader.load(connection, loaderAccount, program, elf); break; } catch (err) { program = new Account(); attempts--; console.log( `Error loading BPF program, ${attempts} attempts remaining:`, err.message, ); } } if (attempts === 0) { throw new Error('Unable to load program'); } */ // Read program id from keypair file let programId; try { const programKeypair = await createKeypairFromFile(PROGRAM_KEYPAIR_PATH); programId = programKeypair.publicKey; } catch (err) { const errMsg = (err).message; throw new Error( `Failed to read program keypair at '${PROGRAM_KEYPAIR_PATH}' due to error: ${errMsg}. Program may need to be deployed with \`solana program deploy dist/program/helloworld.so\``, ); } //programId = new PublicKey('GZPhfEcYRsKEw1VWVzNMt24cYa6qcb9NzZ8hRoJpNjQ7') //;program.publicKey; console.log('Creating dashboard for programId:', programId.toString()); const dashboard = await TicTacToeDashboard.create(connection, programId); console.log('Creating dashboard for programId111:', programId.toString()); await store.save('../../../dist/config.json', { url: urlTls, commitment, secretKey: Buffer.from(dashboard._dashboardAccount.secretKey).toString( 'hex', ), }); return {dashboard, connection, commitment}; } /** * Used when invoking from the command line. First checks for existing dashboard, * if that fails, attempts to create a new one. */ export async function fetchDashboard(): Promise<Object> { try { let ret = await findDashboard(); console.log('Dashboard:', ret.dashboard.publicKey.toBase58()); return ret; } catch (err) { // ignore error, try to create instead } try { console.log("createDashboard.....") let ret = await createDashboard(); console.log('Dashboard:', ret.dashboard.publicKey.toBase58()); return ret; } catch (err) { console.error('Failed to create dashboard: ', err); throw err; } } if (require.main === module) { fetchDashboard() .then(process.exit) .catch(console.error) .then(() => 1) .then(process.exit); }
29.400763
183
0.681812
28f4540ddfd2d62ce474aa215bed35cc53c76653
822
js
JavaScript
p5/matter.js/practice/p5/sketch.js
reporeferences/angeloyeo.github.io
c249e860665b918d1144f9cc5093dbe24b384224
[ "MIT" ]
24
2019-06-16T00:33:44.000Z
2022-01-21T05:25:37.000Z
p5/matter.js/practice/p5/sketch.js
reporeferences/angeloyeo.github.io
c249e860665b918d1144f9cc5093dbe24b384224
[ "MIT" ]
null
null
null
p5/matter.js/practice/p5/sketch.js
reporeferences/angeloyeo.github.io
c249e860665b918d1144f9cc5093dbe24b384224
[ "MIT" ]
27
2019-12-11T11:28:05.000Z
2022-03-23T02:27:05.000Z
// module aliases var Engine = Matter.Engine, // Render = Matter.Render, World = Matter.World, Bodies = Matter.Bodies; var engine; var world; var circles = []; var ground; function setup() { // put setup code here createCanvas(400, 400); engine = Engine.create(); world = engine.world; options = { isStatic: true } ground = Bodies.rectangle(200, height - 50, width, 10, options); World.add(world, ground) Engine.run(engine); } function mouseDragged() { circles.push(new Circle(mouseX, mouseY, 10)) } function draw() { // put drawing code here background(100); for (i = 0; i < circles.length; i++) { circles[i].show(); } rectMode(CENTER); rect(ground.position.x, ground.position.y, width, 10); }
17.869565
69
0.591241
28f4688cf65c222cff3a083dc5ef9f86491cdcd3
1,730
js
JavaScript
src/components/index.js
cristijora/vuesax
0f24bf06c64320e00392acf37089213ff9eec5e3
[ "MIT" ]
1
2018-05-04T18:29:52.000Z
2018-05-04T18:29:52.000Z
src/components/index.js
kyokidG/vuesax
f4f58eb7e222c5bb4cfcac8600c09aebb62e30d6
[ "MIT" ]
null
null
null
src/components/index.js
kyokidG/vuesax
f4f58eb7e222c5bb4cfcac8600c09aebb62e30d6
[ "MIT" ]
null
null
null
import vsButton from './vsButton/vsButton.vue' import vsSelect from './vsSelect/vsSelect.vue' import vsNotifications from './vsNotifications/vsNotifications.js' import vsSwitch from './vsSwitch/vsSwitch.vue' import vsCheckbox from './vsCheckbox/vsCheckbox.vue' import vsRadio from './vsRadio/vsRadio.vue' import vsInput from './vsInput/vsInput.vue' import {message} from './vsMessageBox/vsMessageBox.js' import {confirm} from './vsMessageBox/vsMessageBox.js' import {prompt} from './vsMessageBox/vsMessageBox.js' import vsTabs from './vsTabs/vsTabs.vue' import vsTab from './vsTabs/vsTab.vue' import vsSlider from './vsSlider/vsSlider.vue' import vsInputNumber from './vsInputNumber/vsInputNumber.vue' import vsUpload from './vsUpload/vsUpload.vue' import {vsLoading} from './vsLoading/vsLoading.js' import {vsLoadingClose} from './vsLoading/vsLoading.js' // nuevos si terminar import vsPopup from './vsPopup/vsPopup.vue' import vsDropdown from './vsDropDown/vsDropDown.vue' import vsDropdownItem from './vsDropDown/vsDropdownItem.vue' import vsAnchor from './vsAnchor/vsAnchor.vue' import vsLink from './vsAnchor/vsLink.vue' import vsAlert from './vsAlert/vsAlert.vue' //layout import vsRow from '../layout/vsRow.vue' import vsCol from '../layout/vsCol.vue' //theme import vsTheme from '../utils/theme.js' export const vsComponents = { vsButton, vsSelect, vsSwitch, vsCheckbox, vsRadio, vsInput, vsTabs, vsTab, vsSlider, vsInputNumber, vsUpload, //nuevos sin terminar vsPopup, vsDropdown, vsDropdownItem, vsAnchor, vsLink, vsAlert, //layout vsRow, vsCol, } export const vsFunctions = { vsNotifications, message, confirm, prompt, vsLoading, vsLoadingClose, vsTheme, }
25.441176
66
0.754335
28f5ee81ba0805a2c1522eeca103c4a925e003a0
1,779
js
JavaScript
src/connectors/archive.js
lkaybob/web-scrobbler
fc33c456c0a7b1540e0b7a5b69923b414f2e658e
[ "MIT" ]
1
2015-08-28T10:56:07.000Z
2015-08-28T10:56:07.000Z
src/connectors/archive.js
lkaybob/web-scrobbler
fc33c456c0a7b1540e0b7a5b69923b414f2e658e
[ "MIT" ]
71
2020-08-04T20:25:37.000Z
2022-03-26T16:03:07.000Z
src/connectors/archive.js
lkaybob/web-scrobbler
fc33c456c0a7b1540e0b7a5b69923b414f2e658e
[ "MIT" ]
1
2021-05-13T01:16:19.000Z
2021-05-13T01:16:19.000Z
'use strict'; const artistSelectors = [ '.key-val-big a span', '.metadata-definition > dd', ]; const trackSelectors = [ '.jwrowV2.playing .ttl', '.audio-track-list .selected .track-title', ]; const numericTrackRegex = /^\d+\w+/; const tracksSelector = '.jwrowV2 .ttl'; const filter = new MetadataFilter({ track: removeNumericPrefixes }); Connector.applyFilter(filter); function removeNumericPrefixes(track) { if (hasAllTracksNumericPrefix(tracksSelector)) { return track.trim().replace(/^(\d+\w+)/, ''); } return track; } Connector.currentTimeSelector = '.jw-text-elapsed'; Connector.durationSelector = '.jw-text-duration'; Connector.isPlaying = () => { const videoElement = document.querySelector('video'); if (videoElement === null) { return false; } return !videoElement.paused; }; Connector.playerSelector = '#theatre-ia'; Connector.trackArtSelector = '#theatre-ia center > img'; Connector.getArtistTrack = () => { let track = Util.getTextFromSelectors(trackSelectors); const artist = Util.getTextFromSelectors(artistSelectors); const trackParts = track.split('-').map((item) => { return item.trim(); }); if (trackParts.length === 3 && trackParts[0] === artist) { track = trackParts[2]; } return { artist, track }; }; Connector.albumSelector = '.thats-left > h1 [itemprop=name]'; // Example: https://archive.org/details/AH003_corwin_trails_-_corwin_trails function hasAllTracksNumericPrefix(trackSelector) { const tracks = document.querySelectorAll(trackSelector); if (tracks.length === 0) { return false; } let hasAllTracksNumericPrefix = true; for (const track of tracks) { if (!numericTrackRegex.test(track.textContent)) { hasAllTracksNumericPrefix = false; break; } } return hasAllTracksNumericPrefix; }
22.2375
75
0.709949
28f750f4375616e90e1c072ffc0a5f6c09e653c6
3,138
js
JavaScript
src/adapters/aardvark.js
yingale/Prebid.js-master-3
63745cfa9ad03db0f513974045fd82b032dee759
[ "Apache-2.0" ]
null
null
null
src/adapters/aardvark.js
yingale/Prebid.js-master-3
63745cfa9ad03db0f513974045fd82b032dee759
[ "Apache-2.0" ]
null
null
null
src/adapters/aardvark.js
yingale/Prebid.js-master-3
63745cfa9ad03db0f513974045fd82b032dee759
[ "Apache-2.0" ]
null
null
null
var utils = require('../utils.js'); var bidfactory = require('../bidfactory.js'); var bidmanager = require('../bidmanager.js'); var adloader = require('../adloader'); /** * Adapter for requesting bids from RTK Aardvark * To request an RTK Aardvark Header bidding account * or for additional integration support please contact sales@rtk.io */ var AardvarkAdapter = function AardvarkAdapter() { function _callBids(params) { var rtkBids = params.bids || []; _requestBids(rtkBids); } function _requestBids(bidReqs) { let ref; try { ref = window.top.location.host; } catch (err) { ref = "thor.rtk.io"; } var ai = ""; var shortcodes = []; //build bid URL for RTK utils._each(bidReqs, function (bid) { ai = utils.getBidIdParamater('ai', bid.params); var sc = utils.getBidIdParamater('sc', bid.params); shortcodes.push(sc); }); var scURL = ""; if (shortcodes.length > 1) { scURL = shortcodes.join("_"); } else { scURL = shortcodes[0]; } var scriptUrl = '//thor.rtk.io/' + ai + "/" + scURL + "/aardvark/?jsonp=window.$$PREBID_GLOBAL$$.aardvarkResponse&rtkreferer=" + ref; adloader.loadScript(scriptUrl); } //expose the callback to the global object: window.$$PREBID_GLOBAL$$.aardvarkResponse = function (rtkResponseObj) { //Get all initial Aardvark Bid Objects var bidsObj = $$PREBID_GLOBAL$$._bidsRequested.filter(function (bidder) { return bidder.bidderCode === 'aardvark'; })[0]; var returnedBidIDs = {}; var placementIDmap = {}; if (rtkResponseObj.length > 0) { rtkResponseObj.forEach(function (bid) { if (!bid.error) { var currentBid = bidsObj.bids.filter(function (r) { return r.params.sc === bid.id; })[0]; if (currentBid) { var bidResponse = bidfactory.createBid(1); bidResponse.bidderCode = "aardvark"; bidResponse.cpm = bid.cpm; bidResponse.ad = bid.adm; bidResponse.ad += utils.createTrackPixelHtml(decodeURIComponent(bid.nurl)); bidResponse.width = currentBid.sizes[0][0]; bidResponse.height = currentBid.sizes[0][1]; returnedBidIDs[bid.id] = currentBid.placementCode; bidmanager.addBidResponse(currentBid.placementCode, bidResponse); } } }); } //All bids are back - lets add a bid response for anything that did not receive a bid. var initialSC = []; bidsObj.bids.forEach(function (bid) { initialSC.push(bid.params.sc); placementIDmap[bid.params.sc] = bid.placementCode; }); let difference = initialSC.filter(x => Object.keys(returnedBidIDs).indexOf(x) === -1); difference.forEach(function (shortcode) { var bidResponse = bidfactory.createBid(2); var placementcode = placementIDmap[shortcode]; bidResponse.bidderCode = "aardvark"; bidmanager.addBidResponse(placementcode, bidResponse); }); }; // aardvarkResponse return { callBids: _callBids }; }; module.exports = AardvarkAdapter;
27.769912
137
0.625876
28f86be97c245f27b78bd48e37e5ca8daa514390
4,076
js
JavaScript
engine/tasks/teardown/assign-pot.js
mreece/poker-holdem-engine
511dc70a6614fcb8ae6c78f20e1f763f259bb408
[ "MIT" ]
null
null
null
engine/tasks/teardown/assign-pot.js
mreece/poker-holdem-engine
511dc70a6614fcb8ae6c78f20e1f763f259bb408
[ "MIT" ]
null
null
null
engine/tasks/teardown/assign-pot.js
mreece/poker-holdem-engine
511dc70a6614fcb8ae6c78f20e1f763f259bb408
[ "MIT" ]
null
null
null
"use strict"; const task = require("../task"); const isRunning = require("../utils/is-tournament-running"); const loop = require("../utils/loop-players"); const Task = Object.create(task); Task.name = "Assign pot"; Task.shouldRun = isRunning; Task.run = async (LOGGER, tournament) => { const gamestate = tournament.gamestate; const activePlayers = gamestate.activePlayers; // Shortcut: // When there's only one active player // it gets all the pot. if (activePlayers.length === 1) { assignChips(gamestate, activePlayers[0].id, gamestate.pot); } else { if (gamestate.sidepots.length === 0) { // When there're no sidepot // I create a single sidepot, // so that I can apply the same // algorithm to assign the pot. gamestate.sidepots .push({ minChipsBet: gamestate.callAmount, pot: gamestate.pot, }); } gamestate.sidepots .forEach((sidepot) => { // For each sidepot: // only players who have bet at least // `minChipsBet` have right to compete to win `sidepot.pot` const sidepotContenders = gamestate.handRank .filter(({ playerId }) => { const player = activePlayers.find((p) => p.id === playerId); return player.chipsBet >= sidepot.minChipsBet; }); // console.log({ sidepotContenders }, gamestate); if (!sidepotContenders[0].exequo) { return assignChips(gamestate, sidepotContenders[0].playerId, sidepot.pot); } // If execution reaches this point // the value of `sidepot.pot` should be // split between 2 or more players. const tag = sidepotContenders[0].exequo; const exequoPlayers = sidepotContenders .filter(({ exequo }) => exequo === tag); const splitAmount = Math.floor(sidepot.pot / exequoPlayers.length); exequoPlayers .forEach(({ playerId }) => { assignChips(gamestate, playerId, splitAmount); }); // In case of a split pot, // the chips will be split as evenly as possible, // with any odd chip(s) left over given out // to the winning player with the worst position // (left of the button being the worst). const excidingChips = sidepot.pot % exequoPlayers.length; if (excidingChips > 0) { let assigned = false; loop(gamestate.players, gamestate.dealerPosition, (player) => { if (assigned) { return; } if (exequoPlayers.some((p) => p.id === player.id)) { assignChips(gamestate, player.id, excidingChips); assigned = true; } }); } }); } gamestate.actions = [{ type: "win", }]; await tournament.onFeed(gamestate); LOGGER.info(`Hand ${gamestate.gameProgressiveId}/${gamestate.handProgressiveId} results:\n${prepareLogMessage(gamestate.winners)}`, { tag: gamestate.handUniqueId }); }; module.exports = Task; /** * @name assignChips * @param {Object} gamestate * @param {Number} playerId * @param {Number} amount */ const assignChips = (gamestate, playerId, amount) => { const player = gamestate.activePlayers .find((p) => p.id === playerId); player.chips += amount; gamestate.pot -= amount; if (!gamestate.winners) { gamestate.winners = []; } const winner = gamestate.winners .find((w) => w.playerId === player.id); if (winner) { winner.amount += amount; } else { gamestate.winners .push({ amount, playerId, playerName: player.name, }); } }; const prepareLogMessage = (winners) => winners .reduce( (msg, winner) => `${msg}* ${winner.playerName} wins ${winner.amount}.\n`, "" ) .trim();
27.917808
169
0.556673
28f8b8369a257cfa13fa00ea7b406ee2b5acbe3f
466
js
JavaScript
assets/sap/ui/webc/main/thirdparty/types/ListMode.js
jekyll-openui5/jekyll-openui5
159bfa9a764e0f60278774690fc9b01afcaf47ca
[ "Apache-2.0" ]
null
null
null
assets/sap/ui/webc/main/thirdparty/types/ListMode.js
jekyll-openui5/jekyll-openui5
159bfa9a764e0f60278774690fc9b01afcaf47ca
[ "Apache-2.0" ]
null
null
null
assets/sap/ui/webc/main/thirdparty/types/ListMode.js
jekyll-openui5/jekyll-openui5
159bfa9a764e0f60278774690fc9b01afcaf47ca
[ "Apache-2.0" ]
null
null
null
sap.ui.define(["sap/ui/webc/common/thirdparty/base/types/DataType"],function(e){"use strict";function t(e){return e&&typeof e==="object"&&"default"in e?e["default"]:e}var n=t(e);const l={None:"None",SingleSelect:"SingleSelect",SingleSelectBegin:"SingleSelectBegin",SingleSelectEnd:"SingleSelectEnd",SingleSelectAuto:"SingleSelectAuto",MultiSelect:"MultiSelect",Delete:"Delete"};class i extends n{static isValid(e){return!!l[e]}}i.generateTypeAccessors(l);return i});
466
466
0.772532
28f8e03dda96c73acda05fecbccaa0ec2ee81928
1,238
js
JavaScript
public/scripts/svistyn_add.js
moroztaras/social-network
9fcfdb46f9e40354f54fce0542291289b3410243
[ "FTL" ]
4
2019-02-09T20:30:18.000Z
2019-06-05T13:19:59.000Z
public/scripts/svistyn_add.js
moroztaras/social-network
9fcfdb46f9e40354f54fce0542291289b3410243
[ "FTL" ]
null
null
null
public/scripts/svistyn_add.js
moroztaras/social-network
9fcfdb46f9e40354f54fce0542291289b3410243
[ "FTL" ]
null
null
null
'use strict'; (function($) { var form = $('.form-svistyn-add'); var preview = $('#svistyn_add_preview'); var imageInput = $('.svistyn-upload-image'); imageInput.fileupload({ formData: { handler: 'svistyn_image'}, done: function (e, data) { }, success: function(result, textStatus, jqXHR){ if("messages" in result){ var parent = $('.svistyn-upload-image').parent(); if(parent.find('.error-form').length <= 0){ parent.append('<div class="error-form"></div>'); } parent.find('.error-form').html('<ul class="list r-li"><li class="item">'+result['messages']['warning'][0]+'</li></ul>'); return; } if(!("image_uploaded" in result)){ return; } preview.find('.svistyn-fd--photo').html("<img src='"+result["image_uploaded"]+"?1'/>").removeClass('hide'); } }); form.find('.form-row-text textarea').on('keyup', function () { var value = $(this).val(); var textInput = $("#svistyn_add_preview").find('.svistyn-fd--text'); if(value == ''){ textInput.addClass('hide'); } else { value = value.replace(/\n/g, "<br />"); textInput.html('<p>'+value+"</p>").removeClass('hide'); } }) })(jQuery);
33.459459
129
0.557351
28f9b2e1be75628cca9f8524c6d0b7539c7c1f2b
822
js
JavaScript
cypress/integration/basicStarterTests/adminUser.spec.js
somervda/ourProbes
64fa4f1900e82cb8603237d2c027c8080ad3511f
[ "MIT" ]
null
null
null
cypress/integration/basicStarterTests/adminUser.spec.js
somervda/ourProbes
64fa4f1900e82cb8603237d2c027c8080ad3511f
[ "MIT" ]
11
2020-02-07T17:35:19.000Z
2022-02-13T00:25:23.000Z
cypress/integration/basicStarterTests/adminUser.spec.js
somervda/ourProbes
64fa4f1900e82cb8603237d2c027c8080ad3511f
[ "MIT" ]
null
null
null
// This test walks through a admin user signing in . It checks // that the email login process works and user has // the expected access to admin functionality /// <reference types="Cypress" /> context("Admin user login", () => { it("Site opens", () => { cy.visit("", { onBeforeLoad: win => { win.sessionStorage.clear(); } }); }); it("Login", () => { cy.logonEmail(Cypress.env("adminUser"), Cypress.env("adminUserPassword")); }); it("Navigate to About Page", () => { cy.verifyAboutComponent(); }); it("Navigate to Home Page", () => { cy.verifyHomeComponent(); }); it("Navigate to MyProfile", () => { cy.verifyMyProfileComponent(); }); it("Navigate to Admin", () => { cy.verifyAdmin(); }); it("Logout", () => { cy.verifyLogout(); }); });
22.833333
78
0.569343
28f9b7e2b062aa26a5e7668d5e0ddda1775544f0
913
js
JavaScript
app/scripts/services/tell_me.js
georginajuarez/AskAway
453eb1e8179a6eca8bcfa1b7f9e7e82914880e74
[ "MIT" ]
null
null
null
app/scripts/services/tell_me.js
georginajuarez/AskAway
453eb1e8179a6eca8bcfa1b7f9e7e82914880e74
[ "MIT" ]
null
null
null
app/scripts/services/tell_me.js
georginajuarez/AskAway
453eb1e8179a6eca8bcfa1b7f9e7e82914880e74
[ "MIT" ]
null
null
null
'use strict'; /** * @ngdoc service * @name askAwayApp.tellMe * @description * # tellMe * Factory in the askAwayApp. */ angular.module('askAwayApp') .factory('tellMe', function ($resource) { // Service logic // ... // Public API here return $resource('https://yesno.wtf/api', {}, { query: { method:'GET', params:{ 'answer': 'yes', 'forced': false, 'image': 'https://yesno.wtf/assets/yes/2.gif' }, isArray:false } }); }); /* YESNO PARAMS "answer": "yes", "forced": false, "image": "https://yesno.wtf/assets/yes/2.gif" return $resource('https://yesno.wtf/api?q=:location&units=imperial&APPID=YOUR_API_KEY_HERE' */ /* PER ANGULARJS DOCUMENTATION (https://docs.angularjs.org/api/ngResource/service/$resource) $resource(url, [paramDefaults], [actions], options); */
21.738095
99
0.56736
28f9b9e7249c5a35b240fccb31823a4822df3fd9
2,873
js
JavaScript
lib/common/components/MapModal.js
kdaryani/datatools-ui
1978e7d9c3c77c8eb6483ebad3ea959de4dc933d
[ "MIT" ]
27
2017-08-14T06:24:15.000Z
2021-05-26T08:22:18.000Z
lib/common/components/MapModal.js
kdaryani/datatools-ui
1978e7d9c3c77c8eb6483ebad3ea959de4dc933d
[ "MIT" ]
253
2017-03-23T17:49:52.000Z
2020-03-13T13:17:16.000Z
lib/common/components/MapModal.js
apinf/datatools-ui
b79c619fe786ce57dcbf23e7e7775822e340d758
[ "MIT" ]
13
2017-06-14T08:34:55.000Z
2018-12-16T16:11:16.000Z
// @flow import React, {Component} from 'react' import { Modal, Button } from 'react-bootstrap' import { Map, Marker, TileLayer } from 'react-leaflet' import {defaultTileURL} from '../util/maps' import type {LatLng} from '../../types' type Props = { body?: string, bounds?: [[number, number], [number, number]], initialized?: boolean, marker?: LatLng, markerSelect?: boolean, onConfirm?: any => void, rectangle?: any, rectangleSelect?: boolean, title?: string } type State = { body?: string, bounds?: [[number, number], [number, number]], draw?: boolean, marker?: LatLng, markerSelect?: boolean, onConfirm: any => void, rectangle?: any, rectangleSelect?: boolean, showModal: boolean, title: ?string } export default class MapModal extends Component<Props, State> { state = { showModal: false, onConfirm: () => {}, title: null } close = () => this.setState({showModal: false}) open (props: Props) { this.setState({ showModal: true, title: props.title, marker: props.marker, bounds: props.bounds, rectangle: props.rectangle, markerSelect: props.markerSelect, rectangleSelect: props.rectangleSelect, body: props.body, onConfirm: props.onConfirm, draw: true }) } getMap () { return this.refs.map } _onEditPath () { console.log('Path edited !') } clickHandler = (e: any) => { if (this.state.markerSelect) { this.refs.map.leafletElement.panTo(e.latlng) this.setState({marker: e.latlng}) } } ok = () => { if (this.state.markerSelect) this.state.onConfirm(this.state.marker) if (this.state.rectangleSelect) this.state.onConfirm(this.state.rectangle) else this.state.onConfirm() this.close() } render () { const {Body, Footer, Header, Title} = Modal const bounds = this.state.bounds ? this.state.bounds : [[60, -120], [0, 120]] const mapStyle = { height: '300px', width: '100%' } const marker = this.state.marker ? <Marker position={[this.state.marker.lat, this.state.marker.lng]} key={Math.random()} /> : null const MAPBOX_ATTRIBUTION = process.env.MAPBOX_ATTRIBUTION return ( <Modal show={this.state.showModal} onHide={this.close}> <Header> <Title>{this.state.title}</Title> </Header> <Body> <Map ref='map' bounds={bounds} style={mapStyle} onClick={this.clickHandler}> <TileLayer url={defaultTileURL()} attribution={MAPBOX_ATTRIBUTION} /> {marker} </Map> </Body> <Footer> <Button onClick={this.ok}>OK</Button> <Button onClick={this.close}>Cancel</Button> </Footer> </Modal> ) } }
23.357724
78
0.588583
28f9da0b0cb0586d730be4b8e3ba8bd18247f18e
468
js
JavaScript
api/config/env/index.js
yenigp/noconformidades
6c57a04dc2a1a101f9f4dbde1c39a7490810af96
[ "Apache-2.0" ]
null
null
null
api/config/env/index.js
yenigp/noconformidades
6c57a04dc2a1a101f9f4dbde1c39a7490810af96
[ "Apache-2.0" ]
7
2020-10-09T13:13:29.000Z
2022-03-02T09:32:55.000Z
api/config/env/index.js
yenigp/noconformidades
6c57a04dc2a1a101f9f4dbde1c39a7490810af96
[ "Apache-2.0" ]
null
null
null
'use strict'; var path = require('path'); var nconf = require('nconf'); /* * Setup nconf to use (in-order): * 1. Command-line arguments. * 2. Environment variables. */ nconf .argv() .env('_'); var environment = nconf.get('NODE:ENV') || 'development'; environment = environment.toLowerCase(); nconf.file(environment, path.dirname(require.main.filename) + '/config/env/' + environment + '.json'); nconf.set('env', environment); module.exports = nconf;
23.4
102
0.66453
28f9fcbf28bdc83a1796300949f4a239040577a5
10,378
js
JavaScript
assets/js/jax/output/HTML-CSS/fonts/Latin-Modern/Normal/Regular/Main.js
privapprox/privapprox.github.io
ef9864b45121101d175fc5489bb9becb731dd2e8
[ "MIT" ]
23
2018-03-29T14:50:25.000Z
2021-07-27T11:40:30.000Z
docs/js/MathJax-2.7.0/jax/output/HTML-CSS/fonts/Latin-Modern/Normal/Regular/Main.js
ip-config/dcrdocs
5af0b43244ff475f1c56e0ac974343a24ac34ec9
[ "ISC" ]
13
2021-04-06T05:03:46.000Z
2021-08-02T05:07:25.000Z
docs/js/MathJax-2.7.0/jax/output/HTML-CSS/fonts/Latin-Modern/Normal/Regular/Main.js
ip-config/dcrdocs
5af0b43244ff475f1c56e0ac974343a24ac34ec9
[ "ISC" ]
7
2018-03-30T14:48:51.000Z
2020-12-23T16:12:04.000Z
/* * /MathJax/jax/output/HTML-CSS/fonts/Latin-Modern/Normal/Regular/Main.js * * Copyright (c) 2009-2016 The MathJax Consortium * * 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. */ MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.LatinModernMathJax_Normal={directory:"Normal/Regular",family:"LatinModernMathJax_Normal",testString:"\u00A0\u210E\uD835\uDC00\uD835\uDC01\uD835\uDC02\uD835\uDC03\uD835\uDC04\uD835\uDC05\uD835\uDC06\uD835\uDC07\uD835\uDC08\uD835\uDC09\uD835\uDC0A\uD835\uDC0B\uD835\uDC0C",32:[0,0,332,0,0],160:[0,0,332,0,0],8462:[694,11,576,55,546],119808:[698,0,869,41,827],119809:[686,0,818,39,753],119810:[697,11,831,64,766],119811:[686,0,882,39,817],119812:[680,0,756,39,723],119813:[680,0,724,39,675],119814:[697,11,904,64,845],119815:[686,0,900,39,860],119816:[686,0,436,33,403],119817:[686,11,594,23,527],119818:[686,0,901,39,852],119819:[686,0,692,39,643],119820:[686,0,1092,40,1051],119821:[686,0,900,39,860],119822:[697,11,864,64,799],119823:[686,0,786,39,721],119824:[697,194,864,64,805],119825:[686,11,863,39,858],119826:[697,11,639,64,574],119827:[675,0,800,42,757],119828:[686,11,885,39,845],119829:[686,8,869,26,842],119830:[686,8,1189,24,1164],119831:[686,0,869,34,835],119832:[686,0,869,19,849],119833:[686,0,703,64,645],119834:[453,6,559,27,553],119835:[694,6,639,37,600],119836:[453,6,511,38,478],119837:[694,6,639,38,601],119838:[453,6,527,32,494],119839:[700,0,351,42,437],119840:[455,201,575,32,558],119841:[694,0,639,45,615],119842:[685,0,319,47,286],119843:[685,200,351,-56,267],119844:[694,0,607,37,587],119845:[694,0,319,47,293],119846:[450,0,958,45,935],119847:[450,0,639,45,615],119848:[453,6,575,32,542],119849:[450,194,639,37,600],119850:[450,194,607,38,601],119851:[450,0,474,37,442],119852:[453,6,454,38,415],119853:[635,6,447,21,382],119854:[450,6,639,45,615],119855:[444,4,607,26,580],119856:[444,4,831,25,805],119857:[444,0,607,22,585],119858:[444,200,607,22,580],119859:[444,0,511,32,462],119860:[716,0,750,35,721],119861:[683,0,759,42,756],119862:[705,22,715,50,760],119863:[683,0,828,40,804],119864:[680,0,738,38,763],119865:[680,0,643,38,748],119866:[705,22,786,50,760],119867:[683,0,831,39,881],119868:[683,0,440,34,497],119869:[683,22,555,71,633],119870:[683,0,849,38,889],119871:[683,0,681,39,643],119872:[683,0,970,42,1044],119873:[683,0,803,39,881],119874:[705,22,763,49,740],119875:[683,0,642,40,754],119876:[705,194,791,49,740],119877:[683,22,759,41,755],119878:[705,22,613,52,645],119879:[677,0,584,24,704],119880:[683,22,683,67,760],119881:[683,22,583,56,769],119882:[683,22,944,55,1048],119883:[683,0,828,27,851],119884:[683,0,581,35,762],119885:[683,0,683,58,723],119886:[442,11,529,40,498],119887:[694,11,429,47,415],119888:[442,11,433,41,430],119889:[694,11,520,40,516],119890:[442,11,466,46,430],119891:[705,205,490,53,552],119892:[442,205,477,15,474],119894:[661,11,345,29,293],119895:[661,205,412,-13,397],119896:[694,11,521,55,508],119897:[694,11,298,44,258],119898:[442,11,878,29,848],119899:[442,11,600,29,571],119900:[442,11,485,41,469],119901:[442,194,503,-32,490],119902:[442,194,446,40,452],119903:[442,11,451,29,436],119904:[442,11,469,52,420],119905:[626,11,361,23,330],119906:[442,11,572,29,543],119907:[442,11,485,29,468],119908:[442,11,716,29,691],119909:[442,11,572,29,527],119910:[442,205,490,29,490],119911:[442,11,465,43,467],119912:[711,0,869,45,834],119913:[686,0,866,43,854],119914:[703,17,817,55,855],119915:[686,0,938,43,915],119916:[680,0,810,43,825],119917:[680,0,689,43,809],119918:[703,17,887,55,854],119919:[686,0,982,43,1027],119920:[686,0,511,38,566],119921:[686,17,631,56,694],119922:[686,0,971,43,1003],119923:[686,0,756,43,707],119924:[686,0,1142,46,1216],119925:[686,0,950,43,1027],119926:[703,17,837,53,815],119927:[686,0,723,43,849],119928:[703,194,869,53,815],119929:[686,17,872,43,881],119930:[703,17,693,64,714],119931:[675,0,637,25,772],119932:[686,17,800,63,877],119933:[686,17,678,66,885],119934:[686,17,1093,65,1207],119935:[686,0,947,39,953],119936:[686,0,675,44,875],119937:[686,0,773,68,805],119938:[452,8,633,45,599],119939:[694,8,521,52,506],119940:[452,8,513,46,511],119941:[694,8,610,45,604],119942:[452,8,554,49,511],119943:[702,202,568,62,626],119944:[452,202,545,6,534],119945:[694,8,668,50,634],119946:[694,8,405,32,359],119947:[694,202,471,-14,450],119948:[694,8,604,50,570],119949:[694,8,348,33,288],119950:[452,8,1032,32,998],119951:[452,8,713,32,679],119952:[452,8,585,46,569],119953:[452,194,601,-15,586],119954:[452,194,542,45,543],119955:[452,8,529,32,505],119956:[452,8,531,57,476],119957:[643,8,415,25,379],119958:[452,8,681,32,647],119959:[453,8,567,32,541],119960:[453,8,831,32,797],119961:[452,8,659,38,604],119962:[452,202,590,32,582],119963:[452,8,555,42,538],120484:[442,11,322,29,293],120485:[442,205,384,-13,361],120488:[698,0,869,41,827],120489:[686,0,818,39,753],120490:[680,0,692,39,643],120491:[698,0,958,57,900],120492:[680,0,756,39,723],120493:[686,0,703,64,645],120494:[686,0,900,39,860],120495:[697,11,894,64,829],120496:[686,0,436,33,403],120497:[686,0,901,39,852],120498:[698,0,806,40,765],120499:[686,0,1092,40,1051],120500:[686,0,900,39,860],120501:[675,0,767,48,718],120502:[697,11,864,64,799],120503:[680,0,900,39,860],120504:[686,0,786,39,721],120505:[697,11,894,64,829],120506:[686,0,831,64,766],120507:[675,0,800,42,757],120508:[697,0,894,64,829],120509:[686,0,831,64,766],120510:[686,0,869,34,835],120511:[686,0,894,64,829],120512:[697,0,831,51,779],120513:[686,25,958,57,900],120514:[452,8,743,52,744],120515:[703,194,647,92,562],120516:[452,211,679,26,594],120517:[718,8,551,53,466],120518:[461,17,597,57,471],120519:[703,202,615,83,559],120520:[452,211,615,-3,555],120521:[702,8,567,52,513],120522:[452,8,359,43,361],120523:[452,8,615,59,617],120524:[694,12,618,21,663],120525:[452,211,615,59,617],120526:[452,0,583,-16,522],120527:[703,202,615,83,559],120528:[453,6,575,32,542],120529:[444,9,679,-3,610],120530:[452,211,567,59,513],120531:[452,105,551,84,499],120532:[444,8,695,52,626],120533:[444,12,615,-3,546],120534:[453,8,615,-3,563],120535:[452,216,743,51,690],120536:[452,202,743,-3,744],120537:[694,202,743,-3,690],120538:[453,8,743,51,689],120539:[711,17,679,67,610],120540:[444,8,506,78,505],120541:[702,8,615,-3,608],120542:[452,10,724,35,689],120543:[694,202,743,61,681],120544:[452,194,567,59,514],120545:[444,8,966,-3,897],120546:[716,0,750,35,721],120547:[683,0,759,42,756],120548:[680,0,615,39,720],120549:[716,0,833,49,787],120550:[680,0,738,38,763],120551:[683,0,683,58,723],120552:[683,0,831,39,881],120553:[705,22,763,49,740],120554:[683,0,440,34,497],120555:[683,0,849,38,889],120556:[716,0,694,35,666],120557:[683,0,970,42,1044],120558:[683,0,803,39,881],120559:[677,0,742,53,777],120560:[705,22,763,49,740],120561:[680,0,831,39,880],120562:[683,0,642,40,754],120563:[705,22,763,49,740],120564:[683,0,780,58,806],120565:[677,0,584,24,704],120566:[705,0,583,28,701],120567:[683,0,667,23,643],120568:[683,0,828,27,851],120569:[683,0,612,27,693],120570:[705,0,772,80,786],120571:[683,33,833,50,789],120572:[442,11,640,41,602],120573:[706,194,566,30,574],120574:[442,215,518,18,543],120575:[712,11,444,43,452],120576:[453,22,466,26,429],120577:[697,205,438,46,474],120578:[442,216,497,29,496],120579:[705,11,469,42,455],120580:[442,11,354,56,324],120581:[442,11,576,55,546],120582:[694,13,583,53,548],120583:[442,216,603,30,572],120584:[442,0,494,53,524],120585:[697,205,438,23,446],120586:[442,11,485,41,469],120587:[431,11,570,27,567],120588:[442,216,517,30,502],120589:[442,108,363,31,409],120590:[431,11,571,38,567],120591:[431,12,437,27,511],120592:[442,11,540,29,524],120593:[442,218,654,50,619],120594:[442,205,626,31,594],120595:[694,205,651,29,635],120596:[442,11,622,13,604],120597:[716,22,531,40,566],120598:[431,11,406,47,376],120599:[705,11,591,29,561],120600:[442,12,624,70,582],120601:[694,205,596,49,573],120602:[442,194,517,74,502],120603:[431,11,828,27,817],120604:[711,0,869,45,834],120605:[686,0,866,43,854],120606:[680,0,657,43,777],120607:[711,0,958,60,904],120608:[680,0,810,43,825],120609:[686,0,773,68,805],120610:[686,0,982,43,1027],120611:[703,17,867,53,844],120612:[686,0,511,38,566],120613:[686,0,971,43,1003],120614:[711,0,806,45,772],120615:[686,0,1142,46,1216],120616:[686,0,950,43,1027],120617:[675,0,841,62,867],120618:[703,17,837,53,815],120619:[680,0,982,43,1026],120620:[686,0,723,43,849],120621:[703,17,867,53,844],120622:[686,0,885,69,901],120623:[675,0,637,25,772],120624:[703,0,671,32,802],120625:[686,0,767,28,738],120626:[686,0,947,39,953],120627:[686,0,714,27,792],120628:[703,0,879,93,886],120629:[686,25,958,60,904],120630:[452,8,761,46,704],120631:[703,194,660,35,638],120632:[452,211,590,12,617],120633:[718,8,522,47,513],120634:[461,17,529,35,483],120635:[703,202,508,48,522],120636:[452,211,600,32,594],120637:[702,8,562,46,547],120638:[452,8,412,46,378],120639:[452,8,668,50,634],120640:[694,12,671,47,644],120641:[452,211,708,40,674],120642:[452,0,577,45,603],120643:[703,202,508,24,491],120644:[452,8,585,46,569],120645:[444,9,682,31,668],120646:[452,211,612,40,597],120647:[452,105,424,35,462],120648:[444,8,686,42,671],120649:[444,12,521,31,604],120650:[453,8,631,32,605],120651:[452,216,747,52,704],120652:[452,202,718,37,679],120653:[694,202,758,32,733],120654:[453,8,718,22,691],120655:[711,17,628,59,657],120656:[444,8,483,50,444],120657:[702,8,692,32,655],120658:[452,10,724,72,681],120659:[694,202,713,56,687],120660:[452,194,612,81,597],120661:[444,8,975,31,955],120782:[655,11,575,45,529],120783:[655,0,575,85,494],120784:[655,0,575,57,517],120785:[655,11,575,48,526],120786:[656,0,575,32,542],120787:[655,11,575,57,517],120788:[655,11,575,48,526],120789:[676,11,575,64,558],120790:[655,11,575,48,526],120791:[655,11,575,48,526]};MathJax.Callback.Queue(["initFont",MathJax.OutputJax["HTML-CSS"],"LatinModernMathJax_Normal"],["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Normal/Regular/Main.js"]);
518.9
9,673
0.705724
28fa0d03374c859e718bcea692aeeb82c3416c63
34,097
js
JavaScript
modules/payments/tests/server/payment.server.routes.tests.js
CASAN-TH/thamapp-server
ca2d0c473204b8459cb65d7863fd8a6a730f9a06
[ "MIT" ]
null
null
null
modules/payments/tests/server/payment.server.routes.tests.js
CASAN-TH/thamapp-server
ca2d0c473204b8459cb65d7863fd8a6a730f9a06
[ "MIT" ]
6
2016-12-15T15:58:08.000Z
2016-12-16T00:23:07.000Z
modules/payments/tests/server/payment.server.routes.tests.js
thammaratrud/ThamApp
dd68ca0bfada3c35f51195b894172f6ad57b5904
[ "MIT" ]
1
2020-09-04T13:57:55.000Z
2020-09-04T13:57:55.000Z
'use strict'; var should = require('should'), request = require('supertest'), path = require('path'), mongoose = require('mongoose'), User = mongoose.model('User'), Payment = mongoose.model('Payment'), Accountchart = mongoose.model('Accountchart'), express = require(path.resolve('./config/lib/express')); /** * Globals */ var app, agent, credentials, user, payment, payment2, paymenttest, paymenttest2, paymenttest3, accountchart, accountchart1, accountchart109, accountchart4, accountchart41, accountchart411, accountchart42, accountchart5, accountchart51, accountchart52, accountchart412, accountchart502, accountchart503; /** * Payment routes tests */ describe('Payment CRUD tests', function () { before(function (done) { // Get application app = express.init(mongoose); agent = request.agent(app); done(); }); beforeEach(function (done) { // Create user credentials credentials = { username: 'username', password: 'M3@n.jsI$Aw3$0m3' }; // Create a new user user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: credentials.username, password: credentials.password, provider: 'local' }); accountchart = new Accountchart({ accountno: '1234567', accountname: 'Account Name', user: user }); accountchart1 = new Accountchart({ accountno: '1000000', accountname: 'Balance', user: user }); accountchart109 = new Accountchart({ accountno: '1009000', accountname: 'Balance', user: user }); accountchart4 = new Accountchart({ accountno: '4000000', accountname: 'Income', user: user }); accountchart41 = new Accountchart({ accountno: '4100000', accountname: 'saleIncome', user: user }); accountchart411 = new Accountchart({ accountno: '4110001', accountname: 'saleIncome', user: user }); accountchart412 = new Accountchart({ accountno: '4120000', accountname: 'saleIncome', user: user }); accountchart42 = new Accountchart({ accountno: '4200000', accountname: 'saleIncome', user: user }); accountchart5 = new Accountchart({ accountno: '5000000', accountname: 'Expense', user: user }); accountchart51 = new Accountchart({ accountno: '5100000', accountname: 'Expense', user: user }); accountchart502 = new Accountchart({ accountno: '5020000', accountname: 'Expense', user: user }); accountchart503 = new Accountchart({ accountno: '5030000', accountname: 'Expense', user: user }); accountchart52 = new Accountchart({ accountno: '5200000', accountname: 'Expense', user: user }); payment2 = new Payment({ docno: 'AP201704', user: user }); // Save a user to the test db and create new Payment user.save(function () { accountchart1.save(); accountchart109.save(); accountchart4.save(); accountchart41.save(); accountchart411.save(); accountchart42.save(); accountchart5.save(); accountchart51.save(); accountchart52.save(); accountchart412.save(); accountchart502.save(); accountchart503.save(); accountchart.save(function () { payment = { docno: 'AP201703', docdate: '2017-03-17T04:49:37.653Z', gltype: 'AP', user: user }; done(); }); }); }); it('should be able to save a Payment if logged in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Savea new Payment agent.post('/api/payments') .send(payment) .expect(200) .end(function (paymentSaveErr, paymentSaveRes) { // Handle Payment save error if (paymentSaveErr) { return done(paymentSaveErr); } // Get a list of Payments agent.get('/api/payments') .end(function (paymentsGetErr, paymentsGetRes) { // Handle Payments save error if (paymentsGetErr) { return done(paymentsGetErr); } // Get Payments list var payments = paymentsGetRes.body; // Set assertions (payments[0].user._id).should.equal(userId); (payments[0].docno).should.match('AP201703001'); // Call the assertion callback done(); }); }); }); }); it('should not be able to save an Payment if not logged in', function (done) { agent.post('/api/payments') .send(payment) .expect(403) .end(function (paymentSaveErr, paymentSaveRes) { // Call the assertion callback done(paymentSaveErr); }); }); it('should not be able to save an Payment if docno is not duplicated', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new payment agent.post('/api/payments') .send(payment) .expect(200) .end(function (paymentSaveErr, paymentSaveRes) { // Handle payment save error if (paymentSaveErr) { return done(paymentSaveErr); } // Save a new payment agent.post('/api/payments') .send(payment2) .expect(200) .end(function (paymentSaveErr, paymentSaveRes) { // Handle payment save error if (paymentSaveErr) { return done(paymentSaveErr); } agent.post('/api/payments') .send(payment) .expect(200) .end(function (paymentSaveErr, paymentSaveRes) { // Set message assertion // (paymentSaveRes.body.message.toLowerCase()).should.endWith('docno already exists'); // Handle company save error done(); }); }); }); }); }); it('should not be able to save an Payment if no docno is provided', function (done) { // Invalidate name field payment.docno = ''; agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new Payment agent.post('/api/payments') .send(payment) .expect(200) .end(function (paymentSaveErr, paymentSaveRes) { // Set message assertion // (paymentSaveRes.body[0].docno).should.match('001'); // Handle Payment save error done(paymentSaveErr); }); }); }); it('should be able to update an Payment if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new Payment agent.post('/api/payments') .send(payment) .expect(200) .end(function (paymentSaveErr, paymentSaveRes) { // Handle Payment save error if (paymentSaveErr) { return done(paymentSaveErr); } // Update Payment name payment.docno = 'WHY YOU GOTTA BE SO MEAN?'; // Update an existing Payment agent.put('/api/payments/' + paymentSaveRes.body._id) .send(payment) .expect(200) .end(function (paymentUpdateErr, paymentUpdateRes) { // Handle Payment update error if (paymentUpdateErr) { return done(paymentUpdateErr); } // Set assertions (paymentUpdateRes.body._id).should.equal(paymentSaveRes.body._id); (paymentUpdateRes.body.docno).should.match('WHY YOU GOTTA BE SO MEAN?'); // Call the assertion callback done(); }); }); }); }); it('should be able to get a list of Payments if not signed in', function (done) { // Create new Payment model instance var paymentObj = new Payment(payment); // Save the payment paymentObj.save(function () { // Request Payments request(app).get('/api/payments') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Array).and.have.lengthOf(1); // Call the assertion callback done(); }); }); }); it('should be able to get a single Payment if not signed in', function (done) { // Create new Payment model instance var paymentObj = new Payment(payment); // Save the Payment paymentObj.save(function () { request(app).get('/api/payments/' + paymentObj._id) .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('docno', payment.docno); // Call the assertion callback done(); }); }); }); it('should return proper error for single Payment with an invalid Id, if not signed in', function (done) { // test is not a valid mongoose Id request(app).get('/api/payments/test') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('message', 'Payment is invalid'); // Call the assertion callback done(); }); }); it('should return proper error for single Payment which doesnt exist, if not signed in', function (done) { // This is a valid mongoose Id but a non-existent Payment request(app).get('/api/payments/559e9cd815f80b4c256a8f41') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('message', 'No Payment with that identifier has been found'); // Call the assertion callback done(); }); }); it('should be able to delete an Payment if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new Payment agent.post('/api/payments') .send(payment) .expect(200) .end(function (paymentSaveErr, paymentSaveRes) { // Handle Payment save error if (paymentSaveErr) { return done(paymentSaveErr); } // Delete an existing Payment agent.delete('/api/payments/' + paymentSaveRes.body._id) .send(payment) .expect(200) .end(function (paymentDeleteErr, paymentDeleteRes) { // Handle payment error error if (paymentDeleteErr) { return done(paymentDeleteErr); } // Set assertions (paymentDeleteRes.body._id).should.equal(paymentSaveRes.body._id); // Call the assertion callback done(); }); }); }); }); it('should not be able to delete an Payment if not signed in', function (done) { // Set Payment user payment.user = user; // Create new Payment model instance var paymentObj = new Payment(payment); // Save the Payment paymentObj.save(function () { // Try deleting Payment request(app).delete('/api/payments/' + paymentObj._id) .expect(403) .end(function (paymentDeleteErr, paymentDeleteRes) { // Set message assertion (paymentDeleteRes.body.message).should.match('User is not authorized'); // Handle Payment error error done(paymentDeleteErr); }); }); }); it('should be able to get a single Payment that has an orphaned user reference', function (done) { // Create orphan user creds var _creds = { username: 'orphan', password: 'M3@n.jsI$Aw3$0m3' }; // Create orphan user var _orphan = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'orphan@test.com', username: _creds.username, password: _creds.password, provider: 'local' }); _orphan.save(function (err, orphan) { // Handle save error if (err) { return done(err); } agent.post('/api/auth/signin') .send(_creds) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var orphanId = orphan._id; // Save a new Payment agent.post('/api/payments') .send(payment) .expect(200) .end(function (paymentSaveErr, paymentSaveRes) { // Handle Payment save error if (paymentSaveErr) { return done(paymentSaveErr); } // Set assertions on new Payment (paymentSaveRes.body.docno).should.equal(payment.docno + '001'); should.exist(paymentSaveRes.body.user); should.equal(paymentSaveRes.body.user._id, orphanId); // force the Payment to have an orphaned user reference orphan.remove(function () { // now signin with valid user agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (err, res) { // Handle signin error if (err) { return done(err); } // Get the Payment agent.get('/api/payments/' + paymentSaveRes.body._id) .expect(200) .end(function (paymentInfoErr, paymentInfoRes) { // Handle Payment error if (paymentInfoErr) { return done(paymentInfoErr); } // Set assertions (paymentInfoRes.body._id).should.equal(paymentSaveRes.body._id); (paymentInfoRes.body.docno).should.equal(payment.docno + '001'); should.equal(paymentInfoRes.body.user, undefined); // Call the assertion callback done(); }); }); }); }); }); }); }); it('ledger report', function (done) { var startdate = '2017-03-01'; var enddate = '2017-03-31'; paymenttest2 = new Payment({ docno: 'AP201703022', docdate: '2017-02-17T04:49:37.653Z', gltype: 'AP', credits: [{ account: accountchart1, description: 'ทดสอบ', amount: 200 }], debits: [{ account: accountchart1, description: 'ทดสอบ', amount: 200 }], user: user }); paymenttest3 = new Payment({ docno: 'AP201703033', docdate: '2017-01-17T04:49:37.653Z', gltype: 'AP', credits: [{ account: accountchart1, description: 'ทดสอบ', amount: 200 }], debits: [{ account: accountchart1, description: 'ทดสอบ', amount: 200 }], user: user }); paymenttest = new Payment({ docno: 'AP201703001', docdate: '2017-03-17T04:49:37.653Z', gltype: 'AP', credits: [{ account: accountchart1, description: 'ทดสอบ', amount: 200 }], debits: [{ account: accountchart1, description: 'ทดสอบ', amount: 200 }], user: user }); paymenttest2.save(); paymenttest3.save(); paymenttest.save(function () { agent.get('/api/ledgers/' + startdate + '/' + enddate) .expect(200) .end(function (paymentInfoErr, paymentInfoRes) { // Handle Payment error if (paymentInfoErr) { return done(paymentInfoErr); } // Set assertions (paymentInfoRes.body.startdate).should.equal('2017-03-01'); (paymentInfoRes.body.enddate).should.equal('2017-03-31'); // (paymentInfoRes.body.accounts.length).should.equal(1); (paymentInfoRes.body.accounts[0].account.accountno).should.equal('1000000'); (paymentInfoRes.body.accounts[0].account.accountname).should.equal('Balance'); (paymentInfoRes.body.accounts[0].trns.length).should.equal(2); (paymentInfoRes.body.accounts[0].trns[0].trnsno).should.equal('AP201703001'); (paymentInfoRes.body.accounts[0].trns[0].accountno).should.equal('1000000'); (paymentInfoRes.body.accounts[0].trns[0].accountname).should.equal('Balance'); (paymentInfoRes.body.accounts[0].sumcredit).should.equal(200); (paymentInfoRes.body.accounts[0].sumdebit).should.equal(200); (paymentInfoRes.body.accounts[0].bfsumdebit).should.equal(400); (paymentInfoRes.body.accounts[0].bfsumcredit).should.equal(400); // Call the assertion callback done(); }); }); }); // it('expense report', function (done) { // var startdate = '2017-03-01'; // var enddate = '2017-03-31'; // paymenttest2 = new Payment({ // docno: 'AP201703026', // docdate: '2017-03-17T04:49:37.653Z', // gltype: 'AP', // credits: [{ // account: accountchart4, // description: 'ทดสอบ', // amount: 200 // }], // debits: [{ // account: accountchart5, // description: 'ทดสอบ', // amount: 200 // }], // user: user // }); // paymenttest2.save(function () { // agent.get('/api/expenses/' + startdate + '/' + enddate) // .expect(200) // .end(function (paymentInfoErr, paymentInfoRes) { // // Handle Payment error // if (paymentInfoErr) { // return done(paymentInfoErr); // } // // Set assertions // (paymentInfoRes.body.startdate).should.equal('2017-03-01'); // (paymentInfoRes.body.enddate).should.equal('2017-03-31'); // // (paymentInfoRes.body.accounts.length).should.equal(3); // (paymentInfoRes.body.accounts[0].trns[0].accountno.substring(0, 1)).should.equal('5'); // done(); // }); // }); // }); // it('revenuereport report', function (done) { // var startdate = '2017-03-01'; // var enddate = '2017-03-31'; // paymenttest2 = new Payment({ // docno: 'AP201703027', // docdate: '2017-03-17T04:49:37.653Z', // gltype: 'AP', // credits: [{ // account: accountchart4, // description: 'ทดสอบ', // amount: 200 // }], // debits: [{ // account: accountchart5, // description: 'ทดสอบ', // amount: 200 // }], // user: user // }); // paymenttest2.save(function () { // agent.get('/api/revenues/' + startdate + '/' + enddate) // .expect(200) // .end(function (paymentInfoErr, paymentInfoRes) { // // Handle Payment error // if (paymentInfoErr) { // return done(paymentInfoErr); // } // // Set assertions // (paymentInfoRes.body.startdate).should.equal('2017-03-01'); // (paymentInfoRes.body.enddate).should.equal('2017-03-31'); // // (paymentInfoRes.body.accounts.length).should.equal(4); // (paymentInfoRes.body.accounts[0].trns[0].accountno.substring(0, 1)).should.equal('4'); // // Call the assertion callback // done(); // }); // }); // }); // it('statementincomereport report', function (done) { // var startdate = '2017-03-01'; // var enddate = '2017-03-31'; // paymenttest2 = new Payment({ // docno: 'AP201703027', // docdate: '2017-03-17T04:49:37.653Z', // gltype: 'AP', // credits: [{ // account: accountchart411, // description: 'ทดสอบ', // amount: 200 // }, { // account: accountchart412, // description: 'ทดสอบ', // amount: 200 // }, { // account: accountchart42, // description: 'ทดสอบ', // amount: 200 // }], // debits: [{ // account: accountchart502, // description: 'ทดสอบ', // amount: 200 // }, { // account: accountchart503, // description: 'ทดสอบ', // amount: 200 // }, { // account: accountchart51, // description: 'ทดสอบ', // amount: 200 // }, { // account: accountchart52, // description: 'ทดสอบ', // amount: 200 // }], // user: user // }); // paymenttest2.save(function () { // agent.get('/api/statementincomes/' + startdate + '/' + enddate) // .expect(200) // .end(function (paymentInfoErr, paymentInfoRes) { // // Handle Payment error // if (paymentInfoErr) { // return done(paymentInfoErr); // } // // Set assertions // (paymentInfoRes.body.startdate).should.equal('2017-03-01'); // (paymentInfoRes.body.enddate).should.equal('2017-03-31'); // (paymentInfoRes.body.data.saleincome.trns.length).should.equal(2); // (paymentInfoRes.body.data.saleincome.summary).should.equal(400); // (paymentInfoRes.body.data.costsell.trns.length).should.equal(2); // (paymentInfoRes.body.data.costsell.summary).should.equal(400); // (paymentInfoRes.body.data.otherincome).should.equal(200); // (paymentInfoRes.body.data.othercost).should.equal(200); // (paymentInfoRes.body.data.interestcost).should.equal(200); // (paymentInfoRes.body.data.grossprofit).should.equal(0); // (paymentInfoRes.body.data.grossprofitwithoutotherincome).should.equal(-200); // (paymentInfoRes.body.data.grossprofitwithoutinterest).should.equal(0); // (paymentInfoRes.body.data.netprofit).should.equal(-200); // // (paymentInfoRes.body.accounts[0].trns[0].accountno.substring(0, 1)).should.equal('4'); // // Call the assertion callback // done(); // }); // }); // }); it('balance report', function (done) { var startdate = '2017-03-01'; var enddate = '2017-03-31'; paymenttest2 = new Payment({ docno: 'AP201703027', docdate: '2017-03-17T04:49:37.653Z', gltype: 'AP', credits: [{ account: accountchart1, description: 'ทดสอบ', amount: 200 }, { account: accountchart109, description: 'ทดสอบ', amount: 200 }], debits: [{ account: accountchart502, description: 'ทดสอบ', amount: 200 }, { account: accountchart503, description: 'ทดสอบ', amount: 200 }, { account: accountchart51, description: 'ทดสอบ', amount: 200 }, { account: accountchart52, description: 'ทดสอบ', amount: 200 }], user: user }); paymenttest2.save(function () { agent.get('/api/balance/' + startdate + '/' + enddate) .expect(200) .end(function (paymentInfoErr, paymentInfoRes) { // Handle Payment error if (paymentInfoErr) { return done(paymentInfoErr); } // Set assertions (paymentInfoRes.body.startdate).should.equal('2017-03-01'); (paymentInfoRes.body.enddate).should.equal('2017-03-31'); // (paymentInfoRes.body.data.costsell.trns.length).should.equal(2); // (paymentInfoRes.body.data.costsell.summary).should.equal(400); // (paymentInfoRes.body.data.otherincome).should.equal(200); // (paymentInfoRes.body.data.othercost).should.equal(200); // (paymentInfoRes.body.data.interestcost).should.equal(200); // (paymentInfoRes.body.data.grossprofit).should.equal(0); // (paymentInfoRes.body.data.grossprofitwithoutotherincome).should.equal(-200); // (paymentInfoRes.body.data.grossprofitwithoutinterest).should.equal(0); // (paymentInfoRes.body.data.netprofit).should.equal(-200); // (paymentInfoRes.body.accounts[0].trns[0].accountno.substring(0, 1)).should.equal('4'); // Call the assertion callback done(); }); }); }); xit('Journal report', function (done) { var jrstartdate = '2017-03-01'; var jrenddate = '2017-03-31'; paymenttest = new Payment({ docno: 'AP201703001', docdate: '2017-03-17T04:49:37.653Z', gltype: 'AP', credits: [{ account: accountchart, description: 'ทดสอบ', amount: 200 }], debits: [{ account: accountchart, description: 'ทดสอบ', amount: 200 }], user: user }); paymenttest.save(function () { agent.get('/api/journals/' + jrstartdate + '/' + jrenddate) .expect(200) .end(function (paymentInfoErr, paymentInfoRes) { // Handle Payment error if (paymentInfoErr) { return done(paymentInfoErr); } // Set assertions // (paymentInfoRes.body).should.equal(''); (paymentInfoRes.body.jrstartdate).should.equal('2017-03-01'); (paymentInfoRes.body.jrenddate).should.equal('2017-03-31'); (paymentInfoRes.body.journals.length).should.equal(5); (paymentInfoRes.body.journals[0].gltype).should.equal('AP'); (paymentInfoRes.body.journals[0].trns.length).should.equal(2); (paymentInfoRes.body.journals[0].sumdebit).should.equal(200); (paymentInfoRes.body.journals[0].sumcredit).should.equal(200); // Call the assertion callback done(); }); }); }); afterEach(function (done) { User.remove().exec(function () { Accountchart.remove().exec(function () { Payment.remove().exec(done); }); }); }); });
37.387061
133
0.437898
28fa432dfa7bf94857517fdc9ea823613e01f60b
507
js
JavaScript
src/api/details-api.js
ilan7empest/ui
6bdb5729cf50a6a809257b8432e546d38f9b7c18
[ "Apache-2.0" ]
null
null
null
src/api/details-api.js
ilan7empest/ui
6bdb5729cf50a6a809257b8432e546d38f9b7c18
[ "Apache-2.0" ]
null
null
null
src/api/details-api.js
ilan7empest/ui
6bdb5729cf50a6a809257b8432e546d38f9b7c18
[ "Apache-2.0" ]
null
null
null
import { mainHttpClient } from '../httpClient' const detailsApi = { getJobPods: project => mainHttpClient.get(`/projects/${project}/runtime-resources?group-by=job`), getModelEndpoint: (project, uid) => mainHttpClient.get( `/projects/${project}/model-endpoints/${uid}?feature_analysis=true` ), getModelFeatureVector: (project, name, reference) => mainHttpClient.get( `/projects/${project}/feature-vectors/${name}/references/${reference}` ) } export default detailsApi
29.823529
78
0.69428
28fa71aca4ea8c475839ad71f840e180e189b96c
505
js
JavaScript
app/assets/javascripts/polyfill/console_polyfill.js
Factlink/feedforward
6015d6c9728c4b89ed63d32c9d22513bee94ba1a
[ "MIT" ]
null
null
null
app/assets/javascripts/polyfill/console_polyfill.js
Factlink/feedforward
6015d6c9728c4b89ed63d32c9d22513bee94ba1a
[ "MIT" ]
null
null
null
app/assets/javascripts/polyfill/console_polyfill.js
Factlink/feedforward
6015d6c9728c4b89ed63d32c9d22513bee94ba1a
[ "MIT" ]
null
null
null
// Console-polyfill. MIT license. // https://github.com/paulmillr/console-polyfill // Make it safe to do console.log() always. (function (con) { 'use strict'; var method; var methods = 'assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn'.split(','); con.memory = con.memory || {}; while (method = methods.pop()) con[method] = con[method] || (function() {}); })(window.console = window.console || {});
42.083333
170
0.693069
bbe96bf34f3a4df6810a038814b8295dbfe89e0b
1,383
js
JavaScript
examples/02-Project/index.js
etnetera-activate/node-minicourse
012fc1b08b33f3056cfb4abe6b0509c6922f47be
[ "MIT" ]
null
null
null
examples/02-Project/index.js
etnetera-activate/node-minicourse
012fc1b08b33f3056cfb4abe6b0509c6922f47be
[ "MIT" ]
null
null
null
examples/02-Project/index.js
etnetera-activate/node-minicourse
012fc1b08b33f3056cfb4abe6b0509c6922f47be
[ "MIT" ]
null
null
null
'use strict' var cfg = require("./config.js") var logger = cfg.logger const slack = require("./slackAPI.js") var debug = require("debug")("slack:index") var path = require('path'); const express = require('express') const app = express() //middelware var loggerMiddelware = function(req, res, next) { logger.info(`[REQUEST] ${req.originalUrl}`) next(); } app.use(loggerMiddelware); app.set('view engine', 'pug') app.set('views', path.join(__dirname, '/views')); app.get('/slack/files/all', (req, res) => { slack.getAllSlackFiles().then(files => { res.json(files) }) }) app.get('/slack/files/filter/:size/:age', (req, res) => { var size = req.params['size'] var age = req.params['age'] debug(`Getting files >${size} MB an >${age} days`); slack.getLargeOldFiles(size, age).then(files => { res.json(files) }) }) app.get('/slack/files/filter/:size/:age/html', function(req, res) { var size = req.params['size'] var age = req.params['age'] slack.getLargeOldFiles(size, age).then(files => { res.render('index', { header: `Files >${size}MB and older than ${age} days`, files: files }) }) }) var port = process.env.ENV_VARIABLE ? process.env.ENV_VARIABLE : 30009; app.listen(port, () => { logger.info('Example app listening on port: ' + port); })
28.8125
73
0.600868
bbe99bd8746d02a8e8eb7a01966708aeeb14e7c5
437
js
JavaScript
app/server/modules/friend.js
KanokwanSudleam/projectboth
fb1933401be1f2f1e74a8588d867a596d052270e
[ "MIT" ]
null
null
null
app/server/modules/friend.js
KanokwanSudleam/projectboth
fb1933401be1f2f1e74a8588d867a596d052270e
[ "MIT" ]
null
null
null
app/server/modules/friend.js
KanokwanSudleam/projectboth
fb1933401be1f2f1e74a8588d867a596d052270e
[ "MIT" ]
null
null
null
var mongoose = require('mongoose'); // mongoose.connect('mongodb://localhost/node-login', function(err) { // if (err) { // console.log(err); // } else { // console.log('Connect to mongodb') // } // }) var Schema = mongoose.Schema; var friendlist = new Schema({ username: String, list: [{ fname: String, room: String }], group: [{ type: String, ref: 'group' }] }) module.exports = mongoose.model('friendlist', friendlist);
20.809524
69
0.636156
bbe9bba66a3d06f5cc06093709dd3c7e8044afa5
87
js
JavaScript
demo1/src/js/pages/si0si.js
Lylichen/Demo
fc8ecb923d3a534984e8c7248434eaf8746361b0
[ "MIT" ]
null
null
null
demo1/src/js/pages/si0si.js
Lylichen/Demo
fc8ecb923d3a534984e8c7248434eaf8746361b0
[ "MIT" ]
null
null
null
demo1/src/js/pages/si0si.js
Lylichen/Demo
fc8ecb923d3a534984e8c7248434eaf8746361b0
[ "MIT" ]
null
null
null
import {css} from '../../css/test.css' import '../../css/view0.scss' console.log('404')
29
38
0.62069
bbea1b56a939c04540bb0e62c4796656edc5dc26
7,571
js
JavaScript
thumbnail/waiting-placeholder.js
andersonveiga/react-fine-uploader-publish
824fe5839f8924ec9f857bff12155982242b3a52
[ "MIT" ]
null
null
null
thumbnail/waiting-placeholder.js
andersonveiga/react-fine-uploader-publish
824fe5839f8924ec9f857bff12155982242b3a52
[ "MIT" ]
null
null
null
thumbnail/waiting-placeholder.js
andersonveiga/react-fine-uploader-publish
824fe5839f8924ec9f857bff12155982242b3a52
[ "MIT" ]
null
null
null
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var WaitingPlaceholder = function (_Component) { _inherits(WaitingPlaceholder, _Component); function WaitingPlaceholder() { _classCallCheck(this, WaitingPlaceholder); return _possibleConstructorReturn(this, (WaitingPlaceholder.__proto__ || Object.getPrototypeOf(WaitingPlaceholder)).apply(this, arguments)); } _createClass(WaitingPlaceholder, [{ key: 'render', value: function render() { return _react2.default.createElement( 'svg', { height: this.props.maxSize, width: this.props.maxSize, viewBox: '0 0 251 300', version: '1.1' }, _react2.default.createElement('path', { fill: '#ffffff', d: ' M 0.00 0.00 L 5.50 0.00 C 3.57 0.58 1.55 1.87 1.38 4.07 C 1.02 9.12 1.37 14.18 1.25 19.24 C 3.20 19.24 5.16 19.25 7.11 19.25 C 7.40 28.45 9.49 37.52 12.75 46.10 C 18.73 61.86 27.86 76.33 38.93 89.01 C 51.26 103.08 66.33 115.05 83.64 122.38 C 92.38 125.91 101.16 130.29 107.51 137.46 C 111.25 141.69 113.80 147.59 112.27 153.28 C 110.17 161.20 103.40 166.70 96.69 170.79 C 89.30 175.47 80.72 177.72 73.23 182.19 C 49.26 195.79 30.23 217.29 17.84 241.76 C 11.88 253.74 7.50 266.77 7.12 280.25 C 5.17 280.24 3.21 280.25 1.25 280.25 C 1.33 285.16 1.08 290.08 1.33 294.98 C 1.27 297.00 2.89 298.48 4.63 299.18 L 3.28 300.00 L 0.00 300.00 L 0.00 0.00 Z' }), _react2.default.createElement('path', { fill: '#525352', d: ' M 5.50 0.00 L 247.37 0.00 C 248.74 1.06 250.50 2.15 250.61 4.09 C 250.98 9.13 250.63 14.20 250.74 19.25 C 248.78 19.25 246.83 19.25 244.88 19.24 C 165.62 19.26 86.37 19.25 7.11 19.25 C 5.16 19.25 3.20 19.24 1.25 19.24 C 1.37 14.18 1.02 9.12 1.38 4.07 C 1.55 1.87 3.57 0.58 5.50 0.00 Z' }), _react2.default.createElement('path', { fill: '#ffffff', d: ' M 247.37 0.00 L 251.00 0.00 L 251.00 280.03 C 248.96 280.02 246.91 280.00 244.88 280.00 C 244.45 266.87 240.25 254.16 234.50 242.45 C 221.25 215.98 200.24 192.80 173.59 179.46 C 165.71 175.90 157.44 172.91 150.54 167.53 C 144.88 163.36 139.54 157.36 139.33 149.97 C 139.30 143.07 143.94 137.23 149.09 133.12 C 153.86 129.29 159.25 126.29 164.85 123.87 C 192.12 113.26 214.12 91.86 229.08 67.08 C 237.62 52.52 244.37 36.33 244.88 19.24 C 246.83 19.25 248.78 19.25 250.74 19.25 C 250.63 14.20 250.98 9.13 250.61 4.09 C 250.50 2.15 248.74 1.06 247.37 0.00 Z' }), _react2.default.createElement('path', { fill: '#bababa', d: ' M 7.11 19.25 C 86.37 19.25 165.62 19.26 244.88 19.24 C 244.37 36.33 237.62 52.52 229.08 67.08 C 214.12 91.86 192.12 113.26 164.85 123.87 C 159.25 126.29 153.86 129.29 149.09 133.12 C 143.94 137.23 139.30 143.07 139.33 149.97 C 139.54 157.36 144.88 163.36 150.54 167.53 C 157.44 172.91 165.71 175.90 173.59 179.46 C 200.24 192.80 221.25 215.98 234.50 242.45 C 240.25 254.16 244.45 266.87 244.88 280.00 C 246.91 280.00 248.96 280.02 251.00 280.03 L 251.00 300.00 L 3.28 300.00 L 4.63 299.18 C 32.74 298.76 60.88 299.12 88.99 299.00 C 141.33 298.98 193.67 299.04 246.01 298.97 C 248.39 299.36 250.34 297.28 250.43 295.00 C 250.84 290.16 250.49 285.30 250.54 280.46 C 235.08 280.04 219.61 280.35 204.14 280.24 C 204.25 271.94 200.83 262.74 192.78 259.18 C 179.36 253.86 164.31 255.95 150.76 251.10 C 146.18 249.52 142.78 245.77 140.47 241.63 C 136.29 234.23 134.05 225.89 132.66 217.56 C 129.77 193.84 127.20 169.41 132.91 145.89 C 135.79 134.35 141.55 122.37 152.34 116.37 C 169.77 109.21 183.92 95.49 193.57 79.51 C 199.34 69.89 203.67 59.09 204.10 47.77 C 151.96 47.74 99.82 47.74 47.69 47.77 C 48.53 64.72 57.24 80.21 67.92 92.97 C 76.39 102.82 86.86 111.13 98.92 116.11 C 109.46 121.51 115.24 132.92 118.35 143.87 C 124.19 165.77 122.50 188.78 119.91 211.03 C 119.06 220.86 116.79 230.67 112.47 239.57 C 109.94 244.79 105.92 249.73 100.15 251.43 C 87.83 255.43 74.51 254.35 62.11 258.03 C 57.61 259.31 53.55 262.18 51.19 266.26 C 48.40 270.33 47.98 275.36 47.70 280.13 C 34.18 280.41 20.65 280.18 7.12 280.25 C 7.50 266.77 11.88 253.74 17.84 241.76 C 30.23 217.29 49.26 195.79 73.23 182.19 C 80.72 177.72 89.30 175.47 96.69 170.79 C 103.40 166.70 110.17 161.20 112.27 153.28 C 113.80 147.59 111.25 141.69 107.51 137.46 C 101.16 130.29 92.38 125.91 83.64 122.38 C 66.33 115.05 51.26 103.08 38.93 89.01 C 27.86 76.33 18.73 61.86 12.75 46.10 C 9.49 37.52 7.40 28.45 7.11 19.25 Z' }), _react2.default.createElement('path', { fill: '#525352', d: ' M 47.69 47.77 C 99.82 47.74 151.96 47.74 204.10 47.77 C 203.67 59.09 199.34 69.89 193.57 79.51 C 183.92 95.49 169.77 109.21 152.34 116.37 C 141.55 122.37 135.79 134.35 132.91 145.89 C 127.20 169.41 129.77 193.84 132.66 217.56 C 134.05 225.89 136.29 234.23 140.47 241.63 C 142.78 245.77 146.18 249.52 150.76 251.10 C 164.31 255.95 179.36 253.86 192.78 259.18 C 200.83 262.74 204.25 271.94 204.14 280.24 C 219.61 280.35 235.08 280.04 250.54 280.46 C 250.49 285.30 250.84 290.16 250.43 295.00 C 250.34 297.28 248.39 299.36 246.01 298.97 C 193.67 299.04 141.33 298.98 88.99 299.00 C 60.88 299.12 32.74 298.76 4.63 299.18 C 2.89 298.48 1.27 297.00 1.33 294.98 C 1.08 290.08 1.33 285.16 1.25 280.25 C 3.21 280.25 5.17 280.24 7.12 280.25 C 20.65 280.18 34.18 280.41 47.70 280.13 C 47.98 275.36 48.40 270.33 51.19 266.26 C 53.55 262.18 57.61 259.31 62.11 258.03 C 74.51 254.35 87.83 255.43 100.15 251.43 C 105.92 249.73 109.94 244.79 112.47 239.57 C 116.79 230.67 119.06 220.86 119.91 211.03 C 122.50 188.78 124.19 165.77 118.35 143.87 C 115.24 132.92 109.46 121.51 98.92 116.11 C 86.86 111.13 76.39 102.82 67.92 92.97 C 57.24 80.21 48.53 64.72 47.69 47.77 Z' }) ); } }]); return WaitingPlaceholder; }(_react.Component); WaitingPlaceholder.propTypes = { maxSize: _propTypes2.default.number }; exports.default = WaitingPlaceholder;
137.654545
1,959
0.685114
bbeaf13397409458f086979dd919dd32d3a7c058
1,255
js
JavaScript
src/blocks/modules/product-slider/product-slider.js
KennyNobody/kerasfera-remastered
c5cdba6469e0fcc93101a88057f4a9488811b79e
[ "MIT" ]
null
null
null
src/blocks/modules/product-slider/product-slider.js
KennyNobody/kerasfera-remastered
c5cdba6469e0fcc93101a88057f4a9488811b79e
[ "MIT" ]
null
null
null
src/blocks/modules/product-slider/product-slider.js
KennyNobody/kerasfera-remastered
c5cdba6469e0fcc93101a88057f4a9488811b79e
[ "MIT" ]
null
null
null
import Swiper from 'swiper'; document.addEventListener('DOMContentLoaded', function() { (function initSlider() { let sliderTop = document.querySelector('.product-slider__top-slider'); let sliderThumb = document.querySelector('.product-slider__bottom-slider'); if (sliderThumb) { let length = sliderThumb.querySelectorAll('.product-slider__bottom-slide').length; if (length <= 1) { sliderThumb.classList.add('product-slider__bottom-slider--hidden'); } else { let galleryThumbs = new Swiper(sliderThumb, { spaceBetween: 16, slidesPerView: 3, watchSlidesVisibility: true, watchSlidesProgress: true, loop: true, loopedSlides: 4, slideToClickedSlide: true, centeredSlides: true, slideActiveClass: 'product-slider__bottom-slide--active' }); let galleryTop = new Swiper(sliderTop, { loop: true, loopedSlides: 4, slideActiveClass: 'product-slider__top-slide--active', thumbs: { swiper: galleryThumbs }, navigation: { nextEl: '.product-slider__btn--next', prevEl: '.product-slider__btn--prev', }, }); galleryTop.controller.control = galleryThumbs; galleryThumbs.controller.control = galleryTop; } } })(); })
27.282609
85
0.6749
bbeb43966b059dfd0b386b4dea34fff9577f3f42
56
js
JavaScript
plugin-demo.js
MaksimKniazeu/babel-plugin-console
b0ce229aafd1420c2499f088ae683e9db9fcfc42
[ "MIT" ]
null
null
null
plugin-demo.js
MaksimKniazeu/babel-plugin-console
b0ce229aafd1420c2499f088ae683e9db9fcfc42
[ "MIT" ]
null
null
null
plugin-demo.js
MaksimKniazeu/babel-plugin-console
b0ce229aafd1420c2499f088ae683e9db9fcfc42
[ "MIT" ]
null
null
null
var a = "test"; console.log(a); a = 123; console.dir(a);
14
15
0.607143
bbeb9b436f7a4b4e58d83b38dcad285829629f65
12,212
js
JavaScript
resources/plugins/datatables-select/js/dataTables.select.min.js
makkunii/trbmall
e247bc9c746b798e7a54322f44e6151df7ce3225
[ "MIT" ]
null
null
null
resources/plugins/datatables-select/js/dataTables.select.min.js
makkunii/trbmall
e247bc9c746b798e7a54322f44e6151df7ce3225
[ "MIT" ]
null
null
null
resources/plugins/datatables-select/js/dataTables.select.min.js
makkunii/trbmall
e247bc9c746b798e7a54322f44e6151df7ce3225
[ "MIT" ]
null
null
null
/*! Select for DataTables 1.3.3 2015-2021 SpryMedia Ltd - datatables.net/license/mit */ (function(e){"function"===typeof define&&define.amd?define(["jquery","datatables.net"],function(i){return e(i,window,document)}):"object"===typeof exports?module.exports=function(i,m){i||(i=window);if(!m||!m.fn.dataTable)m=require("datatables.net")(i,m).$;return e(m,i,i.document)}:e(jQuery,window,document)})(function(e,i,m,h){function x(a,c,b){var d;d=function(b,c){if(b>c)var d=c,c=b,b=d;var f=!1;return a.columns(":visible").indexes().filter(function(a){a===b&&(f=!0);return a===c?(f=!1,!0):f})};var f= function(b,c){var d=a.rows({search:"applied"}).indexes();if(d.indexOf(b)>d.indexOf(c))var f=c,c=b,b=f;var e=!1;return d.filter(function(a){a===b&&(e=!0);return a===c?(e=!1,!0):e})};!a.cells({selected:!0}).any()&&!b?(d=d(0,c.column),b=f(0,c.row)):(d=d(b.column,c.column),b=f(b.row,c.row));b=a.cells(b,d).flatten();a.cells(c,{selected:!0}).any()?a.cells(b).deselect():a.cells(b).select()}function t(a){var c=a.settings()[0]._select.selector;e(a.table().container()).off("mousedown.dtSelect",c).off("mouseup.dtSelect", c).off("click.dtSelect",c);e("body").off("click.dtSelect"+z(a.table().node()))}function A(a){var c=e(a.table().container()),b=a.settings()[0],d=b._select.selector,f;c.on("mousedown.dtSelect",d,function(b){if(b.shiftKey||b.metaKey||b.ctrlKey)c.css("-moz-user-select","none").one("selectstart.dtSelect",d,function(){return!1});i.getSelection&&(f=i.getSelection())}).on("mouseup.dtSelect",d,function(){c.css("-moz-user-select","")}).on("click.dtSelect",d,function(b){var c=a.select.items();if(f){var d=i.getSelection(); if((!d.anchorNode||e(d.anchorNode).closest("table")[0]===a.table().node())&&d!==f)return}var d=a.settings()[0],k=a.settings()[0].oClasses.sWrapper.trim().replace(/ +/g,".");if(e(b.target).closest("div."+k)[0]==a.table().container()&&(k=a.cell(e(b.target).closest("td, th")),k.any())){var g=e.Event("user-select.dt");l(a,g,[c,k,b]);g.isDefaultPrevented()||(g=k.index(),"row"===c?(c=g.row,u(b,a,d,"row",c)):"column"===c?(c=k.index().column,u(b,a,d,"column",c)):"cell"===c&&(c=k.index(),u(b,a,d,"cell",c)), d._select_lastCell=g)}});e("body").on("click.dtSelect"+z(a.table().node()),function(c){b._select.blurable&&!e(c.target).parents().filter(a.table().container()).length&&(0!==e(c.target).parents("html").length&&!e(c.target).parents("div.DTE").length)&&q(b,!0)})}function l(a,c,b,d){if(!d||a.flatten().length)"string"===typeof c&&(c+=".dt"),b.unshift(a),e(a.table().node()).trigger(c,b)}function B(a,c,b,d){var f=a[c+"s"]({search:"applied"}).indexes(),d=e.inArray(d,f),n=e.inArray(b,f);if(!a[c+"s"]({selected:!0}).any()&& -1===d)f.splice(e.inArray(b,f)+1,f.length);else{if(d>n)var g=n,n=d,d=g;f.splice(n+1,f.length);f.splice(0,d)}a[c](b,{selected:!0}).any()?(f.splice(e.inArray(b,f),1),a[c+"s"](f).deselect()):a[c+"s"](f).select()}function q(a,c){if(c||"single"===a._select.style){var b=new g.Api(a);b.rows({selected:!0}).deselect();b.columns({selected:!0}).deselect();b.cells({selected:!0}).deselect()}}function u(a,c,b,d,f){var e=c.select.style(),g=c.select.toggleable(),j=c[d](f,{selected:!0}).any();if(!j||g)"os"===e?a.ctrlKey|| a.metaKey?c[d](f).select(!j):a.shiftKey?"cell"===d?x(c,f,b._select_lastCell||null):B(c,d,f,b._select_lastCell?b._select_lastCell[d]:null):(a=c[d+"s"]({selected:!0}),j&&1===a.flatten().length?c[d](f).deselect():(a.deselect(),c[d](f).select())):"multi+shift"==e?a.shiftKey?"cell"===d?x(c,f,b._select_lastCell||null):B(c,d,f,b._select_lastCell?b._select_lastCell[d]:null):c[d](f).select(!j):c[d](f).select(!j)}function z(a){return a.id.replace(/[^a-zA-Z0-9\-\_]/g,"-")}function r(a,c){return function(b){return b.i18n("buttons."+ a,c)}}function v(a){a=a._eventNamespace;return"draw.dt.DT"+a+" select.dt.DT"+a+" deselect.dt.DT"+a}var g=e.fn.dataTable;g.select={};g.select.version="1.3.3";g.select.init=function(a){var c=a.settings()[0],b=c.oInit.select,d=g.defaults.select,b=b===h?d:b,d="row",f="api",n=!1,y=!0,j=!0,k="td, th",i="selected",s=!1;c._select={};if(!0===b)f="os",s=!0;else if("string"===typeof b)f=b,s=!0;else if(e.isPlainObject(b)&&(b.blurable!==h&&(n=b.blurable),b.toggleable!==h&&(y=b.toggleable),b.info!==h&&(j=b.info), b.items!==h&&(d=b.items),f=b.style!==h?b.style:"os",s=!0,b.selector!==h&&(k=b.selector),b.className!==h))i=b.className;a.select.selector(k);a.select.items(d);a.select.style(f);a.select.blurable(n);a.select.toggleable(y);a.select.info(j);c._select.className=i;e.fn.dataTable.ext.order["select-checkbox"]=function(b,c){return this.api().column(c,{order:"index"}).nodes().map(function(c){return"row"===b._select.items?e(c).parent().hasClass(b._select.className):"cell"===b._select.items?e(c).hasClass(b._select.className): !1})};!s&&e(a.table().node()).hasClass("selectable")&&a.select.style("os")};e.each([{type:"row",prop:"aoData"},{type:"column",prop:"aoColumns"}],function(a,c){g.ext.selector[c.type].push(function(b,a,f){var a=a.selected,e,g=[];if(!0!==a&&!1!==a)return f;for(var j=0,k=f.length;j<k;j++)e=b[c.prop][f[j]],(!0===a&&!0===e._select_selected||!1===a&&!e._select_selected)&&g.push(f[j]);return g})});g.ext.selector.cell.push(function(a,c,b){var c=c.selected,d,f=[];if(c===h)return b;for(var e=0,g=b.length;e< g;e++)d=a.aoData[b[e].row],(!0===c&&d._selected_cells&&!0===d._selected_cells[b[e].column]||!1===c&&(!d._selected_cells||!d._selected_cells[b[e].column]))&&f.push(b[e]);return f});var o=g.Api.register,p=g.Api.registerPlural;o("select()",function(){return this.iterator("table",function(a){g.select.init(new g.Api(a))})});o("select.blurable()",function(a){return a===h?this.context[0]._select.blurable:this.iterator("table",function(c){c._select.blurable=a})});o("select.toggleable()",function(a){return a=== h?this.context[0]._select.toggleable:this.iterator("table",function(c){c._select.toggleable=a})});o("select.info()",function(a){return a===h?this.context[0]._select.info:this.iterator("table",function(c){c._select.info=a})});o("select.items()",function(a){return a===h?this.context[0]._select.items:this.iterator("table",function(c){c._select.items=a;l(new g.Api(c),"selectItems",[a])})});o("select.style()",function(a){return a===h?this.context[0]._select.style:this.iterator("table",function(c){c._select.style= a;if(!c._select_init){var b=new g.Api(c);c.aoRowCreatedCallback.push({fn:function(b,a,d){a=c.aoData[d];a._select_selected&&e(b).addClass(c._select.className);b=0;for(d=c.aoColumns.length;b<d;b++)(c.aoColumns[b]._select_selected||a._selected_cells&&a._selected_cells[b])&&e(a.anCells[b]).addClass(c._select.className)},sName:"select-deferRender"});b.on("preXhr.dt.dtSelect",function(c,a){if(a===b.settings()[0]){var d=b.rows({selected:!0}).ids(!0).filter(function(b){return b!==h}),e=b.cells({selected:!0}).eq(0).map(function(a){var c= b.row(a.row).id(!0);return c?{row:c,column:a.column}:h}).filter(function(b){return b!==h});b.one("draw.dt.dtSelect",function(){b.rows(d).select();e.any()&&e.each(function(a){b.cells(a.row,a.column).select()})})}});b.on("draw.dtSelect.dt select.dtSelect.dt deselect.dtSelect.dt info.dt",function(){var a=b.settings()[0];if(a._select.info&&a.aanFeatures.i&&"api"!==b.select.style()){var c=b.rows({selected:!0}).flatten().length,d=b.columns({selected:!0}).flatten().length,g=b.cells({selected:!0}).flatten().length, h=function(a,c,d){a.append(e('<span class="select-item"/>').append(b.i18n("select."+c+"s",{_:"%d "+c+"s selected","0":"",1:"1 "+c+" selected"},d)))};e.each(a.aanFeatures.i,function(b,a){var a=e(a),f=e('<span class="select-info"/>');h(f,"row",c);h(f,"column",d);h(f,"cell",g);var i=a.children("span.select-info");i.length&&i.remove();""!==f.text()&&a.append(f)})}});b.on("destroy.dtSelect",function(){b.rows({selected:!0}).deselect();t(b);b.off(".dtSelect")})}var d=new g.Api(c);t(d);"api"!==a&&A(d);l(new g.Api(c), "selectStyle",[a])})});o("select.selector()",function(a){return a===h?this.context[0]._select.selector:this.iterator("table",function(c){t(new g.Api(c));c._select.selector=a;"api"!==c._select.style&&A(new g.Api(c))})});p("rows().select()","row().select()",function(a){var c=this;if(!1===a)return this.deselect();this.iterator("row",function(b,a){q(b);b.aoData[a]._select_selected=!0;e(b.aoData[a].nTr).addClass(b._select.className)});this.iterator("table",function(b,a){l(c,"select",["row",c[a]],!0)}); return this});p("columns().select()","column().select()",function(a){var c=this;if(!1===a)return this.deselect();this.iterator("column",function(b,a){q(b);b.aoColumns[a]._select_selected=!0;var c=(new g.Api(b)).column(a);e(c.header()).addClass(b._select.className);e(c.footer()).addClass(b._select.className);c.nodes().to$().addClass(b._select.className)});this.iterator("table",function(b,a){l(c,"select",["column",c[a]],!0)});return this});p("cells().select()","cell().select()",function(a){var c=this; if(!1===a)return this.deselect();this.iterator("cell",function(b,a,c){q(b);a=b.aoData[a];a._selected_cells===h&&(a._selected_cells=[]);a._selected_cells[c]=!0;a.anCells&&e(a.anCells[c]).addClass(b._select.className)});this.iterator("table",function(a,d){l(c,"select",["cell",c.cells(c[d]).indexes().toArray()],!0)});return this});p("rows().deselect()","row().deselect()",function(){var a=this;this.iterator("row",function(a,b){a.aoData[b]._select_selected=!1;a._select_lastCell=null;e(a.aoData[b].nTr).removeClass(a._select.className)}); this.iterator("table",function(c,b){l(a,"deselect",["row",a[b]],!0)});return this});p("columns().deselect()","column().deselect()",function(){var a=this;this.iterator("column",function(a,b){a.aoColumns[b]._select_selected=!1;var d=new g.Api(a),f=d.column(b);e(f.header()).removeClass(a._select.className);e(f.footer()).removeClass(a._select.className);d.cells(null,b).indexes().each(function(b){var d=a.aoData[b.row],f=d._selected_cells;d.anCells&&(!f||!f[b.column])&&e(d.anCells[b.column]).removeClass(a._select.className)})}); this.iterator("table",function(c,b){l(a,"deselect",["column",a[b]],!0)});return this});p("cells().deselect()","cell().deselect()",function(){var a=this;this.iterator("cell",function(a,b,d){b=a.aoData[b];b._selected_cells[d]=!1;b.anCells&&!a.aoColumns[d]._select_selected&&e(b.anCells[d]).removeClass(a._select.className)});this.iterator("table",function(c,b){l(a,"deselect",["cell",a[b]],!0)});return this});var w=0;e.extend(g.ext.buttons,{selected:{text:r("selected","Selected"),className:"buttons-selected", limitTo:["rows","columns","cells"],init:function(a,c,b){var d=this;b._eventNamespace=".select"+w++;a.on(v(b),function(){d.enable(-1!==e.inArray("rows",b.limitTo)&&a.rows({selected:!0}).any()||-1!==e.inArray("columns",b.limitTo)&&a.columns({selected:!0}).any()||-1!==e.inArray("cells",b.limitTo)&&a.cells({selected:!0}).any()?!0:!1)});this.disable()},destroy:function(a,c,b){a.off(b._eventNamespace)}},selectedSingle:{text:r("selectedSingle","Selected single"),className:"buttons-selected-single",init:function(a, c,b){var d=this;b._eventNamespace=".select"+w++;a.on(v(b),function(){var b=a.rows({selected:!0}).flatten().length+a.columns({selected:!0}).flatten().length+a.cells({selected:!0}).flatten().length;d.enable(1===b)});this.disable()},destroy:function(a,c,b){a.off(b._eventNamespace)}},selectAll:{text:r("selectAll","Select all"),className:"buttons-select-all",action:function(){this[this.select.items()+"s"]().select()}},selectNone:{text:r("selectNone","Deselect all"),className:"buttons-select-none",action:function(){q(this.settings()[0], !0)},init:function(a,c,b){var d=this;b._eventNamespace=".select"+w++;a.on(v(b),function(){var b=a.rows({selected:!0}).flatten().length+a.columns({selected:!0}).flatten().length+a.cells({selected:!0}).flatten().length;d.enable(0<b)});this.disable()},destroy:function(a,c,b){a.off(b._eventNamespace)}}});e.each(["Row","Column","Cell"],function(a,c){var b=c.toLowerCase();g.ext.buttons["select"+c+"s"]={text:r("select"+c+"s","Select "+b+"s"),className:"buttons-select-"+b+"s",action:function(){this.select.items(b)}, init:function(a){var c=this;a.on("selectItems.dt.DT",function(a,d,e){c.active(e===b)})}}});e(m).on("preInit.dt.dtSelect",function(a,c){"dt"===a.namespace&&g.select.init(new g.Api(c))});return g.select});
421.103448
539
0.666885
bbed0a815388e4c5b0b34de211b4b6035970ab91
723
js
JavaScript
src/dream-team.js
webdevsnarsky/basic-js
33409338737f0931da64bdf9c75d6259d46bb426
[ "MIT" ]
null
null
null
src/dream-team.js
webdevsnarsky/basic-js
33409338737f0931da64bdf9c75d6259d46bb426
[ "MIT" ]
null
null
null
src/dream-team.js
webdevsnarsky/basic-js
33409338737f0931da64bdf9c75d6259d46bb426
[ "MIT" ]
null
null
null
const CustomError = require("../extensions/custom-error"); module.exports = function createDreamTeam(members) { if (typeof(members) === 'number' || typeof(members) === 'boolean' || !members || Array.isArray(members) === false) { return false; } if (members == []) { throw new UserException("error"); } let k = ''; members.forEach(elem => { if (typeof(elem) === 'number' || typeof(elem) === 'boolean' || typeof(elem) === 'object' || elem === null || elem === undefined) { return false; } else { k += elem.trim().toUpperCase().replace(/\s+/g, '').split('').slice(0,1).join(''); }; }); let result = k.split('').sort().join(''); return result; };
25.821429
134
0.544952
bbeead1ca196d74745e587838497b302bd348dec
6,828
js
JavaScript
src/views/dashboard/dashboard-component/TotalGrowthBarChart.js
nParkFitness/NParkFitnessReact
96d4368e7e180e2a5b7de0b6d75bef59654b1ae9
[ "MIT" ]
null
null
null
src/views/dashboard/dashboard-component/TotalGrowthBarChart.js
nParkFitness/NParkFitnessReact
96d4368e7e180e2a5b7de0b6d75bef59654b1ae9
[ "MIT" ]
null
null
null
src/views/dashboard/dashboard-component/TotalGrowthBarChart.js
nParkFitness/NParkFitnessReact
96d4368e7e180e2a5b7de0b6d75bef59654b1ae9
[ "MIT" ]
null
null
null
import PropTypes from 'prop-types'; import React from 'react'; // material-ui import { Grid, MenuItem, TextField, Typography, useTheme } from '@material-ui/core'; // third-party import ApexCharts from 'apexcharts'; import Chart from 'react-apexcharts'; // project imports import SkeletonTotalGrowthBarChart from 'ui-component/cards/Skeleton/TotalGrowthBarChart'; import MainCard from 'ui-component/cards/MainCard'; import { gridSpacing } from 'store/constant'; // chart data // import chartData from './chart-data/total-growth-bar-chart'; const status = [ { value: 'today', label: 'Today' }, { value: 'month', label: 'This Month' }, { value: 'year', label: 'This Year' } ]; // ===========================|| DASHBOARD DEFAULT - TOTAL GROWTH BAR CHART ||=========================== // const TotalGrowthBarChart = ({ isLoading, incomeData }) => { const [value, setValue] = React.useState('today'); const theme = useTheme(); console.log(incomeData); const { primary } = theme.palette.text; const grey200 = theme.palette.grey[200]; const primary200 = theme.palette.primary[200]; const primaryDark = theme.palette.primary.dark; const secondaryMain = theme.palette.secondary.main; const secondaryLight = theme.palette.secondary.light; const grey500 = theme.palette.grey[500]; const month = parseInt(new Date().toISOString().slice(5, 7), 10); let totalGrowth = 0; if (incomeData !== undefined && incomeData.length > 0) { totalGrowth = incomeData[month - 1]; } const chartData = { height: 480, type: 'bar', options: { chart: { id: 'bar-chart', stacked: true, toolbar: { show: true }, zoom: { enabled: true } }, responsive: [ { breakpoint: 480, options: { legend: { position: 'bottom', offsetX: -10, offsetY: 0 } } } ], plotOptions: { bar: { horizontal: false, columnWidth: '50%' } }, xaxis: { type: 'category', categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, legend: { show: true, fontSize: '14px', fontFamily: `'Roboto', sans-serif`, position: 'bottom', offsetX: 20, labels: { useSeriesColors: false }, markers: { width: 16, height: 16, radius: 5 }, itemMargin: { horizontal: 15, vertical: 8 } }, fill: { type: 'solid' }, dataLabels: { enabled: false }, grid: { show: true } }, series: [ { name: 'Income', data: incomeData } ] }; React.useEffect(() => { const newChartData = { ...chartData.options, colors: [secondaryMain, primaryDark, secondaryMain, secondaryLight], xaxis: { labels: { style: { colors: [primary, primary, primary, primary, primary, primary, primary, primary, primary, primary, primary, primary] } } }, yaxis: { labels: { style: { colors: [primary] } } }, grid: { borderColor: grey200 }, tooltip: { theme: 'light' }, legend: { labels: { colors: grey500 } } }; // do not load chart when loading if (!isLoading) { ApexCharts.exec(`bar-chart`, 'updateOptions', newChartData); } }, [secondaryMain, primaryDark, secondaryMain, secondaryLight, primary, grey200, isLoading, grey500]); return ( <> {isLoading ? ( <SkeletonTotalGrowthBarChart /> ) : ( <MainCard> <Grid container spacing={gridSpacing}> <Grid item xs={12}> <Grid container alignItems="center" justifyContent="space-between"> <Grid item> <Grid container direction="column" spacing={1}> <Grid item> <Typography variant="subtitle2">Total Growth</Typography> </Grid> <Grid item> <Typography variant="h3">Rs {totalGrowth}</Typography> </Grid> </Grid> </Grid> <Grid item> <TextField id="standard-select-currency" select value={value} onChange={(e) => setValue(e.target.value)} > {status.map((option) => ( <MenuItem key={option.value} value={option.value}> {option.label} </MenuItem> ))} </TextField> </Grid> </Grid> </Grid> <Grid item xs={12}> <Chart {...chartData} /> </Grid> </Grid> </MainCard> )} </> ); }; TotalGrowthBarChart.propTypes = { isLoading: PropTypes.bool }; export default TotalGrowthBarChart;
31.611111
140
0.38225
bbef5ff55d06df5a3452daaaf042ef6ad4946ab3
1,504
js
JavaScript
example/.temp/internal/page-components.js
iewihc/iewihc.github.io
327a7c61932d3b27526142dcf5c2f56b48d15941
[ "MIT" ]
null
null
null
example/.temp/internal/page-components.js
iewihc/iewihc.github.io
327a7c61932d3b27526142dcf5c2f56b48d15941
[ "MIT" ]
null
null
null
example/.temp/internal/page-components.js
iewihc/iewihc.github.io
327a7c61932d3b27526142dcf5c2f56b48d15941
[ "MIT" ]
4
2019-12-03T07:41:07.000Z
2020-06-20T06:00:49.000Z
/** * Generated by "@vuepress/internal-page-components" */ export default { "v-6e25d6ba": () => import("D:\\im\\vuepress-theme-blog\\example\\_posts\\2018-11-7-frontmatter-in-vuepress-2.md"), "v-c4996c90": () => import("D:\\im\\vuepress-theme-blog\\example\\_posts\\2018-11-7-frontmatter-in-vuepress-3.md"), "v-4dea2604": () => import("D:\\im\\vuepress-theme-blog\\example\\_posts\\2018-11-7-frontmatter-in-vuepress.md"), "v-a98f42c4": () => import("D:\\im\\vuepress-theme-blog\\example\\_posts\\2019-2-26-markdown-slot-2.md"), "v-975b2748": () => import("D:\\im\\vuepress-theme-blog\\example\\_posts\\2019-2-26-markdown-slot-3.md"), "v-85270bcc": () => import("D:\\im\\vuepress-theme-blog\\example\\_posts\\2019-2-26-markdown-slot-4.md"), "v-f23574b0": () => import("D:\\im\\vuepress-theme-blog\\example\\_posts\\2019-2-26-markdown-slot.md"), "v-42723820": () => import("D:\\im\\vuepress-theme-blog\\example\\_posts\\2019-5-6-writing-a-vuepress-theme-2.md"), "v-0e5456ee": () => import("D:\\im\\vuepress-theme-blog\\example\\_posts\\2019-5-6-writing-a-vuepress-theme-3.md"), "v-3de1c9ec": () => import("D:\\im\\vuepress-theme-blog\\example\\_posts\\2019-5-6-writing-a-vuepress-theme-4.md"), "v-5a7f890c": () => import("D:\\im\\vuepress-theme-blog\\example\\_posts\\2019-5-6-writing-a-vuepress-theme.md"), "v-28d78ae0": () => import("D:\\im\\vuepress-theme-blog\\example\\_posts\\cicddevops.md"), "v-6ba0aea3": () => import("D:\\im\\vuepress-theme-blog\\example\\about.md") }
83.555556
117
0.65758
bbefd70c8078379ac6ff4bbb567f00e045bad658
1,054
js
JavaScript
tvshowfantest/admin/modules/tvshow/tvShowListItemView.js
uslperera/TVShowFanTest
1281e81fee1e98a0bb940f90c2e0c8f06c8261f2
[ "MIT" ]
null
null
null
tvshowfantest/admin/modules/tvshow/tvShowListItemView.js
uslperera/TVShowFanTest
1281e81fee1e98a0bb940f90c2e0c8f06c8261f2
[ "MIT" ]
null
null
null
tvshowfantest/admin/modules/tvshow/tvShowListItemView.js
uslperera/TVShowFanTest
1281e81fee1e98a0bb940f90c2e0c8f06c8261f2
[ "MIT" ]
null
null
null
var TVShowListItemView = Backbone.View.extend({ tagName: 'tr', initialize: function(options) { this.tvShow = options.tvShow; this.template = _.template(templates['tvShowListItemView']); //if tvshow is changed render the view var self = this; this.tvShow.bind("change", function() { self.render(); }); }, render: function() { this.$el.html(this.template({ tvShow: this.tvShow.toJSON() })); return this; }, events: { 'click #editTVShow': 'editTVShow', 'click #deleteTVShow': 'deleteTVShow' }, editTVShow: function() { var tvShowView = new TVShowView({ model: this.tvShow }); $("#modal").html(tvShowView.el); }, deleteTVShow: function() { var tvShow = this.tvShow; //show confirm message var confirmMessage = new ConfirmMessage({ message: { title: 'TV Show', body: 'Are you sure you want to delete?' }, callback: function() { tvShow.destroy(); } }); $("#modal").html(confirmMessage.el); } });
24.511628
64
0.591082
bbf08ecdc2ab8e35d63f532f38c807746bcbee06
1,267
js
JavaScript
mozmill-env/msys/firefox/tests/functional/testSearch/testAddMozSearchProvider.js
lucashmorais/x-Bench
2080b8753dd6e45c2212666bcdb05327752a94e9
[ "MIT" ]
null
null
null
mozmill-env/msys/firefox/tests/functional/testSearch/testAddMozSearchProvider.js
lucashmorais/x-Bench
2080b8753dd6e45c2212666bcdb05327752a94e9
[ "MIT" ]
null
null
null
mozmill-env/msys/firefox/tests/functional/testSearch/testAddMozSearchProvider.js
lucashmorais/x-Bench
2080b8753dd6e45c2212666bcdb05327752a94e9
[ "MIT" ]
null
null
null
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; // Include necessary modules var search = require("../../../lib/search"); const BASE_URL = collector.addHttpResource("../../../../data/"); const SEARCH_ENGINE = { name : "mozqa.com", url : BASE_URL + "search/mozsearch.html" }; var setupModule = function(aModule) { aModule.controller = mozmill.getBrowserController(); aModule.engineManager = new search.engineManager(aModule.controller); aModule.searchBar = new search.searchBar(aModule.controller); } var teardownModule = function(aModule) { aModule.searchBar.removeEngine(SEARCH_ENGINE.name); aModule.searchBar.restoreDefaultEngines(); } /** * Add a MozSearch Search plugin */ var testAddMozSearchPlugin = function() { engineManager.installFromUrl(SEARCH_ENGINE.name, SEARCH_ENGINE.url, function () { var addButton = new elementslib.Name(controller.tabs.activeTab, "add"); controller.click(addButton); }); // Select search engine and start a search searchBar.selectedEngine = SEARCH_ENGINE.name; searchBar.search({text: "Firefox", action: "goButton"}); }
31.675
83
0.725335
bbf0f50793c092d2adc3118366274907a8f732d8
1,466
js
JavaScript
packages/cli/src/commands/migrations/entity.yml.js
sky-uk/uiengine
ba96f28a18f39198af5f819fad22b53f4e047e50
[ "MIT" ]
null
null
null
packages/cli/src/commands/migrations/entity.yml.js
sky-uk/uiengine
ba96f28a18f39198af5f819fad22b53f4e047e50
[ "MIT" ]
null
null
null
packages/cli/src/commands/migrations/entity.yml.js
sky-uk/uiengine
ba96f28a18f39198af5f819fad22b53f4e047e50
[ "MIT" ]
null
null
null
const { basename, dirname, join } = require('path') const Core = require('@uiengine/core/src/core') const glob = require('globby') const prettier = require('prettier') const YamlUtil = require('../../yaml') const { FileUtil: { write, remove }, MessageUtil: { reportSuccess, reportError, reportInfo }, StringUtil: { crossPlatformPath } } = require('@uiengine/util') exports.describe = 'Replaces Entity.yml files with Entity.js' exports.handler = async argv => { try { const state = await Core.init(argv) const { config: { source } } = state const { entities } = source if (!entities) return const pattern = crossPlatformPath(join(entities, '**', '*.yml')) const filePaths = await glob(pattern, { onlyFiles: true }) filePaths.forEach(async ymlPath => { const entityPath = dirname(ymlPath) const jsPath = join(entityPath, `${basename(ymlPath, '.yml')}.js`) const attributes = await YamlUtil.fromFile(ymlPath) await Promise.all([ write(jsPath, prettier.format(`module.exports = ${JSON.stringify(attributes, null, 2)}`)) ]) await remove(ymlPath) }) if (filePaths.length > 0) { reportSuccess('The Entity.yml files have been replaced with Entity.js files.') } else { reportInfo('No Entity.yml files to migrate.', { icon: 'ℹ️', transient: false }) } } catch (err) { reportError('Migrating the component.md files failed!', err) process.exit(1) } }
31.869565
97
0.652115
bbf1863a0cc5b3da29cbe72c0be9e3275d466697
598
js
JavaScript
magento2ce/dev/tests/js/jasmine/tests/app/code/Magento/Ui/base/js/grid/columns/select.test.js
downjse/magento2
7bebd5c24d613426159638cd5f7b6b927a017fb4
[ "MIT" ]
null
null
null
magento2ce/dev/tests/js/jasmine/tests/app/code/Magento/Ui/base/js/grid/columns/select.test.js
downjse/magento2
7bebd5c24d613426159638cd5f7b6b927a017fb4
[ "MIT" ]
null
null
null
magento2ce/dev/tests/js/jasmine/tests/app/code/Magento/Ui/base/js/grid/columns/select.test.js
downjse/magento2
7bebd5c24d613426159638cd5f7b6b927a017fb4
[ "MIT" ]
null
null
null
/** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ /*eslint max-nested-callbacks: 0*/ define([ 'Magento_Ui/js/grid/columns/select' ], function (Select) { 'use strict'; describe('Ui/js/grid/columns/select', function () { var select; beforeEach(function () { select = new Select(); }); describe('getLabel method', function () { it('get label while options empty', function () { expect(select.getLabel(2)).toBe(''); }); }); }); });
23
61
0.545151
bbf226daaa3483a3827f891b1510bc49b6a500ab
20,751
js
JavaScript
src/Future.js
sidemash/utilidade-js
761a40d10e8f704f744fe776ae8e6d0cf42b9a0b
[ "MIT" ]
null
null
null
src/Future.js
sidemash/utilidade-js
761a40d10e8f704f744fe776ae8e6d0cf42b9a0b
[ "MIT" ]
null
null
null
src/Future.js
sidemash/utilidade-js
761a40d10e8f704f744fe776ae8e6d0cf42b9a0b
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const lodash_1 = require("lodash"); const Try_1 = require("./Try"); const Option_1 = require("./Option"); const Exception_1 = require("./Exception"); class Future { constructor(_promiseOption, _tryOption) { this._promiseOption = _promiseOption; this._tryOption = _tryOption; this.completeFunctionSubscribers = []; } init(promiseOption) { return (this._setPromiseOption(promiseOption.map(promise => promise .then(value => { this._onSuccess(value); return value; }) .catch(error => { this._onFailure(Exception_1.Exception.createFrom(error)); return error; })))); } static foreverPending() { return Future._foreverPending; } static neverCompleted() { return Future.foreverPending(); } static all(futures) { return Future.fromPromise(Promise.all(futures.map(future => future.toPromise()))); } static firstCompletedOf(futures) { if (futures.length == 0) return Future.foreverPending(); else return (Future.fromPromise(Promise.race(futures.map(future => future.toPromise())))); } static lastCompletedOf(futures) { if (futures.length == 0) return Future.foreverPending(); let nbCompleted = 0; return (Future.fromPromise(new Promise((resolve, reject) => { futures.forEach(f => f.onComplete({ ifSuccess: value => { nbCompleted += 1; if (nbCompleted == futures.length) { resolve(value); } }, ifFailure: ex => { nbCompleted += 1; if (nbCompleted == futures.length) { reject(ex); } } })); }))); } static lazyFrom(f) { return Future.lazyFromFuture(() => Future.from(f)); } static lazyFromFuture(f) { return new LazyFutureImpl(f); } static lazyFromPromise(promise) { return Future.lazyFromFuture(() => Future.fromPromise(promise)); } static lazyFromPromiseFn(fn) { return Future.lazyFromFuture(() => Future.fromPromiseFn(fn)); } static fromPromiseFn(fn) { try { const promise = fn(); return Future.fromPromise(promise); } catch (error) { return Future.fromPromise(Promise.reject(error)); } } static fromPromise(promise) { const promiseOption = Option_1.Option.of(promise); const future = new Future(promiseOption, Option_1.Option.empty()); return future.init(promiseOption); } static startAfter(timeout, fn) { const f = Future.fromPromise(new Promise((resolve, reject) => { setTimeout(() => { try { const value = fn(); resolve(value); } catch (error) { reject(error); } }, timeout); })); return f.flatMap(ft => ft); } static executeAfter(timeout, fn) { return Future.fromPromise(new Promise((resolve, reject) => { setTimeout(() => { try { const value = fn(); resolve(value); } catch (error) { reject(error); } }, timeout); })); } static from(fn, executeFnInNewThread = true) { if (executeFnInNewThread) { return Future.fromPromise(new Promise((resolve, reject) => { try { const value = fn(); resolve(value); } catch (error) { reject(error); } })); } else { try { const value = fn(); return Future.successful(value); } catch (error) { return Future.failed(error); } } } static fromFuture(fn, executeFnInNewThread = true) { if (executeFnInNewThread) { return Future.fromPromise(new Promise((resolve, reject) => { try { const future = fn(); future.onComplete({ ifSuccess: value => resolve(value), ifFailure: exception => reject(exception) }); } catch (error) { reject(error); } })); } else { try { const future = fn(); return future; } catch (error) { return Future.failed(error); } } } static fromTry(t) { return t.fold({ ifSuccess: value => Future.successful(value), ifFailure: exception => Future.failed(exception) }); } static successful(value) { return new FutureCompletedWithValue(value); } static successfulWithVoid() { return Future.successful(true); } static failed(exception) { return new FutureCompletedWithException(exception); } static notYetStarted() { return new FutureNotYetStarted(); } _onSuccess(value) { this._tryOption = Option_1.Option.of(Try_1.Try.successful(value)); setTimeout(() => { this.completeFunctionSubscribers.forEach(o => { try { if (o.ifSuccess != undefined) o.ifSuccess(value); else if (o.whatEver != undefined) o.whatEver(); } catch (e) { console.log("UN CATCHED Execption when executing success callback on future", e); } }); }, 100); } _onFailure(exception) { this._tryOption = Option_1.Option.of(Try_1.Try.failed(exception)); console.log("on failure ", exception); setTimeout(() => { this.completeFunctionSubscribers.forEach(o => { try { if (o.ifFailure != undefined) o.ifFailure(exception); else if (o.whatEver != undefined) o.whatEver(); } catch (e) { console.log("UN CATCHED Execption when executing failure callback on future.", e); } }); }, 100); } _setPromiseOption(promiseOption) { this._promiseOption = promiseOption; return this; } valueOrNull() { if (this.isSuccess()) return this._tryOption.value.value(); else return null; } valueOption() { return Option_1.Option.of(this.valueOrNull()); } toLazy() { return Future.lazyFromFuture(() => this); } exceptionOrNull() { if (this.isFailure()) return this._tryOption.value.exception(); else return null; } isCompleted() { return this._tryOption.isDefined(); } isNotYetStarted() { return this._promiseOption.isEmpty(); } isPending() { return (this._promiseOption.isDefined() && !this.isCompleted()); } isSuccess() { return this.isCompleted() && this._tryOption.value.isSuccess(); } isFailure() { return this.isCompleted() && this._tryOption.value.isFailure(); } map(fn) { if (this.isFailure()) { return this; } else if (this.isSuccess()) { const executeFnInNewThread = false; return Future.from(() => fn(this.valueOrNull()), executeFnInNewThread); } else return Future.fromPromise(new Promise((resolve, reject) => { this.onFailure(error => { reject(error); }); this.onSuccess(value => { try { const mappedValue = fn(value); resolve(mappedValue); } catch (error) { reject(error); } }); })); } completeBefore(obj) { const timeOutPromiseFn = () => new Promise((resolve, reject) => { setTimeout(() => { try { if (this.isPending() || this.isNotYetStarted()) { const timeOutFuture = () => { if (obj.orElse === undefined || obj.orElse == null) { return Future.failed(new Exception_1.TimeOutException(`This future took long to be executed, the duration should not have exceeded ${obj.timeOut}ms`)); } else { try { return obj.orElse(); } catch (ex) { return Future.failed(ex); } } }; const f = timeOutFuture(); resolve(f); } } catch (error) { reject(error); } }, obj.timeOut); }); const theFuture = () => new Promise((resolve, reject) => { this.onComplete(() => resolve(this)); }); return (Future .fromPromise(Promise.race([theFuture(), timeOutPromiseFn()])) .flatMap(f => f)); } filter(fn) { return this.map(value => { if (fn(value)) return value; else throw new Exception_1.NoSuchElementException({ message: "No such element error: the future was completed with exception '" + this._tryOption.value.exception + "' Hence it did not match the predicate in the filter method you have previously called." }); }); } filterNot(fn) { return this.filter(value => !fn(value)); } select(fn) { return this.filter(fn); } flatMap(fn) { if (this.isFailure()) { return this; } else if (this.isSuccess()) { try { return fn(this.valueOrNull()); } catch (error) { return Future.failed(error); } } else return Future.fromPromise(new Promise((resolve, reject) => { this.onFailure(error => { reject(error); }); this.onSuccess(value => { try { fn(value).onComplete({ ifSuccess: secondValue => { resolve(secondValue); }, ifFailure: (error) => { reject(error); } }); } catch (error) { reject(error); } }); })); } toTryOption() { return this._tryOption; } toPromise() { if (this.isNotYetStarted()) throw new Exception_1.Exception("Can not transform this Future into a function because this future has not yet started."); return this._promiseOption.value; } toPromiseOption() { return this._promiseOption; } toArray() { if (this.isSuccess()) return [this.valueOrNull()]; else return []; } forEach(fn) { if (this.isSuccess()) fn(this.valueOrNull()); else { this.completeFunctionSubscribers.push({ ifSuccess: fn }); } } onSuccess(fn) { if (this.isSuccess()) fn(this.valueOrNull()); else { this.completeFunctionSubscribers.push({ ifSuccess: fn }); } } onFailure(fn) { if (this.isFailure()) fn(this.exceptionOrNull()); else { this.completeFunctionSubscribers.push({ ifFailure: fn }); } } onComplete(fn) { if (lodash_1.isFunction(fn)) { const fnAsFunction = fn; if (this.isCompleted()) fnAsFunction(); else { this.completeFunctionSubscribers.push({ whatEver: fnAsFunction }); } } else { const fnAsObject = fn; if (this.isSuccess()) fnAsObject.ifSuccess(this._tryOption.value.value()); else if (this.isFailure()) fnAsObject.ifFailure(this._tryOption.value.exception()); else { this.completeFunctionSubscribers.push(fnAsObject); } } } fold(fold) { const f2 = fold; if (f2.otherwise == undefined) { if (this.isNotYetStarted()) return fold.ifNotYetStarted(); else if (this.isPending()) return fold.ifPending(); else if (this.isFailure()) return fold.ifFailure(this.exceptionOrNull()); else if (this.isSuccess()) return fold.ifSuccess(this.valueOrNull()); } else { if (this.isNotYetStarted() && f2.ifNotYetStarted != undefined) return fold.ifNotYetStarted(); else if (this.isPending() && f2.ifPending != undefined) return fold.ifPending(); else if (this.isFailure() && f2.ifFailure != undefined) return fold.ifFailure(this.exceptionOrNull()); else if (this.isSuccess() && f2.ifSuccess != undefined) return fold.ifSuccess(this.valueOrNull()); else return f2.otherwise(); } } recover(fn) { if (this.isSuccess()) { return this; } else if (this.isFailure()) { const executeFnInNewThread = false; return Future.from(() => fn(this.exceptionOrNull()), executeFnInNewThread); } else return Future.fromPromise(new Promise((resolve, reject) => { this.onSuccess(value => { resolve(value); }); this.onFailure(error => { try { const recoveredValue = fn(error); resolve(recoveredValue); } catch (error) { reject(error); } }); })); } delay(duration) { return this.flatMap(r => Future.executeAfter(duration, () => r)); } flatRecover(fn) { if (this.isSuccess()) { return this; } else if (this.isFailure()) { const executeFnInNewThread = false; return Future.fromFuture(() => fn(this.exceptionOrNull()), executeFnInNewThread); } else return Future.fromPromise(new Promise((resolve, reject) => { this.onFailure(error => { try { fn(error).onComplete({ ifFailure: error => reject(error), ifSuccess: value => resolve(value) }); } catch (error) { reject(error); } }); this.onSuccess(value => { resolve(value); }); })); } transform(transformer) { return this.map(transformer).recover(transformer); } flatTransform(transformer) { return this.flatMap(transformer).flatRecover(transformer); } start() { return this; } isLazy() { return false; } toString() { return (this.fold({ ifPending: () => "Future(Pending)", ifSuccess: value => `Future(Success(${value}))`, ifFailure: exception => `Future(Failure(${exception}))`, ifNotYetStarted: () => "Future(NotYetStarted)", })); } } exports.Future = Future; Future._foreverPending = Future.fromPromise(new Promise((resolve, reject) => { })); class FutureCompletedWithValue extends Future { constructor(value) { super(Option_1.Option.of(Promise.resolve(value)), Option_1.Option.of(Try_1.Try.successful(value))); } toString() { return super.toString(); } } class FutureCompletedWithException extends Future { constructor(exception) { super(Option_1.Option.of(Promise.reject(exception)), Option_1.Option.of(Try_1.Try.failed(exception))); } toString() { return super.toString(); } } class FutureNotYetStarted extends Future { constructor() { super(Option_1.Option.empty(), Option_1.Option.empty()); } toString() { return super.toString(); } } class LazyFuture extends Future { constructor(f) { super(Option_1.Option.empty(), Option_1.Option.empty()); this.f = f; this.evalFutureOption = Option_1.Option.empty(); } evalF() { if (this.evalFutureOption.isDefined()) return this.evalFutureOption.value; else { const evalFuture = this.f().start(); this.evalFutureOption = Option_1.Option.of(evalFuture); return this.init(Option_1.Option.of(evalFuture.toPromise())); } } evalFafter(duration) { const future = Future.executeAfter(duration, () => { if (this.evalFutureOption.isDefined()) return this.evalFutureOption.value; else { const evalFuture = this.f().start(); this.evalFutureOption = Option_1.Option.of(evalFuture); return this.init(Option_1.Option.of(evalFuture.toPromise())); } }); return future.flatMap(f => f); } isLazy() { return true; } toString() { return (this.fold({ ifPending: () => "LazyFuture(Pending)", ifSuccess: value => `LazyFuture(Success(${value}))`, ifFailure: exception => `LazyFuture(Failure(${exception}))`, ifNotYetStarted: () => "LazyFuture(NotYetStarted)", })); } } exports.LazyFuture = LazyFuture; class LazyFutureImpl extends LazyFuture { constructor(f) { super(f); } map(fn) { const f = () => this.evalF().map(fn); return Future.lazyFromFuture(f); } filter(fn) { const f = () => this.evalF().filter(fn); return Future.lazyFromFuture(f); } filterNot(fn) { const f = () => this.evalF().filterNot(fn); return Future.lazyFromFuture(f); } select(fn) { return this.filter(fn); } reject(fn) { return this.filterNot(fn); } flatMap(fn) { const f = () => this.evalF().flatMap(fn); return Future.lazyFromFuture(f); } toLazy() { return this; } onSuccess(fn) { this.evalF().onSuccess(fn); } onFailure(fn) { this.evalF().onFailure(fn); } onComplete(fn) { this.evalF().onComplete(fn); } recover(fn) { const f = () => this.evalF().recover(fn); return Future.lazyFromFuture(f); } flatRecover(fn) { const f = () => this.evalF().flatRecover(fn); return Future.lazyFromFuture(f); } transform(transformer) { const f = () => this.evalF().transform(transformer); return Future.lazyFromFuture(f); } flatTransform(transformer) { const f = () => this.evalF().flatTransform(transformer); return Future.lazyFromFuture(f); } completeBefore(obj) { const f = () => this.evalF().completeBefore(obj); return Future.lazyFromFuture(f); } delay(duration) { return this.flatMap(r => Future.executeAfter(duration, () => r)); } forEach(fn) { this.evalF().forEach(fn); } toString() { return super.toString(); } start() { return this.evalF(); } reinitialize() { return Future.lazyFromFuture(this.f); } startAfter(duration) { return this.evalFafter(duration); } } //# sourceMappingURL=Future.js.map
34.073892
183
0.488603
bbf27ee565c36495dbc02dac603b4bbed5096315
2,449
js
JavaScript
commands/moderation/verify.js
Sam376-sch/HorizoN-2
ac3046b475cb6438c84a248e46b8481c98e26557
[ "MIT" ]
null
null
null
commands/moderation/verify.js
Sam376-sch/HorizoN-2
ac3046b475cb6438c84a248e46b8481c98e26557
[ "MIT" ]
null
null
null
commands/moderation/verify.js
Sam376-sch/HorizoN-2
ac3046b475cb6438c84a248e46b8481c98e26557
[ "MIT" ]
null
null
null
const discord = require("discord.js"); module.exports = { name: "verify", aliases: [""], description: "Verification system", run: async (client, message, args) => { let code = randomInteger(100000, 1000000); message.delete({ timeout: 2000 }); let channel = message.guild.channels.cache.find(ch => ch.name === "verify"); if (!channel) return message.channel.send("Couldnt find channel called verify"); //Searching for a channel called "verify" and if it doesnt find it it will stop everything let embed = new discord.MessageEmbed() .setColor("RED") .setDescription( "This command can only be ran in a channel called verify" ); if (message.channel !== channel) return message.channel.send(embed); //If theyre in the wrong channel it will tell them where they have to run it message.channel .send("Check your DMs") .then(m => m.delete({ timeout: 3000 })); const embeb2 = new discord.MessageEmbed() .setColor("RANDOM") .setTitle("Verification Captcha") .setDescription( `Please type in my DM this code: ${code} to get access to the server` ) .setFooter("3 Minutes until prompt end"); let filter = m => m.author === message.author; let options = { max: 1, time: 180000, errors: ["time"] }; message.author.send(embeb2).then(dmChannel => { //I forgot something dmChannel.channel.awaitMessages(filter, options).then(collected => { if ((collected.content = code)) { let role = message.guild.roles.cache.find(rl => rl.name === "User"); if (!role) return message.author.send("Couldnt find role called User"); let user = message.member; user.roles.add(role); const embed = new discord.MessageEmbed() .setColor("GREEN") .setDescription("Verification Successful"); return message.author.send(embed); //Forgot to return that } if (collected.code != code) { const embed = new discord.MessageEmbed() .setColor("RED") .setDescription("Verification Unsuccessful") .setFooter("Please try again"); return message.author.send(embed); } }); }); function randomInteger(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } } };
36.014706
94
0.606778
bbf2a57acc2d151a75f11d1d586882a67a50065d
327
js
JavaScript
config.js
OlhaPadalka/customers-api
db5e8b739e05e6f135791bf3b7b573f0b83502c1
[ "MIT" ]
null
null
null
config.js
OlhaPadalka/customers-api
db5e8b739e05e6f135791bf3b7b573f0b83502c1
[ "MIT" ]
null
null
null
config.js
OlhaPadalka/customers-api
db5e8b739e05e6f135791bf3b7b573f0b83502c1
[ "MIT" ]
null
null
null
module.exports = { ENV: process.env.NODE_ENV || 'development', PORT: process.env.PORT || 3000, URL: process.env.BASE_URL || 'http://localhost:3000', MONGODB_URI: process.env.MONGODB_URI || 'mongodb://TestUser:test123@ds253203.mlab.com:53203/customer_api', JWT_SECRET: process.env.JWT_SECRET || 'secret1' }
40.875
110
0.697248
bbf2e61a3dc2f5f66593591c8f21809a4728791e
1,417
js
JavaScript
index.js
cc12703/Reed-Json-API
26027ebf344fc6baf619eefdb35cfe217f4747ac
[ "MIT" ]
null
null
null
index.js
cc12703/Reed-Json-API
26027ebf344fc6baf619eefdb35cfe217f4747ac
[ "MIT" ]
null
null
null
index.js
cc12703/Reed-Json-API
26027ebf344fc6baf619eefdb35cfe217f4747ac
[ "MIT" ]
null
null
null
const fs = require('fs'), Router = require('koa-router'), path = require('path'), dummyJson = require('@cc12703m/dummy-json'), { setBadRequest } = require('./lib/util') //TODO: watch file changed for json template module.exports = ({ urlPrefix, filePath, dummyOptions }) => { const source = fs.readFileSync(filePath).toString() let jsonData = '' if (path.extname(filePath).toLowerCase() == '.json') { jsonData = JSON.parse(source) } else { let jsonResult = dummyJson.parse(source, dummyOptions) jsonData = JSON.parse(jsonResult) } const router = new Router() urlPrefix && router.prefix(urlPrefix) router.get('/:name/:id?', require('./lib/get')(jsonData)) .delete('/:name/:id?', require('./lib/delete')(jsonData)) .all('/:name?', handleBadRequest) .post('/:name?', require('./lib/create')(jsonData)) .put('/:name/:id?', require('./lib/update')(jsonData, false)) .patch('/:name/:id?', require('./lib/update')(jsonData, true)) return router.routes() } async function handleBadRequest(ctx, next) { if (['POST', 'PUT', 'PATCH'].includes(ctx.method)) { let entity = ctx.request.body, entityType = typeof entity if (!entity || entityType != 'object' || entity.isEmpty()) { setBadRequest(ctx) return } } return await next() }
29.520833
70
0.589273
bbf654b52740d9175cea645f9f4dc81b2d15abbf
1,206
js
JavaScript
app/assets/svgs/stateNoContact.js
MannimMond86/safe
9b48e2cadd6563666bb431a0e18a4943497ed7fb
[ "MIT" ]
null
null
null
app/assets/svgs/stateNoContact.js
MannimMond86/safe
9b48e2cadd6563666bb431a0e18a4943497ed7fb
[ "MIT" ]
1
2020-06-30T00:57:33.000Z
2020-06-30T00:57:33.000Z
app/assets/svgs/stateNoContact.js
MannimMond86/safe
9b48e2cadd6563666bb431a0e18a4943497ed7fb
[ "MIT" ]
null
null
null
export default `<svg width="850" height="850" viewBox="0 0 850 850" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M425 465C447.091 465 465 447.091 465 425C465 402.909 447.091 385 425 385C402.909 385 385 402.909 385 425C385 447.091 402.909 465 425 465Z" fill="white"/> <path d="M425 457C442.673 457 457 442.673 457 425C457 407.327 442.673 393 425 393C407.327 393 393 407.327 393 425C393 442.673 407.327 457 425 457Z" fill="#D6D6DA"/> <path d="M425 412C417.832 412 412 417.832 412 425C412 432.168 417.832 438 425 438C432.168 438 438 432.168 438 425C438 417.832 432.168 412 425 412ZM425 435.075C419.436 435.075 414.925 430.565 414.925 425C414.925 419.436 419.436 414.925 425 414.925C430.564 414.925 435.075 419.436 435.075 425C435.075 430.565 430.564 435.075 425 435.075Z" fill="white"/> <circle opacity="0.2" cx="425" cy="425" r="85.5" stroke="white"/> <circle opacity="0.2" cx="425" cy="425" r="149.5" stroke="white"/> <circle opacity="0.2" cx="425" cy="425" r="217.5" stroke="white"/> <circle opacity="0.2" cx="425" cy="425" r="283.5" stroke="white"/> <circle opacity="0.2" cx="425" cy="425" r="352.5" stroke="white"/> <circle opacity="0.2" cx="425" cy="425" r="424.5" stroke="white"/> </svg>`;
100.5
351
0.698176
bbf71942a4deba929e62d160449705049ac3d30b
29,072
js
JavaScript
public/js/15.d43631.js
BrandonMendoza/INNSoftware
7dfd5e418b3d0c88db9162f5a1db0448261383e0
[ "MIT" ]
null
null
null
public/js/15.d43631.js
BrandonMendoza/INNSoftware
7dfd5e418b3d0c88db9162f5a1db0448261383e0
[ "MIT" ]
null
null
null
public/js/15.d43631.js
BrandonMendoza/INNSoftware
7dfd5e418b3d0c88db9162f5a1db0448261383e0
[ "MIT" ]
null
null
null
(window.webpackJsonp=window.webpackJsonp||[]).push([[15],{"6FdI":function(t,n,e){"use strict";var a={name:"PanThumb",props:{image:{type:String,required:!0},zIndex:{type:Number,default:1},width:{type:String,default:"150px"},height:{type:String,default:"150px"},hoverable:{type:Boolean,default:!0}}},r=(e("QT2R"),e("KHd+")),i=Object(r.a)(a,(function(){var t=this.$createElement,n=this._self._c||t;return n("div",{class:{"pan-item":1,"pan-item-hover":this.hoverable},style:{zIndex:this.zIndex,height:this.height,width:this.width}},[n("div",{staticClass:"pan-info"},[n("div",{staticClass:"pan-info-roles-container"},[this._t("default")],2)]),this._v(" "),n("img",{staticClass:"pan-thumb",attrs:{src:this.image}})])}),[],!1,null,"0929838b",null);n.a=i.exports},"6mPD":function(t,n,e){"use strict";var a={name:"MdInput",props:{icon:String,name:String,type:{type:String,default:"text"},value:[String,Number],placeholder:String,readonly:Boolean,disabled:Boolean,min:String,max:String,step:String,minlength:Number,maxlength:Number,required:{type:Boolean,default:!0},autoComplete:{type:String,default:"off"},validateEvent:{type:Boolean,default:!0}},data:function(){return{currentValue:this.value,focus:!1,fillPlaceHolder:null}},computed:{computedClasses:function(){return{"material--active":this.focus,"material--disabled":this.disabled,"material--raised":Boolean(this.focus||this.currentValue)}}},watch:{value:function(t){this.currentValue=t}},methods:{handleModelInput:function(t){var n=t.target.value;this.$emit("input",n),"ElFormItem"===this.$parent.$options.componentName&&this.validateEvent&&this.$parent.$emit("el.form.change",[n]),this.$emit("change",n)},handleMdFocus:function(t){this.focus=!0,this.$emit("focus",t),this.placeholder&&""!==this.placeholder&&(this.fillPlaceHolder=this.placeholder)},handleMdBlur:function(t){this.focus=!1,this.$emit("blur",t),this.fillPlaceHolder=null,"ElFormItem"===this.$parent.$options.componentName&&this.validateEvent&&this.$parent.$emit("el.form.blur",[this.currentValue])}}},r=(e("nTgC"),e("KHd+")),i=Object(r.a)(a,(function(){var t=this,n=t.$createElement,e=t._self._c||n;return e("div",{staticClass:"material-input__component",class:t.computedClasses},[e("div",{class:{iconClass:t.icon}},[t.icon?e("i",{staticClass:"el-input__icon material-input__icon",class:["el-icon-"+t.icon]}):t._e(),t._v(" "),"email"===t.type?e("input",{directives:[{name:"model",rawName:"v-model",value:t.currentValue,expression:"currentValue"}],staticClass:"material-input",attrs:{name:t.name,placeholder:t.fillPlaceHolder,readonly:t.readonly,disabled:t.disabled,autoComplete:t.autoComplete,required:t.required,type:"email"},domProps:{value:t.currentValue},on:{focus:t.handleMdFocus,blur:t.handleMdBlur,input:[function(n){n.target.composing||(t.currentValue=n.target.value)},t.handleModelInput]}}):t._e(),t._v(" "),"url"===t.type?e("input",{directives:[{name:"model",rawName:"v-model",value:t.currentValue,expression:"currentValue"}],staticClass:"material-input",attrs:{name:t.name,placeholder:t.fillPlaceHolder,readonly:t.readonly,disabled:t.disabled,autoComplete:t.autoComplete,required:t.required,type:"url"},domProps:{value:t.currentValue},on:{focus:t.handleMdFocus,blur:t.handleMdBlur,input:[function(n){n.target.composing||(t.currentValue=n.target.value)},t.handleModelInput]}}):t._e(),t._v(" "),"number"===t.type?e("input",{directives:[{name:"model",rawName:"v-model",value:t.currentValue,expression:"currentValue"}],staticClass:"material-input",attrs:{name:t.name,placeholder:t.fillPlaceHolder,step:t.step,readonly:t.readonly,disabled:t.disabled,autoComplete:t.autoComplete,max:t.max,min:t.min,minlength:t.minlength,maxlength:t.maxlength,required:t.required,type:"number"},domProps:{value:t.currentValue},on:{focus:t.handleMdFocus,blur:t.handleMdBlur,input:[function(n){n.target.composing||(t.currentValue=n.target.value)},t.handleModelInput]}}):t._e(),t._v(" "),"password"===t.type?e("input",{directives:[{name:"model",rawName:"v-model",value:t.currentValue,expression:"currentValue"}],staticClass:"material-input",attrs:{name:t.name,placeholder:t.fillPlaceHolder,readonly:t.readonly,disabled:t.disabled,autoComplete:t.autoComplete,max:t.max,min:t.min,required:t.required,type:"password"},domProps:{value:t.currentValue},on:{focus:t.handleMdFocus,blur:t.handleMdBlur,input:[function(n){n.target.composing||(t.currentValue=n.target.value)},t.handleModelInput]}}):t._e(),t._v(" "),"tel"===t.type?e("input",{directives:[{name:"model",rawName:"v-model",value:t.currentValue,expression:"currentValue"}],staticClass:"material-input",attrs:{name:t.name,placeholder:t.fillPlaceHolder,readonly:t.readonly,disabled:t.disabled,autoComplete:t.autoComplete,required:t.required,type:"tel"},domProps:{value:t.currentValue},on:{focus:t.handleMdFocus,blur:t.handleMdBlur,input:[function(n){n.target.composing||(t.currentValue=n.target.value)},t.handleModelInput]}}):t._e(),t._v(" "),"text"===t.type?e("input",{directives:[{name:"model",rawName:"v-model",value:t.currentValue,expression:"currentValue"}],staticClass:"material-input",attrs:{name:t.name,placeholder:t.fillPlaceHolder,readonly:t.readonly,disabled:t.disabled,autoComplete:t.autoComplete,minlength:t.minlength,maxlength:t.maxlength,required:t.required,type:"text"},domProps:{value:t.currentValue},on:{focus:t.handleMdFocus,blur:t.handleMdBlur,input:[function(n){n.target.composing||(t.currentValue=n.target.value)},t.handleModelInput]}}):t._e(),t._v(" "),e("span",{staticClass:"material-input-bar"}),t._v(" "),e("label",{staticClass:"material-label"},[t._t("default")],2)])])}),[],!1,null,"3c53f318",null);n.a=i.exports},"76eg":function(t,n,e){"use strict";var a=e("YdKz");e.n(a).a},"7sWw":function(t,n,e){var a=e("VyIk");"string"==typeof a&&(a=[[t.i,a,""]]);var r={hmr:!0,transform:void 0,insertInto:void 0};e("aET+")(a,r);a.locals&&(t.exports=a.locals)},"HF+U":function(t,n,e){"use strict";e("7sWw");var a="@@wavesContext";function r(t,n){function e(e){var a=Object.assign({},n.value),r=Object.assign({ele:t,type:"hit",color:"rgba(0, 0, 0, 0.15)"},a),i=r.ele;if(i){i.style.position="relative",i.style.overflow="hidden";var o=i.getBoundingClientRect(),s=i.querySelector(".waves-ripple");switch(s?s.className="waves-ripple":((s=document.createElement("span")).className="waves-ripple",s.style.height=s.style.width=Math.max(o.width,o.height)+"px",i.appendChild(s)),r.type){case"center":s.style.top=o.height/2-s.offsetHeight/2+"px",s.style.left=o.width/2-s.offsetWidth/2+"px";break;default:s.style.top=(e.pageY-o.top-s.offsetHeight/2-document.documentElement.scrollTop||document.body.scrollTop)+"px",s.style.left=(e.pageX-o.left-s.offsetWidth/2-document.documentElement.scrollLeft||document.body.scrollLeft)+"px"}return s.style.backgroundColor=r.color,s.className="waves-ripple z-active",!1}}return t[a]?t[a].removeHandle=e:t[a]={removeHandle:e},e}var i={bind:function(t,n){t.addEventListener("click",r(t,n),!1)},update:function(t,n){t.removeEventListener("click",t[a].removeHandle,!0),t.addEventListener("click",r(t,n),!1)},unbind:function(t){t.removeEventListener("click",t[a].removeHandle,!1),t[a]=null,delete t[a]}},o=function(t){t.directive("waves",i)};window.Vue&&(window.waves=i,Vue.use(o)),i.install=o;n.a=i},JVAP:function(t,n,e){"use strict";var a=e("NzNl");e.n(a).a},NzNl:function(t,n,e){var a=e("k9D0");"string"==typeof a&&(a=[[t.i,a,""]]);var r={hmr:!0,transform:void 0,insertInto:void 0};e("aET+")(a,r);a.locals&&(t.exports=a.locals)},QT2R:function(t,n,e){"use strict";var a=e("aq7K");e.n(a).a},TM6A:function(t,n,e){(n=e("JPst")(!1)).push([t.i,".material-input__component .material-input-bar[data-v-3c53f318]:before, .material-input__component .material-input-bar[data-v-3c53f318]:after {\n content: '';\n height: 1px;\n width: 0;\n bottom: 0;\n position: absolute;\n -webkit-transition: 0.2s ease all;\n transition: 0.2s ease all;\n}\n.material-input__component[data-v-3c53f318] {\n margin-top: 36px;\n position: relative;\n}\n.material-input__component *[data-v-3c53f318] {\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n}\n.material-input__component .iconClass .material-input__icon[data-v-3c53f318] {\n position: absolute;\n left: 0;\n line-height: 16px;\n color: #2196F3;\n top: 12px;\n width: 30px;\n height: 16px;\n font-size: 16px;\n font-weight: normal;\n pointer-events: none;\n}\n.material-input__component .iconClass .material-label[data-v-3c53f318] {\n left: 30px;\n}\n.material-input__component .iconClass .material-input[data-v-3c53f318] {\n text-indent: 30px;\n}\n.material-input__component .material-input[data-v-3c53f318] {\n font-size: 16px;\n padding: 12px 12px 2px 6px;\n display: block;\n width: 100%;\n border: none;\n line-height: 1;\n border-radius: 0;\n}\n.material-input__component .material-input[data-v-3c53f318]:focus {\n outline: none;\n border: none;\n border-bottom: 1px solid transparent;\n}\n.material-input__component .material-label[data-v-3c53f318] {\n font-weight: normal;\n position: absolute;\n pointer-events: none;\n left: 0px;\n top: 0;\n -webkit-transition: 0.2s ease all;\n transition: 0.2s ease all;\n font-size: 18px;\n}\n.material-input__component .material-input-bar[data-v-3c53f318] {\n position: relative;\n display: block;\n width: 100%;\n}\n.material-input__component .material-input-bar[data-v-3c53f318]:before {\n left: 50%;\n}\n.material-input__component .material-input-bar[data-v-3c53f318]:after {\n right: 50%;\n}\n.material-input__component.material--disabled .material-input[data-v-3c53f318] {\n border-bottom-style: dashed;\n}\n.material-input__component.material--raised .material-label[data-v-3c53f318] {\n top: -28px;\n left: 0;\n font-size: 16px;\n font-weight: bold;\n}\n.material-input__component.material--active .material-input-bar[data-v-3c53f318]:before, .material-input__component.material--active .material-input-bar[data-v-3c53f318]:after {\n width: 50%;\n}\n.material-input__component[data-v-3c53f318] {\n background: white;\n}\n.material-input__component .material-input[data-v-3c53f318] {\n background: none;\n color: black;\n text-indent: 0px;\n border-bottom: 1px solid #E0E0E0;\n}\n.material-input__component .material-label[data-v-3c53f318] {\n color: #9E9E9E;\n}\n.material-input__component .material-input-bar[data-v-3c53f318]:before, .material-input__component .material-input-bar[data-v-3c53f318]:after {\n background: #2196F3;\n}\n.material-input__component.material--active .material-label[data-v-3c53f318] {\n color: #2196F3;\n}\n.material-input__component.material--has-errors.material--active .material-label[data-v-3c53f318] {\n color: #F44336;\n}\n.material-input__component.material--has-errors .material-input-bar[data-v-3c53f318]:before, .material-input__component.material--has-errors .material-input-bar[data-v-3c53f318]:after {\n background: transparent;\n}\n",""]),t.exports=n},U2u0:function(t,n,e){var a=e("iQhf");"string"==typeof a&&(a=[[t.i,a,""]]);var r={hmr:!0,transform:void 0,insertInto:void 0};e("aET+")(a,r);a.locals&&(t.exports=a.locals)},VyIk:function(t,n,e){(n=e("JPst")(!1)).push([t.i,".waves-ripple {\n position: absolute;\n border-radius: 100%;\n background-color: rgba(0, 0, 0, 0.15);\n background-clip: padding-box;\n pointer-events: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n -webkit-transform: scale(0);\n transform: scale(0);\n opacity: 1;\n}\n\n.waves-ripple.z-active {\n opacity: 0;\n -webkit-transform: scale(2);\n transform: scale(2);\n -webkit-transition: opacity 1.2s ease-out, -webkit-transform 0.6s ease-out;\n transition: opacity 1.2s ease-out, -webkit-transform 0.6s ease-out;\n transition: opacity 1.2s ease-out, transform 0.6s ease-out;\n transition: opacity 1.2s ease-out, transform 0.6s ease-out, -webkit-transform 0.6s ease-out;\n}",""]),t.exports=n},YdKz:function(t,n,e){var a=e("pIWR");"string"==typeof a&&(a=[[t.i,a,""]]);var r={hmr:!0,transform:void 0,insertInto:void 0};e("aET+")(a,r);a.locals&&(t.exports=a.locals)},aq7K:function(t,n,e){var a=e("kCOj");"string"==typeof a&&(a=[[t.i,a,""]]);var r={hmr:!0,transform:void 0,insertInto:void 0};e("aET+")(a,r);a.locals&&(t.exports=a.locals)},cby5:function(t,n,e){var a=e("TM6A");"string"==typeof a&&(a=[[t.i,a,""]]);var r={hmr:!0,transform:void 0,insertInto:void 0};e("aET+")(a,r);a.locals&&(t.exports=a.locals)},iQhf:function(t,n,e){(n=e("JPst")(!1)).push([t.i,"\n.mixin-components-container[data-v-220a44d6] {\n background-color: #f0f2f5;\n padding: 30px;\n min-height: calc(100vh - 84px);\n}\n.component-item[data-v-220a44d6]{\n min-height: 100px;\n}\n",""]),t.exports=n},k9D0:function(t,n,e){(n=e("JPst")(!1)).push([t.i,".share-dropdown-menu {\n width: 250px;\n position: relative;\n z-index: 1;\n}\n.share-dropdown-menu-title {\n width: 100%;\n display: block;\n cursor: pointer;\n background: black;\n color: white;\n height: 60px;\n line-height: 60px;\n font-size: 20px;\n text-align: center;\n z-index: 2;\n -webkit-transform: translate3d(0, 0, 0);\n transform: translate3d(0, 0, 0);\n}\n.share-dropdown-menu-wrapper {\n position: relative;\n}\n.share-dropdown-menu-item {\n text-align: center;\n position: absolute;\n width: 100%;\n background: #e0e0e0;\n line-height: 60px;\n height: 60px;\n cursor: pointer;\n font-size: 20px;\n opacity: 1;\n -webkit-transition: -webkit-transform 0.28s ease;\n transition: -webkit-transform 0.28s ease;\n transition: transform 0.28s ease;\n transition: transform 0.28s ease, -webkit-transform 0.28s ease;\n}\n.share-dropdown-menu-item:hover {\n background: black;\n color: white;\n}\n.share-dropdown-menu-item:nth-of-type(1) {\n z-index: -1;\n -webkit-transition-delay: 0.1s;\n transition-delay: 0.1s;\n -webkit-transform: translate3d(0, -60px, 0);\n transform: translate3d(0, -60px, 0);\n}\n.share-dropdown-menu-item:nth-of-type(2) {\n z-index: -1;\n -webkit-transition-delay: 0.2s;\n transition-delay: 0.2s;\n -webkit-transform: translate3d(0, -60px, 0);\n transform: translate3d(0, -60px, 0);\n}\n.share-dropdown-menu-item:nth-of-type(3) {\n z-index: -1;\n -webkit-transition-delay: 0.3s;\n transition-delay: 0.3s;\n -webkit-transform: translate3d(0, -60px, 0);\n transform: translate3d(0, -60px, 0);\n}\n.share-dropdown-menu-item:nth-of-type(4) {\n z-index: -1;\n -webkit-transition-delay: 0.4s;\n transition-delay: 0.4s;\n -webkit-transform: translate3d(0, -60px, 0);\n transform: translate3d(0, -60px, 0);\n}\n.share-dropdown-menu-item:nth-of-type(5) {\n z-index: -1;\n -webkit-transition-delay: 0.5s;\n transition-delay: 0.5s;\n -webkit-transform: translate3d(0, -60px, 0);\n transform: translate3d(0, -60px, 0);\n}\n.share-dropdown-menu-item:nth-of-type(6) {\n z-index: -1;\n -webkit-transition-delay: 0.6s;\n transition-delay: 0.6s;\n -webkit-transform: translate3d(0, -60px, 0);\n transform: translate3d(0, -60px, 0);\n}\n.share-dropdown-menu-item:nth-of-type(7) {\n z-index: -1;\n -webkit-transition-delay: 0.7s;\n transition-delay: 0.7s;\n -webkit-transform: translate3d(0, -60px, 0);\n transform: translate3d(0, -60px, 0);\n}\n.share-dropdown-menu-item:nth-of-type(8) {\n z-index: -1;\n -webkit-transition-delay: 0.8s;\n transition-delay: 0.8s;\n -webkit-transform: translate3d(0, -60px, 0);\n transform: translate3d(0, -60px, 0);\n}\n.share-dropdown-menu.active .share-dropdown-menu-wrapper {\n z-index: 1;\n}\n.share-dropdown-menu.active .share-dropdown-menu-item:nth-of-type(1) {\n -webkit-transition-delay: 0.7s;\n transition-delay: 0.7s;\n -webkit-transform: translate3d(0, 0px, 0);\n transform: translate3d(0, 0px, 0);\n}\n.share-dropdown-menu.active .share-dropdown-menu-item:nth-of-type(2) {\n -webkit-transition-delay: 0.6s;\n transition-delay: 0.6s;\n -webkit-transform: translate3d(0, 60px, 0);\n transform: translate3d(0, 60px, 0);\n}\n.share-dropdown-menu.active .share-dropdown-menu-item:nth-of-type(3) {\n -webkit-transition-delay: 0.5s;\n transition-delay: 0.5s;\n -webkit-transform: translate3d(0, 120px, 0);\n transform: translate3d(0, 120px, 0);\n}\n.share-dropdown-menu.active .share-dropdown-menu-item:nth-of-type(4) {\n -webkit-transition-delay: 0.4s;\n transition-delay: 0.4s;\n -webkit-transform: translate3d(0, 180px, 0);\n transform: translate3d(0, 180px, 0);\n}\n.share-dropdown-menu.active .share-dropdown-menu-item:nth-of-type(5) {\n -webkit-transition-delay: 0.3s;\n transition-delay: 0.3s;\n -webkit-transform: translate3d(0, 240px, 0);\n transform: translate3d(0, 240px, 0);\n}\n.share-dropdown-menu.active .share-dropdown-menu-item:nth-of-type(6) {\n -webkit-transition-delay: 0.2s;\n transition-delay: 0.2s;\n -webkit-transform: translate3d(0, 300px, 0);\n transform: translate3d(0, 300px, 0);\n}\n.share-dropdown-menu.active .share-dropdown-menu-item:nth-of-type(7) {\n -webkit-transition-delay: 0.1s;\n transition-delay: 0.1s;\n -webkit-transform: translate3d(0, 360px, 0);\n transform: translate3d(0, 360px, 0);\n}\n.share-dropdown-menu.active .share-dropdown-menu-item:nth-of-type(8) {\n -webkit-transition-delay: 0s;\n transition-delay: 0s;\n -webkit-transform: translate3d(0, 420px, 0);\n transform: translate3d(0, 420px, 0);\n}\n",""]),t.exports=n},kCOj:function(t,n,e){(n=e("JPst")(!1)).push([t.i,"\n.pan-item[data-v-0929838b] {\n width: 200px;\n height: 200px;\n border-radius: 50%;\n display: inline-block;\n position: relative;\n cursor: default;\n -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);\n}\n.pan-info-roles-container[data-v-0929838b] {\n padding: 20px;\n text-align: center;\n}\n.pan-thumb[data-v-0929838b] {\n width: 100%;\n height: 100%;\n background-size: 100%;\n border-radius: 50%;\n overflow: hidden;\n position: absolute;\n -webkit-transform-origin: 95% 40%;\n transform-origin: 95% 40%;\n -webkit-transition: all 0.3s ease-in-out;\n transition: all 0.3s ease-in-out;\n}\n.pan-thumb[data-v-0929838b]:after {\n content: '';\n width: 8px;\n height: 8px;\n position: absolute;\n border-radius: 50%;\n top: 40%;\n left: 95%;\n margin: -4px 0 0 -4px;\n background: radial-gradient(ellipse at center, rgba(14, 14, 14, 1) 0%, rgba(125, 126, 125, 1) 100%);\n -webkit-box-shadow: 0 0 1px rgba(255, 255, 255, 0.9);\n box-shadow: 0 0 1px rgba(255, 255, 255, 0.9);\n}\n.pan-info[data-v-0929838b] {\n position: absolute;\n width: inherit;\n height: inherit;\n border-radius: 50%;\n overflow: hidden;\n -webkit-box-shadow: inset 0 0 0 5px rgba(0, 0, 0, 0.05);\n box-shadow: inset 0 0 0 5px rgba(0, 0, 0, 0.05);\n}\n.pan-info h3[data-v-0929838b] {\n color: #fff;\n text-transform: uppercase;\n position: relative;\n letter-spacing: 2px;\n font-size: 18px;\n margin: 0 60px;\n padding: 22px 0 0 0;\n height: 85px;\n font-family: 'Open Sans', Arial, sans-serif;\n text-shadow: 0 0 1px #fff, 0 1px 2px rgba(0, 0, 0, 0.3);\n}\n.pan-info p[data-v-0929838b] {\n color: #fff;\n padding: 10px 5px;\n font-style: italic;\n margin: 0 30px;\n font-size: 12px;\n border-top: 1px solid rgba(255, 255, 255, 0.5);\n}\n.pan-info p a[data-v-0929838b] {\n display: block;\n color: #333;\n width: 80px;\n height: 80px;\n background: rgba(255, 255, 255, 0.3);\n border-radius: 50%;\n color: #fff;\n font-style: normal;\n font-weight: 700;\n text-transform: uppercase;\n font-size: 9px;\n letter-spacing: 1px;\n padding-top: 24px;\n margin: 7px auto 0;\n font-family: 'Open Sans', Arial, sans-serif;\n opacity: 0;\n -webkit-transition: opacity 0.3s ease-in-out 0.2s, background 0.2s linear 0s, -webkit-transform 0.3s ease-in-out 0.2s;\n transition: opacity 0.3s ease-in-out 0.2s, background 0.2s linear 0s, -webkit-transform 0.3s ease-in-out 0.2s;\n transition: transform 0.3s ease-in-out 0.2s, opacity 0.3s ease-in-out 0.2s, background 0.2s linear 0s;\n transition: transform 0.3s ease-in-out 0.2s, opacity 0.3s ease-in-out 0.2s, background 0.2s linear 0s, -webkit-transform 0.3s ease-in-out 0.2s;\n -webkit-transform: translateX(60px) rotate(90deg);\n transform: translateX(60px) rotate(90deg);\n}\n.pan-info p a[data-v-0929838b]:hover {\n background: rgba(255, 255, 255, 0.5);\n}\n.pan-item-hover:hover .pan-thumb[data-v-0929838b] {\n -webkit-transform: rotate(-110deg);\n transform: rotate(-110deg);\n}\n.pan-item-hover:hover .pan-info p a[data-v-0929838b] {\n opacity: 1;\n -webkit-transform: translateX(0px) rotate(0deg);\n transform: translateX(0px) rotate(0deg);\n}\n",""]),t.exports=n},kMW3:function(t,n,e){"use strict";e.r(n);var a=e("6FdI"),r=e("6mPD"),i={props:{className:{type:String,default:""},text:{type:String,default:"vue-element-admin"}}},o=(e("76eg"),e("KHd+")),s=Object(o.a)(i,(function(){var t=this.$createElement,n=this._self._c||t;return n("a",{staticClass:"link--mallki",class:this.className,attrs:{href:"#"}},[this._v("\n "+this._s(this.text)+"\n "),n("span",{attrs:{"data-letters":this.text}}),this._v(" "),n("span",{attrs:{"data-letters":this.text}})])}),[],!1,null,null,null).exports,l={props:{items:{type:Array,default:function(){return[]}},title:{type:String,default:"vue"}},data:function(){return{isActive:!1}},methods:{clickTitle:function(){this.isActive=!this.isActive}}},d=(e("JVAP"),Object(o.a)(l,(function(){var t=this,n=t.$createElement,e=t._self._c||n;return e("div",{staticClass:"share-dropdown-menu",class:{active:t.isActive}},[e("div",{staticClass:"share-dropdown-menu-wrapper"},[e("span",{staticClass:"share-dropdown-menu-title",on:{click:function(n){return n.target!==n.currentTarget?null:t.clickTitle(n)}}},[t._v(t._s(t.title))]),t._v(" "),t._l(t.items,(function(n,a){return e("div",{key:a,staticClass:"share-dropdown-menu-item"},[n.href?e("a",{attrs:{href:n.href,target:"_blank"}},[t._v(t._s(n.title))]):e("span",[t._v(t._s(n.title))])])}))],2)])}),[],!1,null,null,null).exports),p=e("HF+U"),c={name:"ComponentMixinDemo",components:{PanThumb:a.a,MdInput:r.a,Mallki:s,DropdownMenu:d},directives:{waves:p.a},data:function(){return{demo:{title:""},demoRules:{title:[{required:!0,trigger:"change",validator:function(t,n,e){6!==n.length?e(new Error("Please enter 6 chars")):e()}}]},articleList:[{title:"Basic article",href:"https://dev.to/tuandm/laravel--vuejs--laravue---a-beautiful-dashboard-for-laravel-3h11"},{title:"Login permission",href:"https://doc.laravue.dev/guide/essentials/permission.html"},{title:"laravue-core",href:"https://dev.to/tuandm/laravue-core---a-laravel-package-to-build-a-beautiful-dashboard-5aia"},{title:"Github",href:"https://github.com/tuandm/laravue"}]}}},u=(e("mjew"),Object(o.a)(c,(function(){var t=this,n=t.$createElement,e=t._self._c||n;return e("div",{staticClass:"mixin-components-container"},[e("el-row",[e("el-card",{staticClass:"box-card"},[e("div",{staticClass:"clearfix",attrs:{slot:"header"},slot:"header"},[e("span",[t._v("Buttons")])]),t._v(" "),e("div",{staticStyle:{"margin-bottom":"50px"}},[e("el-col",{staticClass:"text-center",attrs:{span:4}},[e("router-link",{staticClass:"pan-btn blue-btn",attrs:{to:"/documentation/index"}},[t._v("\n Documentation\n ")])],1),t._v(" "),e("el-col",{staticClass:"text-center",attrs:{span:4}},[e("router-link",{staticClass:"pan-btn light-blue-btn",attrs:{to:"/icon/index"}},[t._v("\n Icons\n ")])],1),t._v(" "),e("el-col",{staticClass:"text-center",attrs:{span:4}},[e("router-link",{staticClass:"pan-btn pink-btn",attrs:{to:"/excel/export-excel"}},[t._v("\n Excel\n ")])],1),t._v(" "),e("el-col",{staticClass:"text-center",attrs:{span:4}},[e("router-link",{staticClass:"pan-btn green-btn",attrs:{to:"/table/complex-table"}},[t._v("\n Table\n ")])],1),t._v(" "),e("el-col",{staticClass:"text-center",attrs:{span:4}},[e("router-link",{staticClass:"pan-btn tiffany-btn",attrs:{to:"/example/create"}},[t._v("\n Form\n ")])],1),t._v(" "),e("el-col",{staticClass:"text-center",attrs:{span:4}},[e("router-link",{staticClass:"pan-btn yellow-btn",attrs:{to:"/theme/index"}},[t._v("\n Theme\n ")])],1)],1)])],1),t._v(" "),e("el-row",{staticStyle:{"margin-top":"50px"},attrs:{gutter:20}},[e("el-col",{attrs:{span:6}},[e("el-card",{staticClass:"box-card"},[e("div",{staticClass:"clearfix",attrs:{slot:"header"},slot:"header"},[e("span",[t._v("Material Design Input")])]),t._v(" "),e("div",{staticStyle:{height:"100px"}},[e("el-form",{attrs:{model:t.demo,rules:t.demoRules}},[e("el-form-item",{attrs:{prop:"title"}},[e("md-input",{attrs:{icon:"search",name:"title",placeholder:"Enter title"},model:{value:t.demo.title,callback:function(n){t.$set(t.demo,"title",n)},expression:"demo.title"}},[t._v("\n Title\n ")])],1)],1)],1)])],1),t._v(" "),e("el-col",{attrs:{span:6}},[e("el-card",{staticClass:"box-card"},[e("div",{staticClass:"clearfix",attrs:{slot:"header"},slot:"header"},[e("span",[t._v("Picture hover effect")])]),t._v(" "),e("div",{staticClass:"component-item"},[e("pan-thumb",{attrs:{width:"100px",height:"100px",image:"https://eclectickoifish.files.wordpress.com/2015/01/7826_one_piece.jpg"}},[t._v("\n laravue\n ")])],1)])],1),t._v(" "),e("el-col",{attrs:{span:6}},[e("el-card",{staticClass:"box-card"},[e("div",{staticClass:"clearfix",attrs:{slot:"header"},slot:"header"},[e("span",[t._v("Ripple wave v-directive")])]),t._v(" "),e("div",{staticClass:"component-item"},[e("el-button",{directives:[{name:"waves",rawName:"v-waves"}],attrs:{type:"primary"}},[t._v("\n Water ripple effect\n ")])],1)])],1),t._v(" "),e("el-col",{attrs:{span:6}},[e("el-card",{staticClass:"box-card"},[e("div",{staticClass:"clearfix",attrs:{slot:"header"},slot:"header"},[e("span",[t._v("Hover text")])]),t._v(" "),e("div",{staticClass:"component-item"},[e("mallki",{attrs:{"class-name":"mallki-text",text:"Laravue Dashboard"}})],1)])],1)],1),t._v(" "),e("el-row",{staticStyle:{"margin-top":"50px"},attrs:{gutter:20}},[e("el-col",{attrs:{span:8}},[e("el-card",{staticClass:"box-card"},[e("div",{staticClass:"clearfix",attrs:{slot:"header"},slot:"header"},[e("span",[t._v("Share")])]),t._v(" "),e("div",{staticClass:"component-item",staticStyle:{height:"420px"}},[e("dropdown-menu",{staticStyle:{margin:"0 auto"},attrs:{items:t.articleList,title:"Article list"}})],1)])],1)],1)],1)}),[],!1,null,"220a44d6",null));n.default=u.exports},mjew:function(t,n,e){"use strict";var a=e("U2u0");e.n(a).a},nTgC:function(t,n,e){"use strict";var a=e("cby5");e.n(a).a},pIWR:function(t,n,e){(n=e("JPst")(!1)).push([t.i,"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/* Mallki */\n.link--mallki {\n font-weight: 800;\n color: #4dd9d5;\n font-family: 'Dosis', sans-serif;\n -webkit-transition: color 0.5s 0.25s;\n transition: color 0.5s 0.25s;\n overflow: hidden;\n position: relative;\n display: inline-block;\n line-height: 1;\n outline: none;\n text-decoration: none;\n}\n.link--mallki:hover {\n -webkit-transition: none;\n transition: none;\n color: transparent;\n}\n.link--mallki::before {\n content: '';\n width: 100%;\n height: 6px;\n margin: -3px 0 0 0;\n background: #3888fa;\n position: absolute;\n left: 0;\n top: 50%;\n -webkit-transform: translate3d(-100%, 0, 0);\n transform: translate3d(-100%, 0, 0);\n -webkit-transition: -webkit-transform 0.4s;\n transition: -webkit-transform 0.4s;\n transition: transform 0.4s;\n transition: transform 0.4s, -webkit-transform 0.4s;\n -webkit-transition-timing-function: cubic-bezier(0.7, 0, 0.3, 1);\n transition-timing-function: cubic-bezier(0.7, 0, 0.3, 1);\n}\n.link--mallki:hover::before {\n -webkit-transform: translate3d(100%, 0, 0);\n transform: translate3d(100%, 0, 0);\n}\n.link--mallki span {\n position: absolute;\n height: 50%;\n width: 100%;\n left: 0;\n top: 0;\n overflow: hidden;\n}\n.link--mallki span::before {\n content: attr(data-letters);\n color: red;\n position: absolute;\n left: 0;\n width: 100%;\n color: #3888fa;\n -webkit-transition: -webkit-transform 0.5s;\n transition: -webkit-transform 0.5s;\n transition: transform 0.5s;\n transition: transform 0.5s, -webkit-transform 0.5s;\n}\n.link--mallki span:nth-child(2) {\n top: 50%;\n}\n.link--mallki span:first-child::before {\n top: 0;\n -webkit-transform: translate3d(0, 100%, 0);\n transform: translate3d(0, 100%, 0);\n}\n.link--mallki span:nth-child(2)::before {\n bottom: 0;\n -webkit-transform: translate3d(0, -100%, 0);\n transform: translate3d(0, -100%, 0);\n}\n.link--mallki:hover span::before {\n -webkit-transition-delay: 0.3s;\n transition-delay: 0.3s;\n -webkit-transform: translate3d(0, 0, 0);\n transform: translate3d(0, 0, 0);\n -webkit-transition-timing-function: cubic-bezier(0.2, 1, 0.3, 1);\n transition-timing-function: cubic-bezier(0.2, 1, 0.3, 1);\n}\n",""]),t.exports=n}}]);
29,072
29,072
0.684129
bbf73e04faf902284c6ef10391522a65fdd2a6e5
544
js
JavaScript
src/frontend/actions/index.js
LuisParraPulido/escuelajs-reto-12
c6a8dcc7ded63a238e3c02b7fb3135dcbb87fdb0
[ "MIT" ]
null
null
null
src/frontend/actions/index.js
LuisParraPulido/escuelajs-reto-12
c6a8dcc7ded63a238e3c02b7fb3135dcbb87fdb0
[ "MIT" ]
null
null
null
src/frontend/actions/index.js
LuisParraPulido/escuelajs-reto-12
c6a8dcc7ded63a238e3c02b7fb3135dcbb87fdb0
[ "MIT" ]
null
null
null
import axios from 'axios'; const addToCart = payload => ({ type: 'ADD_TO_CART', payload, }); const setProducts = payload => ({ type: 'SET_PRODUCTS', payload, }); const setProductsError = payload => ({ type: 'SET_PRODUCTS', payload, error: true, }); const getProductsRequest = payload => (dispatch) => { axios .get('/server/products') .then(({ data: products }) => dispatch(setProducts({ products }))) .catch(error => dispatch(setProductsError(error))); }; export { addToCart, getProductsRequest, setProducts };
20.148148
70
0.652574
bbfa71e191eb329dec10c8f48bd25fa2bbb40a40
405
js
JavaScript
angular-playground/server.js
jeffersonvivanco/WebProgrammingNotes
19a71f033f6f394a19346569e962641f615a6cfa
[ "MIT" ]
null
null
null
angular-playground/server.js
jeffersonvivanco/WebProgrammingNotes
19a71f033f6f394a19346569e962641f615a6cfa
[ "MIT" ]
8
2020-04-10T15:09:40.000Z
2022-02-27T00:53:32.000Z
angular-playground/server.js
jeffersonvivanco/WebProgrammingNotes
19a71f033f6f394a19346569e962641f615a6cfa
[ "MIT" ]
null
null
null
const express = require('express'); const cors = require('cors'); const app = express(); const PORT = 3001; const path = require('path'); app.use(cors()); app.use(express.static(path.join(__dirname, 'dist/angular-playground'))); app.get('/api/hello', (req, res) => { res.json({message: 'Hello!'}); }); app.listen(PORT, () => console.log(`app (serving angular component) listening of port ${PORT}`));
27
97
0.661728
bbff67792e01ee3eaf768f0a85c56f7407cfa7fa
1,990
js
JavaScript
src/Wifi.js
muhammaddadu/node-wifi-utils
17f06438176386ca265b87d3e607e93b014ed609
[ "MIT" ]
null
null
null
src/Wifi.js
muhammaddadu/node-wifi-utils
17f06438176386ca265b87d3e607e93b014ed609
[ "MIT" ]
null
null
null
src/Wifi.js
muhammaddadu/node-wifi-utils
17f06438176386ca265b87d3e607e93b014ed609
[ "MIT" ]
null
null
null
/** * Wifi * @author Muhammad Dadu */ import Debug from 'debug'; import request from 'request'; import * as childProcess from 'child_process'; import _extend from 'util'; const debug = Debug('node-wifi-utils:Wifi'); /** * Wifi Utils */ export default class Wifi { static platform: String; static scanCmd: String; /** * Scan surrounding WiFi access points * @returns { Promise } */ static scan(): Promise { return new Promise((resolve, reject) => { if (!this.scanCmd) { return reject('Platform not supported'); } debug('running command %s', this.scanCmd); childProcess.exec(this.scanCmd, _extend(process.env, { LANG: 'en' }), (err, stdout, stderr) => { if (err) { debug('error: %s', err); return reject(err); } debug('stdout: %s', stdout); debug('stderr: %s', stderr); return resolve(this.parseScan(stdout)); }); }); } /** * Returns geolocation using surrounding WiFi access points * @returns { Promise } */ static location(): Promise { return this .scan() .then(this.locationFromAccessPoints); } /** * Returns geolocation using surrounding WiFi access points * @returns { Promise } */ static locationFromAccessPoints(accessPoints: Array): Promise { return new Promise((resolve, reject) => { let url = 'https://maps.googleapis.com/maps/api/browserlocation/json'; url += '?browser=node-wifi-utils&sensor=true&wifi='; url += accessPoints.map((accessPoint) => { return [ 'mac:' + accessPoint.mac, 'ssid:' + accessPoint.ssid, 'ss:' + accessPoint.signal_level ].join('|'); }).join('&wifi='); request({ method: 'POST', url: url, json: true }, (err, res, body) => { if (err) { return reject(err); } let location = { accuracy: body.accuracy, latitude: body.location.lat, longitude: body.location.lng }; debug('location: %s', JSON.stringify(location)); resolve(location); }); }); } }
21.868132
73
0.61608
010228ee9ce3e667ab04053fdbd7ce9b738ed06d
9,593
js
JavaScript
app.js
zyn1030z/owl_ex
a5520dd6a7520011106a1c73aee7727d17bf6614
[ "MIT" ]
null
null
null
app.js
zyn1030z/owl_ex
a5520dd6a7520011106a1c73aee7727d17bf6614
[ "MIT" ]
null
null
null
app.js
zyn1030z/owl_ex
a5520dd6a7520011106a1c73aee7727d17bf6614
[ "MIT" ]
null
null
null
// (function () { // const { Component } = owl; // const { xml } = owl.tags; // const { whenReady } = owl.utils; // // const { useRef, useSubEnv } = owl.hooks; // // // ------------------------------------------------------------------------- // // Model // // ------------------------------------------------------------------------- // class TaskModel extends owl.core.EventBus { // nextId = 1 // tasks = []; // // constructor(tasks) { // super() // for (let task of tasks) { // this.tasks.push(task); // this.nextId = Math.max(this.nextId, task.id + 1); // } // } // // addTask(title) { // const newTask = { // id: this.nextId++, // title: title, // isCompleted: false, // }; // this.tasks.unshift(newTask); // this.trigger('update'); // } // // toggleTask(id) { // const task = this.tasks.find(t => t.id === id); // task.isCompleted = !task.isCompleted; // this.tasks.sort(function (a,b) { // if (a.isCompleted) { // if (b.isCompleted) { // a.title.localeCompare(b.title) // } else { // return 1; // } // } else { // if (b.isCompleted) { // return -1; // } else { // a.title.localeCompare(b.title) // } // } // }); // this.trigger('update') // } // // deleteTask(id) { // const index = this.tasks.findIndex(t => t.id === id); // this.tasks.splice(index, 1); // this.trigger('update'); // } // } // // class StoredTaskModel extends TaskModel { // constructor(storage) { // const tasks = storage.getItem("todoapp"); // super(tasks ? JSON.parse(tasks) : []); // this.on('update', this, () => { // storage.setItem("todoapp", JSON.stringify(this.tasks)) // }); // } // } // // // ------------------------------------------------------------------------- // // Task Component // // ------------------------------------------------------------------------- // const TASK_TEMPLATE = xml /* xml */` // <div class="task" t-att-class="props.task.isCompleted ? 'done' : ''"> // <input type="checkbox" t-att-checked="props.task.isCompleted" t-on-click="toggleTask"/> // <span><t t-esc="props.task.title"/></span> // <span class="delete" t-on-click="deleteTask">🗑</span> // </div>`; // // class Task extends Component { // static template = TASK_TEMPLATE; // // toggleTask() { // this.env.model.toggleTask(this.props.task.id); // } // // deleteTask() { // this.env.model.deleteTask(this.props.task.id); // } // } // // // ------------------------------------------------------------------------- // // App Component // // ------------------------------------------------------------------------- // const APP_TEMPLATE = xml /* xml */` // <div class="todo-app"> // <input placeholder="Enter a new task" t-on-keyup="addTask" t-ref="add-input"/> // <div class="task-list"> // <t t-foreach="env.model.tasks" t-as="task" t-key="task.id"> // <Task task="task"/> // </t> // </div> // </div>`; // // class App extends Component { // static template = APP_TEMPLATE; // static components = { Task }; // // inputRef = useRef("add-input"); // // constructor() { // super(); // // const model = new StoredTaskModel(this.env.localStorage); // model.on('update', this, this.render); // useSubEnv({model}); // } // // mounted() { // this.inputRef.el.focus(); // } // // addTask(ev) { // // 13 is keycode for ENTER // if (ev.keyCode === 13) { // const title = ev.target.value.trim(); // ev.target.value = ""; // if (title) { // this.env.model.addTask(title); // } // } // } // // } // // // Setup code // function setup() { // App.env.localStorage = window.localStorage; // const app = new App(); // app.mount(document.body); // } // // whenReady(setup); // })(); // (function () { // const {Component, mount} = owl; // const {xml} = owl.tags; // const {whenReady} = owl.utils; // const { useRef } = owl.hooks; // // const TASK_TEMPLATE = xml /* xml */` // <div class="task" t-att-class="props.task.isCompleted ? 'done' : ''"> // <input type="checkbox" t-att-checked="props.task.isCompleted"/> // <span><t t-esc="props.task.title"/></span> // </div>`; // // class Task extends Component { // static template = TASK_TEMPLATE; // static props = ["task"]; // } // // const APP_TEMPLATE = xml /* xml */` // <div class="todo-app"> // <input placeholder="Enter a new task" t-on-keyup="addTask" t-ref="add-input"/> // <div class="task-list"> // <t t-foreach="tasks" t-as="task" t-key="task.id"> // <Task task="task"/> // </t> // </div> // </div>`; // class App extends Component { // static template = APP_TEMPLATE; // static components = { Task }; // inputRef = useRef("add-input"); // // mounted() { // this.inputRef.el.focus(); // } // nextId = 1; // tasks = []; // addTask(ev) { // // 13 is keycode for ENTER // if (ev.keyCode === 13) { // const title = ev.target.value.trim(); // ev.target.value = ""; // if (title) { // const newTask = { // id: this.nextId++, // title: title, // isCompleted: false, // }; // this.tasks.push(newTask); // } // } // } // tasks = [ // { // id: 1, // title: "buy milk", // isCompleted: true, // }, // { // id: 2, // title: "clean house", // isCompleted: false, // }, // ]; // } // // Setup code // function setup() { // App.env.localStorage = window.localStorage; // const app = new App(); // inputRef = useRef("add-input"); // app.mount(document.body); // } // // whenReady(setup); // })(); (function () { const {Component, mount} = owl; const {xml} = owl.tags; const {whenReady} = owl.utils; const {useRef,useState} = owl.hooks; const TASK_TEMPLATE = xml /* xml */` <div class="task" t-att-class="props.task.isCompleted ? 'done' : ''"> <input type="checkbox" t-att-checked="props.task.isCompleted" t-on-click="toggleTask"/> <span><t t-esc="props.task.title"/></span> <span class="delete" t-on-click="deleteTask">🗑</span> </div>`; class Task extends Component { static template = TASK_TEMPLATE; static props = ["task"]; toggleTask() { this.trigger('toggle-task', {id: this.props.task.id}); } deleteTask() { this.trigger('delete-task', {id: this.props.task.id}); } } // ------------------------------------------------------------------------- // App Component // ------------------------------------------------------------------------- const APP_TEMPLATE = xml /* xml */` <div class="todo-app"> <input placeholder="Enter a new task" t-on-keyup="addTask" t-ref="add-input"/> <div class="task-list" t-on-toggle-task="toggleTask" t-on-delete-task="deleteTask"> <t t-foreach="tasks" t-as="task" t-key="task.id"> <Task task="task"/> </t> </div> </div>`; class App extends Component { static template = APP_TEMPLATE; static components = {Task}; inputRef = useRef("add-input"); mounted() { this.inputRef.el.focus(); } toggleTask(ev) { const task = this.tasks.find(t => t.id === ev.detail.id); task.isCompleted = !task.isCompleted; } nextId = 1; tasks = useState([]); addTask(ev) { // 13 is keycode for ENTER if (ev.keyCode === 13) { const title = ev.target.value.trim(); ev.target.value = ""; if (title) { const newTask = { id: this.nextId++, title: title, isCompleted: false, }; this.tasks.push(newTask); } } } deleteTask(ev) { const index = this.tasks.findIndex(t => t.id === ev.detail.id); this.tasks.splice(index, 1); } } // Setup code function setup() { App.env.localStorage = window.localStorage; const app = new App() app.mount(document.body) } whenReady(setup); })();
30.746795
98
0.414052
01036f09d062b763d8bb063d7a316726c3e73407
895
js
JavaScript
index.js
ajs256/ttr-tracker
22da3997a9b3b877d2ddcc5cfe68e89aa5d31572
[ "MIT" ]
null
null
null
index.js
ajs256/ttr-tracker
22da3997a9b3b877d2ddcc5cfe68e89aa5d31572
[ "MIT" ]
null
null
null
index.js
ajs256/ttr-tracker
22da3997a9b3b877d2ddcc5cfe68e89aa5d31572
[ "MIT" ]
null
null
null
var scores = [] scores['red'] = 0 scores['blue'] = 0 scores['green'] = 0 scores['yellow'] = 0 scores['black'] = 0 function changeScore (color, val) { scores[color] += val console.log('Adding', val, "to", color) updateScores() } function evalCustom (color, id, subtract) { input = Number(document.getElementById(id).value) if (subtract == true) { changeScore(color, -Math.abs(input)) return } changeScore(color, input) updateScores() } function updateScores() { document.getElementById('redScore').innerHTML = scores['red'] document.getElementById('blueScore').innerHTML = scores['blue'] document.getElementById('greenScore').innerHTML = scores['green'] document.getElementById('yellowScore').innerHTML = scores['yellow'] document.getElementById('blackScore').innerHTML = scores['black'] } // window.onload = updateScores()
27.96875
71
0.670391
0103a3eaa0dac9453a0267d23581665897df327a
1,826
js
JavaScript
src/components/layout/Side.js
charlievillacr/css-grid-playground
60c78e923da0ad371afe35785b67881848a2ac99
[ "MIT" ]
null
null
null
src/components/layout/Side.js
charlievillacr/css-grid-playground
60c78e923da0ad371afe35785b67881848a2ac99
[ "MIT" ]
null
null
null
src/components/layout/Side.js
charlievillacr/css-grid-playground
60c78e923da0ad371afe35785b67881848a2ac99
[ "MIT" ]
null
null
null
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Link from 'gatsby-link'; import pageData from '../../data/pageData'; // images import done from '../img/done.svg'; import current from '../img/current.svg'; // individual side-nav items const SideItem = props => ( <Link to={props.link}> <div className={classNames( 'side-nav__item', { 'is-active': props.currentPageNum === props.order }, { 'is-done': props.order < props.currentPageNum }, )} > <div className="side-nav__wrap"> <div className="side-nav__circle"> <div className="side-nav__circle-inner"> {props.currentPageNum === props.order ? <img alt="current" src={current} /> : ''} {props.order < props.currentPageNum ? <img alt="done" src={done} /> : ''} </div> </div> <span className="side-nav__page">{props.title}</span> </div> <div className={ props.currentPageNum > props.order && props.order !== pageData.length ? 'side-nav__line is-active' : 'side-nav__line' } /> </div> </Link> ); // The entire sidebar const Side = (props) => { const pages = pageData.map(page => ( <SideItem key={page.order} currentPageNum={props.currentPageNum} order={page.order} title={page.title} link={page.link} /> )); return <div className="side">{pages}</div>; }; SideItem.propTypes = { currentPageNum: PropTypes.number.isRequired, order: PropTypes.number.isRequired, title: PropTypes.string.isRequired, link: PropTypes.string.isRequired, }; Side.propTypes = { currentPageNum: PropTypes.number.isRequired, }; SideItem.defaultProps = { active: false, }; export default Side;
25.361111
93
0.610077
0104bcd580899a776ce367a385a4f945e9d6bdba
2,116
js
JavaScript
src/modules/student/models/model.js
CASAN-TH/students-service
de1df218cd4513c8b4affc7b3d67a320937afd77
[ "MIT" ]
null
null
null
src/modules/student/models/model.js
CASAN-TH/students-service
de1df218cd4513c8b4affc7b3d67a320937afd77
[ "MIT" ]
1
2021-05-10T05:14:02.000Z
2021-05-10T05:14:02.000Z
src/modules/student/models/model.js
CASAN-TH/students-service
de1df218cd4513c8b4affc7b3d67a320937afd77
[ "MIT" ]
null
null
null
"use strict"; // use model var mongoose = require("mongoose"); var Schema = mongoose.Schema; var StudentSchema = new Schema({ school: { type: String, required: "Please fill a Student school" }, class: { type: String, required: "Please fill a Student class" }, room: { type: Number }, studentnumber: { type: Number }, studentid: { type: String, required: "Please fill a Student studentid" }, prefix: { type: String, required: "Please fill a Student prefix" }, firstname: { type: String, required: "Please fill a Student firstname" }, lastname: { type: String, required: "Please fill a Student lastname" }, identificationnumber: { type: Number, required: "Please fill a Student identificationnumber" }, attendancedate: { type: String }, oldschool: { type: String }, province: { type: String }, lastfloor: { type: String }, birthday: { type: String, required: "Please fill a Student birthday" }, sex: { type: String, required: "Please fill a Student sex" }, nationality: { type: String }, religion: { type: String }, fatherfullname: { type: String, required: "Please fill a Student fatherfullname" }, motherfullname: { type: String, required: "Please fill a Student motherfullname" }, phonenumber: { type: String, required: "Please fill a Student phonenumber" }, pp1set: { type: String }, pp1number: { type: String }, pp2number: { type: String }, enddateofapproval: { type: String }, approvaldate: { type: String }, cause: { type: String }, created: { type: Date, default: Date.now }, updated: { type: Date }, createby: { _id: { type: String }, username: { type: String }, displayname: { type: String } }, updateby: { _id: { type: String }, username: { type: String }, displayname: { type: String } } }); mongoose.model("Student", StudentSchema);
16.152672
58
0.57656
0104ec8a48ba9cc4371a1bb6e9d8aa6b62ed624c
231
js
JavaScript
src/app/components/navigationData/navigation.component.js
todes1/webtrkk-test
cd25b81e29780e52ac9369913dfaca29de5663ac
[ "MIT" ]
null
null
null
src/app/components/navigationData/navigation.component.js
todes1/webtrkk-test
cd25b81e29780e52ac9369913dfaca29de5663ac
[ "MIT" ]
null
null
null
src/app/components/navigationData/navigation.component.js
todes1/webtrkk-test
cd25b81e29780e52ac9369913dfaca29de5663ac
[ "MIT" ]
null
null
null
import template from './navigation.template.html'; import navigationController from './navigation.controller'; const navigationComponent = { template, controller: navigationController } export default navigationComponent
23.1
59
0.796537
0105254f5582ed704b154fe398eb289fd4073f75
372
js
JavaScript
lib/spotify.js
iksena/zonify
853db15321eb73a58f524773968519c8a7e7dd80
[ "MIT" ]
null
null
null
lib/spotify.js
iksena/zonify
853db15321eb73a58f524773968519c8a7e7dd80
[ "MIT" ]
null
null
null
lib/spotify.js
iksena/zonify
853db15321eb73a58f524773968519c8a7e7dd80
[ "MIT" ]
null
null
null
import SpotifyWebApi from 'spotify-web-api-node'; import constants from './constants'; const initiateSpotify = (params) => { const spotify = new SpotifyWebApi({ clientId: constants.SPOTIFY_CLIENT_ID, clientSecret: constants.SPOTIFY_CLIENT_SECRET, redirectUri: constants.BASE_URL, ...params, }); return spotify; }; export default initiateSpotify;
21.882353
50
0.733871
010596f322da3a59b8227f1aec39ec45f91dc450
55
js
JavaScript
index.js
rwoody/test-js
03fabf44429e65f3ad24028944f8e845ef992571
[ "MIT" ]
null
null
null
index.js
rwoody/test-js
03fabf44429e65f3ad24028944f8e845ef992571
[ "MIT" ]
null
null
null
index.js
rwoody/test-js
03fabf44429e65f3ad24028944f8e845ef992571
[ "MIT" ]
null
null
null
var a = require('./lib/a') module.exports = { a: a }
11
26
0.545455
01059a906a645b893b9a32fce9bed6c5c2ae95be
369
js
JavaScript
frontend/src/components/MapComponent.js
neilpimley/cardio-react
88a76e7471a60c517a7c7a0327f7a97a9d5c8b8f
[ "MIT" ]
null
null
null
frontend/src/components/MapComponent.js
neilpimley/cardio-react
88a76e7471a60c517a7c7a0327f7a97a9d5c8b8f
[ "MIT" ]
null
null
null
frontend/src/components/MapComponent.js
neilpimley/cardio-react
88a76e7471a60c517a7c7a0327f7a97a9d5c8b8f
[ "MIT" ]
null
null
null
import React from "react"; import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps"; export const MapComponent = withScriptjs(withGoogleMap((props) => <GoogleMap defaultZoom={12} defaultCenter={{ lat: 54.594, lng: -5.805 }} > {props.isMarkerShown && <Marker position={{ lat: 54.594882, lng: -5.805230 }} />} </GoogleMap> ))
30.75
85
0.677507
01081441e47fa229b586c384e1b5672345e7b9a9
1,171
js
JavaScript
src/utils/storage/index.js
Ha-Young/my-blo
843859d38e43b91fc9dcb7a77d21808722db227a
[ "MIT" ]
null
null
null
src/utils/storage/index.js
Ha-Young/my-blo
843859d38e43b91fc9dcb7a77d21808722db227a
[ "MIT" ]
6
2020-06-26T08:51:10.000Z
2020-06-30T05:32:24.000Z
src/utils/storage/index.js
Ha-Young/my-blo
843859d38e43b91fc9dcb7a77d21808722db227a
[ "MIT" ]
null
null
null
import { setValueToSessionStorage, getValueFromSessionStorage, } from './sessionStorage' import { setValueToLocalStorage, getValueFromLocalStorage, } from './localStorage' const SESSION_STORAGE_KEY = '__felog_session_storage_key__' const LOCAL_STORAGE_KEY = '__felog_local_storage_key__' export function getCount(defaultValue) { return ( getValueFromSessionStorage(`${SESSION_STORAGE_KEY}/count`) || defaultValue ) } export function setCount(val) { return setValueToSessionStorage(`${SESSION_STORAGE_KEY}/count`, val) } export function getData() { return getValueFromLocalStorage(LOCAL_STORAGE_KEY) } export function setData(val) { return setValueToLocalStorage(LOCAL_STORAGE_KEY, val) } export function getTheme(defaultValue) { return getValueFromLocalStorage(`${LOCAL_STORAGE_KEY}/theme`) || defaultValue } export function setTheme(val) { return setValueToLocalStorage(`${LOCAL_STORAGE_KEY}/theme`, val) } export function getEffect(defaultValue) { return getValueFromLocalStorage(`${LOCAL_STORAGE_KEY}/effect`) || defaultValue } export function setEffect(val) { return setValueToLocalStorage(`${LOCAL_STORAGE_KEY}/effect`, val) }
25.456522
80
0.789069
010857b48548d9176636576641bc53c2a7b95f8f
206
js
JavaScript
benchmark/training/auth.js
linda121084/Autocannon
343e39c609c861ba3f99746cd242527ca4fef821
[ "MIT" ]
null
null
null
benchmark/training/auth.js
linda121084/Autocannon
343e39c609c861ba3f99746cd242527ca4fef821
[ "MIT" ]
2
2021-05-10T19:41:19.000Z
2021-09-02T02:31:11.000Z
benchmark/training/auth.js
linda121084/Autocannon
343e39c609c861ba3f99746cd242527ca4fef821
[ "MIT" ]
null
null
null
import { API_PATH } from './_env'; export default [ // 登入 { method: 'POST', path: `${API_PATH}/permissions/login`, body: JSON.stringify({ userName: '858142', password: '858142' }), }, ];
18.727273
69
0.582524
010b450e06322b36b6986ddc56c02c1e9161138d
973
js
JavaScript
packages/qc-webpack-seed/config/dev.config.js
jermken/qc
5c16ef4dbfdcbb5e14e43bce5cc4891d762d8bf0
[ "MIT" ]
null
null
null
packages/qc-webpack-seed/config/dev.config.js
jermken/qc
5c16ef4dbfdcbb5e14e43bce5cc4891d762d8bf0
[ "MIT" ]
1
2022-02-27T09:16:09.000Z
2022-02-27T09:16:09.000Z
packages/qc-webpack-seed/config/dev.config.js
jermken/qc-workflow
5c16ef4dbfdcbb5e14e43bce5cc4891d762d8bf0
[ "MIT" ]
null
null
null
const path = require('path') const merge = require('webpack-merge') const webpack = require('webpack') const friendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin') const baseConf = require('./base.config.js') let plugins = [new webpack.HotModuleReplacementPlugin()] module.exports = (options) => merge(baseConf, { mode: process.env.NODE_ENV || 'development', output: { path: path.join(process.env.CWD, './dist'), filename: '[name].js' }, module: { }, devServer: { contentBase: path.join(process.env.CWD, './dist'), historyApiFallback: true, hot: true, port: 8080, open: false, inline: true, progress: true, quiet: options.silent || false }, devtool: 'inline-source-map', plugins: options.silent ? plugins.concat( [new friendlyErrorsWebpackPlugin({messages: ['compiled successfully.']})] ) : plugins })
28.617647
85
0.612539
010c7d79347ab10d6692f41de7fea0dd2c17f065
2,982
js
JavaScript
src/components/footer/style.js
daniellimhong/say-their-names-web
2fa03bfe8a37fa85f5acb442fd960c295ee187d8
[ "MIT" ]
null
null
null
src/components/footer/style.js
daniellimhong/say-their-names-web
2fa03bfe8a37fa85f5acb442fd960c295ee187d8
[ "MIT" ]
null
null
null
src/components/footer/style.js
daniellimhong/say-their-names-web
2fa03bfe8a37fa85f5acb442fd960c295ee187d8
[ "MIT" ]
null
null
null
import styled from 'styled-components'; import Color from '../../constants/Color'; const StyledFooterContainer = styled.footer` display: flex; flex-wrap: wrap; width: 100%; border-top: 2px solid ${Color.GREY}; justify-content: center; `; const FooterContainer = styled.section` display: flex; flex-wrap: wrap; justify-content: space-between; @media (max-width: 780px) { flex-direction: column; } `; const StyledFooter = styled.div` display: flex; flex-direction: column; width: ${(props) => (props.width ? props.width : '20%')} ; h2 { margin: 0px; font-size: 17px; line-height: 20px; }; background-color: ${Color.WHITE}; @media (max-width: 780px) { width: 100%; align-items: center; margin: 0.5rem; } `; const StyledFooterLinks = styled.div` display: flex; flex-wrap: wrap; flex-direction: column; margin: 1rem 0; a { padding: 0.3rem 0rem; color: ${Color.PRIMARY}; &:hover { opacity: 0.6; } } a:not(:first-child) { margin-top: 0.5rem; } @media (max-width: 780px) { align-items: center; } `; const StyleFooterForm = styled.form` display: flex; flex-wrap: wrap; flex-direction: column; width: 40%; margin: 1rem 0; @media (max-width: 850px) { width: 45%; } @media (max-width: 750px) { width: 55%; } @media (max-width: 650px) { width: 100%; align-items: center; } span { color: ${Color.RED}; margin: 0.5rem 0; } h4 { text-transform: uppercase; } .form-container { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; border: 2px solid black; border-radius: 5px; padding: 0.5rem; @media (max-width: 650px) { width: 70%; } @media (max-width: 450px) { width: 90%; } @media (max-width: 350px) { width: 95%; } input { width: 70%; font-family: "Karla", sans-serif; border: none; padding: 0.5rem; &:focus { border: none; outline: none; background: white !important; } } button { width: 20%; border: none; font-family: "Karla", sans-serif; padding: 0.5rem; background-color: white; cursor: pointer; &:focus { border: none; outline: none; background: white !important; } } } `; const StyledFooterMissions = styled.div` display: flex; flex-wrap: wrap; flex-direction: column; width: 80%; @media (max-width: 780px) { width: 100%; margin: 1rem; } p { margin-bottom: 0; @media (max-width: 780px) { text-align: center; } } `; const DowloadLogo = styled.div` display: flex; justify-content: flex-start; img { width: 80%; padding: 0.3rem; } `; export { StyledFooterContainer, StyledFooter, StyledFooterLinks, StyledFooterMissions, StyleFooterForm, FooterContainer, DowloadLogo };
16.943182
60
0.583501
010dff5d7405815ac1899267a9a5a49c8cffa940
2,148
js
JavaScript
src/components/data/work.js
josemartin357/react-portfolio
e398f7ec5accd4c976e268cf43b97ebc23576ee1
[ "MIT" ]
null
null
null
src/components/data/work.js
josemartin357/react-portfolio
e398f7ec5accd4c976e268cf43b97ebc23576ee1
[ "MIT" ]
null
null
null
src/components/data/work.js
josemartin357/react-portfolio
e398f7ec5accd4c976e268cf43b97ebc23576ee1
[ "MIT" ]
null
null
null
export const WorkData = [ { id: 1, company: "Southern Methodist University", title: "Full-stack Development Student", location: "Dallas,TX", startDate: "July, 2021", endDate: "February, 2022", companyLogo: require("./assets/smu-logo.png"), duties: 'Currently participating in a fast-track program, in which I learned front and back-end web development. In it, I have developed various projects while maintaining an "A" as my average grade.', }, { id: 2, company: "NBC Universal", title: "Senior Producer", location: "Fort Worth,TX", startDate: "January, 2017", endDate: "current", companyLogo: require("./assets/nbcuniversal-logo.png"), duties: "Created, wrote and managed newscasts and special projects. Also, led and trained personnel. Recognitions: Emmy Award for breaking news and leaders in Nielsen ratings multiple times.", }, { id: 3, company: "NBC Universal", title: "Producer", location: "Houston,TX", startDate: "April, 2015", endDate: "December, 2016", companyLogo: require("./assets/nbcuniversal-logo.png"), duties: "Created, executed and managed tv and web content (articles, galleries, videos). Recognitions: Increased ratings in primetime and weekend shows. Many projects recognized with Emmy awards.", }, { id: 4, company: "Tyler Media", title: "News Director", location: "Oklahoma City, OK", startDate: "July, 2013", endDate: "March, 2015", companyLogo: require("./assets/tylermedia-logo.png"), duties: "Managed news department and established short and long-term goals. Handled PR programs. Recognitions: Launched weekend shows, led App launch and created 1st bilingual meteorologists unit.", }, { id: 5, company: "Tyler Media", title: "Evening News Producer", location: "Oklahoma City, OK", startDate: "April, 2012", endDate: "July, 2013", companyLogo: require("./assets/tylermedia-logo.png"), duties: "Selected content, created graphics and write stories. Also, promoted content on tv, radio and social media.", }, ];
37.034483
199
0.673184
010e989f570dac4bcbffd52427d4ac4fdb23a47a
3,908
js
JavaScript
src/react/Reducers/accounts.js
fossabot/bunqDesktop
896780dc75dca19665130fd2d0c4050cb8038a39
[ "MIT" ]
null
null
null
src/react/Reducers/accounts.js
fossabot/bunqDesktop
896780dc75dca19665130fd2d0c4050cb8038a39
[ "MIT" ]
null
null
null
src/react/Reducers/accounts.js
fossabot/bunqDesktop
896780dc75dca19665130fd2d0c4050cb8038a39
[ "MIT" ]
null
null
null
import store from "store"; import settings from "../ImportWrappers/electronSettings"; import { STORED_ACCOUNTS } from "../Actions/accounts"; export const SELECTED_ACCOUNT_LOCAION = "BUNQDESKTOP_SELECTED_ACCOUNT"; export const EXCLUDED_ACCOUNT_IDS = "BUNQDESKTOP_EXCLUDED_ACCOUNT_IDS"; const excludedAccountIdsStored = settings.get(EXCLUDED_ACCOUNT_IDS); const selectedAccountStored = store.get(SELECTED_ACCOUNT_LOCAION); const selectedAccountDefault = selectedAccountStored !== undefined ? selectedAccountStored : false; const excludedAccountIdsDefault = excludedAccountIdsStored !== undefined ? excludedAccountIdsStored : []; console.log(excludedAccountIdsDefault) export const defaultState = { accounts: [], loading: false, selectedAccount: selectedAccountDefault, excludedAccountIds: excludedAccountIdsDefault }; export default (state = defaultState, action) => { switch (action.type) { case "ACCOUNTS_SET_INFO": // store the data if we have access to the bunqjsclient if (action.payload.BunqJSClient) { action.payload.BunqJSClient.Session.storeEncryptedData( { items: action.payload.accounts }, STORED_ACCOUNTS ) .then(() => {}) .catch(() => {}); } return { ...state, accounts: action.payload.accounts }; case "ACCOUNTS_SELECT_ACCOUNT": store.set(SELECTED_ACCOUNT_LOCAION, action.payload.selectedAccount); return { ...state, selectedAccount: action.payload.selectedAccount }; case "ACCOUNTS_EXCLUDE_FROM_TOTAL": const currentAccountIds = [...state.excludedAccountIds]; const existingIndex = state.excludedAccountIds.indexOf( action.payload.account_id ); if (existingIndex === -1) { // doesn't exist, add account id to excluded list currentAccountIds.push(action.payload.account_id); // store in settings settings.set(EXCLUDED_ACCOUNT_IDS, currentAccountIds); } return { ...state, excludedAccountIds: currentAccountIds }; case "ACCOUNTS_INCLUDE_IN_TOTAL": const currentAccountIds2 = [...state.excludedAccountIds]; const existingIndex2 = state.excludedAccountIds.indexOf( action.payload.account_id ); if (existingIndex2 > -1) { // exists, remove the id from the excluded list currentAccountIds2.splice(existingIndex2, 1); // store in settings settings.set(EXCLUDED_ACCOUNT_IDS, currentAccountIds2); } return { ...state, excludedAccountIds: currentAccountIds2 }; case "ACCOUNTS_IS_LOADING": case "ACCOUNT_CREATE_IS_LOADING": case "ACCOUNT_STATUS_IS_LOADING": return { ...state, loading: true }; case "ACCOUNTS_IS_NOT_LOADING": case "ACCOUNT_CREATE_IS_NOT_LOADING": case "ACCOUNT_STATUS_IS_NOT_LOADING": return { ...state, loading: false }; case "ACCOUNTS_CLEAR": case "REGISTRATION_CLEAR_PRIVATE_DATA": case "REGISTRATION_LOG_OUT": case "REGISTRATION_CLEAR_USER_INFO": store.remove(SELECTED_ACCOUNT_LOCAION); store.remove(STORED_ACCOUNTS); return { accounts: [], selectedAccount: false, loading: false }; } return state; };
32.566667
80
0.57651
010eb4ace1fbe5d1725cf3d0c254bf62c56895c0
704
js
JavaScript
CyberPunk.js
NicholasARossi/MMM-CyberPunk
e6e78a6aebebaf1e732c7631364063a266ec1df7
[ "MIT" ]
null
null
null
CyberPunk.js
NicholasARossi/MMM-CyberPunk
e6e78a6aebebaf1e732c7631364063a266ec1df7
[ "MIT" ]
null
null
null
CyberPunk.js
NicholasARossi/MMM-CyberPunk
e6e78a6aebebaf1e732c7631364063a266ec1df7
[ "MIT" ]
null
null
null
/* global Module */ /* Magic Mirror * Module: CyberPunk * * By * MIT Licensed. */ Module.register("CyberPunk", { defaults: { updateInterval: 60000, retryDelay: 5000 }, requiresVersion: "2.1.0", // Required version of MagicMirror getDom: function() { var self = this; // create element wrapper for show into the module var wrapper = document.createElement("div"); // If this.dataRequest is not empty var text=document.createElement("div"); var termynal = new Termynal('#termynal'); wrapper.append(termynal) return wrapper; }, getScripts: function() { return ['termynal.js']; }, getStyles: function () { return [ "CyberPunk.css", ]; }, });
12.8
61
0.640625
010fbff3477c1b48d794038dee61acb7e15d3db6
1,074
js
JavaScript
mob_twitter/src/actions/tweetActions.js
Mazurco066/GoWeek-Rocketseat
097c9ac0a918c6f15955d93c21fa7b2f94307fde
[ "MIT" ]
null
null
null
mob_twitter/src/actions/tweetActions.js
Mazurco066/GoWeek-Rocketseat
097c9ac0a918c6f15955d93c21fa7b2f94307fde
[ "MIT" ]
null
null
null
mob_twitter/src/actions/tweetActions.js
Mazurco066/GoWeek-Rocketseat
097c9ac0a918c6f15955d93c21fa7b2f94307fde
[ "MIT" ]
null
null
null
// Importação do uso da api import axios from 'axios' // Definição da Url base da Api const BASE_URL = 'http://10.0.3.2:3001' // Ação de alteração no conteúdo do tweet export const handleInputChange = (text) => ({ type: 'NEW_TWEET_CHANGED', payload: text }) // Ação de criar novo tweet export const handleNewTweet = (tweet) => { return dispatch => { axios.post(`${BASE_URL}/tweets`, tweet) .then(() => { dispatch({ type: 'NEW_TWEET', payload: '' }) }) } } // Ação de dar like em tweet export const handleLike = (id) => { return (dispatch) => { axios.post(`${BASE_URL}/likes/${id}`) .then(() => { dispatch({ type: 'LIKE_TWEET', }) }) } } // Ação de listagem de tweets export const search = () => { return (dispatch) => { axios.get(`${BASE_URL}/tweets`) .then(resp => dispatch({type: 'LIST_TWEETS', payload: resp.data})) } }
23.866667
78
0.5
011044b79ad228e8a0671c85703a9fba76d755d7
1,248
js
JavaScript
src/components/VideoDetail.js
devworld0114/youtube-searcher-reactjs
2fec8d16ab005748b071fdf51ceb1e8ab35862d8
[ "MIT" ]
null
null
null
src/components/VideoDetail.js
devworld0114/youtube-searcher-reactjs
2fec8d16ab005748b071fdf51ceb1e8ab35862d8
[ "MIT" ]
null
null
null
src/components/VideoDetail.js
devworld0114/youtube-searcher-reactjs
2fec8d16ab005748b071fdf51ceb1e8ab35862d8
[ "MIT" ]
null
null
null
import React from 'react'; import Timestamp from 'react-timestamp'; import './VideoDetail.css'; const VideoDetail = ({ video }) => { if (!video) { return ( <div className="block"> {/*<span className="loader"></span>*/} <h4 className="title is-2 is-unselectable is-centered"> Loading <span className="dot">.</span> <span className="dot">.</span> <span className="dot">.</span> </h4> </div> ); } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return ( <div className="video-detail column is-8"> <div className="video-container"> <iframe title="video_yt" src={url} width="700" height="350" /> </div> <br /> <div className="box video-meta"> <div className="video-title"> {video.snippet.title} </div> <div> <small> by {video.snippet.channelTitle}, Published on{' '} <Timestamp time={video.snippet.publishedAt} precision={2} /> </small> </div> <article className="media"> <div className="media-content"> <div className="content"> <p> {video.snippet.description} </p> </div> </div> </article> </div> </div> ); }; export default VideoDetail;
22.690909
66
0.588141
0112cee707eb71291e2e288e6d82c28fddd76893
1,870
js
JavaScript
src/utils.js
h-kishi/serverless-appsync-plugin
4832011350e8db9e381bf88418432b413f02ad7f
[ "MIT" ]
null
null
null
src/utils.js
h-kishi/serverless-appsync-plugin
4832011350e8db9e381bf88418432b413f02ad7f
[ "MIT" ]
null
null
null
src/utils.js
h-kishi/serverless-appsync-plugin
4832011350e8db9e381bf88418432b413f02ad7f
[ "MIT" ]
null
null
null
const moment = require('moment'); const { upperFirst, transform } = require('lodash'); const timeUnits = [ 'years?', 'y', 'quarters?', 'Q', 'months?', 'M', 'weeks?', 'w', 'days?', 'd', 'hours?', 'h', 'minutes?', 'm', 'seconds?', 's', 'milliseconds?', 'ms', ]; const toCfnKeys = object => transform( object, (acc, value, key) => { const newKey = typeof key === 'string' ? upperFirst(key) : key; acc[newKey] = typeof value === 'object' ? toCfnKeys(value) : value; return acc; }, ); module.exports = { parseDuration: (input) => { let duration; if (typeof input === 'number') { duration = moment.duration(input, 'hours'); } else if (typeof input === 'string') { const regexp = new RegExp(`^(\\d+)(${timeUnits.join('|')})$`); const match = input.match(regexp); if (match) { let amount = match[1]; let unit = match[2]; // 1 year could be 366 days on or before leap year, // which would fail. Swap for 365 days if (input.match(/^1y(ears?)?$/)) { amount = 365; unit = 'days'; } duration = moment.duration(amount, unit || 'hours'); } else { throw new Error(`Could not parse ${input} as a valid duration`); } } else { throw new Error(`Could not parse ${input} as a valid duration`); } // Minimum duration is 1 day from 'now' // However, api key expiry is rounded down to the hour. // meaning the minimum expiry date is in fact 25 hours // We accept 24h durations for simplicity of use // but fix them to be 25 // Anything < 24h will be kept to make sure the validation fails later if (duration.asHours() >= 24 && duration.asHours() < 25) { duration = moment.duration(25, 'hours'); } return duration; }, toCfnKeys, };
25.972222
74
0.557754
01163d751b5f77afc3bbadc731d9e36cba50f85f
606
js
JavaScript
server/routes/users.js
AlulaLeak/sports-betting-app
643a1af9b89858480af4b1adf398fc56c7a1f98e
[ "MIT" ]
null
null
null
server/routes/users.js
AlulaLeak/sports-betting-app
643a1af9b89858480af4b1adf398fc56c7a1f98e
[ "MIT" ]
null
null
null
server/routes/users.js
AlulaLeak/sports-betting-app
643a1af9b89858480af4b1adf398fc56c7a1f98e
[ "MIT" ]
null
null
null
/* * All routes for Users are defined here * Since this file is loaded in server.js into api/users, * these routes are mounted onto /users * See: https://expressjs.com/en/guide/using-middleware.html#middleware.router */ const express = require("express"); const router = express.Router(); module.exports = (db) => { router.get("/", (req, res) => { db.query(`SELECT * FROM users;`) .then((data) => { const users = data.rows; res.json({ users }); }) .catch((err) => { res.status(500).json({ error: err.message }); }); }); return router; };
24.24
78
0.589109
0116c7409af38a6f4cc9330afec88d8dd910033c
285
js
JavaScript
src/components/Giphy.js
rubenberna/react-switch-app-one
1282410d4c07c7582408eb98661886387eabc5ca
[ "MIT" ]
null
null
null
src/components/Giphy.js
rubenberna/react-switch-app-one
1282410d4c07c7582408eb98661886387eabc5ca
[ "MIT" ]
null
null
null
src/components/Giphy.js
rubenberna/react-switch-app-one
1282410d4c07c7582408eb98661886387eabc5ca
[ "MIT" ]
null
null
null
import React from 'react' export const Boring = () => { return ( <React.Fragment> <iframe src="https://giphy.com/embed/xT5LMEcHRXKXpIHCCI" width="480" height="362" frameBorder="0" className="giphy-embed" allowFullScreen></iframe> </React.Fragment> ) }
25.909091
103
0.642105
010168b5a0543e7e0709b4c35505de19e585e1c2
1,053
js
JavaScript
app/routes/admin/password.js
CloudKidStudio/Thunder
791fb28d4fb949768ec8e5447a09863794dda1f6
[ "MIT" ]
2
2015-06-15T12:49:02.000Z
2015-08-04T01:55:45.000Z
app/routes/admin/password.js
CloudKidStudio/Thunder
791fb28d4fb949768ec8e5447a09863794dda1f6
[ "MIT" ]
null
null
null
app/routes/admin/password.js
CloudKidStudio/Thunder
791fb28d4fb949768ec8e5447a09863794dda1f6
[ "MIT" ]
null
null
null
var router = require('express').Router(); router.get('/', function(req, res) { render(res, null, req.flash('success')); }); router.post('/', function(req, res) { req.checkBody('oldPassword', 'Current Password is required.').notEmpty(); req.checkBody('newPassword', 'New Password is required.').notEmpty(); req.checkBody('repeatPassword', 'Repeat Password must be equal to New Password.') .equals(req.body.newPassword); var errors = req.validationErrors() || []; if (!req.user.comparePassword(req.body.oldPassword)) { errors.push({ msg: 'Current password is invalid.' }); } if (errors.length) { render(res, errors); return; } req.user.password = req.body.newPassword; req.user.save( function(err, user) { req.flash('success', 'Password updated!'); res.redirect(req.originalUrl); } ); }); function render(res, errors, success) { if (typeof errors == "string") { errors = [{ msg:errors }]; } res.render('admin/password', { errors: errors || [], success: success || null }); } module.exports = router;
20.647059
82
0.65717
bbf33d20d9140e0c0caee186bf1e7532cf5412c4
1,097
js
JavaScript
index.js
azu/gulp-inlining-node-require
35b3e41ec6bc00b38a849c1c89397cdd942647ee
[ "MIT" ]
2
2015-08-14T16:19:44.000Z
2016-06-03T23:35:17.000Z
index.js
azu/gulp-inlining-node-require
35b3e41ec6bc00b38a849c1c89397cdd942647ee
[ "MIT" ]
null
null
null
index.js
azu/gulp-inlining-node-require
35b3e41ec6bc00b38a849c1c89397cdd942647ee
[ "MIT" ]
null
null
null
var through = require("through2"), gutil = require("gulp-util"); var inlining = require("inlining-node-require"); module.exports = function (options) { "use strict"; function inliningNodeRequire(file, enc, callback) { /*jshint validthis:true*/ if (file.isNull()) { this.push(file); return callback(); } if (file.isStream()) { this.emit("error", new gutil.PluginError("gulp-inlining-node-require", "Stream content is not supported")); return callback(); } // check if file.contents is a `Buffer` if (file.isBuffer()) { try { file.contents = Buffer.from(inlining(file.path, options)); } catch (error) { this.emit("error", new gutil.PluginError("gulp-inlining-node-require", "Could not inlining file " + file.path)); return callback(); } this.push(file); } return callback(); } return through.obj(inliningNodeRequire); };
28.868421
113
0.534184
010398b8b7f16ea273197235b8532a1bfa82d6ed
1,942
js
JavaScript
HubTaxi-Client/manager/scripts/controllers/login.js
namndbka/HubTaxi
603e3367ff66f7053142bd0c55e3aeedbe10daac
[ "Apache-2.0" ]
2
2017-07-01T05:12:03.000Z
2017-07-20T16:01:26.000Z
manager/scripts/controllers/login.js
sithukyaw007/HubTaxi-Client
6d4b245166de56bd1db4afcb4a87510124660823
[ "MIT" ]
2
2016-06-15T01:19:58.000Z
2017-01-14T16:19:14.000Z
manager/scripts/controllers/login.js
sithukyaw007/HubTaxi-Client
6d4b245166de56bd1db4afcb4a87510124660823
[ "MIT" ]
7
2017-05-17T07:22:11.000Z
2021-05-28T22:34:35.000Z
/** * Created by chris on 6/24/14. */ angular.module('itaxiManagerApp') .controller('loginCtrl', ['$scope', '$rootScope', '$state' , '$auth', '$logger', '$timeout', function ($scope, $rootScope, $state, $auth, $logger, $timeout) { $scope.data = {}; $scope.loginErr = null; $rootScope.userFullName = $auth.getUserFullName(); $scope.isSubmitting = null; // Required - set to 'success' or 'error' on success/failure $scope.result = null; // Function run ng-bs-animate-button $scope.fakeSubmit = function() { $scope.isSubmitting = true; }; $scope.options = { buttonDefaultText: 'Đăng nhập', buttonSubmittingText: 'Đang đăng nhập', buttonSuccessText: 'Đăng nhập thành công', buttonErrorText: 'Đăng nhập sai', buttonDefaultClass: 'btn-default', buttonSubmittingClass: 'btn-info', buttonSuccessClass: 'btn-success' }; $scope.loginFunc = function(data) { if (data.user == null || data.pass == null) { $scope.loginErr = 'Vui lòng nhập đầy đủ'; $scope.result = 'error'; } else { $scope.loginProcess = true; $auth.login(data.user, data.pass, function (err, resp) { $scope.loginProcess = false; if (err) { $scope.loginErr = 'Tài khoản hay mật khẩu không đúng!'; $scope.data.pass = null; $scope.result = 'error'; } else { $scope.result = 'success'; $state.go('main.googlemap'); $rootScope.userInfo = $auth.getUser(); //console.log('User: ', $auth.getUser()); } }) } }; }]);
36.641509
163
0.481462
010b16922cf241bcc37f847e6560e1a077644660
1,267
js
JavaScript
addon/mixins/multiple-expanded-validators.js
wearemolecule/date-range-picker
b00c4180a0c26d69254cbc9e1ee336e89427b929
[ "MIT" ]
4
2016-09-23T14:17:00.000Z
2018-04-04T21:02:06.000Z
addon/mixins/multiple-expanded-validators.js
wearemolecule/date-range-picker
b00c4180a0c26d69254cbc9e1ee336e89427b929
[ "MIT" ]
90
2016-03-22T21:17:32.000Z
2021-09-01T07:35:29.000Z
addon/mixins/multiple-expanded-validators.js
wearemolecule/date-range-picker
b00c4180a0c26d69254cbc9e1ee336e89427b929
[ "MIT" ]
2
2017-05-19T18:49:41.000Z
2017-05-26T15:50:52.000Z
import Ember from 'ember'; const { observer } = Ember; export default Ember.Mixin.create({ leftMonthIsExpanded: true, leftYearIsExpanded: false, rightMonthIsExpanded: true, rightYearIsExpanded: false, _leftMonthIsExpandedValidator: observer('leftMonthIsExpanded', function() { if (this.get('leftMonthIsExpanded') === true) { this.set('leftYearIsExpanded', false); } }), _leftYearIsExpandedValidator: observer('leftYearIsExpanded', function() { if (this.get('leftYearIsExpanded') === true) { this.set('leftMonthIsExpanded', false); } }), _rightMonthIsExpandedValidator: observer('rightMonthIsExpanded', function() { if (this.get('rightMonthIsExpanded') === true) { this.set('rightYearIsExpanded', false); } }), _rightYearIsExpandedValidator: observer('rightYearIsExpanded', function() { if (this.get('rightYearIsExpanded') === true) { this.set('rightMonthIsExpanded', false); } }), actions: { toggleLeftYearExpanded() { this.toggleProperty('leftYearIsExpanded'); this.toggleProperty('leftMonthIsExpanded'); }, toggleRightYearExpanded() { this.toggleProperty('rightYearIsExpanded'); this.toggleProperty('rightMonthIsExpanded'); }, } });
26.957447
79
0.685872
0104de213d1f0e4798cfbec5549ec84b2179bef2
8,004
js
JavaScript
app/components/sectionGenerator.js
djh329/BudgetTools2
0fd8d9a25bce4d356acfb57e9e3a6e080e7ba2b7
[ "MIT" ]
1
2018-09-05T01:33:59.000Z
2018-09-05T01:33:59.000Z
app/components/sectionGenerator.js
djh329/BudgetTools2
0fd8d9a25bce4d356acfb57e9e3a6e080e7ba2b7
[ "MIT" ]
null
null
null
app/components/sectionGenerator.js
djh329/BudgetTools2
0fd8d9a25bce4d356acfb57e9e3a6e080e7ba2b7
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import {connect} from 'react-redux'; import { Field, FieldArray, reduxForm, formValueSelector, change, initialize} from 'redux-form'; import { Link } from 'react-router-dom' import Collapsible from 'react-collapsible'; import {snakeToTitle} from '../utils' import { DURABLE, TRAVEL, ADMIN, LOCAL, PUBLICATION, GENERAL, LOCAL_CALC_NAME, SECTIONS } from '../constants' import { addDurable, addTravel, addAdmin, addLocal, addPublication, addGeneral } from '../actions' import {durable as durableConfig} from '../budgetSections/durableConfig' import {travel as travelConfig} from '../budgetSections/travelConfig' import {admin as adminConfig} from '../budgetSections/adminConfig' import {local as localConfig} from '../budgetSections/localConfig' import {publication as publicationConfig} from '../budgetSections/publicationConfig' import {general as generalConfig} from '../budgetInfo/generalInfo' import {speaker_calc as speakerCalc} from '../budgetInfo/speakerFunding' var configs = {} configs[DURABLE]=durableConfig configs[TRAVEL]=travelConfig configs[LOCAL]=localConfig configs[ADMIN]=adminConfig configs[PUBLICATION]=publicationConfig import FormGenerator from './formGenerator' import {validationCreator} from './validate' function classMaker(name, config, onSubmit_) { return ( class Section extends Component { constructor(props) { super(props) this.onSubmit_ = onSubmit_ this.config = config } onSubmit(values) { this.props.adderFunction(values) window.alert(snakeToTitle(name) + ' Saved To Budget') // writeBudget() if(this.onSubmit_) { this.onSubmit_(values) } } render() { var {handleSubmit, calculated, configs} = this.props; return( <div> <form onSubmit={handleSubmit(this.onSubmit.bind(this))}> <FormGenerator calculated={calculated} configs={configs} json={this.config} /> </form> </div> ); } } ) } /* ------------------------- SECTION/CALCULATOR STP ------------------------- */ function getTotalSpent(state, selector, config, section) { var temp = {} var values = {} var total = 0 if (config.repeat) { for (var key in config.repeat) { var repeatable = config.repeat[key] temp[repeatable.name] = selector(state, 'form', section, 'values', repeatable.name)[repeatable.name] repeatable.values.forEach((question, index) => { if (question.type == 'calculated') { var calculate = question.function if (temp[repeatable.name]) { temp[repeatable.name].forEach((response, index2) => { var output = calculate(response, temp, index2) if (!values[`${repeatable.name}`]) { values[`${repeatable.name}`] = [] } values[`${repeatable.name}`][`${parseInt(index2)}`] = {} var name = question.name values[`${repeatable.name}`][`${parseInt(index2)}`][name] = output if (question.monetary) { total+=output } }) } } else { if (question.monetary && temp[repeatable.name]) { if (temp[repeatable.name]) { temp[repeatable.name].forEach((response) => { if (response[question.name]) { var price = parseFloat(response[question.name]) total += price } }) } } } }) } } if (config.single) { for (var key in config.single) { var single = config.single[key] temp[single.name] = selector(state, 'form', section, 'values', single.name)[single.name] if (single.type == 'calculated') { var calculate = single.function var output = calculate(temp) values[single.name] = output if (single.monetary) { total+=output } } else { if (single.monetary) { total += parseFloat(temp[single.name]) } } } } values.total = total values.max_funding = config.max ? Math.min(total, config.max) : total // console.log(total) return values // console.log(state.form[section].values) // console.log(temp) } function generateSTP(section, config) { const selector = formValueSelector(section); return ( function mapStateToProps(state) { var calculated = getTotalSpent(state, selector, config, section) return ({ initialValues: state.budget[section], calculated: calculated, whole: state.budget }) } ) } function generateSection(name, adderFunction, config, onSubmit) { return ( connect( generateSTP(name, config), {adderFunction} )(reduxForm({ validate: validationCreator(config), form: name, // enableReinitialize: true, destroyOnUnmount: false })( classMaker(name, config, onSubmit) )) ) } /* ------------------------- GENERAL STP ----------------------------- */ function getTotals(state, selectors, config, section) { var totals = {} console.log(state) SECTIONS.forEach(section => { var calced = getTotalSpent(state, selectors[section], configs[section], section) totals[section] = calced.total }) var calculated = getTotalSpent(state, selectors[GENERAL], generalConfig, GENERAL) // totals[ADMIN] = getTotalSpent(state, selectors, adminConfig, ADMIN) // totals[DURABLE] = getTotalSpent(state, selector, durableConfig, DURABLE) // totals[LOCAL] = getTotalSpent(state, selector, localConfig, LOCAL) // totals[TRAVEL] = getTotalSpent(state, selector, travelConfig, TRAVEL) // totals[PUBLICATION] = getTotalSpent(state, selector, publicationConfig, PUBLICATION) // console.log(totals[ADMIN]) // totals[GENERAL]= totals[ADMIN] + totals[DURABLE] + totals[LOCAL] + totals[TRAVEL] + totals[PUBLICATION] return {...calculated, totals: totals} } function generateGeneralSTP(section, config) { var selectors = {} SECTIONS.forEach(section => { selectors[section] = formValueSelector(section) }) selectors[GENERAL] = formValueSelector(GENERAL) return ( function mapStateToProps(state) { var calculated = getTotals(state, selectors, config, section) return ({ initialValues: state.budget[section], calculated: calculated, whole: state.budget, configs: configs }) } ) } function generateGeneral(name, adderFunction, config, onSubmit) { return ( connect( generateGeneralSTP(name, config), {adderFunction} )(reduxForm({ validate: validationCreator(config), form: name, // enableReinitialize: true, destroyOnUnmount: false })( classMaker(name, config, onSubmit) )) ) } function onSubmitDurable(values) { // console.log('DURABBLE', values) } function onSubmitTravel(values) { // console.log('TRAVEL', values) } function onSubmitAdmin(values) { // console.log('TRAVEL', values) } function onSubmitLocal(values) { } function onSubmitPublication(values) { } function onSubmitGeneral(values) { } export const durable = generateSection(DURABLE, addDurable, durableConfig, onSubmitDurable) export const travel = generateSection(TRAVEL, addTravel, travelConfig, onSubmitTravel) export const admin = generateSection(ADMIN, addAdmin, adminConfig, onSubmitAdmin) export const local = generateSection(LOCAL, addLocal, localConfig, onSubmitLocal) export const publication = generateSection(PUBLICATION, addPublication, publicationConfig, onSubmitPublication) export const general = generateGeneral(GENERAL, addGeneral, generalConfig, onSubmitGeneral) export const speaker_calc = generateSection(LOCAL_CALC_NAME, undefined, speakerCalc, ()=>{})
28.183099
111
0.636432
bbfac763e31e679e8300f2b16093d8167b675ad8
10,044
js
JavaScript
src/extensions/renderer/canvas/drawing-nodes.js
johntango/cytoscape.js
385e2b403bb9106994f1fb7bf2fe4f9b8b524449
[ "MIT" ]
1
2018-12-30T06:06:00.000Z
2018-12-30T06:06:00.000Z
src/extensions/renderer/canvas/drawing-nodes.js
JaylinLee/cytoscape.js
5645eb5bd49aaa9ced4e9b5a864d54051002e435
[ "MIT" ]
null
null
null
src/extensions/renderer/canvas/drawing-nodes.js
JaylinLee/cytoscape.js
5645eb5bd49aaa9ced4e9b5a864d54051002e435
[ "MIT" ]
null
null
null
/* global Path2D */ import * as is from '../../../is'; import * as util from '../../../util'; let CRp = {}; CRp.drawNode = function( context, node, shiftToOriginWithBb, drawLabel = true, shouldDrawOverlay = true ){ let r = this; let nodeWidth, nodeHeight; let _p = node._private; let rs = _p.rscratch; let pos = node.position(); if( !is.number( pos.x ) || !is.number( pos.y ) ){ return; // can't draw node with undefined position } if( !node.visible() ){ return; } let parentOpacity = node.effectiveOpacity(); let usePaths = r.usePaths(); let path; let pathCacheHit = false; let padding = node.padding(); nodeWidth = node.width() + 2 * padding; nodeHeight = node.height() + 2 * padding; // // setup shift let bb; if( shiftToOriginWithBb ){ bb = shiftToOriginWithBb; context.translate( -bb.x1, -bb.y1 ); } // // load bg image let bgImgProp = node.pstyle( 'background-image' ); let urls = bgImgProp.value; let urlDefined = new Array( urls.length ); let image = new Array( urls.length ); let numImages = 0; for( let i = 0; i < urls.length; i++ ){ let url = urls[i]; let defd = urlDefined[i] = url != null && url !== 'none'; if( defd ){ let bgImgCrossOrigin = node.cy().style().getIndexedStyle(node, 'background-image-crossorigin', 'value', i); numImages++; // get image, and if not loaded then ask to redraw when later loaded image[i] = r.getCachedImage( url, bgImgCrossOrigin, function(){ _p.backgroundTimestamp = Date.now(); node.emitAndNotify('background'); } ); } } // // setup styles let darkness = node.pstyle('background-blacken').value; let borderWidth = node.pstyle('border-width').pfValue; let bgOpacity = node.pstyle('background-opacity').value * parentOpacity; let borderColor = node.pstyle('border-color').value; let borderStyle = node.pstyle('border-style').value; let borderOpacity = node.pstyle('border-opacity').value * parentOpacity; context.lineJoin = 'miter'; // so borders are square with the node shape let setupShapeColor = ( bgOpy = bgOpacity ) => { r.eleFillStyle( context, node, bgOpy ); }; let setupBorderColor = ( bdrOpy = borderOpacity ) => { r.colorStrokeStyle( context, borderColor[0], borderColor[1], borderColor[2], bdrOpy ); }; // // setup shape let styleShape = node.pstyle('shape').strValue; let shapePts = node.pstyle('shape-polygon-points').pfValue; if( usePaths ){ context.translate( pos.x, pos.y ); let pathCache = r.nodePathCache = r.nodePathCache || []; let key = util.hashStrings( styleShape === 'polygon' ? styleShape + ',' + shapePts.join(',') : styleShape, '' + nodeHeight, '' + nodeWidth ); let cachedPath = pathCache[ key ]; if( cachedPath != null ){ path = cachedPath; pathCacheHit = true; rs.pathCache = path; } else { path = new Path2D(); pathCache[ key ] = rs.pathCache = path; } } let drawShape = () => { if( !pathCacheHit ){ let npos = pos; if( usePaths ){ npos = { x: 0, y: 0 }; } r.nodeShapes[ r.getNodeShape( node ) ].draw( ( path || context ), npos.x, npos.y, nodeWidth, nodeHeight ); } if( usePaths ){ context.fill( path ); } else { context.fill(); } }; let drawImages = ( nodeOpacity = parentOpacity ) => { let prevBging = _p.backgrounding; let totalCompleted = 0; for( let i = 0; i < image.length; i++ ){ if( urlDefined[i] && image[i].complete && !image[i].error ){ totalCompleted++; r.drawInscribedImage( context, image[i], node, i, nodeOpacity ); } } _p.backgrounding = !(totalCompleted === numImages); if( prevBging !== _p.backgrounding ){ // update style b/c :backgrounding state changed node.updateStyle( false ); } }; let drawPie = ( redrawShape = false, pieOpacity = parentOpacity ) => { if( r.hasPie( node ) ){ r.drawPie( context, node, pieOpacity ); // redraw/restore path if steps after pie need it if( redrawShape ){ if( !usePaths ){ r.nodeShapes[ r.getNodeShape( node ) ].draw( context, pos.x, pos.y, nodeWidth, nodeHeight ); } } } }; let darken = ( darkenOpacity = parentOpacity ) => { let opacity = ( darkness > 0 ? darkness : -darkness ) * darkenOpacity; let c = darkness > 0 ? 0 : 255; if( darkness !== 0 ){ r.colorFillStyle( context, c, c, c, opacity ); if( usePaths ){ context.fill( path ); } else { context.fill(); } } }; let drawBorder = () => { if( borderWidth > 0 ){ context.lineWidth = borderWidth; context.lineCap = 'butt'; if( context.setLineDash ){ // for very outofdate browsers switch( borderStyle ){ case 'dotted': context.setLineDash( [ 1, 1 ] ); break; case 'dashed': context.setLineDash( [ 4, 2 ] ); break; case 'solid': case 'double': context.setLineDash( [ ] ); break; } } if( usePaths ){ context.stroke( path ); } else { context.stroke(); } if( borderStyle === 'double' ){ context.lineWidth = borderWidth / 3; let gco = context.globalCompositeOperation; context.globalCompositeOperation = 'destination-out'; if( usePaths ){ context.stroke( path ); } else { context.stroke(); } context.globalCompositeOperation = gco; } // reset in case we changed the border style if( context.setLineDash ){ // for very outofdate browsers context.setLineDash( [ ] ); } } }; let drawOverlay = () => { if( shouldDrawOverlay ){ r.drawNodeOverlay( context, node, pos, nodeWidth, nodeHeight ); } }; let drawText = () => { r.drawElementText( context, node, null, drawLabel ); }; let ghost = node.pstyle('ghost').value === 'yes'; if( ghost ){ let gx = node.pstyle('ghost-offset-x').pfValue; let gy = node.pstyle('ghost-offset-y').pfValue; let ghostOpacity = node.pstyle('ghost-opacity').value; let effGhostOpacity = ghostOpacity * parentOpacity; context.translate( gx, gy ); setupShapeColor( ghostOpacity * bgOpacity ); drawShape(); drawImages( effGhostOpacity ); drawPie( darkness !== 0 || borderWidth !== 0 ); darken( effGhostOpacity ); setupBorderColor( ghostOpacity * borderOpacity ); drawBorder(); context.translate( -gx, -gy ); } setupShapeColor(); drawShape(); drawImages(); drawPie( darkness !== 0 || borderWidth !== 0 ); darken(); setupBorderColor(); drawBorder(); if( usePaths ){ context.translate( -pos.x, -pos.y ); } drawText(); drawOverlay(); // // clean up shift if( shiftToOriginWithBb ){ context.translate( bb.x1, bb.y1 ); } }; CRp.drawNodeOverlay = function( context, node, pos, nodeWidth, nodeHeight ){ let r = this; let overlayPadding = node.pstyle( 'overlay-padding' ).pfValue; let overlayOpacity = node.pstyle( 'overlay-opacity' ).value; let overlayColor = node.pstyle( 'overlay-color' ).value; if( overlayOpacity > 0 ){ pos = pos || node.position(); if( nodeWidth == null || nodeHeight == null ){ let padding = node.padding(); nodeWidth = node.width() + 2 * padding; nodeHeight = node.height() + 2 * padding; } r.colorFillStyle( context, overlayColor[0], overlayColor[1], overlayColor[2], overlayOpacity ); r.nodeShapes[ 'roundrectangle' ].draw( context, pos.x, pos.y, nodeWidth + overlayPadding * 2, nodeHeight + overlayPadding * 2 ); context.fill(); } }; // does the node have at least one pie piece? CRp.hasPie = function( node ){ node = node[0]; // ensure ele ref return node._private.hasPie; }; CRp.drawPie = function( context, node, nodeOpacity, pos ){ node = node[0]; // ensure ele ref pos = pos || node.position(); let cyStyle = node.cy().style(); let pieSize = node.pstyle( 'pie-size' ); let x = pos.x; let y = pos.y; let nodeW = node.width(); let nodeH = node.height(); let radius = Math.min( nodeW, nodeH ) / 2; // must fit in node let lastPercent = 0; // what % to continue drawing pie slices from on [0, 1] let usePaths = this.usePaths(); if( usePaths ){ x = 0; y = 0; } if( pieSize.units === '%' ){ radius = radius * pieSize.pfValue; } else if( pieSize.pfValue !== undefined ){ radius = pieSize.pfValue / 2; } for( let i = 1; i <= cyStyle.pieBackgroundN; i++ ){ // 1..N let size = node.pstyle( 'pie-' + i + '-background-size' ).value; let color = node.pstyle( 'pie-' + i + '-background-color' ).value; let opacity = node.pstyle( 'pie-' + i + '-background-opacity' ).value * nodeOpacity; let percent = size / 100; // map integer range [0, 100] to [0, 1] // percent can't push beyond 1 if( percent + lastPercent > 1 ){ percent = 1 - lastPercent; } let angleStart = 1.5 * Math.PI + 2 * Math.PI * lastPercent; // start at 12 o'clock and go clockwise let angleDelta = 2 * Math.PI * percent; let angleEnd = angleStart + angleDelta; // ignore if // - zero size // - we're already beyond the full circle // - adding the current slice would go beyond the full circle if( size === 0 || lastPercent >= 1 || lastPercent + percent > 1 ){ continue; } context.beginPath(); context.moveTo( x, y ); context.arc( x, y, radius, angleStart, angleEnd ); context.closePath(); this.colorFillStyle( context, color[0], color[1], color[2], opacity ); context.fill(); lastPercent += percent; } }; export default CRp;
24.8
113
0.582139
bbef36e9bef3b861328717b5d19c4d2c0fc3505c
7,285
js
JavaScript
src/services/validator/index.js
lennokiki/hc-materials
69367bb819ed04c679d08e8ccb9cad121732fd1e
[ "MIT" ]
1
2019-04-15T15:20:20.000Z
2019-04-15T15:20:20.000Z
src/services/validator/index.js
lennokiki/hc-materials
69367bb819ed04c679d08e8ccb9cad121732fd1e
[ "MIT" ]
null
null
null
src/services/validator/index.js
lennokiki/hc-materials
69367bb819ed04c679d08e8ccb9cad121732fd1e
[ "MIT" ]
null
null
null
/** * # 通用校验模块 * 1. 通过定义校验规则用于校验数据合法 * 2. 集成antd-form,校验表单合法 */ import AsyncValidator from 'async-validator'; import hoistNonReactStatics from 'hoist-non-react-statics'; import Form from 'antd/lib/form'; import message from 'antd/lib/message'; import {Deferred} from '../../core/defer'; /** * + async-validator@1.6.6 * > see: https://github.com/yiminghe/async-validator */ export class Validator { static enhanceForm = (option) => BaseComponent => { const Component = Form.create(Object.assign(option || {}, {withRef: true}))(BaseComponent); Component.prototype.getRealInstance = function () { return this.refs.wrappedComponent.refs.formWrappedComponent; }; return hoistNonReactStatics(Component, BaseComponent); } static validate = (rules, source, callback) => { const descriptor = {}; for (let key in rules) { if (typeof rules[key] === 'boolean') { descriptor[key] = { type: 'string', required: rules[key] }; } else { descriptor[key] = rules[key]; } } const validator = new AsyncValidator(descriptor); validator.validate(source, callback); } /* eslint-disable camelcase */ static templates = { pattern: { // #! 中英字母数字下划线 legal: /^[A-Za-z0-9_\u4e00-\u9fa5]*$/, // #! 必须是字母数字、下划线、中划线以及 light_legal: /^[A-Za-z0-9._-]*$/, // #! 以字母开头,不能包含中文或特殊字符 light_light_legal: /^[a-zA-Z]\w*$/, // #! 中英字母数字下划线 dark_legal: /^[A-Za-z0-9_\u4e00-\u9fa5]*$/, // #! 必须是中英字母数字下划线以及. dark_dark_legal: /^[A-Za-z0-9._\u4e00-\u9fa5]*$/ } } /** * + 校验规则 * ``` * fieldRules = [{ * [fieldName]: { * type: ['string', 'number', 'boolean', 'method', 'regexp', 'integer', 'float', 'array', 'object', 'enum', 'date', 'url', 'hex', 'email'], * required, * pattern, * whitespace, * transform, * message, * validator, * [range(min, max): 'string' | 'array' | 'integer'], * [length: 'string' | 'array'] * [enum: 'enum'], * [fields: 'deep rules'], * [defaultField: 'array' | 'object'] * } * },...] * ``` */ static $inject = ['props', 'validateRules']; constructor(props, validateRules) { for (let key in validateRules) { validateRules[key] = this.pack(validateRules[key]); } this._validateRules = validateRules || {}; this._handleSubmit = (errors, values) => { if (errors) { return false; } else { return values; } }; this._submitting = false; this._validating = false; } isSubmitting() { return this._submitting; } isValidating() { return this._validating; } pack(rule) { if (Array.isArray(rule)) { rule = rule.map(item => { if (typeof item.pattern === 'string') { item.pattern = Validator.templates.pattern[item.pattern]; } return item; }); } else { if (typeof rule.pattern === 'string') { rule.pattern = Validator.templates.pattern[rule.pattern]; } } return rule; } setForm(form, validateRules, submitCallback) { this._form = form; if (submitCallback) { this._handleSubmit = submitCallback; if (validateRules) { for (let key in validateRules) { validateRules[key] = this.pack(validateRules[key]); } this._validateRules = validateRules; } } else if (validateRules) { this._handleSubmit = validateRules; } } reset() { this ._form .resetFields(); } getProps(fieldName, rule) { if (this._validateRules[fieldName]) { return assignDeep(this._validateRules[fieldName], rule && this.pack(rule)); } else { return rule && this.pack(rule); } } // #! for antd-form getFieldProps(fieldName, option) { if (!option.rules && option.rule) { option.rules = [option.rule]; } if (this._validateRules[fieldName]) { // option.rules = assignDeep([].concat(this._validateRules[fieldName]), // option.rules && this.pack(option.rules) || []); option.rules = [].concat(this._validateRules[fieldName], option.rules && this.pack(option.rules) || []); } else if (option.rules) { option.rules = this.pack(option.rules); } return this ._form .getFieldProps(fieldName, option); } getFieldDecorator(fieldName, option) { if (!option.rules && option.rule) { option.rules = [option.rule]; } if (this._validateRules[fieldName]) { // option.rules = assignDeep([].concat(this._validateRules[fieldName]), // option.rules && this.pack(option.rules) || []); option.rules = [].concat(this._validateRules[fieldName], option.rules && this.pack(option.rules) || []); } else if (option.rules) { option.rules = this.pack(option.rules); } return this ._form .getFieldDecorator(fieldName, option); } _validate(opt) { const defer = new Deferred(); this._validating = true; this._form.setFields(); opt.preCallback && opt.preCallback(); const callback = (errors, values) => { this._validating = false; const postCallback = () => { opt.postCallback && opt.postCallback(); this._form.setFields(); }; if (errors) { if (opt.catchError) { opt.catchError(errors); } else { message.error('表单校验失败'); } postCallback(); return defer.reject(false); } const result = opt.callback && opt.callback(errors, values); if (result && result.then) { result.then(defer.resolve, defer.reject); } else if (result === false) { defer.reject(false); } else { defer.resolve(result); } defer.promise.then(postCallback, postCallback); }; if (opt.source) { new AsyncValidator(this._validateRules).validate(opt.source, callback); } else { this._form[opt.method](callback); } return defer.promise; } validateFields(callback, catchError) { return this._validate({ method: 'validateFields', callback: callback, catchError: catchError }); } validateFieldsAndScroll(callback, catchError) { return this._validate({ method: 'validateFieldsAndScroll', callback: callback, catchError: catchError }); } validate(source, callback, catchError) { return this._validate({ source: source, callback: callback, catchError: catchError }); } submit(callback, catchError) { return this._validate({ method: 'validateFieldsAndScroll', preCallback: () => { this._submitting = true; }, postCallback: () => { this._submitting = false; }, callback: (errors, values) => { values = this._handleSubmit(errors, values); if (values === false) { return false; } else { return callback(values); } }, catchError: catchError }); } } function assignDeep(obj, newObj) { if (Array.isArray(obj)) { return obj.map((item, index) => { return assignDeep(item, newObj[index]); }); } else { return Object.assign(obj, newObj); } }
26.490909
144
0.579684
bbf87747d8b9db63b430d5addbb8c2acc143e4d5
2,556
js
JavaScript
src/components/index/ytplayer.js
audioCaps/audioCaps
37ed6a278af584472c483036f23650619cb9f080
[ "MIT" ]
1
2019-04-26T18:51:06.000Z
2019-04-26T18:51:06.000Z
src/components/index/ytplayer.js
audioCaps/audioCaps
37ed6a278af584472c483036f23650619cb9f080
[ "MIT" ]
9
2021-03-09T03:04:33.000Z
2022-02-26T10:32:42.000Z
src/components/index/ytplayer.js
audioCaps/audioCaps.github.io
37ed6a278af584472c483036f23650619cb9f080
[ "MIT" ]
null
null
null
import React from "react" import ReactPlayer from "react-player" import Caption from "./caption" import VideoControl from "./videoControl" import { Image } from "./image" class Ytplayer extends React.Component { state = { playing: false, playedSeconds: 0, } ref = player => { this.player = player } play = () => { this.setState({ playing: true }) } pause = () => { this.setState({ playing: false }) } replay = () => { this.player.seekTo(0) this.play() } onProgress = state => { const { video } = this.props const { playedSeconds } = this.state this.setState(state) if (playedSeconds > video.duration) { this.player.seekTo(0) } } onPlay = () => { this.setState({ playing: true }) } onPause = () => { this.setState({ playing: false }) } onStart = () => { this.setState({ playing: true }) } onEnded = () => { this.player.seekTo(0) } openNewTabSecurely = () => { const { video } = this.props const ytUrl = `https://www.youtube.com/watch?v=${video.id}` window.open(ytUrl, '_blank').opener = null } render() { const { video, visible } = this.props const { playing, playedSeconds } = this.state return ( <div className="video"> <Caption visible={visible} video={video} /> <VideoControl playing={playing} pauseFunc={this.pause} playFunc={this.play} // To show full progress bar despite update delays progressInPercent={(playedSeconds / (video.duration - 1)) * 100} /> <div style={{position: "relative"}}> <ReactPlayer ref={this.ref} className={!visible ? 'invisible' : ''} style={{ marginBottom: "1rem", }} config={{ youtube: { playerVars: { showinfo: 1, fs: 1 }, }, }} width="100%" height="" progressInterval={100} playing={playing} url={require(`../../videos/${video.id}_${video.startSeconds}.mp4`)} onEnded={this.onEnded} onProgress={this.onProgress} onPlay={this.onPlay} onPause={this.onPause} /> <div className={`yt-link ${!visible && 'invisible'}`} onClick={this.openNewTabSecurely} > <Image fileName='yt_icon_rgb.png' /> </div> </div> </div> ) } } export default Ytplayer
23.449541
79
0.521518
bbfbb4f1ed7690e2e8f8df55a846160aa1af342f
836
js
JavaScript
src/router/modules/BusinessManage.js
1823616178/vue-Crm
b14903d72c98fd5cc9973643519b38e8d68a12f8
[ "MIT" ]
1
2020-02-20T06:06:09.000Z
2020-02-20T06:06:09.000Z
src/router/modules/BusinessManage.js
1823616178/vue-Crm
b14903d72c98fd5cc9973643519b38e8d68a12f8
[ "MIT" ]
null
null
null
src/router/modules/BusinessManage.js
1823616178/vue-Crm
b14903d72c98fd5cc9973643519b38e8d68a12f8
[ "MIT" ]
null
null
null
/** When your routing table is too long, you can split it into small modules**/ import Layout from '@/views/layout/Layout' const BusinessManage = { path: '/Busin-Manage', component: Layout, redirect: '/table/Busin-Manage', name: 'BusinManage', alwaysShow: true, meta: { title: 'BusinManage', icon: 'peoples' }, children: [ { path: '/Busin-New', component: () => import('@/views/BusinessManage/EnterpriseNew'), name: 'EnterpriseNew', meta: {title: 'EnterpriseNew'} }, { path: '/Special-Buiness', component: () => import('@/views/BusinessManage/SpecialBuiness'), name: 'SpecialBuiness', meta: {title: 'SpecialBuiness'} }, ] } export default BusinessManage
26.967742
79
0.555024
0103e21840faac1ffb6014488a5d9caa7922169d
1,653
js
JavaScript
tf/ts/static/js/images.js
nanda-03/africantranslator.com
fdc06a821a61f36458029b1a3761a90ad8adb2ab
[ "MIT" ]
1
2020-03-05T20:01:39.000Z
2020-03-05T20:01:39.000Z
tf/ts/static/js/images.js
nanda-03/africantranslator.com
fdc06a821a61f36458029b1a3761a90ad8adb2ab
[ "MIT" ]
null
null
null
tf/ts/static/js/images.js
nanda-03/africantranslator.com
fdc06a821a61f36458029b1a3761a90ad8adb2ab
[ "MIT" ]
null
null
null
var selectedImages = []; var button = document.getElementById("button-submission"); button.innerText = 'Mettre les elements dans le pannier'; button.disabled = true; for(checkbox of document.getElementsByTagName('checkbox')){ if(checkbox.checked){ button.innerText = 'Sauvegarder'; button.disabled = false; break; } } function images_select(checkbox){ a = checkbox.id.split('-')[1] if(checkbox.checked){ selectedImages.push(a); } else{ selectedImages.splice(selectedImages.indexOf(a)); } console.log(selectedImages); if(selectedImages.length!=0){ button.disabled = false; button.innerText = 'Sauvegarder'; }else{ button.disabled = true; button.innerText = 'Mettre les elements dans le pannier'; } } function submission(){ console.log(selectedImages); //window.location.reload(true); //window.location.replace('http://127.0.0.1:8000/log') //window.location.assign('http://127.0.0.1:8000/log'); $.ajax({ type: "GET", url: "validation", dataType: "json", traditional: true, //headers: { 'api-key':'myKey' }, data: {'list_article': JSON.stringify(selectedImages)}, success: function(data) { console.log(data); }, error:function(data) { console.log('error', data); } }); } function modifier(){ console.log('modifier'); document.getElementById('username').disabled = false; document.getElementById('password').disabled = false; document.getElementById('modal-link').disabled = true; }
27.098361
65
0.614035
bbe9e09b2d2e9a65da73f41cc949fe76827de3ec
777
js
JavaScript
src/views/Dashboard/components/LatestProducts/data.js
sroy05/HISPEDIA
3a15a776bc38628ffe15f28ab9aa883207bddd5f
[ "MIT" ]
9
2020-04-24T17:40:44.000Z
2020-04-29T04:24:22.000Z
src/views/Dashboard/components/LatestProducts/data.js
sroy05/HISPEDIA
3a15a776bc38628ffe15f28ab9aa883207bddd5f
[ "MIT" ]
144
2020-04-24T16:07:58.000Z
2021-07-28T13:35:14.000Z
src/views/Dashboard/components/LatestProducts/data.js
sroy05/HISPEDIA
3a15a776bc38628ffe15f28ab9aa883207bddd5f
[ "MIT" ]
20
2020-03-17T20:59:36.000Z
2022-03-16T12:19:09.000Z
import uuid from 'uuid/v1'; import moment from 'moment'; export default [ { id: uuid(), name: 'Dropbox', imageUrl: '/images/products/product_1.png', updatedAt: moment().subtract(2, 'hours') }, { id: uuid(), name: 'Medium Corporation', imageUrl: '/images/products/product_2.png', updatedAt: moment().subtract(2, 'hours') }, { id: uuid(), name: 'Slack', imageUrl: '/images/products/product_3.png', updatedAt: moment().subtract(3, 'hours') }, { id: uuid(), name: 'Lyft', imageUrl: '/images/products/product_4.png', updatedAt: moment().subtract(5, 'hours') }, { id: uuid(), name: 'GitHub', imageUrl: '/images/products/product_5.png', updatedAt: moment().subtract(9, 'hours') } ];
21.583333
47
0.590734
010de563fb30497df21921e633d5110e320ba1eb
74
js
JavaScript
client/src/constants/index.js
ethonline-2020/boundless
c832024ce959a7dece9cf7bb0d9ef95e7e208352
[ "MIT" ]
6
2020-03-02T16:34:21.000Z
2020-05-02T20:14:28.000Z
client/src/constants/index.js
ethonline-2020/boundless
c832024ce959a7dece9cf7bb0d9ef95e7e208352
[ "MIT" ]
null
null
null
client/src/constants/index.js
ethonline-2020/boundless
c832024ce959a7dece9cf7bb0d9ef95e7e208352
[ "MIT" ]
4
2020-03-13T06:32:28.000Z
2021-02-06T11:39:55.000Z
export const PDAI_ADDRESS = "0x5dbA0a59BEd7e1AEdd700021b396b118eF1224B4";
37
73
0.878378
bbe791b7d79b91d6955c1fef6448d0185d76c351
1,532
js
JavaScript
test/unit/layout/circular-spec.js
mage3k/g6
5a39181edb5e07120c217eafd2e37bb78e9dc390
[ "MIT" ]
2
2020-05-20T09:21:54.000Z
2020-06-09T07:22:02.000Z
test/unit/layout/circular-spec.js
mage3k/g6
5a39181edb5e07120c217eafd2e37bb78e9dc390
[ "MIT" ]
null
null
null
test/unit/layout/circular-spec.js
mage3k/g6
5a39181edb5e07120c217eafd2e37bb78e9dc390
[ "MIT" ]
1
2020-08-27T04:57:28.000Z
2020-08-27T04:57:28.000Z
const expect = require('chai').expect; const G6 = require('../../../src'); const data = require('./data.json'); const div = document.createElement('div'); div.id = 'force-layout'; document.body.appendChild(div); function mathEqual(a, b) { return Math.abs(a - b) < 1; } describe.only('circular layout', () => { it('circular layout with default configs', () => { const graph = new G6.Graph({ container: div, layout: { type: 'circular' }, width: 500, height: 500, defaultNode: { size: 10 } }); graph.data(data); graph.render(); const width = graph.get('width'); const height = graph.get('height'); const radius = height > width ? width / 2 : height / 2; expect(mathEqual(data.nodes[0].x, 250 + radius)).to.equal(true); expect(mathEqual(data.nodes[0].y, 250)).to.equal(true); expect(data.nodes[0].y === 250); graph.destroy(); }); it('circular counterclockwise, and fixed radius, start angle, end angle', () => { const graph = new G6.Graph({ container: div, layout: { type: 'circular', center: [ 250, 250 ], radius: 200, startAngle: Math.PI / 4, endAngle: Math.PI }, width: 500, height: 500, defaultNode: { size: 10 } }); graph.data(data); graph.render(); const pos = 200 * Math.sqrt(2) / 2; expect(mathEqual(data.nodes[0].x, 250 + pos)).to.equal(true); expect(mathEqual(data.nodes[0].y, 250 + pos)).to.equal(true); graph.destroy(); }); });
27.854545
83
0.577023
010c52afe98140029cfe18b855c9e4b9d7dfd70d
23,794
js
JavaScript
public/js/script.js
aspargas2/seedcloud
9b451b426b02bdd53da08510e6be1e9a962332f5
[ "MIT" ]
4
2020-06-21T18:58:50.000Z
2020-06-27T06:33:34.000Z
public/js/script.js
aspargas2/seedcloud
9b451b426b02bdd53da08510e6be1e9a962332f5
[ "MIT" ]
null
null
null
public/js/script.js
aspargas2/seedcloud
9b451b426b02bdd53da08510e6be1e9a962332f5
[ "MIT" ]
4
2020-07-13T21:40:19.000Z
2022-03-07T12:36:24.000Z
var REFRESH_STATE_INTERVAL = 1000; function resetfc() { var currentTask = localStorage.getItem('taskId'); jQuery.ajax({ type: 'POST', dataType: 'json', data: { action: 'reset-fc', taskId: localStorage.getItem('taskId') }, success: function (data) { if (currentTask === localStorage.getItem('taskId')) { setTimeout(checkStatusForCurrentTask, 500); } } }); } function base64ArrayBuffer(arrayBuffer) { var base64 = ''; var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var bytes = new Uint8Array(arrayBuffer); var byteLength = bytes.byteLength; var byteRemainder = byteLength % 3; var mainLength = byteLength - byteRemainder; var a, b, c, d; var chunk; // Main loop deals with bytes in chunks of 3 for (var i = 0; i < mainLength; i = i + 3) { // Combine the three bytes into a single integer chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; // Use bitmasks to extract 6-bit segments from the triplet a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18 b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12 c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6 d = chunk & 63; // 63 = 2^6 - 1 // Convert the raw binary segments to the appropriate ASCII encoding base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]; } // Deal with the remaining bytes and padding if (byteRemainder == 1) { chunk = bytes[mainLength]; a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2 // Set the 4 least significant bits to zero b = (chunk & 3) << 4; // 3 = 2^2 - 1 base64 += encodings[a] + encodings[b] + '=='; } else if (byteRemainder == 2) { chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]; a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10 b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4 // Set the 2 least significant bits to zero c = (chunk & 15) << 2; // 15 = 2^4 - 1 base64 += encodings[a] + encodings[b] + encodings[c] + '='; } return base64; } function processMovablePart1() { var fileInput = document.getElementById("p1file"); var fileList = fileInput.files; if (fileList.length === 1 && fileList[0].size === 0x1000) { var file = fileInput.files[0]; var fileReader = new FileReader(); fileReader.readAsArrayBuffer(file); fileReader.addEventListener("loadend", function (){ let arrayBuffer = fileReader.result let lfcsBuffer = arrayBuffer.slice(0, 8) let lfcsArray = new Uint8Array(lfcsBuffer) let textDecoder = new TextDecoder() let lfcsString = textDecoder.decode(lfcsArray) if (lfcsString == textDecoder.decode(new Uint8Array(8))) { alert("movable_part1.sed is invalid") return } document.getElementById("part1b64").value = base64ArrayBuffer(lfcsBuffer) let id0Buffer = arrayBuffer.slice(0x10, 0x10+32) let id0Array = new Uint8Array(id0Buffer) document.getElementById("friendCode").disabled = true document.getElementById("friendCode").value = "movable_part1 provided" let id0String = textDecoder.decode(id0Array) console.log(id0String, btoa(id0String), id0String.length) if (btoa(id0String) != "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") { // non blank, if id0 is injected with seedminer_helper let id0Input = document.getElementById("id0") id0Input.disabled = true id0Input.value = id0String } }) } } /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS PUB 180-1 * Version 2.1a Copyright Paul Johnston 2000 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for details. */ /* * Configurable variables. You may need to tweak these to be compatible with * the server-side, but the defaults work in most cases. */ var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ /* * These are the functions you'll usually want to call * They take string arguments and return either hex or base-64 encoded strings */ function sha1encoded(s){return binb2hex(core_sha1(str2binb(unescape(s)),unescape(s).length * chrsz));} /* * Calculate the SHA-1 of an array of big-endian words, and a bit length */ function core_sha1(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (24 - len % 32); x[((len + 64 >> 9) << 4) + 15] = len; var w = Array(80); var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var e = -1009589776; for(var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; var olde = e; for(var j = 0; j < 80; j++) { if(j < 16) w[j] = x[i + j]; else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))); e = d; d = c; c = rol(b, 30); b = a; a = t; } a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); e = safe_add(e, olde); } return Array(a, b, c, d, e); } /* * Perform the appropriate triplet combination function for the current * iteration */ function sha1_ft(t, b, c, d) { if(t < 20) return (b & c) | ((~b) & d); if(t < 40) return b ^ c ^ d; if(t < 60) return (b & c) | (b & d) | (c & d); return b ^ c ^ d; } /* * Determine the appropriate additive constant for the current iteration */ function sha1_kt(t) { return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514; } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * Convert an 8-bit or 16-bit string to an array of big-endian words * In 8-bit function, characters >255 have their hi-byte silently ignored. */ function str2binb(str) { var bin = Array(); var mask = (1 << chrsz) - 1; for(var i = 0; i < str.length * chrsz; i += chrsz) bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32); return bin; } /* * Convert an array of big-endian words to a hex string. */ function binb2hex(binarray) { var hex_tab = "0123456789abcdef"; var str = ""; for(var i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF); } return str; } function CheckFC(friendcode) { var fc=friendcode.replace(/[^0-9]/g,""); if (fc.length !== 12) { // FC must be 12 digits return false; } // friend code to int var str_ifc=(parseInt(fc,10)).toString(16); for (var i=str_ifc.length;i<10;i++) { str_ifc="0"+str_ifc; } var le_str="%"+str_ifc.substr(8,2)+"%"+str_ifc.substr(6,2)+"%"+str_ifc.substr(4,2)+"%"+str_ifc.substr(2,2); var fc_check=str_ifc.substr(0,2); var sha_check = (parseInt(sha1encoded(le_str).substr(0,2),16)>>>1).toString(16); if (sha_check.length === 1) { sha_check = "0"+sha_check; } return (sha_check.toLowerCase() == fc_check.toLowerCase()); } var STEP_INITIAL = 1; var STEP_WAITING_FOR_PART1_DUMPER = 2; var STEP_ADD_THE_BOT = 3; var STEP_BRUTEFORCE_CHOOSE = 4; var STEP_BRUTEFORCING = 5; var STEP_MOVABLE_DONE = 6; jQuery(function () { function showUnmineableModal() { jQuery('#unmineableModal').modal(); } window.showUnmineableModal = showUnmineableModal; function changeStep(wantedStep) { jQuery('#accordion button[data-toggle="collapse"]:not([data-target="#collapseOne"])').prop('disabled', true); jQuery('#accordion .collapse.show:not(#collapseOne)').removeClass('show'); jQuery('.request-form-main').hide(); document.getElementById("fcProgress").style.display = "none"; if (wantedStep === STEP_INITIAL) { localStorage.removeItem('taskId'); //jQuery('button[data-target="#collapseTwo"]').prop('disabled', false); document.getElementById("beginButton").disabled = false; //jQuery('#collapseTwo').addClass('show'); jQuery('.request-form-main').show(); document.getElementById("fcProgress").style.display = "none"; } else if (wantedStep === STEP_BRUTEFORCING) { jQuery('#id0Fill').html(localStorage.getItem('id0')); jQuery('button[data-target="#collapseFour"]').prop('disabled', false); jQuery('#collapseFour').addClass('show'); console.log('request status from server every 5 seconds'); var currentTask = localStorage.getItem('taskId'); function checkStatusForCurrentTask() { jQuery.ajax({ type: 'POST', dataType: 'json', data: { action: 'get-state', taskId: localStorage.getItem('taskId') }, success: function (data) { if (currentTask === localStorage.getItem('taskId')) { var currentState = data.currentState * 1; if (currentState === -1) { showUnmineableModal(); changeStep(STEP_INITIAL); } if (currentState === -2) { showUnmineableModal(); changeStep(STEP_INITIAL); } jQuery("#bfProgress").removeClass("bg-warning"); if (currentState === 4) { jQuery("#bfProgress").addClass("bg-warning"); jQuery("#bfProgress").text("Bruteforcing..."); } if (currentState === 5) { changeStep(STEP_MOVABLE_DONE); } if (currentState === 3 || currentState === 4) { setTimeout(checkStatusForCurrentTask, REFRESH_STATE_INTERVAL); } } } }); } checkStatusForCurrentTask(); } else if (wantedStep === STEP_MOVABLE_DONE) { jQuery('button[data-target="#collapseFive"]').prop('disabled', false); jQuery('#collapseFive').addClass('show'); jQuery('#downloadMovable').attr('href', '/get_movable?task=' + localStorage.getItem('taskId') ); jQuery('#downloadMovable2').attr('href', '/get_movable?task=' + localStorage.getItem('taskId') ); } else if (wantedStep === STEP_WAITING_FOR_PART1_DUMPER) { jQuery('.request-form-main').slideUp(); document.getElementById("fcProgress").style.display = "block"; console.log('request status from server every 5 seconds'); var currentTask = localStorage.getItem('taskId'); function checkStatusForCurrentTask() { jQuery.ajax({ type: 'POST', dataType: 'json', data: { action: 'get-state', taskId: localStorage.getItem('taskId') }, success: function (data) { if (currentTask === localStorage.getItem('taskId')) { var currentState = data.currentState * 1; if (currentState === -1) { showUnmineableModal(); changeStep(STEP_INITIAL); } if (currentState === -2) { showUnmineableModal(); changeStep(STEP_INITIAL); } if (currentState === 0) { setTimeout(checkStatusForCurrentTask, REFRESH_STATE_INTERVAL); } if (currentState === 1 ) { //= Part1 Dumper Claimed localStorage.setItem('claimedBy', data.claimedBy) changeStep(STEP_ADD_THE_BOT); } if (currentState === 2 ) { //= Part1 Dumper Done changeStep(STEP_BRUTEFORCE_CHOOSE) } if (currentState === 4 || currentState === 3) { //= Bruteforcing or Wait for Bruteforce changeStep(STEP_BRUTEFORCING); } if (currentState === 5 ) { //= Movable.sed ready changeStep(STEP_MOVABLE_DONE); } } } }); } checkStatusForCurrentTask(); } else if (wantedStep === STEP_ADD_THE_BOT) { jQuery('button[data-target="#collapseTwo"]').prop('disabled', false); document.getElementById("collapseTwo").classList.add("show"); var s = localStorage.getItem('claimedBy'); var claimedBy = (s.substring(0,4) + "-" + s.substring(4,8) + "-" + s.substring(8,12)); jQuery('.js-friendcode').html(claimedBy); console.log('request status from server every 5 seconds'); var currentTask = localStorage.getItem('taskId'); function checkStatusForCurrentTask() { jQuery.ajax({ type: 'POST', dataType: 'json', data: { action: 'get-state', taskId: localStorage.getItem('taskId') }, success: function (data) { if (currentTask === localStorage.getItem('taskId')) { var currentState = data.currentState * 1; if (currentState === -1) { showUnmineableModal(); changeStep(STEP_INITIAL); } if (currentState === -2) { showUnmineableModal(); changeStep(STEP_INITIAL); } if (currentState === 0) { setTimeout(checkStatusForCurrentTask, REFRESH_STATE_INTERVAL); } if (currentState === 1 ) { //= Part1 Dumper Claimed localStorage.setItem('claimedBy', data.claimedBy) changeStep(STEP_ADD_THE_BOT); } if (currentState === 2 ) { //= Part1 Dumper Done changeStep(STEP_BRUTEFORCE_CHOOSE) } if (currentState === 4 || currentState === 3) { //= Bruteforcing or Wait for Bruteforce changeStep(STEP_BRUTEFORCING); } if (currentState === 5 ) { //= Movable.sed ready changeStep(STEP_MOVABLE_DONE); } if (data.timeout === "true" || data.timeout === true) { jQuery('#collapseTwo .card-body').css('display', 'none'); jQuery('#collapseTwo .card-body.js-timeout').css('display', 'block'); jQuery('#collapseTwo .card-body.js-lockout').css('display', 'none'); } else if (data.lockout === "true" || data.lockout === true) { jQuery('#collapseTwo .card-body').css('display', 'none'); jQuery('#collapseTwo .card-body.js-timeout').css('display', 'none'); jQuery('#collapseTwo .card-body.js-lockout').css('display', 'block'); } else { jQuery('#collapseTwo .card-body').css('display', 'block'); jQuery('#collapseTwo .card-body.js-timeout').css('display', 'none'); jQuery('#collapseTwo .card-body.js-lockout').css('display', 'none'); } } } }); } checkStatusForCurrentTask(); } else if (wantedStep === STEP_BRUTEFORCE_CHOOSE){ jQuery('button[data-target="#collapseThree"]').prop('disabled', false); document.getElementById("collapseThree").classList.add("show"); document.getElementById("downloadPart1").href = "/getPart1?task=" + localStorage.getItem("taskId"); jQuery('#continue').off('click').on('click', function () { jQuery.ajax({ type: 'POST', data: { action: 'do-bruteforce', taskId: localStorage.getItem('taskId') }, success: function (data) { changeStep(STEP_BRUTEFORCING); } }); }); } } if (localStorage.getItem('taskId')) { var currentTask = localStorage.getItem('taskId'); jQuery.ajax({ type: 'POST', dataType: 'json', data: { action: 'get-state', taskId: localStorage.getItem('taskId') }, success: function (data) { if (currentTask === localStorage.getItem('taskId')) { var currentState = data.currentState; if (currentState === -1) { showUnmineableModal(); changeStep(STEP_INITIAL); } if (currentState === -2) { showUnmineableModal(); changeStep(STEP_INITIAL); } if (currentState === 0 ) { //= Waitingfor Part1 Dumper changeStep(STEP_WAITING_FOR_PART1_DUMPER); } if (currentState === 1 ) { //= Part1 Dumper Claimed localStorage.setItem('claimedBy', data.claimedBy) changeStep(STEP_ADD_THE_BOT); } if (currentState === 2 ) { //= Part1 Dumper Done changeStep(STEP_BRUTEFORCE_CHOOSE) } if (currentState === 4 || currentState === 3) { //= Bruteforcing or Wait for Bruteforce changeStep(STEP_BRUTEFORCING); } if (currentState === 5 ) { //= Movable.sed ready changeStep(STEP_MOVABLE_DONE); } } } }); //@TODO: Instead of going to BRUTEFORCING this needs to get the state first from the server } else { changeStep(STEP_INITIAL); } jQuery(document).on('click', '#cancelButton3, #cancelButton, #cancelButton2, #cancelButton1', function () { changeStep(STEP_INITIAL); }); jQuery(document).on('click', '#cancelButton3', function () { changeStep(STEP_INITIAL); }); var beginButton = document.getElementById("beginButton"); beginButton.addEventListener("click", function (e) { e.preventDefault(); document.getElementById("beginButton").disabled = true; document.getElementById("id0").value = document.getElementById("id0").value.toLowerCase(); if (document.getElementById("part1b64").value.length === 0) { processMovablePart1(); } var id0Val = document.getElementById("id0").value.replace(/[^A-Za-z0-9]/g,""); document.getElementById("id0").value = id0Val; var part1b64Val = document.getElementById("part1b64").value; if (part1b64Val.length > 0 && id0Val.length === 32) { //Part1 Supplied, we can skip the bot phase localStorage.setItem("id0", id0Val); localStorage.setItem("part1b64", part1b64Val.value); jQuery.ajax({ type: 'POST', dataType: 'json', data: { id0: id0Val, part1b64: part1b64Val }, success: function (data) { if (data.success === true) { localStorage.setItem("taskId", data.taskId); changeStep(STEP_BRUTEFORCING); } else { alert(data.message); } } }); return; } document.getElementById("friendCode").value = document.getElementById("friendCode").value.toLowerCase(); var fcVal = document.getElementById("friendCode").value.replace(/[^0-9]/g,""); document.getElementById("friendCode").value = fcVal; if (!CheckFC(fcVal)) { alert('The FriendCode you supplied is not valid. Please make sure your input was correct.'); } if (fcVal.length === 12 && id0Val.length === 32 && CheckFC(fcVal)) { //Part1 not supplied, send and wait for bot localStorage.setItem("id0", id0Val); jQuery.ajax({ type: 'POST', dataType: 'json', data: { id0: id0Val, friendcode: fcVal }, success: function (data) { if (data.success === true) { localStorage.setItem("taskId", data.taskId); changeStep(STEP_WAITING_FOR_PART1_DUMPER); } else { alert(data.message); changeStep(STEP_INITIAL); } } }); return; } if (id0Val.length > 0 && id0Val.length < 32) { alert("The id0 you provided is not of the correct length. Expected 32 Characters"); } }); jQuery('#uploadp1').on('click', function (e) { let fileInput = document.getElementById("p1file"); fileInput.click(); e.preventDefault(); }); jQuery('#p1file').on('change', function (e) { processMovablePart1(); e.preventDefault(); }); });
37.470866
140
0.495125
0106037734cce94459abd3be1bb48da4b95089bd
495
js
JavaScript
src/components/pages/films.js
AaronIngersoll/kelseyCreations
ecbeb23b211c78add717621f9ce668bb85b07ee9
[ "MIT" ]
1
2020-07-23T22:36:48.000Z
2020-07-23T22:36:48.000Z
src/components/pages/films.js
AaronIngersoll/kelseyCreations
ecbeb23b211c78add717621f9ce668bb85b07ee9
[ "MIT" ]
6
2021-03-09T01:07:26.000Z
2022-02-26T09:59:28.000Z
src/components/pages/films.js
AaronIngersoll/kelseyCreations
ecbeb23b211c78add717621f9ce668bb85b07ee9
[ "MIT" ]
null
null
null
import React from "react"; import VidGrid from "../films/filmsNav"; export default function() { return ( <div className="filmsPage"> <div className="skewed-header"> <div className="header-bg2" /> <div className="skewed-header-wrapper"> <div className="skewed-header-content"> <div className="heading-wrapper"> <h1>Gallery</h1> </div> </div> </div> </div> <VidGrid /> </div> ); }
20.625
49
0.533333
0115d33aa2032d322902abaca9b42cd2747a921c
6,833
js
JavaScript
manage.js
stranger777/slick-rss
5c7121351025fe54987d675767bf041bc379bba7
[ "MIT" ]
14
2015-05-25T22:17:58.000Z
2020-08-04T08:32:41.000Z
manage.js
stranger777/slick-rss
5c7121351025fe54987d675767bf041bc379bba7
[ "MIT" ]
1
2019-10-10T14:07:58.000Z
2019-10-10T14:07:58.000Z
manage.js
stranger777/slick-rss
5c7121351025fe54987d675767bf041bc379bba7
[ "MIT" ]
13
2015-03-13T04:49:35.000Z
2021-04-17T00:17:29.000Z
var bgPage = chrome.extension.getBackgroundPage(); var options = bgPage.options; var feeds = bgPage.feeds; var lastBadRow = null; $(document).ready(function() { $('#save').click(function(){Save();}); $('#add').click(function(){Add();}); }); window.onload = ShowFeeds; function Add() { var title = document.getElementById("newTitle").value; var url = document.getElementById("newUrl").value; var maxItems = document.getElementById("newMaxItems").value; var order = document.getElementById("newOrder").value; var key = null; var maxOrder = 0; var itemOrder = 0; if(!IsValid(title, url, maxItems, order)) { return; } AddRow(feeds.push(bgPage.CreateNewFeed(title, url, maxItems, order)) - 1); for(feedKey in feeds) { itemOrder = parseInt(feeds[feedKey].order); if(itemOrder > maxOrder) { maxOrder = itemOrder; } } document.getElementById("newOrder").value = maxOrder + 1; document.getElementById("newTitle").value = ""; document.getElementById("newUrl").value = ""; } function IsValid(title, url, maxItems, order) { if(title == "") { alert("A title is required. Name it something useful like 'My Awesome Gaming News Feed'."); return false; } if(url == "") { alert("A URL is required. It's the full HTTP path to your feed."); return false; } if(maxItems == "") { alert("Max items is required. It's the max number of items you want me to show you for this feed."); return false; } if(maxItems == "0") { alert("Ha ha funny person. You need at least 1 max item in order to show you a feed."); return false; } if(!/^\d+$/.test(maxItems)) { alert("Very funny, you and I both know '" + maxItems + "' isn't a value max item number."); return false; } if(order == "") { alert("Order is required. It's the order I'll display your feeds in the viewer."); return false; } if(!/^\d+$/.test(order)) { alert("Very funny, you and I both know '" + order + "' isn't a value order."); return false; } return true; } function AddRow(feedKey) { var grid = null; var row = null; var input = null; var button = null; grid = document.getElementById("feedGrid"); row = grid.insertRow(grid.rows.length); row.setAttribute("id", feedKey); input = document.createElement('input'); input.setAttribute("type", "text"); input.setAttribute("class", "title"); input.setAttribute("value", feeds[feedKey].title); row.insertCell(0).appendChild(input); input = document.createElement('input'); input.setAttribute("type", "text"); input.setAttribute("class", "url"); input.setAttribute("value", feeds[feedKey].url); row.insertCell(1).appendChild(input); input = document.createElement('input'); input.setAttribute("type", "text"); input.setAttribute("class", "maxItems"); input.setAttribute("value", feeds[feedKey].maxitems); row.insertCell(2).appendChild(input); input = document.createElement('input'); input.setAttribute("type", "text"); input.setAttribute("class", "order"); input.setAttribute("value", feeds[feedKey].order); row.insertCell(3).appendChild(input); button = document.createElement("img"); button.setAttribute("src", "x.gif"); button.setAttribute("class", "delete"); //var tmp = this.parentNode.parentNode; $(button).click({id:feedKey}, function(event) { MarkDelete($('#' + event.data.id).get(0)); }); //button.setAttribute("onclick", "MarkDelete(this.parentNode.parentNode);"); button.setAttribute("title", "Delete feed"); row.insertCell(4).appendChild(button); } function MarkDelete(row) { var marked = (row.className == "markDelete"); if(!marked) { row.setAttribute("class", "markDelete"); } else { if(row != lastBadRow) { row.setAttribute("class", ""); } else { row.setAttribute("class", "badRow"); } } row.childNodes[0].childNodes[0].disabled = !marked; // title row.childNodes[1].childNodes[0].disabled = !marked; // url row.childNodes[2].childNodes[0].disabled = !marked; // max items row.childNodes[3].childNodes[0].disabled = !marked; // order } function Save() { var row = null; var title; var url; var maxItems; var order; if(lastBadRow != null && lastBadRow.className != "markDelete") { lastBadRow.className = ""; } for(feedKey in feeds) { // skip read later feed if(feedKey == 0) { continue; } row = document.getElementById(feedKey); title = row.childNodes[0].childNodes[0].value; url = row.childNodes[1].childNodes[0].value; maxItems = row.childNodes[2].childNodes[0].value; order = row.childNodes[3].childNodes[0].value; if(row.className != "markDelete" && !IsValid(title, url, maxItems, order)) { row.className = "badRow"; lastBadRow = row; return; } feeds[feedKey].title = title; feeds[feedKey].url = url; feeds[feedKey].maxitems = maxItems; feeds[feedKey].order = order; } // delete feeds that are marked, start from end so indexes don't get screwed up for(i = feeds.length - 1;i > 0;i--) { row = document.getElementById(i); if(row.className == "markDelete") { feeds.splice(i, 1); } } // remove read later feed feeds.splice(0,1); localStorage["feeds"] = JSON.stringify(feeds); bgPage.UpdateSniffer(); bgPage.CleanUpUnreadOrphans(); // get feeds to re-order the feeds bgPage.GetFeeds(function() { bgPage.CheckForUnreadStart(); window.location = 'viewer.html'; }); } function ShowFeeds() { var maxOrder = 0; var itemOrder = 0; for(feedKey in feeds) { // skip read later feed if(feedKey == 0) { continue; } AddRow(feedKey); itemOrder = parseInt(feeds[feedKey].order); if(itemOrder > maxOrder) { maxOrder = itemOrder; } } document.getElementById("newOrder").value = maxOrder + 1; document.getElementById("newMaxItems").value = options.maxitems; }
25.214022
109
0.563442
bbf1deec868c59bc3a72b84e0c635be8879b4812
109
js
JavaScript
src/spec.helpers.js
twuni/throwables.js
57f9a6c9857b913c39d95a0b3d70c8a904362f4f
[ "MIT" ]
1
2020-08-06T17:11:11.000Z
2020-08-06T17:11:11.000Z
src/spec.helpers.js
twuni/throwables.js
57f9a6c9857b913c39d95a0b3d70c8a904362f4f
[ "MIT" ]
3
2020-09-05T18:24:29.000Z
2021-05-09T18:02:34.000Z
src/spec.helpers.js
twuni/throwables.js
57f9a6c9857b913c39d95a0b3d70c8a904362f4f
[ "MIT" ]
null
null
null
import { describe, it } from 'mocha'; import { expect } from 'chai'; export { describe, expect, it };
12.111111
37
0.614679
010e38c21b8d60b131d34368f2d5edcde44aa46c
2,281
js
JavaScript
studio/node_modules/@sanity/form-builder/lib/inputs/InvalidValueInput/converters.js
JoseGarciaM/TC3049
ee13fe3c6e490321aa686d193df1ac61b04f04ae
[ "MIT" ]
1
2020-09-13T08:10:13.000Z
2020-09-13T08:10:13.000Z
studio/node_modules/@sanity/form-builder/lib/inputs/InvalidValueInput/converters.js
JoseGarciaM/TC3049
ee13fe3c6e490321aa686d193df1ac61b04f04ae
[ "MIT" ]
26
2020-07-21T06:38:39.000Z
2022-03-26T23:23:58.000Z
studio/node_modules/@sanity/form-builder/lib/inputs/InvalidValueInput/converters.js
JoseGarciaM/TC3049
ee13fe3c6e490321aa686d193df1ac61b04f04ae
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _is_valid = _interopRequireDefault(require("date-fns/is_valid")); var _parse = _interopRequireDefault(require("date-fns/parse")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TRUTHY_STRINGS = ['yes', 'true', '1']; var FALSEY_STRINGS = ['false', 'no', 'false', '0', 'null']; var BOOL_STRINGS = TRUTHY_STRINGS.concat(FALSEY_STRINGS); var TRUE = () => true; var has = prop => val => val && val[prop]; var is = typeName => val => (val && val._type) === typeName; function toLocalDate(input) { var newDate = new Date(input.getTime() + input.getTimezoneOffset() * 60 * 1000); var offset = input.getTimezoneOffset() / 60; var hours = input.getHours(); newDate.setHours(hours - offset); return newDate; } function getTZName() { try { return Intl.DateTimeFormat().resolvedOptions().timeZone; } catch (e) {} // eslint-disable-line no-empty return null; } var _default = { string: { number: { test: Number, convert: Number }, boolean: { test: value => BOOL_STRINGS.includes(value.toLowerCase()), convert: value => TRUTHY_STRINGS.includes(value.toLowerCase()) || !FALSEY_STRINGS.includes(value.toLowerCase()) }, richDate: { test: val => (0, _is_valid.default)((0, _parse.default)(val)), convert: value => { return { _type: 'richDate', local: toLocalDate(new Date(value)).toJSON(), utc: new Date(value).toJSON(), timezone: getTZName(), offset: new Date().getTimezoneOffset() }; } } }, date: { richDate: { test: is('date'), convert: value => Object.assign({}, value, { _type: 'richDate' }) } }, richDate: { datetime: { test: has('utc'), convert: value => value.utc } }, number: { string: { test: TRUE, convert: String }, boolean: { test: TRUE, convert: Number } }, boolean: { string: { test: TRUE, convert: value => value ? 'Yes' : 'No' }, number: { test: TRUE, convert: Number } } }; exports.default = _default;
23.040404
117
0.586146
bbeba58bf83d4be4d7b0453464dae62c0e46fe13
899
js
JavaScript
server/ghost.js
ClemDelp/iso.io
852c611f7872eace9a2052464fdfd9fc67584ae1
[ "MIT" ]
3
2018-01-02T13:04:21.000Z
2020-12-07T20:16:47.000Z
server/ghost.js
ClemDelp/iso.io
852c611f7872eace9a2052464fdfd9fc67584ae1
[ "MIT" ]
null
null
null
server/ghost.js
ClemDelp/iso.io
852c611f7872eace9a2052464fdfd9fc67584ae1
[ "MIT" ]
null
null
null
import Element from './Element' export default class Ghost extends Element { constructor () { super() this.type = 'ghost' this.canHover = ['grass'] this.img = 'assets/sprites/ghosts.png' this.animations = { top: { frames: [120, 140], duration: 10, loop: true }, right: { frames: [0, 20], duration: 10, loop: true }, bottom: { frames: [40, 60], duration: 10, loop: true }, left: { frames: [80, 100], duration: 10, loop: true } } this.body.collideWorldBounds = false this.size = [32, 32] this.scale = [0.75, 0.75] this.orientation = 'bottom' this.velocity = 5 // px per move this.speed = 100 this.triesBeforeExplosion = 2 this.explosion = true this.tileName = 'ghost' this.isoZ = 200 } }
20.906977
44
0.517241
01168f278777cbf301038ffb98542490c6c97fd5
10,690
js
JavaScript
app/models/server/raw/LivechatDepartment.js
dirkmueller/Rocket.Chat
e8d8b2f0d2469fecca962356e3dcc0818b86332e
[ "MIT" ]
1
2021-03-23T10:41:48.000Z
2021-03-23T10:41:48.000Z
app/models/server/raw/LivechatDepartment.js
dirkmueller/Rocket.Chat
e8d8b2f0d2469fecca962356e3dcc0818b86332e
[ "MIT" ]
3
2021-08-04T00:24:17.000Z
2022-01-15T02:10:40.000Z
app/models/server/raw/LivechatDepartment.js
santoshsingh-94/rocketchat2
666f617820471fd22fca69c5ff5552e7c687602b
[ "MIT" ]
null
null
null
import { BaseRaw } from './BaseRaw'; import { getValue } from '../../../settings/server/raw'; export class LivechatDepartmentRaw extends BaseRaw { findAllRooms({ start, end, answered, departmentId, options = {} }) { const roomsFilter = [ { $gte: ['$$room.ts', new Date(start)] }, { $lte: ['$$room.ts', new Date(end)] }, ]; if (answered !== undefined) { roomsFilter.push({ [answered ? '$ne' : '$eq']: ['$$room.waitingResponse', true] }); } const lookup = { $lookup: { from: 'rocketchat_room', localField: '_id', foreignField: 'departmentId', as: 'rooms', }, }; const project = { $project: { name: 1, description: 1, enabled: 1, rooms: { $size: { $filter: { input: '$rooms', as: 'room', cond: { $and: roomsFilter, }, }, }, }, }, }; const match = { $match: { _id: departmentId, }, }; const params = [lookup, project]; if (departmentId) { params.unshift(match); } if (options.offset) { params.push({ $skip: options.offset }); } if (options.count) { params.push({ $limit: options.count }); } if (options.sort) { params.push({ $sort: { name: 1 } }); } return this.col.aggregate(params).toArray(); } findAllAverageServiceTime({ start, end, departmentId, options = {} }) { const roomsFilter = [ { $gte: ['$$room.ts', new Date(start)] }, { $lte: ['$$room.ts', new Date(end)] }, ]; const lookup = { $lookup: { from: 'rocketchat_room', localField: '_id', foreignField: 'departmentId', as: 'rooms', }, }; const projects = [ { $project: { department: '$$ROOT', rooms: { $filter: { input: '$rooms', as: 'room', cond: { $and: roomsFilter, }, }, }, }, }, { $project: { department: '$department', chats: { $size: '$rooms' }, chatsDuration: { $sum: '$rooms.metrics.chatDuration' }, }, }, { $project: { name: '$department.name', description: '$department.description', enabled: '$department.enabled', averageServiceTimeInSeconds: { $ceil: { $cond: [{ $eq: ['$chats', 0] }, 0, { $divide: ['$chatsDuration', '$chats'] }] } }, }, }]; const match = { $match: { _id: departmentId, }, }; const params = [lookup, ...projects]; if (departmentId) { params.unshift(match); } if (options.offset) { params.push({ $skip: options.offset }); } if (options.count) { params.push({ $limit: options.count }); } if (options.sort) { params.push({ $sort: { name: 1 } }); } return this.col.aggregate(params).toArray(); } findAllServiceTime({ start, end, departmentId, options = {} }) { const roomsFilter = [ { $gte: ['$$room.ts', new Date(start)] }, { $lte: ['$$room.ts', new Date(end)] }, ]; const lookup = { $lookup: { from: 'rocketchat_room', localField: '_id', foreignField: 'departmentId', as: 'rooms', }, }; const projects = [ { $project: { department: '$$ROOT', rooms: { $filter: { input: '$rooms', as: 'room', cond: { $and: roomsFilter, }, }, }, }, }, { $project: { name: '$department.name', description: '$department.description', enabled: '$department.enabled', chats: { $size: '$rooms' }, chatsDuration: { $ceil: { $sum: '$rooms.metrics.chatDuration' } }, }, }]; const match = { $match: { _id: departmentId, }, }; const params = [lookup, ...projects]; if (departmentId) { params.unshift(match); } if (options.offset) { params.push({ $skip: options.offset }); } if (options.count) { params.push({ $limit: options.count }); } if (options.sort) { params.push({ $sort: { name: 1 } }); } return this.col.aggregate(params).toArray(); } findAllAverageWaitingTime({ start, end, departmentId, options = {} }) { const roomsFilter = [ { $gte: ['$$room.ts', new Date(start)] }, { $lte: ['$$room.ts', new Date(end)] }, { $ne: ['$$room.waitingResponse', true] }, ]; const lookup = { $lookup: { from: 'rocketchat_room', localField: '_id', foreignField: 'departmentId', as: 'rooms', }, }; const projects = [{ $project: { department: '$$ROOT', rooms: { $filter: { input: '$rooms', as: 'room', cond: { $and: roomsFilter, }, }, }, }, }, { $project: { department: '$department', chats: { $size: '$rooms' }, chatsFirstResponses: { $sum: '$rooms.metrics.response.ft' }, }, }, { $project: { name: '$department.name', description: '$department.description', enabled: '$department.enabled', averageWaitingTimeInSeconds: { $ceil: { $cond: [{ $eq: ['$chats', 0] }, 0, { $divide: ['$chatsFirstResponses', '$chats'] }] } }, }, }]; const match = { $match: { _id: departmentId, }, }; const params = [lookup, ...projects]; if (departmentId) { params.unshift(match); } if (options.offset) { params.push({ $skip: options.offset }); } if (options.count) { params.push({ $limit: options.count }); } if (options.sort) { params.push({ $sort: { name: 1 } }); } return this.col.aggregate(params).toArray(); } findAllNumberOfTransferredRooms({ start, end, departmentId, options = {} }) { const messageFilter = [ { $gte: ['$$message.ts', new Date(start)] }, { $lte: ['$$message.ts', new Date(end)] }, { $eq: ['$$message.t', 'livechat_transfer_history'] }, ]; const roomsLookup = { $lookup: { from: 'rocketchat_room', localField: '_id', foreignField: 'departmentId', as: 'rooms', }, }; const messagesLookup = { $lookup: { from: 'rocketchat_message', localField: 'rooms._id', foreignField: 'rid', as: 'messages', }, }; const projectRooms = { $project: { department: '$$ROOT', rooms: 1, }, }; const projectMessages = { $project: { department: '$department', messages: { $filter: { input: '$messages', as: 'message', cond: { $and: messageFilter, }, }, }, }, }; const projectTransfersSize = { $project: { department: '$department', transfers: { $size: { $ifNull: ['$messages', []] } }, }, }; const group = { $group: { _id: { departmentId: '$department._id', name: '$department.name', description: '$department.description', enabled: '$department.enabled', }, numberOfTransferredRooms: { $sum: '$transfers' }, }, }; const presentationProject = { $project: { _id: '$_id.departmentId', name: '$_id.name', description: '$_id.description', enabled: '$_id.enabled', numberOfTransferredRooms: 1, }, }; const unwind = { $unwind: { path: '$rooms', preserveNullAndEmptyArrays: true, }, }; const match = { $match: { _id: departmentId, }, }; const params = [roomsLookup, projectRooms, unwind, messagesLookup, projectMessages, projectTransfersSize, group, presentationProject]; if (departmentId) { params.unshift(match); } if (options.offset) { params.push({ $skip: options.offset }); } if (options.count) { params.push({ $limit: options.count }); } if (options.sort) { params.push({ $sort: { name: 1 } }); } return this.col.aggregate(params).toArray(); } async findAllNumberOfAbandonedRooms({ start, end, departmentId, options = {} }) { const roomsFilter = [ { $gte: ['$$room.ts', new Date(start)] }, { $lte: ['$$room.ts', new Date(end)] }, { $gte: ['$$room.metrics.visitorInactivity', await getValue('Livechat_visitor_inactivity_timeout')] }, ]; const lookup = { $lookup: { from: 'rocketchat_room', localField: '_id', foreignField: 'departmentId', as: 'rooms', }, }; const projects = [{ $project: { department: '$$ROOT', rooms: { $filter: { input: '$rooms', as: 'room', cond: { $and: roomsFilter, }, }, }, }, }, { $project: { name: '$department.name', description: '$department.description', enabled: '$department.enabled', abandonedRooms: { $size: '$rooms' }, }, }]; const match = { $match: { _id: departmentId, }, }; const params = [lookup, ...projects]; if (departmentId) { params.unshift(match); } if (options.offset) { params.push({ $skip: options.offset }); } if (options.count) { params.push({ $limit: options.count }); } if (options.sort) { params.push({ $sort: { name: 1 } }); } return this.col.aggregate(params).toArray(); } findPercentageOfAbandonedRooms({ start, end, departmentId, options = {} }) { const roomsFilter = [ { $gte: ['$$room.ts', new Date(start)] }, { $lte: ['$$room.ts', new Date(end)] }, ]; const lookup = { $lookup: { from: 'rocketchat_room', localField: '_id', foreignField: 'departmentId', as: 'rooms', }, }; const projectRooms = { $project: { department: '$$ROOT', rooms: { $filter: { input: '$rooms', as: 'room', cond: { $and: roomsFilter, }, }, }, }, }; const unwind = { $unwind: { path: '$rooms', preserveNullAndEmptyArrays: true, }, }; const group = { $group: { _id: { departmentId: '$department._id', name: '$department.name', description: '$department.description', enabled: '$department.enabled', }, abandonedChats: { $sum: { $cond: [{ $and: [ { $ifNull: ['$rooms.metrics.visitorInactivity', false] }, { $gte: ['$rooms.metrics.visitorInactivity', 1] }, ], }, 1, 0], }, }, chats: { $sum: 1 }, }, }; const presentationProject = { $project: { _id: '$_id.departmentId', name: '$_id.name', description: '$_id.description', enabled: '$_id.enabled', percentageOfAbandonedChats: { $floor: { $cond: [ { $eq: ['$chats', 0] }, 0, { $divide: [{ $multiply: ['$abandonedChats', 100] }, '$chats'] }, ], }, }, }, }; const match = { $match: { _id: departmentId, }, }; const params = [lookup, projectRooms, unwind, group, presentationProject]; if (departmentId) { params.unshift(match); } if (options.offset) { params.push({ $skip: options.offset }); } if (options.count) { params.push({ $limit: options.count }); } if (options.sort) { params.push({ $sort: { name: 1 } }); } return this.col.aggregate(params).toArray(); } }
21.816327
136
0.537886
bbf1228f364d535a823f82cf68f6478941751c6a
677
js
JavaScript
packages/material-ui-icons/src/ContactSupportRounded.js
silver-snoopy/material-ui
917a3ddb8c72651fdbd4d35b1cd48ce9a06f8139
[ "MIT" ]
8
2021-03-18T08:41:32.000Z
2021-04-19T10:24:50.000Z
packages/material-ui-icons/src/ContactSupportRounded.js
Hypermona/material-ui
9ff8d1627016ee2eb3bded3dd55bccebe8f3a306
[ "MIT" ]
129
2021-05-05T15:07:04.000Z
2022-03-27T02:51:27.000Z
packages/material-ui-icons/src/ContactSupportRounded.js
danncortes/material-ui
1eea9427971f716bd7fd17401d918841a9bd749e
[ "MIT" ]
1
2021-03-25T23:57:05.000Z
2021-03-25T23:57:05.000Z
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M11.5 2C6.81 2 3 5.81 3 10.5S6.81 19 11.5 19h.5v3c4.86-2.34 8-7 8-11.5C20 5.81 16.19 2 11.5 2zm-.02 14c-.59 0-1.05-.47-1.05-1.05 0-.59.47-1.04 1.05-1.04.59 0 1.04.45 1.04 1.04 0 .58-.44 1.05-1.04 1.05zm2.51-6.17c-.63.93-1.23 1.21-1.56 1.81-.08.14-.13.26-.16.49-.05.39-.36.68-.75.68h-.03c-.44 0-.79-.38-.75-.82.03-.28.09-.57.25-.84.41-.73 1.18-1.16 1.63-1.8.48-.68.21-1.94-1.14-1.94-.61 0-1.01.32-1.26.7-.19.29-.57.39-.89.25-.42-.18-.6-.7-.34-1.07C9.5 6.55 10.35 6 11.47 6c1.23 0 2.08.56 2.51 1.26.36.61.58 1.73.01 2.57z" /> , 'ContactSupportRounded');
96.714286
534
0.630724
01174ceb815e0f78c8aba5891e389155783eacbe
1,247
js
JavaScript
.eslintrc.js
yaremenkosa/mu
191fd7c15c6e42b93a829c2b051439b96b5fc5cc
[ "MIT" ]
6
2016-04-24T07:04:03.000Z
2021-04-21T10:58:05.000Z
.eslintrc.js
yaremenkosa/mu
191fd7c15c6e42b93a829c2b051439b96b5fc5cc
[ "MIT" ]
2
2019-12-29T22:09:59.000Z
2021-05-08T21:50:01.000Z
.eslintrc.js
yaremenkosa/mu
191fd7c15c6e42b93a829c2b051439b96b5fc5cc
[ "MIT" ]
1
2021-05-08T21:39:12.000Z
2021-05-08T21:39:12.000Z
module.exports = { root: true, env: { browser: true, node: true, es6: true, }, globals: { app: 'readonly', Alice: 'readonly', }, extends: [ //https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb-base/rules // 'airbnb-base', 'plugin:sonarjs/recommended', 'prettier', ], plugins: ['prettier', 'sonarjs'], parserOptions: { parser: 'babel-eslint', sourceType: 'module', }, rules: { 'global-require': 0, // Only allow debugger in development 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', // Only allow `console.log` in development 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', 'import/no-unresolved': 0, 'no-unused-vars': ['error', { vars: 'all', args: 'none', ignoreRestSiblings: false }], 'no-underscore-dangle': 'warn', 'sonarjs/no-identical-expressions': 'error', 'sonarjs/no-identical-functions': 'warn', 'sonarjs/cognitive-complexity': ['warn', 15], /*'unicorn/filename-case': [ 'error', { cases: { camelCase: true, pascalCase: true, }, }, ], 'unicorn/prevent-abbreviations': 'warn',*/ }, }
26.531915
95
0.581395
bbe890a8b9ae7bac0c97829cc98d3010ff4cc0ef
957
js
JavaScript
public/metronic/js/vendor/ckeditor/plugins/clipboard/lang/ca.js
Murukan-GitHub/TalentSaga
194214e8e76f4a0424eb2457d02aeac240f51b08
[ "MIT" ]
1
2021-05-19T01:23:25.000Z
2021-05-19T01:23:25.000Z
public/metronic/js/vendor/ckeditor/plugins/clipboard/lang/ca.js
Murukan-GitHub/TalentSaga
194214e8e76f4a0424eb2457d02aeac240f51b08
[ "MIT" ]
1
2016-12-10T20:07:53.000Z
2016-12-10T20:07:53.000Z
public/metronic/js/vendor/ckeditor/plugins/clipboard/lang/ca.js
Murukan-GitHub/TalentSaga
194214e8e76f4a0424eb2457d02aeac240f51b08
[ "MIT" ]
1
2021-05-19T01:25:01.000Z
2021-05-19T01:25:01.000Z
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'clipboard', 'ca', { copy: 'Copiar', copyError: 'La configuració de seguretat del vostre navegador no permet executar automàticament les operacions de copiar. Si us plau, utilitzeu el teclat (Ctrl/Cmd+C).', cut: 'Retallar', cutError: 'La configuració de seguretat del vostre navegador no permet executar automàticament les operacions de retallar. Si us plau, utilitzeu el teclat (Ctrl/Cmd+X).', paste: 'Enganxar', pasteArea: 'Àrea d\'enganxat', pasteMsg: 'Si us plau, enganxi dins del següent camp utilitzant el teclat (<strong>Ctrl/Cmd+V</strong>) i premi OK.', securityMsg: 'A causa de la configuració de seguretat del vostre navegador, l\'editor no pot accedir a les dades del porta-retalls directament. Enganxeu-ho un altre cop en aquesta finestra.', title: 'Enganxar' } );
59.8125
192
0.754441
bbe81b359ea293c1402ada935dd020b2b25feb59
278
js
JavaScript
tests/files/webpack.config.js
robin-hartmann/eslint-plugin-import
e7d3b48ccff43e4aa093f9397ab100388db5ab86
[ "MIT" ]
3,584
2015-03-19T15:56:46.000Z
2021-07-23T09:32:27.000Z
tests/files/webpack.config.js
robin-hartmann/eslint-plugin-import
e7d3b48ccff43e4aa093f9397ab100388db5ab86
[ "MIT" ]
2,011
2015-03-17T11:28:54.000Z
2021-07-24T04:49:19.000Z
tests/files/webpack.config.js
robin-hartmann/eslint-plugin-import
e7d3b48ccff43e4aa093f9397ab100388db5ab86
[ "MIT" ]
1,531
2015-07-16T17:32:17.000Z
2021-07-24T04:18:06.000Z
module.exports = { resolve: { extensions: ['', '.js', '.jsx'], root: __dirname, alias: { 'alias/chai$': 'chai', // alias for no-extraneous-dependencies tests 'alias/esm-package': 'esm-package' // alias for no-extraneous-dependencies tests } }, }
25.272727
86
0.593525
010ac984a018ded3e67f453d8307ee13e0223723
4,907
js
JavaScript
parser.js
jamesduncan/digihymnal
b270bc585c91145a8212f50e59740776ae512016
[ "MIT" ]
3
2020-11-25T06:56:11.000Z
2021-08-13T17:25:28.000Z
parser.js
Achoobert/digihymnal
761d83dbd28edb742a36dfdf8e5a1584e2284a1e
[ "MIT" ]
39
2020-11-23T07:22:34.000Z
2022-03-07T05:33:16.000Z
parser.js
Achoobert/digihymnal
761d83dbd28edb742a36dfdf8e5a1584e2284a1e
[ "MIT" ]
1
2021-05-09T06:13:52.000Z
2021-05-09T06:13:52.000Z
const dirTree = require("directory-tree"); var fs = require('fs'); const { stringify } = require("querystring"); var parseDir = function (path) { // an npm module that makes a tree out of a dir var currDir = dirTree(path); //return currDir currDir.children.forEach(element => { openFile(element.path) }); }; function openFile(path){ var fs = require('fs'); fs.readFile(path, 'ucs2', function(err, data) { if (err) throw err; var filename = path.split("/").pop() filename = path.split("\\").pop() filename = filename.split(".").shift() console.log(filename) onSong2JSON(data, filename); }); } // FEED ME YOUR T E S T D A T A parseDir("D:/schubert.dev/parser/samples") var testData = (`Kencho Gi Gawa Dzongkha Key: E [E]Kencho [G#m]Choe gi [A]sem gi phodrang [E]na nga [A]lu [E]Choe gi za[B]na [C#m]Choe gi [G#m]gawa gi [A]nga [E]lu zhing[F#m]kham gi [B]lam [E]toen ye [E]Ha..[G#m]lle..[A]lu…[E]jah Ha..[A]lle..[E]lu…[B]jah [C#m]Choe gi [G#m]gawa gi [A]nga [E]lu zhing[F#m]kham gi [B]lam [E]toen ye [E]Kencho [G#m]Choe gi [A]sem gi phodrang [E]na nga [A]lu [E]Choe gi za[B]na [C#m]Choe gi [G#m]gawa gi [A]nga [E]lu zhing[F#m]kham gi [B]lam [E]toen ye [E]Ha..[G#m]lle..[A]lu…[E]jah Ha..[A]lle..[E]lu…[B]jah [C#m]Choe gi [G#m]gawa gi [A]nga [E]lu zhing[F#m]kham gi [B]lam [E]toen ye`) // This one is guaranteed to work // onSong2JSON(testData) //this will parse XML file function onSong2JSON(data, filename) { try { var song = {}; var removeSpaces = /\s+,"-"/ //str = str.trim().replaceAll("\\s+", " "); song.id = filename.replace(/\s+/g, "_") //song.id = (filename) // Clean any un-needed characters function cleanString(input) { // TODO strip out all '/t' var output = ""; var output = input.replace(/([\t])/g, ''); //for (var i=0; i<input.length; i++) { // if (input.charCodeAt(i) <= 127) { // output += input.charAt(i); // } //} return output; } data = cleanString(data) // select the first three lines // [0] is the whole dataset, first line is '1' var dataArray = data.split(/\r?\n/) //var getMetaLines = /(.*?)\n(.*?)\n(.*?)\n(.*)/ // first line //song.title = (getMetaLines.exec(data)[1]) currentTitle = dataArray[0] song.title = ({"en":currentTitle}) // second line //song.author = (getMetaLines.exec(data)[2]) song.author = (dataArray[1]) // third line skip "Key: " var selectKey = /(?![Key: ])(.*)/ //console.log(selectKey.exec("Key: G#")[0]) //console.log(selectKey.exec("Key: C")[0]) //song.key = (selectKey.exec(getMetaLines.exec(data)[3])[0]) song.key = (selectKey.exec(dataArray[2])[0]) song.lyrics = {} song.lyrics.Verses = [] // TODO I'm assuming data starts on 5th line let lyricsStart = 4 // Make array of just lyrics var toBeParsed = dataArray.splice(lyricsStart) //console.log(lyrics) // A temporary variable that toBeParsed calls var currentVerse = {} currentVerse.lines = [] // TODO use label, using a number for now var currentVerseLabel = 1 currentVerse.label = ("verse " + currentVerseLabel.toString()) // add a set of phrases (line) to the verse function addToVerse(currentLine){ currentVerse.lines.push({phrases:currentLine}) } // close the verse, push it to the song, and clear it function closeVerse(){ song.lyrics.Verses.push(currentVerse) currentVerseLabel++ currentVerse = {} currentVerse.lines = [] currentVerse.label = ("verse " + currentVerseLabel.toString()) } // parse each remaining line in the file toBeParsed.forEach(line => { if(line == ""){ // If there's a totally blank line, new verse/chorus closeVerse() } else { var currentLine = [] function addPhrase(phrase){ currentLine.push({"chord":phrase[0], "en":phrase[1]}) } var phrases = (line.split(/\r?\[/)) phrases.forEach(phrase => { let currentPhrase = phrase.split(/\r?]/) // try splitting if(currentPhrase.length === 2){ // has chord addPhrase(currentPhrase) } else if (currentPhrase.length === 1 && currentPhrase != ""){ // Just lyric addPhrase(['', currentPhrase[0]]) } }); // once all phrases have been split up, add the line addToVerse(currentLine) } }); if (currentVerse.length>0){ closeVerse() } // print the file console.log(song) output = (`export default ${JSON.stringify(song)} ;`) // Output the file... fs.writeFile((`./json/${filename}.js`), output, function(err) { if (err) { console.log(err); } }); } catch (e) { console.error(e.message); } }
28.52907
86
0.578969
0114a9858b1f80237e22b25f251fe6d9ddcd1689
1,145
js
JavaScript
math/is-jumping-number.js
ganorberg/algorithms-javascript
305023441cbadc99f7cf09b35fe60383cda7fdd9
[ "MIT" ]
5
2017-11-29T05:04:59.000Z
2021-09-19T17:11:18.000Z
math/is-jumping-number.js
ganorberg/algorithms-javascript
305023441cbadc99f7cf09b35fe60383cda7fdd9
[ "MIT" ]
null
null
null
math/is-jumping-number.js
ganorberg/algorithms-javascript
305023441cbadc99f7cf09b35fe60383cda7fdd9
[ "MIT" ]
null
null
null
/* Determine if a number x is a Jumping Number. A number is called a Jumping * Number if all adjacent digits in it differ by 1. The difference between ‘9’ * and ‘0’ is not considered to be 1. All single digit numbers are considered * Jumping Numbers. * * For example 7, 8987 and 4343456 are Jumping numbers but 796 and 89098 are not. * * ASSUMPTIONS: * - safe positive integers only * - input is in number format, not string */ function isJumpingNumber(x) { const numStr = String(x); // Store first value so loop can start at 1 and does not need i === 0 check let checkJump = Number(numStr[0]); for (let i = 1; i < numStr.length; i++) { const digit = Number(numStr[i]); // Keep looping if jumping assertion is true and remember last digit for check if (checkJump === digit + 1 || checkJump === digit - 1) { checkJump = digit; } else { return false; } } return true; } console.log(true, isJumpingNumber(7)); console.log(true, isJumpingNumber(8987)); console.log(true, isJumpingNumber(4343456)); console.log(false, isJumpingNumber(796)); console.log(false, isJumpingNumber(89098));
30.945946
82
0.682969
01140ad9430997e9fc841a60b30bf508976c1702
441
js
JavaScript
js-test-suite/testsuite/bf9747cd432b224ccd84a9af8b5728ee.js
hao-wang/Montage
d1c98ec7dbe20d0449f0d02694930cf1f69a5cea
[ "MIT" ]
16
2020-03-23T12:53:10.000Z
2021-10-11T02:31:50.000Z
js-test-suite/testsuite/bf9747cd432b224ccd84a9af8b5728ee.js
hao-wang/Montage
d1c98ec7dbe20d0449f0d02694930cf1f69a5cea
[ "MIT" ]
null
null
null
js-test-suite/testsuite/bf9747cd432b224ccd84a9af8b5728ee.js
hao-wang/Montage
d1c98ec7dbe20d0449f0d02694930cf1f69a5cea
[ "MIT" ]
1
2020-08-17T14:06:59.000Z
2020-08-17T14:06:59.000Z
function shouldBe(actual, expected) { if (actual !== expected) throw new Error('bad value: ' + actual); } var builtin = createBuiltin(`(function (a) { a = 42; return @argument(0); })`); noInline(builtin); (function () { for (var i = 0; i < 1e4; ++i) { shouldBe(builtin(), undefined); shouldBe(builtin(1), 42); shouldBe(builtin(1, 2), 42); shouldBe(builtin(1, 2, 3), 42); } }());
22.05
48
0.544218
010de77636236dcf766554cf916b2a92066e478e
4,371
js
JavaScript
app/vendors/tooltipList.js
ortance/Front_visualisationEV
87ffebba0fe5ae77604c0782dafee66d40cc9eb8
[ "MIT" ]
15
2015-02-15T18:02:54.000Z
2021-10-31T00:08:41.000Z
app/vendors/tooltipList.js
ortance/Front_visualisationEV
87ffebba0fe5ae77604c0782dafee66d40cc9eb8
[ "MIT" ]
505
2015-03-24T15:16:55.000Z
2022-03-21T22:17:11.000Z
app/vendors/tooltipList.js
ortance/Front_visualisationEV
87ffebba0fe5ae77604c0782dafee66d40cc9eb8
[ "MIT" ]
31
2015-04-09T10:48:31.000Z
2020-12-08T16:32:30.000Z
(function ( $ ) { $.fn.tooltipList = function(options) { // ----------------------------------------------- // Settings // this.settings = $.extend({ // Default position : top position : 'top', // Default animation : fade animation: 'fade', // By default when we click out of tooltip, it close itself automaticly autoClose: true, // Allow to add a class to the tooltipster element tooltipClass : 'tooltipList', // We create a default option with negative value availableOptions : [{ label : 'default option', val : -1 }], // Callbacks // We set an useless default li click event callback liClickEvent : function(liValue, origin, tooltip) { console.log ("Li clicked, value : ", liValue); } }, options); // ----------------------------------------------- // Bind li click event and run specified callback // this.bindLiClick = function() { this.tooltip.find('li').bind('click', $.proxy(function(e) { // Run specified callback this.settings.liClickEvent($(e.target).data('value'), this.origin, this.tooltip); }, this)); }; // ----------------------------------------------- // Update List function when input value changed // this.updateLiList = function(inputValue, origin, tooltip) { // When input text value change (we used keyup because we change the list in real time) // We change list options // First we clear the last list tooltip.find('ul').html(''); $.map(this.settings.availableOptions, $.proxy(function(val, index) { if (val.label.indexOf( inputValue ) >= 0) { // Append element on the list tooltip.find('ul').append('<li data-value="' + val.val + '" >' + val.label + '</li>'); } }, this)); this.bindLiClick(); }; // ----------------------------------------------- // Tooltip HYML element // this.tooltipHTMLContent = $.proxy(function() { var html = ''; $.map(this.settings.availableOptions, $.proxy(function(val, index) { html += '<li data-value="' + val.val + '" >' + val.label + '</li>'; }, this)); return $('\ <div class="">\ <input type="text" />\ <i class="reneco search"></i>\ <ul>' + html + '</ul>\ </div>\ ') }, this); // ----------------------------------------------- // Create tooltip with tooltipster library // $(this).tooltipster({ // Plugin HTML content content: this.tooltipHTMLContent , // animation animation : this.settings.animation, // position position : this.settings.position, // autoclose options autoClose : this.settings.autoClose, // Allow HTML content contentAsHTML: true, // Allow interative tooltip (for search functionnality) interactive: true, // Add class theme: 'tooltipster-default ' + this.settings.tooltipClass, // Callbacks functionReady : $.proxy(function(origin, tooltip) { this.origin = origin; this.tooltip = tooltip; $(tooltip).find('input').bind('keyup', $.proxy(function(e) { this.updateLiList( $(e.target).val(), origin, tooltip ); }, this)); this.updateLiList("", origin, tooltip); }, this), functionAfter: function (origin, tooltip) { // When the mouse move out of the tooltip we destroy otherwise the tooltip is trigger when we hover the button $(origin).tooltipster('destroy'); } }); // Show tooltipster $(this).tooltipster('show'); }; }( jQuery ));
34.968
126
0.453443
bbe8785ab50398307ed05cf086d146913adc7a92
1,983
js
JavaScript
backend/controller/index.js
sanand34/File-Share-and-Messaging-Application
166b8117ecaa2f81ef77d806ae84b843626d36dd
[ "MIT" ]
5
2021-06-10T07:25:45.000Z
2022-01-05T18:43:09.000Z
backend/controller/index.js
sanand34/file-share-and-messaging-application
166b8117ecaa2f81ef77d806ae84b843626d36dd
[ "MIT" ]
null
null
null
backend/controller/index.js
sanand34/file-share-and-messaging-application
166b8117ecaa2f81ef77d806ae84b843626d36dd
[ "MIT" ]
null
null
null
import pusher from "./pusher.js"; import uploadFile from "./middleware/upload.js"; import fs from "fs"; const port = process.env.PORT || 8000; const baseUrl = `${port}/files/`; const upload = async (req, res) => { try { await uploadFile(req, res); if (req.file == undefined) { return res.status(400).send({ message: "Please upload a file!" }); } res.status(200).send({ message: "Uploaded the file successfully: " + req.file.originalname, }); } catch (err) { console.log(err); if (err.code == "LIMIT_FILE_SIZE") { return res.status(500).send({ message: "File size cannot be larger than 10MB!", }); } res.status(500).send({ message: `Could not upload the file: ${req.file.originalname}. ${err}`, }); } }; const getListFiles = (req, res) => { const directoryPath = __basedir + "/uploads/"; fs.readdir(directoryPath, function (err, files) { if (err) { res.status(500).send({ message: "Unable to scan files!", }); } let fileInfos = []; files.map((file) => { fileInfos.push({ name: file, url: baseUrl + file, }); }); res.status(200).send(fileInfos); }); }; const download = (req, res) => { const fileName = req.params.name; const directoryPath = __basedir + "/uploads/"; res.download(directoryPath + fileName, fileName, (err) => { if (err) { res.status(500).send({ message: "Could not download the file. " + err, }); } }); }; let message = (req, res) => { pusher.trigger("messages", req.params.room, { name: req.body.name, message: req.body.message, date: req.body.date, }); }; let fileshare = (req, res) => { pusher.trigger("fileshare", req.params.room, { name: req.body.name, }); }; const welcome = (req, res) => { res.send("Welcome,backend is developed by Sanchit Anand"); }; export { message, upload, getListFiles, download, welcome, fileshare };
23.05814
77
0.585477
bbed27a13c046dff22741aed54366934efd94d83
1,132
js
JavaScript
src/routes/Mocks/model/index.js
LANIF-UI/dva-boot-desktop
aecba458696e1cd990b37329b56cb500a11b5cc3
[ "MIT" ]
21
2018-11-23T15:46:28.000Z
2022-01-10T06:35:24.000Z
src/routes/Mocks/model/index.js
LANIF-UI/dva-boot-desktop
aecba458696e1cd990b37329b56cb500a11b5cc3
[ "MIT" ]
null
null
null
src/routes/Mocks/model/index.js
LANIF-UI/dva-boot-desktop
aecba458696e1cd990b37329b56cb500a11b5cc3
[ "MIT" ]
11
2019-02-19T06:03:13.000Z
2020-11-28T06:42:54.000Z
import $$ from 'cmn-utils'; import { join } from 'path'; import { readFileSync, existsSync, removeSync, writeFileSync } from 'fs-extra'; import { routerRedux } from 'dva/router'; import * as acorn from 'acorn'; import jsx from 'acorn-jsx'; import * as walk from 'acorn-walk'; import { message } from 'antd'; import escodegen from 'escodegen'; let comments = []; let tokens = []; export default { namespace: 'mocks', state: { columnsData: [] }, subscriptions: { setup({ history, dispatch }) { return history.listen(({ pathname }) => { const link = $$.getQueryValue('link'); if (pathname.indexOf('/route') !== -1 && link) { comments = []; // 清空 tokens = []; // 清空 dispatch({ type: 'parseRoute', payload: { link } }); } }); } }, effects: { // 从指定mock里分析出columns *parseMock({ payload }, { call, put, select }) { const { name } = payload; const global = yield select(state => state.global); const { currentProject } = global; } }, reducers: {} };
22.64
79
0.541519
bbf98df17b38d6ae6fa554d8e706f743ca7bd38d
762
js
JavaScript
src/library/connect-to-redis/index.js
mkralla11/safe-redis-leader
34b46e2fdb9b8ae7d832ae71af6a127d27f8daa1
[ "MIT" ]
3
2021-05-05T23:25:14.000Z
2022-01-18T20:58:20.000Z
src/library/connect-to-redis/index.js
mkralla11/safe-redis-leader
34b46e2fdb9b8ae7d832ae71af6a127d27f8daa1
[ "MIT" ]
null
null
null
src/library/connect-to-redis/index.js
mkralla11/safe-redis-leader
34b46e2fdb9b8ae7d832ae71af6a127d27f8daa1
[ "MIT" ]
1
2021-07-14T23:49:55.000Z
2021-07-14T23:49:55.000Z
// const redis = require('redis') const Redis = require("ioredis") // const RedisClustr = require('redis-clustr') const {promisify} = require('util') // const { // execMultiAsync // } = require('../../utils') module.exports = async function connectToRedis({redisCreds, promisifyFnNames=[]}){ let { host, port, password } = redisCreds // debugger // console.log(redisCreds) port = port || 6379 let asyncRedis = new Redis({ host, port, password, // Not the best solution, but we know // that Redis Elasticasche on AWS // has a weird tls related issue, // so just set this to true solves it // (not an issue when local) tls: /amazonaws\.com$/.test(host) ? true : undefined }) return asyncRedis }
23.090909
82
0.633858
bbedba2a2b10c25b363098ef4eae1a40677da9ef
173
js
JavaScript
public/config.js
HackMIT/playground-frontend
2366519cc3a57eb09cef2937af3ca32f08da8bd9
[ "MIT" ]
4
2020-09-19T18:55:27.000Z
2022-01-31T11:08:06.000Z
public/config.js
HackMIT/playground-frontend
2366519cc3a57eb09cef2937af3ca32f08da8bd9
[ "MIT" ]
3
2022-01-27T16:13:16.000Z
2022-02-27T10:08:12.000Z
public/config.js
HackMIT/playground-frontend
2366519cc3a57eb09cef2937af3ca32f08da8bd9
[ "MIT" ]
1
2021-08-08T22:36:51.000Z
2021-08-08T22:36:51.000Z
window.GoogleSamples = window.GoogleSamples || {}; window.GoogleSamples.Config = window.GoogleSamples.Config || { gcmAPIKey: 'AIzaSyDpBC2jRkt6LkywhzfIKzAHFXEA6PkKjoU', };
34.6
62
0.786127
bbedfada40b1221ecc72d9fbcc97730bfc3592fe
1,821
js
JavaScript
app/app.js
maniacs-m/NortalTechDay
3c3edb7d280197572a31843da1ab00ca6957a42f
[ "MIT" ]
267
2015-04-20T05:27:42.000Z
2022-02-14T15:33:43.000Z
app/app.js
maniacs-m/NortalTechDay
3c3edb7d280197572a31843da1ab00ca6957a42f
[ "MIT" ]
3
2015-04-29T05:00:08.000Z
2017-06-07T09:20:24.000Z
app/app.js
maniacs-m/NortalTechDay
3c3edb7d280197572a31843da1ab00ca6957a42f
[ "MIT" ]
51
2015-04-20T07:18:53.000Z
2022-02-14T15:33:48.000Z
/* * Nortal TechDay React Native App * Mikko Junnila * @mikkoj * http://github.com/mikkoj/NortalTechDay */ 'use strict'; var React = require('react-native') var { AppRegistry, StyleSheet, NavigatorIOS, Text, View, ScrollView } = React var Icon = require('FAKIconImage') var SMXTabBarIOS = require('SMXTabBarIOS') var SMXTabBarItemIOS = SMXTabBarIOS.Item var InitialTab = "schedule"; var Tabs = [ { name: "schedule", iconName: "fontawesome|calendar", iconSize: 26, content: require('./components/TracksView') }, { name: "info", iconName: "foundation|info", iconSize: 30, content: require('./components/InfoView') }, { name: "rooms", iconName: "ion|ios-navigate", iconSize: 29, content: require('./components/RoomsView') }, { name: "social", iconName: "ion|chatboxes", iconSize: 30, content: require('./components/SocialView') } ] var NortalTechDay = React.createClass({ getInitialState: function() { return { selectedTab: InitialTab, } }, renderTab: function(tab) { var TabContent = tab.content return ( <SMXTabBarItemIOS name={tab.name} iconName={tab.iconName} title={''} iconSize={tab.iconSize} selected={this.state.selectedTab === tab.name} onPress={() => { this.setState({ selectedTab: tab.name, }); }}> <TabContent /> </SMXTabBarItemIOS> ) }, render: function() { var self = this; return ( <SMXTabBarIOS selectedTab={self.state.selectedTab} tintColor={'green'} barTintColor={'#fff'}> {Tabs.map(this.renderTab)} </SMXTabBarIOS> ) }, }) module.exports = NortalTechDay
18.773196
56
0.58045
0114d8a94859a8b7b30bb683adbd7ac2a507e196
2,625
js
JavaScript
src/components/organisms/FullScreenCertificate/_components.fullscreen-certificate-css.js
ICE-Institute/blockcerts-verifier
ea83e1dfcc7748d172203bd55fbaa61b371cda72
[ "MIT" ]
46
2018-09-11T16:32:05.000Z
2022-02-27T16:20:25.000Z
src/components/organisms/FullScreenCertificate/_components.fullscreen-certificate-css.js
ICE-Institute/blockcerts-verifier
ea83e1dfcc7748d172203bd55fbaa61b371cda72
[ "MIT" ]
1,219
2018-09-11T16:46:09.000Z
2022-03-31T15:21:30.000Z
src/components/organisms/FullScreenCertificate/_components.fullscreen-certificate-css.js
ICE-Institute/blockcerts-verifier
ea83e1dfcc7748d172203bd55fbaa61b371cda72
[ "MIT" ]
48
2018-11-20T01:21:26.000Z
2022-01-14T07:11:45.000Z
import {html} from '@polymer/lit-element'; export default html`<style>.buv-o-text-11{font-size:11px}.buv-o-text-12{font-size:12px}.buv-o-text-13{font-size:13px}.buv-o-text-15{font-size:15px;line-height:20px}.buv-c-certificate--fixed-width{max-width:460px;min-width:0;margin:0 auto}.buv-c-fullscreen-certificate{z-index:200;position:fixed;top:0;left:0;background-color:#fff;width:100vw;height:100vh;overflow:auto;box-sizing:border-box}@media only screen and (max-width: 750px){.buv-c-fullscreen-certificate{padding-top:170px}}.buv-c-fullscreen-certificate-header{box-shadow:0 1px 5px rgba(0,0,0,0.15);width:100%;background-color:#fff}@media only screen and (max-width: 750px){.buv-c-fullscreen-certificate-header{position:fixed;top:0;z-index:10}}.buv-c-fullscreen-certificate-header__content{max-width:1440px;margin:0 auto;padding:20px;display:flex;align-items:center;position:relative;box-sizing:border-box}@media only screen and (max-width: 750px){.buv-c-fullscreen-certificate-header__content{flex-direction:column;justify-content:left;align-items:unset}}.buv-c-fullscreen-certificate__title{margin:0 30px 0 0}@media only screen and (max-width: 750px){.buv-c-fullscreen-certificate__title{margin-bottom:10px}}.buv-c-fullscreen-certificate__close{right:20px}.buv-c-fullscreen-certificate__content{padding:20px;display:flex;max-width:1440px;margin:20px auto 0}@media only screen and (max-width: 750px){.buv-c-fullscreen-certificate__content{flex-direction:column-reverse;margin-top:0}}.buv-c-fullscreen-certificate__details{display:flex;flex-grow:1;flex-direction:column;max-width:280px;min-width:220px;margin-right:20px}@media only screen and (max-width: 750px){.buv-c-fullscreen-certificate__details{max-width:100vw;margin:20px 0 0}}.buv-c-fullscreen-certificate__verification-status{margin-bottom:15px}@media only screen and (max-width: 750px){.buv-c-fullscreen-certificate__verification-status{position:absolute;top:90px;width:calc(100% - 40px);margin:0}}.buv-c-fullscreen-certificate__details-item{margin-top:5px}.buv-c-fullscreen-certificate__separator{margin-top:30px;padding-top:30px;border-top:1px solid #f1f2f3}.buv-c-fullscreen-certificate__certificate{box-shadow:0 1px 5px rgba(0,0,0,0.15);padding:20px;background-color:#fff;font-family:serif;text-align:center;color:#49555f;font-size:12px;word-wrap:break-word;min-height:calc(100vh - 145px);box-sizing:border-box;margin:0 auto;min-width:600px;line-height:initial}@media only screen and (max-width: 750px){.buv-c-fullscreen-certificate__certificate{min-width:unset;width:100%;overflow:auto}}.buv-c-fullscreen-certificate__verify-other{margin-top:20px} </style>`;
656.25
2,570
0.806095
0116d7550669b720ea8457ab46556fa25177ef18
2,932
js
JavaScript
index.js
rjt-rockx/pdfgrid
eb1c124cf3c27257216992402dc08804b0fd719e
[ "MIT" ]
1
2022-03-12T14:06:43.000Z
2022-03-12T14:06:43.000Z
index.js
rjt-rockx/pdfgrid
eb1c124cf3c27257216992402dc08804b0fd719e
[ "MIT" ]
null
null
null
index.js
rjt-rockx/pdfgrid
eb1c124cf3c27257216992402dc08804b0fd719e
[ "MIT" ]
null
null
null
const PDFDocument = require("pdfkit"); const format = { start: { x: 24.945, y: 235.275 }, maxWidth: 11, maxHeight: 10 }; const drawPixels = (pixelCount, gridsToGenerate = 1, verticalSymmetry = () => true, horizontalSymmetry = () => false) => { for (let gridCount = 0; gridCount < gridsToGenerate; gridCount++) { let grid = new PDFDocument({ autoFirstPage: false }); grid.pipe(require("fs").createWriteStream(`./${pixelCount}/grid_${gridCount + 1}.pdf`)); grid.addPage({ layout: "portrait", size: "A3" }); grid.rect(format.start.x, format.start.y, format.maxWidth * 72, format.maxHeight * 72).stroke('#000'); const drawPixel = (x, y) => grid.rect(format.start.x + (x * 72), format.start.y + (y * 72), 72, 72).fill('#000'); const randomCoords = () => Math.floor(Math.random() * format.maxWidth) + "/" + Math.floor(Math.random() * format.maxHeight); let generatedCoords = [], previousCoords; let coords = Array(pixelCount).fill(0).map(_ => { let randomC, nextIsRandom = false; while (generatedCoords.includes(randomC) || !randomC) { const symmetries = { vertical: verticalSymmetry(), horizontal: horizontalSymmetry() }; let randomSymmetry = symmetries.vertical === true && symmetries.horizontal === true; randomSymmetry = randomSymmetry ? Math.random() > 0.5 : false; if (randomSymmetry) { if (symmetries.horizontal && previousCoords && !nextIsRandom) { let c = previousCoords.split("/").map(x => Number(x)); c[0] = format.maxWidth - c[0] - 1; randomC = c.join("/"); nextIsRandom = true; continue; } if (symmetries.vertical && previousCoords && !nextIsRandom) { let c = previousCoords.split("/").map(x => Number(x)); c[1] = format.maxHeight - c[1] - 1; randomC = c.join("/"); nextIsRandom = true; continue; } } else if (!randomSymmetry) { if (symmetries.vertical && previousCoords && !nextIsRandom) { let c = previousCoords.split("/").map(x => Number(x)); c[1] = format.maxHeight - c[1] - 1; randomC = c.join("/"); nextIsRandom = true; continue; } if (symmetries.horizontal && previousCoords && !nextIsRandom) { let c = previousCoords.split("/").map(x => Number(x)); c[0] = format.maxWidth - c[0] - 1; randomC = c.join("/"); nextIsRandom = true; continue; } } if (!previousCoords || nextIsRandom) { randomC = randomCoords(); nextIsRandom = false; continue; } console.log(`PreviousCoords: ${previousCoords}, Symmetries: ${JSON.stringify(symmetries)}, RandomCoords: ${randomC}`); console.log(`generatedCoords: ${JSON.stringify(generatedCoords)}`); } generatedCoords.push(randomC); previousCoords = randomC; return randomC.split("/").map(x => Number(x)); }); for (const [x, y] of coords) drawPixel(x, y); grid.end(); } }; drawPixels(10, 5, () => true, () => true);
40.722222
126
0.615962
bbe81e0cb6050eb739f3b6df945d2d453cd211ae
3,138
js
JavaScript
server/router/users/usersRouter.js
fixmylife-boilerplates/next-node-api
70cc88a1da534e6274b046d2862e260e663367b0
[ "MIT" ]
4
2019-08-29T12:00:00.000Z
2022-03-16T02:26:28.000Z
server/router/users/usersRouter.js
fixmylife-boilerplates/next-node-api
70cc88a1da534e6274b046d2862e260e663367b0
[ "MIT" ]
5
2021-03-09T16:31:40.000Z
2021-12-09T01:08:34.000Z
router/users/usersRouter.js
cammac725/boilerplate-node-api
5b168b60028cfbfc598738f2fb36bdc67cdf1f7b
[ "MIT" ]
5
2019-08-29T16:27:32.000Z
2022-03-16T02:26:45.000Z
const router = require("express").Router(); const Users = require("./usersModel"); const Posts = require("../posts/postsModel"); const restricted = require("../auth/middleware/restrictedMiddleware"); const { verifyUserExist } = require("./middleware"); router.get("/all", (req, res) => { Users.getUsers() .then(users => { res.status(200).json(users); }) .catch(err => { res .status(500) .json({ err, message: "Cannot retrieve users from database." }); }); }); router.get("/", restricted, (req, res) => { Users.findById(req.decodedToken.id) .then(user => { Posts.getUserPosts(req.decodedToken.id) .where({ user_id: req.decodedToken.id }) .then(posts => { if (!posts) { user.posts = []; return res.status(200).json(user); } else { user.posts = posts; return res.status(200).json(user); } }) .catch(err => { res.status(200).json(err); }); }) .catch(err => { res .status(500) .json({ err, message: "we ran into an error retreving the user" }); }); }); router.get("/:id", verifyUserExist, (req, res) => { Users.findById(req.params.id) .then(user => { Posts.getUserPosts(req.params.id) .where({ user_id: req.params.id }) .then(posts => { if (!posts) { user.posts = []; return res.status(200).json(user); } else { user.posts = posts; return res.status(200).json(user); } }) .catch(err => { res.status(200).json(user); }); }) .catch(err => { res .status(500) .json({ err, message: "we ran into an error retreving the user" }); }); }); router.put("/:id", restricted, (req, res) => { const id = req.params.id; const changes = req.body; Users.update(id, changes) .then(update => { res.status(200).json(update); }) .catch(error => { res.status(500).json({ errorMessage: error }); }); }); router.delete("/:id", restricted, (req, res) => { const user = req.decodedToken; if (req.decodedToken.id == req.params.id) { Users.remove(req.params.id) .then(del => { res .status(200) .json({ user, message: `User:${user.username} was successfully deleted` }) .end(del); }) .catch(err => { res.status(500).json({ err, message: "error, unable to delete user" }); }); } else { res.status(400).json({ user, message: "you are not able to delete another users account" }); } }); router.delete("/", restricted, (req, res) => { Users.remove(req.decodedToken.id) .then(del => { res .status(200) .json({ message: `User was successfully deleted` }) .end(del); }) .catch(err => { res.status(500).json({ err, message: "error, unable to delete user" }); }); }); module.exports = router;
24.904762
79
0.50733
010335e3c62d834fa652d11a616108d6f92796d4
1,452
js
JavaScript
components/Blog/Sidebar/PostWidget.js
High-Stepper/oiron-starter
948df662eb129f583eb8df34f33c7119abf7da6f
[ "MIT" ]
7
2022-01-02T00:44:23.000Z
2022-03-25T18:13:54.000Z
components/Blog/Sidebar/PostWidget.js
High-Stepper/oiron-starter
948df662eb129f583eb8df34f33c7119abf7da6f
[ "MIT" ]
null
null
null
components/Blog/Sidebar/PostWidget.js
High-Stepper/oiron-starter
948df662eb129f583eb8df34f33c7119abf7da6f
[ "MIT" ]
4
2021-11-24T10:49:58.000Z
2022-01-17T11:27:54.000Z
import React from 'react'; import PropTypes from 'prop-types'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import { withTranslation } from '~/i18n'; import Paper from '../../Paper'; import useStyles from '../blog-style'; function PostWidget(props) { const classes = useStyles(); const { t } = props; const news = [{ title: 'Vestibulum bibendum nisi eget magna', date: 'Jan 9, 2014' }, { title: 'Quisque a consequat ante', date: 'Jan 9, 2014' }, { title: 'Donec dignissim, odio ac imperdiet luctus', date: 'Jan 9, 2014' }, { title: 'Suspendisse eleifend nunc non', date: 'Jan 9, 2014' }, { title: 'Vestibulum a massa vestibulum', date: 'Jan 9, 2014' }]; return ( <Paper title={t('common:blog_post')} icon="ion-android-bookmark" whiteBg desc=""> <div className={classes.albumRoot}> <List component="nav"> {news.map((item, index) => ( <ListItem key={index.toString()} button> <ListItemText primary={item.title} secondary={item.date} /> </ListItem> ))} </List> </div> </Paper> ); } PostWidget.propTypes = { t: PropTypes.func.isRequired, }; PostWidget.getInitialProps = async () => ({ namespacesRequired: ['common'], }); export default withTranslation(['common'])(PostWidget);
25.034483
85
0.615702
01100f506853fa71b2e7c648ccb85293a3c38a2c
182
js
JavaScript
src/templates/underscore.js
lagersmit/json-editor
7581f7a597af02a5db77e358df41f3a63771401c
[ "MIT" ]
3,102
2017-12-05T15:19:47.000Z
2022-03-31T09:23:21.000Z
src/templates/underscore.js
lagersmit/json-editor
7581f7a597af02a5db77e358df41f3a63771401c
[ "MIT" ]
965
2017-12-21T14:20:19.000Z
2022-03-30T11:13:41.000Z
src/templates/underscore.js
lagersmit/json-editor
7581f7a597af02a5db77e358df41f3a63771401c
[ "MIT" ]
633
2017-12-19T23:14:44.000Z
2022-03-29T07:37:54.000Z
export const underscoreTemplate = () => { if (!window._) return false return { compile (template) { return context => window._.template(template)(context) } } }
18.2
60
0.620879