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
1d305d7f3da9cb27d21fde9d2729544c440e2a14
404
js
JavaScript
code/nodejs/02.js
wangwanged/node
14899c9a6077f72409b014ee908c77d84c1b4929
[ "MIT" ]
null
null
null
code/nodejs/02.js
wangwanged/node
14899c9a6077f72409b014ee908c77d84c1b4929
[ "MIT" ]
null
null
null
code/nodejs/02.js
wangwanged/node
14899c9a6077f72409b014ee908c77d84c1b4929
[ "MIT" ]
null
null
null
// 引入http模块 const http = require('http'); // 创建服务 const server = http.createServer(function(req, res) { console.log(`来自${req.connection.remoteAddress}的客户端在${new Date().toLocaleTimeString()}访问了本服务器`); res.end(`<h1>hello world! very good!!-fanyoufu</h1> <p>${req.connection.remoteAddress}</p>`); }); // 启动服务 server.listen(8081, function() { console.log('服务器启动成功,请在http://localhost:8081中访问....'); });
33.666667
97
0.690594
1d31003ac55bc4d99c4d02a499fb9f74ec56c2ae
4,924
js
JavaScript
src/actions.js
ntratcliff/lights.app-api
2710fff73814baf6d36b4bd2c3dbe3d9aa2ea1f6
[ "MIT" ]
null
null
null
src/actions.js
ntratcliff/lights.app-api
2710fff73814baf6d36b4bd2c3dbe3d9aa2ea1f6
[ "MIT" ]
null
null
null
src/actions.js
ntratcliff/lights.app-api
2710fff73814baf6d36b4bd2c3dbe3d9aa2ea1f6
[ "MIT" ]
null
null
null
import { DateTime } from 'luxon' import MathUtil from './math-utils' export class Action { /** Creates Action object from source properties */ constructor(source, lights) { Object.assign(this, source) this.lights = lights; this._originalValues = [] } /* Applies the action to its lights */ /* e.x. a time-based action would start its polling function */ // apply () { } /* Undoes anything caused by this action and disables the action */ /* e.x. the time-based action would stop its polling function */ // undo () { } toJSON () { // auto exclude props starting with _ (private) var copy = {} for (var prop in this) { if (!String(prop).startsWith("_")) { copy[prop] = this[prop] } } return copy } static from(source, lights) { source.type = source.type.toLowerCase() if (types[source.type]) { return new types[source.type](source, lights) } else { throw `Unexpected action type ${source.type}` } } } /** * TODO: proper jsdoc * @var {Object} values id and value for each light this action applies to * e.x { id: 0, value: 255 } */ export class SimpleAction extends Action { apply() { this.values.forEach(l => { var light = this.lights[l.id] // TODO: reference lights by name? if (light) { this._originalValues[l.id] = light.value light.value = l.value } }) } undo() { this.values.forEach(l => { var light = this.lights[l.id] if (light) { light.value = this._originalValues[l.id] } }) } } export class TimeAction extends Action { constructor(source, lights) { super(source, lights) this._animators = {} } apply() { this.timings.forEach(t => { var light = this.lights[t.id] if (light) { this._originalValues[t.id] = light.value // create animator this._animators[t.id] = new TimeAnimatedLight(light, t.values) this._animators[t.id].start() } }) } undo() { this.timings.forEach(t => { var light = this.lights[t.id] if (light) { this._animators[t.id].stop() light.value = this._originalValues[t.id] } }) } } class TimeAnimatedLight { constructor (light, values) { this.light = light this.values = values this.handle = -1 } start () { this.update() } stop () { clearTimeout(this.handle) } update () { // DEBUG console.log(`Updating light ${this.light.name} from time action`) console.log('Values:') console.log(this.values) // current time var current = DateTime.local() console.log(`Current time is ${current.toString()}`) // DEBUG // get closest time before current time var previous = null var prevIndex = -1 for (let i = 0; i < this.values.length; i++) { var v = this.values[i]; var time = DateTime.fromISO(v.time) if (time <= current) { previous = { time: time, value: v.value } prevIndex = i } else if (i === 0) { // current time is before first value, use last value yesterday v = this.values[this.values.length - 1] previous = { time: DateTime.fromISO(v.time).minus({ days: 1}), value: v.value } prevIndex = -1 } } // get next time in list var nextIndex = (prevIndex + 1) % this.values.length var next = this.values[nextIndex] next = { time: DateTime.fromISO(next.time), value: next.value } // add a day to nextif we wrapped into tomorrow time if (nextIndex < prevIndex) { next.time = next.time.plus({ day: 1 }) } // DEBUG console.log(`Nearest previous time: ${previous.time.toString()}`) console.log(`Nearest next time: ${next.time.toString()}`) // calculate current time relative to prev/next var range = next.time.diff(previous.time).milliseconds var norm = current.diff(previous.time).milliseconds var progress = norm / range console.log( `${(progress*100).toFixed(2)}% between` + ` ${previous.time.toString()} and` + ` ${next.time.toString()}` ) // DEBUG // set light value by progress between previous and current // linear interpolation between [previous.value, next.value] // TODO: support easing functions v = MathUtil.lerp(previous.value, next.value, progress) v = Math.round(v) console.log( `${(progress*100).toFixed(2)}%` + ` [${previous.value} ---` + ` ${v} ---` + ` ${next.value}]` ) // DEBUG this.light.value = v // calculate next update time from current and next timings var vd = next.value - previous.value var rate = 0 if (vd !== 0) { // rate = |(v2 - v1) / (t2 - t1)| rate = Math.floor(1 / Math.abs(vd / range)) console.log(`${rate}ms = 1ms / |${vd}u / ${range}ms|`) } else { // no value change until next time rate = range - norm // range - norm = ms to next time console.log(`${rate}ms = ${range}ms - ${norm}ms (vd = ${vd})`) } console.log(`Next update in ${rate}`) this.handle = setTimeout(this.update.bind(this), rate) } } const types = { 'simple': SimpleAction, 'time': TimeAction }
23.336493
88
0.625508
1d3145ad921b4fcb8993b2e3dcb9decaaab3570a
3,669
js
JavaScript
disabled_apps/sms/services/test/unit/moz_mobile_connections/moz_mobile_connections_shim_test.js
NickProgramm/gaia
975a35c0f5010df341e96d6c5ec60217f5347412
[ "Apache-2.0" ]
3
2016-08-17T08:52:51.000Z
2020-03-29T04:56:45.000Z
disabled_apps/sms/services/test/unit/moz_mobile_connections/moz_mobile_connections_shim_test.js
NickProgramm/gaia
975a35c0f5010df341e96d6c5ec60217f5347412
[ "Apache-2.0" ]
1
2017-02-21T21:36:12.000Z
2017-02-21T21:36:30.000Z
disabled_apps/sms/services/test/unit/moz_mobile_connections/moz_mobile_connections_shim_test.js
NickProgramm/gaia
975a35c0f5010df341e96d6c5ec60217f5347412
[ "Apache-2.0" ]
1
2019-03-03T01:31:58.000Z
2019-03-03T01:31:58.000Z
/*global bridge, BroadcastChannel, MockMozMobileConnections, MocksHelper, MozMobileConnectionsShim, MozSettingsShim */ 'use strict'; require('/services/test/unit/mock_bridge.js'); require('/services/test/unit/mock_moz_mobile_connections.js'); require('/services/test/unit/moz_settings/mock_moz_settings_shim.js'); require('/views/shared/test/unit/mock_broadcast_channel.js'); require('/services/js/bridge_service_mixin.js'); require('/services/js/moz_mobile_connections/moz_mobile_connections_shim.js'); var MocksHelperForAttachment = new MocksHelper([ 'bridge', 'BroadcastChannel', 'MozMobileConnections', 'MozSettingsShim' ]).init(); suite('MozMobileConnectionsShim >', function() { var serviceStub; const APP_ID = 'fake-app-id'; MocksHelperForAttachment.attachTestHelpers(); suiteSetup(function() { serviceStub = sinon.stub({ method: () => {}, listen: () => {} }); sinon.spy(window, 'BroadcastChannel'); sinon.stub(bridge, 'service').returns(serviceStub); }); setup(function() { MozMobileConnectionsShim.init(APP_ID, MockMozMobileConnections); }); test('bridge service is correctly initialized', function() { sinon.assert.calledOnce(bridge.service); sinon.assert.calledWith(bridge.service, 'moz-mobile-connections-shim'); sinon.assert.calledTwice(serviceStub.listen); sinon.assert.calledWith( serviceStub.listen, sinon.match.instanceOf(BroadcastChannel) ); sinon.assert.calledWith( BroadcastChannel, 'moz-mobile-connections-shim-channel-' + APP_ID ); }); suite('methods for wrapping up API', function() { suite('getServiceIdByIccId', function() { test('returns the correct id', function() { assert.equal(MozMobileConnectionsShim.getServiceIdByIccId('SIM 1'), 0); assert.equal(MozMobileConnectionsShim.getServiceIdByIccId('SIM 2'), 1); assert.isNull(MozMobileConnectionsShim.getServiceIdByIccId('SIM 3')); }); }); suite('switchMmsSimHandler', function() { setup(function() { this.sinon.stub(MozSettingsShim, 'set'); }); test('serviceId is null', function(done) { MozMobileConnectionsShim.switchMmsSimHandler('SIM 3').then(() => { throw new Error('Resolve should not be called'); }, (err) => { assert.equal(err, 'NoSimCardError'); }).then(done, done); }); test('mozMobileConnection is already registered', function(done) { MockMozMobileConnections[0].data.state = 'registered'; MozMobileConnectionsShim.switchMmsSimHandler('SIM 1').then(() => { // No need to set the default serviceId sinon.assert.notCalled(MozSettingsShim.set); }).then(done, done); }); test('switch sim and return when state is ready', function(done) { this.sinon.stub(MockMozMobileConnections[0], 'addEventListener'); this.sinon.stub(MockMozMobileConnections[0], 'removeEventListener'); MockMozMobileConnections[0].data.state = 'searching'; MozMobileConnectionsShim.switchMmsSimHandler('SIM 1').then(() => { sinon.assert.calledWith(MozSettingsShim.set, { 'ril.mms.defaultServiceId': 0, 'ril.data.defaultServiceId': 0 }); sinon.assert.called(MockMozMobileConnections[0].removeEventListener); }).then(done, done); // Change target connection state to registered and invoke the event MockMozMobileConnections[0].data.state = 'registered'; MockMozMobileConnections[0].addEventListener.yield(); }); }); }); });
32.758929
79
0.667484
1d31ca8883393dca9632457ad01a8b75c485c1b1
3,049
js
JavaScript
andrea-castellucci/making_visible/sketchbook/13.TextHead-SR-ControlFontSize/sketch.js
andrea-castellucci/archive
27adc375cbd6f71dad9fac3c73cb732c74e352c4
[ "MIT" ]
1
2021-05-29T08:11:21.000Z
2021-05-29T08:11:21.000Z
andrea-castellucci/making_visible/sketchbook/13.TextHead-SR-ControlFontSize/sketch.js
andrea-castellucci/archive
27adc375cbd6f71dad9fac3c73cb732c74e352c4
[ "MIT" ]
29
2021-03-10T18:36:59.000Z
2021-06-20T14:33:16.000Z
andrea-castellucci/making_visible/sketchbook/13.TextHead-SR-ControlFontSize/sketch.js
andrea-castellucci/archive
27adc375cbd6f71dad9fac3c73cb732c74e352c4
[ "MIT" ]
14
2021-03-05T14:14:50.000Z
2021-03-05T14:16:18.000Z
// __ __ _ ____ ____ ____ __ // / _\ ( ( \( \( _ \( __) / _\ // / \/ / ) D ( ) / ) _) / \ // \_/\_/\_)__)(____/(__\_)(____)\_/\_/ // // - // TextHead-SR-ControlFontSize by Andrea [yourself, words, motion] // 2021 © Andrea @AndrCastellucci, Daniele @Fupete and the course DS-2021 at DESIGN.unirsm // github.com/ds-2021-unirsm — github.com/fupete — github.com/andrea-castellucci // Educational purposes, MIT License, 2021, San Marino // — // Credits/Thanks to: // // p5.speech.js Speech Recognition, Speech synthesis, R.Luke DuBois // The ABILITY lab, New York University // http://ability.nyu.edu/p5.js-speech/ // https://github.com/IDMNYU/p5.js-speech/blob/master/LICENSE // original license: MIT License 2017 // — // // Help: // [microfono] rilevamento del parlato per scrittura // [webcam] rilevamento movimenti del corpo // // — let video; let poseNet; let pose; let skeleton; // Settings let w, h; let lang = "it"; // Speech Object let speech; let recordingavviato = true; // Speech testo let testo = ""; let testoSplit = ""; let fraseRicostruita = ""; function setup() { createCanvas(640, 480); video = createCapture(VIDEO); video.hide(); poseNet = ml5.poseNet(video, modelLoaded); poseNet.on("pose", gotPoses); background(50); startRec(); } function startRec() { console.log("Inizia a parlare"); // Create a Speech Recognition object with callback speechRec = new p5.SpeechRec("it-IT", gotSpeech); // "Continuous recognition" (as opposed to one time only) let continuous = true; // If you want to try partial recognition (faster, less accurate) let interimResults = false; // This must come after setting the properties speechRec.start(continuous, interimResults); // Speech recognized event function gotSpeech() { // Something is there // Get it as a string // console.log(speechRec); if (speechRec.resultValue && recordingavviato == true) { testo = testo + " " + speechRec.resultString; // Show user console.log(testo); testoSplit = testo.split(" "); testoSplit.splice(0, 1); } } } function gotPoses(poses) { // console.log(poses); if (poses.length > 0) { // se è stata rilevata almeno una posa pose = poses[0].pose; // console.log(pose) skeleton = poses[0].skeleton; } } function modelLoaded() { console.log("poseNet ready"); } function draw() { background(50, 50); image(video, 0, 0); if (pose) { fill(177, 219, 231); textAlign(CENTER); leftWristX = pose.leftWrist.x; leftWristY = pose.leftWrist.y; rightWristX = pose.rightWrist.x; rightWristY = pose.rightWrist.y; let a = (pose.leftWrist.x + pose.rightWrist.x) / 2; let b = (pose.leftWrist.y + pose.rightWrist.y) / 2; let d = dist(leftWristX, leftWristY, rightWristX, rightWristY); textSize(d/5); let widthText = 400; let heightText = 800 push(); translate(-widthText/2, 0); text(testo, pose.nose.x, pose.nose.y, widthText, heightText); pop(); } }
25.198347
91
0.643162
1d32d72981e1b8c7961869f62229fa024eb739be
478
js
JavaScript
app/components/Footer/messages.js
iyang0/DMI-frontend
29d1b6ee7a06150ccf73120be94f520414854316
[ "MIT" ]
null
null
null
app/components/Footer/messages.js
iyang0/DMI-frontend
29d1b6ee7a06150ccf73120be94f520414854316
[ "MIT" ]
null
null
null
app/components/Footer/messages.js
iyang0/DMI-frontend
29d1b6ee7a06150ccf73120be94f520414854316
[ "MIT" ]
null
null
null
/* * Footer Messages * * This contains all the text for the Footer component. */ import { defineMessages } from 'react-intl'; export const scope = 'DMI-frontend.components.Footer'; export default defineMessages({ byMessage: { id: `${scope}.boilerplate.message`, defaultMessage: 'This project was made by Ivan Yang with the {boilerplate}.', }, forMessage: { id: `${scope}.author.message`, defaultMessage: ` Made for {for}. `, }, });
20.782609
67
0.644351
1d32f1231dc529b4a01c8cceab21b419d7cb35a2
627
js
JavaScript
routes/wx/wexin.js
chuilee/bigbig
9529360a63f569f5e0c61a736f3c5c9e97d5239e
[ "MIT" ]
null
null
null
routes/wx/wexin.js
chuilee/bigbig
9529360a63f569f5e0c61a736f3c5c9e97d5239e
[ "MIT" ]
null
null
null
routes/wx/wexin.js
chuilee/bigbig
9529360a63f569f5e0c61a736f3c5c9e97d5239e
[ "MIT" ]
null
null
null
const crypto = require('crypto') const TOKEN = 'paintersphotography' exports = module.exports = function (req, res) { var signature = req.query.signature; var timestamp = req.query.timestamp; var echostr = req.query.echostr; var nonce = req.query.nonce; var tmpArray = [nonce, timestamp, TOKEN]; tmpArray.sort(); var tmpStr = tmpArray.join(''); var shasum = crypto.createHash('sha1'); shasum.update(tmpStr) var shaResult = shasum.digest('hex'); if (signature == shaResult) { //验证成功 res.send(echostr); } else { //验证失败 console.log('not wexin server') res.send('not wexin server'); } }
25.08
48
0.668262
1d338ffab09888fd6e7d4ed0b9a3401046764608
220
js
JavaScript
client/app/main/main.controller.js
shijingjing1221/nodedemo
f766a1ef6e2ef82035c69db622f7c5ef73a3bc98
[ "Apache-2.0" ]
null
null
null
client/app/main/main.controller.js
shijingjing1221/nodedemo
f766a1ef6e2ef82035c69db622f7c5ef73a3bc98
[ "Apache-2.0" ]
null
null
null
client/app/main/main.controller.js
shijingjing1221/nodedemo
f766a1ef6e2ef82035c69db622f7c5ef73a3bc98
[ "Apache-2.0" ]
null
null
null
'use strict'; angular.module('nodedemoApp') .controller('MainCtrl', function ($scope, $translate, LocalizationService) { $translate.use(LocalizationService.favoriteLanguage); $scope.test = "nodedemo"; });
22
78
0.709091
1d33dc36d1ad8647786859f7cacb91aaf948777e
643
js
JavaScript
src/packs/component.js
briza23/responsive-auto-repair-website
8b9a2ca9dde55e0bb9f877da088e988bda7f8075
[ "MIT" ]
null
null
null
src/packs/component.js
briza23/responsive-auto-repair-website
8b9a2ca9dde55e0bb9f877da088e988bda7f8075
[ "MIT" ]
null
null
null
src/packs/component.js
briza23/responsive-auto-repair-website
8b9a2ca9dde55e0bb9f877da088e988bda7f8075
[ "MIT" ]
null
null
null
import { connect } from "react-redux"; import * as Actions from "./actions/actions"; import React from "react"; import Header from "./content/header"; import Footer from "./content/footer"; import Body from './content/body_content/home'; class Components extends React.Component { render() { return ( <div> <Header/> <Body/> <Footer/> </div> ); } } Components.propTypes = { }; function mapStateToProps(state) { return state; } const VisibleConfigs = connect( mapStateToProps, Actions )(Components); export default VisibleConfigs;
19.484848
47
0.603421
1d33e0b509ac801a236a3d6d2879823be4d7843b
6,206
js
JavaScript
test/Observer.js
smalluban/papillon
81e376e0b07578779cfc929b6dd4a4e26150a927
[ "MIT" ]
8
2015-07-01T11:24:34.000Z
2019-02-03T21:07:37.000Z
test/Observer.js
smalluban/papillon
81e376e0b07578779cfc929b6dd4a4e26150a927
[ "MIT" ]
null
null
null
test/Observer.js
smalluban/papillon
81e376e0b07578779cfc929b6dd4a4e26150a927
[ "MIT" ]
null
null
null
import { Observer, State } from '../papillon'; describe('Observer', () => { describe('constructor', () => { it('throw error for invalid arguments', () => { expect(() => new Observer()).toThrow(); expect(() => new Observer({})).toThrow(); expect(() => new Observer({}, 'one')).toThrow(); expect(() => new Observer(undefined, 'one', () => {})).toThrow(); }); it('throw error for non-configurable properties', () => { const host = {}; Object.defineProperty(host, 'one', { value: 'test', }); expect(() => new Observer(host, 'one', () => {})).toThrow(); }); }); describe('observe changes with host object', () => { let host; let list; let value; beforeEach(() => { value = 'one'; host = { one: 'one', get two() { return value; }, set two(newVal) { value = newVal; }, }; const observer = new Observer(host, ['one', 'two'], () => {}); list = observer.state.target; }); it('link watched property to list object', () => { expect(list.one).toEqual('one'); host.one = 'new value'; expect(list.one).toEqual('new value'); }); it('link watched getter/setter property to list object', () => { expect(host.two).toEqual('one'); expect(list.two).toEqual('one'); host.two = 'new value'; expect(list.two).toEqual('new value'); expect(value).toEqual('new value'); }); }); describe('check method', () => { let host; let observer; beforeEach(() => { host = { one: 'two', two: {} }; Object.defineProperty(host, 'three', { get: () => Math.random(), configurable: true, }); observer = new Observer(host, ['one', 'two', 'three'], () => {}); spyOn(observer, 'check'); }); it('is called when setting new value', () => { host.one = 'new value'; expect(observer.check).toHaveBeenCalled(); }); it('is not called when getting primitive watched property', () => { host.one; // eslint-disable-line expect(observer.check).not.toHaveBeenCalled(); }); it('is called when getting object watched property', () => { host.two; // eslint-disable-line expect(observer.check).toHaveBeenCalled(); }); it('is called for computed property with return new value', () => { host.three = 'new value'; expect(observer.check).toHaveBeenCalled(); }); it('is called for computed property with return new value', () => { host.three; // eslint-disable-line expect(observer.check).toHaveBeenCalled(); }); }); describe('callback', () => { let host; let spy; beforeEach(() => { host = { one: 'two' }; spy = jasmine.createSpy('spy'); new Observer(host, 'one', spy); // eslint-disable-line }); it('called when property changed before next repaint', (done) => { host.one = 'new value'; window.requestAnimationFrame(() => { expect(spy).toHaveBeenCalled(); done(); }); }); it('called with proper changelog', (done) => { host.one = 'new value'; window.requestAnimationFrame(() => { expect(spy).toHaveBeenCalledWith({ one: { type: 'set', oldValue: 'two' }, }); done(); }); }); it('not called when not watched property changed', (done) => { host.two = 'new value'; window.requestAnimationFrame(() => { expect(spy).not.toHaveBeenCalled(); done(); }); }); }); describe('destroy', () => { let host; let observer; let getter; let spy; beforeEach(() => { getter = () => 'one'; host = { one: 'one' }; spy = jasmine.createSpy('callback'); Object.defineProperty(host, 'two', { get: getter, set: getter, configurable: true, }); observer = new Observer(host, ['one', 'two'], spy); }); it('revert property to original definition', () => { let desc = Object.getOwnPropertyDescriptor(host, 'one'); expect(desc.get).toBeDefined(); observer.destroy(); desc = Object.getOwnPropertyDescriptor(host, 'one'); expect(desc.get).not.toBeDefined(); }); it('revert property with actual value', () => { host.one = 'two'; observer.destroy(); expect(host.one).toEqual('two'); }); it('revert property getter/setter methods', () => { observer.destroy(); const desc = Object.getOwnPropertyDescriptor(host, 'two'); expect(desc.get).toEqual(getter); }); it('cancel callback call', (done) => { host.one = 'two'; observer.destroy(); window.requestAnimationFrame(() => { expect(spy).not.toHaveBeenCalled(); done(); }); }); }); describe('with multiply instances', () => { let host; let spy; let observer1; let observer2; beforeEach(() => { host = { one: 'two' }; spy = jasmine.createSpy('callback'); observer1 = new Observer(host, 'one', () => {}); observer2 = new Observer(host, 'one', spy); }); it('work after destroying one of them', (done) => { observer1.destroy(); host.one = 'three'; window.requestAnimationFrame(() => { expect(spy).toHaveBeenCalled(); done(); }); }); it('revert to original state before observing', () => { observer1.destroy(); observer2.destroy(); expect(Object.getOwnPropertyDescriptor(host, 'one')).toEqual({ writable: true, enumerable: true, configurable: true, value: 'two', }); }); }); describe('nested observers', () => { it('callback in the same animation frame', (done) => { let frame1; let frame2; const host = {}; new Observer(host, 'test1', () => { // eslint-disable-line frame1 = State.now(); expect(frame1).toEqual(frame2); done(); }); new Observer(host, 'test2', () => { // eslint-disable-line frame2 = State.now(); host.test1 = 'new value'; }); host.test2 = 'new value'; }); }); });
26.75
71
0.533194
1d387836037f7bfc900c2bbfb6f39e00393cd256
1,953
js
JavaScript
js/LighterOverlay.js
truemaxdh/SpecialEffects
c4247fb6ba5c05606d643bdefc4db26e6b144e9b
[ "MIT" ]
null
null
null
js/LighterOverlay.js
truemaxdh/SpecialEffects
c4247fb6ba5c05606d643bdefc4db26e6b144e9b
[ "MIT" ]
null
null
null
js/LighterOverlay.js
truemaxdh/SpecialEffects
c4247fb6ba5c05606d643bdefc4db26e6b144e9b
[ "MIT" ]
null
null
null
if (typeof specialEffects === 'undefined' || !specialEffects) { specialEffects = {}; } specialEffects.lighterOverlay = function(el) { console.log(el.style); const obj = this.lighterOverlay; obj.objName = "lighterOverlay"; this.runningObj = obj; const shapeCnt = 200; const bgColor = "black"; var cnv_bg = document.createElement("CANVAS"); cnv_bg.style.position = "relative"; cnv_bg.style.width = el.style.width; cnv_bg.style.height = el.style.height; cnv_bg.id = "cnv_bg"; cnv_bg.width = cnv_bg.style.width.replace("px",""); cnv_bg.height = cnv_bg.style.height.replace("px",""); el.appendChild(cnv_bg); var ctx_bg = cnv_bg.getContext("2d"); var w = cnv_bg.width; var h = cnv_bg.height; // --------- // bg canvas // --------- ctx_bg.fillStyle = bgColor; ctx_bg.fillRect(0, 0, w, h); this.lighterOverlay.w = w; this.lighterOverlay.h = h; this.lighterOverlay.shapeCnt = shapeCnt; this.lighterOverlay.ctx_bg = ctx_bg; this.lighterOverlay.drawFrm(); }; specialEffects.lighterOverlay.drawFrm = function(timeStamp) { const obj = specialEffects.lighterOverlay; if (!obj.lastTimeStamp) obj.lastTimeStamp = timeStamp; if ((timeStamp - obj.lastTimeStamp) > 200) { obj.lastTimeStamp = timeStamp; var w = specialEffects.lighterOverlay.w; var h = specialEffects.lighterOverlay.h; var ctx_bg = specialEffects.lighterOverlay.ctx_bg; var cx = Math.random() * w; var cy = Math.random() * h; var r = Math.random() * ((w > h) ? (h / 7) : (w / 7)); var rgb = "rgba(" + (Math.random() * 256) + "," + (Math.random() * 256) + "," + (Math.random() * 256) + ")"; ctx_bg.globalCompositeOperation = 'lighter'; ctx_bg.beginPath(); ctx_bg.fillStyle = rgb; ctx_bg.arc(cx, cy, r, 0, 2 * Math.PI); ctx_bg.fill(); } if (specialEffects.runningObj.objName == obj.objName) { if (--obj.shapeCnt > 0) requestAnimationFrame(obj.drawFrm); } }
28.304348
112
0.646697
1d3a392126311a43f08db20522051108aab75e22
253
js
JavaScript
app/controllers/mappers/login.server.mapper.js
RafaelMih/MarriedApp-NodeJS
f55cc8be9f301817aaf2769239f183a0aba9a193
[ "MIT" ]
null
null
null
app/controllers/mappers/login.server.mapper.js
RafaelMih/MarriedApp-NodeJS
f55cc8be9f301817aaf2769239f183a0aba9a193
[ "MIT" ]
null
null
null
app/controllers/mappers/login.server.mapper.js
RafaelMih/MarriedApp-NodeJS
f55cc8be9f301817aaf2769239f183a0aba9a193
[ "MIT" ]
null
null
null
'use strict'; /** * Mapper login object */ exports.User = function(user) { var outUser = { id : user._id, name : user.firstName + ' ' + user.lastName, type : user.roles[0], login : user.username, email : user.email }; return outUser; };
15.8125
46
0.612648
1d3ab532d4fba0f86ba3aa533322ed2052db2dab
346
js
JavaScript
config/networks/ganache/signers.js
tpscrpt/teller-protocol-v1
e5d0f1a927c4bb2acceff17ffcf8394625f98c62
[ "MIT" ]
null
null
null
config/networks/ganache/signers.js
tpscrpt/teller-protocol-v1
e5d0f1a927c4bb2acceff17ffcf8394625f98c62
[ "MIT" ]
null
null
null
config/networks/ganache/signers.js
tpscrpt/teller-protocol-v1
e5d0f1a927c4bb2acceff17ffcf8394625f98c62
[ "MIT" ]
null
null
null
module.exports = { _1: '0xE8bF0ceF0Bf531Fd56081Ad0B85706cE37A7FD34', _2: '0x34fA03245325fd8cf67C694685932B73aC73666C', _3: '0x981D72d7E8dCaeae14D10db3A94f50958904C117', _4: '0xa75f98d2566673De80Ac4169Deab45c6adad3164', _5: '0x924Af6Cfa15F76E04763D9e24a1c892fD7767983', _6: '0x3Eb394E83f82be8ed7ac86aF0DcbdaE4890Be307', };
38.444444
53
0.800578
1d3d9d79c741ad35622441ab3bb28bb6eff32a07
442
js
JavaScript
lulu_birthday/src/config.js
ykss/lulu_birthday
2d225e73651cfec09ffb4f0a3a5a597e9c4ac07d
[ "MIT" ]
null
null
null
lulu_birthday/src/config.js
ykss/lulu_birthday
2d225e73651cfec09ffb4f0a3a5a597e9c4ac07d
[ "MIT" ]
null
null
null
lulu_birthday/src/config.js
ykss/lulu_birthday
2d225e73651cfec09ffb4f0a3a5a597e9c4ac07d
[ "MIT" ]
null
null
null
import { KAKAO_MAP_API_KEY, T_MAP_API_KEY } from "./API_KEY"; const config = { global: { kakaomapAPIKey: KAKAO_MAP_API_KEY, tmapAPIKey: T_MAP_API_KEY, }, title: `루루의 네번째 생일파티🎂`, author: { name: "루루", }, place: { name: "리블링코코", address: "경기 남양주시 별내면 송산로 519-7 1층", contact: "031-527-2053", latitude: 37.6869859, longitude: 127.133569, }, date: "2021년 12월 4일 토요일 5시", }; export default config;
19.217391
61
0.61991
1d3dbebe45baeebd8175ee0647c45ae659b2ca5d
391
js
JavaScript
week-5/es5-built-in-functions.js
VisionsICStudios/web-231
4fa8ffd0ee0a048bf83beb49c9c48579d9c3f158
[ "MIT" ]
1
2020-07-01T03:58:21.000Z
2020-07-01T03:58:21.000Z
week-5/es5-built-in-functions.js
VisionsICStudios/web-231
4fa8ffd0ee0a048bf83beb49c9c48579d9c3f158
[ "MIT" ]
null
null
null
week-5/es5-built-in-functions.js
VisionsICStudios/web-231
4fa8ffd0ee0a048bf83beb49c9c48579d9c3f158
[ "MIT" ]
null
null
null
/* ============================================ ; Title: es5-built-in-functions.js ; Author: Professor Krasso ; Date: 25 June 2017 ; Description: Demonstrates how to loop through an array using the forEach and arrow functions ;=========================================== */ // array of numbers const numbers = [1, 2, 3, 4, 5]; // output numbers.forEach((num) => { console.log(num) })
23
94
0.526854
1d3fbc8a6641780985980420f30938163682ad68
5,420
js
JavaScript
pages/coin/[id].js
Mridul2820/crypto-check
6b05cc5282e1587ad58feaff5d76483046f89290
[ "MIT" ]
null
null
null
pages/coin/[id].js
Mridul2820/crypto-check
6b05cc5282e1587ad58feaff5d76483046f89290
[ "MIT" ]
16
2022-01-05T19:55:04.000Z
2022-01-22T10:48:17.000Z
pages/coin/[id].js
Mridul2820/crypto-check
6b05cc5282e1587ad58feaff5d76483046f89290
[ "MIT" ]
null
null
null
import React, { useEffect, useState } from 'react' import dynamic from 'next/dynamic'; import { NextSeo } from 'next-seo'; import { useRouter } from 'next/router'; import axios from 'axios'; import { useRecoilValue } from 'recoil'; import { currencyState } from '../../atoms/currencyAtom'; const CoinMarket = dynamic(() => import('../../components/detail/CoinMarket')); const PriceChange = dynamic(() => import('../../components/detail/PriceChange')); const SocialMarket = dynamic(() => import('../../components/detail/SocialMarket')); const CoinDetail = dynamic(() => import('../../components/detail/CoinDetail')); const PriceChartFull = dynamic(() => import('../../components/detail/PriceChartFull')); const CoinDescription = dynamic(() => import('../../components/detail/CoinDescription')); const CoinNews = dynamic(() => import('../../components/detail/CoinNews')); import Loader from '../../components/widget/Loader'; const { SITE_URL } = process.env const { THEGUARDIAN_API_KEY } = process.env const Coin = () => { const router = useRouter() const { id } = router.query const [coin, setCoin] = useState([]) const [price, setPrice] = useState([]) const [news, setNews] = useState([]) const [loading, setLoading] = useState(true) const currencyId = useRecoilValue(currencyState); const getCoinData = async() => { const { data } = await axios.get( `https://api.coingecko.com/api/v3/coins/${id}?tickers=false&developer_data=false&community_data=false&localization=false` ); setCoin(data) setLoading(false) } const getPriceData = async() => { const { data } = await axios.get( `https://api.coingecko.com/api/v3/coins/${id}/market_chart?vs_currency=${currencyId}&days=7` ); setPrice(data) } const getNewsData = async() => { const data = await axios.get( `https://content.guardianapis.com/search?q=${id} OR ${coin.id}&query-fields=headline,thumbnail,description&order-by=newest&page=1&page-size=6&show-elements=image&show-fields=headline,thumbnail,short-url&api-key=${THEGUARDIAN_API_KEY}` ); setNews(data?.data?.response?.results) } useEffect(() => { if(!router.isReady) return; if(coin){ getNewsData() } getCoinData() const interval = setInterval(() => { getCoinData() }, 60000); return () => clearInterval(interval); // eslint-disable-next-line }, [router.isReady]); useEffect(() => { if(!router.isReady) return; getPriceData() const interval = setInterval(() => { getPriceData() }, 60000); return () => clearInterval(interval); // eslint-disable-next-line }, [currencyId, router.isReady]); const SEO = { title: `${coin?.name} (${coin?.symbol?.toUpperCase()}) info, price today, market cap`, description: `View ${coin?.name} crypto price and chart, ${coin?.symbol?.toUpperCase()} market cap, circulating supply, latest news and more.`, canonical: `${SITE_URL}/coin/${coin?.id}`, openGraph: { title: `${coin?.name} (${coin?.symbol?.toUpperCase()}) info, price today, market cap`, url: `${SITE_URL}/coin/${coin?.id}`, description: `View ${coin?.name} crypto price and chart, ${coin?.symbol?.toUpperCase()} market cap, circulating supply, latest news and more.`, images: [ { url: coin?.image?.large, width: 300, height: 300, alt: coin?.name } ], } }; if(loading) return <Loader /> return ( <div className="p-4 min-h-[calc(100vh-112px)] bg-light-blue mb-5"> <NextSeo {...SEO} /> <CoinDetail coin={coin} /> <PriceChange market={coin.market_data} /> <div className="flex gap-y-4 gap-x-8 flex-col md:flex-row max-w-[1000px] mx-auto mt-8"> <CoinMarket coinName={coin.name} coinDate={coin.genesis_date} coinMarket={coin.market_data} /> <SocialMarket coinName={coin.name} Links={coin.links} /> </div> {price?.prices && <div className="flex flex-col justify-center items-center mt-8 shadow-bs2 w-full max-w-[1000px] mx-auto rounded-md bg-white p-3 select-none"> <p className='font-semibold text-lg mb-5 text-center'> {coin.name} price in Last 7 Days </p> <div className="w-full h-52 md:h-80"> <PriceChartFull prices={price?.prices} /> </div> </div> } {coin.description.en && <CoinDescription name={coin.name} description={coin.description.en} /> } {news?.length > 0 && <CoinNews name={coin.name} newsList={news} /> } </div> ) } export default Coin
34.303797
246
0.535609
1d4049b35a9fefc03fdffb5f3638713d557be804
10,556
js
JavaScript
src/Pages/Album.js
HicoderDR/vqa_album
8d1549ac7a92f4406a765583032118eb44064f27
[ "MIT" ]
null
null
null
src/Pages/Album.js
HicoderDR/vqa_album
8d1549ac7a92f4406a765583032118eb44064f27
[ "MIT" ]
null
null
null
src/Pages/Album.js
HicoderDR/vqa_album
8d1549ac7a92f4406a765583032118eb44064f27
[ "MIT" ]
null
null
null
import React, { useState, useEffect } from 'react'; import AppBar from '@material-ui/core/AppBar'; import Button from '@material-ui/core/Button'; import CameraIcon from '@material-ui/icons/PhotoCamera'; import Card from '@material-ui/core/Card'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import CardMedia from '@material-ui/core/CardMedia'; import CssBaseline from '@material-ui/core/CssBaseline'; import Grid from '@material-ui/core/Grid'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import { makeStyles,useTheme } from '@material-ui/core/styles'; import Container from '@material-ui/core/Container'; import Link from '@material-ui/core/Link'; import Fade from '@material-ui/core/Fade'; import Grow from '@material-ui/core/Grow'; import CircleStatus from './CircleStatus' import List from '@material-ui/core/List'; import Divider from '@material-ui/core/Divider'; import ListItem from '@material-ui/core/ListItem'; import Drawer from '@material-ui/core/Drawer'; import ListItemText from '@material-ui/core/ListItemText'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'; import ChevronRightIcon from '@material-ui/icons/ChevronRight'; import clsx from 'clsx'; import mockdata from './vqa_album.json' function Copyright() { return ( <Typography variant="body2" color="textSecondary" align="center"> {'Copyright © '} <Link color="inherit" href="https://hicoderdr.github.io/"> HicoDR </Link>{' '} {new Date().getFullYear()} {'.'} </Typography> ); } const drawerWidth = 240; const useStyles = makeStyles((theme) => ({ icon: { marginRight: theme.spacing(2), }, heroContent: { backgroundColor: theme.palette.background.paper, padding: theme.spacing(8, 0, 6), }, heroButtons: { marginTop: theme.spacing(4), }, cardGrid: { paddingTop: theme.spacing(8), paddingBottom: theme.spacing(8), }, card: { height: '100%', display: 'flex', flexDirection: 'column', }, cardMedia: { paddingTop: '56.25%', // 16:9 }, cardContent: { flexGrow: 1, }, footer: { backgroundColor: theme.palette.background.paper, padding: theme.spacing(6), }, drawer: { width: drawerWidth, flexShrink: 0, }, drawerPaper: { width: drawerWidth, }, // necessary for content to be below app bar toolbar: theme.mixins.toolbar, content: { flexGrow: 1, backgroundColor: theme.palette.background.default, padding: theme.spacing(3), }, })); const ques=['what color is/are the','what type/kind of','how many/what number is','how many people are','what time','what/what is/what is the','what sport is','what animal is','what is in the','what is on the','what room is','why'] const restype=[ ['what color are the','what color is the'], ['what type of','what kind of'],['how many','what number is'], ['how many people are'],['what time'],['what','what is the','what is'], ['what sport is'],['what animal is'],['what is in the'], ['what is on the'],['what room is'],['why'], ] export default function Album() { const classes = useStyles(); const theme = useTheme(); const [fade,setfade]=useState(true); const [showres,setshowres]=useState(false); const [slted,setslted]=useState(0) const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; return ( <React.Fragment> <CssBaseline /> <AppBar position="relative" className={clsx(classes.appBar, { [classes.appBarShift]: open, })} > <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" className={clsx(classes.menuButton, open && classes.hide)} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap> RGCN-VQA </Typography> </Toolbar> </AppBar> <Drawer className={classes.drawer} variant="persistent" anchor="left" open={open} classes={{ paper: classes.drawerPaper, }} > <div className={classes.drawerHeader}> <IconButton onClick={handleDrawerClose}> {theme.direction === 'ltr' ? <ChevronLeftIcon /> : <ChevronRightIcon />} </IconButton> </div> <Divider /> <List> {ques.map(function(item){ function click(item){ var index = ques.indexOf(item) setslted(index) } return( <ListItem button key={item} onClick={click.bind(this,item)} selected={slted==ques.indexOf(item)} > <ListItemText primary={item} /> </ListItem> ) },this) } </List> </Drawer> <main> {/* Hero unit */} <div className={classes.heroContent}> {showres? <Grow in={showres}> {sections()} </Grow> : <> <Grid container spacing={2} justify="center" style={{position:'absolute'}}> {fade ?<div> </div> : <CircleStatus size={100} /> } </Grid> <Fade in={fade}> {selector()} </Fade> </> } </div> </main> {/* Footer */} <footer className={classes.footer}> <Typography variant="h6" align="center" gutterBottom> 华东理工大学 大学生创新创业项目 </Typography> <Typography variant="subtitle1" align="center" color="textSecondary" component="p"> 指导老师:张静 </Typography> <Copyright /> </footer> {/* End footer */} </React.Fragment> ); function sectionlist(slted){ var ans=[] var res=[] var qs=restype[slted] for(var i in mockdata){ var data=mockdata[i] if(qs.indexOf(data['question_type'])!=-1){ var label=data['label'] for(var j in label){ if(ans.indexOf(j)==-1&&label[j]>=0.9){ ans.push(j) res.push([]) var index=ans.indexOf(j) res[index]=res[index].concat([data['img_id']]) }else if(ans.indexOf(j)&&label[j]>=0.9){ var index=ans.indexOf(j) if(res[index].indexOf(data['img_id'])==-1) res[index]=res[index].concat([data['img_id']]) } } } } return ( <div> <Container maxWidth="md"> {ans.map((item,idx)=>{ return( <div> <Typography component="h4" variant="h4" align="center" color="textPrimary" gutterBottom> {item} </Typography> <Grid container spacing={4}> {res[idx].map((id)=>{ return ( <Grid item key={id} xs={12} sm={6} md={4}> <Card className={classes.card}> <CardMedia className={classes.cardMedia} image={require('../vqa_album/'+id+'.jpg')} title="Image title" /> </Card> </Grid> ) })} </Grid> </div> ) })}</Container> </div> ) } function sections(props){ var imglist=[] return ( <div {...props}> <Container maxWidth="md"> <Typography component="h1" variant="h2" align="center" color="textPrimary" gutterBottom> {ques[slted]} </Typography> {sectionlist(slted)} </Container> </div> ); } function selector(props){ var imglist=[] return ( <div {...props}> <Container maxWidth="md"> <Typography component="h1" variant="h2" align="center" color="textPrimary" gutterBottom> Now,let us select one question! </Typography> <Grid container spacing={2} justify="center"> {ques.map(function(item){ function click(item){ setfade(false) setTimeout(function(){setshowres(true)},5000) var index = ques.indexOf(item) setslted(index) } return( <Grid item> <Button variant="outlined" color="primary" size="large" onClick={click.bind(this,item)} > {item} </Button> </Grid> ) },this) } </Grid> </Container> <Container className={classes.cardGrid} maxWidth="md"> {/* End hero unit */} <Grid container spacing={4}> {mockdata.map((item) => { var img_id=item['img_id'] if(imglist.indexOf(img_id)==-1){ imglist.push(img_id) return( <Grid item key={item['img_id']} xs={12} sm={6} md={4}> <Card className={classes.card}> <CardMedia className={classes.cardMedia} image={require('../vqa_album/'+item['img_id']+'.jpg')} title="Image title" /> </Card> </Grid> ) } })} </Grid> </Container> </div> ); } // function selector1(props){ // var imglist=[] // return ( // <Container maxWidth="md"> // <Typography component="h1" variant="h2" align="center" color="textPrimary" gutterBottom> // {slted} // </Typography> // <Grid container spacing={4}> // {sectionlist(slted)} // </Grid> // </Container> // ); // } }
29.651685
231
0.511368
1d4111b233eca740995f2529dc96ebb6903918f2
1,168
js
JavaScript
test/harness/testTypedArray.js
polsevev/test262
04cd6da021461653b2fb1076392b6e13ffb9b1d7
[ "BSD-3-Clause" ]
2
2021-10-10T09:40:06.000Z
2021-11-09T10:46:48.000Z
test/harness/testTypedArray.js
polsevev/test262
04cd6da021461653b2fb1076392b6e13ffb9b1d7
[ "BSD-3-Clause" ]
null
null
null
test/harness/testTypedArray.js
polsevev/test262
04cd6da021461653b2fb1076392b6e13ffb9b1d7
[ "BSD-3-Clause" ]
2
2022-01-09T17:46:14.000Z
2022-03-29T03:16:54.000Z
// Copyright (c) 2017 Rick Waldron. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: > Including testTypedArray.js will expose: var typedArrayConstructors = [ array of TypedArray constructors ] var TypedArray testWithTypedArrayConstructors() testTypedArrayConversions() includes: [testTypedArray.js] features: [TypedArray] ---*/ assert(typeof TypedArray === "function"); assert.sameValue(TypedArray, Object.getPrototypeOf(Uint8Array)); var callCount = 0; testWithTypedArrayConstructors(() => callCount++); assert.sameValue(callCount, 9); assert.sameValue(typedArrayConstructors[0], Float64Array); assert.sameValue(typedArrayConstructors[1], Float32Array); assert.sameValue(typedArrayConstructors[2], Int32Array); assert.sameValue(typedArrayConstructors[3], Int16Array); assert.sameValue(typedArrayConstructors[4], Int8Array); assert.sameValue(typedArrayConstructors[5], Uint32Array); assert.sameValue(typedArrayConstructors[6], Uint16Array); assert.sameValue(typedArrayConstructors[7], Uint8Array); assert.sameValue(typedArrayConstructors[8], Uint8ClampedArray);
35.393939
73
0.780822
1d41716e241e96fa59536b5b894de8e57aee38c3
451
js
JavaScript
src/privates/_isArrayIndex.js
ascartabelli/lamb
4e39fc297b07f84b410ce73c5eb750c9838658e4
[ "MIT" ]
19
2015-04-10T13:58:27.000Z
2021-09-23T19:37:48.000Z
src/privates/_isArrayIndex.js
ascartabelli/lamb
4e39fc297b07f84b410ce73c5eb750c9838658e4
[ "MIT" ]
8
2016-09-03T05:58:05.000Z
2021-05-28T22:35:17.000Z
src/privates/_isArrayIndex.js
ascartabelli/lamb
4e39fc297b07f84b410ce73c5eb750c9838658e4
[ "MIT" ]
7
2015-04-10T10:22:08.000Z
2018-02-06T20:45:56.000Z
import _isEnumerable from "./_isEnumerable"; /** * Accepts a target object and a key name and verifies that the target is an array and that * the key is an existing index. * @private * @param {Object} target * @param {String|Number} key * @returns {Boolean} */ function _isArrayIndex (target, key) { var n = +key; return Array.isArray(target) && n % 1 === 0 && !(n < 0 && _isEnumerable(target, key)); } export default _isArrayIndex;
25.055556
91
0.669623
1d41a8944051f5d9c9cdc8a302df1cb7b7373dbd
804
js
JavaScript
src/redux/reducers/todoReducer.js
naxir/todo
8191058ba7c6c45d9ba8c48d082ac8ceb9bcc24e
[ "Apache-2.0" ]
null
null
null
src/redux/reducers/todoReducer.js
naxir/todo
8191058ba7c6c45d9ba8c48d082ac8ceb9bcc24e
[ "Apache-2.0" ]
null
null
null
src/redux/reducers/todoReducer.js
naxir/todo
8191058ba7c6c45d9ba8c48d082ac8ceb9bcc24e
[ "Apache-2.0" ]
null
null
null
import { ADD_TODO, EDIT_TODO, REMOVE_TODO, TOGGLE_TODO } from '../types' const todoReducer =(state = [], action)=> { switch (action.type) { case ADD_TODO: return [ ...state, { todo: action.todo, id: action.id, isCompleted: false } ] case EDIT_TODO: return state.map(todo => { return todo.id === action.id ? Object.assign({}, todo, { todo: action.todo }) : todo }) case REMOVE_TODO: return state.filter(todo => todo.id !== action.id) case TOGGLE_TODO: return state.map(todo => { return todo.id === action.id ? { ...todo, isCompleted: !todo.isCompleted } : todo }) default: return state } } export {todoReducer};
24.363636
72
0.518657
1d41d83383f01143e22d23fea280ccb54fa88e31
400
js
JavaScript
resources/js/lang/es/sidebar.js
vishnuvs369/Laravel-BlogWebsite
45362b66d5eae7912aaa343ff0d420781194d921
[ "MIT" ]
3,272
2016-12-27T06:41:56.000Z
2022-03-24T09:10:26.000Z
resources/js/lang/es/sidebar.js
vishnuvs369/Laravel-BlogWebsite
45362b66d5eae7912aaa343ff0d420781194d921
[ "MIT" ]
172
2016-12-27T09:21:40.000Z
2022-02-27T05:14:00.000Z
resources/js/lang/es/sidebar.js
vishnuvs369/Laravel-BlogWebsite
45362b66d5eae7912aaa343ff0d420781194d921
[ "MIT" ]
1,123
2016-12-27T07:12:10.000Z
2022-03-23T14:03:39.000Z
export default { dashboard: 'Tablero', user: 'Usuarios', article: 'Artículos', discussion: 'Discusión', comment: 'Comentarios', tag: 'Etiquetas', file: 'Archivos', category: 'Categorías', link: 'Enlaces', visitor: 'Visitantes', role: 'Roles', system: 'Sistemas', modules: { base: 'Módulo base', content: 'Módulo de contenido', system: 'Módulo del sistema' } }
20
35
0.635
1d438802f440443fd53374f6e665e3dad624db5a
773
js
JavaScript
node_modules/gatsby-remark-vscode/src/host.js
jgaya/condetodo
9d567483454358e8077e0a61b34ab32929eb090b
[ "MIT" ]
null
null
null
node_modules/gatsby-remark-vscode/src/host.js
jgaya/condetodo
9d567483454358e8077e0a61b34ab32929eb090b
[ "MIT" ]
null
null
null
node_modules/gatsby-remark-vscode/src/host.js
jgaya/condetodo
9d567483454358e8077e0a61b34ab32929eb090b
[ "MIT" ]
null
null
null
// @ts-check const request = require('request'); const decompress = require('decompress'); const { gunzip } = require('./utils'); /** @type {Host} */ const host = { fetch: (url, options) => new Promise((resolve, reject) => { request.get(url, options, async (error, res, body) => { if (error) { return reject(error); } if (res.statusCode !== 200) { return resolve({ body, statusCode: res.statusCode }); } if (res.headers['content-encoding'] === 'gzip') { const unzipped = await gunzip(body); return resolve({ body: unzipped, statusCode: res.statusCode }); } resolve({ body, statusCode: res.statusCode }); }); }), decompress }; module.exports = host;
25.766667
73
0.556274
1d4560a8db586ca6aeb5e8376028ad5c3103a313
453
js
JavaScript
src/Home.js
DevinDai13/TFArchive
bc7ba78c054912626521897db29d87cbab7c2950
[ "Apache-2.0" ]
null
null
null
src/Home.js
DevinDai13/TFArchive
bc7ba78c054912626521897db29d87cbab7c2950
[ "Apache-2.0" ]
null
null
null
src/Home.js
DevinDai13/TFArchive
bc7ba78c054912626521897db29d87cbab7c2950
[ "Apache-2.0" ]
null
null
null
import withRoot from './withRoot'; import React from 'react'; import ProductCategories from './ProductCategories'; import AppFooter from './AppFooter'; import ProductHero from './ProductHero'; import AppAppBar from './AppAppBar'; function Index() { return ( <React.Fragment> <AppAppBar /> <ProductHero /> <ProductCategories /> <AppFooter /> </React.Fragment> ); } export default withRoot(Index);
22.65
53
0.651214
1d45692bab8d0aef704688a80242351966e804d1
631
js
JavaScript
src/theme/Introduction.js
marbar3778/tauri-docs
1b34c92dd6f7a4e2b4bad0ae61479ea868a6aee5
[ "MIT" ]
null
null
null
src/theme/Introduction.js
marbar3778/tauri-docs
1b34c92dd6f7a4e2b4bad0ae61479ea868a6aee5
[ "MIT" ]
null
null
null
src/theme/Introduction.js
marbar3778/tauri-docs
1b34c92dd6f7a4e2b4bad0ae61479ea868a6aee5
[ "MIT" ]
null
null
null
import Mermaid from './Mermaid' import React from 'react' export default () => { const chart = ` graph TD U-->JS JS-->B B-->BUILD B-->DEV DEV==>DBG BUILD-->BND BND==>WIN U(HTML<br>CSS<br>JS) JS(Tauri Node<br>CLI) style JS stroke:#77CFE4,stroke-width:4px WIN[Installer for<br>target platform] B{Tauri Core<br>CLI} style B stroke:#D08050,stroke-width:4px BND((Tauri<br>Bundler)) style BND stroke:#EFD3AF, stroke-width:4px DBG[WebView:Debug<br>with HMR] ` return <div style={{overflow: 'auto'}}><Mermaid chart={chart} /></div> }
24.269231
72
0.58954
1d45a18086e5bd08ae4e04feb9b6943d8e634c5a
1,739
js
JavaScript
src/components/Contact.js
LeoRoma/Leo-Portfolio-React
06a4622afa004a9f43a1e509caa622a163962614
[ "MIT" ]
null
null
null
src/components/Contact.js
LeoRoma/Leo-Portfolio-React
06a4622afa004a9f43a1e509caa622a163962614
[ "MIT" ]
null
null
null
src/components/Contact.js
LeoRoma/Leo-Portfolio-React
06a4622afa004a9f43a1e509caa622a163962614
[ "MIT" ]
null
null
null
// Customize this 'myform.js' script and add it to your JS bundle. // Then import it with 'import MyForm from "./myform.js"'. // Finally, add a <MyForm/> element whereever you wish to display the form. import React, {Component} from "react"; import {FaGithub, FaLinkedin} from 'react-icons/fa'; import {Row, Col} from 'react-bootstrap'; import Manella from '../images/manella.jpg'; class Contact extends Component{ render() { return ( <section id="contact"> <div className="contact" style={{width:'80%', margin:'auto'}}> <Row className="card-row" style={{marginLeft:'0%'}}> <Col lg={6}> <div className="card-o" > <h1>Contact</h1> <p> For any projects, enquiries, or if you just want to say hi, drop me an email at: xiajtn@gmail.com </p> <p> Or check me out on socials: </p> <div className="social-links-contact"> <a href="https://www.linkedin.com/in/jia-tian-leo-xia" rel="noopenr noreferrer" target="_blank"> <FaLinkedin /> </a> <a href="https://github.com/LeoRoma" rel="noopenr noreferrer" target="_blank" style={{paddingLeft:"30px"}}> <FaGithub /> </a> </div> </div> </Col> <Col lg={6} className="contact-img"> <img src={Manella} alt="contact"></img> </Col> </Row> </div> </section> ); } } export default Contact;
34.78
131
0.481311
1d45bf0633acbf399ab7df0d6ec5ca9f3ea04d9c
2,314
js
JavaScript
core/modules/resize.js
isdampe/BosonEditorExperimental
2f2cdbd118ce938a512fcf61c19438aef3d41bbc
[ "MIT" ]
77
2015-05-30T08:42:30.000Z
2022-02-04T17:41:48.000Z
core/modules/resize.js
isdampe/BosonEditorExperimental
2f2cdbd118ce938a512fcf61c19438aef3d41bbc
[ "MIT" ]
7
2015-06-04T09:56:45.000Z
2018-11-01T12:29:40.000Z
core/modules/resize.js
isdampe/BosonEditorExperimental
2f2cdbd118ce938a512fcf61c19438aef3d41bbc
[ "MIT" ]
30
2015-06-17T13:24:55.000Z
2021-06-23T15:43:50.000Z
var resize = this; var bs, elements, resizeElement, sideBarWidth; var resizeTimer = false; exports.init = function(core) { bs = core.bs; elements = core.elements; sideBarWidth = core.config.sidebarWidth; resizeElement = window.document.createElement("div"); resizeElement.className = "resize-element"; resizeElement.setAttribute("draggable", "true"); core.elements.body.appendChild(resizeElement); //Set sidebar width from config. resize.setWidthByConfig(core.config.sidebarWidth); resize.render(); window.addEventListener("resize", function(e) { resize.render(); }); resizeElement.addEventListener("drag", function(e) { /* Throttle the resize function and let chromium smoothly animate the resize with css. */ if (resizeTimer === false) { resize.setWidthByConfig(e.clientX); resizeTimer = setTimeout(function() { resizeTimer = false; }, 30); } }); resizeElement.addEventListener("dragend", function(e) { bs.updateConfig("sidebarWidth", sideBarWidth); resize.render(); }); }; exports.render = function() { //Render the bar in the correct location. var sidebar_width, element_width, sidebar_offset, x; sidebar_width = window.getComputedStyle(elements.sidebar).width; element_width = window.getComputedStyle(resizeElement).width; x = parseInt(sidebar_width, 10); resizeElement.style.left = x + "px"; }; exports.setWidthByHook = function(event) { if (event.rect.width < 160 || event.rect.width > 639) { return; } var target = event.target, x = (parseFloat(target.getAttribute('data-x')) || 0), y = (parseFloat(target.getAttribute('data-y')) || 0); target.style.width = event.rect.width + 'px'; var calcString = "calc(100% - " + event.rect.width + "px)"; elements.editorEntryPoint.style.width = calcString; elements.editorEntryPoint.style.left = event.rect.width + 'px'; elements.topbar.style.width = calcString; elements.topbar.style.left = event.rect.width + 'px'; target.setAttribute('data-x', x); target.setAttribute('data-y', y); sideBarWidth = event.rect.width; resize.render(); }; exports.setWidthByConfig = function(width) { var ev = {}; ev.rect = {}; ev.rect.width = width; ev.target = elements.sidebar; resize.setWidthByHook(ev); };
24.357895
66
0.687554
1d48103c3b0e6f7fbda8e44b5737edd27edc0b99
2,393
js
JavaScript
main.js
Lucsvieirabr/PrimeiroApp
dc7dda3da82163f9fdcba751b223453b454a2a31
[ "MIT" ]
null
null
null
main.js
Lucsvieirabr/PrimeiroApp
dc7dda3da82163f9fdcba751b223453b454a2a31
[ "MIT" ]
null
null
null
main.js
Lucsvieirabr/PrimeiroApp
dc7dda3da82163f9fdcba751b223453b454a2a31
[ "MIT" ]
null
null
null
var tarefas = JSON.parse(localStorage.getItem('tarefas')) || []; var count = localStorage.getItem('counter') || 0; function listarTarefas() { var ul = document.getElementById('tarefas'); ul.innerHTML = "" tarefas.forEach((t) => { if (!t.arquivada) { let li = document.createElement('li') li.setAttribute('id', t.id) let check = document.createElement('input') check.setAttribute('type', 'checkbox') check.onclick = function() { markAsComplete(t.id) } check.checked = t.concluida; if (t.concluida) { li.classList.add('concluida') } let button = document.createElement('button') button.classList.add('arquivar') button.innerHTML = '&#10005;' button.onclick = function() { markAsArchived(t.id) } li.append(check) let p = document.createElement('p') p.innerText = t.texto li.append(p) li.append(button) ul.append(li) } }) } function markAsComplete(idTarefa) { for (let i = 0; i < tarefas.length; i++) { if (tarefas[i].id === idTarefa) { tarefas[i].concluida = !tarefas[i].concluida; localStorage.setItem('tarefas', JSON.stringify(tarefas)) listarTarefas() } } } function markAsArchived(idTarefa) { for (let i = 0; i < tarefas.length; i++) { if (tarefas[i].id === idTarefa) { tarefas[i].arquivada = !tarefas[i].arquivada; localStorage.setItem('tarefas', JSON.stringify(tarefas)) listarTarefas() } } } function adicionarTarefa() { let input = prompt("Tarefa"); if (input !== null & input !== "") { tarefas.push({ texto: input, concluida: false, arquivada: false, id: count }) count++ localStorage.setItem('counter', count) localStorage.setItem('tarefas', JSON.stringify(tarefas)) listarTarefas() } } function docReady(fn) { if (document.readyState === "complete" || document.readyState === "interactive") { setTimeout(fn, 1); } else { document.addEventListener("DOMContentLoaded", fn); } } docReady(listarTarefas)
28.488095
86
0.535729
1d48c9e4797797f7e274cb4b02de91fdb1b76806
903
js
JavaScript
client/src/test/Location.test.js
rickBucket/JobSite
10226a3242028150d74511339023f367851feb3c
[ "MIT" ]
1
2021-04-19T02:12:22.000Z
2021-04-19T02:12:22.000Z
client/src/test/Location.test.js
kevin-the-engi/frontend-jobsite
f92f32d585490f03d779771046b692d6fc6c8162
[ "MIT" ]
1
2021-04-07T05:53:57.000Z
2021-04-07T05:53:57.000Z
client/src/test/Location.test.js
kevin-the-engi/frontend-jobsite
f92f32d585490f03d779771046b692d6fc6c8162
[ "MIT" ]
2
2021-04-19T02:11:27.000Z
2021-04-22T02:41:01.000Z
import React from 'react'; import { shallow } from 'enzyme'; import Location from '../components/Location.jsx'; describe('Location', () => { let wrapper = shallow(<Location />); const expected = { target: { name: 'location', value: 'San Francisco', }, }; it('should detect onChange', () => { wrapper.find('#location').simulate('change', expected); }); it('should correctly update state with onChange value', () => { const setLocation = jest.fn(); const useStateSpy = jest.spyOn(React, 'useState'); wrapper = shallow(<Location setLocation={setLocation} />); useStateSpy.mockImplementation((location) => [location, setLocation]); wrapper.find('#location').simulate('change', expected); wrapper.find('#locationBar').simulate('submit', { preventDefault: () => null }); expect(setLocation).toHaveBeenCalledWith('San Francisco'); }); });
30.1
84
0.645626
1d493ceb093584d94f5d84e25c41d0eb370e53d9
3,567
js
JavaScript
src/lib/discord/discordWebhookWorker.js
Piikachuu/PoracleJS
dc2e71311ad9f6a02bbc6509273efb7386d93720
[ "ISC" ]
null
null
null
src/lib/discord/discordWebhookWorker.js
Piikachuu/PoracleJS
dc2e71311ad9f6a02bbc6509273efb7386d93720
[ "ISC" ]
null
null
null
src/lib/discord/discordWebhookWorker.js
Piikachuu/PoracleJS
dc2e71311ad9f6a02bbc6509273efb7386d93720
[ "ISC" ]
null
null
null
const axios = require('axios') const FairPromiseQueue = require('../FairPromiseQueue') const hookRegex = new RegExp('(?:(?:https?):\\/\\/|www\\.)(?:\\([-A-Z0-9+&@#\\/%=~_|$?!:,.]*\\)|[-A-Z0-9+&@#\\/%=~_|$?!:,.])*(?:\\([-A-Z0-9+&@#\\/%=~_|$?!:,.]*\\)|[A-Z0-9+&@#\\/%=~_|$])', 'igm') class DiscordWebhookWorker { constructor(config, logs) { this.config = config this.logs = logs this.busy = true this.users = [] this.userCount = 0 this.client = {} this.axios = axios this.webhookQueue = [] this.queueProcessor = new FairPromiseQueue(this.webhookQueue, this.config.tuning.concurrentDiscordWebhookConnections, ((t) => t.target)) } // eslint-disable-next-line class-methods-use-this async sleep(n) { return new Promise((resolve) => setTimeout(resolve, n)) } addUser(id) { this.users.push(id) this.userCount += 1 } async sendAlert(data) { if ((Math.random() * 100) > 95) this.logs.log.verbose(`DiscordQueue[Webhook] is currently ${this.webhookQueue.length}`) // todo: per minute await this.webhookAlert(data) } async webhookAlert(firstData) { const data = firstData if (!data.target.match(hookRegex)) return this.logs.discord.warn(`Webhook, ${data.name} does not look like a link, exiting`) if (data.message.embed && data.message.embed.color) { data.message.embed.color = parseInt(data.message.embed.color.replace(/^#/, ''), 16) } if (data.message.embed) data.message.embeds = [data.message.embed] try { const logReference = data.logReference ? data.logReference : 'Unknown' this.logs.discord.info(`${logReference}: http(s)> ${data.name} WEBHOOK Sending discord message`) this.logs.discord.debug(`${logReference}: http(s)> ${data.name} WEBHOOK Sending discord message to ${data.target}`, data.message) let retryLimit = 5 let shouldRetry = true while (--retryLimit && shouldRetry) { shouldRetry = false // loop and sleep around issues... const res = await this.axios({ method: 'post', url: data.target, data: data.message, validateStatus: ((status) => status < 500), }) if (res.status === 429) { this.logs.discord.warn(`${logReference}: ${data.name} WEBHOOK 429 Rate limit [Discord Webhook] x-ratelimit-bucket ${res.headers['x-ratelimit-bucket']} retry after ${res.headers['retry-after']} limit ${res.headers['x-ratelimit-limit']} global ${res.headers['x-ratelimit-global']} reset after ${res.headers['x-ratelimit-reset-after']} `) // const resetAfter = res.headers["x-ratelimit-reset-after"] const retryAfterMs = res.headers['retry-after'] if (!res.headers.via) { this.logs.discord.error(`${logReference}: ${data.name} WEBHOOK 429 Rate limit [Discord Webhook] TELL @JABES ON DISCORD THIS COULD BE FROM CLOUDFLARE: ${retryAfterMs}`) } await this.sleep(retryAfterMs) shouldRetry = true } else if (res.status < 200 || res.status > 299) { this.logs.discord.warn(`${logReference}: ${data.name} WEBHOOK Got ${res.status} ${res.statusText}`) } this.logs.discord.silly(`${logReference}: ${data.name} WEBHOOK results ${data.target} ${res.statusText} ${res.status}`, res.headers) } if (retryLimit === 0 && shouldRetry) { this.logs.discord.warn(`${logReference}: ${data.name} WEBHOOK given up sending after retries`) } } catch (err) { this.logs.discord.error(`${data.logReference}: ${data.name} WEBHOOK failed`, err) } return true } work(data) { this.webhookQueue.push(data) this.queueProcessor.run((work) => (this.sendAlert(work))) } } module.exports = DiscordWebhookWorker
39.633333
340
0.66106
1d49529e26ae906fe0a4bae6b3d0cd5099a37478
1,236
js
JavaScript
packages/core/navigation-next/components/presentational/LayoutManager/primitives.js
HeartCommunity/uiKit
be4d040d314a93db216726a87c579e362760455d
[ "Apache-2.0" ]
1
2020-08-09T09:10:20.000Z
2020-08-09T09:10:20.000Z
packages/core/navigation-next/components/presentational/LayoutManager/primitives.js
fnamazing/uiKit
be4d040d314a93db216726a87c579e362760455d
[ "Apache-2.0" ]
null
null
null
packages/core/navigation-next/components/presentational/LayoutManager/primitives.js
fnamazing/uiKit
be4d040d314a93db216726a87c579e362760455d
[ "Apache-2.0" ]
2
2019-10-02T19:17:44.000Z
2019-12-25T11:44:11.000Z
import { css as _css2 } from "emotion"; import _extends from "@babel/runtime/helpers/extends"; import { css as _css } from "emotion"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; import React from 'react'; import { layers } from '@findable/theme'; export var LayoutContainer = function LayoutContainer(_ref) { var topOffset = _ref.topOffset, props = _objectWithoutProperties(_ref, ["topOffset"]); return React.createElement("div", _extends({ className: _css({ display: 'flex', flexDirection: 'row', height: "calc(100vh - ".concat(topOffset || 0, "px)") }) }, props)); }; export var NavigationContainer = function NavigationContainer(_ref2) { var topOffset = _ref2.topOffset, innerRef = _ref2.innerRef, props = _objectWithoutProperties(_ref2, ["topOffset", "innerRef"]); return React.createElement("div", _extends({ ref: innerRef, className: _css2({ bottom: 0, display: 'flex', flexDirection: 'row', left: 0, position: 'fixed', top: topOffset, zIndex: layers.navigation(), height: "calc(100vh - ".concat(topOffset, "px)") }) }, props)); }; // Resizable Elements can be disabled
33.405405
86
0.666667
1d4a4ee08a98d763fd72dbbfd171b0138fd2edde
721
js
JavaScript
src/components/Menus/FooterMenu.js
aljmiller87/gatsby-wordpress
fa1f8367c4ad707ee0983f9cee41b62c0666fb62
[ "MIT" ]
null
null
null
src/components/Menus/FooterMenu.js
aljmiller87/gatsby-wordpress
fa1f8367c4ad707ee0983f9cee41b62c0666fb62
[ "MIT" ]
null
null
null
src/components/Menus/FooterMenu.js
aljmiller87/gatsby-wordpress
fa1f8367c4ad707ee0983f9cee41b62c0666fb62
[ "MIT" ]
null
null
null
import React from "react"; import { graphql, useStaticQuery, Link } from "gatsby"; export const query = graphql` { menus: allWordpressWpApiMenusMenusItems( filter: { name: { eq: "Footer" } } ) { edges { menu: node { items { title object_slug } } } } } `; const MainMenu = () => { const { menus } = useStaticQuery(query); return ( <div> <ul> {menus.edges[0].menu.items.map(link => { return ( <li key={link.object_slug}> <Link to={link.object_slug}>{link.title}</Link> </li> ); })} </ul> </div> ); }; export default MainMenu;
18.487179
61
0.472954
1d4ab083895a1aebc762a6085cad27af82a04c1f
900
js
JavaScript
client/src/firebase/fbconfig.js
oguzkarademir/Portfolio
07a562d0bc4bcad80caa7b3c149826d3dfa42894
[ "MIT" ]
1
2021-02-09T12:53:29.000Z
2021-02-09T12:53:29.000Z
client/src/firebase/fbconfig.js
oguzkarademir/Portfolio
07a562d0bc4bcad80caa7b3c149826d3dfa42894
[ "MIT" ]
null
null
null
client/src/firebase/fbconfig.js
oguzkarademir/Portfolio
07a562d0bc4bcad80caa7b3c149826d3dfa42894
[ "MIT" ]
null
null
null
import firebase from 'firebase'; import "firebase/auth"; var firebaseConfig = { apiKey: process.env.REACT_APP_API_KEY, authDomain: process.env.REACT_APP_AUTH_DOMAIN, projectId: process.env.REACT_APP_PROJECT_ID, storageBucket: process.env.REACT_APP_STORAGE_BUCKET, messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID, appId: process.env.REACT_APP_APP_ID }; class Firebase { constructor(){ firebase.initializeApp(firebaseConfig); this.firebaseAuth=firebase.auth() this.firebase = firebase } async signIn(email,password){ try { await this.firebaseAuth.signInWithEmailAndPassword(email,password) return true } catch { return false } } signOut(){ this.firebaseAuth.signOut() } } export default new Firebase()
22.5
76
0.646667
1d4c00a8e42d92457e025e47239b9898ddd8da55
698
js
JavaScript
utils/helpers.js
cjsmith1988/CMS-Blog-Site
050f0d9f8f469247b1ffea51ff374abf4dcc44b2
[ "MIT" ]
null
null
null
utils/helpers.js
cjsmith1988/CMS-Blog-Site
050f0d9f8f469247b1ffea51ff374abf4dcc44b2
[ "MIT" ]
null
null
null
utils/helpers.js
cjsmith1988/CMS-Blog-Site
050f0d9f8f469247b1ffea51ff374abf4dcc44b2
[ "MIT" ]
null
null
null
module.exports = { format_date: date => { const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; const days = ["1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th","13th","14th","15th","16th","17th","18th","19th","20th", "21st","22nd","23rd","24th","25th","26th","27th","28th","29th","30th","31st"]; return `${months[new Date(date).getMonth()]} ${days[new Date(date).getDate()-1]}, ${new Date( date ).getFullYear()}`; }, format_plural: (word, amount) => { if (amount !== 1) { return `${word}s`; } return word; }, }
38.777778
153
0.469914
1d4c8893bf8dd02623fc2dd6573ef55bd3368f44
1,932
js
JavaScript
elements/random-image/src/random-image.js
cgldevel/lrnwebcomponents
b301e58b042b606ab6378bdaae24ac537bfc0c0e
[ "Apache-2.0" ]
1
2019-09-04T20:39:01.000Z
2019-09-04T20:39:01.000Z
elements/random-image/src/random-image.js
jnb5409/lrnwebcomponents
ba6bc82345a01b17b58437c47a59e7839b8b0a1e
[ "Apache-2.0" ]
null
null
null
elements/random-image/src/random-image.js
jnb5409/lrnwebcomponents
ba6bc82345a01b17b58437c47a59e7839b8b0a1e
[ "Apache-2.0" ]
null
null
null
import { html, PolymerElement } from "@polymer/polymer/polymer-element.js"; import { afterNextRender } from "@polymer/polymer/lib/utils/render-status.js"; /** `random-image` Element to show random image from a given group. * @demo demo/index.html */ class RandomImage extends PolymerElement { constructor() { super(); import("@polymer/iron-image/iron-image.js"); } static get template() { return html` <style> :host { display: block; } .is-circle { border: 1px solid grey; border-radius: 50%; box-shadow: 0px 5px 10px #ccc; } </style> <iron-image style="width:200px; height:200px;" class$="[[mode]]" sizing="contain" src$="[[imgSrc]]" title$="[[imgTitle]]" ></iron-image> `; } static get tag() { return "random-image"; } static get properties() { return { mode: { type: String, notify: true, value: "" }, imgSrc: { type: String }, imgTitle: { type: String }, imagesList: { type: Object, notify: true, // When initializing a property to an object or array value, use a function to ensure that each element // gets its own copy of the value, rather than having an object or array shared across all instances of the element value() { return []; } } }; } _pickRandomProperty(obj) { var result; var count = 0; for (var prop in obj) if (Math.random() < 1 / ++count) result = prop; return result; } ready() { super.ready(); var randomPos = this._pickRandomProperty(this.imagesList); this.imgSrc = this.imagesList[randomPos].path; this.imgTitle = this.imagesList[randomPos].title; } } window.customElements.define(RandomImage.tag, RandomImage); export { RandomImage };
23.851852
123
0.574534
1d4eb8ee40c5e503fd461c4d4283ec153a9cca21
3,913
js
JavaScript
html/src/math/Bezier.js
drojdjou/squareroot.js
3b8a8780c2f50c4fef9bc2b37210d76d539c612f
[ "MIT" ]
126
2015-01-05T22:37:07.000Z
2021-07-05T03:16:40.000Z
html/src/math/Bezier.js
drojdjou/squareroot.js
3b8a8780c2f50c4fef9bc2b37210d76d539c612f
[ "MIT" ]
2
2015-11-01T20:59:50.000Z
2017-08-10T08:09:28.000Z
html/src/math/Bezier.js
drojdjou/squareroot.js
3b8a8780c2f50c4fef9bc2b37210d76d539c612f
[ "MIT" ]
21
2015-01-09T01:05:35.000Z
2020-07-27T20:31:53.000Z
/** * @class Bezier * @memberof SQR * * @description Represents a cubic bezier curve. All paramaters can be either {@link SQR.V3} or {@link SQR.V2}. * * @param _p0 start position * @param _c0 first control point * @param _c1 last control point * @param _c1 end position * */ SQR.Bezier = function(_p0, _c0, _c1, _p1) { var that = this; /** * @var p0 * @memberof SQR.Bezier.prototype * @descripton The start position, can be either {@link SQR.V3} or {@link SQR.V2}. */ this.p0 = _p0; /** * @var c0 * @memberof SQR.Bezier.prototype * @descripton First control point. Can be either {@link SQR.V3} or {@link SQR.V2}. */ this.c0 = _c0; /** * @var c1 * @memberof SQR.Bezier.prototype * @descripton Second control point. Can be either {@link SQR.V3} or {@link SQR.V2}. */ this.c1 = _c1; /** * @var p1 * @memberof SQR.Bezier.prototype * @descripton End position. Can be either {@link SQR.V3} or {@link SQR.V2}. */ this.p1 = _p1; var interpolatedValue, interpolatedVelocity, interpolatedMatrix; var pfunc = SQR.Interpolation.bezierPosition; var vfunc = SQR.Interpolation.bezierVelocity; /** * @method velocityAt * @memberof SQR.Bezier.prototype * @description Returns the velocity on a curve. * @param t interpolation value [0-1] * @param v vector to write the value to. If omitted, returns a temporary value, that will be overwritten on next call so do not store this object. */ this.velocityAt = function(t, v) { interpolatedVelocity = interpolatedVelocity || this.p0.clone().set(); v = v || interpolatedVelocity; v.x = vfunc(t, this.p0.x, this.c0.x, this.c1.x, this.p1.x); v.y = vfunc(t, this.p0.y, this.c0.y, this.c1.y, this.p1.y); if(v.z !== null && this.p0.z !== null) { v.z = vfunc(t, this.p0.z, this.c0.z, this.c1.z, this.p1.z); } return v; } /** * @method valueAt * @memberof SQR.Bezier.prototype * @description Returns the position on a curve. * @param t interpolation value [0-1] * @param v vector to write the value to. If omitted, returns a temporary value, that will be overwritten on next call so do not store this object. */ this.valueAt = function(t, v) { interpolatedValue = interpolatedValue || this.p0.clone().set(); v = v || interpolatedValue; v.x = pfunc(t, this.p0.x, this.c0.x, this.c1.x, this.p1.x); v.y = pfunc(t, this.p0.y, this.c0.y, this.c1.y, this.p1.y); if(v.z !== null && this.p0.z !== null) { v.z = pfunc(t, this.p0.z, this.c0.z, this.c1.z, this.p1.z); } return v; } /** * @method matrixAt * @memberof SQR.Bezier.prototype * @description Returns the transformation matrix that can be used to align an object to the curve at a given point. * Not tested in 2D but shoud work fine. * @param t interpolation value [0-1] * @param m {@link SQR.Matrix44} to write the matrix to. If omitted, returns a temporary value, that will be overwritten on next call so do not store this object. */ this.matrixAt = function(t, m) { interpolatedMatrix = interpolatedMatrix || new SQR.Matrix44(); m = m || interpolatedMatrix; m.identity(); var va = that.valueAt(t); var vc = that.velocityAt(t).norm(); var vl = SQR.V3.__tv1.set().cross(vc, SQR.V3.up);//.norm(); var vn = SQR.V3.__tv2.set().cross(vc, vl);//.norm() m.data[0] = vl.x, m.data[4] = vn.x, m.data[8] = vc.x; m.data[1] = vl.y, m.data[5] = vn.y, m.data[9] = vc.y; m.data[2] = vl.z, m.data[6] = vn.z, m.data[10] = vc.z; m.setTranslation(va.x, va.y, va.z); return m; } }
30.811024
167
0.58114
1d4f7b43cb1873a1db3b4a960c518f55d73e1e78
4,627
js
JavaScript
store/index.js
jonasbbernardi/moneictrl
bdb99ab8d5d35a3a560ab80b8b3fbee6745b5b71
[ "MIT" ]
null
null
null
store/index.js
jonasbbernardi/moneictrl
bdb99ab8d5d35a3a560ab80b8b3fbee6745b5b71
[ "MIT" ]
1
2022-02-27T11:31:56.000Z
2022-02-27T11:31:56.000Z
store/index.js
jonasbbernardi/moneictrl
bdb99ab8d5d35a3a560ab80b8b3fbee6745b5b71
[ "MIT" ]
null
null
null
import { combineReducers, createStore, applyMiddleware } from 'redux'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { Cache } from "react-native-cache"; import thunk from 'redux-thunk'; import moment from 'moment'; import { getStorageItems } from '../actions/getItems'; import { getStorageLocale } from '../actions/getLocale'; import { initListReducer, getStorageItemsReducer } from './getItems'; import addItemReducer from './addItem'; import editItemReducer from './editItem'; import removeItemReducer from './removeItem'; import {doneItemReducer, undoneItemReducer} from './doneItem'; import clearItemsReducer from './clearItems'; import loadCurrentItemsReducer from './loadCurrentItems'; import { initLocaleReducer, getStorageLocaleReducer } from './getLocale'; import setMoneyMaskReducer from './setMoneyMask'; import setDateFormatReducer from './setDateFormat'; global.storage = new Cache({ namespace: "monei", policy: { maxEntries: 50000, // if unspecified, it can have unlimited entries stdTTL: 0 }, backend: AsyncStorage }); const loadCurrentItems = () => { setTimeout(() => { let {items, currentDate, currentFilter} = store.getState(); let payload = {items, currentDate, currentFilter}; store.dispatch({type: gActions.LOAD_CURRENT_ITEMS, payload: payload}); }); } const items = (state = [], action) => { let items = state; switch(action.type){ case gActions.INIT_LIST: items = initListReducer(state, action.payload); break; case gActions.ADD_ITEM: items = addItemReducer(state, action.payload); break; case gActions.EDIT_ITEM: items = editItemReducer(state, action.payload); break; case gActions.REMOVE_ITEM: items = removeItemReducer(state, action.payload); break; case gActions.DONE_ITEM: items = doneItemReducer(state, action.payload); break; case gActions.UNDONE_ITEM: items = undoneItemReducer(state, action.payload); break; case gActions.CLEAR_ITEMS: items = clearItemsReducer(state); break; case gActions.GET_STORAGE_ITEMS: items = getStorageItemsReducer(state, store); break; default: return state; } loadCurrentItems(); return items; }; const initialCurrentDate = moment(); const currentDate = (state = initialCurrentDate, action) => { switch(action.type){ case gActions.SET_MONTH: loadCurrentItems(); return moment(action.payload); case gActions.RESET_MONTH: return initialCurrentDate; default: return state; } } const currentItems = (state = [], action) => { switch(action.type){ case gActions.LOAD_CURRENT_ITEMS: return loadCurrentItemsReducer(action.payload); default: return state; } } const currentFilter = (state = {}, action) => { switch(action.type){ case gActions.FILTER_BY_DESCRIPTION: loadCurrentItems(); return {...state, description: action.payload.description}; case gActions.FILTER_BY_TYPE: loadCurrentItems(); return {...state, type: action.payload.type}; case gActions.RSEET_FILTER: return {}; default: return state; } } import * as Localization from 'expo-localization'; const initialMoneyMask = setMoneyMaskReducer(Localization.locale); const initialDateFormat = setDateFormatReducer(Localization.locale); const initialLocale = { lang: Localization.locale, moneyMask: initialMoneyMask, dateFormat: initialDateFormat } const locale = (state = initialLocale, action) => { switch(action.type){ case gActions.SET_LOCALE: let lang = action.lang || initialLocale.lang; let moneyMask = setMoneyMaskReducer(lang); let dateFormat = setDateFormatReducer(lang); let newLocale = {lang, moneyMask, dateFormat} storage.set(localeStorageKey,JSON.stringify(newLocale)); return newLocale; case gActions.GET_STORAGE_LOCALE: return getStorageLocaleReducer(state, store); case gActions.INIT_LOCALE: return initLocaleReducer(state, action.payload); default: return state; } }; const reducers = { items, currentDate, currentFilter, currentItems, locale, } const store = createStore(combineReducers(reducers), applyMiddleware(thunk)); store.dispatch(getStorageLocale()); store.dispatch(getStorageItems()); export default store;
33.528986
78
0.670197
1d4f989e51e94ebcf0160f538de65df904799662
4,475
js
JavaScript
functionalTest/mb.js
msy53719/mountebank
8a0f731113eac68c5394fb682b25d737ec59260b
[ "MIT" ]
null
null
null
functionalTest/mb.js
msy53719/mountebank
8a0f731113eac68c5394fb682b25d737ec59260b
[ "MIT" ]
null
null
null
functionalTest/mb.js
msy53719/mountebank
8a0f731113eac68c5394fb682b25d737ec59260b
[ "MIT" ]
null
null
null
'use strict'; var Q = require('q'), fs = require('fs'), path = require('path'), spawn = require('child_process').spawn, exec = require('child_process').exec, httpClient = require('./api/http/baseHttpClient').create('http'), headers = { connection: 'close' }, isWindows = require('os').platform().indexOf('win') === 0, mbPath = process.env.MB_EXECUTABLE || path.join(__dirname, '/../bin/mb'), pidfile = 'test.pid', logfile = 'mb-test.log'; function whenFullyInitialized (operation, callback) { var count = 0, pidfileMustExist = operation === 'start', spinWait = function () { count += 1; if (count > 20) { console.log('ERROR: mb ' + operation + ' not initialized after 2 seconds'); callback({}); } else if (fs.existsSync(pidfile) === pidfileMustExist) { callback({}); } else { Q.delay(100).done(spinWait); } }; spinWait(); } function spawnMb (args) { var command = mbPath, result; if (isWindows) { args.unshift(mbPath); if (mbPath.indexOf('.cmd') >= 0) { // Accommodate the self-contained Windows zip files that ship with mountebank args.unshift('/c'); command = 'cmd'; } else { command = 'node'; } } result = spawn(command, args); result.stderr.on('data', function (data) { console.log(data.toString('utf8')); }); return result; } function create (port) { function start (args) { var deferred = Q.defer(), mbArgs = ['restart', '--port', port, '--logfile', logfile, '--pidfile', pidfile].concat(args || []), mb; whenFullyInitialized('start', deferred.resolve); mb = spawnMb(mbArgs); mb.on('error', deferred.reject); return deferred.promise; } function stop () { var deferred = Q.defer(), command = mbPath + ' stop --pidfile ' + pidfile; if (isWindows && mbPath.indexOf('.cmd') < 0) { command = 'node ' + command; } exec(command, function (error, stdout, stderr) { if (error) { throw error; } if (stdout) { console.log(stdout); } if (stderr) { console.error(stderr); } whenFullyInitialized('stop', deferred.resolve); }); return deferred.promise; } function restart (args) { // Can't simply call mb restart // The start function relies on whenFullyInitialized to wait for the pidfile to already exist // If it already does exist, and you're expecting mb restart to kill it, the function will // return before you're ready for it return stop(args).then(function () { return start(args); }); } function execCommand (command, args) { var deferred = Q.defer(), mbArgs = [command, '--port', port].concat(args || []), mb, stdout = '', stderr = ''; mb = spawnMb(mbArgs); mb.on('error', deferred.reject); mb.stdout.on('data', function (chunk) { stdout += chunk; }); mb.stderr.on('data', function (chunk) { stderr += chunk; }); mb.on('close', function (exitCode) { deferred.resolve({ exitCode: exitCode, stdout: stdout, stderr: stderr }); }); return deferred.promise; } function save (args) { return execCommand('save', args); } function replay (args) { return execCommand('replay', args); } // After trial and error, I discovered that we have to set // the connection: close header on Windows or we end up with // ECONNRESET errors function get (endpoint) { return httpClient.responseFor({ method: 'GET', path: endpoint, port: port, headers: headers }); } function post (endpoint, body) { return httpClient.responseFor({ method: 'POST', path: endpoint, port: port, body: body, headers: headers }); } return { port: port, url: 'http://localhost:' + port, start: start, restart: restart, stop: stop, save: save, get: get, post: post, replay: replay }; } module.exports = { create: create };
28.322785
116
0.532514
1d4fa07f12392661d3c4acfe063e73cd1adfbd6f
1,813
js
JavaScript
lambdas/scored-reports/handler.js
carlgieringer/thorninside
9c2a5d30ec4161c5f88a4c2579a11f1a2aa6a58d
[ "Unlicense" ]
null
null
null
lambdas/scored-reports/handler.js
carlgieringer/thorninside
9c2a5d30ec4161c5f88a4c2579a11f1a2aa6a58d
[ "Unlicense" ]
null
null
null
lambdas/scored-reports/handler.js
carlgieringer/thorninside
9c2a5d30ec4161c5f88a4c2579a11f1a2aa6a58d
[ "Unlicense" ]
null
null
null
const serverless = require('serverless-http'); const express = require('express'); const app = express(); const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies const dynamoDb = new AWS.DynamoDB.DocumentClient(); app.get('/', (request, response) => { console.log(`GET: ${request.originalUrl}`); response.send('Thorn Cybertip Report Scorer is Running'); }); app.get('/reports', (request, response) => { scanReports(reports => response.json(reports)) }); app.get('/reports/:reportId', (request, response) => { const reportId = request.params.reportId; getReport(reportId, report => response.json(report)) }); app.post('/reports/:reportId', (request, response) => { const reportId = request.params.reportId; const newLabel = request.body['newLabel'] updateReportLabel(reportId, newLabel, () => response.json({message: "Success"})) }); const scanReports = (callback) => { const params = { TableName: process.env.DYNAMODB_TABLE, }; return dynamoDb.scan(params, (error, data) => { if (error) throw error callback(data['Items']) }); } const getReport = (reportId, callback) => { const params = { Key: { "reportId": { N: +reportId } }, TableName: process.env.DYNAMODB_TABLE, }; return dynamoDb.getItem(params, (error, data) => { if (error) throw error callback(data['Item']) }); } const updateReportLabel = (reportId, newLabel, callback) => { const params = { Item: { "reportId": { N: +reportId }, "Label": { S: newLabel } }, TableName: process.env.DYNAMODB_TABLE, }; return dynamoDb.putItem(params, (error, data) => { if (error) throw error console.log(data) callback() }); } module.exports.handler = serverless(app);
23.855263
88
0.635962
1d503806ba0ba091b0f9f11d95258fa3f7b6a109
589
js
JavaScript
src/store/sagas/saga.js
duc110789/vmms
b80c20aa7056e8acbb4a44110c9c7a28710b4309
[ "MIT" ]
null
null
null
src/store/sagas/saga.js
duc110789/vmms
b80c20aa7056e8acbb4a44110c9c7a28710b4309
[ "MIT" ]
null
null
null
src/store/sagas/saga.js
duc110789/vmms
b80c20aa7056e8acbb4a44110c9c7a28710b4309
[ "MIT" ]
null
null
null
import { all, fork } from 'redux-saga/effects'; import merchantListSaga from './listMerchantSaga'; import commonSourceSate from './commonSourceSage'; import addMerchant from './addMerchantBySage'; import editMerchantSaga from './editMerchantSaga'; import detailMerchantSaga from './detailMerchantSaga'; import approveMerchantSaga from './approveMerchantSaga'; export default function* rootSaga() { yield all([ fork(merchantListSaga), fork(commonSourceSate), fork(addMerchant), fork(editMerchantSaga), fork(detailMerchantSaga), fork(approveMerchantSaga), ]); }
31
56
0.760611
1d5045700f82d14ebe84d228c813d2abdef8a2f0
5,983
js
JavaScript
test/extend_ui.js
mytharcher/ER2
68a2d3414566e1f9a48c4e108c8104d0cc8b8840
[ "BSD-3-Clause" ]
21
2015-03-04T09:25:30.000Z
2021-11-08T09:03:53.000Z
test/extend_ui.js
mytharcher/ER2
68a2d3414566e1f9a48c4e108c8104d0cc8b8840
[ "BSD-3-Clause" ]
1
2019-03-30T12:07:41.000Z
2019-03-30T12:07:41.000Z
test/extend_ui.js
mytharcher/ER2
68a2d3414566e1f9a48c4e108c8104d0cc8b8840
[ "BSD-3-Clause" ]
9
2015-01-14T09:25:17.000Z
2020-01-27T21:25:31.000Z
er.template.parse( '<!-- target: uiview --><div ui="type:Button;id:myButton"></div><div ui="type:Select;id:mySelect;datasource:*users"></div>' ); er.template.parse( '<!-- target: uiviewsimple --><div ui="type:Button;id:myButton"></div><div ui="type:Select;id:mySelect;"></div>' ); er.template.parse( '<!-- target: uiinputview --><div ui="type:Button;id:myButton"></div>' + '<div ui="type:Select;id:mySelect;"></div>' + '<input type="text" ui="type:TextInput;id:myText;value:*textValue"/>' + '<span ui="type:Label;id:myLabel"></span>'); er.template.parse( '<!-- target: uiclear -->just test' ); var testUserData = [ { name:'erik', value: 1 }, { name:'ouyang', value: 2 }, { name:'season', value: 3 } ]; var testUserData2 = [ { name:'erik', value: 1 }, { name:'ouyang', value: 2 }, { name:'season', value: 3 }, { name:'hello', value: 4 } ]; var testModule = new er.Module( { config: { action: [ { path : '/', action : 'testModule.action' }, { path : '/two', action : 'testModule.action2' }, { path : '/clear', action : 'testModule.actionc' }, { path : '/input', action : 'testModule.actioni' }, { path : '/inputnosilence', action : 'testModule.actionii' } ] } } ); var testUserModel = new er.Model( { LOADER_LIST: [ 'loadUser' ], loadUser: new er.Model.Loader( function () { this.set( 'users', testUserData ); } ) } ) ; testModule.actionc = new er.Action( { view: 'uiclear', model: testUserModel } ); var inputList = null; var testInputText = null; testModule.actioni = new er.Action( { view: 'uiinputview', model: testUserModel, ontraceinput: function () { inputList = this.view.getInputList(); }, ontracevalue: function () { testInputText = esui.get( 'myText' ).getValue(); }, oneditvalue: function ( value ) { this.model.set( 'textValue', value ); } } ); testModule.actionii = new er.Action( { MODEL_SILENCE: false, view: 'uiinputview', model: testUserModel, ontraceinput: function () { inputList = this.view.getInputList(); }, ontracevalue: function () { testInputText = esui.get( 'myText' ).getValue(); }, oneditvalue: function ( value ) { this.model.set( 'textValue', value ); }, oneditvaluesilence: function ( value ) { this.model.set( 'textValue', value, {silence: true} ); } } ); testModule.action = new er.Action( { view: 'uiview', model: testUserModel, onafterrender: function () { esui.get( 'myButton' ).onclick = this.btnClick; }, btnClick: function () { window._selectedUser = esui.get( 'mySelect' ).getValue(); }, onclear: function () { this.view.clear(); }, onchangeuser: function () { this.model.set( 'users', testUserData2 ); this.view.repaint(); } } ); testModule.action2 = new er.Action( { view: new er.View( { template: 'uiviewsimple', UI_PROP: { mySelect: { datasource: '*users' } } } ), model: testUserModel, onafterrender: function () { esui.get( 'myButton' ).onclick = this.btnClick; }, btnClick: function () { window._selectedUser = esui.get( 'mySelect' ).getValue(); } } ); module("er.extend.ui"); test("render repaint & clear", function() { er.locator.redirect('/'); same( esui.get('myButton') instanceof esui.Button, true, "button控件被渲染" ); same( esui.get('mySelect') instanceof esui.Select, true, "select控件被渲染" ); same( esui.get('mySelect').datasource.length, 3, "*var的方法引用到数据模型" ); var isRepainted = 0; var renderFunc = esui.get('mySelect').render; esui.get('mySelect').render = function() { isRepainted = 1; renderFunc.call( this ); }; er.controller.fireMain('changeuser'); same( esui.get('mySelect').datasource.length, 4, "数据被重新灌入" ); same( isRepainted, 1, "重绘动作发生" ); er.controller.fireMain('clear'); same( esui.get('myButton') , null, "button控件被清除" ); same( esui.get('mySelect') , null, "select控件被清除" ); }); test("new View 4 action", function() { er.locator.redirect('/two'); same( esui.get('myButton') instanceof esui.Button, true, "button控件被渲染" ); same( esui.get('mySelect') instanceof esui.Select, true, "select控件被渲染" ); same( esui.get('mySelect').datasource.length, 3, "select的datasource被UI_PROP指定" ); }); test("getInputList", function() { er.locator.redirect('/input'); er.controller.fireMain('traceinput'); same( inputList.length, 2, "取到两个控件" ); for ( var i = 0; i < inputList.length; i++ ) { same( inputList[i] instanceof esui.InputControl, true, inputList[i].id + "控件是input控件" ); } same( esui.get('myLabel') instanceof esui.Control, true, "其他非input控件存在" ); }); test("auto repaint when set model", function() { er.locator.redirect('/input'); er.controller.fireMain('tracevalue'); same( testInputText, '', "text控件初始值为空" ); er.controller.fireMain('editvalue', 'erik'); er.controller.fireMain('tracevalue'); same( testInputText, '', "默认情况不自动repaint控件" ); er.locator.redirect('/inputnosilence'); er.controller.fireMain('tracevalue'); same( testInputText, '', "text控件初始值为空" ); er.controller.fireMain('editvalue', 'erik'); er.controller.fireMain('tracevalue'); same( testInputText, 'erik', "设置MODEL_SILENCE时,model的变更自动映射到控件" ); er.controller.fireMain('editvaluesilence', 'sea'); er.controller.fireMain('tracevalue'); same( testInputText, 'erik', "通过{silence:true}设置model,不会自动重绘并更新控件" ); });
27.957944
145
0.57396
1d507cc02ff9a70b20b5e1c2f72a0ea066d7ea3b
599
js
JavaScript
webpack-vuex/src/router/index.js
adrienloup/boilerplates
9849dd1390d0ffa4ca46122d2ce5acfaa7729187
[ "0BSD" ]
null
null
null
webpack-vuex/src/router/index.js
adrienloup/boilerplates
9849dd1390d0ffa4ca46122d2ce5acfaa7729187
[ "0BSD" ]
33
2019-12-29T23:03:57.000Z
2021-10-06T02:43:45.000Z
webpack-vuex/src/router/index.js
adrienloup/starter
834352e35402951036a55726af115c5bf9356cc0
[ "ISC" ]
2
2020-04-10T14:00:13.000Z
2020-04-25T02:17:32.000Z
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ mode: 'history', routes: [ { path: '/', name: 'home', component: () => import('@/pages/Home.vue') }, { path: '/women', name: 'women', component: () => import('@/pages/Women.vue') }, { path: '/men', name: 'men', component: () => import('@/pages/Men.vue') }, { path: '/sale', name: 'sale', component: () => import('@/pages/Sale.vue') }, { path: '*', redirect: '/' } ] })
17.114286
50
0.45409
1d50c08c0c2d313dc77096400f3c63c5da1f6633
1,214
js
JavaScript
js/sykepengesoknad/soknad-selvstendig-frilanser/kvittering/Kvittering.js
navikt/sykepengesoknad
b5b07c7cee66b03e8ae0dc1d3245a0bd860bd000
[ "MIT" ]
1
2019-11-05T15:05:27.000Z
2019-11-05T15:05:27.000Z
js/sykepengesoknad/soknad-selvstendig-frilanser/kvittering/Kvittering.js
navikt/sykepengesoknad
b5b07c7cee66b03e8ae0dc1d3245a0bd860bd000
[ "MIT" ]
5
2019-05-28T16:40:46.000Z
2020-06-29T12:38:52.000Z
js/sykepengesoknad/soknad-selvstendig-frilanser/kvittering/Kvittering.js
navikt/sykepengesoknad
b5b07c7cee66b03e8ae0dc1d3245a0bd860bd000
[ "MIT" ]
null
null
null
import React from 'react'; import { getLedetekst, getHtmlLedetekst } from '@navikt/digisyfo-npm'; import { Link } from 'react-router'; import Sidetopp from '../../../components/Sidetopp'; import { IllustrertInnholdGronnHake } from '../../../components/IllustrertInnhold'; const Kvittering = () => { return (<div> <Sidetopp tittel={getLedetekst('sykepengesoknad-selvstendig.kvittering.sendt.tittel')} /> <div className="panel"> <IllustrertInnholdGronnHake> <h2 className="panel__tittel"> {getLedetekst('sykepengesoknad-selvstendig.kvittering.sendt.undertittel')} </h2> <div className="redaksjonelt-innhold" dangerouslySetInnerHTML={getHtmlLedetekst('sykepengesoknad-selvstendig.kvittering.sendt.informasjon')} /> </IllustrertInnholdGronnHake> </div> <p className="ikke-print blokk navigasjonsstripe"> <Link to={`${process.env.REACT_APP_CONTEXT_ROOT}/soknader`} className="tilbakelenke"> {getLedetekst('sykepengesoknad.navigasjon.gaa-til')} </Link> </p> </div>); }; export default Kvittering;
40.466667
125
0.627677
1d5236cf387939ea7bc5677ae83a5964278ed4bd
803
js
JavaScript
service/tshirts.js
manuelpuetz/pace
c5f046724648cadb10e4c47d5fa707dffaa6cb5c
[ "Apache-2.0" ]
12
2015-07-15T17:10:38.000Z
2018-01-29T23:20:07.000Z
service/tshirts.js
manuelpuetz/pace
c5f046724648cadb10e4c47d5fa707dffaa6cb5c
[ "Apache-2.0" ]
86
2015-10-05T16:56:01.000Z
2018-09-11T09:17:18.000Z
service/tshirts.js
manuelpuetz/pace
c5f046724648cadb10e4c47d5fa707dffaa6cb5c
[ "Apache-2.0" ]
21
2015-07-15T16:38:39.000Z
2018-09-28T21:07:13.000Z
/* jshint node: true */ /* jshint esnext: true */ 'use strict'; const _ = require('lodash'); const db = require('../service/util/dbHelper'); let tshirts = {}; tshirts.addFor = (tshirt, participantId) => { return db.insert('insert into tshirts ' + '(size, model, participantId) ' + 'values($1, $2, $3) returning id', [tshirt.size, tshirt.model, participantId]); }; tshirts.getFor = (participantId) => { return db.select('SELECT * FROM tshirts WHERE participantid = $1', [participantId]); }; tshirts.findAndAddTo = function (participant) { return tshirts.getFor(participant.id) .then(shirts => { if (shirts.length > 0) { participant.tshirt = _.pick(shirts[0], ['size', 'model']); } return participant; }); }; module.exports = tshirts;
23.617647
86
0.62142
1d5278a4600c278159eefdd4c04ff1f926fffaa8
412
js
JavaScript
setEmoji.js
scrollback/remarkable-emoji
d297420e39e24b0e0edead11548294f4852d03b3
[ "MIT" ]
15
2015-01-29T13:38:36.000Z
2020-12-30T12:07:41.000Z
setEmoji.js
scrollback/remarkable-emoji
d297420e39e24b0e0edead11548294f4852d03b3
[ "MIT" ]
2
2017-03-20T21:06:47.000Z
2018-03-14T09:49:34.000Z
setEmoji.js
scrollback/remarkable-emoji
d297420e39e24b0e0edead11548294f4852d03b3
[ "MIT" ]
3
2017-05-30T13:42:26.000Z
2020-04-04T19:20:11.000Z
/* jshint node:true */ var emojiMap = require('./emoji-map.js'); module.exports = function (text) { if (typeof text !== "string") { return; } var emoji; var words = text.split(/[,. ]+/); words.forEach(function (word) { if (emojiMap.hasOwnProperty(word)) { emoji = emojiMap[word]; text = text.replace(word, emoji); } }); return text; };
24.235294
45
0.531553
1d53ff8d6c8d0727cd37da769cb930bee11c4569
2,173
js
JavaScript
offline/3.38/esri/layers/pixelFilters/VectorFieldPixelFilter.js
shreepaulnsg/MociPortal_staging_final
82ad837975ef244de4b7f81f1c53f05bd14bcee2
[ "Apache-2.0" ]
null
null
null
offline/3.38/esri/layers/pixelFilters/VectorFieldPixelFilter.js
shreepaulnsg/MociPortal_staging_final
82ad837975ef244de4b7f81f1c53f05bd14bcee2
[ "Apache-2.0" ]
null
null
null
offline/3.38/esri/layers/pixelFilters/VectorFieldPixelFilter.js
shreepaulnsg/MociPortal_staging_final
82ad837975ef244de4b7f81f1c53f05bd14bcee2
[ "Apache-2.0" ]
null
null
null
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/3.38/esri/copyright.txt for details. //>>built define("esri/layers/pixelFilters/VectorFieldPixelFilter","dojo/_base/declare dojo/_base/lang dojo/has ../../kernel ../../lang dojo/_base/array".split(" "),function(g,q,z,A,r,v){g=g(null,{declaredClass:"esri.layers.pixelFilters.VectorFieldPixelFilter",speedUnits:["esriMetersPerSecond","esriKilometersPerHour","esriKnots","esriFeetPerSecond","esriMilesPerHour"],constructor:function(b){q.mixin(this,b);this.isDataUV=b&&b.isDataUV?b.isDataUV:!1;this.computeMagnitudeAndDirection=q.hitch(this,this.computeMagnitudeAndDirection); this.unitConversionFactor=1;this._updateUnitConvFactor()},setUnits:function(b,a){this.inputUnit=b;this.outputUnit=a;this.unitConversionFactor=1;this._updateUnitConvFactor()},_updateUnitConvFactor:function(){var b=v.indexOf(this.speedUnits,this.inputUnit),a=v.indexOf(this.speedUnits,this.outputUnit);if(this.inputUnit&&this.outputUnit&&0<=b&&0<=a){var c=[1,.277778,.514444,.3048,.44704,0];this.unitConversionFactor=c[b]/c[a]}},computeMagnitudeAndDirection:function(b){if(!r.isDefined(b))throw"Could not compute magnitude and direction. No pixel data is available."; var a=b.pixelBlock;if(!r.isDefined(a)||2!==a.getPlaneCount())throw"Could not compute magnitude and direction. Pixel data does not contain two bands.";var c=b.extent,w=(c.xmax-c.xmin)/a.width,x=(c.ymax-c.ymin)/a.height,B=c.xmin+w/2;c=c.ymax-x/2;a.statistics[0].minValue=0;a.statistics[0].maxValue=0;var C=180/Math.PI,y=[],h=0,k=0,d=0,D=!r.isDefined(a.mask),l,m,n,p;var t=n=Infinity;var u=p=-Infinity;for(h=0;h<a.height;h++)for(k=0;k<a.width;k++,d++)if(y.push([B+w*k,c-x*h]),D||a.mask[d]){var e=l=a.pixels[0][d]; var f=m=a.pixels[1][d];this.isDataUV&&(e=Math.sqrt(l*l+m*m),f=90-C*Math.atan2(m,l));a.pixels[0][d]=e*this.unitConversionFactor;a.pixels[1][d]=f;e>u&&(u=e);e<t&&(t=e);f>p&&(p=f);f<n&&(n=f)}a.statistics[0].maxValue=u;a.statistics[0].minValue=t;a.statistics[1].maxValue=p;a.statistics[1].minValue=n;b.locations=y;return b}});z("extend-esri")&&q.setObject("layers.pixelFilters.VectorFieldPixelFilter",g,A);return g});
310.428571
565
0.747814
1d5430f9759028bc674e392ecb6088d6b751c3a5
113
js
JavaScript
src/js/index.js
kalen992/webpack_compile_ts_to_js
c3a6eea9ca32a96e492386e2b694fc4b3cc694b3
[ "MIT" ]
null
null
null
src/js/index.js
kalen992/webpack_compile_ts_to_js
c3a6eea9ca32a96e492386e2b694fc4b3cc694b3
[ "MIT" ]
null
null
null
src/js/index.js
kalen992/webpack_compile_ts_to_js
c3a6eea9ca32a96e492386e2b694fc4b3cc694b3
[ "MIT" ]
null
null
null
import arr from './arr' console.log(`es compile start`); arr.forEach(element => { console.log(element); });
16.142857
32
0.654867
1d55825b8f13bc6ac38ae910282081d2ce17fcb3
988
js
JavaScript
src/lib/Server/Oring.Server.IncomingMessageBase.js
dlid/oringjs
49221ceec41bc6b374637e325d77f5ebd6827ede
[ "MIT" ]
null
null
null
src/lib/Server/Oring.Server.IncomingMessageBase.js
dlid/oringjs
49221ceec41bc6b374637e325d77f5ebd6827ede
[ "MIT" ]
null
null
null
src/lib/Server/Oring.Server.IncomingMessageBase.js
dlid/oringjs
49221ceec41bc6b374637e325d77f5ebd6827ede
[ "MIT" ]
null
null
null
var IncomingMessageBase = { _t : null, _d : null, _c : null, _i : null, _w : null, getData : function() { return this._d; }, getType : function() { return this._t; }, getInvocationID : function() { return this._i; }, expectingResponse : function() { return this._i ? true : false; } }; IncomingMessageBase.__proto__.parse = function(jsonMessage) { console.warn("PARSE", jsonMessage); var o = null; try { o = JSON.parse(jsonMessage); } catch(e) {} if (o && o._t && o._d && o._c) { return Object.create(IncomingMessageBase, { _t : { value : o._t, enumerable : true }, _d : { value : o._d, enumerable : true }, _i : { value : o._i ? o._i : null, enumerable : true } }); } }; module.exports = IncomingMessageBase;
22.454545
61
0.469636
1d55b0fc58f322c3914708cf1a560450830fc2c6
729
js
JavaScript
vuetify.options.js
Sphereon-Opensource/poe-js-webapp
dbc5f1d065cb3a318a9acb5d46edcbbed7741657
[ "Apache-2.0" ]
null
null
null
vuetify.options.js
Sphereon-Opensource/poe-js-webapp
dbc5f1d065cb3a318a9acb5d46edcbbed7741657
[ "Apache-2.0" ]
3
2021-03-10T02:27:18.000Z
2021-06-28T14:26:28.000Z
vuetify.options.js
Sphereon-Opensource/poe-js-webapp
dbc5f1d065cb3a318a9acb5d46edcbbed7741657
[ "Apache-2.0" ]
null
null
null
import LRU from 'lru-cache'; import colors from 'vuetify/lib/util/colors'; const isProduction = process.env.NODE_ENV === 'production'; const themeCache = new LRU({ max: 10, maxAge: 1000 * 60 * 60 }); export default { theme: { options: { themeCache, minifyTheme: value => isProduction ? value.replace(/[\r\n|\r|\n]/g, '') : value, customProperties: true }, themes: { light: { anchor: '#4fe799', primary: '#5000ff', secondary: '#1f2041', tertiary: '#4fe799', accent: colors.blue.accent1, error: colors.red.accent2, info: colors.blue.base, success: colors.green.base, warning: colors.amber.base } } } }
22.090909
86
0.573388
21d301dde4c3c0b3cd3d0689a8798910d4e731e8
4,747
js
JavaScript
JSON/ValueTransformer.randomdatewithrange.js
SmartJSONEditor/PublicDocuments
47e120aebe616f20517a8a94e44191edeeef9b15
[ "MIT" ]
35
2017-09-04T18:28:13.000Z
2022-03-16T16:32:37.000Z
JSON/ValueTransformer.randomdatewithrange.js
SmartJSONEditor/PublicDocuments
47e120aebe616f20517a8a94e44191edeeef9b15
[ "MIT" ]
25
2017-10-17T18:26:30.000Z
2022-03-10T11:35:32.000Z
JSON/ValueTransformer.randomdatewithrange.js
SmartJSONEditor/PublicDocuments
47e120aebe616f20517a8a94e44191edeeef9b15
[ "MIT" ]
7
2017-09-20T02:21:02.000Z
2021-08-16T23:25:54.000Z
var ValueTransformer = function () { this.displayName = "Random Date with Range"; this.shortDescription = "Creates random date string with format within defined range"; this.isEditingDisabled = true; this.infoUrl = "https://github.com/SmartJSONEditor/PublicDocuments/wiki/ValueTransformer-RandomDateWithRange"; this.parameters = function () { var popupDefaultValue = [ { displayName: "Timestamp in seconds | parse() * 1000", value: "timestamp_seconds" }, { displayName: "Timestamp in miliseconds | parse()", value: "timestamp_miliseconds" }, { displayName: "Mon Jan 01 2000 | toDateString()", value: "toDateString" }, { displayName: "2000-01-01T00:00:00.000Z | toISOString()", value: "toISOString" }, { displayName: "01/01/2000 | toLocaleDateString()", value: "toLocaleDateString" }, { displayName: "Mon Jan 01 200 00:00:00 GMT-00600 (CST) | toString()", value: "toString" }, { displayName: "Mon, 01 Jan 2000 00:00:00 GMT | toUTCString()", value: "toUTCString" }, { displayName: "Swift DateFormatter Format", value: "dateformatter" } ]; var popupUIParam = { name: "type", type: "Popup", displayName: "Date Output Format", description: "Select date output format.", defaultValue: popupDefaultValue }; var mindateUIParam = { type: "String", name: "minDate", displayName: "Min Date", description: "Minimum date in Javascript ISO format of yyyy-mm-dd", defaultValue: "2017-01-01" }; var maxdateUIParam = { type: "String", name: "maxDate", displayName: "Max Date", description: "Maximum date in Javascript ISO format of yyyy-mm-dd", defaultValue: "2017-01-30" }; var swiftFormatUIParam = { type: "String", name: "swiftFormatter", displayName: "Swift DateFormatter Format", description: "Using Apple Swift DateFormatter class format string.", defaultValue: "yyyy-MM-dd" }; var segmentsDefaultValues = [ { displayName: "Prepend", enabled: 0 }, { displayName: "Replace" , enabled: 1 }, { displayName: "Append" , enabled: 0 } ]; var segmentsUIParam = { type: "Segments", name: "output", displayName: "Output", description: "Select how to output the value.", defaultValue: segmentsDefaultValues }; return [mindateUIParam, maxdateUIParam, popupUIParam, swiftFormatUIParam, segmentsUIParam]; } this.transform = function (inputValue, jsonValue, arrayIndex, parameters, info) { var type = (Array.isArray(parameters.type) == true) ? "timestamp_seconds" : parameters.type; var minDateString = (parameters.minDate === undefined) ? "2017-01-01" : parameters.minDate; var maxDateString = (parameters.maxDate === undefined) ? "2017-01-30" : parameters.maxDate; var format = (parameters.swiftFormatter === undefined) ? "" : parameters.swiftFormatter; var minDate = new Date(minDateString).getTime(); var maxDate = new Date(maxDateString).getTime(); if (minDate > maxDate) { var tempMin = minDate; var tempMax = maxDate minDate = tempMax; maxDate = tempMin; } var randomTimestamp = integer(minDate, maxDate); var randomDate = new Date(randomTimestamp); var value; if (type == "timestamp_seconds") { value = parseInt(Date.parse(randomDate) / 1000); } if (type == "timestamp_miliseconds") { value = Date.parse(randomDate); } if (type == "toDateString") { value = randomDate.toDateString(); } if (type == "toISOString") { value = randomDate.toISOString(); } if (type == "toLocaleDateString") { value = randomDate.toLocaleDateString(); } if (type == "toString") { value = randomDate.toString(); } if (type == "toUTCString") { value = randomDate.toUTCString(); } if (type == "dateformatter") { value = DocumentModel.dateTimeString(format, parseInt(Date.parse(randomDate) / 1000)); } if (parameters.output[0].enabled == 1) { return value + inputValue; }; if (parameters.output[1].enabled == 1) { return value; }; if (parameters.output[2].enabled == 1) { return inputValue + value; }; return "Error"; }; function integer(min,max) { return Math.floor(Math.random() * (max - min + 1) + min); } } function sjeClass() { return new ValueTransformer(); }
41.640351
121
0.597009
21d3724c0c99ac31782cc0042810fef422afd612
697
js
JavaScript
src/index.js
DevTyping/lavie
ce31aa20452913f1458004f00270447af527fba6
[ "MIT" ]
null
null
null
src/index.js
DevTyping/lavie
ce31aa20452913f1458004f00270447af527fba6
[ "MIT" ]
null
null
null
src/index.js
DevTyping/lavie
ce31aa20452913f1458004f00270447af527fba6
[ "MIT" ]
null
null
null
import * as components from './components' import './css/lavie.css' // Declare install function executed by Vue.use() export default function install (Vue) { if (install.installed) return install.installed = true for (const key in components) { const component = components[key] if (component) { Vue.component(key, component) } } } // Create module definition for Vue.use() const plugin = { install } // Auto-install when vue is found (eg. in browser via <script> tag) let GlobalVue = null if (typeof window !== 'undefined') { GlobalVue = window.Vue } else if (typeof global !== 'undefined') { GlobalVue = global.Vue } if (GlobalVue) { GlobalVue.use(plugin) }
22.483871
67
0.681492
21d3a9c4c3b58732d1a0196dbff10b58bbb9fb1d
1,036
js
JavaScript
ch14/p-06-auto-views.js
Hans-Tsai/nodejs-express-practice
1b6ae0225dfa09f023d9b4b11cae86d0fd400066
[ "MIT" ]
1
2020-12-07T03:37:18.000Z
2020-12-07T03:37:18.000Z
ch14/p-06-auto-views.js
Hans-Tsai/nodejs-express-practice
1b6ae0225dfa09f023d9b4b11cae86d0fd400066
[ "MIT" ]
null
null
null
ch14/p-06-auto-views.js
Hans-Tsai/nodejs-express-practice
1b6ae0225dfa09f023d9b4b11cae86d0fd400066
[ "MIT" ]
null
null
null
const express = require('express'); const expressHandlebars = require('express-handlebars'); const app = express(); // configure Handlebars view engine app.engine('handlebars', expressHandlebars({ defaultLayout: 'main' })); app.set('view engine', 'handlebars'); app.use(express.static(__dirname + '/public')); // provide a home page app.get('/', (req, res) => res.render('06-home')); const autoViews = {}; const fs = require('fs'); const { promisify } = require('util'); const fileExists = promisify(fs.exists); app.use(async (req, res, next) => { const path = req.path.toLowerCase() // 檢查快取,如果它在哪裡,算繪view if(autoViews[path]) return res.render(autoViews[path]) // 如果它沒有在快取,看看有沒有一個相符的(.handlebars)的檔案 if(await fileExists(__dirname + '/views' + path + '.handlebars')) { autoViews[path] = path.replace(/^\//, '') return res.render(autoViews[path]) } // 找到view,交給404處理式 next() }); const port = process.env.PORT || 3000; app.listen(port, () => console.log( `\nnavigate to http://localhost:${port}/05-staff`));
29.6
88
0.67278
21d3ebdf929d55fe2bb5f863bd074066d9dae0f2
2,153
js
JavaScript
infra/platys-datahub/adr/.log4brains/out/_next/static/chunks/3da477db.e49cd5277ed36ace32c1.js
martinpz/data-mesh-hackathon
49b68b478ac870a0c6fe774ba2ed65fea59866f6
[ "Apache-2.0" ]
1
2022-02-10T08:05:56.000Z
2022-02-10T08:05:56.000Z
infra/platys-datahub/adr/.log4brains/out/_next/static/chunks/3da477db.e49cd5277ed36ace32c1.js
martinpz/data-mesh-hackathon
49b68b478ac870a0c6fe774ba2ed65fea59866f6
[ "Apache-2.0" ]
null
null
null
infra/platys-datahub/adr/.log4brains/out/_next/static/chunks/3da477db.e49cd5277ed36ace32c1.js
martinpz/data-mesh-hackathon
49b68b478ac870a0c6fe774ba2ed65fea59866f6
[ "Apache-2.0" ]
8
2022-02-10T09:30:12.000Z
2022-02-10T16:28:46.000Z
(window.webpackJsonp_N_E=window.webpackJsonp_N_E||[]).push([[6],{"OiM/":function(c,t,n){"use strict";n.d(t,"a",(function(){return a})),n.d(t,"b",(function(){return r}));var s=n("1d1W");function a(c){return Object(s.a)({tag:"svg",attr:{version:"1.1",viewBox:"0 0 32 32"},child:[{tag:"path",attr:{d:"M16 3.737v0c-6.126 0-11.127 1.647-11.127 3.692 0 0.539 1.336 8.261 1.866 11.324 0.238 1.373 3.787 3.387 9.259 3.387l0.006-0.017v0.017c5.472 0 9.021-2.014 9.259-3.387 0.53-3.063 1.866-10.785 1.866-11.324-0-2.045-5.002-3.692-11.128-3.692zM16 19.659c-1.953 0-3.537-1.584-3.537-3.537s1.584-3.537 3.537-3.537c1.954 0 3.537 1.584 3.537 3.537s-1.584 3.537-3.537 3.537zM15.998 8.57c-3.936-0.006-7.125-0.69-7.124-1.528s3.193-1.511 7.129-1.505c3.936 0.006 7.125 0.69 7.124 1.528s-3.193 1.511-7.129 1.505zM23.998 21.23c-0.169 0-0.305 0.12-0.305 0.12s-2.74 2.17-7.693 2.17c-4.953-0-7.693-2.17-7.693-2.17s-0.136-0.12-0.305-0.12c-0.202 0-0.394 0.136-0.394 0.435 0 0.032 0.003 0.063 0.009 0.094 0.425 2.276 0.736 3.891 0.791 4.137 0.371 1.675 3.647 2.938 7.591 2.938v0h0.001c3.945-0 7.22-1.264 7.591-2.938 0.055-0.246 0.365-1.861 0.791-4.137 0.006-0.031 0.009-0.062 0.009-0.094 0-0.3-0.192-0.435-0.393-0.435zM18.030 16.15c0 1.064-0.863 1.927-1.927 1.927s-1.927-0.863-1.927-1.927c0-1.064 0.863-1.927 1.927-1.927s1.927 0.863 1.927 1.927z"}}]})(c)}function r(c){return Object(s.a)({tag:"svg",attr:{version:"1.1",viewBox:"0 0 32 32"},child:[{tag:"path",attr:{d:"M26.852 15.281l-9.848-9.848c-0.567-0.567-1.487-0.567-2.054 0l-2.045 2.045 2.594 2.594c0.603-0.204 1.294-0.067 1.775 0.413 0.483 0.483 0.619 1.181 0.41 1.786l2.5 2.5c0.605-0.209 1.303-0.074 1.786 0.41 0.675 0.675 0.675 1.769 0 2.444s-1.769 0.675-2.445 0c-0.508-0.508-0.633-1.254-0.376-1.88l-2.332-2.332v6.136c0.164 0.082 0.32 0.19 0.457 0.327 0.675 0.675 0.675 1.769 0 2.445-0.675 0.675-1.77 0.675-2.444 0-0.675-0.676-0.675-1.77 0-2.445 0.167-0.167 0.36-0.293 0.566-0.377v-6.193c-0.206-0.084-0.399-0.209-0.566-0.377-0.511-0.511-0.634-1.262-0.372-1.889l-2.557-2.558-6.753 6.752c-0.567 0.568-0.567 1.488 0 2.055l9.849 9.848c0.567 0.567 1.486 0.567 2.054 0l9.802-9.802c0.567-0.567 0.567-1.488 0-2.055z"}}]})(c)}}}]);
2,153
2,153
0.666976
21d5c22ff197a7872d226a5524f150c84d6dc508
7,230
js
JavaScript
functions.js
hammam1311/JSEpisode4
206d7fca33abcb3ba6717e5a65dbfde423ea167a
[ "MIT" ]
null
null
null
functions.js
hammam1311/JSEpisode4
206d7fca33abcb3ba6717e5a65dbfde423ea167a
[ "MIT" ]
null
null
null
functions.js
hammam1311/JSEpisode4
206d7fca33abcb3ba6717e5a65dbfde423ea167a
[ "MIT" ]
null
null
null
/************************************************************** * getBookById(bookId, books): * - receives a bookId * - recieves an array of book objects * - returns the book object that matches that id * - returns undefined if no matching book is found ****************************************************************/ function getBookById(bookId, books) { // Your code goes here var bookindex let temp = books.map(function(item,index,array){ if (item.id == bookId) { bookindex =index return item; } }) return books[bookindex] } /************************************************************** * getAuthorByName(authorName, authors): * - receives an authorName * - recieves an array of author objects * - returns the author that matches that name (CASE INSENSITIVE) * - returns undefined if no matching author is found ****************************************************************/ function getAuthorByName(authorName, authors) { // Your code goes here var authindex; let temp = authors.map(function(item,index,array){ if (item.name.toLowerCase() == authorName.toLowerCase()) { authindex =index return item; } }) return authors[authindex] } /************************************************************** * bookCountsByAuthor(authors): * - receives an array of authors * - returns an array of objects with the format: * [{ author: <NAME>, bookCount: <NUMBER_OF_BOOKS> }] ****************************************************************/ function bookCountsByAuthor(authors) { // Your code goes here let soso = []; let obob = { author:"", bookCount:0 } let temp = authors.map(function(item,index,array){ obob.author = item.name; obob.bookCount = item.books.length; soso.push(obob) obob = { author:"", bookCount:0 } return 0 } ) return soso; } /************************************************************** * booksByColor(books): * - receives an array of books * - returns an object where the keys are colors * and the values are arrays of book titles: * { <COLOR>: [<BOOK_TITLES>] } ****************************************************************/ function booksByColor(books) { const colors = {}; let bookt = [] books.forEach(element => { if (!colors[element.color]) { bookt.push(element.title) colors[element.color]=bookt; bookt=[] } else { colors[element.color].push(element.title) } } ) // Your code goes here return colors; } /************************************************************** * titlesByAuthorName(authorName, authors, books): * - receives an authorName * - recieves an array of author objects * - recieves an array of book objects * - returns an array of the titles of the books written by that author: * ["The Hitchhikers Guide", "The Meaning of Liff"] ****************************************************************/ function titlesByAuthorName(authorName, authors, books) { let booksList =[] let booksId=[] authors.forEach(element => { if (element.name.toLowerCase() == authorName.toLowerCase()){ element.books.forEach(book => { booksId.push(book) }); } }); books.forEach(id1 => { booksId.forEach(id2 => { if (id1.id == id2) { booksList.push(id1.title) } }); }); return booksList } /************************************************************** * mostProlificAuthor(authors): * - receives a list of authors * - returns the name of the author with the most books * * Note: assume there will never be a tie ****************************************************************/ function mostProlificAuthor(authors) { let theTop ; let bestNowName = 0 ; let bestNowNum = 0; authors.forEach(x => { if (x.books.length>bestNowNum) { bestNowName = x.name bestNowNum = x.books.length } }); return bestNowName } /************************************************************** * relatedBooks(bookId, authors, books): * - receives a bookId * - receives a list of authors * - receives a list of books * - returns a list of the titles of all the books by * the same author as the book with bookId * (including the original book) * * e.g. Let's send in bookId 37 ("The Shining Girls" by Lauren Beukes): * relatedBooks(37); * We should get back all of Lauren Beukes's books: * ["The Shining Girls", "Zoo City"] * * NOTE: YOU NEED TO TAKE INTO ACCOUNT BOOKS WITH MULTIPLE AUTHORS * * e.g. Let's send in bookId 46 ("Good Omens" by Terry Pratchett and Neil Gaiman): * relatedBooks(46); * We should get back all of Neil Gaiman's books AND all of Terry Pratchett's books: * ["Good Omens", "Good Omens", "Neverwhere", "Coraline", "The Color of Magic", "The Hogfather", "Wee Free Men", "The Long Earth", "The Long War", "The Long Mars"] * * BONUS: REMOVE DUPLICATE BOOKS ****************************************************************/ function relatedBooks(bookId, authors, books) { let theAuthor = []; let bookList=[]; books.forEach(book => { if (book.id==bookId){ book.authors.forEach(auth => { theAuthor.push(auth.name) }); } }); books.forEach(book => { theAuthor.forEach(name => { book.authors.forEach(author => { if (author.name == name){ bookList.push(book.title) } }); }); }); return bookList } /************************************************************** * friendliestAuthor(authors): * - receives a list of authors * - returns the name of the author that has * co-authored the greatest number of books ****************************************************************/ function friendliestAuthor(authors) { let dAuthors = []; let counter = 0 ; authors.forEach(author1 => { authors.forEach(author2 => { author1.books.forEach(book1 => { author2.books.forEach(book2 => { if(book1==book2){ dAuthors.push(author2.name) } }); }); }); }); let x = 0 ; let y = 0; let me = 0; let temp ; dAuthors.forEach(a1 => { me = 0 dAuthors.forEach(a2 => { if (a2 == a1) { if (me == 0) { me++; } else { x++ } } }); if (x > y) { y = x temp = a1 x = 0 } }); return temp } module.exports = { getBookById, getAuthorByName, bookCountsByAuthor, booksByColor, titlesByAuthorName, mostProlificAuthor, relatedBooks, friendliestAuthor }; /** * Uncomment the following lines if you * want to manually test your code */ // const authors = require("./authors.json"); // const books = require("./books.json"); // console.log(getBookById(12, books)); // console.log(getAuthorByName("J.K. Rowling", authors)); // console.log(bookCountsByAuthor(authors)); // console.log(booksByColor(books)); // console.log(titlesByAuthorName("George R.R. Martin", authors, books)); // console.log(mostProlificAuthor(authors)); // console.log(relatedBooks(50, authors, books)); // console.log(friendliestAuthor(authors));
25.457746
168
0.533333
21d5f25e55ce344db97280e702fdc485b44694ea
55
js
JavaScript
app/actions/ActionTypes.js
catdematos98/FTCScout
7234b3a3148a6a83191977926d9de100ffa770b3
[ "MIT" ]
null
null
null
app/actions/ActionTypes.js
catdematos98/FTCScout
7234b3a3148a6a83191977926d9de100ffa770b3
[ "MIT" ]
null
null
null
app/actions/ActionTypes.js
catdematos98/FTCScout
7234b3a3148a6a83191977926d9de100ffa770b3
[ "MIT" ]
null
null
null
// export const SET_RATING_VALUE = 'SET_RATING_VALUE';
27.5
54
0.781818
21d60b521a9f0cbf353c101f1578e63595452984
3,200
js
JavaScript
implementations/server/server.js
Announcement/yaclient
f36e2cf4a6f4b46b872cdcdfb25a61f124afe569
[ "MIT" ]
null
null
null
implementations/server/server.js
Announcement/yaclient
f36e2cf4a6f4b46b872cdcdfb25a61f124afe569
[ "MIT" ]
null
null
null
implementations/server/server.js
Announcement/yaclient
f36e2cf4a6f4b46b872cdcdfb25a61f124afe569
[ "MIT" ]
null
null
null
const net = require('net') const server = new net.Server() const nicks = new Set // LS, LIST, REQ, ACK, NAK, and END. server.on('connection', socket => { let nick; let messages_from_client = 0; console.log('connection') socket.on('close', () => { console.log('close') }) socket.on('connect', () => { console.log('connect') const to = nick !== null && nick !== undefined ? nick : '*' socket.write(`:localhost NOTICE ${to} :***Checking client ID`) socket.write(`:localhost NOTICE ${to} :***JK Welcome to the Server!`) }) socket.on('data', (data /*: Buffer | String */) => { messages_from_client++ const parser = /(?<command>[A-Za-z]+|\d+)(?<parameters>(?: [^\r\n\0: ][^\r\n\0 ]*)*( \:[^\r\n\0]*)?)[\n\r\0]+/gy for (const match of getMatches(parser, data.toString('utf8'))) { const { command } = match.groups const parameters = match.groups.parameters.substring(1) const to = nick !== null && nick !== undefined ? nick : '*' if (command.toUpperCase() === 'capability'.substring(0, 3).toUpperCase()) { if (!/^(LS|LIST|REQ|ACK|NAK|END)/.exec(parameters)) { const errorenous_command = parameters.match(/[a-zA-Z]+ /)[0] socket.write(`:localhost 410 ${to} ${parameters} :CAP subcommand is not valid.\r\n`) } if (/^LS/.test(parameters)) { socket.write(`CAP ${to} LS :identify-msg\r\n`) } console.log('capability negotiation', parameters) } if (command.toUpperCase() === 'NICK') { if (nick !== null && nick !== undefined && !nicks.has(parameters)) { nicks.delete(nick) } if (!nicks.has(parameters)) { nicks.add(parameters) nick = parameters socket.write(`:localhost NOTICE ${to} :Nick shall now be ${nick}\r\n`) } else if (nicks.has(parameters) && nick === parameters) { socket.write(`:localhost NOTICE ${to} :${nick} already the current nick.\r\n`) } else { socket.write(`:localhost NOTICE ${to} :${nick} is already taken!\r\n`) } } console.log({command: match.groups.command, parameters: match.groups.parameters.substring(1)}, messages_from_client) } // console.log(parser.exec(data.toString('utf8'))) process.stdout.write('data: ') process.stdout.write(data.toString('utf8').replace(/[\r\n]+/gim, `\n : `)) console.log('') }) socket.on('drain', () => { console.log('drain') }) socket.on('end', () => { console.log('end') }) socket.on('error', (error /*: Error */) => { console.log('error', error) }) socket.on('lookup', (error/*: Error | null */, address/*: String */, family/*: String | null */, host/*: String */) => { console.log('lookup', { error, address, family, host }) }) socket.on('ready', () => { console.log('ready') }) socket.on('timeout', () => { console.log('timeout') }) }) server.on('listening', (...them) => { console.log('listening', server.address()) }) server.listen(50557) function * getMatches(expression, string) { let that; while ((that = expression.exec(string)) !== null && that !== undefined) yield that }
31.683168
122
0.569063
21d6283cf7b764c4ceb0bd3f25cd94b31549a180
288
js
JavaScript
src/state/loader/reducers/index.js
sgermain06/codebreaker
0fd1e5f53e425b75ea6d8420af931b396d73f71a
[ "MIT" ]
3
2021-03-01T17:03:49.000Z
2021-12-15T20:05:57.000Z
src/state/loader/reducers/index.js
sgermain06/codebreaker
0fd1e5f53e425b75ea6d8420af931b396d73f71a
[ "MIT" ]
null
null
null
src/state/loader/reducers/index.js
sgermain06/codebreaker
0fd1e5f53e425b75ea6d8420af931b396d73f71a
[ "MIT" ]
null
null
null
import {types as EventTypes} from '../events'; import genericReducer from '../../_common/reducers/generic-reducer'; const initialState = false; const reductionLookup = { [EventTypes.Loading]: (_, loading) => loading, }; export default genericReducer(initialState, reductionLookup);
28.8
68
0.743056
21d706ca7e3d9c5152c0d563ab25344d1788f994
3,736
js
JavaScript
dataStore.js
JakeLin/moments-api
7c1e21c727c389fa9d8864c9a564193d14286a4f
[ "MIT" ]
null
null
null
dataStore.js
JakeLin/moments-api
7c1e21c727c389fa9d8864c9a564193d14286a4f
[ "MIT" ]
null
null
null
dataStore.js
JakeLin/moments-api
7c1e21c727c389fa9d8864c9a564193d14286a4f
[ "MIT" ]
null
null
null
const moment = require('moment'); const momentsDetails = { userDetails: { id: '0', name: 'Jake Lin', avatar: 'https://avatars0.githubusercontent.com/u/573856?s=460&v=4', backgroundImage: 'https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg' }, moments: [ { id: '0', userDetails: { id: '1', name: 'Taylor Swift', avatar: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQlk0dgrwcQ0FiTKdgR3atzstJ_wZC4gtPgOmUYBsLO2aa9ssXs', backgroundImage: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQlk0dgrwcQ0FiTKdgR3atzstJ_wZC4gtPgOmUYBsLO2aa9ssXs' }, type: 'PHOTOS', title: null, url: null, photos: ['https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRisv-yQgXGrto6OxQxX62JyvyQGvRsQQ760g&usqp=CAU'], createdDate: moment().subtract(2, 'm').unix(), isLiked: false, likes: [{id: '100', avatar: 'https://images.generated.photos/SZ43KV-Oo26-wpPUM7zDLo19CpGFH0eBnjegQFtvaUc/rs:fit:512:512/Z3M6Ly9nZW5lcmF0/ZWQtcGhvdG9zLzA4/NTUzMzguanBn.jpg'}, {id: '101', avatar: 'https://randomuser.me/api/portraits/women/68.jpg'}, {id: '102', avatar: 'https://uifaces.co/our-content/donated/Si9Qv42B.jpg'}], }, { id: '1', userDetails: { id: '2', name: 'Mattt', avatar: 'https://pbs.twimg.com/profile_images/969321564050112513/fbdJZmEh_400x400.jpg', backgroundImage: 'https://pbs.twimg.com/profile_images/969321564050112513/fbdJZmEh_400x400.jpg' }, type: 'PHOTOS', title: 'Low-level programming on iOS', url: null, photos: ['https://i.pinimg.com/originals/15/27/3e/15273e2fa37cba67b5c539f254b26c21.png'], createdDate: moment().subtract(25, 'm').unix(), isLiked: false, likes: [{id: '103', avatar: 'https://images-na.ssl-images-amazon.com/images/M/MV5BMjEzNjAzMTgzMV5BMl5BanBnXkFtZTcwNjU2NjA2NQ@@._V1_UY256_CR11,0,172,256_AL_.jpg'}, {id: '104', avatar: 'https://uifaces.co/our-content/donated/fID5-1BV.jpg'}, {id: '105', avatar: 'https://randomuser.me/api/portraits/women/69.jpg'}], }, { id: '2', userDetails: { id: '2', name: 'Swift Language', avatar: 'https://developer.apple.com/swift/images/swift-og.png', backgroundImage: 'https://developer.apple.com/swift/images/swift-og.png' }, type: 'PHOTOS', title: "Swift 5.5 🎉 with Async/Await", url: null, photos: ['https://i.morioh.com/210323/d1a235fe.webp'], createdDate: moment().subtract(1, 'd').unix(), isLiked: true, likes: [{id: '0', avatar: 'https://avatars0.githubusercontent.com/u/573856?s=460&v=4'}, {id: '104', avatar: 'https://uifaces.co/our-content/donated/fID5-1BV.jpg'}], }, { id: '3', userDetails: { id: '3', name: 'Swift UI', avatar: 'https://devimages-cdn.apple.com/wwdc-services/articles/images/6F49D049-3D36-4B68-B8C4-96A20A4AF5E1/2048.jpeg', backgroundImage: 'https://devimages-cdn.apple.com/wwdc-services/articles/images/6F49D049-3D36-4B68-B8C4-96A20A4AF5E1/2048.jpeg' }, type: 'PHOTOS', title: 'Swift UI is awesome!!', url: null, photos: ['https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTu_qaT2v7INBNFIOou6MFKdJCJQgXS-sLR5j6VXESd1V7DxOsRjlHiCPFqLN2IdezeIRk&usqp=CAU'], createdDate: moment().subtract(2, 'd').unix(), isLiked: true, likes: [{id: '0', avatar: 'https://avatars0.githubusercontent.com/u/573856?s=460&v=4'}, {id: '105', avatar: 'https://randomuser.me/api/portraits/women/69.jpg'}], }, ] } module.exports = { momentsDetails };
42.942529
179
0.633833
21d726416ae9d05a8e7973a446503e805a8c4e60
449
js
JavaScript
components/activity/type/lang/en.js
BrightspaceHypermediaComponents/foundation-components
485652cd0796c16ca44448521ce67bc1881e91b6
[ "Apache-2.0" ]
4
2020-12-22T16:42:23.000Z
2021-11-02T16:55:07.000Z
components/activity/type/lang/en.js
BrightspaceHypermediaComponents/foundation-components
485652cd0796c16ca44448521ce67bc1881e91b6
[ "Apache-2.0" ]
371
2020-10-21T18:50:03.000Z
2022-03-31T18:35:55.000Z
components/activity/type/lang/en.js
BrightspaceHypermediaComponents/foundation-components
485652cd0796c16ca44448521ce67bc1881e91b6
[ "Apache-2.0" ]
1
2021-03-08T22:37:43.000Z
2021-03-08T22:37:43.000Z
/* eslint quotes: 0 */ export default { "label-activity": "Activity", "label-assignment": "Assignment", "label-checklist": "Checklist", "label-content": "Content", "label-course": "Course", "label-discussion": "Discussion", "label-group": "Group Assignment", "label-groupCategory": "Group Category", "label-individual": "Individual Assignment", "label-learningPath": "Learning Path", "label-quiz": "Quiz", "label-surveys": "Survery" };
26.411765
45
0.685969
21d7d28bb12e902fa6089784a2718b9d2908e0a6
1,050
js
JavaScript
gatsby/data/data.normalize.js
Frainlar/portfolio
f4660585a7beff7538ebdd82d25ea65b94a9e3c5
[ "MIT" ]
2
2021-03-25T05:33:08.000Z
2021-05-12T03:06:41.000Z
gatsby/data/data.normalize.js
Frainlar/portfolio
f4660585a7beff7538ebdd82d25ea65b94a9e3c5
[ "MIT" ]
2
2020-03-15T06:43:19.000Z
2022-02-10T21:29:51.000Z
gatsby/data/data.normalize.js
Frainlar/portfolio
f4660585a7beff7538ebdd82d25ea65b94a9e3c5
[ "MIT" ]
null
null
null
function normalizeHero(article) { let hero = { full: {}, regular: {}, narrow: {}, seo: {} }; if (article.hero) { hero = { full: article.hero.full.fluid }; } else { console.log("\u001B[33m", `Missing hero for "${article.title}"`); } return hero; } module.exports.local = { articles: ({ node: article }) => { return { ...article, hero: normalizeHero(article), date: article.dateString, timeToRead: article.timeToRead, lastModifiedTime: article.lastModificationTime === null ? article.date : article.lastModificationTime, lastModifiedTimeString: article.lastModificationTime === null ? article.dateString : article.lastModificationTimeString, dateModifiedSeoFormat: article.dateModifiedSeoFormat, datePublishedSeoFormat: article.datePublishedSeoFormat, commentId: article.commentId === null ? article.slug : article.commentId, tableOfContents: article.tableOfContents }; } };
25
79
0.625714
21da0498c05769b14ea827c360e6534aced74771
462
js
JavaScript
test/fixtures/jsconfig/src/App.test.js
jhsware/create-inferno-app-experimental
ce420cbb103d69241e8c47934dec1f95ef7102ee
[ "MIT" ]
null
null
null
test/fixtures/jsconfig/src/App.test.js
jhsware/create-inferno-app-experimental
ce420cbb103d69241e8c47934dec1f95ef7102ee
[ "MIT" ]
null
null
null
test/fixtures/jsconfig/src/App.test.js
jhsware/create-inferno-app-experimental
ce420cbb103d69241e8c47934dec1f95ef7102ee
[ "MIT" ]
null
null
null
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import Inferno from 'inferno'; import { render } from 'inferno'; import App from './App'; test('loads modules absolutely with baseUrl', () => { const div = document.createElement('div'); return new Promise(resolve => { render(<App onReady={resolve} />, div); }); });
25.666667
66
0.670996
21dac531201d38ff6beb86e220f149e91df7a5c6
149
js
JavaScript
docs/Doxygen/html/search/variables_3.js
AdrianKoch3010/MarsBaseEngine
77bdd93c74caad0576b226c25ac4b0fe375f51be
[ "MIT" ]
4
2019-06-28T09:27:54.000Z
2020-04-10T03:24:35.000Z
docs/Doxygen/html/search/variables_3.js
AdrianKoch3010/MarsBaseEngine
77bdd93c74caad0576b226c25ac4b0fe375f51be
[ "MIT" ]
null
null
null
docs/Doxygen/html/search/variables_3.js
AdrianKoch3010/MarsBaseEngine
77bdd93c74caad0576b226c25ac4b0fe375f51be
[ "MIT" ]
1
2020-09-15T02:33:21.000Z
2020-09-15T02:33:21.000Z
var searchData= [ ['open',['open',['../classmbe_1_1detail_1_1_a_star_node.html#a3133811951b14150b41a106f570fe38d',1,'mbe::detail::AStarNode']]] ];
29.8
127
0.744966
21dd70c92ca730d57029695efe2879a54ea5e84d
237
js
JavaScript
jest.config.js
HumanBrainProject/hbp-quickfire
2d2c8ec5380815272cfc1182be110eecbdf30c21
[ "MIT" ]
5
2018-11-15T03:48:30.000Z
2020-12-20T16:13:17.000Z
jest.config.js
HumanBrainProject/hbp-quickfire
2d2c8ec5380815272cfc1182be110eecbdf30c21
[ "MIT" ]
7
2019-05-11T00:15:18.000Z
2022-02-12T04:12:06.000Z
jest.config.js
HumanBrainProject/hbp-quickfire
2d2c8ec5380815272cfc1182be110eecbdf30c21
[ "MIT" ]
1
2018-11-15T03:48:37.000Z
2018-11-15T03:48:37.000Z
module.exports = { "verbose": true, "testMatch": ["<rootDir>/src/**/*.test.js"], "transform": { "^.+\\.jsx?$": "babel-jest" }, "collectCoverageFrom": ["<rootDir>/src/**/*.js"], "setupFiles": ["<rootDir>/jest.setup.js"] };
26.333333
51
0.544304
21ded6895705351ac9a091639b1b19499253618e
1,116
js
JavaScript
__tests__/Employee.test.js
civ187/Team-Profile-Genereator
ffef9434c978a4b242f9926369fe18d0a64a8f25
[ "MIT" ]
null
null
null
__tests__/Employee.test.js
civ187/Team-Profile-Genereator
ffef9434c978a4b242f9926369fe18d0a64a8f25
[ "MIT" ]
3
2020-07-26T20:18:50.000Z
2020-07-30T04:32:36.000Z
__tests__/Employee.test.js
civ187/Team-Profile-Generator
ffef9434c978a4b242f9926369fe18d0a64a8f25
[ "MIT" ]
null
null
null
const Employee = require('../lib/Employee.js'); test('Creates Employee Obj', () => { const employee = new Employee('Victor', '0019', 'civ187@gmail.com') expect(employee.name).toBe('Victor'); expect(employee.id).toBe('0019'); expect(employee.email).toBe('civ187@gmail.com'); expect(employee).toEqual(expect.any(Object)); }); test('Get employee Name', () => { const employee = new Employee('Victor', '0019', 'civ187@gmail.com') expect(employee.getName()).toEqual(expect.stringContaining(employee.name.toString())); }); test('Get employee ID', () => { const employee = new Employee('Victor', '0019', 'civ187@gmail.com') expect(employee.getId()).toEqual(expect.stringContaining(employee.id.toString())); }); test('Get employee email', () => { const employee = new Employee('Victor', '0019', 'civ187@gmail.com') expect(employee.getEmail()).toEqual(expect.stringContaining(employee.email.toString())); }); test('Get employee role', () => { const employee = new Employee('Victor', '0019', 'civ187@gmail.com') expect(employee.getRole()).toBe('Employee'); });
32.823529
92
0.659498
21df8eccac4f49c1965a21550d1235ead8ae2eee
9,389
js
JavaScript
demo/scripts/admin_interface.js
filmmaker3d/realitybuilder
5195869b53e46fe4b62d0be3a3d13ec82e6fd014
[ "Apache-2.0" ]
null
null
null
demo/scripts/admin_interface.js
filmmaker3d/realitybuilder
5195869b53e46fe4b62d0be3a3d13ec82e6fd014
[ "Apache-2.0" ]
null
null
null
demo/scripts/admin_interface.js
filmmaker3d/realitybuilder
5195869b53e46fe4b62d0be3a3d13ec82e6fd014
[ "Apache-2.0" ]
null
null
null
// Admin interface to the Reality Builder. // Copyright 2010-2012 Felix E. Klee <felix.klee@inka.de> // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. /*jslint browser: true, maxerr: 50, maxlen: 79 */ /*global $, define */ define(['reality_builder', 'scene/prerendered_sim_poses_b_list.js' ], function (realityBuilder, prerenderedSimPosesBList) { 'use strict'; function updateBlocksVisibilityButton(type, text, blocksAreVisible, setVisibility) { var node = $('.admin.interface button.' + type + 'BlocksVisibility'); node. text((blocksAreVisible ? "Hide" : "Show") + " " + text + " Blocks"). unbind('click'). // necessary if this code is run several times click(function () { node.unbind('click'); setVisibility(!blocksAreVisible); }); } function updateRealBlocksVisibilityButton() { var setVisibility, blocksAreVisible; setVisibility = $.proxy(realityBuilder.setRealBlocksVisibility, realityBuilder); blocksAreVisible = realityBuilder.realBlocksAreVisible(); updateBlocksVisibilityButton('real', 'Real', blocksAreVisible, setVisibility); } function updatePendingBlocksVisibilityButton() { var setVisibility, blocksAreVisible; setVisibility = $.proxy(realityBuilder.setPendingBlocksVisibility, realityBuilder); blocksAreVisible = realityBuilder.pendingBlocksAreVisible(); updateBlocksVisibilityButton('pending', 'Pending', blocksAreVisible, setVisibility); } function setUpSaveSettingsButton() { $('.admin.interface button.saveSettings').click(function () { updateCamera(); realityBuilder.camera.saveToServer(); }); } // Updates the camera, reading data from the camera controls. function updateCamera() { var data = { pos: [parseFloat($('#cameraXTextField').val()) || 0, parseFloat($('#cameraYTextField').val()) || 0, parseFloat($('#cameraZTextField').val()) || 0], aX: parseFloat($('#cameraAXTextField').val()) || 0, aY: parseFloat($('#cameraAYTextField').val()) || 0, aZ: parseFloat($('#cameraAZTextField').val()) || 0, fl: parseFloat($('#cameraFlTextField').val()) || 1, sensorResolution: parseFloat($('#cameraSensorResolutionTextField').val()) || 100 }; realityBuilder.camera.update(data); } function setUpPreviewCameraButton() { $('.admin.interface button.previewCamera').click(updateCamera); } // Updates controls defining the camera "camera". function updateCameraControls() { var camera, pos; camera = realityBuilder.camera; pos = camera.pos(); $('#cameraXTextField').val(pos[0]); $('#cameraYTextField').val(pos[1]); $('#cameraZTextField').val(pos[2]); $('#cameraAXTextField').val(camera.aX()); $('#cameraAYTextField').val(camera.aY()); $('#cameraAZTextField').val(camera.aZ()); $('#cameraFlTextField').val(camera.fl()); $('#cameraSensorResolutionTextField').val(camera.sensorResolution()); } // Resets the construction to the blocks matching the first prerendered // block configuration. function resetBlocks() { var simPosesB = prerenderedSimPosesBList[0]; realityBuilder.constructionBlocks().replaceBlocksOnServer(simPosesB); } function setUpResetBlocksButton() { $('.admin.interface button.resetBlocks').click(resetBlocks); } function updatePosAndADisplay() { var newBlock = realityBuilder.newBlock(); $('.admin.interface .newBlockPose .xB').text(newBlock.xB()); $('.admin.interface .newBlockPose .yB').text(newBlock.yB()); $('.admin.interface .newBlockPose .zB').text(newBlock.zB()); $('.admin.interface .newBlockPose .a').text(newBlock.a()); } // Sorting function for sorting blocks for display in the table. function sortForTable(x, y) { // Sorts first by state (pending < real < deleted), and then by // date-time. if (x.state() === y.state()) { // state the same => sort by date-time if (x.timeStamp() > y.timeStamp()) { return -1; } else if (x.timeStamp() < y.timeStamp()) { return 1; } else { return 0; } } else if (x.state() === 1) { return -1; } else if (x.state() === 2) { return y.state() === 1 ? 1 : -1; } else { return 1; } } // Returns the list of all blocks, except the new block, sorted for display // in the table. function blocksSortedForTable() { return realityBuilder.constructionBlocks().blocks().sort(sortForTable); } // Reads the value of the state selector "selectNode" associated with the // block "block" and triggers setting of the state. function applyStateFromStateSelector(selectNode, block) { realityBuilder.constructionBlocks(). setBlockStateOnServer(block.posB(), block.a(), parseInt(selectNode.val(), 10)); } // Returns a node representing a select button for the state of the block // "block", with the state of that block preselected. function stateSelectorNode(block) { var node; node = $('<select/>', {size: 1}); $.each(['Deleted', 'Pending', 'Real'], function (state, stateName) { var optionNode = $('<option/>', { value: state, text: stateName, selected: state === block.state() }); node.append(optionNode); }); node.change(function () { applyStateFromStateSelector(node, block); }); return node; } function padded(x) { return ((x < 10) ? '0' : '') + x; } // Returns the date-time (local time) in a readable format. function formattedDateTime(timestamp) { var date = new Date(timestamp * 1000); return (date.getFullYear() + '-' + padded((date.getMonth() + 1)) + '-' + padded(date.getDate()) + ' ' + padded(date.getHours()) + ':' + padded(date.getMinutes()) + ':' + padded(date.getSeconds())); } // Creates a row for the blocks table and returns the row node. function blocksTableRowNode(block) { var node, rowValues, cellNode; node = $('<tr/>'); rowValues = [ block.xB(), block.yB(), block.zB(), block.a(), formattedDateTime(block.timeStamp()), stateSelectorNode(block)]; $.each(rowValues, function (i, rowValue) { cellNode = $('<td/>'); if (i < 5) { cellNode.text(rowValue); } else { cellNode.append(rowValue); } if (i < 4) { cellNode.addClass('number'); } node.append(cellNode); }); return node; } // Refreshes the table displaying the list of blocks. function updateBlocksTable() { var node = $('.admin.interface table.blocks tbody'); node.empty(); $.each(blocksSortedForTable(), function (i, block) { node.append(blocksTableRowNode(block)); }); } function onJsonpError() { window.alert('JSONP request failed.'); } function onReady() { setUpSaveSettingsButton(); setUpPreviewCameraButton(); updateCameraControls(); realityBuilder.setRealBlocksVisibility(false); realityBuilder.setPendingBlocksVisibility(false); updateRealBlocksVisibilityButton(); updatePendingBlocksVisibilityButton(); updatePosAndADisplay(); setUpResetBlocksButton(); } return { onReady: onReady, onJsonpError: onJsonpError, onRealBlocksVisibilityChanged: updateRealBlocksVisibilityButton, onPendingBlocksVisibilityChanged: updatePendingBlocksVisibilityButton, onCameraChanged: updateCameraControls, onConstructionBlocksChanged: updateBlocksTable, onMovedOrRotated: updatePosAndADisplay }; });
35.033582
80
0.565023
21dfc47c9b4ee7de2580ca80364cc4c33ab70c73
15,100
js
JavaScript
app/SysUpdateAlerts/SysUpdateAlerts.js
nizovn/luna-systemui
9db5f65a072d2f5af7070efbf38af41705232990
[ "Apache-2.0" ]
null
null
null
app/SysUpdateAlerts/SysUpdateAlerts.js
nizovn/luna-systemui
9db5f65a072d2f5af7070efbf38af41705232990
[ "Apache-2.0" ]
null
null
null
app/SysUpdateAlerts/SysUpdateAlerts.js
nizovn/luna-systemui
9db5f65a072d2f5af7070efbf38af41705232990
[ "Apache-2.0" ]
null
null
null
// @@@LICENSE // // Copyright (c) 2010-2012 Hewlett-Packard Development Company, L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // LICENSE@@@ /* * Popup Alert for Sys Update Install Alert. */ enyo.kind({ name: "SysUpdateInstallAlert", kind: "VFlexBox", components: [ { kind: enyo.Container, className: "notification-container", domAttributes:{ "x-palm-popup-content": " " }, components: [ { className: "notification-icon icon-systemupdate" }, { className: "notification-text", components: [ { className: "title", content: $L("Update Available") }, { className: "message", name:"alertMsg" } ] } ] }, {kind: "ApplicationEvents", onWindowDeactivated:"handleWindowDeActivated"}, {kind: "NotificationButton", className: "enyo-notification-button", layoutKind:"HFlexLayout", pack:"center", onclick: "installlater", components:[{content: $L("Install later")}]}, {kind: "NotificationButton", className: "enyo-notification-button-affirmative", layoutKind:"HFlexLayout", pack:"center", onclick: "installnow", components:[{content: $L("Install now")}]}, { kind:enyo.PalmService, service:"palm://com.palm.update/", components:[ {name:"installLater", method:"InstallLater"}, {name:"alertDisplayed", method:"AlertDisplayed"} ] }, { kind:enyo.PalmService, name:"launchApp", service:"palm://com.palm.applicationManager/", method:"open" } ], create: function() { this.inherited(arguments); this.params = enyo.windowParams; this.tappedOnButton = false; var msg = $L("Installing #{version} will take about #{installTime} minutes. You cannot use your device during this time."); this.$.alertMsg.setContent(new enyo.g11n.Template(msg).evaluate(this.params)); this.$.alertDisplayed.call({open:true}); }, handleWindowDeActivated: function() { if(!this.tappedOnButton) this.$.installLater.call(); this.$.alertDisplayed.call({open:false}); }, installlater: function() { this.tappedOnButton = true; this.$.installLater.call(); this.params.alertType = "first"; enyo.application.getSysUpdateService().showUpdateWaitingDashboard(this.params); close(); }, installnow: function() { this.tappedOnButton = true; //Send InstallLater Message to Update Daemon before launching the Update App. this.$.installLater.call(); //Close the USB Alert. enyo.application.getStoragedService().closeUSBAlerts(); var callParams = { id: 'com.palm.app.updates', 'params': {installNow: true} }; this.$.launchApp.call(callParams); close(); }, cancelAlert: function() { this.tappedOnButton = true; close(); } }); /* * Popup Alert for Sys Update Download. */ enyo.kind({ name: "SysUpdateDownloadAlert", kind: "VFlexBox", components: [ { kind: enyo.Container, className: "notification-container", domAttributes:{ "x-palm-popup-content": " " }, components: [ { className: "notification-icon icon-systemupdate" }, { className: "notification-text", components: [ { className: "title", content: $L("Update Available") }, { className: "message", name:"alertMsg" } ] } ] }, {kind: "ApplicationEvents", onWindowDeactivated:"handleWindowDeActivated"}, {kind: "NotificationButton", className: "enyo-notification-button", layoutKind:"HFlexLayout", pack:"center", onclick: "downloadlater", components:[{content: $L("Download later")}]}, {kind: "NotificationButton", className: "enyo-notification-button-affirmative", layoutKind:"HFlexLayout", pack:"center", onclick: "downloadnow", components:[{content: $L("Download now")}]}, { kind:enyo.PalmService, service:"palm://com.palm.update/", components:[ {name:"installLater", method:"InstallLater"}, {name:"alertDisplayed", method:"AlertDisplayed"} ] }, { kind:enyo.PalmService, name:"launchApp", service:"palm://com.palm.applicationManager/", method:"open" } ], create: function() { this.inherited(arguments); this.params = enyo.windowParams; var msg; if(this.params.allowIncomingCalls) msg = $L("#{version} is ready for download. Because no high speed data connection is available, it will take much longer to download this update."); else msg = $L("#{version} is ready for download. Because no high speed data connection is available, you will be unable to receive incoming calls while the update is downloading."); this.$.alertMsg.setContent(new enyo.g11n.Template(msg).evaluate(this.params)); this.$.alertDisplayed.call({open:true}); }, handleWindowDeActivated: function() { this.$.alertDisplayed.call({open:false}); }, downloadlater: function() { close(); }, downloadnow: function() { var callParams = { id: 'com.palm.app.updates' }; this.$.launchApp.call(callParams); close(); }, cancelAlert: function() { close(); } }); /* * Popup Alert for Sys Update Install(countdown). */ enyo.kind({ name: "SysUpdateFinalInstallAlert", kind: "VFlexBox", components: [ { kind: enyo.Container, className: "notification-container", domAttributes:{ "x-palm-popup-content": " " }, components: [ { className: "notification-icon icon-systemupdate" }, { className: "notification-text", components: [ { className: "title", content: $L("Update Available") }, { className: "message", name:"alertMsg" }, { className: "message", name:"timerMsg" } ] } ] }, {kind: "ApplicationEvents", onWindowDeactivated:"handleWindowDeActivated"}, {kind: "NotificationButton", className: "enyo-notification-button", layoutKind:"HFlexLayout", pack:"center",onclick: "onInstallLater", name:"installLaterButton", components:[{content: $L("Install later")}]}, {kind: "NotificationButton", className: "enyo-notification-button-affirmative", layoutKind:"HFlexLayout", pack:"center", onclick: "onInstallNow", name:"installNowButton", components:[{content: $L("Install now")}]}, { kind:enyo.PalmService, service:"palm://com.palm.update/", components:[ {name:"installLater", method:"InstallLater"}, {name:"installNow", method:"InstallNow"}, {name:"alertDisplayed", method:"AlertDisplayed"} ] }, { kind:enyo.PalmService, name:"launchApp", service:"palm://com.palm.applicationManager/", method:"open" }, { kind:enyo.PalmService, name:"displayOn", service:"palm://com.palm.display/control", method:"setState" } ], create: function() { this.inherited(arguments); this.params = enyo.windowParams; this.tappedOnButton = false; this.choiceSecondStr = new enyo.g11n.Template($L("1#Installation will start in 1 second.|#Installation will start in #{counter} seconds.")); this.choiceMinuteStr = new enyo.g11n.Template($L("1#Installation will start in 1 minute.|#Installation will start in #{counter} minutes.")); // 'Installation will start in n minutes, when your battery is sufficiently charged.' this.choiceSecondBigStr = new enyo.g11n.Template($L("1#Installation will start in 1 second, when your battery is sufficiently charged.|#Installation will start in #{counter} seconds, when your battery is sufficiently charged.")); this.choiceMinuteBigStr = new enyo.g11n.Template($L("1#Installation will start in 1 minute, when your battery is sufficiently charged.|#Installation will start in #{counter} minutes, when your battery is sufficiently charged.")); var msg = $L("Installing #{version} will take about #{installTime} minutes. You cannot use your device during this time."); this.$.alertMsg.setContent(new enyo.g11n.Template(msg).evaluate(this.params)); this.msgUpdateTimer = setInterval(enyo.bind(this, "msgUpdate"), 60000); this.minutesCounter = this.params.countdownTime; this.counter = this.params.countdownTime * 60; this.countdown = 60; if(!this.params.showLaterButton) this.$.installLaterButton.setShowing(false); if (!this.params.shownowbutton) this.$.installNowButton.setShowing(false); this.msgUpdate(); this.$.alertDisplayed.call({open:true}); }, handleWindowDeActivated: function() { if(!this.installlaterselected && this.params.showLaterButton) this.onInstallLater(); else if(!this.installlaterselected && !this.params.showLaterButton) this.onInstallNow(); this.$.alertDisplayed.call({open:false}); }, onInstallNow:function() { if (enyo.application.getPowerdService().getBatteryLevel() < enyo.application.getSysUpdateService().getMinBatThresholdForUpdate()) { this.updateTimeMsg(); return; } this.installlaterselected = true; enyo.application.getStoragedService().closeUSBAlerts(); this.clearTimer(); this.$.installNow.call(); close(); }, onInstallLater:function(){ this.installlaterselected = true; this.clearTimer(); this.$.installLater.call(); this.params.alertType = "final"; enyo.application.getSysUpdateService().showUpdateWaitingDashboard(this.params); close(); }, msgUpdate: function() { var minuteString = (this.params.shownowbutton == true) ? this.choiceMinuteStr : this.choiceMinuteBigStr; var secondString = (this.params.shownowbutton == true) ? this.choiceSecondStr : this.choiceSecondBigStr; if(this.counter > 60) { this.$.timerMsg.setContent(minuteString.formatChoice(this.minutesCounter, {"counter":this.minutesCounter})); } else if(this.counter == 60) { this.$.timerMsg.setContent(minuteString.formatChoice(this.minutesCounter, {"counter":this.minutesCounter})); this.countdown = 30; this.clearTimer(); this.msgUpdateTimer = setInterval(enyo.hitch(this, "msgUpdate"), 30000); } else { this.counter < 0 ? this.$.timerMsg.setContent(secondString.formatChoice(this.counter, {"counter":0})) : this.$.timerMsg.setContent(secondString.formatChoice(this.counter, {"counter":this.counter})); if(this.counter == 30) { this.countdown = 1; this.clearTimer(); this.msgUpdateTimer = setInterval(enyo.hitch(this, "msgUpdate"), 1000); } else if(this.counter == 5) { this.$.displayOn.call({state: "on"}); } else if(this.counter < 0) { this.clearTimer(); this.onInstallNow(); } } this.minutesCounter--; this.counter = this.counter - this.countdown; }, updateTimeMsg : function() { this.$.timerMsg.setContent($L("Installation will start when your battery is sufficiently charged.")); }, updateBatLevel: function() { if(this.counter <= 0) { this.onInstallNow(); return; } if(!this.params.shownowbutton) { this.clearTimer(); this.installlaterselected = true; this.minutesCounter = this.minutesCounter <= 0 ? 1 : this.minutesCounter + 1; this.params.countdownTime = this.minutesCounter; enyo.application.getSysUpdateService().showDelayedFinalUpdateAlert(this.params); close(); } }, clearTimer: function() { if (this.msgUpdateTimer) { try { window.clearInterval(this.msgUpdateTimer); } catch (e) { } this.msgUpdateTimer = undefined; } }, cancelAlert: function() { this.clearTimer(); this.installlaterselected = true; close(); }, }); enyo.kind({ name: "SysUpdateAvailableDash", kind: "HFlexBox", className:"dashboard-window", components: [ { kind: enyo.Container, className: "dashboard-notification-module single", components: [ { className: "palm-dashboard-icon-container", components:[ { name: "dashboard-icon", className: "palm-dashboard-icon updateAvailable" } ]}, { className: "palm-dashboard-text-container", components: [{ className: "dashboard-title", name:"dashTitle" }, { content: $L("Download in progress..."), className: "palm-dashboard-text normal" }] } ] }, { kind:enyo.PalmService, name:"launchApp", service:"palm://com.palm.applicationManager/", method:"open" } ], create: function() { this.inherited(arguments); this.params = enyo.windowParams; this.$.dashTitle.setContent(this.params.version) }, clickHandler: function(inSender) { this.$.launchApp.call({id: 'com.palm.app.updates'}); close(); }, }); enyo.kind({ name: "SysUpdateWaitingDash", kind: "HFlexBox", className:"dashboard-window", components: [ { kind: enyo.Container, className: "dashboard-notification-module single", components: [ { className: "palm-dashboard-icon-container", components:[ { name: "dashboard-icon", className: "palm-dashboard-icon updateAvailable" } ]}, { className: "palm-dashboard-text-container", components: [{ className: "dashboard-title", name:"dashTitle", content: $L("Update available") }, { name:"dashMsg", className: "palm-dashboard-text normal" }] } ] } ], create: function() { this.inherited(arguments); this.params = enyo.windowParams; this.$.dashMsg.setContent(this.params.version); }, clickHandler: function(inSender) { if(this.params.alertType === "first") { enyo.application.getSysUpdateService().showUpdateAlert(this.params); } else { enyo.application.getSysUpdateService().showFinalUpdateAlert(this.params); } close(); }, }); enyo.kind({ name: "SysUpdateDownloadFailedDash", kind: "HFlexBox", className:"dashboard-window", components: [ { kind: enyo.Container, className: "dashboard-notification-module single", components: [ { className: "palm-dashboard-icon-container", components:[ { name: "dashboard-icon", className: "palm-dashboard-icon updateAvailable" } ]}, { className: "palm-dashboard-text-container", components: [{ className: "dashboard-title", name:"dashTitle" }, { content: $L("Download failed"), className: "palm-dashboard-text normal" }] } ] }, { kind:enyo.PalmService, name:"launchApp", service:"palm://com.palm.applicationManager/", method:"open" } ], create: function() { this.inherited(arguments); this.params = enyo.windowParams; this.$.dashTitle.setContent(this.params.version) }, clickHandler: function(inSender) { this.$.launchApp.call({id: 'com.palm.app.updates'}); close(); }, });
28.224299
232
0.661656
21dfd5eb6355606abc97beacce8869ac635def21
5,410
js
JavaScript
js/utils/match/view_model.test.js
FelixRichter2000/FelixRichter2000.github.io
610f310c5b265d82ea07d0c1bf7c0b26436d06f1
[ "MIT" ]
4
2020-02-20T15:26:14.000Z
2021-07-10T13:47:41.000Z
js/utils/match/view_model.test.js
FelixRichter2000/FelixRichter2000.github.io
610f310c5b265d82ea07d0c1bf7c0b26436d06f1
[ "MIT" ]
3
2020-07-11T20:09:04.000Z
2022-02-27T08:51:32.000Z
js/utils/match/view_model.test.js
FelixRichter2000/FelixRichter2000.github.io
610f310c5b265d82ea07d0c1bf7c0b26436d06f1
[ "MIT" ]
1
2022-01-06T22:34:43.000Z
2022-01-06T22:34:43.000Z
const ViewModel = require('./view_model'); describe('test ViewModel', () => { test('create', () => { new ViewModel(); }); test('update_view with hans', () => { document.body.innerHTML = ` <label name="username">defaultUsername</label> `; let viewModel = new ViewModel(); viewModel.update_view({ username: ['hans'] }); expect(document.getElementsByName('username')[0].innerHTML).toEqual('hans'); }); test('update_view with null parameter should not throw error', () => { document.body.innerHTML = ` <label name="username">defaultUsername</label> `; let viewModel = new ViewModel(); viewModel.update_view({ username: null }); expect(document.getElementsByName('username')[0].innerHTML).toEqual('defaultUsername'); }); test('update_view with 0 parameter should work', () => { document.body.innerHTML = ` <label name="username">defaultUsername</label> `; let viewModel = new ViewModel(); viewModel.update_view({ username: [0] }); expect(document.getElementsByName('username')[0].innerHTML).toEqual('0'); }); test('update_view with empty array parameter should not throw error', () => { document.body.innerHTML = ` <label name="username">defaultUsername</label> `; let viewModel = new ViewModel(); viewModel.update_view({ username: [] }); expect(document.getElementsByName('username')[0].innerHTML).toEqual(''); }); test('update_view with another value', () => { document.body.innerHTML = ` <label name="username">defaultUsername</label> `; let viewModel = new ViewModel(); viewModel.update_view({ username: ['another_value'] }); expect(document.getElementsByName('username')[0].innerHTML).toEqual('another_value'); }); test('update_view and element does not exist expect no error', () => { document.body.innerHTML = ` `; let viewModel = new ViewModel(); viewModel.update_view({ username: ['another_value'] }); }); test('update_view with multiple elements with the same name and multiple values', () => { document.body.innerHTML = ` <label name="username">defaultUsername1</label> <label name="username">defaultUsername2</label> `; let viewModel = new ViewModel(); viewModel.update_view({ username: ['another_value1', 'another_value2'] }); expect([...document.getElementsByName('username')].map(e => e.innerHTML)).toEqual(['another_value1', 'another_value2']); }); test('switch_view after update_view should reverse order', () => { document.body.innerHTML = ` <label name="username">defaultUsername1</label> <label name="username">defaultUsername2</label> `; let viewModel = new ViewModel(); viewModel.update_view({ username: ['another_value1', 'another_value2'] }); viewModel.switch_view(); expect([...document.getElementsByName('username')].map(e => e.innerHTML)).toEqual(['another_value2', 'another_value1']); }); test('update_view after switch_view should reverse order', () => { document.body.innerHTML = ` <label name="username">defaultUsername1</label> <label name="username">defaultUsername2</label> `; let viewModel = new ViewModel(); viewModel.switch_view(); viewModel.update_view({ username: ['another_value1', 'another_value2'] }); expect([...document.getElementsByName('username')].map(e => e.innerHTML)).toEqual(['another_value2', 'another_value1']); }); test('update_view with multiple different namees', () => { document.body.innerHTML = ` <label name="username">defaultUsername1</label> <label name="username">defaultUsername2</label> <label name="algoname">defaultAlgoname1</label> <label name="algoname">defaultAlgoname2</label> `; let viewModel = new ViewModel(); viewModel.update_view({ username: ['another_value1', 'another_value2'], algoname: ['another_value10', 'another_value20'] }); expect([...document.getElementsByName('username')].map(e => e.innerHTML)).toEqual(['another_value1', 'another_value2']); expect([...document.getElementsByName('algoname')].map(e => e.innerHTML)).toEqual(['another_value10', 'another_value20']); }); test('update_view with multiple different namees and switch view after', () => { document.body.innerHTML = ` <label name="username">defaultUsername1</label> <label name="username">defaultUsername2</label> <label name="algoname">defaultAlgoname1</label> <label name="algoname">defaultAlgoname2</label> `; let viewModel = new ViewModel(); viewModel.update_view({ username: ['another_value1', 'another_value2'], algoname: ['another_value10', 'another_value20'] }); viewModel.switch_view(); expect([...document.getElementsByName('username')].map(e => e.innerHTML)).toEqual(['another_value2', 'another_value1']); expect([...document.getElementsByName('algoname')].map(e => e.innerHTML)).toEqual(['another_value20', 'another_value10']); }); });
38.642857
130
0.620333
21e14f7849327f92d804c42c89549f1964bf9a1d
1,076
js
JavaScript
src/pages/impressum.js
machermanufaktur/machermanufaktur.at
5fd45a964d45c322f3785f61750a6aa83803f8b7
[ "MIT" ]
null
null
null
src/pages/impressum.js
machermanufaktur/machermanufaktur.at
5fd45a964d45c322f3785f61750a6aa83803f8b7
[ "MIT" ]
null
null
null
src/pages/impressum.js
machermanufaktur/machermanufaktur.at
5fd45a964d45c322f3785f61750a6aa83803f8b7
[ "MIT" ]
null
null
null
import React from 'react'; import Helmet from 'react-helmet'; import Page from '../components/Page'; const SiteNotice = () => { return ( <Page title="Site Notice"> <Helmet> <meta name="robots" content="noindex" /> </Helmet> <h1>Impressum</h1> <p> Offenlegung gemäß § 25 Mediengesetz und § 5 E-Commerce Gesetz: <br /> Heldenmacher <br /> Dominic Pfeffer <br /> Anschrift: <br /> Porzelangasse 3, 1090 Wien <br /> Tel: <a href="tel:+4369919831028">+43 699 198 310 28</a> <br /> E-Mail:{' '} <a href="mailto:office@machermanufaktur.at " > office@machermanufaktur.at </a> <br /> Web: www.machermanufaktur.at </p> <p> Unternehmensgegenstand: <br /> Werbeagentur </p> <p> Rechtsform: <br /> Einzelunternehmen </p> <p> UID-Nummer: <br /> ATU63599207 </p> <p> Kammerzugehörigkeit: <br /> Mitglied der WKÖ, WKOÖ, Fachverband Werbung und Marktkommunikation </p> </Page> ); }; export default SiteNotice;
17.354839
70
0.57342
21e1e192efffc43a8da626ae86bf2b051460a014
542
js
JavaScript
test/data.js
hcxing-se109a/se109a-blog
eb9c298c0f6f846bfae65a4d7cdf2deeeb5c9f42
[ "MIT" ]
null
null
null
test/data.js
hcxing-se109a/se109a-blog
eb9c298c0f6f846bfae65a4d7cdf2deeeb5c9f42
[ "MIT" ]
null
null
null
test/data.js
hcxing-se109a/se109a-blog
eb9c298c0f6f846bfae65a4d7cdf2deeeb5c9f42
[ "MIT" ]
1
2020-11-25T08:06:30.000Z
2020-11-25T08:06:30.000Z
const User = require("../server/models/user"); const Post = require("../server/models/post"); module.exports = { user: { email: "test1@gmail.com", name: "test-user", password: "123456", }, deleteTestUser: async () => { await User.findOneAndDelete({ email: "test1@gmail.com" }); }, post: { title: "test-post", content: "Lorem Ipsum is simply dummy text of the printing and typesetting industry.", }, deleteTestPost: async () => { await Post.findOneAndDelete({ title: "test-post" }); }, };
21.68
83
0.608856
21e25f5502e2799794d3d44ed6790b4bb5af8f08
1,977
js
JavaScript
app.js
ibhi/angular2-parties-app
8b2682d143ce1054d7dda04e2f984f0288c01d05
[ "MIT" ]
null
null
null
app.js
ibhi/angular2-parties-app
8b2682d143ce1054d7dda04e2f984f0288c01d05
[ "MIT" ]
null
null
null
app.js
ibhi/angular2-parties-app
8b2682d143ce1054d7dda04e2f984f0288c01d05
[ "MIT" ]
null
null
null
if (typeof __decorate !== "function") __decorate = function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; if (typeof __metadata !== "function") __metadata = function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var angular2_1 = require('angular2/angular2'); var forms_1 = require('angular2/forms'); var parties_service_1 = require('service/parties-service'); var PartiesComponent = (function () { function PartiesComponent(partiesService, fb) { this.partiesService = partiesService; this.parties = this.partiesService.parties; this.party = fb.group({ title: ['', forms_1.Validators.required], description: ['', forms_1.Validators.required] }); } PartiesComponent.prototype.addParty = function () { this.partiesService.addParty(this.party.value); }; PartiesComponent = __decorate([ angular2_1.Component({ selector: 'parties-list', injectables: [parties_service_1.PartiesService, forms_1.FormBuilder] }), angular2_1.View({ templateUrl: 'parties.html', directives: [angular2_1.For, forms_1.formDirectives] }), __metadata('design:paramtypes', [parties_service_1.PartiesService, (typeof FormBuilder !== 'undefined' && FormBuilder) || Object]) ], PartiesComponent); return PartiesComponent; })(); angular2_1.bootstrap(PartiesComponent);
48.219512
138
0.648457
21e37da6b85eac5b2a3d0513f1d28c929e7b5fc7
1,284
js
JavaScript
docs/js/product_view.js
OlegChuy/Client_Development
b41b7d67165fe12e1bc84b34fad79d9dff819adc
[ "MIT" ]
null
null
null
docs/js/product_view.js
OlegChuy/Client_Development
b41b7d67165fe12e1bc84b34fad79d9dff819adc
[ "MIT" ]
null
null
null
docs/js/product_view.js
OlegChuy/Client_Development
b41b7d67165fe12e1bc84b34fad79d9dff819adc
[ "MIT" ]
null
null
null
"use strict"; import { addInBasketListener, updateButtons } from './addInBasket.js'; const main = document.querySelector('main'); let viewsHTML = []; const productView = (product, productId) => { if (viewsHTML[productId] != undefined) { main.innerHTML = viewsHTML[productId]; addInBasketListener(); updateButtons(); return; } const imageURL = product['images']; let productName = product['productName']; if (product['spicy'] === true) { productName += ` <span class="spicy">(гостра)</span>`; } const weight = (product['categoryId'] === 2) ? `${product['weight']} л` : `${product['weight']} г`; const productHTML = ` <div class="productDiv"> <img class="singleProductImage" src="${imageURL}"> <h4 class="productTitle">${productName}</h4> <p class="productDescription">${product['productDescription']}</p> <div class="priceAndWeight"> <div class="singleProductWeight">${weight}</div> <div class="singleProductPrice productPrice"><span>${product['price']}</span> грн</div> </div> <div id="add${productId}" class="addInBasket">В кошик</div> <div id="rem${productId}" class="removeFromBasket">Відмінити</div> </div> `; viewsHTML.push(productHTML); } export { productView };
31.317073
101
0.640187
21e4f323c1019f22c2df6b1f7d8bbd45c19c7024
10,965
js
JavaScript
src/views/administrator/transaksi/penerimaan/modules/ModalViewPengerjaan.js
antoniluthfi/react-sis-twincom
2eb64f9feae513137816a30fcc77b8dd728968bc
[ "MIT" ]
1
2021-04-09T02:20:19.000Z
2021-04-09T02:20:19.000Z
src/views/administrator/transaksi/penerimaan/modules/ModalViewPengerjaan.js
antoniluthfi/react-sis-twincom
2eb64f9feae513137816a30fcc77b8dd728968bc
[ "MIT" ]
null
null
null
src/views/administrator/transaksi/penerimaan/modules/ModalViewPengerjaan.js
antoniluthfi/react-sis-twincom
2eb64f9feae513137816a30fcc77b8dd728968bc
[ "MIT" ]
null
null
null
import React from "react"; import { CRow, CCol, CModal, CModalHeader, CModalTitle, CModalBody, CFormGroup, CLabel, CInput, CModalFooter, CTextarea, CInputRadio, } from "@coreui/react"; import CurrencyFormat from "react-currency-format"; const ModalViewPengerjaan = (props) => { const { openViewPengerjaanModal, setOpenViewPengerjaanModal, loadCurrentPengerjaan, setLoadCurrentPengerjaan, currentPengerjaan, setCurrentPengerjaan, } = props; return ( <CModal show={openViewPengerjaanModal} onClose={() => { setOpenViewPengerjaanModal(!openViewPengerjaanModal); setLoadCurrentPengerjaan(true); setCurrentPengerjaan({}); }} color="info" closeOnBackdrop={false} > <CModalHeader closeButton> <CModalTitle>Status Pengerjaan</CModalTitle> </CModalHeader> <CModalBody> {loadCurrentPengerjaan ? ( <div> <div className="text-center" style={{ height: 400, paddingTop: 180 }} > <div className="spinner-border" role="status" style={{ width: "3rem", height: "3rem" }} > <p className="sr-only">Loading...</p> </div> <h6 className="text-center">Tunggu bentar yaa..</h6> </div> </div> ) : ( <> <CRow> <CCol xs="12" md="6" className="mb-3"> <CLabel>Status Pengerjaan</CLabel> <CFormGroup variant="custom-radio"> <CInputRadio custom id="status-pengerjaan-2" name="status_pengerjaan" value="0" checked={ currentPengerjaan.status_pengerjaan.toString() === "0" } disabled /> <CLabel variant="custom-checkbox" htmlFor="status-pengerjaan-2" > Belum Dikerjakan </CLabel> </CFormGroup> <CFormGroup variant="custom-radio"> <CInputRadio custom id="status-pengerjaan-2" name="status_pengerjaan" value="2" checked={ currentPengerjaan.status_pengerjaan.toString() === "2" } disabled /> <CLabel variant="custom-checkbox" htmlFor="status-pengerjaan-2" > Sedang dikerjakan </CLabel> </CFormGroup> <CFormGroup variant="custom-radio"> <CInputRadio custom id="status-pengerjaan-3" name="status_pengerjaan" value="3" checked={ currentPengerjaan.status_pengerjaan.toString() === "3" } disabled /> <CLabel variant="custom-checkbox" htmlFor="status-pengerjaan-3" > Selesai </CLabel> </CFormGroup> <CFormGroup variant="custom-radio"> <CInputRadio custom id="status-pengerjaan-1-2" name="status_pengerjaan" value="1" checked={ currentPengerjaan.status_pengerjaan.toString() === "1" } disabled /> <CLabel variant="custom-checkbox" htmlFor="status-pengerjaan-1-2" > Cancel </CLabel> </CFormGroup> </CCol> <CCol xs="12" md="6" className={ currentPengerjaan.status_pengerjaan.toString() === "3" ? "d-inline" : "d-none" } > <CLabel>Cek Stiker</CLabel> <CFormGroup variant="custom-radio"> <CInputRadio custom id="belum-ditempel" name="cek_stiker" value="0" checked={ currentPengerjaan.cek_stiker && currentPengerjaan.cek_stiker.toString() === "0" } disabled /> <CLabel variant="custom-checkbox" htmlFor="belum-ditempel"> Belum ditempel </CLabel> </CFormGroup> <CFormGroup variant="custom-radio"> <CInputRadio custom id="sudah-ditempel" name="cek_stiker" value="1" checked={ currentPengerjaan.cek_stiker && currentPengerjaan.cek_stiker.toString() === "1" } disabled /> <CLabel variant="custom-checkbox" htmlFor="sudah-ditempel"> Sudah Ditempel </CLabel> </CFormGroup> </CCol> </CRow> <CRow> <CCol xs="12" md="6" className={ currentPengerjaan.status_pengerjaan.toString() === "3" ? "d-inline" : "d-none" } > <CFormGroup> <CLabel htmlFor="garansi">Garansi (Hari)</CLabel> <CInput type="number" id="garansi" name="garansi" value={currentPengerjaan.garansi} min="0" placeholder="Masukkan Garansi" disabled /> </CFormGroup> </CCol> <CCol xs="12" md="6" className={ currentPengerjaan.status_pengerjaan.toString() === "1" ? "d-inline" : "d-none" } > <CFormGroup> <CLabel htmlFor="alasan-batal">Alasan Batal</CLabel> <CInput type="text" id="alasan-batal" name="alasan_batal" value={currentPengerjaan.alasan_batal} placeholder="Alasan Batal" disabled /> </CFormGroup> </CCol> <CCol xs="12" md="6"> <CFormGroup> <CLabel htmlFor="biaya-service">Biaya Service</CLabel> <CurrencyFormat id="biaya-service" thousandSeparator={true} prefix={"Rp. "} customInput={CInput} name="biaya_service" value={currentPengerjaan.biaya_service} placeholder="Masukkan Biaya Service" disabled /> </CFormGroup> </CCol> </CRow> <CRow> <CCol xs="12" md="6"> <CLabel htmlFor="pengerjaan">Pengerjaan</CLabel> <CTextarea name="pengerjaan" id="pengerjaan" rows="5" placeholder="Masukkan Pengerjaan" value={ currentPengerjaan.detail_pengerjaan && currentPengerjaan.detail_pengerjaan.pengerjaan } disabled /> </CCol> <CCol xs="12" md="6"> <CLabel htmlFor="keterangan-2">Keterangan</CLabel> <CTextarea name="keterangan" id="keterangan-2" rows="5" placeholder="Masukkan Keterangan" value={ currentPengerjaan.detail_pengerjaan && currentPengerjaan.detail_pengerjaan.keterangan } disabled /> </CCol> </CRow> {currentPengerjaan.penerimaan.jenis_penerimaan !== "Persiapan Barang & QC" && ( <CRow> <CCol xs="12" md="12" className="mt-3"> <CLabel htmlFor="Sparepart">Sparepart</CLabel> <table className="table table-bordered"> <thead> <tr> <th className="text-center" width="10%"> No </th> <th className="text-center">No Faktur</th> <th className="text-center">Nominal</th> <th className="text-center">Keterangan</th> </tr> </thead> <tbody> {currentPengerjaan.sparepart.length > 0 ? ( currentPengerjaan.sparepart.map((item, i) => ( <tr> <td className="text-center" width="10%"> {i + 1} </td> <td className="text-center">{item.no_faktur}</td> <td className="text-right"> Rp.{" "} {new Intl.NumberFormat(["ban", "id"]).format( item.nominal )} </td> <td>{item.keterangan}</td> </tr> )) ) : ( <tr> <td className="text-center" colSpan="4"> Tidak Ada Data </td> </tr> )} </tbody> </table> </CCol> </CRow> )} </> )} </CModalBody> <CModalFooter></CModalFooter> </CModal> ); }; export default ModalViewPengerjaan;
33.027108
77
0.382125
21e53aa91ccde1dd5dffbe3754051ae88b565526
850
js
JavaScript
src/node/squel.factory.js
saphyre/saphyre-data
3d2460b2f1048e3728341f529c3895fd127b4932
[ "MIT" ]
4
2016-03-24T01:13:30.000Z
2020-01-23T18:15:06.000Z
src/node/squel.factory.js
saphyre/saphyre-data
3d2460b2f1048e3728341f529c3895fd127b4932
[ "MIT" ]
12
2016-03-31T13:04:33.000Z
2021-09-01T20:13:27.000Z
src/node/squel.factory.js
saphyre/saphyre-data
3d2460b2f1048e3728341f529c3895fd127b4932
[ "MIT" ]
1
2017-08-04T12:19:18.000Z
2017-08-04T12:19:18.000Z
const squel = require('squel'); exports.get = function (model) { return getBySequelize(model.sequelize); }; exports.getBySequelize = getBySequelize; function getBySequelize(sequelize) { switch (sequelize.options.dialect) { case 'postgres': squel.cls.DefaultQueryBuilderOptions.tableAliasQuoteCharacter = '"'; squel.cls.DefaultQueryBuilderOptions.fieldAliasQuoteCharacter = '"'; squel.cls.DefaultQueryBuilderOptions.nameQuoteCharacter = ""; squel.cls.DefaultQueryBuilderOptions.autoQuoteAliasNames = true; squel.cls.DefaultQueryBuilderOptions.autoQuoteTableNames = true; squel.cls.DefaultQueryBuilderOptions.autoQuoteFieldNames = true; return squel; case 'mysql': return squel; default: return squel; } }
35.416667
80
0.675294
21e5a8621e56fa1083ab4b9c768eb7745fa04437
613
js
JavaScript
src/Breadcrumbs/props/overrides.js
Maks1mS/community-kit
16b5e75808568a5108e174c8cf90aa81a2359516
[ "MIT" ]
5
2021-04-08T13:52:31.000Z
2022-01-21T09:34:19.000Z
src/Breadcrumbs/props/overrides.js
Maks1mS/community-kit
16b5e75808568a5108e174c8cf90aa81a2359516
[ "MIT" ]
15
2021-04-10T07:19:23.000Z
2021-11-16T09:12:44.000Z
src/Breadcrumbs/props/overrides.js
Maks1mS/community-kit
16b5e75808568a5108e174c8cf90aa81a2359516
[ "MIT" ]
4
2021-04-08T13:52:52.000Z
2021-07-28T16:52:51.000Z
export default { Link: { kind: 'Link', props: { margin: '0', padding: '6px .25em', 'text-decoration': 'none', display: 'inline-block', }, }, Text: { kind: 'Text', props: { as: 'span', margin: '0', padding: '6px .25em', display: 'inline-block', }, }, Separator: { kind: 'Text', props: { as: 'span', margin: '0', padding: '6px 0 6px .25em', display: 'inline-block', }, }, };
20.433333
39
0.358891
21e602fa41853d445b32af522cf2f3b741041bdc
412
js
JavaScript
client/components/footer.js
GraceShopper-Anastasia-Daryl-Sasha/array-of-gems
1d9a121a2a08989a62256b2382f1770b94c3da93
[ "MIT" ]
null
null
null
client/components/footer.js
GraceShopper-Anastasia-Daryl-Sasha/array-of-gems
1d9a121a2a08989a62256b2382f1770b94c3da93
[ "MIT" ]
36
2018-07-23T20:34:21.000Z
2018-07-27T16:32:27.000Z
client/components/footer.js
GraceShopper-Anastasia-Daryl-Sasha/array-of-gems
1d9a121a2a08989a62256b2382f1770b94c3da93
[ "MIT" ]
null
null
null
import React from 'react' // import { connect } from 'react-redux' // import { Link } from 'react-router-dom' const Footer = () => ( <footer> <div className="info"> <span className="title">Array Of Gems</span> </div> <div className="copyright"> <span>© 2018, Array Of Gems (A Grace Hopper Brand)</span> </div> </footer> ) export default Footer
21.684211
69
0.565534
21e6d3c133c71509059911266a1432c0837dccf0
555
js
JavaScript
api/lib/services/training-test/training-test.create.service.js
anniyanvr/articulate
b7925c191f6e9065384d5e04796a4d3303f2ee9b
[ "Apache-2.0" ]
592
2018-01-17T13:38:19.000Z
2022-03-25T06:42:52.000Z
api/lib/services/training-test/training-test.create.service.js
anniyanvr/articulate
b7925c191f6e9065384d5e04796a4d3303f2ee9b
[ "Apache-2.0" ]
1,092
2018-01-09T03:53:14.000Z
2022-02-15T00:46:45.000Z
api/lib/services/training-test/training-test.create.service.js
VinayaSathyanarayana/articulate
927c791a359dd51e6f73830f4fefd66716aa50ec
[ "Apache-2.0" ]
175
2018-02-01T14:38:05.000Z
2022-03-25T06:42:54.000Z
import { MODEL_TRAINING_TEST, ROUTE_DOCUMENT, ROUTE_AGENT } from '../../../util/constants'; import ESErrorHandler from '../../errors/es.error-handler'; module.exports = async function ({ data }) { const { es } = this.server.app; const { documentService } = await this.server.services(); const TrainingTestModel = es.models[MODEL_TRAINING_TEST]; try { const result = await TrainingTestModel.createInstance({ data, refresh: true }); return data; } catch (error) { throw ESErrorHandler({ error }); } };
30.833333
91
0.652252
21e79a84c3aa4f36c7e058c2fa53814e14cdcd78
585
js
JavaScript
stories/conversation/conversationCard.js
fishtripr-com/ui
88efe1fc36d8574922961d068a57fea31634a371
[ "MIT" ]
1
2019-07-28T11:26:31.000Z
2019-07-28T11:26:31.000Z
stories/conversation/conversationCard.js
fishtripr-com/ui
88efe1fc36d8574922961d068a57fea31634a371
[ "MIT" ]
11
2019-07-17T12:07:26.000Z
2022-02-26T10:01:11.000Z
stories/conversation/conversationCard.js
fishtripr-com/ui
88efe1fc36d8574922961d068a57fea31634a371
[ "MIT" ]
1
2019-12-12T16:27:38.000Z
2019-12-12T16:27:38.000Z
import { storiesOf } from '@storybook/vue' storiesOf('Conversation card', module) .add( 'Basic', () => ` <conversation-card image="https://s.gravatar.com/avatar/a3895a2d6f26155968be47fc03dddc40?s=80" user-name="Vincent Battaglia" time="a day ago" lastMessage="Hello, I would like to book your experience in Patagonia" additionnalInfo="1 guest - 19 June, 2019 - €33.00" price="€33.00" status="Accepted" statusClass="success" /> `, ) .add( 'Loading mode', () => ` <conversation-card loading/> `, )
23.4
81
0.605128
21e7f83afd8467ad020121bc5f415d47e9c67c01
675
js
JavaScript
src/routes/index.js
aakashsr/HitUP
d2e843825518e441a2f055e9bea423eec53a60cb
[ "MIT" ]
193
2019-02-22T02:38:42.000Z
2022-03-30T13:15:59.000Z
src/routes/index.js
aakashsr/HitUP
d2e843825518e441a2f055e9bea423eec53a60cb
[ "MIT" ]
31
2021-04-04T16:29:11.000Z
2021-07-28T10:33:34.000Z
src/routes/index.js
aakashsr/HitUP
d2e843825518e441a2f055e9bea423eec53a60cb
[ "MIT" ]
21
2019-03-25T10:13:27.000Z
2022-02-09T09:16:56.000Z
import React from 'react'; import { Route, Switch } from 'react-router-dom'; import FeedContainer from 'containers/feed'; import CommentsContainer from 'containers/comments'; import withTracker from './with-tracker'; const FeedContainerWithGATracker = withTracker(FeedContainer); const AppRoutes = () => { return ( <Switch> <Route exact path='/' component={ FeedContainerWithGATracker }/> {/* evaluate HOC wrapper in below can make a rerender after theme change */} <Route exact path='/comments' component={ withTracker(CommentsContainer) }/> <Route component={ FeedContainerWithGATracker }/> </Switch> ); }; export default AppRoutes;
30.681818
82
0.715556
21e85bc15fa28f29182e05b5cabb423134752dd6
780
js
JavaScript
Chapter13/speakermeet-spa/src/App.js
obrieti/Packt-TDD_Development_book
42fb65866b76708a5ae31d124516446f86944707
[ "MIT" ]
16
2018-01-22T15:49:31.000Z
2022-02-12T20:22:50.000Z
Chapter13/speakermeet-spa/src/App.js
obrieti/Packt-TDD_Development_book
42fb65866b76708a5ae31d124516446f86944707
[ "MIT" ]
1
2019-05-18T00:02:31.000Z
2020-09-17T12:54:57.000Z
Chapter13/speakermeet-spa/src/App.js
obrieti/Packt-TDD_Development_book
42fb65866b76708a5ae31d124516446f86944707
[ "MIT" ]
16
2019-04-20T05:23:45.000Z
2022-03-05T16:08:15.000Z
import React, { Component } from 'react'; import { Switch, Route } from 'react-router-dom'; import logo from './logo.svg'; import Header from './common/Header'; import NotFound from './common/NotFound'; import SpeakersPage from './speakers/SpeakersPage'; import SpeakerDetailPage from './speakers/SpeakerDetailPage'; import './App.css'; class App extends Component { render() { return ( <div className="container-fluid"> <Header/> <main> <Switch> <Route exact path='/speakers/:id' component={SpeakerDetailPage}/> <Route exact path='/speakers' component={SpeakersPage}/> <Route path='**' component={NotFound}/> </Switch> </main> </div> ); } } export default App;
27.857143
77
0.611538
21e98f3828f6404f99bab2ba6a3597070556ab74
381
js
JavaScript
index.js
jeremyagray/relue
ccac0a5e0bc5f870029920b59dd0cdd0681b6029
[ "MIT" ]
null
null
null
index.js
jeremyagray/relue
ccac0a5e0bc5f870029920b59dd0cdd0681b6029
[ "MIT" ]
null
null
null
index.js
jeremyagray/relue
ccac0a5e0bc5f870029920b59dd0cdd0681b6029
[ "MIT" ]
null
null
null
'use strict'; /** * @fileOverview Top level module for relue. * * @author Jeremy A Gray <jeremy.a.gray@gmail.com> * * relue * * @module relue */ exports.math = require('./lib/relue/math/index.js'); exports.object = require('./lib/relue/object/index.js'); exports.str = require('./lib/relue/str/index.js'); exports.validation = require('./lib/relue/validation/index.js');
22.411765
64
0.674541
21ea24b68f5fa2b067b5556596cc58d4c75819eb
437
js
JavaScript
common/helpers/metricPrefix.js
ysfBenali/covid-19-next
c9895c5a925197e7bcacfa6a309646f54513f627
[ "MIT" ]
2
2021-08-27T23:29:22.000Z
2021-09-17T08:20:37.000Z
common/helpers/metricPrefix.js
ysfBenali/covid-19-next
c9895c5a925197e7bcacfa6a309646f54513f627
[ "MIT" ]
1
2021-03-11T16:07:06.000Z
2021-03-11T16:07:06.000Z
common/helpers/metricPrefix.js
ysfBenali/covid-19-next
c9895c5a925197e7bcacfa6a309646f54513f627
[ "MIT" ]
null
null
null
const metricPrefix = (value) => { var ranges = [ { divider: 1e9, suffix: "B" }, { divider: 1e6, suffix: "M" }, { divider: 1e3, suffix: "k" }, ]; function formatNumber(n) { for (var i = 0; i < ranges.length; i++) { if (n >= ranges[i].divider) { return (n / ranges[i].divider).toString() + ranges[i].suffix; } } return n; } return formatNumber(value); }; export default metricPrefix;
23
69
0.546911
21eaa433062391ca5414ef563284dfdfa2e1a075
2,480
js
JavaScript
assets/scripts/script.js
Bounty556/Scheduler
68bc015341c169bf68024fa6d5683e25290d0127
[ "Unlicense" ]
null
null
null
assets/scripts/script.js
Bounty556/Scheduler
68bc015341c169bf68024fa6d5683e25290d0127
[ "Unlicense" ]
null
null
null
assets/scripts/script.js
Bounty556/Scheduler
68bc015341c169bf68024fa6d5683e25290d0127
[ "Unlicense" ]
null
null
null
$(document).ready(function() { $("#current-day").text(moment().format('dddd, MMMM D')); $("#time-slots").empty(); // Generate all event time slots for today createTimeSlots(); // Functionality when clicking "save" $(document).on('click', '.save-btn', saveEvent); }); function createTimeSlots() { let startTime = moment(); let currentDaysEvents = JSON.parse(localStorage.getItem(moment().format('MMMMDDYYYY'))); let currentHour = moment().hour(); // Start at 9 am startTime.hour(9); // Go until 5 pm while (startTime.hour() <= 17) { let divRow = $("<div>").attr("class", "row"); let pHour = $("<p>").attr("class", "hour"); let textareaDesc = $("<textarea>"); let saveButton = $("<button>").attr("class", "save-btn"); let formattedTime = startTime.format("hA"); // Display the text as 1 PM for example pHour.text(startTime.format("h A")); if (currentHour > startTime.hour()) { textareaDesc.attr("class", "description past"); } else if (currentHour == startTime.hour()) { textareaDesc.attr("class", "description present"); } else if (currentHour < startTime.hour()) { textareaDesc.attr("class", "description future"); } textareaDesc.attr("id", formattedTime) // Check if current time slot has an event added already if (currentDaysEvents != null && currentDaysEvents[formattedTime] != null) { textareaDesc.text(currentDaysEvents[formattedTime]); } saveButton.html("<i class=\"far fa-save\"></i>"); saveButton.attr("data-hour", formattedTime); divRow.append(pHour); divRow.append(textareaDesc); divRow.append(saveButton); $("#time-slots").append(divRow); // Go to the next hour startTime.hour(startTime.hour() + 1); } } function saveEvent() { // See if days events exists let currentDaysEvents = JSON.parse(localStorage.getItem(moment().format('MMMMDDYYYY'))); if (currentDaysEvents == null) { currentDaysEvents = {}; } // Grab the hour the button is associated with let hour = $(this).attr("data-hour"); // Set the text of the hour in the saved object to be what's in the textarea input currentDaysEvents[hour] = $("#" + hour).val(); localStorage.setItem(moment().format("MMMMDDYYYY"), JSON.stringify(currentDaysEvents)); }
32.207792
92
0.602823
21eb8b41cd4cb7b115ce8bd131f9913aee686716
8,233
js
JavaScript
components/js/siteUsers.js
retvain/yiiwebtest
3ef8bbb7e94df010a2971362140cfbfd361c8558
[ "BSD-3-Clause" ]
null
null
null
components/js/siteUsers.js
retvain/yiiwebtest
3ef8bbb7e94df010a2971362140cfbfd361c8558
[ "BSD-3-Clause" ]
null
null
null
components/js/siteUsers.js
retvain/yiiwebtest
3ef8bbb7e94df010a2971362140cfbfd361c8558
[ "BSD-3-Clause" ]
null
null
null
$(document).ready(function () { //показать всех пользователей при загрузке страницы $.getJSON("http://yiiwebtest.test/users", function (data) { let html = ''; $.each(data, function (key, value) { html += '<tr>'; html += '<th scope="row">' + value.id + '</th>'; html += '<td><img src="' + value.avatar + '"></td>'; html += '<td>' + value.name + '</td>'; html += '<td>' + value.city + '</td>'; html += '<td>' + value.born_date + '</td>'; html += '<td>' + value.phone_number + '</td>'; html += '<td><button class="showComments" id="' + value.id + '">Show comments</button></td>'; html += '</tr>'; }); $('#users').html(html); }); //сгенерировать список для выбора пользователя при добавлении комментария $.getJSON("http://yiiwebtest.test/users", function (data) { let html = ''; $.each(data, function (key, value) { html += '<option value="'+value.id+'">'+value.id+'</option>'; }); $('#user_id').html(html); }); //добавить пользователя и обновить список пользователей $('#SaveUserToBd').on('click', function () { let nameValue = $('#name').val(); let born_dateValue = $('#born_date').val(); let cityValue = $('#city').val(); let phone_numberValue = $('#phone_number').val(); console.log(nameValue, born_dateValue, cityValue, phone_numberValue); /*send data*/ $.ajax({ method: "POST", url: "http://yiiwebtest.test/user/create", data: {name: nameValue, born_date: born_dateValue, city: cityValue, phone_number: phone_numberValue} }) .done(); $('#name').val(''); $('#born_date').val(''); $('#city').val(''); $('#phone_number').val(''); $.getJSON("http://yiiwebtest.test/users", function (data) { let html = ''; $.each(data, function (key, value) { html += '<tr>'; html += '<th scope="row">' + value.id + '</th>'; html += '<td><img src="' + value.avatar + '"></td>'; html += '<td>' + value.name + '</td>'; html += '<td>' + value.city + '</td>'; html += '<td>' + value.born_date + '</td>'; html += '<td>' + value.phone_number + '</td>'; html += '<td><button class="showComments" id="' + value.id + '">Show comments</button></td>'; html += '</tr>'; }); $('#users').html(html); $.getJSON("http://yiiwebtest.test/users", function (data) { let html = ''; $.each(data, function (key, value) { html += '<option value="'+value.id+'">'+value.id+'</option>'; }); $('#user_id').html(html); }); }); }); //добавить и сохранить комментарий $('#SaveCommentToBd').on('click', function () { let textValue = $('#text').val(); let dateValue = $('#date').val(); let userIdValue = $('#user_id').val(); let publishedValue = $("#published").is(":checked") ? 1 : 0; /*send data*/ $.ajax({ method: "POST", url: "http://yiiwebtest.test/comment/create", data: {text: textValue, date: dateValue, user_id: userIdValue, published: publishedValue} }) .done(); $('#text').val(''); }) //изменить статус комментария опубликовано и не опубликовано $('#comments').on('click', 'td.changePublished', function () { let commentId = $(this).attr('id'); let userId = $(this).attr('userid'); let urlForEdit = "http://yiiwebtest.test/comment/update?id=" + commentId; let url = "http://yiiwebtest.test/comment/filter?userId=" + userId; let urlForCheck = "http://yiiwebtest.test/comment/view?id=" + commentId; $.getJSON(urlForCheck, function (data) { if (data.published == 1) { $.ajax({ method: "PUT", url: urlForEdit, data: {published: 0} }) .done(); } else { $.ajax({ method: "PUT", url: urlForEdit, data: {published: 1} }) .done(); } $.getJSON(url, function (data) { let html = ''; $.each(data, function (key, value) { if (value.published == 1) { value.published = 'published'; } else {value.published = 'NOT published'} html += '<tr>'; html += '<th scope="row">' + value.id + '</th>'; html += '<td>' + value.user_id + '</td>'; html += '<td>' + value.date + '</td>'; html += '<td>' + value.text + '</td>'; html += '<td class="changePublished" id="'+value.id+'" userid="'+value.user_id+'">'+ value.published +' CLICK ME TO CHANGE :) '+'</td>'; html += '<td><button class="deleteComment" id="' + value.id + '" userid="' + value.user_id + '">Delete comment</button></td>'; html += '</tr>'; }); $('#comments').html(html); }); }); }); // вывод комментариев пользователя $('#users').on('click', 'button.showComments', function () { let userId = $(this).attr('id'); let url = "http://yiiwebtest.test/comment/filter?userId=" + userId; $.getJSON(url, function (data) { let html = ''; $.each(data, function (key, value) { if (value.published == 1) { value.published = 'published'; } else {value.published = 'NOT published'} html += '<tr>'; html += '<th scope="row">' + value.id + '</th>'; html += '<td>' + value.user_id + '</td>'; html += '<td>' + value.date + '</td>'; html += '<td>' + value.text + '</td>'; html += '<td class="changePublished" id="'+value.id+'" userid="'+value.user_id+'">'+ value.published +' CLICK ME TO CHANGE :) '+'</td>'; html += '<td><button class="deleteComment" id="' + value.id + '" userid="' + value.user_id + '">Delete comment</button></td>'; html += '</tr>'; }); $('#comments').html(html); }); }); //удаление комментария и отрисовка обновленного списка $('#comments').on('click', 'button.deleteComment', function () { let commentId = $(this).attr('id'); let userId = $(this).attr('userid') let urlForDelete = "http://yiiwebtest.test/comment/delete?id=" + commentId; let url = "http://yiiwebtest.test/comment/filter?userId=" + userId; $.ajax({ method: "DELETE", url: urlForDelete, }) .done(); $.getJSON(url, function (data) { let html = ''; $.each(data, function (key, value) { if (value.published == 1) { value.published = 'published'; } else {value.published = 'NOT published'} html += '<tr>'; html += '<th scope="row">' + value.id + '</th>'; html += '<td>' + value.user_id + '</td>'; html += '<td>' + value.date + '</td>'; html += '<td>' + value.text + '</td>'; html += '<td>' + value.published + '</td>'; html += '<td class="changePublished" id="'+value.id+'" userid="'+value.user_id+'">'+ value.published +' CLICK ME TO CHANGE :) '+'</td>'; html += '<td><button class="deleteComment" id="' + value.id + '" userid="' + value.user_id + '">Delete comment</button></td>'; html += '</tr>'; }); $('#comments').html(html); }); }); });
39.581731
158
0.448439
21ebc78935f2bafd207c07c6efb1807913bb1650
1,410
js
JavaScript
05-merge-styles/index.js
HandleWith/HTML-builder
f975c878542b170fc7b01578e9a5d83cc03cd8cb
[ "MIT" ]
null
null
null
05-merge-styles/index.js
HandleWith/HTML-builder
f975c878542b170fc7b01578e9a5d83cc03cd8cb
[ "MIT" ]
null
null
null
05-merge-styles/index.js
HandleWith/HTML-builder
f975c878542b170fc7b01578e9a5d83cc03cd8cb
[ "MIT" ]
null
null
null
const fs = require('fs'); const path = require('path/posix'); const stylePath = path.join('05-merge-styles', 'styles') const mergePath = path.join('05-merge-styles', 'project-dist', 'bundle.css') async function mergeStyle(stylePath, mergePath) { fs.readdir(stylePath, {withFileTypes: true}, (err, data) => { let result = [] if(err) throw err let styles = data.filter(el => path.extname(el.name) === '.css' && el.isFile()) styles.forEach(el => fs.readFile(path.join(stylePath, el.name), 'utf-8', (err, data) => { if(err) throw err result.push(data) createFile(result) })) async function createFile(data) { fs.stat(mergePath, (err) => { if(!err) { rmFile().then( fs.writeFile(mergePath, data.join('\n'), (err) => { if(err) throw err }) ) } else if(err.code === 'ENOENT') fs.writeFile(mergePath, data.join(''), (err) => { if(err) throw err }) }) } async function rmFile() { fs.writeFile(mergePath, '', (err) => { if(err) throw err }) } }) } mergeStyle(stylePath, mergePath)
34.390244
87
0.456738
21ec2028362de781df0905eef28bdbade32a6833
661
js
JavaScript
test/hash_test.js
shmibblez/geocomb-node
af6ae02ae82039b1f6ed254e2702ef4d56bd7e65
[ "MIT" ]
null
null
null
test/hash_test.js
shmibblez/geocomb-node
af6ae02ae82039b1f6ed254e2702ef4d56bd7e65
[ "MIT" ]
null
null
null
test/hash_test.js
shmibblez/geocomb-node
af6ae02ae82039b1f6ed254e2702ef4d56bd7e65
[ "MIT" ]
null
null
null
/* eslint-disable no-undef */ /* eslint-disable no-console */ const geocomb = require("geocomb-node"); // import { HashProperties, Icosahedron, Point3 } from "../lib/index.js"; const Icosahedron = geocomb.Icosahedron; const ico = new Icosahedron("ECEF", "gnomonic"); const lat = 71; const lon = 27; const point = ico.pointFromCoords(lat, lon); const res = 777; const props = ico.hash(point, res); const parsedPoint = ico.parseHash(props); console.log( `hash properties for coords lat: ${lat}, lon: ${lon}, res: ${res}: ` + JSON.stringify(props, null, 2) ); console.log( "parsed point for hash properties: " + JSON.stringify(parsedPoint, null, 2) );
27.541667
77
0.688351
21ecb6a0c3ce4e6c0eec1f7b000572a0cc92060f
746
js
JavaScript
lib/epgp/models/import.js
NoBreaks/API
a7678eb5b3e5fec32f347b19ba18d40ed3221ffa
[ "MIT" ]
null
null
null
lib/epgp/models/import.js
NoBreaks/API
a7678eb5b3e5fec32f347b19ba18d40ed3221ffa
[ "MIT" ]
null
null
null
lib/epgp/models/import.js
NoBreaks/API
a7678eb5b3e5fec32f347b19ba18d40ed3221ffa
[ "MIT" ]
null
null
null
'use strict'; let moment = require('moment-timezone'); let mongoose = require('mongoose'); let Schema = mongoose.Schema; let epgpImportSchema = new Schema({ "data": String, "timestamp": { type: Number, unique: true}, "guildId": { type: mongoose.Schema.Types.ObjectId, ref: 'Guild' }, "createdAt": Date, "updatedAt": Date }); epgpImportSchema.pre('findOneAndUpdate', function(next) { let currentDate = moment(); this.findOneAndUpdate({}, { $set: { updatedAt: currentDate } }); if (!this.createdAt) { this.findOneAndUpdate({}, { $set: { createdAt: currentDate } }); } next(); }); let EPGPImport = mongoose.model('EPGPImport', epgpImportSchema); module.exports = EPGPImport;
22.606061
69
0.635389
21ee6527923d1e32b48af1511eedde0223fb97a3
600
js
JavaScript
server/server/static/models/member.js
imldresden/cofind-plugin
aa0ec580492c6760b6e140680ba330cf5f31746d
[ "MIT" ]
null
null
null
server/server/static/models/member.js
imldresden/cofind-plugin
aa0ec580492c6760b6e140680ba330cf5f31746d
[ "MIT" ]
null
null
null
server/server/static/models/member.js
imldresden/cofind-plugin
aa0ec580492c6760b6e140680ba330cf5f31746d
[ "MIT" ]
null
null
null
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const MemberSchema = new Schema({ __id: Schema.Types.ObjectId, user: { type: Schema.Types.ObjectId, ref: 'User' }, group: { type: Schema.Types.ObjectId, ref: 'Group' }, isActive: { type: Boolean, default: true }, isLoggedIn: { type: Boolean, default: false }, sessions: [{ type: Schema.Types.ObjectId, ref: 'Session' }] }, { timestamps: true }); const Member = mongoose.model('Member', MemberSchema); module.exports = Member;
22.222222
54
0.585
21f17f11457612a463d6c16d729805a82cc78119
445
js
JavaScript
src/components/organisms/page/landing/SectionSyntax/styled/index.js
LeGmask/nord-docs
d38ae7fdb42008bd5d6c08ea29a6437dd5171654
[ "MIT" ]
86
2018-04-27T11:59:39.000Z
2022-02-20T09:31:41.000Z
src/components/organisms/page/landing/SectionSyntax/styled/index.js
LeGmask/nord-docs
d38ae7fdb42008bd5d6c08ea29a6437dd5171654
[ "MIT" ]
160
2018-05-12T18:28:48.000Z
2021-09-21T05:54:53.000Z
src/components/organisms/page/landing/SectionSyntax/styled/index.js
LeGmask/nord-docs
d38ae7fdb42008bd5d6c08ea29a6437dd5171654
[ "MIT" ]
36
2019-01-21T18:35:33.000Z
2021-12-20T04:51:03.000Z
/* * Copyright (C) 2018-present Arctic Ice Studio <development@arcticicestudio.com> * Copyright (C) 2018-present Sven Greb <development@svengreb.de> * * Project: Nord Docs * Repository: https://github.com/arcticicestudio/nord-docs * License: MIT */ import CodeSyntaxLines, { POSE_DRAW, POSE_ERASE } from "./CodeSyntaxLines"; import WaveDivider from "./WaveDivider"; export { CodeSyntaxLines, WaveDivider, POSE_DRAW, POSE_ERASE };
31.785714
81
0.739326
21f2dc8576b6dae525fd7085cc5e0ea175c8088b
315
js
JavaScript
lib/models/form-gen-model.js
libertyware-limited/ngx-form
20cf2340d4d08ef3b6cabe9065f379cc42618344
[ "MIT" ]
null
null
null
lib/models/form-gen-model.js
libertyware-limited/ngx-form
20cf2340d4d08ef3b6cabe9065f379cc42618344
[ "MIT" ]
1
2021-09-02T02:33:05.000Z
2021-09-02T02:33:05.000Z
lib/models/form-gen-model.js
libertyware-limited/ngx-form
20cf2340d4d08ef3b6cabe9065f379cc42618344
[ "MIT" ]
null
null
null
import { validate } from 'class-validator'; import { plainToClassFromExist } from 'class-transformer'; export class FormGenModel { constructor(data) { plainToClassFromExist(this, data); } async isValid() { const errors = await validate(this); return errors.length === 0; } }
26.25
58
0.650794
21f4ca9366516ce9c625c04f39868ecaca2ccd89
1,123
js
JavaScript
src/commands/Util/invite.js
AetherLibs/Aero
4eb02869b6b93bd968d98f60d6e03b4600a60180
[ "BSD-3-Clause" ]
null
null
null
src/commands/Util/invite.js
AetherLibs/Aero
4eb02869b6b93bd968d98f60d6e03b4600a60180
[ "BSD-3-Clause" ]
null
null
null
src/commands/Util/invite.js
AetherLibs/Aero
4eb02869b6b93bd968d98f60d6e03b4600a60180
[ "BSD-3-Clause" ]
null
null
null
const { MessageEmbed, Permissions: { FLAGS } } = require('discord.js'); const { Command } = require('@aero/klasa'); const req = require('@aero/http'); module.exports = class extends Command { constructor(...args) { super(...args, { guarded: true, description: language => language.get('COMMAND_INVITE_DESCRIPTION'), aliases: ['inv'] }); } async run(message) { const invite = req('https://discord.com/oauth2/authorize') .query('client_id', this.client.user.id) .query('scope', this.client.config.install_params.scopes.join(' ')) .query('permissions', this.client.config.install_params.permissions) .url.href || this.client.config.inviteURL || this.client.invite; return !message.guild.me.permissions.has(FLAGS.EMBED_LINKS) ? message.sendLocale('COMMAND_INVITE', this.client.user.username, invite) : message.sendEmbed(new MessageEmbed() .setAuthor(this.client.user.username, this.client.user.avatarURL()) .setDescription(`${message.guild.language.get('COMMAND_INVITE_SUCCESS', this.client.user.username, invite, this.client.config.supportServer)}`) ); } };
33.029412
147
0.700801
21f8d6996e6b70179b4b186b076fa801aa9d6889
7,952
js
JavaScript
models/Encryptor/Encryptor_Signer.js
DICE-Money/DICE-Cli-Core
42371e2555891a38194f85b3b105ae4e27ad717f
[ "Apache-2.0" ]
2
2018-06-25T21:17:45.000Z
2018-08-08T18:42:14.000Z
models/Encryptor/Encryptor_Signer.js
DICE-Money/DICE-Cli-Core
42371e2555891a38194f85b3b105ae4e27ad717f
[ "Apache-2.0" ]
null
null
null
models/Encryptor/Encryptor_Signer.js
DICE-Money/DICE-Cli-Core
42371e2555891a38194f85b3b105ae4e27ad717f
[ "Apache-2.0" ]
2
2018-06-27T06:29:15.000Z
2018-07-13T19:37:24.000Z
/* javascript-obfuscator:disable */ /* * Copyright 2017-2018 Mihail Maldzhanski<pollarize@gmail.com>. * DICE Money Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //Required const modCrypto = require("crypto"); const modSecp160k1 = require("../AddressCalculator/Secp160k1.js"); const certificateWorker = require("../AddressCalculator/CertificateWorker.js"); /* javascript-obfuscator:enable */ //Class access var _Method = Encryptor.prototype; //Local const const cIV_LENGTH = 16; // For AES, this is always 16 const cAUTH_TAG_LENGTH = 32; // For GCM, is always 32 const cErrorLevel_1 = 1; const cErrorLevel_2 = 2; const cErrorLevel_3 = 3; const cAlgorithm = 'aes-256-gcm'; //Constructor function Encryptor(keyPair, security) { //Init component with already known keys this._160k1 = new modSecp160k1(_checkForNull(keyPair)); //Set Security _Method.setSecurityLevel(security); //Hold Big Certificate this._certificateBank = {digitalAddress: undefined, certificate: undefined}; } //Private Methods function _Encrypt(data, sharedKey) { var bufData = new Buffer.from(data); let iv = modCrypto.randomBytes(cIV_LENGTH); var cipher = modCrypto.createCipheriv(cAlgorithm, sharedKey, iv); var encrypted = cipher.update(bufData.toString("hex"), 'hex', 'hex'); encrypted += cipher.final('hex'); var tag = cipher.getAuthTag(); var returnData = { iv: iv.toString("base64"), content: Buffer.from(encrypted, "hex").toString("base64"), tag: tag.toString("base64") }; return Buffer.from(JSON.stringify(returnData), "utf8").toString("base64"); } function _Decrypt(data, sharedKey) { var encrypted = JSON.parse(Buffer.from(data, "base64").toString("utf8")); var decipher = modCrypto.createDecipheriv(cAlgorithm, sharedKey, Buffer.from(encrypted.iv, "base64")); decipher.setAuthTag(Buffer.from(encrypted.tag, "base64")); var decrypted = decipher.update(encrypted.content, 'base64', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } function _checkForNull(data) { if (data === null) { throw "Cannot be Null !"; } return data; } function _SHA256(text) { var hash = modCrypto. createHash('sha256'). update(text). digest(); return hash; } //Public Methods _Method.encryptDataPublicKey = function (toEncrypt, publicKey) { //Check for existing certificate if (this._certificateBank[publicKey] !== undefined) { certificate = this._certificateBank[publicKey]; } else { return "Invalid public Key"; } //1. Prepare secret var sharedKey = this.certWorker.computeSecret(certificate); //2. Sign with small key var smallSignature = this._160k1.sign(toEncrypt); //3. Sign data and signature with big key var dataAndSmallSignature = {data: toEncrypt, sign: smallSignature}; var dataAndBigSignature = this.certWorker.sign(JSON.stringify(dataAndSmallSignature)); //4. Return encetypted data with two signatures return _Encrypt(JSON.stringify({data: dataAndSmallSignature, sign: dataAndBigSignature}), _SHA256(sharedKey), null, null); }; _Method.decryptDataPublicKey = function (toDecrypt, publicKey) { var decryptedAndVerifiedData = undefined; //Check for existing certificate if (this._certificateBank[publicKey] !== undefined) { certificate = this._certificateBank[publicKey]; } else { return "Invalid public Key"; } //1. Prepare secret var sharedKey = this.certWorker.computeSecret(certificate); //2. Decrypt data and parse it to object var decryptedData = JSON.parse(_Decrypt(toDecrypt, _SHA256(sharedKey), null, null)); //3. Verify is signed with private key of publicKey (Big) if (false !== this.certWorker.verify(JSON.stringify(decryptedData.data), decryptedData.sign, certificate)) { //4. Verify is signed with private key of publicKey (Big) if (false !== this._160k1.verify(decryptedData.data.data, decryptedData.data.sign, publicKey)) { decryptedAndVerifiedData = decryptedData.data.data; } else { return cErrorLevel_2; } } else { return cErrorLevel_1; } //5. Return decrypted data return decryptedAndVerifiedData; }; _Method.encryptFilePublicKey = function (toEncrypt, publicKey) { var sharedKey = this._160k1.computeSecret(publicKey); return _Encrypt(toEncrypt, _SHA256(sharedKey), null, null); }; _Method.decryptFilePublicKey = function (toDecrypt, publicKey) { var sharedKey = this._160k1.computeSecret(publicKey); return _Decrypt(toDecrypt, _SHA256(sharedKey), null, null); }; _Method.setPrivateKey = function (keyPair) { //Init component with already known keys this._160k1 = new modSecp160k1(keyPair); }; _Method.setSecurityLevel = function (security) { //Create unique key pair for big keys this.certWorker = new certificateWorker(security); this.certWorker.genarateKeys(); }; _Method.getKeyExchangeCertificate = function (publicKey) { //1. Prepare sectret var sharedKey = this._160k1.computeSecret(publicKey); //2. Prepare certificate and sign it with small key var bigCertificate = this.certWorker.getCertificate(); var bigCertSignature = this._160k1.sign(bigCertificate); //3. Sign bigCertificate with big key var bigCertWithSiganture = {cert: bigCertificate, sign: bigCertSignature}; var bigCertSignPairSignature = this.certWorker.sign(JSON.stringify(bigCertWithSiganture)); //4. Last Sign everything with small key var lastSignedData = {cert: bigCertWithSiganture, sign: bigCertSignPairSignature}; var lastSignedDataSignature = this._160k1.sign(lastSignedData); //5. Return encrypted data return _Encrypt(JSON.stringify({cert: lastSignedData, sign: lastSignedDataSignature}), _SHA256(sharedKey), null, null); }; _Method.acceptKeyExchangeCertificate = function (signedCertificate, publicKey) { //1. Prepare sectret var sharedKey = this._160k1.computeSecret(publicKey); //2. Decrypt data var decryptedData = JSON.parse(_Decrypt(signedCertificate, _SHA256(sharedKey), null, null)); //3. Verify is signed with private key of publicKey (Small) if (false !== this._160k1.verify(decryptedData.cert, decryptedData.sign, publicKey)) { //4. Verify is signed with private key of publicKey (Big) if (false !== this.certWorker.verify(JSON.stringify(decryptedData.cert.cert), decryptedData.cert.sign, decryptedData.cert.cert.cert)) { //5. Verify is signed with private key of publicKey (Small) if (false !== this._160k1.verify(decryptedData.cert.cert.cert, decryptedData.cert.cert.sign, publicKey)) { this._certificateBank[publicKey] = decryptedData.cert.cert.cert; } else { return cErrorLevel_3; } } else { return cErrorLevel_2; } } else { return cErrorLevel_1; } return this._certificateBank[publicKey]; }; _Method.removeOldCertificate = function (publicKey) { try { delete this._certificateBank[publicKey.toString("utf8")]; } catch (e) { //The operation was invalid but there is no action needed } }; _Method.IsBankEmpty = function () { return Object.keys(this._certificateBank).length === 2; }; module.exports = Encryptor;
34.128755
143
0.699447
21f912eae5fff1d90b3df3687a8cbb7632e913c4
328
js
JavaScript
src/components/title.js
tzablah/alpha-brands
db35c020d069b912c65c55affc7fc647b774d33e
[ "RSA-MD" ]
null
null
null
src/components/title.js
tzablah/alpha-brands
db35c020d069b912c65c55affc7fc647b774d33e
[ "RSA-MD" ]
null
null
null
src/components/title.js
tzablah/alpha-brands
db35c020d069b912c65c55affc7fc647b774d33e
[ "RSA-MD" ]
1
2020-12-21T19:53:15.000Z
2020-12-21T19:53:15.000Z
import React from "react"; const Title = ({ text, id, sans, className }) => { return ( <h3 id={id} className={`${sans ? 'font-opensans text-xl' : 'font-poppins text-2xl'} md:text-brandmd lg:text-3xl font-bold leading-9 tracking-widest text-black ${className}`}> {text} </h3> ); }; export default Title;
27.333333
168
0.621951
21f98e3140c3f91aeecfb296c4b9392aad59648f
1,067
js
JavaScript
src/App.js
Ashwanikumar27/DemoPOC
bdd3298df2668e174999c7a5c0afb74f26dfd2f6
[ "Apache-2.0" ]
null
null
null
src/App.js
Ashwanikumar27/DemoPOC
bdd3298df2668e174999c7a5c0afb74f26dfd2f6
[ "Apache-2.0" ]
null
null
null
src/App.js
Ashwanikumar27/DemoPOC
bdd3298df2668e174999c7a5c0afb74f26dfd2f6
[ "Apache-2.0" ]
null
null
null
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Child from './child.js'; var i=-1; class App extends Component { constructor(props) { super(props); this.state = { display:[], src:['one','two','three','four','five','six','seven','eight','nine','ten'], renderChild: false }; } plus() { i=i+1; if(i<this.state.src.length) { this.state.display.push(this.state.src[i]); this.setState({renderChild: true}); } } remove(index) { var simi= this.state.display; simi.splice(index,1); this.setState({display:simi}); this.render(); } render() { var opp=this.state.display.map(function(value,key){ return( <Child value={value} key1={key} delete1={this.remove.bind(this)} /> ) }.bind(this)); return ( <div className="App"> <button onClick={this.plus.bind(this)}>plus</button> {this.state.renderChild ? opp : null} </div> ); } } export default App;
18.719298
81
0.56045
21fa9089bfbe4ad8f85a13936d60ff65e95522fc
1,480
js
JavaScript
lib/allParentsIds.js
nearform/nscale-planner
40a33413dce28d2f95b3a8036a7c63a6c82b877e
[ "Artistic-2.0" ]
1
2019-06-12T19:34:18.000Z
2019-06-12T19:34:18.000Z
lib/allParentsIds.js
nearform/nscale-planner
40a33413dce28d2f95b3a8036a7c63a6c82b877e
[ "Artistic-2.0" ]
null
null
null
lib/allParentsIds.js
nearform/nscale-planner
40a33413dce28d2f95b3a8036a7c63a6c82b877e
[ "Artistic-2.0" ]
null
null
null
/* * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ 'use strict'; /** @module lib/allParentsIds */ /** * Returns all parents of the passed container, minus the root. * * @param {object} context - the system definition in which to perform the search * @param {object} container - the container to search */ function allParentsIds(context, container, parents) { var isLeaf = parents === undefined; parents = parents || []; // doing this before pushing skips the root if (!container.containedBy || container.containedBy === container.id) { return parents; } if (!isLeaf) { parents.push(container.id); } // let's order them by tree order return allParentsIds(context, context.topology.containers[container.containedBy], parents); } module.exports = allParentsIds;
33.636364
93
0.72973
21fa97a9ab8d260242d8c6738139ef8b6f5dba90
3,141
js
JavaScript
src/layers/screen-saver.js
Azerothian/code-deck
e47c51397fa870e38c256d56f169de7c654d73a4
[ "MIT" ]
null
null
null
src/layers/screen-saver.js
Azerothian/code-deck
e47c51397fa870e38c256d56f169de7c654d73a4
[ "MIT" ]
null
null
null
src/layers/screen-saver.js
Azerothian/code-deck
e47c51397fa870e38c256d56f169de7c654d73a4
[ "MIT" ]
null
null
null
import {Layer, LayerGroup} from "../engine"; import { getColours, rgbToHex } from "../utils/gradient"; import { WIDTH, HEIGHT } from "../utils/deck"; const g = [ { position: 0, colour: { r: 49, g: 192, b: 246, }, }, { position: 50, colour: { r: 165, g: 0, b: 165, }, }, { position: 100, colour: { r: 255, g: 126, b: 39, }, }, ]; function Factory(colours) { this.x = Math.round(Math.random() * WIDTH); this.y = Math.round(Math.random() * HEIGHT); this.rad = Math.round(Math.random() * 1) + 1; this.rgba = colours[Math.round(Math.random() * 10)]; this.vx = Math.round(Math.random() * 3) - 1.5; this.vy = Math.round(Math.random() * 3) - 1.5; } class ScreenSaverLayer extends Layer { constructor() { super(); this.particles = []; this.particlesNum = 20; this.colors = getColours(g, 11).map((c) => rgbToHex(c)); for (var i = 0; i < this.particlesNum; i++) { this.particles.push(new Factory(this.colors)); } this.opacitySpeed = 0.1; this.opacityDir = true; //true = increment } update(delta) { const diff = 1 / (delta * this.opacitySpeed); let o = this.opacity; if (this.opacityDir) { o += diff; } else { o -= diff; } if (o > 1) { this.opacityDir = false; o = 1; } else if (o < 0) { this.opacityDir = true; o = 0; } this.opacity = o; } render() { this.ctx.clearRect(0, 0, WIDTH, HEIGHT); this.ctx.globalCompositeOperation = "lighter"; for (var i = 0; i < this.particlesNum; i++) { var temp = this.particles[i]; var factor = 1; for (var j = 0; j < this.particlesNum; j++) { var temp2 = this.particles[j]; this.ctx.linewidth = 0.5; if (temp.rgba === temp2.rgba && findDistance(temp, temp2) < 50) { this.ctx.strokeStyle = temp.rgba; this.ctx.beginPath(); this.ctx.moveTo(temp.x, temp.y); this.ctx.lineTo(temp2.x, temp2.y); this.ctx.stroke(); factor++; } } this.ctx.fillStyle = temp.rgba; this.ctx.strokeStyle = temp.rgba; this.ctx.beginPath(); this.ctx.arc(temp.x, temp.y, temp.rad * factor, 0, Math.PI * 2, true); this.ctx.fill(); this.ctx.closePath(); this.ctx.beginPath(); this.ctx.arc(temp.x, temp.y, (temp.rad + 5) * factor, 0, Math.PI * 2, true); this.ctx.stroke(); this.ctx.closePath(); temp.x += temp.vx; temp.y += temp.vy; if (temp.x > WIDTH) { temp.x = 0; } if (temp.x < 0) { temp.x = WIDTH; } if (temp.y > HEIGHT) { temp.y = 0; } if (temp.y < 0) { temp.y = HEIGHT; } } } } function findDistance(p1, p2) { return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2)); } export default () => { const screenSaverArr = []; for (let i = 1; i < 4; i++) { const s = new ScreenSaverLayer(); s.opacitySpeed = i / 10; s.opacity = i / 10; s.opacityDir = i === 2; screenSaverArr.push(s); } return new LayerGroup(screenSaverArr); };
23.440299
82
0.530723
21fb115041a1a88b9063832c85c4c9281b1d9977
723
js
JavaScript
src/Solvers/Heuristic.js
3izzo/N-Puzzle
3f2837ce5df988bad5410da58d4acc9a3748fd7f
[ "MIT" ]
1
2020-09-04T16:00:04.000Z
2020-09-04T16:00:04.000Z
src/Solvers/Heuristic.js
ziyadmsq/N-Puzzle---AI-class
0234e13d7a2cb063588dc9697905f616c5fab337
[ "MIT" ]
5
2020-04-14T21:19:55.000Z
2021-03-10T12:12:25.000Z
src/Solvers/Heuristic.js
3izzo/N-Puzzle
3f2837ce5df988bad5410da58d4acc9a3748fd7f
[ "MIT" ]
null
null
null
const manhattanDistance = (node) => { let result = 0; for (let i = 0; i < node.state.length; i++) { for (let j = 0; j < node.state[i].length; j++) { let elem = node.state[i][j]; if (elem == 0) continue; let targetRow = parseInt((elem-1) / node.state.length); let targetCol = (elem - 1) % node.state.length; // console.log(elem + " " + targetRow + " " + targetCol + " " + Math.abs(i - targetRow) + Math.abs(j - targetCol)); result += Math.abs(i - targetRow) + Math.abs(j - targetCol); } } // console.table(node.state); // console.log(result); return result; }; export default manhattanDistance;
36.15
127
0.521438
21fbcc9b8183d5bff7560de37c13a94c80063e0d
170
js
JavaScript
balances/src/routes/index.js
EliseevNP/nodetest
9ea05cd89fb2b0028bf345a66ab6d481982671b1
[ "MIT" ]
null
null
null
balances/src/routes/index.js
EliseevNP/nodetest
9ea05cd89fb2b0028bf345a66ab6d481982671b1
[ "MIT" ]
null
null
null
balances/src/routes/index.js
EliseevNP/nodetest
9ea05cd89fb2b0028bf345a66ab6d481982671b1
[ "MIT" ]
null
null
null
const Router = require('koa-router'); const balances = require('./balances'); const router = new Router(); router.use('/balances', balances); module.exports = router;
18.888889
39
0.7
21fc41d6ba23bd118491cfe9f6190d2561647b44
142
js
JavaScript
src/all/Array.prototype.all.js
mcibique/linq-for-js
5737214731634cba590bb4ce17cbcb28132f0d13
[ "MIT" ]
3
2017-03-22T02:20:21.000Z
2019-08-16T14:04:17.000Z
src/all/Array.prototype.all.js
mcibique/linq-for-js
5737214731634cba590bb4ce17cbcb28132f0d13
[ "MIT" ]
2
2018-05-22T23:34:29.000Z
2020-01-27T12:14:33.000Z
src/all/Array.prototype.all.js
mcibique/linq-for-js
5737214731634cba590bb4ce17cbcb28132f0d13
[ "MIT" ]
null
null
null
import Iterator from '../iterators/Iterator'; Array.prototype.all = function all(condition) { return new Iterator(this).all(condition); };
23.666667
47
0.739437
21fc645d59991e03dd34264d231fa77ffb4d63e6
22
js
JavaScript
src/assets/js/index.js
corderophilosophy/the-ball-of-wax
989f9e9a988bc04cd343da5b6c245eafc4d15196
[ "MIT" ]
null
null
null
src/assets/js/index.js
corderophilosophy/the-ball-of-wax
989f9e9a988bc04cd343da5b6c245eafc4d15196
[ "MIT" ]
null
null
null
src/assets/js/index.js
corderophilosophy/the-ball-of-wax
989f9e9a988bc04cd343da5b6c245eafc4d15196
[ "MIT" ]
null
null
null
// Main JS goes here
11
21
0.636364
21fca123639ce77cfc88affc8d83f2dfa87a0852
4,181
js
JavaScript
src/block.js
joshtechnologygroup/blockchain
479dd6527164b2e1b6e086c28e9a9955ed49aa94
[ "MIT" ]
null
null
null
src/block.js
joshtechnologygroup/blockchain
479dd6527164b2e1b6e086c28e9a9955ed49aa94
[ "MIT" ]
null
null
null
src/block.js
joshtechnologygroup/blockchain
479dd6527164b2e1b6e086c28e9a9955ed49aa94
[ "MIT" ]
2
2018-02-25T18:56:03.000Z
2018-10-21T01:40:17.000Z
'use strict'; module.exports = class Block { constructor(index, hash, previousHash, data, timestamp, nonce) { this.index = index; this.hash = hash.toString(); this.previousHash = previousHash.toString(); this.data = data; this.timestamp = timestamp; this.nonce = nonce; this.state = { content: {}, author: {}, contract: {}, content_contract: {}, content_to_buyer: {}, user_credit: {} } } getContentIndex(content) { return this.state["content"][content]; } copyPreviousState(previousBlock) { this.state = JSON.parse(JSON.stringify(previousBlock.state)); } verifyContent() { const users = this.data['entities']; for (let i = 0; i < users.length; i++) { if (!this.state["author"].hasOwnProperty(users[i])) { return false; } } return true; } updateAuthorState() { // if (!this.state["author"].hasOwnProperty(this.data["address"])) { this.state["author"][this.data["address"]] = this.index; // } } updateContentState() { // if (!this.state["content"].hasOwnProperty(this.data["address"])) { this.state["content"][this.data["address"]] = this.index; this.updateContentContractState(); // } }; updateContractState() { // if (!this.state["contract"].hasOwnProperty(this.data["address"])) { this.state["contract"][this.data["address"]] = this.index; // } } updateContentContractState() { const previousContent = this.state["content"][this.data["address"]]; this.state["content"][this.data["address"]] = this.index; const actions = this.data["content"]["actions"]; if (this.state["content_contract"].hasOwnProperty(previousContent)) { this.state["content_contract"][this.index] = this.state["content_contract"][previousContent]; delete this.state["content_contract"][previousContent] } else { this.state["content_contract"][this.index] = {} } const actionList = Object.keys(actions); for (let i = 0; i < actionList.length; i++) { const type = actionList[i]; const contract = actions[type]["contract"]; const params = actions[type]["params"]; this.state["content_contract"][this.index][type] = { contract: this.state["contract"][contract] } } } updateTransactionState() { const transactions = this.data["txns"]; for (let i = 0; i < transactions.length; i++) { const transaction = transactions[i]; const transactionType = transaction["tx_type"]; const to = transaction["to"]; const from = transaction["from"]; const value = transaction["value"]; const action = transaction["action"]; if (transactionType === "user-content") { const state = transaction["state"]; const contract = this.state["contract"][from]; const content = this.state["content"][value]; if (!this.state["content_to_buyer"].hasOwnProperty(content)) { this.state["content_to_buyer"][content] = { entities: [] }; } this.state["content_to_buyer"][content]["entities"].push({ "user": to, "action": action, "state": state }) } else if (transactionType === "user-credit") { if (!this.state["user_credit"].hasOwnProperty(from)) { this.state["user_credit"][from] = 0; } if (!this.state["user_credit"].hasOwnProperty(to)) { this.state["user_credit"][to] = 0; } this.state["user_credit"][from] -= value; this.state["user_credit"][to] += value; } } } };
35.735043
105
0.520928
21feaf1e5e3e4dbe61e57d1913f9b45e0c5f115b
2,243
js
JavaScript
src/utils/UploadBase.js
HastingsGreer/girder_web_components
ef91df35e09c850bb8b2cfcf0dc2f8ce0567eab8
[ "Apache-2.0" ]
16
2018-08-10T15:42:42.000Z
2022-03-22T13:00:21.000Z
src/utils/UploadBase.js
HastingsGreer/girder_web_components
ef91df35e09c850bb8b2cfcf0dc2f8ce0567eab8
[ "Apache-2.0" ]
221
2018-08-07T17:26:55.000Z
2022-03-15T17:34:29.000Z
src/utils/UploadBase.js
HastingsGreer/girder_web_components
ef91df35e09c850bb8b2cfcf0dc2f8ce0567eab8
[ "Apache-2.0" ]
8
2019-04-17T13:40:20.000Z
2020-12-15T16:18:23.000Z
export default class UploadBase { /** * The abstract base class of a single file uploader. * @abstract * @param {File | Blob} file the file to upload * @param {Object} opts upload options. * @param {Object} opts.$rest an axios instance used for communicating with Girder. * @param {Object} opts.parent upload destination. Must have ``_id`` and ``_modelType``. * @param {Function} opts.progress A progress callback for the upload. It can take an Object * argument with either ``"indeterminate": true``, or numeric ``current`` and ``size`` fields. */ constructor( file, { $rest, parent, progress = () => null, } = {}, ) { Object.assign(this, { $rest, file, parent, progress, }); } /** * Start the upload. The returned Promise will be resolved with the Girder file that was created * or rejected with an ``Error`` that has ``config``, ``request``, and ``response`` properties. * @abstract */ async start() { // eslint-disable-line class-methods-use-this throw new Error('not implemented'); } /** * If an error has been encountered, when user clicks the Resume button, * this ``resume()`` will be called. The simplest implementation is to call ``start()`` directly. */ async resume() { return this.start(); } /** * This callback is called before the upload is started. This callback is asynchronous. * If it returns a Promise, the caller will await its resolution before continuing. */ // eslint-disable-next-line class-methods-use-this, no-unused-vars beforeUpload() {} /** * This callback is called after the upload is completed. This callback is asynchronous. * If it returns a Promise, the caller will await its resolution before continuing. */ // eslint-disable-next-line class-methods-use-this, no-unused-vars afterUpload() {} /** * This callback is called if an error occurs during the upload. This callback is asynchronous. * If it returns a Promise, the caller will await its resolution before continuing. * @param {Exception} error The exception object. */ // eslint-disable-next-line class-methods-use-this, no-unused-vars onError(error) {} }
33.477612
99
0.662506
21ff74eb3bd4ab2880427adf99f6e7a4dff2e53c
5,890
js
JavaScript
pet/pages/unPayWork/index.js
leeboo741/pet
898eb4103e6d8b6e01ab78d68f9e12653c0f5bc5
[ "MIT" ]
1
2020-08-14T06:18:35.000Z
2020-08-14T06:18:35.000Z
pet/pages/unPayWork/index.js
leeboo741/pet
898eb4103e6d8b6e01ab78d68f9e12653c0f5bc5
[ "MIT" ]
null
null
null
pet/pages/unPayWork/index.js
leeboo741/pet
898eb4103e6d8b6e01ab78d68f9e12653c0f5bc5
[ "MIT" ]
1
2019-09-16T06:23:41.000Z
2019-09-16T06:23:41.000Z
// pages/unPayWork/index.js const util = require("../../utils/util.js"); const config = require("../../utils/config.js"); const loginUtil = require("../../utils/loginUtils.js"); const pagePath = require("../../utils/pagePath.js"); const ShareUtil = require("../../utils/shareUtils.js"); const workOrderManager = require("../../manager/orderManager/workOrderManager.js"); const notificationCenter = require("../../manager/notificationCenter.js"); const { WORKORDER_DELETE, WORKORDER_ADD_REMARK, WORKORDER_CHANGE_PRICE, WORKORDER_UPLOAD_PAYMENT_VOUCHER, WORKORDER_ADD_TEMPDELIVER } = require("../../static/notificationName.js"); const app = getApp(); const Limit = 20; Page({ /** * 页面的初始数据 */ data: { orderList: [], // 订单列表 userInfo: null, loadMoreLoading: false, loadMoreTip: "暂无数据", offset: 0, keyword: null, orderDate: null, orderStateList: [ config.Order_State_ToPay, // 待付款 config.Order_State_ToVerify // 待审核 ], // 订单状态列表 currentOrderState: "全部", // 当前订单状态 }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { app.globalData.verifyPaymentVoucherOrder = null; wx.startPullDownRefresh(); }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, startRefresh: function(){ this.data.offset = 0; let that = this; this.setData({ loadMoreLoading: true, loadMoreTip: "数据加载中" }) this.getOrderData(this.data.offset, function getDataCallback(data){ that.setData({ orderList: data }) that.data.offset = that.data.offset + Limit; that.setData({ loadMoreLoading: false, }) if (data.length >= Limit) { that.setData({ loadMoreTip: "上拉加载数据" }) } else if (data.length < Limit && data.length > 0) { that.setData({ loadMoreTip: "已经到底了" }) } else { that.setData({ loadMoreTip: "暂无数据" }) } } ); }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { this.startRefresh(); }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { if (this.data.loadMoreTip == "已经到底了" || this.data.loadMoreTip == "数据加载中" || this.data.loadMoreTip == "暂无数据") { return; } this.setData({ loadMoreTip: "数据加载中", }) let that = this; this.getOrderData(this.data.offset, function getDataCallback(data){ let tempList = that.data.orderList.concat(data); that.setData({ orderList: tempList }) that.data.offset = that.data.offset + Limit; that.setData({ loadMoreLoading: false, }) if (data.length >= Limit) { that.setData({ loadMoreTip: "上拉加载数据" }) } else { that.setData({ loadMoreTip: "已经到底了" }) } } ) }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { return ShareUtil.getOnShareAppMessageForShareOpenId(); }, /** * 点击确认输入搜索 * @param {*}} e */ searchOrder: function(e) { this.data.keyword = e.detail.value; wx.startPullDownRefresh(); }, /** * 点击选择状态 */ tapStateFilter: function() { let that = this; wx.showActionSheet({ itemList: ['全部','待付款','待审核'], success(res) { if (res.tapIndex == 0) { that.changeCurrentOrderState("全部"); } else if (res.tapIndex == 1) { that.changeCurrentOrderState(config.Order_State_ToPay); } else if (res.tapIndex == 2) { that.changeCurrentOrderState(config.Order_State_ToVerify); } } }) }, /** * 更改当前订单状态 */ changeCurrentOrderState: function(state) { this.setData({ currentOrderState : state }) if (state != config.Order_State_ToPay && state != config.Order_State_ToVerify) { this.data.orderStateList = [ config.Order_State_ToPay, config.Order_State_ToVerify ]; } else { this.data.orderStateList = [state]; } wx.startPullDownRefresh(); }, /** * 获取数据 */ getOrderData: function (offset, getDataCallback) { let that = this; loginUtil.checkLogin(function alreadyLoginCallback(state) { if (state) { if (util.checkEmpty(that.data.userInfo)) { that.setData({ userInfo: loginUtil.getUserInfo() }) } that.requestOrderList(offset, function callback(data) { if (getDataCallback && typeof getDataCallback == "function") { getDataCallback(data); } } ); } }) }, /** * 请求单据 */ requestOrderList: function (offset, getOrderDataCallback) { let that = this; workOrderManager.getOrderList_1(this.data.orderStateList, offset, Limit, this.data.keyword, this.data.orderDate, function(success, data) { wx.stopPullDownRefresh(); wx.hideLoading(); if (success) { if (util.checkIsFunction(getOrderDataCallback)) { getOrderDataCallback(data); } } else { wx.showToast({ title: '获取订单列表失败', icon: 'none' }) } }) }, /** * 拨打电话 */ callPhone: function (e) { let phoneNumber = e.currentTarget.dataset.phone; if (util.checkEmpty(phoneNumber)) { return; } wx.makePhoneCall({ phoneNumber: phoneNumber, }) }, /** * 点击订单详情 */ tapOrderDetail: function(e) { wx.navigateTo({ url: '/pages/orderDetail/workOrderDetail/index' + "?orderno=" + e.currentTarget.dataset.orderno, }) }, })
22.310606
180
0.56129