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
b1ffa24af7e576f3d018f2ff9827efe511286902
697
js
JavaScript
src/components/SearchButton.js
fakundo/tarkov-raid-items
b83f6a6bfaa3267a8afea579a347a44b9a967731
[ "MIT" ]
5
2021-02-19T20:40:08.000Z
2022-02-24T01:20:18.000Z
src/components/SearchButton.js
fakundo/tarkov-raid-items
b83f6a6bfaa3267a8afea579a347a44b9a967731
[ "MIT" ]
null
null
null
src/components/SearchButton.js
fakundo/tarkov-raid-items
b83f6a6bfaa3267a8afea579a347a44b9a967731
[ "MIT" ]
1
2021-07-12T17:56:19.000Z
2021-07-12T17:56:19.000Z
import React, { useEffect } from 'react' import { useSearch } from 'hooks' import Button from 'components/Button' import { SearchIcon } from 'components/Icons' export default (props) => { const { openSearchBox } = useSearch() useEffect(() => { const handler = (ev) => { if (ev.key === 'f' && (ev.metaKey || ev.ctrlKey)) { ev.preventDefault() window.scrollTo(0, 0) openSearchBox() } } document.addEventListener('keydown', handler, true) return () => { document.removeEventListener('keydown', handler, true) } }, []) return ( <Button {...props} icon={<SearchIcon />} onClick={openSearchBox} /> ) }
22.483871
60
0.578192
b17c720b8aee4b5d31e45932859651b49387d91e
99
js
JavaScript
code_documentation/dg_tools/documentation/search/namespaces_0.js
machines-in-motion/machines-in-motion.github.io
6deb8c3ade0b30893843084da6813789c63d9b43
[ "BSD-3-Clause" ]
1
2021-02-18T21:10:53.000Z
2021-02-18T21:10:53.000Z
code_documentation/dg_tools/documentation/search/namespaces_0.js
machines-in-motion/machines-in-motion.github.io
6deb8c3ade0b30893843084da6813789c63d9b43
[ "BSD-3-Clause" ]
4
2020-05-04T08:34:07.000Z
2021-03-24T11:22:45.000Z
code_documentation/dg_tools/documentation/search/namespaces_0.js
machines-in-motion/machines-in-motion.github.io
6deb8c3ade0b30893843084da6813789c63d9b43
[ "BSD-3-Clause" ]
1
2021-02-18T21:10:54.000Z
2021-02-18T21:10:54.000Z
var searchData= [ ['py_5fdg_5ftools',['py_dg_tools',['../namespacepy__dg__tools.html',1,'']]] ];
19.8
77
0.666667
b17c7faf9a2dcb5d186093d20197e9bb1ef4c000
209
js
JavaScript
src/pages/index.js
minimalsm/westry-teampage
8ce1fd800ab977de305b6d1648b74b8ed551be06
[ "RSA-MD" ]
null
null
null
src/pages/index.js
minimalsm/westry-teampage
8ce1fd800ab977de305b6d1648b74b8ed551be06
[ "RSA-MD" ]
null
null
null
src/pages/index.js
minimalsm/westry-teampage
8ce1fd800ab977de305b6d1648b74b8ed551be06
[ "RSA-MD" ]
null
null
null
import React from "react" import { Nav } from "../components/Nav" import { Team } from "../components/Team" export default function Home() { return <div className='py4'> <Nav /> <Team /> </div> }
19
41
0.62201
b17eb991935b31dc65a96fc805a3d8515723ec37
270
js
JavaScript
packages/helpers-fn/src/log/_modules/separator.js
selfrefactor/commit-message
bede9e310d9bbd9468d6992bcfbe3910fa110f1f
[ "MIT" ]
23
2017-11-25T07:27:59.000Z
2019-06-13T15:08:08.000Z
packages/helpers-fn/src/log/_modules/separator.js
selfrefactor/commit-message
bede9e310d9bbd9468d6992bcfbe3910fa110f1f
[ "MIT" ]
14
2017-11-25T22:28:19.000Z
2018-03-27T17:03:20.000Z
packages/helpers-fn/src/log/_modules/separator.js
selfrefactor/commit-message
bede9e310d9bbd9468d6992bcfbe3910fa110f1f
[ "MIT" ]
1
2018-09-27T06:57:44.000Z
2018-09-27T06:57:44.000Z
const gradient = require('gradient-string') const R = require('rambdax') function separator(mode){ const char = mode.endsWith('x') ? '🀰' : '_' const longLine = R.join('', R.repeat(char, 55)) console.log(gradient.mind(longLine)) } exports.separator = separator
20.769231
49
0.681481
b17f06e1c31cd37e4511e476924c36b8a81617d2
2,483
js
JavaScript
index.js
uber-workflow/probot-app-pr-issue
47b2e70a66adecf879561ec2e88af19096b1a0fc
[ "MIT" ]
2
2018-12-09T03:40:34.000Z
2019-02-06T15:05:50.000Z
index.js
uber-workflow/probot-app-pr-issue
47b2e70a66adecf879561ec2e88af19096b1a0fc
[ "MIT" ]
59
2018-01-10T23:09:56.000Z
2019-02-20T23:40:37.000Z
index.js
uber-workflow/probot-app-pr-issue
47b2e70a66adecf879561ec2e88af19096b1a0fc
[ "MIT" ]
3
2018-01-22T20:46:07.000Z
2018-02-13T22:50:19.000Z
/** Copyright (c) 2017 Uber Technologies, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const issueRegex = require('issue-regex'); module.exports = robot => { robot.on('pull_request.opened', check); robot.on('pull_request.edited', check); robot.on('pull_request.labeled', check); robot.on('pull_request.unlabeled', check); robot.on('pull_request.synchronize', check); async function check(context) { const {github} = context; const pr = context.payload.pull_request; setStatus({ state: 'pending', description: 'Checking if PR correctly references an issue', }); const config = await context.config('pr-issue.yml', { ignore: ['release', 'docs'], }); const labels = await github.issues.getIssueLabels(context.issue()); let shouldIgnore = false; // PRs with whitelisted labels don't need to reference an issue shouldIgnore = shouldIgnore || labels.data.some(label => { let name = label.name.toLowerCase(); return config.ignore.some(ignored => ignored === name); }); // Bots don't need to reference an issue shouldIgnore = shouldIgnore || pr.user.type === 'Bot'; if (shouldIgnore) { setStatus({ state: 'success', description: 'PR does not need to reference an issue', }); return; } function hasIssue() { const issues = matchMaybe(pr.body, issueRegex()); if (issues !== null) { return true; } const repo = context.payload.repository.full_name; const urlRegex = new RegExp(`${repo}/issues/\\d+`, 'g'); return matchMaybe(pr.body, urlRegex) !== null; } const status = hasIssue() ? { state: 'success', description: 'PR references an issue', } : { state: 'failure', description: 'PR does not reference an issue', }; setStatus(status); function setStatus(status) { const params = Object.assign( { sha: pr.head.sha, context: 'probot/pr-issue', }, status, ); return github.repos.createStatus(context.repo(params)); } } }; function matchMaybe(maybeString, pattern) { return typeof maybeString === 'string' ? maybeString.match(pattern) : null; }
27.588889
78
0.586387
b17f4d1c0200d8c5b68ae805cdf637d7c63ce6df
1,482
js
JavaScript
gannt/lib/Scheduler/view/DependencyEditor.js
ww362034710/Gannt
ab9d4fd08c55a16fbf4c40798f9da71441ef1c8f
[ "MIT" ]
null
null
null
gannt/lib/Scheduler/view/DependencyEditor.js
ww362034710/Gannt
ab9d4fd08c55a16fbf4c40798f9da71441ef1c8f
[ "MIT" ]
null
null
null
gannt/lib/Scheduler/view/DependencyEditor.js
ww362034710/Gannt
ab9d4fd08c55a16fbf4c40798f9da71441ef1c8f
[ "MIT" ]
1
2021-11-18T05:47:04.000Z
2021-11-18T05:47:04.000Z
import Popup from '../../Core/widget/Popup.js'; /** * @module Scheduler/view/DependencyEditor */ /** * A dependency editor popup. * * @extends Core/widget/Popup * @private */ export default class DependencyEditor extends Popup { static get $name() { return 'DependencyEditor'; } static get defaultConfig() { return { items : [], draggable : { handleSelector : ':not(button,.b-field-inner)' // blacklist buttons and field inners }, axisLock : 'flexible' }; } processWidgetConfig(widget) { const dependencyEditFeature = this.dependencyEditFeature; let fieldConfig = {}; if (widget.ref === 'lagField' && !dependencyEditFeature.showLagField) { return false; } if (widget.ref === 'deleteButton' && !dependencyEditFeature.showDeleteButton) { return false; } Object.assign(widget, fieldConfig); return super.processWidgetConfig(widget); } afterShow(...args) { const deleteButton = this.widgetMap.deleteButton; // Only show delete button if the dependency record belongs to a store if (deleteButton) { deleteButton.hidden = !this.record.isPartOfStore(); } super.afterShow(...args); } onInternalKeyDown(event) { this.trigger('keyDown', { event }); super.onInternalKeyDown(event); } }
24.295082
100
0.584345
b1805f4aa2270326328d03ef6507fbf0159314d7
1,692
js
JavaScript
index.js
noffle/ipfs-hyperlog
3b87a7c22e49257221dc5257a532d457cc4467e7
[ "MIT" ]
60
2016-02-12T00:59:08.000Z
2020-07-28T14:41:49.000Z
index.js
hackergrrl/ipfs-hyperlog
3b87a7c22e49257221dc5257a532d457cc4467e7
[ "MIT" ]
1
2017-12-05T20:25:49.000Z
2017-12-05T20:25:49.000Z
index.js
hackergrrl/ipfs-hyperlog
3b87a7c22e49257221dc5257a532d457cc4467e7
[ "MIT" ]
6
2016-02-29T18:49:18.000Z
2020-07-28T14:41:52.000Z
var async = require('async') var hyperlog = require('hyperlog') var merkledag = require('ipfs-dag') var defined = require('defined') module.exports = function (db, opts) { opts = defined(opts, { hashFunction: undefined, asyncHashFunction: hash }) // The inner hyperlog object. var log = hyperlog(db, opts) // Hash an opaque value blob and a list of links to an IPFS multihash. function hash (links, value, cb) { convertToMerkleDagNode(value, links, doneConversion) function doneConversion (err, dagNode) { if (err) return cb(err) cb(null, dagNode.multihash) } } function keyToMerkleDagNode (key, cb) { // Look up the node by its key and convert it recursively. log.get(key, function (err, node) { if (err) return cb(err) convertToMerkleDagNode(node.value, node.links, cb) }) } // Take an opaque value and list of links and conver them into an IPFS Merkle // DAG node (recursively). function convertToMerkleDagNode (value, links, cb) { // Base class: no links. if (!links || links.length <= 0) { var dagNode = new merkledag.Node(value) process.nextTick(function () { cb(null, dagNode) }) return } // Retrieve each key as a hyperlog node. async.map(links, keyToMerkleDagNode, onLinksReady) function onLinksReady (err, nodes) { if (err) return cb(err) // Convert each Merkle DAG node to a Merkle DAG link. nodes = nodes.map(function (node) { return node.asLink('') }) // Create the final Merkle DAG node. var dagNode = new merkledag.Node(value, nodes) cb(null, dagNode) } } return log }
25.253731
79
0.640071
b1812c692dbadb942cf113ffd668efa37aee14d4
213
js
JavaScript
frontend-pos/src/components/Home/Home.js
micahriley88/pos-system
f10e669b187e5deb6fc407f34a94daa60227c7f1
[ "MIT" ]
null
null
null
frontend-pos/src/components/Home/Home.js
micahriley88/pos-system
f10e669b187e5deb6fc407f34a94daa60227c7f1
[ "MIT" ]
null
null
null
frontend-pos/src/components/Home/Home.js
micahriley88/pos-system
f10e669b187e5deb6fc407f34a94daa60227c7f1
[ "MIT" ]
null
null
null
import React from 'react'; import PropTypes from 'prop-types'; const Home = () => ( <div data-testid="Home"> Home Component </div> ); Home.propTypes = {}; Home.defaultProps = {}; export default Home;
13.3125
35
0.638498
b181a63a4309c3e20f343fe147463ea34201c7fb
2,931
js
JavaScript
base-2021/js/app.js
madc/themes
4ec4e67a898b59d3a8550a74f3c537afce405ef7
[ "MIT" ]
null
null
null
base-2021/js/app.js
madc/themes
4ec4e67a898b59d3a8550a74f3c537afce405ef7
[ "MIT" ]
null
null
null
base-2021/js/app.js
madc/themes
4ec4e67a898b59d3a8550a74f3c537afce405ef7
[ "MIT" ]
null
null
null
/*Toggle header colours*/ var scrollpos = window.scrollY; var header = document.getElementById("header"); var navcontent = document.getElementById("nav-content"); var navaction = document.getElementById("navAction"); var brandname = document.getElementById("brandname"); var toToggle = document.querySelectorAll(".toggleColour"); document.addEventListener('scroll', function() { /*Apply classes for slide in bar*/ scrollpos = window.scrollY; if(scrollpos > 10){ header.classList.add("bg-white"); header.classList.remove("text-white"); header.classList.add("text-black"); //Use to switch toggleColour colours for (var i = 0; i < toToggle.length; i++) { toToggle[i].classList.add("text-black"); toToggle[i].classList.remove("text-white"); } header.classList.add("shadow"); } else { header.classList.remove("bg-white"); header.classList.remove("text-black"); header.classList.add("text-white"); //Use to switch toggleColour colours for (var i = 0; i < toToggle.length; i++) { toToggle[i].classList.add("text-white"); toToggle[i].classList.remove("text-gray-800"); } header.classList.remove("shadow"); } }); /*Toggle dropdown list*/ /*https://gist.github.com/slavapas/593e8e50cf4cc16ac972afcbad4f70c8*/ var navMenuDiv = document.getElementById("nav-content"); var navMenu = document.getElementById("nav-toggle"); document.onclick = check; function check(e){ var target = (e && e.target) || (event && event.srcElement); //Nav Menu if (!checkParent(target, navMenuDiv)) { // click NOT on the menu if (checkParent(target, navMenu)) { // click on the link if (navMenuDiv.classList.contains("hidden")) { navMenuDiv.classList.remove("hidden"); } else {navMenuDiv.classList.add("hidden");} } else { // click both outside link and outside menu, hide menu navMenuDiv.classList.add("hidden"); } } } function checkParent(t, elm) { while(t.parentNode) { if( t == elm ) {return true;} t = t.parentNode; } return false; } /* Progress bar */ //Source: https://alligator.io/js/progress-bar-javascript-css-variables/ var h = document.documentElement, b = document.body, st = 'scrollTop', sh = 'scrollHeight', progress = document.querySelector('#progress'), scroll; var scrollpos = window.scrollY; var header = document.getElementById("header"); var navcontent = document.getElementById("nav-content"); document.addEventListener('scroll', function () { /*Refresh scroll % width*/ scroll = (h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight) * 100; progress.style.setProperty('--scroll', scroll + '%'); /*Apply classes for slide in bar*/ scrollpos = window.scrollY; if (scrollpos > 10) { header.classList.add("bg-white"); header.classList.add("shadow"); } else { header.classList.remove("bg-white"); header.classList.remove("shadow"); } });
26.645455
74
0.671443
b183518efaebff5750557fd782cd724927f8b1f1
5,566
js
JavaScript
src/components/User/__tests__/UserValidation.test.js
alenworld/internship-template-tests
1042d1202bc8752fc147ca53b7ea134a16737cd6
[ "MIT" ]
null
null
null
src/components/User/__tests__/UserValidation.test.js
alenworld/internship-template-tests
1042d1202bc8752fc147ca53b7ea134a16737cd6
[ "MIT" ]
null
null
null
src/components/User/__tests__/UserValidation.test.js
alenworld/internship-template-tests
1042d1202bc8752fc147ca53b7ea134a16737cd6
[ "MIT" ]
null
null
null
const UserValidation = require('../validation'); describe('UserValidation', () => { describe('findById', () => { test('return object containing value', (done) => { expect.assertions(2); const data = { id: '61f26cebe98112983822b133' }; expect(UserValidation.findById(data)).toHaveProperty('value'); expect(UserValidation.findById(data)).not.toHaveProperty('error'); done(); }); test('return object containing value, error', (done) => { expect.assertions(2); const data = { id: '61f26cebe981129' }; expect(UserValidation.findById(data)).toHaveProperty('error'); expect(UserValidation.findById(data)).toHaveProperty('value'); done(); }); }); describe('create', () => { test('return object success, given a validate data', (done) => { expect.assertions(2); const data = { email: 'test@mail.com', fullName: 'Tester' }; expect(UserValidation.create(data)).toMatchObject({ value: data }); expect(UserValidation.create(data).error).toBeUndefined(); done(); }); test('return object error, an email given is empty string', (done) => { expect.assertions(2); const data = { email: '', fullName: 'Tester' }; expect(UserValidation.create(data)).toMatchObject({ value: data }); expect(UserValidation.create(data).error.details[0].path).toContain('email'); done(); }); test('return object error, given a not valid email', (done) => { const data = { email: 'notemail', fullName: 'Tester' }; expect(UserValidation.create(data)).toMatchObject({ value: data }); expect(UserValidation.create(data).error.details[0].path).toContain('email'); done(); }); test('return object error, a fullName given is empty string', (done) => { const data = { email: 'test@mail.com', fullName: '' }; expect(UserValidation.create(data)).toMatchObject({ value: data }); expect(UserValidation.create(data).error.details[0].path).toContain('fullName'); done(); }); test('return object error, a fullName length < 5', (done) => { const data = { email: 'test@mail.com', fullName: 'asd' }; expect(UserValidation.create(data)).toMatchObject({ value: data }); expect(UserValidation.create(data).error.details[0].path).toContain('fullName'); done(); }); test('return object error, a fullName exists number or symbols', (done) => { const data = { email: 'test@mail.com', fullName: 'T3stu#ser' }; expect(UserValidation.create(data)).toMatchObject({ value: data }); expect(UserValidation.create(data).error.details[0].path).toContain('fullName'); done(); }); }); describe('updateById', () => { test('return object success, given a validate data', (done) => { expect.assertions(2); const data = { id: '61f26cebe98112983822b133', fullName: 'Tester' }; expect(UserValidation.updateById(data)).toMatchObject({ value: data }); expect(UserValidation.updateById(data).error).toBeUndefined(); done(); }); test('return object error, given a not valid id', (done) => { expect.assertions(2); const data = { id: 'noid', fullName: 'Tester' }; expect(UserValidation.updateById(data)).toMatchObject({ value: data }); expect(UserValidation.updateById(data).error.details[0].path).toContain('id'); done(); }); test('return object error, a fullName given is empty string', (done) => { expect.assertions(2); const data = { id: '61f26cebe98112983822b133', fullName: '' }; expect(UserValidation.updateById(data)).toMatchObject({ value: data }); expect(UserValidation.updateById(data).error.details[0].path).toContain('fullName'); done(); }); test('return object error, a fullName length < 5', (done) => { expect.assertions(2); const data = { id: '61f26cebe98112983822b133', fullName: 'asd' }; expect(UserValidation.updateById(data)).toMatchObject({ value: data }); expect(UserValidation.updateById(data).error.details[0].path).toContain('fullName'); done(); }); test('return object error, a fullName length > 30', (done) => { expect.assertions(2); const data = { id: '61f26cebe98112983822b133', fullName: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; expect(UserValidation.updateById(data)).toMatchObject({ value: data }); expect(UserValidation.updateById(data).error.details[0].path).toContain('fullName'); done(); }); test('return object error, a fullName exists number or symbols', (done) => { expect.assertions(2); const data = { id: '61f26cebe98112983822b133', fullName: 'T3stu#ser' }; expect(UserValidation.updateById(data)).toMatchObject({ value: data }); expect(UserValidation.updateById(data).error.details[0].path).toContain('fullName'); done(); }); }); describe('deleteById', () => { test('return object containing value', (done) => { expect.assertions(2); const data = { id: '61f26cebe98112983822b133' }; expect(UserValidation.deleteById(data)).toHaveProperty('value'); expect(UserValidation.deleteById(data)).not.toHaveProperty('error'); done(); }); test('return object containing value, error', (done) => { expect.assertions(2); const data = { id: '61f26cebe981129' }; expect(UserValidation.deleteById(data)).toHaveProperty('error'); expect(UserValidation.deleteById(data)).toHaveProperty('value'); done(); }); }); });
40.926471
99
0.637801
b1839873acace1d89b17b36c63c7ef8f4d210602
330
js
JavaScript
packages/try-pwa-web-push-client/src/plugins/firebase/core/FirebaseApp.js
mya-ake/try-pwa-apis
16bec2a8447bdeedea5e216da46e90c42bc7acaa
[ "MIT" ]
3
2018-09-06T17:50:40.000Z
2020-12-03T09:41:20.000Z
packages/try-pwa-web-push-client/src/plugins/firebase/core/FirebaseApp.js
mya-ake/try-pwa-apis
16bec2a8447bdeedea5e216da46e90c42bc7acaa
[ "MIT" ]
7
2018-08-26T06:16:52.000Z
2019-10-20T08:37:41.000Z
packages/try-pwa-web-push-client/src/plugins/firebase/core/FirebaseApp.js
mya-ake/try-pwa-apis
16bec2a8447bdeedea5e216da46e90c42bc7acaa
[ "MIT" ]
null
null
null
import firebase from "firebase/app"; import "firebase/messaging"; export class FirebaseApp { constructor(config) { this._app = firebase.initializeApp(config); } get app() { return this._app; } createMessaging() { try { return this.app.messaging(); } catch (err) { return null; } } }
15.714286
47
0.618182
b183c8d28c38a032f643cf9ca9927ce53b981fa3
666
js
JavaScript
photo-app/dist/main.js
CesarGBkR/Typescript
4c0b820d0fdf0565f2efd8eb5c960cef29aed5ad
[ "MIT" ]
null
null
null
photo-app/dist/main.js
CesarGBkR/Typescript
4c0b820d0fdf0565f2efd8eb5c960cef29aed5ad
[ "MIT" ]
null
null
null
photo-app/dist/main.js
CesarGBkR/Typescript
4c0b820d0fdf0565f2efd8eb5c960cef29aed5ad
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const album_1 = require("../src/album"); const picture_1 = require("./picture"); const pictureOrientation_1 = require("../src/pictureOrientation"); const user_1 = require("../src/user"); const user = new user_1.User(1, 'BKR', 'Cesar', true); const album = new album_1.Album(10, 'Platzi Pictures'); const picture = new picture_1.Picture(1, 'TypeScript Course', '2022-26', pictureOrientation_1.PictureOrientation.Landscape); //Creamos relaciones user.addAlbum(album); album.addPicture(picture); console.log('user', user); //Borramos Album user.removeAlbum(album); console.log('user', user);
39.176471
124
0.735736
b1843337e82e72b678198c60f34032b0cf9f2f44
1,005
es6
JavaScript
assets/javascripts/discourse/components/carbonads-ad.js.es6
anythingagency/discourse-cm-adplugin
0d534ce52a48a636a00fa54bf4ef2eeac0cac503
[ "MIT" ]
null
null
null
assets/javascripts/discourse/components/carbonads-ad.js.es6
anythingagency/discourse-cm-adplugin
0d534ce52a48a636a00fa54bf4ef2eeac0cac503
[ "MIT" ]
null
null
null
assets/javascripts/discourse/components/carbonads-ad.js.es6
anythingagency/discourse-cm-adplugin
0d534ce52a48a636a00fa54bf4ef2eeac0cac503
[ "MIT" ]
null
null
null
import AdComponent from "discourse/plugins/discourse-adplugin/discourse/components/ad-component"; import { default as computed } from "ember-addons/ember-computed-decorators"; const serve_id = Discourse.SiteSettings.carbonads_serve_id, placement = Discourse.SiteSettings.carbonads_placement; export default AdComponent.extend({ init() { this.set("serve_id", serve_id); this._super(); }, @computed("serve_id") url(serveId) { return `//cdn.carbonads.com/carbon.js?serve=${serveId}&placement=${placement}`.htmlSafe(); }, @computed("currentUser.trust_level") showToTrustLevel(trustLevel) { return !( trustLevel && trustLevel > Discourse.SiteSettings.carbonads_through_trust_level ); }, @computed("showToTrustLevel", "showToGroups", "showOnCurrentPage") showAd(showToTrustLevel, showToGroups, showOnCurrentPage) { return ( placement && serve_id && showToTrustLevel && showToGroups && showOnCurrentPage ); } });
27.162162
97
0.706468
b1843e929321d7b38ba3e62c05fb72caaa875dca
487
js
JavaScript
resources/js/src/appRedux/reducers/Settings.js
MoFoLuWaSo/square1-test
a2560d631c1038b2d3b33ac8850eecf8f989f600
[ "CC0-1.0" ]
null
null
null
resources/js/src/appRedux/reducers/Settings.js
MoFoLuWaSo/square1-test
a2560d631c1038b2d3b33ac8850eecf8f989f600
[ "CC0-1.0" ]
null
null
null
resources/js/src/appRedux/reducers/Settings.js
MoFoLuWaSo/square1-test
a2560d631c1038b2d3b33ac8850eecf8f989f600
[ "CC0-1.0" ]
null
null
null
const initialSettings = { isDirectionRTL: false, locale: { languageId: 'english', locale: 'en', name: 'English', icon: 'us' } }; const SettingsReducer = (state = initialSettings, action) => { switch (action.type) { case 'SWITCH_LANGUAGE': return { ...state, locale: action.payload, }; default: return state; } } export default SettingsReducer;
16.793103
62
0.501027
b186403d7be49260e450c93480a69fb47dc48c04
2,796
js
JavaScript
node_modules/@forge/api/out/store/product-scoped/__test__/confluence-versioned-storage.test.js
hyiij/intelligent_inventories
46ea3c88e3e5eecdcda45afdd8e5e6039dff0d3a
[ "Unlicense" ]
null
null
null
node_modules/@forge/api/out/store/product-scoped/__test__/confluence-versioned-storage.test.js
hyiij/intelligent_inventories
46ea3c88e3e5eecdcda45afdd8e5e6039dff0d3a
[ "Unlicense" ]
null
null
null
node_modules/@forge/api/out/store/product-scoped/__test__/confluence-versioned-storage.test.js
hyiij/intelligent_inventories
46ea3c88e3e5eecdcda45afdd8e5e6039dff0d3a
[ "Unlicense" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const confluence_versioned_storage_1 = require("../confluence-versioned-storage"); const getStorage = (apiClientMock) => new confluence_versioned_storage_1.ConfluenceVersionedStorage('test.com', apiClientMock); const getApiClientMock = (response, statusCode = 200) => { return jest.fn().mockReturnValue({ ok: statusCode !== 200 ? false : true, status: statusCode, json: jest.fn().mockResolvedValue(Object.assign({}, response)) }); }; describe('ConfluenceVersionedStorage', () => { describe('versionedSet', () => { it('should create a new versioned object, if the API returns 404 for the provided key', async () => { const apiClientMock = getApiClientMock(undefined, 404); const versionedStorage = getStorage(apiClientMock); await versionedStorage.versionedSet('testKey', 'testValue'); const expectedVersionedObject = { value: 'testValue', version: { number: 1 } }; expect(apiClientMock).toHaveBeenNthCalledWith(1, 'test.com/testKey'); expect(apiClientMock).toHaveBeenNthCalledWith(2, 'test.com/testKey', { method: 'POST', body: JSON.stringify(expectedVersionedObject), headers: { 'content-type': 'application/json' } }); }); it('should bump the version of an existing object, if the API returns a value for the provided key', async () => { const apiClientMock = getApiClientMock({ version: { number: 1 } }, 200); const versionedStorage = getStorage(apiClientMock); await versionedStorage.versionedSet('testKey', 'testValue'); const expectedVersionedObject = { value: 'testValue', version: { number: 2 } }; expect(apiClientMock).toHaveBeenNthCalledWith(1, 'test.com/testKey'); expect(apiClientMock).toHaveBeenNthCalledWith(2, 'test.com/testKey', { method: 'PUT', body: JSON.stringify(expectedVersionedObject), headers: { 'content-type': 'application/json' } }); }); it('should throw an error, if the API returns an unexpected status code', async () => { const apiClientMock = getApiClientMock(undefined, 500); const versionedStorage = getStorage(apiClientMock); const response = versionedStorage.versionedSet('testKey', 'testValue'); await expect(response).rejects.toThrow(); }); }); });
46.6
127
0.581545
b18658d054813636c36ff5104ff8950203863320
2,613
js
JavaScript
src/createEnhancer.js
sskyy/redux-event-bus
58adf412bc29a7845fe5a02e3b05c161b5e116bf
[ "MIT" ]
111
2016-03-08T06:55:29.000Z
2020-07-20T15:23:10.000Z
src/createEnhancer.js
sskyy/redux-event-bus
58adf412bc29a7845fe5a02e3b05c161b5e116bf
[ "MIT" ]
4
2016-03-11T03:16:26.000Z
2017-02-20T16:28:56.000Z
src/createEnhancer.js
sskyy/redux-event-bus
58adf412bc29a7845fe5a02e3b05c161b5e116bf
[ "MIT" ]
5
2016-03-11T10:19:04.000Z
2019-07-25T04:57:28.000Z
import { flat } from './helpers' import Bus from './bus' export const ActionTypes = { PERFORM_ACTION: 'BUS_PERFORM_ACTION', CHANGE_STATUS: 'BUS_CHANGE_STATUS', REDUX_INIT: '@@redux/INIT' } function performAction(action) { if (typeof action.type === 'undefined') { throw new Error( 'Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?' ) } return { type: ActionTypes.PERFORM_ACTION, action, timestamp: Date.now() } } function liftAction(action) { return performAction(action) } function liftReducerWithBus(reducer, initialCommittedState) { const initialLiftedState = { status: {}, computedState: initialCommittedState } return (liftedState = initialLiftedState, liftedAction) => { let { status,computedState } = liftedState switch (liftedAction.type) { case ActionTypes.CHANGE_STATUS : status = liftedAction.payload break case ActionTypes.REDUX_INIT: computedState = reducer(computedState, { type: ActionTypes.REDUX_INIT }) break } return { status, computedState: liftedAction.action ? reducer(computedState, liftedAction.action) : computedState } } } function unliftState(liftedState) { return liftedState.computedState } function unliftStore(reduxTaskLiftedStore, liftReducer, bus) { return { ...reduxTaskLiftedStore, reduxTaskLiftedStore, dispatch(action) { reduxTaskLiftedStore.dispatch(liftAction(action)) bus.emit(action) return action }, getState() { return unliftState(reduxTaskLiftedStore.getState()) }, replaceReducer(nextReducer) { reduxTaskLiftedStore.replaceReducer(liftReducer(nextReducer)) } } } export default function createEnhancer(listeners) { return createStore=>(reducer, initialState, enhancer)=> { const bus = new Bus function liftReducer(r, bus) { return liftReducerWithBus(r, initialState, bus) } //once we createStore, it will use internal dispatch init action const liftedStore = createStore(liftReducer(reducer, bus), enhancer) const store = unliftStore(liftedStore, liftReducer, bus) bus.setDefaultContext({ dispatch: store.dispatch, getState: store.getState }) liftedStore.bus = bus //flat listeners //so we can create multiple listeners which shares a closure flat(listeners).forEach(listener=> { bus.listen(listener) }) bus.onStateChange(status=>liftedStore.dispatch({ type: ActionTypes.CHANGE_STATUS, payload: status })) return store } }
24.194444
105
0.693456
b1867e0eed7db179d078e0f294d8ae63e4bacd1d
565
js
JavaScript
my-app/src/pages/home.js
AuroraBrune/restaurantApp
18a755d615fe41b75334069a1817f4a3d4da4194
[ "MIT" ]
null
null
null
my-app/src/pages/home.js
AuroraBrune/restaurantApp
18a755d615fe41b75334069a1817f4a3d4da4194
[ "MIT" ]
null
null
null
my-app/src/pages/home.js
AuroraBrune/restaurantApp
18a755d615fe41b75334069a1817f4a3d4da4194
[ "MIT" ]
null
null
null
import React from 'react'; import Carousel from '../components/Carousel/index'; import Sidebar from '../components/Sidebar'; import Header from '../components/Header'; import Footer from '../components/Footer'; function Home() { return ( <div> <div> <Header /> </div> <div className="main"> <div className="panel"> <Carousel /> </div> <div className="sidebar"> <Sidebar /> </div> </div> <div> <Footer /> </div> </div> ); } export default Home;
17.65625
52
0.530973
b1869e4843015938b9233a5499225c51c4b606f7
616
js
JavaScript
migrations/20210725084507_alter_table_delivery_services_add_columns.js
ATR-BPN/backend-pertanahan-app
63a82523b3131d0ab924dac01c37e6212af23202
[ "MIT" ]
null
null
null
migrations/20210725084507_alter_table_delivery_services_add_columns.js
ATR-BPN/backend-pertanahan-app
63a82523b3131d0ab924dac01c37e6212af23202
[ "MIT" ]
1
2021-09-02T21:40:13.000Z
2021-09-02T21:40:13.000Z
migrations/20210725084507_alter_table_delivery_services_add_columns.js
ATR-BPN/backend-pertanahan-app
63a82523b3131d0ab924dac01c37e6212af23202
[ "MIT" ]
null
null
null
exports.up = function (knex) { return knex.schema.alterTable('delivery_services', (table) => { table.string('empower_path') table.string('shipping_notes') table.boolean('is_paid') table.date('schedule_date') table.time('schedule_time') table.string('checklist') table.string('invoice_path') }) } exports.down = function (knex) { return knex.schema.alterTable('delivery_services', (table) => { table.dropColumns([ 'empower_path', 'shipping_notes', 'is_paid', 'schedule_date', 'schedule_time', 'checklist', 'invoice_path', ]) }) }
23.692308
65
0.633117
b186a0ae99717c18a7a921c357a942edede58b96
3,925
js
JavaScript
test/__fixtures__/async/transformed/spec.js
isabella232/codemod-1
95354715b2144067a68b83e67baafc95ce5b118b
[ "MIT" ]
null
null
null
test/__fixtures__/async/transformed/spec.js
isabella232/codemod-1
95354715b2144067a68b83e67baafc95ce5b118b
[ "MIT" ]
1
2022-03-19T12:32:30.000Z
2022-03-19T12:32:30.000Z
test/__fixtures__/async/transformed/spec.js
isabella232/codemod-1
95354715b2144067a68b83e67baafc95ce5b118b
[ "MIT" ]
null
null
null
const Login = require('./page'); describe('Test describe', () => { before(async () => { await Login.authenticate(); }); it('general commands', async () => { await Login.foo(); await $('.foo').click(); await browser.pause(5000); await browser.waitUntil(async () => { return (await $('.bar').getText()) === 'foo'; }); await foo(); current_date = moment(current_date, `MM/DD/YYYY`).add(1, `days`).format(`MM/DD/YYYY`); dates.push(moment(current_date, `MM/DD/YYYY`).format(format_to_return)); await Promise.all(foobar.map(String)); await expect(1).toBe(1); const foobar = async () => {} const testing = String(`foo`); const testing2 = `foo`.toUpperCase(); }); it(`browser.execute`, async () => { const arr = await $$('.foo'); await browser.execute(() => { $('.foo').click(); }); await browser.execute(() => { document.querySelector('.foo').click(); $('.foo').click(); }); await browser.execute(foo => { $(`.`).click(); document.querySelector(`.foo`).click(); }, `.foo`); await browser.execute(() => $(`.foo`).click()); await browser.execute((date, time) => { const $date = $(`[data-title="Date Field"] .field-input.newdate`); const $time = $(`[data-title="Time Field"] .field-input.time`); $date.val(date); $time.val(time); }, date, time); await browser.execute(this.setHash(options.hash)); const foo = await browser.execute(() => { $(`.foo`).click(); }); async function bar() { return browser.execute(() => { $(`.foo`).click(); }); } const results = await browser.execute(() => { const bar = 123; (function foo() { const testing = 456; foo(); })() }); testing = await browser.execute(() => { $(`.foo`).click(); }); }); it('loops', async () => { for (const num of [1, 2, 3]) { await $('.foo').setValue(num); }; await Promise.all([ 1, 2, 3 ].map(async num => { await $('.foo').setValue(num); })); for (const { foo, bar } of [{ foo : 123, bar : 456, }, { foo : 999, bar : 888, }]) { await $('.foo').setValue(foo); await $('.bar').setValue(bar); }; for (const num of foo) { await $('.bar').setValue('aaa'); }; for (const foo of button_data) { await checkAuthPage(true); }; for (const [index, word] of [`foo`].entries()) { console.log(word, index); }; for (const word of foo) { console.log(word); }; for (const [index, word] of foo.entries()) { console.log(word, index); }; for (const [index, word] of foo.bar.entries()) { console.log(word, index); }; for (const word of foo.bar) { console.log(word); }; for (const num of [`foo`]) { console.log(word); }; await Promise.all((await $$(`.foo`)).map(async el => { await el.click(); })); const bar = await Promise.all((await $$(`.foo`)).map(async el => { await el.click(); })); }); }); async function foo() { const bar = 123; await $('.foo').setValue(bar); } const getColumns = async (foo, bar) => { await $(`.123`).setValue(123); } const foobar = () => ({ foo : 123 });
23.502994
94
0.43414
b186a3785c13e430de522dfab96d534622233a09
921
js
JavaScript
www/src/components/BrowserGlobalsCodeBlock.js
Sporego/react-bootstrap
68b4f0a1c9bdd773c53cd4327439615034ab9576
[ "MIT" ]
null
null
null
www/src/components/BrowserGlobalsCodeBlock.js
Sporego/react-bootstrap
68b4f0a1c9bdd773c53cd4327439615034ab9576
[ "MIT" ]
1
2020-10-04T23:36:44.000Z
2020-10-04T23:36:44.000Z
www/src/components/BrowserGlobalsCodeBlock.js
Sporego/react-bootstrap
68b4f0a1c9bdd773c53cd4327439615034ab9576
[ "MIT" ]
null
null
null
import React from 'react'; import CodeBlock from './CodeBlock'; const propTypes = {}; function BrowserGlobalsCodeBlock() { return ( <CodeBlock mode="html" codeText={` /* This is React.js a React-Bootstrap depenancy... duhh*/ /*Automatically added, if you are using a react framework (e.g., next.js, create-react-app, and gastby).*/ <script src="https://unpkg.com/react/umd/react.production.min.js" crossorigin></script> <script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js" crossorigin></script> /* This is React-Bootstrap's browser global*/ /* Notice it is loaded after React.js*/ <script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js" crossorigin></script> /*Your other scripts*/ <script>let ReactBootstrapBeAwesome = true </script> `} /> ); } BrowserGlobalsCodeBlock.propTypes = propTypes; export default BrowserGlobalsCodeBlock;
24.891892
106
0.715527
b186b32c8ef084096bf808ab6e88dcd788d4b9f4
2,221
js
JavaScript
build/lib/index.js
bradleyridge/screenshotr
673628e18ab6338c5cd6727b9884f090cc137e23
[ "MIT" ]
null
null
null
build/lib/index.js
bradleyridge/screenshotr
673628e18ab6338c5cd6727b9884f090cc137e23
[ "MIT" ]
null
null
null
build/lib/index.js
bradleyridge/screenshotr
673628e18ab6338c5cd6727b9884f090cc137e23
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _fs = _interopRequireDefault(require("fs")); var _utils = require("./utils"); var _config = _interopRequireDefault(require("../config")); var _launchBrowser = _interopRequireDefault(require("./launchBrowser")); var _captureScreenshot = _interopRequireDefault(require("./captureScreenshot")); var _tryToCloseBrowser = _interopRequireDefault(require("./tryToCloseBrowser")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const captureScreenshots = async (screenshots, page, destinationFolder) => { const screenshot = screenshots.pop(); const output = await (0, _captureScreenshot.default)(screenshot, page, destinationFolder); if (screenshots.length > 0) return [output, ...(await captureScreenshots(screenshots, page, destinationFolder))]; return [output]; }; const validateDestinationDirectory = (destiationPath = _config.default.destination) => { _utils.log.debug(`- verifying destination folder exists\n\t- ${destiationPath}`); if (!_fs.default.existsSync(destiationPath)) _fs.default.mkdirSync(destiationPath); }; var _default = async ({ screenshots, destination = _config.default.destination }) => { _utils.log.inform('Executing Screenshotr'); let browser; validateDestinationDirectory(destination); try { browser = await (0, _launchBrowser.default)(); _utils.log.debug('- opening new page'); const page = await browser.newPage(); const results = await captureScreenshots(screenshots, page, destination); _utils.log.debug('- closing browser'); await browser.close(); browser = null; const successfulResults = results.filter(result => !result.error); const errors = results.filter(result => !!result.error); _utils.log.succeed(`Captured ${successfulResults.length} Screenshots with Screenshotr`); return { errors, screenshots: successfulResults, destination }; } catch (error) { _utils.log.error(`Screenshotr Failed: ${error}`); } (0, _tryToCloseBrowser.default)(browser); }; exports.default = _default; module.exports = exports.default;
30.013514
115
0.722197
b18739a6698f478e7ea96551ecd6424250fd7ea7
157
js
JavaScript
lib/util/ensure.js
faber-forks/node-wpapi
e2c89fd650baf03e72ef730cb7539b9b593162de
[ "MIT" ]
null
null
null
lib/util/ensure.js
faber-forks/node-wpapi
e2c89fd650baf03e72ef730cb7539b9b593162de
[ "MIT" ]
null
null
null
lib/util/ensure.js
faber-forks/node-wpapi
e2c89fd650baf03e72ef730cb7539b9b593162de
[ "MIT" ]
null
null
null
'use strict'; module.exports = function( obj, prop, propDefaultValue ) { if ( obj && obj[ prop ] === undefined ) { obj[ prop ] = propDefaultValue; } };
19.625
58
0.617834
b1879a00742dbea81fe8f979081af568379102be
410
js
JavaScript
src/infra/database.js
ArthurCamilo/API-Challenge
588ccdc2f3361967dd21eb4d938de9144815452a
[ "MIT" ]
null
null
null
src/infra/database.js
ArthurCamilo/API-Challenge
588ccdc2f3361967dd21eb4d938de9144815452a
[ "MIT" ]
null
null
null
src/infra/database.js
ArthurCamilo/API-Challenge
588ccdc2f3361967dd21eb4d938de9144815452a
[ "MIT" ]
null
null
null
const { Sequelize } = require('sequelize'); require('dotenv/config'); const username = process.env.DB_USER; const password = process.env.DB_PASSWORD; const host = process.env.DB_HOST; const port = process.env.DB_PORT; const database = process.env.DB_NAME; const sequelize = new Sequelize(database, username, password, { host: host, port: port, dialect: 'postgres' }); module.exports = sequelize;
25.625
63
0.726829
b18b72bccae29056e2309a99af02713f39a8217b
6,079
js
JavaScript
js/router.js
playwolsey/fragment
cfa0e0950a924593e53ed0f0d650406ba9c7be85
[ "MIT" ]
null
null
null
js/router.js
playwolsey/fragment
cfa0e0950a924593e53ed0f0d650406ba9c7be85
[ "MIT" ]
null
null
null
js/router.js
playwolsey/fragment
cfa0e0950a924593e53ed0f0d650406ba9c7be85
[ "MIT" ]
null
null
null
import React, { PureComponent } from 'react'; import { BackHandler, Animated, Easing } from 'react-native'; import { connect } from 'react-redux'; import { TabNavigator, TabBarBottom, StackNavigator, addNavigationHelpers, NavigationActions, } from 'react-navigation'; import { createReduxBoundAddListener, createReactNavigationReduxMiddleware, } from 'react-navigation-redux-helpers'; import { Icon } from 'react-native-elements'; import HomeScreen from './screens/Home'; import CatesScreen from './screens/products/Cates'; import ListScreen from './screens/products/List'; // import DetailScreen from './screens/products/Detail'; // import ApplyScreen from './screens/products/Apply'; // import SettingsScreen from './screens/Me/Settings'; // import BorrowerScreen from './screens/Business/Borrower'; // import ProjectScreen from './screens/Business/Project'; // import BusinessScreen from './screens/Business/Business'; // import AddBorrowerScreen from './screens/Business/AddBorrower'; // import AddPersonBorrowerScreen from './screens/Business/AddPersonBorrower'; // import AddCompanyBorrowerScreen from './screens/Business/AddCompanyBorrower'; // import RecommendScreen from './screens/Business/Recommend'; import LoginScreen from './screens/Login'; import MeScreen from './screens/Me/Me'; import Loading from './screens/Loading'; import WebviewScreen from './screens/Webview'; /** * 基本路由模块 * Home 首页模块 * Cates 产品模块 * Business 业务模块 * Me 个人模块 */ const Tabs = TabNavigator({ Home: { screen: HomeScreen, navigationOptions: { // tabBarLabel: '首页', tabBarIcon: ({ tintColor }) => <Icon name="home" size={25} color={tintColor} />, }, }, Cates: { screen: CatesScreen, navigationOptions: { // tabBarLabel: '产品', tabBarIcon: ({ tintColor }) => <Icon name="layers" size={25} color={tintColor} />, }, }, // Business: { // screen: BusinessScreen, // navigationOptions: { // tabBarLabel: '业务', // // tabBarIcon: ({ tintColor }) => <Icon name="folder-open" size={25} color={tintColor} />, // }, // }, Me: { screen: MeScreen, navigationOptions: { // tabBarLabel: '我的', tabBarIcon: ({ tintColor }) => <Icon name="perm-identity" size={25} color={tintColor} />, }, }, }, { tabBarComponent: TabBarBottom, tabBarPosition: 'bottom', swipeEnabled: false, animationEnabled: false, lazyLoad: true, tabBarOptions: { activeTintColor: '#00acff', showLabel: false, }, }); /** * 头部导航栏模块 * Tabs 底部栏模块 * List 产品列表模块 * Settings 设置中心模块 * Borrower 借款人页面模块 * AddBorrower 添加借款人页面模块 * AddPersonBorrower 添加借款人(个人)页面模块 * AddCompanyBorrower 添加借款人(企业)页面模块 * Project 项目页面模块 * Recommend 我的推荐页面模块 * Login 登录页面模块 */ const MainNavigator = StackNavigator({ Tabs: { screen: Tabs, }, List: { screen: ListScreen, }, // Detail: { // screen: DetailScreen, // }, // Apply: { // screen: ApplyScreen, // }, // Settings: { // screen: SettingsScreen, // }, // Borrower: { // screen: BorrowerScreen, // }, // AddBorrower: { // screen: AddBorrowerScreen, // }, // AddPersonBorrower: { // screen: AddPersonBorrowerScreen, // }, // AddCompanyBorrower: { // screen: AddCompanyBorrowerScreen, // }, // Project: { // screen: ProjectScreen, // }, // Recommend: { // screen: RecommendScreen, // }, Webview: { screen: WebviewScreen, }, }, { mode: 'screen', headerMode: 'none', }); const AppNavigator = StackNavigator( { Main: { screen: MainNavigator }, Login: { screen: LoginScreen }, }, { headerMode: 'none', cardStyle: { backgroundColor: 'red' }, mode: 'modal', navigationOptions: { gesturesEnabled: false, }, transitionConfig: () => ({ transitionSpec: { duration: 300, easing: Easing.out(Easing.poly(4)), timing: Animated.timing, }, screenInterpolator: (sceneProps) => { const { layout, position, scene } = sceneProps; const { index } = scene; const height = layout.initHeight; const translateY = position.interpolate({ inputRange: [index - 1, index, index + 1], outputRange: [height, 0, 0], }); const opacity = position.interpolate({ inputRange: [index - 1, index - 0.99, index], outputRange: [0, 1, 1], }); return { opacity, transform: [{ translateY }] }; }, }), }, ); function getCurrentScreen(navigationState) { if (!navigationState) { return null; } const route = navigationState.routes[navigationState.index]; if (route.routes) { return getCurrentScreen(route); } return route.routeName; } export const routerMiddleware = createReactNavigationReduxMiddleware( 'root', state => state.router, ); const addListener = createReduxBoundAddListener('root'); @connect(({ app, router }) => ({ app, router })) class Router extends PureComponent { componentWillMount() { BackHandler.addEventListener('hardwareBackPress', this.backHandle); } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.backHandle); } backHandle = () => { const currentScreen = getCurrentScreen(this.props.router); if (currentScreen === 'Login') { return true; } if (currentScreen !== 'Home') { this.props.dispatch(NavigationActions.back()); return true; } return false; }; render() { const { dispatch, app, router } = this.props; if (app.loading) { return <Loading />; } return ( <AppNavigator navigation={addNavigationHelpers({ dispatch, state: router, addListener, })} /> ); } } export function routerReducer(state, action = {}) { return AppNavigator.router.getStateForAction(action, state); } export default Router;
25.542017
99
0.618852
b18f1e704a191fd279cea2b14dde3caff89082cf
1,136
js
JavaScript
services/frontend/src/utils/searchGlobals.js
CDH-Studio/Skillhub
173660ccbb9466260146b40f841063012d3c55ff
[ "MIT" ]
4
2019-08-02T23:02:10.000Z
2022-03-02T08:42:20.000Z
services/frontend/src/utils/searchGlobals.js
CDH-Studio/Skillhub
173660ccbb9466260146b40f841063012d3c55ff
[ "MIT" ]
16
2019-05-29T17:48:53.000Z
2021-05-09T08:33:08.000Z
services/frontend/src/utils/searchGlobals.js
CDH-Studio/Skillhub
173660ccbb9466260146b40f841063012d3c55ff
[ "MIT" ]
3
2019-08-06T01:34:10.000Z
2020-11-23T17:18:51.000Z
import uuidv4 from "uuid/v4"; export class Query{ constructor({ searchTerm = "", searchBy = "", id = uuidv4() } = {}) { this.searchTerm = searchTerm; this.searchBy = searchBy; this.id = id; } } export const searchRecords = (records, searchTerm, searchType) => { if (searchType === "name") { const searchTermLC = searchTerm.toLowerCase(); return records.filter((record) => { const recordNameLC = record.name.toLowerCase(); return recordNameLC.includes(searchTermLC); }); } else if (searchType === "skill") { const searchTermLC = searchTerm.toLowerCase(); return records.filter((record) => { return record.skills.reduce((acc, skill) => { const skillNameLC = skill.name.toLowerCase(); return acc || skillNameLC.includes(searchTermLC); }, false); }); } else { return records; } }; export const FILTER_PROJECTS = "Projects"; export const FILTER_PROFILES = "Profiles"; export const SEARCH_OPTIONS = [ "Name", "Skill" ];
28.4
67
0.571303
b18f345b5a68ecfe7093911f304d690d19a5a2aa
4,998
js
JavaScript
lib/kernel.js
bsingr/opal
351045a892bdce6e556031ec3b53eced49f92ebb
[ "MIT" ]
1
2015-11-05T01:28:59.000Z
2015-11-05T01:28:59.000Z
lib/kernel.js
bsingr/opal
351045a892bdce6e556031ec3b53eced49f92ebb
[ "MIT" ]
null
null
null
lib/kernel.js
bsingr/opal
351045a892bdce6e556031ec3b53eced49f92ebb
[ "MIT" ]
null
null
null
var Opal = $opal, self = Opal.top, nil = Opal.Qnil, $class = Opal.dc, $def = Opal.dm;$class(self, nil, "Kernel", function() {var self = this; $def(self, "require", function(path) {var self = this; return $opal.require(path); }, 0); $def(self, "loop", function() {var self = this; while (true) { try { __block__.call(__block__.$self); } catch (e) { switch (e.$keyword) { case 2: return e['@exit_value']; default: throw e; } } } return self; }, 0); $def(self, "proc", function() {var self = this; if (block_given) {self.m$raise(rb_vm_cg(self, "ArgumentError"), "block required")}; return self.m$block(); }, 0); $def(self, "lambda", function() {var self = this; if (block_given) {self.m$raise(rb_vm_cg(self, "ArgumentError"), "block required")}; return self.m$block(); }, 0); $def(self, "raise", function(exception, string) {var self = this; var msg = nil, exc; if (typeof exception == 'string') { msg = exception; exc = rb_vm_cg(self, "RuntimeError").m$new(msg); } else if (exception["m$kind_of?"](rb_vm_cg(self, "Exception")).$r) { exc = exception; } else { if (string != nil) msg = string; exc = exception.m$new(msg); } rb_vm_raise(exc); }, 0); $def(self, "fail", function(exception, string) {var self = this; return self.m$raise(self.m$exception(), self.m$string()); }, 0); $def(self, "instance_variable_defined?", function(name) {var self = this; name = self.m$name().m$to_s(); return self[name] == undefined ? Qfalse : Qtrue; }, 0); $def(self, "instance_variable_get", function(name) {var self = this; name = self.m$name().m$to_s(); return self[name] == undefined ? nil : self[name]; }, 0); $def(self, "instance_variable_set", function(name, value) {var self = this; name = self.m$name().m$to_s(); return self[name] = value; }, 0); $def(self, "block_given?", function() {var self = this; return Qfalse; }, 0); $def(self, "method_missing", function(sym, args) {var self = this;args = [].slice.call(arguments, 1); return self.m$raise(rb_vm_cg(self, "NoMethodError"), ("undefined method `" + self.m$sym().m$to_s() + "` for " + self.m$inspect().m$to_s())); }, 0); $def(self, "to_a", function() {var self = this; return [self]; }, 0); $def(self, "tap", function() {var self = this; if (block_given) {self.m$raise(rb_vm_cg(self, "LocalJumpError"), "no block given")}; __block__.call(__block__.$self); return self; }, 0); $def(self, "kind_of?", function(klass) {var self = this; var search = self.$klass; while (search) { if (search == klass) { return Qtrue; } search = search.$super; } return Qfalse; }, 0); $def(self, "is_a?", function(klass) {var self = this; return self["m$kind_of?"](self.m$klass()); }, 0); $def(self, "nil?", function() {var self = this; return Qfalse; }, 0); $def(self, "respond_to?", function(method_id) {var self = this; if (self['m$' + method_id.m$to_s()]) { return Qtrue; } return Qfalse; }, 0); $def(self, "===", function(other) {var self = this; return self["m$=="](self.m$other()); }, 0); $def(self, "__send__", function(method_id, args) {var self = this;args = [].slice.call(arguments, 1); return self['m$' + self.m$method_id().m$to_s()].apply(self, args); }, 0); $def(self, "send", function(method_id, args) {var self = this;args = [].slice.call(arguments, 1); return self.m$__send__(self.m$method_id()); }, 0); $def(self, "class", function() {var self = this; return rb_class_real(self.$klass); }, 0); $def(self, "rand", function(max) {var self = this; if (max != undefined) return Math.floor(Math.random() * max); else return Math.random(); }, 0); $def(self, "__id__", function() {var self = this; return self.$hash(); }, 0); $def(self, "object_id", function() {var self = this; return self.$hash(); }, 0); $def(self, "to_s", function() {var self = this; return ("#<" + rb_class_real(self.$klass).m$to_s() + ":0x" + (self.$hash() * 400487).toString(16).m$to_s() + ">"); }, 0); $def(self, "inspect", function() {var self = this; return self.m$to_s(); }, 0); $def(self, "instance_eval", function() {var self = this; if (block_given) {block.call(self)}; return self; }, 0); $def(self, "const_set", function(name, value) {var self = this; return rb_const_set(rb_class_real(self.$klass), name, value); }, 0); $def(self, "const_defined?", function(name) {var self = this; return Qfalse; }, 0); }, 2);
21.450644
144
0.544618
b18fd84ffb3e995a688b5186b0fec98d274d15d8
428
js
JavaScript
plugins/revoke.js
KuKuKuT/Cat-Bot
afd4ddcf3dd7ef778b1a0f8d2a546c6b8c039d1e
[ "MIT" ]
null
null
null
plugins/revoke.js
KuKuKuT/Cat-Bot
afd4ddcf3dd7ef778b1a0f8d2a546c6b8c039d1e
[ "MIT" ]
null
null
null
plugins/revoke.js
KuKuKuT/Cat-Bot
afd4ddcf3dd7ef778b1a0f8d2a546c6b8c039d1e
[ "MIT" ]
null
null
null
let handler = async (m, { conn }) => { let res = await conn.revokeInvite(m.chat) await conn.sendButton(m.chat, ` *🔗 New Link :* https://chat.whatsapp.com/${res.code} `.trim(), `Do you want to revoke link again? Click the button below! 😺`, `Revoke Again 😹`, `,${_p}revoke`) } handler.command = /^revoke?$/i handler.group = true handler.register = true handler.admin = true handler.botAdmin = true module.exports = handler
25.176471
106
0.675234
b1922e14af4771ff66575525807f0580274e23ce
5,222
js
JavaScript
lib/gk-framework.js
gameknife/electron-shadermonki
a6780567960fc0d0d6a523e8fab951cef1eef72a
[ "MIT" ]
35
2016-11-11T03:56:39.000Z
2021-08-06T17:32:48.000Z
lib/gk-framework.js
gameknife/electron-shadermonki
a6780567960fc0d0d6a523e8fab951cef1eef72a
[ "MIT" ]
1
2017-01-11T03:47:26.000Z
2020-11-10T06:50:22.000Z
lib/gk-framework.js
gameknife/electron-shadermonki
a6780567960fc0d0d6a523e8fab951cef1eef72a
[ "MIT" ]
4
2016-11-11T03:57:19.000Z
2020-05-26T07:16:06.000Z
/** * Created by gameKnife on 2016/12/1. */ 'use strict'; const gTimer = require("./gk-timer.js"); const Fabricate = require("./fabricate.js"); const gkCore = require("./gk-core.js"); const acEditor = require('./gk-acewrap'); const glw = require("./gk-glwrap"); class Framework { constructor() { } init() { } update() { } destroy() { } } class ShaderMonkiFramework extends Framework { constructor() { super(); this.renderer = null; this.sceneMgr = null; this.mainCamera = null; this.modelrotation = 0; this.camerarotationx = 0; this.camerarotationy = 0; this.camerapanx = 0; this.camerapany = 0; this.autoRotate = false; this.vsp_source = null; this.fsp_source = null; this.holderGameObject = null; this.cameraCenter = gkCore.math.vec3.create(); this.cameraRadius = 500.0; } init() { gTimer.init(); this.renderer = gkCore.renderer; this.renderer.init(); this.sceneMgr = gkCore.sceneMgr; this.sceneMgr.init(); this.mainCamera = Fabricate(gkCore.GameObject.Camera); this.mainCamera.transform.parent = this.sceneMgr.getSceneRoot().transform; // temporary camera transform setting this.mainCamera.transform.position = gkCore.math.vec3.fromValues(0,15,50); this.mainCamera.transform.lookAt( gkCore.math.vec3.fromValues(0,0,0) ); this.mainLight = Fabricate(gkCore.GameObject.Light); this.mainLight.transform.position = gkCore.math.vec3.fromValues(-1000,1500,1000); this.mainLight.transform.lookAt( gkCore.math.vec3.fromValues(0,0,0) ); this.mainLight.transform.parent = this.sceneMgr.getSceneRoot().transform; // create editor let refthis = this; let vseditor = new acEditor.AceEditorWindow("vs-editor-panel"); vseditor.setChangeCallback( function(str) { refthis.vsp_source = str; refthis.updateShader(); } ) let fseditor = new acEditor.AceEditorWindow("fs-editor-panel"); fseditor.setChangeCallback( function(str) { refthis.fsp_source = str; refthis.updateShader(); } ); // default assets loading vseditor.loadFile('res/shader/base_vs.glsl'); fseditor.loadFile('res/shader/base_fs.glsl'); } update() { gTimer.update(); // update mouse let relDelta = gkCore.mouse.frameUpdate(); if(gkCore.mouse.moveType === gkCore.mouse.HOLDLEFT) { this.camerarotationy -= relDelta.y * 0.005; this.camerarotationx -= relDelta.x * 0.005; } else if(gkCore.mouse.moveType === gkCore.mouse.HOLDMIDDLE) { this.camerapany += relDelta.y * (0.002 * this.cameraRadius); this.camerapanx -= relDelta.x * (0.002 * this.cameraRadius); } this.cameraRadius *= (1.0 - relDelta.z * 0.25); let rot = gkCore.math.quat.create(); gkCore.math.quat.rotateY(rot, rot, this.camerarotationx); gkCore.math.quat.rotateX(rot, rot, this.camerarotationy); this.mainCamera.transform.rotation = rot; this.mainCamera.transform.position = this.cameraCenter; this.mainCamera.transform.translateLocal(gkCore.math.vec3.fromValues(this.camerapanx,this.camerapany,0)); this.mainCamera.transform.translateLocal(gkCore.math.vec3.fromValues(0,0,this.cameraRadius)); this.sceneMgr.update(); this.renderer.render(); } destory() { } updateShader() { if(this.vsp_source !== null && this.fsp_source !== null && this.vsp_source !== "" && this.fsp_source !== "") { let program = glw.createProgramObject(this.vsp_source, this.fsp_source); this.renderer.overrideProgram = program; } } bindShowObj( gameObject) { // load a mesh into gameobject struct if(this.holderGameObject !== null) { this.holderGameObject.transform.parent = null; } // bind it to scene root gameObject.transform.parent = gkCore.sceneMgr.getSceneRoot().transform; this.holderGameObject = gameObject; // camera target reset let mrs = gameObject.transform.getComponent( gkCore.Component.MeshRenderer ); let aabbTotal = gkCore.mathext.aabb.create(); mrs.forEach( meshRenderer => { let aabb = meshRenderer.bounds; gkCore.mathext.aabb.mergeAABB(aabbTotal, aabb); }); this.cameraCenter = gkCore.mathext.aabb.center(gkCore.math.vec3.create(), aabbTotal); this.cameraRadius = gkCore.mathext.aabb.radius(aabbTotal) * 1.5; this.camerapanx = 0; this.camerapany = 0; //console.info(aabbTotal); if( isNaN( this.cameraCenter[0] )) { this.cameraCenter = gkCore.math.vec3.create(); this.cameraRadius = 100.0; } console.info(this.cameraCenter); console.log(this.cameraRadius); } } module.exports = ShaderMonkiFramework;
29.011111
118
0.604941
b19245ebd9c4c309e605706ae3e179062ffdd00b
507
js
JavaScript
rollup.config.js
ChrisCinelli/monkeypatcher
6834311e0e6fd9cf97b8a6185b79b23d6a8e0e23
[ "MIT" ]
null
null
null
rollup.config.js
ChrisCinelli/monkeypatcher
6834311e0e6fd9cf97b8a6185b79b23d6a8e0e23
[ "MIT" ]
null
null
null
rollup.config.js
ChrisCinelli/monkeypatcher
6834311e0e6fd9cf97b8a6185b79b23d6a8e0e23
[ "MIT" ]
null
null
null
import nodeResolve from 'rollup-plugin-node-resolve'; import babel from 'rollup-plugin-babel'; const output = { file: 'dist/index.js', format: 'cjs', outro: ` module.exports = exports['default']; for (var m in exports) { module.exports[m] = exports[m]; } `, sourcemap: true, }; export default { input: './index.js', output, plugins: [ nodeResolve({ module: true, jsnext: true }), babel({ exclude: 'node_modules/**', runtimeHelpers: true }) ], };
16.354839
53
0.601578
b1944568947fb73e461062808364fc194d01f20d
3,865
js
JavaScript
test/suite/hash.js
riv0manana/argon2-browser
bb0d359a62dd6e36aa6189aebd0a945203fc5d93
[ "MIT" ]
2
2021-06-25T09:44:06.000Z
2021-06-25T10:37:16.000Z
test/suite/hash.js
riv0manana/argon2-browser
bb0d359a62dd6e36aa6189aebd0a945203fc5d93
[ "MIT" ]
null
null
null
test/suite/hash.js
riv0manana/argon2-browser
bb0d359a62dd6e36aa6189aebd0a945203fc5d93
[ "MIT" ]
null
null
null
describe('argon2.hash', function() { const { assert } = chai; it('should compute hash', async function() { const hash = await argon2.hash({ pass: 'p@ssw0rd', salt: 'somesalt' }); assert.ok(hash); assert.deepStrictEqual(hash.hash, new Uint8Array([ 36, 99, 163, 35, 223, 30, 71, 14, 26, 134, 8, 54, 243, 110, 116, 23, 61, 129, 40, 65, 101, 227, 197, 230 ])); assert.strictEqual(hash.hashHex, '2463a323df1e470e1a860836f36e74173d81284165e3c5e6'); assert.strictEqual(hash.encoded, '$argon2d$v=19$m=1024,t=1,p=1$c29tZXNhbHQ$JGOjI98eRw4ahgg28250Fz2BKEFl48Xm'); }); it('should be able to work several times', async function() { let hash = await argon2.hash({ pass: 'p@ssw0rd', salt: 'somesalt' }); assert.ok(hash); assert.strictEqual(hash.hashHex, '2463a323df1e470e1a860836f36e74173d81284165e3c5e6'); assert.strictEqual(hash.encoded, '$argon2d$v=19$m=1024,t=1,p=1$c29tZXNhbHQ$JGOjI98eRw4ahgg28250Fz2BKEFl48Xm'); hash = await argon2.hash({ pass: 'p@ssw0rd2', salt: 'somesalt' }); assert.ok(hash); assert.strictEqual(hash.hashHex, 'f02360855fe22752362451bcd41206041304ce7908b5645b'); assert.strictEqual(hash.encoded, '$argon2d$v=19$m=1024,t=1,p=1$c29tZXNhbHQ$8CNghV/iJ1I2JFG81BIGBBMEznkItWRb'); }); it('should compute hash for Argon2d', async function() { const hash = await argon2.hash({ pass: 'p@ssw0rd', salt: 'somesalt', type: argon2.ArgonType.Argon2d }); assert.strictEqual(hash.encoded, '$argon2d$v=19$m=1024,t=1,p=1$c29tZXNhbHQ$JGOjI98eRw4ahgg28250Fz2BKEFl48Xm'); }); it('should compute hash for Argon2i', async function() { const hash = await argon2.hash({ pass: 'p@ssw0rd', salt: 'somesalt', type: argon2.ArgonType.Argon2i }); assert.strictEqual(hash.encoded, '$argon2i$v=19$m=1024,t=1,p=1$c29tZXNhbHQ$I4odzyBxoIvAnqjao5xt4/xS02zts+Jb'); }); it('should compute hash for Argon2id', async function() { const hash = await argon2.hash({ pass: 'p@ssw0rd', salt: 'somesalt', type: argon2.ArgonType.Argon2id }); assert.strictEqual(hash.encoded, '$argon2id$v=19$m=1024,t=1,p=1$c29tZXNhbHQ$dF4LZGqnznPWATUG/6m1Yp/Id1nKVSlk'); }); it('should compute hash with different time complexity', async function() { const hash = await argon2.hash({ pass: 'p@ssw0rd', salt: 'somesalt', time: 10 }); assert.strictEqual(hash.encoded, '$argon2d$v=19$m=1024,t=10,p=1$c29tZXNhbHQ$uo6bzQ2Wjb9LhxGoSHnaMrIOAB/6dGAS'); }); it('should compute hash with different memory complexity', async function() { const hash = await argon2.hash({ pass: 'p@ssw0rd', salt: 'somesalt', mem: 2048 }); assert.strictEqual(hash.encoded, '$argon2d$v=19$m=2048,t=1,p=1$c29tZXNhbHQ$6OXzaE6bdwMuoUqJt5U1TCrfJBF/8X3O'); }); it('should compute hash with different length', async function() { const hash = await argon2.hash({ pass: 'p@ssw0rd', salt: 'somesalt', hashLen: 32 }); assert.strictEqual(hash.encoded, '$argon2d$v=19$m=1024,t=1,p=1$c29tZXNhbHQ$3w1C/UXK5b+K9eGlhctsuw1TivVU1JFCmB+DmM+MIiY'); }); it('should compute hash with different parallelism', async function() { const hash = await argon2.hash({ pass: 'p@ssw0rd', salt: 'somesalt', parallelism: 4 }); assert.strictEqual(hash.encoded, '$argon2d$v=19$m=1024,t=1,p=4$c29tZXNhbHQ$0/nLmgLRIKqzzOET6/YYHgZrp0xJjACg'); }); });
39.040404
129
0.598448
b19543aaa2fb7d3ed8fa50395d4ff8a78848bcaf
181
js
JavaScript
src/app/index.js
Konstantin-Ushakov/django-react-heroku-csrf
7703ddc714864e615f69e1ac94fc483dae33dff2
[ "Apache-2.0" ]
null
null
null
src/app/index.js
Konstantin-Ushakov/django-react-heroku-csrf
7703ddc714864e615f69e1ac94fc483dae33dff2
[ "Apache-2.0" ]
null
null
null
src/app/index.js
Konstantin-Ushakov/django-react-heroku-csrf
7703ddc714864e615f69e1ac94fc483dae33dff2
[ "Apache-2.0" ]
null
null
null
import React from "react"; import CsrfScene from '../scenes/csrf'; function App() { return ( <div className="App"> <CsrfScene /> </div> ); } export default App;
13.923077
39
0.60221
b19600a053a2930927f6e3a4a6f447e024045030
335
js
JavaScript
src/tool/transformtools/nw-resize-tool.js
eclipseglory/mulin
17577e77f7814579c237680563172091103d1921
[ "Apache-2.0" ]
10
2021-07-06T04:57:33.000Z
2022-01-19T09:08:26.000Z
src/tool/transformtools/nw-resize-tool.js
eclipseglory/mulin
17577e77f7814579c237680563172091103d1921
[ "Apache-2.0" ]
14
2020-06-14T20:20:55.000Z
2021-06-22T16:36:38.000Z
src/tool/transformtools/nw-resize-tool.js
eclipseglory/mulin
17577e77f7814579c237680563172091103d1921
[ "Apache-2.0" ]
2
2021-07-28T07:47:33.000Z
2021-11-15T12:44:23.000Z
import ScaleTool from "./scale-tool.js"; export default class NWResizeTool extends ScaleTool { constructor(f, m, b) { super(f, m, b, 'nw-resize'); } getTransformAnchor(feedback) { return { x: feedback.width, y: feedback.height }; } processDx(dx) { return -dx }; processDy(dy) { return -dy }; }
25.769231
57
0.61194
b1962c26c078ac6ea9f0640b2056e6bd8f85b9b3
278
js
JavaScript
src/services/localstorageService.js
dev-algosolver/sharetribe-flex-web
5f9382f9e0a99d1e41f970ee6f0c8eb81c847deb
[ "Apache-2.0" ]
null
null
null
src/services/localstorageService.js
dev-algosolver/sharetribe-flex-web
5f9382f9e0a99d1e41f970ee6f0c8eb81c847deb
[ "Apache-2.0" ]
null
null
null
src/services/localstorageService.js
dev-algosolver/sharetribe-flex-web
5f9382f9e0a99d1e41f970ee6f0c8eb81c847deb
[ "Apache-2.0" ]
null
null
null
export const setLSItem = (key,value)=>{ localStorage.setItem(key,JSON.stringify(value)) } const updateLSItem = ()=>{} export const getLSItem = (key)=>{ return JSON.parse(localStorage.getItem(key)) } export const deleteLSItem = (key)=>{ localStorage.removeItem(key) }
27.8
51
0.705036
b196acf94332c37563018c08232c3b8d463a7587
1,107
js
JavaScript
ethapi/format/transaction.js
jacogr/ethrpc-webrtc-bridge
8cd4923c0788dc08c9d028e28921719482418a28
[ "MIT" ]
1
2022-01-27T08:47:25.000Z
2022-01-27T08:47:25.000Z
ethapi/format/transaction.js
jacogr/ethrpc-webrtc-bridge
8cd4923c0788dc08c9d028e28921719482418a28
[ "MIT" ]
null
null
null
ethapi/format/transaction.js
jacogr/ethrpc-webrtc-bridge
8cd4923c0788dc08c9d028e28921719482418a28
[ "MIT" ]
null
null
null
// @flow const { toChecksumAddress } = require('ethereumjs-util'); const { hexToBn } = require('./bn'); /*:: export type TransactionType = { blockNumber: BN, creates: ?string, from: string, gas: BN, gasPrice: BN, networkId: number, nonce: BN, to: string, value: BN } */ function transactionOutput (tx/*: any */)/*: TransactionType */ { return Object .keys(tx) .reduce((result/*: TransactionType */, key/*: string */) => { switch (key) { case 'blockNumber': case 'gas': case 'gasPrice': case 'nonce': case 'value': result[key] = hexToBn(tx[key]); break; case 'creates': case 'from': case 'to': result[key] = tx[key] ? toChecksumAddress(tx[key]) : tx[key]; break; case 'networkId': result[key] = parseInt(tx[key], 10); break; default: result[key] = tx[key]; break; } return result; }, ({}/*: $Shape<TransactionType> */)); } module.exports = { transactionOutput };
19.767857
65
0.513098
b19823c132c64f479fc9d0f49a03a781b1ae93fa
3,136
js
JavaScript
server.js
MilanSusa/Molecious-frontend
3cefeef889d8529f5b2499d35dfeac9a3125e98b
[ "MIT" ]
null
null
null
server.js
MilanSusa/Molecious-frontend
3cefeef889d8529f5b2499d35dfeac9a3125e98b
[ "MIT" ]
null
null
null
server.js
MilanSusa/Molecious-frontend
3cefeef889d8529f5b2499d35dfeac9a3125e98b
[ "MIT" ]
null
null
null
const express = require('express'); const bodyParser = require('body-parser'); const axios = require('axios'); const cookieParser = require('cookie-parser'); const path = require('path'); const FormData = require('form-data'); const multer = require('multer'); const upload = multer(); const app = express(); const port = process.env.PORT || 4000; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.post('/api/v1/users/sign-up', async (req, res) => { try { await axios.post(process.env.MOLECIOUS_BACKEND_URL + '/api/v1/users/sign-up', { firstName: req.body.firstName, lastName: req.body.lastName, email: req.body.email, password: req.body.password }); res.sendStatus(200); } catch (err) { res.status(400).send(err.response.data); } }); app.post('/api/v1/users/authenticate', async (req, res) => { try { const response = await axios.post(process.env.MOLECIOUS_BACKEND_URL + '/api/v1/users/authenticate', { username: req.body.username, password: req.body.password }); res.cookie('JWT', response.data.data.jwt, { httpOnly: true }); res.sendStatus(200); } catch (err) { res.status(400).send(err.response.data); } }); app.post('/api/v1/users/logout', (req, res) => { res.clearCookie('JWT'); res.sendStatus(200); }); app.post('/api/v1/users/jwt', async (req, res) => { try { const response = await axios.post(process.env.MOLECIOUS_BACKEND_URL + '/api/v1/users/jwt', null, { headers: { 'Cookie': `JWT=${req.cookies['JWT']}` } }); res.send(response.data); } catch (err) { res.status(400).send(err.response.data); } }); app.post('/api/v1/inferences', upload.single('file'), async (req, res) => { try { const formData = new FormData(); formData.append('file', req.file.buffer, { filename: req.file.originalname }); const response = await axios.post(process.env.MOLECIOUS_BACKEND_URL + '/api/v1/inferences', formData, { headers: { ...formData.getHeaders(), 'Cookie': `JWT=${req.cookies['JWT']}` } }); res.send(response.data); } catch (err) { res.status(400).send(err.response.data); } }); app.get('/api/v1/inferences/users/jwt', async (req, res) => { try { const response = await axios.get(process.env.MOLECIOUS_BACKEND_URL + '/api/v1/inferences/users/jwt', { headers: { 'Cookie': `JWT=${req.cookies['JWT']}` } }); res.send(response.data); } catch (err) { res.status(400).send(err.response.data); } }); if (process.env.NODE_ENV === 'production') { app.use(express.static(path.join(__dirname, 'client/build'))); app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'client/build', 'index.html')); }); } app.listen(port, () => console.log(`Listening on port ${port}`));
30.745098
111
0.573342
b19836525020ff9c67ea7a15d24a3805504a4492
224
js
JavaScript
vendor/RxJS/add/operator/auditTime.js
mgechev/closure-compiler-angular-bundling
0887631ec6bf8423ecc245e523b023f06bb6d7ee
[ "MIT" ]
9
2016-08-22T21:16:00.000Z
2018-11-27T20:09:49.000Z
vendor/RxJS/add/operator/auditTime.js
mgechev/closure-compiler-angular-bundling
0887631ec6bf8423ecc245e523b023f06bb6d7ee
[ "MIT" ]
null
null
null
vendor/RxJS/add/operator/auditTime.js
mgechev/closure-compiler-angular-bundling
0887631ec6bf8423ecc245e523b023f06bb6d7ee
[ "MIT" ]
7
2016-08-22T21:16:03.000Z
2020-05-15T11:49:31.000Z
goog.module('rxjs$add$operator$auditTime'); var Observable_1 = goog.require('rxjs$Observable'); var auditTime_1 = goog.require('rxjs$operator$auditTime'); Observable_1.Observable.prototype.auditTime = auditTime_1.auditTime;
44.8
68
0.803571
b199d42e289e38a9338578aa24cf4f3406c3f64d
2,819
js
JavaScript
test/test.js
edewit/rollup-plugin-license
f22294c56873c1f03b5e44293f73c882e1c30e8b
[ "MIT" ]
null
null
null
test/test.js
edewit/rollup-plugin-license
f22294c56873c1f03b5e44293f73c882e1c30e8b
[ "MIT" ]
null
null
null
test/test.js
edewit/rollup-plugin-license
f22294c56873c1f03b5e44293f73c882e1c30e8b
[ "MIT" ]
null
null
null
'use strict' const test = require('mvt') const { run, plugin } = require('./../index') const { resolve: resolvePath, join } = require('path') const { rollup: rollupLatest } = require('rollup') const { rollup: rollup60 } = require('rollup60') const { rollup: rollup100 } = require('rollup100') const fixtures = resolvePath(__dirname, '_fixtures') // const importA = 'the-declaration-of-independence' const baseOpts = { input: join(fixtures, 'bundle-a.js'), output: { format: 'cjs' } } // test against many versions of rollup const rollers = [ { rollup: rollupLatest, version: 'latest', opts: baseOpts }, { rollup: rollup100, version: '1.0.x', opts: baseOpts } ] test('require signature works destructured, direct, and as .default', (assert) => { const { plugin: destructured } = require('./../index') const direct = require('./../index') assert.true(typeof destructured === 'function') assert.true(typeof direct === 'function') assert.true(typeof direct.default === 'function') }) // main rollers.forEach(({ rollup, version, opts }) => { test(`${version}: modules returns array`, async (assert) => { const bundle = await rollup(opts) const results = await run(bundle) assert.truthy(Array.isArray(results.modules)) }) test(`${version}: license object has expected properties`, async (assert) => { const bundle = await rollup(opts) const result = await run(bundle) assert.truthy('modules' in result) const firstModule = result.modules[0] assert.truthy('id' in firstModule) assert.truthy('packageJson' in firstModule) assert.truthy('files' in firstModule) }) // test(`${version}: root works as expected`, async (assert) => { // const bundle = await rollup(opts) // assert.not( // join(__dirname, (await run(bundle, { root: 'fakepath' })).modules[0].files[0]), // resolvePath(fixtures, `${importA}.js`) // ) // assert.is( // join(__dirname, (await run(bundle, { root: __dirname })).modules[0].files[0]), // resolvePath(fixtures, `${importA}.js`) // ) // }) test(`${version}: it works with generated bundle as well`, async (assert) => { const bundle = await rollup(opts) await bundle.generate({ format: 'cjs' }) const results = await run(bundle) assert.is(typeof results, 'object') }) }) test('rollup < 1.0.0 prints warning about support', async (assert) => { let results = '' const oldCslErr = console.error console.error = (...args) => { results += args.join() } const rollOpts = Object.assign({ plugins: [plugin()] }, baseOpts) const bundle = await rollup60(rollOpts) await bundle.generate({ format: 'cjs' }) const expect = 'rollup-plugin-license-xml: Rollup version not supported' assert.is(results.split('\n')[0], expect) console.error = oldCslErr })
33.559524
88
0.652359
b199e6d870444f12b58944c94c5a83e6003e5e1b
35,519
js
JavaScript
src/flicking/Flicking.js
make-story/ui
9640cab11691513c6adf7d0d09062b6c3962522f
[ "MIT" ]
10
2016-06-14T08:44:32.000Z
2020-12-19T06:37:27.000Z
src/flicking/Flicking.js
make-story/ui
9640cab11691513c6adf7d0d09062b6c3962522f
[ "MIT" ]
6
2021-02-04T09:08:43.000Z
2022-03-02T12:49:49.000Z
src/flicking/Flicking.js
make-story/ui
9640cab11691513c6adf7d0d09062b6c3962522f
[ "MIT" ]
null
null
null
/** * Flicking */ /* - block node https://github.com/nhn/tui.editor/blob/master/apps/editor/src/js/utils/dom.js /^(ADDRESS|ARTICLE|ASIDE|BLOCKQUOTE|DETAILS|DIALOG|DD|DIV|DL|DT|FIELDSET|FIGCAPTION|FIGURE|FOOTER|FORM|H[\d]|HEADER|HGROUP|HR|LI|MAIN|NAV|OL|P|PRE|SECTION|UL)$/gi.test(''); */ import browser from '../browser'; import $ from '../dom'; import { extend, numberUnit, isNumeric, numberReturn, } from '../util'; import { requestAnimationFrame, cancelAnimationFrame, } from '../animate'; const EVENT_TRANSITION_FLICKING = 'EVENT_TRANSITION_FLICKING'; const EVENT_RESIZE_FLICKING = 'EVENT_RESIZE_FLICKING'; const EVENT_MOUSEDOWN_FLICKING = 'EVENT_MOUSEDOWN_FLICKING'; const EVENT_MOUSEMOVE_FLICKING = 'EVENT_MOUSEMOVE_FLICKING'; const EVENT_MOUSEUP_FLICKING = 'EVENT_MOUSEUP_FLICKING'; const EVENT_MOUSEWHEEL_FLICKING = 'EVENT_MOUSEWHEEL_FLICKING'; // node.children // Overwrites native 'children' prototype. // Adds Document & DocumentFragment support for IE9 & Safari. // Returns array instead of HTMLCollection. ;(function(constructor) { if (constructor && constructor.prototype && constructor.prototype.children == null) { Object.defineProperty(constructor.prototype, 'children', { get: function() { var i = 0, node, nodes = this.childNodes, children = []; while (node = nodes[i++]) { if (node.nodeType === 1) { children.push(node); } } return children; } }); } })(window.Node || window.Element); const setAnimate = (() => { if(browser.is.transform === true && browser.is.transition === true) { return ({ element, duration=0/*애니메이션 진행시간 (단위기준: 1s)*/, left=0/*translateX*/, top=0/*translateY*/, complete, }) => { // transform (GPU) try { element.style.webkitTransitionDuration = element.style.MozTransitionDuration = element.style.msTransitionDuration = element.style.OTransitionDuration = element.style.transitionDuration = `${Number(duration)}s`; element.style.webkitTransform = `translate(${left}px, ${top}px) translateZ(0)`; // translateZ : CSS GPU가속 사용을 위한 핵 (3d로 속여서 GPU가속 사용) element.style.msTransform = element.style.MozTransform = element.style.OTransform = `translate(${left}px, ${top}px)`; $(element).off(`${browser.event.transitionend}.${EVENT_TRANSITION_FLICKING}`).on(`${browser.event.transitionend}.${EVENT_TRANSITION_FLICKING}`, function(e) { let event = (typeof e === 'object' && e.originalEvent || e) || window.event; // originalEvent: jQuery Event let currentTarget = event.currentTarget; let target = event.target || event.srcElement; let propertyName = event.propertyName; // 트랜지션 실행된 프로퍼티명 (transform) //console.log('event', event); //console.log('currentTarget', currentTarget); //console.log('target', target); //console.log('propertyName', propertyName); if(currentTarget && target && currentTarget.isEqualNode(target)) { // complete 실행 if(typeof complete === 'function') { complete.call(element); } } }); }catch(e) { console.log(e); } }; }else { return ({ element, duration=0/*애니메이션 진행시간 (단위기준: 1s)*/, left=0, top=0, complete, }) => { // requestAnimationFrame / cancelAnimationFrame // ease const easeOutQuad = (t, b, c, d) => { return -c *(t/=d)*(t-2) + b; }; const easeInOutQuad = (t, b, c, d) => { if((t/=d/2) < 1) { return c/2*t*t + b; }else { return -c/2 * ((--t)*(t-2) - 1) + b; } }; let start = 0; // 애니메이션 시작값 (기존 css등 설정값) let end = 0; // 애니메이션 종료값 (사용자 설정값) let properties = { 'left': {}, 'top': {} }; let current = 0; let increment = 20; let request = null; let setFrame; element.style.position = 'absolute'; if(!duration) { element.style.left = `${left}px`; element.style.top = `${top}px`; }else { // duration 값 변경 duration = Number(duration) * 1000; // start, end 값 추출 start = Number(this.numberReturn(element.style.left) || 0); properties.left.start = start; properties.left.end = end = Number(left); properties.left.change = end - start; start = Number(this.numberReturn(element.style.top) || 0); properties.top.start = start; properties.top.end = end = Number(top); properties.top.change = end - start; // 애니메이션 프레임 함수 (반복실행) setFrame = function frame() { let key, value; // increment the time current += increment; for(key in properties) { value = easeInOutQuad(current, properties[key].start, properties[key].change, duration); element.style[key] = `${value}px`; } if(current < duration) { // frame request = requestAnimationFrame(frame); }else if(request) { cancelAnimationFrame(request); // complete 실행 if(typeof complete === 'function') { complete.call(element); } } }; if(request) { cancelAnimationFrame(request); } setFrame(); } }; } })(); // event passive let passiveSupported = false; try { const options = { get passive() { passiveSupported = true; } }; window.addEventListener("test", options, options); window.removeEventListener("test", options, options); }catch(error) { passiveSupported = false; } export default class Flicking { constructor(target=null, settings={}) { this.settings = { 'key': '', // 플리킹 작동 고유키 (선택) 'flow': 'horizontal', // 플리킹 방향 (가로:horizontal, 세로:vertical) 'width': 'auto', // 슬라이드 width 값 설정 (auto: 슬라이드가 target 가운데 위치하도록 wrap width 값에 따라 자동설정) 'height': 'auto', // 슬라이드 height 값 설정 (숫자, auto, min, max) - css height 값이 auto 경우 wrap height 값이 0으로 보이는 경우가 있다. 이 경우 wrap css 값 overflow: auto; 또는 :after { content: ""; display: block; clear: both; } 해결가능하다. 'centered': '', // auto / margin / padding 'speed': 300, // 슬라이드 속도 'touch': true, // 클릭 또는 터치 슬라이드 작동여부 'auto': 0, // 자동 슬라이드 작동여부 (0 이상의 값이 입력되면 작동합니다.) 'wheel': false, // 마우스 휠 이벤트 작동여부 'edge': true, // 가장자리 터치(클릭)시 슬라이드 이동여부 'listeners': { // 플리킹 작동 listeners (선택) 'initialize': null, 'next': null, 'prev': null, 'slidechange': null, 'append': null, 'remove': null, 'transitionend': null } }; this.settings = extend(this.settings, settings); this.elements = {}; this.total = 0; // 총 슬라이드 수 this.index = 1; // 현재 출력되고 있는 슬라이드 (1부터 시작) this.width = {}; // 플리킹 wrap width value, unit 값 this.height = {}; // 플리킹 wrap height value, unit 값 this.current = 0; // container 의 이동전(현재) translateX, left 또는 translateY, top 값 this.time = { 'auto': 0, // 자동슬라이드 time key 'resize': 0 }; if(this.settings.centered && (typeof this.settings.centered !== 'string' || !/margin|padding/i.test(this.settings.centered) || this.settings.centered.toLowerCase() === 'auto')) { this.settings.centered = 'margin'; } // target target = (typeof target === 'string' && /^[a-z]+/i.test(target) ? `#${target}` : target); this.elements.target = (typeof target === 'object' && target.nodeType ? target : $(target).get(0)); // initialize this.reset(); this.wrap(); this.view(); this.on(); this.auto({'mode': 'start'}); this.wheel({'mode': 'on'}); // resize event $(window).off(`resize.${EVENT_RESIZE_FLICKING}_${this.settings.key}`); if((typeof this.settings.width === 'string' && /auto|min|max/ig.test(this.settings.width)) || (typeof this.settings.height === 'string' && /auto|min|max/ig.test(this.settings.height))) { $(window).on(`resize.${EVENT_RESIZE_FLICKING}_${this.settings.key}`, (e) => { console.log('[플리킹 정보] resize event'); window.clearTimeout(this.time.resize); this.time.resize = window.setTimeout(() => { console.log('[플리킹 정보] resize set'); // 애니메이션 정지! this.wrap(); this.view(); }, 300); }); } // listeners if(typeof this.settings.listeners.initialize === 'function') { this.settings.listeners.initialize.call(this, this.elements.target); } } reset() { this.start = { "left": 0, "top": 0, "time": 0 }; this.end = { "left": 0, "top": 0, "time": 0 }; } // 설정값 변경 change(settings={}) { let key, temp; try { for(key in settings) { switch(key) { case 'listeners': for(temp in settings[key]) { if(settings[key].hasOwnProperty(temp)) { this.settings.listeners[temp] = settings[key][temp]; } } break; case 'width': case 'height': this.settings[key] = settings[key]; // resize event window.clearTimeout(this.time.resize); $(window).off(`resize.${EVENT_RESIZE_FLICKING}_${this.settings.key}`); if(this.settings[key] === 'auto') { $(window).on(`resize.${EVENT_RESIZE_FLICKING}_${this.settings.key}`, (e) => { window.clearTimeout(this.time.resize); this.time.resize = window.setTimeout(() => { // 애니메이션 정지! this.wrap(); this.view(); }, 300); }); } // this.wrap(); this.view(); break; } } }catch(e) {} return this; } // 플리킹(target) 감싸는 element width, style 등 설정 wrap() { let display; // flex 검사 let target = this.elements.target; let parent = target.parentNode; // target 상위 element let temp; let style = { 'parent': {}, 'target': {} }; let translate = { 'element': target, //'duration': Number(this.settings.speed) / 1000 'duration': 0 }; console.log('[플리킹 정보] parent', parent); // toLowerCase if(/^(horizontal|vertical)$/i.test(this.settings.flow) === false) { this.settings.flow = 'horizontal'; }else { this.settings.flow = this.settings.flow.toLowerCase(); } if(typeof this.settings.width === 'string') { this.settings.width = this.settings.width.toLowerCase(); } if(typeof this.settings.height === 'string') { this.settings.height = this.settings.height.toLowerCase(); } // slide this.elements.children = this.elements.target.children; // 슬라이드 elements (IE8 이하 사용 불가능) this.total = this.elements.children.length || 0; // width / height 초기값 this.width = { 'value': 0, 'unit': 'px' }; this.height = { 'value': 0, 'unit': 'px' }; // 사용자가 width / height 를 설정 if(isNumeric(this.settings.width)) { this.width = { 'value': Number(this.settings.width), 'unit': 'px' }; }else if(/^([0-9]+)(\D+)$/i.test(this.settings.width)) { temp = numberUnit(this.settings.width); this.width = { 'value': Number(temp[1]), 'unit': temp[2] }; } if(isNumeric(this.settings.height)) { this.height = { 'value': Number(this.settings.height), 'unit': 'px' }; }else if(/^([0-9]+)(\D+)$/i.test(this.settings.height)) { temp = numberUnit(this.settings.height); this.height = { 'value': Number(temp[1]), 'unit': temp[2] }; } // wrap 크기 정보 // auto (parent element의 width / height 를 구함) if((typeof this.settings.width === 'string' && /auto|min|max/ig.test(this.settings.width)) || (typeof this.settings.height === 'string' && /auto|min|max/ig.test(this.settings.height))) { // display // flow, flow-root, table, flex, ruby, grid, list-item // !/flow|table|flex|ruby|grid|list/ig.test(display) display = $(target).css('display'); //console.log('[플리킹 정보] display', display); // target 상위 parent element 의 정확한 값을 구하기 위해 플리킹 wrap 의 width / height 초기화 // float해제방식: overflow: hidden; 또는 부모요소 inline-block //$(target).css({'width': '0px', 'height': '0px', 'overflow': 'hidden'}); $(target).css({'display': 'none'}); if(this.settings.width === 'auto') { this.width = { 'value': Number(numberReturn($(parent).innerWidth()) || 0), 'unit': 'px' }; } if(this.settings.height === 'auto' && this.settings.flow === 'vertical') { this.height = { 'value': Number(numberReturn($(parent).innerHeight()) || 0), 'unit': 'px' }; } $(target).css({'display': display || ''}); //console.log('[플리킹 정보] wrap width', this.width); //console.log('[플리킹 정보] wrap height', this.height); } // style style.parent['position'] = 'relative'; style.parent['overflow'] = 'hidden'; style.target['height'] = 'auto'; style.target['user-select'] = 'none'; //style.target['touch-action'] = 'pan-y'; //style.target['-webkit-user-drag'] = 'none'; if(this.settings.flow === 'vertical') { style.target['width'] = `${this.width.value}px`; }else { style.target['width'] = `${(this.width.value * this.total)}px`; } $(parent).css(style.parent); $(target).css(style.target); // translate if(this.settings.flow === 'vertical') { translate.top = this.current = (this.height.value * (this.index - 1)) * -1; }else { translate.left = this.current = (this.width.value * (this.index - 1)) * -1; } setAnimate(translate); // resize 콜백 발생시 슬라이드 위치 초기화 return this; } // 슬라이드 element width, style 등 설정 view({ index/*해당 슬라이드 index*/, element/*해당 슬라이드 element*/, }={}) { let i, max; const setStyle = (element) => { let parent; // 상위 element let centered = this.settings.centered; let width = 0, height = 0; let rect = {}; let past = { // 기존 element 에 설정된 style 값 'min-width': '', 'max-width': '', 'min-height': '', 'max-height': '', 'display': '' }; let style = { // 슬라이드 기본 style 설정 값 'min-width': '0', // default value 0 'max-width': 'none', // default value none 'min-height': '0', // default value 0 'max-height': 'none', // default value none 'display': 'block' }; let temp; if(element) { parent = element.parentNode; element = $(element); // 가운데 정렬을 위한 초기화 if(centered) { temp = {}; if(this.settings.flow === 'vertical') { temp[`${centered}-top`] = '0px'; temp[`${centered}-bottom`] = '0px'; }else { temp[`${centered}-left`] = '0px'; temp[`${centered}-right`] = '0px'; } element.css(temp); } // 기존 style 값 저장 past['min-width'] = element.css('min-width'); past['max-width'] = element.css('max-width'); past['min-height'] = element.css('min-height'); past['max-height'] = element.css('max-height'); past['display'] = element.css('display'); console.log('[플리킹 정보] 대상 element 기존 style', past); // 슬라이드의 width / height 값 계산(정확한 width / height 값 반환을 위해 float: left 설정, max-width 값 초기화) // 플리킹을 위한 기본 style 설정 if(parent && /flow|table|flex|ruby|grid|list/ig.test(parent.style && parent.style.display || '')) { element.css({'min-width': '0', 'max-width': 'none', 'min-height': '0', 'max-height': 'none', 'position': 'relative'}); }else { element.css({'min-width': '0', 'max-width': 'none', 'min-height': '0', 'max-height': 'none', 'position': 'relative', 'float': 'left'}); } // 슬라이드 내부 이미지의 경우 정확한 width/height 값을 구하기 어려움! // border 값을 포함한 width / height 값 // 중앙정렬 조건이 padding 경우 width, height 값 확인 다시! width = Number(numberReturn(element.outerWidth()) || 0); height = Number(numberReturn(element.outerHeight()) || 0); console.log('[플리킹 정보] 슬라이드 사이즈 확인(outerWidth/outerHeight)', [width, height].join('/')); if(element.get(0) && typeof element.get(0).getBoundingClientRect === 'function') { // chrome 에서는 정수가 아닌 실수단위로 정확한 값을 요구하므로 getBoundingClientRect 사용 rect = element.get(0).getBoundingClientRect(); // width/height: IE9 이상 지원 if('width' in rect || 'height' in rect) { width = rect.width || width; height = rect.height || height; console.log('[플리킹 정보] 슬라이드 사이즈 확인(getBoundingClientRect)', [width, height].join('/')); } } // style (px, em, rem 에 따른 분기 작업필요) /*if(centered) { style[`${centered}-left`] = past[`${centered}-left`] || '0px'; style[`${centered}-right`] = past[`${centered}-right`] || '0px'; style[`${centered}-top`] = past[`${centered}-top`] || '0px'; style[`${centered}-bottom`] = past[`${centered}-bottom`] || '0px'; }*/ // width //console.log('[플리킹 정보] width', width); if(0 < this.width.value/* && this.width.value < width*/) { // 슬라이드 width 크기가 플리킹 wrap width 보다 클경우 강제 width 설정 style['max-width'] = `${this.width.value}px`; } if(centered) { // 양쪽 여백값 (슬라이드를 가운데 위치시키기 위함) style['min-width'] = `${width}px`; style[`${centered}-left`] = style[`${centered}-right`] = `${((this.width.value - width) / 2)}px`; }else { // 최소 가로 크기 (슬라이드 가로 크기) style['min-width'] = `${this.width.value}px`; } // height //console.log('[플리킹 정보] height', height); if(this.settings.flow === 'vertical') { if(0 < this.height.value/* && this.height.value < height*/) { // 슬라이드 height 크기가 플리킹 wrap height 보다 클경우 강제 height 설정 style['max-height'] = `${this.height.value}px`; } if(centered) { // 위아래 여백값 (슬라이드 가운데 위치시키기 위함) style['min-height'] = `${height}px`; style[`${centered}-top`] = style[`${centered}-bottom`] = `${((this.height.value - height) / 2)}px`; }else { // 최소 세로 크기 (슬라이드 세로 크기) style['min-height'] = `${this.height.value}px`; } } console.log('[플리킹 정보] style', style); element.css(style); } }; // element = index && this.elements.children[index-1] ? this.elements.children[index-1] : element; if(element) { setStyle(element); }else { for(i=0, max=this.total; i<max; i++) { setStyle(this.elements.children[i]); } } return this; } // 슬라이드 추가 append({ index='last'/*지정된 위치에 삽입 (last, first, 숫자)*/, html, element, }={}) { if(typeof html === 'string' && html.length > 0) { element = ((html) => { // getBoundingClientRect 사용을 위해 fragment 를 활용하지 않는다. // getBoundingClientRect 는 크롬에서의 소수점 단위의 정확한 width / height 값을 알기 위해 사용한다. let div = document.createElement('div'); div.innerHTML = html; return div.firstChild; // IE8 이하 사용 불가능 })(html); }else { element = $(element).get(0); } if(typeof element === 'object' && element.nodeType) { // index 값에 따라 해당 위치에 삽입 if(isNumeric(index)) { // 숫자 if(!this.elements.target.insertBefore(element, this.elements.children[index-1])) { return false; } }else if(typeof index === 'string') { // 문자 switch(index.toLowerCase()) { case 'first': if(!this.elements.target.insertBefore(element, this.elements.target.firstChild)) { return false; } break; case 'last': if(!this.elements.target.appendChild(element)) { return false; } break; } } // 정보 업데이트 this.elements.children = this.elements.target.children; // 슬라이드 elements (IE8 이하 사용 불가능) this.total = this.elements.children.length || 0; $(this.elements.target).css({'width': `${(this.settings.flow === 'vertical' ? this.width.value : (this.width.value * this.total))}px`}); // wrap width 수정 this.view({'index': this.total}); console.log('[플리킹 정보] append total', this.total); // listeners if(typeof this.settings.listeners.append === 'function') { this.settings.listeners.append.call(this, element); } } return this; } // 슬라이드 삭제 remove({ index='last'/*current, last, 숫자*/, }={}) { let element; let is = false; // 삭제 후 술라이드 이동 여부 (현재 슬라이드 삭제 등의 경우) const setDelete = (element) => { $(element).off(); if(typeof element === 'object' && element.nodeType && element.parentNode.removeChild(element)) { return true; }else { return false; } }; if(index) { if(isNumeric(index)) { // 숫자 if(index == this.index) { is = true; } element = this.elements.children[index-1]; }else if(typeof index === 'string') { // 문자 switch(index.toLowerCase()) { case 'current': is = true; element = this.index && this.elements.children[this.index-1]; break; case 'last': is = false; element = this.total && this.elements.children[this.total-1]; break; } } setDelete(element); }else { // 전체제거 for(index in this.elements.children) { setDelete(this.elements.children[index]); } } // 정보 업데이트 this.elements.children = this.elements.target.children; // 슬라이드 elements (IE8 이하 사용 불가능) this.total = this.elements.children.length || 0; $(this.elements.target).css({'width': `${(this.settings.flow === 'vertical' ? this.width.value : (this.width.value * this.total))}px`}); if(is) { this.slide({'index': 'prev'}); } // listeners if(typeof this.settings.listeners.remove === 'function') { this.settings.listeners.remove.call(this, this.elements.target); } return this; } // 슬라이드 위치 설정 slide({ index, duration, }={}) { index = index && typeof index === 'string' && String(index).toLowerCase() || index; // index 숫자이면 해당 index로 이동, next || prev 이면 해당 모드에 따라 이동 duration = isNumeric(duration) ? duration : Number(this.settings.speed) / 1000; let is = false; // 이동이 발생했는지 여부 let before = this.index; // 현재 슬라이드 index let after = this.index; // 이동할 슬라이드 index let translate = { 'element': this.elements.target, 'duration': duration }; // 해당 index 로 이동 switch(index) { case 'next': // 다음 슬라이드 이동 if(after < this.total) { after += 1; }/*else { // 처음으로 이동 after = 1; }*/ break; case 'prev': // 이전 슬라이드 이동 if(1 < after) { after -= 1; }/*else { // 마지막으로 이동 after = this.total; }*/ break; default: // index 값에 해당하는 index 로 이동 if(isNumeric(index)) { after = index; } } // 다음 또는 이전 이동이 발생했는지 확인 if(isNumeric(after) && 1 <= after && (before < after || before > after) && after <= this.total) { is = true; } // slide 이동 if(this.settings.flow === 'horizontal') { translate.left = this.current = (this.width.value * ((is ? after : before) - 1)) * -1; }else if(this.settings.flow === 'vertical') { translate.top = this.current = (this.height.value * ((is ? after : before) - 1)) * -1; } setAnimate(translate/*, complete*/); if(is) { // 값 변경 this.index = after; // listeners if(before < after && typeof this.settings.listeners.next === 'function') { // next this.settings.listeners.next.call(this, this.elements.target); }else if(before > after && typeof this.settings.listeners.prev === 'function') { // prev this.settings.listeners.prev.call(this, this.elements.target); } if(typeof this.settings.listeners.slidechange === 'function') { // slidechange this.settings.listeners.slidechange.call(this, this.elements.target); } } // auto this.auto({'mode': 'start'}); return true; } // 마우스, 터치 이벤트 설정 on() { const that = this; let rect = {}; /** * up */ const setUp = (event) => { //console.log('[플리킹 정보] MOUSEUP'); let self = event.currentTarget; // event listener element (event 실행 element) let target = event && event.target; // event 가 발생한 element //let touch = (event.touches && event.touches[0]) || (event.changedTouches && event.changedTouches[0]); let touch = event.changedTouches; // touchend let time; let left, top; let index, duration; let standard = { // 기준값 (이동) 'time': 100, 'move': 30, // 최소/최대 이동범위 'size': 6 // 화면 분할 기준 }; let is = false; const isChildren = (element) => { let i, max; for(i=0, max=this.total; i<max; i++) { if(this.elements.children[i].isEqualNode(element)) { return true; } } return false; }; // event.currentTarget; // event listener element (event 실행 element) // event.target; // event 가 발생한 element // 현재 이벤트의 기본 동작을 중단한다. (터치 디바이스에서 기본 이벤트를 중단시키면 슬라이드 내부 a 태그등이 작동을 안한다. 모바일에서는 user-select: none; CSS로 해결한다.) //event.preventDefault(); // 정지값 if(touch) { this.end.left = touch[0].clientX; this.end.top = touch[0].clientY; }else { this.end.left = event.clientX; this.end.top = event.clientY; } this.end.time = new Date().getTime(); time = Number(this.end.time) - Number(this.start.time); left = this.end.left - this.start.left; top = this.end.top - this.start.top; index = this.index; duration = Number(this.settings.speed) / 1000; /* 300 / 1000 */ // 이동 가능한지 검사 if(this.settings.flow === 'horizontal' && ((Math.abs(left) > Math.abs(top)/*좌우 이동값이 더 큰 경우*/ && (time <= standard.time && standard.move <= Math.abs(left)/*마우스를 빠르게 이동한 경우*/)) || (this.width.value / standard.size) < Math.abs(left)/*슬라이드 크기 기준 어느정도 이동이 발생했을 때*/)) { if(index < this.total && left < 0) { // 다음 index++; }else if(1 < index && left > 0) { // 이전 index--; } // 슬라이드 속도 duration = (time > 1000 || 6000 < time) ? duration : (time+100) / 1000; }else if(this.settings.flow === 'vertical' && ((Math.abs(top) > Math.abs(left)/*상하 이동값이 더 큰 경우*/ && (time <= standard.time && standard.move <= Math.abs(top)/*마우스를 빠르게 이동한 경우*/)) || (this.height.value / standard.size) < Math.abs(top)/*슬라이드 크기 기준 어느정도 이동이 발생했을 때*/)) { if(index < this.total && top < 0) { // 다음 index++; }else if(1 < index && top > 0) { // 이전 index--; } // 슬라이드 속도 duration = (time > 1000 || 6000 < time) ? duration : (time+100) / 1000; }else if(typeof rect === 'object' && this.settings.edge === true && Math.abs(left) < standard.move && Math.abs(top) < standard.move && (this.elements.target.isEqualNode(target)/*슬라이드 영역*/ || (this.elements.target.contains(target)/*바로하위자식*/ && isChildren(target)))) { // 슬라이드 좌/우 또는 상/하 끝부분을 클릭(터치) 했을 경우 console.log('[플리킹 정보] 슬라이드 좌/우 또는 상/하 끝부분'); console.log('current slide', this.elements.children[this.index-1]); console.log('rect', rect); console.log('start', this.start); console.log('end', this.end); //console.log(rect.left <= this.end.left); //console.log(this.end.left <= rect.left+standard.move); //console.log(rect.right-standard.move <= this.end.left); //console.log(this.end.left <= rect.right); if(this.settings.flow === 'horizontal') { if(rect.left <= this.end.left && this.end.left <= rect.left+standard.move) { // 좌측기준 index--; }else if(rect.right-standard.move <= this.end.left && this.end.left <= rect.right) { // 우측기준 index++; } }else if(this.settings.flow === 'vertical') { if(rect.top <= this.end.top && this.end.top <= rect.top+standard.move) { // 상단기준 index--; }else if(rect.bottom-standard.move <= this.end.top && this.end.top <= rect.bottom) { // 하단기준 index++; } } } //console.log('slide element', this.elements.target); //console.log('target', target); /* // 로그 console.log('[플리킹 정보] 실행정보'); console.log(`index: ${this.index}`); console.log(`index: ${index}`); console.log(`duration: ${duration}`); console.dir(this.start); console.dir(this.end); */ // 슬라이드 이동이 예상되는 경우 기본 이벤트 정지(클릭 등 정지) if(index <= this.total && (this.index < index || index > this.index)) { event.preventDefault(); is = true; } // 슬라이드 이동 (transitionend 이벤트 발생됨) this.slide({'index': index, 'duration': duration}); // ---------- ---------- ---------- ---------- ---------- ---------- // 이벤트 정지 $(window).off(`.${EVENT_MOUSEMOVE_FLICKING}_${this.settings.key}`); $(window).off(`.${EVENT_MOUSEUP_FLICKING}_${this.settings.key}`); // auto this.auto({'mode': 'start'}); // initialize this.reset(); return is; }; /** * move */ const setMove = (event) => { //console.log('[플리킹 정보] MOUSEMOVE'); let self = event.currentTarget; // event listener element (event 실행 element) let target = event && event.target; // event 가 발생한 element //let touch = (event.touches && event.touches[0]) || (event.changedTouches && event.changedTouches[0]); let touch = event.touches || event.changedTouches; let left, top; let is = true; let translate = { 'element': this.elements.target, 'duration': 0 }; // event.currentTarget; // event listener element (event 실행 element) // event.target; // event 가 발생한 element // event.currentTarget.contains(event.target); // 특정 노드가 다른 노드 내에 포함되었는지 여부 // 마우스 element target 이 플리킹 내부 element 가 아니면 중지시킨다. //console.log('contains', this.elements.target.contains(target)); if(this.elements.target.contains(target) === false) { console.log('contains', target); setUp(event); /*this.slide({'index': this.index}); // 이벤트 정지 $(window).off(`.${EVENT_MOUSEMOVE_FLICKING}_${this.settings.key}`); $(window).off(`.${EVENT_MOUSEUP_FLICKING}_${this.settings.key}`); // auto this.auto({'mode': 'start'}); // initialize this.reset();*/ return false; } // 현재 이벤트의 기본 동작을 중단한다. if(this.settings.flow === 'vertical') { event.preventDefault(); } // 이동값 if(touch) { left = touch[0].clientX; top = touch[0].clientY; }else { left = event.clientX; top = event.clientY; } // 로그 /*console.log("left: " + left); console.log("this.start.left: " + this.start.left); console.log("top: " + top); console.log("this.start.top: " + this.start.top); console.log(Math.abs(left - this.start.left)); console.log(Math.abs(top - this.start.top));*/ // 슬라이드 영역 외 element 검사 /*if(!this.elements.target.contains(event.target)) { this.slide({'index': this.index, 'duration': Number(this.settings.speed) / 1000}); return false; }*/ // 사용자 터치가 브라우저 스크롤인지 슬라이드 이동 목적인지 확인하여 실행(안정화) if(this.settings.flow === 'horizontal' && Math.abs(left - this.start.left) > Math.abs(top - this.start.top)) { translate.left = (left - this.start.left) + this.current; }else if(this.settings.flow === 'vertical' && Math.abs(top - this.start.top) > Math.abs(left - this.start.left)) { translate.top = (top - this.start.top) + this.current; }else { is = false; } if(is) { // 현재 이벤트의 기본 동작을 중단한다. (슬라이드가 작동중일 때 모바일의 기본이벤트인 스크롤 작동을 중단시킨다.) event.preventDefault(); // slide 이동 setAnimate(translate); } return is; }; /** * down */ const setDown = (event) => { //console.log('[플리킹 정보] MOUSEDOWN'); let self = event.currentTarget; // event listener element (event 실행 element) let target = event && event.target; // event 가 발생한 element //let touch = (event.touches && event.touches[0]) || (event.changedTouches && event.changedTouches[0]); let touch = event.touches; // touchstart // 위치 / 크기 if(self.parentNode) { rect = self.parentNode.getBoundingClientRect(); } console.log('[플리킹 정보] element 값', self); console.log('[플리킹 정보] offset 값', `left(${self.offsetLeft}), top(${self.offsetTop}), width(${self.offsetWidth}), height(${self.offsetHeight})`); console.log('[플리킹 정보] client 값', `left(${self.clientLeft}), top(${self.clientTop}), width(${self.clientWidth}), height(${self.clientHeight})`); // 버블링(stopPropagation) 중지시키면, 상위 이벤트(예: document 에 적용된 이벤트)이 작동을 안한다. // 현재 이벤트의 기본 동작을 중단한다. (터치 디바이스에서 기본 이벤트를 중단시키면 스크롤이 작동을 안한다. 모바일에서는 user-select: none; CSS로 해결한다.) if(!browser.is.touch && /[^input|select|textarea|button]/i.test(target.tagName)) { // PC에서는 마우스 이벤트 정확도(기능 정상작동)를 올리기 위해 정지 event.preventDefault(); } // 멀티터치 방지 if(touch && touch.length && 1 < touch.length) { return; } // ---------- ---------- ---------- ---------- ---------- ---------- // 이벤트 정지 $(window).off(`.${EVENT_MOUSEMOVE_FLICKING}_${this.settings.key}`); $(window).off(`.${EVENT_MOUSEUP_FLICKING}_${this.settings.key}`); // auto this.auto({'mode': 'stop'}); // initialize this.reset(); // ---------- ---------- ---------- ---------- ---------- ---------- // 시작값 if(touch) { this.start.left = touch[0].clientX; this.start.top = touch[0].clientY; }else { this.start.left = event.clientX; this.start.top = event.clientY; } this.start.time = new Date().getTime(); }; // 이벤트 초기화 this.off(); if(this.settings.touch === true) { // down 이벤트 $(this.elements.target).on(`${browser.event.down}.${EVENT_MOUSEDOWN_FLICKING}_${this.settings.key}`, function(e) { setDown((typeof e === 'object' && e.originalEvent || e) || window.event); // originalEvent: jQuery Event // move 이벤트 $(window).on(`${browser.event.move}.${EVENT_MOUSEMOVE_FLICKING}_${that.settings.key}`, function(e) { setMove((typeof e === 'object' && e.originalEvent || e) || window.event); // originalEvent: jQuery Event }); // up 이벤트 $(window).on(`${browser.event.up}.${EVENT_MOUSEUP_FLICKING}_${that.settings.key}`, function(e) { setUp((typeof e === 'object' && e.originalEvent || e) || window.event); // originalEvent: jQuery Event }); }); // 트랜지션 (하위 자식 노드의 transition 전파에 따라 실행될 수 있다. 자식의 transition 전파를 막으려면 해당 자식 이벤트에 stopPropagation 실행) // 또는 addEventListener 를 사용하여, event.target 를 검사하여, 해당되는 element의 경우에만 콜백을 실행해야 한다. // transition 값이 여러개의 경우 각각의 프로퍼티별로 콜백이 실행된다. (left/top 두개 트랜지션이 설정되었을 경우, left/top 각각 콜백이 두번 실행된다.) if(typeof this.settings.listeners.transitionend === 'function') { $(this.elements.target).off(`${browser.event.transitionend}.${EVENT_TRANSITION_FLICKING}_${this.settings.key}`).on(`${browser.event.transitionend}.${EVENT_TRANSITION_FLICKING}_${this.settings.key}`, function(e) { let event = (typeof e === 'object' && e.originalEvent || e) || window.event; // originalEvent: jQuery Event let currentTarget = event.currentTarget; // event listener element let target = event.target || event.srcElement; // event 가 발생한 element let propertyName = event.propertyName; // 트랜지션 실행된 프로퍼티명 - horizontal/vertical 설정 값에 따라 left/top 둘 중 하나의 값 /*console.log(event); console.log(currentTarget); console.log(target);*/ if(currentTarget.isEqualNode(target)) { that.settings.listeners.transitionend.call(this, that.elements.target); } }); } } return this; } off() { $(window).off(`.${EVENT_MOUSEMOVE_FLICKING}_${this.settings.key}`); $(window).off(`.${EVENT_MOUSEUP_FLICKING}_${this.settings.key}`); $(this.elements.target).off(`.${EVENT_MOUSEDOWN_FLICKING}_${this.settings.key}`); $(this.elements.target).off(`.${EVENT_TRANSITION_FLICKING}_${this.settings.key}`); return this; } // 슬라이드 자동 플리킹 설정 auto({ mode, }={}) { mode = /^(start|stop)$/i.test(mode) && mode.toLowerCase() || 'stop'; window.clearTimeout(this.time.auto); if(mode === 'start' && this.settings.auto > 0) { this.time.auto = window.setTimeout(() => { if(this.index < this.total) { this.slide({'index': 'next'}); }else { this.slide({'index': 1}); } }, this.settings.auto); } return this; } // 마우스 휠 wheel({ mode, }={}) { const that = this; mode = /^(on|off)$/i.test(mode) && mode.toLowerCase() || 'off'; $(this.elements.target).off(`.${EVENT_MOUSEWHEEL_FLICKING}_${this.settings.key}`); if(mode === 'on' && this.settings.wheel === true) { $(this.elements.target).on(`${browser.event.wheel}.${EVENT_MOUSEWHEEL_FLICKING}_${this.settings.key}`, function(e) { let event = (typeof e === 'object' && e.originalEvent || e) || window.event; // originalEvent: jQuery Event let scroll; // 현재 이벤트의 기본 동작을 중단한다. event.preventDefault(); // if(event.wheelDelta) { scroll = event.wheelDelta / 3600; // Chrome / Safari }else if(event.detail) { scroll = event.detail / -90; // Mozilla }else { return false; } // scroll = 1 + scroll; // Zoom factor: 0.9 / 1.1 if(scroll > 1) { // prev that.slide({'index': 'prev'}); }else if(scroll < 1) { // next that.slide({'index': 'next'}); }else { return false; } }); } } }
32.348816
269
0.600467
b19a34d718bd44b9de9580c11806894d880041f2
160
js
JavaScript
packages/@sanity/components/src/buttons/DefaultButton.js
coreyward/sanity
3033f230bcea9cb7adb84e6ccdbb3467e45c6a6b
[ "MIT" ]
15
2018-08-15T04:41:24.000Z
2022-02-02T15:41:52.000Z
packages/@sanity/components/src/buttons/DefaultButton.js
crazyrex/sanity
6bba644798fbf923852f944cd9adb28133b27c35
[ "MIT" ]
219
2018-01-18T10:35:20.000Z
2022-03-20T03:27:45.000Z
packages/@sanity/components/src/buttons/DefaultButton.js
crazyrex/sanity
6bba644798fbf923852f944cd9adb28133b27c35
[ "MIT" ]
5
2019-05-21T14:25:04.000Z
2020-05-09T17:58:30.000Z
import createButtonLike from './createButtonLike' export default createButtonLike('button', { displayName: 'BaseButton', defaultProps: {type: 'button'} })
22.857143
49
0.75
b19a8b2b7669a5dfd2c5bf831ac3c176d603060b
323
js
JavaScript
apps/core/static/js/copy.js
Visualway/Vitary
c7db9a25837fa7390b2177b9db48e73c6f1ab3c8
[ "BSD-3-Clause" ]
4
2021-12-24T16:07:44.000Z
2022-03-04T02:30:20.000Z
apps/core/static/js/copy.js
Visualway/Vitary
c7db9a25837fa7390b2177b9db48e73c6f1ab3c8
[ "BSD-3-Clause" ]
4
2021-12-30T13:32:56.000Z
2022-03-15T03:58:48.000Z
apps/core/static/js/copy.js
Visualway/Vitary
c7db9a25837fa7390b2177b9db48e73c6f1ab3c8
[ "BSD-3-Clause" ]
null
null
null
function copyLink(id) { var copyText = "https://vitary.pythonanywhere.com/vit/" + id + "/"; navigator.clipboard.writeText(copyText); document.getElementById("copyLink_" + id).innerHTML = "Copied!"; setTimeout(function () { document.getElementById("copyLink" + id).innerHTML = "Copy"; }, 2000); }
40.375
71
0.656347
b19b1ed22432c3685c7c55e94e33b229e6aa5f63
1,011
js
JavaScript
test/test-app-javascript.js
imnotjames/generator-phaser-unofficialest
36c65d329e9a6bada6bbf7cab17896ea94e2bc5b
[ "MIT" ]
1
2015-12-23T04:10:04.000Z
2015-12-23T04:10:04.000Z
test/test-app-javascript.js
imnotjames/generator-phaser-unofficialest
36c65d329e9a6bada6bbf7cab17896ea94e2bc5b
[ "MIT" ]
1
2015-07-12T15:34:58.000Z
2015-07-12T15:39:42.000Z
test/test-app-javascript.js
imnotjames/generator-phaser-unofficialest
36c65d329e9a6bada6bbf7cab17896ea94e2bc5b
[ "MIT" ]
null
null
null
'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; var assert = require('yeoman-generator').assert; describe('phaser generator:app js', function () { before(function (done) { helpers.run(path.join( __dirname, '../generators/app' )) .withPrompts({ scriptLanguage: 'javascript' }) .on('end', done); }); it('creates a javascript-oriented gruntfile', function(done) { assert.fileContent('Gruntfile.js', /browserify: \{/); assert.fileContent('Gruntfile.js', /'browserify:app'/); assert.noFileContent('Gruntfile.js', /'ts:app'/); assert.noFileContent('Gruntfile.js', /ts: \{/); done(); }); it('creates javascript files', function (done) { assert.file([ 'src/assets/scripts/index.js', 'src/assets/scripts/Game/index.js', 'src/assets/scripts/Game/States/index.js', 'src/assets/scripts/Game/States/boot.js', 'src/assets/scripts/Game/States/mainmenu.js', 'src/assets/scripts/Game/States/preload.js' ]); done(); }); });
25.275
63
0.665678
b19b28bb10bd973d294364397afc5869b3318fe1
3,586
js
JavaScript
app/components/Catalog.js
dedan/ape-db
a21916e0751363b2da083242c1caf8628a7cc4ca
[ "MIT" ]
null
null
null
app/components/Catalog.js
dedan/ape-db
a21916e0751363b2da083242c1caf8628a7cc4ca
[ "MIT" ]
6
2021-01-28T19:59:03.000Z
2022-03-25T18:46:23.000Z
app/components/Catalog.js
dedan/ape-db
a21916e0751363b2da083242c1caf8628a7cc4ca
[ "MIT" ]
null
null
null
import React, {Component} from 'react'; import path from 'path' import { Link } from 'react-router-dom'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; import Chip from 'material-ui/Chip'; import {green300, red300, blue300, green100, red100, blue100} from 'material-ui/styles/colors'; export default class Catalog extends Component { render() { const {bookId, bookPages, entries, dispatch} = this.props return <div> <Table selectable={false}> <TableHeader displaySelectAll={false} adjustForCheckbox={false}> <TableRow> <TableHeaderColumn style={{width: 100}}>Image</TableHeaderColumn> <TableHeaderColumn style={{width: 100}}>Page</TableHeaderColumn> <TableHeaderColumn> <span>Entries</span> <ColoredChip isLight={true} status="valid" label="valid" /> <ColoredChip isLight={true} status="invalid" label="invalid" /> <ColoredChip isLight={true} status="placeholder" label="placeholder" /> </TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={false}> {bookPages.map(page => { return <TableRow key={page.pageId}> <TableRowColumn style={{width: 100}}> <Thumbnail page={page} size={100} /> </TableRowColumn> <TableRowColumn style={{width: 100}}> <Link to={`/current-page/${bookId}/${page.pageId}`}>{page.pageId}</Link> </TableRowColumn> <TableRowColumn> <div style={{display: 'flex', flexWrap: 'wrap'}}> {(page.entries || []).map((entryId, i) => { return <EntryChip key={entryId} bookId={bookId} pageId={page.pageId} entry={entries[entryId]} /> })} </div> </TableRowColumn> </TableRow> })} </TableBody> </Table> <ul> </ul> </div> } } const CHIP_STATUS_COLORS = { valid: green300, invalid: red300, placeholder: blue300, } const LIGHT_CHIP_STATUS_COLORS = { valid: green100, invalid: red100, placeholder: blue100, } const EntryChip = ({bookId, pageId, entry}) => { const entryStatus = entry.isPlaceholder ? 'placeholder' : entry.isValidated ? entry.isValid ? 'valid' : 'invalid' : null const entryUrl = `/current-page/${bookId}/${pageId}/${entry.entryId}` return <Link to={entryUrl}> <ColoredChip style={{cursor: 'pointer'}} status={entryStatus} label={entry.form} /> </Link> } const ColoredChip = ({status, label, style, isLight}) => ( <Chip backgroundColor={isLight ? LIGHT_CHIP_STATUS_COLORS[status] : CHIP_STATUS_COLORS[status]} style={{margin: 4, ...style}}> {label} </Chip> ) const Thumbnail = ({page, size}) => { const filePath = 'file://' + page.thumbnail const style= { display: 'flex', alignItems: 'center', justifyContent: 'center', } const placeholderStyle = { display: 'flex', alignItems: 'center', justifyContent: 'center', width: size, height: size, flexDirection: 'column', color: '#bbb', } return ( <div style={style}> {page.thumbnail ? <img src={filePath} width={size} height={size} /> : <div style={placeholderStyle}> <div>🐒</div> <div>missing</div> </div>} </div> ) }
28.919355
95
0.571946
b19ba8ec62a60a28def02ea8633052e80b13b6e1
1,520
js
JavaScript
src/Views/Widgets/Pill/PillStyles.js
nmachine-io/ui-js
21a2674c5b515957ebe9eea0de1f9bd33fb30ec9
[ "MIT" ]
null
null
null
src/Views/Widgets/Pill/PillStyles.js
nmachine-io/ui-js
21a2674c5b515957ebe9eea0de1f9bd33fb30ec9
[ "MIT" ]
21
2021-08-28T12:02:34.000Z
2021-09-08T20:52:13.000Z
src/Views/Widgets/Pill/PillStyles.js
nmachine-io/ui-js
21a2674c5b515957ebe9eea0de1f9bd33fb30ec9
[ "MIT" ]
null
null
null
// noinspection NpmUsedModulesInstalled import styled, {css} from 'styled-components' import {colorKeys, commonSizeAttrs} from '../../../styles/constants' import {easyColor} from "../../../styles/utils"; import Layout from "../../../styles/layout-styles"; const borderRad = "5.0px"; const borderWidth = "0.0px"; const vertPadding = 3.5; const Letter = styled.p` width: 18px; border-width: ${borderWidth}; text-align: center; border-style: solid none; border-radius: 0; border-color: ${p => easyColor(p, null, colorKeys.primaryColor)}; background: ${p => easyColor(p, p.emotion, colorKeys.cool)}; color: ${p => easyColor(p, null, colorKeys.contrastColor)}; padding: ${vertPadding}px 0; &:last-child{ border-style: solid solid solid none; border-radius: 0 ${borderRad} ${borderRad} 0; } `; const Text = styled.p` background: #f7f6f6; color: ${p => easyColor(p, p.emotion, 'primaryBkg')}; border-style: solid none solid solid; border-radius: ${borderRad} 0 0 ${borderRad}; border-width: ${borderWidth}; border-color: ${p => easyColor(p, null, colorKeys.primaryColor)}; padding: ${vertPadding}px 6px; ${p => childlessPillStyle(p)}; `; function childlessPillStyle(p){ if(p.childCount < 1){ return css` border-radius: ${borderRad}; border-style: solid; `; } } // noinspection JSUnresolvedFunction const Container = styled(Layout.Div)` ${commonSizeAttrs}; display: inline-flex; `; const S = { Text, Container, Letter } export default S;
24.918033
68
0.669737
b19d2a5b87f9dfc89a2f954cb9459c70434d235d
1,760
js
JavaScript
server/src/services/api.js
sibartlett/methodical
9f0d48b3c265ac987a5bf1661f213beda8e5f302
[ "MIT" ]
null
null
null
server/src/services/api.js
sibartlett/methodical
9f0d48b3c265ac987a5bf1661f213beda8e5f302
[ "MIT" ]
null
null
null
server/src/services/api.js
sibartlett/methodical
9f0d48b3c265ac987a5bf1661f213beda8e5f302
[ "MIT" ]
null
null
null
const MongoClient = require('mongodb').MongoClient; const mongoService = require('feathers-mongodb'); const withJsonPatch = require('feathers-json-patch'); const createService = withJsonPatch(mongoService); const newService = ({ db, prefix, ...options }) => { let cache = {}; let getService; if (options.Model) { cache = createService(options); getService = () => cache; } else { getService = (params) => { const { route: { collection } } = params; if (!cache[collection]) { cache[collection] = createService({ ...options, Model: db.collection(`${prefix || ''}${collection}`) }); } return cache[collection]; }; } return { find: (params) => getService(params).find(params), get: (id, params) => getService(params).get(id, params), create: (data, params) => getService(params).create(data, params), remove: (id, params) => getService(params).remove(id, params), update: (id, data, params) => getService(params).update(id, data, params), patch: (id, data, params) => getService(params).patch(id, data, params), }; }; module.exports = app => { MongoClient.connect('mongodb://localhost:27017/feathers', { useNewUrlParser: true }).then(client => { app.use('/api/schemas', newService({ Model: client.db('feathers').collection('schemas') })); app.use('/api/documents/:collection', newService({ db: client.db('feathers'), prefix: 'documents/' })); app.use('/api/document', { patch(id, data, params) { return Promise.resolve(data); }, find() { return Promise.resolve(schemas); }, get(id) { return Promise.resolve(schemas[id]); } }); }); };
27.5
103
0.594318
b19d3b9b050a0d218a4ed96e39da828932fa7fdf
1,212
js
JavaScript
commons_remove/css/images.js
smalltowngame/webapp
42b9935ec34703c69c4540e86f72fe1ba7c28414
[ "BSD-Source-Code" ]
1
2015-03-16T17:37:39.000Z
2015-03-16T17:37:39.000Z
commons_remove/css/images.js
smalltowngame/webapp
42b9935ec34703c69c4540e86f72fe1ba7c28414
[ "BSD-Source-Code" ]
null
null
null
commons_remove/css/images.js
smalltowngame/webapp
42b9935ec34703c69c4540e86f72fe1ba7c28414
[ "BSD-Source-Code" ]
1
2017-07-01T02:21:46.000Z
2017-07-01T02:21:46.000Z
console.log("images.js"); var smltown_css = ""; var smltown_cssPre = "{background-image:url(" + SMLTOWN.path_static; var smltown_cssFin = ")}"; function css(nombre, url) { smltown_css += nombre + smltown_cssPre + "static/" + url + smltown_cssFin; } //BASE css("#smltown_html", "img/background4.jpg"); css("#androidAd", "img/android_smalltownad.jpg"); css("#smltown_forumLink", "img/forum.png"); css(".smltown_loader", "img/loader.gif"); css(".smltown_night #smltown_sun > div", "img/moon.png"); css("#smltown_sun > div", "img/sun.png"); css("#smltown_cardBack", "img/unflipped.jpg"); css(".smltown_sleep", "img/zzz.png"); css(".smltown_dead", "img/player_night.gif"); css("#smltown_user .smltown_player", "img/player_green.gif"); css(".smltown_night #smltown_user .smltown_player", "img/player_night.gif"); css("#smltown_listAlive", "img/player_blue.gif"); css(".smltown_waiting .smltown_player, .smltown_waiting #smltown_user .smltown_player", "img/player_night.gif"); var smltown_style = document.createElement('style'); smltown_style.type = 'text/css'; smltown_style.innerHTML = smltown_css; document.getElementsByTagName('html')[0].appendChild(smltown_style); console.log("!!!!!!!!!!!!!!!!!!!!");
35.647059
112
0.716172
b19d770087b9c1fb5395fa00c07330cde7251318
1,185
js
JavaScript
view/frontend/requirejs-config.js
memorious/Magento2_Affirm
486200b3a1a1a321e32d521c45ace46557b597ef
[ "BSD-3-Clause" ]
7
2017-10-19T16:35:07.000Z
2019-11-20T14:42:09.000Z
view/frontend/requirejs-config.js
memorious/Magento2_Affirm
486200b3a1a1a321e32d521c45ace46557b597ef
[ "BSD-3-Clause" ]
11
2018-01-11T18:23:50.000Z
2021-11-29T22:53:27.000Z
view/frontend/requirejs-config.js
memorious/Magento2_Affirm
486200b3a1a1a321e32d521c45ace46557b597ef
[ "BSD-3-Clause" ]
15
2018-07-02T19:05:14.000Z
2022-02-19T17:06:45.000Z
/** * Astound * NOTICE OF LICENSE * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to codemaster@astoundcommerce.com so we can send you a copy immediately. * * @category Affirm * @package Astound_Affirm * @copyright Copyright (c) 2016 Astound, Inc. (http://www.astoundcommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ var config = { map: { '*': { 'synchPost': 'Astound_Affirm/js/action/send-request', 'affirmPixel': 'Astound_Affirm/js/affirmPixel', 'affirmWidget': 'Astound_Affirm/js/affirmWidget', 'aslowasPDP': 'Astound_Affirm/js/aslowasPDP', 'aslowasPLP': 'Astound_Affirm/js/aslowasPLP', 'aslowasCC': 'Astound_Affirm/js/aslowasCC', 'aslowasMC': 'Astound_Affirm/js/aslowasMC' } } };
38.225806
89
0.664135
b19dd0f82fa3a4e682e07760b55657a9cc45a943
4,697
js
JavaScript
src/javascripts/modules/visualizations/Donut.js
gene1wood/internet-health-report
51e5ed9e63e97978fbaea6fa218e31ccf480164c
[ "MIT" ]
3
2016-09-15T18:25:26.000Z
2018-02-22T16:14:57.000Z
src/javascripts/modules/visualizations/Donut.js
gene1wood/internet-health-report
51e5ed9e63e97978fbaea6fa218e31ccf480164c
[ "MIT" ]
34
2016-09-16T18:02:00.000Z
2019-11-19T12:54:05.000Z
src/javascripts/modules/visualizations/Donut.js
gene1wood/internet-health-report
51e5ed9e63e97978fbaea6fa218e31ccf480164c
[ "MIT" ]
7
2016-11-15T12:14:47.000Z
2021-09-18T00:45:56.000Z
/* global Waypoint */ import * as constants from '../constants'; import $ from 'jquery'; import * as d3 from 'd3'; import '../../plugins/noframework.waypoints'; window.$ = $; class Donut { constructor(el, dataUrl) { this.el = el; this.dataUrl = dataUrl; this.legendRectSize = 18; this.legendSpacing = 4; this.legendHeight = this.legendRectSize + this.legendSpacing; this.color = d3.scaleOrdinal() .range(constants.colorRange); this.classes = [`donut__svg-container`,`donut__svg`, `donut__g`, `donut__arc`, `donut__text`, `donut__layer`, `donut__value`]; this.legendClasses = [`legend legend--donut`, `legend__item`, `legend__key`, `legend__name`]; this.svg = d3.select(this.el) .append(`div`) .attr(`class`, this.classes[0]) .append(`svg`) .attr(`class`, this.classes[1]); this.svgData = this.svg.append(`g`) .attr(`class`, this.classes[2]); } setSizes(transition = false) { this.width = $(this.el).width(); this.radius = Math.min(this.width) * 0.5; this.svg .attr(`width`, this.width) .attr(`height`, this.width); this.arc = d3.arc() .innerRadius((this.radius/10) * 7) .outerRadius(this.radius); this.svgData .attr(`transform`, `translate(${this.radius}, ${this.radius})`); this.svg.selectAll(`.${this.classes[6]}`) .attr(`transform`, `translate(${this.radius}, ${this.radius})`); if (transition) { this.animateChart(); } else { this.svg.selectAll(`.${this.classes[3]}`) .attr(`d`, this.arc); } } animateChart() { const arcAnimationDuration = 800; $(this.el).addClass(`is-active`); this.svg.selectAll(`.${this.classes[3]}`) .transition() .duration(arcAnimationDuration) .ease(d3.easeCubicOut) .attrTween(`d`, (d) => { const i = d3.interpolate(d.startAngle, d.endAngle); return (t) => { d.endAngle = i(t); return this.arc(d); }; }); this.svg.selectAll(`.${this.classes[6]}`) .transition() .duration(300) .delay(arcAnimationDuration) .style(`opacity`, 1); } render() { d3.csv(this.dataUrl, (error, data) => { if (error) { throw error; } this.data = data; this.dataKeys = constants.getDataKeys(this.data); this.data.forEach(this.type.bind(this)); this.isSingleValue = this.data.length === 1; this.pie = d3.pie() .value(d => d[this.dataKeys[1]]) .sort(null); if (this.isSingleValue) { const value = this.data[0][this.dataKeys[1]]; const newData = {}; newData[this.dataKeys[0]] = `other`; newData[this.dataKeys[1]] = 100 - value; this.data.push(newData); } this.svgData.selectAll(`g`) .data(this.pie(this.data)) .enter() .append(`g`) .attr(`class`, this.classes[5]) .append(`path`) .attr(`class`, this.classes[3]) .attr(`fill`, d => this.color(d.data[this.dataKeys[0]])); if (!this.isSingleValue) { this.renderLegend(); } else { this.svg.append(`text`) .attr(`class`, this.classes[6]) .style(`font-size`, `40px`) .style(`fill`, `#fff`) .style(`opacity`, 0) .attr(`text-anchor`, `middle`) .attr(`alignment-baseline`, `central`) .text(`${this.data[0][this.dataKeys[1]]}%`); } const waypoint = new Waypoint({ element: document.getElementById(this.el.substr(1)), handler: () => { this.setSizes(true); waypoint.destroy(); }, offset: `50%`, }); $(window).on(`resize`, this.resize.bind(this)); }); } type(d) { d[this.dataKeys[1]] = +d[this.dataKeys[1]]; return d; } renderLegend() { const $legend = d3.select(this.el).append(`ul`) .attr(`class`, this.legendClasses[0]); const legendItems = $legend.selectAll(`li`) .data(this.color.domain()) .enter() .append(`li`) .attr(`class`, this.legendClasses[1]); legendItems.append(`span`) .attr(`class`, this.legendClasses[2]) .style(`background-color`, this.color); legendItems.append(`span`) .attr(`class`, this.legendClasses[3]) .text(d => d); } resize() { this.setSizes(); } } const loadDonuts = () => { const $donuts = $(`.js-donut`); $donuts.each((index) => { const $this = $donuts.eq(index); const id = $this.attr(`id`); const url = $this.data(`url`); new Donut(`#${id}`, url).render(); }); }; export { loadDonuts };
25.807692
130
0.550777
b19eb8bb03764c3999ee5e994cb53d38a78a24dd
843
js
JavaScript
private/jsapp/oa/mrouter/components/MRouterLazyImageImg.js
developedbyme/dbm-content
e877074d1427b5bdf25b7ce123d90a2eaf113f61
[ "MIT" ]
null
null
null
private/jsapp/oa/mrouter/components/MRouterLazyImageImg.js
developedbyme/dbm-content
e877074d1427b5bdf25b7ce123d90a2eaf113f61
[ "MIT" ]
null
null
null
private/jsapp/oa/mrouter/components/MRouterLazyImageImg.js
developedbyme/dbm-content
e877074d1427b5bdf25b7ce123d90a2eaf113f61
[ "MIT" ]
null
null
null
import React, {Component} from 'react'; import { connect } from 'react-redux'; import OaLazyImage from "oa/react/OaLazyImage"; //import MRouterLazyImageImg from "oa/mrouter/components/MRouterLazyImageImg"; //import {MRouterLazyImageImgReduxConnected} from "oa/mrouter/components/MRouterLazyImageImg"; export default class MRouterLazyImageImg extends OaLazyImage { constructor (props) { super(props); this._mainElementType = "img"; } _getImageData() { return this.props.data.sizes; } static mapStateToProps(state, myProps) { //console.log("oa/mrouter/components/MRouterLazyImageImg.mapStateToProps (static)"); //console.log(state, myProps); return OaLazyImage.mapStateToProps(state, myProps); }; } export let MRouterLazyImageImgReduxConnected = connect(MRouterLazyImageImg.mapStateToProps)(MRouterLazyImageImg);
29.068966
113
0.775801
b1a0283429419bd4b6e0406b5486433299c260d9
9,543
js
JavaScript
src/scenes/CodingValidation/__tests__/CodingValidation.test.js
CDCgov/phlip
a793556c781b675ee5bb6d37addeb8dbc26bd698
[ "Apache-2.0" ]
null
null
null
src/scenes/CodingValidation/__tests__/CodingValidation.test.js
CDCgov/phlip
a793556c781b675ee5bb6d37addeb8dbc26bd698
[ "Apache-2.0" ]
5
2020-05-11T20:36:25.000Z
2021-11-02T15:49:04.000Z
src/scenes/CodingValidation/__tests__/CodingValidation.test.js
LaudateCorpus1/phlip
a793556c781b675ee5bb6d37addeb8dbc26bd698
[ "Apache-2.0" ]
2
2020-12-21T21:23:00.000Z
2022-02-27T23:12:56.000Z
import React from 'react' import { shallow } from 'enzyme' import { CodingValidation } from '../index' const props = { project: { id: 1, name: 'Project Test', projectJurisdictions: [{ id: 11 }, { id: 10 }, { id: 20, name: 'florida' }] }, page: 'coding', isValidation: false, question: { id: 1, text: 'question!' }, currentIndex: 0, questionOrder: [1], showNextButton: false, isSchemeEmpty: false, areJurisdictionsEmpty: false, user: { id: 11, role: 'Admin' }, selectedCategory: null, selectedCategoryId: null, schemeError: null, gettingStartedText: '', answerErrorContent: null, apiErrorAlert: { open: false, text: '' }, match: { url: '/project/1/code', params: { id: 1, view: 'code' } }, history: { replace: jest.fn() }, actions: { setPage: jest.fn(), getOutlineRequest: jest.fn(), onCloseScreen: jest.fn(), getPrevQuestion: jest.fn(), getNextQuestion: jest.fn(), onQuestionSelectedInNav: jest.fn(), updateUserAnswer: jest.fn(), saveUserAnswerRequest: jest.fn(), showQuestionLoader: jest.fn(), setHeaderText: jest.fn(), onChangeComment: jest.fn(), onChangePincite: jest.fn(), onChangeCategory: jest.fn(), onCloseAlert: jest.fn(), onClearAnswer: jest.fn(), applyAnswerToAll: jest.fn(), showPageLoader: jest.fn(), toggleAnnotationMode: jest.fn() } } describe('CodingValidation', () => { test('should render Coding component correctly', () => { expect(shallow(<CodingValidation {...props} />)).toMatchSnapshot() }) describe('setting page name', () => { test('should set document title to code if on coding', () => { shallow( <CodingValidation {...props} project={{ name: 'Blep', id: 4, projectJurisdictions: [] }} /> ) expect(document.title).toEqual('PHLIP - Blep - Code') }) test('should set document title to validate if on validation', () => { shallow( <CodingValidation {...props} isValidation project={{ name: 'Blep', id: 4, projectJurisdictions: [] }} /> ) expect(document.title).toEqual('PHLIP - Blep - Validate') }) }) describe('unmounting', () => { test('should clear the info when leaving the page', () => { const spy = jest.spyOn(props.actions, 'onCloseScreen') const wrapper = shallow(<CodingValidation {...props} />) wrapper.unmount() expect(spy).toHaveBeenCalled() }) }) describe('getting outline', () => { test('should get outline', () => { const spy = jest.spyOn(props.actions, 'getOutlineRequest') shallow(<CodingValidation {...props} />) expect(spy).toHaveBeenCalled() }) }) describe('setting jurisdiction', () => { test('should set it to empty if there are no project jurisdictions', () => { const wrapper = shallow( <CodingValidation {...props} project={{ id: 4, name: 'blep', projectJurisdictions: [] }} /> ) expect(wrapper.state().jurisdiction).toEqual({ id: null }) }) test('should use route param if one is present', () => { const wrapper = shallow(<CodingValidation {...props} match={{ params: { jid: 20 } }} />) expect(wrapper.state().jurisdiction).toEqual({ id: 20, name: 'florida' }) }) test('should use first jurisdiction if no route param is present', () => { const wrapper = shallow(<CodingValidation {...props} />) expect(wrapper.state().jurisdiction).toEqual({ id: 11 }) }) }) describe('changing routes', () => { test('should change routes if component updated and has a new question', () => { const spy = jest.spyOn(props.history, 'replace') const wrapper = shallow(<CodingValidation {...props} />) wrapper.setProps({ question: { id: 32 } }) expect(spy).toHaveBeenCalledWith({ pathname: '/project/1/code/11/32' }) spy.mockReset() }) test('should change routes if component is updated and has a new jurisdiction', () => { const spy = jest.spyOn(props.history, 'replace') const wrapper = shallow(<CodingValidation {...props} />) wrapper.setState({ jurisdiction: { id: 20 } }) expect(spy).toHaveBeenCalledWith({ pathname: '/project/1/code/20/1' }) spy.mockReset() }) test('should change routes after load and scheme isn\'t empty', () => { const spy = jest.spyOn(props.history, 'replace') const wrapper = shallow(<CodingValidation {...props} getRequestInProgress />) wrapper.setProps({ getRequestInProgress: false }) expect(spy).toHaveBeenCalledWith({ pathname: '/project/1/code/11/1' }) spy.mockReset() }) test('should not change the route if scheme or jurisdictions are empty', () => { const spy = jest.spyOn(props.history, 'replace') shallow(<CodingValidation {...props} isSchemeEmpty areJurisdictionsEmpty />) expect(spy).not.toHaveBeenCalled() }) }) describe('changing questions', () => { test('should open an alert if the user tries to change questions while current answer is saving', () => { const wrapper = shallow(<CodingValidation {...props} unsavedChanges />) wrapper.instance().getQuestion('next', 0) expect(wrapper.state().stillSavingAlertOpen).toEqual(true) }) test('should handle if the user selects a question in the navigator', () => { const spy = jest.spyOn(props.actions, 'onQuestionSelectedInNav') const wrapper = shallow(<CodingValidation {...props} />) wrapper.instance().getQuestion('nav', { id: 4, text: 'floop' }) expect(spy).toHaveBeenCalledWith({ id: 4, text: 'floop' }, { id: 4, text: 'floop' }, 1, 11) }) test('should handle if the user selects the next question', () => { const spy = jest.spyOn(props.actions, 'getNextQuestion') const wrapper = shallow(<CodingValidation {...props} questionOrder={[1, 3]} />) wrapper.instance().getQuestion('next', 1) expect(spy).toHaveBeenCalledWith(3, 1, 1, 11) }) test('should handle if the user selects the previous question', () => { const spy = jest.spyOn(props.actions, 'getPrevQuestion') const wrapper = shallow(<CodingValidation {...props} questionOrder={[1, 3]} currentIndex={1} />) wrapper.instance().getQuestion('prev', 0) expect(spy).toHaveBeenCalledWith(1, 0, 1, 11) }) }) describe('on answering the question when it\'s not a text field', () => { const saveSpy = jest.spyOn(props.actions, 'saveUserAnswerRequest') const updateSpy = jest.spyOn(props.actions, 'updateUserAnswer') const setSpy = jest.spyOn(props.actions, 'setHeaderText') const wrapper = shallow(<CodingValidation {...props} />) wrapper.find('Connect(QuestionCard)').simulate('change', 12, 23) test('should update the answer', () => { expect(updateSpy).toHaveBeenCalledWith(1, 11, 1, 12, 23) }) test('should save the answer', () => { expect(saveSpy).toHaveBeenCalledWith(1, 11, 1, null) }) test('should set header text to Saving...', () => { expect(setSpy).toHaveBeenCalledWith('Saving...') }) }) describe('when changing a text field part of the answer', () => { const wrapper = shallow(<CodingValidation {...props} />) test('should handle if the user changes the text answer field', () => { const spy = jest.spyOn(props.actions, 'updateUserAnswer') wrapper.find('Connect(QuestionCard)').simulate('changeTextAnswer', 'textAnswer', 22, 'new text answer') expect(spy).toHaveBeenCalledWith(1, 11, 1, 22, 'new text answer') }) test('should update the pincite if the user changes the pincite', () => { const spy = jest.spyOn(props.actions, 'onChangePincite') wrapper.find('Connect(QuestionCard)').simulate('changeTextAnswer', 'pincite', 22, 'pincite here') expect(spy).toHaveBeenCalledWith(1, 11, 1, 22, 'pincite here') }) test('should update the comment if the user changes the comment', () => { const spy = jest.spyOn(props.actions, 'onChangeComment') wrapper.find('Connect(QuestionCard)').simulate('changeTextAnswer', 'comment', null, 'comment here') expect(spy).toHaveBeenCalledWith(1, 11, 1, 'comment here') }) test('should save the new answer', () => { const spy = jest.spyOn(props.actions, 'saveUserAnswerRequest') wrapper.find('Connect(QuestionCard)').simulate('changeTextAnswer', 'textAnswer', 22, 'new text answer') expect(spy).toHaveBeenCalledWith(1, 11, 1, null) }) test('should set header text to Saving...', () => { const spy = jest.spyOn(props.actions, 'setHeaderText') wrapper.find('Connect(QuestionCard)').simulate('changeTextAnswer', 'textAnswer', 22, 'new text answer') expect(spy).toHaveBeenCalledWith('Saving...') }) }) xdescribe('answer error api alert', () => { test('should close the alert', () => { }) }) describe('changing categories', () => { test('should move to the new category', () => { const spy = jest.spyOn(props.actions, 'onChangeCategory') const wrapper = shallow(<CodingValidation {...props} />) wrapper.find('Connect(QuestionCard)').simulate('changeCategory', null, 3) expect(spy).toHaveBeenCalledWith(3) }) }) })
36.703846
120
0.614063
b1a0421632a409b4a30da1a7c596a6b38e358e44
789
js
JavaScript
Hybris/osfglobalhybrisemarsysstorefront/web/webroot/_ui/desktop/common/js/acc.carousel.js
isabella232/3rd-party-integrations-hybris
4f6dfabd05be9f1ae19e840abab2b91076e1aaac
[ "MIT" ]
null
null
null
Hybris/osfglobalhybrisemarsysstorefront/web/webroot/_ui/desktop/common/js/acc.carousel.js
isabella232/3rd-party-integrations-hybris
4f6dfabd05be9f1ae19e840abab2b91076e1aaac
[ "MIT" ]
null
null
null
Hybris/osfglobalhybrisemarsysstorefront/web/webroot/_ui/desktop/common/js/acc.carousel.js
isabella232/3rd-party-integrations-hybris
4f6dfabd05be9f1ae19e840abab2b91076e1aaac
[ "MIT" ]
1
2022-02-18T10:55:20.000Z
2022-02-18T10:55:20.000Z
ACC.carousel = { addthis_config: { ui_click: true }, bindAll: function () { this.bindJCarousel(); }, bindJCarousel: function () { jQuery('.yCmsContentSlot.span-4 .jcarousel-skin').jcarousel({ vertical: true }); jQuery('.yCmsContentSlot.span-24 .scroller .jcarousel-skin').jcarousel({ }); $(".modal").colorbox({ onComplete: function () { ACC.common.refreshScreenReaderBuffer(); }, onClosed: function () { ACC.common.refreshScreenReaderBuffer(); } }); $('#homepage_slider').waitForImages(function () { $(this).slideView({toolTip: true, ttOpacity: 0.6, autoPlay: true, autoPlayTime: 8000}); }); } }; $(document).ready(function () { ACC.carousel.bindAll(); });
16.102041
91
0.583016
b1a16c4681403d4e2ec58fc8fb3c8249729d10c2
2,356
js
JavaScript
app/services/loan-calculator.js
seangrant/react-loan-calculator
8b1fb95c9b4a8ea63287183b6be150c1229e8eb4
[ "MIT" ]
1
2018-08-16T13:00:28.000Z
2018-08-16T13:00:28.000Z
app/services/loan-calculator.js
seangrant/react-loan-calculator
8b1fb95c9b4a8ea63287183b6be150c1229e8eb4
[ "MIT" ]
null
null
null
app/services/loan-calculator.js
seangrant/react-loan-calculator
8b1fb95c9b4a8ea63287183b6be150c1229e8eb4
[ "MIT" ]
null
null
null
'use strict'; (function(){ var monthlyBreakdown = function(interestRate, years, principal, payment){ var interest = interestRate; var rate = interest/1200; var months = years * 12; var monthlyPrincipal = rate / (Math.pow(1 + rate, months) - 1) * principal; var monthlyInterest = rate > 0 ? (rate * principal) : principal / months; return { interest: monthlyInterest, principal : monthlyPrincipal, payment: payment - monthlyInterest } }; var calcMonthly = function(interestRate, years, principal){ var breakdown = monthlyBreakdown(interestRate, years, principal); var monthly = breakdown.interest + breakdown.principal; return { payment: monthly, interest: breakdown.interest }; }; var ammortize = function(interestRate, years, principal){ principal = principal * 100; var monthly = this.monthlyPayment(interestRate, years, principal); console.log(monthly); var mortgageTable = this.monthlyTable(interestRate, years, principal, 0,[], monthly.payment); var intterest = 0; return mortgageTable.map(function(row){ return { month: row.month, principal: Math.round(row.principal / 100), interest: Math.round(row.interest / 100), payment: Math.round(monthly.payment / 100), balance: Math.round(row.balance / 100), } }); }; var monthlyTable = function(interestRate, years, principal, month, mortgageTable, payment) { var totalMonths = (years * 12); mortgageTable = mortgageTable || []; if(month <= totalMonths){ var breakdown = monthlyBreakdown(interestRate, years, principal, payment); var balance = principal - breakdown.payment; var record = {month: month, principal: principal, interest: breakdown.interest, balance: balance}; mortgageTable.push(record); month += 1; monthlyTable(interestRate, years, balance , month, mortgageTable, payment); } return mortgageTable; }; module.exports = { monthlyPayment: calcMonthly, monthlyTable: monthlyTable, ammortize: ammortize } }());
34.647059
105
0.60017
b1a1b16bcba9a1c106b1f9e088ae752e4c34844c
3,348
js
JavaScript
src/parse-server/cloud/functions/service-url.js
dexa187/cello
52358de19d5ebe9557e34d4da561ef731ae66916
[ "Apache-2.0" ]
null
null
null
src/parse-server/cloud/functions/service-url.js
dexa187/cello
52358de19d5ebe9557e34d4da561ef731ae66916
[ "Apache-2.0" ]
null
null
null
src/parse-server/cloud/functions/service-url.js
dexa187/cello
52358de19d5ebe9557e34d4da561ef731ae66916
[ "Apache-2.0" ]
null
null
null
/* SPDX-License-Identifier: Apache-2.0 */ 'use strict'; const Parse = require('parse/node'); const CaConfig = Parse.Object.extend("CaConfig"); const OrgConfig = Parse.Object.extend("OrgConfig"); const PeerConfig = Parse.Object.extend("PeerConfig"); const OrdererConfig = Parse.Object.extend("OrdererConfig"); async function findRegex(regex, value) { const matches = []; await value.replace(regex, async match => { matches.push(match); }); return matches; } async function storeUrl(chain, networkConfig, key, value) { const number_regex = /[+-]?\d+(\.\d+)?/g; let matches = []; if (key.startsWith('ca_org')) { matches = await findRegex(number_regex, key); const caIndex = parseInt(matches[0]); const caConfig = new CaConfig(); await caConfig.save({ address: value, sequence: caIndex, networkConfig: networkConfig, }); } else if (key.startsWith('peer')) { const peerType = key.split('_').slice(-1)[0]; matches = await findRegex(number_regex, key); const orgIndex = parseInt(matches[1]); const peerIndex = parseInt(matches[0]); const orgConfigQuery = new Parse.Query("OrgConfig"); orgConfigQuery.equalTo("networkConfig", networkConfig); orgConfigQuery.equalTo("sequence", orgIndex); orgConfigQuery.equalTo("name", `peerOrg${orgIndex}`); orgConfigQuery.equalTo("mspid", `Org${orgIndex}MSP`); let org = await orgConfigQuery.first(); if (org) { org.set("name", `peerOrg${orgIndex}`); org.set("mspid", `Org${orgIndex}MSP`); await org.save(); } else { org = new OrgConfig(); await org.save({ networkConfig: networkConfig, sequence: orgIndex, name: `peerOrg${orgIndex}`, mspid: `Org${orgIndex}MSP`, }) } const updateData = {}; updateData[`${peerType}`] = value; const peerConfigQuery = new Parse.Query("PeerConfig"); peerConfigQuery.equalTo("orgConfig", org); peerConfigQuery.equalTo("networkConfig", networkConfig); peerConfigQuery.equalTo("sequence", peerIndex); let peer = await peerConfigQuery.first(); if (peer) { for (const updateKey in updateData) { peer.set(updateKey, updateData[updateKey]); } await peer.save(); } else { peer = new PeerConfig(); await peer.save({ networkConfig: networkConfig, sequence: peerIndex, orgConfig: org, ...updateData, }) } } else if (key === 'orderer') { const ordererConfig = new OrdererConfig(); await ordererConfig.save({ networkConfig: networkConfig, serverHostName: 'orderer.example.com', url: value, }); } } Parse.Cloud.define("storeServiceUrl", async function (request) { const { chainId, networkConfigId } = request.params; let config = request.params.config || {}; let result = { success: true, error: '', }; try { const chainQuery = new Parse.Query("Chain"); const networkConfigQuery = new Parse.Query("NetworkConfig"); const chain = await chainQuery.get(chainId); const networkConfig = await networkConfigQuery.get(networkConfigId); for (const key in config) { await storeUrl(chain, networkConfig, key, config[key]); } } catch (e) { result.success = false; result.error = e.message; } return result; });
28.615385
72
0.64098
b1a1ed57bd855e993e919f9b715c3f4aae6ae0b3
1,302
js
JavaScript
packages/js-fetcher/src/utils/index.js
docomodigital/js-utils
09ef0193e8daab3f4d03ae7fd1e127616f9635d4
[ "MIT" ]
null
null
null
packages/js-fetcher/src/utils/index.js
docomodigital/js-utils
09ef0193e8daab3f4d03ae7fd1e127616f9635d4
[ "MIT" ]
28
2019-02-26T16:08:20.000Z
2020-06-02T18:12:06.000Z
packages/js-fetcher/src/utils/index.js
docomodigital/js-utils
09ef0193e8daab3f4d03ae7fd1e127616f9635d4
[ "MIT" ]
1
2020-07-24T13:12:58.000Z
2020-07-24T13:12:58.000Z
import URLSearchParams from 'url-search-params'; /** * @description Parse the fetch response (call the response json function) * @param {Object} res * @return {Promise<any>} */ export function parseResponse(res) { return res.json(); } /** * @description Check if the given string is an absolute url (starts with http(s)) * @param {String} str * @return {boolean} * @example * isAbsoluteUrl('http://endpoint.com/api/users') // true * isAbsoluteUrl('/api/users') // false */ export function isAbsoluteUrl(str) { const regex = /(https?)?:?\/\//g; return regex.test(str); } /** * @description Append the given query params object to the given url as queryparams * @param {string} url * @param {Object} queryParams * @return {String} * @example * compose('http://endpoint.com/api/users', {page: 1, limit: 10}); // http://endpoint.com/api/users?page=1&limit=10 */ export function compose(url, queryParams) { const splittedUrl = url.split('?'); const endpoint = splittedUrl[0]; const params = splittedUrl.length > 0 ? splittedUrl[1] : ''; const urlSearchParams = new URLSearchParams(params); Object.keys(queryParams).forEach((key) => { urlSearchParams.set(key, queryParams[key]); }); return `${endpoint}?${urlSearchParams.toString()}`; }
28.933333
115
0.668203
b1a39cbadb57c163975e320f0c60a180e87d35db
9,164
js
JavaScript
src/__tests__/DirectoryTree.test.js
lissitz/react-accessible-treeview
46ce9efd733bf73c4dc04b5369491b79eb125628
[ "MIT" ]
24
2019-09-05T12:25:59.000Z
2022-03-26T18:50:08.000Z
src/__tests__/DirectoryTree.test.js
lissitz/react-accessible-treeview
46ce9efd733bf73c4dc04b5369491b79eb125628
[ "MIT" ]
20
2019-08-21T20:41:42.000Z
2022-03-31T17:59:03.000Z
src/__tests__/DirectoryTree.test.js
lissitz/react-accessible-treeview
46ce9efd733bf73c4dc04b5369491b79eb125628
[ "MIT" ]
5
2019-10-10T14:37:29.000Z
2022-01-22T02:50:47.000Z
import React from "react"; import "@testing-library/jest-dom/extend-expect"; import { render, fireEvent } from "@testing-library/react"; import TreeView, { flattenTree } from ".."; const folder = { name: "", children: [ { name: "src", children: [{ name: "index.js" }, { name: "styles.css" }] }, { name: "node_modules", children: [ { name: "react-accessible-treeview", children: [{ name: "index.js" }] }, { name: "react", children: [{ name: "index.js" }] } ] }, { name: ".npmignore" }, { name: "package.json" }, { name: "webpack.config.js" } ] }; const data = flattenTree(folder); function DirectoryTreeView() { return ( <div> <div> <TreeView data={data} aria-label="directory tree" onBlur={({ treeState, dispatch }) => { dispatch({ type: "DESELECT", id: Array.from(treeState.selectedIds)[0] }); }} nodeRenderer={({ element, getNodeProps }) => ( <div {...getNodeProps()}>{element.name}</div> )} /> </div> </div> ); } test("nodes have aria properties", () => { const { queryAllByRole } = render(<DirectoryTreeView />); let nodes = queryAllByRole("treeitem"); expect(nodes[0]).toHaveAttribute("aria-level", "1"); expect(nodes[0]).toHaveAttribute("aria-posinset", "1"); expect(nodes[0]).toHaveAttribute("aria-setsize", "5"); expect(nodes[0]).toHaveAttribute("aria-expanded", "false"); }); test("there is an element with role=tree", () => { const { queryByRole } = render(<DirectoryTreeView />); expect(queryByRole("tree")).toBeDefined(); }); //Mouse test("clicking a branch node toggles aria-expanded", () => { const { queryAllByRole, container } = render(<DirectoryTreeView />); let nodes = queryAllByRole("treeitem"); let node = container.querySelector( '[role="treeitem"][aria-level="1"][aria-posinset="1"]' ); const inner = node.querySelector(".tree-node"); expect(nodes[0]).toHaveAttribute("aria-expanded", "false"); fireEvent.click(inner); expect(nodes[0]).toHaveAttribute("aria-expanded", "true"); fireEvent.click(inner); expect(nodes[0]).toHaveAttribute("aria-expanded", "false"); }); test("clicking a node makes aria-selected=true ", () => { const { queryAllByRole, container } = render(<DirectoryTreeView />); let nodes = queryAllByRole("treeitem"); let node = container.querySelector( '[role="treeitem"][aria-level="1"][aria-posinset="1"]' ); const inner = node.querySelector(".tree-node"); expect(inner).toBeTruthy(); fireEvent.click(inner); expect(nodes[0]).toHaveAttribute("aria-selected", "true"); fireEvent.click(inner); expect(nodes[0]).toHaveAttribute("aria-selected", "true"); }); //Key bindings test("Key bindings toggle aria-expanded", () => { const { queryAllByRole, container } = render(<DirectoryTreeView />); let nodes = queryAllByRole("treeitem"); let node = container.querySelector( '[role="treeitem"][aria-level="1"][aria-posinset="1"]' ); fireEvent.keyDown(node, { key: " " }); expect(nodes[0]).toHaveAttribute("aria-expanded", "false"); fireEvent.keyDown(node, { key: "Enter" }); expect(nodes[0]).toHaveAttribute("aria-expanded", "false"); fireEvent.keyDown(node, { key: "ArrowRight" }); expect(nodes[0]).toHaveAttribute("aria-expanded", "true"); fireEvent.keyDown(node, { key: "ArrowLeft" }); expect(nodes[0]).toHaveAttribute("aria-expanded", "false"); }); test("Spacebar sets aria-selected=true ", () => { const { container, queryAllByRole } = render(<DirectoryTreeView />); let nodes = queryAllByRole("treeitem"); let node = container.querySelector( '[role="treeitem"][aria-level="1"][aria-posinset="1"]' ); fireEvent.keyDown(node, { key: " " }); expect(nodes[0]).toHaveAttribute("aria-selected", "true"); }); test("Enter sets aria-selected=true ", () => { const { container, queryAllByRole } = render(<DirectoryTreeView />); let nodes = queryAllByRole("treeitem"); let node = container.querySelector( '[role="treeitem"][aria-level="1"][aria-posinset="1"]' ); fireEvent.keyDown(node, { key: "Enter" }); expect(nodes[0]).toHaveAttribute("aria-selected", "true"); }); //WAI-ARIA pattern checklist test("Right arrow", () => { const { queryAllByRole, container } = render(<DirectoryTreeView />); let nodes = queryAllByRole("treeitem"); let node = container.querySelector( '[role="treeitem"][aria-level="1"][aria-posinset="1"]' ); // When focus is on a closed node, opens the node; focus does not move. nodes[0].focus(); expect(nodes[0]).toHaveAttribute("aria-expanded", "false"); expect(document.activeElement).toEqual(nodes[0]); fireEvent.keyDown(node, { key: "ArrowRight" }); expect(nodes[0]).toHaveAttribute("aria-expanded", "true"); expect(document.activeElement).toEqual(nodes[0]); // When focus is on a open node, moves focus to the first child node. fireEvent.keyDown(node, { key: "ArrowRight" }); let childNode = container.querySelector( '[role="treeitem"][aria-level="2"][aria-posinset="1"]' ); expect(document.activeElement).toEqual(childNode); // When focus is on an end node, does nothing. fireEvent.keyDown(node, { key: "ArrowRight" }); expect(document.activeElement).toEqual(childNode); }); test("Left arrow", () => { const { queryAllByRole, container } = render(<DirectoryTreeView />); let nodes = queryAllByRole("treeitem"); nodes[0].focus(); //When focus is on an open node, closes the node. expect(nodes[0]).toHaveAttribute("aria-expanded", "false"); fireEvent.keyDown(nodes[0], { key: "ArrowRight" }); expect(nodes[0]).toHaveAttribute("aria-expanded", "true"); fireEvent.keyDown(nodes[0], { key: "ArrowLeft" }); expect(nodes[0]).toHaveAttribute("aria-expanded", "false"); fireEvent.keyDown(nodes[0], { key: "ArrowRight" }); fireEvent.keyDown(nodes[0], { key: "ArrowRight" }); //When focus is on a child node that is also either an end node or a closed node, moves focus to its parent node. fireEvent.keyDown(nodes[0], { key: "ArrowRight" }); let childNode = container.querySelector( '[role="treeitem"][aria-level="2"][aria-posinset="1"]' ); childNode.focus(); expect(document.activeElement).toEqual(childNode); fireEvent.keyDown(nodes[0], { key: "ArrowLeft" }); expect(document.activeElement).toEqual(nodes[0]); //When focus is on a root node that is also either an end node or a closed node, does nothing. fireEvent.keyDown(nodes[0], { key: "ArrowLeft" }); expect(document.activeElement).toEqual(nodes[0]); }); test("Up/Down Arrow", () => { const { queryAllByRole, container } = render(<DirectoryTreeView />); //Up / Down Arrow: Moves focus to the previous / next node that is focusable without opening or closing a node. let nodes = queryAllByRole("treeitem"); nodes[0].focus(); fireEvent.keyDown(nodes[0], { key: "ArrowDown" }); expect(document.activeElement).toEqual(nodes[1]); fireEvent.keyDown(nodes[0], { key: "ArrowUp" }); expect(document.activeElement).toEqual(nodes[0]); fireEvent.keyDown(nodes[0], { key: "ArrowRight" }); fireEvent.keyDown(nodes[0], { key: "ArrowDown" }); let childNode = container.querySelector( '[role="treeitem"][aria-level="2"][aria-posinset="1"]' ); expect(document.activeElement).toEqual(childNode); fireEvent.keyDown(nodes[0], { key: "ArrowUp" }); expect(document.activeElement).toEqual(nodes[0]); }); test("Home Key", () => { const { queryAllByRole } = render(<DirectoryTreeView />); let nodes = queryAllByRole("treeitem"); nodes[nodes.length - 1].focus(); fireEvent.keyDown(nodes[0], { key: "Home" }); expect(document.activeElement).toEqual(nodes[0]); }); test("End Key", () => { const { queryAllByRole } = render(<DirectoryTreeView />); let nodes = queryAllByRole("treeitem"); nodes[0].focus(); fireEvent.keyDown(nodes[0], { key: "End" }); expect(document.activeElement).toEqual(nodes[nodes.length - 1]); }); test("Asterisk", () => { const { queryAllByRole, container } = render(<DirectoryTreeView />); let nodes = queryAllByRole("treeitem"); nodes[0].focus(); let rootNodes = container.querySelectorAll( '.tree-branch-wrapper[role="treeitem"][aria-level="1"]' ); expect(rootNodes.length).toBeTruthy(); rootNodes.forEach(x => expect(x).toHaveAttribute("aria-expanded", "false")); fireEvent.keyDown(nodes[0], { key: "*" }); rootNodes.forEach(x => expect(x).toHaveAttribute("aria-expanded", "true")); }); test("Single character typeahead", () => { const { queryAllByRole, getByText } = render(<DirectoryTreeView />); let nodes = queryAllByRole("treeitem"); nodes[0].focus(); fireEvent.keyDown(nodes[0], { key: "p" }); expect(document.activeElement).toEqual(getByText("package.json")); fireEvent.keyDown(nodes[0], { key: "p" }); expect(document.activeElement).toEqual(getByText("package.json")); //branch node fireEvent.keyDown(nodes[0], { key: "s" }); expect(document.activeElement).toEqual(getByText("src").parentElement); });
33.567766
115
0.649935
b1a49b4eae817c89de70ad959693e5fe3b76d062
3,878
js
JavaScript
dockerfiles/base/files/wso2iot-3.3.0/repository/deployment/server/jaggeryapps/store/modules/rxt/converter.js
ahbonsu/docker-iot
a191d4033d779fce13ef4574af62fffdd411ee2b
[ "Apache-2.0" ]
null
null
null
dockerfiles/base/files/wso2iot-3.3.0/repository/deployment/server/jaggeryapps/store/modules/rxt/converter.js
ahbonsu/docker-iot
a191d4033d779fce13ef4574af62fffdd411ee2b
[ "Apache-2.0" ]
null
null
null
dockerfiles/base/files/wso2iot-3.3.0/repository/deployment/server/jaggeryapps/store/modules/rxt/converter.js
ahbonsu/docker-iot
a191d4033d779fce13ef4574af62fffdd411ee2b
[ "Apache-2.0" ]
1
2018-06-25T19:12:36.000Z
2018-06-25T19:12:36.000Z
var utility=require('utility.js').rxt_utility(); var rxt_domain=require('rxt.domain.js').rxt_domain(); var log=require('log.js').LogContainer(); /* Description: The file holds the logic used to generate RXT templates Filename:converter.js Created Date: 28/7/2013 */ var rxt_converter=function(){ function XmlConversionProcess(options){ this.xmlDocument=null; this.rxtTemplate=new rxt_domain.RxtTemplate(); this.mnger=null; this.instrList=null; this.currentRoot=null; utility.config(options,this); } XmlConversionProcess.prototype.execute=function(xmlDocument,rxtTemplate){ if(xmlDocument){ this.xmlDocument=xmlDocument; } if(rxtTemplate){ this.rxtTemplate=rxtTemplate; } this.instrList.execute(this); return this.rxtTemplate; } function InstrList(options){ this.instr=[]; utility.config(options,this); } InstrList.prototype.execute=function(context){ context.root=context.xmlDocument; for(var i=0;i<this.instr.length;i++){ var handler=context.mnger.getHandler(this.instr[i]); if(handler){ handler.execute(context); } } } function Handler(options){ this.fn=null; this.tag=''; utility.config(options,this); } Handler.prototype.execute=function(context){ //Do nothing this is the default handler if(this.fn){ this.fn(context); } } function HandlerManager(){ this.handlers=[]; } HandlerManager.prototype.registerHandler=function(handler){ this.handlers.push(handler); } HandlerManager.prototype.xmlQueryAttr=function(xmlRoot,attr){ return xmlRoot['@'+attr+''].toString(); } HandlerManager.prototype.xmlQueryElement=function(xmlRoot,attr){ return xmlRoot[''+attr+''].toString(); } /* */ HandlerManager.prototype.fill=function(xmlRoot,object){ //Go through all properties in the object for(var key in object){ if((typeof object[key]!='function')&&(!(object[key] instanceof Array))){ var value=this.xmlQueryAttr(xmlRoot,key); if(value==''){ value=this.xmlQueryElement(xmlRoot,key); } if(value!=''){ object[key]=value; } } } } HandlerManager.prototype.getHandler=function(strTag){ for(var i=0;i<this.handlers.length;i++){ if(this.handlers[i].tag==strTag){ return this.handlers[i]; } } return null; } var mnger=new HandlerManager(); mnger.registerHandler(new Handler({ tag:'head', fn:function(context){ log.debug(stringify(context.rxtTemplate)); mnger.fill(context.xmlDocument,context.rxtTemplate); log.debug(stringify(context.rxtTemplate)); }})); mnger.registerHandler(new Handler({ tag:'ui', fn:function(context){ //Implement ui handler }})); mnger.registerHandler(new Handler({ tag:'body', fn:function(context){ }})); mnger.registerHandler(new Handler({ tag:'content', fn:function(context){ var content=context.xmlDocument.content; for each(var table in content.table){ var objTable=new rxt_domain.Table(); mnger.fill(table,objTable); //Go through each field in the table for each(var field in table.field){ var objField=new rxt_domain.Field(); //Fill the current field mnger.fill(field,objField); var objName=new rxt_domain.Name(); mnger.fill(field.name,objName); objName.name=field.name.toString(); objField.addName(objName); //Check if there are any values for each(var v in field.values.value){ objField.addValue(v.toString()); } log.debug('objField: '+stringify(objField)); //Add the field to the table objTable.addField(objField); } //Add the table to the template context.rxtTemplate.getContent().addTable(objTable); } }})); var instr=new InstrList({ instr: ['head','ui','content'] } ); return{ XmlConversionProcess:XmlConversionProcess, Handler:Handler, converter:mnger, instrList:instr } };
19.585859
75
0.687726
b1a4df5e216d9a2e56943f8e4116809983d88868
966
js
JavaScript
test/exports.js
radotzki/validator.js
41c2ac0d848fbc82673c222a195cee6a7c7c448a
[ "MIT" ]
4
2021-01-21T10:49:47.000Z
2021-01-21T12:30:59.000Z
test/exports.js
radotzki/validator.js
41c2ac0d848fbc82673c222a195cee6a7c7c448a
[ "MIT" ]
21
2018-07-15T13:16:54.000Z
2018-12-21T08:08:32.000Z
test/exports.js
radotzki/validator.js
41c2ac0d848fbc82673c222a195cee6a7c7c448a
[ "MIT" ]
null
null
null
let assert = require('assert'); let validator = require('../index'); let isPostalCodeLocales = require('../lib/isPostalCode').locales; describe('Exports', () => { it('should export validators', () => { assert.equal(typeof validator.isEmail, 'function'); assert.equal(typeof validator.isAlpha, 'function'); }); it('should export sanitizers', () => { assert.equal(typeof validator.toBoolean, 'function'); assert.equal(typeof validator.toFloat, 'function'); }); it('should export the version number', () => { /* eslint-disable global-require */ assert.equal( validator.version, require('../package.json').version, 'Version number mismatch in "package.json" vs. "validator.js"' ); /* eslint-enable global-require */ }); it('should export isPostalCode\'s supported locales', () => { assert.ok(isPostalCodeLocales instanceof Array); assert.ok(validator.isPostalCodeLocales instanceof Array); }); });
32.2
68
0.664596
b1a546b22ad4429edb4db1afb040ab21a7ea5aff
189
js
JavaScript
entity/Image.js
zzy1661/node-regist
22606968a8620a46c6e11e50204db4f8548ec439
[ "MIT" ]
1
2018-12-25T17:42:23.000Z
2018-12-25T17:42:23.000Z
entity/Image.js
zzy1661/node-regist
22606968a8620a46c6e11e50204db4f8548ec439
[ "MIT" ]
null
null
null
entity/Image.js
zzy1661/node-regist
22606968a8620a46c6e11e50204db4f8548ec439
[ "MIT" ]
null
null
null
class Image { constructor({id,base64,url,name}) { this.id = id; this.base64 = base64; this.url = url, this.name = name; } } module.exports = Image;
17.181818
39
0.529101
b1a5afa754a3dfdc56f5f67f1851f079f6b92d02
51
js
JavaScript
testfile.js
torch2424/learningSVN
c395a8427933175996ca4f0b08c94a2b187742d0
[ "MIT" ]
null
null
null
testfile.js
torch2424/learningSVN
c395a8427933175996ca4f0b08c94a2b187742d0
[ "MIT" ]
1
2017-10-25T18:27:13.000Z
2017-11-10T18:06:58.000Z
testfile.js
torch2424/learningSVN
c395a8427933175996ca4f0b08c94a2b187742d0
[ "MIT" ]
null
null
null
console.log('testsdfskldfkjasdadasdasldjalksjdl');
25.5
50
0.862745
b1a7bdc5a9ca6925661718aec69a48f95cb18cb0
61
js
JavaScript
tests/baselines/reference/binaryArithmatic3.js
fdecampredon/jsx-typescript-old-version
f84ea6a7881723953a6c38d643de432c17fd5d98
[ "Apache-2.0" ]
3
2018-03-29T12:12:45.000Z
2019-04-16T10:59:34.000Z
tests/baselines/reference/binaryArithmatic3.js
fdecampredon/jsx-typescript-old-version
f84ea6a7881723953a6c38d643de432c17fd5d98
[ "Apache-2.0" ]
null
null
null
tests/baselines/reference/binaryArithmatic3.js
fdecampredon/jsx-typescript-old-version
f84ea6a7881723953a6c38d643de432c17fd5d98
[ "Apache-2.0" ]
null
null
null
//// [binaryArithmatic3.js] var v = undefined | undefined;
20.333333
31
0.672131
b1a86a36aaea2410d1d451c68418ac1552163a68
3,709
js
JavaScript
pages/component/article/article.js
adobe/aem-miniprogram-integration-demo
89653726934e106c9a67ec3ec45f893c0eebc7fb
[ "Apache-2.0" ]
4
2019-11-14T15:29:53.000Z
2021-09-10T04:25:50.000Z
pages/component/article/article.js
liangrockman/aem-miniprogram-integration-demo
89653726934e106c9a67ec3ec45f893c0eebc7fb
[ "Apache-2.0" ]
null
null
null
pages/component/article/article.js
liangrockman/aem-miniprogram-integration-demo
89653726934e106c9a67ec3ec45f893c0eebc7fb
[ "Apache-2.0" ]
4
2019-11-14T15:29:54.000Z
2021-09-10T05:57:04.000Z
/* Copyright 2019 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pages/component/article/article.js var app = getApp() Page({ /** * Page initial data */ data: { heroImage: '', parList:new Array, parimgList:new Array }, /** * Lifecycle function--Called when page load */ onLoad: function (options) { var idx=options.index; var himgPath=app.globalData.globalitemList[idx].image; var contentPath = app.globalData.globalitemList[idx].path; var paragraphs=new Array; this.setData({ heroImage:himgPath, }); wx.request({ url: contentPath+".model.json", headers: { 'Content-Type': 'application/json' }, success: res => { paragraphs = res.data[":items"].root[":items"].responsivegrid[":items"].contentfragment.elements.main.paragraphs; //replace html tag and adding style to control the style in paragraph //Note: rpx doesn't work here /*paragraphs = ['<h1>this is a H1</h1>',]; var i; for(i=0;i<paragraphs.length;i++){ paragraphs[i] = paragraphs[i].replace(/<h1/i,'<h1 style="font-size:24px;"'); };*/ var tempList = res.data[":items"].root[":items"].responsivegrid[":items"].contentfragment[":items"]; var i; var componentList=new Array; for(i=0;i<paragraphs.length;i++){ var key='par'+(i+1); if (tempList.hasOwnProperty(key)){ //there are components after current paragraph var imgList = new Array; var imgKey; //collect images after current paragrahp for (imgKey in tempList[key][":items"]) { var imgSrc = app.globalData.rootPath+tempList[key][":items"][imgKey].src; imgList.push(imgSrc); } if(imgList.length==0){ componentList.push({ hasComponents: false, html: paragraphs[i] }); }else{ componentList.push({ hasComponents: true, html: paragraphs[i], imageList: imgList }) } }else{ componentList.push({ hasComponents: false, html: paragraphs[i] }); } } this.setData({ parList: componentList }); } }) }, /** * Lifecycle function--Called when page is initially rendered */ onReady: function () { }, /** * Lifecycle function--Called when page show */ onShow: function () { }, /** * Lifecycle function--Called when page hide */ onHide: function () { }, /** * Lifecycle function--Called when page unload */ onUnload: function () { }, /** * Page event handler function--Called when user drop down */ onPullDownRefresh: function () { }, /** * Called when page reach bottom */ onReachBottom: function () { }, /** * Called when user click on the top right corner to share */ onShareAppMessage: function () { } })
25.756944
121
0.570774
b1a8e7f1020a5756a58db550c720c60ca4e6ff6b
92
js
JavaScript
main.js
nicolachoquet06250/urban_marginal_nodejs
aad5f18274eb4ee455691cc92c0f41a1c32a99fe
[ "CC0-1.0" ]
null
null
null
main.js
nicolachoquet06250/urban_marginal_nodejs
aad5f18274eb4ee455691cc92c0f41a1c32a99fe
[ "CC0-1.0" ]
null
null
null
main.js
nicolachoquet06250/urban_marginal_nodejs
aad5f18274eb4ee455691cc92c0f41a1c32a99fe
[ "CC0-1.0" ]
null
null
null
'use strict'; const { main } = require('./src/modules/functions-for-main-script'); main();
18.4
68
0.663043
b1a918e1fa91b0fa234d45659df12b364f5af8e5
231
js
JavaScript
carro.js
leto-silva/jogo-javascript
6f8a782f841d4a6b88ac7b4d0a24f6e7751ba85d
[ "Apache-2.0" ]
null
null
null
carro.js
leto-silva/jogo-javascript
6f8a782f841d4a6b88ac7b4d0a24f6e7751ba85d
[ "Apache-2.0" ]
null
null
null
carro.js
leto-silva/jogo-javascript
6f8a782f841d4a6b88ac7b4d0a24f6e7751ba85d
[ "Apache-2.0" ]
null
null
null
/* Classe do objeto Carro */ function Carro(cor, velocMaxima) { this.cor = cor; this.velocMaxima = velocMaxima; this.velocAtual = 0; } Carro.prototype = { acelerar: function() { this.velocAtual += 10; } }
16.5
34
0.619048
b1a940867314a9bef6834395ae9bb244a017d62f
807
js
JavaScript
src/components/LikeAnime/index.js
francgarcia1/AnimeApp
59987e5591f24a4b7492d68936ab96da235bc72d
[ "MIT" ]
null
null
null
src/components/LikeAnime/index.js
francgarcia1/AnimeApp
59987e5591f24a4b7492d68936ab96da235bc72d
[ "MIT" ]
null
null
null
src/components/LikeAnime/index.js
francgarcia1/AnimeApp
59987e5591f24a4b7492d68936ab96da235bc72d
[ "MIT" ]
null
null
null
import React, { useState } from "react"; import { LikeButtonContainer, LikeButton } from "./LikeAnimeElements"; import { AiFillHeart, AiOutlineHeart } from "react-icons/ai"; import { DeleteAnime, AddAnime } from "../../storage/reducers/AnimeReducers"; import { useSelector, useDispatch } from "react-redux"; const LikeAnime = ({ isFav, item }) => { const dispatch = useDispatch(); const favList = useSelector((state) => state?.anime?.favList); function onLike() { if (isFav) { dispatch(DeleteAnime(item, favList)); } else { dispatch(AddAnime(item, favList)); } } return ( <LikeButtonContainer> <LikeButton onClick={onLike}> {isFav ? <AiFillHeart /> : <AiOutlineHeart />} </LikeButton> </LikeButtonContainer> ); }; export default LikeAnime;
28.821429
77
0.660471
b1a9cd4fc0d924364601ac9ca7d329563c6c68a7
438
js
JavaScript
js/task-02.js
ElenaIvanova28/goit-js-hw-07
a0a96e90198cdc36293ff969a6937dbdf198b793
[ "MIT" ]
null
null
null
js/task-02.js
ElenaIvanova28/goit-js-hw-07
a0a96e90198cdc36293ff969a6937dbdf198b793
[ "MIT" ]
null
null
null
js/task-02.js
ElenaIvanova28/goit-js-hw-07
a0a96e90198cdc36293ff969a6937dbdf198b793
[ "MIT" ]
null
null
null
const ingredients = [ 'Картошка', 'Грибы', 'Чеснок', 'Помидоры', 'Зелень', 'Приправы', ]; const menuItem = document.getElementById('ingredients'); const itemName = ingredients.map(ingredient => { const itemList = document.createElement('li'); itemList.classList.add('list'); itemList.textContent = ingredient; return itemList; }); menuItem.append(...itemName); console.log(...itemName);
25.764706
58
0.646119
b1aa62721d458d55573a6b77846fc8babed21f14
2,380
js
JavaScript
src/navigation/TabNavigator.js
eusouwilson/Info-COVID19-BR
265dd300b9dec42a8f08935818f80fd0be6fa972
[ "MIT" ]
1
2020-05-06T04:39:37.000Z
2020-05-06T04:39:37.000Z
src/navigation/TabNavigator.js
eusouwilson/Info-COVID19-BR
265dd300b9dec42a8f08935818f80fd0be6fa972
[ "MIT" ]
null
null
null
src/navigation/TabNavigator.js
eusouwilson/Info-COVID19-BR
265dd300b9dec42a8f08935818f80fd0be6fa972
[ "MIT" ]
null
null
null
import React from 'react'; import { Platform } from 'react-native'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { createStackNavigator } from '@react-navigation/stack'; import TabBarIcon from './TabIcon'; import colors from '../../constants/Colors'; //Tabs import HomeScreen from '../screens/HomeScreen'; import NewsScreen from '../screens/NewsScreen'; import InfoScreen from '../screens/InfoScreen'; import StatisticScreen from '../screens/StatisticScreen'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; const Tab = createBottomTabNavigator(); const INITIAL_ROUTE_NAME = 'HomeScreen'; const RootStack = createStackNavigator(); const TabNavigator = () => ( <Tab.Navigator initialRouteName={INITIAL_ROUTE_NAME} tabBarOptions={{ activeTintColor: colors.tabIconSelected, inactiveTintColor: colors.tabIconDefault, labelStyle: { fontSize: 12 }, style: { height: hp('11%'), width: wp('96%'), marginHorizontal: hp('1%'), borderRadius: 20, marginBottom: 15, paddingVertical: hp('1%'), backgroundColor: colors.defaultColor, }, /* style: { height: hp('8%'), width: wp('96%'), backgroundColor: colors.defaultColor, marginBottom: 15, marginHorizontal: hp('1%'), marginTop: -10, //Platform.OS === 'ios' ? -20 : 10, }, */ }} > <Tab.Screen name="Home" component={HomeScreen} options={{ tabBarIcon: ({ focused }) => ( <TabBarIcon focused={focused} name="md-home" /> ), }} /> <Tab.Screen name="Statisticas" component={StatisticScreen} options={{ tabBarIcon: ({ focused }) => ( <TabBarIcon focused={focused} name="md-pie" /> ), }} /> <Tab.Screen name="Notícias" component={NewsScreen} options={{ tabBarIcon: ({ focused }) => ( <TabBarIcon focused={focused} name="ios-paper" /> ), }} /> <Tab.Screen name="Info" component={InfoScreen} options={{ tabBarIcon: ({ focused }) => ( <TabBarIcon focused={focused} name="md-information-circle" /> ), }} /> </Tab.Navigator> ); export default TabNavigator;
26.153846
73
0.593277
b1aa6c3b3d5ff12f7c01492f6240fd160f20d011
2,296
js
JavaScript
src/angular-password-validator.js
Kapaacius/angular-password-validator
8cf6f25689275b85463137fba2205576817b0d20
[ "MIT" ]
null
null
null
src/angular-password-validator.js
Kapaacius/angular-password-validator
8cf6f25689275b85463137fba2205576817b0d20
[ "MIT" ]
null
null
null
src/angular-password-validator.js
Kapaacius/angular-password-validator
8cf6f25689275b85463137fba2205576817b0d20
[ "MIT" ]
null
null
null
(function(angular){ 'use strict'; var module = angular.module('passwordValidatorModule', []); /** * Parent Directive Has to be attached to parent html element. * Holds first password field value and compares it with second password field value. */ module.directive('passwordManager', function(){ return { restrict : 'A', controller : function(){ var one; this.passwordOneValue = function(value){ one = value; }; this.getPasswordOneValue = function(){ return one; }; this.validatePasswords = function(two){ return one === two; }; } }; }); /** * First password field directive. Just saves field value to password manager. */ module.directive('passwordFieldOne', function(){ return { restrict : 'A', require : ['^passwordManager', 'ngModel'], link : function(scope, elem, attr, ctrl){ scope.$watch(function(){ return ctrl[1].$viewValue; }, function(value){ ctrl[0].passwordOneValue(value); }); } }; }); /** * Second password field directive. * Asks password manager for first field value and compares it with second field current value. * If values do not match, sets form validity to false. * Is also triggered if first field value changes. */ module.directive('passwordFieldTwo', function(){ return { restrict : 'A', require : ['^passwordManager', 'ngModel'], link : function(scope, elem, attr, ctrl){ var manager = ctrl[0], model = ctrl[1]; function setValidity(viewValue){ model.$setValidity('passwordNoMatch', manager.validatePasswords(viewValue)); } scope.$watch(function(){ return manager.getPasswordOneValue(); }, function(){ setValidity(model.$viewValue); }); // For DOM -> model validation model.$parsers.unshift(function(value) { setValidity(value); return value; }); // For model -> DOM validation model.$formatters.unshift(function(value) { setValidity(value); return value; }); } }; }); })(angular);
27.333333
97
0.569686
b1ad31d0b8b4b32391ae1193e5742f4daa992df8
94
js
JavaScript
src/common/Ellipsis/index.js
galezra/wix-style-react
724886bd17d1be22571c074ffb46ff53c55a611c
[ "MIT" ]
null
null
null
src/common/Ellipsis/index.js
galezra/wix-style-react
724886bd17d1be22571c074ffb46ff53c55a611c
[ "MIT" ]
null
null
null
src/common/Ellipsis/index.js
galezra/wix-style-react
724886bd17d1be22571c074ffb46ff53c55a611c
[ "MIT" ]
3
2021-06-06T00:17:25.000Z
2022-01-24T21:07:17.000Z
export { default } from './Ellipsis'; export { extractEllipsisProps } from './EllipsisUtils';
31.333333
55
0.723404
b1adaf2297e08c0902669abe6c228db7b1653005
2,493
js
JavaScript
controllers/landingRoutes.js
Mark33Mark/movie-scheduler
bd7d09b6cd962086b27c2b1fbcdb0fb52f34799e
[ "MIT" ]
null
null
null
controllers/landingRoutes.js
Mark33Mark/movie-scheduler
bd7d09b6cd962086b27c2b1fbcdb0fb52f34799e
[ "MIT" ]
16
2021-11-25T08:10:30.000Z
2021-12-02T09:41:57.000Z
controllers/landingRoutes.js
Mark33Mark/movie-scheduler
bd7d09b6cd962086b27c2b1fbcdb0fb52f34799e
[ "MIT" ]
2
2021-11-30T01:24:43.000Z
2021-12-07T07:52:22.000Z
const router = require('express').Router(); const { Genre, GenreMovie, Movie, User, UserMovie } = require('../models'); const withAuth = require('../utilities/auth'); router.get('/', async (req, res) => { try { const movies = await Movie.findAll({ attributes: [ 'id', 'title', 'release_date', 'overview', 'poster_path', ], }); const movieInfo = movies.map(( info ) => info.get({ plain: true }) ); const posterCount = movieInfo.length; res.render('landing', { movieInfo, posterCount, logged_in: req.session.logged_in }); } catch (err) { res.status(500).json(err); } }); router.get('/dashboard', withAuth, async (req, res) => { try { const userData = await User.findAll({ where: { id:req.session.user_id, }, attributes: { exclude: ['password'], }, include: [ { model: Movie, attributes:['title', 'release_date', 'poster_path'], include:[{model:Genre, attributes:['genre_name']}] }, ], }); let user = userData.map(( post ) => post.get({ plain: true })); res.render( "watchlist", { user, layout: "dashboard", logged_in: req.session.logged_in, }); } catch (err) { res.status(500).json(err); } }); router.get('/login', (req, res) => { // If the user is already logged in, redirect the request to another route if (req.session.logged_in) { res.redirect('/dashboard'); return; } res.render('login', { layout: 'signin', }); }); router.get('/join', (req, res) => { // If the user is already logged in, redirect the request to another route if (req.session.logged_in) { res.redirect('/'); return; } res.render('join', { layout: 'signin', }); }); router.post('/logout', (req, res) => { console.log("User wants to log out."); if (req.session.logged_in) { req.session.destroy(() => { res.status(204).end(); }); } else { res.status(404).end(); } }); module.exports = router;
22.87156
80
0.461292
b1aeb951190e0273e0c60ee1044e24a22b541efd
3,295
js
JavaScript
assets/js/services/settings.js
hermantran/taxgraphs
0f32359f127b64964faa9882f881ebaed94a939b
[ "MIT" ]
17
2015-01-27T21:53:50.000Z
2022-01-05T22:44:00.000Z
assets/js/services/settings.js
hermantran/taxgraphs
0f32359f127b64964faa9882f881ebaed94a939b
[ "MIT" ]
4
2015-02-22T07:23:43.000Z
2021-04-15T05:48:22.000Z
assets/js/services/settings.js
hermantran/taxgraphs
0f32359f127b64964faa9882f881ebaed94a939b
[ "MIT" ]
2
2018-11-13T17:27:07.000Z
2019-01-28T09:11:24.000Z
/* eslint-disable no-use-before-define */ /* @ngInject */ function settings(APP_NAME, APP_VERSION, TAX_YEAR, localStorageService) { const service = {}; service.key = `${APP_NAME}Settings${APP_VERSION}`; service.get = get; service.set = set; service.xAxisScales = { linear: 'Linear', log: 'Logarithmic', }; service.axisFormats = { dollar: 'dollar', number: 'number', percent: 'percent', }; service.deductionDefaults = { itemizedDeduction: 0, standardDeduction: true, personalExemption: true, dependents: false, numDependents: 0, hasTradRetirement: false, tradRetirementContribution: 0, }; service.creditDefaults = { retirementSavers: false, retirementContribution: 0, }; service.graphDefaults = { xAxisScale: service.xAxisScales.linear, xMin: 0, xMax: 300000, yMin: 0, yMax: 0.6, animationTime: 1050, }; const getBaseDefaults = () => ({ year: TAX_YEAR, status: 'single', state: 'CA', deductions: createDeductionSettings(), credits: createCreditSettings(), graph: { ...service.graphDefaults }, }); const defaults = { stateBreakdownData: { ...getBaseDefaults(), graphLines: { effective: true, marginal: false, totalEffective: true, totalMarginal: true, }, }, stateComparisonData: { ...getBaseDefaults(), states: { CA: true, IL: true, PA: true, NY: true, TX: true, }, graphLines: { effective: true, marginal: false, }, }, stateHistoryData: { ...getBaseDefaults(), graphLines: { [TAX_YEAR]: true, [TAX_YEAR - 1]: true, [TAX_YEAR - 2]: true, [TAX_YEAR - 3]: true, [TAX_YEAR - 4]: true, }, }, stockOptionAmtData: { ...getBaseDefaults(), state: 'CA', income: 150000, stockOptions: [{ isoAmount: 7000, strikePrice: 6.15, optionValue: 10.75, }], graph: { ...getBaseDefaults().graph, }, deductions: createDeductionSettings({ hasTradRetirement: true, tradRetirementContribution: 10000, }), }, takeHomePayData: { ...getBaseDefaults(), graphLines: { single: true, married: true, }, }, }; const cache = localStorageService.get(service.key) || defaults; function get(key) { return cache[key]; } function set(key, value) { cache[key] = value; localStorageService.set(service.key, cache); } function createDeductionSettings(federalIncomeOverrides) { return { federal: { ordinaryIncome: { ...service.deductionDefaults, ...(federalIncomeOverrides || {}), }, amt: { amtExemption: true, }, }, state: { income: { ...service.deductionDefaults }, amt: { amtExemption: true, }, }, }; } function createCreditSettings() { return { federal: { ordinaryIncome: { ...service.creditDefaults }, }, state: { income: { ...service.creditDefaults }, }, }; } return service; } export default settings;
20.72327
73
0.55478
b1af70eca1c51d1515682eae8602192572604ff5
730
js
JavaScript
algoexpert.io/js/LongestSubstringWithoutDuplication.js
abhinavveenu/Algorithms-1
34e90f4479d0bc8ddaa051576840a5f30ec53976
[ "MIT" ]
null
null
null
algoexpert.io/js/LongestSubstringWithoutDuplication.js
abhinavveenu/Algorithms-1
34e90f4479d0bc8ddaa051576840a5f30ec53976
[ "MIT" ]
null
null
null
algoexpert.io/js/LongestSubstringWithoutDuplication.js
abhinavveenu/Algorithms-1
34e90f4479d0bc8ddaa051576840a5f30ec53976
[ "MIT" ]
null
null
null
function longestPalindromiSubstring(str) { var hashmap = {}; var longest = 0; var startIndex = 0; var longestWord = ""; var currentLongest = 0; for (var i = 0; i < str.length; i++) { if (!hashmap[str[i]]) { hashmap[str[i]] = i; currentLongest++; if (currentLongest > longest) { longest = currentLongest; longestWord = str.substr(startIndex, i - startIndex + 1) } } else { startIndex = hashmap[str[i]] + 1; currentLongest = i - hashmap[str[i]]; hashmap[str[i]] = i; } } return longestWord; } console.log(longestPalindromiSubstring('clementisacap'));
28.076923
72
0.517808
b1afb611b5cb366d78c11fe38f410f095b92b44b
1,695
js
JavaScript
samples/push-per-user-tags/api/register.js
mikejohanson/azure-mobile-apps-node
17339b46f6631fd56fbbc7fb5b7e870f144ee764
[ "MIT" ]
null
null
null
samples/push-per-user-tags/api/register.js
mikejohanson/azure-mobile-apps-node
17339b46f6631fd56fbbc7fb5b7e870f144ee764
[ "MIT" ]
null
null
null
samples/push-per-user-tags/api/register.js
mikejohanson/azure-mobile-apps-node
17339b46f6631fd56fbbc7fb5b7e870f144ee764
[ "MIT" ]
1
2021-02-03T13:23:49.000Z
2021-02-03T13:23:49.000Z
// ---------------------------------------------------------------------------- // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- var promises = require('azure-mobile-apps/src/utilities/promises'); // a custom push notification registration that adds any tags added for this installation module.exports = { post: function (req, res, next) { var context = req.azureMobile, installationId = req.get('X-ZUMO-INSTALLATION-ID'); // retrieve the list of tags that this installation has registered for context.tables('tags') .where({ userId: context.user.id }) .read() .then(function (tagRows) { // create an installation object that notification hubs accepts var installation = { installationId: installationId, pushChannel: req.body.pushChannel, platform: 'wns', // map the tag from each row in the table into an array tags: tagRows.map(row => row.tag) }; context.logger.info('Registering for notifications with installation ' + JSON.stringify(installation)); // wrap the callback style notification hubs function into a promise return promises.wrap(context.push.createOrUpdateInstallation, context.push)(installation) }) .then(function (result) { res.status(204).end(); }) .catch(next); } }; module.exports.post.authenticated = true;
43.461538
119
0.526254
b1afce926920ff925cc510925faf2b794c589870
191
js
JavaScript
app/routes/v1/materi.js
eripin91/api_elearning
7cd51c5673626864ee5e2819ab38c0e7e1384825
[ "Beerware" ]
null
null
null
app/routes/v1/materi.js
eripin91/api_elearning
7cd51c5673626864ee5e2819ab38c0e7e1384825
[ "Beerware" ]
null
null
null
app/routes/v1/materi.js
eripin91/api_elearning
7cd51c5673626864ee5e2819ab38c0e7e1384825
[ "Beerware" ]
null
null
null
/* global MateriControllers */ 'use strict' var Route = express.Router() Route .get('', MateriControllers.get) .patch('/:idMaterial', MateriControllers.update) module.exports = Route
15.916667
50
0.717277
b1b0b4e230c88023bd3f906eced2de809004e192
6,348
js
JavaScript
node_modules/@logicflow/extension/es/turbo-adapter/index.js
daothiem/source-base-webadmin
4382d28d17662530192213f4dd8525fbfda3bc88
[ "MIT" ]
null
null
null
node_modules/@logicflow/extension/es/turbo-adapter/index.js
daothiem/source-base-webadmin
4382d28d17662530192213f4dd8525fbfda3bc88
[ "MIT" ]
null
null
null
node_modules/@logicflow/extension/es/turbo-adapter/index.js
daothiem/source-base-webadmin
4382d28d17662530192213f4dd8525fbfda3bc88
[ "MIT" ]
null
null
null
var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var TurboType; (function (TurboType) { TurboType[TurboType["SEQUENCE_FLOW"] = 1] = "SEQUENCE_FLOW"; TurboType[TurboType["START_EVENT"] = 2] = "START_EVENT"; TurboType[TurboType["END_EVENT"] = 3] = "END_EVENT"; TurboType[TurboType["USER_TASK"] = 4] = "USER_TASK"; // SERVICE_TASK = 5, 暂不支持 TurboType[TurboType["EXCLUSIVE_GATEWAY"] = 6] = "EXCLUSIVE_GATEWAY"; })(TurboType || (TurboType = {})); // 转换Turbo识别的类型 function getTurboType(type) { switch (type) { case 'bpmn:sequenceFlow': return TurboType.SEQUENCE_FLOW; case 'bpmn:startEvent': return TurboType.START_EVENT; case 'bpmn:endEvent': return TurboType.END_EVENT; case 'bpmn:userTask': return TurboType.USER_TASK; // case 'bpmn:serviceTask': // return TurboType.SERVICE_TASK; case 'bpmn:exclusiveGateway': return TurboType.EXCLUSIVE_GATEWAY; default: return type; } } // 将LogicFlow中的Node数据转换为Turbo元素数据 function convertNodeToTurboElement(node) { var id = node.id, type = node.type, x = node.x, y = node.y, _a = node.text, text = _a === void 0 ? '' : _a, properties = node.properties; return { incoming: [], outgoing: [], dockers: [], type: getTurboType(node.type), properties: __assign(__assign({}, properties), { name: (text && text.value) || '', x: x, y: y, text: text, logicFlowType: type }), key: id, }; } // 将LogicFlow中的Eedg数据转换为Turbo元素数据 function convertEdgeToTurboElement(edge) { var id = edge.id, type = edge.type, sourceNodeId = edge.sourceNodeId, targetNodeId = edge.targetNodeId, startPoint = edge.startPoint, endPoint = edge.endPoint, pointsList = edge.pointsList, _a = edge.text, text = _a === void 0 ? '' : _a, properties = edge.properties; return { incoming: [sourceNodeId], outgoing: [targetNodeId], type: getTurboType(type), dockers: [], properties: __assign(__assign({}, properties), { name: (text && text.value) || '', text: text, startPoint: startPoint, endPoint: endPoint, pointsList: pointsList, logicFlowType: type }), key: id, }; } // 将LogicFlow中数据转换为Turbo数据 export function toTurboData(data) { var nodeMap = new Map(); var turboData = { flowElementList: [], }; data.nodes.forEach(function (node) { var flowElement = convertNodeToTurboElement(node); turboData.flowElementList.push(flowElement); nodeMap.set(node.id, flowElement); }); data.edges.forEach(function (edge) { var flowElement = convertEdgeToTurboElement(edge); var sourceElement = nodeMap.get(edge.sourceNodeId); sourceElement.outgoing.push(flowElement.key); var targetElement = nodeMap.get(edge.targetNodeId); targetElement.incoming.push(flowElement.key); turboData.flowElementList.push(flowElement); }); return turboData; } // 将Turbo元素数据转换为LogicFlow中的Eedg数据 function convertFlowElementToEdge(element) { var incoming = element.incoming, outgoing = element.outgoing, properties = element.properties, key = element.key; var text = properties.text, startPoint = properties.startPoint, endPoint = properties.endPoint, pointsList = properties.pointsList, logicFlowType = properties.logicFlowType; var edge = { id: key, type: logicFlowType, sourceNodeId: incoming[0], targetNodeId: outgoing[0], text: text, startPoint: startPoint, endPoint: endPoint, pointsList: pointsList, properties: {}, }; // 这种转换方式,在自定义属性中不能与excludeProperties中的属性重名,否则将在转换过程中丢失 var excludeProperties = ['startPoint', 'endPoint', 'pointsList', 'text', 'logicFlowType']; Object.keys(element.properties).forEach(function (property) { if (excludeProperties.indexOf(property) === -1) { edge.properties[property] = element.properties[property]; } }); return edge; } // 将Turbo元素数据转换为LogicFlow中的Node数据 function convertFlowElementToNode(element) { var properties = element.properties, key = element.key; var x = properties.x, y = properties.y, text = properties.text, logicFlowType = properties.logicFlowType; var node = { id: key, type: logicFlowType, x: x, y: y, text: text, properties: {}, }; // 这种转换方式,在自定义属性中不能与excludeProperties中的属性重名,否则将在转换过程中丢失 var excludeProperties = ['x', 'y', 'text', 'logicFlowType']; Object.keys(element.properties).forEach(function (property) { if (excludeProperties.indexOf(property) === -1) { node.properties[property] = element.properties[property]; } }); return node; } // 将Turbo元素数据转换为LogicFlow数据 export function toLogicflowData(data) { var lfData = { nodes: [], edges: [], }; var list = data.flowElementList; list && list.length > 0 && list.forEach(function (element) { if (element.type === TurboType.SEQUENCE_FLOW) { var edge = convertFlowElementToEdge(element); lfData.edges.push(edge); } else { var node = convertFlowElementToNode(element); lfData.nodes.push(node); } }); return lfData; } var TurboAdapter = { pluginName: 'turboAdapter', install: function (lf) { lf.adapterIn = this.adapterIn; lf.adapterOut = this.adapterOut; }, shapeConfigMap: new Map(), setCustomShape: function (key, val) { this.shapeConfigMap.set(key, val); }, adapterOut: function (logicflowData) { if (logicflowData) { return toTurboData(logicflowData); } }, adapterIn: function (turboData) { if (turboData) { return toLogicflowData(turboData); } }, }; export { TurboAdapter }; export default TurboAdapter;
35.864407
271
0.62051
b1b0ea0044a45800631d7d48bcb69f23f5afc3f5
595
js
JavaScript
client/src/redux/middlewares/reduxActionTool.middleware.js
zachyutw/es6mernframe
4e69734164532fde8d15ec2ee25209de18ecc6e0
[ "MIT" ]
null
null
null
client/src/redux/middlewares/reduxActionTool.middleware.js
zachyutw/es6mernframe
4e69734164532fde8d15ec2ee25209de18ecc6e0
[ "MIT" ]
null
null
null
client/src/redux/middlewares/reduxActionTool.middleware.js
zachyutw/es6mernframe
4e69734164532fde8d15ec2ee25209de18ecc6e0
[ "MIT" ]
null
null
null
import { ASYNC_PHASES } from 'redux-action-tools' import _ from 'lodash' export default ({ dispatch }) => { return (next) => (action) => { const asyncPhase = _.get(action, 'meta.asyncPhase') const omitLoading = _.get(action, 'meta.omitLoading') if (asyncPhase && !omitLoading) { console.log(action) dispatch({ type: asyncPhase === ASYNC_PHASES.START ? 'ASYNC_STARTED' : 'ASYNC_ENDED', payload: { source: 'ACTION', action }, isLoading: asyncPhase === ASYNC_PHASES.START }) } return next(action) } }
24.791667
82
0.589916
b1b192c31eca7b19bdbe94da356baf9019d51a11
1,463
js
JavaScript
src/index.js
kenzoheye/bachelorproef_js
c2cfd8906509fce82ab3f6855eb11ba425fceabf
[ "MIT" ]
null
null
null
src/index.js
kenzoheye/bachelorproef_js
c2cfd8906509fce82ab3f6855eb11ba425fceabf
[ "MIT" ]
null
null
null
src/index.js
kenzoheye/bachelorproef_js
c2cfd8906509fce82ab3f6855eb11ba425fceabf
[ "MIT" ]
null
null
null
import http from 'http'; import express from 'express'; import cors from 'cors'; import morgan from 'morgan'; import bodyParser from 'body-parser'; import initializeDb from './db'; import middleware from './middleware'; import api from './api'; import config from './config.json'; import parking from './models/parking' const request = require('request') let app = express(); app.server = http.createServer(app); // logger app.use(morgan('dev')); // 3rd party middleware app.use(cors({ exposedHeaders: config.corsHeaders })); app.use(bodyParser.json({ limit : config.bodyLimit })); // connect to db initializeDb( db => { // internal middleware app.use(middleware({ config, db })); // api router app.use('/api', api({ config, db })); app.use('/', express.static('ui')); app.server.listen(process.env.PORT || config.port, () => { console.log(`Started on port ${app.server.address().port}`); }); }); const minutes = 5, interval = minutes * 60 * 1000; setInterval(() => { request('https://datatank.stad.gent/4/mobiliteit/bezettingparkingsrealtime.json', {}, (err, res, body) => { if(err) {return console.log(err)} body = JSON.parse(body) body = body.map(m => { return { 'name': m.name, 'available': m.parkingStatus.availableCapacity, 'total': m.parkingStatus.totalCapacity, 'open': m.parkingStatus.open } }) parking.push({ datetime: new Date(), parking: body }) }) }, interval) export default app;
21.514706
108
0.663021
b1b25c6d9faa52642530e05c1e0a6b303920eabe
901
js
JavaScript
src/utils/testdbhandler.js
OluwmayowaF/twitter-clone-api
45b630bfe7cc50e8de0dfa58ed53d1e3bac53862
[ "MIT" ]
null
null
null
src/utils/testdbhandler.js
OluwmayowaF/twitter-clone-api
45b630bfe7cc50e8de0dfa58ed53d1e3bac53862
[ "MIT" ]
null
null
null
src/utils/testdbhandler.js
OluwmayowaF/twitter-clone-api
45b630bfe7cc50e8de0dfa58ed53d1e3bac53862
[ "MIT" ]
null
null
null
const mongoose = require('mongoose'); // const uri = 'mongodb://test:password12345@cluster0-shard-00-00-7pndu.mongodb.net:27017,cluster0-shard-00-01-7pndu.mongodb.net:27017,cluster0-shard-00-02-7pndu.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority'; const uri = 'mongodb://127.0.0.1:27017/twitter-clone-test'; module.exports = { /* connect: async () => { await mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true }); },*/ /** * Drop database, close the connection and stop mongod. */ closeDatabase: async () => { await mongoose.connection.dropDatabase(); await mongoose.connection.close(); }, /** * Remove all the data for all db collections. *//* clearDatabase: async (collection) => { await mongoose.connection.collection(collection).deleteMany({}); },*/ };
31.068966
268
0.703663
b1b2ab2f03fe11e29ad14fbfa9494ddaa5a76992
257
js
JavaScript
src/count-cats.js
naTpuk-ep/basic-js
0f92f5e65124061f7ed2cb91bd5bb435982cbb2b
[ "MIT" ]
null
null
null
src/count-cats.js
naTpuk-ep/basic-js
0f92f5e65124061f7ed2cb91bd5bb435982cbb2b
[ "MIT" ]
null
null
null
src/count-cats.js
naTpuk-ep/basic-js
0f92f5e65124061f7ed2cb91bd5bb435982cbb2b
[ "MIT" ]
null
null
null
const CustomError = require("../extensions/custom-error"); module.exports = function countCats(matrix) { return matrix.length == 0 ? 0 : matrix.reduce((acc, curr) => acc.filter(item => item === '^^').concat(curr.filter(item => item === '^^'))).length; };
51.4
148
0.645914
b1b31173d3bc3e635f4624b18c6153a7adf76620
2,855
js
JavaScript
client/reducers/availability.js
phuhien92/scheduleAppt
0fe64bd5671cf932b911e9465b201ab8c3e79be7
[ "MIT" ]
null
null
null
client/reducers/availability.js
phuhien92/scheduleAppt
0fe64bd5671cf932b911e9465b201ab8c3e79be7
[ "MIT" ]
15
2019-12-13T19:35:30.000Z
2022-02-10T19:05:04.000Z
client/reducers/availability.js
phuhien92/scheduleAppt
0fe64bd5671cf932b911e9465b201ab8c3e79be7
[ "MIT" ]
null
null
null
import * as types from '../actions/actionTypes'; const initialState = { uid: null, eventId: null, slots: [ { on: false, type: "recur", timeRange: [ { type: "recur", start: "09:00 AM", end: "5:00 PM" }, { type: "single", start: "09:00 AM", } ] }, { on: true, type: "recur", timeRange: [ { type: "recur", start: "09:00 AM", end: "5:00 PM" }, { type: "single", start: "09:00 AM", } ] }, { on: true, type: "recur", timeRange: [ { type: "recur", start: "09:00 AM", end: "5:00 PM" }, { type: "single", start: "09:00 AM", } ] }, { on: true, type: "recur", timeRange: [ { type: "recur", start: "09:00 AM", end: "5:00 PM" }, { type: "single", start: "09:00 AM", } ] }, { on: true, type: "recur", timeRange: [ { type: "recur", start: "09:00 AM", end: "5:00 PM" }, { type: "single", start: "09:00 AM", } ] }, { on: true, type: "recur", timeRange: [ { type: "recur", start: "09:00 AM", end: "5:00 PM" }, { type: "single", start: "09:00 AM", } ] }, { on: false, type: "recur", timeRange: [ { type: "recur", start: "09:00 AM", end: "5:00 PM" }, { type: "single", start: "09:00 AM", } ] } ] } const availability = (state = initialState, action) => { switch(action.type) { default: return state; } } export default availability;
23.401639
56
0.24063
b1b3968818b9a2dc502c66bc7ef48549556df592
26,155
js
JavaScript
Client/test/actions.js
azupatrick0/Fast-Food-Fast
3fb0da30d2ead0857e7aec2a9d848480816856f6
[ "MIT" ]
1
2019-10-19T00:57:27.000Z
2019-10-19T00:57:27.000Z
Client/test/actions.js
azupatrick0/Fast-Food-Fast
3fb0da30d2ead0857e7aec2a9d848480816856f6
[ "MIT" ]
60
2018-09-05T05:00:49.000Z
2021-01-05T05:01:53.000Z
Client/test/actions.js
azupatrick0/Fast-Food-Fast
3fb0da30d2ead0857e7aec2a9d848480816856f6
[ "MIT" ]
1
2019-04-20T10:02:10.000Z
2019-04-20T10:02:10.000Z
import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import { expect } from 'chai'; import moxios from 'moxios'; import fetchMock from 'fetch-mock'; import { SignupAUser, SigninAUser, getMenu, GetHistory, GetAllOrders, AcceptOrders, DeclineOrders, CompleteOrders, UpdateMenu, PopulateMenu, DeleteMenu, CloudinaryImageUpload } from '../src/actions/index'; import { USER_SIGNUP_SUCCESS, USER_SIGNUP_FAILED, USER_SIGNIN_SUCCESS, USER_SIGNIN_FAILED, GET_MENU_SUCCESS, GET_MENU_FAILED, GET_HISTORY_SUCCESS, GET_HISTORY_FAILED, } from '../src/actions/actionTypes'; const middlewares = [thunk]; const mockStore = configureMockStore(middlewares); const meal = 'Frutties'; const price = 1000; const imgurl = 'https://res.cloudinary.com/pato/image/upload/v1548545164/fe39xu5xp6ncnpzeotc7.jpg'; const userDetails = { name: "Nikita Cheng", email: "email6@email.com", password: "password", role: "user" }; const userDetails2 = { email: "email@email.com", password: "password" }; const responseData = { status: "success", data: { message: "New user created", userDetails: { id: 11, name: "Nikita Cheng", email: "email6@email.com", password: "$2b$10$J5GlxL1lVwr133vQrK1jvO2IJMM8EHJS1Ly9dL/d0xxnjExhbJkzG", role: "user", createdat: "2018-10-21T08:06:36.169Z" }, token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVtYWlsNUBlbWFpbC5jb20iLCJpYXQiOjE1NDAxMDkxOTYsImV4cCI6MTU0MDE5NTU5Nn0.qOg1WRqiYfU3Na29jL-7aGakUF3KQhI9XvD3R4rp4qw" } }; const responseData2 = { status: "success", data: { message: "Welcome, Azu Patrick", userDetails: { id: 1, name: "Azu Patrick", email: "email@email.com", password: "$2b$10$elPlTA1joXI0FJAGmgLPGemIPXKsSlFWMuraqDZZsLMcfEFLjX7Ym", role: "admin", createdat: "2018-10-04T17:26:33.608Z" }, token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVtYWlsQGVtYWlsLmNvbSIsImlhdCI6MTUzODY3NDA4MSwiZXhwIjoxNTM4NzYwNDgxfQ.FUwub-imRWXVAUItPQkxA4nOcIYtzxiA_nxdvICJ0g8" } } const menu = { status: 'success', data: { message: 'Available menu returned successfully.', items: [ { id: 1, meal: 'Fruttie', price: 400, imgurl: 'https://res.cloudinary.com/pato/image/upload/v1539986387/yjvhhoun9pajw07zu0dw.jpg', createdat: '2018-10-19T21:59:48.634Z', updatedat: '2018-10-19T21:59:48.634Z' }, { id: 2, meal: 'Burger', price: 200, imgurl: 'https://res.cloudinary.com/pato/image/upload/v1539986437/psjp6ayhoemdidt8vcro.png', createdat: '2018-10-19T22:00:39.734Z', updatedat: '2018-10-19T22:00:39.734Z' }, { id: 3, meal: 'Veggie', price: 350, imgurl: 'https://res.cloudinary.com/pato/image/upload/v1539986467/n9usp2sumwxxmgiaogbd.png', createdat: '2018-10-19T22:01:08.732Z', updatedat: '2018-10-19T22:01:08.732Z' } ] } } const history = { status: 'success', data: { message: 'All orders history returned, thank you.', history: [ { id: 4, menuid: 1, meal: 'Fruttie', imgurl: 'https://res.cloudinary.com/pato/image/upload/v1539986387/yjvhhoun9pajw07zu0dw.jpg', userid: 1, name: 'Azu Patrick', quantity: 2, amount: 800, location: 'Lagos', status: 'new', createdat: '2018-10-21T08:28:42.590Z', createddate: '2018-10-21T00:00:00.000Z' }, { id: 3, menuid: 2, meal: 'Burger', imgurl: 'https://res.cloudinary.com/pato/image/upload/v1539986437/psjp6ayhoemdidt8vcro.png', userid: 1, name: 'Azu Patrick', quantity: 3, amount: 600, location: 'Abuja', status: 'processing', createdat: '2018-10-19T22:02:06.962Z', createddate: '2018-10-19T00:00:00.000Z' }, { id: 2, menuid: 3, meal: 'Veggie', imgurl: 'https://res.cloudinary.com/pato/image/upload/v1539986467/n9usp2sumwxxmgiaogbd.png', userid: 1, name: 'Azu Patrick', quantity: 9, amount: 3150, location: 'Abuja', status: 'complete', createdat: '2018-10-19T22:02:03.956Z', createddate: '2018-10-19T00:00:00.000Z' }, { id: 1, menuid: 1, meal: 'Fruttie', imgurl: 'https://res.cloudinary.com/pato/image/upload/v1539986387/yjvhhoun9pajw07zu0dw.jpg', userid: 1, name: 'Azu Patrick', quantity: 4, amount: 1600, location: 'Abuja', status: 'complete', createdat: '2018-10-19T22:02:03.869Z', createddate: '2018-10-19T00:00:00.000Z' } ] } } const allOrders = { status: 'success', data: { message: 'All orders returned, thank you.', orders: [ { id: 3, menuid: 2, meal: 'Burger', imgurl: 'https://res.cloudinary.com/pato/image/upload/v1539986437/psjp6ayhoemdidt8vcro.png', userid: 1, name: 'Azu Patrick', quantity: 3, amount: 600, location: 'Abuja', status: 'processing', createdat: '2018-10-19T22:02:06.962Z', createddate: '2018-10-19T00:00:00.000Z' }, { id: 2, menuid: 3, meal: 'Veggie', imgurl: 'https://res.cloudinary.com/pato/image/upload/v1539986467/n9usp2sumwxxmgiaogbd.png', userid: 1, name: 'Azu Patrick', quantity: 9, amount: 3150, location: 'Abuja', status: 'complete', createdat: '2018-10-19T22:02:03.956Z', createddate: '2018-10-19T00:00:00.000Z' }, { id: 1, menuid: 1, meal: 'Fruttie', imgurl: 'https://res.cloudinary.com/pato/image/upload/v1539986387/yjvhhoun9pajw07zu0dw.jpg', userid: 1, name: 'Azu Patrick', quantity: 4, amount: 1600, location: 'Abuja', status: 'new', createdat: '2018-10-19T22:02:03.869Z', createddate: '2018-10-19T00:00:00.000Z' } ] } } describe('Fast-Food-Fast Actions Test Suite', () => { // FROM: https://www.npmjs.com/package/node-localstorage beforeEach(() => { moxios.install(); const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVtYWlsQGVtYWlsLmNvbSIsImlhdCI6MTUzODY3NDA4MSwiZXhwIjoyMDAwMDAwMDAwfQ.WS29iggWiAknaAnPDXsGku-F2NXBU33iBAQE-Hb6zSQ' if (typeof localStorage === "undefined" || localStorage === null) { var LocalStorage = require('node-localstorage').LocalStorage; // eslint-disable-next-line no-global-assign localStorage = new LocalStorage('./scratch'); } localStorage.setItem('token', token); }) afterEach(() => moxios.uninstall()); describe('Signup Actions', () => { const store = mockStore({}); it('creates USER_SIGNUP_SUCCESS when user has been signed up', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/auth/signup`, { status: 201, response: responseData, }); const expected = [{ type: USER_SIGNUP_SUCCESS, payload: responseData, }] store.dispatch(SignupAUser(userDetails)).then(() => { expect(store.getActions()).to.eql(expected) }) }) it('creates USER_SIGNUP_FAILED when user fails authentication during sign up', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/auth/signup`, { status: 409, response: `Email => ${userDetails.email} already in use, please choose another.`, }); const expected = [{ type: USER_SIGNUP_FAILED, payload: `Email => ${userDetails.email} already in use, please choose another.`, }] store.dispatch(SignupAUser(userDetails)).then(() => { expect(store.getActions()).to.eql(expected) }) }) }) describe('Signin Actions', () => { const store = mockStore({}); it('creates USER_SIGNIN_SUCCESS when user has been signed in', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/auth/login`, { status: 200, response: responseData2, }); const expected = [{ type: USER_SIGNIN_SUCCESS, payload: responseData2, }] store.dispatch(SigninAUser(userDetails2)).then(() => { expect(store.getActions()).to.eql(expected) }) }) it('creates USER_SIGNIN_FAILED when user fails authentication during signed in', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/auth/login`, { status: 401, response: 'Email or password incorrect', }); const expected = [{ type: USER_SIGNIN_FAILED, payload: 'Email or password incorrect', }] store.dispatch(SigninAUser(userDetails2)).then(() => { expect(store.getActions()).to.eql(expected) }) }) }) describe('GetMenu Actions', () => { const store = mockStore({}); const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVtYWlsQGVtYWlsLmNvbSIsImlhdCI6MTUzODY3NDA4MSwiZXhwIjoyMDAwMDAwMDAwfQ.WS29iggWiAknaAnPDXsGku-F2NXBU33iBAQE-Hb6zSQ'; it('creates GET_MENU_SUCCESS, when menu is retrieved successfully', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/menu?token=${token}`, { status: 200, response: menu, }); const expected = [{ type: GET_MENU_SUCCESS, payload: menu, }] store.dispatch(getMenu(token)).then(() => { expect(store.getActions()).to.eql(expected) }) }) it('creates GET_MENU_FAILED when menu is not retrieved successfully', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/menu`, { status: 401, response: 'Failed to authenticate user token', }); const expected = [{ type: GET_MENU_FAILED, payload: 'Failed to authenticate user token', }] store.dispatch(getMenu(token)).then(() => { expect(store.getActions()).to.eql(expected) }) }) }) describe('GetHistory Actions', () => { const store = mockStore({}); const id = 1; const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVtYWlsQGVtYWlsLmNvbSIsImlhdCI6MTUzODY3NDA4MSwiZXhwIjoyMDAwMDAwMDAwfQ.WS29iggWiAknaAnPDXsGku-F2NXBU33iBAQE-Hb6zSQ'; it('creates GET_HISTORY_SUCCESS, when history is retrieved successfully', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/users/${id}/orders?token=${token}`, { status: 200, response: history, }); const expected = [{ type: GET_HISTORY_SUCCESS, payload: history, }] store.dispatch(GetHistory()).then(() => { expect(store.getActions()).to.eql(expected) }) }) it('creates GET_HISTORY_FAILED when menu is not retrieved successfully', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/menu`, { status: 401, response: 'Failed to authenticate user token', }); const expected = [{ type: GET_HISTORY_FAILED, payload: 'Failed to authenticate user token', }] store.dispatch(GetHistory()).then(() => { expect(store.getActions()).to.eql(expected) }) }) }) describe('GetAllOrders Actions', () => { const store = mockStore({}); const role = 'admin'; const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVtYWlsQGVtYWlsLmNvbSIsImlhdCI6MTUzODY3NDA4MSwiZXhwIjoyMDAwMDAwMDAwfQ.WS29iggWiAknaAnPDXsGku-F2NXBU33iBAQE-Hb6zSQ'; it('creates GET_ORDERS_SUCCESS, when all orders are retrieved successfully', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/orders/?role=${role}&token=${token}`, { status: 200, response: allOrders, }); const expected = [{ type: 'GET_ORDERS_SUCCESS', payload: history, }] store.dispatch(GetAllOrders(role, token)).then(() => { expect(store.getActions()).to.eql(expected) }) }) it('creates GET_ORDERS_FAILED when all orders are not retrieved successfully', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/orders/?role=${role}&token=${token}`, { status: 401, response: 'Failed to authenticate user token', }); const expected = [{ type: 'GET_ORDERS_FAILED', payload: 'Failed to authenticate user token', }] store.dispatch(GetAllOrders(role, token)).then(() => { expect(store.getActions()).to.eql(expected) }) }) }) describe('AcceptOrders Actions', () => { const store = mockStore({}); const role = 'admin'; const val = 148; const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVtYWlsQGVtYWlsLmNvbSIsImlhdCI6MTUzODY3NDA4MSwiZXhwIjoyMDAwMDAwMDAwfQ.WS29iggWiAknaAnPDXsGku-F2NXBU33iBAQE-Hb6zSQ'; it('creates ACCEPT_ORDERS_SUCCESS, when an order is accepted by admin', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/orders/${val}?role=${role}&token=${token}`, { status: 200, response: '1', }); const expected = [{ type: 'ACCEPT_ORDERS_SUCCESS', payload: '1', }] store.dispatch(AcceptOrders(role, token, val)).then(() => { expect(store.getActions()).to.eql(expected) }) }) it('creates ACCEPT_ORDERS_ERROR when an error occur during accepting a users order', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/orders/${val}?role=${role}&token=${token}`, { status: 500, response: 'An error occured while trying to update the order, please try again', }); const expected = [{ type: 'ACCEPT_ORDERS_ERROR', payload: 'An error occured while trying to update the order, please try again', }] store.dispatch(AcceptOrders(role, token, val)).then(() => { expect(store.getActions()).to.eql(expected) }) }) }) describe('DeclineOrders Actions', () => { const store = mockStore({}); const role = 'admin'; const val = 147; const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVtYWlsQGVtYWlsLmNvbSIsImlhdCI6MTUzODY3NDA4MSwiZXhwIjoyMDAwMDAwMDAwfQ.WS29iggWiAknaAnPDXsGku-F2NXBU33iBAQE-Hb6zSQ'; it('creates DECLINE_ORDERS_SUCCESS, when an order is declined by admin', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/orders/${val}?role=${role}&token=${token}`, { status: 200, response: '1', }); const expected = [{ type: 'DECLINE_ORDERS_SUCCESS', payload: '1', }] store.dispatch(DeclineOrders(role, token, val)).then(() => { expect(store.getActions()).to.eql(expected) }) }) it('creates DECLINE_ORDERS_ERROR when an error occur during adeclining a users order', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/orders/${val}?role=${role}&token=${token}`, { status: 500, response: 'An error occured while trying to update the order, please try again', }); const expected = [{ type: 'DECLINE_ORDERS_ERROR', payload: 'An error occured while trying to update the order, please try again', }] store.dispatch(DeclineOrders(role, token, val)).then(() => { expect(store.getActions()).to.eql(expected) }) }) }) describe('CompleteOrders Actions', () => { const store = mockStore({}); const role = 'admin'; const val = 148; const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVtYWlsQGVtYWlsLmNvbSIsImlhdCI6MTUzODY3NDA4MSwiZXhwIjoyMDAwMDAwMDAwfQ.WS29iggWiAknaAnPDXsGku-F2NXBU33iBAQE-Hb6zSQ'; it('creates COMPLETE_ORDERS_SUCCESS, when an order is completed by admin', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/orders/${val}?role=${role}&token=${token}`, { status: 200, response: '1', }); const expected = [{ type: 'COMPLETE_ORDERS_SUCCESS', payload: '1', }] store.dispatch(CompleteOrders(role, token, val)).then(() => { expect(store.getActions()).to.eql(expected) }) }) it('creates COMPLETE_ORDERS_ERROR when an error occur during completing a users order', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/orders/${val}?role=${role}&token=${token}`, { status: 500, response: 'An error occured while trying to update the order, please try again', }); const expected = [{ type: 'COMPLETE_ORDERS_ERROR', payload: 'An error occured while trying to update the order, please try again', }] store.dispatch(CompleteOrders(role, token, val)).then(() => { expect(store.getActions()).to.eql(expected) }) }) }) describe('UpdateMenu Actions', () => { const store = mockStore({}); const role = 'admin'; const itemId= 1; const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVtYWlsQGVtYWlsLmNvbSIsImlhdCI6MTU0ODU2ODczNiwiZXhwIjoxNTQ4NjU1MTM2fQ.JBhxffA8umRWA-z3gf7i8maj9Zcw8WoBZC2PKentI6c'; it('returns UPDATE_MENU_SUCCESS, when a food item is updated by admin', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/menu/${itemId}?role=${role}&token=${token}`, { status: 200, response: 'Item with id => 148, updated successfully.', }); const expected = [{ type: 'UPDATE_MENU_SUCCESS', payload: 'Item with id => 148, updated successfully.', }] store.dispatch(UpdateMenu(itemId, role, token, meal, price, imgurl)).then(() => { expect(store.getActions()).to.eql(expected) }) }) it('returns UPDATE_MENU_ERROR when an error occur during updating food item in the menu', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/menu/${itemId}?role=${role}&token=${token}`, { status: 500, response: 'An error occured while trying to update the item, please try again.', }); const expected = [{ type: 'UPDATE_MENU_ERROR', payload: 'An error occured while trying to update the item, please try again.', }] store.dispatch(UpdateMenu(itemId, role, token, meal, price, imgurl)).then(() => { expect(store.getActions()).to.eql(expected) }) }) }) describe('PopulateMenu Actions', () => { const store = mockStore({}); const role = 'admin'; const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVtYWlsQGVtYWlsLmNvbSIsImlhdCI6MTU0ODU2ODczNiwiZXhwIjoxNTQ4NjU1MTM2fQ.JBhxffA8umRWA-z3gf7i8maj9Zcw8WoBZC2PKentI6c'; it('returns POPULATE_MENU_SUCCESS, when a food item is added to the menu by admin', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/menu?role=${role}&token=${token}`, { status: 200, response: 'New food item added to menu successfully.', }); const expected = [{ type: 'POPULATE_MENU_SUCCESS', payload: 'New food item added to menu successfully.', }] store.dispatch(PopulateMenu(role, token, meal, price, imgurl)).then(() => { expect(store.getActions()).to.eql(expected) }) }) it('returns POPULATE_MENU_ERROR when an error occurs during an admin adding a food item to the menu', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/menu?role=${role}&token=${token}`, { status: 500, response: 'An error occured while trying to update the item, please try again.', }); const expected = [{ type: 'POPULATE_MENU_ERROR', payload: 'An error occured while trying to add new food item to menu, please try again.', }] store.dispatch(PopulateMenu(role, token, meal, price, imgurl)).then(() => { expect(store.getActions()).to.eql(expected) }) }) }) describe('DeleteMenu Actions', () => { const store = mockStore({}); const role = 'admin'; const itemId = 1; const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVtYWlsQGVtYWlsLmNvbSIsImlhdCI6MTU0ODU2ODczNiwiZXhwIjoxNTQ4NjU1MTM2fQ.JBhxffA8umRWA-z3gf7i8maj9Zcw8WoBZC2PKentI6c'; it('returns DELETE_MENU_SUCCESS, when a food item is deleted from the menu by admin', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/menu/items/${itemId}?role=${role}&token=${token}`, { status: 200, response: 'Item with id => 1, deleted successfully', }); const expected = [{ type: 'DELETE_MENU_SUCCESS', payload: 'Item with id => 1, deleted successfully', }] store.dispatch(DeleteMenu(itemId, role, token)).then(() => { expect(store.getActions()).to.eql(expected) }) }) it('returns DELETE_MENU_ERROR when an error occurs during an admin deleteing a food item from the menu', () => { moxios.stubRequest(`${process.env.BASE_URL_PROD}/api/v1/menu/items/${itemId}?role=${role}&token=${token}`, { status: 500, response: 'An error occured while trying to delete the item, from the menu please try again.', }); const expected = [{ type: 'DELETE_MENU_ERROR', payload: 'An error occured while trying to delete the item, from the menu please try again.', }] store.dispatch(DeleteMenu(itemId, role, token)).then(() => { expect(store.getActions()).to.eql(expected) }) }) }) describe('Cloudinary Actions', () => { const store = mockStore({}); const formData = new FormData(); formData.append('upload_preset', 'kls6oowk'); beforeEach(() => { store.clearActions(); }) afterEach(() => { fetchMock.restore() }) it('returns CLOUDINARY_IMAGE_UPLOAD_SUCCESS, when an image is uploaded successfully by admin', () => { fetchMock.post('https://api.cloudinary.com/v1_1/pato/upload', { body: formData, response: 'https://res.cloudinary.com/pato/image/upload/v1548545164/fe39xu5xp6ncnpzeotc7.jpg', headers: { 'Content-Type': 'application/json', } }); const expected = [{ type: 'CLOUDINARY_IMAGE_UPLOAD_SUCCESS', payload: 'https://res.cloudinary.com/pato/image/upload/v1548545164/fe39xu5xp6ncnpzeotc7.jpg', }] store.dispatch(CloudinaryImageUpload(formData)).then(() => { expect(store.getActions()).to.eql(expected) }) }) it('returns CLOUDINARY_IMAGE_UPLOAD_ERROR when an error occurs during an admin uploading an image', () => { const formData = new FormData(); formData.append('upload_preset', 'kls6oowk'); fetchMock.post('https://api.cloudinary.com/v1_1/pato/upload', { body: formData, response: 'https://res.cloudinary.com/pato/image/upload/v1548545164/fe39xu5xp6ncnpzeotc7.jpg', headers: { 'Content-Type': 'application/json', } }); const expected = [{ type: 'CLOUDINARY_IMAGE_UPLOAD_ERROR', payload: 'Failed to upload image', }] store.dispatch(CloudinaryImageUpload(formData)).then(() => { expect(store.getActions()).to.eql(expected) }) }) }) });
35.828767
205
0.558708
b1b50f071ba119b63646ffd8dd08485d986f873e
382
js
JavaScript
packages/api/lib/app.js
mattp94/pigeon
ba3fe31e298553cd4fc12b2d84e69965f8001a60
[ "MIT" ]
null
null
null
packages/api/lib/app.js
mattp94/pigeon
ba3fe31e298553cd4fc12b2d84e69965f8001a60
[ "MIT" ]
1
2021-09-02T07:38:09.000Z
2021-09-02T07:38:09.000Z
packages/api/lib/app.js
mattp94/pigeon
ba3fe31e298553cd4fc12b2d84e69965f8001a60
[ "MIT" ]
null
null
null
const Koa = require("koa"); const auth = require("./middlewares/auth"); const cors = require("./middlewares/cors"); const logger = require("./middlewares/logger"); const message = require("./middlewares/message"); const validator = require("./middlewares/validator"); const app = new Koa(); app.use(cors).use(logger).use(validator).use(auth).use(message); module.exports = app;
27.285714
64
0.709424
b1b6bf806df89bab975ebd628b5677a0f46cce35
1,769
js
JavaScript
app/assets/javascripts/home/about-sec3.js
eggchi21/workout
ddf13478cda5ab227f1341d26e31fb36094bf7b2
[ "Unlicense", "MIT" ]
null
null
null
app/assets/javascripts/home/about-sec3.js
eggchi21/workout
ddf13478cda5ab227f1341d26e31fb36094bf7b2
[ "Unlicense", "MIT" ]
14
2020-02-29T05:30:09.000Z
2022-03-30T23:59:38.000Z
app/assets/javascripts/home/about-sec3.js
eggchi21/workout
ddf13478cda5ab227f1341d26e31fb36094bf7b2
[ "Unlicense", "MIT" ]
null
null
null
$(function(){ $(window).bind("load", function(){ if(document.URL.match(/\/homes\/about/)) { /** * --------------------------------------- * This demo was created using amCharts 4. * * For more information visit: * https://www.amcharts.com/ * * Documentation is available at: * https://www.amcharts.com/docs/v4/ * --------------------------------------- */ // Themes begin am4core.useTheme(am4themes_material); am4core.useTheme(am4themes_animated); // Themes end var chart = am4core.create("chartdiv", am4plugins_wordCloud.WordCloud); var series = chart.series.push(new am4plugins_wordCloud.WordCloudSeries()); series.accuracy = 4; series.step = 15; series.rotationThreshold = 0.7; series.maxCount = 200; series.minWordLength = 2; series.labels.template.margin(4,4,4,4); series.maxFontSize = am4core.percent(30); series.text = "BCAA EAA アウターマッスル アスタキサンチン アナボリック アブローラー アンチエイジング インナーマッスル ウェイトトレーニング ウエストニッパー エアロバイク カーフレイズ カーボ カタボリック カロリー クランチ グルテンフリーダイエット クレアチン ケトジェニックダイエット コレステロール サーキットトレーニング サイドレイズ ササミ サプリ ショルダープレス スクワット ダンベル ダンベルカール ダンベルトライセップス チンニング ツイストクランチ デッドリフト デトックス ノンカロリー バーディップ バーベルカール バーベルトライセップス バターコーヒーダイエット バナナダイエット ハムストリング ヒップリフト フィジーク プロテイン ベンチプレス ベントオーバーローイング ボディビル マイクロダイエット マシーントレーニング ヨガ ラットプルダウン リバウンド レッグレイズ ロハスダイエット ワンハンドロウ" series.colors = new am4core.ColorSet(); series.colors.passOptions = {}; // makes it loop //series.labelsContainer.rotation = 45; series.angles = [0,-90]; series.fontWeight = "700" setInterval(function () { series.dataItems.getIndex(Math.round(Math.random() * (series.dataItems.length - 1))).setValue("value", Math.round(Math.random() * 10)); }, 4000) } }) })
37.638298
440
0.66026
b1b73fdd51476bf783247f8813b20cec3cbfdb86
815
js
JavaScript
source/assets/javascripts/vendor/fontawesome.js
RobotsBuildingRobots/robotsbuildingrobots.com
c6ef64c6c9799b7d4cf893720f7ac8878b2b79ed
[ "MIT" ]
null
null
null
source/assets/javascripts/vendor/fontawesome.js
RobotsBuildingRobots/robotsbuildingrobots.com
c6ef64c6c9799b7d4cf893720f7ac8878b2b79ed
[ "MIT" ]
97
2020-01-08T05:11:17.000Z
2021-01-09T17:40:16.000Z
source/assets/javascripts/vendor/fontawesome.js
RobotsBuildingRobots/robotsbuildingrobots.com
c6ef64c6c9799b7d4cf893720f7ac8878b2b79ed
[ "MIT" ]
null
null
null
import { library, dom } from '@fortawesome/fontawesome-svg-core'; import { faHammer } from '@fortawesome/free-solid-svg-icons/faHammer'; import { faBars } from '@fortawesome/free-solid-svg-icons/faBars'; import { faProjectDiagram } from '@fortawesome/free-solid-svg-icons/faProjectDiagram'; import { faEnvelope } from '@fortawesome/free-regular-svg-icons/faEnvelope'; import { faBrain } from '@fortawesome/free-solid-svg-icons/faBrain'; import { faPhoneSquare } from '@fortawesome/free-solid-svg-icons/faPhoneSquare'; import { faQuoteRight } from '@fortawesome/free-solid-svg-icons/faQuoteRight'; import { faQuoteLeft } from '@fortawesome/free-solid-svg-icons/faQuoteLeft'; library.add(faBars, faBrain, faEnvelope, faPhoneSquare, faQuoteRight, faQuoteLeft, faProjectDiagram, faHammer); dom.watch();
38.809524
86
0.76319
b1b7be9f085e1efdd8e7cc29049fa6615d96475a
5,279
js
JavaScript
scripts/main.js
Sneedd/DayOfYear-Calendar
9b58a437b7038caac4ba8419a9a9e57dae767585
[ "MIT" ]
null
null
null
scripts/main.js
Sneedd/DayOfYear-Calendar
9b58a437b7038caac4ba8419a9a9e57dae767585
[ "MIT" ]
null
null
null
scripts/main.js
Sneedd/DayOfYear-Calendar
9b58a437b7038caac4ba8419a9a9e57dae767585
[ "MIT" ]
null
null
null
/* * main.js - DayOfYear viwer and printing template * Copyright 2020, Steffen Ott */ function RushCalendar() { this.monthNames = { "de" : ["Januar", "Februar", "M&auml;rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], "en" : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "Oktober", "November", "Dezember" ], "hr" : ["Sije&#269;anj", "Velja&#269;a", "O&#382;ujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac" ] }; this.weekDayNames = { "de" : ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"], "en" : ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], "hr" : ["Pon", "Uto", "Sri", "Cet", "Pet", "Sub", "Ned"] }; this.lang = "en"; this.year = 0; this.init(); } RushCalendar.prototype.init = function() { this.year = (new Date()).getFullYear(); var navElement = $("#cal-nav"); var yearSelect = $("<div></div>"); navElement.append(yearSelect); for (var i = this.year-5; i<this.year+5; ++i) { if (this.year == i) { yearSelect.append("<a class=\"w3-bar-item w3-button w3-blue-gray cal-year-select\" href=\"#\">" + i + "</a>"); } else { yearSelect.append("<a class=\"w3-bar-item w3-button cal-year-select\" href=\"#\">" + i + "</a>"); } } navElement.append("<div style=\"border: 1px solid gray; margin: 5px;\"></div>"); var languageSelect = $("<div></div>"); navElement.append(languageSelect); languageSelect.append("<a class=\"w3-bar-item w3-button w3-blue-gray cal-language-select\" data-lang=\"en\" href=\"#\">English</a>"); languageSelect.append("<a class=\"w3-bar-item w3-button cal-language-select\" data-lang=\"de\" href=\"#\">Deutsch</a>"); languageSelect.append("<a class=\"w3-bar-item w3-button cal-language-select\" data-lang=\"hr\" href=\"#\">Hrvatski</a>"); this.render(); $("nav.w3-sidebar a").click(function(event) { var clicked = $(event.target); // Exchange background color clicked.siblings().removeClass("w3-blue-gray"); clicked.addClass("w3-blue-gray"); if (clicked.hasClass("cal-year-select")) { // Parse year and render this.year = parseInt(clicked.text()); this.render(); return (false); } else if (clicked.hasClass("cal-language-select")) { // Read language code and render this.lang = clicked.data("lang"); this.render(); return (false); } }.bind(this)); }; RushCalendar.prototype.render = function() { var today = new Date(); for (var month = 1; month < 13; ++month) { // Render month name var monthCaptionElement = $("<h6 class=\"cal-month\">" + this.monthNames[this.lang][month-1] + "</h6>"); // Render month table var monthTableElement = $("<table class=\"w3-table w3-centered\"></table>"); // Render table header var tableHeader = $("<tr></tr>"); for (var i = 0; i < 7; ++i) { tableHeader.append("<td><b>" + this.weekDayNames[this.lang][i] + "</b></td>"); } monthTableElement.append(tableHeader); // Calculate when this month starts var currentDate = new DateTime(this.year, month, 1); currentDate = currentDate.addDays(-currentDate.getDayOfWeek(true)); // Render the weeks for the month for (var i = 0; i < 6; ++i) { var weekElement = $("<tr></tr>"); for (var j = 0; j < 7; ++j) { var todayClass = ""; if (today.getYear() == currentDate.getYear() && today.getMonth()+1 == currentDate.getMonth() && today.getDate() == currentDate.getDay()) { todayClass = "cal-today"; } if (currentDate.getMonth() != month) { weekElement.append("<td class=\"w3-text-light-gray "+todayClass+"\">" + currentDate.getDay() + "<br/>" + currentDate.getDayOfYear() + "</td>"); } else { weekElement.append("<td class=\""+todayClass+"\">" + currentDate.getDay() + "<br/>" + currentDate.getDayOfYear() + "</td>"); } currentDate = currentDate.addDays(1); } monthTableElement.append(weekElement); } var monthElement = $("td#cal-month-" + month); monthElement.empty(); monthElement.append(monthCaptionElement); monthElement.append(monthTableElement); var yearElement = $("#cal-year"); yearElement.text(this.year); } }; $(function() { window.cal = new RushCalendar(); });
36.916084
162
0.488729
b1b7c8d33a3293c021039d43dd9d120583b5719b
320
js
JavaScript
app/profile/components/authentication/Logout.js
kiwicom/mobile
ef6de517f1c17aec1fdca8ccc7ba38e619c15b52
[ "MIT" ]
137
2018-05-04T04:15:36.000Z
2021-08-31T18:23:56.000Z
app/profile/components/authentication/Logout.js
alienzhou/mobile
9e07a15948f279249874c5a3cb6134681b3539f2
[ "MIT" ]
489
2018-05-02T09:35:27.000Z
2021-09-01T01:05:48.000Z
app/profile/components/authentication/Logout.js
alienzhou/mobile
9e07a15948f279249874c5a3cb6134681b3539f2
[ "MIT" ]
29
2018-05-10T01:32:33.000Z
2022-01-25T10:57:16.000Z
// @flow import * as React from 'react'; import { LinkButton, Translation } from '@kiwicom/mobile-shared'; type Props = {| +onLogout: () => void, |}; export default function Logout(props: Props) { return ( <LinkButton onPress={props.onLogout} title={<Translation id="core.authentication.logout" />} /> ); }
21.333333
99
0.6625
b1b821aba87d1b5c156c547a29fd0180147cbbd9
5,234
js
JavaScript
js/admin/admin_slider.js
jjhesk/v-server-content-bank
e928a5ba87a63cf80e41d82ae130b0c619683bc8
[ "MIT" ]
null
null
null
js/admin/admin_slider.js
jjhesk/v-server-content-bank
e928a5ba87a63cf80e41d82ae130b0c619683bc8
[ "MIT" ]
1
2015-01-06T06:02:40.000Z
2015-01-06T06:02:40.000Z
js/admin/admin_slider.js
jjhesk/v-server-content-bank
e928a5ba87a63cf80e41d82ae130b0c619683bc8
[ "MIT" ]
null
null
null
/** * Created by ryo on 14年11月21日. */ var setting_ob = setting_ob || {}; jQuery(function ($) { "use strict"; (function (d, interaction) { var screen_option = new WPScreenOptionSupport(), status_support = new PublishingSupport(), metabox_support = MetaBoxSupport; var checker = new SliderCheckCompletion(); var $slider_setup = $("#slider_setup_status"); var setup_status = parseInt($slider_setup.val()); if (setup_status == 0) { status_support.PubLabel("Next"); status_support.setTitle("Proceed to next step"); status_support.hideContent(); screen_option.ALL(false); screen_option.ON("slider_basic_setup_box"); new SliderStep1Config(checker); status_support.publishEnable(false); checker.setTriggerOnCheck(function (e, b) { if ($("#slider_setup_status").val() == "1") status_support.publishEnable(true); else status_support.publishEnable(false); }); } else if (setup_status == 2) { status_support.PubLabel("NEXT"); status_support.setTitle("Proceed to next step"); status_support.hideContent(); metabox_support.InputControlSingle($("#payment"), true); metabox_support.InputControlSingle($("#platform"), true); metabox_support.InputControlSingle($("#time_to_next"), true); screen_option.ALL(false); screen_option.ON("slider_basic_setup_box"); metabox_control(); var cat_id = "", countries_id = ""; switch ($("option:selected", $("#platform", $("#slider_basic_setup_box"))).val()) { case "ios": cat_id = "taxonomy-appcate"; countries_id = "taxonomy-countryios_nd"; break; case "android": cat_id = "taxonomy-appandroid"; countries_id = "taxonomy-countryandroid"; break; case "rewards": cat_id = "taxonomy-category"; countries_id = "taxonomy-country"; break; case "coupons": cat_id = "taxonomy-category"; countries_id = "taxonomy-country"; break; } new SliderStep2Config(checker, cat_id, countries_id); status_support.publishEnable(false); checker.setTriggerOnCheck(function (e, b) { if ($("#slider_setup_status").val() == "3") status_support.publishEnable(true); else status_support.publishEnable(false); }); } else if (setup_status == 4) { screen_option.ALL(false); screen_option.ON("slid_list_box"); screen_option.ON("slider_basic_setup_box"); metabox_control(); status_support.PubLabel("Publish"); metabox_support.InputControlSingle($("#payment"), true); metabox_support.InputControlSingle($("#platform"), true); metabox_support.InputControlSingle($("#time_to_next"), true); new SliderStep3Config(checker); status_support.publishEnable(false); checker.setTriggerOnCheck(function (e, b) { if ($("#slider_setup_status").val() == "5") status_support.publishEnable(true); else status_support.publishEnable(false); }); } else if (setup_status == 6) { screen_option.ALL(false); screen_option.ON("slid_list_box"); screen_option.ON("slider_basic_setup_box"); metabox_control(); metabox_support.InputControlSingle($("#payment"), false); metabox_support.InputControlSingle($("#platform"), true); metabox_support.InputControlSingle($("#time_to_next"), false); } //status_support.PubLabel(); function metabox_control() { switch ($("option:selected", $("#platform", $("#slider_basic_setup_box"))).val()) { case "ios": screen_option.ON("countryios_nddiv"); screen_option.ON("appcatediv"); screen_option.ON("slider_basic_setup_box"); break; case "android": screen_option.ON("countryandroiddiv"); screen_option.ON("appandroiddiv"); screen_option.ON("slider_basic_setup_box"); break; case "rewards": screen_option.ON("categorydiv"); screen_option.ON("countrydiv"); screen_option.ON("slider_basic_setup_box"); break; case "coupons": screen_option.ON("categorydiv"); screen_option.ON("countrydiv"); screen_option.ON("slider_basic_setup_box"); break; } } }(document, "click tap touch")); });
40.890625
95
0.533053
b1b881f5a871b26c90846a78192545969abc4f30
769
js
JavaScript
file-uploader/main.js
Doresimon/toolbox
ac76cd826f6e1600a790001828db49c371a8157e
[ "MIT" ]
null
null
null
file-uploader/main.js
Doresimon/toolbox
ac76cd826f6e1600a790001828db49c371a8157e
[ "MIT" ]
11
2021-08-31T17:42:47.000Z
2021-11-29T14:12:25.000Z
file-uploader/main.js
Doresimon/toolbox
ac76cd826f6e1600a790001828db49c371a8157e
[ "MIT" ]
null
null
null
const FormData = require('form-data'); const fs = require("fs") const axios = require("axios") main() function main() { const PATH_TO_FILE = "./tmp/fake.file" const form = new FormData(); const stream = fs.createReadStream(PATH_TO_FILE); form.append('image', stream); form.append('xxxxxxxxxxxxxx', value = "value"); // In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders` const formHeaders = form.getHeaders(); console.log("formheaders", formHeaders) console.log("form", form) const url = "http://localhost:80/api/test/file_upload" axios.post(url, form, { headers: { ...formHeaders, }, }) .then(response => response) .catch(error => error) }
29.576923
120
0.659298
b1b94f838abec71624b0d3503516f1488fb26e27
90
js
JavaScript
app/components/ActivateAccountForm/index.js
danielzy95/oaa-chat
a70f4a37b38e6886cc3f8b0bcfa7a683484066a0
[ "MIT" ]
null
null
null
app/components/ActivateAccountForm/index.js
danielzy95/oaa-chat
a70f4a37b38e6886cc3f8b0bcfa7a683484066a0
[ "MIT" ]
null
null
null
app/components/ActivateAccountForm/index.js
danielzy95/oaa-chat
a70f4a37b38e6886cc3f8b0bcfa7a683484066a0
[ "MIT" ]
null
null
null
import ActivateAccountForm from './ActivateAccountForm' export default ActivateAccountForm
45
55
0.888889
b1ba229ec373f974cb88dfc145510a94ea48d17c
2,970
js
JavaScript
src/pages/index.js
EzzypooOfNazareth/Flickering_Wick
e3ce7a9bea063d944f5070a6919afc6464824ac7
[ "MIT" ]
null
null
null
src/pages/index.js
EzzypooOfNazareth/Flickering_Wick
e3ce7a9bea063d944f5070a6919afc6464824ac7
[ "MIT" ]
null
null
null
src/pages/index.js
EzzypooOfNazareth/Flickering_Wick
e3ce7a9bea063d944f5070a6919afc6464824ac7
[ "MIT" ]
null
null
null
import React from "react"; import Layout from "../components/layout"; import SEO from "../components/seo"; import { Link } from 'gatsby'; import styled from 'styled-components'; import Fade from 'react-reveal'; const Container = styled.div` width: 100%; display: flex; flex-direction: column; align-items: center; `; const HalfSplit = styled.div` display: flex; justify-content: space-between; flex-wrap: wrap; `; const ImageContainer = styled.div` flex-basis: 460px; float: left; `; const SplitImage = styled.img` width: 100%; height: auto; object-fit: contain; `; const SplitText = styled.div` flex-basis: 460px; float: right; display: flex; flex-direction: column; align-items: start; flex-wrap: wrap; `; const SplitHeader = styled.h2` font-size: 26px; margin: 0; margin-bottom: 25px; `; const SplitBody = styled.p` font-size: 14px; margin: 0; `; const LearnButton = styled(Link)` padding: 10px 15px; text-decoration: none; background-color: darkred; color: white; margin-top: 25px; transition: 0.2s ease; &:hover { background-color: red; } `; const Divider = styled.hr` width: 100%; margin: 25px auto; border: none; &:before { content: ""; height: 1px; background: linear-gradient(to right, rgba(0,0,0,0) 0%,rgba(147,147,147,1) 50%,rgba(0,0,0,0) 100%); display: block; margin-bottom: 10px; margin-top: 10px; } `; const WholeBlock = styled.div` width: 100%; `; const WholeImage = styled.img` width: 100%; height: auto; `; const ButtonWrap = styled.div` position: relative; width: 100%; bottom: 100px; text-align: center; `; const FloatingButton = styled(Link)` padding: 10px 15px; text-decoration: none; background-color: darkred; color: white; transition: 0.2s ease; font-size: 30px; margin: 0 auto; &:hover { background-color: red; } `; const IndexPage = () => ( <Layout> <SEO title="Home" /> <Container> <HalfSplit> <ImageContainer> <Fade left> <SplitImage src={require('../images/green.jpg')} /> </Fade> </ImageContainer> <SplitText> <SplitHeader> Find out what makes us Different by Design </SplitHeader> <SplitBody> Flickering Wick CFS is dedicated to keeping our planet green and completely eliminating chemicals in household candles. Click the button below to learn more about the advantages of soy-wax candles over traditional methods. </SplitBody> <LearnButton to={'/'}>Learn More</LearnButton> </SplitText> </HalfSplit> <Divider /> <WholeBlock> <WholeImage src={require('../images/flickeringwickimage.jpg')} /> <ButtonWrap> <FloatingButton>Click Here</FloatingButton> </ButtonWrap> </WholeBlock> </Container> </Layout> ); export default IndexPage;
19.285714
104
0.626936
b1ba696faecf8d2815a68baca032efa73513aeb6
19
js
JavaScript
disc/data/collections/items/modules/items/core/types/items/Disc/metas/id.js
rbokenkamp/core
eddf5b0cc7e7765b932f4d3f311eb2b0ae4a9e11
[ "Apache-2.0" ]
null
null
null
disc/data/collections/items/modules/items/core/types/items/Disc/metas/id.js
rbokenkamp/core
eddf5b0cc7e7765b932f4d3f311eb2b0ae4a9e11
[ "Apache-2.0" ]
null
null
null
disc/data/collections/items/modules/items/core/types/items/Disc/metas/id.js
rbokenkamp/core
eddf5b0cc7e7765b932f4d3f311eb2b0ae4a9e11
[ "Apache-2.0" ]
null
null
null
module.exports = 32
19
19
0.789474
b1ba946050083bcf9d2f19cadaa003bc855e1407
507
js
JavaScript
src/runtimes/node/src/index.js
soederpop/skypager-next
ef06d6101b70e0964d306cd052bf1c692209fbf2
[ "MIT" ]
null
null
null
src/runtimes/node/src/index.js
soederpop/skypager-next
ef06d6101b70e0964d306cd052bf1c692209fbf2
[ "MIT" ]
null
null
null
src/runtimes/node/src/index.js
soederpop/skypager-next
ef06d6101b70e0964d306cd052bf1c692209fbf2
[ "MIT" ]
null
null
null
import runtime from '@skypager/runtime' import * as features from './features' // eslint-disable-line import * as NodeFeature from './feature' runtime.features.register('runtimes/node', () => NodeFeature) runtime.feature('runtimes/node').enable() /** * @typedef NodeRuntime * @property {GitFeature} git interact with git * @property {FileSystemFeature} fsx interact with a file system * */ /** * @type NodeRuntime - @skypager/runtime with the node feature set enabled */ module.exports = runtime
25.35
74
0.725838
b1bae77d91e000768f2edd8193fb09d17803875e
367
js
JavaScript
src/redux/reducers/profile.js
blenson/blockmarket
203cbbb9cc3faa4b0bd9edd892f91a96e0a434ea
[ "MIT" ]
null
null
null
src/redux/reducers/profile.js
blenson/blockmarket
203cbbb9cc3faa4b0bd9edd892f91a96e0a434ea
[ "MIT" ]
4
2021-03-09T23:46:24.000Z
2022-02-18T15:20:45.000Z
src/redux/reducers/profile.js
blenson/blockmarket
203cbbb9cc3faa4b0bd9edd892f91a96e0a434ea
[ "MIT" ]
null
null
null
import { SET_PROFILE } from "../actionTypes"; const initialState = { user: null }; const profile = (state = initialState, action) => { switch (action.type) { case SET_PROFILE: return { ...state, user: action.user }; default: return state; } }; export default profile;
18.35
51
0.506812
b1baf08f7c03ee662a7b0330bd59c19a9df3d2a6
3,244
js
JavaScript
src/main/webapp/js2/nuevoPrestamo.js
alblagu/Biblioteca
ff7c72f954355f0073b0893726fe2c84f1c1a6da
[ "Apache-2.0" ]
null
null
null
src/main/webapp/js2/nuevoPrestamo.js
alblagu/Biblioteca
ff7c72f954355f0073b0893726fe2c84f1c1a6da
[ "Apache-2.0" ]
null
null
null
src/main/webapp/js2/nuevoPrestamo.js
alblagu/Biblioteca
ff7c72f954355f0073b0893726fe2c84f1c1a6da
[ "Apache-2.0" ]
null
null
null
angular.module("app") .controller("prestamoController", function ($scope, $http) { $scope.NUM_MAX_PRESTAMOS=3; $scope.dni = ""; $scope.codigo = ""; $scope.textoError = ""; $scope.fechaFin = new Date(); $scope.fechaFin.setSeconds(14 * 86400); //Añado el tiempo $scope.textoErrorFecha=""; $scope.fechaMinima=function(){ var fechaMinima=new Date(); fechaMinima.setSeconds(14 * 86400); var mes=fechaMinima.getMonth()+1; return fechaMinima.getDate()+"-"+mes+"-"+fechaMinima.getFullYear(); }; $scope.cancelar=function(){ $scope.avanzar=false; }; $scope.obtener = function () { $scope.textoError=""; if ($scope.dni.length === 0 || $scope.codigo.length === 0){ $scope.textoError = "Los campos no pueden estar vacios"; } else { $http({ method: 'GET', url: 'http://localhost:8080/Zinal/webresources/ejemplares/' + $scope.codigo }).then(function successCallback(response) { $scope.ejemplar = response.data; if(!$scope.ejemplar.disponible){ $scope.textoError="Ese ejemplar no esta disponible"; } else{ $http({ method: 'GET', url: 'http://localhost:8080/Zinal/webresources/usuarios/usuario/' + $scope.dni }).then(function successCallback(response) { $scope.usuario = response.data; if($scope.usuario.tipoUsuario==='ADMIN'){ $scope.textoError = "El administrador no puede tener prestamos"; } else{ $scope.comprobarMasXPrestamos(); } }, function errorCallback(response) { $scope.textoError = "No hay ningun usuario con ese dni"; }); } }, function errorCallback(response) { $scope.textoError = "No hay ningun ejemplar con ese codigo"; }); } }; $scope.comprobarMasXPrestamos=function(){ if($scope.usuario.tipoUsuario==='PROFESOR'){ $scope.avanzar=true; } else{ $http({ url: 'http://localhost:8080/Zinal/webresources/ejemplares/prestamosUsu/'+$scope.usuario.dni }).then(function successCallback(response) { if(response.data.length>=$scope.NUM_MAX_PRESTAMOS){ $scope.textoError = "Ese ALUMNO ya tiene "+$scope.NUM_MAX_PRESTAMOS+" prestamos, No puede tener mas"; } else{ $scope.avanzar=true; } }); } }; $scope.nuevoPrestamo = function () { $scope.textoErrorFecha=""; if($scope.fechaFin===null){ $scope.textoErrorFecha="Seleccione una fecha"; } else{ if($scope.fechaFin.getDay()===6||$scope.fechaFin.getDay()===0){ $scope.textoErrorFecha="El prestamo no puede acabar en finde semana"; } else{ var fecha={ dia:$scope.fechaFin.getDate(), mes:$scope.fechaFin.getMonth() + 1, anio:$scope.fechaFin.getFullYear() }; $http({ headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: 'POST', url: 'http://localhost:8080/Zinal/webresources/ejemplares/prestamos/'+$scope.dni+"/"+$scope.codigo, data: JSON.stringify(fecha) }).then(function successCallback(response) { alert("Se ha añadido un prestamo al ejemplar con el codigo " + $scope.codigo); location.reload(); }); } } }; });
27.033333
105
0.616831
b1bc61e0f951e24a1a6880872e57461ad6c53b32
2,884
js
JavaScript
src/main/resources/static/assets/js/system/role/edit.js
roamerxv/RIL
52d511d81dfd06593ed547724eabd11863c4553f
[ "Apache-2.0" ]
null
null
null
src/main/resources/static/assets/js/system/role/edit.js
roamerxv/RIL
52d511d81dfd06593ed547724eabd11863c4553f
[ "Apache-2.0" ]
null
null
null
src/main/resources/static/assets/js/system/role/edit.js
roamerxv/RIL
52d511d81dfd06593ed547724eabd11863c4553f
[ "Apache-2.0" ]
null
null
null
$().ready(function () { $("#m_modal_role_edit").on('hidden.bs.modal', function () { $("#role-role").val(""); $("#role-description").val(""); }); // 模式对话框被打开 $("#m_modal_role_edit").on('shown.bs.modal', function () { if (operator === "edit"){ Logger.debug("开始显示 id 是" + role_id + "的角色信息!"); $.ajax({ type: 'get', url: contextPath + 'role/' + role_id + '.json', async: true,//默认为true contentType: "application/json", dataType: 'json',//默认为预期服务器返回的数据类型 beforeSend: function () { mApp.block('#m_modal_role_edit .modal-content', { overlayColor: '#000000', state: 'primary', message: "正在获取数据..." }); }, success: function (data, textStatus, jqXHR) { $("#role-id").val(data.id); $("#role-role").val(data.role); $("#role-description").val(data.description); }, error: function (jqXHR, textStatus, errorThrown) { showMessage("danger", "错误", jqXHR.responseJSON.data[0].errorMessage); }, complete: function () { mApp.unblock('#m_modal_role_edit .modal-content'); } }); }else if (operator === "create"){ } }); $("#role-form").submit(function () { var ajax_type = ""; if (operator === "edit"){ ajax_type = "put"; }else{ ajax_type = "post" } var role = {}; role.id = role_id; role.role = $("#role-role").val(); role.description = $("#role-description").val(); $.ajax({ type: ajax_type, url: contextPath + 'role.json', async: true,//默认为true data: JSON.stringify(role), contentType: "application/json", dataType: 'json',//默认为预期服务器返回的数据类型 beforeSend: function () { mApp.block('#m_modal_role_edit .modal-content', { overlayColor: '#000000', state: 'primary', message: "正在更新数据..." }); }, success: function (data, textStatus, jqXHR) { role_table.ajax.reload(); $("#m_modal_role_edit").modal("hide"); }, error: function (jqXHR, textStatus, errorThrown) { showMessage("danger", "错误", jqXHR.responseJSON.data[0].errorMessage); }, complete: function () { mApp.unblock('#m_modal_role_edit .modal-content'); } }); return false; }) });
35.604938
89
0.438974
b1bcc7437d0eefc4bb437bb161f17abb61f55ea2
814
js
JavaScript
src/util/permissions.js
michaeltranxd/veym-discord-bot
b5b5cc17b8ae4c9e4341ba79e17e0cd84b50e398
[ "MIT" ]
null
null
null
src/util/permissions.js
michaeltranxd/veym-discord-bot
b5b5cc17b8ae4c9e4341ba79e17e0cd84b50e398
[ "MIT" ]
null
null
null
src/util/permissions.js
michaeltranxd/veym-discord-bot
b5b5cc17b8ae4c9e4341ba79e17e0cd84b50e398
[ "MIT" ]
1
2020-11-19T22:10:58.000Z
2020-11-19T22:10:58.000Z
const { devs } = require("../config.json"); class Permissions { constructor() {} isDev(message) { let isDev = false; devs.forEach((dev) => { if (message.author.id === dev) { isDev = true; } }); return isDev; } isAdmin(message) { let isAdmin = false; // If insufficient permissions then just say we don't recognize that command let guildAdminRoles = message.client.guildMetadatas.get(message.guild.id) .roles_admin; guildAdminRoles.forEach((adminRole) => { if (message.member.roles.cache.get(adminRole)) { isAdmin = true; } }); // If the user is owner of guild then automatic admin if (message.author.id === message.guild.ownerID) isAdmin = true; return isAdmin; } } module.exports = new Permissions();
22
80
0.617936
b1bd71d22225055fc760ef4c0d5b6ad30631d619
147
js
JavaScript
force-app/main/illustrationLibrary/lwc/lakeMountain/lakeMountain.js
jbrandolinisf/EDA
16e3ad1ec2a161cfd6e233780cfc4aae677db25a
[ "BSD-3-Clause" ]
113
2019-05-03T14:57:51.000Z
2022-03-25T18:09:24.000Z
force-app/main/illustrationLibrary/lwc/lakeMountain/lakeMountain.js
aarsvoboda/EDA
a01224b38b1c0126092930e299055de5079c93be
[ "BSD-3-Clause" ]
637
2019-04-30T18:29:28.000Z
2022-03-31T22:01:08.000Z
force-app/main/illustrationLibrary/lwc/lakeMountain/lakeMountain.js
aarsvoboda/EDA
a01224b38b1c0126092930e299055de5079c93be
[ "BSD-3-Clause" ]
111
2015-03-12T00:35:54.000Z
2019-03-29T20:09:11.000Z
import { LightningElement, api } from "lwc"; export default class LakeMountain extends LightningElement { @api title; @api description; }
21
60
0.727891
b1bdc6551893c9b0c7279f651b055997fe2ac434
483
js
JavaScript
bab-8/bab-8-websocket-express-socketio.js
pustakalupi/ls-panduan-nodejs-8x
073a0406346a85862aaa3f1bc55dadaf0c84f08a
[ "MIT" ]
null
null
null
bab-8/bab-8-websocket-express-socketio.js
pustakalupi/ls-panduan-nodejs-8x
073a0406346a85862aaa3f1bc55dadaf0c84f08a
[ "MIT" ]
null
null
null
bab-8/bab-8-websocket-express-socketio.js
pustakalupi/ls-panduan-nodejs-8x
073a0406346a85862aaa3f1bc55dadaf0c84f08a
[ "MIT" ]
null
null
null
var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(654); app.get('/', function (req, res) { res.sendfile(__dirname + '/bab-8-websocket-express-socketio.html'); }); io.on('connection', function (socket) { socket.on('event_ke_server', function (data) { console.log(data); }); socket.emit('salam', { content: 'Selamat Coding!' }); socket.emit('salam1', { content: 'Selamat Coding 1!' }); });
20.125
68
0.643892
b1bde2099efb524ee1a2f3384ccbe7dfd5ecf6db
811
js
JavaScript
test/test.js
wadjih-bencheikh18/disjoint-set
46ebb660a83a633826e772296e9629c2429682ce
[ "MIT" ]
3
2016-07-18T15:30:01.000Z
2021-05-29T00:22:24.000Z
test/test.js
wadjih-bencheikh18/disjoint-set
46ebb660a83a633826e772296e9629c2429682ce
[ "MIT" ]
1
2017-07-21T01:46:19.000Z
2017-07-28T03:48:46.000Z
test/test.js
wadjih-bencheikh18/disjoint-set
46ebb660a83a633826e772296e9629c2429682ce
[ "MIT" ]
1
2022-03-04T16:21:26.000Z
2022-03-04T16:21:26.000Z
'use strict'; const DisjointSet = require('..'); describe('disjoint-set', function () { it('should work', function () { const ds = new DisjointSet(); const x0 = ds.add(0); const x1 = ds.add(1); const x2 = ds.add(3); const x3 = ds.add(4); const objVal1 = {}; const objVal2 = {}; const xObj1 = ds.add(objVal1); const xObj2 = ds.add(objVal2); xObj1.should.not.equal(xObj2); ds.add(0).should.equal(x0); ds.union(x0, x1); ds.union(x2, x3); ds.connected(x0, x1).should.true(); ds.connected(x1, x0).should.true(); ds.connected(x2, x3).should.true(); ds.connected(x1, x3).should.false(); ds.find(x0).should.equal(x0); ds.find(x1).should.equal(x0); }); });
27.965517
44
0.527744
b1beab9f626f363fa5ce0ba4da28c4ead59895c5
1,945
js
JavaScript
src/lang/isContext.test.js
brianneisler/moltres
eca8abe6cdac9a86172a14fe5f095ec0a780f3be
[ "Apache-2.0" ]
14
2016-09-16T01:47:23.000Z
2021-07-13T04:04:14.000Z
src/lang/isContext.test.js
brianneisler/moltres
eca8abe6cdac9a86172a14fe5f095ec0a780f3be
[ "Apache-2.0" ]
71
2020-08-04T15:37:25.000Z
2021-09-22T01:18:22.000Z
src/lang/isContext.test.js
brianneisler/moltres
eca8abe6cdac9a86172a14fe5f095ec0a780f3be
[ "Apache-2.0" ]
1
2020-04-22T01:17:11.000Z
2020-04-22T01:17:11.000Z
import isContext from './isContext' describe('isContext', () => { test('Returns true for an object with a an isContext property set to true', () => { expect( isContext({ isContext: true, }) ).toBe(true) }) test('returns false for all other values', () => { expect(isContext(undefined)).toBe(false) expect(isContext(null)).toBe(false) expect(isContext('')).toBe(false) expect(isContext('abc')).toBe(false) expect(isContext(false)).toBe(false) expect(isContext(true)).toBe(false) expect(isContext(0)).toBe(false) expect(isContext(-1)).toBe(false) expect(isContext(1)).toBe(false) expect(isContext(NaN)).toBe(false) expect(isContext(Infinity)).toBe(false) expect(isContext(-Infinity)).toBe(false) expect(isContext([])).toBe(false) expect(isContext(new Array(0))).toBe(false) expect(isContext([0])).toBe(false) expect(isContext({})).toBe(false) expect(isContext(/abc/)).toBe(false) expect(isContext(async () => {})).toBe(false) expect(isContext(() => {})).toBe(false) expect(isContext(function () {})).toBe(false) expect(isContext((function* () {})())).toBe(false) expect(isContext(new ArrayBuffer(2))).toBe(false) expect(isContext(new Boolean(false))).toBe(false) expect(isContext(new Boolean(true))).toBe(false) expect(isContext(new Date())).toBe(false) expect(isContext(new Error())).toBe(false) expect(isContext(new Map())).toBe(false) expect(isContext(new Number(1))).toBe(false) expect(isContext(new Promise(() => {}))).toBe(false) expect(isContext(new Proxy({}, {}))).toBe(false) expect(isContext(new Set())).toBe(false) expect(isContext(new String('abc'))).toBe(false) expect(isContext(Symbol('abc'))).toBe(false) expect(isContext(Symbol.for('def'))).toBe(false) expect(isContext(new WeakMap())).toBe(false) expect(isContext(new WeakSet())).toBe(false) }) })
38.137255
85
0.652956
b1bf51aae5bfc7d4b563eb3c8130db9e274efee2
427
js
JavaScript
src/redux/actions/authentication.actions.js
prince-verma/react-native-template-demo
adcbef3522e6c6f7fc2c4beddd5163cce39ec782
[ "MIT" ]
1
2018-04-30T05:37:08.000Z
2018-04-30T05:37:08.000Z
src/redux/actions/authentication.actions.js
prince-verma/react-native-template-demo
adcbef3522e6c6f7fc2c4beddd5163cce39ec782
[ "MIT" ]
null
null
null
src/redux/actions/authentication.actions.js
prince-verma/react-native-template-demo
adcbef3522e6c6f7fc2c4beddd5163cce39ec782
[ "MIT" ]
1
2018-03-21T09:11:42.000Z
2018-03-21T09:11:42.000Z
import { UPDATE_AUTHENTICATION_STATE, UPDATE_AUTHENTICATION_LOADING_STATE } from '../reduxConstants'; /** * function to handle user-login flow. * @param {boolean} isAuthenticated * @param {boolean} isLoading * @returns {Function} */ export const updateAuthenticationState = (isAuthenticated, isLoading = false) => dispatch => dispatch({ type: UPDATE_AUTHENTICATION_STATE, payload: { isAuthenticated, isLoading }, });
32.846154
103
0.751756
b1bf5ecbb54452a8d8feb7e42ae4a6bb05968af4
6,553
js
JavaScript
test/public/parseInputChange.test.js
Citifyd/simple-time-input-engine
f7d4424e4fa36ca9493a6161d9e1c8a76079071d
[ "MIT" ]
null
null
null
test/public/parseInputChange.test.js
Citifyd/simple-time-input-engine
f7d4424e4fa36ca9493a6161d9e1c8a76079071d
[ "MIT" ]
null
null
null
test/public/parseInputChange.test.js
Citifyd/simple-time-input-engine
f7d4424e4fa36ca9493a6161d9e1c8a76079071d
[ "MIT" ]
null
null
null
'use strict' const { parseInputChange } = require('../../src/index') const { assert } = require('chai') // Helper constants const MORNING_TIME = '08:00' // use this when time must be in morning, but you don't care about the specific time const AFTERNOON_TIME = '13:00' // use this when time must be in afternoon, but you don't care about the specific time const ANY_TIME = '01:00' // use this when the time doesn't matter const assertValidParseInputChangeResult = ({ input, expectedNewTime }) => { const { valid, time } = parseInputChange(input) assert.isTrue(valid, `Failed when ${JSON.stringify(input)}`) assert.equal(time, expectedNewTime, `Failed when ${JSON.stringify(input)}`) } const assertInvalidParseInputChangeResult = ({ input }) => { const { valid } = parseInputChange(input) assert.isFalse(valid, `Failed when ${JSON.stringify(input)}`) } describe('public api', () => { describe('parseInputChange', () => { describe('all modes', () => { it('should return time as empty string when newValue is empty', () => { for (const clockMode of [12, 24]) { assertValidParseInputChangeResult({ input: { clockMode, newValue: '', previousTime: ANY_TIME }, expectedNewTime: '' }) } }) it('should return object with valid = false when newValue is in invalid format', () => { for (const clockMode of [12, 24]) { for (const newValue of ['wat', '12345']) { assertInvalidParseInputChangeResult({ input: { clockMode, newValue, previousTime: ANY_TIME } }) } } }) it("should use period informed on newValue to generate result if it's specified, no matter what period of day of the previousTime is", () => { for (const clockMode of [12, 24]) { // checks support for a variety of different inputs for 06:00 (6am) for (const newValue of ['6a', '6am', '06a', '06am', '6:00am', '06:00am', '600am', '0600am']) { assertValidParseInputChangeResult({ input: { clockMode, newValue, previousTime: MORNING_TIME }, expectedNewTime: '06:00' }) assertValidParseInputChangeResult({ input: { clockMode, newValue, previousTime: AFTERNOON_TIME }, expectedNewTime: '06:00' }) } // checks support for a variety of different inputs for 18:00 (6pm) for (const newValue of ['6p', '6pm', '06p', '06pm', '6:00pm', '06:00pm', '600pm', '0600pm', '18', '1800']) { assertValidParseInputChangeResult({ input: { clockMode, newValue, previousTime: MORNING_TIME }, expectedNewTime: '18:00' }) assertValidParseInputChangeResult({ input: { clockMode, newValue, previousTime: AFTERNOON_TIME }, expectedNewTime: '18:00' }) } // makes sure midnight is always returned if '0:00'-like time is provided for (const newValue of ['0:00', '00:00', '0', '000']) { assertValidParseInputChangeResult({ input: { clockMode, newValue, previousTime: MORNING_TIME }, expectedNewTime: '00:00' }) assertValidParseInputChangeResult({ input: { clockMode, newValue, previousTime: AFTERNOON_TIME }, expectedNewTime: '00:00' }) } } }) }) describe('when clockMode = 12', () => { it('should maintain same period of day of previousTime if period of day is not specified on newValue', () => { // AM for (const newValue of ['6:00', '06:00', '6', '06']) { assertValidParseInputChangeResult({ input: { newValue, previousTime: MORNING_TIME, clockMode: 12 }, expectedNewTime: '06:00' }) } for (const newValue of ['06:35', '6:35', '0635', '635']) { assertValidParseInputChangeResult({ input: { newValue, previousTime: MORNING_TIME, clockMode: 12 }, expectedNewTime: '06:35' }) } assertValidParseInputChangeResult({ input: { newValue: '12:00', previousTime: MORNING_TIME, clockMode: 12 }, expectedNewTime: '00:00' }) // PM for (const newValue of ['06:00', '6:00', '6', '06']) { assertValidParseInputChangeResult({ input: { newValue, previousTime: AFTERNOON_TIME, clockMode: 12 }, expectedNewTime: '18:00' }) } for (const newValue of ['06:35', '6:35', '0635', '635']) { assertValidParseInputChangeResult({ input: { newValue, previousTime: AFTERNOON_TIME, clockMode: 12 }, expectedNewTime: '18:35' }) } assertValidParseInputChangeResult({ input: { newValue: '12:00', previousTime: AFTERNOON_TIME, clockMode: 12 }, expectedNewTime: '12:00' }) }) }) describe('when clockMode = 24', () => { it('should not take period of day of previousTime into consideration', () => { // AM for (const newValue of ['6:00', '06:00', '6', '06']) { assertValidParseInputChangeResult({ input: { newValue, previousTime: MORNING_TIME, clockMode: 24 }, expectedNewTime: '06:00' }) } for (const newValue of ['06:35', '6:35', '0635', '635']) { assertValidParseInputChangeResult({ input: { newValue, previousTime: MORNING_TIME, clockMode: 24 }, expectedNewTime: '06:35' }) } assertValidParseInputChangeResult({ input: { newValue: '12:00', previousTime: MORNING_TIME, clockMode: 24 }, expectedNewTime: '12:00' }) // PM for (const newValue of ['06:00', '6:00', '6', '06']) { assertValidParseInputChangeResult({ input: { newValue, previousTime: AFTERNOON_TIME, clockMode: 24 }, expectedNewTime: '06:00' }) } for (const newValue of ['06:35', '6:35', '0635', '635']) { assertValidParseInputChangeResult({ input: { newValue, previousTime: AFTERNOON_TIME, clockMode: 24 }, expectedNewTime: '06:35' }) } assertValidParseInputChangeResult({ input: { newValue: '12:00', previousTime: AFTERNOON_TIME, clockMode: 24 }, expectedNewTime: '12:00' }) }) }) }) })
39.475904
148
0.566458