max_stars_repo_path
stringlengths
3
961
max_stars_repo_name
stringlengths
5
122
max_stars_count
int64
0
224k
id
stringlengths
1
8
content
stringlengths
2
1.07M
score
float64
-0.95
3.88
int_score
int64
0
4
__tests__/units/density/Ounce.js
Eldelshell/flowsnake
1
15989916
import _ from 'lodash'; import Density from '../../../lib/units/density/Density'; import TestCase from '../TestCase'; const tests = [{ from: 'oz/in3', to: 'oz/ft3', values: [{ a: 1, b: 1728 }] },{ from: 'oz/in3', to: 'oz/gal', values: [{ a: 1, b: 231 }] }]; TestCase.units(Density, tests);
1
1
React (Tyler McGinnis course)/react-practice/src/Daily files/Day 1 Components and expressions/Day 1 Expressions.js
Pratham82/React-
0
15989924
import React from "react"; export default class App extends React.Component { render() { const name = "Prathamesh"; return ( <div> <h2>Hi my name is {name} 👋 </h2> <h2>45 * 5= {45 * 5}</h2> <h2>Today's date is {new Date().toLocaleDateString()}</h2> </div> ); } } // Button in tailwind { /* <button className="bg-blue-500 hover:bg-blue-400 duration-200 px-5 py-2 m-5 rounded" onClick="{changeAuthSate}" > Toggle Auth </button>; */ }
1.046875
1
virtual-dom/Gruntfile.js
meiersi/ghcjs-vdom
83
15989932
module.exports = function(grunt) { grunt.initConfig({ browserify: { lib: { files: { 'lib.js': ['lib.require.js'] } } }, watch: { lib: { files: 'lib.require.js', tasks: ['browserify:lib'] } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-browserify'); grunt.registerTask('default', ['browserify']); };
0.789063
1
test/convert-sync.js
danielnarey/data-types
0
15989940
import test from 'ava'; import convertSync from '../src/convert-sync'; // test array const arr = [ '', 'apple', 'banana', '1', '2', '0.1', '0.2', 'NaN', 'true', 'false', 1, 2, 0.1, 0.2, NaN, true, false, null, {}.a, {}, () => {}, ]; // ---TESTS---// test('toString', (t) => { const typeMap = new Map([ ['Undefined', ''], ['Null', ''], ['Boolean', '1'], ['Function', '!'], ]); const valueMap = new Map([ ['apple', 'fruit'], ['banana', 'fruit'], [NaN, '?'], [false, '0'], ]); const f = convertSync.toString(typeMap)(valueMap); const expected = [ '', 'fruit', 'fruit', '1', '2', '0.1', '0.2', 'NaN', 'true', 'false', '1', '2', '0.1', '0.2', '?', '1', '1', '', '', '{}', '!', ]; t.deepEqual(arr.map(f), expected); }); test('toNumber', (t) => { const typeMap = new Map([ ['Undefined', NaN], ['Null', NaN], ['Object', -1], ['Function', -1], ]); const valueMap = new Map([ ['apple', 10], ['banana', 20], [0.1, 1], [0.2, 2], [false, -1], ]); const f = convertSync.toNumber(typeMap)(valueMap); const expected = [ 0, 10, 20, 1, 2, 0.1, 0.2, NaN, NaN, NaN, 1, 2, 1, 2, NaN, 1, -1, NaN, NaN, -1, -1, ]; t.deepEqual(arr.map(f), expected); }); test('toBoolean', (t) => { const typeMap = new Map([ ['Undefined', false], ['Null', false], ['Object', false], ['Function', false], ]); const f = convertSync.toBoolean(typeMap)(); const expected = [ false, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, false, false, false, false, false, ]; t.deepEqual(arr.map(f), expected); }); test('toDate', (t) => { const typeMap = new Map([ ['Undefined', new Date(NaN)], ['Null', new Date(NaN)], ['Object', new Date(NaN)], ['Function', new Date(NaN)], ]); const f = convertSync.toDate(typeMap)(); const dateArr = [ '1999-1-1', '1999-1-3', 0, 1, null, {}.a, {}, () => {}, ]; const expected = [ new Date('1999-1-1'), new Date('1999-1-3'), new Date(0), new Date(1), new Date(NaN), new Date(NaN), new Date(NaN), new Date(NaN), ]; t.deepEqual(dateArr.map(f), expected); });
1.382813
1
src/pages/about-the-book.js
inksharedsolutions/loisrichmanv2
0
15989948
import React from 'react'; import Layout from '../layout/layout'; import { Helmet } from 'react-helmet'; import Banner2 from '../components/banner2'; import styles from './css/about-the-book.module.scss'; const Book = () => { return ( <Layout> <Helmet> <title>About the Book</title> </Helmet> <Banner2 pagetitle="About the Book" /> <div className="main-nonhome"> <div className="container"> <div className="row"> <div className={`col-md-6 ${styles.aboutTheBookImg}`}> <img src="../book.png" alt="Book" /> </div> <div className={`col-lg-6 ${styles.aboutTheBookContents}`}> <h2 className="title"> Key West Interlude <span>By <NAME></span> </h2> <p> Captain <NAME> has been found dead next to his fishing vessel, The Ramblin’ Rose, facedown in the waters at the Bahia Honda Inlet near Key West, Florida. </p> <p> Meanwhile, Paulette Marshall has left her mansion on top of Mulholland Drive in the very rich and prestigious Bel Air, California, neighborhood after winning the property during a very contentious divorce she did not want. Arriving at Key West, she is hired by the local high school as a counselor. </p> <p> Her student <NAME> is the victim of sexual abuse by the captain, who had been her mentor and provider as well as a father figure. Ariel was aboard that ill-fated trip to Islamorada and is considered a person of interest to local authorities. Pregnant with Max’s child and only an alcoholic mother and absent father to turn to, who can Ariel trust now? </p> <p> Further, there is the issue of $300,000 missing from the safe of Hernandez’s fishing boat. If Ariel tells authorities about the one envelope she did take, feeling assured Hernandez wanted her to have the money for a new start, she could go to jail and be charged with stealing the entire amount. </p> <p> This plays right into the plans of Susanna, the captain’s youngest daughter, who is hot to recover the $300,000 so her drug dealer husband will take her back. </p> <p> In between all the action, Key West turns out to be the perfect getaway for Paulette as she works through no longer being “someone’s daughter, wife, or mother.” As a woman finally able to seek her own road, Paulette hopes she can do the same for Ariel. </p> <ul className={`${styles.booklinks}`}> <li> <b>Ebook:</b> </li> <li> <a href="https://www.amazon.com/Key-West-Interlude-Lois-Richman-ebook/dp/B07QMP67HG/" target="_blank" rel="noopener noreferrer" > Amazon </a> </li> <li> <a href="https://www.barnesandnoble.com/w/key-west-interlude-lois-richman/1131275986?ean=9781643454658" target="_blank" rel="noopener noreferrer" > Barnes &amp; Noble </a> </li> </ul> <ul className={`${styles.booklinks}`}> <li> <b>Paperback:</b> </li> <li> <a href="https://www.amazon.com/Key-West-Interlude-Lois-Richman/dp/1643454633/" target="_blank" rel="noopener noreferrer" > Amazon </a> </li> <li> <a href="https://www.barnesandnoble.com/w/key-west-interlude-lois-richman/1131275986" target="_blank" rel="noopener noreferrer" > Barnes &amp; Noble </a> </li> <li> <a href="https://www.booksamillion.com/p/Key-West-Interlude/Lois-Richman/9781643454634" target="_blank" rel="noopener noreferrer" > Books-A-Million </a> </li> </ul> </div> </div> </div> </div> </Layout> ); }; export default Book;
1.460938
1
HIPCCyto/web/HIPCCyto/RemoveGSs.js
juyeongkim/LabKeyModules
5
15989956
/* removeGSs.js <NAME> 2019 Tool to remove outputs from create-gating set run - cytometry.gatingSetMetaData - cytometry.gatingSetInputFiles - flowWorkspace::save_gs() files Invoked by Remove GS button in cytometry_procressing.gatingSetMetaData Opens a new window displaying paths of deleted/not deleted HTML found in HIPCCyto/views */ function removeGSs(dataRegion) { // CHECK THAT FILES CAN BE REMOVED ------------------------------------------------------------- function canDelete(gsObj, filteredInputFiles) { var fileSystem = new LABKEY.FileSystem.WebdavFileSystem({ baseUrl: '/_webdav/Studies/' + gsObj['study'] + '/@files' + gsObj['path'] }); var folderRec = fileSystem.recordFromCache(''); var folder = fileSystem.canDelete(folderRec); if(folder) { rmRunRows(gsObj, filteredInputFiles); } else { notAllowedPaths.push(gsObj['path']); doneCheck.update(1); } } // REMOVE ROWS FROM GATING SET META DATA ------------------------------------------------------- function rmRunRows(gsObj, filteredInputFiles) { selRows.responseJSON.rows.forEach( function(rw) { if(gsObj['wsid'] == rw.wsid) { var path = containerPath != '/Studies' ? containerPath : containerPath + '/' + gsObj['study']; LABKEY.Query.deleteRows({ schemaName: schemaName, queryName: queryName, containerPath: path, rows: [{ 'key' : rw.key }], success: function(data) { rmInputRows(gsObj, filteredInputFiles); }, failure: function(errorInfo, options, responseObj) { notDeletedNames.push(gsObj['wsid']); doneCheck.update(1); } }); } }); } // REMOVE ROWS FROM GATING SET INPUT FILES ----------------------------------------------------- function rmInputRows(gsObj, filteredInputFiles) { var path = containerPath != '/Studies' ? containerPath : containerPath + '/' + gsObj['study']; LABKEY.Query.deleteRows({ schemaName: schemaName, queryName: 'gatingSetInputFiles', containerPath: path, rows: filteredInputFiles, success: function(data) { rmGSFiles(gsObj); }, failure: function(errorInfo, options, responseObj) { notDeletedNames.push(gsObj['wsid']); doneCheck.update(1); } }); } // REMOVE DIRECTORY W GATING SET OBJECT -------------------------------------------------------- function rmFiles(fileSystem, rmPath) { fileSystem.deletePath({ path: rmPath, isFile: false, // deleting the whole wsid directory success: function(fileSystem, path) { removedFiles.push(rmPath); doneCheck.update(3); }, failure: function(response, options) { notRemovedFiles.push(rmPath); doneCheck.update(3); }, scope: this }); } function rmGSFiles(gsObj) { var fileSystem = new LABKEY.FileSystem.WebdavFileSystem({ baseUrl:'/_webdav/Studies/' + gsObj['study'] + '/@files' }); rmFiles(fileSystem, gsObj['path']); // rm analysis/gating_set/<wsID> } // GO TO VIEW AFTER DELETE --------------------------------------------------------------------- function goToView() { if(doneCheck['count'] / 3 == selRows.responseJSON.rowCount) { window.location = LABKEY.ActionURL.buildURL( 'HIPCCyto', 'RemoveGSs.view', null, { notAllowed: notAllowedPaths, dbNotRemoved: notDeletedDb, rmFail: notRemovedFiles, rmSuccess: removedFiles, returnUrl: window.location }); } setTimeout(goToView, 1000) } // CHECK THAT ALL OUTPUT FROM WSID IS SELECTED ------------------------------------------------- // check to see that all gatingsets from wsids have been selected // return t/f function wsidCheck(data, allRows) { var selRowsWsids = data.rows.map(function(obj) { return obj.wsid; }); var allRowsFiltered = allRows.responseJSON.rows.filter(function(item) { return selRowsWsids.indexOf(item.wsid) !== 1; }); var check = allRowsFiltered.length === selRowsWsids.length; return(check); } function distinctWsids(data) { var selRowsWsids = data.rows.map(function(obj) { return obj.wsid; }); var filteredArray = selRowsWsids.filter(function(item, pos){ return selRowsWsids.indexOf(item)== pos; }); return filteredArray } // GLOBAL VARIABLES ---------------------------------------------------------------------------- // vars to populate var notDeletedNames = []; var notAllowedPaths = []; var notDeletedDb = []; var notRemovedFiles = []; var removedFiles = []; var doneCheck = { count: 0, update: function(num){ this['count'] = this['count'] + num; } } // vars pulled from labkeyURL var schemaName = LABKEY.ActionURL.getParameters()['schemaName'] // gatingSetMetaData var queryName = LABKEY.ActionURL.getParameters()['query.queryName'] // cytometry_processing var selectionKey = dataRegion.selectionKey; var containerPath = LABKEY.ActionURL.getContainer(); // /Studies/SDYXXX var study = LABKEY.ActionURL.getContainerName(); // queries var inputFiles = LABKEY.Query.selectRows({ schemaName: schemaName, queryName: 'gatingSetInputFiles', containerPath: containerPath, columns: ['container','file_info_name', 'wsid', 'key'] }); var allRows = LABKEY.Query.selectRows({ schemaName: schemaName, queryName: queryName, containerPath: containerPath, columns: ['gating_set', 'wsid', 'study', 'container', 'key'] }); // MAIN FUNCTION ------------------------------------------------------------------------------- // kicks off file check, file deletion, and row deletion // kicks off counter and opens new window function onSuccess(data) { var counter = 0; var check = wsidCheck(data, allRows); if(check) { var uniqueWsids = distinctWsids(data); uniqueWsids.forEach(function(rw) { var gsObj = {}; gsObj['wsid'] = rw; gsObj['study'] = study gsObj['path'] = 'analysis/gating_set/' + rw; // filter inputfiles by selected wsid var inputFilesArray = inputFiles.responseJSON.rows; var filteredInputFiles = inputFilesArray.filter(function(item) { return [ gsObj['wsid'] ].indexOf(item.wsid) !== -1; }); canDelete(gsObj, filteredInputFiles); counter++; if(counter === uniqueWsids.length) { goToView(); } }); } else { Ext.Msg.alert("Missing gatingsets. Please select all gating sets that correspond to selected workspace Ids"); } } // GET ROWS THAT HAVE BEEN SELECTED IN THE UI TO DELETE ----------------------------------------- var selRows = LABKEY.Query.selectRows({ schemaName: schemaName, queryName: queryName, containerPath: containerPath, showRows: 'selected', columns: ['gating_set', 'wsid', 'study', 'container', 'key'], selectionKey: selectionKey, success: onSuccess }); }
1.203125
1
src/model/story_type.js
ahmadassaf/Hacker-menu
1,117
15989964
export default class StoryType {} StoryType.TOP_TYPE = 'top' StoryType.SHOW_TYPE = 'show' StoryType.ASK_TYPE = 'ask' StoryType.ALL = [ StoryType.TOP_TYPE, StoryType.SHOW_TYPE, StoryType.ASK_TYPE ]
0.235352
0
newIDE/app/src/UI/EditorMosaic/EditorNavigator.js
psydox/GDevelop
2,990
15989972
// @flow import { Trans } from '@lingui/macro'; import * as React from 'react'; import { type Editor } from '.'; import { Column, Line } from '../Grid'; import FlatButton from '../FlatButton'; import ArrowBack from '@material-ui/icons/ArrowBack'; import Background from '../Background'; type Props = {| initialEditorName: string, editors: { [string]: Editor, }, transitions: { [string]: {| nextEditor?: string | (() => string), nextLabel?: React.Node, nextIcon?: React.Node, previousEditor?: string | (() => string), |}, }, onEditorChanged: (editorName: string) => void, |}; export type EditorNavigatorInterface = {| openEditor: (editorName: string) => void, |}; // Flow types might have to be changed/removed if upgrading Flow // (see example at https://github.com/wgao19/flow-notes/blob/master/react/react-memo.md) export default React.forwardRef<Props, EditorNavigatorInterface>( ( { initialEditorName, editors, transitions, onEditorChanged }: Props, ref ) => { const [currentEditorName, setCurrentEditorName] = React.useState( initialEditorName ); React.useImperativeHandle(ref, () => ({ openEditor: editorName => { setCurrentEditorName(editorName); }, })); React.useEffect( () => { onEditorChanged(currentEditorName); }, [currentEditorName, onEditorChanged] ); const transition = transitions[currentEditorName]; let buttonLineJustifyContent = 'space-between'; if (transition) { if (transition.previousEditor && !transition.nextEditor) { buttonLineJustifyContent = 'flex-start'; } if (!transition.previousEditor && transition.nextEditor) { buttonLineJustifyContent = 'flex-end'; } } return ( <Column noMargin expand> {transition && ( <Background maxWidth noExpand noFullHeight> <Column> <Line justifyContent={buttonLineJustifyContent}> {transition.previousEditor && ( <FlatButton label={<Trans>Back</Trans>} onClick={() => { if (transition.previousEditor) setCurrentEditorName(transition.previousEditor); }} icon={<ArrowBack />} /> )} {transition.nextLabel && transition.nextEditor && ( <FlatButton label={transition.nextLabel} onClick={() => { if (transition.nextEditor) setCurrentEditorName(transition.nextEditor); }} icon={transition.nextIcon} /> )} </Line> </Column> </Background> )} {editors[currentEditorName] ? editors[currentEditorName].renderEditor() : null} </Column> ); } );
1.585938
2
work/exampleIgFQ.js
stinsonga/geo-prime-workspace
0
15989980
function my_function972(){ //54129225158489365384934849721431FdqAGEUqDqKVidGbfiaVMQdwSQoybMRN } function my_function814(){ //36407145421410180206132159255245NVFaGIKjJDVkHtkxFGcULSmEuOGEUejT } function my_function431(){ //66342743293045747076853982951952xuJtjjdMQcYEQVwmBcwyFRAdNUBWmIWJ } function my_function014(){ //83139799174283866461768123115128PevghhwLmHUvfxDuMPMPmxtiUFqWghTX } function my_function545(){ //00912755607822109904278113171137rKKNPErftJyGIikLqthxXLHGrwMDDNWV } function my_function426(){ //32983686009514415566839303745097ZtxKhsGFJtRGVYPNSIQXIJFVXXoFcLGq } function my_function493(){ //16344466945714239484727220359215SDcQOAFxzKdIRqhuYEqsLvOHOCtZMCKf } function my_function349(){ //66752628999246925991365898109234eKqsoyphpWUBaVXYyFpDIzlGnIRKwBEp } function my_function868(){ //30505769381938690913917170593306jdwbJWRaWsgOUsBgRRMBAHbYXItXdLhB } function my_function331(){ //56361255663561159305854451980573HDaYkRMkurJpjLloFGMEBahgZyUzlYSl } function my_function716(){ //99649450642521070502813983823738ArTPxegPgNkweFTkuxSOdyLKhIsfpjPv } function my_function298(){ //37987769194071311223768511510040QuapbBRjugakPpmiRsyrqtPvwjpUpqos } function my_function572(){ //19437684338779553022503568506429pnEqjXdVMCZWjdSCgIidGjkjEKjQSNhU } function my_function620(){ //16479666413675283791686216637030HKEFPupnySpwmszFNbONGJeJCAwersvw } function my_function148(){ //74463589505838288136469069138887yLtfsADWYARbNKcWOSydQZdNidbdRDSD } function my_function921(){ //43424085049524636234873219324551wHIytnQcsxkZcMbzCSUXAkrPEKgDLtko } function my_function373(){ //48407228457616450356153370767890qceoEOWzHMrznAZHINKRruoUbZpMdOvT } function my_function840(){ //07744526621938432323962771868485hyiTrXVWrOtAwRIEqWurlhxAmpyYNcDZ } function my_function111(){ //76040976340346282480598938139529XhJkskawCWLWjRfidIjaIXRhFNkMMXUM } function my_function075(){ //13169882147419127788773032714136JbcJCDKfKsRNqRvophIPATxZkCDCKvhx } function my_function363(){ //92537072942726782161928749554934cAMvYDaItdCDQCqvpOjToAGLgvzVyImq } function my_function071(){ //46139419924765920940331670104197KCcYMtegTewEejaQFwWiWFxaonkKqWOj } function my_function163(){ //04667997733898081641316578450997PkzbAribrIAGEMXdtaslDGOLgWxfOkRw } function my_function586(){ //56911162097295648617945181826847qKZ<KEY> } function my_function345(){ //36510811539813631530359123403529rhHalWQRiAYeXEEHUdFrRxmaoSkWExVn } function my_function724(){ //03621583629773557765345548910461tYjUFdKfWdVQMDHevWPYFMHyGvqfvTYC } function my_function953(){ //76589169681392875560501479398771sRyjIAcCopzJJPCIJxqIHREoHeXiskem } function my_function548(){ //86343643784385221387951845866662GPKmtfQTbCPajYMhypXVCmyKseXojiAS } function my_function850(){ //65527490794408532217100187414071MsIyIKtKftjneRglaRUYCwjwaMveZLGh } function my_function649(){ //93002219146259096401563847600897kXTLvsqfiUXjeLGdGlXqsaqIsrDNMJqH } function my_function737(){ //89320101930476031514314386521824eHwImaVfrxpozCsHljJwKgJGjXgwdcGe } function my_function554(){ //36417292923307073348240099817936IYPaWgOjpLkdOBxywbHPFqOuVpWfLpUW } function my_function782(){ //61042668112838775464292017290239ZksoNoQgQLASKizbsrlvVrnMUfvPuNSp } function my_function500(){ //74355364843536438683328177653872hwUYAYknyKGTVaedcUoDnqHoFhGOMBHR } function my_function386(){ //75670562611991247320250753737910BnbgrpHEeRGWOTchrprOovKEVFBqmvlQ } function my_function640(){ //67676900213909880559297916616670pAmxuAsdNQdDtiqvXwapPGDzCAsrtPua } function my_function267(){ //43127131481533462166818152897219JgScTcdYuISpEeKlHdddyjEBlJdBtmTe } function my_function391(){ //93657856536910974096961083362651XfhHolCHLSBqHBmrpCjKNmhlbSaJipIz } function my_function900(){ //56335208096280484380104986808059MUDfHAEFiJZqpxkZiFCfkdkgcWbDWbnG } function my_function892(){ //91597906694608377109386712318553DLROjrrjJvlJEFoTYFnLCgJaEokWfpeE } function my_function094(){ //38506169513766632905161879540591SUBDOXIthxliYkuLSygLCuToZgaIfXrp } function my_function288(){ //96379690811107798815902109723011KAItZIDeoJIdqxbaKQTKYhgClCvQvlTI } function my_function066(){ //44160346236774799725447150272294JJtmvlvoGKCVLkZmeGrjxIwPQWOrSucH } function my_function220(){ //85428097375423761351075694977518baDcelujAgxuFGSlYYEBDVDwNHBqsAlE } function my_function509(){ //93862376299380542283740717179320dlAFvMYKYvqWbnUcMbUpRIusfqQIqkwy } function my_function138(){ //31983695853529000285988177575558zVYFnWKPcfOiWSqoCpXEdmmPONvcACUJ } function my_function118(){ //04932309327789134712794238854530ECyLSGkKJAxPXnIrFDwbGOqtyxEkMcHk } function my_function473(){ //66673855371890221466268700835080SHuXaPZyNQKdHkVnGNzppbiDAXdwbyrg } function my_function968(){ //08751134918091612281746732174016XclHtsYAUppCeUjySBeZNdExXkBEnwch } function my_function248(){ //47983543089264440165826985187405nGTTJLfgIDuSLkQukKspVUkwUyYAYAWJ } function my_function901(){ //69004196298962036513624240488266cerqcRFsBDyNKAXdisEWZBgSizscqnoi }
0.585938
1
src/containers/page.js
lauravuo/react-project-template
0
15989988
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import User from '../components/user'; const Page = ({ user }) => ( <div> {user && <User name={user.name} location={user.location} />} <div>{CONFIG.setting}</div> </div> ); Page.propTypes = { user: PropTypes.object, }; Page.defaultProps = { user: null, }; const mapStateWithProps = ({ user }) => ({ user, }); export default connect(mapStateWithProps)(Page);
1.085938
1
src/constants/messages_en.js
Endsion/react-en
0
15989996
export default { // when 404,500 error got ['ERROR_MSG']: 'Request Error', // no operation permission ['NO_PERMISSION']: 'No Permission', };
0.324219
0
src/cmds/kick.js
OhSkilouxe/B0T
1
15990004
const Discord = require('discord.js'); /** * @param {Discord.Client} client * @param {Discord.Message} message * @param {string[]} args */ exports.run = (client, message, args) => { let member = (message.guild.member(message.mentions.users.first() || message.guild.members.cache.get(args[0]))); if(!member) return message.reply(':x: | Please enter a valid member.') const reason = args.join(' ').slice(args[0].length + 1) if(!reason) return message.reply(':x: | Please supply a reason.') message.guild.member(member).kick(reason).then(() => { message.channel.send(`**${member.user.username}** was kicked. | **Reason : ${reason}** !`); }); } exports.infos = { permission: 'KICK_MEMBERS', permissionDelete: false, permissionSilent: false }
1.648438
2
script.js
geotecdev/YouTube-Movie-Search
1
15990012
const API_key = '<KEY>'; const url = 'https://api.themoviedb.org/3/search/movie?api_key=<KEY>' const imgUrl = 'https://image.tmdb.org/t/p/w500' //select elements from the DOM let buttonEl = document.querySelector('#search') let inputEl = document.querySelector('#inputValue') let moviesSearchable = document.querySelector('#movies-searchable') // created a function that loops through our movie path and returns the Image function movieSection(movies) { return movies.map((movie) => { if (movie.poster_path) { return `<img src=${imgUrl + movie.poster_path} data-movie-id=${movie.id}/>` } }) } function createMovieContainer(movies) { const movieEl = document.createElement('div') movieEl.setAttribute('class', 'movie') const movieTemplate = ` <section class="section"> ${movieSection(movies)} </section> <div class="content"> <p id="content-close"> x </p> </div> </div>` movieEl.innerHTML = movieTemplate; return movieEl } function renderSearhableMovies(data) { moviesSearchable.innerHTML = '' const movies = data.results; const movieBlock = createMovieContainer(movies) // create an html element to dumb our value in moviesSearchable.appendChild(movieBlock); console.log('Data :', data); } buttonEl.onclick = function (event) { event.preventDefault(); const value = inputEl.value; let newUrl = url + '&query=' + value; fetch(newUrl) .then((res) => res.json()) .then(renderSearhableMovies) .catch((error) => { console.log('Error :', error); }) inputEl.value = '' console.log('value :', value); }
2.21875
2
index.js
thedeex/deexdex
2
15990020
"use strict"; module.exports = require("./deex").default;
0.203125
0
src/components/index/indexConsole/commands/fetchCommands/Track/Delete.js
TBS093A/music-service-frontend
0
15990028
import React, { useState, useEffect } from 'react' import { connect } from 'react-redux' import { deleteTrack } from '../../../../../../stores/track/duck/operations' import { AbstractDelete } from '../Abstract Utils/AbstractDelete' import { FormGenerator } from '../Abstract Utils/FormGenerator' import { ResetComponent } from '../Abstract Utils/ResetComponent' const TrackDelete = ({ user, deleteTrack, consoleHistory, setConsoleHistory, componentVisible, setComponentVisible, activateConsoleInput }) => { const [message, setMessage] = useState('') const idInput = React.createRef() let refList = [ idInput ] let inputList = [ { type: 'info', action: 'Delete', endpoint: 'Track' }, { type: 'text', name: 'id', ref: idInput } ] const deleteFetch = (event) => { AbstractDelete( refList, consoleHistory, setConsoleHistory, setMessage, deleteTrack, user.token ) } const resetState = () => { setConsoleHistory( consoleHistory + message ) setComponentVisible( false ) setMessage('') } return ( <div> <FormGenerator inputList={ inputList } refList={ refList } action={ deleteFetch } /> <ResetComponent resetState={ resetState } refList={ refList } message={ message } componentVisible={ componentVisible } activateConsoleInput={ activateConsoleInput } /> </div> ) } const mapStateToProps = state => ({ user: state.user }) const mapDispatchToProps = dispatch => ({ deleteTrack: (id, token) => deleteTrack(id, token) }) export default connect(mapStateToProps, mapDispatchToProps)(TrackDelete)
1.796875
2
src/store/index.js
chenweilong1022/back-front
0
15990036
import Vue from 'vue' import Vuex from 'vuex' import app from './modules/app' import permission from './modules/permission' import user from './modules/user' import manager from './modules/manager' import role from './modules/role' import menu from './modules/menu' import game from './modules/game' import player from './modules/player' import platform from './modules/platform' import robotManager from './modules/robotManager' import spread from './modules/spread' import agent from './modules/agent' import activity from './modules/activity' import getters from './getters' Vue.use(Vuex) const store = new Vuex.Store({ modules: { app, permission, user, manager, role, menu, robotManager, game, player, platform, spread, agent, activity }, getters }) export default store
0.988281
1
frontend/src/_tests_/NearbyVenue.test.js
QA-AKAM/QACinema-Project
1
15990044
import NearbyVenue from "../Components/Information/Nearby/NearbyVenue"; import { create } from 'react-test-renderer'; import VenueCote from '../Images/venue_cote.jpg'; describe(`NearbyVenue component testing with props`, () => { const nearbyVenueData = { img: VenueCote, title: "Cote - St Katherine's Docks", description: "Modern, all-day French brasserie chain, serving regional specialities and traditional classics. Choose any cooked breakfast or light main, a fresh juice or a hot drink, and a glass of sparkling Baron de Marck Champagne. Available at all of our brasseries.", address: "International House, 1 St Katharine's Way, London E1W 1UN", telephone: "+442074883668", offers: [ "Free lunch for children", "Dinner 2 for 1 as a couple", "Double for single price" ], nav: "https://www.google.co.uk/maps/place/Cote+-+St+Katherine's+Docks/@51.5082267,-0.0755847,17z/data=!4m5!3m4!1s0x48760348e2c50419:0x548a54f8679423f4!8m2!3d51.5082086!4d-0.0737684" }; let testComponent; beforeEach(() => { const TestInstance = create(<NearbyVenue cardData={nearbyVenueData} />); testComponent = TestInstance.root; }); it(`Should match the snapshot`, () => { const element = create(<NearbyVenue cardData={nearbyVenueData} />).toJSON(); expect(element).toMatchSnapshot(); }) it(`Should render card-title which contains the name of the venue`, () => { // const cardTitle = testComponent.findByType('Card.Title'); // expect(cardTitle.children).toEqual([nearbyVenueData.title]); expect(true).toEqual(true); }); });
1.515625
2
ruoyi-ui/src/api/maintenance/server/server.js
aisc521/RuoYi-Cloud
0
15990052
import request from '@/utils/request' // 查询服务器管理列表 export function listServer(query) { return request({ url: '/maintenance/server/list', method: 'get', params: query }) } // 查询服务器管理详细 export function getServer(serverId) { return request({ url: '/maintenance/server/' + serverId, method: 'get' }) } // 新增服务器管理 export function addServer(data) { return request({ url: '/maintenance/server', method: 'post', data: data }) } // 修改服务器管理 export function updateServer(data) { return request({ url: '/maintenance/server', method: 'put', data: data }) } // 删除服务器管理 export function delServer(serverId) { return request({ url: '/maintenance/server/' + serverId, method: 'delete' }) } // 导出服务器管理 export function exportServer(query) { return request({ url: '/maintenance/server/export', method: 'get', params: query }) } export function testServerConnect(data) { return request({ url: '/maintenance/server/testConnect', method: 'post', data }) }
0.929688
1
src/components/auth/Credentials.js
team-anchor/CitySecrets
0
15990060
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import FormControl from '../shared/FormControl'; import styles from './Auth.css'; class Credentials extends PureComponent { state = { name: '', email: '', password: '' }; static propTypes = { submit: PropTypes.func.isRequired, action: PropTypes.string.isRequired, allowName: PropTypes.bool }; handleChange = ({ target }) => { this.setState({ [target.name]: target.value }); }; handleSubmit = event => { event.preventDefault(); this.props.submit(this.state); }; render() { const { action, allowName = false } = this.props; const { name, email, password } = this.state; return ( <div className={styles.auth}> <section className="login-form"> <form onSubmit={this.handleSubmit}> {allowName && <FormControl label="name"> <input name="name" value={name} onChange={this.handleChange}/> </FormControl> } <FormControl label="email"> <input name="email" value={email} onChange={this.handleChange}/> </FormControl> <FormControl label="password"> <input name="password" type="password" value={password} onChange={this.handleChange}/> </FormControl> <button>{action}</button> </form> </section> </div> ); } } export default Credentials;
1.648438
2
unicom/test/mongodb.js
NextZeus/beyond-webapp
0
15990068
var _ = require('underscore'); var async = require('async'); var crypto = require('crypto'); var mongoose = require('mongoose'); var ObjectID = require('mongodb').ObjectID; var config = { db: require('../config/db') }; //import the models var models = { PlatformFeature: require('../models/PlatformFeature')(mongoose), PlatformRole: require('../models/PlatformRole')(mongoose), ChannelCategory: require('../models/ChannelCategory')(mongoose), ChannelDepartment: require('../models/ChannelDepartment')(mongoose), ChannelGrid: require('../models/ChannelGrid')(mongoose), ProductCard: require('../models/ProductCard')(mongoose), OrderCard: require('../models/OrderCard')(mongoose), WoRevenue: require('../models/WoRevenue')(mongoose), }; mongoose.connect(config.db.URI,function onMongooseError(err){ if(err) { console.error('Error: can not open Mongodb.'); throw err; } }); /** * 准备数据 * */ var dropCollections = function(done) { async.series( [ function(callback) { models.PlatformFeature.remove(callback); }, function(callback) { models.PlatformRole.remove(callback); }, function(callback) { models.ChannelCategory.remove(callback); }, function(callback) { models.ChannelDepartment.remove(callback); }, function(callback) { models.ChannelGrid.remove(callback); }, function(callback) { models.ChannelGrid.remove(callback); }, function(callback) { models.ProductCard.remove(callback); }, function(callback) { models.OrderCard.remove(callback); }, function(callback) { models.WoRevenue.remove(callback); }, ], function(err, result) { if (err) return done(err); done(null, result); } ); }; /** * * create PlatformFeatures * */ var upsertPlatformFeatures = function(done) { var features = require('./fixtures/platform.feature'); async.eachSeries(features, function(feature, callback) { models.PlatformFeature.create(feature, function(err) { if (err) return callback(err); callback(null); }); }, done); }; /** * * create PlatformRoles * */ var upsertPlatformRoles = function(done) { var roles = require('./fixtures/platform.role'); async.eachSeries(roles, function(role, callback) { models.PlatformRole.create(role, function(err) { if (err) return callback(err); callback(null); }); }, done); }; /** * * create ChannelCategories * */ var upsertChannelCategories = function(done) { var categories = require('./fixtures/channel.category'); async.eachSeries(categories, function(category, callback) { models.ChannelCategory.create(category, function(err) { if (err) return callback(err); callback(null); }); }, done); }; /** * * create ChannelDepartments * */ var upsertChannelDepartments = function(done) { var departments = require('./fixtures/channel.department'); async.eachSeries(departments, function(department, callback) { models.ChannelDepartment.create(department, function(err) { if (err) return callback(err); callback(null); }); }, done); }; /** * * create ChannelGrids * */ var upsertChannelGrids = function(done) { var grids = require('./fixtures/channel.grid'); async.eachSeries(grids, function(grid, callback) { models.ChannelGrid.create(grid, function(err) { if (err) return callback(err); callback(null); }); }, done); }; /** * * create ProductCards * */ var upsertProductCards = function(done) { var cards = require('./fixtures/product.card'); async.eachSeries(cards, function(card, callback) { models.ProductCard.create(card, function(err) { if (err) return callback(err); callback(null); }); }, done); }; /** * * create OrderCards * */ var upsertOrderCards = function(done) { var orders = require('./fixtures/order.card'); async.eachSeries(orders, function(order, callback) { models.OrderCard.create(order, function(err) { if (err) return callback(err); callback(null); }); }, done); }; /** * * create WoRevenues * */ var upsertWoRevenues = function(done) { var revenues = require('./fixtures/wo.revenue'); async.eachSeries(revenues, function(revenue, callback) { models.WoRevenue.create(revenue, function(err) { if (err) return callback(err); callback(null); }); }, done); }; /** * process workflow * */ async.series( [ dropCollections, upsertPlatformFeatures, upsertPlatformRoles, upsertChannelCategories, upsertChannelDepartments, upsertChannelGrids, upsertProductCards, upsertOrderCards, upsertWoRevenues, ], function(err, result) { if (err) console.log(err); mongoose.disconnect(); } );
1.40625
1
balances/src/routes/balances.js
EliseevNP/nodetest
0
15990076
const constraints = require('../constraints'); const Router = require('koa-router'); const models = require('../models'); const validateMiddleware = require('../middlewares/validate'); const router = new Router(); router.get('/:id', (ctx, next) => { ctx.paramsConstraints = { id: constraints.id }; return next(); }, validateMiddleware, async (ctx) => { try { ctx.body = await models.Balance.findOne({ id: ctx.params.id }, {balance: 1, _id: 0}).exec(); ctx.status = 200; } catch (err) { console.log(`[SERVER][GET /balances/:id] ${err}`); ctx.status = 500; } } ); module.exports = router.routes();
1.3125
1
app/assets/javascripts/diffs/utils/performance.js
Testiduk/gitlabhq
11,467
15990084
import { performanceMarkAndMeasure } from '~/performance/utils'; import { MR_DIFFS_MARK_FILE_TREE_START, MR_DIFFS_MARK_FILE_TREE_END, MR_DIFFS_MARK_DIFF_FILES_START, MR_DIFFS_MARK_FIRST_DIFF_FILE_SHOWN, MR_DIFFS_MARK_DIFF_FILES_END, MR_DIFFS_MEASURE_FILE_TREE_DONE, MR_DIFFS_MEASURE_DIFF_FILES_DONE, } from '../../performance/constants'; import { EVT_PERF_MARK_FILE_TREE_START, EVT_PERF_MARK_FILE_TREE_END, EVT_PERF_MARK_DIFF_FILES_START, EVT_PERF_MARK_FIRST_DIFF_FILE_SHOWN, EVT_PERF_MARK_DIFF_FILES_END, } from '../constants'; import eventHub from '../event_hub'; function treeStart() { performanceMarkAndMeasure({ mark: MR_DIFFS_MARK_FILE_TREE_START, }); } function treeEnd() { performanceMarkAndMeasure({ mark: MR_DIFFS_MARK_FILE_TREE_END, measures: [ { name: MR_DIFFS_MEASURE_FILE_TREE_DONE, start: MR_DIFFS_MARK_FILE_TREE_START, end: MR_DIFFS_MARK_FILE_TREE_END, }, ], }); } function filesStart() { performanceMarkAndMeasure({ mark: MR_DIFFS_MARK_DIFF_FILES_START, }); } function filesEnd() { performanceMarkAndMeasure({ mark: MR_DIFFS_MARK_DIFF_FILES_END, measures: [ { name: MR_DIFFS_MEASURE_DIFF_FILES_DONE, start: MR_DIFFS_MARK_DIFF_FILES_START, end: MR_DIFFS_MARK_DIFF_FILES_END, }, ], }); } function firstFile() { performanceMarkAndMeasure({ mark: MR_DIFFS_MARK_FIRST_DIFF_FILE_SHOWN, }); } export const diffsApp = { instrument() { eventHub.$on(EVT_PERF_MARK_FILE_TREE_START, treeStart); eventHub.$on(EVT_PERF_MARK_FILE_TREE_END, treeEnd); eventHub.$on(EVT_PERF_MARK_DIFF_FILES_START, filesStart); eventHub.$on(EVT_PERF_MARK_DIFF_FILES_END, filesEnd); eventHub.$on(EVT_PERF_MARK_FIRST_DIFF_FILE_SHOWN, firstFile); }, deinstrument() { eventHub.$off(EVT_PERF_MARK_FIRST_DIFF_FILE_SHOWN, firstFile); eventHub.$off(EVT_PERF_MARK_DIFF_FILES_END, filesEnd); eventHub.$off(EVT_PERF_MARK_DIFF_FILES_START, filesStart); eventHub.$off(EVT_PERF_MARK_FILE_TREE_END, treeEnd); eventHub.$off(EVT_PERF_MARK_FILE_TREE_START, treeStart); }, };
0.957031
1
frontend/src/entity/fabric_pattern.js
daniortega9607/textiles-hernandez
0
15990092
import SearchBoxList from "../components/Form/SearchBoxList"; export const FabricPattern = { name: 'FabricPattern', display_name: 'Modelos', display_single_name: 'Modelo', url: 'fabric_patterns', field_configurations: { form: [ { key: 'sku', render_type: 'text', attributes: { placeholder: 'Ejemplo: Brush-1234' } }, { key: 'fabric_id', render_type: 'custom', attributes: { required: true }, renderer: SearchBoxList, props: { entity:'Fabric' } }, { key: 'design_id', render_type: 'custom', renderer: SearchBoxList, props: { entity:'Design' } }, { key: 'color_id', render_type: 'custom', renderer: SearchBoxList, props: { entity:'Color' } }, ], list: { order: ['id', 'sku', 'fabric.name', 'design.name', 'color.name'], fields: {} } }, fields: { id: { type: Number, is_primary: true, auto_generated: true, display_name: 'ID' }, sku: { type: String, display_name: 'Código' }, fabric: { type: Object, entity:'Fabric' }, fabric_id: { type: Number, display_name: 'Tela' }, color: { type: Object, entity:'Fabric' }, color_id: { type: Number, display_name: 'Color' }, design: { type: Object, entity:'Fabric' }, design_id: { type: Number, display_name: 'Diseño' }, } } export default FabricPattern;
1.03125
1
exercicio04/script.js
Joaopedromdes/JavaScript_CV
0
15990100
function gerar(){ var num = window.document.getElementById('txtnum') var n = Number(num.value) if(num.value.length == 0){ alert('Por favor informe um número') }else{ var res = window.document.getElementById('seltab') var c = 1 res.innerHTML = '' //Isso é para limpar a tabuada antes de começar, assim ela n se repetirá while(c <= 10){ var item = document.createElement('option') //Para criar elementos de HTML dento de JS var mult = n * c item.text = `${n} X ${c} = ${mult}` item.value = `tab${c}` res.appendChild(item) //Adicionar elemento filho c++ } } }
2.09375
2
src/directives/index.js
LondonOktober/bootstrap-vue
10
15990108
import { pluginFactory } from '../utils/plugins' import { VBModalPlugin } from './modal' import { VBPopoverPlugin } from './popover' import { VBScrollspyPlugin } from './scrollspy' import { VBTogglePlugin } from './toggle' import { VBTooltipPlugin } from './tooltip' // Main plugin for installing all directive plugins export const directivesPlugin = /*#__PURE__*/ pluginFactory({ plugins: { VBModalPlugin, VBPopoverPlugin, VBScrollspyPlugin, VBTogglePlugin, VBTooltipPlugin } })
0.558594
1
src/Components/Recognition.js
WisTiCeJEnT/RevCode
3
15990116
window.SpeechRecognition = window.webkitSpeechRecognition || window.SpeechRecognition; let recognition = new window.SpeechRecognition(); recognition.lang = "en-US"; recognition.lang = "th-TH"; recognition.interimResults = true; recognition.maxAlternatives = 10; recognition.continuous = true; export default recognition
0.570313
1
node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/collection/SeqViewLike$$anon$13.js
ignaciocases/hermeneumatics
0
15990124
/** @constructor */ ScalaJS.c.scala_collection_SeqViewLike$$anon$13 = (function() { ScalaJS.c.scala_collection_SeqViewLike$AbstractTransformed.call(this); this.fst$2 = null; this.$$outer$2 = null }); ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype = new ScalaJS.inheritable.scala_collection_SeqViewLike$AbstractTransformed(); ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype.constructor = ScalaJS.c.scala_collection_SeqViewLike$$anon$13; ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype.iterator__Lscala_collection_Iterator = (function() { return ScalaJS.impls.scala_collection_GenSeqViewLike$Prepended$class__iterator__Lscala_collection_GenSeqViewLike$Prepended__Lscala_collection_Iterator(this) }); ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype.length__I = (function() { return ScalaJS.impls.scala_collection_GenSeqViewLike$Prepended$class__length__Lscala_collection_GenSeqViewLike$Prepended__I(this) }); ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype.apply__I__O = (function(idx) { return ScalaJS.impls.scala_collection_GenSeqViewLike$Prepended$class__apply__Lscala_collection_GenSeqViewLike$Prepended__I__O(this, idx) }); ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype.viewIdentifier__T = (function() { return ScalaJS.impls.scala_collection_GenSeqViewLike$Prepended$class__viewIdentifier__Lscala_collection_GenSeqViewLike$Prepended__T(this) }); ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype.fst__O = (function() { return this.fst$2 }); ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype.scala$collection$GenSeqViewLike$Prepended$$$outer__Lscala_collection_GenSeqViewLike = (function() { return this.$$outer$2 }); ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype.apply__O__O = (function(v1) { return this.apply__I__O(ScalaJS.uI(v1)) }); ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype.init___Lscala_collection_SeqViewLike__O = (function($$outer, elem$1) { if (($$outer === null)) { throw new ScalaJS.c.java_lang_NullPointerException().init___() } else { this.$$outer$2 = $$outer }; var fst = elem$1; this.fst$2 = fst; ScalaJS.c.scala_collection_SeqViewLike$AbstractTransformed.prototype.init___Lscala_collection_SeqViewLike.call(this, $$outer); ScalaJS.impls.scala_collection_GenSeqViewLike$Prepended$class__$init$__Lscala_collection_GenSeqViewLike$Prepended__V(this); return this }); ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype.scala$collection$GenSeqViewLike$Prepended$$$outer__ = (function() { return this.scala$collection$GenSeqViewLike$Prepended$$$outer__Lscala_collection_GenSeqViewLike() }); ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype.fst__ = (function() { return this.fst__O() }); /** @constructor */ ScalaJS.inheritable.scala_collection_SeqViewLike$$anon$13 = (function() { /*<skip>*/ }); ScalaJS.inheritable.scala_collection_SeqViewLike$$anon$13.prototype = ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype; ScalaJS.is.scala_collection_SeqViewLike$$anon$13 = (function(obj) { return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_collection_SeqViewLike$$anon$13))) }); ScalaJS.as.scala_collection_SeqViewLike$$anon$13 = (function(obj) { if ((ScalaJS.is.scala_collection_SeqViewLike$$anon$13(obj) || (obj === null))) { return obj } else { ScalaJS.throwClassCastException(obj, "scala.collection.SeqViewLike$$anon$13") } }); ScalaJS.isArrayOf.scala_collection_SeqViewLike$$anon$13 = (function(obj, depth) { return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_collection_SeqViewLike$$anon$13))) }); ScalaJS.asArrayOf.scala_collection_SeqViewLike$$anon$13 = (function(obj, depth) { if ((ScalaJS.isArrayOf.scala_collection_SeqViewLike$$anon$13(obj, depth) || (obj === null))) { return obj } else { ScalaJS.throwArrayCastException(obj, "Lscala.collection.SeqViewLike$$anon$13;", depth) } }); ScalaJS.data.scala_collection_SeqViewLike$$anon$13 = new ScalaJS.ClassTypeData({ scala_collection_SeqViewLike$$anon$13: 0 }, false, "scala.collection.SeqViewLike$$anon$13", ScalaJS.data.scala_collection_SeqViewLike$AbstractTransformed, { scala_collection_SeqViewLike$$anon$13: 1, scala_collection_SeqViewLike$Prepended: 1, scala_collection_GenSeqViewLike$Prepended: 1, scala_collection_SeqViewLike$AbstractTransformed: 1, scala_collection_SeqViewLike$Transformed: 1, scala_collection_GenSeqViewLike$Transformed: 1, scala_collection_SeqView: 1, scala_collection_GenSeqView: 1, scala_collection_SeqViewLike: 1, scala_collection_GenSeqViewLike: 1, scala_collection_IterableViewLike$Transformed: 1, scala_collection_GenIterableViewLike$Transformed: 1, scala_collection_TraversableViewLike$Transformed: 1, scala_collection_GenTraversableViewLike$Transformed: 1, scala_collection_IterableView: 1, scala_collection_GenIterableView: 1, scala_collection_IterableViewLike: 1, scala_collection_GenIterableViewLike: 1, scala_collection_TraversableView: 1, scala_collection_GenTraversableView: 1, scala_collection_TraversableViewLike: 1, scala_collection_GenTraversableViewLike: 1, scala_collection_ViewMkString: 1, scala_collection_Seq: 1, scala_collection_SeqLike: 1, scala_collection_GenSeq: 1, scala_collection_GenSeqLike: 1, scala_collection_Iterable: 1, scala_collection_IterableLike: 1, scala_Equals: 1, scala_collection_GenIterable: 1, scala_collection_GenIterableLike: 1, scala_collection_Traversable: 1, scala_collection_GenTraversable: 1, scala_collection_generic_GenericTraversableTemplate: 1, scala_collection_TraversableLike: 1, scala_collection_GenTraversableLike: 1, scala_collection_Parallelizable: 1, scala_collection_TraversableOnce: 1, scala_collection_GenTraversableOnce: 1, scala_collection_generic_FilterMonadic: 1, scala_collection_generic_HasNewBuilder: 1, scala_PartialFunction: 1, scala_Function1: 1, java_lang_Object: 1 }); ScalaJS.c.scala_collection_SeqViewLike$$anon$13.prototype.$classData = ScalaJS.data.scala_collection_SeqViewLike$$anon$13; //@ sourceMappingURL=SeqViewLike$$anon$13.js.map
1.453125
1
src/pages/self-assessment/covid-exposure.js
Dithn/covid-19-self-assessment
0
15990132
import React from "react" import QuestionTemplate from "../../templates/yes-no-question-template" import { logic } from "../../shared" const CovidExposure = () => ( <QuestionTemplate lang="en" yesLink={logic.q8.yes} noLink={logic.q8.no}> <h2> In the last 14 days, have you been in close physical contact with someone who tested positive for COVID-19?{" "} </h2> <p>Close physical contact means:</p> <ul> <li>a face-to-face conversation for 15 minutes</li> <li>being in the same room for 2 hours</li> <li>living in the same home</li> <li>working in the same workplace</li> </ul> </QuestionTemplate> ) export default CovidExposure
1.15625
1
public/CaseOne/ext/classic/theme-material/overrides/tree/View.js
Muratbatirov/Case1
0
15990140
Ext.define('Ext.theme.material.tree.View', { override: 'Ext.tree.View', config: { color: 'default' } });
0.667969
1
node_modules/expres/test/type.js
carolinem15/mvcburger
3
15990148
describe('type', function(){ beforeEach(createServer); afterEach(closeServer); describe('.type(str)', function(){ it('should set the Content-Type with type/subtype', function(done){ respond(function(req, res){ res.type('application/vnd.amazon.ebook') .send('var name = "tj";'); }); request() .get('/') .expect('Content-Type', 'application/vnd.amazon.ebook', done); }); }); });
1.398438
1
server/db/couchdb/bundles.js
lnceballosz/inventaire
0
15990156
const couch_ = require('lib/couch') const assert_ = require('lib/utils/assert_types') module.exports = (db, _) => { const actionAndReturn = (verb, doc) => { assert_.object(doc) return db[verb](doc) .then(updateIdAndRev.bind(null, doc)) } const bulkDelete = async docs => { assert_.objects(docs) if (docs.length === 0) return [] _.warn(docs, `${db.dbName} bulkDelete`) return db.bulk(couch_.setDocsDeletedTrue(docs)) } return { byIds: async ids => { ids = _.forceArray(ids) const { docs } = await db.fetch(ids) return docs }, postAndReturn: actionAndReturn.bind(null, 'post'), putAndReturn: actionAndReturn.bind(null, 'put'), bulkDelete } } const updateIdAndRev = (doc, couchRes) => { if (!doc._id) doc._id = couchRes.id doc._rev = couchRes.rev return doc }
1.3125
1
docs/.vitepress/config.js
BradPatras/rose-pine-theme
2
15990164
module.exports = { title: "Rosé Pine", description: "All natural pine, faux fur and a bit of soho vibes for the classy minimalist", themeConfig: { nav: [ { text: "Themes", link: "/themes" }, { text: "Palette", link: "/palette" }, { text: "Contributing", link: "/contributing" }, { text: "Twitter", link: "https://twitter.com/rosepinetheme" }, { text: "GitHub", link: "https://github.com/rose-pine/rose-pine-theme" }, ], }, };
0.347656
0
1_funciones/cmp/e1-funciones-return.js
gilpgpoojs/gilpgpoojs.github.io
0
15990172
import { Diapositiva } from "../../lib/Diapositiva.js"; import "../../lib/muestra-codigo.js"; export class E1FuncionesReturn extends Diapositiva { /** @override */ connectedCallback() { super.connectedCallback(); this.innerHTML = /* html */ `<h1>E. Funciones con valor de regreso</h1> <div class="horizontal"> <div> <h2>Salida</h2> <iframe src="/1_funciones/src/5_funciones_return.html"></iframe> <p class="noPrint"> <a target="_blank" href="/1_funciones/src/5_funciones_return.html">Ábrelo en otra pestaña.</a> </p> <p class="noPrint"> <a target="_blank" href="https://gilpgedit.github.io/#%3Cscript%3E%0A%20debugger%3B%0A%20const%20x%20%3D%20fna(8%2C%205)%3B%0A%20document.write(fna(4%2C%201)%2C%20%22%3Cbr%3E%22)%3B%0A%20document.write(x%2C%20%22%3Cbr%3E%22)%3B%0A%20function%20fna(t%2C%20bc)%20%7B%0A%20%20document.%0A%20%20%20write(t%20%2B%20bc%20*%202%2C%20%22%3Cbr%3E%22)%3B%0A%20%20return%201%20%2B%20t%20*%208%3B%0A%20%7D%0A%3C%2Fscript%3E"> Revísalo en gilpgedit. </a> </p> </div> <muestra-codigo> <div> <div><span style="color: #800000;">&lt;script&gt;</span></div> <div>&nbsp;<span style="color: #0000ff;">debugger</span>;</div> <div>&nbsp;<span style="color: #0000ff;">const</span>&nbsp;<span style="color: #0070c1;">x</span>&nbsp;=&nbsp;<span style="color: #795e26;">fna</span>(<span style="color: #098658;">8</span>,&nbsp;<span style="color: #098658;">5</span>);</div> <div>&nbsp;<span style="color: #001080;">document</span>.<span style="color: #795e26;">write</span>(<span style="color: #795e26;">fna</span>(<span style="color: #098658;">4</span>,&nbsp;<span style="color: #098658;">1</span>),&nbsp;<span style="color: #a31515;">"&lt;br&gt;"</span>);</div> <div>&nbsp;<span style="color: #001080;">document</span>.<span style="color: #795e26;">write</span>(<span style="color: #0070c1;">x</span>,&nbsp;<span style="color: #a31515;">"&lt;br&gt;"</span>);</div> <div>&nbsp;<span style="color: #0000ff;">function</span>&nbsp;<span style="color: #795e26;">fna</span>(<span style="color: #001080;">t</span>,&nbsp;<span style="color: #001080;">bc</span>)&nbsp;{</div> <div>&nbsp;&nbsp;<span style="color: #001080;">document</span>.</div> <div>&nbsp;&nbsp;&nbsp;<span style="color: #795e26;">write</span>(<span style="color: #001080;">t</span>&nbsp;+&nbsp;<span style="color: #001080;">bc</span>&nbsp;*&nbsp;<span style="color: #098658;">2</span>,&nbsp;<span style="color: #a31515;">"&lt;br&gt;"</span>);</div> <div>&nbsp;&nbsp;<span style="color: #af00db;">return</span>&nbsp;(<span style="color: #098658;">1</span>&nbsp;+&nbsp;<span style="color: #001080;">t</span>&nbsp;*&nbsp;<span style="color: #098658;">8</span>);</div> <div>&nbsp;}</div> <div><span style="color: #800000;">&lt;/script&gt;</span></div> </div> </muestra-codigo> </div> <div class="lectura"> <p> La palabra reservada <code class="language-javascript">return</code> y el paréntesis que le sigue, <strong>siempre</strong> deben ir en el mismo renglón. </p> </div> </muestra-codigo> </div>`; } } customElements.define("e1-funciones-return", E1FuncionesReturn);
1.4375
1
hackernews/frontend-react/src/components/LinkList.js
philippe-heitzmann/python-apps
13
15990180
import React from 'react'; import Link from './Link'; import { useQuery, gql } from '@apollo/client'; const FEED_QUERY = gql` { feed { id links { id createdAt url description } } } `; const LinkList = () => { const { data } = useQuery(FEED_QUERY); return ( <div> {data && ( <> {data.feed.links.map((link) => ( <Link key={link.id} link={link} /> ))} </> )} </div> ); }; export default LinkList;
1.117188
1
pages/index/index.js
dengbaoling/wuzhoushop
208
15990188
/* 承载页 */ var app = getApp() var bearer = require('../../utils/bearer.js'); var util = require('../../utils/util.js'); var ports = require('../../utils/ports.js'); Page({ onLoad: function () { bearer.init(); } })
0.753906
1
src/utils/backEndTableUtils/tableSortingUtils.js
marvelperseus/Real-Estate-website-frontend
1
15990196
import moment from 'moment'; export const compareDate = (a, b) => { let Date1; let Date2; if (typeof a === 'string') { Date1 = a; } else { Date1 = a; } if (typeof b === 'string') { Date2 = b; } else { Date2 = b; } if (Date1 === Date2) return 0; if (moment(Date1).isBefore(Date2)) return -1; return 1; }; export const compareNumber = (a, b) => { let Num1; let Num2; if (typeof a === 'string') { Num1 = a.startsWith('$') ? Number(a.substring(1).replace(/,/g, '')) : Number(a.replace(/,/g, '')); } else { Num1 = a; } if (typeof b === 'string') { Num2 = b.startsWith('$') ? Number(b.substring(1).replace(/,/g, '')) : Number(b.replace(/,/g, '')); } else { Num2 = b; } if (Num1 === Num2) return 0; if (Num1 > Num2) return 1; return -1; };
1.546875
2
src/v2/view-builder/views/consent/EnduserConsentViewFooter.js
cluesblues/okta-signin-widget
0
15990204
import { View } from 'okta'; import hbs from 'handlebars-inline-precompile'; const ConsentViewFooter = View.extend({ className: 'consent-footer', template: hbs( '\ {{#if termsOfService}}\ <a class="terms-of-service" href="{{termsOfService}}" target="_blank">\ {{i18n code="consent.required.termsOfService" bundle="login"}}\ </a>\ {{#if privacyPolicy}}\ &#8226\ {{/if}}\ {{/if}}\ {{#if privacyPolicy}}\ <a class="privacy-policy" href="{{privacyPolicy}}" target="_blank">\ {{i18n code="consent.required.privacyPolicy" bundle="login"}}\ </a>\ {{/if}}\ ' ), getTemplateData: function() { const appState = this.options.appState; const app = appState.get('app'); return { termsOfService: app.termsOfService && app.termsOfService.href, privacyPolicy: app.privacyPolicy && app.privacyPolicy.href, }; }, }); export default ConsentViewFooter;
0.910156
1
test/msg.js
charleyw/react-weui
3,064
15990212
import React from 'react'; import { shallow } from 'enzyme'; import assert from 'assert'; import WeUI from '../src/index'; const {Msg, Icon, Button, Footer} = WeUI; describe('<Msg></Msg>', ()=> { const type = 'success'; const title = '成功'; const description = '感谢你的反馈'; const buttons = [{ type: 'primary', label: '确定', onClick: ()=>{ console.log('ok'); } }]; const TestFooter = () => <Footer />; it('should have footer for 0.4.x method', ()=> { const $warningWrapper = shallow( <Msg extraHref="test" extraText="label" /> ) assert($warningWrapper.find(Footer).shallow().hasClass('weui-footer')); //assert(spy.calledOnce()); }); ['success', 'info', 'waiting', 'warn'].map((type) => { describe(`<msg type="${type}"></msg>`, ()=> { const wrapper = shallow( <Msg type={type} title={title} description={description} buttons={buttons} footer={TestFooter} /> ); it('should render <Msg></Msg> component', ()=> { assert(wrapper.instance() instanceof Msg); assert(wrapper.hasClass('weui-msg')); }); it(`should have <Icon value="${type}"></Icon>`, ()=> { const $icon = wrapper.find(Icon).shallow(); assert($icon.instance() instanceof Icon); assert($icon.hasClass(`weui-icon-${type}`)); }); it(`should have title ${title}`, ()=> { const $title = wrapper.find('.weui-msg__title'); assert($title.text() === title); }); it(`should have description ${description}`, ()=> { const $desc = wrapper.find('.weui-msg__desc'); assert($desc.text() === description); }); it(`should render ${buttons.length} buttons`, ()=> { const $buttons = wrapper.find(Button).shallow(); assert($buttons.length === buttons.length); $buttons.map(($button, index) => { assert($button.text() === buttons[index].label); assert($button.prop('onClick') === buttons[index].onClick); assert($button.hasClass(`weui-btn_${buttons[index].type}`)); }); }); it('should have <Footer>', ()=> { const $footer = wrapper.find(Footer).shallow(); assert($footer.hasClass('weui-footer')); }); }); }); });
1.5625
2
src/Screen/Place.js
yliu138/wedding-invitation
0
15990220
import React from 'react'; import { Row, Col, } from 'reactstrap'; import { Map } from '../Component'; export default function Place(props) { const { name, latitude, longitude, } = props.config.wedding.place; return ( <Row> <Col> <Row className="pt-3"> <Col> <h3>{name}</h3> </Col> </Row> <Row className="pt-3"> <Col> <Map config={props.config.wedding.place} /> </Col> </Row> </Col> </Row> ); }
1.101563
1
src/components/Icon/Green.js
GiftEquation/giftequation
1
15990228
import React from 'react'; const SvgGreen = props => ( <svg width={18} height={20} {...props}> <g fill={props.color} fillRule="evenodd"> <path d="M6.1 7.697a2.421 2.421 0 0 0-.241-3.416C4.849 3.405.617 2.936.617 2.936s.85 3.943 2.069 5.001a2.421 2.421 0 0 0 3.414-.24M10 9.07c0-.322.102-.694.285-1.074a3.516 3.516 0 0 0 4.431-.498c1.355-1.39 2.386-7.494 2.386-7.494s-5.79.908-7.426 2.587a3.512 3.512 0 0 0-.741 3.758C8.305 7.27 8 8.245 8 9.07V12h2V9.07zM14.674 13H3.325a.998.998 0 0 0-.96 1.275l1.428 5a.998.998 0 0 0 .961.725h8.491a1 1 0 0 0 .962-.725l1.428-5a.997.997 0 0 0-.96-1.275" /> </g> </svg> ); export default SvgGreen;
1.023438
1
HttpTrigger1/node_modules/@pnp/office365-cli/dist/o365/yammer/commands/message/message-add.js
VelinGeorgiev/azure-function-office365-cli-powershell
0
15990236
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const commands_1 = require("../../commands"); const YammerCommand_1 = require("../../../base/YammerCommand"); const request_1 = require("../../../../request"); const vorpal = require('../../../../vorpal-init'); class YammerMessageAddCommand extends YammerCommand_1.default { get name() { return commands_1.default.YAMMER_MESSAGE_ADD; } get description() { return 'Posts a Yammer network message on behalf of the current user'; } getTelemetryProperties(args) { const telemetryProps = super.getTelemetryProperties(args); telemetryProps.repliedToId = args.options.repliedToId !== undefined; telemetryProps.directToUserIds = args.options.directToUserIds !== undefined; telemetryProps.groupId = args.options.groupId !== undefined; telemetryProps.networkId = args.options.networkId !== undefined; return telemetryProps; } commandAction(cmd, args, cb) { const requestOptions = { url: `${this.resource}/v1/messages.json`, headers: { accept: 'application/json;odata.metadata=none', 'content-type': 'application/json;odata=nometadata' }, json: true, body: { body: args.options.body, replied_to_id: args.options.repliedToId, direct_to_user_ids: args.options.directToUserIds, group_id: args.options.groupId, network_id: args.options.networkId } }; request_1.default .post(requestOptions) .then((res) => { let result = null; if (res.messages && res.messages.length == 1) { result = res.messages[0]; } if (args.options.output === 'json') { cmd.log(result); } else { cmd.log({ id: result.id }); } cb(); }, (err) => this.handleRejectedODataJsonPromise(err, cmd, cb)); } options() { const options = [ { option: '-b, --body <body>', description: 'The text of the message body' }, { option: '-r, --repliedToId [repliedToId]', description: 'The message ID this message is in reply to. If this is set then groupId and networkId are inferred from it' }, { option: '-d, --directToUserIds [directToUserIds]', description: 'Send a private message to one or more users, specified by ID. Alternatively, you can use the Yammer network e-mail addresses instead of the IDs' }, { option: '--groupId [groupId]', description: 'Post the message to this group, specified by ID. If this is set then the networkId is inferred from it. A post without directToUserIds, repliedToId or groupId will default to All Company group' }, { option: '--networkId [networkId]', description: 'Post a message in the "All Company" feed of this network, if repliedToId, directToUserIds and groupId are all omitted' } ]; const parentOptions = super.options(); return options.concat(parentOptions); } validate() { return (args) => { if (!args.options.body) { return 'Required body value is missing'; } if (args.options.groupId && typeof args.options.groupId !== 'number') { return `${args.options.groupId} is not a number`; } if (args.options.networkId && typeof args.options.networkId !== 'number') { return `${args.options.networkId} is not a number`; } if (args.options.repliedToId && typeof args.options.repliedToId !== 'number') { return `${args.options.repliedToId} is not a number`; } return true; }; } commandHelp(args, log) { const chalk = vorpal.chalk; log(vorpal.find(this.name).helpInformation()); log(` Remarks: ${chalk.yellow('Attention:')} In order to use this command, you need to grant the Azure AD application used by the Office 365 CLI the permission to the Yammer API. To do this, execute the ${chalk.blue('consent --service yammer')} command. Examples: Posts a message to the "All Company" feed ${this.name} --body "Hello everyone!" Replies to a message with the ID 1231231231 ${this.name} --body "Hello everyone!" --repliedToId 1231231231 Sends a private conversation to the user with the ID 1231231231 ${this.name} --body "Hello everyone!" --directToUserIds 1231231231 Sends a private conversation to multiple users by ID ${this.name} --body "Hello everyone!" --directToUserIds "1231231231,1121312" Sends a private conversation to the user with the e-mail <EMAIL> and <EMAIL> ${this.name} --body "Hello everyone!" --directToUserIds "<EMAIL>,<EMAIL>" Posts a message to the group with the ID 12312312312 ${this.name} --body "Hello everyone!" --groupId 12312312312 Posts a message to the "All Company" feed of the network 11112312 ${this.name} --body "Hello everyone!" --networkId 11112312 `); } } module.exports = new YammerMessageAddCommand(); //# sourceMappingURL=message-add.js.map
1.367188
1
speech_1_00.js
lovroselic/GhostRun2
0
15990244
//////////////////speech.js///////////////////////// // // // SPEECH version 1.00 by LS // // // //////////////////////////////////////////////////// /* TODO: */ //////////////////////////////////////////////////// var SPEECH = { VERSION: "1.00", CSS: "color: #0A0", interval: 20, browserSupport: true, voices: null, voice: null, settings: null, wait: function () { if (!SPEECH.browserSupport) return; if (SPEECH.ready) { return; } else { console.log(`%cwaiting for voices to load ....`, "color: #0A0"); setTimeout(SPEECH.wait, SPEECH.inteval); } }, init: function () { if (!("speechSynthesis" in window)) { SPEECH.browserSupport = false; console.log( `%cInitializing SPEECH failed. Browser not supported!`, "color: #F00" ); return; } let ready = Promise.all([SPEECH.getVoices()]).then(function () { SPEECH.ready = true; console.log(`%cSPEECH ${SPEECH.VERSION}: ready`, SPEECH.CSS); SPEECH.voice = SPEECH.voices[0]; }); let def = new VoiceSetting(1, 1, 1); SPEECH.settings = def; SPEECH.wait(); }, speak: function (txt) { if (!SPEECH.ready){ console.log(`%cSPEECH not ready ....`, "color: #A00"); return; } let msg = new SpeechSynthesisUtterance(); msg.text = txt; msg.pitch = SPEECH.settings.pitch; msg.rate = SPEECH.settings.pitch; msg.volume = SPEECH.settings.pitch; msg.voice = SPEECH.voice; //console.log("saying msg", msg); speechSynthesis.speak(msg); }, getVoices: function () { if (navigator.userAgent.includes("Firefox")) { console.log(`%cInitializing SPEECH - Firefox`, SPEECH.CSS); return new Promise((resolve) => { let voices; voices = speechSynthesis.getVoices(); SPEECH.voices = voices; resolve(voices); }); } else if (navigator.userAgent.includes("Chrome")) { console.log(`%cInitializing SPEECH - Chrome`, SPEECH.CSS); return new Promise((resolve) => { let voices; speechSynthesis.onvoiceschanged = function () { voices = speechSynthesis.getVoices(); SPEECH.voices = voices; resolve(voices); }; }); } else { SPEECH.browserSupport = false; console.log( `%cInitializing SPEECH failed. Browser not supported!`, "color: #F00" ); } }, ready: false }; class VoiceSetting { constructor(rate, pitch, volume) { this.rate = rate; this.pitch = pitch; this.volume = volume; } } console.log(`%cSPEECH ${SPEECH.VERSION} loaded.`, SPEECH.CSS);
1.390625
1
docs/mvc/store.js
rondinif/phytojs
3
15990252
import {remove} from './helpers.js' export default Store /** * Creates a new client side storage object and will create an empty * collection if no collection already exists. * * @param {string} name The name of our DB we want to use * @param {function} callback Our fake DB uses callbacks because in * real life you probably would be making AJAX calls */ function Store(name, callback) { callback = callback || function() { } this._dbName = name if (!localStorage[name]) { var data = { plants: [] } localStorage[name] = JSON.stringify(data) } callback.call(this, JSON.parse(localStorage[name])) this.subscribers = [] } Store.prototype.subscribe = function(subscriber) { this.subscribers.push(subscriber) return () => remove(this.subscribers, subscriber) } Store.prototype._notify = function() { this.subscribers.forEach(s => s()) } /** * Finds items based on a query given as a JS object * * @param {object} query The query to match against (i.e. {foo: 'bar'}) * @param {function} callback The callback to fire when the query has * completed running * * @example * db.find({foo: 'bar', hello: 'world'}, function (data) { * // data will return any items that have foo: bar and * // hello: world in their properties * }); */ Store.prototype.find = function(query, callback) { if (!callback) { return } var plants = JSON.parse(localStorage[this._dbName]).plants callback.call(this, plants.filter(function(plant) { for (var q in query) { if (query[q] !== plant[q]) { return false } } return true })) } /** * Will retrieve all data from the collection * * @param {function} callback The callback to fire upon retrieving data */ Store.prototype.findAll = function(callback) { callback = callback || function() { } callback.call(this, JSON.parse(localStorage[this._dbName]).plants) } /** * Will save the given data to the DB. If no item exists it will create a new * item, otherwise it'll simply update an existing item's properties * * @param {object} updateData The data to save back into the DB * @param {function} callback The callback to fire after saving * @param {number} id An optional param to enter an ID of an item to update */ Store.prototype.save = function(updateData, callback, id) { var data = JSON.parse(localStorage[this._dbName]) var plants = data.plants callback = callback || function() { } // If an ID was actually given, find the item and update each property if (id) { console.log(`store.save: <b0s1> updateData:${JSON.stringify(updateData)}`) for (var i = 0; i < plants.length; i++) { if (plants[i].id === id) { for (var key in updateData) { // eslint-disable-line guard-for-in plants[i][key] = updateData[key] } break } } localStorage[this._dbName] = JSON.stringify(data) callback.call(this, JSON.parse(localStorage[this._dbName]).plants) } else { // updateData is the data received from `model.createPlant` (a plant + an id and a completed flag) console.log(`store.save: <b1s1> updateData:${JSON.stringify(updateData)}`) // DO NOT Generate an ID - it was received from model // updateData.id = updateData.entityId // new Date().getTime() console.log(`store.save: <b1s2> updateData:${JSON.stringify(updateData)}`) if ((updateData.plant.image) === undefined) { updateData.completed = true } let isPlantAlreadyStored = false for (var i = 0; i < plants.length; i++) { if (plants[i].id === updateData.id) { isPlantAlreadyStored = true plants[i].completed = false break } } if ( isPlantAlreadyStored ) { console.log(`store.save: <b1s4> already stored:${updateData.id})`) } else { plants.push(updateData) console.log(`store.save: <b1s3> plants:${JSON.stringify(plants)}`) console.log(`store.save: <b1s3> data:${JSON.stringify(data)}`) } localStorage[this._dbName] = JSON.stringify(data) callback.call(this, [updateData]) } this._notify() } /** * Will remove an item from the Store based on its ID * * @param {number} id The ID of the item you want to remove * @param {function} callback The callback to fire after saving */ Store.prototype.remove = function(id, callback) { var data = JSON.parse(localStorage[this._dbName]) var plants = data.plants for (var i = 0; i < plants.length; i++) { if (plants[i].id === id) { plants.splice(i, 1) break } } localStorage[this._dbName] = JSON.stringify(data) callback.call(this, JSON.parse(localStorage[this._dbName]).plants) this._notify() } /** * Will drop all storage and start fresh * * @param {function} callback The callback to fire after dropping the data */ Store.prototype.drop = function(callback) { localStorage[this._dbName] = JSON.stringify({plants: []}) callback.call(this, JSON.parse(localStorage[this._dbName]).plants) this._notify() }
2.375
2
js-test-suite/testsuite/38a79becbf8db806fea643474785c86a.js
hao-wang/Montage
16
15990260
load("fcfbc86708bc3a4062c2091a062e13b6.js"); load("bcb77b03ed13784489484535627fca54.js"); /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/licenses/publicdomain/ */ // Very simple initial test that the "length" property of a function is // configurable. More thorough tests follow. var f = function (a1, a2, a3, a4) {}; assertEq(delete f.length, true); assertEq(f.hasOwnProperty("length"), false); assertEq(f.length, 0); // inherited from Function.prototype.length assertEq(delete Function.prototype.length, true); assertEq(f.length, undefined); // Now for the details. // // Many of these tests are poking at the "resolve hook" mechanism SM uses to // lazily create this property, which is wonky and deserving of some extra // skepticism. // We've deleted Function.prototype.length. Check that the resolve hook does // not resurrect it. assertEq("length" in Function.prototype, false); Function.prototype.length = 7; assertEq(Function.prototype.length, 7); delete Function.prototype.length; assertEq(Function.prototype.length, undefined); // OK, define Function.prototype.length back to its original state per spec, so // the remaining tests can run in a more typical environment. Object.defineProperty(Function.prototype, "length", {value: 0, configurable: true}); // Check the property descriptor of a function length property. var g = function f(a1, a2, a3, a4, a5) {}; var desc = Object.getOwnPropertyDescriptor(g, "length"); assertEq(desc.configurable, true); assertEq(desc.enumerable, false); assertEq(desc.writable, false); assertEq(desc.value, 5); // After deleting the length property, assigning to f.length fails because // Function.prototype.length is non-writable. In strict mode it would throw. delete g.length; g.length = 12; assertEq(g.hasOwnProperty("length"), false); assertEq(g.length, 0); // After deleting both the length property and Function.prototype.length, // assigning to f.length creates a new plain old data property. delete Function.prototype.length; g.length = 13; var desc = Object.getOwnPropertyDescriptor(g, "length"); assertEq(desc.configurable, true); assertEq(desc.enumerable, true); assertEq(desc.writable, true); assertEq(desc.value, 13); // Deleting the .length of one instance of a FunctionDeclaration does not // affect other instances. function mkfun() { function fun(a1, a2, a3, a4, a5) {} return fun; } g = mkfun(); var h = mkfun(); delete h.length; assertEq(g.length, 5); assertEq(mkfun().length, 5); // Object.defineProperty on a brand-new function is sufficient to cause the // LENGTH_RESOLVED flag to be set. g = mkfun(); Object.defineProperty(g, "length", {value: 0}); assertEq(delete g.length, true); assertEq(g.hasOwnProperty("length"), false); // Object.defineProperty on a brand-new function correctly merges new // attributes with the builtin ones. g = mkfun(); Object.defineProperty(g, "length", { value: 42 }); desc = Object.getOwnPropertyDescriptor(g, "length"); assertEq(desc.configurable, true); assertEq(desc.enumerable, false); assertEq(desc.writable, false); assertEq(desc.value, 42); reportCompare(0, 0, 'ok');
1.992188
2
node_modules/@0x/subproviders/lib/src/utils/wallet_utils.js
lohba/chainlink
2
15990268
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.walletUtils = void 0; const ethUtil = require("ethereumjs-util"); const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000; class DerivedHDKeyInfoIterator { constructor(initialDerivedKey, searchLimit = DEFAULT_ADDRESS_SEARCH_LIMIT) { this._searchLimit = searchLimit; this._parentDerivedKeyInfo = initialDerivedKey; this._index = 0; } next() { const baseDerivationPath = this._parentDerivedKeyInfo.baseDerivationPath; const derivationIndex = this._index; const fullDerivationPath = `m/${baseDerivationPath}/${derivationIndex}`; const path = `m/${derivationIndex}`; const hdKey = this._parentDerivedKeyInfo.hdKey.derive(path); const address = exports.walletUtils.addressOfHDKey(hdKey); const derivedKey = { address, hdKey, baseDerivationPath, derivationPath: fullDerivationPath, }; const isDone = this._index === this._searchLimit; this._index++; return { done: isDone, value: derivedKey, }; } [Symbol.iterator]() { return this; } } exports.walletUtils = { calculateDerivedHDKeyInfos(parentDerivedKeyInfo, numberOfKeys) { const derivedKeys = []; const derivedKeyIterator = new DerivedHDKeyInfoIterator(parentDerivedKeyInfo, numberOfKeys); for (const key of derivedKeyIterator) { derivedKeys.push(key); } return derivedKeys; }, findDerivedKeyInfoForAddressIfExists(address, parentDerivedKeyInfo, searchLimit) { const lowercaseAddress = address.toLowerCase(); let matchedKey; const derivedKeyIterator = new DerivedHDKeyInfoIterator(parentDerivedKeyInfo, searchLimit); for (const key of derivedKeyIterator) { if (key.address === lowercaseAddress) { matchedKey = key; break; } } return matchedKey; }, addressOfHDKey(hdKey) { const shouldSanitizePublicKey = true; const derivedPublicKey = hdKey.publicKey; const ethereumAddressUnprefixed = ethUtil .publicToAddress(derivedPublicKey, shouldSanitizePublicKey) .toString('hex'); const address = ethUtil.addHexPrefix(ethereumAddressUnprefixed).toLowerCase(); return address; }, }; //# sourceMappingURL=wallet_utils.js.map
1.585938
2
app/assets/javascripts/views/components/Editor/EditableComponent.js
TwoStoryRobot/fv-web-ui
0
15990276
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import provide from 'react-redux-provide'; import selectn from 'selectn'; import t from 'tcomb-form'; import DOMPurify from 'dompurify'; import Preview from 'views/components/Editor/Preview'; import StatusBar from 'views/components/StatusBar'; // Models import {Document} from 'nuxeo'; // Schemas import fields from 'models/schemas/fields'; import options from 'models/schemas/options'; import IconButton from '@material-ui/core/IconButton'; import EditIcon from '@material-ui/icons/Edit'; import CircularProgress from '@material-ui/core/CircularProgress'; import IntlService from "views/services/intl"; const intl = IntlService.instance; const RenderRegular = function (currentValue, preview, previewType, returnWrapper = 'span') { let output = []; let values = []; if (!Array.isArray(currentValue)) { values[0] = currentValue; } else { values = currentValue; } output = values.map(function (value, i) { let id = (value && value.hasOwnProperty('uid') ? value.uid : value); return (preview) ? <Preview key={i} id={id} type={previewType}/> : React.createElement(returnWrapper, { key: i, dangerouslySetInnerHTML: {__html: DOMPurify.sanitize(value)} }); }); return output; } @provide export default class EditableComponent extends Component { static propTypes = { computeEntity: PropTypes.object.isRequired, updateEntity: PropTypes.func.isRequired, property: PropTypes.string.isRequired, sectionProperty: PropTypes.string, context: PropTypes.object, className: PropTypes.string, options: PropTypes.array, accessDenied: PropTypes.bool, showPreview: PropTypes.bool, previewType: PropTypes.string }; static defaultProps = { accessDenied: false, className: '', showPreview: false }; constructor(props, context) { super(props, context); this.state = { editModeEnabled: false, savedValue: null }; // Bind methods to 'this' ['_onEditRequest', '_onRequestSaveField'].forEach((method => this[method] = this[method].bind(this))); } /** * Allows an element to be rendered as regular text or as an editable form, derived from a larger type (e.g. fv-portal:about from FVPortal type) * Note: This will only work with 'properties' from the document as they are the only mutable fields. * @param {property} string - The property field id (used for Structs) * @param {entity} doc - The entitiy to derive current values from, Nuxeo doc object * @returns - Element to be rendered */ _editableElement() { const {property} = this.props; let entity = selectn('response', this.props.computeEntity); // If still computing, return spinner if (entity.isFetching) return <CircularProgress style={{ color: "#b40000" }} variant="indeterminate" size={119}/>; // Get current value for field from properties let currentValue = selectn(property, this.state.savedValue) || selectn("properties." + property, entity); // Get all options for type from entity field definition let fieldFormOptions = selectn(entity.type, options); // Handle edit mode if (this.state.editModeEnabled && !this.props.accessDenied) { let fieldFormValues = {}; let fieldFormStruct, fieldFormFields = null; // Get all fields for type from entity field definition fieldFormFields = selectn(entity.type, fields); // If fields and options found, try to create form our of field if (fieldFormFields && fieldFormOptions) { // If extended options enabled if (this.props.options && this.props.options.length > 0) { fieldFormOptions.fields[property].options = this.props.options; } // Create a sub-structure for this field let newFieldFormSchema = {}; // Set field to be new schema (note: selectn doesn't work with functions defined in maps) newFieldFormSchema[property] = fieldFormFields[property]; if (newFieldFormSchema) { // Create a new sub-structure for schema fieldFormStruct = t.struct(newFieldFormSchema); // Set default value to current value fieldFormValues[property] = currentValue; return <form className="editableComponentForm" onSubmit={e => this._onRequestSaveField(e, property)}> <t.form.Form ref={"form_" + property} value={fieldFormValues} type={fieldFormStruct} context={selectn('response', this.props.context) || selectn('response', this.props.computeEntity)} options={fieldFormOptions}/> <button type="submit" className="btn btn-primary">{intl.trans('save', 'Save', 'first')}</button> </form>; } } } // Render regular field if not in edit mode return <div> {RenderRegular(currentValue, this.props.showPreview, this.props.previewType)} <IconButton style={{ verticalAlign: '-4px', margin: '0 5px 0 -5px', padding: '0px 5px', height: '22px', width: '22px', display: (this.props.accessDenied) ? 'none' : 'inline-block' }} onClick={this._onEditRequest.bind(this, property)} tooltip={intl.trans('edit', 'Edit', 'first')}><EditIcon /></IconButton> </div>; } shouldComponentUpdate(newProps, newState) { if (newState != this.state || newProps.computeEntity.response != this.props.computeEntity.response) return true; if (newProps.options != null) return true; return false; } _onRequestSaveField(e, property) { // Prevent default behaviour e.preventDefault(); // TODO: Find better way to construct object then accessing internal function // Create new document rather than modifying the original document let newDocument = new Document(this.props.computeEntity.response, { 'repository': this.props.computeEntity.response._repository, 'nuxeo': this.props.computeEntity.response._nuxeo }); let formValue = this.refs["form_" + property].getValue(); // Set new value property on document newDocument.set(formValue); // Save document this.props.updateEntity(newDocument, null, '\'' + selectn('props.options.fields' + '.' + property + '.label', this.refs["form_" + property]) + '\' updated successfully!'); this.setState({ editModeEnabled: false, savedValue: formValue }); } _onEditRequest(fieldToEdit) { this.setState({ editModeEnabled: true }); } render() { return (<div className={this.props.className}>{this._editableElement()} <StatusBar message={selectn('message', this.props.computeEntity)}/></div>); }; } export class EditableComponentHelper extends Component { render() { if (this.props.isSection) { return <div>{RenderRegular(selectn(this.props.sectionProperty || 'properties.' + this.props.property, this.props.entity), this.props.showPreview, this.props.previewType, 'div')}</div>; } return <EditableComponent {...this.props} />; } }
1.523438
2
src/Snackbar/provideSnackbar.test.js
i-obraztsov/rambler-ui
203
15990284
import React, {Component} from 'react' import Snackbar from './Snackbar' import provideSnackbar from './provideSnackbar' import {withTheme, mount} from '../../test/utils' const WithSnackbar = provideSnackbar( class extends Component { static displayName = 'WithSnackbar' render() { return <div className="wrapped">Hi</div> } } ) describe('provideSnackbar()', () => { let containerNode const mountWrapper = () => mount(withTheme(<WithSnackbar />)) const mountSnackbar = props => { const wrapper = mountWrapper() const {openSnackbar, closeSnackbar} = wrapper.find('WithSnackbar').props() let onOpen let onClose const whenOpen = new Promise(resolve => { onOpen = resolve }) const whenClose = new Promise(resolve => { onClose = resolve }) const snackbar = openSnackbar( <Snackbar className="snackbar" containerRef={ref => { containerNode = ref if (ref) onOpen() else onClose() }} {...props}> Hi </Snackbar> ) return { snackbar, closeSnackbar, whenOpen, whenClose } } beforeEach(() => { containerNode = undefined }) it('should append wrapped component', () => { const wrapper = mountWrapper() const wrappedNode = wrapper.find('.wrapped') expect(wrappedNode.text()).toEqual('Hi') }) it('should open/close snackbar when call props.{openSnackbar,closeSnackbar}', async done => { expect(containerNode).toBeUndefined() const {snackbar, closeSnackbar, whenOpen, whenClose} = mountSnackbar() await whenOpen expect(document.body.lastElementChild).toEqual(containerNode) expect(document.body.lastElementChild.childElementCount).toEqual(1) closeSnackbar(snackbar) await whenClose expect(containerNode).toBeUndefined() done() }) it('should close snackbar when call snackbar.close', async done => { const {snackbar, whenOpen, whenClose} = mountSnackbar() await whenOpen expect(document.body.lastElementChild).toEqual(containerNode) expect(document.body.lastElementChild.childElementCount).toEqual(1) snackbar.close() await whenClose expect(containerNode).toBeUndefined() done() }) it('should close snackbar when click on close button', async done => { const {whenOpen, whenClose} = mountSnackbar({ showClose: true }) await whenOpen expect(document.body.lastElementChild).toEqual(containerNode) expect(document.body.lastElementChild.childElementCount).toEqual(1) containerNode.querySelector('.snackbar button').click() await whenClose expect(containerNode).toBeUndefined() done() }) it('should close snackbar when click on action button', async done => { const {snackbar, whenOpen, whenClose} = mountSnackbar({ actionButton: 'Ok', onAction: () => { snackbar.close() } }) await whenOpen expect(document.body.lastElementChild).toEqual(containerNode) expect(document.body.lastElementChild.childElementCount).toEqual(1) containerNode.querySelector('.snackbar button').click() await whenClose expect(containerNode).toBeUndefined() done() }) })
1.523438
2
gulpfile.js
JavascriptFTW/KA-Contest-Judging-System
6
15990292
var gulp = require("gulp"); var sass = require("gulp-sass"); var jshint = require("gulp-jshint"); var browserSync = require("browser-sync").create(); var browserify = require("browserify"); var babelify = require("babelify"); var source = require('vinyl-source-stream'); var buildDir = "./build"; browserSync.init({ server: { baseDir: "./" } }); gulp.task("styles", function() { gulp.src("sass/**/*.scss") .pipe(sass().on("error", sass.logError)) .pipe(gulp.dest(buildDir + "/css/")); }); function transpileScripts(filePath) { browserify(filePath, {debug: true}) .transform(babelify) .bundle() .pipe(source(filePath)) .pipe(gulp.dest(buildDir)); } gulp.task("jshint", function() { return gulp.src("src/**/*.js") .pipe(jshint()) .pipe(jshint.reporter("default")); }); gulp.task("default", function() { var scripts = gulp.watch("src/**/*.js", ["jshint"]).on("change", browserSync.reload); scripts.on("change", function(evt) { transpileScripts(evt.path); }); gulp.watch("sass/**/*.scss", ["styles"]).on("change", browserSync.reload); gulp.watch("./**/*.html").on("change", browserSync.reload); });
1.15625
1
joyFromDance_website/old_src/src/components/login/login-view.js
RadoslawOsinski/JoyFromDance
0
15990300
import {html} from '@polymer/lit-element'; import {PageViewElement} from './../page-view-element.js'; import {MDCRipple} from '@material/ripple'; import {SharedStyles} from './../shared-styles.js'; class ContactView extends PageViewElement { _render(props) { console.log('render!'); return html` ${SharedStyles} <section> <h2>Contact</h2> <!--<p>Contact informations</p>--> <paper-contact-list style="width: 300px;"> <paper-contact-email><EMAIL></paper-contact-email> <paper-contact-email><a target="_blank" href="/pgp/[email protected]">GPG <EMAIL></a></paper-contact-email> <paper-contact-email><a target="_blank" href="/pgp/<EMAIL>.asc">GPG <EMAIL></a></paper-contact-email> <paper-contact-mobile>+48 791-101-335</paper-contact-mobile> <paper-contact-address latitude="51.5287718" longitude="-0.2416798">06-430 Sońsk, ul Ogrodowa 6, Poland</paper-contact-address> <paper-contact-address latitude="51.5287718" longitude="-0.2416798">Plus Code: 9G42QMGX+6C</paper-contact-address> </paper-contact-list> </section> <button class="mdc-button" id="bbbc"> Button </button> <section> <h2>Issues & features</h2> <p>Issues and features requests can be created at: <a href="https://gitlab.com/OsinskiRadoslaw/JoyFromDance/issues" target="_blank">Reporting</a></p> </section> `; } constructor() { super(); this.language = 'en'; this.resources = { 'en': { 'contact': 'Contact' }, 'pl': { 'contact': 'Kontakt' } }; console.log('const'); // new MDCRipple(document.querySelector('mdc-button')) } ready() { super.ready(); console.log('ready'); console.log(this); console.log(this.shadowRoot.querySelector('#bbbc')); try { const z = new MDCRipple(this.shadowRoot.querySelector('#bbbc')); console.log('zzz: ' + z); } catch (e) { console.log(e) } } } window.customElements.define('contact-view', ContactView);
1.234375
1
web/digital.js
jubilly/Turn-on-and-variant-brightness-of-a-led
0
15990308
$(document).ready(function() { $("#button").click(function() { var a = $("#quantidade").val(); var numero = parseInt(a); for (var b = 0; b < numero; b++) { // $('#secundaria').append("<button id = button " + b + "> Entrada " + b + "</button> <button id = button2 " + b + "> Saída " + b + "</button></br></br>"); // $('#secundaria').append(" <button id='lampada'" + " data-state='' " + '>' + "Led 01 </button>"); $('#secundaria').append('<button id="lampada" data-state="off" alt="off" > Led 01 </button>'); } }); });
1.390625
1
brain/logic/hub.js
Nakasar/bot-architecture-poc
1
15990316
'use strict'; const path = require('path'); /** * Handle an intent. Find the related skill and call it. * @param {String} intentName The name of the intent (slug given by nlp service provider). * @param {Object} [entities={}] - Entities returned by the nlp service provider (if any). * @param {Object} [data={}] - Data sent by the connector to the brain. * @return {Promise} Promise object represents the answer of the skill (message to send back to connector, optional data...) */ function handleIntent(intentName, entities = {}, data = {}) { return new Promise((resolve, reject) => { console.log(`> [INFO] Handling intent "\x1b[4m${intentName}\x1b[0m"`); if (SkillManager.intents.has(intentName) && SkillManager.intents.get(intentName).active) { let intent = SkillManager.intents.get(intentName); for (let entity of intent.expected_entities) { if (!Object.keys(entities).includes(entity)) { return resolve({ success: false, message: { text: `I understand the intent is ${intentName}, but I'm missing some entities. I expect : ${intent.expected_entities.join(", ")}.` }}); } } intent.handle({ entities, data }).then((response) => { return resolve({ success: true, message: response.message }); }).catch((err) => { return reject(err); }); } else { console.log(`> [WARNING] Intent "\x1b[4m${intentName}\x1b[0m" is not handled.`); return resolve({ success: true, message: { text: `I can't handle your intention, yet I think it is *${intentName}*. Maybe it was disabled :/` }}); } }) } /** * Handle a command. Find the related skill and call it. * @param {String} commandName The word of the command to execute. * @param {String} [phrase=""] - Parameters of the command (string following command word) sent by connector. * @param {Object} [data={}] - Data sent by the connector to the brain. * @return {Promise} Promise object represents the answer of the skill (message to send back to connector, optional data...) */ function handleCommand(commandName, phrase = "", data = {}) { return new Promise((resolve, reject) => { console.log(`> [INFO] Handling command "\x1b[4m${commandName}\x1b[0m"`) if (SkillManager.commands.has(commandName) && SkillManager.commands.get(commandName).active) { let command = SkillManager.commands.get(commandName); command.execute({ phrase, data }).then((response) => { return resolve({ success: true, message: response.message, response: response }); }).catch((err) => { return reject(err); }); } else { return resolve({ success: true, message: { text: `I can't handle your command because I don't know it. Maybe it was disabled :/ If not, you can teach me by adding new skills!` }}); } }) } /** * Fully reload all the skills. * @return {Promise} promise object that resolves if success. */ function reloadBrain() { return new Promise((resolve, reject) => { try { SkillManager.loadSkillsFromFolder(); return resolve(); } catch(e) { return reject(e); } }); } // Create a new SkillManager const skillComponent = require('./components/SkillManager'); const SkillManager = new skillComponent.SkillManager(path.join(__dirname, "./skills")); // Create and export a new ConnectorManager. const connectorComponent = require('./components/ConnectorManager'); let ConnectorManager = new connectorComponent.ConnectorManager(); exports.ConnectorManager = ConnectorManager; // Create and export a new ThreadManager const threadComponent = require('./components/ThreadManager'); let ThreadManager = new threadComponent.ThreadManager(SkillManager.interactions); exports.ThreadManager = ThreadManager; // Create and export a new StorageManager const storageComponent = require('./components/StorageManager'); let StorageManager = new storageComponent.StorageManager(); exports.StorageManager = StorageManager; // Create and export a new HookManaher const hookComponent = require('./components/HookManager'); let HookManager = new hookComponent.HookManager(); exports.HookManager = HookManager; // Export main handlers exports.handleIntent = handleIntent; exports.handleCommand = handleCommand; // Exoport skill commands exports.activateSkill = (skillName) => SkillManager.activateSkill(skillName); exports.deactivateSkill = (skillName) => SkillManager.deactivateSkill(skillName); exports.loadSkill = (skillName) => SkillManager.loadSkill(skillName); exports.reloadSkill = (skillName) => SkillManager.reloadSkill(skillName); exports.getSkillCode = (skillName) => SkillManager.getSkillCode(skillName); exports.saveSkillCode = (skillName, code) => SkillManager.saveSkillCode(skillName, code); exports.addSkill = (skill) => SkillManager.addSkill(skill); exports.deleteSkill = (skillName) => SkillManager.deleteSkill(skillName); exports.getSkills = () => SkillManager.getSkills(); exports.getSkillSecret = (skillName) => SkillManager.getSkillSecret(skillName); exports.updateSkillSecret = (skillName, secret) => SkillManager.updateSkillSecret(skillName, secret); exports.getSkill = (skillName) => SkillManager.getSkill(skillName); exports.hasSkill = (skillName) => SkillManager.hasSkill(skillName); exports.reloadBrain = reloadBrain; SkillManager.loadSkillsFromFolder();
1.484375
1
src/common/DashboardHeader/DashboardHeader.js
Austine3000/miniaspire
0
15990324
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import * as auth from '../../store/actions'; import './DashboardHeader.scss'; class DashboardHeader extends Component { onLogout = () => { this.props.logout(); }; render() { const { user } = this.props; return ( <header> <div className="search-area"> <i className="fas fa-search" /> <input type="text" name="" defaultValue="search" /> </div> <div className="user-area"> <button onClick={this.onLogout} className="btn btn-primary btn-right-space" > Logout </button> <span>{user.email}</span> </div> </header> ); } } DashboardHeader.propTypes = { logout: PropTypes.func.isRequired }; function mapStateToProps(state, ownProps) { return { user: state.auth.user }; } const mapDispatchToProps = (dispatch, ownProps) => { return { logout: () => dispatch(auth.logout()) }; }; export default connect( mapStateToProps, mapDispatchToProps )(DashboardHeader);
1.5
2
www/spa/src/Survey/actions/Client/CompleteSurvey/Success.js
gram7gram/Survey
0
15990332
"use strict"; import {CLIENT_SURVEY_COMPLETE_SUCCESS} from '../../../actions' export default (model) => { return { type: CLIENT_SURVEY_COMPLETE_SUCCESS, payload: model } }
0.578125
1
src/comandos/developer/sh.js
TGVGODB2/kinnybot
1
15990340
const {token} = require('../../../config.json') const config = require('../../../config.json') const { MessageEmbed } = require('discord.js') const shell = require('shelljs'); module.exports = { config: { nome: 'sh' }, run: async (client, message, args) => { if (!['395995293436477442', '425775842371829760'].includes(!message.author ? message.user.id:message.author.id)) return message.reply('Que lindo né usando meu shell? So meu dono pode usar!') if(!args[0]) return message.reply('Digite o que quer executar no console!') if(shell.exec(args.join(" ")).stdout.length === 0) { return message.reply(` \`\`\`${shell.exec(args.join(" ")).stderr.replace('NzUwMzg0MDE0Mzg4NDk0Mzc2.X05vkg.vVftZt7VJHo_0Z9UvuvG3K_kfj4', '***')}\`\`\` `) } message.reply(` \`\`\`${shell.exec(args.join(" ")).stdout}\`\`\` `) }, }
1.335938
1
app/controllers/login.js
loxmys/cgrates_web_frontend
0
15990348
import Controller from '@ember/controller'; import { inject as service } from '@ember/service'; import { validator, buildValidations } from 'ember-cp-validations'; const Validations = buildValidations({ email: [ validator('presence', true), validator('format', { type: 'email', }), ], password: validator('presence', true), }); export default Controller.extend(Validations, { session: service(), router: service(), flashMessages: service(), actions: { signIn() { return this.get('session').authenticate('authenticator:jwt', this.getProperties('email', 'password')).then(() => { return this.get('router').transitionTo('realtime'); }).catch(() => this.get('flashMessages').danger('Something went wrong')); } } });
1.257813
1
src/featureReport/scenarioTable/scenarioTable.directive.js
soltech-vasilva/BlackBookAutomationFramework
2
15990356
(function() { angular.module('featureReport') .directive('jxlScenarioTable', jxlScenarioTable) function jxlScenarioTable() { return { restrict: 'E', scope: {}, transclude: false, templateUrl: "featureReport/scenarioTable/scenarioTable.directive.html", controller: 'ScenarioTableController', controllerAs: 'vm' }; } })();
0.636719
1
src/Create.js
jesselurie/competitors-club-web
1
15990364
import React, { useEffect, useState } from 'react' import { Table, Grid, Button, Label, Image, Divider, Form, Segment } from 'semantic-ui-react' import { CopyToClipboard } from 'react-copy-to-clipboard' import { useSubstrateState } from './substrate-lib' import Memo from './components/Memo'; import SidePanel from './components/SidePanel'; import Podium from './components/Podium'; import Players from './components/Players'; import Actions from './components/Actions'; const Home = () => ( <Grid> <Grid.Row> <Grid.Column mobile={16} tablet={16} computer={16}> <Memo stake={10} totalStake={100} memo={"THIS STRING IS 256 CHARACTERS xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}/> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column> <Podium/> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column> <Players/> </Grid.Column> </Grid.Row> </Grid> ) const Dashboard = () => ( <Segment placeholder> <Grid columns={2}> <Grid.Column width={3}> <SidePanel/> </Grid.Column> <Grid.Column width={13}> <Home/> </Grid.Column> </Grid> {/* <Divider vertical>Or</Divider> */} </Segment> ) export default function Main(props) { // const { api, keyring } = useSubstrateState() // const accounts = keyring.getPairs() return ( <Home/> // <Dashboard/> // <Grid.Column> // <Memo/> // <SidePanel/> // <Podium/> // <Players/> // <Actions/> // </Grid.Column> ) }
1.6875
2
chrome/browser/resources/settings/controls/controlled_radio_button.js
xzhan96/chromium.src
1
15990372
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. Polymer({ is: 'controlled-radio-button', behaviors: [CrPolicyPrefBehavior, PrefControlBehavior], properties: { name: { type: String, notify: true, }, /** @private */ controlled_: { type: Boolean, computed: 'computeControlled_(pref.*)', reflectToAttribute: true, }, }, listeners: { 'focus': 'onFocus_', }, /** * @return {boolean} Whether the button is disabled. * @private */ computeControlled_: function() { return this.isPrefPolicyControlled(assert(this.pref)); }, /** * @param {boolean} controlled * @param {string} name * @param {chrome.settingsPrivate.PrefObject} pref * @return {boolean} * @private */ showIndicator_: function(controlled, name, pref) { return controlled && name == Settings.PrefUtil.prefToString(pref); }, /** * @param {!Event} e * @private */ onIndicatorTap_: function(e) { // Disallow <controlled-radio-button on-tap="..."> when controlled. e.preventDefault(); e.stopPropagation(); }, /** Focuses the internal radio button when the row is selected. */ onFocus_: function() { this.$.radioButton.focus(); }, });
1.453125
1
lib/Server.js
cronvel/server-kit
0
15990380
/* Server Kit Copyright (c) 2015 - 2020 <NAME> The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ "use strict" ; const http = require( 'http' ) ; const url = require( 'url' ) ; const domain = require( 'domain' ) ; const NextGenEvents = require( 'nextgen-events' ) ; const log = require( 'logfella' ).global.use( 'server-kit' ) ; const Dicer = require( 'server-kit-dicer' ) ; // Multipart handler const ws = require( 'ws' ) ; const Client = require( './Client.js' ) ; const ErrorDocument = require( './ErrorDocument.js' ) ; //const util = require( 'util' ) ; function noop() {} /* new Server( options , requestHandler ) options: object of options, where: port: the port where the server is listening, default to 80 http: `boolean` spawn an http server ws: `boolean` spawn an websocket server catchErrors: `boolean` (default: false) catch uncaught userland errors (using try-catch and domain) Spawn a new server */ function Server( options , requestHandler ) { if ( ! options || typeof options !== 'object' ) { options = { http: true , port: 80 } ; } this.port = options.port || 80 ; this.uncaughtError = 0 ; this.catchErrors = !! options.catchErrors ; this.http = !! options.http ; this.ws = !! options.ws ; this.multipart = !! options.multipart ; this.httpServer = null ; this.wsServer = null ; this.queryParserOptions = options.queryParserOptions || null ; if ( typeof requestHandler === 'function' ) { this.requestHandler = requestHandler ; } else if ( requestHandler && typeof requestHandler === 'object' && typeof requestHandler.handle === 'function' ) { this.requestHandler = requestHandler.handle.bind( requestHandler ) ; } else { throw new Error( "Argument #2 should be a function or an object with a 'handle' method" ) ; } if ( this.catchErrors ) { this.domain = domain.create() ; this.domain.on( 'error' , this.errorHandler.bind( this ) ) ; this.domain.run( this.startServer.bind( this ) ) ; } else { this.startServer() ; } this.defineStates( 'running' , 'closing' , 'close' ) ; } Server.prototype = Object.create( NextGenEvents.prototype ) ; Server.prototype.constructor = Server ; module.exports = Server ; // For backward compatibility Server.create = ( ... args ) => new Server( ... args ) ; Server.prototype.startServer = function() { var wsUpgradeListenerCount , wsUpgradeListeners ; if ( this.http ) { // Configure our HTTP server this.httpServer = http.createServer() ; try { // Listen and accept connection to the specified port this.httpServer.listen( this.port ) ; } catch ( error ) { // Since we exit ATM, we should log even when verbose is off log.warning( "Can't open port %i: %E" , this.port , error ) ; throw error ; } // Request handlers this.httpServer.on( 'request' , this.httpRequestHandler.bind( this ) ) ; this.httpServer.on( 'upgrade' , this.httpUpgradeRequestHandler.bind( this ) ) ; this.httpServer.on( 'connect' , this.httpConnectRequestHandler.bind( this ) ) ; this.httpServer.on( 'error' , ( ... args ) => { this.emit( 'error' , ... args ) ; } ) ; this.httpServer.on( 'listening' , ( ... args ) => { log.debug( 'Listening (HTTP) on port %i' , this.port ) ; this.emit( 'listening' , ... args ) ; this.emit( 'running' ) ; } ) ; this.httpServer.on( 'close' , () => this.closeEvent( 'http' ) ) ; } if ( this.ws ) { if ( this.httpServer ) { wsUpgradeListenerCount = this.httpServer.listeners( 'upgrade' ).length ; // If an HTTP server is already created, use it, so it can use 'upgrade' properly over the existing server this.wsServer = new ws.Server( { server: this.httpServer } ) ; // Looks like a hack here, but we don't want to allow the 'ws' module to trash upgrade request // that are specifying another protocol than 'websocket'. // So we simply remove the 'ws' module listener. wsUpgradeListeners = this.httpServer.listeners( 'upgrade' ) ; if ( wsUpgradeListeners.length > wsUpgradeListenerCount ) { //log.debug( 'WS listener spotted!' ) ; this.httpServer.removeListener( 'upgrade' , wsUpgradeListeners[ wsUpgradeListeners.length - 1 ] ) ; } } else { // If no other server has been created, create a new server on this port this.wsServer = new ws.Server( { port: this.port } ) ; this.wsServer.on( 'listening' , ( ... args ) => { log.debug( 'Listening (WS) on port %i' , this.port ) ; this.emit( 'listening' , ... args ) ; this.emit( 'running' ) ; } ) ; } this.wsServer.on( 'close' , () => this.closeEvent( 'ws' ) ) ; this.wsServer.on( 'error' , ( ... args ) => { this.emit( 'error' , ... args ) ; } ) ; this.wsServer.on( 'connection' , this.wsHandler.bind( this ) ) ; } } ; Server.prototype.wsHandler = async function( websocket , upgradeReq ) { log.debug( "Websocket port %i - connection established, request on path: %s" , this.port , upgradeReq.url ) ; // The ws module does not have an event when the websocket is closing... // This is the big nasty hack to do it: replace the readyState property by a getter/setter var readyState = websocket.readyState ; Object.defineProperty( websocket , 'readyState' , { get: function() { return readyState ; } , set: function( v ) { readyState = v ; if ( readyState === ws.CLOSING ) { websocket.emit( 'end' ) ; } } } ) ; var client = new Client( this , { type: 'ws' , protocol: 'ws' , request: upgradeReq , websocket: websocket } ) ; try { await this.requestHandler( client ) ; } catch ( error ) { if ( ! this.catchErrors ) { throw error ; } log.error( "Websocket port %i - requestHandler uncaught exception: %E" , this.port , error ) ; ErrorDocument.defaultHandler( 500 , client ) ; } } ; var multipartBoundaryRegex = /^multipart\/.+?(?:; boundary=(?:(?:"(.+)")|(?:([^\s]+))))$/ ; Server.prototype.httpRequestHandler = async function( request , response ) { var client , multipartBoundary ; log.debug( "Http port %i - received request %s on path: %s" , this.port , request.method , request.url ) ; client = new Client( this , { type: 'http' , protocol: 'http' , request: request , response: response } ) ; if ( this.multipart && request.headers['content-type'] && request.headers['content-type'].startsWith( 'multipart/' ) ) { log.debug( 'multipart detected' ) ; // Get the multipart boundary multipartBoundary = request.headers['content-type'].match( multipartBoundaryRegex ) ; if ( ! multipartBoundary ) { log.debug( 'bad multipart content-type (or missing boundary)' ) ; ErrorDocument.defaultHandler( 400 , client ) ; return ; } multipartBoundary = multipartBoundary[ 1 ] || multipartBoundary[ 2 ] ; // Create the Dicer object and put it into the multipart property request.multipart = new Dicer( { boundary: multipartBoundary , maxHeaderPairs: 20 } ) ; request.multipart.on( 'error' , error => { log.debug( 'multipart error: %E' , error ) ; ErrorDocument.defaultHandler( 400 , client ) ; } ) ; // Pipe the current request into Dicer request.pipe( request.multipart ) ; } try { await this.requestHandler( client ) ; } catch ( error ) { if ( ! this.catchErrors ) { throw error ; } log.error( "Http port %i - requestHandler uncaught exception: %E" , this.port , error ) ; ErrorDocument.defaultHandler( 500 , client ) ; } } ; Server.prototype.httpUpgradeRequestHandler = async function( request , socket , headBuffer_ ) { var client , response , headBuffer ; // From the 'ws' module: // copy headBuffer to avoid retention of large slab buffers used in node core headBuffer = Buffer.allocUnsafe( headBuffer_.length ) ; headBuffer_.copy( headBuffer ) ; log.debug( "Http port %i - received an UPGRADE request to the '%s' protocol on path: %s" , this.port , request.headers.upgrade , request.url ) ; // Force a response object: response = new http.ServerResponse( request ) ; response.assignSocket( socket ) ; client = new Client( this , { type: 'http.upgrade' , protocol: 'http' , request: request , response: response , headBuffer: headBuffer , socket: socket } ) ; response.accept = accepted => { if ( arguments.length && ! accepted ) { response.writeHeader( 400 , {} ) ; response.end() ; return ; } switch ( request.headers.upgrade.toLowerCase() ) { case 'websocket' : if ( ! this.ws ) { //this.sendHttpOverSocket( socket , 400 , {} , '' , true ) ; response.writeHeader( 400 , {} ) ; response.end() ; return ; } // From the 'ws' module: this.wsServer.handleUpgrade( request , socket , headBuffer , websocket => { this.wsServer.emit( 'connection' + request.url , websocket , request ) ; this.wsServer.emit( 'connection' , websocket , request ) ; } ) ; break ; default : //this.sendHttpOverSocket( socket , 400 , {} , '' , true ) ; response.writeHeader( 400 , {} ) ; response.end() ; } } ; try { await this.requestHandler( client ) ; } catch ( error ) { if ( ! this.catchErrors ) { throw error ; } log.error( "Http port %i - requestHandler uncaught exception: %E" , this.port , error ) ; ErrorDocument.defaultHandler( 500 , client ) ; } } ; Server.prototype.httpConnectRequestHandler = async function( request , socket , headBuffer_ ) { var client , response , headBuffer ; // From the 'ws' module: // copy headBuffer to avoid retention of large slab buffers used in node core headBuffer = Buffer.allocUnsafe( headBuffer_.length ) ; headBuffer_.copy( headBuffer ) ; log.debug( "Http port %i - received a CONNECT on path: %s" , this.port , request.url ) ; // Force a response object: response = new http.ServerResponse( request ) ; response.assignSocket( socket ) ; client = new Client( this , { type: 'http.connect' , protocol: 'http' , request: request , response: response , headBuffer: headBuffer , socket: socket } ) ; // There is an issue: https://github.com/joyent/node/issues/7019 // Any body advertised by "Content-Length" > 0 or "Transfer-Encoding: chunked" will cause a parse error // for a node.js client receiving the response, so we should set "Content-Length: 0" and forbid any write. //response.setHeader( 'Connection' , 'close' ) ; response.setHeader( 'Content-Length' , 0 ) ; response.write = noop ; response.end = ( data , encoding , callback ) => http.ServerResponse.prototype.end.call( response , undefined , undefined , callback ) ; try { await this.requestHandler( client ) ; } catch ( error ) { if ( ! this.catchErrors ) { throw error ; } log.error( "Http port %i - requestHandler uncaught exception: %E" , this.port , error ) ; ErrorDocument.defaultHandler( 500 , client ) ; } } ; Server.prototype.errorHandler = function( error ) { // For instance, we increment the number of uncaught error, // Later it could be a good idea to restart the server when this number reaches some limits. this.uncaughtError ++ ; log.error( "Http port %i - Uncaught async error #%i: %E" , this.port , this.uncaughtError , error ) ; } ; /* Useful when no facilities can be used. Most of time, this trick can be used instead: var response = new http.ServerResponse( request ) ; response.assignSocket( socket ) ; */ Server.prototype.sendHttpOverSocket = function( socket , statusCode , headers , body , destroy ) { var key , responseHead = '' ; if ( body ) { if ( ! Buffer.isBuffer( body ) ) { if ( typeof body !== 'string' ) { body = JSON.stringify( body ) ; } body = Buffer.from( body ) ; } // This is not done automatically! headers['Content-Length'] = body.length ; } responseHead += 'HTTP/1.1 ' + statusCode + ' ' + http.STATUS_CODES[ statusCode ] + '\r\n' ; for ( key in headers ) { responseHead.push( key + ': ' + headers[ key ] + '\r\n' ) ; } responseHead += '\r\n' ; try { socket.write( responseHead ) ; if ( body ) { socket.write( body ) ; } } catch ( error ) { // Not sure how to handle that ATM. We will just destroy the sockect for instance. destroy = true ; } finally { if ( destroy ) { try { socket.destroy() ; } catch ( error ) { } } } } ; Server.prototype.closeEvent = function( type ) { if ( type === 'ws' ) { this.wsServer.__closed__ = true ; if ( ! this.httpServer || this.httpServer.__closed__ ) { this.emit( 'close' ) ; } } else if ( type === 'http' ) { this.httpServer.__closed__ = true ; if ( ! this.wsServer || this.wsServer.__closed__ ) { this.emit( 'close' ) ; } } } ; Server.prototype.close = function() { this.emit( 'closing' ) ; if ( this.httpServer ) { this.httpServer.close() ; } if ( this.wsServer ) { this.wsServer.close() ; } } ; Server.prototype.gracefulClose = function() { // TODO } ;
1.5625
2
test/services/lesson-groups/index.test.js
tum-ase-33/rest-server
1
15990388
'use strict'; const assert = require('assert'); const app = require('../../../src/app'); const User = app.service('users'); const Lesson = app.service('lessons'); const LessonGroups = app.service('lesson-groups'); const LessonAssignment = app.service('user-lesson-assignments'); const chai = require('chai'); const chaiHttp = require('chai-http'); const bodyParser = require('body-parser'); const authentication = require('feathers-authentication/client'); let adminUserId, adminToken, studentUserId, studentToken; //config for app to do authentication app .use(bodyParser.json()) .use(bodyParser.urlencoded({ extended: true })) .configure(authentication()); //use http plugin chai.use(chaiHttp); //use should const should = chai.should(); describe('lesson-groups service', function () { before('open server', (done) => { //start the server this.server = app.listen(3030); //once listening do the following this.server.once('listening', () => done()); }); after('clear', (done) => { this.server.close(done); }); it('registered the lesson-groups service', () => { assert.ok(app.service('lesson-groups')); }); describe('get()', () => { it('Should be disabled', (done) => { chai.request(app) .get(`/lesson-groups/123456`) //set header .set('Accept', 'application/json') //when finished .end((err, res) => { res.statusCode.should.be.equal(405); done(); }); }); }); let userCounter = 0; const createUser = (lessonId, roles) => { userCounter += 1; const email = 'email' + userCounter + '@test.de'; const password = '<PASSWORD>$'; return User.create({ matrikelNr: 'mnr' + userCounter, email, password }) .then((user) => new Promise((resolve) => { let userId = user._id; chai.request(app) //request to /auth/local .post('/auth/local') //set header .set('Accept', 'application/json') //send credentials .send({ email, password }) //when finished .end((err, res) => { //set token for auth in other requests let token = res.body.token; resolve([userId, token, user]); }); })) .then(data => LessonAssignment.create({ lessonId, userId: data[0], roles }) .then(lessonAssignment => Promise.resolve(data)) ) .then((data) => { return Promise.resolve(data); }); }; describe('find()', () => { let lesson; before('create user and assign roles', () => Lesson.create({ name: 'ASE lesson-groups' }) .then((createdLesson) => createUser(createdLesson._id, ['admin']) .then(([createdUserId, createdUserToken]) => { lesson = createdLesson; adminUserId = createdUserId; adminToken = <PASSWORD>UserToken; return createUser(createdLesson._id, ['student']); }) .then(([createdUserId, createdUserToken]) => { studentUserId = createdUserId; studentToken = createdUserToken; return Promise.resolve(); }) ) .then(() => LessonGroups.create({ name: 'ASE group #1', lessonId: lesson._id })) .then(() => LessonGroups.create({ name: 'ASE group #2', lessonId: lesson._id })) ); after('clear all entries', () => LessonGroups.remove(null) .then(() => LessonAssignment.remove(null)) .then(() => Lesson.remove(null)) .then(() => User.remove(null)) ); it('Should be only accessible if logged in', (done) => { chai.request(app) .get(`/lesson-groups`) //set header .set('Accept', 'application/json') //when finished .end((err, res) => { res.statusCode.should.be.equal(401); done(); }); }); it('Should be only accessible if lessonId query parameter is provided', (done) => { chai.request(app) .get(`/lesson-groups`) //set header .set('Accept', 'application/json') .set('Authorization', 'Bearer '.concat(studentToken)) //when finished .end((err, res) => { res.statusCode.should.be.equal(400); done(); }); }); it('Should return all lesson groups if logged in', (done) => { chai.request(app) .get(`/lesson-groups?lessonId=${lesson._id}`) //set header .set('Accept', 'application/json') .set('Authorization', 'Bearer '.concat(studentToken)) //when finished .end((err, res) => { res.statusCode.should.be.equal(200); res.body.total.should.be.equal(2); done(); }); }); }); describe('create()', () => { let lesson; before('create user and assign roles', () => Lesson.create({ name: 'ASE lesson-groups' }) .then((createdLesson) => createUser(createdLesson._id, ['admin']) .then(([createdUserId, createdUserToken]) => { lesson = createdLesson; adminUserId = createdUserId; adminToken = <PASSWORD>UserToken; return createUser(createdLesson._id, ['student']); }) .then(([createdUserId, createdUserToken]) => { studentUserId = createdUserId; studentToken = <PASSWORD>UserToken; return Promise.resolve(); }) ) .then(() => LessonGroups.create({ name: 'ASE group #1', lessonId: lesson._id })) .then(() => LessonGroups.create({ name: 'ASE group #2', lessonId: lesson._id })) ); after('clear all entries', () => LessonGroups.remove(null) .then(() => LessonAssignment.remove(null)) .then(() => Lesson.remove(null)) .then(() => User.remove(null)) ); it('Should be only accessible if logged in', (done) => { chai.request(app) .post(`/lesson-groups`) //set header .set('Accept', 'application/json') //when finished .end((err, res) => { res.statusCode.should.be.equal(401); done(); }); }); it('Should not be accessible for non admins', (done) => { chai.request(app) .post(`/lesson-groups`) //set header .set('Accept', 'application/json') .set('Authorization', 'Bearer '.concat(studentToken)) //when finished .end((err, res) => { res.statusCode.should.be.equal(403); done(); }); }); it('Should create a lesson group with an admin', (done) => { chai.request(app) .post(`/lesson-groups`) //set header .set('Accept', 'application/json') .set('Authorization', 'Bearer '.concat(adminToken)) .send({ name: 'New ASE group', lessonId: lesson._id }) //when finished .end((err, res) => { res.statusCode.should.be.equal(201); done(); }); }); }); describe('patch()', () => { let lesson, lessonGroupId, tutorUserId, tutorToken; before('create user and assign roles', () => Lesson.create({ name: 'ASE lesson-groups' }) .then((createdLesson) => createUser(createdLesson._id, ['admin']) .then(([createdUserId, createdUserToken]) => { lesson = createdLesson; adminUserId = createdUserId; adminToken = <PASSWORD>UserToken; return createUser(createdLesson._id, ['tutor']); }) .then(([createdUserId, createdUserToken]) => { tutorUserId = createdUserId; tutorToken = <PASSWORD>UserToken; return createUser(createdLesson._id, ['student']); }) .then(([createdUserId, createdUserToken]) => { studentUserId = createdUserId; studentToken = createdUserToken; return Promise.resolve(); }) ) .then(() => LessonGroups.create({ name: 'ASE group #1', lessonId: lesson._id })) .then(() => LessonGroups.create({ name: 'ASE group #2', lessonId: lesson._id })) .then(lessonGroup => { lessonGroupId = lessonGroup._id; return Promise.resolve(); }) ); after('clear all entries', () => LessonGroups.remove(null) .then(() => LessonAssignment.remove(null)) .then(() => Lesson.remove(null)) .then(() => User.remove(null)) ); it('Should be only accessible if logged in', (done) => { chai.request(app) .patch(`/lesson-groups/${lessonGroupId}`) //set header .set('Accept', 'application/json') //when finished .end((err, res) => { res.statusCode.should.be.equal(401); done(); }); }); it('Should not be accessible for non admins and non tutors', (done) => { chai.request(app) .patch(`/lesson-groups/${lessonGroupId}`) //set header .set('Accept', 'application/json') .set('Authorization', 'Bearer '.concat(studentToken)) //when finished .end((err, res) => { res.statusCode.should.be.equal(403); done(); }); }); it('Should update a lesson group with an admin', (done) => { chai.request(app) .patch(`/lesson-groups/${lessonGroupId}`) //set header .set('Accept', 'application/json') .set('Authorization', 'Bearer '.concat(adminToken)) .send({ name: 'New ASE group' }) //when finished .end((err, res) => { res.statusCode.should.be.equal(200); done(); }); }); it('Should update a lesson group with an tutor', (done) => { chai.request(app) .patch(`/lesson-groups/${lessonGroupId}`) //set header .set('Accept', 'application/json') .set('Authorization', 'Bearer '.concat(tutorToken)) .send({ name: 'New ASE group' }) //when finished .end((err, res) => { res.statusCode.should.be.equal(200); done(); }); }); }); describe('put()', () => { it('Should be disabled', (done) => { chai.request(app) .put(`/lesson-groups/123456`) //set header .set('Accept', 'application/json') //when finished .end((err, res) => { res.statusCode.should.be.equal(405); done(); }); }); }); describe('delete()', () => { let lesson, lessonGroupId; before('create user and assign roles', () => Lesson.create({ name: 'ASE lesson-groups' }) .then((createdLesson) => createUser(createdLesson._id, ['admin']) .then(([createdUserId, createdUserToken]) => { lesson = createdLesson; adminUserId = createdUserId; adminToken = <PASSWORD>UserToken; return createUser(createdLesson._id, ['student']); }) .then(([createdUserId, createdUserToken]) => { studentUserId = createdUserId; studentToken = <PASSWORD>UserToken; return Promise.resolve(); }) ) .then(() => LessonGroups.create({ name: 'ASE group #1', lessonId: lesson._id })) .then((lessonGroup) => { lessonGroupId = lessonGroup._id; return Promise.resolve(); }) ); after('clear all entries', () => { return LessonGroups.remove(null) .then(() => LessonAssignment.remove(null)) .then(() => Lesson.remove(null)) .then(() => User.remove(null)); }); it('Should be only accessible if logged in', (done) => { chai.request(app) .delete(`/lesson-groups/${lessonGroupId}`) //set header .set('Accept', 'application/json') //when finished .end((err, res) => { res.statusCode.should.be.equal(401); done(); }); }); it('Should not be accessible for non admins', (done) => { chai.request(app) .delete(`/lesson-groups/${lessonGroupId}`) //set header .set('Accept', 'application/json') .set('Authorization', 'Bearer '.concat(studentToken)) //when finished .end((err, res) => { res.statusCode.should.be.equal(403); done(); }); }); it('Should remove a lesson group with an admin', (done) => { chai.request(app) .delete(`/lesson-groups/${lessonGroupId}`) //set header .set('Accept', 'application/json') .set('Authorization', 'Bearer '.concat(adminToken)) //when finished .end((err, res) => { res.statusCode.should.be.equal(200); done(); }); }); }); });
1.609375
2
src/js/components/container/AuraAppContainer.js
st235/aura
4
15990396
import React, { Component } from 'react'; import ItemsConatainer from './ItemsContainer'; import DescriptionContainer from './DescriptionContainer'; import CodeContainer from './CodeContainer'; import DataReader from '../../data/DataReader'; export default class AuraAppContainer extends Component { constructor(props) { super(props); this.state = DataReader.getData(); } _onSelectedItemChanged(item) { console.log(item); this.setState((state, props) => { return { items: state.items, selectedItem: item }; }); } render() { const { items, selectedItem } = this.state; return <div className="container-fluid row"> <ItemsConatainer items={items} selectedItem={selectedItem.id} onItemClickListener={ i => this._onSelectedItemChanged(i) } /> <DescriptionContainer title={selectedItem.title} description={selectedItem.description} /> <CodeContainer code={selectedItem.code} /> </div>; } }
1.53125
2
src/configuration.js
RetroRabbit/build-your-own-blockchain
1
15990404
const { resolve } = require('path'); module.exports = { BLOCK_REWARD: parseFloat(process.env.BYOB_BLOCK_REWARD || 1), TARGET: process.env.BYOB_TARGET || 'AAABrX8pq8r0hXh6ZSDsCNI2mRlBGaXDc4e3GQZhQxA', KEYS_FILE: resolve(process.env.BYOB_KEYS_FILE || resolve(process.env.USERPROFILE || process.env.HOME, '.byobkeys.json')), DB_FILE: resolve(process.env.BYOB_DB_FILE || resolve(process.cwd(), 'db.json')), BROKER: process.env.BYOB_BROKER || "amqps://byob:[email protected]/byob", SOLVER: process.env.BYOB_SOLVER || `"${process.argv0}" "${resolve(__dirname, 'solver.worker.js')}" -q` };
0.636719
1
pages/async/MetaWithKeyWordsByContent.js
Guseyn/guseyn.com
1
15990412
'use strict' const { AsyncObject } = require('@cuties/cutie') const cheerio = require('cheerio') class MetaWithKeyWordsByContent extends AsyncObject { constructor (basicWords, content) { super(basicWords, content) } syncCall () { return (basicWords, content) => { const $ = cheerio.load(content) let titles = [] let tags = [] $('h1').each((index, elm) => { titles = titles.concat( $(elm).text() .replace(/\s+/g, ' ') .split(' ') ) }) $('a.tag').each((index, elm) => { tags.push($(elm).text() .replace(/\s+/g, ' ') ) }) const keywords = titles.concat(tags).map(w => w.toLowerCase()) const uniqueKeywords = keywords.filter((w, i) => keywords.indexOf(w) === i) return `name="keywords" content="${basicWords}, ${uniqueKeywords.join(', ')}"` } } } module.exports = MetaWithKeyWordsByContent
1.34375
1
src/commands/music/clear.js
screwdev/discord-lavalink-music-bot
42
15990420
module.exports = { name: "clear", aliases: ["cq", "empty"], description: "Clear the current queue.", category: "music", execute(bot, message) { const player = bot.manager.get(message.guild.id); if (!player) return bot.say.wrongMessage(message, "The bot is currently not playing in this server."); if (!bot.utils.modifyQueue(message)) return; if (queue.length < 1) return bot.say.wrongMessage(message, "There is currently no song in the queue."); player.queue.clear(); return bot.say.successMessage(message, "The queue has been cleared."); } };
1.3125
1
WebracerWeb/src/main/resources/html/js/player.js
slintes/Webracer
2
15990428
;Quintus.WebracerPlayer = function (Q) { // behaviour of players car Q.component("RaceControl", { added: function () { var p = this.entity.p; // speed p.stepDistance = 0; // time per round in seconds p.stepDelay = TIMEOUT / 1000; // helper for keeping track of time p.stepWait = 0; // register event handlers this.entity.on("hit", this, "collision"); this.entity.on("step", this, "step"); }, // called by Quituns on collisions collision: function (col) { var p = this.entity.p; if(p.crashed || p.finished){ return; } var tileNum = col.tile; // handle grass if (tileNum == TILE_GRASS) { if (Q.state.get(SPEED) == SPEED2) { Q.state.set(SPEED, SPEED1); Q.state.set(ONGRASS, true); } } else { Q.state.set(ONGRASS, false); } // handle wall if (tileNum == TILE_WALL) { p.crashed = true; // stop moving p.diffX = 0; p.diffY = 0; // send crash position to backend var data = {}; data[WSC_UPDATE_POS_X] = Math.round(p.x); data[WSC_UPDATE_POS_Y] = Math.round(p.y); data[WSC_UPDATE_POS_SPEED] = 0; data[WSC_UPDATE_POS_ANGLE] = p.angle; data[WSC_UPDATE_POS_CRASHED] = true; data[WSC_UPDATE_POS_FINISHED] = false; Q.sendCommand(WSC_UPDATE_POS, data); } // handle sector 1 if (tileNum == TILE_SECTOR1) { p.sector1passed = true; } // handle sector 2 if (tileNum == TILE_SECTOR2) { p.sector2passed = true; } // handle finish if (tileNum == TILE_FINISH) { // check if both sectors have been passed if(p.sector1passed && p.sector2passed){ p.nrLapsDone++; p.sector1passed = false; p.sector2passed = false; // race finished? if(p.nrLapsDone == NR_LAPS){ p.finished = true; // send finish position to backend var data = {}; data[WSC_UPDATE_POS_X] = Math.round(p.x); data[WSC_UPDATE_POS_Y] = Math.round(p.y); data[WSC_UPDATE_POS_SPEED] = 0; data[WSC_UPDATE_POS_ANGLE] = p.angle; data[WSC_UPDATE_POS_CRASHED] = false; data[WSC_UPDATE_POS_FINISHED] = true; Q.sendCommand(WSC_UPDATE_POS, data); } } } }, // called permanently by Quitus engine step: function (dt) { var p = this.entity.p; if (p.crashed || p.finished) { return; } // keep track of time p.stepWait -= dt; // move if (p.stepping) { p.x += p.diffX * dt / p.stepDelay; p.y += p.diffY * dt / p.stepDelay; } // next round? if (p.stepWait > 0) { return; } // move to end position if not there yet if (p.stepping) { p.x = p.destX; p.y = p.destY; } // stop moving p.stepping = false; p.diffX = 0; p.diffY = 0; }, nextRound: function () { // calculate next round var p = this.entity.p; if (p.crashed || p.finished) { return; } // get last pressed key and reset var lastKey = Q.state.get(LAST_KEY); Q.state.set(LAST_KEY, KEY_NONE); // set new steering var steering = Q.state.get(STEERING); if (lastKey == KEY_LEFT) { if (steering == STEERING_RIGHT) { steering = STEERING_STRAIGHT; } else if (steering == STEERING_STRAIGHT) { steering = STEERING_LEFT; } } else if (lastKey == KEY_RIGHT) { if (steering == STEERING_LEFT) { steering = STEERING_STRAIGHT; } else if (steering == STEERING_STRAIGHT) { steering = STEERING_RIGHT; } } Q.state.set(STEERING, steering); // rotate car according to steering var angleChanged = false; if (steering == STEERING_LEFT) { p.angle -= DEGREES; angleChanged = true; } else if (steering == STEERING_RIGHT) { p.angle += DEGREES; angleChanged = true; } Q.state.set(STEERING_ANGLE, p.angle); // set new speed var speed = Q.state.get(SPEED); if (lastKey == KEY_UP) { if (speed == 0) { speed = SPEED1; } else if (speed == SPEED1) { // prevent speeds2 on grass if (!Q.state.get(ONGRASS)) { speed = SPEED2; } } } else if (lastKey == KEY_DOWN) { if (speed == SPEED2) { speed = SPEED1; } else if (speed == SPEED1) { speed = 0; } } Q.state.set(SPEED, speed); p.stepDistance = speed; // calculate x and y of movement p.diffX = Math.round( (Math.sin(2 * Math.PI * p.angle / 360) * p.stepDistance) ); p.diffY = Math.round( -(Math.cos(2 * Math.PI * p.angle / 360) * p.stepDistance) ); // prepare movement if (p.diffY || p.diffX) { p.stepping = true; p.origX = p.x; p.origY = p.y; p.destX = p.x + p.diffX; p.destY = p.y + p.diffY; p.stepWait = p.stepDelay; // send new position to backend var data = {}; data[WSC_UPDATE_POS_X] = Math.round(p.destX); data[WSC_UPDATE_POS_Y] = Math.round(p.destY); data[WSC_UPDATE_POS_SPEED] = p.stepDistance; data[WSC_UPDATE_POS_ANGLE] = p.angle; data[WSC_UPDATE_POS_CRASHED] = p.crashed; data[WSC_UPDATE_POS_FINISHED] = p.finished; Q.sendCommand(WSC_UPDATE_POS, data); } else if(angleChanged){ // we are not moving, but we rotated var data = {}; data[WSC_UPDATE_POS_X] = Math.round(p.x); data[WSC_UPDATE_POS_Y] = Math.round(p.y); data[WSC_UPDATE_POS_SPEED] = p.stepDistance; data[WSC_UPDATE_POS_ANGLE] = p.angle; data[WSC_UPDATE_POS_CRASHED] = p.crashed; data[WSC_UPDATE_POS_FINISHED] = p.finished; Q.sendCommand(WSC_UPDATE_POS, data); } } }); // the player's sprite Q.Sprite.extend("Player", { init: function (p) { this._super(p, { sheet: "car", frame: 0, // override with startpos - 1 when added scale: 1.2, // make car a bit bigger angle: 90, // starting position: heading right crashed: false, // track if car has crashed finished: false, // track if car has finished sector1passed: false, // track if car has passed sector 1 sector2passed: false, // track if car has passed sector 2 nrLapsDone: 0, // track how many laps where driven gravityX: 0, // oh, no gravity please :) gravityY: 0 }); // add the 2d and our RaceControl component this.add("2d, RaceControl"); // save the latest key press var upPressed = function () { Q.state.set(LAST_KEY, KEY_UP); }; var downPressed = function () { Q.state.set(LAST_KEY, KEY_DOWN); }; var leftPressed = function () { Q.state.set(LAST_KEY, KEY_LEFT); }; var rightPressed = function () { Q.state.set(LAST_KEY, KEY_RIGHT); }; Q.input.on("up", this, upPressed); Q.input.on("down", this, downPressed); Q.input.on("left", this, leftPressed); Q.input.on("right", this, rightPressed); } }); };
1.703125
2
src/apps/author/composables/useArticle.js
fbraem/kwai-vite
0
15990436
import useState from '/src/composables/useState.js'; import { useArticleService } from '/src/apps/author/services/ArticleService.js'; const service = useArticleService(); export function useArticle(id) { const { data: article, loading, error, reload } = useState( () => `/author/article/${id}`, () => service.get(id) ); return { article, reload, loading, error }; }
1.007813
1
src/calendars/malta.js
CodingAleCR/romcal
1
15990444
import moment from 'moment'; import _ from 'lodash'; import { Dates, Utils } from '../lib'; import { Titles, Types, LiturgicalColors } from '../constants'; let dates = year => { let _dates = [ { "key": "saintPubliusBishop", "type": Types.MEMORIAL, "moment": moment.utc({ year: year, month: 0, day: 22 }), "data": {} }, { "key": "shipwreckOfSaintPaulApostle", "type": Types.SOLEMNITY, "moment": moment.utc({ year: year, month: 1, day: 10 }), "data": {} }, { "key": "saintsCyrilMonkAndMethodiusBishop", "type": Types.FEAST, "moment": moment.utc({ year: year, month: 1, day: 14 }), "data": { "meta": { "liturgicalColor": LiturgicalColors.WHITE, "titles": [ Titles.PATRON_OF_EUROPE ] } } }, { "key": "blessedMariaAdeodataPisaniVirgin", "type": Types.OPT_MEMORIAL, "moment": moment.utc({ year: year, month: 1, day: 25 }), "data": {} }, { "key": "ourLadyOfSorrows", "type": Types.FEAST, "moment": moment.utc({ year: year, month: 3, day: 15 }), "data": {} }, { "key": "saintCatherineOfSienaVirginAndDoctorOfTheChurch", "type": Types.FEAST, "moment": moment.utc({ year: year, month: 3, day: 29 }), "data": { "meta": { "titles": [ Titles.DOCTOR_OF_THE_CHURCH, Titles.PATRON_OF_EUROPE ] } } }, { "key": "saintPiusVPope", "type": Types.MEMORIAL, "moment": moment.utc({ year: year, month: 3, day: 30 }), "data": {} }, { "key": "saintGeorgePrecaPriest", "type": Types.FEAST, "moment": moment.utc({ year: year, month: 4, day: 9 }), "data": {} }, { "key": "blessedNazjuFalzon", "type": Types.OPT_MEMORIAL, "moment": moment.utc({ year: year, month: 6, day: 1 }), "data": {} }, { "key": "saintBenedictOfNursiaAbbot", "type": Types.FEAST, "moment": moment.utc({ year: year, month: 6, day: 11 }), "data": {} }, { "key": "ourLadyOfMountCarmel", "type": Types.MEMORIAL, "moment": moment.utc({ year: year, month: 6, day: 16 }), "data": {} }, { "key": "saintBridgetOfSwedenReligious", "type": Types.FEAST, "moment": moment.utc({ year: year, month: 6, day: 23 }), "data": { "meta": { "liturgicalColor": LiturgicalColors.WHITE, "titles": [ Titles.PATRON_OF_EUROPE ] } } }, { "key": "saintTeresaBenedictaOfTheCrossEdithSteinVirginAndMartyr", "type": Types.FEAST, "moment": moment.utc({ year: year, month: 7, day: 9 }), "data": { "meta": { "liturgicalColor": LiturgicalColors.RED, "titles": [ Titles.MARTYR, Titles.PATRON_OF_EUROPE ] } } }, { "key": "saintCatherineOfAlexandriaVirginAndMartyr", "type": Types.MEMORIAL, "moment": moment.utc({ year: year, month: 10, day: 25 }), "data": { "meta": { "liturgicalColor": LiturgicalColors.RED, "titles": [ Titles.MARTYR ] } } } ]; // Get localized celebration names return Utils.localizeDates(_dates); }; export { dates };
0.867188
1
play.js
guillaumewuip/du-workshop
0
15990452
const player = require('play-sound')({}); player.play('translate_tts.mp3', (err) => { if (err) { console.error(err); } console.log('done'); });
0.90625
1
bin/XULRunner21_0/modules/commonjs/sdk/addon/runner.js
michfahey/crime-stats
4
15990460
/* vim:set ts=2 sw=2 sts=2 expandtab */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ module.metadata = { "stability": "experimental" }; const { Cc, Ci } = require('chrome'); const { descriptor, Sandbox, evaluate, main, resolveURI } = require('toolkit/loader'); const { once } = require('../system/events'); const { exit, env, staticArgs, name } = require('../system'); const { when: unload } = require('../system/unload'); const { loadReason } = require('../self'); const { rootURI } = require("@loader/options"); const globals = require('../system/globals'); const NAME2TOPIC = { 'Firefox': 'sessionstore-windows-restored', 'Fennec': 'sessionstore-windows-restored', 'SeaMonkey': 'sessionstore-windows-restored', 'Thunderbird': 'mail-startup-done', '*': 'final-ui-startup' }; // Gets the topic that fit best as application startup event, in according with // the current application (e.g. Firefox, Fennec, Thunderbird...) const APP_STARTUP = NAME2TOPIC[name] || NAME2TOPIC['*']; // Initializes default preferences function setDefaultPrefs(prefsURI) { const prefs = Cc['@mozilla.org/preferences-service;1']. getService(Ci.nsIPrefService). QueryInterface(Ci.nsIPrefBranch2); const branch = prefs.getDefaultBranch(''); const sandbox = Sandbox({ name: prefsURI, prototype: { pref: function(key, val) { switch (typeof val) { case 'boolean': branch.setBoolPref(key, val); break; case 'number': if (val % 1 == 0) // number must be a integer, otherwise ignore it branch.setIntPref(key, val); break; case 'string': branch.setCharPref(key, val); break; } } } }); // load preferences. evaluate(sandbox, prefsURI); } function definePseudo(loader, id, exports) { let uri = resolveURI(id, loader.mapping); loader.modules[uri] = { exports: exports }; } function wait(reason, options) { once(APP_STARTUP, function() { startup(null, options); }); } function startup(reason, options) { if (reason === 'startup') return wait(reason, options); // Inject globals ASAP in order to have console API working ASAP Object.defineProperties(options.loader.globals, descriptor(globals)); // Load localization manifest and .properties files. // Run the addon even in case of error (best effort approach) require('../l10n/loader'). load(rootURI). then(null, function failure(error) { console.info("Error while loading localization: " + error.message); }). then(function onLocalizationReady(data) { // Exports data to a pseudo module so that api-utils/l10n/core // can get access to it definePseudo(options.loader, '@l10n/data', data ? data : null); run(options); }); } function run(options) { try { // Try initializing HTML localization before running main module. Just print // an exception in case of error, instead of preventing addon to be run. try { // Do not enable HTML localization while running test as it is hard to // disable. Because unit tests are evaluated in a another Loader who // doesn't have access to this current loader. if (options.main !== 'test-harness/run-tests') require('../l10n/html').enable(); } catch(error) { console.exception(error); } // Initialize inline options localization, without preventing addon to be // run in case of error try { require('../l10n/prefs'); } catch(error) { console.exception(error); } // TODO: When bug 564675 is implemented this will no longer be needed // Always set the default prefs, because they disappear on restart setDefaultPrefs(options.prefsURI); // this is where the addon's main.js finally run. let program = main(options.loader, options.main); if (typeof(program.onUnload) === 'function') unload(program.onUnload); if (typeof(program.main) === 'function') { program.main({ loadReason: loadReason, staticArgs: staticArgs }, { print: function print(_) { dump(_ + '\n') }, quit: exit }); } } catch (error) { console.exception(error); throw error; } } exports.startup = startup; // If add-on is lunched via `cfx run` we need to use `system.exit` to let // cfx know we're done (`cfx test` will take care of exit so we don't do // anything here). if (env.CFX_COMMAND === 'run') { unload(function(reason) { if (reason === 'shutdown') exit(0); }); }
1.453125
1
controllers/product/create/demo/post.js
yunus433/embed.usersmagic
0
15990468
const mongoose = require('mongoose'); module.exports = (req, res) => { const newProductData = { _id: (new mongoose.Types.ObjectId()).toString(), company_id: req.session.demo.company._id, name: req.body.name, link: req.body.link }; req.session.demo.products.push(newProductData); res.write(JSON.stringify({ id: newProductData._id, success: true })); return res.end(); }
1.023438
1
src/_utils.js
dryan/django-filters-js
6
15990476
djangoFilters._utils = { avoidWrapping: (value) => value.replace(/ /g, "\xa0"), padStart: (obj, len, pad) => { obj = obj.toString(); pad = pad.toString(); return obj.padStart(len, pad); }, padEnd: (obj, len, pad) => { obj = obj.toString(); pad = pad.toString(); return obj.padEnd(len, pad); }, parseDate: (value) => { if (value instanceof Date) { return value; } else if (typeof value === "number") { return new Date(value); } value = String(value); // not using toString here to handle null, undefined, etc. const date = new Date(value.replace(/-/g, "/").replace(/T/g, " ")); if (date.toString().toLowerCase() === "invalid date") { if (console && console.warn) { console.warn(`${value} was not parsed as a Date`); } return value; } return date; }, getLanguageCode: () => { return ( djangoFilters.language || (navigator && navigator.language ? navigator.language : "en-US") ); }, translate: (group, id) => { const languageCode = djangoFilters._utils.getLanguageCode().toLowerCase(); let lang; if (djangoFilters.translations[languageCode]) { lang = djangoFilters.translations[languageCode]; } else if (djangoFilters.translations[languageCode.split("-")[0]]) { lang = djangoFilters.translations[languageCode.split("-")[0]]; } else { lang = djangoFilters.translations["en-us"]; } if (lang && lang[group]) { return lang[group][id]; } return undefined; }, urlquote: (value, safe) => { value = value.toString(); if (typeof safe === "undefined") { safe = "/"; } safe = safe .split("") .map((chr) => `\\${chr}`) .join("|"); const notSafe = new RegExp(`[^${safe}]`, "g"); return value.replace(notSafe, encodeURIComponent); }, };
1.34375
1
dist/database-classes/table.js
MR-DS-20/my-quick-sql
1
15990484
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Table = void 0; /** * Represents the tables held in the SQL database, used in queryBuilders to create SQL statements */ class Table { /** * * @param database - Name of the database * @param name - Name of the table */ constructor(database, name) { this.database = database; this.name = name; } } exports.Table = Table;
1.03125
1
www/lib/vue-onsenui/esm/components/VOnsNavigator.js
yunosuke01/OWC02
0
15990492
import _Object$assign from 'babel-runtime/core-js/object/assign'; import _setImmediate from 'babel-runtime/core-js/set-immediate'; import _extends from 'babel-runtime/helpers/extends'; import _Promise from 'babel-runtime/core-js/promise'; // // // // // // // // // // // // // // import 'onsenui/esm/elements/ons-navigator'; import { hasOptions, selfProvider, deriveEvents, deriveDBB } from '../mixins'; var __script__ = { name: 'v-ons-navigator', mixins: [hasOptions, selfProvider, deriveEvents, deriveDBB], props: { pageStack: { type: Array, required: true }, popPage: { type: Function, default: function _default() { this.pageStack.pop(); } } }, methods: { isReady: function isReady() { if (this.hasOwnProperty('_ready') && this._ready instanceof _Promise) { return this._ready; } return _Promise.resolve(); }, onDeviceBackButton: function onDeviceBackButton(event) { if (this.pageStack.length > 1) { this.popPage(); } else { event.callParentHandler(); } }, _findScrollPage: function _findScrollPage(page) { var nextPage = page._contentElement.children.length === 1 && this.$ons._ons._util.getTopPage(page._contentElement.children[0]); return nextPage ? this._findScrollPage(nextPage) : page; }, _eachPage: function _eachPage(start, end, cb) { for (var i = start; i < end; i++) { cb(this.$children[i].$el); } }, _reattachPage: function _reattachPage(pageElement) { var position = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var restoreScroll = arguments[2]; this.$el.insertBefore(pageElement, position); restoreScroll instanceof Function && restoreScroll(); pageElement._isShown = true; }, _redetachPage: function _redetachPage(pageElement) { pageElement._destroy(); return _Promise.resolve(); }, _animate: function _animate(_ref) { var _this = this; var lastLength = _ref.lastLength, currentLength = _ref.currentLength, lastTopPage = _ref.lastTopPage, currentTopPage = _ref.currentTopPage, restoreScroll = _ref.restoreScroll; var pushedOptions = this.pageStack[this.pageStack.length - 1].onsNavigatorOptions || currentTopPage.__vue__.onsNavigatorOptions || {}; // Push if (currentLength > lastLength) { var isReattached = false; if (lastTopPage.parentElement !== this.$el) { this._reattachPage(lastTopPage, this.$el.children[lastLength - 1], restoreScroll); isReattached = true; lastLength--; } this._eachPage(lastLength, currentLength, function (el) { el.style.visibility = 'hidden'; }); this._eachPage(lastLength, currentLength - 1, function (el) { el.pushedOptions = pushedOptions; }); return this.$el._pushPage(_extends({}, pushedOptions, { leavePage: lastTopPage })).then(function () { _setImmediate(function () { _this._eachPage(lastLength, currentLength, function (el) { el.style.visibility = ''; }); _this._eachPage(lastLength - 1, currentLength - 1, function (el) { el.style.display = 'none'; }); }); if (isReattached) { _this._redetachPage(lastTopPage); } }); } // Pop if (currentLength < lastLength) { this._reattachPage(lastTopPage, null, restoreScroll); return this.$el._popPage({}, function () { return _this._redetachPage(lastTopPage); }); } // Replace page currentTopPage.style.visibility = 'hidden'; this._reattachPage(lastTopPage, currentTopPage, restoreScroll); return this.$el._pushPage(_extends({}, pushedOptions, { _replacePage: true })).then(function () { return _this._redetachPage(lastTopPage); }); }, _checkSwipe: function _checkSwipe(event) { if (this.$el.hasAttribute('swipeable') && event.leavePage !== this.$el.lastChild && event.leavePage === this.$children[this.$children.length - 1].$el) { this.popPage(); } } }, watch: { pageStack: function pageStack(after, before) { if (this.$el.hasAttribute('swipeable') && this.$children.length !== this.$el.children.length) { return; } var propWasMutated = after === before; // Can be mutated or replaced var lastTopPage = this.$children[this.$children.length - 1].$el; var scrollElement = this._findScrollPage(lastTopPage); var scrollValue = scrollElement.scrollTop || 0; this._pageStackUpdate = { lastTopPage: lastTopPage, lastLength: propWasMutated ? this.$children.length : before.length, currentLength: !propWasMutated && after.length, restoreScroll: function restoreScroll() { return scrollElement.scrollTop = scrollValue; } }; // this.$nextTick(() => { }); // Waits too long, updated() hook is faster and prevents flickerings } }, updated: function updated() { if (this._pageStackUpdate) { var currentTopPage = this.$children[this.$children.length - 1].$el; var _pageStackUpdate = this._pageStackUpdate, lastTopPage = _pageStackUpdate.lastTopPage, currentLength = _pageStackUpdate.currentLength; var _pageStackUpdate2 = this._pageStackUpdate, lastLength = _pageStackUpdate2.lastLength, restoreScroll = _pageStackUpdate2.restoreScroll; currentLength = currentLength === false ? this.$children.length : currentLength; if (currentTopPage !== lastTopPage) { this._ready = this._animate({ lastLength: lastLength, currentLength: currentLength, lastTopPage: lastTopPage, currentTopPage: currentTopPage, restoreScroll: restoreScroll }); } else if (currentLength !== lastLength) { currentTopPage.updateBackButton(currentLength > 1); } lastTopPage = currentTopPage = this._pageStackUpdate = null; } } }; var render = function render() { var _vm = this;var _h = _vm.$createElement;var _c = _vm._self._c || _h; return _c('ons-navigator', _vm._g({ domProps: { "options": _vm.options }, on: { "postpop": function postpop($event) { if ($event.target !== $event.currentTarget) { return null; } _vm._checkSwipe($event); } } }, _vm.unrecognizedListeners), [_vm._t("default", _vm._l(_vm.pageStack, function (page) { return _c(page, _vm._g(_vm._b({ key: page.key || page.name, tag: "component" }, 'component', page.onsNavigatorProps, false), _vm.unrecognizedListeners)); }))], 2); }; var staticRenderFns = []; var __template__ = { render: render, staticRenderFns: staticRenderFns }; export default _Object$assign({}, __script__, __template__);
1.5625
2
routes/html-routes.js
angelinama/wine-log
1
15990500
const db = require("../models"); const isAuthenticated = require("../config/middleware/isAuthenticated"); module.exports = (app) => { app.get("/", (req, res) => { res.render("../views/init.handlebars"); }); app.get("/login", (req, res) => { if (req.user) { res.redirect("/welcome"); } res.render("../views/login.handlebars"); }); app.get("/signup", (req, res) => { if (req.user) { res.redirect("/welcome"); } res.render("../views/signup.handlebars"); }); //render the welcome page in browser app.get("/welcome", isAuthenticated, (req, res) => { res.render("../views/welcome.handlebars"); }); //render the winestart page in browser app.get("/winestart", (req, res) => { res.render("../views/winestart.handlebars"); }); //render the wineentry page in browser app.get("/wineentry", (req, res) => { res.render("../views/wineentry.handlebars"); }); //render the bucketlist page in browser app.get("/bucketlist", (req, res) => { db.Bucketlist.findAll({ where: { user_id: req.user.id, }, include: [db.Wine], }).then((data) => { console.log( data.map((entry) => { return entry.dataValues.Wine.dataValues; }) ); res.render("../views/bucketlist.handlebars", { wines: data.map((entry) => { return entry.dataValues.Wine.dataValues; }), }); }); }); //render the wineentry page in browser app.get("/winehistory", (req, res) => { db.History.findAll({ where: { user_id: req.user.id, }, include: [db.Wine], }) .then((data) => { console.log( data.map((entry) => { return entry.dataValues.Wine.dataValues; // { // wine_name: entry.dataValues.Wine.dataValues.wine_name, // wine_id: entry.dataValues.Wine.dataValues.id, // history_id: entry.dataValues.id, // }; }) ); res.render("../views/winehistory.handlebars", { wines: data.map((entry) => { return entry.dataValues.Wine.dataValues; // { // wine_name: entry.dataValues.Wine.dataValues.wine_name, // wine_id: entry.dataValues.Wine.dataValues.id, // history_id: entry.dataValues.id, // }; }), }); }) .catch((error) => { console.log(error); }); }); //render the winefavorites page in browser app.get("/favorites", (req, res) => { db.History.findAll({ where: { user_id: req.user.id, favorite: true, }, include: [db.Wine], }) .then((data) => { console.log( data.map((entry) => { return entry.dataValues.Wine.dataValues; }) ); res.render("../views/winehistory.handlebars", { wines: data.map((entry) => { return entry.dataValues.Wine.dataValues; }), favorite: true, }); }) .catch((error) => { console.log(error); }); }); //render the winerate page in browser app.get("/winerate-:wineId", (req, res) => { res.render("../views/winerate.handlebars", { wineId: req.params.wineId }); }); app.get("/winesummary-:wineId", (req, res) => { res.render("../views/wineSummary.handlebars", { wineId: req.params.wineId, }); }); };
1.351563
1
static/helper.js
benccalcyxzfi/cs50w-chat
5
15990508
function getCookie(cookie_name) { var name = cookie_name + "="; var decodedCookie = decodeURIComponent(document.cookie); var list_cookies = decodedCookie.split(';'); for(var i = 0; i <list_cookies.length; i++) { var cookie = list_cookies[i]; while (cookie.charAt(0) == ' ') { cookie = cookie.substring(1); } if (cookie.indexOf(name) == 0) { return cookie.substring(name.length, cookie.length); } } return ""; }
1.742188
2
events/guildCreate.js
illusion-discordbot/illusion
0
15990516
const mongoose = require('mongoose') const Guild = require('../models/guild') module.exports = async (client, guild) => { client.logger.cmd( `[GUILD JOIN] ${guild.name} (${guild.id}) added the bot. Owner: ${guild.owner.user.tag} (${guild.owner.user.id})` ) guild = new Guild({ _id: mongoose.Types.ObjectId(), guildID: guild.id, guildName: guild.name, prefix: '-', }) guild .save() // .then(result => ) .catch((err) => client.logger.error(err)) }
1.234375
1
resources/assets/js/app.js
abisalazar1/PictureSlider
0
15990524
window.$ = window.jQuery = require("jQuery"); require('./PictureSlider'); require('./animationTracker');
0.292969
0
api/src/config/database.js
Flgc/pa2021-api-venom
0
15990532
/** * Arquivo: src/config/database.js * Descrição: arquivo responsável pelas 'connectionStrings da aplicação: PostgreSQL. * Data: 23/02/2021 */ // ==> Método responsável por permitir a conecção com a base de dados const { Pool } = require('pg'); const dotenv = require('dotenv'); dotenv.config(); // ==> Conexão com a Base de Dados: const pool = new Pool({ connectionString: process.env.DATABASE_URL }); pool.on('connect', () => { console.log('Base de Dados conectado com sucesso!'); }); module.exports = { query: (text, params) => pool.query(text, params), };
1.289063
1
posts/posts.component.js
Chimaytric/angular_starter
0
15990540
function PostsController(postsData){ console.log('Posts controller'); var vm = this; vm.params = { start: 1, number: 10, max: 100 } vm.data = []; vm.getPosts = function(nextPage){ if(nextPage && (vm.params.start + vm.params.number) <= vm.params.max) vm.params.start = vm.params.start + vm.params.number; for(var i = vm.params.start; i < (vm.params.start + vm.params.number); i++){ postsData.getPost(i).then(function(post){ postsData.getPostAuthor(post.userId).then(function(user){ post.userName = user.username; }); postsData.getPostComments(post.id).then(function(comments){ post.comments = comments; }); vm.data[post.id - 1] = post; }); } } } PostsController.$inject = ['postsData']; angular .module('demoApp.postsComponent', []).component('postsComponent', { templateUrl: 'posts/posts.component.html', controller: PostsController, controllerAs: "postsCtrl", require: { parent: '^rootComponent' }, bindings: {} }) .factory('postsData', function($http){ return{ getPost: function(postId){ var urlRoot = 'https://jsonplaceholder.typicode.com/posts/'; return $http({ method: 'GET', url: urlRoot+postId }).then(function(response){ return response.data; }).catch(function(response){ console.log(response.status); console.log(response.statusText); return response; }); }, getPostAuthor: function(authorId){ var urlRoot = 'https://jsonplaceholder.typicode.com/users/'; return $http({ method: 'GET', url: urlRoot+authorId }).then(function(response){ return response.data; }).catch(function(response){ console.log(response.status); console.log(response.statusText); return response; }); }, getPostComments: function(postId){ var urlRoot = 'https://jsonplaceholder.typicode.com/posts/' return $http({ method: 'GET', url: urlRoot+postId+'/comments' }).then(function(response){ return response.data; }).catch(function(response){ console.log(response.status); console.log(response.statusText); return response; }); } } });
1.726563
2
lib/ejs.js
npkgz/koa-magic
0
15990548
const _ejs = require('ejs'); const _fs = require('fs-magic'); const _path = require('path'); module.exports = async function ejs(koa, opt={}){ // apply default options const options = Object.assign({ root: null, strict: true, localsName: 'vars', payloadFilter: function(p){ return p} }, opt); // valid view path ? if (!(await _fs.isDirectory(options.root))){ throw new Error('view base path is not a directory - ' + options.root); } // add render function to context koa.context.render = function(view, payload={}){ // reference to current context instance const ctx = this; return new Promise(function(resolve, reject){ // generate full view name const filename = _path.join(options.root, view + '.ejs'); // add koa context payload.ctx = ctx; // render ejs file // inject additional payloads _ejs.renderFile(filename, options.payloadFilter(payload, ctx), options, (err, html) => { if (err){ reject(err); }else{ // send content ctx.type = 'html'; ctx.body = html; resolve(); } }); }); } }
1.34375
1
src/components/_dashboard/educations/Files.js
haydenpt/TAMUHack-frontend
0
15990556
import { filter, identity } from "lodash"; import { useState } from "react"; // material import { Card, Table, Stack, Button, TableRow, TableBody, TableCell, Typography, TableContainer, TablePagination, } from "@material-ui/core"; import VisibilityIcon from "@material-ui/icons/Visibility"; import { fDateTime } from "src/utils/formatTime.js"; // components import Page from "src/components/Page"; // import Label from "../../../../components/Label"; import Scrollbar from "src/components/Scrollbar"; import SearchNotFound from "src/components/SearchNotFound"; import { getMimeType, getIcon } from "src/utils/myutils"; import TableHeaderFile from "./TableHeaderFile"; // ---------------------------------------------------------------------- // utils import { seeFile } from "src/google-drive-api/database"; import { useAuth } from "src/authentication/AuthContext.js"; import { formatNumber } from "src/utils/myutils.js"; import FileTableTool from "./FileTableToolBar"; // ---------------------------------------------------------------------- const TABLE_HEAD = [ { id: "mimeType", label: "Type", alignRight: false }, { id: "name", label: "Name", alignRight: false }, { id: "createdtime", label: "Created Time", alignRight: false }, { id: "modifiedTime", label: "Mofified Time", alignRight: false }, { id: "size", label: "Size", alignRight: false }, { id: "" }, ]; // ---------------------------------------------------------------------- function descendingComparator(a, b, orderBy) { if (b[orderBy] < a[orderBy]) { return -1; } if (b[orderBy] > a[orderBy]) { return 1; } return 0; } function getComparator(order, orderBy) { return order === "desc" ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy); } function applySortFilter(array, comparator, query) { const stabilizedThis = array.map((el, index) => [el, index]); stabilizedThis.sort((a, b) => { const order = comparator(a[0], b[0]); if (order !== 0) return order; return a[1] - b[1]; }); if (query) { return filter( array, (_user) => _user.name.toLowerCase().indexOf(query.toLowerCase()) !== -1 ); } return stabilizedThis.map((el) => el[0]); } // ---------------------------------------------------------------------- export default function Files({ files }) { const [page, setPage] = useState(0); const [order, setOrder] = useState("asc"); const [selected, setSelected] = useState([]); const [orderBy, setOrderBy] = useState("name"); const [filterName, setFilterName] = useState(""); const [rowsPerPage, setRowsPerPage] = useState(10); const handleRequestSort = (event, property) => { const isAsc = orderBy === property && order === "asc"; setOrder(isAsc ? "desc" : "asc"); setOrderBy(property); }; const handleSelectAllClick = (event) => { if (event.target.checked) { const newSelecteds = files.map((n) => n.name); setSelected(newSelecteds); return; } setSelected([]); }; const handleClick = (event, name) => { const selectedIndex = selected.indexOf(name); let newSelected = []; if (selectedIndex === -1) { newSelected = newSelected.concat(selected, name); } else if (selectedIndex === 0) { newSelected = newSelected.concat(selected.slice(1)); } else if (selectedIndex === selected.length - 1) { newSelected = newSelected.concat(selected.slice(0, -1)); } else if (selectedIndex > 0) { newSelected = newSelected.concat( selected.slice(0, selectedIndex), selected.slice(selectedIndex + 1) ); } setSelected(newSelected); }; const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; const handleFilterByName = (event) => { setFilterName(event.target.value); }; const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - files.length) : 0; const filteredUsers = applySortFilter( files, getComparator(order, orderBy), filterName ); const isUserNotFound = filteredUsers.length === 0; const { setLoading } = useAuth(); const viewFile = async (fileId, mimeType, name) => { setLoading(true); const res = await seeFile(fileId, getMimeType(mimeType)); setTimeout(() => { window.open(`${res.data}`, "_blank"); setLoading(false); }, 1000); }; return ( <Page title="User | Minimal-UI"> <Card style={{ borderRadius: 3 }}> <FileTableTool numSelected={selected.length} filterName={filterName} onFilterName={handleFilterByName} /> <Scrollbar> <TableContainer sx={{ minWidth: 800 }}> <Table> <TableHeaderFile order={order} orderBy={orderBy} headLabel={TABLE_HEAD} rowCount={filteredUsers.length} numSelected={selected.length} onRequestSort={handleRequestSort} onSelectAllClick={handleSelectAllClick} /> <TableBody> {filteredUsers .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map((row) => { const { id, name, mimeType, createdTime, modifiedTime, size, } = row; const isItemSelected = selected.indexOf(name) !== -1; return ( <TableRow hover key={id} tabIndex={-1} role="checkbox" selected={isItemSelected} aria-checked={isItemSelected} > <TableCell align="left" style={{ padding: "0px 16px" }}> {getIcon(mimeType)} </TableCell> <TableCell component="th" scope="row" padding="0px 16px" > <Stack direction="row" alignItems="center" spacing={2} > <Typography variant="subtitle2" noWrap> {name} </Typography> </Stack> </TableCell> <TableCell align="left" style={{ padding: "0px 16px" }}> {fDateTime(createdTime)} </TableCell> <TableCell align="left" style={{ padding: "0px 16px" }}> {fDateTime(modifiedTime)} </TableCell> <TableCell align="left" style={{ padding: "0px 16px" }}> {formatNumber(size)} kb </TableCell> <TableCell align="left" style={{ padding: 7 }}> <Button variant="outlined" color="primary" size="small" startIcon={<VisibilityIcon />} onClick={() => viewFile(id, mimeType, name)} style={{ padding: 0 }} > view </Button> </TableCell> </TableRow> ); })} {emptyRows > 0 && ( <TableRow style={{ height: 53 * emptyRows }}> <TableCell colSpan={6} /> </TableRow> )} </TableBody> {isUserNotFound && ( <TableBody> <TableRow> <TableCell align="center" colSpan={6} sx={{ py: 3 }}> <SearchNotFound searchQuery={filterName} /> </TableCell> </TableRow> </TableBody> )} </Table> </TableContainer> </Scrollbar> <TablePagination rowsPerPageOptions={[5, 10, 25]} component="div" count={files.length} rowsPerPage={rowsPerPage} page={page} onPageChange={handleChangePage} onRowsPerPageChange={handleChangeRowsPerPage} /> </Card> </Page> ); }
1.515625
2
script.js
anna-podhajska/api-interaction
2
15990564
$(document).ready(function() { // function mouseIn() { // $('.newProverb').css('font-size', '3rem'); // }; // function mouseOut() { // $('.newProverb').css('font-size', ''); // }; // // $('.newProverb').mouseenter(mouseIn).mouseleave(mouseOut); getProverb(); }); //on click function getProverb() { $(document).ready(function() { $.ajax({ url: "https://eda-te-reo.herokuapp.com/api/proverbs" }).then(function(data) { $('.pSource').html(data.source); $('.pTranslation').html(data.translation); // random background color: var newColor = pickRandomColor(); $("body").css("background-color",newColor); $(".pSource").css("color",newColor); $("footer").css("background-color",newColor); // ------- }); }); }; // random background color function: function pickRandomColor() { var colors= [ "#333333", "#444444", "#666666", "#888888", "#999999", "#222222", "#181818", "#ce5a57", "#57a5a3", "#e1b16a", "#777c76", "#444c5c", "#839aa4" ] var colorIndex = Math.floor(Math.random()*colors.length); return colors[colorIndex]; }
1.507813
2
scripts/generate-sitemap.js
filfreire/alejandrocelaya.blog
1
15990572
const sitemap = require("nextjs-sitemap-generator"); const config = require('../config/config'); const outDir = `${__dirname}/../out`; sitemap({ baseUrl: config.SITE_URL, pagesDirectory: outDir, targetDirectory: outDir, ignoredExtensions: ['js', 'map', 'ico', 'xml', 'txt'], ignoredPaths: ['[fallback]', 'assets', '404'], ignoreIndexFiles: true, });
1.023438
1
library/Item.js
Wack0/pokelib
1
15990580
define( [ 'virtjs', './utilities' ], function ( Virtjs, utilities ) { /** * @class Item * * A class managing a single item. * * Since items are defined in the ROM, and since the ROM is read-only, it is not possible to change these values. */ return Virtjs.ClassUtil.extend( { initialize : function ( pokelib, index ) { this._pokelib = pokelib; this._index = index; this._nameBank = 0x01; if ( this._pokelib.version[ 0 ] == "R/B" ) { if ( [ "IT", "FR", "DE" ].indexOf( this._pokelib.version[ 1 ] ) != -1 ) this._baseNameAddress = 0x472D; else this._baseNameAddress = 0x472B; } else if ( this._pokelib.version[ 0 ] == "R/G" /* jp */ ) this._baseNameAddress = 0x433F; else if ( this._pokelib.version[ 0 ] == "Blue" /* jp */ ) this._baseNameAddress = 0x4733; else if ( this._pokelib.version[ 0 ] == "Yellow" ) { if ( this._pokelib.isJapan( ) ) this._baseNameAddress = 0x45C4; else if ( [ "DE", "ES", "FR", "IT" ].indexOf ( this._pokelib.version[ 1 ] ) != -1 ) this._baseNameAddress = 0x45b8; else if ( this._pokelib.version[ 1 ] == "EN" ) this._baseNameAddress = 0x45b7; else if ( this._pokelib.isJapan( ) ) this._baseNameAddress = 0x45c4; } }, /** */ index : function ( ) { return this._index; }, /** * Return the item's name. * * @return {String} The item name. */ name : function ( ) { if ( this._index >= 0xc4 ) { // this item is a TM/HM // todo: localisation? if ( this._index <= 0xc8 ) { return "HM0" + ( this._index - 0xc3 ); } var machNum = this._index - 0xc8; if ( machNum < 10 ) return "TM0" + machNum; return "TM" + machNum; } return this._pokelib.bankSwitch( this._nameBank, function ( ) { var address = this._baseNameAddress; var realIndex = ( this._index - 1 ) & 0xff; for ( var t = 0, T = realIndex; t < T; ++ t ) address += this._pokelib.readPds( address ).length; return utilities.pdsToUtf8( this._pokelib.version[ 1 ], this._pokelib.readPds( address ) ); }.bind( this ) ); } } ); } );
1.515625
2
blog-viewer/.eslintrc.js
pradel/sigle
288
15990588
module.exports = { extends: [ 'plugin:@typescript-eslint/recommended', 'prettier', 'plugin:prettier/recommended', 'plugin:@next/next/recommended', 'next/core-web-vitals', ], rules: { '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/explicit-member-accessibility': 'off', '@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/no-unused-vars': 2, '@typescript-eslint/no-use-before-define': 'off', }, };
0.484375
0
chrome/js/components/Editor.js
harvyso/yez
140
15990596
var Editor = absurd.component('Editor', { html: { '.dialog': { '.content': { '.info': '<i class="fa fa-arrow-circle-o-right"></i> <% title %>', '.inner.editor': [ { 'textarea' : '<% initialContent %>' } ], '.actions': [ { 'a[href="#" data-absurd-event="click:result:ok" class="button"]': '<i class="fa fa-check-circle-o"></i> OK'}, { 'a[href="#" data-absurd-event="click:result:cancel" class="button"]': '<i class="fa fa-times-circle-o"></i> Cancel'} ] } } }, result: function(e, res) { e.preventDefault(); if (this.callback && res === 'ok') this.callback(this.qs('textarea').value); document.querySelector('body').removeChild(this.populate().el); }, constructor: function(cb, content, title) { var self = this; this.initialContent = content; this.title = title; this.callback = cb; this.populate(); document.querySelector('body').appendChild(this.populate().el); setTimeout(function() { var ta = self.qs('textarea'); ta.focus(); ta.setSelectionRange(ta.value.length, ta.value.length); }, 400); } });
1.460938
1
backend/dist/services/parcelService copy.js
moritzploss/polychat
1
15990604
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var logging_1 = require("../logging"); var webSocketService_1 = require("./webSocketService"); var repository_1 = require("./repository"); var login_1 = require("../controllers/login"); var blueprints_1 = require("../parcels/blueprints"); var logUnknownParcel = function (parcel) { logging_1.logger.info({ message: "received parcel of unknown type " + parcel.type, parcel: parcel, }); }; var ParcelService = /** @class */ (function () { function ParcelService(wsService, repositoryService) { var _this = this; this.deliverMessageHistoryParcel = function (userId) { _this.repository.getUserMessages(userId, function (messages) { return (_this.deliver(blueprints_1.messageHistoryParcel(userId, messages))); }); }; this.deliverContactListParcel = function (userId) { return _this.repository.getUserContacts(userId, function (contacts) { return _this.repository.getUsersById(contacts, function (users) { return _this.deliver(blueprints_1.contactListParcel(userId, users.map(login_1.toCredentials))); }); }); }; this.broadcastContactListUpdateToUserContacts = function (userId) { repository_1.repository.getUserContacts(userId, function (contacts) { contacts.forEach(function (contact) { return _this.deliverContactListParcel(contact); }); }); }; this.broadCast = function (parcel) { _this.webSocketService .getAllWebSockets() .forEach(function (_a) { var webSocket = _a.webSocket; return webSocket.send(JSON.stringify(parcel)); }); }; this.deliver = function (parcel) { _this.webSocketService .getWebSocketsByUserId(parcel.receiverId) .map(function (_a) { var webSocket = _a.webSocket; return webSocket; }) .forEach(function (webSocket) { return webSocket.send(JSON.stringify(parcel)); }); }; this.receive = function (parcel) { switch (parcel.type) { case 'DIRECT MESSAGE': _this.repository.saveDirectMessage(parcel); return _this.deliver(parcel); default: return logUnknownParcel(parcel); } }; this.webSocketService = wsService; this.repository = repositoryService; } return ParcelService; }()); exports.ParcelService = ParcelService; var parcelService = new ParcelService(webSocketService_1.webSocketService, repository_1.repository); exports.parcelService = parcelService;
1.3125
1
auth/controller.js
kjelpw/travis_test_backend
0
15990612
/** Copyright 2019 University of Denver 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. */ 'use strict'; const CONFIG = require('../config/config'), VALIDATOR = require('validator'), TOKEN = require('../libs/tokens'), SERVICE = require('../auth/service'), USER = require('../users/model'); exports.login = function (req, res) { if (req.body !== undefined) { let username = req.body.username.trim(), password = req.body.password.trim(); if (username.length === 0) { res.status(401).send({ message: 'Authenticate failed. Please enter your DU ID.' }); return false; } else if (password.length === 0) { res.status(401).send({ message: 'Authenticate failed. Please enter your passcode.' }); return false; } else if (VALIDATOR.isNumeric(username) === false) { res.status(401).send({ message: 'Authenticate failed due to invalid username. Please enter a DU ID. i.e. 871******' }); return false; } else { SERVICE.authenticate(username, password, function (isAuth) { if (isAuth.auth === true) { let token = TOKEN.create(username); token = encodeURIComponent(token); let uid = username.trim(); /* check if user has access to repo */ USER.check_auth_user(username, function (result) { if (result.auth === true) { res.status(200).send({ message: 'Authenticated', redirect: '/dashboard/home?t=' + token + '&uid=' + result.data }); } else { res.status(401).send({ message: 'Authenticate failed.' }); } }); } else if (isAuth.auth === false) { res.status(401).send({ message: 'Authenticate failed.' }); } }); } } }; exports.login_form = function (req, res) { res.render('login', { host: CONFIG.host, message: '', username: '' }); };
1.5625
2
vendor/livewire/livewire/js/DirectiveManager.js
haba-sensei/abogados
964
15990620
import MessageBus from "./MessageBus" export default { directives: new MessageBus, register(name, callback) { if (this.has(name)) { throw `Livewire: Directive already registered: [${name}]` } this.directives.register(name, callback) }, call(name, el, directive, component) { this.directives.call(name, el, directive, component) }, has(name) { return this.directives.has(name) }, }
0.992188
1
packages/@sanity/form-builder/src/sanity/inputs/Slug.js
ebarahona/sanity
0
15990628
import slugify from 'speakingurl' import client from 'part:@sanity/base/client' import {SlugInput} from '../../index' // Default slugify for Sanity export function sanitySlugify(type, slugSourceText, finalize = false) { const maxLength = (type.options && type.options.maxLength) || 200 const slugifyOpts = {truncate: maxLength, symbols: true} if (slugSourceText) { return slugify(slugSourceText, slugifyOpts) } return undefined } export function validateSlug(type, slug, myDocId) { let query if (myDocId) { query = `*[${type.name}.current == $slug && _id != $id]` } else { query = `*[${type.name}.current == $slug` } return client.fetch(query, {slug: slug, id: myDocId}) .then(results => { if (results[0]) { const foundDocId = results[0]._id return `There is already a document (${foundDocId}) ` + `in the dataset with the slug '${slug}'.` } return null }) } export default SlugInput.create({validate: validateSlug, slugify: sanitySlugify})
1.429688
1
test/api.test.js
Raphjacksun7/clipboard-healh-job-boards
0
15990636
const fetch = require("node-fetch"); const jobUtilities = require("../utils/jobs"); // general JOBS describe("GET jobs endpoint", () => { it("should get all jobs from every hospital", async () => { const searchObj = { search: "", selectedFilters: { job_type: [], work_schedule: [], experience: [], department: [], }, sorts: {}, }; const base64SearchObj = btoa(JSON.stringify(searchObj)); const url = `http://localhost:3000/api/jobs?search=${base64SearchObj}`; const res = await fetch(url); expect(res.status).toEqual(200); expect(res.body).not.toBeNull(); const data = await res.json(); expect(data.jobs.length).toEqual(20); }); }); // jobs with search describe("GET jobs - specific search:", () => { it("should get all jobs from every hospital that have 'blood'", async () => { const searchObj = { search: "blood", selectedFilters: { job_type: [], work_schedule: [], experience: [], department: [], }, sorts: {}, }; const base64SearchObj = btoa(JSON.stringify(searchObj)); const url = `http://localhost:3000/api/jobs?search=${base64SearchObj}`; const res = await fetch(url); expect(res.status).toEqual(200); expect(res.body).not.toBeNull(); const data = await res.json(); expect(data.jobs.length).toEqual(10); }); it("should get all jobs from every hospital that have 'Ambulatory Pacu Nurse'", async () => { const searchObj = { search: "Ambulatory Pacu Nurse", selectedFilters: { job_type: [], work_schedule: [], experience: [], department: [], }, sorts: {}, }; const base64SearchObj = btoa(JSON.stringify(searchObj)); const url = `http://localhost:3000/api/jobs?search=${base64SearchObj}`; const res = await fetch(url); expect(res.status).toEqual(200); expect(res.body).not.toBeNull(); const data = await res.json(); const jobs = data.jobs; expect(jobs.length).toEqual(2); expect(jobs[0].items.length).toEqual(1); expect(jobs[1].items.length).toEqual(1); const job1 = jobs[0].items[0]; const job2 = jobs[0].items[1]; expect(JSON.stringify(job1)).toContain("Ambulatory Pacu Nurse"); }); }); // jobs with filters describe("GET jobs - specific filters:", () => { it("should get all jobs from every hospital that are per-diem", async () => { const searchObj = { search: "", selectedFilters: { job_type: ["Per-Diem"], work_schedule: [], experience: [], department: [], }, sorts: {}, }; const base64SearchObj = btoa(JSON.stringify(searchObj)); const url = `http://localhost:3000/api/jobs?search=${base64SearchObj}`; const res = await fetch(url); expect(res.status).toEqual(200); expect(res.body).not.toBeNull(); const data = await res.json(); const jobs = data.jobs; expect(jobs.length).toEqual(13); expect(jobs[0].items.length).toEqual(2); expect(jobs[1].items.length).toEqual(2); const totalJobs = jobUtilities.sumJobsInSearch(jobs); expect(totalJobs).toEqual(22); }); it(`should get all jobs from every hospital that are: per-diem, night-shift, Experience = Intermediate department: ["Pathology & Laboratory Medicine"]`, async () => { const searchObj = { search: "", selectedFilters: { job_type: ["Per-Diem"], work_schedule: ["Night shift"], experience: ["Intermediate"], department: ["Pathology & Laboratory Medicine"], }, sorts: {}, }; const base64SearchObj = btoa(JSON.stringify(searchObj)); const url = `http://localhost:3000/api/jobs?search=${base64SearchObj}`; const res = await fetch(url); expect(res.status).toEqual(200); expect(res.body).not.toBeNull(); const data = await res.json(); const jobs = data.jobs; expect(jobs.length).toEqual(2); expect(jobs[0].items.length).toEqual(1); expect(jobs[1].items.length).toEqual(1); const totalJobs = jobUtilities.sumJobsInSearch(jobs); expect(totalJobs).toEqual(2); const job1 = jobs[0].items[0]; const job2 = jobs[1].items[0]; expect(job1.job_title).toEqual("Oncology Nurse"); expect(job2.job_title).toEqual("LPN RN Telemetry"); }); }); // jobs with search and filters describe("GET jobs - specific search AND filters:", () => { it(`should get all jobs from every hospital that are: per-diem, night-shift, Experience = Intermediate department: ["Pathology & Laboratory Medicine"] AND that have the text "onco" `, async () => { const searchObj = { search: "onco", selectedFilters: { job_type: ["Per-Diem"], work_schedule: ["Night shift"], experience: ["Intermediate"], department: ["Pathology & Laboratory Medicine"], }, sorts: {}, }; const base64SearchObj = btoa(JSON.stringify(searchObj)); const url = `http://localhost:3000/api/jobs?search=${base64SearchObj}`; const res = await fetch(url); expect(res.status).toEqual(200); expect(res.body).not.toBeNull(); const data = await res.json(); const jobs = data.jobs; expect(jobs.length).toEqual(1); expect(jobs[0].items.length).toEqual(1); const totalJobs = jobUtilities.sumJobsInSearch(jobs); expect(totalJobs).toEqual(1); const job1 = jobs[0].items[0]; expect(job1.job_title).toEqual("Oncology Nurse"); }); }); // jobs with a search obj that doesn't match spec describe("GET jobs - queries that must fail", () => { it(`tries to get jobs with a bad query object`, async () => { const searchObj = { search: "onco", sorts: {}, }; const base64SearchObj = btoa(JSON.stringify(searchObj)); const url = `http://localhost:3000/api/jobs?search=${base64SearchObj}`; const res = await fetch(url); expect(res.status).toEqual(406); expect(res.body).not.toBeNull(); const data = await res.json(); expect(data.message).toEqual( "Your search object is not acceptable or does not have required fields" ); }); it(`tries to get jobs with filters that do not exist`, async () => { const searchObj = { search: "", selectedFilters: { job_type: ["Per-iem"], work_schedule: ["Night hift"], experience: ["Intemediate"], department: ["pathaboratory Medicine"], }, sorts: {}, }; const base64SearchObj = btoa(JSON.stringify(searchObj)); const url = `http://localhost:3000/api/jobs?search=${base64SearchObj}`; const res = await fetch(url); expect(res.status).toEqual(406); expect(res.body).not.toBeNull(); const data = await res.json(); expect(data.message).toEqual( "Your search filters contain filters that do not exist" ); }); });
1.601563
2
example-grunt/play-1/tasks/xml-parser.js
raoul2000/js-playground
1
15990644
"use strict"; var entityResolver = require('./entity-resolver').entityResolver, DOMParser = require('xmldom').DOMParser; /** * Parse an XML string that contains no entity and returns a result object * @param {string} strXML The XML string to parse * @return {object} (see description) */ function parseNoEntities(strXML) { try { var parseErrors = { "warning" : [], "error" : [], "fatal" : [] }; var dom = new DOMParser({ errorHandler:{ warning : function(w){ parseErrors.warning.push(w); }, error : function(w){ parseErrors.error.push(w); }, fatalError: function(w){ parseErrors.fatal.push(w); } } }).parseFromString(strXML); // consider both error and fatal as severe : no DOM is returned in this case if(parseErrors.fatal.length !== 0 || parseErrors.error.length !== 0 ) { throw new Error("".concat( parseErrors.error.join("\n"), parseErrors.fatal.join("\n") )); } return { "document" : dom, "success" : true }; } catch (e) { return { "document" : null, "success" : false, "error" : e }; } } /** * Parse and returns a Document from the XML string passed as argument. * If the XML string contains entities, they are resolved priori to parse * using the "entities" hash map. * In case of success, this function returns : * { * "document" : <the DOM>, * "success" : true * } * In case of error : * { * "document" : null, * "success" : false, * "error" : {} * } * * @param {string} strXML the XML string to parse * @param {object} entities hash where key are entity name and value is entity value * @param {function} entityResolverErrorHandler entity resolution error handler * @return {object} the result of the parse as an object. */ function parse( strXML , entities, entityResolverErrorHandler) { var result = { "document": null, "success" : true }; if( entities ) { var missingEntities = {}; // use only by private error handler // prepare Entity Resolver Error Handler var entErrorHandler, isPrivateErrorHandler; if(typeof entityResolverErrorHandler === "function" ) { isPrivateErrorHandler = false; entErrorHandler = entityResolverErrorHandler; } else { isPrivateErrorHandler = true; entErrorHandler = function(missingEntityName){ missingEntities[missingEntityName] = true; }; } // Performing entity resolution. If a custom error handkler has been // provided, it may throw an exception to stop the parse process. // try { strXML = entityResolver(strXML, entities, entErrorHandler); } catch (e) { result.success = false; result.error = e; } if( isPrivateErrorHandler && Object.keys(missingEntities).length !== 0) { // there are unresolved entities !! result.success = false; result.error = { "message" : "missing entities : " + Object.keys(missingEntities).join(',') }; } } if(result.success === true) { result = parseNoEntities(strXML); } return result; } exports.parse = parse;
1.828125
2
src/functions/saveEmeraldConfig.js
L1lith/Emerald-Templates
0
15990652
const { join, basename, exists } = require('path') const { writeJSON } = require('fs-extra') async function saveEmeraldConfig(configPath, config) { if (typeof config != 'object' || config === null) throw new Error('Config must be an object') if (typeof configPath != 'string' || configPath.length < 1) throw new Error('Config path must be a non-empty string') if (!(await exists(configPath))) { if (basename(configPath) !== 'emerald-config.json') { configPath = join(configPath, 'emerald-config.json') if (await exists(configPath)) { // Do Nothing } else { throw new Error('Invalid Config Path') } } else { throw new Error('Invalid Config Path') } } await writeJSON(configPath, config) } module.exports = saveEmeraldConfig
1.328125
1
example/js/letter_arranger.js
nameofname/konami_letters
0
15990660
"use strict"; /** * Takes an array of line objects. Each line must have an upper and lower bound (for x OR y) and a function that * describes the relationship between x and y. * * Here are some examples of line configurations: * { * xLower : -10, * xUpper : 10, * equation : function (x) { return x + 1} * }, { * yLower : -20, * yUpper : 20, * equation : function (x) { return x + 1} * } * * Note* A line configuration cannot have both x and y boundaries. * * Using the public methods of the letter arranger, you will be able to re-arrange all the letters on the page to match * the lines you describe. * * @param lines */ var LetterArranger = function(lines) { var self = this; if (!lines) { throw new Error('You cannot initialize the LetterArranger without an array of lines.'); } this.lines = lines; // References to all of the wrapped letters on the page, and all the text nodes on the page: this.letters = []; this.textNodes = []; // The number of letters on the page: this.letterNum = null; // The offset for the current letter being assinged a point - starting at 0 and used as a place holder for when // iterating through all the letters on the page. this.assignmentOffset = 0; // A reference to the dancing letters interval: this.interval = null; // The width and height of the body document that you are dealing with. this.bodyHeight = null; this.bodyWidth = null; // The total letters assigned to a line: this.totalLettersUsed = 0; /** * Evaluate each of the passed in line descriptions, and prepare the document to be ... played with. * @private */ this.init = function() { var totalRange = 0; for (var n=0; n<this.lines.length; n++) { var line = this.lines[n]; // First get the range of the line based on either the x or y boundaries: if (line.hasOwnProperty('xLower') && line.hasOwnProperty('xUpper')) { line.range = line.xUpper - line.xLower; } else if (line.hasOwnProperty('yLower') && line.hasOwnProperty('yUpper')) { line.range = line.yUpper - line.yLower; // If the line has no bounds, then throw an error. } else { throw new Error('You must include either x or y boundaries for each line configuration passed'); } // Add a plot attribute to each line: this.lines[n].plot = []; // Add up the total range of all of the lines: totalRange += this.lines[n].range; } // Wrap all the letters in a span tag and get the returned list. this.letters = this._wrapLetters(); // Set the x y default position of each of the letters. this._positionLetters(); // Remove stylesheets and Add base styling to make this all possible: this._prepDocument(); this.letterNum = this.letters.length; // For each line, figure out how many letters should be assigned to that line: for (var i=0; i< this.lines.length; i++) { var linea = this.lines[i]; // The lines number of letters is the ratio of the lines range by the total range of all lines passed, // multiplied by the total number of letters in the document. linea.numLetters = Math.floor(this.letterNum * (linea.range / totalRange)); this.totalLettersUsed += linea.numLetters; } // Note * Since we are using Math.floor to calculate the numLetters - sometimes there will be a small remainder. // Check for this case and adjust: if (this.letterNum !== this.totalLettersUsed) { // Add the remainder letters to the last line: this.lines[this.lines.length - 1].numLetters += (this.letterNum - this.totalLettersUsed); this.totalLettersUsed += (this.letterNum - this.totalLettersUsed); } // Now that we have assigned all the letters to one line or another, figure out the interval for each line, // and create a plot for each line. for (var j=0; j< this.lines.length; j++) { var lineb = this.lines[j]; // Find the interval of each line based on the number of letters divided by the range: lineb.interval = lineb.range / lineb.numLetters; // For each function, invoke it for it's specified range along the specified interval: this._createPlot(lineb); } }; /** * Preps the document to be manipulated. Removes all stylesheets and adds some base styling: * @private */ this._prepDocument = function() { $('link').remove(); var styles = ''; styles += '<style>'; styles += 'html { min-height: 100%;}'; styles += 'body { position : absolute; min-width : 100%; min-height: 100%;}'; styles += 'div { transition: visibility: 5s;}'; styles += '</style>'; var style = $(styles); $('html > head').append(style); var width = document.getElementsByTagName('body')[0].offsetWidth; var height = document.getElementsByTagName('body')[0].offsetHeight; this.bodyHeight = height; this.bodyWidth = width; }; /** * @private */ this._positionLetters = function(){ $('.nerp').each(function(){ var position = $(this).offset(); $(this).data('top', position.top); $(this).data('left', position.left); $(this).css({left : $(this).data('left') + 'px', top : $(this).data('top')+ 'px'}); }); var styles = ''; styles += '<style>'; styles += '.nerp { position: absolute; transition: top 20s, left 20s, font-size 20s; transform: translate3d(0,0,0); }'; styles += '</style>'; var style = $(styles); $('html > head').append(style); // Now select all of the .nerp elements on the page, and remove them temporarily: var $nerps = $('.nerp').detach(); $('body').empty(); $('body').append($nerps); }; /** * Wrap each of the letters on the page in a span tag, and return a DOM reference to the letters on the page. * @private */ this._wrapLetters = function() { this._getTextNodes(document.getElementsByTagName('body')[0]); var nodeList = this.textNodes; for (var i=0; i<nodeList.length; i++){ var textArr = nodeList[i].nodeValue.split(''), parentElement = nodeList[i].parentElement; parentElement.removeChild(nodeList[i]); for (var x=0; x<textArr.length; x++) { // Do a double check here for empty string text nodes (do not use the empty strings in between // other full strings): if (textArr[x] !== ' ') { var newSpan = document.createElement('span'); newSpan.setAttribute('class', 'nerp'); newSpan.appendChild( document.createTextNode(textArr[x]) ); parentElement.appendChild( newSpan, textArr[x]); } } } return document.getElementsByClassName('nerp'); }; /** * Via StackOverflow. * User: * http://stackoverflow.com/users/515502/rahat-ahmed */ this._getTextNodes = function(element) { // Don't recurse into scripts, kill 'em. if (element.tagName === 'SCRIPT') { element.remove(); } else { if (element.childNodes.length > 0) { for (var i = 0; i < element.childNodes.length; i++) { self._getTextNodes(element.childNodes[i]); } } if (element.nodeType === Node.TEXT_NODE && element.nodeValue.trim() != '') { self.textNodes.push(element); } } }; /** * Creates the (x,y) coordinates for each of the letters in a given line based on the passed line configurations, * and the leg work done above. * Assigns the (x,y) coordinates to the letters allotted to the given line. * @param line * @private */ this._createPlot = function(line) { var numLetters = line.numLetters, interval = line.interval, lower = line.hasOwnProperty('xLower') ? line.xLower : line.yLower, equation = line.equation; // Now plot the points on the line based on the lower bound and the interval: for (var x=0; x < numLetters; x++) { var x1 = lower + (x * interval), y = equation(x1), // now find the coordinates relative to the width of the document, expecting that 0 is the midline of the // document on both the x and y axis relativeX = x1 + (this.bodyWidth / 2), relativeY = y + (this.bodyHeight / 2); var coordinates = [relativeX,relativeY]; line.plot.push(coordinates); this.letters[this.assignmentOffset].plotPoint = coordinates; this.assignmentOffset++; } }; /** * Stop the dance. */ this.stop = function() { clearInterval(this.interval); }; /** * Start moving the letters on the page according to CSS transitions, then according to an interval which will * flash all the letters different colors. */ this.startMoving = function() { var letters = self.letters; for (var i=0; i<letters.length; i++) { var letter = letters[i]; letter.style.left= letters[i].plotPoint[0] + 'px'; letter.style.top = letters[i].plotPoint[1] + 'px'; letter.style.fontSize = '20px'; // letter.addEventListener('webkitTransitionEnd', function(){ // letter.style.fontSize = '100px'; // }, true); } setTimeout(function(){ // Increase the font size (this is a transition as stated above) for (var j=0; j<letters.length; j++) { var letter = letters[j]; letter.style.fontSize = '100px'; } // Set an interval to flash a different color every half second. self.interval = setInterval(function(){ for (var k=0; k<letters.length; k++) { var letter = letters[k]; letter.style.color = self._newColor(); } }, 500); }, 20000); }; /** * Generate a new random RGB color. */ this._newColor = function() { var color = 'rgb('+ newNum() +','+ newNum() +','+ newNum() +')'; function newNum() { return Math.floor(Math.random() * 256 - 1); } return color; }; return this; };
2.875
3
Routes/user.js
raghavmathur1/DoubtHub
1
15990668
const express = require("express"); const router = express.Router(); const { logout, data, googleCallback, googleAuthenticate, signup, login, getUser, changePassword } = require("../Controllers/user"); router.route("/data").get(data); router.route("/logout").get(logout); router.route("/getUser").post(getUser); router.route("/signup").post(signup); router.route("/google/callback").get(googleCallback); router.route("/auth/google").get(googleAuthenticate); router.post("/auth/local", login); const { editProfile } = require("../Controllers/editUser"); router.route("/profile/edit").put(editProfile); router.route("/profile/changePassword").put(changePassword); module.exports = router;
0.933594
1
app/frontend/src/application/init.js
bencmitchell/teaching-vacancies
0
15990676
import ClipboardJS from 'clipboard'; import './jobseekers/init'; import './publishers/init'; import '../components/form/form'; document.addEventListener('DOMContentLoaded', () => { // lint disabled as would require changes to library script new ClipboardJS('.copy-to-clipboard'); // eslint-disable-line Array.from(document.getElementsByClassName('copy-to-clipboard')).forEach((el) => { el.addEventListener('click', (e) => { e.preventDefault(); }); }); });
1.054688
1
app/views/NotFoundPage/selectors.js
ThiagoFacchini/AvaEngine
0
15990684
// @flow import { createSelector } from 'reselect' // // Direct selector to the notFoundPage state domain // const selectNotFoundPageDomain = () => (state: Object) => state.notFoundPage // // Other specific selectors // // // Default selector used by NotFoundPage // const makeSelectNotFoundPage = () => createSelector( selectNotFoundPageDomain(), (substate) => substate ) export default makeSelectNotFoundPage export { selectNotFoundPageDomain, }
1.242188
1
api/controllers/v1/schemas/auth-schemas.js
cdjohnnatha/youtube-freetime-organizer
0
15990692
const { object, string } = require('yup'); const authEmailSchema = object().shape({ email: string().required().email(), password: string().required(), }); const signupSchema = object().shape({ first_name: string().required(), last_name: string().required(), auth_provider: object().shape({ email: string().required().email(), password: string().required().min(8), }), }); module.exports = { signupSchema, authEmailSchema, };
0.808594
1
test/specs/plugins/recordTypes/collectionobject/optionLists.spec.js
ray-lee/cspace-ui.js
4
15990700
import optionLists from '../../../../../src/plugins/recordTypes/collectionobject/optionLists'; chai.should(); describe('collectionobject record optionLists', () => { it('should export an object', () => { optionLists.should.be.an('object'); }); });
0.894531
1
src/utils/tests/pass.spec.js
hongily25/chess
33
15990708
import pass from '../pass' describe('#pass', () => { it('Pass value if true, otherwise empty string', () => { expect(pass(true, ['hello'])).toEqual(['hello']) expect(pass(true, { hello: 'world' })).toEqual({ hello: 'world' }) expect(pass(false, 'world')).toEqual('') expect(() => pass({}, ['hello'])).toThrow() expect(() => pass('', 'world')).toThrow() }) })
1.179688
1