hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
dbaa39b2452e1758a9908e9abcc77584cf7b0701
295
js
JavaScript
basic/sources/producer.js
adaschevici/router-dealer
4e5188bf31418b9b5258837e4a38fb991263fc41
[ "MIT" ]
null
null
null
basic/sources/producer.js
adaschevici/router-dealer
4e5188bf31418b9b5258837e4a38fb991263fc41
[ "MIT" ]
1
2021-05-11T05:41:42.000Z
2021-05-11T05:41:42.000Z
basic/sources/producer.js
adaschevici/router-dealer
4e5188bf31418b9b5258837e4a38fb991263fc41
[ "MIT" ]
null
null
null
const zmq = require('zeromq') async function run() { const sock = new zmq.Push() await sock.bind('tcp://127.0.0.1:3000') console.log('Producer bound to port 3000') while (true) { await sock.send('some work') await new Promise(resolve => setTimeout(resolve, 500)) } } run()
18.4375
58
0.644068
dbaad147102dbe270a364a90fbd82780620fb5df
348
js
JavaScript
hat/assets/js/apps/Iaso/routing/actions.js
ekhalilbsq/iaso
e6400c52aeb4f67ce1ca83b03efa3cb11ef235ee
[ "MIT" ]
29
2020-12-26T07:22:19.000Z
2022-03-07T13:40:09.000Z
hat/assets/js/apps/Iaso/routing/actions.js
ekhalilbsq/iaso
e6400c52aeb4f67ce1ca83b03efa3cb11ef235ee
[ "MIT" ]
150
2020-11-09T15:03:27.000Z
2022-03-07T15:36:07.000Z
hat/assets/js/apps/Iaso/routing/actions.js
ekhalilbsq/iaso
e6400c52aeb4f67ce1ca83b03efa3cb11ef235ee
[ "MIT" ]
4
2020-11-09T10:38:13.000Z
2021-10-04T09:42:47.000Z
import { push, replace } from 'react-router-redux'; import { createUrl } from 'bluesquare-components'; export function redirectTo(key, params) { return dispatch => dispatch(push(`${key}${createUrl(params, '')}`)); } export function redirectToReplace(key, params) { return dispatch => dispatch(replace(`${key}${createUrl(params, '')}`)); }
34.8
75
0.689655
dbac81f366da5784e8394fc3524cf43de8729bf9
2,399
js
JavaScript
index.js
cs-fullstack-2019-spring/frontend-halfday1-itayanna
198ecdc54622e8852d5759800f989057d8fc5aaf
[ "Apache-2.0" ]
null
null
null
index.js
cs-fullstack-2019-spring/frontend-halfday1-itayanna
198ecdc54622e8852d5759800f989057d8fc5aaf
[ "Apache-2.0" ]
null
null
null
index.js
cs-fullstack-2019-spring/frontend-halfday1-itayanna
198ecdc54622e8852d5759800f989057d8fc5aaf
[ "Apache-2.0" ]
null
null
null
//this code is pulling the button elements and making them count the score var p1Score= document.getElementById('p1score'); var p2Score= document.getElementById('p2score'); var p1Btn= document.getElementById('p1'); var p2Btn= document.getElementById('p2'); // the code that gets the mouse and keybord buttons working var mouseSettingBtn= document.getElementById('mouse'); var keyboardsettingBtn= document.getElementById('keyboard'); mouseSettingBtn.addEventListener("click", function () { p1Btn.addEventListener('click', updatep1score); p2Btn.addEventListener('click', updatep2score); }); // the functions that makes the scores change function updatep1score(){ p1Score.innerText= parseInt(p1Score.innerText)+1; console.log(1); winnercheck(); } function updatep2score(){ p2Score.innerText= parseInt(p2Score.innerText)+1; console.log(2); winnercheck(); } //this code makes the keybord setting work keyboardsettingBtn.addEventListener("click", function () { console.log('b'); document.addEventListener('keydown', function (e) { console.log(e.code); if (e.code==='KeyQ'){ updatep1score(); winnercheck() } }); document.addEventListener('keydown', function (e) { console.log(e.code); if (e.code==='KeyP'){ updatep2score(); winnercheck() } }) }); //this function checks wor a winner function winnercheck() { if (p1Score.innerText==='15'){ alert('Player 1 Wins!!'); p1Score.innerText='0'; p2Score.innerText='0'; } else if (p2Score.innerText==='15'){ alert('Player 2 wins!!'); p1Score.innerText='0'; p2Score.innerText='0'; } } //these variables pull the button elements aso i can use them in this javascript file var blue= document.getElementById('blue'); var red= document.getElementById('red'); var yellow= document.getElementById('yellow'); var backdrop= document.getElementsByTagName('body'); //these three event listensers turnes the background when button is pressed blue.addEventListener("click", function () { backdrop[0].style.backgroundColor='blue' }); red.addEventListener("click", function () { backdrop[0].style.backgroundColor='red' }); yellow.addEventListener("click", function () { backdrop[0].style.backgroundColor='yellow' });
21.230088
85
0.671113
dbac90db9a35c4c6f3dfe44c448b923dd5d262f4
597
js
JavaScript
components/hero.js
eomine/work-omine-net
b96f24cb4adab3ea174b78f7f44d63543b7ccefd
[ "MIT" ]
1
2021-05-07T22:02:22.000Z
2021-05-07T22:02:22.000Z
components/hero.js
eomine/work-omine-net
b96f24cb4adab3ea174b78f7f44d63543b7ccefd
[ "MIT" ]
null
null
null
components/hero.js
eomine/work-omine-net
b96f24cb4adab3ea174b78f7f44d63543b7ccefd
[ "MIT" ]
null
null
null
import Link from 'next/link'; import common from '../styles/common.module.css'; export default function Hero() { return ( <section className={common.box}> <h1 className={common.h3}> Eduardo Ōmine </h1> <p> Senior front-end developer<br/> React, Redux, Typescript </p> <p> <Link href="/about"> <a className={common.link}>About &rarr;</a> </Link> </p> <p> <Link href="/cv-eduardo-omine.pdf"> <a className={common.link}>CV &rarr;</a> </Link> </p> </section> ); }
22.111111
53
0.517588
dbad4134d3b99fa08623a0d217ffaa1fd823071a
3,115
js
JavaScript
app/assets/javascripts/views/dataset/dataset_create_chorus_view_sidebar.js
bornio/chorus
dddee70821d9f37bf8fca919ddc41f7204c689dd
[ "Apache-2.0" ]
null
null
null
app/assets/javascripts/views/dataset/dataset_create_chorus_view_sidebar.js
bornio/chorus
dddee70821d9f37bf8fca919ddc41f7204c689dd
[ "Apache-2.0" ]
null
null
null
app/assets/javascripts/views/dataset/dataset_create_chorus_view_sidebar.js
bornio/chorus
dddee70821d9f37bf8fca919ddc41f7204c689dd
[ "Apache-2.0" ]
1
2020-11-11T08:20:09.000Z
2020-11-11T08:20:09.000Z
chorus.views.CreateChorusViewSidebar = chorus.views.Sidebar.extend({ templateName: "dataset_create_chorus_view_sidebar", events: { "click button.create": "createChorusView", "click a.remove": "removeColumnClicked", "click img.delete": "removeJoinClicked", "click a.preview": "previewSqlLinkClicked" }, setup: function() { this.selectedHandle = chorus.PageEvents.subscribe("column:selected", this.addColumn, this); this.deselectedHandle = chorus.PageEvents.subscribe("column:deselected", this.removeColumn, this); this.chorusView = this.model.deriveChorusView() this.chorusView.aggregateColumnSet = this.options.aggregateColumnSet; this.bindings.add(this.chorusView, "change", this.render); }, teardown: function() { this.cleanup(); this._super("teardown"); }, cleanup: function() { chorus.PageEvents.unsubscribe(this.selectedHandle); chorus.PageEvents.unsubscribe(this.deselectedHandle); this.options.aggregateColumnSet.each(function(column) { delete column.selected; }); }, postRender: function() { this.$("a.preview, button.create").data("parent", this); this.$("a.add_join").data("chorusView", this.chorusView) this._super("postRender") }, additionalContext: function(ctx) { return { columns: this.chorusView.sourceObjectColumns, joins: this.chorusView.joins } }, addColumn: function(column) { this.chorusView.addColumn(column) this.$("button.create").prop("disabled", false); }, removeColumn: function(column) { if (!column) { return; } this.chorusView.removeColumn(column); }, removeColumnClicked: function(e) { e.preventDefault(); var $li = $(e.target).closest("li"); var column = this.chorusView.aggregateColumnSet.getByCid($li.data('cid')); this.removeColumn(column); chorus.PageEvents.broadcast("column:removed", column); }, removeJoinClicked: function(e) { var cid = $(e.target).closest("div.join").data("cid"); var dialog = new chorus.alerts.RemoveJoinConfirmAlert({dataset: this.chorusView.getJoinDatasetByCid(cid), chorusView: this.chorusView}) dialog.launchModal(); }, previewSqlLinkClicked: function(e) { e.preventDefault(); this.chorusView.set({ query: this.sql() }); var dialog = new chorus.dialogs.SqlPreview({ model: this.chorusView }); dialog.launchModal(); }, createChorusView: function(e) { e && e.preventDefault(); this.chorusView.set({ query: this.sql() }); var dialog = new chorus.dialogs.VerifyChorusView({ model : this.chorusView }); dialog.launchModal(); }, whereClause: function() { return this.filters.whereClause(); }, sql: function() { return [this.chorusView.generateSelectClause(), this.chorusView.generateFromClause(), this.whereClause()].join("\n"); } });
33.138298
143
0.630177
dbad83f00cf0bff586fed45a4eff4583c41501f4
2,777
js
JavaScript
server/test/e2e_local/test.e2e.findNearAws.js
pokers/TodayWeather
17e0b2642039ac380705f0c9740dbcf5951853da
[ "MIT" ]
null
null
null
server/test/e2e_local/test.e2e.findNearAws.js
pokers/TodayWeather
17e0b2642039ac380705f0c9740dbcf5951853da
[ "MIT" ]
null
null
null
server/test/e2e_local/test.e2e.findNearAws.js
pokers/TodayWeather
17e0b2642039ac380705f0c9740dbcf5951853da
[ "MIT" ]
null
null
null
/** * Created by aleckim on 2018. 03. 16.. */ "use strict"; const controllerKmaStnWeather = require('../../controllers/controllerKmaStnWeather'); const Town = require('../../models/town'); const assert = require('assert'); const mongoose = require('mongoose'); const async = require('async'); const Logger = require('../../lib/log'); global.log = new Logger(__dirname + "/debug.log"); describe('e2e test - ', function() { before(function (done) { this.timeout(10*1000); mongoose.Promise = global.Promise; mongoose.connect('mongodb://localhost/todayweather', function(err) { if (err) { console.error('Could not connect to MongoDB!'); } done(); }); mongoose.connection.on('error', function(err) { if (err) { console.error('MongoDB connection error: ' + err); done(); } }); }); it('..', function(done) { this.timeout(60*1000*30); async.waterfall([ callback => { Town.find({}, {_id:0}).lean().exec(callback); }, (list, callback) => { console.info('town length='+list.length); async.mapLimit(list, 20, (townInfo, callback)=> { console.info(townInfo.town); let coords = [townInfo.gCoord.lon, townInfo.gCoord.lat]; controllerKmaStnWeather.getStnList(coords, 0.1, undefined, 5, (err, results)=> { if (err) { return callback(null, {town: townInfo, err:err}); } callback(null, {town: townInfo, results:results}); }); }, callback); } ], (err, results) => { let validCount= 0; results.forEach(obj => { if (obj.results && obj.results.length >= 2) { console.info({town: obj.town.town, stnCount: obj.results.length}); validCount++; } else { if (obj.results) { console.error({town: obj.town.town, stnCount: obj.results.length}); } else { console.error({town: obj.town.town, stnCount: 0}); } } }); console.info('validCount:'+validCount); done(); }); }); });
35.151899
108
0.423839
dbb07e333d2adaec44f6efef2ccec8dfb44e94ae
557
js
JavaScript
middleware/index.js
gnurgeldiyev/object-detection-api
95b75d2a81749cdf672f80dc567e486f2ccd2bf9
[ "MIT" ]
2
2022-02-05T11:54:33.000Z
2022-02-22T19:21:45.000Z
middleware/index.js
gnurgeldiyev/object-detection-api
95b75d2a81749cdf672f80dc567e486f2ccd2bf9
[ "MIT" ]
2
2020-07-08T10:48:53.000Z
2021-09-02T11:41:56.000Z
middleware/index.js
gnurgeldiyev/object-detection-api
95b75d2a81749cdf672f80dc567e486f2ccd2bf9
[ "MIT" ]
3
2021-03-18T05:35:32.000Z
2021-03-28T19:40:35.000Z
function validateNewDetection(req, res, next) { const imageBuffer = req.body // validate input data length if (!imageBuffer.length) { return res.status(400).json({ message: 'Bad request' }) } // validate image format const head = imageBuffer.slice(0, 2) const tail = imageBuffer.slice(-2) if ( !head.equals(Buffer.from('ffd8', 'hex')) || !tail.equals(Buffer.from('ffd9', 'hex')) ) { return res.status(400).json({ message: 'Accepts only jpg/jpeg format' }) } return next() } module.exports = { validateNewDetection }
25.318182
76
0.657092
dbb123f6c303e76c0565a7a35414eb3e3b417596
29,934
js
JavaScript
servlet_JSP_Bootstrap_CRUD/src/main/webapp/static/custom/js/scripts.js
simiyu17/java_projects
eea23cf3373d808da545e026c00c86ad70f85c74
[ "MIT" ]
null
null
null
servlet_JSP_Bootstrap_CRUD/src/main/webapp/static/custom/js/scripts.js
simiyu17/java_projects
eea23cf3373d808da545e026c00c86ad70f85c74
[ "MIT" ]
8
2020-07-04T21:24:44.000Z
2022-03-02T09:38:08.000Z
struts2_JSP_Bootstrap_CRUD/src/main/webapp/static/custom/js/scripts.js
simiyu17/java_projects
eea23cf3373d808da545e026c00c86ad70f85c74
[ "MIT" ]
null
null
null
function format_no(yourNumber) { if (typeof yourNumber != 'undefined') { //Seperates the components of the number var n = yourNumber.toString().split("."); //Comma-fies the first part n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); //Combines the two sections return n.join("."); } return yourNumber; } /*document.onmousedown=disableclick; function disableclick(event) { if(event.button==2) { return false; } } */ function hasKey(json, key) { return json.hasOwnProperty(key); } function reload() { if ($('#scheme_id').val() != '') { start_wait(); $.ajax({ url: $('#base_url').val() + 'admin', type: 'post', data: {ACTION: 'CHANGE_SCHEME', schemeID: $('#scheme_id').val()}, dataType: 'json', success: function (json) { console.log(json); if (json.success) setTimeout(function () { window.location.href = $('#base_url').val() + "admin"; }, 0); } }); } } function reloadmember() { if ($('#scheme_id').val() != '') { start_wait(); $.ajax({ url: $('#base_url').val() + 'member', type: 'post', data: {ACTION: 'CHANGE_SCHEME', schemeID: $('#scheme_id').val()}, dataType: 'json', success: function (json) { console.log(json); if (json.success) setTimeout(function () { var schemeID = $('#scheme_id').val(); console.log("Scheme Id: " + schemeID); window.location.href = $('#base_url').val() + "member?scheme_id=" + schemeID; }, 0); } }); } } var menu_done = false; var content_done = false; function load_menu(MODULE) { $.ajax({ url: $('#base_url').val() + 'menu', type: 'get', data: {menu: MODULE}, dataType: 'html', success: function (html) { $('#sub-menu').fadeOut('slow', function () { menu_done = true; if (content_done) { stop_wait(); $('.modal-backdrop').addClass('hide'); } $('#sub-menu').html(html); $('#sub-menu').fadeIn('slow'); }); } }); } function loadDashboard(MODULE) { $.ajax({ url: $('#base_url').val() + 'dashboard', type: 'get', data: {dashboard: MODULE}, dataType: 'html', success: function (html) { $('#dashboard').fadeOut('slow', function () { content_done = true; if (menu_done) { stop_wait(); $('.modal-backdrop').addClass('hide'); } $('#dashboard').html(html); $('#dashboard').fadeIn('slow'); }); } }); } $(document).ready(function () { $('.datepicker').datetimepicker({ language: 'en', weekStart: 1, todayBtn: 1, autoclose: 1, todayHighlight: 1, startView: 2, minView: 2, forceParse: 0, format: 'dd-mm-yyyy' }); function m_switch(MODULE) { menu_done = true; start_wait(); loadDashboard(MODULE); } function switch_page(MODULE) { menu_done = false; content_done = false; start_wait(); load_menu(MODULE); loadDashboard(MODULE); } /***** ADMINISTRATION MENU *****/ $('#admin-dashboard-li').click(function () { start_wait(); window.location.href = $('#base_url').val() + "admin"; }); $('#switch_profile').click(function () { var profile = "member"; if ($('#switch_to').val() == 'admin') profile = 'managerial'; bootbox.confirm("<p class=\"text-center\">You are about to switch your " + profile + ". Are you sure?</p>", function (result) { if (result) { start_wait(); setTimeout(function () { window.location.href = $('#base_url').val() + $('#switch_to').val(); }, 0); } }); }); $('#setup-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#setup-main-li').addClass('active'); switch_page('SETUP'); }); $('#pwd-reset-btn').click(function () { $('#modal-pwd-reset').modal('show'); }); $('#content-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#content-main-li').addClass('active'); switch_page('CONTENT'); }); $('#scheme-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#scheme-main-li').addClass('active'); switch_page('SCHEME'); }); $('#calc-log').click(function () { $('#calc-log li').removeClass('active'); $('#calc-log').addClass('active'); switch_page('CALC-LOG'); }); $('#member-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#member-main-li').addClass('active'); switch_page('MEMBER'); }); $('#member-listing-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#member-listing-main-li').addClass('active'); switch_page('MEMBER_LISTING'); }); $('#corporate-statement-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#corporate-statement-main-li').addClass('active'); switch_page('CORPORATE_STATEMENT'); }); $('#member-operations-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#member-operations-main-li').addClass('active'); switch_page('MEMBER_OPERATIONS'); }); $('#withdrawal-statement-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#withdrawal-statement-main-li').addClass('active'); switch_page('WITHDRAWAL_STATEMENT'); }); $('#withdrawal-settlements-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#withdrawal-settlements-main-li').addClass('active'); switch_page('WITHDRAWAL_SETTLEMENTS'); }); $('#admin_fee_listing-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#admin_fee_listing-main-li').addClass('active'); switch_page('ADMIN_FEE_LISTING'); }); $('#member-movement-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#member-movement-main-li').addClass('active'); switch_page('MEMBER_MOVEMENT'); }); $('#fund-movement-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#fund-movement-main-li').addClass('active'); switch_page('FUND_MOVEMENT'); }); $('#receipt-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#receipt-main-li').addClass('active'); switch_page('RECEIPT_SUMMARY'); }); $('#media-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#media-main-li').addClass('active'); switch_page('MEDIA'); }); $('#receipts-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#receipts-main-li').addClass('active'); m_switch('RECEIPT'); }); $('#payments-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#payments-main-li').addClass('active'); m_switch('PAYMENT'); }); $('#registered-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#registered-main-li').addClass('active'); m_switch('PORTAL_MEMBER'); }); $('#sponsors-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#sponsors-main-li').addClass('active'); m_switch('SPONSOR'); }); $('#uac-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#uac-main-li').addClass('active'); switch_page('UAC'); }); $('#analytics-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#analytics-main-li').addClass('active'); switch_page('ANALYTICS'); }); /*** AGENTS ONLY MENU ****/ $('#commissions-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#commissions-main-li').addClass('active'); switch_page('COMMISSIONS'); }); $('#clients-main-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#clients-main-li').addClass('active'); switch_page('CLIENTS'); }); /*** MEMBERS ONLY MENU ****/ $('#member-dashboard-li').click(function () { start_wait(); window.location.href = $('#base_url').val() + "member"; }); $('#pensioner-dashboard-li').click(function () { start_wait(); window.location.href = $('#base_url').val() + "pensioner"; }); $('#personal-information-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#personal-information-li').addClass('active'); m_switch("PI"); }); $('#pensioner-information-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#pensioner-information-li').addClass('active'); m_switch("PENSIONER_INFO"); }); $('#pension-details-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#pension-details-li').addClass('active'); m_switch("PENSION_DETAILS"); }); $('#pension-advice-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#pension-advice-li').addClass('active'); m_switch("PENSION_ADVICE"); }); $('#pension-advice-grid').click(function () { $('#main-menu.nav li').removeClass('active'); $('#pension-advice-grid').addClass('active'); m_switch("PENSION_ADVICE_GRID"); }); $('#contribution-history-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#contribution-history-li').addClass('active'); m_switch("CH"); }); $('#contribution-history-grid-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#contribution-history-grid-li').addClass('active'); m_switch("CH_GRID"); }); $('#statement-of-account-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#statement-of-account-li').addClass('active'); m_switch("SA"); }); $('#statement-of-account-grid-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#statement-of-account-grid-li').addClass('active'); m_switch("SA_GRID"); }); $('#unitized-statement-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#unitized-statement-li').addClass('active'); m_switch("US"); }); $('#what-if-analysis-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#what-if-analysis-li').addClass('active'); m_switch("WIA"); }); $('#benefits-projection-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#benefits-projection-li').addClass('active'); m_switch("BP"); }); $('#benefits-projection-grid-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#benefits-projection-grid-li').addClass('active'); m_switch("BP_GRID"); }); $('#media-files-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#media-files-li').addClass('active'); m_switch("MF"); }); $('#member-claims-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#member-claims-li').addClass('active'); m_switch("MC"); }); $('#balances-history-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#balances-history-li').addClass('active'); m_switch("BH"); }); $('#balances-history-grid-li').click(function () { $('#main-menu.nav li').removeClass('active'); $('#balances-history-grid-li').addClass('active'); m_switch("BAL_HISTORY_GRID"); }); /***** Other Menu Items *****/ $('#change-pwd-li').click(function () { bootbox.confirm("<p style=\"text-center\">You have requested to change your password. Are you sure?</p>", function (result) { if (result) { $.ajax({ url: $('#base_url').val() + $('#path').val(), type: 'post', data: {ACTION: 'PRE_CHANGE_PASSWORD'}, dataType: 'json', success: function (json) { if (json.success) { $('#modal-change-pwd').modal('show'); } else { bootbox.alert(json.message); } } }); } }); }); $('#send-email-btn').click(function () { $('#modal-send-email').modal('show'); }); $('#logout-li').click(function () { bootbox.confirm("<p class='text-center'>Are you sure?</p>", function (result) { if (result) { $.ajax({ url: $('#base_url').val() + "admin", type: 'post', data: {ACTION: 'LOGOUT'}, dataType: 'json', success: function (json) { if (json.success) { bootbox.alert('<p class="text-center">You have been logged out successfully.<br />Redirecting...</p>'); location.reload(); } } }); } }); }); $('#register-btn').click(function () { $('#modal-register').modal('show'); }); $('#form-change-password').bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, excluded: ':disabled', fields: { currentPassword: { validators: { notEmpty: { message: 'Please enter your current password' } } }, securityCode: { validators: { notEmpty: { message: 'Please enter the security code' } } }, newPassword: { validators: { notEmpty: { message: 'Please enter your new password' }, identical: { field: 'confirmPassword', message: 'Your passwords must match' }, callback: { message: 'Invalid password entered', callback: function (value, validator, $field) { if (value === '') { return true; } // Check the password strength if (value.length < minimum && minimum > 0) { console.log("minimum...."); return { valid: false, message: 'It must be at least ' + minimum + ' characters long' }; } // The password doesn't contain any uppercase character if (value === value.toLowerCase() && uppercase == "true") { console.log("uppercase...."); return { valid: false, message: 'It must contain at least one upper case character' } } // The password doesn't contain any uppercase character if (value === value.toUpperCase() && lowercase == "true") { console.log("lowercase...."); return { valid: false, message: 'It must contain at least one lower case character' } } // The password doesn't contain any digit if (value.search(/[0-9]/) < 0 && numbers == "true") { console.log("numbers...."); return { valid: false, message: 'It must contain at least one digit' } } return true; } } } }, confirmPassword: { validators: { notEmpty: { message: 'Please confirm the new password' }, identical: { field: 'newPassword', message: 'Your passwords must match' }, callback: { message: 'Invalid password entered', callback: function (value, validator, $field) { if (value === '') { return true; } // Check the password strength if (value.length < minimum && minimum > 0) { console.log("minimum...."); return { valid: false, message: 'It must be at least ' + minimum + ' characters long' }; } // The password doesn't contain any uppercase character if (value === value.toLowerCase() && uppercase == "true") { console.log("uppercase...."); return { valid: false, message: 'It must contain at least one upper case character' } } // The password doesn't contain any uppercase character if (value === value.toUpperCase() && lowercase == "true") { console.log("lowercase...."); return { valid: false, message: 'It must contain at least one lower case character' } } // The password doesn't contain any digit if (value.search(/[0-9]/) < 0 && numbers == "true") { console.log("numbers...."); return { valid: false, message: 'It must contain at least one digit' } } return true; } } } } } }) .on('success.form.bv', function (e) { // Prevent form submission e.preventDefault(); start_wait(); $.ajax({ url: $('#base_url').val() + 'admin', type: 'POST', data: {ACTION: 'CHANGE_PASSWORD', currentPassword: $('#currentPassword').val(), securityCode: $('#securityCode').val(), newPassword: $('#newPassword').val()}, dataType: 'json', success: function (json) { stop_wait(); if (json.success) $('#modal-change-pwd').modal('hide'); bootbox.alert(json.message); } }); }); }); $('#form-password-reset').bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, excluded: ':disabled', fields: { email: { validators: { notEmpty: { message: 'Please enter your username' } } } } }) .on('success.form.bv', function (e) { // Prevent form submission e.preventDefault(); start_wait(); $.ajax({ url: $('#base_url').val() + 'password-reset', type: 'POST', data: {ACTION: 'REQUEST_RESET', email: $('#email').val()}, dataType: 'json', success: function (json) { stop_wait(); bootbox.alert(json.message); if (json.success) $('#modal-pwd-reset').modal('hide'); } }); }); $('#form-reset-password').bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { securityCode: { validators: { notEmpty: { message: 'Please enter the security code' } } }, newPassword: { validators: { notEmpty: { message: 'Please enter your new password' }, identical: { field: 'confirmPassword', message: 'Your passwords must match' }, callback: { message: 'Invalid password entered', callback: function (value, validator, $field) { if (value === '') { return true; } // Check the password strength if (value.length < minimum && minimum > 0) { console.log("minimum...."); return { valid: false, message: 'It must be at least ' + minimum + ' characters long' }; } // The password doesn't contain any uppercase character if (value === value.toLowerCase() && uppercase == "true") { console.log("uppercase...."); return { valid: false, message: 'It must contain at least one upper case character' } } // The password doesn't contain any uppercase character if (value === value.toUpperCase() && lowercase == "true") { console.log("lowercase...."); return { valid: false, message: 'It must contain at least one lower case character' } } // The password doesn't contain any digit if (value.search(/[0-9]/) < 0 && numbers == "true") { console.log("numbers...."); return { valid: false, message: 'It must contain at least one digit' } } return true; } } } }, confirmPassword: { validators: { notEmpty: { message: 'Please confirm the new password' }, identical: { field: 'newPassword', message: 'Your passwords must match' }, callback: { message: 'Invalid password entered', callback: function (value, validator, $field) { if (value === '') { return true; } // Check the password strength if (value.length < minimum && minimum > 0) { console.log("minimum...."); return { valid: false, message: 'It must be at least ' + minimum + ' characters long' }; } // The password doesn't contain any uppercase character if (value === value.toLowerCase() && uppercase == "true") { console.log("uppercase...."); return { valid: false, message: 'It must contain at least one upper case character' } } // The password doesn't contain any uppercase character if (value === value.toUpperCase() && lowercase == "true") { console.log("lowercase...."); return { valid: false, message: 'It must contain at least one lower case character' } } // The password doesn't contain any digit if (value.search(/[0-9]/) < 0 && numbers == "true") { console.log("numbers...."); return { valid: false, message: 'It must contain at least one digit' } } return true; } } } } } }) .on('success.form.bv', function (e) { // Prevent form submission e.preventDefault(); start_wait(); $.ajax({ url: $('#base_url').val() + 'password-reset', type: 'POST', data: {ACTION: 'RESET_PASSWORD', securityCode: $('#securityCode').val(), newPassword: $('#newPassword').val()}, dataType: 'json', success: function (json) { stop_wait(); bootbox.alert(json.message); if (json.success) setTimeout(function () { window.location.href = $('#base_url').val(); }, 3000); } }); });
30.145015
179
0.405459
dbb3c28a5babc061c36d92376412a632686bd0f4
161
js
JavaScript
src/number.js
mrouabeh/type-utils-js
f282aab64d98bd8815852422b6d9dc3f8f4803e9
[ "MIT" ]
null
null
null
src/number.js
mrouabeh/type-utils-js
f282aab64d98bd8815852422b6d9dc3f8f4803e9
[ "MIT" ]
null
null
null
src/number.js
mrouabeh/type-utils-js
f282aab64d98bd8815852422b6d9dc3f8f4803e9
[ "MIT" ]
null
null
null
const isNumber = (value) => { return (typeof value === 'number' || value instanceof Number) && !Number.isNaN(value); } module.exports = exports = isNumber;
26.833333
90
0.658385
dbb6073442fa5b1e72a3ceb49712b4701b78467c
1,139
js
JavaScript
src/constants/CameraConstants.js
Jayden-Chiu/MinecraftClone
44841a66cdbcef4ec65888f115c8bc3bee6f94b5
[ "MIT" ]
6
2020-09-27T14:44:15.000Z
2022-03-10T19:06:45.000Z
src/constants/CameraConstants.js
Jayden-Chiu/MinecraftClone
44841a66cdbcef4ec65888f115c8bc3bee6f94b5
[ "MIT" ]
1
2021-06-17T07:17:37.000Z
2021-06-17T08:01:31.000Z
src/constants/CameraConstants.js
Jayden-Chiu/MinecraftClone
44841a66cdbcef4ec65888f115c8bc3bee6f94b5
[ "MIT" ]
2
2020-09-26T16:58:23.000Z
2021-12-10T07:43:54.000Z
import * as WorldConstants from "./WorldConstants.js"; import * as GameConstants from "./GameConstants.js"; export const RENDER_DISTANCE = 8; export const CAMERA_DEFAULT_X = RENDER_DISTANCE * WorldConstants.CHUNK_SIZE + WorldConstants.CHUNK_SIZE/2 + 0.01; export const CAMERA_DEFAULT_Y = WorldConstants.WORLD_HEIGHT/3 + 0.01; export const CAMERA_DEFAULT_Z = RENDER_DISTANCE * WorldConstants.CHUNK_SIZE + WorldConstants.CHUNK_SIZE/2 + 0.01; export const CAMERA_DEFAULT_CHUNK_X = Math.floor(CAMERA_DEFAULT_X/WorldConstants.CHUNK_SIZE); export const CAMERA_DEFAULT_CHUNK_Y = Math.floor(CAMERA_DEFAULT_Y/WorldConstants.CHUNK_SIZE); export const CAMERA_DEFAULT_CHUNK_Z = Math.floor(CAMERA_DEFAULT_Z/WorldConstants.CHUNK_SIZE); export const FOV = 75; export const ASPECT = window.innerWidth / window.innerHeight; export const NEAR = 0.1; export const FAR = 1000; // MOVEMENT export const MOVEMENT_SPEED = 0.28; export const ACCELERATION = 0.05; export const GRAVITY_VELOCITY = -0.08; export const JUMP_VELOCITY = 0.42; export const GROUND_FRICTION = 0.91; export const AIR_FRICTION = 0.95; // VOXEL PLACEMENT export const BLOCK_DISTANCE = 5;
43.807692
113
0.803336
dbb7f9ceb45db368700c69e8e5eb1feb6a5c2e7b
632
js
JavaScript
NEXT_APPS/ecomerce/server/modals/cart.js
boby-tudu-au6/Projects
6d6a46c1e153a4e8a87ca946d33142d46461927c
[ "MIT" ]
4
2021-06-19T10:33:37.000Z
2022-02-04T10:57:10.000Z
NEXT_APPS/ecomerce/server/modals/cart.js
attulsharmma/Projects
6d6a46c1e153a4e8a87ca946d33142d46461927c
[ "MIT" ]
20
2021-04-22T08:26:06.000Z
2022-02-27T14:04:47.000Z
NEXT_APPS/ecomerce/server/modals/cart.js
attulsharmma/Projects
6d6a46c1e153a4e8a87ca946d33142d46461927c
[ "MIT" ]
5
2020-11-21T07:39:25.000Z
2021-12-07T05:09:36.000Z
import { Schema, model, models } from 'mongoose'; const itemSchema = new Schema({ product: { type: Schema.Types.ObjectId, ref: 'product' }, quantity: { type: Number, default: 1 } }) const cartSchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: 'user' }, products: [{ product: { type: Schema.Types.ObjectId, ref: 'product' }, quantity: { type: Number, default: 1 } }] }); export default models.cart || model('cart', cartSchema);
20.387097
56
0.473101
dbb873814f734a246da2bd4331882238b035ff45
2,117
js
JavaScript
src/components/App/App.test.js
martoio/exabyte-flo
d16ab40ed1205dfe1b6520ef3976e14e05262584
[ "MIT" ]
null
null
null
src/components/App/App.test.js
martoio/exabyte-flo
d16ab40ed1205dfe1b6520ef3976e14e05262584
[ "MIT" ]
null
null
null
src/components/App/App.test.js
martoio/exabyte-flo
d16ab40ed1205dfe1b6520ef3976e14e05262584
[ "MIT" ]
null
null
null
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import Enzyme from 'enzyme'; import {expect} from 'chai'; import Adapter from 'enzyme-adapter-react-16'; Enzyme.configure({adapter: new Adapter()}); it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<App/>, div); ReactDOM.unmountComponentAtNode(div); }); describe('graph tests', () => { const wrapper = Enzyme.shallow(<App />); beforeEach(()=>{ wrapper.setState({ "windows":{ "library":true, "json":true, "console":false, "node":false }, "graph":{ "nodes":[ { "id":0, "title":"", "type":"begin", "x":0, "y":0, "outEdge":0, "inEdge":null }, { "id":1, "title":"", "type":"end", "x":-38.231478452682495, "y":576.7096977233887, "outEdge":null, "inEdge":1 }, { "id":2, "title":"", "type":"process", "x":273.8779910802841, "y":217.66093826293945, "outEdge":3, "inEdge":2 }, { "id":3, "title":"", "type":"decision", "x":-46.126819252967834, "y":223.42677688598633, "outEdge":1, "inEdge":0, "falseEdge":2 }, { "id":4, "title":"", "type":"end", "x":529.0169749855995, "y":259.463339805603, "outEdge":null, "inEdge":3 } ], "edges":[ { "id":0, "source":0, "target":3, "type":"emptyEdge" }, { "id":1, "source":3, "target":1, "type":"trueEdge" }, { "id":2, "source":3, "target":2, "type":"falseEdge" }, { "id":3, "source":2, "target":4, "type":"emptyEdge" } ] }, "selected":{ "id":4, "title":"", "type":"end", "x":529.0169749855995, "y":259.463339805603, "outEdge":null, "inEdge":3 }, "blockType":"empty", "nextEdgeId":4, "nextNodeId":5, "lastAddedNode":4, "canEditNode":false }); }); });
17.940678
46
0.470949
dbb8a1d9ff45e5cfbc328efb1147b282ba1cc78a
978
js
JavaScript
config/env/development.js
winechess/MEAN
952ad211fbecde77139075dd0764d1bbb789ff47
[ "MIT" ]
null
null
null
config/env/development.js
winechess/MEAN
952ad211fbecde77139075dd0764d1bbb789ff47
[ "MIT" ]
null
null
null
config/env/development.js
winechess/MEAN
952ad211fbecde77139075dd0764d1bbb789ff47
[ "MIT" ]
null
null
null
/** * Created by vinichenkosa on 05.03.15. */ module.exports = { //Development configuration options sessionSecret: 'developmentSessionSecret', db: 'mongodb://localhost/mean', facebook: { clientID: '362870707252113', clientSecret: '968ff15583f63c0992132c2d94c9f490', callbackURL: 'http://localhost:3000/oauth/facebook/callback' }, twitter: { clientID: 'QgoYLkJwA9uV9s6ip0f30pTQP', clientSecret: 'ZicO4KXQmKaGoUY3odE0Wi3UrvVQReFqBiom2IcQMpFQeDTXM8', callbackURL: 'http://localhost:3000/oauth/twitter/callback' }, google: { clientID: '810458430363-ppalfpgp3975m8jr9g1q163mgdsn4lr8.apps.googleusercontent.com', clientSecret: 'faZ7q3J0n2bDlNAhl471dQwm', callbackURL: 'http://localhost:3000/oauth/google/callback' }, vk: { clientID: '4824344', clientSecret: 'uvBe7YBcmsIgVtnRACKk', callbackURL: 'http://localhost:3000/oauth/vk/callback' } };
34.928571
93
0.677914
dbb8aed43023a2295023ca2d22655f8ed09a959c
2,672
js
JavaScript
dist/decoder/jpeg.js
dcm-web/dicom-parser
46b9f05d257930955b6ac839eab88b191961db8d
[ "MIT" ]
null
null
null
dist/decoder/jpeg.js
dcm-web/dicom-parser
46b9f05d257930955b6ac839eab88b191961db8d
[ "MIT" ]
null
null
null
dist/decoder/jpeg.js
dcm-web/dicom-parser
46b9f05d257930955b6ac839eab88b191961db8d
[ "MIT" ]
null
null
null
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const libjpeg_turbo_1 = __importDefault(require("libjpeg-turbo")); const utils_1 = require("./utils"); let decoder; const decode = function (data, encoding, pixelDescription, frameNumbers) { return __awaiter(this, void 0, void 0, function* () { const fragments = (0, utils_1.pixelDataToFragments)(data, encoding); let encodedFrames = (0, utils_1.fragmentsToFrames)(fragments); if (frameNumbers) { encodedFrames = encodedFrames.filter((_, i) => frameNumbers.includes(i)); } const frames = []; for (const encodedFrame of encodedFrames) { frames.push(yield decodeFrame(encodedFrame)); } return { frames, pixelDescription: Object.assign(Object.assign({}, pixelDescription), { // JPEGs (mostly) use YBR_FULL_422 internally but when decoded with // libjpeg-turbo the conversion to rgb is also performed, so the // photometric interpretation needs to be updated. photometricInterpretation: pixelDescription.samplesPerPixel === 3 ? "RGB" : pixelDescription.photometricInterpretation }), }; }); }; const decodeFrame = function (data) { return __awaiter(this, void 0, void 0, function* () { if (!decoder) { const libJpegTurbo = yield (0, libjpeg_turbo_1.default)(); decoder = new libJpegTurbo.JPEGDecoder(); } const buffer = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); const encodedBuffer = decoder.getEncodedBuffer(buffer.length); encodedBuffer.set(buffer); decoder.decode(); return decoder.getDecodedBuffer(); }); }; exports.default = decode;
48.581818
118
0.627994
dbb968b9da8abe37382e13f3f9068879adbf2094
2,747
js
JavaScript
src/index.js
ChKer/https-github.com-dimpu-html5-video-chat
2a49dd32a1026c71148b6efff4feb4821036fb58
[ "MIT" ]
25
2017-05-06T18:11:52.000Z
2022-03-25T09:54:27.000Z
src/index.js
apex-quest/html5-video-chat
2a49dd32a1026c71148b6efff4feb4821036fb58
[ "MIT" ]
1
2017-12-09T19:00:50.000Z
2017-12-09T19:00:50.000Z
src/index.js
apex-quest/html5-video-chat
2a49dd32a1026c71148b6efff4feb4821036fb58
[ "MIT" ]
20
2015-09-26T19:42:22.000Z
2022-01-08T22:04:01.000Z
require('./app'); // navigator.getUserMedia_ = ( navigator.mediaDevices.getUserMedia // || navigator.mediaDevices.webkitGetUserMedia // || navigator.mediaDevices.mozGetUserMedia // || navigator.mediaDevices.msGetUserMedia); // var getUserMedia_ = navigator.getUserMedia // getUserMedia_({video:true,audio:false}, function(stream){ // var Peer = require('simple-peer'); // var peer = new Peer({ // initiator:location.hash === '#init', // trickle:false, // stream:stream // }); // peer.on('signal',function(data){ // console.log(data); // $('.loader').hide(); // $('#myId').val(JSON.stringify(data)); // }); // peer.on('connect', function () { // console.log('CONNECT') // peer.send('whatever' + Math.random()) // }) // peer.on('data', function (data) { // console.log('data: ' + data) // }) // peer.on('stream',function(stream){ // var video = document.createElement('video'); // $('#video-area').append(video); // video.src = window.URL.createObjectURL(stream); // video.play(); // }); // $("#connect").on('click',function(){ // var otherId = $("#otherId").val(); // peer.signal(otherId); // }); // }, function(err){ // console.error(err); // }); // var SimplePeer = require('simple-peer') // // get video/voice stream navigator.getUserMedia({ video: true, audio: true }, gotMedia, function () {}) function gotMedia(stream) { var Peer = require('simple-peer'); var peer = new Peer({ initiator:location.hash === '#init', trickle:false, stream:stream }); peer.on('signal',function(data){ console.log(data); $('.loader').hide(); $('#myId').val(JSON.stringify(data)); }); peer.on('connect', function () { console.log('CONNECT') peer.send('whatever' + Math.random()) }) peer.on('data', function (data) { console.log('data: ' + data) }) peer.on('stream',function(stream){ var video = document.createElement('video'); $('#video-area').append(video); video.src = window.URL.createObjectURL(stream); video.play(); }); $("#connect").on('click',function(){ var otherId = $("#otherId").val(); peer.signal(otherId); }); } // function gotMedia (stream) { // var peer1 = new SimplePeer({ initiator: true, stream: stream }) // var peer2 = new SimplePeer() // peer1.on('signal', function (data) { // peer2.signal(data) // }) // peer2.on('signal', function (data) { // peer1.signal(data) // }) // peer2.on('stream', function (stream) { // // got remote video stream, now let's show it in a video tag // var video = document.querySelector('video') // console.log(stream); // video.src = window.URL.createObjectURL(stream) // video.play() // }) // }
25.672897
78
0.598835
dbb9c6d321686982c7173f0af5ce5b4a44b664b2
1,149
js
JavaScript
LongestCommonPrefix/JavaScript/LongestCommonPrefix.js
jasonmauss/LeetCode
f7bebb23ad2f5afe1249934a40332ec99ba3bffe
[ "MIT" ]
1
2022-03-11T19:01:35.000Z
2022-03-11T19:01:35.000Z
LongestCommonPrefix/JavaScript/LongestCommonPrefix.js
jasonmauss/LeetCode
f7bebb23ad2f5afe1249934a40332ec99ba3bffe
[ "MIT" ]
null
null
null
LongestCommonPrefix/JavaScript/LongestCommonPrefix.js
jasonmauss/LeetCode
f7bebb23ad2f5afe1249934a40332ec99ba3bffe
[ "MIT" ]
null
null
null
// Solution for: https://leetcode.com/problems/longest-common-prefix/ var longestCommonPrefix = function (strs) { if (strs && strs.length > 0) { // start off by making the first string the longest prefix // then start comparing from the second word onward in the // loop below var longestPrefix = strs[0]; for (var i = 1; i < strs.length; i++) { var matchingString = strs[i]; // keep removing the last letter of the prefix string // until a potential prefix match is found using .slice() while (matchingString.indexOf(longestPrefix) !== 0) { longestPrefix = longestPrefix.slice(0, longestPrefix.length - 1); if (longestPrefix.length === 0) { return ''; } } } return longestPrefix; } else { return ''; } }; // some test cases console.log(longestCommonPrefix(['flower', 'flow', 'flight'])); // 'fl' console.log(longestCommonPrefix(['dog', 'racecar', 'car'])); // '' console.log(longestCommonPrefix(['break', 'breakfast', 'bread'])); // 'brea'
39.62069
81
0.571802
dbba5ac683aeb6634af8776ca0c50e7240f18b0c
991
js
JavaScript
src/slick-vertical/index.js
MrGoodBye/House-Desigh
09f0aca020ccf59d255f42138131a6bc7da8cefd
[ "MIT" ]
null
null
null
src/slick-vertical/index.js
MrGoodBye/House-Desigh
09f0aca020ccf59d255f42138131a6bc7da8cefd
[ "MIT" ]
null
null
null
src/slick-vertical/index.js
MrGoodBye/House-Desigh
09f0aca020ccf59d255f42138131a6bc7da8cefd
[ "MIT" ]
null
null
null
import 'slick-carousel/slick/slick' import 'slick-carousel/slick/slick.scss' import 'slick-carousel/slick/slick-theme.scss' import './index.scss' const $slider = $('.slider') if (!window.isMobile) { console.log('init vertical slider') $slider.slick({ infinite: false, arrows: false, vertical: true, dots: true, draggable: false, speed: 1200, cssEase: 'cubic-bezier(0.86, 0, 0.07, 1)' }) $slider.on('wheel', function (e) { e.preventDefault() if (e.originalEvent.deltaY > 0) { if ($(this).slick('slickCurrentSlide') === $(this).find('.slick-slide').length - 1) return $(this).slick('slickNext') } else { if ($(this).slick('slickCurrentSlide') === 0) { return } $(this).slick('slickPrev') } }) $slider.on('afterChange', function(event, $slick, direction){ $(this).find('.aos-init').removeClass('aos-animate') $(this).find('.slick-current .slide .aos-init').addClass('aos-animate') }) }
26.078947
96
0.611504
dbbc266e11c2319f30c9099d86c51b11f0dd7d90
897
js
JavaScript
custom-citgm-test.js
CloudNativeJS/module-insights-ci
46a7b3c370f240a2212c1ec99b7bbddd7e395017
[ "Apache-2.0" ]
null
null
null
custom-citgm-test.js
CloudNativeJS/module-insights-ci
46a7b3c370f240a2212c1ec99b7bbddd7e395017
[ "Apache-2.0" ]
2
2019-03-06T16:11:22.000Z
2020-11-25T11:21:26.000Z
custom-citgm-test.js
CloudNativeJS/module-insights-ci
46a7b3c370f240a2212c1ec99b7bbddd7e395017
[ "Apache-2.0" ]
1
2021-02-25T06:27:25.000Z
2021-02-25T06:27:25.000Z
"use strict"; /*************************************************************************** * * (C) Copyright IBM Corp. 2018 * * This program and the accompanying materials are made available * under the terms of the Apache License v2.0 which accompanies * this distribution. * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * Contributors: * Multiple authors (IBM Corp.) - initial implementation and documentation ***************************************************************************/ const { spawnSync } = require("child_process"); const packageName = require(process.cwd() + "/package.json").name; const nyc = (process.env.OS === "win") ? "nyc.cmd" : "nyc"; const result = spawnSync(nyc, ["--reporter=json-summary", `--report-dir=${process.env.WORKSPACE}/${packageName}`, "npm", "test" ]); process.exit(result.status);
32.035714
76
0.576366
dbbc27b966fe736eaec6dc777aabd3cb53896eaf
9,037
js
JavaScript
src/image.js
ample/imgix-optimizer
597a0781f1720594a3259a82de9192674e246e7b
[ "MIT" ]
null
null
null
src/image.js
ample/imgix-optimizer
597a0781f1720594a3259a82de9192674e246e7b
[ "MIT" ]
7
2018-07-26T11:54:02.000Z
2020-07-16T07:17:49.000Z
src/image.js
ample/imgix-optimizer
597a0781f1720594a3259a82de9192674e246e7b
[ "MIT" ]
null
null
null
export default class Image { constructor(img) { // Length of crossfade transition. this.timeToFade = 500; // Data attribute applied before processing. this.processingAttr = 'data-imgix-img-processed'; // The main image (pixelated placeholder). this.placeholderImg = $(img); // Tracks state of the transition so some actions don't fire during the // transition period. this.transitioning = false; // Wait for the image to load prior to kicking off the optimization process. if (this.placeholderImg.height() > 0) { this.init(); } else { this.placeholderImg.on('load', $.proxy(this.init, this)); } } /** * Configure the main placeholder image and kick off the optimization process. */ init() { this.initPlaceholder(); this.initOptimization(); } /** * Load an image in memory (not within the DOM) with the same source as the * placeholder image. Once that has completed, we know we're safe to begin * listening for the image to intersect the viewport. */ initOptimization() { $('<img>') .on('load', $.proxy(this.listenForIntersection, this)) .attr('src', this.placeholderImg.attr('src')); } // ---------------------------------------- | Lazy Loading Control /** * When the placeholder image intersects the viewport, begin processing. * (IntersectionObserver and Object.assign() are not supported by IE, but the * polyfills are loaded by Imgix.Optimizer.) */ listenForIntersection() { const observer = new IntersectionObserver($.proxy(this.onIntersection, this)); observer.observe(this.placeholderImg[0]); } /** * When the placeholder image intersects the viewport, check if it is in the * viewport and has not yet been processed. If those conditions are true, * begin rendering the full size image and the transition process. */ onIntersection(entries, observer) { let img = $(entries[0].target); if (!entries[0].isIntersecting || $(img).attr(this.processingAttr)) return; img.attr(this.processingAttr, true); this.renderFullSizeImg(); } // ---------------------------------------- | Placeholder Image /** * Make necessary CSS adjustments to main placeholder image and listen for * changes. */ initPlaceholder() { this.wrapPlaceholder(); this.setPlaceholderCss(); $(window).resize($.proxy(this.rewrapPlaceholder, this)); } /** * Wrap the placeholder image in a <div>. This enables better control over the * wrapping element and provides a more fluid transition process. */ wrapPlaceholder(margin = null) { this.tmpWrapper = $('<div>').css({ display: 'inline-block', position: 'relative', height: this.placeholderImg[0].getBoundingClientRect().height, width: this.placeholderImg[0].getBoundingClientRect().width, margin: margin || this.placeholderImg.css('margin') }); this.placeholderImg.wrap(this.tmpWrapper); } /** * The main image must have a position set for it to remain in front of the * full-size image. We assume that if the element is not explicitly positioned * absolutely, then it can safely be positioned relatively. * * And temporarily remove any margin from the image, as the box model gets * delegated to the temporary wrapper during the transition period. */ setPlaceholderCss() { if (this.placeholderImg.css('position') != 'absolute') { this.placeholderImg.css('position', 'relative'); } this.placeholderImg.css({ margin: 0 }); } /** * If the transition has not yet happened, figure out the margin of the * wrapper, then unwrap and rewrap. This resets the size of the wrapper so it * doesn't overflow after resize events. */ rewrapPlaceholder() { if (this.transitioning || !this.placeholderImg) return true; var wrapperMargin = this.tmpWrapper.css('margin'); this.placeholderImg.unwrap(); this.wrapPlaceholder(wrapperMargin); } // ---------------------------------------- | Full-Size Image /** * Render the full-size image behind the placeholder image. */ renderFullSizeImg() { this.rewrapPlaceholder(); this.transitioning = true; this.initFullSizeImg(); this.setFullSizeImgTempCss(); this.setFullSizeImgSrc(); this.addFullSizeImgToDom(); this.initTransition(); } /** * The full-size image is a clone of the placeholder image. This enables us to * easily replace it without losing any necessary styles or attributes. */ initFullSizeImg() { this.fullSizeImg = this.placeholderImg.clone(); } /** * Give the full-size image a temporary set of CSS rules so that it can sit * directly behind the placeholder image while loading. */ setFullSizeImgTempCss() { this.fullSizeImg.css({ position: 'absolute', top: this.placeholderImg.position().top, left: this.placeholderImg.position().left, width: '100%', height: '100%' }); } /** * Return the width and height of the placeholder image, including decimals. * Uses precise measurements like this helps ensure the element doesn't slide * when transitioning to the full size image. */ getPlaceholderImgRect() { return { width: this.placeholderImg[0].getBoundingClientRect().width, height: this.placeholderImg[0].getBoundingClientRect().height }; } /** * Prep the full-size image with the attributes necessary to become its full * size. Right now it is still just a replica of the placeholder, sitting * right behind the placeholder. * * We set the src directly even though we're using imgix.js because older * browsers don't support the srcset attribute which is what imgix.js relies * upon. */ setFullSizeImgSrc() { let newSrc = this.placeholderImg .attr('src') .replace(/(\?|\&)(w=)(\d+)/i, '$1$2' + this.getPlaceholderImgRect().width) .replace(/(\?|\&)(h=)(\d+)/i, '$1$2' + this.getPlaceholderImgRect().height); // Add a height attribute if it is missing. This is the key to the image not // jumping around after transitioning to the full-size image. if (newSrc.search(/(\?|\&)(h=)(\d+)/i) < 0) { newSrc = `${newSrc}&h=${this.getPlaceholderImgRect().height}&fit=crop`; } this.fullSizeImg.attr('ix-src', newSrc); // TODO: Make this a configurable option or document it as a more semantic temporary class this.fullSizeImg.addClass('img-responsive imgix-optimizing'); // TODO: This should respect the option from the Optimizer class for the select this.fullSizeImg.removeAttr('data-optimize-img'); } /** * Render the full-size image in the DOM. */ addFullSizeImgToDom() { this.fullSizeImg.insertBefore(this.placeholderImg); } // ---------------------------------------- | Image Transition /** * Once the full-size image is loaded, begin the transition. This is the * critical piece of this process. Imgix.js uses the ix-src attribute to build * out the srcset attribute. Then, based on the sizes attribute, the browser * determines which source to render. Therefore we can't preload in memory * because we need imgix to do its thing directly in the DOM. */ initTransition() { this.fullSizeImg.on('load', () => this.transitionImg()); imgix.init(); } /** * Fade out the placeholder image, effectively showing the image behind it. * * Once the fade out transition has completed, remove any temporary properties * from the full-size image (so it gets back to being a clone of the * placeholder, with the full-size src). * * Finally, remove the placeholder image from the DOM since we don't need it * any more. */ transitionImg() { if (!this.placeholderImg) return true; this.fadeOutPlaceholder(); setTimeout(() => { this.removeFullSizeImgProperties(); this.removePlaceholderImg(); this.unwrapImg(); this.transitioning = false; }, this.timeToFade); } /** * Fade out the placeholder image. */ fadeOutPlaceholder() { this.placeholderImg.fadeTo(this.timeToFade, 0); } /** * Remove temporary styles and class from the full-size image, which * effectively means it has replaced the placeholder image. */ removeFullSizeImgProperties() { this.fullSizeImg.removeAttr('style'); // TODO: Update this with how the class is handled above. this.fullSizeImg.removeClass('imgix-optimizing'); } /** * Remove the placeholder image from the DOM since we no longer need it. */ removePlaceholderImg() { if (!this.placeholderImg) { return; } this.placeholderImg.remove(); this.placeholderImg = undefined; } /** * Remove the temporary wrapper and and give the margin back to the image. */ unwrapImg() { this.fullSizeImg.css("margin", this.tmpWrapper.css("margin")); if(navigator.userAgent.toLowerCase().indexOf('firefox') === -1){ this.fullSizeImg.unwrap(); } } }
33.224265
94
0.661281
dbbd798ab59f9535899fee0b84543e4061b6e316
3,019
js
JavaScript
node_modules/facebook-nodejs-business-sdk/src/objects/extended-credit.js
miguelaf4/UmbraWebsite
72925ba2476801166a72f704141bad1d7ae8dbeb
[ "RSA-MD" ]
null
null
null
node_modules/facebook-nodejs-business-sdk/src/objects/extended-credit.js
miguelaf4/UmbraWebsite
72925ba2476801166a72f704141bad1d7ae8dbeb
[ "RSA-MD" ]
null
null
null
node_modules/facebook-nodejs-business-sdk/src/objects/extended-credit.js
miguelaf4/UmbraWebsite
72925ba2476801166a72f704141bad1d7ae8dbeb
[ "RSA-MD" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the * LICENSE file in the root directory of this source tree. * @flow */ import {AbstractCrudObject} from './../abstract-crud-object'; import AbstractObject from './../abstract-object'; import Cursor from './../cursor'; import ExtendedCreditInvoiceGroup from './extended-credit-invoice-group'; import ExtendedCreditAllocationConfig from './extended-credit-allocation-config'; /** * ExtendedCredit * @extends AbstractCrudObject * @see {@link https://developers.facebook.com/docs/marketing-api/} */ export default class ExtendedCredit extends AbstractCrudObject { static get Fields (): Object { return Object.freeze({ allocated_amount: 'allocated_amount', balance: 'balance', credit_available: 'credit_available', credit_type: 'credit_type', id: 'id', is_access_revoked: 'is_access_revoked', is_automated_experience: 'is_automated_experience', legal_entity_name: 'legal_entity_name', liable_biz_name: 'liable_biz_name', max_balance: 'max_balance', online_max_balance: 'online_max_balance', owner_business: 'owner_business', owner_business_name: 'owner_business_name', partition_from: 'partition_from', receiving_credit_allocation_config: 'receiving_credit_allocation_config', send_bill_to_biz_name: 'send_bill_to_biz_name', }); } getExtendedCreditInvoiceGroups (fields: Array<string>, params: Object = {}, fetchFirstPage: boolean = true): Cursor | Promise<*> { return this.getEdge( ExtendedCreditInvoiceGroup, fields, params, fetchFirstPage, '/extended_credit_invoice_groups' ); } createExtendedCreditInvoiceGroup (fields: Array<string>, params: Object = {}): Promise<ExtendedCreditInvoiceGroup> { return this.createEdge( '/extended_credit_invoice_groups', fields, params, ExtendedCreditInvoiceGroup ); } getOwningCreditAllocationConfigs (fields: Array<string>, params: Object = {}, fetchFirstPage: boolean = true): Cursor | Promise<*> { return this.getEdge( ExtendedCreditAllocationConfig, fields, params, fetchFirstPage, '/owning_credit_allocation_configs' ); } createOwningCreditAllocationConfig (fields: Array<string>, params: Object = {}): Promise<ExtendedCreditAllocationConfig> { return this.createEdge( '/owning_credit_allocation_configs', fields, params, ExtendedCreditAllocationConfig ); } createWhatsappCreditSharingAndAttach (fields: Array<string>, params: Object = {}): Promise<AbstractObject> { return this.createEdge( '/whatsapp_credit_sharing_and_attach', fields, params, ); } get (fields: Array<string>, params: Object = {}): ExtendedCredit { // $FlowFixMe : Support Generic Types return this.read( fields, params ); } }
30.494949
134
0.697913
dbbdeb5a2dd8cffd4a609b175472c9c8d7ab0f16
65
js
JavaScript
app/pages/Editor/CrdtEditor/index.js
abdallahMansour/ESSA-6907
b05ad4c5a17360d8fd1bbfd186c692153000dd35
[ "MIT" ]
null
null
null
app/pages/Editor/CrdtEditor/index.js
abdallahMansour/ESSA-6907
b05ad4c5a17360d8fd1bbfd186c692153000dd35
[ "MIT" ]
1
2020-07-17T17:40:05.000Z
2020-07-17T17:40:05.000Z
app/pages/Editor/CrdtEditor/index.js
abdallahMansour/ESSA-6907
b05ad4c5a17360d8fd1bbfd186c692153000dd35
[ "MIT" ]
null
null
null
import CrdtEditor from './CrdtEditor' export default CrdtEditor
16.25
37
0.815385
dbbe02cc7f9cae551a314239961ff23dba3ec12c
798
js
JavaScript
app/assets/scripts/components/assets-section-row.js
vnopenroads/openroads-vn-analytics
27edfc9e8808a1155f2a47c5ca21ed209f0babfc
[ "BSD-2-Clause" ]
null
null
null
app/assets/scripts/components/assets-section-row.js
vnopenroads/openroads-vn-analytics
27edfc9e8808a1155f2a47c5ca21ed209f0babfc
[ "BSD-2-Clause" ]
15
2021-03-09T09:25:11.000Z
2022-02-12T12:39:08.000Z
app/assets/scripts/components/assets-section-row.js
vnopenroads/openroads-vn-analytics
27edfc9e8808a1155f2a47c5ca21ed209f0babfc
[ "BSD-2-Clause" ]
3
2020-09-23T07:27:38.000Z
2020-09-25T02:18:41.000Z
'use strict'; import React from 'react'; const AssetsSectionRow = React.createClass({ 'displayName': 'AssetsSectionRow', propTypes: { data: React.PropTypes.array, onMouseOver: React.PropTypes.func, onMouseOut: React.PropTypes.func }, handleMouseOver: function () { const { data, onMouseOver } = this.props; onMouseOver(data[0]); }, handleMouseOut: function () { const { data, onMouseOut } = this.props; onMouseOut(data[0]); }, render: function () { const { data } = this.props; return ( <tr onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut}> {data.map((val, i) => { return ( <td key={i}>{val}</td> ); })} </tr> ); } }); module.exports = AssetsSectionRow;
20.461538
78
0.591479
dbbe7e884675d257bfcb33b0edf398652b403499
373
js
JavaScript
src/card.js
OfozorObianuju/robots
21fe514b05a125e93d664b0639229a1707d151ed
[ "MIT" ]
null
null
null
src/card.js
OfozorObianuju/robots
21fe514b05a125e93d664b0639229a1707d151ed
[ "MIT" ]
8
2020-09-07T10:26:49.000Z
2022-02-26T18:15:40.000Z
src/card.js
OfozorObianuju/robots
21fe514b05a125e93d664b0639229a1707d151ed
[ "MIT" ]
null
null
null
import React from 'react'; const Card = (props) => { return ( <div className='tc bg-light-green dib br3 pa3 ma2 grow bw2 shadow-5 '> <img alt='robots' src={`http://robohash.org/${props.id}test?200200`} /> <div> <h2>{ props.name}</h2> <p>{props.email}</p> </div> </div> ); } export default Card;
24.866667
81
0.509383
dbbfb2a5d857c814b463f616e5501f8dff391c28
759
js
JavaScript
lib/adapter.js
smashwilson/hubot-harness
f751ee6f472cf2c9ce12a6c812750cd0af61e9b2
[ "MIT" ]
1
2020-09-02T16:03:03.000Z
2020-09-02T16:03:03.000Z
lib/adapter.js
smashwilson/hubot-harness
f751ee6f472cf2c9ce12a6c812750cd0af61e9b2
[ "MIT" ]
20
2021-06-07T06:07:00.000Z
2022-03-25T10:03:16.000Z
lib/adapter.js
smashwilson/hubot-harness
f751ee6f472cf2c9ce12a6c812750cd0af61e9b2
[ "MIT" ]
null
null
null
const Hubot = require("hubot/es2015"); class Adapter extends Hubot.Adapter { constructor(robot) { super(robot); this.subscribers = []; } send(envelope, ...strings) { for (const string of strings) { for (const subscriber of this.subscribers) { subscriber({...envelope, message: string}); } } } reply(envelope, ...strings) { this.send(envelope, ...strings.map((s) => `${envelope.user.name}: ${s}`)); } run() { // } close() { this.subscribers = []; } onDidProduceMessage(callback) { this.subscribers.push(callback); return { dispose: () => { this.subscribers = this.subscribers.filter((cb) => cb !== callback); }, }; } } module.exports = {Adapter};
18.071429
78
0.566535
dbc06e98ad90be743fd5816a278a85d6cc216a80
9,519
js
JavaScript
swagger/news.js
Weislife/egg-swagger-joi
ab397d44335c47fe726d56e3cc29405eed0f11f5
[ "MIT" ]
5
2018-07-31T02:17:42.000Z
2019-01-15T07:10:25.000Z
swagger/news.js
Weislife/egg-swagger-joi
ab397d44335c47fe726d56e3cc29405eed0f11f5
[ "MIT" ]
null
null
null
swagger/news.js
Weislife/egg-swagger-joi
ab397d44335c47fe726d56e3cc29405eed0f11f5
[ "MIT" ]
null
null
null
'use strict'; module.exports = function(Joi) { return { tag: { name: 'Site', description: '官网管理' }, paths: { '/v1/manage/site/news': { get: { summary: '新闻列表(后台)', tags: [ 'Site' ], parameters: { headers: Joi.object().keys({ authorization: Joi.string().required().description('Bearer + 空格 + token'), }).unknown({ allow: true }), query: Joi.object().keys({ page_number: Joi.number().integer().greater(0).required().description('第几页'), page_size: Joi.number().integer().greater(0).required().description('每页展示数据数目'), title: Joi.string().empty('').optional().description('标题'), category: Joi.number().integer().valid(1, 2, 3, 4, 5).allow('', 'all').required().description('分类 all表示所有 1游戏产品;2科普知识;3行业新闻;4合作;5其他'), is_focus: Joi.boolean().allow('', 'all').required().description('是否重点新闻 all表示所有 true 重点新闻 false 非重点新闻'), }), }, responses: { 200: { description: 'Success', schema: Joi.object().keys({ data: Joi.object().keys({}).unknown({ allow: true }), }), }, default: { description: 'Error happened', schema: Joi.object().keys({ message: Joi.string(), }), }, }, }, post: { summary: '添加新闻(后台)', tags: [ 'Site' ], parameters: { headers: Joi.object().keys({ authorization: Joi.string().required().description('Bearer + 空格 + token'), }).unknown({ allow: true }), body: Joi.object().keys({ title: Joi.string().required().description('新闻标题'), description: Joi.string().required().description('描述'), category: Joi.number().integer().valid(1, 2, 3, 4, 5).required().description('分类 1游戏产品;2科普知识;3行业新闻;4合作;5其他'), is_focus: Joi.boolean().required().description('是否重点新闻 true 重点新闻 false 非重点新闻'), news_img_url: Joi.string().required().description('新闻宣传图'), content: Joi.string().required().description('新闻内容'), sort_id: Joi.number().integer().greater(-1).required().description('排序id,数值越大排序越靠前'), }), }, responses: { 200: { description: 'Success', schema: Joi.object().keys({ data: Joi.object().keys({}).unknown({ allow: true }), }), }, default: { description: 'Error happened', schema: Joi.object().keys({ message: Joi.string(), }), }, }, }, }, '/v1/manage/site/news/{id}': { get: { summary: '获取新闻信息(后台)', tags: [ 'Site' ], parameters: { headers: Joi.object().keys({ authorization: Joi.string().required().description('Bearer + 空格 + token'), }).unknown({ allow: true }), pathParams: Joi.object().keys({ id: Joi.string().mongodbId().required().description('id'), }), }, responses: { 200: { description: 'Success', schema: Joi.object().keys({ data: Joi.object().keys({}).unknown({ allow: true }), }), }, default: { description: 'Error happened', schema: Joi.object().keys({ message: Joi.string(), }), }, }, }, put: { summary: '更新新闻(后台)', tags: [ 'Site' ], parameters: { headers: Joi.object().keys({ authorization: Joi.string().required().description('Bearer + 空格 + token'), }).unknown({ allow: true }), pathParams: Joi.object().keys({ id: Joi.string().mongodbId().required().description('id'), }), body: Joi.object().keys({ title: Joi.string().required().description('新闻标题'), description: Joi.string().required().description('描述'), category: Joi.number().integer().valid(1, 2, 3, 4, 5).required().description('分类 1游戏产品;2科普知识;3行业新闻;4合作;5其他'), is_focus: Joi.boolean().required().description('是否重点新闻 true 重点新闻 false 非重点新闻'), news_img_url: Joi.string().required().description('新闻宣传图'), content: Joi.string().required().description('新闻内容'), sort_id: Joi.number().integer().greater(-1).required().description('排序id,数值越大排序越靠前'), state: Joi.number().valid(0, 1, 2, 3).required().description('1 待上架, 2 上架, 3 下架'), }), }, responses: { 200: { description: 'Success', schema: Joi.object().keys({ data: Joi.object().keys({}).unknown({ allow: true }), }), }, default: { description: 'Error happened', schema: Joi.object().keys({ message: Joi.string(), }), }, }, }, delete: { summary: '删除新闻(后台)', tags: [ 'Site' ], parameters: { headers: Joi.object().keys({ authorization: Joi.string().required().description('Bearer + 空格 + token'), }).unknown({ allow: true }), pathParams: Joi.object().keys({ id: Joi.string().mongodbId().required().description('id'), }), }, responses: { 200: { description: 'Success', schema: Joi.object().keys({ data: Joi.object().keys({}).unknown({ allow: true }), }), }, default: { description: 'Error happened', schema: Joi.object().keys({ message: Joi.string(), }), }, }, }, }, '/v1/site/news/{id}': { get: { summary: '获取新闻内容(客户端)', tags: [ 'Site' ], parameters: { pathParams: Joi.object().keys({ id: Joi.string().mongodbId().required().description('id'), }), }, responses: { 200: { description: 'Success', schema: Joi.object().keys({ data: Joi.object().keys({ title: Joi.string().required().description('新闻标题'), description: Joi.string().required().description('描述'), category: Joi.number().integer().valid(1, 2, 3, 4, 5).required().description('分类 1游戏产品;2科普知识;3行业新闻;4合作;5其他'), is_focus: Joi.boolean().required().description('是否重点新闻 true 重点新闻 false 非重点新闻'), news_img_url: Joi.string().required().description('新闻宣传图'), content: Joi.string().required().description('新闻内容'), create_time: Joi.string().required().description('创建时间'), }), }), }, default: { description: 'Error happened', schema: Joi.object().keys({ message: Joi.string(), }), }, }, }, }, '/v1/site/news': { get: { summary: '新闻列表(客户端)', tags: [ 'Site' ], parameters: { query: Joi.object().keys({ page_number: Joi.number().integer().greater(0).required().description('第几页'), page_size: Joi.number().integer().greater(0).required().description('每页展示数据数目'), category: Joi.number().integer().valid(0, 1, 2, 3, 4, 5).required().description('分类 0所有 1游戏产品;2科普知识;3行业新闻;4合作;5其他'), is_focus: Joi.boolean().valid('', true, false).optional().description('是否重点新闻 空字符串为所有 true 重点新闻 false 非重点新闻'), }), }, responses: { 200: { description: 'Success', schema: Joi.object().keys({ data: Joi.object().keys({ page_number: Joi.number().integer().greater(0).required().description('第几页'), page_size: Joi.number().integer().greater(0).required().description('每页展示数据数目'), count: Joi.number().integer().required().description('总数目'), list: Joi.array().items(Joi.object().keys({ id: Joi.string().mongodbId().required().description('id'), title: Joi.string().required().description('新闻标题'), description: Joi.string().required().description('描述'), category: Joi.number().integer().valid(1, 2, 3, 4, 5).required().description('分类 1游戏产品;2科普知识;3行业新闻;4合作;5其他'), is_focus: Joi.boolean().required().description('是否重点新闻 true 重点新闻 false 非重点新闻'), news_img_url: Joi.string().required().description('新闻宣传图'), create_time: Joi.string().required().description('创建时间'), })), }), }), }, default: { description: 'Error happened', schema: Joi.object().keys({ message: Joi.string(), }), }, }, }, }, }, }; };
39.995798
148
0.463179
dbc08634dbed8a0dc8a54a191d4df93caa860fa7
1,260
js
JavaScript
src/navigation/BottomTabNavigator.js
Jamaru99/Fidelity-Company
33ad8326257ff2c96c529544c9378d0bfa5462c9
[ "MIT" ]
null
null
null
src/navigation/BottomTabNavigator.js
Jamaru99/Fidelity-Company
33ad8326257ff2c96c529544c9378d0bfa5462c9
[ "MIT" ]
null
null
null
src/navigation/BottomTabNavigator.js
Jamaru99/Fidelity-Company
33ad8326257ff2c96c529544c9378d0bfa5462c9
[ "MIT" ]
null
null
null
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import * as React from 'react'; import TabBarIcon from '../components/TabBarIcon'; import { ProfileScreen, QRCodeScreen } from '@screens'; const BottomTab = createBottomTabNavigator(); const INITIAL_ROUTE_NAME = 'Home'; export default function BottomTabNavigator({ navigation, route }) { navigation.setOptions({ headerTitle: getHeaderTitle(route) }); return ( <BottomTab.Navigator initialRouteName={INITIAL_ROUTE_NAME}> <BottomTab.Screen name="Home" component={QRCodeScreen} options={{ title: 'QR Code', tabBarIcon: ({ focused }) => <TabBarIcon focused={focused} name="qrcode" />, }} /> <BottomTab.Screen name="Info" component={ProfileScreen} options={{ title: 'Info', tabBarIcon: ({ focused }) => <TabBarIcon focused={focused} name="information" />, }} /> </BottomTab.Navigator> ); } function getHeaderTitle(route) { const routeName = route.state?.routes[route.state.index]?.name ?? INITIAL_ROUTE_NAME switch (routeName) { case 'Home': return 'Cartão Fidelidade - QR Code' case 'Info': return 'Meus dados' } }
27.391304
91
0.639683
dbc19dfb3fc32df4eefb833be16c7cba5ec31e3e
110
js
JavaScript
server/publications/column.js
palakbhansali/cross-tab
7237eae4f83c2393c6c02058b6bb3a3a1eb16138
[ "MIT" ]
null
null
null
server/publications/column.js
palakbhansali/cross-tab
7237eae4f83c2393c6c02058b6bb3a3a1eb16138
[ "MIT" ]
null
null
null
server/publications/column.js
palakbhansali/cross-tab
7237eae4f83c2393c6c02058b6bb3a3a1eb16138
[ "MIT" ]
null
null
null
/** * Created by Dhingu on 5/4/15. */ Meteor.publish('columns', function () { return Column.find(); });
15.714286
39
0.590909
dbc24b0740023de3db08eaa858eb7f5a071c5d1d
1,928
js
JavaScript
client/store/transactions.js
Thanh-Lai/TTP-FS
86f1f98bf743e811d92e28892ced13d23d7b0e1e
[ "MIT" ]
null
null
null
client/store/transactions.js
Thanh-Lai/TTP-FS
86f1f98bf743e811d92e28892ced13d23d7b0e1e
[ "MIT" ]
2
2021-03-09T08:35:04.000Z
2021-05-09T06:05:50.000Z
client/store/transactions.js
Thanh-Lai/TTP-FS
86f1f98bf743e811d92e28892ced13d23d7b0e1e
[ "MIT" ]
null
null
null
import axios from 'axios' //Action types const GET_TRANSACTIONS = 'GET_TRANSACTIONS' const POST_TRANSACTION = 'POST_TRANSACTION' const UPDATE_UNIQUE_TRANSACTIONS = 'UPDATE_UNIQUE_TRANSACTIONS' //Initial State const initialState = { allTransactions: [], uniqueTransactions: {} } //Action creators const getTransactions = allTransactions => ({type: GET_TRANSACTIONS, allTransactions}) const createTransaction = transaction => ({type: POST_TRANSACTION, transaction}) const updateUniqueTransactions = transactions => ({type: UPDATE_UNIQUE_TRANSACTIONS, transactions}) //Thunk creators export const fetchTransactions = (id) => { return dispatch => { axios.get(`/api/transactions/${id}`) .then(res => res.data) .then(allTransactions => { dispatch(getTransactions(allTransactions)) }) .catch(console.error) } } export const postTransaction = (transaction) => { return dispatch => { axios.post('/api/transactions', transaction) .then(res => res.data) .then(createdTransaction => { dispatch(createTransaction(createdTransaction)) }) .catch(console.error) } } export const updateUnique = (transactions) => { return dispatch => { dispatch(updateUniqueTransactions(transactions)) } } //Reducers export default function (state = initialState, action) { switch (action.type) { case GET_TRANSACTIONS: return { ...state, allTransactions: action.allTransactions } case POST_TRANSACTION: return { ...state, allTransactions: [...state.allTransactions, action.transaction] } case UPDATE_UNIQUE_TRANSACTIONS: return { ...state, uniqueTransactions: action.transactions } default: return state } }
27.542857
99
0.629149
dbc2b2b1bfcb1748977c6134c5e0c834e0a7b78d
204
js
JavaScript
src/views/PersonPage/Settings/routes.js
frontend-park-mail-ru/2020_1_Joblessness
73c4580562b328ef3ad406f1a87ed9cd9d0ff1dd
[ "MIT" ]
1
2020-02-10T15:48:57.000Z
2020-02-10T15:48:57.000Z
src/views/PersonPage/Settings/routes.js
frontend-park-mail-ru/2020_1_Joblessness
73c4580562b328ef3ad406f1a87ed9cd9d0ff1dd
[ "MIT" ]
11
2020-02-21T10:54:13.000Z
2022-02-27T00:20:01.000Z
src/views/PersonPage/Settings/routes.js
frontend-park-mail-ru/2020_1_Joblessness
73c4580562b328ef3ad406f1a87ed9cd9d0ff1dd
[ "MIT" ]
null
null
null
import {SubRoutes, ROOT_ELEMENT} from './SubRoutes'; const Routes = [ { path: '/*settings', element: ROOT_ELEMENT, childRoutes: [ ...SubRoutes, ], }, ]; export default Routes;
14.571429
52
0.593137
dbc39061f3dbd97d0ae87e78b06cce95675884c1
349
js
JavaScript
app/pods/dashboard/index/controller.js
NullVoxPopuli/aeonvera-ui
9ffbb2033ebc9a6a0cb18b2bba5273f55c540292
[ "MIT" ]
4
2015-05-17T18:42:59.000Z
2016-03-17T17:24:24.000Z
app/pods/dashboard/index/controller.js
NullVoxPopuli/aeonvera-ui
9ffbb2033ebc9a6a0cb18b2bba5273f55c540292
[ "MIT" ]
367
2015-05-13T03:20:15.000Z
2018-05-16T10:14:21.000Z
app/pods/dashboard/index/controller.js
NullVoxPopuli/aeonvera-ui
9ffbb2033ebc9a6a0cb18b2bba5273f55c540292
[ "MIT" ]
2
2016-01-28T18:39:25.000Z
2016-03-03T22:01:22.000Z
import Ember from 'ember'; import { alias } from 'ember-decorators/object/computed'; const { inject } = Ember; export default Ember.Controller.extend({ session: inject.service('session'), @alias('session.currentUser') currentUser: null, @alias('model.upcoming') upcomingEvents: null, @alias('model.hosted') upcomingHostedEvents: null });
26.846154
57
0.730659
dbc3980a31382d7a72a987a9fb0e81c7511417e5
693
js
JavaScript
constants/hubs.js
Shashank151090/react-native
26e7a84355dbcd3a59a4351063901eff17de5d0d
[ "MIT" ]
null
null
null
constants/hubs.js
Shashank151090/react-native
26e7a84355dbcd3a59a4351063901eff17de5d0d
[ "MIT" ]
null
null
null
constants/hubs.js
Shashank151090/react-native
26e7a84355dbcd3a59a4351063901eff17de5d0d
[ "MIT" ]
null
null
null
export default [ { title: 'Hub 1', src : require('../assets/imgs/hub-default.png'), cta: 'View hub', mac: '1234-xxxx-xxxx-5678' }, { title: 'Hub 2', src : require('../assets/imgs/hub-default.png'), cta: 'View hub', mac: '1234-xxxx-xxxx-5678' }, { title: 'Hub 3', src : require('../assets/imgs/hub-default.png'), cta: 'View hub', mac: '1234-xxxx-xxxx-5678' }, { title: 'Hub 4', src : require('../assets/imgs/hub-default.png'), cta: 'View hub', mac: '1234-xxxx-xxxx-5678' }, { title: 'Hub 5', src : require('../assets/imgs/hub-default.png'), cta: 'View hub', mac: '1234-xxxx-xxxx-5678' }, ];
21.65625
52
0.531025
dbc43ee9d1539083607bc222456b9a86dded4315
374
js
JavaScript
perms.js
our-lab-training/olt-plugin-content
a94e59726996d1c85a815b8c2f73f34d7a785771
[ "MIT" ]
null
null
null
perms.js
our-lab-training/olt-plugin-content
a94e59726996d1c85a815b8c2f73f34d7a785771
[ "MIT" ]
null
null
null
perms.js
our-lab-training/olt-plugin-content
a94e59726996d1c85a815b8c2f73f34d7a785771
[ "MIT" ]
null
null
null
module.exports = groupId => [ { text: 'Content - View Visible', value: `${groupId}.content.read`, defaultRoles: ['user', 'moderator', 'admin'] }, { text: 'Content - View Hidden', value: `${groupId}.content.read-hidden`, defaultRoles: ['moderator', 'admin'] }, { text: 'Content - Edit All', value: `${groupId}.content.write`, defaultRoles: ['moderator', 'admin'] }, ];
62.333333
117
0.639037
dbc4539e37b8e755bbe7e6805edcd15ffd8d2e0f
204
js
JavaScript
src/main/utils/EmailUtil.js
greatbsky/ES6MVC
b28ebd9931a0228e2ef098ff6578b3b0607a4da8
[ "Apache-2.0" ]
1
2016-09-29T02:25:12.000Z
2016-09-29T02:25:12.000Z
src/main/utils/EmailUtil.js
greatbsky/ES6MVC
b28ebd9931a0228e2ef098ff6578b3b0607a4da8
[ "Apache-2.0" ]
null
null
null
src/main/utils/EmailUtil.js
greatbsky/ES6MVC
b28ebd9931a0228e2ef098ff6578b3b0607a4da8
[ "Apache-2.0" ]
null
null
null
'use strict'; /** * email工具类 * @author Architect.bian */ var log = Log(__filename); module.exports = class EmailUtil { static send() { log.debug('send()'); return true; } }
12
34
0.558824
dbc487e8ddb16133e0979fe907aafc462763df85
1,353
js
JavaScript
02-JS-Language-Fundamentals/11-If-Statements-Comparison-Operators/app.js
0x00000024/learn-javascript
3687ed917a61ab93cae915dfa52ce50e97dd955e
[ "MIT" ]
null
null
null
02-JS-Language-Fundamentals/11-If-Statements-Comparison-Operators/app.js
0x00000024/learn-javascript
3687ed917a61ab93cae915dfa52ce50e97dd955e
[ "MIT" ]
null
null
null
02-JS-Language-Fundamentals/11-If-Statements-Comparison-Operators/app.js
0x00000024/learn-javascript
3687ed917a61ab93cae915dfa52ce50e97dd955e
[ "MIT" ]
null
null
null
const id = 100; // EQUAL TO if (id == 100) { console.log('CORRECT'); } else { console.log('INCORRECT'); } // NOT EQUAL TO if (id != 101) { console.log('CORRECT'); } else { console.log('INCORRECT'); } // EQUAl TO VALUE & TYPE if (id === 100) { console.log('CORRECT'); } else { console.log('INCORRECT'); } // Test if undefined if (typeof id !== 'undefined') { console.log(`The ID is ${id}`); } else { console.log('NO ID'); } // GREATER OR LESS THANN if (id >= 100) { console.log('CORRECT'); } else { console.log('INCORRECT'); } // IF ELSE const color = 'blue'; if (color === 'red') { console.log('Color is red'); } else if (color === 'blue') { console.log('Color is blue'); } else { console.log('Color is not red or blue'); } // LOGICAL OPERATORS const name = 'Ethan'; const age = 23; if (age > 0 && age < 12) { console.log(`${name} is a child`); } else if (age >= 12 && age <= 19) { console.log(`${name} is a teenager`); } else { console.log(`${name} is an adult`); } // OR || if (age < 16 || age > 65) { console.log(`${name} can not run in race`); } else { console.log(`${name} is registered for the race`); } // Ternary console.log(id === 100 ? 'CORRECT' : 'INCORRECT'); // WITHOUT BRACES if (id === 100) console.log('CORRECT'); else console.log('INCORRECT');
17.802632
54
0.562454
dbc48f54710de6e21b4323c7c7e274c224dd5c34
223
js
JavaScript
src/config/mail.js
Fbueno12/gymPoint
2b295023b8aa8ce952c9e62aa241041ef8a70897
[ "MIT" ]
null
null
null
src/config/mail.js
Fbueno12/gymPoint
2b295023b8aa8ce952c9e62aa241041ef8a70897
[ "MIT" ]
3
2021-05-08T10:39:45.000Z
2021-09-02T01:33:45.000Z
src/config/mail.js
Fbueno12/gymPoint-backend
2b295023b8aa8ce952c9e62aa241041ef8a70897
[ "MIT" ]
null
null
null
export default { host: 'smtp.mailtrap.io', port: 2525, secure: false, auth: { user: '580f4db3556d47', pass: 'ee521a89418700', }, default: { from: 'Equipe gymPoint <noreply@gympoint.com.br>', }, };
17.153846
54
0.605381
dbc4be78598db3c3352b1e723970aa2ca65a0a77
1,085
js
JavaScript
frontend/src/pages/Login/styles.js
mateusbzerra/edef-exam-generator
15f5b7727dae0d4ad7df71613703eca85adb5f44
[ "MIT" ]
null
null
null
frontend/src/pages/Login/styles.js
mateusbzerra/edef-exam-generator
15f5b7727dae0d4ad7df71613703eca85adb5f44
[ "MIT" ]
5
2021-05-08T09:20:37.000Z
2022-02-26T19:13:51.000Z
frontend/src/pages/Login/styles.js
mateusbzerra/edef-exam-generator
15f5b7727dae0d4ad7df71613703eca85adb5f44
[ "MIT" ]
null
null
null
import styled from 'styled-components'; export const Container = styled.div` height: 100%; background: #6986be; display: flex; align-items: center; justify-content: center; `; export const Content = styled.form` background: #eee; display: flex; flex-direction: column; width: 100%; max-width: 350px; padding: 20px; border-radius: 10px; `; export const Input = styled.input` margin-bottom: 10px; height: 44px; border: none; padding: 0px 10px; border-radius: 5px; font-size: 14px; `; export const Image = styled.img` max-width: 100%; width: 100%; margin-bottom: 20px; `; export const Button = styled.button` height: 50px; background: #40426e; display: flex; align-items: center; justify-content: center; border-radius: 10px; color: #fff; font-weight: bold; font-size: 15px; margin-top: 10px; margin-bottom: 10px; `; export const Label = styled.p` font-size: 15px; margin: 10px 0px; color: #40426e; `; export const Error = styled.p` color: #f54; font-size: 13px; text-align: center; margin-bottom: 0px; `;
18.389831
39
0.671889
dbc590c94a49091bebc1a61e3ca7c97c295d3077
411
js
JavaScript
reaction/src/Todo.js
mrngoitall/the-vue-reaction
ebbb51a89d0a5a6395589ad2656abd89b9fc8278
[ "MIT" ]
2
2017-09-20T23:59:14.000Z
2017-09-21T01:19:15.000Z
reaction/src/Todo.js
mrngoitall/the-vue-reaction
ebbb51a89d0a5a6395589ad2656abd89b9fc8278
[ "MIT" ]
1
2017-09-21T05:51:28.000Z
2017-09-21T05:51:28.000Z
reaction/src/Todo.js
mrngoitall/the-vue-reaction
ebbb51a89d0a5a6395589ad2656abd89b9fc8278
[ "MIT" ]
5
2017-09-21T01:02:33.000Z
2017-09-21T17:17:12.000Z
import React from 'react' import pt from 'prop-types' export const Todo = (props) => ( <div> { props.todo.value }{ ' ' } <button onClick={ (e) => { e.preventDefault() props.onDelete(props.todo.id) }}> [X] </button> </div> ) Todo.defaultProps = { todo: {}, onDelete() {} } Todo.propTypes = { todo: pt.shape({value: pt.string, id: pt.string}), onDelete: pt.func }
16.44
52
0.559611
dbc6298e39773c18296acbf3a8b21a5360803f24
16,079
js
JavaScript
admin/js/jsplumb/jsPlumb-renderers-vml-1.3.13-RC1.js
Dealerpriest/weather-sound-spacebrew
0f799b872d14ba4e231959125d6068608ce0d109
[ "MIT" ]
117
2015-01-06T00:54:42.000Z
2022-03-10T18:50:28.000Z
admin/js/jsplumb/jsPlumb-renderers-vml-1.3.13-RC1.js
Dealerpriest/weather-sound-spacebrew
0f799b872d14ba4e231959125d6068608ce0d109
[ "MIT" ]
29
2015-01-20T08:27:19.000Z
2019-11-06T01:03:32.000Z
admin/js/jsplumb/jsPlumb-renderers-vml-1.3.13-RC1.js
Dealerpriest/weather-sound-spacebrew
0f799b872d14ba4e231959125d6068608ce0d109
[ "MIT" ]
27
2015-01-18T00:29:42.000Z
2021-09-17T21:52:15.000Z
/* * jsPlumb * * Title:jsPlumb 1.3.13 * * Provides a way to visually connect elements on an HTML page, using either SVG, Canvas * elements, or VML. * * This file contains the VML renderers. * * Copyright (c) 2010 - 2012 Simon Porritt (http://jsplumb.org) * * http://jsplumb.org * http://github.com/sporritt/jsplumb * http://code.google.com/p/jsplumb * * Dual licensed under the MIT and GPL2 licenses. */ ;(function() { // http://ajaxian.com/archives/the-vml-changes-in-ie-8 // http://www.nczonline.net/blog/2010/01/19/internet-explorer-8-document-and-browser-modes/ // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/ var vmlAttributeMap = { "stroke-linejoin":"joinstyle", "joinstyle":"joinstyle", "endcap":"endcap", "miterlimit":"miterlimit" }, jsPlumbStylesheet = null; if (document.createStyleSheet && document.namespaces) { var ruleClasses = [ ".jsplumb_vml", "jsplumb\\:textbox", "jsplumb\\:oval", "jsplumb\\:rect", "jsplumb\\:stroke", "jsplumb\\:shape", "jsplumb\\:group" ], rule = "behavior:url(#default#VML);position:absolute;"; jsPlumbStylesheet = document.createStyleSheet(); for (var i = 0; i < ruleClasses.length; i++) jsPlumbStylesheet.addRule(ruleClasses[i], rule); // in this page it is also mentioned that IE requires the extra arg to the namespace // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/ // but someone commented saying they didn't need it, and it seems jsPlumb doesnt need it either. // var iev = document.documentMode; //if (!iev || iev < 8) document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml"); //else // document.namespaces.add("jsplumb", "urn:schemas-microsoft-com:vml", "#default#VML"); } jsPlumb.vml = {}; var scale = 1000, _groupMap = {}, _getGroup = function(container, connectorClass) { var id = jsPlumb.getId(container), g = _groupMap[id]; if(!g) { g = _node("group", [0,0,scale, scale], {"class":connectorClass}); //g.style.position=absolute; //g["coordsize"] = "1000,1000"; g.style.backgroundColor="red"; _groupMap[id] = g; jsPlumb.appendElement(g, container); // todo if this gets reinstated, remember to use the current jsplumb instance. //document.body.appendChild(g); } return g; }, _atts = function(o, atts) { for (var i in atts) { // IE8 fix: setattribute does not work after an element has been added to the dom! // http://www.louisremi.com/2009/03/30/changes-in-vml-for-ie8-or-what-feature-can-the-ie-dev-team-break-for-you-today/ //o.setAttribute(i, atts[i]); /*There is an additional problem when accessing VML elements by using get/setAttribute. The simple solution is following: if (document.documentMode==8) { ele.opacity=1; } else { ele.setAttribute(‘opacity’,1); } */ o[i] = atts[i]; } }, _node = function(name, d, atts, parent, _jsPlumb, deferToJsPlumbContainer) { atts = atts || {}; var o = document.createElement("jsplumb:" + name); if (deferToJsPlumbContainer) _jsPlumb.appendElement(o, parent); else jsPlumb.CurrentLibrary.appendElement(o, parent); o.className = (atts["class"] ? atts["class"] + " " : "") + "jsplumb_vml"; _pos(o, d); _atts(o, atts); return o; }, _pos = function(o,d, zIndex) { o.style.left = d[0] + "px"; o.style.top = d[1] + "px"; o.style.width= d[2] + "px"; o.style.height= d[3] + "px"; o.style.position = "absolute"; if (zIndex) o.style.zIndex = zIndex; }, _conv = jsPlumb.vml.convertValue = function(v) { return Math.floor(v * scale); }, // tests if the given style is "transparent" and then sets the appropriate opacity node to 0 if so, // or 1 if not. TODO in the future, support variable opacity. _maybeSetOpacity = function(styleToWrite, styleToCheck, type, component) { if ("transparent" === styleToCheck) component.setOpacity(type, "0.0"); else component.setOpacity(type, "1.0"); }, _applyStyles = function(node, style, component, _jsPlumb) { var styleToWrite = {}; if (style.strokeStyle) { styleToWrite["stroked"] = "true"; var strokeColor = jsPlumbUtil.convertStyle(style.strokeStyle, true); styleToWrite["strokecolor"] = strokeColor; _maybeSetOpacity(styleToWrite, strokeColor, "stroke", component); styleToWrite["strokeweight"] = style.lineWidth + "px"; } else styleToWrite["stroked"] = "false"; if (style.fillStyle) { styleToWrite["filled"] = "true"; var fillColor = jsPlumbUtil.convertStyle(style.fillStyle, true); styleToWrite["fillcolor"] = fillColor; _maybeSetOpacity(styleToWrite, fillColor, "fill", component); } else styleToWrite["filled"] = "false"; if(style["dashstyle"]) { if (component.strokeNode == null) { component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:style["dashstyle"] }, node, _jsPlumb); } else component.strokeNode.dashstyle = style["dashstyle"]; } else if (style["stroke-dasharray"] && style["lineWidth"]) { var sep = style["stroke-dasharray"].indexOf(",") == -1 ? " " : ",", parts = style["stroke-dasharray"].split(sep), styleToUse = ""; for(var i = 0; i < parts.length; i++) { styleToUse += (Math.floor(parts[i] / style.lineWidth) + sep); } if (component.strokeNode == null) { component.strokeNode = _node("stroke", [0,0,0,0], { dashstyle:styleToUse }, node, _jsPlumb); } else component.strokeNode.dashstyle = styleToUse; } _atts(node, styleToWrite); }, /* * Base class for Vml endpoints and connectors. Extends jsPlumbUIComponent. */ VmlComponent = function() { var self = this; jsPlumb.jsPlumbUIComponent.apply(this, arguments); this.opacityNodes = { "stroke":null, "fill":null }; this.initOpacityNodes = function(vml) { self.opacityNodes["stroke"] = _node("stroke", [0,0,1,1], {opacity:"0.0"}, vml, self._jsPlumb); self.opacityNodes["fill"] = _node("fill", [0,0,1,1], {opacity:"0.0"}, vml, self._jsPlumb); }; this.setOpacity = function(type, value) { var node = self.opacityNodes[type]; if (node) node["opacity"] = "" + value; }; var displayElements = [ ]; this.getDisplayElements = function() { return displayElements; }; this.appendDisplayElement = function(el, doNotAppendToCanvas) { if (!doNotAppendToCanvas) self.canvas.parentNode.appendChild(el); displayElements.push(el); }; }, /* * Base class for Vml connectors. extends VmlComponent. */ VmlConnector = jsPlumb.VmlConnector = function(params) { var self = this; self.strokeNode = null; self.canvas = null; VmlComponent.apply(this, arguments); var clazz = self._jsPlumb.connectorClass + (params.cssClass ? (" " + params.cssClass) : ""); this.paint = function(d, style, anchor) { if (style != null) { var path = self.getPath(d), p = { "path":path }; //* if (style.outlineColor) { var outlineWidth = style.outlineWidth || 1, outlineStrokeWidth = style.lineWidth + (2 * outlineWidth), outlineStyle = { strokeStyle : jsPlumbUtil.convertStyle(style.outlineColor), lineWidth : outlineStrokeWidth }; for (var aa in vmlAttributeMap) outlineStyle[aa] = style[aa]; if (self.bgCanvas == null) { p["class"] = clazz; p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale); self.bgCanvas = _node("shape", d, p, params.parent, self._jsPlumb, true); _pos(self.bgCanvas, d, self.getZIndex()); self.appendDisplayElement(self.bgCanvas, true); self.attachListeners(self.bgCanvas, self); self.initOpacityNodes(self.bgCanvas, ["stroke"]); } else { p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale); _pos(self.bgCanvas, d, self.getZIndex()); _atts(self.bgCanvas, p); } _applyStyles(self.bgCanvas, outlineStyle, self); } //*/ if (self.canvas == null) { p["class"] = clazz; p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale); if (self.tooltip) p["label"] = self.tooltip; self.canvas = _node("shape", d, p, params.parent, self._jsPlumb, true); //var group = _getGroup(params.parent); // test of append everything to a group //group.appendChild(self.canvas); // sort of works but not exactly; //params["_jsPlumb"].appendElement(self.canvas, params.parent); //before introduction of groups self.appendDisplayElement(self.canvas, true); self.attachListeners(self.canvas, self); self.initOpacityNodes(self.canvas, ["stroke"]); } else { p["coordsize"] = (d[2] * scale) + "," + (d[3] * scale); _pos(self.canvas, d, self.getZIndex()); _atts(self.canvas, p); } _applyStyles(self.canvas, style, self, self._jsPlumb); } }; //self.appendDisplayElement(self.canvas); this.reattachListeners = function() { if (self.canvas) self.reattachListenersForElement(self.canvas, self); }; }, /* * * Base class for Vml Endpoints. extends VmlComponent. * */ VmlEndpoint = window.VmlEndpoint = function(params) { VmlComponent.apply(this, arguments); var vml = null, self = this, opacityStrokeNode = null, opacityFillNode = null; self.canvas = document.createElement("div"); self.canvas.style["position"] = "absolute"; var clazz = self._jsPlumb.endpointClass + (params.cssClass ? (" " + params.cssClass) : ""); //var group = _getGroup(params.parent); //group.appendChild(self.canvas); params["_jsPlumb"].appendElement(self.canvas, params.parent); if (self.tooltip) self.canvas.setAttribute("label", self.tooltip); this.paint = function(d, style, anchor) { var p = { }; jsPlumb.sizeCanvas(self.canvas, d[0], d[1], d[2], d[3]); if (vml == null) { p["class"] = clazz; vml = self.getVml([0,0, d[2], d[3]], p, anchor, self.canvas, self._jsPlumb); self.attachListeners(vml, self); self.appendDisplayElement(vml, true); self.appendDisplayElement(self.canvas, true); self.initOpacityNodes(vml, ["fill"]); } else { _pos(vml, [0,0, d[2], d[3]]); _atts(vml, p); } _applyStyles(vml, style, self); }; this.reattachListeners = function() { if (vml) self.reattachListenersForElement(vml, self); }; }; jsPlumb.Connectors.vml.Bezier = function() { jsPlumb.Connectors.Bezier.apply(this, arguments); VmlConnector.apply(this, arguments); this.getPath = function(d) { return "m" + _conv(d[4]) + "," + _conv(d[5]) + " c" + _conv(d[8]) + "," + _conv(d[9]) + "," + _conv(d[10]) + "," + _conv(d[11]) + "," + _conv(d[6]) + "," + _conv(d[7]) + " e"; }; }; jsPlumb.Connectors.vml.Straight = function() { jsPlumb.Connectors.Straight.apply(this, arguments); VmlConnector.apply(this, arguments); this.getPath = function(d) { return "m" + _conv(d[4]) + "," + _conv(d[5]) + " l" + _conv(d[6]) + "," + _conv(d[7]) + " e"; }; }; jsPlumb.Connectors.vml.Flowchart = function() { jsPlumb.Connectors.Flowchart.apply(this, arguments); VmlConnector.apply(this, arguments); this.getPath = function(dimensions) { var p = "m " + _conv(dimensions[4]) + "," + _conv(dimensions[5]) + " l"; // loop through extra points for (var i = 0; i < dimensions[8]; i++) { p = p + " " + _conv(dimensions[9 + (i*2)]) + "," + _conv(dimensions[10 + (i*2)]); } // finally draw a line to the end p = p + " " + _conv(dimensions[6]) + "," + _conv(dimensions[7]) + " e"; return p; }; }; jsPlumb.Endpoints.vml.Dot = function() { jsPlumb.Endpoints.Dot.apply(this, arguments); VmlEndpoint.apply(this, arguments); this.getVml = function(d, atts, anchor, parent, _jsPlumb) { return _node("oval", d, atts, parent, _jsPlumb); }; }; jsPlumb.Endpoints.vml.Rectangle = function() { jsPlumb.Endpoints.Rectangle.apply(this, arguments); VmlEndpoint.apply(this, arguments); this.getVml = function(d, atts, anchor, parent, _jsPlumb) { return _node("rect", d, atts, parent, _jsPlumb); }; }; /* * VML Image Endpoint is the same as the default image endpoint. */ jsPlumb.Endpoints.vml.Image = jsPlumb.Endpoints.Image; /** * placeholder for Blank endpoint in vml renderer. */ jsPlumb.Endpoints.vml.Blank = jsPlumb.Endpoints.Blank; /** * VML Label renderer. uses the default label renderer (which adds an element to the DOM) */ jsPlumb.Overlays.vml.Label = jsPlumb.Overlays.Label; /** * VML Custom renderer. uses the default Custom renderer (which adds an element to the DOM) */ jsPlumb.Overlays.vml.Custom = jsPlumb.Overlays.Custom; var AbstractVmlArrowOverlay = function(superclass, originalArgs) { superclass.apply(this, originalArgs); VmlComponent.apply(this, originalArgs); var self = this, path = null; self.canvas = null; self.isAppendedAtTopLevel = true; var getPath = function(d, connectorDimensions) { return "m " + _conv(d.hxy.x) + "," + _conv(d.hxy.y) + " l " + _conv(d.tail[0].x) + "," + _conv(d.tail[0].y) + " " + _conv(d.cxy.x) + "," + _conv(d.cxy.y) + " " + _conv(d.tail[1].x) + "," + _conv(d.tail[1].y) + " x e"; }; this.paint = function(connector, d, lineWidth, strokeStyle, fillStyle, connectorDimensions) { var p = {}; if (strokeStyle) { p["stroked"] = "true"; p["strokecolor"] = jsPlumbUtil.convertStyle(strokeStyle, true); } if (lineWidth) p["strokeweight"] = lineWidth + "px"; if (fillStyle) { p["filled"] = "true"; p["fillcolor"] = fillStyle; } var xmin = Math.min(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x), ymin = Math.min(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y), xmax = Math.max(d.hxy.x, d.tail[0].x, d.tail[1].x, d.cxy.x), ymax = Math.max(d.hxy.y, d.tail[0].y, d.tail[1].y, d.cxy.y), w = Math.abs(xmax - xmin), h = Math.abs(ymax - ymin), dim = [xmin, ymin, w, h]; // for VML, we create overlays using shapes that have the same dimensions and // coordsize as their connector - overlays calculate themselves relative to the // connector (it's how it's been done since the original canvas implementation, because // for canvas that makes sense). p["path"] = getPath(d, connectorDimensions); p["coordsize"] = (connectorDimensions[2] * scale) + "," + (connectorDimensions[3] * scale); dim[0] = connectorDimensions[0]; dim[1] = connectorDimensions[1]; dim[2] = connectorDimensions[2]; dim[3] = connectorDimensions[3]; if (self.canvas == null) { //p["class"] = jsPlumb.overlayClass; // TODO currentInstance? self.canvas = _node("shape", dim, p, connector.canvas.parentNode, connector._jsPlumb, true); connector.appendDisplayElement(self.canvas, true); self.attachListeners(self.canvas, connector); self.attachListeners(self.canvas, self); } else { _pos(self.canvas, dim); _atts(self.canvas, p); } }; this.reattachListeners = function() { if (self.canvas) self.reattachListenersForElement(self.canvas, self); }; this.cleanup = function() { if (self.canvas != null) jsPlumb.CurrentLibrary.removeElement(self.canvas); }; }; jsPlumb.Overlays.vml.Arrow = function() { AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Arrow, arguments]); }; jsPlumb.Overlays.vml.PlainArrow = function() { AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.PlainArrow, arguments]); }; jsPlumb.Overlays.vml.Diamond = function() { AbstractVmlArrowOverlay.apply(this, [jsPlumb.Overlays.Diamond, arguments]); }; })();
35.4163
135
0.622924
dbc6ffcdac1f08eb03b461afc72923c010ce2bae
331
js
JavaScript
public/js/clientIO.js
juancjara/my-hangout
98501aa3b42c02312aef065eda014975ff80b66c
[ "MIT" ]
1
2017-07-31T21:56:40.000Z
2017-07-31T21:56:40.000Z
public/js/clientIO.js
juancjara/my-hangout
98501aa3b42c02312aef065eda014975ff80b66c
[ "MIT" ]
null
null
null
public/js/clientIO.js
juancjara/my-hangout
98501aa3b42c02312aef065eda014975ff80b66c
[ "MIT" ]
null
null
null
module.exports = socket = io(); /*= (function() { var socket = io(); var funs = {}; return { join: function(user) { socket.emit('add user', user); }, register: function(nameFun, fun) { funs[nameFun] = fun; }, emit: function(nameFun, data) { socket.emit(nameFun, data); } } })();*/
20.6875
49
0.52568
dbc729825ce750404538628073e0c4c4d03f6e0d
8,631
js
JavaScript
react-native-sample/SendBirdReactNativeSample/src/pages/groupChannel.js
shilu-stha/SendBird-JavaScript
e55d0094eb0873458237b33c5744f22d90d4d3fc
[ "MIT" ]
1
2020-09-26T03:42:55.000Z
2020-09-26T03:42:55.000Z
react-native-sample/SendBirdReactNativeSample/src/pages/groupChannel.js
shilu-stha/SendBird-JavaScript
e55d0094eb0873458237b33c5744f22d90d4d3fc
[ "MIT" ]
11
2020-01-21T21:46:52.000Z
2020-03-27T03:40:51.000Z
react-native-sample/SendBirdReactNativeSample/src/pages/groupChannel.js
shilu-stha/SendBird-JavaScript
e55d0094eb0873458237b33c5744f22d90d4d3fc
[ "MIT" ]
1
2021-04-14T20:20:22.000Z
2021-04-14T20:20:22.000Z
import React, { Component } from 'react' import { View, Text, Image, ListView, TouchableHighlight, Alert, StyleSheet } from 'react-native' import { CachedImage } from 'react-native-cached-image'; import {APP_ID, PULLDOWN_DISTANCE} from '../consts'; import TopBar from '../components/topBar'; import moment from 'moment'; import SendBird from 'sendbird'; var sb = null; var ds = null; export default class GroupChannel extends Component { constructor(props) { super(props); sb = SendBird.getInstance(); ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { channelList: [], dataSource: ds.cloneWithRows([]), listQuery: sb.GroupChannel.createMyGroupChannelListQuery(), editMode: false }; this._getChannelList = this._getChannelList.bind(this); this._onHideChannel = this._onHideChannel.bind(this); this._refresh = this._refresh.bind(this); this._channelUpdate = this._channelUpdate.bind(this); this._refreshChannelList = this._refreshChannelList.bind(this); } componentDidMount() { this._getChannelList(); // channel handler var _SELF = this; var ChannelHandler = new sb.ChannelHandler(); ChannelHandler.onUserJoined = function(channel, user) { _SELF._channelUpdate(channel); }; ChannelHandler.onUserLeft = function(channel, user) { _SELF._channelUpdate(channel); }; ChannelHandler.onChannelChanged = function(channel) { _SELF._channelUpdate(channel); }; sb.addChannelHandler('ChannelHandlerInList', ChannelHandler); var ConnectionHandler = new sb.ConnectionHandler(); ConnectionHandler.onReconnectSucceeded = function(){ _SELF._refreshChannelList(); } sb.addConnectionHandler('ConnectionHandlerInList', ConnectionHandler); } componentWillUnmount() { sb.removeChannelHandler('ChannelHandlerInList'); sb.removeChannelHandler('ConnectionHandlerInList'); } _channelUpdate(channel) { if(!channel) return; var _SELF = this; var _exist = false; var _list = _SELF.state.channelList.filter(function(ch) { return channel.url != ch.url }); _list.unshift(channel); _SELF.setState({ channelList: _list, dataSource: ds.cloneWithRows(_list) }); } _refresh(channel) { this._channelUpdate(channel); } _channelTitle(members) { var _members = []; members.forEach(function(user) { if (user.userId != sb.currentUser.userId) { _members.push(user); } }); var _title = _members.map(function(elem){ if (elem.userId != sb.currentUser.userId) { return elem.nickname; } }).join(","); _title = _title.replace(',,', ','); return (_title.length > 15) ? _title.substring(0, 11) + '...' : _title; } _onChannelPress(channel) { var _SELF = this; if (_SELF.state.editMode) { Alert.alert( 'Group Channel Edit', null, [ {text: 'leave', onPress: () => { channel.leave(function(response, error) { if (error) { console.log(error); return; } _SELF._onHideChannel(channel); }); }}, {text: 'hide', onPress: () => { channel.hide(function(response, error) { if (error) { console.log(error); return; } _SELF._onHideChannel(channel); }); }}, {text: 'Cancel'} ] ) } else { _SELF.props.navigator.push({name: 'chat', channel: channel, _onHideChannel: _SELF._onHideChannel, refresh: _SELF._refreshChannelList}); } } _onHideChannel(channel) { this.setState({channelList: this.state.channelList.filter((ch) => { return channel.url !== ch.url })}, ()=> { this.setState({ dataSource: ds.cloneWithRows(this.state.channelList) }); }); } _refreshChannelList() { var _SELF = this; var listQuery = sb.GroupChannel.createMyGroupChannelListQuery(); listQuery.next(function(channelList, error){ if (error) { console.log(error); return; } _SELF.setState({ listQuery: listQuery, channelList: channelList, dataSource: ds.cloneWithRows(channelList)}); }); } _getChannelList() { var _SELF = this; _SELF.state.listQuery.next(function(channelList, error){ if (error) { console.log(error); return; } var newList = _SELF.state.channelList.concat(channelList); _SELF.setState({ channelList: newList, dataSource: ds.cloneWithRows(newList)}); }); } _onBackPress() { this.props.navigator.pop(); } _onGroupChannel() { var _SELF = this; if (_SELF.state.editMode) { Alert.alert( 'Group Channel Event', null, [ {text: 'Done', onPress: () => { _SELF.setState({editMode: false}); }} ] ) } else{ Alert.alert( 'Group Channel Event', null, [ {text: 'Edit', onPress: () => { _SELF.setState({editMode: true}); }}, {text: 'Create', onPress: () => { _SELF.props.navigator.push({name: 'inviteUser', _onHideChannel: _SELF._onHideChannel, refresh: _SELF._refreshChannelList, }); }}, {text: 'Cancel'} ] ) } } render() { return ( <View style={styles.container}> <TopBar onBackPress={this._onBackPress.bind(this)} onGroupChannel={this._onGroupChannel.bind(this)} title='Group Channel' /> <View style={styles.listContainer}> <ListView removeClippedSubviews={false} enableEmptySections={true} onEndReached={() => this._getChannelList()} onEndReachedThreshold={PULLDOWN_DISTANCE} dataSource={this.state.dataSource} renderRow={(rowData) => <TouchableHighlight onPress={() => this._onChannelPress(rowData)}> <View style={styles.listItem}> <View style={styles.listIcon}> <CachedImage style={styles.channelIcon} key={rowData.coverUrl} source={{uri: rowData.coverUrl.replace('http://', 'https://')}} /> </View> <View style={styles.listInfo}> <Text style={styles.titleLabel}>{this._channelTitle(rowData.members)}</Text> <Text style={styles.memberLabel}>{rowData.lastMessage ? ( rowData.lastMessage.message && rowData.lastMessage.message.length > 15 ? rowData.lastMessage.message.substring(0, 11) + '...' : rowData.lastMessage.message ) : '' }</Text> </View> <View style={{flex: 1, flexDirection: 'row', alignItems: 'flex-end', marginRight: 10}}> <View style={{flex: 1, flexDirection: 'column', alignItems: 'flex-end', marginRight: 4}}> <Text style={{color: '#861729'}}>{rowData.unreadMessageCount}</Text> </View> <View style={{flex: 1, alignItems: 'flex-end'}}> <Text style={styles.descText}>{rowData.memberCount} members</Text> <Text style={styles.descText}>{(!rowData.lastMessage || rowData.lastMessage.createdAt == 0) ? '-' : moment(rowData.lastMessage.createdAt).format('MM/DD HH:mm')}</Text> </View> </View> </View> </TouchableHighlight> } /> </View> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'stretch', backgroundColor: '#ffffff' }, listContainer: { flex: 11, justifyContent: 'center', alignItems: 'stretch' }, listItem: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#f7f8fc', borderBottomWidth: 0.5, borderColor: '#D0DBE4', padding: 5 }, listIcon: { justifyContent: 'flex-start', paddingLeft: 10, paddingRight: 15 }, channelIcon: { width: 30, height: 30 }, listInfo: { flex: 1, justifyContent: 'flex-start' }, titleLabel: { fontSize: 15, fontWeight: '600', color: '#60768b', }, memberLabel: { fontSize: 13, fontWeight: '400', color: '#abb8c4', }, descText: { textAlign: 'center', fontSize: 12, color: '#ababab' } });
28.57947
249
0.578728
dbc783bbbb49f85d83f005a96f99db2caf6f378d
637
js
JavaScript
algorithm/sorting/counting/basic/code.js
diegous/AlgorithmVisualizer
47010c4b2782d5ed7c322470d9fc5caa04f28a6e
[ "MIT" ]
5
2017-02-18T15:40:04.000Z
2018-04-23T07:42:02.000Z
algorithm/sorting/counting/basic/code.js
diegous/AlgorithmVisualizer
47010c4b2782d5ed7c322470d9fc5caa04f28a6e
[ "MIT" ]
null
null
null
algorithm/sorting/counting/basic/code.js
diegous/AlgorithmVisualizer
47010c4b2782d5ed7c322470d9fc5caa04f28a6e
[ "MIT" ]
2
2020-11-06T17:00:10.000Z
2021-06-11T19:36:28.000Z
//set counts values for (let i = 0; i < A.length; i++) { tracer._select(0, i)._wait(); counts[A[i]]++; tracer._notify(1, A[i], D[1][A[i]])._wait(); tracer._deselect(0, i); tracer._denotify(1, A[i], D[1][A[i]])._wait(); } //sort var i = 0; for (var j = 0; j <= maxValue; j++) { while (counts[j] > 0) { tracer._select(1, j)._wait(); sortedA[i] = j; counts[j]--; tracer._notify(1, j, D[1][j]); tracer._notify(2, i, D[2][i])._wait(); tracer._deselect(1, j); tracer._denotify(1, j, D[1][j]); tracer._denotify(2, i, D[2][i])._wait(); i++; } }
26.541667
50
0.485086
dbc8bc72d3ead6aba9bf4ec80fbdf1730e701d79
649
js
JavaScript
packages/griffith-mp4/src/fmp4/boxes/hdlr.js
kingsleydon/griffith
b14a0a87b4c37c67615db4520b940d29730a8fe5
[ "MIT" ]
2
2019-04-18T01:24:59.000Z
2019-04-18T01:25:31.000Z
packages/griffith-mp4/src/fmp4/boxes/hdlr.js
kingsleydon/griffith
b14a0a87b4c37c67615db4520b940d29730a8fe5
[ "MIT" ]
null
null
null
packages/griffith-mp4/src/fmp4/boxes/hdlr.js
kingsleydon/griffith
b14a0a87b4c37c67615db4520b940d29730a8fe5
[ "MIT" ]
1
2019-07-20T03:30:09.000Z
2019-07-20T03:30:09.000Z
import { generateVersionAndFlags, generatePredefined, generateReserved, str2TypedArray, generateBox, } from '../utils' export default function hdlr(type) { let handler = '' let name = '' switch (type) { case 'video': handler = 'vide' name = 'VideoHandler' break case 'audio': handler = 'soun' name = 'SoundHandler' } // prettier-ignore const content = new Uint8Array([ ...generateVersionAndFlags(0, 0), ...generatePredefined(4), ...str2TypedArray(handler), // ** ...generateReserved(12), ...str2TypedArray(name), 0x00, ]) return generateBox('hdlr', content) }
20.28125
37
0.619414
dbc99d28c7fa39dd1990c40d096c2a1bc77212cd
736
js
JavaScript
src/model/Person.js
WhatIfWeDigDeeper/logic-of-fp
d626447d4d42ef1bdcb16c454cf5f14cc2320107
[ "MIT" ]
null
null
null
src/model/Person.js
WhatIfWeDigDeeper/logic-of-fp
d626447d4d42ef1bdcb16c454cf5f14cc2320107
[ "MIT" ]
9
2020-07-04T12:37:52.000Z
2021-12-31T16:20:58.000Z
src/model/Person.js
WhatIfWeDigDeeper/logic-of-fp
d626447d4d42ef1bdcb16c454cf5f14cc2320107
[ "MIT" ]
null
null
null
/** * Person object * Domain model object for LMS use cases covered in the book * Author: Luis Atencio */ exports.Person = class Person { constructor(ssn,firstname, lastname, birthYear = null, address = null) { this._ssn = ssn; this._firstname = firstname; this._lastname = lastname; this._birthYear = birthYear; this._address = address; } get ssn() { return this._ssn; } get firstname() { return this._firstname; } set firstname(firstname) { this._firstname = firstname; return this; } get lastname() { return this._lastname; } get birthYear() { return this._birthYear; } get address() { return this._address; } get fullname() { return `${this._firstname} ${this._lastname}`; } };
17.116279
73
0.668478
dbc9cae5a86f71f4b88739d5925d7ef498f44459
8,871
js
JavaScript
js/netpie.plugin.microgear.js
chavee/nexpie-freeboard
fc0a64c5f64c19350b16b32f49b6dfed7c1923f1
[ "MIT" ]
23
2016-05-30T01:42:24.000Z
2021-05-02T07:21:32.000Z
js/netpie.plugin.microgear.js
chavee/nexpie-freeboard
fc0a64c5f64c19350b16b32f49b6dfed7c1923f1
[ "MIT" ]
4
2016-05-30T16:41:23.000Z
2018-08-02T08:34:29.000Z
js/netpie.plugin.microgear.js
chavee/nexpie-freeboard
fc0a64c5f64c19350b16b32f49b6dfed7c1923f1
[ "MIT" ]
34
2016-05-30T01:42:41.000Z
2020-06-11T04:32:19.000Z
/* NETPIE Microgear Freeboard plugin */ /* Developed by Chavee Issariyapat */ /* More information about NETPIE please visit https://netpie.io */ if (typeof microgear === "undefined") { microgear = {}; } (function() { freeboard.loadDatasourcePlugin({ "type_name" : "netpie_microgear", "display_name": "NETPIE Microgear", "description" : "Connect to NETPIE as a microgear to communicate real-time with other microgears in the same App ID. The microgear of this datasource is referenced by microgear[DATASOURCENAME]", "external_scripts" : [ "https://cdn.netpie.io/microgear.js" ], "settings" : [ { "name" : "appid", "display_name" : "App ID", "type" : "text", "description" : "NETPIE App ID obtained from https://netpie.io/app", "required" : true }, { "name" : "key", "display_name" : "Key", "type" : "text", "description" : "Key", "required" : true }, { "name" : "secret", "display_name" : "Secret", "type" : "text", "description" : "Secret", "type" : "text", "required" : true }, { "name" : "topics", "display_name" : "Subscribed Topics", "type" : "text", "description" : "Topics of the messages that this datasource will consume, the default is /# which means all messages in this app ID.", "default_value": "/#", "required" : false }, { "name" : "onCreatedAction", "display_name" : "onCreated Action", "type" : "text", "description" : "JS code to run after a datasource is created" }, { "name" : "onConnectedAction", "display_name" : "onConnected Action", "type" : "text", "description" : "JS code to run after a microgear datasource is connected to NETPIE" } ], newInstance : function(settings, newInstanceCallback, updateCallback) { newInstanceCallback(new netpieDatasourcePlugin(settings, updateCallback)); } }); var netpieDatasourcePlugin = function(settings, updateCallback) { var self = this; var currentSettings = settings; var gconf = { key: settings.key, secret: settings.secret } if (settings.alias) gconf.alias = settings.alias; var data = {}; var aliasList = {}; function initSubscribe(toparr, toSub) { if (toparr && toparr.length>0) { for (var i=0; i< toparr.length; i++) { if (toSub) { self.mg.subscribe(toparr[i]); } else { self.mg.unsubscribe(toparr[i]); } } } } self.updateNow = function() { } self.onSettingsChanged = function(newSettings) { if (currentSettings.name && (currentSettings.name != newSettings.name)) { var modifiedname = newSettings.name.substring(0,16); if (newSettings.name != modifiedname) { var text = "The datasource name should not be longer than 16 characters otherwise the associative id will be shorten i.e. now the microgear object is referenced by microgear[\""+modifiedname+"\"] and the microgear device alias is trimmed to \""+modifiedname+"\"."; newSettings.name = modifiedname; freeboard.showDialog(text, "Warning", "I understand"); } if (microgear[currentSettings.name]) { delete(microgear[currentSettings.name]); } microgear[newSettings.name] = self.mg; self.mg.setAlias(newSettings.name); } if (currentSettings.topics != newSettings.topics) { initSubscribe(currentSettings.topics.trim().split(','), false); initSubscribe(newSettings.topics.trim().split(','), true); } if (currentSettings.appid != newSettings.appid || currentSettings.key != newSettings.key || currentSettings.secret != newSettings.secret) { freeboard.showDialog("Reconfigure AppID, Key or Secret needs a page reloading. Make sure you save the current configuration before processding.", "Warning", "OK", "CANCEL", function() { location.reload(true); }) } currentSettings = newSettings; } self.onDispose = function() { delete(self.mg); } self.mg = Microgear.create(gconf); if(settings.name !== undefined){ settings.name = settings.name.replace(' ','_').substring(0,16); } microgear[settings.name] = self.mg; self.mg.on('message', function(topic,msg) { if (topic && msg) { data[topic] = msg; updateCallback(data); } }); self.mg.on('present', function(m) { var mtoken = m.gear; var aobj = { token : mtoken }; var found = false; if (typeof(aliasList[m.alias]) != 'undefined') { for (var k=0; k<aliasList[m.alias].length; k++) { if (aliasList[m.alias][k].token == mtoken) { found = true; break; } } } else { aliasList[m.alias] = []; } if (!found) { // if the alias changed, remove the old one located under the old alias name if (m.type=='aliased') { for (var _alias in aliasList) { for (var k=0; k<aliasList[_alias].length; k++) { if (aliasList[_alias][k].token == mtoken) { aliasList[_alias].splice(k,1); } } } } aliasList[m.alias].push(aobj); } for (var _alias in aliasList) { if (aliasList[_alias].length == 0) { console.log(); delete aliasList[_alias]; } } data['alias'] = aliasList; updateCallback(data); }); self.mg.on('absent', function(m) { var mtoken = m.gear; if (typeof(aliasList[m.alias]) != 'undefined') { for (var k=0; k<aliasList[m.alias].length; k++) { if (aliasList[m.alias][k].token == mtoken) { aliasList[m.alias].splice(k,1); if (aliasList[m.alias].length == 0) delete aliasList[m.alias]; break; } } } data['alias'] = aliasList; updateCallback(data); }); self.mg.on('connected', function() { aliasList = {}; data['alias'] = aliasList; updateCallback(data); initSubscribe(settings.topics.trim().split(','), true); if (gconf.alias) { self.mg.setAlias(gconf.alias); } else if (settings.name) { self.mg.setAlias(settings.name); } if (settings.onConnectedAction) { var timer = setInterval(function() { if (Object.getOwnPropertyNames(microgear).length > 0) { clearInterval(timer); eval(settings.onConnectedAction); } },200); } if (typeof(onConnectedHandler) != 'undefined') { onConnectedHandler(settings.name); } }) self.mg.on('disconnected', function() { aliasList = {}; data['alias'] = aliasList; updateCallback(data); }); if (settings.onCreatedAction) { eval(settings.onCreatedAction); } self.mg.connect(settings.appid, function(){ }); } }());
35.063241
284
0.457671
dbca66c007c404ac09838a2e99b793f5840b4008
6,055
js
JavaScript
src/index.js
Sheraff/use-imported-hook
ff9e10916468485af0b1fc611b218befd07ecf05
[ "MIT" ]
2
2021-06-05T18:38:59.000Z
2022-02-05T16:25:30.000Z
src/index.js
Sheraff/use-imported-hook
ff9e10916468485af0b1fc611b218befd07ecf05
[ "MIT" ]
5
2021-06-06T11:09:36.000Z
2021-11-23T07:32:45.000Z
src/index.js
Sheraff/use-imported-hook
ff9e10916468485af0b1fc611b218befd07ecf05
[ "MIT" ]
null
null
null
const readImportee = require('./read-importee') const findImportStatementNode = require('./resolve-import-statement') const { BABEL_MARKER_COMMENT, EXTRA_DEPENDENCY_IDENTIFIER_NAME, INITIAL_STATES_IDENTIFIER_NAME, STATEFUL_HOOKS, STATELESS_HOOKS, SIMPLEST_HOOKS, NO_MARKER_ERROR, SINGLE_ARGUMENT_ERROR, NO_IMPORT_STATEMENT, NO_DYNAMIC_IMPORT_PATH, MULTIPLE_IMPORTS_ERROR, STATEFUL_HOOKS_NEED_STATIC_INITIAL_STATE, } = require('./config') const {isNodeStaticValue, staticValueTypeConstructor} = require('./isNodeStaticValue') function transform(babel) { const { types: t } = babel return { name: "find-imported-hooks", visitor: { // find hook call in importer CallExpression(path) { if(path.node.callee.name !== 'useImportedHook') { return } // find importee path const importArg = findImportStatementNode(path) if(!importArg) { throw path.buildCodeFrameError(NO_IMPORT_STATEMENT) } if (importArg.type !== "StringLiteral") { throw path.buildCodeFrameError(NO_DYNAMIC_IMPORT_PATH) } if (this.foundImport) { throw path.buildCodeFrameError(MULTIPLE_IMPORTS_ERROR) } this.foundImport = true // read imported file const fileRelativePath = importArg.value const program = path.findParent(path => path.isProgram()) const state = { hooks: [], foundComment: false, } readImportee(program.hub.file.opts.filename, fileRelativePath, state, path) // throw if imported file doesn't have BABEL_MARKER_COMMENT comment if(!state.foundComment) { throw path.buildCodeFrameError(NO_MARKER_ERROR) } // force hook call optional arguments path.node.arguments[1] = path.node.arguments[1] || t.identifier('undefined') path.node.arguments[2] = path.node.arguments[2] || t.identifier('undefined') // add hooks argument to useImportedHook call const reserveStatelessHooks = t.arrayExpression() const reserveStatefulHooks = t.arrayExpression() state.hooks.forEach((descriptor) => { const slot = t.arrayExpression() slot.elements.push(t.identifier(descriptor.name)) if('value' in descriptor) { slot.elements.push(staticValueTypeConstructor(t, descriptor.value)) } if(descriptor.type === 'stateful') { reserveStatefulHooks.elements.push(slot) } else { reserveStatelessHooks.elements.push(slot) } }) path.node.arguments.push(reserveStatefulHooks) path.node.arguments.push(reserveStatelessHooks) if (state.hooks.length === 0) { return } // add import declarations to top of document let reactImport = program.node.body.find( (node) => node.type === 'ImportDeclaration' && node.source.value.toLowerCase() === 'react' ) if(!reactImport) { reactImport = t.importDeclaration([], t.stringLiteral('react')) program.node.body.unshift(reactImport) } state.hooks.forEach(({name}) => { const alreadyImported = reactImport.specifiers.find( specifier => specifier.type === "ImportSpecifier" && specifier.imported.name === name ) if(!alreadyImported) { const identifier = t.identifier(name) const specifier = t.importSpecifier(identifier, identifier) reactImport.specifiers.push(specifier) } }) }, // find hook declaration in importee "FunctionDeclaration|ExportDefaultDeclaration"(path) { const comment = path.node.leadingComments && path.node.leadingComments.find( ({value}) => value.includes(BABEL_MARKER_COMMENT) ) if(!comment) { return } // add function parameter const params = path.node.type === 'FunctionDeclaration' ? path.node.params : path.node.declaration.params if(params.length === 0) { params.push(t.objectPattern([])) } if(params.length >= 2 && (params[1].type !== 'Identifier' || params[1].name !== EXTRA_DEPENDENCY_IDENTIFIER_NAME)) { throw path.buildCodeFrameError(SINGLE_ARGUMENT_ERROR) } if(params.length === 1) { params.push(t.identifier(EXTRA_DEPENDENCY_IDENTIFIER_NAME)) params.push(t.identifier(INITIAL_STATES_IDENTIFIER_NAME)) } // tweak hooks this.initialStateIndex = 0 path.traverse({ CallExpression(path) { const name = path.node.callee.name // add hooks dependency if(STATELESS_HOOKS.includes(name)) { if(!path.node.arguments[1]) { path.node.arguments[1] = t.arrayExpression() } const dependencies = path.node.arguments[1] if(dependencies.type === "ArrayExpression") { const first = dependencies.elements[0] if(!first || first.name !== EXTRA_DEPENDENCY_IDENTIFIER_NAME) { dependencies.elements.unshift(t.identifier(EXTRA_DEPENDENCY_IDENTIFIER_NAME)) } } } // replace stateful hooks if(STATEFUL_HOOKS.includes(name)) { const initialState = isNodeStaticValue(path.node.arguments[0]) if(!initialState) { throw path.buildCodeFrameError(STATEFUL_HOOKS_NEED_STATIC_INITIAL_STATE) } const member = t.memberExpression( t.identifier(INITIAL_STATES_IDENTIFIER_NAME), t.numericLiteral(this.initialStateIndex), true ) path.replaceWith(member) this.initialStateIndex++ } } }, this) }, } } } module.exports = transform
36.257485
124
0.603303
dbca6bfb6a59f9f4a2919336ed0e8034b79aabf5
2,544
js
JavaScript
src/depends/blackcoin-network.js
danielclough/blk.js
91d3305b2e08780d714f6df72eb1d8d78d195a32
[ "MIT" ]
null
null
null
src/depends/blackcoin-network.js
danielclough/blk.js
91d3305b2e08780d714f6df72eb1d8d78d195a32
[ "MIT" ]
null
null
null
src/depends/blackcoin-network.js
danielclough/blk.js
91d3305b2e08780d714f6df72eb1d8d78d195a32
[ "MIT" ]
null
null
null
const blackcoin = require("node-blackcoin-more"); const config = require('./config.js'); const client = new blackcoin.Client(config); function addnode(node, arg) { return new Promise((resolve, reject) => { client.cmd('addnode', function(err, data){ if (err) return reject(err); resolve(data); }); }); } function clearbanned() { return new Promise((resolve, reject) => { client.cmd('clearbanned', function(err, data){ if (err) return reject(err); resolve(data); }); }); } function disconnectnode(node) { return new Promise((resolve, reject) => { client.cmd('disconnectnode', function(err, data){ if (err) return reject(err); resolve(data); }); }); } function getaddednodeinfo(dummy, node) { return new Promise((resolve, reject) => { client.cmd('getaddednodeinfo', function(err, data){ if (err) return reject(err); resolve(data); }); }); } function getconnectioncount() { return new Promise((resolve, reject) => { client.cmd('getconnectioncount', function(err, data){ if (err) return reject(err); resolve(data); }); }); } function getnettotals() { return new Promise((resolve, reject) => { client.cmd('getnettotals', function(err, data){ if (err) return reject(err); resolve(data); }); }); } function getnetworkinfo() { return new Promise((resolve, reject) => { client.cmd('getnetworkinfo', function(err, data){ if (err) return reject(err); resolve(data); }); }); } function getpeerinfo() { return new Promise((resolve, reject) => { client.cmd('getpeerinfo', function(err, data){ if (err) return reject(err); resolve(data); }); }); } function listbanned() { return new Promise((resolve, reject) => { client.cmd('listbanned', function(err, data){ if (err) return reject(err); resolve(data); }); }); } function ping() { return new Promise((resolve, reject) => { client.cmd('ping', function(err, data){ if (err) return reject(err); resolve(data); }); }); } /*function(setban, ip, arg, bantime, absolute) { return new Promise((resolve, reject) => { client.cmd('setban', function(err, data){ if (err) return reject(err); resolve(data); }); }); }*/ module.exports = (function(){ return { addnode, clearbanned, disconnectnode, getaddednodeinfo, getconnectioncount, getnettotals, getnetworkinfo, getpeerinfo, listbanned, ping } })();
21.559322
57
0.605739
dbca77bc848fa7df70969c98afb34b552a98baba
295
js
JavaScript
data/migrations/20201215174223_create-priority.js
MTaylor-tech/xcel-wom-be-b
be6b408076644d894d26ca3d381ceac7bd821104
[ "MIT" ]
null
null
null
data/migrations/20201215174223_create-priority.js
MTaylor-tech/xcel-wom-be-b
be6b408076644d894d26ca3d381ceac7bd821104
[ "MIT" ]
7
2020-12-16T01:14:25.000Z
2021-02-02T00:37:11.000Z
data/migrations/20201215174223_create-priority.js
MTaylor-tech/xcel-wom-be-b
be6b408076644d894d26ca3d381ceac7bd821104
[ "MIT" ]
3
2020-12-15T02:52:43.000Z
2021-02-05T00:34:03.000Z
exports.up = (knex) => { return knex.schema.createTable('priority', function (table) { table.increments('id').notNullable().unique().primary(); table.string('name'); table.string('color'); }); }; exports.down = (knex) => { return knex.schema.dropTableIfExists('priority'); };
24.583333
63
0.640678
dbca8a6cd198dd58874d356009efe3306e59bb5d
4,239
js
JavaScript
libs/graph/ccnetviz/0-quadTree.js
mwolf-eu/hdsf-hive-examples
45d3673f4ac2ac83f9cae3b6ab4ac22572afe3ef
[ "MIT" ]
null
null
null
libs/graph/ccnetviz/0-quadTree.js
mwolf-eu/hdsf-hive-examples
45d3673f4ac2ac83f9cae3b6ab4ac22572afe3ef
[ "MIT" ]
null
null
null
libs/graph/ccnetviz/0-quadTree.js
mwolf-eu/hdsf-hive-examples
45d3673f4ac2ac83f9cae3b6ab4ac22572afe3ef
[ "MIT" ]
null
null
null
/** * Copyright (c) 2016, Helikar Lab. * All rights reserved. * * This source code is licensed under the GPLv3 License. * Author: David Tichy */ H.Namespace.set(H, 'ccnetvis.quad'); H.ccnetvis.quad = function() { var tree = function(points) { let d, xs, ys, i, n, x1_, y1_, x2_, y2_; x2_ = y2_ = -(x1_ = y1_ = Infinity); xs = [], ys = []; n = points.length; for (i = 0; i < n; ++i) { d = points[i]; if (d.x < x1_) x1_ = d.x; if (d.y < y1_) y1_ = d.y; if (d.x > x2_) x2_ = d.x; if (d.y > y2_) y2_ = d.y; xs.push(d.x); ys.push(d.y); } let dx = x2_ - x1_; let dy = y2_ - y1_; dx > dy ? y2_ = y1_ + dx : x2_ = x1_ + dy; function create() { return { leaf: true, nodes: [], point: null, x: null, y: null }; } function visit(f, node, x1, y1, x2, y2) { if (!f(node, x1, y1, x2, y2)) { let sx = (x1 + x2) * 0.5; let sy = (y1 + y2) * 0.5; let children = node.nodes; if (children[0]) visit(f, children[0], x1, y1, sx, sy); if (children[1]) visit(f, children[1], sx, y1, x2, sy); if (children[2]) visit(f, children[2], x1, sy, sx, y2); if (children[3]) visit(f, children[3], sx, sy, x2, y2); } } function insert(n, d, x, y, x1, y1, x2, y2) { if (n.leaf) { let nx = n.x; let ny = n.y; if (nx !== null) { if (nx === x && ny === y) { insertChild(n, d, x, y, x1, y1, x2, y2); } else { let nPoint = n.point; n.x = n.y = n.point = null; insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); insertChild(n, d, x, y, x1, y1, x2, y2); } } else { n.x = x, n.y = y, n.point = d; } } else { insertChild(n, d, x, y, x1, y1, x2, y2); } } function insertChild(n, d, x, y, x1, y1, x2, y2) { let xm = (x1 + x2) * 0.5; let ym = (y1 + y2) * 0.5; let right = x >= xm; let below = y >= ym; let i = below << 1 | right; n.leaf = false; n = n.nodes[i] || (n.nodes[i] = create()); right ? x1 = xm : x2 = xm; below ? y1 = ym : y2 = ym; insert(n, d, x, y, x1, y1, x2, y2); } function findNode(root, x, y, x0, y0, x3, y3) { let minDistance2 = Infinity; let closestPoint; (function find(node, x1, y1, x2, y2) { if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; let point; if (point = node.point) { let dx = x - node.x; let dy = y - node.y; let distance2 = dx * dx + dy * dy; if (distance2 < minDistance2) { let distance = Math.sqrt(minDistance2 = distance2); x0 = x - distance, y0 = y - distance; x3 = x + distance, y3 = y + distance; closestPoint = point; } } let children = node.nodes; let xm = (x1 + x2) * .5; let ym = (y1 + y2) * .5; let right = x >= xm; let below = y >= ym; for (let i = below << 1 | right, j = i + 4; i < j; ++i) { if (node = children[i & 3]) switch (i & 3) { case 0: find(node, x1, y1, xm, ym); break; case 1: find(node, xm, y1, x2, ym); break; case 2: find(node, x1, ym, xm, y2); break; case 3: find(node, xm, ym, x2, y2); break; } } })(root, x0, y0, x3, y3); return closestPoint; } let root = create(); root.visit = f => visit(f, root, x1_, y1_, x2_, y2_); root.find = (x, y) => findNode(root, x, y, x1_, y1_, x2_, y2_); for (i = 0; i < n; i++) insert(root, points[i], xs[i], ys[i], x1_, y1_, x2_, y2_); --i; xs = ys = points = d = null; return root; }; return { tree : tree } }();
28.449664
86
0.404812
dbcadbe33b82a682e5a118d09dfd34950f38cf0c
329
js
JavaScript
js/components/plugins/testplugin2.js
rolfvandekrol/flux-react-requirejs-layers
a8c93c2a5e08c28d6c789042f0df9a717df7e8a7
[ "MIT" ]
7
2015-12-23T07:35:47.000Z
2019-05-14T11:44:26.000Z
js/components/plugins/testplugin2.js
rolfvandekrol/flux-react-requirejs-layers
a8c93c2a5e08c28d6c789042f0df9a717df7e8a7
[ "MIT" ]
null
null
null
js/components/plugins/testplugin2.js
rolfvandekrol/flux-react-requirejs-layers
a8c93c2a5e08c28d6c789042f0df9a717df7e8a7
[ "MIT" ]
4
2017-03-01T13:44:28.000Z
2019-06-04T05:38:22.000Z
define( ['react', 'components/plugins/testplugin2/sub'], function(React, Sub) { return React.createClass({ displayName: 'TestPlugin2', render: function() { return ( <div className="test-plugin"> TestPlugin2 <Sub /> </div> ); } }); } );
18.277778
50
0.489362
dbcb6b666351068b5b335e175ad6975001141484
26,161
js
JavaScript
jstests/multiVersion/set_feature_compatibility_version.js
i80and/mongo
67f4d6495ad14fe95067f06e0366823887828c0e
[ "Apache-2.0" ]
null
null
null
jstests/multiVersion/set_feature_compatibility_version.js
i80and/mongo
67f4d6495ad14fe95067f06e0366823887828c0e
[ "Apache-2.0" ]
null
null
null
jstests/multiVersion/set_feature_compatibility_version.js
i80and/mongo
67f4d6495ad14fe95067f06e0366823887828c0e
[ "Apache-2.0" ]
null
null
null
/** * Tests setFeatureCompatibilityVersion. */ // Checking UUID consistency involves talking to a shard node, which in this test is shutdown TestData.skipCheckingUUIDsConsistentAcrossCluster = true; // Some of the test cases in this file clear the FCV document, so the validate command's UUID checks // will fail. TestData.skipCollectionAndIndexValidation = true; // A replset test case checks that replication to a secondary ceases, so we do not expect identical // data. TestData.skipCheckDBHashes = true; (function() { "use strict"; load("jstests/replsets/rslib.js"); load("jstests/libs/feature_compatibility_version.js"); load("jstests/libs/get_index_helpers.js"); let dbpath = MongoRunner.dataPath + "feature_compatibility_version"; resetDbpath(dbpath); let res; const latest = "latest"; const lastStable = "last-stable"; const latestFCV = "4.0"; const lastStableFCV = "3.6"; /** * If we're using mmapv1, we must recover the journal files from an unclean shutdown before * attempting to run with --repair. */ let recoverMMapJournal = function(isMMAPv1, conn, dbpath) { if (isMMAPv1) { let returnCode = runMongoProgram("mongod", "--port", conn.port, "--journalOptions", /*MMAPV1Options::JournalRecoverOnly*/ 4, "--dbpath", dbpath); assert.eq(returnCode, /*EXIT_NET_ERROR*/ 48); } }; /** * Ensure that a mongod (without using --repair) fails to start up if there are non-local * collections and either the admin database has been dropped or the FCV document in the admin * database has been removed. * * The mongod has 'version' binary and is started up on 'dbpath'. */ let doStartupFailTests = function(version, dbpath) { // Set up a mongod with a user collection but without an admin database. setupUserCollAndMissingAdminDB(version, dbpath); // Now attempt to start up a new mongod without clearing the data files from 'dbpath', which // contain a user collection but are missing the admin database. The mongod should fail to // start up if the admin database is missing but there are non-local collections. conn = MongoRunner.runMongod({dbpath: dbpath, binVersion: version, noCleanData: true}); assert.eq( null, conn, "expected mongod to fail when data files are present but no admin database is found."); // Set up a mongod with an admin database but without a FCV document in the admin database. setupMissingFCVDoc(version, dbpath); // Now attempt to start up a new mongod without clearing the data files from 'dbpath', which // contain the admin database but are missing the FCV document. The mongod should fail to // start start up if there is a non-local collection and the FCV document is missing. conn = MongoRunner.runMongod({dbpath: dbpath, binVersion: version, noCleanData: true}); assert.eq( null, conn, "expected mongod to fail when data files are present but no FCV document is found."); }; /** * Starts up a mongod with binary 'version' on 'dbpath', then removes the FCV document from the * admin database and returns the mongod. */ let setupMissingFCVDoc = function(version, dbpath) { let conn = MongoRunner.runMongod({dbpath: dbpath, binVersion: version}); assert.neq(null, conn, "mongod was unable to start up with version=" + version + " and no data files"); adminDB = conn.getDB("admin"); removeFCVDocument(adminDB); MongoRunner.stopMongod(conn); return conn; }; /** * Starts up a mongod with binary 'version' on 'dbpath' and creates a user collection. Then * drops the admin database and returns the mongod. */ let setupUserCollAndMissingAdminDB = function(version, dbpath) { conn = MongoRunner.runMongod({dbpath: dbpath, binVersion: version}); assert.neq(null, conn, "mongod was unable to start up with version=" + version + " and no data files"); let testDB = conn.getDB("test"); assert.commandWorked(testDB.createCollection("testcoll")); adminDB = conn.getDB("admin"); assert.commandWorked(adminDB.runCommand({dropDatabase: 1}), "expected drop of admin database to be successful"); MongoRunner.stopMongod(conn); return conn; }; // // Standalone tests. // let conn; let adminDB; // A 'latest' binary standalone should default to 'latestFCV'. conn = MongoRunner.runMongod({dbpath: dbpath, binVersion: latest}); assert.neq( null, conn, "mongod was unable to start up with version=" + latest + " and no data files"); adminDB = conn.getDB("admin"); checkFCV(adminDB, lastStableFCV); // TODO: make this 'latestFCV' when SERVER-32597 bumps default // TODO: remove this when SERVER-32597 bumps the default to 4.0. assert.commandWorked(adminDB.runCommand({setFeatureCompatibilityVersion: latestFCV})); // featureCompatibilityVersion cannot be set to invalid value. assert.commandFailed(adminDB.runCommand({setFeatureCompatibilityVersion: 5})); assert.commandFailed(adminDB.runCommand({setFeatureCompatibilityVersion: "3.2"})); assert.commandFailed(adminDB.runCommand({setFeatureCompatibilityVersion: "4.2"})); assert.commandFailed(adminDB.runCommand({setFeatureCompatibilityVersion: "3.4"})); // setFeatureCompatibilityVersion rejects unknown fields. assert.commandFailed( adminDB.runCommand({setFeatureCompatibilityVersion: lastStable, unknown: 1})); // setFeatureCompatibilityVersion can only be run on the admin database. assert.commandFailed( conn.getDB("test").runCommand({setFeatureCompatibilityVersion: lastStable})); // featureCompatibilityVersion cannot be set via setParameter. assert.commandFailed( adminDB.runCommand({setParameter: 1, featureCompatibilityVersion: lastStable})); // setFeatureCompatibilityVersion fails to downgrade FCV if the write fails. assert.commandWorked(adminDB.runCommand({ configureFailPoint: "failCollectionUpdates", data: {collectionNS: "admin.system.version"}, mode: "alwaysOn" })); assert.commandFailed(adminDB.runCommand({setFeatureCompatibilityVersion: lastStableFCV})); checkFCV(adminDB, latestFCV); assert.commandWorked(adminDB.runCommand({ configureFailPoint: "failCollectionUpdates", data: {collectionNS: "admin.system.version"}, mode: "off" })); // featureCompatibilityVersion can be downgraded to 'lastStableFCV'. assert.commandWorked(adminDB.runCommand({setFeatureCompatibilityVersion: lastStableFCV})); checkFCV(adminDB, lastStableFCV); // setFeatureCompatibilityVersion fails to upgrade to 'latestFCV' if the write fails. assert.commandWorked(adminDB.runCommand({ configureFailPoint: "failCollectionUpdates", data: {collectionNS: "admin.system.version"}, mode: "alwaysOn" })); assert.commandFailed(adminDB.runCommand({setFeatureCompatibilityVersion: latestFCV})); checkFCV(adminDB, lastStableFCV); assert.commandWorked(adminDB.runCommand({ configureFailPoint: "failCollectionUpdates", data: {collectionNS: "admin.system.version"}, mode: "off" })); // featureCompatibilityVersion can be upgraded to 'latestFCV'. assert.commandWorked(adminDB.runCommand({setFeatureCompatibilityVersion: latestFCV})); checkFCV(adminDB, latestFCV); // TODO: remove these FCV 3.4 / 4.0 tests when FCV 3.4 is removed (SERVER-32597). // ---------------------------------------------------------------------------------- // Cannot jump down two FCVs from 4.0 to 3.4 assert.commandFailed(adminDB.runCommand({setFeatureCompatibilityVersion: "3.4"})); checkFCV(adminDB, latestFCV); assert.commandWorked(adminDB.runCommand({setFeatureCompatibilityVersion: lastStableFCV})); assert.commandWorked(adminDB.runCommand({setFeatureCompatibilityVersion: "3.4"})); checkFCV(adminDB, "3.4"); // Cannot jump up two FCVs from 3.4 to 4.0 assert.commandFailed(adminDB.runCommand({setFeatureCompatibilityVersion: latestFCV})); checkFCV(adminDB, "3.4"); // ------------------ end FCV 3.4/4.0 testing --------------------------------------- MongoRunner.stopMongod(conn); // featureCompatibilityVersion is durable. // TODO: update this to use 'latestFCV' and 'lastStableFCV', rather than 'lastStableFCV' and // '3.4', respectively, when SERVER-32597 bumps the default to 4.0. conn = MongoRunner.runMongod({dbpath: dbpath, binVersion: latest}); assert.neq( null, conn, "mongod was unable to start up with version=" + latest + " and no data files"); adminDB = conn.getDB("admin"); checkFCV(adminDB, lastStableFCV); assert.commandWorked(adminDB.runCommand({setFeatureCompatibilityVersion: "3.4"})); checkFCV(adminDB, "3.4"); MongoRunner.stopMongod(conn); conn = MongoRunner.runMongod({dbpath: dbpath, binVersion: latest, noCleanData: true}); assert.neq(null, conn, "mongod was unable to start up with binary version=" + latest + " and featureCompatibilityVersion=3.4"); adminDB = conn.getDB("admin"); checkFCV(adminDB, "3.4"); MongoRunner.stopMongod(conn); // If you upgrade from 'lastStable' binary to 'latest' binary and have non-local databases, FCV // remains 'lastStableFCV'. conn = MongoRunner.runMongod({dbpath: dbpath, binVersion: lastStable}); assert.neq(null, conn, "mongod was unable to start up with version=" + lastStable + " and no data files"); assert.writeOK(conn.getDB("test").coll.insert({a: 5})); adminDB = conn.getDB("admin"); checkFCV(adminDB, lastStableFCV); MongoRunner.stopMongod(conn); conn = MongoRunner.runMongod({dbpath: dbpath, binVersion: latest, noCleanData: true}); assert.neq(null, conn, "mongod was unable to start up with binary version=" + latest + " and featureCompatibilityVersion=" + lastStableFCV); adminDB = conn.getDB("admin"); checkFCV(adminDB, lastStableFCV); MongoRunner.stopMongod(conn); // A 'latest' binary mongod started with --shardsvr and clean data files defaults to // 'lastStableFCV'. conn = MongoRunner.runMongod({dbpath: dbpath, binVersion: latest, shardsvr: ""}); assert.neq( null, conn, "mongod was unable to start up with version=" + latest + " and no data files"); adminDB = conn.getDB("admin"); checkFCV(adminDB, lastStableFCV); MongoRunner.stopMongod(conn); // Check that start up without --repair fails if there is non-local DB data and either the admin // database was dropped or the FCV doc was deleted. doStartupFailTests(latest, dbpath); const isMMAPv1 = jsTest.options().storageEngine === "mmapv1"; // --repair can be used to restore a missing admin database, and thus FCV document that resides // in the admin database, if at least some collections have UUIDs. conn = setupUserCollAndMissingAdminDB(latest, dbpath); recoverMMapJournal(isMMAPv1, conn, dbpath); let returnCode = runMongoProgram("mongod", "--port", conn.port, "--repair", "--dbpath", dbpath); assert.eq( returnCode, 0, "expected mongod --repair to execute successfully when restoring a missing admin database."); conn = MongoRunner.runMongod({dbpath: dbpath, binVersion: latest, noCleanData: true}); assert.neq(null, conn, "mongod was unable to start up with version=" + latest + " and existing data files"); // FCV is 3.4 and targetVersion is 3.6 because the admin database needed to be restored. // TODO: update this code and comment when SERVER-32597 bumps the FCV defaults. adminDB = conn.getDB("admin"); assert.eq(adminDB.system.version.findOne({_id: "featureCompatibilityVersion"}).version, "3.4"); assert.eq(adminDB.system.version.findOne({_id: "featureCompatibilityVersion"}).targetVersion, lastStableFCV); MongoRunner.stopMongod(conn); // --repair can be used to restore a missing featureCompatibilityVersion document to an existing // admin database if at least some collections have UUIDs. conn = setupMissingFCVDoc(latest, dbpath); recoverMMapJournal(isMMAPv1, conn, dbpath); returnCode = runMongoProgram("mongod", "--port", conn.port, "--repair", "--dbpath", dbpath); assert.eq( returnCode, 0, "expected mongod --repair to execute successfully when restoring a missing FCV document."); conn = MongoRunner.runMongod({dbpath: dbpath, binVersion: latest, noCleanData: true}); assert.neq(null, conn, "mongod was unable to start up with version=" + latest + " and existing data files"); // FCV is 'latestFCV' because all collections were left intact with UUIDs. // TODO: update 'lastStableFCV' to 'latestFCV' when SERVER-32597 bumps the FCV defaults. adminDB = conn.getDB("admin"); assert.eq(adminDB.system.version.findOne({_id: "featureCompatibilityVersion"}).version, lastStableFCV); MongoRunner.stopMongod(conn); // If the featureCompatibilityVersion document is present but there are no collection UUIDs, // --repair should not attempt to restore the document and should return success. conn = MongoRunner.runMongod({dbpath: dbpath, binVersion: lastStable}); assert.neq(null, conn, "mongod was unable to start up with version=" + lastStable + " and no data files"); MongoRunner.stopMongod(conn); recoverMMapJournal(isMMAPv1, conn, dbpath); returnCode = runMongoProgram("mongod", "--port", conn.port, "--repair", "--dbpath", dbpath); assert.eq(returnCode, 0); // // Replica set tests. // let rst; let rstConns; let replSetConfig; let primaryAdminDB; let secondaryAdminDB; // 'latest' binary replica set. rst = new ReplSetTest({nodes: 2, nodeOpts: {binVersion: latest}}); rst.startSet(); rst.initiate(); primaryAdminDB = rst.getPrimary().getDB("admin"); secondaryAdminDB = rst.getSecondary().getDB("admin"); // FCV should default to 'latestFCV' on primary and secondary in a 'latest' binary replica set. // TODO: update these to 'latestFCV' when SERVER-32597 bumps the FCV default. checkFCV(primaryAdminDB, lastStableFCV); rst.awaitReplication(); checkFCV(secondaryAdminDB, lastStableFCV); // featureCompatibilityVersion propagates to secondary. // TODO: update these to 'lastStableFCV' when SERVER-32597 bumps the FCV default. assert.commandWorked(primaryAdminDB.runCommand({setFeatureCompatibilityVersion: "3.4"})); checkFCV(primaryAdminDB, "3.4"); rst.awaitReplication(); checkFCV(secondaryAdminDB, "3.4"); // setFeatureCompatibilityVersion cannot be run on secondary. // TODO: update this to 'latestFCV' when SERVER-32597 bumps the FCV default. assert.commandFailed( secondaryAdminDB.runCommand({setFeatureCompatibilityVersion: lastStableFCV})); rst.stopSet(); // A 'latest' binary secondary with a 'lastStable' binary primary will have 'lastStableFCV' rst = new ReplSetTest({nodes: [{binVersion: lastStable}, {binVersion: latest}]}); rstConns = rst.startSet(); replSetConfig = rst.getReplSetConfig(); replSetConfig.members[1].priority = 0; replSetConfig.members[1].votes = 0; rst.initiate(replSetConfig); rst.waitForState(rstConns[0], ReplSetTest.State.PRIMARY); secondaryAdminDB = rst.getSecondary().getDB("admin"); checkFCV(secondaryAdminDB, lastStableFCV); rst.stopSet(); // Test that a 'lastStable' secondary can successfully perform initial sync from a 'latest' // primary with 'lastStableFCV'. rst = new ReplSetTest( {nodes: [{binVersion: latest}, {binVersion: latest, rsConfig: {priority: 0}}]}); rst.startSet(); rst.initiate(); let primary = rst.getPrimary(); primaryAdminDB = primary.getDB("admin"); let secondary = rst.add({binVersion: lastStable}); secondaryAdminDB = secondary.getDB("admin"); // Rig the election so that the first node running latest version remains the primary after the // 'lastStable' secondary is added to the replica set. replSetConfig = rst.getReplSetConfig(); replSetConfig.version = 4; replSetConfig.members[2].priority = 0; reconfig(rst, replSetConfig); // Verify that the 'lastStable' secondary successfully performed its initial sync. assert.writeOK( primaryAdminDB.getSiblingDB("test").coll.insert({awaitRepl: true}, {writeConcern: {w: 3}})); // Test that a 'lastStable' secondary can no longer replicate from the primary after the FCV is // upgraded to 'latestFCV'. assert.commandWorked(primary.adminCommand({setFeatureCompatibilityVersion: latestFCV})); checkFCV(secondaryAdminDB, lastStableFCV); assert.writeOK(primaryAdminDB.getSiblingDB("test").coll.insert({shouldReplicate: false})); assert.eq(secondaryAdminDB.getSiblingDB("test").coll.find({shouldReplicate: false}).itcount(), 0); rst.stopSet(); // Test idempotency for setFeatureCompatibilityVersion. rst = new ReplSetTest({nodes: 2, nodeOpts: {binVersion: latest}}); rst.startSet(); rst.initiate(); // Set FCV to 'lastStableFCV' so that a 'lastStable' binary node can join the set. primary = rst.getPrimary(); assert.commandWorked(primary.adminCommand({setFeatureCompatibilityVersion: lastStableFCV})); rst.awaitReplication(); // Add a 'lastStable' binary node to the set. secondary = rst.add({binVersion: lastStable}); rst.reInitiate(); // Ensure the 'lastStable' binary node succeeded its initial sync. assert.writeOK(primary.getDB("test").coll.insert({awaitRepl: true}, {writeConcern: {w: 3}})); // Run {setFCV: lastStableFCV}. This should be idempotent. assert.commandWorked(primary.adminCommand({setFeatureCompatibilityVersion: lastStableFCV})); rst.awaitReplication(); // Ensure the secondary is still running. rst.stopSet(); // // Sharding tests. // let st; let mongosAdminDB; let configPrimaryAdminDB; let shardPrimaryAdminDB; // A 'latest' binary cluster started with clean data files will set FCV to 'latestFCV'. st = new ShardingTest({ shards: {rs0: {nodes: [{binVersion: latest}, {binVersion: latest}]}}, other: {useBridge: true} }); mongosAdminDB = st.s.getDB("admin"); configPrimaryAdminDB = st.configRS.getPrimary().getDB("admin"); shardPrimaryAdminDB = st.rs0.getPrimary().getDB("admin"); // TODO: update this to 'latestFCV' when SERVER-32597 bumps the FCV default. checkFCV(configPrimaryAdminDB, lastStableFCV); checkFCV(shardPrimaryAdminDB, lastStableFCV); // TODO: remove this when SERVER-32597 bumps the FCV default ot 4.0. assert.commandWorked(mongosAdminDB.runCommand({setFeatureCompatibilityVersion: latestFCV})); // featureCompatibilityVersion cannot be set to invalid value on mongos. assert.commandFailed(mongosAdminDB.runCommand({setFeatureCompatibilityVersion: 5})); assert.commandFailed(mongosAdminDB.runCommand({setFeatureCompatibilityVersion: "3.2"})); assert.commandFailed(mongosAdminDB.runCommand({setFeatureCompatibilityVersion: "4.2"})); // setFeatureCompatibilityVersion rejects unknown fields on mongos. assert.commandFailed( mongosAdminDB.runCommand({setFeatureCompatibilityVersion: lastStableFCV, unknown: 1})); // setFeatureCompatibilityVersion can only be run on the admin database on mongos. assert.commandFailed( st.s.getDB("test").runCommand({setFeatureCompatibilityVersion: lastStableFCV})); // featureCompatibilityVersion cannot be set via setParameter on mongos. assert.commandFailed( mongosAdminDB.runCommand({setParameter: 1, featureCompatibilityVersion: lastStableFCV})); // Prevent the shard primary from receiving messages from the config server primary. When we try // to set FCV to 'lastStableFCV', the command should fail because the shard cannot be contacted. st.rs0.getPrimary().discardMessagesFrom(st.configRS.getPrimary(), 1.0); assert.commandFailed( mongosAdminDB.runCommand({setFeatureCompatibilityVersion: lastStableFCV, maxTimeMS: 1000})); checkFCV( configPrimaryAdminDB, lastStableFCV, lastStableFCV /* indicates downgrade in progress */); st.rs0.getPrimary().discardMessagesFrom(st.configRS.getPrimary(), 0.0); // FCV can be set to 'lastStableFCV' on mongos. // This is run through assert.soon() because we've just caused a network interruption // by discarding messages in the bridge. assert.soon(function() { res = mongosAdminDB.runCommand({setFeatureCompatibilityVersion: lastStableFCV}); if (res.ok == 0) { print("Failed to set feature compatibility version: " + tojson(res)); return false; } return true; }); // featureCompatibilityVersion propagates to config and shard. checkFCV(configPrimaryAdminDB, lastStableFCV); checkFCV(shardPrimaryAdminDB, lastStableFCV); // A 'latest' binary replica set started as a shard server defaults to 'lastStableFCV'. let latestShard = new ReplSetTest({ name: "latestShard", nodes: [{binVersion: latest}, {binVersion: latest}], nodeOptions: {shardsvr: ""}, useHostName: true }); latestShard.startSet(); latestShard.initiate(); let latestShardPrimaryAdminDB = latestShard.getPrimary().getDB("admin"); checkFCV(latestShardPrimaryAdminDB, lastStableFCV); assert.commandWorked(mongosAdminDB.runCommand({addShard: latestShard.getURL()})); checkFCV(latestShardPrimaryAdminDB, lastStableFCV); // FCV can be set to 'latestFCV' on mongos. assert.commandWorked(mongosAdminDB.runCommand({setFeatureCompatibilityVersion: latestFCV})); checkFCV(st.configRS.getPrimary().getDB("admin"), latestFCV); checkFCV(shardPrimaryAdminDB, latestFCV); checkFCV(latestShardPrimaryAdminDB, latestFCV); // Call ShardingTest.stop before shutting down latestShard, so that the UUID check in // ShardingTest.stop can talk to latestShard. st.stop(); latestShard.stopSet(); // Create cluster with a 'lastStable' binary mongos so that we can add 'lastStable' binary // shards. st = new ShardingTest({shards: 0, other: {mongosOptions: {binVersion: lastStable}}}); mongosAdminDB = st.s.getDB("admin"); configPrimaryAdminDB = st.configRS.getPrimary().getDB("admin"); checkFCV(configPrimaryAdminDB, lastStableFCV); // Adding a 'lastStable' binary shard to a cluster with 'lastStableFCV' succeeds. let lastStableShard = new ReplSetTest({ name: "lastStableShard", nodes: [{binVersion: lastStable}, {binVersion: lastStable}], nodeOptions: {shardsvr: ""}, useHostName: true }); lastStableShard.startSet(); lastStableShard.initiate(); assert.commandWorked(mongosAdminDB.runCommand({addShard: lastStableShard.getURL()})); checkFCV(lastStableShard.getPrimary().getDB("admin"), lastStableFCV); // call ShardingTest.stop before shutting down lastStableShard, so that the UUID check in // ShardingTest.stop can talk to lastStableShard. st.stop(); lastStableShard.stopSet(); // Create a cluster running with 'latestFCV' st = new ShardingTest({shards: 1, mongos: 1}); mongosAdminDB = st.s.getDB("admin"); configPrimaryAdminDB = st.configRS.getPrimary().getDB("admin"); shardPrimaryAdminDB = st.shard0.getDB("admin"); // TODO: update this to 'latestFCV' when SERVER-32597 updates the FCV defaults. checkFCV(configPrimaryAdminDB, lastStableFCV); checkFCV(shardPrimaryAdminDB, lastStableFCV); // TODO: remove this when SERVER-32597 updates the FCV defaults. assert.commandWorked(mongosAdminDB.runCommand({setFeatureCompatibilityVersion: latestFCV})); // Ensure that a 'lastStable' binary mongos can be added to a 'lastStableFCV' cluster. assert.commandWorked(mongosAdminDB.runCommand({setFeatureCompatibilityVersion: lastStableFCV})); checkFCV(configPrimaryAdminDB, lastStableFCV); checkFCV(shardPrimaryAdminDB, lastStableFCV); let lastStableMongos = MongoRunner.runMongos({configdb: st.configRS.getURL(), binVersion: lastStable}); assert.neq(null, lastStableMongos, "mongos was unable to start up with binary version=" + latest + " and connect to FCV=" + lastStableFCV + " cluster"); // Ensure that the 'lastStable' binary mongos can perform reads and writes to the shards in the // cluster. assert.writeOK(lastStableMongos.getDB("test").foo.insert({x: 1})); let foundDoc = lastStableMongos.getDB("test").foo.findOne({x: 1}); assert.neq(null, foundDoc); assert.eq(1, foundDoc.x, tojson(foundDoc)); // The 'lastStable' binary mongos can no longer perform reads and writes after the cluster is // upgraded to 'latestFCV'. assert.commandWorked(mongosAdminDB.runCommand({setFeatureCompatibilityVersion: latestFCV})); assert.writeError(lastStableMongos.getDB("test").foo.insert({x: 1})); // The 'latest' binary mongos can still perform reads and writes after the FCV is upgraded to // 'latestFCV'. assert.writeOK(st.s.getDB("test").foo.insert({x: 1})); st.stop(); })();
45.027539
101
0.683116
dbcbeb34f8b395af2e6f49ff121df7697f3ebff7
440
js
JavaScript
public/css/wp-content/themes/adalainedesign-ladyboss/js/global8a54.js
vutruong626/truong.sky.com
0e1bba01e123c7f6c31b42dcb855dc7791e7d03d
[ "MIT" ]
null
null
null
public/css/wp-content/themes/adalainedesign-ladyboss/js/global8a54.js
vutruong626/truong.sky.com
0e1bba01e123c7f6c31b42dcb855dc7791e7d03d
[ "MIT" ]
null
null
null
public/css/wp-content/themes/adalainedesign-ladyboss/js/global8a54.js
vutruong626/truong.sky.com
0e1bba01e123c7f6c31b42dcb855dc7791e7d03d
[ "MIT" ]
null
null
null
jQuery(function( $ ){ // Sticky Announcement Bar var headerHeight = $('.site-header').innerHeight(); var beforeheaderHeight = $('.before-header').outerHeight(); var abovenavHeight = headerHeight + beforeheaderHeight - 1; $(window).scroll(function(){ if ($(document).scrollTop() > abovenavHeight){ $('.announcement-widget').addClass('fixed'); } else { $('.announcement-widget').removeClass('fixed'); } }); });
20
60
0.647727
dbcc0fabc0195c03b59e2d711f2da389666389ff
258
js
JavaScript
src/components/transformer/index.js
xom9ikk/verticals-backend
d8b969965e7550c774c8fd0f8407ee0df6ccd8e7
[ "MIT" ]
null
null
null
src/components/transformer/index.js
xom9ikk/verticals-backend
d8b969965e7550c774c8fd0f8407ee0df6ccd8e7
[ "MIT" ]
null
null
null
src/components/transformer/index.js
xom9ikk/verticals-backend
d8b969965e7550c774c8fd0f8407ee0df6ccd8e7
[ "MIT" ]
1
2022-01-01T14:21:46.000Z
2022-01-01T14:21:46.000Z
const { CDN_ADDRESS, } = process.env; class TransformerComponent { transformLink(relativePath) { return relativePath ? `${CDN_ADDRESS}/${relativePath}` : relativePath; } } module.exports = { TransformerComponent: new TransformerComponent(), };
18.428571
74
0.717054
dbcc3194e020036d8b7c5f1b7d0fc535923af21a
827
js
JavaScript
src/reducers/sleepRecorder.js
chriswu14/BabySleepNotes
d320266cc2a20f5ded89b53f059f74e576bba404
[ "MIT" ]
null
null
null
src/reducers/sleepRecorder.js
chriswu14/BabySleepNotes
d320266cc2a20f5ded89b53f059f74e576bba404
[ "MIT" ]
null
null
null
src/reducers/sleepRecorder.js
chriswu14/BabySleepNotes
d320266cc2a20f5ded89b53f059f74e576bba404
[ "MIT" ]
null
null
null
import { START_WATCH, STOP_WATCH, RESET_WATCH } from '../actions/sleepRecorder'; const initialState = { isRunning: false, initialTime: null, startTime: null, stopTime: null }; export default function sleepRecorder(state = initialState, action) { switch (action.type) { case START_WATCH: return { ...state, initialTime: !state.initialTime ? action.time : state.initialTime, isRunning: true, startTime: action.time, stopTime: null }; case STOP_WATCH: return { ...state, isRunning: false, stopTime: action.time }; case RESET_WATCH: return { ...state, initialTime: null, isRunning: false, startTime: null, stopTime: null }; default: return state; } };
20.170732
80
0.585248
dbcc4cbeb0c7ba7bc824dc84ed41989ce179fb2c
525
js
JavaScript
src/commands/restart.js
Musix-Development/musix-v3
f6161004746077a55b0586b255dea2a1d68d97b5
[ "MIT" ]
1
2021-06-14T17:35:00.000Z
2021-06-14T17:35:00.000Z
src/commands/restart.js
Musix-Development/musix-v3
f6161004746077a55b0586b255dea2a1d68d97b5
[ "MIT" ]
null
null
null
src/commands/restart.js
Musix-Development/musix-v3
f6161004746077a55b0586b255dea2a1d68d97b5
[ "MIT" ]
null
null
null
module.exports = { name: 'restart', alias: ["none"], usage: '', description: 'restart all shards', onlyDev: true, permission: 'dev', category: 'util', async execute(msg, args, client, Discord, command) { client.shard.broadcastEval("this.funcs.saveDB(this);"); msg.channel.send(client.messages.dbSaved); msg.channel.send(client.messages.restart); client.shard.respawnAll(client.config.shardDelay, client.config.respawnDelay, client.config.spawnTimeout); } };
35
114
0.655238
dbce49485883f37ca4cc153e089b8905d22fcb0a
471
js
JavaScript
publication/assets/admui/js/examples/pages/general/faq.js
ximenwenbo/iliao
cbb8eb91f1692a226e49fbf6b33f9adf439b27e7
[ "Apache-2.0" ]
null
null
null
publication/assets/admui/js/examples/pages/general/faq.js
ximenwenbo/iliao
cbb8eb91f1692a226e49fbf6b33f9adf439b27e7
[ "Apache-2.0" ]
null
null
null
publication/assets/admui/js/examples/pages/general/faq.js
ximenwenbo/iliao
cbb8eb91f1692a226e49fbf6b33f9adf439b27e7
[ "Apache-2.0" ]
null
null
null
/** * Admui-iframe v2.0.0 (http://www.admui.com/) * Copyright 2015-2018 Admui Team * Licensed under the Admui License 1.1 (http://www.admui.com/about/license) */ (function (document, window, $) { 'use strict'; if ($('.list-group[data-plugin="nav-tabs"]').length) { $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { $(e.target).addClass('active').siblings().removeClass('active'); }); } })(document, window, jQuery);
31.4
76
0.592357
dbce6b3127aefe8b8b321c353476668139078f65
8,772
js
JavaScript
src/utils/list.js
lab-result/web-plugins
6b18226e454b419454e8ded7676694933cfeeee2
[ "MIT" ]
null
null
null
src/utils/list.js
lab-result/web-plugins
6b18226e454b419454e8ded7676694933cfeeee2
[ "MIT" ]
null
null
null
src/utils/list.js
lab-result/web-plugins
6b18226e454b419454e8ded7676694933cfeeee2
[ "MIT" ]
1
2020-04-06T22:05:47.000Z
2020-04-06T22:05:47.000Z
import _ from 'lodash'; /** * Pushes items to the start of an array. Does not mutate the array. * * @example * console.log(pushStart([1, 1, 1], 2)); * // [2, 1, 1, 1] * console.log(pushStart([1, 1, 1], 1, 2, 3)); * // [3, 2, 1, 1, 1, 1] * * @param {any[]} arr - Array to push to. * @param {...any} items - Items to push into the start of the array. * @return {any[]} Resulting array. */ export const pushStart = (arr, ...items) => [..._.reverse(items), ...arr]; /** * Like {@link pushStart}, but pushes to the end. Does not mutate the array. * * @example * console.log(pushEnd([1, 1, 1], 2)); * // [1, 1, 1, 2] * console.log(pushEnd([1, 1, 1], 1, 2, 3)); * // [1, 1, 1, 1, 2, 3] */ export const pushEnd = (arr, ...items) => [...arr, ...items]; /** * Sets the given index of the array to the given value. Does not mutate the * array. * * @example * console.log(setIndex(['foo', 'bar', 'baz'], 1, 'quax')) * // ['foo', 'quax', 'baz'] * * @param {any[]} arr - Array to change. * @param {number} index - Index of element to be set. * @param {any} value - Value to set. * @return {any[]} Resulting array. */ export const setIndex = (arr, index, value) => arr.map((v, i) => i === index ? value : v); /** * Removes the element with the given index from the array. Does not mutate the * array. * * @example * console.log(removeIndex(['foo', 'bar', 'baz'], 1)) * // ['foo', 'baz'] * * @param {any[]} arr - Array to remove from. * @param {number} index - Index of element to be removed. * @return {any[]} Resulting array. */ export const removeIndex = (arr, index) => arr.filter((v, i) => i !== index); /** * Pads an array if necessary to reach a minimum length. The provided padding * item is appended to the array. * * @example * console.log(padEnd(['foo', 'bar'], 5, '--')); * // ['foo', 'bar', '--', '--', '--'] * * @param {any[]} arr - Array to pad. * @param {number} length - Minimum length of the resulting padded array. * @param {any} item - Item to pad if arr does not meet the minimum length. * @return {any[]} The padded array. */ export const padEnd = (arr = [], length, item) => arr.length > length ? arr : _.concat(arr, Array(length - arr.length).fill(item)); /** * Assigns a weight property to each item in an array based on their order. * Items can be grouped into a sub-array to assign equal weights to them. Useful * for calculating weights of queue items. * * @example * console.log(assignWeight([{}, {}, {}])); * // [{weight: 0}, {weight: 1}, {weight: 2}] * console.log(assignWeight([{}, [{auto: true}, {auto: true}], {}])); * // [{weight: 0}, {auto: true, weight: 1}, {auto: true, weight: 1}, {weight: 2}] * * @param {Object[]} arr - Array of objects to which weights must be assigned. * @param {number} [startAt=0] - Minimum weight to start at. * @return {Object[]} Flat array of all weighted objects. */ export const assignWeight = (arr, initialIndex = 0) => ( arr.flatMap((item, i) => _.isArray(item) ? item.map(v => ({ ...v, weight: +initialIndex + i })) : ({ ...item, weight: +initialIndex + i })) ); /** * Sorts array of objects whether by ascending or descending. * * @example * console.log(sortArrayOfObject([{ foo: '2' }, { foo: '1' }], true, 'foo')); * // [{ foo: '1' }, { foo: '2' }] * console.log(sortArrayOfObject([{ foo: 1 }, { foo: 2 }], false, 'foo')); * // [{ foo: 2 }, { foo: 1 }] * * @param {Object[]} arr - Array of object to be sorted. * @param {boolean} isAscending - Sort specs. * @param {string} sortKey - Key to be sorted. */ export const sortArrayOfObject = (arr, isAscending, sortKey) => arr .sort((item1, item2) => { if (!item1[sortKey]) return 0; if (!item2[sortKey]) return 0; const a = item1[sortKey]; const b = item2[sortKey]; return isAscending ? a > b ? 1 : -1 : a < b ? 1 : -1; }); /** * Finds the intersection of elements between two arrays. * * An object of keys is first built to check values against, to allow for O(n) * to get the intersection instead of a naive nested loop for O(n^2). * * To compare arrays of objects, pass in a third `path` parameter to use for * extracting an identifying key (e.g. 'id'). * * @example * const arr1 = ['foo', 'bar', 'baz']; * const arr2 = ['bar', 'baz', 'quax']; * console.log(intersect(arr1, arr2)); * // ['bar', 'baz'] * * const objArr1 = [{id: 1}, {id: 2}, {id: 3}]; * const objArr2 = [{id: 2}, {id: 4}, {id: 6}]; * console.log(intersect(objArr1, objArr2, 'id')); * // [{id: 2}] * * @param {any[]} arr1 * @param {any[]} arr2 * @param {String} [path] - Path for extracting an ID for comparing objects. * @return {any[]} Intersection of arr1 and arr2. */ export const intersect = (arr1, arr2, path) => { arr1 = arr1 || []; arr2 = arr2 || []; const map = arr1.reduce((acc, val) => { const key = _.isObject(val) ? val[path] : val; return _.set(acc, key, val); }, {}); const filtered = arr2.filter(val => { const key = _.isObject(val) ? val[path] : val; return _.has(map, key); }); const merged = filtered.map(val => { if (!_.isObject(val)) return val; const other = _.get(map, val[path]); return { ...other, ...val }; }); return merged; }; /** * Finds the set difference between two arrays. That is, all elements of the * first array that are not also elements of the second array. * * Has the same object-building optimization as {@link intersect}. * * To compare arrays of objects, pass in a third `path` parameter to use for * extracting an identifying key (e.g. 'id'). * * @example * const arr1 = ['foo', 'bar', 'baz']; * const arr2 = ['bar', 'baz', 'quax']; * console.log(subtract(arr1, arr2)); * // ['foo'] * * const objArr1 = [{id: 1}, {id: 2}, {id: 3}]; * const objArr2 = [{id: 2}, {id: 4}, {id: 6}]; * console.log(subtract(objArr1, objArr2, 'id')); * // [{id: 1}, {id: 3}] * * @param {any[]} arr1 * @param {any[]} arr2 * @param {String} [path] - Path for extracting an ID for comparing objects. * @return {any[]} Intersection of arr1 and arr2. */ export const subtract = (arr1, arr2, path) => { // build a map from arr2, since we'll be comparing against arr2 const map = arr2.reduce((acc, val) => { const key = _.isObject(val) ? val[path] : val; return _.set(acc, key, val); }, {}); const filtered = arr1.filter(val => { const key = _.isObject(val) ? val[path] : val; return !_.has(map, key); }); return filtered; }; function increment (arr, bounds, index = 0) { const result = [...arr]; const max = bounds[index]; if (index >= arr.length) return null; if (+arr[index] < max - 1) { result[index]++; return result; } else { result[index] = 0; return increment(result, bounds, index + 1); } } function * walkCombinations (arr2d) { let state = Array(arr2d.length).fill(0); const bounds = arr2d.map(arr => arr.length); while (state !== null) { yield arr2d.map((arr, i) => arr[state[i]]); state = increment(state, bounds); } } /** * Generates all combinations (as in combinatorics) of the given sets of * elements. * * The generated combinations will contain one element from each of the given * arrays: first element will be from the first array, second element from the * second array, and so on. * * @example * console.log(getCombinations(['soft', 'hard'], ['red', 'blue', 'green'])); * // [ * // ['soft', 'red'], * // ['hard', 'red'], * // ['soft', 'blue'], * // ['hard', 'blue'], * // ['soft', 'green'], * // ['hard', 'green'], * // ] * * @param {...any[]} arrs - The arrays from which elements will be taken for * generating combinations. * @return {any[][]} The generated combinations. */ export const getCombinations = (...arrs) => [...walkCombinations(arrs)]; const sumObjValues = (a, b) => _.mergeWith(a, b, (x = 0, y = 0) => +x + +y); /** * Sums a list of corresponding object values. * * @example * const arr = [{a: 2, b: 5}, {a: 3, b: 5}]; * console.log(sumObjects(arr)); * // {a: 5, b: 10} * * @param {Object[]} arr - Array of objects whose values will be summed. * @return {Object} Object whose keys contain the sums of all corresponding * values in the given array. */ export const sumObjects = arr => arr.reduce(sumObjValues, {}); const rangeGenerator = function * (start, end) { for (let i = start; i <= end; i++) { yield i; } }; export const range = (firstArg, secondArg) => { let start; let end; if (_.isNil(secondArg)) { // case: range(n), count from 1 to n start = 1; end = firstArg; } else { // case: range(start, end), count from start to end start = firstArg; end = secondArg; } return [...rangeGenerator(start, end)]; };
30.248276
82
0.589375
dbce97872a8f29c81b7711c94ea58e4b5f5fba99
3,811
js
JavaScript
scripts/script.js
3imed-jaberi/play-with-drawing
911da7fff283a8ab86317668c418b3f302470b1b
[ "MIT" ]
null
null
null
scripts/script.js
3imed-jaberi/play-with-drawing
911da7fff283a8ab86317668c418b3f302470b1b
[ "MIT" ]
null
null
null
scripts/script.js
3imed-jaberi/play-with-drawing
911da7fff283a8ab86317668c418b3f302470b1b
[ "MIT" ]
null
null
null
"use strict"; // the url for the save.php script => save the image in aa folder .. const GLOBALE_URL = "http://localhost/app/php/save.php" ; // canvas dom object .. let canvas = document.getElementById('myCan'); // put the context of the canvas => 2D .. let context = canvas.getContext('2d'); // canvas size value .. let canvasSize = { width : canvas.width , height : canvas.height } ; // mouse coordinates .. let mouse = { x: 0, y: 0 }; let last_mouse = { x: 0, y: 0 }; // init default value .. let drawup = false; let drawColor = 'black'; let drawWidth = document.getElementById('pen-width').value; // listen to the change value of the pen color .. document.getElementById('pen-color').addEventListener('change', function () { drawColor = document.getElementById('pen-color').value; }); // listen to the change value of the pen size .. document.getElementById('pen-width').addEventListener('change', function () { drawWidth = document.getElementById('pen-width').value; }); // clear your canvas .. document.getElementById('clear').addEventListener("click", function () { swal({ title: "Are you sure?", text: "you want to clear this canvas ?", icon: "warning", buttons: true, dangerMode: true, }) .then((willDelete) => { if (willDelete) { // init the canvas ( return to the beginning value ) .. context.clearRect(0, 0, canvasSize.width, canvasSize.height); // hide the image if he is in the show mode .. document.getElementById('canvas-result').style.display = 'none'; } }); }); // save the picture is drawn .. document.getElementById('save').addEventListener("click", function () { let dataURL = canvas.toDataURL(); // default is 'image/png' .. document.getElementById('canvas-result').src = dataURL; document.getElementById('canvas-result').style.display = 'inline'; //AJAX to Server base64 data to the server $.ajax({ type:"POST", url: GLOBALE_URL, dataType: "text", data: { basedata : dataURL }, success: function (result){ console.log(result); } }); }); // mouse movement in the canvas .. canvas.addEventListener('mousemove', function (event) { // make listen the current mouse coordinates ( history in last mouse coordinates ) .. last_mouse.x = mouse.x; last_mouse.y = mouse.y; // get the current mouse coordinates compared to the offset .. mouse.x = event.pageX - this.offsetLeft; mouse.y = event.pageY - this.offsetTop; // draw .. draw('move'); }, false); // when the mouse move down in the canvas => draw down .. canvas.addEventListener('mousedown', function (event) { draw('down'); }, false); // when the mouse move up in the canvas => draw up .. canvas.addEventListener('mouseup', function (event) { draw('up'); }, false); /* * for limit the pen in the canvas size : * canvas.addEventListener('mouseout', function (event) { draw('up'); }, false); * */ // draw function ( real time hhh :p ) .. function draw (movment_action) { // condition for drawing in the right state .. if (movment_action == 'down') { drawup = true; } if (movment_action == 'up') { drawup = false; } // if the state is right .. if (drawup) { context.beginPath(); // the line start .. context.moveTo(last_mouse.x, last_mouse.y); // the line end .. context.lineTo(mouse.x, mouse.y); // some style for each point of the line .. context.strokeStyle = drawColor; context.lineWidth = drawWidth; context.stroke(); context.closePath(); } }
28.22963
91
0.604828
dbcf0b3ff2fff35f7b7879a37dadbf463b48bd68
851
js
JavaScript
src/lib/useRaf.js
0m15/mysite
4fe1189c10e54a8af029efe937c26e8399579de5
[ "MIT" ]
null
null
null
src/lib/useRaf.js
0m15/mysite
4fe1189c10e54a8af029efe937c26e8399579de5
[ "MIT" ]
14
2020-01-06T10:01:02.000Z
2022-02-26T13:01:28.000Z
src/lib/useRaf.js
0m15/mysite
4fe1189c10e54a8af029efe937c26e8399579de5
[ "MIT" ]
null
null
null
import { useLayoutEffect, useState } from 'react'; const useRaf = (ms, delay) => { const [elapsed, set] = useState(0); useLayoutEffect(() => { let raf; let timerStop; let start; const onFrame = () => { const time = Math.min(1, (Date.now() - start) / ms); set(time); loop(); }; const loop = () => { raf = requestAnimationFrame(onFrame); }; const onStart = () => { timerStop = setTimeout(() => { cancelAnimationFrame(raf); set(1); }, ms); start = Date.now(); loop(); }; const timerDelay = setTimeout(onStart, delay); return () => { clearTimeout(timerStop); clearTimeout(timerDelay); cancelAnimationFrame(raf); }; }, [ms, delay]); return elapsed; }; export default useRaf;
21.820513
59
0.515864
dbcf3907f9e76b15422c1b4b66a1233ea28ab289
247
js
JavaScript
worker/worker.js
adamchalmers/quiet-serverless
2a761ab28274b2c6349503edac272f09d9cb4bb2
[ "Apache-2.0", "MIT" ]
1
2020-10-12T01:48:47.000Z
2020-10-12T01:48:47.000Z
worker/worker.js
adamchalmers/quiet-serverless
2a761ab28274b2c6349503edac272f09d9cb4bb2
[ "Apache-2.0", "MIT" ]
null
null
null
worker/worker.js
adamchalmers/quiet-serverless
2a761ab28274b2c6349503edac272f09d9cb4bb2
[ "Apache-2.0", "MIT" ]
null
null
null
addEventListener('fetch', event => { event.respondWith(handle(event)) }) async function handle(event) { const { main } = wasm_bindgen; await wasm_bindgen(wasm); let resp = await main(event); console.log("resp:", resp); return resp; }
20.583333
36
0.680162
dbd054c17fdd7e39983dd3a56a7f9e0f822b7ff8
286
js
JavaScript
src/index.js
1cgeo/dsgdocs
59d8865de0f0bb36e9d4a6c411ec6f7d9eb3925e
[ "MIT" ]
1
2019-01-13T23:54:16.000Z
2019-01-13T23:54:16.000Z
src/index.js
1cgeo/DSGDocs
59d8865de0f0bb36e9d4a6c411ec6f7d9eb3925e
[ "MIT" ]
null
null
null
src/index.js
1cgeo/DSGDocs
59d8865de0f0bb36e9d4a6c411ec6f7d9eb3925e
[ "MIT" ]
null
null
null
"use strict"; require("dotenv").config(); const app = require("./app"); const { logger } = require("./logger"); //Starts server app.listen(process.env.PORT, () => { logger.info("Server start", { context: "index", information: { port: process.env.PORT } }); });
16.823529
39
0.583916
dbd0cb82402ef1148bd0ee4ce549968abd3ec8ad
290
js
JavaScript
models/ordersModel.js
darksun27/zomentum-hiring-challenge
82c19f55c3ad4e6ba614e3a18eb84c80d20a2fed
[ "MIT" ]
null
null
null
models/ordersModel.js
darksun27/zomentum-hiring-challenge
82c19f55c3ad4e6ba614e3a18eb84c80d20a2fed
[ "MIT" ]
null
null
null
models/ordersModel.js
darksun27/zomentum-hiring-challenge
82c19f55c3ad4e6ba614e3a18eb84c80d20a2fed
[ "MIT" ]
1
2020-08-30T21:33:56.000Z
2020-08-30T21:33:56.000Z
const mongoose = require('mongoose'); const OrderSchema = new mongoose.Schema({ serial_number: String, name: String, customer: String, rent_on: Date, rent_due: Date, rent_pm: Number, agreement: String, }); module.exports = mongoose.model("Order", OrderSchema);
22.307692
54
0.67931
dbd160d610854f6f2aa37a8ed2ff5b2185b82fdd
5,178
js
JavaScript
web-client/src/presenter/actions/updatePetitionDetailsAction.test.js
kkoskelin/ef-cms
871bc91aff17ed57669b1608f21eb3f58a44a7dd
[ "CC0-1.0" ]
null
null
null
web-client/src/presenter/actions/updatePetitionDetailsAction.test.js
kkoskelin/ef-cms
871bc91aff17ed57669b1608f21eb3f58a44a7dd
[ "CC0-1.0" ]
null
null
null
web-client/src/presenter/actions/updatePetitionDetailsAction.test.js
kkoskelin/ef-cms
871bc91aff17ed57669b1608f21eb3f58a44a7dd
[ "CC0-1.0" ]
null
null
null
import { applicationContextForClient as applicationContext } from '../../../../shared/src/business/test/createTestApplicationContext'; import { presenter } from '../presenter-mock'; import { runAction } from 'cerebral/test'; import { updatePetitionDetailsAction } from './updatePetitionDetailsAction'; describe('updatePetitionDetailsAction', () => { let PAYMENT_STATUS; beforeAll(() => { ({ PAYMENT_STATUS } = applicationContext.getConstants()); presenter.providers.applicationContext = applicationContext; applicationContext .getUseCases() .updatePetitionDetailsInteractor.mockReturnValue({ docketNumber: '123-20', }); }); it('creates date from form month, day, year fields and calls the use case with form data for a waived payment', async () => { const result = await runAction(updatePetitionDetailsAction, { modules: { presenter, }, state: { caseDetail: { docketNumber: '123-20' }, form: { paymentDateWaivedDay: '01', paymentDateWaivedMonth: '01', paymentDateWaivedYear: '2001', petitionPaymentStatus: PAYMENT_STATUS.WAIVED, }, }, }); expect( applicationContext.getUseCases().updatePetitionDetailsInteractor, ).toHaveBeenCalled(); expect( applicationContext.getUseCases().updatePetitionDetailsInteractor.mock .calls[0][0], ).toMatchObject({ petitionDetails: { petitionPaymentStatus: PAYMENT_STATUS.WAIVED, petitionPaymentWaivedDate: '2001-01-01T05:00:00.000Z', }, }); expect(result.output).toEqual({ alertSuccess: { message: 'Changes saved.', }, caseDetail: { docketNumber: '123-20' }, docketNumber: '123-20', tab: 'caseInfo', }); }); it('creates date from form month, day, year fields and calls the use case with form data for a paid payment', async () => { const result = await runAction(updatePetitionDetailsAction, { modules: { presenter, }, state: { caseDetail: { docketNumber: '123-20' }, form: { paymentDateDay: '01', paymentDateMonth: '01', paymentDateYear: '2001', petitionPaymentStatus: PAYMENT_STATUS.PAID, }, }, }); expect( applicationContext.getUseCases().updatePetitionDetailsInteractor, ).toHaveBeenCalled(); expect( applicationContext.getUseCases().updatePetitionDetailsInteractor.mock .calls[0][0], ).toMatchObject({ petitionDetails: { petitionPaymentDate: '2001-01-01T05:00:00.000Z', petitionPaymentStatus: PAYMENT_STATUS.PAID, }, }); expect(result.output).toEqual({ alertSuccess: { message: 'Changes saved.', }, caseDetail: { docketNumber: '123-20' }, docketNumber: '123-20', tab: 'caseInfo', }); }); it('creates IRS notice date from form month, day, year fields and calls the use case with form data', async () => { const result = await runAction(updatePetitionDetailsAction, { modules: { presenter, }, state: { caseDetail: { docketNumber: '123-20' }, form: { irsDay: '01', irsMonth: '01', irsYear: '2001', }, }, }); expect( applicationContext.getUseCases().updatePetitionDetailsInteractor, ).toHaveBeenCalled(); expect( applicationContext.getUseCases().updatePetitionDetailsInteractor.mock .calls[0][0], ).toMatchObject({ petitionDetails: { irsNoticeDate: '2001-01-01T05:00:00.000Z', }, }); expect(result.output).toEqual({ alertSuccess: { message: 'Changes saved.', }, caseDetail: { docketNumber: '123-20' }, docketNumber: '123-20', tab: 'caseInfo', }); }); it('should send preferredTrialCity to the use case as null if it is not on the form', async () => { await runAction(updatePetitionDetailsAction, { modules: { presenter, }, state: { caseDetail: { docketNumber: '123-20' }, form: {}, }, }); expect( applicationContext.getUseCases().updatePetitionDetailsInteractor, ).toHaveBeenCalled(); expect( applicationContext.getUseCases().updatePetitionDetailsInteractor.mock .calls[0][0], ).toMatchObject({ petitionDetails: { preferredTrialCity: null, }, }); }); it('should send preferredTrialCity to the use case if it is on the form', async () => { await runAction(updatePetitionDetailsAction, { modules: { presenter, }, state: { caseDetail: { docketNumber: '123-20' }, form: { preferredTrialCity: 'Fresno, California' }, }, }); expect( applicationContext.getUseCases().updatePetitionDetailsInteractor, ).toHaveBeenCalled(); expect( applicationContext.getUseCases().updatePetitionDetailsInteractor.mock .calls[0][0], ).toMatchObject({ petitionDetails: { preferredTrialCity: 'Fresno, California', }, }); }); });
28.766667
134
0.610854
dbd408f20297e1e5cd8a2154a4e9293e35bc8fa6
127
js
JavaScript
src/components/status.js
lta4/eli-martinez-realtor
41edcc66068465aa8ba6365dee340c6522fd282f
[ "RSA-MD" ]
null
null
null
src/components/status.js
lta4/eli-martinez-realtor
41edcc66068465aa8ba6365dee340c6522fd282f
[ "RSA-MD" ]
null
null
null
src/components/status.js
lta4/eli-martinez-realtor
41edcc66068465aa8ba6365dee340c6522fd282f
[ "RSA-MD" ]
null
null
null
import * as React from "react" const Status = () => { return ( <h1>status page</h1> ) } export default Status
14.111111
30
0.566929
dbd4c153f8118316405ada8e67515aaa419da496
2,862
js
JavaScript
bench/Path.bench.js
DarrenPaulWright/path-artisan
54af38554c1a0e327198f5116e37ce706c10a08f
[ "MIT" ]
null
null
null
bench/Path.bench.js
DarrenPaulWright/path-artisan
54af38554c1a0e327198f5116e37ce706c10a08f
[ "MIT" ]
7
2021-06-20T17:16:58.000Z
2021-06-20T17:17:04.000Z
bench/Path.bench.js
DarrenPaulWright/pathinator
54af38554c1a0e327198f5116e37ce706c10a08f
[ "MIT" ]
null
null
null
import { benchSettings } from 'karma-webpack-bundle'; import { Path } from '../index.js'; suite('Path', () => { let temporaryTarget = {}; benchmark('single point', () => { temporaryTarget = new Path('m1,2l3,4z'); }, benchSettings); benchmark('three points', () => { temporaryTarget = new Path('m1,2c1,2 3,4 5,6z'); }, benchSettings); benchmark('three points compressed', () => { temporaryTarget = new Path('m1,2c1,2-3,-4 5-9z'); }, benchSettings); benchmark('complex', () => { temporaryTarget = new Path('M213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.9\n C33.3,145.1,67.5,170.3,125,217c59.3-46.7,93.5-71.9,111.5-106.1C263.4,64.2,247.2,22.9,213.1,6.7zM213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.9\n C33.3,145.1,67.5,170.3,125,217c59.3-46.7,93.5-71.9,111.5-106.1C263.4,64.2,247.2,22.9,213.1,6.7zM213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.9\n C33.3,145.1,67.5,170.3,125,217c59.3-46.7,93.5-71.9,111.5-106.1C263.4,64.2,247.2,22.9,213.1,6.7zM213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.9\n C33.3,145.1,67.5,170.3,125,217c59.3-46.7,93.5-71.9,111.5-106.1C263.4,64.2,247.2,22.9,213.1,6.7zM213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.9\n C33.3,145.1,67.5,170.3,125,217c59.3-46.7,93.5-71.9,111.5-106.1C263.4,64.2,247.2,22.9,213.1,6.7z'); }, benchSettings); const path = new Path('M213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.9\n C33.3,145.1,67.5,170.3,125,217c59.3-46.7,93.5-71.9,111.5-106.1C263.4,64.2,247.2,22.9,213.1,6.7zM213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.9\n C33.3,145.1,67.5,170.3,125,217c59.3-46.7,93.5-71.9,111.5-106.1C263.4,64.2,247.2,22.9,213.1,6.7zM213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.9\n C33.3,145.1,67.5,170.3,125,217c59.3-46.7,93.5-71.9,111.5-106.1C263.4,64.2,247.2,22.9,213.1,6.7zM213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.9\n C33.3,145.1,67.5,170.3,125,217c59.3-46.7,93.5-71.9,111.5-106.1C263.4,64.2,247.2,22.9,213.1,6.7zM213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.9\n C33.3,145.1,67.5,170.3,125,217c59.3-46.7,93.5-71.9,111.5-106.1C263.4,64.2,247.2,22.9,213.1,6.7z'); benchmark('export', (deferred) => { return path.export() .then(() => { deferred.resolve(); }); }, { ...benchSettings, defer: true }); benchmark('export async', (deferred) => { return path.export({ async: true }) .then(() => { deferred.resolve(); }); }, { ...benchSettings, defer: true }); });
63.6
1,008
0.62334
dbd55d5d334642a1521d83aa9e1a8273feb0af7d
1,392
js
JavaScript
backend/external_api/oauth.js
ClassroomWebApplication/classroom
d8a8464713d4e6843d43e155bccd0958491719fe
[ "MIT" ]
2
2021-09-08T15:03:46.000Z
2021-09-24T21:21:50.000Z
backend/external_api/oauth.js
ClassroomWebApplication/classroom
d8a8464713d4e6843d43e155bccd0958491719fe
[ "MIT" ]
null
null
null
backend/external_api/oauth.js
ClassroomWebApplication/classroom
d8a8464713d4e6843d43e155bccd0958491719fe
[ "MIT" ]
1
2022-01-01T12:02:48.000Z
2022-01-01T12:02:48.000Z
const { google } = require("googleapis"); const dotenv = require("dotenv"); dotenv.config(); const googleConfig = { clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, redirect: "https://3248-2401-4900-5304-8e99-d17f-1836-91be-9b6d.ngrok.io" } /** * Create the google auth object which gives us access to talk to google's apis. */ function createConnection() { return new google.auth.OAuth2( googleConfig.clientId, googleConfig.clientSecret, googleConfig.redirect ); } /** * This scope tells google what information we want to request. */ const defaultScope = [ 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.email', ]; /** * Get a url which will open the google sign-in page and request access to the scope provided (such as calendar events). */ function getConnectionUrl(auth) { return auth.generateAuthUrl({ access_type: 'online', prompt: 'consent', // access type and approval prompt will force a new refresh token to be made each time signs in scope: defaultScope }); } /** * Create the google url to be sent to the client. */ function urlGoogle() { const auth = createConnection(); // this is from previous step const url = getConnectionUrl(auth); console.log(url); return url; } module.exports = { urlGoogle }
26.264151
122
0.68319
dbd5c295c87b5f9851e5fa2197d14a68f5a6ac86
345
js
JavaScript
src/reducers/index.js
markanator/foodtrucktrackr-frontend
94ba878bef9eaa71dfa1f4d89e4b481b139619da
[ "MIT" ]
null
null
null
src/reducers/index.js
markanator/foodtrucktrackr-frontend
94ba878bef9eaa71dfa1f4d89e4b481b139619da
[ "MIT" ]
null
null
null
src/reducers/index.js
markanator/foodtrucktrackr-frontend
94ba878bef9eaa71dfa1f4d89e4b481b139619da
[ "MIT" ]
2
2020-07-22T23:23:37.000Z
2020-08-03T02:21:21.000Z
import { combineReducers } from "redux"; // import all reducers import { truckReducer } from "./TruckReducer"; import { menuItemReducer } from "./MenuItemReducer"; import { dinerOperatorReducer } from "./dinerOperatorReducer.js"; export const rootReducer = combineReducers({ dinerOperatorReducer, truckReducer, menuItemReducer, });
28.75
65
0.744928
dbd601bf9dc30b83e9b3c6df2085666722a84d59
5,244
js
JavaScript
scorm_c2_plugin/edittime.js
Mimiste/c2-scorm-plugin
11b25bc3e3cf22a622643e84de55a11970682a6f
[ "MIT" ]
6
2016-10-06T08:13:02.000Z
2020-07-14T16:43:36.000Z
scorm_c2_plugin/edittime.js
wagstalos/c2-scorm-plugin
11b25bc3e3cf22a622643e84de55a11970682a6f
[ "MIT" ]
3
2016-10-25T22:26:41.000Z
2017-03-14T08:42:25.000Z
scorm_c2_plugin/edittime.js
wagstalos/c2-scorm-plugin
11b25bc3e3cf22a622643e84de55a11970682a6f
[ "MIT" ]
3
2019-03-12T17:30:50.000Z
2021-03-19T10:49:05.000Z
function GetPluginSettings() { return { "name": "Scorm C2", // as appears in 'insert object' dialog, can be changed as long as "id" stays the same "id": "scormc2", // this is used to identify this plugin and is saved to the project; never change it "version": "1.0", // (float in x.y format) Plugin version - C2 shows compatibility warnings based on this "description": "A Scorm 1.2 and 2004 Plugin for Construct 2", "author": "Loïc Martinez", "help url": "", "category": "General", // Prefer to re-use existing categories, but you can set anything here "type": "object", // either "world" (appears in layout and is drawn), else "object" "rotatable": false, // only used when "type" is "world". Enables an angle property on the object. "flags": 0 // uncomment lines to enable flags... | pf_singleglobal // exists project-wide, e.g. mouse, keyboard. "type" must be "object". // | pf_texture // object has a single texture (e.g. tiled background) // | pf_position_aces // compare/set/get x, y... // | pf_size_aces // compare/set/get width, height... // | pf_angle_aces // compare/set/get angle (recommended that "rotatable" be set to true) // | pf_appearance_aces // compare/set/get visible, opacity... // | pf_tiling // adjusts image editor features to better suit tiled images (e.g. tiled background) // | pf_animations // enables the animations system. See 'Sprite' for usage // | pf_zorder_aces // move to top, bottom, layer... // | pf_nosize // prevent resizing in the editor // | pf_effects // allow WebGL shader effects to be added // | pf_predraw // set for any plugin which draws and is not a sprite (i.e. does not simply draw // a single non-tiling image the size of the object) - required for effects to work properly }; }; //////////////////////////////////////// // Conditions AddCondition(0, cf_none, "Is scorm initialised", "Initialisation", "Is scorm initialised", "Check if the game is connected to the LMS", "isScormInitialised"); AddCondition(1, cf_none, "Is scorm on error", "Error handling", "Is scorm on error", "Check if an error occured", "isScormOnError"); //////////////////////////////////////// // Actions AddAction(0, af_none, "Initialise LMS", "Initialisation", "Initialise LMS", "Initialise connexion to the LMS", "initialiseLMS"); AddStringParam("Name", "Name of the value to set."); AddStringParam("Value", "The value"); AddAction(1, af_none, "Set LMS Value", "Usage", "Set LMS Value {0} - {1}", "Update a value on the LMS (refer on the Scorm 1.2 / 2004 documentation for possible values)", "setLMSValue"); AddAction(2, af_none, "Do LMS Commit", "Usage", "Do LMS Commit", "Commit the updated values on the LMS server side", "doLMSCommit"); AddAction(3, af_none, "Terminate", "Initialisation", "Terminate", "Close the connexion with the LMS", "doTerminate"); //////////////////////////////////////// // Expressions AddExpression(0, ef_return_string, "Initialisation", "Error handling", "getLastError", "Get the last Scorm error message"); AddExpression(1, ef_return_number, "Initialisation", "Error handling", "getLastErrorID", "Get the last Scorm error ID"); AddStringParam("Name", "Name of the value to get."); AddExpression(2, ef_return_string, "Initialisation", "Usage", "getLMSValue", "Get a value from the LMS (refer on the Scorm 1.2 / 2004 documentation for possible values)"); //////////////////////////////////////// ACESDone(); var property_list = [ ]; // Called by IDE when a new object type is to be created function CreateIDEObjectType() { return new IDEObjectType(); } // Class representing an object type in the IDE function IDEObjectType() { assert2(this instanceof arguments.callee, "Constructor called as a function"); } // Called by IDE when a new object instance of this type is to be created IDEObjectType.prototype.CreateInstance = function(instance) { return new IDEInstance(instance); } // Class representing an individual instance of an object in the IDE function IDEInstance(instance, type) { assert2(this instanceof arguments.callee, "Constructor called as a function"); // Save the constructor parameters this.instance = instance; this.type = type; // Set the default property values from the property table this.properties = {}; for (var i = 0; i < property_list.length; i++) this.properties[property_list[i].name] = property_list[i].initial_value; // Plugin-specific variables // this.myValue = 0... } // Called when inserted via Insert Object Dialog for the first time IDEInstance.prototype.OnInserted = function() { } // Called when double clicked in layout IDEInstance.prototype.OnDoubleClicked = function() { } // Called after a property has been changed in the properties bar IDEInstance.prototype.OnPropertyChanged = function(property_name) { } // For rendered objects to load fonts or textures IDEInstance.prototype.OnRendererInit = function(renderer) { } // Called to draw self in the editor if a layout object IDEInstance.prototype.Draw = function(renderer) { } // For rendered objects to release fonts or textures IDEInstance.prototype.OnRendererReleased = function(renderer) { }
41.619048
185
0.688215
dbd76a9a60036d77c63a1a45c348aab34c6a3fd9
504
js
JavaScript
packages/terra-functional-testing/tests/jest/commands/utils/getViewportSize.test.js
cerner/terra-toolk
d325a7a65b9ee064d7a056019308e1901b268dd8
[ "Apache-2.0" ]
31
2017-07-28T22:11:18.000Z
2022-01-28T17:38:27.000Z
packages/terra-functional-testing/tests/jest/commands/utils/getViewportSize.test.js
cerner/terra-toolk
d325a7a65b9ee064d7a056019308e1901b268dd8
[ "Apache-2.0" ]
423
2017-01-30T18:16:15.000Z
2022-03-21T15:17:00.000Z
packages/terra-functional-testing/tests/jest/commands/utils/getViewportSize.test.js
cerner/terra-toolk
d325a7a65b9ee064d7a056019308e1901b268dd8
[ "Apache-2.0" ]
45
2017-11-02T13:04:02.000Z
2021-12-16T09:50:15.000Z
const { getViewportSize } = require('../../../../src/commands/utils'); describe('getViewportSize', () => { it('should get the current viewport size', () => { const mockExecute = jest.fn().mockReturnValue({ screenWidth: 1000, screenHeight: 768 }); global.browser = { execute: mockExecute, }; const viewportSize = getViewportSize(); expect(mockExecute).toHaveBeenCalled(); expect(viewportSize.width).toEqual(1000); expect(viewportSize.height).toEqual(768); }); });
29.647059
92
0.654762
dbd7b0a2c59be0b1b3df24c6b8becfad989741e1
367
js
JavaScript
frontend/src/store/index.js
bayramlcm/vue-basic-panel
a43ea821eebe4800f58628ece5ff9b7a80dae0ff
[ "MIT" ]
2
2019-12-24T15:05:04.000Z
2020-01-20T15:35:37.000Z
frontend/src/store/index.js
bayramlcm/vue-basic-panel
a43ea821eebe4800f58628ece5ff9b7a80dae0ff
[ "MIT" ]
4
2021-03-10T02:22:12.000Z
2022-02-18T17:19:43.000Z
frontend/src/store/index.js
bayramlcm/vue-node-basic-panel
a43ea821eebe4800f58628ece5ff9b7a80dae0ff
[ "MIT" ]
null
null
null
import Vue from 'vue'; import Vuex from 'vuex'; import Server from './modules/server'; import UI from './modules/ui'; import Account from './modules/account'; import Notification from './modules/notification'; Vue.use(Vuex); export default new Vuex.Store({ modules: { server: Server, ui: UI, account: Account, notification: Notification }, });
19.315789
50
0.686649
dbd86b4c711ae76e915bd68f541609ab6c0e7d1c
1,311
js
JavaScript
JS Advanced/05. DOM Manipulation and Events - Lab/07. Shopping-Cart/solution.js
A-Manev/SoftUni-JavaScript
d1989e570f0b29112ab74f4921db3b79d19fff1d
[ "MIT" ]
1
2021-04-12T10:11:28.000Z
2021-04-12T10:11:28.000Z
JS Advanced/05. DOM Manipulation and Events - Lab/07. Shopping-Cart/solution.js
A-Manev/SoftUni-JavaScript
d1989e570f0b29112ab74f4921db3b79d19fff1d
[ "MIT" ]
null
null
null
JS Advanced/05. DOM Manipulation and Events - Lab/07. Shopping-Cart/solution.js
A-Manev/SoftUni-JavaScript
d1989e570f0b29112ab74f4921db3b79d19fff1d
[ "MIT" ]
5
2021-01-20T21:51:20.000Z
2022-03-05T16:12:35.000Z
function solve() { let allAddButtons = [...document.querySelectorAll('body > div > div > div.product-add > button')]; allAddButtons.forEach(b => { b.addEventListener('click', addToBasket); }); let textarea = document.querySelector('body > div > textarea'); let producuts = {}; function addToBasket(event) { const name = event.target.parentNode.parentNode.children[1].children[0].textContent; const price = Number(event.target.parentNode.parentNode.children[3].textContent); producuts[name] ? producuts[name] += price : producuts[name] = price; textarea.textContent += `Added ${name} for ${price.toFixed(2)} to the cart.\n`; } let checkoutButton = document.querySelector('body > div > button'); checkoutButton.addEventListener('click', checkout); function checkout() { let purchasedProducts = []; let totalPrice = 0; for (const [key, value] of Object.entries(producuts)) { purchasedProducts.push(key); totalPrice += value; } textarea.textContent += `You bought ${purchasedProducts.join(', ')} for ${totalPrice.toFixed(2)}.` allAddButtons.forEach(b => { b.removeEventListener('click', addToBasket); }); checkoutButton.removeEventListener('click', checkout); } }
30.488372
104
0.651411
dbd9d5e1b4c0283b5c4aab683a7339125f1001c9
1,191
js
JavaScript
components/WYSIWYG/components/Toolbar/toolbar.js
augusto-santos/webapp
2db4a3d4fbd0f4b5633a78368ec4f082186dcf1d
[ "MIT" ]
null
null
null
components/WYSIWYG/components/Toolbar/toolbar.js
augusto-santos/webapp
2db4a3d4fbd0f4b5633a78368ec4f082186dcf1d
[ "MIT" ]
null
null
null
components/WYSIWYG/components/Toolbar/toolbar.js
augusto-santos/webapp
2db4a3d4fbd0f4b5633a78368ec4f082186dcf1d
[ "MIT" ]
null
null
null
import React, { Component } from 'react' import s from './toolbar.css' class Toolbar extends Component{ render(){ return( <div className={`${s.wysiwyg_toolbar}`}> <div className={`${s.toolbar_section}`}> <button><i className={`material-icons`}>format_italic</i></button> <button><i className={`material-icons`}>format_bold</i></button> <button><i className={`material-icons`}>format_underlined</i></button> </div> <div className={`${s.toolbar_section}`}> <button><i className={`material-icons`}>format_align_left</i></button> <button><i className={`material-icons`}>format_align_center</i></button> <button><i className={`material-icons`}>format_align_right</i></button> <button><i className={`material-icons`}>format_align_justify</i></button> </div> <div className={`${s.toolbar_section}`}> <button><i className={`material-icons`}>insert_photo</i></button> </div> <div className={`${s.toolbar_section}`}> <button><i className={`material-icons`}>code</i></button> </div> </div> ) } } export default Toolbar
38.419355
83
0.604534
dbdab3c965f09d8105ee49f14dd2e5be08a04e72
1,078
js
JavaScript
lib/tunnel.js
Gerhut/koxy
a95eb1321ea89735f84778553865e38446aeb46e
[ "MIT" ]
1
2017-06-08T08:33:40.000Z
2017-06-08T08:33:40.000Z
lib/tunnel.js
Gerhut/koxy
a95eb1321ea89735f84778553865e38446aeb46e
[ "MIT" ]
18
2020-05-09T06:39:57.000Z
2020-11-24T00:46:15.000Z
lib/tunnel.js
Gerhut/kroxy
a95eb1321ea89735f84778553865e38446aeb46e
[ "MIT" ]
null
null
null
'use strict' const net = require('net') const debug = require('debug')('kroxy:tunnel') module.exports = () => (request, source, head) => { debug(`CONNECT ${request.url}`) function cleanup (error) { /* istanbul ignore if */ if (error instanceof Error) { debug('ERROR', error) } debug(`DISCONNECT ${request.url}`) if (source) { source.destroyed || source.destroy() source.removeAllListeners() source = null } if (target) { target.destroyed || target.destroy() target.removeAllListeners() target = null } } const urlParts = request.url.split(':') const hostname = urlParts[0] const port = +urlParts[1] let target = net.connect(port, hostname, () => { source.write(`HTTP/${request.httpVersion} 200 Connection Established\r\n\r\n`) target.write(head) source.pipe(target) target.pipe(source) }) source.on('close', cleanup) source.on('end', cleanup) source.on('error', cleanup) target.on('close', cleanup) target.on('end', cleanup) target.on('error', cleanup) }
24.5
82
0.624304
dbdbe854f8e1d47d60bfcb015c4cad21d79716a6
534
js
JavaScript
src/components/aggrid/date.js
ndom91/timeoff
21f2aa654cd220b16e6e75cca18f1469ef65cd13
[ "MIT" ]
6
2020-06-27T20:12:04.000Z
2021-04-26T03:14:59.000Z
src/components/aggrid/date.js
ndom91/timeoff
21f2aa654cd220b16e6e75cca18f1469ef65cd13
[ "MIT" ]
11
2020-06-17T11:36:08.000Z
2022-03-23T18:51:27.000Z
src/components/aggrid/date.js
ndom91/timeoff
21f2aa654cd220b16e6e75cca18f1469ef65cd13
[ "MIT" ]
null
null
null
import React, { Component } from 'react' export default class DateField extends Component { render () { const props = this.props const value = this.props.value let dateTime if (props.value && !isNaN(Date.parse(props.value))) { const dateAr = value.split('.') const day = dateAr[0] const month = dateAr[1] const year = dateAr[2] dateTime = `${day}.${month}.${year}` } else { dateTime = props.value } return ( <span> {dateTime} </span> ) } };
22.25
57
0.56367
dbdc3476da9b1af8f36349553a8f292914f14b50
897
js
JavaScript
assets/test/integrationTest/xcrpc/SqlServiceSpec.js
xcalar/xcalar-idl
69aa08fb42cde6c905b3aa2129c365c4c3e575f9
[ "Apache-2.0" ]
null
null
null
assets/test/integrationTest/xcrpc/SqlServiceSpec.js
xcalar/xcalar-idl
69aa08fb42cde6c905b3aa2129c365c4c3e575f9
[ "Apache-2.0" ]
null
null
null
assets/test/integrationTest/xcrpc/SqlServiceSpec.js
xcalar/xcalar-idl
69aa08fb42cde6c905b3aa2129c365c4c3e575f9
[ "Apache-2.0" ]
1
2021-01-31T20:52:28.000Z
2021-01-31T20:52:28.000Z
const expect = require('chai').expect; exports.testSuite = function(sqlService) { describe('SqlService Test', function () { it('Check service availability', async () => { let error = null; const invalidSql = 'MyInvalidSql'; try { await sqlService.executeSql({ sqlQuery: invalidSql, queryName: 'Whatever query name', userName: 'Whatever user name', userId: 12345678, sessionName: 'Whatever session name' }); } catch(e) { error = e; } // Expect api error, but not js error expect(error != null, 'Service call should fail').to.be.true; expect(error.error.indexOf(invalidSql), 'Service should be available').to.be.gt(-1); }); }); };
37.375
96
0.500557
dbdc9a658a8d4db5979f3c7c6deb7973a8bd0f57
4,946
js
JavaScript
zipdata/zip-076.js
danglephuc/jp-postalcode-lookup
eb58480bee152712edadd0f52ba5db0868a3a314
[ "MIT" ]
null
null
null
zipdata/zip-076.js
danglephuc/jp-postalcode-lookup
eb58480bee152712edadd0f52ba5db0868a3a314
[ "MIT" ]
null
null
null
zipdata/zip-076.js
danglephuc/jp-postalcode-lookup
eb58480bee152712edadd0f52ba5db0868a3a314
[ "MIT" ]
null
null
null
zipdata({ "0760000":[[1,1229,"富良野市","フラノシ",12290000,""," ",""]], "0760001":[[1,1229,"富良野市","フラノシ",12290009,"北扇山","キタオウギヤマ",""]], "0760002":[[1,1229,"富良野市","フラノシ",12290058,"南扇山","ミナミオウギヤマ",""]], "0760003":[[1,1229,"富良野市","フラノシ",12290040,"布部石綿","ヌノベイシワタ",""]], "0760004":[[1,1229,"富良野市","フラノシ",12290042,"布部市街地","ヌノベシガイチ",""]], "0760005":[[1,1229,"富良野市","フラノシ",12290041,"布部一","ヌノベイチ",""]], "0760006":[[1,1229,"富良野市","フラノシ",12290031,"西扇山","ニシオウギヤマ",""]], "0760007":[[1,1229,"富良野市","フラノシ",12290061,"南町","ミナミマチ",""]], "0760008":[[1,1229,"富良野市","フラノシ",12290002,"扇町","オウギマチ",""]], "0760011":[[1,1229,"富良野市","フラノシ",12290023,"末広町","スエヒロチョウ",""]], "0760012":[[1,1229,"富良野市","フラノシ",12290019,"下五区","シモゴク",""]], "0760013":[[1,1229,"富良野市","フラノシ",12290027,"中五区","ナカゴク",""]], "0760014":[[1,1229,"富良野市","フラノシ",12290006,"上五区","カミゴク",""]], "0760015":[[1,1229,"富良野市","フラノシ",12290007,"上御料","カミゴリョウ",""]], "0760016":[[1,1229,"富良野市","フラノシ",12290028,"中御料","ナカゴリョウ",""]], "0760017":[[1,1229,"富良野市","フラノシ",12290020,"下御料","シモゴリョウ",""]], "0760018":[[1,1229,"富良野市","フラノシ",12290099,"弥生町","ヤヨイチョウ",""]], "0760021":[[1,1229,"富良野市","フラノシ",12290056,"緑町","ミドリマチ",""]], "0760022":[[1,1229,"富良野市","フラノシ",12290102,"若葉町","ワカバチョウ",""]], "0760023":[[1,1229,"富良野市","フラノシ",12290015,"栄町","サカエマチ",""]], "0760024":[[1,1229,"富良野市","フラノシ",12290014,"幸町","サイワイチョウ",""]], "0760025":[[1,1229,"富良野市","フラノシ",12290052,"日の出町","ヒノデマチ",""]], "0760026":[[1,1229,"富良野市","フラノシ",12290001,"朝日町","アサヒマチ",""]], "0760027":[[1,1229,"富良野市","フラノシ",12290043,"花園町","ハナゾノチョウ",""]], "0760028":[[1,1229,"富良野市","フラノシ",12290033,"錦町","ニシキマチ",""]], "0760031":[[1,1229,"富良野市","フラノシ",12290063,"本町","モトマチ",""]], "0760032":[[1,1229,"富良野市","フラノシ",12290103,"若松町","ワカマツチョウ",""]], "0760033":[[1,1229,"富良野市","フラノシ",12290022,"新富町","シントミチョウ",""]], "0760034":[[1,1229,"富良野市","フラノシ",12290011,"北の峰町","キタノミネチョウ",""]], "0760035":[[1,1229,"富良野市","フラノシ",12290003,"学田三区","ガクデンサンク",""]], "0760036":[[1,1229,"富良野市","フラノシ",12290017,"島ノ下","シマノシタ",""]], "0760037":[[1,1229,"富良野市","フラノシ",12290038,"西町","ニシマチ",""]], "0760038":[[1,1229,"富良野市","フラノシ",12290005,"桂木町","カツラギチョウ",""]], "0760039":[[1,1229,"富良野市","フラノシ",12290016,"信濃沢","シナノサワ",""]], "0760041":[[1,1229,"富良野市","フラノシ",12290047,"東鳥沼","ヒガシトリヌマ",""]], "0760042":[[1,1229,"富良野市","フラノシ",12290036,"西鳥沼","ニシトリヌマ",""]], "0760043":[[1,1229,"富良野市","フラノシ",12290059,"南大沼","ミナミオオヌマ",""]], "0760044":[[1,1229,"富良野市","フラノシ",12290010,"北大沼","キタオオヌマ",""]], "0760045":[[1,1229,"富良野市","フラノシ",12290045,"東学田二区","ヒガシガクデンニク",""]], "0760046":[[1,1229,"富良野市","フラノシ",12290054,"北斗町","ホクトチョウ",""]], "0760047":[[1,1229,"富良野市","フラノシ",12290032,"西学田二区","ニシガクデンニク",""]], "0760048":[[1,1229,"富良野市","フラノシ",12290018,"清水山","シミズヤマ",""]], "0760050":[[1,1229,"富良野市","フラノシ",12290104,"東雲町","シノノメチョウ",""]], "0760051":[[1,1229,"富良野市","フラノシ",12290044,"東麻町","ヒガシアサマチ",""]], "0760052":[[1,1229,"富良野市","フラノシ",12290057,"南麻町","ミナミアサマチ",""]], "0760053":[[1,1229,"富良野市","フラノシ",12290049,"東町","ヒガシマチ",""]], "0760054":[[1,1229,"富良野市","フラノシ",12290004,"春日町","カスガチョウ",""]], "0760055":[[1,1229,"富良野市","フラノシ",12290030,"西麻町","ニシアサマチ",""]], "0760056":[[1,1229,"富良野市","フラノシ",12290055,"瑞穂町","ミズホチョウ",""]], "0760057":[[1,1229,"富良野市","フラノシ",12290024,"住吉町","スミヨシチョウ",""]], "0760058":[[1,1229,"富良野市","フラノシ",12290021,"新光町","シンコウチョウ",""]], "0760059":[[1,1229,"富良野市","フラノシ",12290008,"北麻町","キタアサマチ",""]], "0760081":[[1,1216,"芦別市","アシベツシ",12160004,"泉","イズミ",""]], "0760161":[[1,1229,"富良野市","フラノシ",12290101,"麓郷市街地","ロクゴウシガイチ",""]], "0760162":[[1,1229,"富良野市","フラノシ",12290051,"東麓郷","ヒガシロクゴウ",""]], "0760163":[[1,1229,"富良野市","フラノシ",12290039,"西麓郷","ニシロクゴウ",""]], "0760164":[[1,1229,"富良野市","フラノシ",12290062,"南麓郷","ミナミロクゴウ",""]], "0760165":[[1,1229,"富良野市","フラノシ",12290013,"北麓郷","キタロクゴウ",""]], "0760171":[[1,1229,"富良野市","フラノシ",12290053,"布礼別市街地","フレベツシガイチ",""]], "0760172":[[1,1229,"富良野市","フラノシ",12290048,"東布礼別","ヒガシフレベツ",""]], "0760173":[[1,1229,"富良野市","フラノシ",12290037,"西布礼別","ニシフレベツ",""]], "0760174":[[1,1229,"富良野市","フラノシ",12290060,"南布礼別","ミナミフレベツ",""]], "0760175":[[1,1229,"富良野市","フラノシ",12290012,"北布礼別","キタフレベツ",""]], "0760176":[[1,1229,"富良野市","フラノシ",12290029,"中布礼別","ナカフレベツ",""]], "0760181":[[1,1229,"富良野市","フラノシ",12290046,"東富丘","ヒガシトミオカ",""]], "0760182":[[1,1229,"富良野市","フラノシ",12290035,"西富丘","ニシトミオカ",""]], "0760183":[[1,1229,"富良野市","フラノシ",12290026,"富丘更生","トミオカコウセイ",""]], "0760184":[[1,1229,"富良野市","フラノシ",12290064,"八幡丘","ヤハタオカ",""]], "0760201":[[1,1229,"富良野市","フラノシ",12290034,"西達布","ニシタップ",""]], "0760202":[[1,1229,"富良野市","フラノシ",12290050,"東山","ヒガシヤマ",""]], "0760203":[[1,1229,"富良野市","フラノシ",12290100,"老節布","ロウセップ",""]], "0760204":[[1,1229,"富良野市","フラノシ",12290025,"平沢","タイラザワ",""]], "0768511":[[1,1229,"富良野市","フラノシ",12290028,"中御料","ナカゴリョウ",""]], "0768555":[[1,1229,"富良野市","フラノシ",12290099,"弥生町","ヤヨイチョウ",""]], "0768609":[[1,1229,"富良野市","フラノシ",12290056,"緑町","ミドリマチ",""]], "0768666":[[1,1229,"富良野市","フラノシ",12290001,"朝日町","アサヒマチ",""]], "0768765":[[1,1229,"富良野市","フラノシ",12290024,"住吉町","スミヨシチョウ",""]] })
61.825
68
0.578447
dbdd890fab0a4b036d1f7a3e050db60ebcee6ba3
192
js
JavaScript
excel-snippets/addChartTitle.js
nhun206/office-js-snippet-explorer
d481baaadd72f1ec9f3bd1cd6e909f812861190a
[ "MIT" ]
51
2015-09-25T22:27:07.000Z
2021-08-30T21:19:49.000Z
excel-snippets/addChartTitle.js
rashidkhan46211/VSTO
de7ed69e36b8c5f9c60e5238163b4ecffbbe4805
[ "MIT" ]
11
2015-10-03T06:06:50.000Z
2017-06-27T23:03:41.000Z
excel-snippets/addChartTitle.js
rashidkhan46211/VSTO
de7ed69e36b8c5f9c60e5238163b4ecffbbe4805
[ "MIT" ]
24
2015-11-04T01:55:45.000Z
2021-12-22T03:21:25.000Z
Excel.run(function (ctx) { ctx.workbook.worksheets.getActiveWorksheet().charts.getItemAt(0).title.text = "New Title"; return ctx.sync(); }).catch(function (error) { console.log(error); });
27.428571
91
0.713542
dbdded53c0bd732e1a490193011b812e0e4ee7b6
40,063
js
JavaScript
node_modules/sucrase/dist/esm/parser/plugins/typescript.js
aquaigni/455-project
75821f6d388b73d74192496afabe3c88f95333ef
[ "Unlicense", "MIT" ]
null
null
null
node_modules/sucrase/dist/esm/parser/plugins/typescript.js
aquaigni/455-project
75821f6d388b73d74192496afabe3c88f95333ef
[ "Unlicense", "MIT" ]
null
null
null
node_modules/sucrase/dist/esm/parser/plugins/typescript.js
aquaigni/455-project
75821f6d388b73d74192496afabe3c88f95333ef
[ "Unlicense", "MIT" ]
null
null
null
import { eat, lookaheadType, lookaheadTypeAndKeyword, match, next, nextTemplateToken, popTypeContext, pushTypeContext, } from "../tokenizer/index"; import {ContextualKeyword} from "../tokenizer/keywords"; import {TokenType, TokenType as tt} from "../tokenizer/types"; import {isJSXEnabled, state} from "../traverser/base"; import { atPossibleAsync, baseParseMaybeAssign, baseParseSubscript, parseCallExpressionArguments, parseExprAtom, parseExpression, parseFunctionBody, parseIdentifier, parseLiteral, parseMaybeAssign, parseMaybeUnary, parsePropertyName, parseTemplate, } from "../traverser/expression"; import {parseBindingIdentifier, parseBindingList, parseImportedIdentifier} from "../traverser/lval"; import { baseParseMaybeDecoratorArguments, parseBlockBody, parseClass, parseFunction, parseFunctionParams, parseStatement, parseVarStatement, } from "../traverser/statement"; import { canInsertSemicolon, eatContextual, expect, expectContextual, hasPrecedingLineBreak, isContextual, isLineTerminator, isLookaheadContextual, semicolon, unexpected, } from "../traverser/util"; import {nextJSXTagToken} from "./jsx"; function tsIsIdentifier() { // TODO: actually a bit more complex in TypeScript, but shouldn't matter. // See https://github.com/Microsoft/TypeScript/issues/15008 return match(tt.name); } function isLiteralPropertyName() { return ( match(tt.name) || Boolean(state.type & TokenType.IS_KEYWORD) || match(tt.string) || match(tt.num) || match(tt.bigint) || match(tt.decimal) ); } function tsNextTokenCanFollowModifier() { // Note: TypeScript's implementation is much more complicated because // more things are considered modifiers there. // This implementation only handles modifiers not handled by babylon itself. And "static". // TODO: Would be nice to avoid lookahead. Want a hasLineBreakUpNext() method... const snapshot = state.snapshot(); next(); const canFollowModifier = (match(tt.bracketL) || match(tt.braceL) || match(tt.star) || match(tt.ellipsis) || match(tt.hash) || isLiteralPropertyName()) && !hasPrecedingLineBreak(); if (canFollowModifier) { return true; } else { state.restoreFromSnapshot(snapshot); return false; } } export function tsParseModifiers(allowedModifiers) { while (true) { const modifier = tsParseModifier(allowedModifiers); if (modifier === null) { break; } } } /** Parses a modifier matching one the given modifier names. */ export function tsParseModifier( allowedModifiers, ) { if (!match(tt.name)) { return null; } const modifier = state.contextualKeyword; if (allowedModifiers.indexOf(modifier) !== -1 && tsNextTokenCanFollowModifier()) { switch (modifier) { case ContextualKeyword._readonly: state.tokens[state.tokens.length - 1].type = tt._readonly; break; case ContextualKeyword._abstract: state.tokens[state.tokens.length - 1].type = tt._abstract; break; case ContextualKeyword._static: state.tokens[state.tokens.length - 1].type = tt._static; break; case ContextualKeyword._public: state.tokens[state.tokens.length - 1].type = tt._public; break; case ContextualKeyword._private: state.tokens[state.tokens.length - 1].type = tt._private; break; case ContextualKeyword._protected: state.tokens[state.tokens.length - 1].type = tt._protected; break; case ContextualKeyword._override: state.tokens[state.tokens.length - 1].type = tt._override; break; case ContextualKeyword._declare: state.tokens[state.tokens.length - 1].type = tt._declare; break; default: break; } return modifier; } return null; } function tsParseEntityName() { parseIdentifier(); while (eat(tt.dot)) { parseIdentifier(); } } function tsParseTypeReference() { tsParseEntityName(); if (!hasPrecedingLineBreak() && match(tt.lessThan)) { tsParseTypeArguments(); } } function tsParseThisTypePredicate() { next(); tsParseTypeAnnotation(); } function tsParseThisTypeNode() { next(); } function tsParseTypeQuery() { expect(tt._typeof); if (match(tt._import)) { tsParseImportType(); } else { tsParseEntityName(); } } function tsParseImportType() { expect(tt._import); expect(tt.parenL); expect(tt.string); expect(tt.parenR); if (eat(tt.dot)) { tsParseEntityName(); } if (match(tt.lessThan)) { tsParseTypeArguments(); } } function tsParseTypeParameter() { parseIdentifier(); if (eat(tt._extends)) { tsParseType(); } if (eat(tt.eq)) { tsParseType(); } } export function tsTryParseTypeParameters() { if (match(tt.lessThan)) { tsParseTypeParameters(); } } function tsParseTypeParameters() { const oldIsType = pushTypeContext(0); if (match(tt.lessThan) || match(tt.typeParameterStart)) { next(); } else { unexpected(); } while (!eat(tt.greaterThan) && !state.error) { tsParseTypeParameter(); eat(tt.comma); } popTypeContext(oldIsType); } // Note: In TypeScript implementation we must provide `yieldContext` and `awaitContext`, // but here it's always false, because this is only used for types. function tsFillSignature(returnToken) { // Arrow fns *must* have return token (`=>`). Normal functions can omit it. const returnTokenRequired = returnToken === tt.arrow; tsTryParseTypeParameters(); expect(tt.parenL); // Create a scope even though we're doing type parsing so we don't accidentally // treat params as top-level bindings. state.scopeDepth++; tsParseBindingListForSignature(false /* isBlockScope */); state.scopeDepth--; if (returnTokenRequired) { tsParseTypeOrTypePredicateAnnotation(returnToken); } else if (match(returnToken)) { tsParseTypeOrTypePredicateAnnotation(returnToken); } } function tsParseBindingListForSignature(isBlockScope) { parseBindingList(tt.parenR, isBlockScope); } function tsParseTypeMemberSemicolon() { if (!eat(tt.comma)) { semicolon(); } } function tsParseSignatureMember() { tsFillSignature(tt.colon); tsParseTypeMemberSemicolon(); } function tsIsUnambiguouslyIndexSignature() { const snapshot = state.snapshot(); next(); // Skip '{' const isIndexSignature = eat(tt.name) && match(tt.colon); state.restoreFromSnapshot(snapshot); return isIndexSignature; } function tsTryParseIndexSignature() { if (!(match(tt.bracketL) && tsIsUnambiguouslyIndexSignature())) { return false; } const oldIsType = pushTypeContext(0); expect(tt.bracketL); parseIdentifier(); tsParseTypeAnnotation(); expect(tt.bracketR); tsTryParseTypeAnnotation(); tsParseTypeMemberSemicolon(); popTypeContext(oldIsType); return true; } function tsParsePropertyOrMethodSignature(isReadonly) { eat(tt.question); if (!isReadonly && (match(tt.parenL) || match(tt.lessThan))) { tsFillSignature(tt.colon); tsParseTypeMemberSemicolon(); } else { tsTryParseTypeAnnotation(); tsParseTypeMemberSemicolon(); } } function tsParseTypeMember() { if (match(tt.parenL) || match(tt.lessThan)) { // call signature tsParseSignatureMember(); return; } if (match(tt._new)) { next(); if (match(tt.parenL) || match(tt.lessThan)) { // constructor signature tsParseSignatureMember(); } else { tsParsePropertyOrMethodSignature(false); } return; } const readonly = !!tsParseModifier([ContextualKeyword._readonly]); const found = tsTryParseIndexSignature(); if (found) { return; } if ( (isContextual(ContextualKeyword._get) || isContextual(ContextualKeyword._set)) && tsNextTokenCanFollowModifier() ) { // This is a getter/setter on a type. The tsNextTokenCanFollowModifier // function already called next() for us, so continue parsing the name. } parsePropertyName(-1 /* Types don't need context IDs. */); tsParsePropertyOrMethodSignature(readonly); } function tsParseTypeLiteral() { tsParseObjectTypeMembers(); } function tsParseObjectTypeMembers() { expect(tt.braceL); while (!eat(tt.braceR) && !state.error) { tsParseTypeMember(); } } function tsLookaheadIsStartOfMappedType() { const snapshot = state.snapshot(); const isStartOfMappedType = tsIsStartOfMappedType(); state.restoreFromSnapshot(snapshot); return isStartOfMappedType; } function tsIsStartOfMappedType() { next(); if (eat(tt.plus) || eat(tt.minus)) { return isContextual(ContextualKeyword._readonly); } if (isContextual(ContextualKeyword._readonly)) { next(); } if (!match(tt.bracketL)) { return false; } next(); if (!tsIsIdentifier()) { return false; } next(); return match(tt._in); } function tsParseMappedTypeParameter() { parseIdentifier(); expect(tt._in); tsParseType(); } function tsParseMappedType() { expect(tt.braceL); if (match(tt.plus) || match(tt.minus)) { next(); expectContextual(ContextualKeyword._readonly); } else { eatContextual(ContextualKeyword._readonly); } expect(tt.bracketL); tsParseMappedTypeParameter(); if (eatContextual(ContextualKeyword._as)) { tsParseType(); } expect(tt.bracketR); if (match(tt.plus) || match(tt.minus)) { next(); expect(tt.question); } else { eat(tt.question); } tsTryParseType(); semicolon(); expect(tt.braceR); } function tsParseTupleType() { expect(tt.bracketL); while (!eat(tt.bracketR) && !state.error) { // Do not validate presence of either none or only labeled elements tsParseTupleElementType(); eat(tt.comma); } } function tsParseTupleElementType() { // parses `...TsType[]` if (eat(tt.ellipsis)) { tsParseType(); } else { // parses `TsType?` tsParseType(); eat(tt.question); } // The type we parsed above was actually a label if (eat(tt.colon)) { // Labeled tuple types must affix the label with `...` or `?`, so no need to handle those here tsParseType(); } } function tsParseParenthesizedType() { expect(tt.parenL); tsParseType(); expect(tt.parenR); } function tsParseTemplateLiteralType() { // Finish `, read quasi nextTemplateToken(); // Finish quasi, read ${ nextTemplateToken(); while (!match(tt.backQuote) && !state.error) { expect(tt.dollarBraceL); tsParseType(); // Finish }, read quasi nextTemplateToken(); // Finish quasi, read either ${ or ` nextTemplateToken(); } next(); } var FunctionType; (function (FunctionType) { const TSFunctionType = 0; FunctionType[FunctionType["TSFunctionType"] = TSFunctionType] = "TSFunctionType"; const TSConstructorType = TSFunctionType + 1; FunctionType[FunctionType["TSConstructorType"] = TSConstructorType] = "TSConstructorType"; const TSAbstractConstructorType = TSConstructorType + 1; FunctionType[FunctionType["TSAbstractConstructorType"] = TSAbstractConstructorType] = "TSAbstractConstructorType"; })(FunctionType || (FunctionType = {})); function tsParseFunctionOrConstructorType(type) { if (type === FunctionType.TSAbstractConstructorType) { expectContextual(ContextualKeyword._abstract); } if (type === FunctionType.TSConstructorType || type === FunctionType.TSAbstractConstructorType) { expect(tt._new); } tsFillSignature(tt.arrow); } function tsParseNonArrayType() { switch (state.type) { case tt.name: tsParseTypeReference(); return; case tt._void: case tt._null: next(); return; case tt.string: case tt.num: case tt.bigint: case tt.decimal: case tt._true: case tt._false: parseLiteral(); return; case tt.minus: next(); parseLiteral(); return; case tt._this: { tsParseThisTypeNode(); if (isContextual(ContextualKeyword._is) && !hasPrecedingLineBreak()) { tsParseThisTypePredicate(); } return; } case tt._typeof: tsParseTypeQuery(); return; case tt._import: tsParseImportType(); return; case tt.braceL: if (tsLookaheadIsStartOfMappedType()) { tsParseMappedType(); } else { tsParseTypeLiteral(); } return; case tt.bracketL: tsParseTupleType(); return; case tt.parenL: tsParseParenthesizedType(); return; case tt.backQuote: tsParseTemplateLiteralType(); return; default: if (state.type & TokenType.IS_KEYWORD) { next(); state.tokens[state.tokens.length - 1].type = tt.name; return; } break; } unexpected(); } function tsParseArrayTypeOrHigher() { tsParseNonArrayType(); while (!hasPrecedingLineBreak() && eat(tt.bracketL)) { if (!eat(tt.bracketR)) { // If we hit ] immediately, this is an array type, otherwise it's an indexed access type. tsParseType(); expect(tt.bracketR); } } } function tsParseInferType() { expectContextual(ContextualKeyword._infer); parseIdentifier(); } function tsParseTypeOperatorOrHigher() { if ( isContextual(ContextualKeyword._keyof) || isContextual(ContextualKeyword._unique) || isContextual(ContextualKeyword._readonly) ) { next(); tsParseTypeOperatorOrHigher(); } else if (isContextual(ContextualKeyword._infer)) { tsParseInferType(); } else { tsParseArrayTypeOrHigher(); } } function tsParseIntersectionTypeOrHigher() { eat(tt.bitwiseAND); tsParseTypeOperatorOrHigher(); if (match(tt.bitwiseAND)) { while (eat(tt.bitwiseAND)) { tsParseTypeOperatorOrHigher(); } } } function tsParseUnionTypeOrHigher() { eat(tt.bitwiseOR); tsParseIntersectionTypeOrHigher(); if (match(tt.bitwiseOR)) { while (eat(tt.bitwiseOR)) { tsParseIntersectionTypeOrHigher(); } } } function tsIsStartOfFunctionType() { if (match(tt.lessThan)) { return true; } return match(tt.parenL) && tsLookaheadIsUnambiguouslyStartOfFunctionType(); } function tsSkipParameterStart() { if (match(tt.name) || match(tt._this)) { next(); return true; } // If this is a possible array/object destructure, walk to the matching bracket/brace. // The next token after will tell us definitively whether this is a function param. if (match(tt.braceL) || match(tt.bracketL)) { let depth = 1; next(); while (depth > 0 && !state.error) { if (match(tt.braceL) || match(tt.bracketL)) { depth++; } else if (match(tt.braceR) || match(tt.bracketR)) { depth--; } next(); } return true; } return false; } function tsLookaheadIsUnambiguouslyStartOfFunctionType() { const snapshot = state.snapshot(); const isUnambiguouslyStartOfFunctionType = tsIsUnambiguouslyStartOfFunctionType(); state.restoreFromSnapshot(snapshot); return isUnambiguouslyStartOfFunctionType; } function tsIsUnambiguouslyStartOfFunctionType() { next(); if (match(tt.parenR) || match(tt.ellipsis)) { // ( ) // ( ... return true; } if (tsSkipParameterStart()) { if (match(tt.colon) || match(tt.comma) || match(tt.question) || match(tt.eq)) { // ( xxx : // ( xxx , // ( xxx ? // ( xxx = return true; } if (match(tt.parenR)) { next(); if (match(tt.arrow)) { // ( xxx ) => return true; } } } return false; } function tsParseTypeOrTypePredicateAnnotation(returnToken) { const oldIsType = pushTypeContext(0); expect(returnToken); const finishedReturn = tsParseTypePredicateOrAssertsPrefix(); if (!finishedReturn) { tsParseType(); } popTypeContext(oldIsType); } function tsTryParseTypeOrTypePredicateAnnotation() { if (match(tt.colon)) { tsParseTypeOrTypePredicateAnnotation(tt.colon); } } export function tsTryParseTypeAnnotation() { if (match(tt.colon)) { tsParseTypeAnnotation(); } } function tsTryParseType() { if (eat(tt.colon)) { tsParseType(); } } /** * Detect a few special return syntax cases: `x is T`, `asserts x`, `asserts x is T`, * `asserts this is T`. * * Returns true if we parsed the return type, false if there's still a type to be parsed. */ function tsParseTypePredicateOrAssertsPrefix() { const snapshot = state.snapshot(); if (isContextual(ContextualKeyword._asserts) && !hasPrecedingLineBreak()) { // Normally this is `asserts x is T`, but at this point, it might be `asserts is T` (a user- // defined type guard on the `asserts` variable) or just a type called `asserts`. next(); if (eatContextual(ContextualKeyword._is)) { // If we see `asserts is`, then this must be of the form `asserts is T`, since // `asserts is is T` isn't valid. tsParseType(); return true; } else if (tsIsIdentifier() || match(tt._this)) { next(); if (eatContextual(ContextualKeyword._is)) { // If we see `is`, then this is `asserts x is T`. Otherwise, it's `asserts x`. tsParseType(); } return true; } else { // Regular type, so bail out and start type parsing from scratch. state.restoreFromSnapshot(snapshot); return false; } } else if (tsIsIdentifier() || match(tt._this)) { // This is a regular identifier, which may or may not have "is" after it. next(); if (isContextual(ContextualKeyword._is) && !hasPrecedingLineBreak()) { next(); tsParseType(); return true; } else { // Regular type, so bail out and start type parsing from scratch. state.restoreFromSnapshot(snapshot); return false; } } return false; } export function tsParseTypeAnnotation() { const oldIsType = pushTypeContext(0); expect(tt.colon); tsParseType(); popTypeContext(oldIsType); } export function tsParseType() { tsParseNonConditionalType(); if (hasPrecedingLineBreak() || !eat(tt._extends)) { return; } // extends type tsParseNonConditionalType(); expect(tt.question); // true type tsParseType(); expect(tt.colon); // false type tsParseType(); } function isAbstractConstructorSignature() { return isContextual(ContextualKeyword._abstract) && lookaheadType() === tt._new; } export function tsParseNonConditionalType() { if (tsIsStartOfFunctionType()) { tsParseFunctionOrConstructorType(FunctionType.TSFunctionType); return; } if (match(tt._new)) { // As in `new () => Date` tsParseFunctionOrConstructorType(FunctionType.TSConstructorType); return; } else if (isAbstractConstructorSignature()) { // As in `abstract new () => Date` tsParseFunctionOrConstructorType(FunctionType.TSAbstractConstructorType); return; } tsParseUnionTypeOrHigher(); } export function tsParseTypeAssertion() { const oldIsType = pushTypeContext(1); tsParseType(); expect(tt.greaterThan); popTypeContext(oldIsType); parseMaybeUnary(); } export function tsTryParseJSXTypeArgument() { if (eat(tt.jsxTagStart)) { state.tokens[state.tokens.length - 1].type = tt.typeParameterStart; const oldIsType = pushTypeContext(1); while (!match(tt.greaterThan) && !state.error) { tsParseType(); eat(tt.comma); } // Process >, but the one after needs to be parsed JSX-style. nextJSXTagToken(); popTypeContext(oldIsType); } } function tsParseHeritageClause() { while (!match(tt.braceL) && !state.error) { tsParseExpressionWithTypeArguments(); eat(tt.comma); } } function tsParseExpressionWithTypeArguments() { // Note: TS uses parseLeftHandSideExpressionOrHigher, // then has grammar errors later if it's not an EntityName. tsParseEntityName(); if (match(tt.lessThan)) { tsParseTypeArguments(); } } function tsParseInterfaceDeclaration() { parseBindingIdentifier(false); tsTryParseTypeParameters(); if (eat(tt._extends)) { tsParseHeritageClause(); } tsParseObjectTypeMembers(); } function tsParseTypeAliasDeclaration() { parseBindingIdentifier(false); tsTryParseTypeParameters(); expect(tt.eq); tsParseType(); semicolon(); } function tsParseEnumMember() { // Computed property names are grammar errors in an enum, so accept just string literal or identifier. if (match(tt.string)) { parseLiteral(); } else { parseIdentifier(); } if (eat(tt.eq)) { const eqIndex = state.tokens.length - 1; parseMaybeAssign(); state.tokens[eqIndex].rhsEndIndex = state.tokens.length; } } function tsParseEnumDeclaration() { parseBindingIdentifier(false); expect(tt.braceL); while (!eat(tt.braceR) && !state.error) { tsParseEnumMember(); eat(tt.comma); } } function tsParseModuleBlock() { expect(tt.braceL); parseBlockBody(/* end */ tt.braceR); } function tsParseModuleOrNamespaceDeclaration() { parseBindingIdentifier(false); if (eat(tt.dot)) { tsParseModuleOrNamespaceDeclaration(); } else { tsParseModuleBlock(); } } function tsParseAmbientExternalModuleDeclaration() { if (isContextual(ContextualKeyword._global)) { parseIdentifier(); } else if (match(tt.string)) { parseExprAtom(); } else { unexpected(); } if (match(tt.braceL)) { tsParseModuleBlock(); } else { semicolon(); } } export function tsParseImportEqualsDeclaration() { parseImportedIdentifier(); expect(tt.eq); tsParseModuleReference(); semicolon(); } function tsIsExternalModuleReference() { return isContextual(ContextualKeyword._require) && lookaheadType() === tt.parenL; } function tsParseModuleReference() { if (tsIsExternalModuleReference()) { tsParseExternalModuleReference(); } else { tsParseEntityName(); } } function tsParseExternalModuleReference() { expectContextual(ContextualKeyword._require); expect(tt.parenL); if (!match(tt.string)) { unexpected(); } parseLiteral(); expect(tt.parenR); } // Utilities // Returns true if a statement matched. function tsTryParseDeclare() { if (isLineTerminator()) { return false; } switch (state.type) { case tt._function: { const oldIsType = pushTypeContext(1); next(); // We don't need to precisely get the function start here, since it's only used to mark // the function as a type if it's bodiless, and it's already a type here. const functionStart = state.start; parseFunction(functionStart, /* isStatement */ true); popTypeContext(oldIsType); return true; } case tt._class: { const oldIsType = pushTypeContext(1); parseClass(/* isStatement */ true, /* optionalId */ false); popTypeContext(oldIsType); return true; } case tt._const: { if (match(tt._const) && isLookaheadContextual(ContextualKeyword._enum)) { const oldIsType = pushTypeContext(1); // `const enum = 0;` not allowed because "enum" is a strict mode reserved word. expect(tt._const); expectContextual(ContextualKeyword._enum); state.tokens[state.tokens.length - 1].type = tt._enum; tsParseEnumDeclaration(); popTypeContext(oldIsType); return true; } } // falls through case tt._var: case tt._let: { const oldIsType = pushTypeContext(1); parseVarStatement(state.type); popTypeContext(oldIsType); return true; } case tt.name: { const oldIsType = pushTypeContext(1); const contextualKeyword = state.contextualKeyword; let matched = false; if (contextualKeyword === ContextualKeyword._global) { tsParseAmbientExternalModuleDeclaration(); matched = true; } else { matched = tsParseDeclaration(contextualKeyword, /* isBeforeToken */ true); } popTypeContext(oldIsType); return matched; } default: return false; } } // Note: this won't be called unless the keyword is allowed in `shouldParseExportDeclaration`. // Returns true if it matched a declaration. function tsTryParseExportDeclaration() { return tsParseDeclaration(state.contextualKeyword, /* isBeforeToken */ true); } // Returns true if it matched a statement. function tsParseExpressionStatement(contextualKeyword) { switch (contextualKeyword) { case ContextualKeyword._declare: { const declareTokenIndex = state.tokens.length - 1; const matched = tsTryParseDeclare(); if (matched) { state.tokens[declareTokenIndex].type = tt._declare; return true; } break; } case ContextualKeyword._global: // `global { }` (with no `declare`) may appear inside an ambient module declaration. // Would like to use tsParseAmbientExternalModuleDeclaration here, but already ran past "global". if (match(tt.braceL)) { tsParseModuleBlock(); return true; } break; default: return tsParseDeclaration(contextualKeyword, /* isBeforeToken */ false); } return false; } /** * Common code for parsing a declaration. * * isBeforeToken indicates that the current parser state is at the contextual * keyword (and that it is not yet emitted) rather than reading the token after * it. When isBeforeToken is true, we may be preceded by an `export` token and * should include that token in a type context we create, e.g. to handle * `export interface` or `export type`. (This is a bit of a hack and should be * cleaned up at some point.) * * Returns true if it matched a declaration. */ function tsParseDeclaration(contextualKeyword, isBeforeToken) { switch (contextualKeyword) { case ContextualKeyword._abstract: if (tsCheckLineTerminator(isBeforeToken) && match(tt._class)) { state.tokens[state.tokens.length - 1].type = tt._abstract; parseClass(/* isStatement */ true, /* optionalId */ false); return true; } break; case ContextualKeyword._enum: if (tsCheckLineTerminator(isBeforeToken) && match(tt.name)) { state.tokens[state.tokens.length - 1].type = tt._enum; tsParseEnumDeclaration(); return true; } break; case ContextualKeyword._interface: if (tsCheckLineTerminator(isBeforeToken) && match(tt.name)) { // `next` is true in "export" and "declare" contexts, so we want to remove that token // as well. const oldIsType = pushTypeContext(isBeforeToken ? 2 : 1); tsParseInterfaceDeclaration(); popTypeContext(oldIsType); return true; } break; case ContextualKeyword._module: if (tsCheckLineTerminator(isBeforeToken)) { if (match(tt.string)) { const oldIsType = pushTypeContext(isBeforeToken ? 2 : 1); tsParseAmbientExternalModuleDeclaration(); popTypeContext(oldIsType); return true; } else if (match(tt.name)) { const oldIsType = pushTypeContext(isBeforeToken ? 2 : 1); tsParseModuleOrNamespaceDeclaration(); popTypeContext(oldIsType); return true; } } break; case ContextualKeyword._namespace: if (tsCheckLineTerminator(isBeforeToken) && match(tt.name)) { const oldIsType = pushTypeContext(isBeforeToken ? 2 : 1); tsParseModuleOrNamespaceDeclaration(); popTypeContext(oldIsType); return true; } break; case ContextualKeyword._type: if (tsCheckLineTerminator(isBeforeToken) && match(tt.name)) { const oldIsType = pushTypeContext(isBeforeToken ? 2 : 1); tsParseTypeAliasDeclaration(); popTypeContext(oldIsType); return true; } break; default: break; } return false; } function tsCheckLineTerminator(isBeforeToken) { if (isBeforeToken) { // Babel checks hasFollowingLineBreak here and returns false, but this // doesn't actually come up, e.g. `export interface` can never be on its own // line in valid code. next(); return true; } else { return !isLineTerminator(); } } // Returns true if there was a generic async arrow function. function tsTryParseGenericAsyncArrowFunction() { const snapshot = state.snapshot(); tsParseTypeParameters(); parseFunctionParams(); tsTryParseTypeOrTypePredicateAnnotation(); expect(tt.arrow); if (state.error) { state.restoreFromSnapshot(snapshot); return false; } parseFunctionBody(true); return true; } function tsParseTypeArguments() { const oldIsType = pushTypeContext(0); expect(tt.lessThan); while (!eat(tt.greaterThan) && !state.error) { tsParseType(); eat(tt.comma); } popTypeContext(oldIsType); } export function tsIsDeclarationStart() { if (match(tt.name)) { switch (state.contextualKeyword) { case ContextualKeyword._abstract: case ContextualKeyword._declare: case ContextualKeyword._enum: case ContextualKeyword._interface: case ContextualKeyword._module: case ContextualKeyword._namespace: case ContextualKeyword._type: return true; default: break; } } return false; } // ====================================================== // OVERRIDES // ====================================================== export function tsParseFunctionBodyAndFinish(functionStart, funcContextId) { // For arrow functions, `parseArrow` handles the return type itself. if (match(tt.colon)) { tsParseTypeOrTypePredicateAnnotation(tt.colon); } // The original code checked the node type to make sure this function type allows a missing // body, but we skip that to avoid sending around the node type. We instead just use the // allowExpressionBody boolean to make sure it's not an arrow function. if (!match(tt.braceL) && isLineTerminator()) { // Retroactively mark the function declaration as a type. let i = state.tokens.length - 1; while ( i >= 0 && (state.tokens[i].start >= functionStart || state.tokens[i].type === tt._default || state.tokens[i].type === tt._export) ) { state.tokens[i].isType = true; i--; } return; } parseFunctionBody(false, funcContextId); } export function tsParseSubscript( startTokenIndex, noCalls, stopState, ) { if (!hasPrecedingLineBreak() && eat(tt.bang)) { state.tokens[state.tokens.length - 1].type = tt.nonNullAssertion; return; } if (match(tt.lessThan)) { // There are number of things we are going to "maybe" parse, like type arguments on // tagged template expressions. If any of them fail, walk it back and continue. const snapshot = state.snapshot(); if (!noCalls && atPossibleAsync()) { // Almost certainly this is a generic async function `async <T>() => ... // But it might be a call with a type argument `async<T>();` const asyncArrowFn = tsTryParseGenericAsyncArrowFunction(); if (asyncArrowFn) { return; } } tsParseTypeArguments(); if (!noCalls && eat(tt.parenL)) { // With f<T>(), the subscriptStartIndex marker is on the ( token. state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex; parseCallExpressionArguments(); } else if (match(tt.backQuote)) { // Tagged template with a type argument. parseTemplate(); } else { unexpected(); } if (state.error) { state.restoreFromSnapshot(snapshot); } else { return; } } else if (!noCalls && match(tt.questionDot) && lookaheadType() === tt.lessThan) { // If we see f?.<, then this must be an optional call with a type argument. next(); state.tokens[startTokenIndex].isOptionalChainStart = true; // With f?.<T>(), the subscriptStartIndex marker is on the ?. token. state.tokens[state.tokens.length - 1].subscriptStartIndex = startTokenIndex; tsParseTypeArguments(); expect(tt.parenL); parseCallExpressionArguments(); } baseParseSubscript(startTokenIndex, noCalls, stopState); } export function tsStartParseNewArguments() { if (match(tt.lessThan)) { // 99% certain this is `new C<T>();`. But may be `new C < T;`, which is also legal. const snapshot = state.snapshot(); state.type = tt.typeParameterStart; tsParseTypeArguments(); if (!match(tt.parenL)) { unexpected(); } if (state.error) { state.restoreFromSnapshot(snapshot); } } } export function tsTryParseExport() { if (eat(tt._import)) { // One of these cases: // export import A = B; // export import type A = require("A"); if (isContextual(ContextualKeyword._type) && lookaheadType() !== tt.eq) { // Eat a `type` token, unless it's actually an identifier name. expectContextual(ContextualKeyword._type); } tsParseImportEqualsDeclaration(); return true; } else if (eat(tt.eq)) { // `export = x;` parseExpression(); semicolon(); return true; } else if (eatContextual(ContextualKeyword._as)) { // `export as namespace A;` // See `parseNamespaceExportDeclaration` in TypeScript's own parser expectContextual(ContextualKeyword._namespace); parseIdentifier(); semicolon(); return true; } else { if (isContextual(ContextualKeyword._type) && lookaheadType() === tt.braceL) { next(); } return false; } } export function tsTryParseExportDefaultExpression() { if (isContextual(ContextualKeyword._abstract) && lookaheadType() === tt._class) { state.type = tt._abstract; next(); // Skip "abstract" parseClass(true, true); return true; } if (isContextual(ContextualKeyword._interface)) { // Make sure "export default" are considered type tokens so the whole thing is removed. const oldIsType = pushTypeContext(2); tsParseDeclaration(ContextualKeyword._interface, true); popTypeContext(oldIsType); return true; } return false; } export function tsTryParseStatementContent() { if (state.type === tt._const) { const ahead = lookaheadTypeAndKeyword(); if (ahead.type === tt.name && ahead.contextualKeyword === ContextualKeyword._enum) { expect(tt._const); expectContextual(ContextualKeyword._enum); state.tokens[state.tokens.length - 1].type = tt._enum; tsParseEnumDeclaration(); return true; } } return false; } export function tsTryParseClassMemberWithIsStatic(isStatic) { const memberStartIndexAfterStatic = state.tokens.length; tsParseModifiers([ ContextualKeyword._abstract, ContextualKeyword._readonly, ContextualKeyword._declare, ContextualKeyword._static, ContextualKeyword._override, ]); const modifiersEndIndex = state.tokens.length; const found = tsTryParseIndexSignature(); if (found) { // Index signatures are type declarations, so set the modifier tokens as // type tokens. Most tokens could be assumed to be type tokens, but `static` // is ambiguous unless we set it explicitly here. const memberStartIndex = isStatic ? memberStartIndexAfterStatic - 1 : memberStartIndexAfterStatic; for (let i = memberStartIndex; i < modifiersEndIndex; i++) { state.tokens[i].isType = true; } return true; } return false; } // Note: The reason we do this in `parseIdentifierStatement` and not `parseStatement` // is that e.g. `type()` is valid JS, so we must try parsing that first. // If it's really a type, we will parse `type` as the statement, and can correct it here // by parsing the rest. export function tsParseIdentifierStatement(contextualKeyword) { const matched = tsParseExpressionStatement(contextualKeyword); if (!matched) { semicolon(); } } export function tsParseExportDeclaration() { // "export declare" is equivalent to just "export". const isDeclare = eatContextual(ContextualKeyword._declare); if (isDeclare) { state.tokens[state.tokens.length - 1].type = tt._declare; } let matchedDeclaration = false; if (match(tt.name)) { if (isDeclare) { const oldIsType = pushTypeContext(2); matchedDeclaration = tsTryParseExportDeclaration(); popTypeContext(oldIsType); } else { matchedDeclaration = tsTryParseExportDeclaration(); } } if (!matchedDeclaration) { if (isDeclare) { const oldIsType = pushTypeContext(2); parseStatement(true); popTypeContext(oldIsType); } else { parseStatement(true); } } } export function tsAfterParseClassSuper(hasSuper) { if (hasSuper && match(tt.lessThan)) { tsParseTypeArguments(); } if (eatContextual(ContextualKeyword._implements)) { state.tokens[state.tokens.length - 1].type = tt._implements; const oldIsType = pushTypeContext(1); tsParseHeritageClause(); popTypeContext(oldIsType); } } export function tsStartParseObjPropValue() { tsTryParseTypeParameters(); } export function tsStartParseFunctionParams() { tsTryParseTypeParameters(); } // `let x: number;` export function tsAfterParseVarHead() { const oldIsType = pushTypeContext(0); eat(tt.bang); tsTryParseTypeAnnotation(); popTypeContext(oldIsType); } // parse the return type of an async arrow function - let foo = (async (): number => {}); export function tsStartParseAsyncArrowFromCallExpression() { if (match(tt.colon)) { tsParseTypeAnnotation(); } } // Returns true if the expression was an arrow function. export function tsParseMaybeAssign(noIn, isWithinParens) { // Note: When the JSX plugin is on, type assertions (`<T> x`) aren't valid syntax. if (isJSXEnabled) { return tsParseMaybeAssignWithJSX(noIn, isWithinParens); } else { return tsParseMaybeAssignWithoutJSX(noIn, isWithinParens); } } export function tsParseMaybeAssignWithJSX(noIn, isWithinParens) { if (!match(tt.lessThan)) { return baseParseMaybeAssign(noIn, isWithinParens); } // Prefer to parse JSX if possible. But may be an arrow fn. const snapshot = state.snapshot(); let wasArrow = baseParseMaybeAssign(noIn, isWithinParens); if (state.error) { state.restoreFromSnapshot(snapshot); } else { return wasArrow; } // Otherwise, try as type-parameterized arrow function. state.type = tt.typeParameterStart; // This is similar to TypeScript's `tryParseParenthesizedArrowFunctionExpression`. tsParseTypeParameters(); wasArrow = baseParseMaybeAssign(noIn, isWithinParens); if (!wasArrow) { unexpected(); } return wasArrow; } export function tsParseMaybeAssignWithoutJSX(noIn, isWithinParens) { if (!match(tt.lessThan)) { return baseParseMaybeAssign(noIn, isWithinParens); } const snapshot = state.snapshot(); // This is similar to TypeScript's `tryParseParenthesizedArrowFunctionExpression`. tsParseTypeParameters(); const wasArrow = baseParseMaybeAssign(noIn, isWithinParens); if (!wasArrow) { unexpected(); } if (state.error) { state.restoreFromSnapshot(snapshot); } else { return wasArrow; } // Try parsing a type cast instead of an arrow function. // This will start with a type assertion (via parseMaybeUnary). // But don't directly call `tsParseTypeAssertion` because we want to handle any binary after it. return baseParseMaybeAssign(noIn, isWithinParens); } export function tsParseArrow() { if (match(tt.colon)) { // This is different from how the TS parser does it. // TS uses lookahead. Babylon parses it as a parenthesized expression and converts. const snapshot = state.snapshot(); tsParseTypeOrTypePredicateAnnotation(tt.colon); if (canInsertSemicolon()) unexpected(); if (!match(tt.arrow)) unexpected(); if (state.error) { state.restoreFromSnapshot(snapshot); } } return eat(tt.arrow); } // Allow type annotations inside of a parameter list. export function tsParseAssignableListItemTypes() { const oldIsType = pushTypeContext(0); eat(tt.question); tsTryParseTypeAnnotation(); popTypeContext(oldIsType); } export function tsParseMaybeDecoratorArguments() { if (match(tt.lessThan)) { tsParseTypeArguments(); } baseParseMaybeDecoratorArguments(); }
27.033063
173
0.676909
dbde0bd624e68b67c90b11c2df1c2086137d6dde
2,240
js
JavaScript
Utils/GenerateM.js
anhnguyendon92/ReadMeGenerator-
a1e1f51a490b71c079d0e9a553bd419ffa9469fa
[ "MIT" ]
null
null
null
Utils/GenerateM.js
anhnguyendon92/ReadMeGenerator-
a1e1f51a490b71c079d0e9a553bd419ffa9469fa
[ "MIT" ]
null
null
null
Utils/GenerateM.js
anhnguyendon92/ReadMeGenerator-
a1e1f51a490b71c079d0e9a553bd419ffa9469fa
[ "MIT" ]
null
null
null
const licenseBadgeLinks = require('./License'); // function to generate markdown for README const generateMarkdown = (data) => { // set url for license badge data.licenseBadge = licenseBadgeLinks[data.license]; //return markdown content return ` ## Badges ${data.licenseBadge} # Project Title : ${data.title} ## Project Description: ${data.desc} ## Table of Contents * [Description](#description) * [Installation](#installation) * [Usage](#usage) * [Contributing](#contributing) * [Test](#test) * [Questions](#questions) * [License](#license) * [Author](#Author) * [Badges](#badges) ## Installation To install dependencies, run the following: \` ${data.installation} \` ## Usage ${data.usage} ## Contributors ${data.contributors} ## Test To run tests, run the following: \` ${data.tests} \` ## Questions If you have questions about this repository? Please contact me at [${data.email}](mailto:${data.email}). View more of my work in GitHub at [${data.username}](https://github.com/${data.username}). ## License This repository is licensed under the ${data.license} license. Copyright (c) [2020] [Anh Nguyen] 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. ## Author ![GitHub profile pic](${data.image}) `; } module.exports = generateMarkdown;
37.966102
460
0.748661
dbde8aec0f9d200a4439405252148a82a59e212c
1,628
js
JavaScript
test/import-export.js
squidsoup/js-macaroon
667cfc44782ae43c168c22cb8570ad4bc86bc5b2
[ "BSD-3-Clause" ]
34
2015-01-22T07:02:46.000Z
2021-11-03T21:49:36.000Z
test/import-export.js
squidsoup/js-macaroon
667cfc44782ae43c168c22cb8570ad4bc86bc5b2
[ "BSD-3-Clause" ]
25
2015-10-15T13:36:49.000Z
2021-05-07T20:09:06.000Z
test/import-export.js
squidsoup/js-macaroon
667cfc44782ae43c168c22cb8570ad4bc86bc5b2
[ "BSD-3-Clause" ]
19
2015-01-05T09:34:37.000Z
2021-02-25T18:21:10.000Z
'use strict'; const test = require('tape'); const m = require('../macaroon'); const testUtils = require('./test-utils'); test('importMacaroon should import from a single object', t => { const obj = { location: 'a location', identifier: 'id 1', signature: 'e0831c334c600631bf7b860ca20c9930f584b077b8eac1f1e99c6a45d11a3d20', caveats: [ { 'cid': 'a caveat' }, { 'cid': '3rd question', 'vid': 'MMVAwhLcKvsgJS-SCTuhi9fMNYT9SjSePUX2q4z8y4_TpYfB82UCirA0ZICOdUb7ND_2', 'cl': '3rd loc' }, ], }; const macaroon = m.importMacaroon(obj); t.equal(macaroon.location, 'a location'); t.equal(testUtils.bytesToString(macaroon.identifier), 'id 1'); t.equal( testUtils.bytesToHex(macaroon.signature), 'e0831c334c600631bf7b860ca20c9930f584b077b8eac1f1e99c6a45d11a3d20'); // Test that it round trips. const obj1 = macaroon.exportJSON(); t.deepEqual(obj1, obj); t.end(); }); test('importMacaroons should import from an array', t => { const objs = [{ location: 'a location', identifier: 'id 0', signature: '4579ad730bf3f819a299aaf63f04f5e897d80690c4c5814a1ae026a45989de7d', }, { location: 'a location', identifier: 'id 1', signature: '99b1c2dede0ce1cba0b632e3996e9924bdaee6287151600468644b92caf3761b', }]; const macaroon = m.importMacaroons(objs); t.equal(macaroon.length, 2); t.equal(testUtils.bytesToString(macaroon[0].identifier), 'id 0'); t.equal(testUtils.bytesToString(macaroon[1].identifier), 'id 1'); t.deepEqual([ macaroon[0].exportJSON(), macaroon[1].exportJSON()], objs); t.end(); });
28.561404
86
0.67629
c12df958f896e7911eeb191ac5f762ed59eca4b9
473
js
JavaScript
genKeys.js
hmbeale/dictionary
4d652f81eace30d38c3081777b298165af36aa3c
[ "MIT" ]
null
null
null
genKeys.js
hmbeale/dictionary
4d652f81eace30d38c3081777b298165af36aa3c
[ "MIT" ]
null
null
null
genKeys.js
hmbeale/dictionary
4d652f81eace30d38c3081777b298165af36aa3c
[ "MIT" ]
null
null
null
const fs = require('fs'); //note this isn't actual json just js that looks like json //dictionary is an object with a whole dictionary in it! //it's big so be careful const dictionaryObject = require('./dictionary.js'); const dictionary = dictionaryObject['dictionary']; //awkward because it generates a rather large array const getAllKeys = (obj) => { return Object.keys(dictionary); } dictWords = getAllKeys(dictionary); fs.writeFileSync('allWords.js', dictWords);
27.823529
58
0.744186
c12e2e69dbff8d4561d5275e436e4531326e00f0
5,707
js
JavaScript
test/server-version.spec.js
aldebout/nuxeo-js-client
f9a786c4ca4913da36be54e74432298e46cd4e7d
[ "Apache-2.0" ]
null
null
null
test/server-version.spec.js
aldebout/nuxeo-js-client
f9a786c4ca4913da36be54e74432298e46cd4e7d
[ "Apache-2.0" ]
null
null
null
test/server-version.spec.js
aldebout/nuxeo-js-client
f9a786c4ca4913da36be54e74432298e46cd4e7d
[ "Apache-2.0" ]
null
null
null
const ServerVersion = require('../lib/server-version'); describe('ServerVersion', () => { describe('#constructor', () => { it('should parse known server versions', () => { let version = new ServerVersion('9.10'); expect(version.major).to.equal(9); expect(version.minor).to.equal(10); expect(version.hotfix).to.be.equal(-1); version = new ServerVersion('7.10-HF31'); expect(version.major).to.equal(7); expect(version.minor).to.equal(10); expect(version.hotfix).to.be.equal(31); version = new ServerVersion('8.10-SNAPSHOT'); expect(version.major).to.equal(8); expect(version.minor).to.equal(10); expect(version.hotfix).to.be.equal(-1); version = new ServerVersion('8.10-I20180101_1522'); expect(version.major).to.equal(8); expect(version.minor).to.equal(10); expect(version.hotfix).to.be.equal(-1); }); it('should throw an error for unknown version format', () => { expect(() => new ServerVersion('BAD_VERSION')).to.throw('Unknown Nuxeo Server version: BAD_VERSION'); expect(() => new ServerVersion('9_10')).to.throw('Unknown Nuxeo Server version: 9_10'); }); }); it('#toString', () => { const version = new ServerVersion('9.10'); expect(version.toString()).to.equal('9.10'); }); it('#eq', () => { // equal versions let version1 = new ServerVersion('9.10'); let version2 = new ServerVersion('9.10'); expect(version1.eq(version2)).to.be.true(); version1 = new ServerVersion('8.10'); version2 = new ServerVersion('8.10-SNAPSHOT'); expect(version1.eq(version2)).to.be.true(); version1 = new ServerVersion('7.10'); version2 = new ServerVersion('7.10-I20180101_1212'); expect(version1.eq(version2)).to.be.true(); version1 = new ServerVersion('6.0-HF44'); expect(version1.eq('6.0-HF44')).to.be.true(); // non-equal versions version1 = new ServerVersion('9.10'); version2 = new ServerVersion('8.10'); expect(version1.eq(version2)).to.be.false(); version1 = new ServerVersion('7.10'); version2 = new ServerVersion('6.0'); expect(version1.eq(version2)).to.be.false(); version1 = new ServerVersion('8.10-SNAPSHOT'); version2 = new ServerVersion('7.10'); expect(version1.eq(version2)).to.be.false(); version1 = new ServerVersion('7.10-HF44'); version2 = new ServerVersion('6.0-HF45'); expect(version1.eq(version2)).to.be.false(); version1 = new ServerVersion('8.10-HF10'); expect(version1.eq('8.10-HF11')).to.be.false(); }); it('#gt', () => { // greater let version1 = new ServerVersion('10.1'); let version2 = new ServerVersion('9.10'); expect(version1.gt(version2)).to.be.true(); version1 = new ServerVersion('9.2'); version2 = new ServerVersion('9.1'); expect(version1.gt(version2)).to.be.true(); version1 = new ServerVersion('7.10-HF20'); version2 = new ServerVersion('7.10'); expect(version1.gt(version2)).to.be.true(); version1 = new ServerVersion('6.0-HF44'); expect(version1.gt('6.0-HF43')).to.be.true(); // non-greater version1 = new ServerVersion('9.10'); version2 = new ServerVersion('10.1'); expect(version1.gt(version2)).to.be.false(); version1 = new ServerVersion('9.1'); version2 = new ServerVersion('9.2'); expect(version1.gt(version2)).to.be.false(); version1 = new ServerVersion('7.10'); version2 = new ServerVersion('7.10-HF20'); expect(version1.gt(version2)).to.be.false(); version1 = new ServerVersion('6.0-HF43'); expect(version1.gt('6.0-HF44')).to.be.false(); }); it('#lt', () => { // lesser let version1 = new ServerVersion('9.10'); let version2 = new ServerVersion('10.1'); expect(version1.lt(version2)).to.be.true(); version1 = new ServerVersion('9.1'); version2 = new ServerVersion('9.2'); expect(version1.lt(version2)).to.be.true(); version1 = new ServerVersion('7.10'); version2 = new ServerVersion('7.10-HF20'); expect(version1.lt(version2)).to.be.true(); version1 = new ServerVersion('6.0-HF43'); expect(version1.lt('6.0-HF44')).to.be.true(); // non-lesser version1 = new ServerVersion('10.1'); version2 = new ServerVersion('9.10'); expect(version1.lt(version2)).to.be.false(); version1 = new ServerVersion('9.2'); version2 = new ServerVersion('9.1'); expect(version1.lt(version2)).to.be.false(); version1 = new ServerVersion('7.10-HF20'); version2 = new ServerVersion('7.10'); expect(version1.lt(version2)).to.be.false(); version1 = new ServerVersion('6.0-HF44'); expect(version1.lt('6.0-HF43')).to.be.false(); }); it('#gte', () => { // greater or equal let version1 = new ServerVersion('9.10'); let version2 = new ServerVersion('9.10'); expect(version1.gte(version2)).to.be.true(); version1 = new ServerVersion('9.10'); version2 = new ServerVersion('8.10'); expect(version1.gte(version2)).to.be.true(); // non-greater or non-equal version1 = new ServerVersion('7.10'); version2 = new ServerVersion('8.10'); expect(version1.gte(version2)).to.be.false(); }); it('#lte', () => { // lesser or equal let version1 = new ServerVersion('9.10'); let version2 = new ServerVersion('9.10'); expect(version1.lte(version2)).to.be.true(); version1 = new ServerVersion('8.10'); version2 = new ServerVersion('9.10'); expect(version1.lte(version2)).to.be.true(); // non-lesser or non-equal version1 = new ServerVersion('9.10'); version2 = new ServerVersion('8.10'); expect(version1.lte(version2)).to.be.false(); }); });
32.426136
107
0.628001
c12e566a1b8f7f54e29abc8cfccc6b311c4afe34
130
js
JavaScript
index.js
maslick/react-radiaslider
2d561bea0b8c2117fdc1f6fae93d4cf64ba3cd74
[ "MIT" ]
null
null
null
index.js
maslick/react-radiaslider
2d561bea0b8c2117fdc1f6fae93d4cf64ba3cd74
[ "MIT" ]
1
2021-03-09T00:01:21.000Z
2021-03-09T00:01:21.000Z
index.js
maslick/react-radiaslider
2d561bea0b8c2117fdc1f6fae93d4cf64ba3cd74
[ "MIT" ]
null
null
null
import RadiaSlider from "./RadiaComponent"; import LinearSlider from "./LinearComponent"; export { RadiaSlider, LinearSlider };
21.666667
45
0.776923
c12e91af776d157cef628e44cc160def1f3f2e3d
394
js
JavaScript
JavaScript/M02_JavaScriptFundamentals/L06_ObjectsAndClasses/Exercises/P06_MakeADictionary.js
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
3
2021-04-06T21:35:50.000Z
2021-08-07T09:51:58.000Z
JavaScript/M02_JavaScriptFundamentals/L06_ObjectsAndClasses/Exercises/P06_MakeADictionary.js
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
null
null
null
JavaScript/M02_JavaScriptFundamentals/L06_ObjectsAndClasses/Exercises/P06_MakeADictionary.js
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
1
2022-02-23T13:03:14.000Z
2022-02-23T13:03:14.000Z
function foo(data) { let result = {}; data.forEach(x => { const parsed = JSON.parse(x) const key = Object.keys(parsed)[0] const value = Object.values(parsed)[0] result[key] = value }); Object .entries(result) .sort((x, y) => x[0].localeCompare(y[0])) .forEach(x => console.log(`Term: ${x[0]} => Definition: ${x[1]}`)); }
26.266667
75
0.515228
c12f8b88c624dbcd58d043ec60c160a327037bb8
2,411
js
JavaScript
app/containers/ManageTaskPage/constants.js
osehra-ocp/ocp-ui
22868ff1496dda6324f89c569e262bf8805518b7
[ "Apache-2.0" ]
null
null
null
app/containers/ManageTaskPage/constants.js
osehra-ocp/ocp-ui
22868ff1496dda6324f89c569e262bf8805518b7
[ "Apache-2.0" ]
null
null
null
app/containers/ManageTaskPage/constants.js
osehra-ocp/ocp-ui
22868ff1496dda6324f89c569e262bf8805518b7
[ "Apache-2.0" ]
1
2020-03-23T03:18:57.000Z
2020-03-23T03:18:57.000Z
/* * * ManageTaskPage constants * */ /** * ManageTaskPage action types * @type {string} */ export const GET_PATIENT = 'ocpui/ManageTaskPage/GET_PATIENT'; export const GET_PATIENT_SUCCESS = 'ocpui/ManageTaskPage/GET_PATIENT_SUCCESS'; export const GET_ACTIVITY_DEFINITIONS = 'ocpui/ManageTaskPage/GET_ACTIVITY_DEFINITIONS'; export const GET_ACTIVITY_DEFINITIONS_SUCCESS = 'ocpui/ManageTaskPage/GET_ACTIVITY_DEFINITIONS_SUCCESS'; export const GET_ACTIVITY_DEFINITIONS_ERROR = 'ocpui/ManageTaskPage/GET_ACTIVITY_DEFINITIONS_ERROR'; export const GET_PRACTITIONER = 'ocpui/ManageTaskPage/GET_PRACTITIONER'; export const GET_PRACTITIONER_SUCCESS = 'ocpui/ManageTaskPage/GET_PRACTITIONER_SUCCESS'; export const GET_PRACTITIONER_ERROR = 'ocpui/ManageTaskPage/GET_PRACTITIONER_ERROR'; export const GET_PRACTITIONERS = 'ocpui/ManageTaskPage/GET_PRACTITIONERS'; export const GET_PRACTITIONERS_SUCCESS = 'ocpui/ManageTaskPage/GET_PRACTITIONERS_SUCCESS'; export const GET_PRACTITIONERS_ERROR = 'ocpui/ManageTaskPage/GET_PRACTITIONERS_ERROR'; export const GET_EVENT_TYPES = 'ocpui/ManageTaskPage/GET_EVENT_TYPES'; export const GET_EVENT_TYPES_SUCCESS = 'ocpui/ManageTaskPage/GET_EVENT_TYPES_SUCCESS'; export const GET_EVENT_TYPES_ERROR = 'ocpui/ManageTaskPage/GET_EVENT_TYPES_ERROR'; export const CREATE_TASK_SUCCESS = 'ocpui/ManageTaskPage/CREATE_TASK_SUCCESS'; export const CREATE_TASK_ERROR = 'ocpui/ManageTaskPage/CREATE_TASK_ERROR'; export const CREATE_TASK = 'ocpui/ManageTaskPage/CREATE_TASK '; export const PUT_TASK_SUCCESS = 'ocpui/ManageTaskPage/PUT_TASK_SUCCESS'; export const PUT_TASK_ERROR = 'ocpui/ManageTaskPage/PUT_TASK_ERROR'; export const PUT_TASK = 'ocpui/ManageTaskPage/PUT_TASK '; export const GET_TASK_SUCCESS = 'ocpui/ManageTaskPage/GET_TASK_SUCCESS'; export const GET_TASK_ERROR = 'ocpui/ManageTaskPage/GET_TASK_ERROR'; export const GET_TASK = 'ocpui/ManageTaskPage/GET_TASK '; export const GET_SUB_TASKS_SUCCESS = 'ocpui/ManageTaskPage/GET_SUB_TASKS_SUCCESS'; export const GET_SUB_TASKS_ERROR = 'ocpui/ManageTaskPage/GET_SUB_TASKS_ERROR'; export const GET_SUB_TASKS = 'ocpui/ManageTaskPage/GET_SUB_TASKS '; export const GET_TASKS_BY_PATIENT_SUCCESS = 'ocpui/ManageTaskPage/GET_TASKS_BY_PATIENT_SUCCESS'; export const GET_TASKS_BY_PATIENT_ERROR = 'ocpui/ManageTaskPage/GET_TASKS_BY_PATIENT_ERROR'; export const GET_TASKS_BY_PATIENT = 'ocpui/ManageTaskPage/GET_TASKS_BY_PATIENT ';
46.365385
104
0.842804
c131c027ae70d5b26520383c7b0b131710bdd624
29,598
js
JavaScript
widgets/timeandweather/js/jquery.zweatherfeed.js
aurodionov/ioBroker.vis-timeandweather
fde8246202042328770a995eba191541272d4ede
[ "MIT" ]
16
2016-02-10T05:54:16.000Z
2021-06-26T12:17:22.000Z
widgets/timeandweather/js/jquery.zweatherfeed.js
aurodionov/ioBroker.vis-timeandweather
fde8246202042328770a995eba191541272d4ede
[ "MIT" ]
11
2017-08-09T08:06:21.000Z
2022-03-24T10:34:04.000Z
widgets/timeandweather/js/jquery.zweatherfeed.js
aurodionov/ioBroker.vis-timeandweather
fde8246202042328770a995eba191541272d4ede
[ "MIT" ]
7
2016-02-15T15:37:37.000Z
2019-12-12T23:02:25.000Z
/** * Plugin: jquery.zWeatherFeed * * Version: 1.2.1 * (c) Copyright 2011-2013, Zazar Ltd * * Description: jQuery plugin for display of Yahoo! Weather feeds * * History: * 1.2.1 - Handle invalid locations * 1.2.0 - Added forecast data option * 1.1.0 - Added user callback function * New option to use WOEID identifiers * New day/night CSS class for feed items * Updated full forecast link to feed link location * 1.0.3 - Changed full forecast link to Weather Channel due to invalid Yahoo! link Add 'linktarget' option for forecast link * 1.0.2 - Correction to options / link * 1.0.1 - Added hourly caching to YQL to avoid rate limits * Uses Weather Channel location ID and not Yahoo WOEID * Displays day or night background images * **/ /* If used custom mode update widget as follow: $wid.weatherfeed('', 'update', { "units": { "distance": "km", "pressure": "mb", "speed": "km/h", "temperature": "C" }, "location": { "city": "Karlsruhe" }, "wind": { "chill": "66", "direction": "255", "speed": "11.27" }, "atmosphere": { "humidity": "71" }, "image": { "url": "http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif" }, "item": { "condition": { "code": "26", "temp": "19", "text": "Cloudy" }, "forecast": [ { "code": "12", "high": "20", "low": "14", "text": "Rain" }, { "code": "39", "high": "21", "low": "13", "text": "Scattered Showers" }, { "code": "4", "high": "22", "low": "15", "text": "Thunderstorms" }, { "code": "28", "high": "23", "low": "13", "text": "Mostly Cloudy" }, { "code": "4", "high": "24", "low": "15", "text": "Thunderstorms" }, { "code": "47", "high": "23", "low": "16", "text": "Scattered Thunderstorms" }, { "code": "30", "high": "23", "low": "16", "text": "Partly Cloudy" } ] } }); */ (function($){ "use strict"; // Translation function. DONT make ARRAY. Numbers are important var _tt = []; { _tt[0] = {'en':'Tornado', 'de': 'Tornado', 'ru': 'Торнадо - сиди дома!'}; _tt[1] = {'en':'Tropical storm', 'de': 'Tropischer Sturm', 'ru': 'Тропический шторм'}; _tt[2] = {'en':'Hurricane', 'de': 'Hurrikan', 'ru': 'Ураган'}; _tt[3] = {'en':'Severe thunderstorms', 'de': 'Starke Gewitter', 'ru': 'Сильная непогода'}; _tt[4] = {'en':'Thunderstorms', 'de': 'Gewitter', 'ru': 'Грозы'}; _tt[5] = {'en':'Mixed rain and snow', 'de' : 'Regen mit Schnee', 'ru': 'Дождь со снегом'}; _tt[6] = {'en':'Mixed rain and sleet', 'de' : 'Regen mit Graupel', 'ru': 'Дождь с градом'}; _tt[7] = {'en':'Mixed snow and sleet', 'de' : 'Schnee mit Graupel', 'ru': 'Снег с градом'}; _tt[8] = {'en':'Freezing drizzle', 'de' : 'Eisnieselregen', 'ru': 'Изморозь'}; _tt[9] = {'en':'Drizzle', 'de' : 'Nieselregen', 'ru': 'Моросящий дождь'}; _tt[10] = {'en':'Freezing rain', 'de': 'Eisregen', 'ru': 'Ледяной дождь'}; _tt[11] = {'en':'Showers', 'de': 'Regenschauer', 'ru': 'Ливень'}; _tt[12] = {'en':'Showers', 'de': 'Regenschauer', 'ru': 'Ливень'}; _tt[13] = {'en':'Snow flurries', 'de': 'Schneetreiben', 'ru': 'Снегопад'}; _tt[14] = {'en':'Light snow showers', 'de': 'Leichter Schneeregen', 'ru': 'Небольшой дождь со снегом'}; _tt[15] = {'en':'Bowing snow', 'de': 'Schneeb&ouml;en', 'ru': 'Снег'}; _tt[16] = {'en':'Snow', 'de': 'Schnee', 'ru': 'Снег'}; _tt[17] = {'en':'Hail', 'de': 'Hagel', 'ru': 'Град'}; _tt[18] = {'en':'Sleet', 'de': 'Graupel', 'ru': 'Мелкий град'}; _tt[19] = {'en':'Dust', 'de':'Diesig', 'ru': 'Пыльно'}; _tt[20] = {'en':'Foggy', 'de':'Neblig', 'ru': 'Туманно'}; _tt[21] = {'en':'Haze', 'de':'Dunst', 'ru': 'Туман'}; _tt[22] = {'en':'Smoky', 'de':'Qualmig', 'ru': 'Задымление'}; _tt[23] = {'en':'Blustery', 'de':'St&uuml;rmisch', 'ru': 'Порывистый ветер'}; _tt[24] = {'en':'Windy', 'de':'Windig', 'ru': 'Ветрянно'}; _tt[25] = {'en':'Cold', 'de':'Kalt', 'ru': 'Холодно'}; _tt[26] = {'en':'Cloudy', 'de':'Wolkig', 'ru': 'Облачно'}; _tt[27] = {'en':'Mostly cloudy (night)', 'de':'&Uuml;berwiegend wolkig (Nacht)', 'ru': 'В основном облачно'}; _tt[28] = {'en':'Mostly cloudy (day)', 'de':'&Uuml;berwiegend wolkig (Tag)', 'ru': 'В основном облачно'}; _tt[29] = {'en':'partly cloudy (night)', 'de':'Teilweise wolkig (Nacht)', 'ru': 'Местами облачно'}; _tt[30] = {'en':'partly cloudy (day)', 'de':'Teilweise wolkig (Tag)', 'ru': 'Приемущественно солнечно'}; _tt[31] = {'en':'clear (night)', 'de':'Klare Nacht', 'ru': 'Ясно'}; _tt[32] = {'en':'sunny', 'de':'Sonnig', 'ru': 'Солнечно'}; _tt[33] = {'en':'fair (night)', 'de': 'Sch&ouml;nwetter (Nacht)', 'ru': 'Прекрасная погода'}; _tt[34] = {'en':'fair (day)', 'de': 'Sch&ouml;nwetter (Tag)', 'ru': 'Прекрасная погода'}; _tt[35] = {'en':'mixed rain and hail', 'de': 'Regen mit Hagel', 'ru': 'Снег с градом'}; _tt[36] = {'en':'hot', 'de': 'Hei&szlig;', 'ru': 'Жарко'}; _tt[37] = {'en':'isolated thunderstorms', 'de': 'Gebietsweise Gewitter', 'ru': 'Одиночные грозы'}; _tt[38] = {'en':'scattered thunderstorms', 'de': 'Vereinzelte Gewitter', 'ru': 'Грозы'}; _tt[39] = {'en':'scattered thunderstorms', 'de': 'Vereinzelte Gewitter', 'ru': 'Грозы'}; _tt[40] = {'en':'scattered showers', 'de': 'Vereinzelter Regen', 'ru': 'Дождь'}; _tt[41] = {'en':'heavy snow', 'de':'Starker Schneefall', 'ru': 'Сильный снегопад'}; _tt[42] = {'en':'scattered snow showers', 'de': 'Vereinzelter Schneeregen', 'ru': 'Ливень с дождем'}; _tt[43] = {'en':'heavy snow', 'de':'Starker Schneefall', 'ru': 'Сильный снегопад'}; _tt[44] = {'en':'partly cloudy', 'de':'Teilweise wolkig', 'ru': 'Переменная облачность'}; _tt[45] = {'en':'thundershowers', 'de':'Gewitterschauer', 'ru': 'Штормовой дождь'}; _tt[46] = {'en':'snow showers', 'de': 'Schneeregen', 'ru': 'Снег с дождем'}; _tt[47] = {'en':'isolated thundershowers', 'de': 'Gebietsweise Gewitterschauer', 'ru': 'Местами грозы'}; _tt[100] = {code: 39, 'en':'scattered thunderstorms', 'de': 'Vereinzelte Gewitter', 'ru': 'Грозы'}; _tt[101] = {code: 32, 'en':'sunny', 'de':'Sonnig', 'ru': 'Солнечно'}; _tt[3200] = {'en':'not available', 'de': '', 'ru': ''}; } function _translate(word, lang) { if (word === undefined || word == null || word == "") return ''; if (lang == 'de') { // If date if (word.length > 1 && word[0] >= '0' && word[0] <= '9') { word = word.replace ('Jan', 'Januar'); word = word.replace ('Feb', 'Februar'); word = word.replace ('Mar', 'M&auml;rz'); word = word.replace ('Apr', 'April'); word = word.replace ('Mai', 'Mai'); word = word.replace ('Jun', 'Juni'); word = word.replace ('Jul', 'Juli'); word = word.replace ('Aug', 'August'); word = word.replace ('Sep', 'September'); word = word.replace ('Oct', 'Oktober'); word = word.replace ('Nov', 'November'); word = word.replace ('Dec', 'Dezember'); return word; } if (word == 'High') return 'H&ouml;chste'; if (word == 'Low') return 'Niedrigste'; if (word == 'Wind') return 'Wind'; if (word == 'Humidity') return 'Luftfeuchte'; if (word == 'Visibility') return 'Sichtweite'; if (word == 'Sunrise') return 'Sonnenaufgang'; if (word == 'Sunset') return 'Sonnenuntergang'; if (word == 'City not found') return 'Stadt nicht gefunden'; if (word == 'Full forecast') return 'Volle Vorhersage'; if (word == 'Read full forecast') return 'Sehe volle Vorhersage'; if (word == 'Mon') return 'Montag'; if (word == 'Tue') return 'Dienstag'; if (word == 'Wed') return 'Mittwoch'; if (word == 'Thu') return 'Donnerstag'; if (word == 'Fri') return 'Freitag'; if (word == 'Sat') return 'Samstag'; if (word == 'Sun') return 'Sonntag'; if (word == 'Temperature') return 'Temperatur'; } if (lang == 'ru') { // If date if (word.length > 1 && word[0] >= '0' && word[0] <= '9') { word = word.replace ('Jan', 'Январь'); word = word.replace ('Feb', 'Февраль'); word = word.replace ('Mar', 'Март'); word = word.replace ('Apr', 'Апрель'); word = word.replace ('Mai', 'Май'); word = word.replace ('Jun', 'Июнь'); word = word.replace ('Jul', 'Июль'); word = word.replace ('Aug', 'Август'); word = word.replace ('Sep', 'Сентябрь'); word = word.replace ('Oct', 'Октябрь'); word = word.replace ('Nov', 'Ноябрь'); word = word.replace ('Dec', 'Декабрь'); return word; } if (word == 'High') return 'Макс.'; if (word == 'Temperature') return 'Температура'; if (word == 'Low') return 'Мин.'; if (word == 'Wind') return 'Ветер'; if (word == 'Humidity') return 'Влажность'; if (word == 'Visibility') return 'Видимость'; if (word == 'Sunrise') return 'Восход'; if (word == 'Sunset') return 'Закат'; if (word == 'City not found') return 'Город не найден'; if (word == 'Full forecast') return 'Полный прогноз'; if (word == 'Read full forecast') return 'См. полный прогноз'; if (word == 'Mon') return 'Понедельник'; if (word == 'Tue') return 'Вторник'; if (word == 'Wed') return 'Среда'; if (word == 'Thu') return 'Четверг'; if (word == 'Fri') return 'Пятница'; if (word == 'Sat') return 'Суббота'; if (word == 'Sun') return 'Воскресение'; } return word; } function findCode(text) { text = text.toLowerCase(); for (var i = 0; i < _tt.length && i < 200; i++) { if (!_tt[i]) continue; var de = _tt[i].de.toLowerCase().replace(/&ouml;/, 'ö').replace(/&uuml;/, 'ü').replace(/&szlig;/, 'ß'); if (_tt[i].en.toLowerCase() === text || de=== text || _tt[i].ru.toLowerCase() === text) { return _tt[i].code !== undefined ? _tt[i].code : i; } } for (var i = 0; i < _tt.length && i < 200; i++) { if (!_tt[i]) continue; var de = _tt[i].de.toLowerCase().replace(/&ouml;/, 'ö').replace(/&uuml;/, 'ü').replace(/&szlig;/, 'ß'); if (_tt[i].en.toLowerCase().indexOf(text) !== -1 || de.indexOf(text) !== -1 || _tt[i].ru.toLowerCase().indexOf(text) !== -1) { return _tt[i].code !== undefined ? _tt[i].code : i; } } return null; } // Function to each feed item function _process(e, options) { var $e = $(e); var row = 'odd'; var feed = $e[0].feed; if (!options) options = $e.data('options'); $e.empty(); if (options.width) $e.css ({width: options.width}); if (options.height) $e.css ({height: options.height}); var isShort = (options.width < 100); var html; // Check for invalid location if (feed.description !== 'Yahoo! Weather Error' && feed.wind) { // Format feed items var wd = feed.wind.direction; if (wd >= 348.75 && wd <= 360) { wd = 'N'; } else if (wd >= 0 && wd < 11.25) { wd = 'N'; } else if (wd >= 11.25 && wd < 33.75) { wd = 'NNE'; } else if (wd >= 33.75 && wd < 56.25) { wd = 'NE'; } else if (wd >= 56.25 && wd < 78.75) { wd = 'ENE'; } else if (wd >= 78.75 && wd < 101.25) { wd = 'E'; } else if (wd >= 101.25 && wd < 123.75) { wd = 'ESE'; } else if (wd >= 123.75 && wd < 146.25) { wd = 'SE'; } else if (wd >= 146.25 && wd < 168.75) { wd = 'SSE'; } else if (wd >= 168.75 && wd < 191.25) { wd = 'S'; } else if (wd >= 191.25 && wd < 213.75) { wd = 'SSW'; } else if (wd >= 213.75 && wd < 236.25) { wd = 'SW'; } else if (wd >= 236.25 && wd < 258.75) { wd = 'WSW'; } else if (wd >= 258.75 && wd < 281.25) { wd = 'W'; } else if (wd >= 281.25 && wd < 303.75) { wd = 'WNW'; } else if (wd >= 303.75 && wd < 326.25) { wd = 'NW'; } else if (wd >= 326.25 && wd < 348.75) { wd = 'NNW'; } var wf = feed.item.forecast[0]; // Determine day or night image var wpd = feed.item.pubDate || (new Date().toString()); var n = wpd.indexOf(':'); var tpb = _getTimeAsDate(wpd.substr(n - 2, 8)); var tsr = feed.astronomy && feed.astronomy.sunrise ? _getTimeAsDate(feed.astronomy.sunrise) : null; var tss = feed.astronomy && feed.astronomy.sunset ? _getTimeAsDate(feed.astronomy.sunset) : null; var daynight; // Get night or day if (tsr === null) { var hh = new Date().getHours(); daynight = (hh > 20 || hh < 7) ? 'night' : 'day'; } else { if (tpb > tsr && tpb < tss) { daynight = 'day'; } else { daynight = 'night'; } } // Add item container html = '<div class="weatherItem ' + row + ' ' + daynight + '" style="'; if (options.image) { if (feed.item.condition.code !== undefined && feed.item.condition.code !== null) { html += 'background-image: url(http://l.yimg.com/a/i/us/nws/weather/gr/' + feed.item.condition.code + daynight.substring(0, 1) + '.png); background-repeat: no-repeat;'; } else if (feed.item.condition.icon) { html += 'background-image: url(' + feed.item.condition.icon + '); background-repeat: no-repeat;'; } else { var code = findCode(feed.item.condition.text); if (code !== null) { html += 'background-image: url(http://l.yimg.com/a/i/us/nws/weather/gr/' + code + daynight.substring(0, 1) + '.png); background-repeat: no-repeat;'; } } } html += ($(e).css('border-radius') ? 'border-radius: ' + $(e).css('border-radius') : '') + '"'; html += '>'; // Add item data html += '<div class="weatherCity">' + (options.city || feed.location.city) + '</div>'; if (options.country) html += '<div class="weatherCountry">' + feed.location.country + '</div>'; if (feed.item.condition.temp !== null) html += '<div class="weatherTemp">' + feed.item.condition.temp + '&deg;</div>'; if (feed.item.condition.code !== null && _tt[feed.item.condition.code]) { html += '<div class="weatherDesc">' + (_tt[feed.item.condition.code][options.lang] || _tt[feed.item.condition.code]['en']) + '</div>'; } else if (feed.item.condition.text !== null) { var code = findCode(feed.item.condition.text); if (code !== null) feed.item.condition.text = _tt[code][options.lang] || _tt[code]['en']; html += '<div class="weatherDesc">' + feed.item.condition.text + '</div>'; } // Add optional data if (wf) { if (wf.high !== null && options.highlow && !isShort) html += '<div class="weatherRange">' + _translate('High', options.lang) + ': ' + wf.high + '&deg; ' + _translate('Low', options.lang) + ': ' + wf.low + '&deg;</div>'; if (wf.low !== null && options.highlow && isShort) html += '<div class="weatherRange">' + wf.low + '&deg;-' + wf.high + '&deg;</div>'; } if (feed.wind.speed !== null && options.wind && !isShort) html += '<div class="weatherWind">' + _translate('Wind', options.lang) + ': ' + wd + ' ' + feed.wind.speed + _translate(feed.units.speed) + '</div>'; if (feed.atmosphere && feed.atmosphere.humidity !== null && options.humidity && !isShort) html += '<div class="weatherHumidity">' + _translate('Humidity', options.lang) + ': ' + feed.atmosphere.humidity + '%</div>'; if (feed.atmosphere && feed.atmosphere.humidity !== null && options.humidity && isShort) html += '<div class="weatherHumidity">' + feed.atmosphere.humidity + '%</div>'; if (feed.atmosphere && feed.atmosphere.visibility !== null && options.visibility) html += '<div class="weatherVisibility">' + _translate('Visibility', options.lang) + ': ' + feed.atmosphere.visibility + '</div>'; if (feed.astronomy && feed.astronomy.sunrise !== null && options.sunrise) html += '<div class="weatherSunrise">' + _translate('Sunrise', options.lang) + ': ' + feed.astronomy.sunrise + '</div>'; if (feed.astronomy && feed.astronomy.sunset !== null && options.sunset) html += '<div class="weatherSunset">' + _translate('Sunset', options.lang) + ': ' + feed.astronomy.sunset + '</div>'; // Add item forecast data if (options.forecast && feed.item) { html += '<div class="weatherForecast">'; var wfi = feed.item.forecast; for (var i = 0; i < wfi.length; i++) { if (options.maxDays && (i + 1) > options.maxDays) break; if (!wfi[i].date) { var now = new Date(); now.setDate(now.getDate() + i); wfi[i].date = now.toDateString(); wfi[i].day = wfi[i].date.substring(0, 3); wfi[i].date = wfi[i].date.substring(8, 11) + wfi[i].date.substring(4, 7) + wfi[i].date.substring(10); } if (wfi[i].code !== null && wfi[i].code !== undefined) { html += '<div class="weatherForecastItem" style="background-image: url(http://l.yimg.com/a/i/us/nws/weather/gr/'+ wfi[i].code + 's.png); background-repeat: no-repeat;">'; } else if (wfi[i].icon) { html += '<div class="weatherForecastItem" style="background-image: url(' + wfi[i].icon + '); background-repeat: no-repeat;">'; } else if (wfi[i].text) { var code = findCode(wfi[i].text); if (code !== null) { html += '<div class="weatherForecastItem" style="background-image: url(http://l.yimg.com/a/i/us/nws/weather/gr/' + code + 's.png); background-repeat: no-repeat;">'; } else { html += '<div class="weatherForecastItem">'; } } else { html += '<div class="weatherForecastItem">'; } if (wfi[i].day) html += '<div class="weatherForecastDay">' + _translate(wfi[i].day, options.lang, isShort) + '</div>'; if (wfi[i].date) html += '<div class="weatherForecastDate">' + _translate(wfi[i].date, options.lang, isShort) + '</div>'; if (wfi[i].code !== null && _tt[wfi[i].code]) { html += '<div class="weatherForecastText">' + (_tt[wfi[i].code][options.lang] || _tt[wfi[i].code]['en']) + '</div>'; } else if (wfi[i].text) { var code = findCode(wfi[i].text); if (code !== null) wfi[i].text = _tt[code][options.lang] || _tt[code]['en']; html += '<div class="weatherForecastText">' + _(wfi[i].text) + '</div>'; } if (isShort) { if (wfi[i].low !== null) html += '<div class="weatherForecastRange">' + wfi[i].low + '&deg;-' + wfi[i].high + '&deg;</div>'; } else { if (wfi[i].low !== null) html += '<div class="weatherForecastRange">' + _translate('Temperature', options.lang) + ': '+ wfi[i].low + '&deg;-' + wfi[i].high + '&deg;</div>'; } html += '</div>'; } html += '</div>' } if (options.link) html += '<div class="weatherLink"><a href="'+ feed.link +'" target="'+ options.linktarget +'" title="'+_translate('Read full forecast', options.lang)+'">'+_translate('Full forecast', options.lang)+'</a></div>'; } else { html = '<div class="weatherItem ' + row + '">'; html += '<div class="weatherError">' + _translate('City not found', options.lang) + '</div>'; } html += '</div>'; // Alternate row classes if (row == 'odd') { row = 'even'; } else { row = 'odd'; } $e.append(html); if (typeof options.rendered === 'function') options.rendered(); if (options.resizable && !$e.data('inited')) { $e.data('inited', true); $e.resizable().resize(function() { var timer = $e.data('timer'); if (timer) clearTimeout(timer); $e.data('timer', setTimeout ( function () { $e.data('timer', null); options.width = $e.width(); options.height = $e.height(); _process($e[0], options); }, 1000)); }); } } // Get time string as date function _getTimeAsDate (t) { return new Date(new Date().toDateString() + ' ' + t); } $.fn.weatherfeed = function (locations, _options, fn) { if (typeof _options === 'string') { if (_options === 'update') { return this.each(function () { this.feed = fn; _process(this); }); } return; } // Set plugin defaults var defaults = { unit: 'c', image: true, country: false, highlow: true, wind: true, humidity: false, visibility: false, sunrise: false, sunset: false, forecast: false, link: true, showerror: true, linktarget: '_blank', woeid: false, lang: 'en', update: 60 // minutes }; var options = $.extend(defaults, _options); // Functions return this.each(function (i, e) { var $e = $(e); $e.data('options', options); console.log($e.attr('id')); // Add feed class to user div if (!$e.hasClass('weatherFeed')) $e.addClass('weatherFeed'); // Check and append locations if (!options.custom && !$.isArray(locations)) return false; if (!options.custom) { var _requestData = function () { var count = locations.length; if (count > 10) count = 10; var locationid = ''; for (var i = 0; i < count; i++) { if (locationid != '') locationid += ','; locationid += "'" + locations[i] + "'"; } // Cache results for an hour to prevent overuse var now = new Date(); // Select location ID type var queryType = options.woeid ? 'woeid' : 'location'; // Create Yahoo Weather feed API address var query = "select * from weather.forecast where " + queryType + " in (" + locationid + ") and u='" + options.unit + "'"; var protocol = window.location.protocol; if (protocol !== 'http:' && protocol !== 'https:') protocol = 'https:'; var api = protocol + '//query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&rnd=' + now.getFullYear() + now.getMonth() + now.getDay() + now.getHours() +'&format=json&callback=?'; // Send request $.ajax({ type: 'GET', url: api, dataType: 'json', context: $e, success: function (data) { if (data.query && data.query.results) { this[0].feed = data.query.results.channel; if (data.query.results.channel && data.query.results.channel.length > 0 ) { // Multiple locations var result = data.query.results.channel.length; for (var i = 0; i < result; i++) { // Create weather feed item _process(e, options); } } else { // Single location only _process(e, options); } // Optional user callback function if ($.isFunction(fn)) fn.call(this,$e); } else { console.error('Got answer: ' + JSON.stringify(data)); if (options.showerror) $e.html('<p>Weather information unavailable</p>'); } }, error: function (err) { console.error('Got error: ' + JSON.stringify(err)); if (options.showerror) $e.html('<p>Weather request failed</p>'); } }); }; this.startUpdater = function () { _requestData(); if (options.update > 0){ var that = this; setTimeout(function () { that.startUpdater(); }, options.update * 60000); } }; } if (this.startUpdater) this.startUpdater(); }); }; })(jQuery);
45.959627
265
0.42736
c132d707c645c5c076ff3dcfaf07f05d07cbdb49
901
js
JavaScript
src/citizenapp/src/Utils/fakeGlucose.js
helsenorge/pasientdata
69bc31db1874d113af4096ce60a2767a3e4c598b
[ "MIT" ]
null
null
null
src/citizenapp/src/Utils/fakeGlucose.js
helsenorge/pasientdata
69bc31db1874d113af4096ce60a2767a3e4c598b
[ "MIT" ]
1
2021-01-21T15:19:36.000Z
2021-01-21T15:19:36.000Z
src/citizenapp/src/Utils/fakeGlucose.js
helsenorge/pasientdata2019
69bc31db1874d113af4096ce60a2767a3e4c598b
[ "MIT" ]
1
2019-08-07T10:09:25.000Z
2019-08-07T10:09:25.000Z
import moment from "moment"; function FakeGlucoseData() { let start = []; let end = []; let value = []; let data = []; const period = 10; let currX; const interval = 8; const mean = 9; const sum = 15; const dataLength = 2000; for (let i = 0; i < dataLength; i++) { currX = i / period; start.push( moment() .subtract(i, "minutes") .format("YYYY-MM-DDTHH:mm:ss") ); end.push( moment() .subtract(i - 1, "minutes") .format("YYYY-MM-DDTHH:mm:ss") ); value.push( ((Math.sin(currX) + 5 * Math.sin(2 * currX) + 3 * Math.sin(8 * currX) + 4 * Math.sin(10 * currX) + 3 * Math.cos(0.05 * currX)) / sum) * interval + mean ); data.push({ start: start[i], end: end[i], value: value[i] }); } return data.reverse(); } export default FakeGlucoseData;
20.477273
65
0.510544
c132dec788bb89aec97123a5fda0ef003394a111
257
js
JavaScript
react-admin-dashboard/src/App.js
yetabalij/react-admin-dashboard
232f48136f290281058228ff31dfd543154d367d
[ "MIT" ]
null
null
null
react-admin-dashboard/src/App.js
yetabalij/react-admin-dashboard
232f48136f290281058228ff31dfd543154d367d
[ "MIT" ]
null
null
null
react-admin-dashboard/src/App.js
yetabalij/react-admin-dashboard
232f48136f290281058228ff31dfd543154d367d
[ "MIT" ]
null
null
null
import { Topbar } from "./components/topbar/Topbar"; import { MainContainer } from "./components/container/MainContainer"; function App() { return ( <div className="App"> <Topbar /> <MainContainer /> </div> ); } export default App;
19.769231
69
0.634241
c13327815abf977ba5db8f29a24829ed12275b42
48
js
JavaScript
src/exceptions/index.js
med499/contact-vue-project
e27adae4ca42114344a173dfa670f7e23783a861
[ "MIT" ]
null
null
null
src/exceptions/index.js
med499/contact-vue-project
e27adae4ca42114344a173dfa670f7e23783a861
[ "MIT" ]
null
null
null
src/exceptions/index.js
med499/contact-vue-project
e27adae4ca42114344a173dfa670f7e23783a861
[ "MIT" ]
null
null
null
export const HTTP_EXCEPTION = "HTTP_EXCEPTION";
24
47
0.8125
c133d54d181351693f070b4eccb4717e598aa159
10,878
js
JavaScript
tools/test/wish-rpc-large-reply.js
ControlThings/mist-node-api-node
09f05bb63f6b0eae77d0ade681311754a05932c7
[ "Apache-2.0" ]
null
null
null
tools/test/wish-rpc-large-reply.js
ControlThings/mist-node-api-node
09f05bb63f6b0eae77d0ade681311754a05932c7
[ "Apache-2.0" ]
null
null
null
tools/test/wish-rpc-large-reply.js
ControlThings/mist-node-api-node
09f05bb63f6b0eae77d0ade681311754a05932c7
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2020, ControlThings Oy Ab * * 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 * * @license Apache-2.0 */ var Mist = require('../../index.js').Mist; var MistNode = require('../../index.js').MistNode; var WishApp = require('../../index.js').WishApp; var util = require('./deps/util.js'); var inspect = require('util').inspect; const testBlobSize = 130*1024; //MIST_RPC_REPLY_BUF_LEN in mist_app.h must allow this, and of course wish-core-client and the wish core must be able to handle RPC data spanning over multiple TCP transport frames /** * This test will test behaviour of wish-rpc, when very large blobs of data are sent over wish-rpc in reply to a mist control.read. * By "very large" we mean blobs of any size that are larger than MIST_RPC_REPLY_BUF_LEN. Also think about the WISH_PORT_RPC_BUFFER_SZ in wish-core */ describe('Mist sending a large blob of data over wish-rpc', function () { var mist; var mistIdentity; var app1; before(function(done) { console.log('before 1'); app1 = new WishApp({ name: 'PeerTester1', protocols: ['test'], corePort: 9095 }); // , protocols: [] }); setTimeout(done, 200); app1.on('ready', () => { app1.request('signals', [], (err, data) => { console.log("app1 wish signals", data); /* Friend request acceptor for the situation where remote core asks for data */ if (data && data[0] === 'friendRequest') { app1.request('identity.friendRequestList', [], (err, list) => { //console.log("identity.friendRequestList", list); if (!list[0]) { return; } app1.request('identity.friendRequestAccept', [list[0].luid, list[0].ruid], (err, data) => { //console.log("friendRequestAccept cb", err, data); }); }); } }); }); }); before(function(done) { util.clear(app1, done); }); var name1 = 'Alice'; before(function(done) { util.ensureIdentity(app1, name1, function(err, identity) { if (err) { done(new Error('util.js: Could not ensure identity.')); } mistIdentity = identity; done(); }); }); before('start a mist api', function(done) { mist = new Mist({ name: 'MistApi', corePort: 9095 }); // , coreIp: '127.0.0.1', corePort: 9095 setTimeout(done, 200); }); var peer; var end = false; var node; var enabled = true; before('should start a mist node', function(done) { node = new MistNode({ name: 'ControlThings', corePort: 9095 }); // , coreIp: '127.0.0.1' node.addEndpoint('mist', { type: 'string' }); node.addEndpoint('mist.name', { label: 'Name', type: 'string', read: true, write: true }); node.addEndpoint('largeDataBlob', { label: 'A large blob of data', type: 'string', read: function(args, peer, cb) { //cb(null, { code: 6, msg: 'Read says no.' }); var largeBuffer = new Buffer(testBlobSize); cb(null, largeBuffer); } }); setTimeout(done, 200); }); before('should find the peer', function(done) { this.timeout(10*1000); function peers(err, data) { //console.log('==========================', data, mistIdentity); for(var i in data) { if ( Buffer.compare(data[i].luid, mistIdentity.uid) === 0 && Buffer.compare(data[i].ruid, mistIdentity.uid) === 0 ) { if (!data[i] || !data[i].online) { console.log('peer -- but not online'); return; } peer = data[0]; //console.log("The peers is:", peer); done(); done = function() {}; break; } } } mist.request('signals', [], function(err, signal) { //console.log('signal:', err, signal); if( Array.isArray(signal) ) { signal = signal[0]; } if (signal === 'peers') { mist.request('listPeers', [], peers); } }); mist.request('listPeers', [], peers); }); it('should check identity in core', function (done) { node.wish.request('identity.list', [], function(err, data) { if (err) { return done(new Error('wish rpc returned error')); } //console.log("got the identity list", err, data); done(); }); }); it('shuold test control.read, large reply, service requesting from itself', function(done) { //this.timeout(10*1000); /* Make a request to an other */ node.request(peer, "control.read", ["largeDataBlob"], function (err, value) { if (err) { return done(new Error(inspect(value))); } //console.log("Got counter value:", err, value); if (typeof value === 'object' && value.length === testBlobSize) { //console.log("Got:", value) done(); } else { done(new Error('Value type is unexpected: ' + typeof value)); } }); }); it('shuold test control.read, large reply from a mist-api app on local core', function(done) { //this.timeout(10*1000); mist.request('mist.control.read', [peer, 'largeDataBlob'], function (err, value) { if (err) { return done(new Error(inspect(value))); } //console.log("Got counter value:", err, value); if (typeof value === 'object' && value.length === testBlobSize) { //console.log("Got:", value) done(); } else { done(new Error('Value type is unexpected: ' + typeof value)); } }); }); var name2 = "Tester number 2"; var remoteIdentity; var app2; var mist2; var peer2; before(function(done) { console.log('before 2'); app2 = new WishApp({ name: 'PeerTester2', protocols: ['test'], corePort: 9096 }); // , protocols: [] }); setTimeout(done, 200); }); before(function(done) { util.ensureIdentity(app2, name2, function(err, identity) { if (err) { done(new Error('util.js: Could not ensure identity.')); } remoteIdentity = identity; done(); }); }); before('start a mist api this time on other core', function(done) { this.timeout(10*1000); mist2 = new Mist({ name: 'MistApi tester 2', corePort: 9096 }); // , coreIp: '127.0.0.1', corePort: 9095 mist2.request('signals', [], (err, data) => { function doWldList() { mist2.wish.request("wld.list", [], (err, wldList) => { //console.log("wldList ", wldList); if (!wldList) { } for (entry of wldList) { if (Buffer.compare(mistIdentity.uid, entry.ruid) === 0) { mist2.wish.request("wld.friendRequest", [remoteIdentity.uid, entry.ruid, entry.rhid], (err, data) => { console.log("Sent the friend request", err, data); done(); done = function() {}; doWldList = function() {}; }); } } }); } if (data && data[0]=== 'ready') { doWldList(); } if (data && data[0] === 'localDiscovery') { doWldList(); } }); }); before('should find the peer on other core', function(done) { this.timeout(10*1000); function peers(err, data) { //console.log('==========================', data, mistIdentity); for(var i in data) { //console.log("peers2", data[i].rsid.toString(), Buffer.compare(data[i].luid, remoteIdentity.uid), Buffer.compare(data[i].ruid, mistIdentity.uid)) if ( Buffer.compare(data[i].luid, remoteIdentity.uid) === 0 && Buffer.compare(data[i].ruid, mistIdentity.uid) === 0) { if (!data[i] || !data[i].online) { console.log('peer -- but not online'); return; } /* Get model of the peer candidate in order to distinguish it form the other MistApi running on core (port 9095) */ ((peerCandidate) => { mist2.request('mist.control.model', [peerCandidate], function (err, model) { //console.log("model:", model); if (model.largeDataBlob) { peer2 = peerCandidate; //console.log("The peers2 is:", peer); done(); done = function() {}; } }); })(data[i]); } } } mist2.request('signals', [], function(err, signal) { //console.log('signal2:', err, signal); if( Array.isArray(signal) ) { signal = signal[0]; } if (signal === 'peers') { mist2.request('listPeers', [], peers); } }); mist2.request('listPeers', [], peers); }); it('shuold test control.read, large reply from a mist-api app on other core', function(done) { //this.timeout(10*1000); mist2.request('mist.control.read', [peer2, 'largeDataBlob'], function (err, value) { if (err) { return done(new Error(inspect(value))); } //console.log("Got counter value:", err, value); if (typeof value === 'object' && value.length === testBlobSize) { //console.log("Got:", value) done(); } else { done(new Error('Value type is unexpected: ' + typeof value)); } }); }); });
37.770833
211
0.47619
c1346d0beb973d2a2a718e6668833ab4c644cc57
8,945
js
JavaScript
docs/cpp_linear/search/enumvalues_9.js
AlohaChina/or-tools
1ece0518104db435593a1a21882801ab6ada3e15
[ "Apache-2.0" ]
8,273
2015-02-24T22:10:50.000Z
2022-03-31T21:19:27.000Z
docs/cpp_linear/search/enumvalues_9.js
AlohaChina/or-tools
1ece0518104db435593a1a21882801ab6ada3e15
[ "Apache-2.0" ]
2,530
2015-03-05T04:27:21.000Z
2022-03-31T06:13:02.000Z
docs/cpp_linear/search/enumvalues_9.js
AlohaChina/or-tools
1ece0518104db435593a1a21882801ab6ada3e15
[ "Apache-2.0" ]
2,057
2015-03-04T15:02:02.000Z
2022-03-30T02:29:27.000Z
var searchData= [ ['model_5finvalid_0',['MODEL_INVALID',['../classoperations__research_1_1_m_p_solver.html#a573d479910e373f5d771d303e440587dae071e79c23f061c9dd00ee09519a0031',1,'operations_research::MPSolver']]], ['model_5fsynchronized_1',['MODEL_SYNCHRONIZED',['../classoperations__research_1_1_m_p_solver_interface.html#a98638775910339c916ce033cbe60257da22054edb527b75998eccfbfd075dbd92',1,'operations_research::MPSolverInterface']]], ['mpmodelrequest_5fsolvertype_5fbop_5finteger_5fprogramming_2',['MPModelRequest_SolverType_BOP_INTEGER_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689af523c539a31bee5db12cd7566af59a40',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fcbc_5fmixed_5finteger_5fprogramming_3',['MPModelRequest_SolverType_CBC_MIXED_INTEGER_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689a2ff8af502bfbbc76836bd658144b4f8a',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fclp_5flinear_5fprogramming_4',['MPModelRequest_SolverType_CLP_LINEAR_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689a4d77685d54eb87c232beed1e460c5aaa',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fcplex_5flinear_5fprogramming_5',['MPModelRequest_SolverType_CPLEX_LINEAR_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689ac40195f69d9c078b3f2249221baa4a0e',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fcplex_5fmixed_5finteger_5fprogramming_6',['MPModelRequest_SolverType_CPLEX_MIXED_INTEGER_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689aeb076e6845a57af474212cd24d9de85c',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fglop_5flinear_5fprogramming_7',['MPModelRequest_SolverType_GLOP_LINEAR_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689a162575d5bea8a8393ff4d9fc11275ec3',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fglpk_5flinear_5fprogramming_8',['MPModelRequest_SolverType_GLPK_LINEAR_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689a7a5586fa6b3f31587894d20b33ebd8bf',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fglpk_5fmixed_5finteger_5fprogramming_9',['MPModelRequest_SolverType_GLPK_MIXED_INTEGER_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689a85fa72a05039663be93853d86e3c174c',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fgurobi_5flinear_5fprogramming_10',['MPModelRequest_SolverType_GUROBI_LINEAR_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689a1ccff29cebf50c35a55f15b83fbbae32',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fgurobi_5fmixed_5finteger_5fprogramming_11',['MPModelRequest_SolverType_GUROBI_MIXED_INTEGER_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689aad4dc18cf5fd6463aa0b26440f23a8b1',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fknapsack_5fmixed_5finteger_5fprogramming_12',['MPModelRequest_SolverType_KNAPSACK_MIXED_INTEGER_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689afdb40bacb05f8e852322924fb3597433',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fsat_5finteger_5fprogramming_13',['MPModelRequest_SolverType_SAT_INTEGER_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689a5985a25f8da9d50c769a78025b9fb0bf',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fscip_5fmixed_5finteger_5fprogramming_14',['MPModelRequest_SolverType_SCIP_MIXED_INTEGER_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689a16663d704b6e0b28605e998a6bd36164',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fxpress_5flinear_5fprogramming_15',['MPModelRequest_SolverType_XPRESS_LINEAR_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689a25de47e453fa0175e7d254c61e75c847',1,'operations_research']]], ['mpmodelrequest_5fsolvertype_5fxpress_5fmixed_5finteger_5fprogramming_16',['MPModelRequest_SolverType_XPRESS_MIXED_INTEGER_PROGRAMMING',['../namespaceoperations__research.html#ac417714eb4dbaf83717bb2aa9affc689a5343614c63eb3585cf34d7f48c30d9de',1,'operations_research']]], ['mpsolver_5fabnormal_17',['MPSOLVER_ABNORMAL',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1baf6f49dcf49ad7df71d2e5b5f2c81ff88',1,'operations_research']]], ['mpsolver_5fcancelled_5fby_5fuser_18',['MPSOLVER_CANCELLED_BY_USER',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1ba44a70f17e7bb4d99a6635673a0447074',1,'operations_research']]], ['mpsolver_5ffeasible_19',['MPSOLVER_FEASIBLE',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1badbeb0b2ee95779317b20e5876609bf04',1,'operations_research']]], ['mpsolver_5fincompatible_5foptions_20',['MPSOLVER_INCOMPATIBLE_OPTIONS',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1baaf7b72c19d9cf5d0231a5a84f809e1fc',1,'operations_research']]], ['mpsolver_5finfeasible_21',['MPSOLVER_INFEASIBLE',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1ba12a89c0e1b72e6c40e8c0ed16afa48a6',1,'operations_research']]], ['mpsolver_5fmodel_5finvalid_22',['MPSOLVER_MODEL_INVALID',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1ba5d004f74784501a516258dff6b7740ec',1,'operations_research']]], ['mpsolver_5fmodel_5finvalid_5fsolution_5fhint_23',['MPSOLVER_MODEL_INVALID_SOLUTION_HINT',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1badcf1ef4c6880afe0aeb3e0c80a9dd4e9',1,'operations_research']]], ['mpsolver_5fmodel_5finvalid_5fsolver_5fparameters_24',['MPSOLVER_MODEL_INVALID_SOLVER_PARAMETERS',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1bae98571c24fbf68a473b3d93ca45c6e7a',1,'operations_research']]], ['mpsolver_5fmodel_5fis_5fvalid_25',['MPSOLVER_MODEL_IS_VALID',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1ba81239917bc019f71d9f78b550c6acf37',1,'operations_research']]], ['mpsolver_5fnot_5fsolved_26',['MPSOLVER_NOT_SOLVED',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1ba3955ab5aa529fab85eb3566271a043e2',1,'operations_research']]], ['mpsolver_5foptimal_27',['MPSOLVER_OPTIMAL',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1ba9cff14a44a54cc44f4b91d65e8cd73b1',1,'operations_research']]], ['mpsolver_5fsolver_5ftype_5funavailable_28',['MPSOLVER_SOLVER_TYPE_UNAVAILABLE',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1bacd2f1efd0290a03172495d05d131cbfe',1,'operations_research']]], ['mpsolver_5funbounded_29',['MPSOLVER_UNBOUNDED',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1ba4b81d5eafe0b99411fc94d676bc286db',1,'operations_research']]], ['mpsolver_5funknown_5fstatus_30',['MPSOLVER_UNKNOWN_STATUS',['../namespaceoperations__research.html#aeaeaf340789f2dd271dcf9204279cb1ba55c6337c519b0ef4070cfe89dead866f',1,'operations_research']]], ['mpsolvercommonparameters_5flpalgorithmvalues_5flp_5falgo_5fbarrier_31',['MPSolverCommonParameters_LPAlgorithmValues_LP_ALGO_BARRIER',['../namespaceoperations__research.html#a8913360b55a9b9861237e0ad039f6979a3615540cdf96dce3f3ca1c2c05c6d434',1,'operations_research']]], ['mpsolvercommonparameters_5flpalgorithmvalues_5flp_5falgo_5fdual_32',['MPSolverCommonParameters_LPAlgorithmValues_LP_ALGO_DUAL',['../namespaceoperations__research.html#a8913360b55a9b9861237e0ad039f6979a533fac70679c30c889a2f75a7e46170e',1,'operations_research']]], ['mpsolvercommonparameters_5flpalgorithmvalues_5flp_5falgo_5fprimal_33',['MPSolverCommonParameters_LPAlgorithmValues_LP_ALGO_PRIMAL',['../namespaceoperations__research.html#a8913360b55a9b9861237e0ad039f6979af3259b56473cfb82c63b503b80efd283',1,'operations_research']]], ['mpsolvercommonparameters_5flpalgorithmvalues_5flp_5falgo_5funspecified_34',['MPSolverCommonParameters_LPAlgorithmValues_LP_ALGO_UNSPECIFIED',['../namespaceoperations__research.html#a8913360b55a9b9861237e0ad039f6979a18a46e7e7a130a3a38c7915f577301c2',1,'operations_research']]], ['mpsosconstraint_5ftype_5fsos1_5fdefault_35',['MPSosConstraint_Type_SOS1_DEFAULT',['../namespaceoperations__research.html#a7f0aabaee920119f0b683ba887250f0bae59773cfdb0c5a52b6dafc8b9c853ae6',1,'operations_research']]], ['mpsosconstraint_5ftype_5fsos2_36',['MPSosConstraint_Type_SOS2',['../namespaceoperations__research.html#a7f0aabaee920119f0b683ba887250f0ba29baea5082ad9cfbd015d2e0f04a80f1',1,'operations_research']]], ['must_5freload_37',['MUST_RELOAD',['../classoperations__research_1_1_m_p_solver_interface.html#a98638775910339c916ce033cbe60257daa99c5e45f0517571611940811f09c744',1,'operations_research::MPSolverInterface']]] ];
212.97619
280
0.883846
c1349eabd09639ab42547f15e0bc248cf579fe1c
133
js
JavaScript
exercicios/ex006/f05.js
brenoedl0/JavaScript
f1cea38cc42d6b07523f2d18686600ac5d30e414
[ "MIT" ]
null
null
null
exercicios/ex006/f05.js
brenoedl0/JavaScript
f1cea38cc42d6b07523f2d18686600ac5d30e414
[ "MIT" ]
null
null
null
exercicios/ex006/f05.js
brenoedl0/JavaScript
f1cea38cc42d6b07523f2d18686600ac5d30e414
[ "MIT" ]
null
null
null
function fatoriaal(n){ if(n == 1){ return 1 }else{ return n* fatoriaal(n-1) } } console.log(fatoriaal(5))
16.625
32
0.533835
c134bf8a9cab771f6b12451f961fe6885f9f2268
1,407
js
JavaScript
PPD/src/components/Testimonial/Testimonial.js
alphiek/PPD
cd361ee9a425d7fc49bb0ae8303dbdf9e60179a5
[ "MIT" ]
null
null
null
PPD/src/components/Testimonial/Testimonial.js
alphiek/PPD
cd361ee9a425d7fc49bb0ae8303dbdf9e60179a5
[ "MIT" ]
5
2021-03-09T18:46:21.000Z
2022-02-18T11:29:32.000Z
PPD/src/components/Testimonial/Testimonial.js
alphiek/PPD
cd361ee9a425d7fc49bb0ae8303dbdf9e60179a5
[ "MIT" ]
1
2019-11-23T21:44:48.000Z
2019-11-23T21:44:48.000Z
import React from "react"; import styled from "styled-components"; import { colors } from "../Utils/colors"; import quotes from "../../images/quotes.png"; import quotesbottom from "../../images/quotesbottom.png"; export const Testimonial = () => { return ( <Section> <Top src={quotes} alt="opening quotation marks" /> <Text> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </Text> <Bottom src={quotesbottom} alt="closing quotation marks" /> </Section> ); }; const Section = styled.section` width: 100%; height: 40vh; background-color: ${colors.black}; color: white; display: flex; align-items: center; position: relative; `; const Text = styled.p` color: white; text-align: center; margin: 0 auto; width: 50%; `; const Top = styled.img` position: absolute; top: 2rem; left: 20%; width: 10%; @media (max-width: 1180px) { left: 10%; width: 15%; } @media (max-width: 660px) { left: 5%; } `; const Bottom = styled.img` position: absolute; bottom: 2rem; right: 20%; width: 10%; @media (max-width: 1180px) { right: 10%; width: 15%; } @media (max-width: 660px) { right: 5%; } `;
21.318182
79
0.626155
c1352181e8c3247e0525ab2f1de43a2a3644daa3
3,315
js
JavaScript
build/static/js/main.99bf9421.chunk.js
swhachey/reactive_employee_manager
9db9e9858fd2de5d311fa81dcb3b661df1742fd3
[ "ISC" ]
null
null
null
build/static/js/main.99bf9421.chunk.js
swhachey/reactive_employee_manager
9db9e9858fd2de5d311fa81dcb3b661df1742fd3
[ "ISC" ]
null
null
null
build/static/js/main.99bf9421.chunk.js
swhachey/reactive_employee_manager
9db9e9858fd2de5d311fa81dcb3b661df1742fd3
[ "ISC" ]
null
null
null
(this.webpackJsonpempire=this.webpackJsonpempire||[]).push([[0],{24:function(e,t,n){},45:function(e,t,n){"use strict";n.r(t);var c=n(2),r=n(12),a=n.n(r),s=(n(24),n(0));var i=function(){return Object(s.jsxs)("div",{className:"jumbotron",children:[Object(s.jsx)("h1",{children:"EMPIRE"}),Object(s.jsx)("h3",{children:"Organize your empire and take over the world."})]})},l=n(17),o=n(13),h=n(14),j=n(15),u=n(19),d=n(18);var b=function(e){return Object(s.jsxs)("tr",{className:"table-info",children:[Object(s.jsx)("th",{scope:"row",children:e.id+1}),Object(s.jsx)("td",{children:e.first}),Object(s.jsx)("td",{children:e.last}),Object(s.jsx)("td",{children:e.email}),Object(s.jsx)("td",{children:e.city}),Object(s.jsx)("td",{children:e.phone})]})};var m=function(e){return Object(s.jsxs)("table",{className:"table",children:[Object(s.jsx)("thead",{children:Object(s.jsxs)("tr",{className:"table-primary",children:[Object(s.jsx)("th",{scope:"col",children:"#"}),Object(s.jsx)("th",{scope:"col",children:"First"}),Object(s.jsx)("th",{scope:"col",children:"Last"}),Object(s.jsx)("th",{scope:"col",children:"Email"}),Object(s.jsx)("th",{scope:"col",children:"City"}),Object(s.jsx)("th",{scope:"col",children:"Phone"})]})}),Object(s.jsx)("tbody",{children:e.result.map((function(e){return Object(s.jsx)(b,{first:e.firstName,last:e.lastName,email:e.email,phone:e.phone,city:e.city,photo:e.picture,id:e.id},e.key)}))})]})},p=n(16),O=n.n(p),x=function(e){return O.a.get("https://randomuser.me/api/?results="+e)};var f=function(e){return Object(s.jsx)("form",{children:Object(s.jsxs)("div",{className:"form-group",children:[Object(s.jsx)("label",{htmlFor:"search",children:"How Many Results?:"}),Object(s.jsx)("input",{onChange:e.handleInputChange,value:e.value,name:"search",type:"text",className:"form-control",placeholder:"How many employees?",id:"search"}),Object(s.jsx)("br",{}),Object(s.jsx)("button",{onClick:e.handleFormSubmit,className:"btn btn-primary",children:"Search"})]})})},y=function(e){Object(u.a)(n,e);var t=Object(d.a)(n);function n(){var e;Object(h.a)(this,n);for(var c=arguments.length,r=new Array(c),a=0;a<c;a++)r[a]=arguments[a];return(e=t.call.apply(t,[this].concat(r))).state={result:[],search:""},e.getEmployees=function(t){x(t).then((function(t){return e.setState({result:t.data.results.map((function(e,t){return{firstName:e.name.first,lastName:e.name.last,picture:e.picture.large,email:e.email,phone:e.phone,city:e.location.city,id:t,key:t}}))})})).catch((function(e){return console.log(e)}))},e.handleInputChange=function(t){var n=t.target.value,c=t.target.name;e.setState(Object(o.a)({},c,n))},e.handleFormSubmit=function(t){t.preventDefault(),e.getEmployees(e.state.search)},e}return Object(j.a)(n,[{key:"componentDidMount",value:function(){this.getEmployees(10)}},{key:"render",value:function(){return Object(s.jsxs)("div",{className:"container",children:[Object(s.jsx)(f,{value:this.state.search,handleInputChange:this.handleInputChange,handleFormSubmit:this.handleFormSubmit}),Object(s.jsx)(m,{result:Object(l.a)(this.state.result)})]})}}]),n}(c.Component);var v=function(){return Object(s.jsxs)(s.Fragment,{children:[Object(s.jsx)(i,{}),Object(s.jsx)(y,{})]})};n(44);a.a.render(Object(s.jsx)(v,{}),document.getElementById("root"))}},[[45,1,2]]]); //# sourceMappingURL=main.99bf9421.chunk.js.map
1,657.5
3,267
0.696531
c1353c0d6d0346db3300e2b72a1097c8fa740150
401
js
JavaScript
tests/perf/test-closure-inner-functions.js
wenq1/duktape
5ed3eee19b291f3b3de0b212cc62c0aba0ab4ecb
[ "MIT" ]
4,268
2015-01-01T17:33:40.000Z
2022-03-31T17:53:31.000Z
tests/perf/test-closure-inner-functions.js
GyonGyon/duktape
3f732345c745059d1d7307b17b5b8d070e9609e9
[ "MIT" ]
1,667
2015-01-01T22:43:03.000Z
2022-02-23T22:27:19.000Z
tests/perf/test-closure-inner-functions.js
GyonGyon/duktape
3f732345c745059d1d7307b17b5b8d070e9609e9
[ "MIT" ]
565
2015-01-08T14:15:28.000Z
2022-03-31T16:29:31.000Z
function test() { var src = []; var i; var fun; src.push('(function outer() {'); for (i = 0; i < 100; i++) { src.push(' function inner' + i + '() {}'); } src.push('})'); //print(src.join('\n')); fun = eval(src.join('\n')); for (i = 0; i < 1e4; i++) { fun(); } } try { test(); } catch (e) { print(e.stack || e); throw e; }
15.423077
53
0.394015
c136877d54dca1c01e8ee6e6cfe68238a16ae2c8
13,298
js
JavaScript
build/ti-selector.js
kchapelier/ti-selector
3fe2c25196ee0ca80f6ffe9dac64e9ab5189c467
[ "MIT" ]
2
2015-11-21T11:14:02.000Z
2015-12-10T07:01:14.000Z
build/ti-selector.js
kchapelier/ti-selector
3fe2c25196ee0ca80f6ffe9dac64e9ab5189c467
[ "MIT" ]
null
null
null
build/ti-selector.js
kchapelier/ti-selector
3fe2c25196ee0ca80f6ffe9dac64e9ab5189c467
[ "MIT" ]
null
null
null
/** * ti-selector * * Simple selector for Titanium's native view elements. * * Author: Kevin Chapelier * Version: 1.0.0 * License: MIT * Repository: https://github.com/kchapelier/ti-selector.git */ (function() { "use strict"; var operators = (function () { var list = { 'match-tag': function (actual, expected) { actual = actual.substr(actual.lastIndexOf('.') + 1); return (actual.toLowerCase() === expected.toLowerCase()); }, '=': function (actual, expected) { return (actual === expected); }, '!=': function (actual, expected) { return (actual !== expected); }, '~=': function (actual, expected) { return (' ' + actual + ' ').indexOf(' ' + expected + ' ') > -1; }, '|=': function (actual, expected) { return (actual === expected) | (actual.indexOf(expected + '-') === 0); }, '^=': function (actual, expected) { return (actual.indexOf(expected) === 0); }, '$=': function (actual, expected) { return (actual.lastIndexOf(expected) === actual.length - expected.length); }, '*=': function (actual, expected) { return (actual.indexOf(expected) > -1); } }; var operators = function (operator, actual, expected) { var result = false, typeActual = typeof actual; if (operator === 'has') { result = (typeof actual !== 'undefined'); } else if ( (typeActual === 'string' || typeActual === 'number') && list.hasOwnProperty(operator) ) { result = !!list[operator](String(actual), String(expected)); } return result; }; return operators; }()); var iterator = (function () { var getChildren = function (element) { var children = []; if (element.children && element.children.length) { children = element.children; } else if (element.apiName === 'Ti.UI.TableView') { if (element.sections && element.sections.length) { children = element.sections; } } else if (element.apiName === 'Ti.UI.TableViewSection') { children = element.rows; } return children; }; var getParents = function (element) { var parents = []; if (element.parent) { parents.push(element.parent); } return parents; }; var getSiblings = function (element) { var siblings = [], parent = getParents(element); if (parent.length) { siblings = getChildren(parent[0]); } return siblings.filter(function (siblingElement) { return siblingElement !== element; }); }; var createWalkFunction = function (baseFunction, iterative) { var self = function (root, func) { var elements = baseFunction(root), element, i; for (i = 0; i < elements.length; i++) { element = elements[i]; if (func(element) === false) { return; } if (iterative) { self(element, func); } } }; return self; }; return { walkParents: createWalkFunction(getParents, true), walkChildren: createWalkFunction(getChildren, true), walkSiblings: createWalkFunction(getSiblings, false) }; }()); var parser = (function () { var tokenizer = function (query) { var position = 0, length = query.length, tokens = []; var allowedCharactersForId = 'azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN1234567890-_'.split(''), allowedCharactersForClassName = allowedCharactersForId, allowedCharactersForTagName = allowedCharactersForId, allowedCharactersForAttribute = allowedCharactersForId, allowedCharactersForoperator = '^$*|!='.split(''), hexadecimalCharacters = 'ABCDEFabcdef0123456789'.split(''); var readBasicSelector = function (property, operator, allowedCharacters) { var value = '', character; while (position < length) { character = query[position]; if (allowedCharacters.indexOf(character) >= 0) { value += character; position++; } else { position--; break; } } return { property: property, operator: operator, value: value }; }; var readTagName = function () { return readBasicSelector('tagname', 'match-tag', allowedCharactersForTagName); }; var readId = function () { return readBasicSelector('id', '=', allowedCharactersForId); }; var readClassName = function () { return readBasicSelector('class', '~=', allowedCharactersForClassName); }; var readQuotedString = function () { var quote = query[position], result = '', escaped = false, escapedToken, character, characterCode; while (position < length) { position++; character = query[position]; if (escaped) { if (hexadecimalCharacters.indexOf(character) > -1 && escapedToken.length < 6) { escapedToken += character; } else { if (escapedToken) { characterCode = parseInt(escapedToken.toString(), 16); result += String.fromCharCode(characterCode); position--; } else { result += character; } escaped = false; } } else { if (character === quote) { break; } else if (character === '\\') { escaped = true; escapedToken = ''; } else { result += character; } } } return result; }; var readAttributeSelector = function () { var property = '', operator = '', value = '', step = 0, //0 : property, 1 : operator, 2 : value character; while (position < length) { character = query[position]; if (character === ']') { break; } if (step === 0) { if (allowedCharactersForAttribute.indexOf(character) >= 0) { property += character; } else { step++; } } if (step === 1) { if (allowedCharactersForoperator.indexOf(character) >= 0) { operator += character; } else { step++; } } if (step === 2) { if (character === '\'' || character === '"') { value = readQuotedString(character); } else { value += character; } } position++; } return { property: property, operator: operator ? operator : 'has', value: value }; }; while (position < length) { var character = query[position]; if (character === '[') { position = position + 1; tokens.push(readAttributeSelector()); } else if (character === '.') { position = position + 1; tokens.push(readClassName()); } else if (character === '#') { position = position + 1; tokens.push(readId()); } else if (allowedCharactersForTagName.indexOf(character) >= 0) { tokens.push(readTagName()); } else { throw new Error('Unexpected character : "' + character + '"'); } position++; } return tokens; }; var parser = function (query) { var ruleSetList = [], individualQueries = query.split(','); individualQueries.forEach(function (individualQuery) { individualQuery = individualQuery.trim(); var ruleSet = tokenizer(individualQuery); if (ruleSet.length > 0) { ruleSetList.push(ruleSet); } }); return ruleSetList; }; return parser; }()); var selector = (function () { var getMatchingFunction = function (query) { var type = typeof query, matchingFunction, ruleSetList; if (type === 'function') { matchingFunction = query; } else if (type === 'string') { ruleSetList = parser(query); matchingFunction = function (element) { var ruleSet, matching, i, j; for (i = 0; i < ruleSetList.length; i++) { ruleSet = ruleSetList[i]; matching = true; for (j = 0; j < ruleSet.length && matching; j++) { var property = ruleSet[j].property, value = ruleSet[j].value, operator = ruleSet[j].operator; if (property === 'class') { property = 'className'; } else if (property === 'tagname') { property = 'apiName'; } matching = operators(operator, element[property], value); } if (matching) { return true; } } return false; }; } else { throw new Error('Unexpected type of query : ' + type); } return matchingFunction; }; var createGetFunction = function (walkingFunction, limit) { return function (root, query) { var queryFunction = getMatchingFunction(query), results = []; walkingFunction(root, function (element) { if (queryFunction(element)) { results.push(element); } if (limit && results.length >= limit) { return false; } }); return limit === 1 ? results[0] : results; }; }; var getElements = createGetFunction(iterator.walkChildren, null), getElement = createGetFunction(iterator.walkChildren, 1), getParents = createGetFunction(iterator.walkParents, null), getParent = createGetFunction(iterator.walkParents, 1), getSiblings = createGetFunction(iterator.walkSiblings, null), getSibling = createGetFunction(iterator.walkSiblings, 1); var selector = getElements; selector.getElements = getElements; selector.getElement = getElement; selector.getParents = getParents; selector.getParent = getParent; selector.getSiblings = getSiblings; selector.getSibling = getSibling; return selector; }()); module.exports = selector; }());
32.593137
118
0.418484
c1371247a3e76af1a309ee4265f6807f9e2aa35e
290
js
JavaScript
lecture_notes/importing_from_other_file.js
nia-ja/notes-app
82ff76a0cc71d15638696007c6d6f462a0decf03
[ "MIT" ]
null
null
null
lecture_notes/importing_from_other_file.js
nia-ja/notes-app
82ff76a0cc71d15638696007c6d6f462a0decf03
[ "MIT" ]
null
null
null
lecture_notes/importing_from_other_file.js
nia-ja/notes-app
82ff76a0cc71d15638696007c6d6f462a0decf03
[ "MIT" ]
null
null
null
// IMPORTing variables const name = require('./exporting_vars_funcs_etc.js'); // will run first -> first output in console console.log(name); // second output in console // IMPORTing functions const add = require('./exporting_vars_funcs_etc.js'); const sum = add(4, -2); console.log(sum);
32.222222
99
0.731034
c1378241f3310e2a5f19b90ee8b84afff69f5aa3
38
js
JavaScript
test/fixtures/string/actual.js
0xflotus/babel-plugin-tcomb
1c97001ec5c9b5fcc63ad2733dfb91e32660efdd
[ "MIT" ]
534
2015-10-03T18:12:01.000Z
2021-05-07T14:07:48.000Z
test/fixtures/string/actual.js
0xflotus/babel-plugin-tcomb
1c97001ec5c9b5fcc63ad2733dfb91e32660efdd
[ "MIT" ]
144
2015-06-03T19:16:28.000Z
2019-11-04T07:14:57.000Z
test/fixtures/string/actual.js
0xflotus/babel-plugin-tcomb
1c97001ec5c9b5fcc63ad2733dfb91e32660efdd
[ "MIT" ]
31
2015-10-22T05:43:57.000Z
2018-09-16T16:17:54.000Z
function foo(x: string) { return x }
12.666667
25
0.657895
c13807e2d2e7b15b1b98c27bdfbfb3ba6d079f91
1,661
js
JavaScript
frontend/src/global.js
jeferson-sb/be-the-hero
49aabd2e4b2101b8c1d52ee2aee2e3d32df1f1da
[ "MIT" ]
1
2020-07-18T04:54:47.000Z
2020-07-18T04:54:47.000Z
frontend/src/global.js
MatteusGuedz/be-the-hero-1
132d254c29ea2dcd95eb83e566213dfe5e7ca70c
[ "MIT" ]
4
2022-01-02T11:28:20.000Z
2022-02-20T01:56:06.000Z
frontend/src/global.js
MatteusGuedz/be-the-hero-1
132d254c29ea2dcd95eb83e566213dfe5e7ca70c
[ "MIT" ]
13
2020-03-29T00:44:40.000Z
2020-10-08T12:17:17.000Z
import { createGlobalStyle } from 'styled-components'; export const GlobalStyle = createGlobalStyle` @import url("https://fonts.googleapis.com/css?family=Roboto:400,500,700&display=swap"); :root { --font-family: 'Roboto', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; --bg-color: #f0f0f5; --primary-color: #e02041; --black: #333; --gray: #dcdce6; } *, *::before, *::after{ box-sizing: border-box; outline: 0; } html{ text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } html, body{ height: 100%; } body{ margin: 0; padding: 0; font: 400 14px var(--font-family); background-color: var(--bg-color); } ul[class], ol[class] { list-style: none; list-style-type: none; } input, button, textarea, select { font: inherit; } a { text-decoration: none; } button{ cursor: pointer; border: 0; } form{ input{ width: 100%; height: 60px; color: var(--black); border: 1px solid var(--gray); border-radius: 8px; padding: 0 24px; box-shadow: 0 0 3px rgba(0, 0, 0, 0.2) inset; } textarea{ width: 100%; resize: vertical; min-height: 140px; color: var(--black); border: 1px solid var(--gray); border-radius: 8px; padding: 16px 24px; box-shadow: 0 0 3px rgba(0, 0, 0, 0.2) inset; line-height: 24px; } input:focus, textarea:focus{ border: 2px solid var(--primary-color); } } `;
20.256098
153
0.583384
c13b615810b5ff4f7f83c8b324ae241461b7311f
680
js
JavaScript
dist/src/migrations/1641700889714-update_user_email_09_01_2021.js
minhhc06/source_backend_JSC
4b87222965714240d31b0126e50e5cb661271806
[ "MIT" ]
null
null
null
dist/src/migrations/1641700889714-update_user_email_09_01_2021.js
minhhc06/source_backend_JSC
4b87222965714240d31b0126e50e5cb661271806
[ "MIT" ]
null
null
null
dist/src/migrations/1641700889714-update_user_email_09_01_2021.js
minhhc06/source_backend_JSC
4b87222965714240d31b0126e50e5cb661271806
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.updateUserEmail090120211641700889714 = void 0; class updateUserEmail090120211641700889714 { constructor() { this.name = 'updateUserEmail090120211641700889714'; } async up(queryRunner) { await queryRunner.query(`ALTER TABLE "user" RENAME COLUMN "phone_number" TO "email"`); } async down(queryRunner) { await queryRunner.query(`ALTER TABLE "user" RENAME COLUMN "email" TO "phone_number"`); } } exports.updateUserEmail090120211641700889714 = updateUserEmail090120211641700889714; //# sourceMappingURL=1641700889714-update_user_email_09_01_2021.js.map
42.5
94
0.75
c13b66be606599ff3846d8950c71fc968ae3b28b
16,579
js
JavaScript
generators/app/index.js
liucaizhong/generator-dsx-misvc
f5511af7911c05874aef72fcf0dea93864c6bb61
[ "MIT" ]
null
null
null
generators/app/index.js
liucaizhong/generator-dsx-misvc
f5511af7911c05874aef72fcf0dea93864c6bb61
[ "MIT" ]
null
null
null
generators/app/index.js
liucaizhong/generator-dsx-misvc
f5511af7911c05874aef72fcf0dea93864c6bb61
[ "MIT" ]
null
null
null
const Generator = require('yeoman-generator') const fs = require('fs-extra') const chalk = require('chalk') const minimist = require('minimist') const path = require('path') const execa = require('execa') const { execSync } = require('child_process') const validateServiceName = require('validate-npm-package-name') const semver = require('semver') const { clearConsole } = require('./utils/logger') const { logWithSpinner, stopSpinner } = require('./utils/spinner') const { hasYarn, hasProjectYarn, hasGit, hasProjectGit } = require('./utils/env') const generateReadme = require('./utils/generateReadme') const generateChangelog = require('./utils/generateChangelog') module.exports = class extends Generator { constructor (args, opts) { super(args, opts) // options this.option('help', { desc: 'Output usage information', alias: 'h', }) this.option('version', { desc: 'Print version', alias: 'v', }) // desc this.desc('create a new microservice powered by dsx-misvc') // arguments this.argument('svcName', { type: String, required: false, desc: 'The name for your new microservice', }) } // private funtion _runSync (command, options = {}) { return execSync(command, Object.assign({ cwd: this.targetDir, stdio: 'inherit', }, options)) } _checkSvcNameExistOrNot () { const argvLen = minimist(process.argv.slice(3))._.length if (!argvLen) { console.error(chalk.red(`\nMissing required argument ${chalk.yellow('<svcName>')}.`)) return false } else { if (argvLen > 1) { console.info(chalk.yellow('\nInfo: You provided more than one argument. The first one will be used as the microservice\'s name, the rest are ignored.')) } return true } } _shouldInitGit (cliOptions) { if (!hasGit()) { return false } // default: true unless already in a git repo return !hasProjectGit(this.cwd) } _shouldInstallDeps (cliOptions, type = 'node') { // force to install dependencies return true } async _getRegistry(packageName) { let info try { info = (await execa('npm', ['info', packageName, '--json'])).stdout } catch(e) { console.log(e) process.exit(1) } return info } _replaceFileContent(filePath, from, to) { try { const fileContent = fs.readFileSync(filePath).toString('utf8') const re = new RegExp(from,'g') const result = fileContent.replace(re, to) fs.writeFileSync(filePath, result, 'utf8') } catch (error) { console.error(error) } } initializing () { // print version number if (this.options.version) { const version = require(`../../package.json`).version console.log(version) process.exit(1) } } async prompting () { // get the name of microservice if (!this._checkSvcNameExistOrNot()) { clearConsole() // check update const current = require(`../../package.json`).version const registry = await this._getRegistry('generator-dsx-misvc') const latest = JSON.parse(registry)['dist-tags']['latest'] if (semver.gt(latest, current)) { let title = chalk.bold.blue(`generator-dsx-misvc v${current}`) let upgradeMessage = `New version available ${chalk.magenta(current)} → ${chalk.green(latest)}` const command = 'npm i -g' upgradeMessage += `\nRun ${chalk.yellow(`${command} generator-dsx-misvc`)} to update!` const upgradeBox = require('boxen')(upgradeMessage, { align: 'center', borderColor: 'green', dimBorder: true, padding: 1 }) title += `\n${upgradeBox}\n` console.log(title) } const { svcName } = await this.prompt([{ name: 'svcName', type: 'input', message: 'Please enter your microservice\'s name:', }]) this.options.svcName = svcName } this.cwd = this.destinationRoot() || process.cwd() this.inCurrent = this.options.svcName === '.' this.serviceName = this.inCurrent ? path.relative('../', this.cwd) : this.options.svcName this.targetDir = path.resolve(this.cwd, this.options.svcName || '.') // validate service name const validResult = validateServiceName(this.serviceName) if (!validResult.validForNewPackages) { console.error(chalk.red(`Invalid microservice name: "${this.serviceName}"`)) validResult.errors && validResult.errors.forEach(err => { console.error(chalk.red.dim(`Error: ${err}`)) }) validResult.warnings && validResult.warnings.forEach(warn => { console.warn(chalk.red.dim(`Warning: ${warn}`)) }) process.exit(1) } // check microservice exist or not if (fs.existsSync(this.targetDir)) { clearConsole() if (this.inCurrent) { const { ok } = await this.prompt([{ name: 'ok', type: 'confirm', message: 'Generate microservice in current directory?', default: true, }]) if (!ok) { process.exit(1) } } else { const { action } = await this.prompt([{ name: 'action', type: 'list', message: `Target directory ${chalk.cyan(this.targetDir)} already exists. Pick an action:`, choices: [{ name: 'Override', value: 'override', }, { name: 'Cancel', value: false, }], }]) if (!action) { process.exit(1) } else { console.log(`\nRemoving ${chalk.cyan(this.targetDir)}...`) await fs.remove(this.targetDir) } } } // ask the users for the application type of microservice // which they want to create clearConsole() const { type } = await this.prompt([{ name: 'type', type: 'list', message: 'Choose the microservice\'s type which you want to create:', choices: [{ name: 'Node', value: 'node', }, { name: 'React', value: 'react', }, { name: 'Vue', value: 'vue', }, { name: 'Python', value: 'python', }], }]) this.cliOptions = Object.assign({}, { type, }) // ask the users if need to install dependencies Object.assign(this.cliOptions, { installDeps: this._shouldInstallDeps(this.options, type), }) if (this.cliOptions.installDeps === undefined) { clearConsole() const { installDeps } = await this.prompt([{ name: 'installDeps', type: 'confirm', message: 'Do you want to install all the dependencies/packages now?', default: false, }]) this.cliOptions.installDeps = installDeps } } configuring () {} default () {} writing () { switch(this.cliOptions.type) { case 'react': execa( 'npx', [ 'create-react-app', this.serviceName, '--use-npm', '--template', 'typescript', ], { stdio: 'inherit', }, ).then(() => { if (fs.existsSync(path.resolve(this.targetDir, 'package.json'))) { // fs.copySync(path.resolve(this.sourceRoot(), this.cliOptions.type, 'template'), // this.targetDir) // enable Eslint and Prettier console.log() logWithSpinner('Enabling Eslint and Prettier...', '🎀') console.log() const useYarn = hasProjectYarn(this.cwd) || hasYarn() this._runSync( `npx install-peerdeps --dev eslint-config-dsx-react`) if (useYarn) { this._runSync('yarn add -D husky lint-staged eclint in-publish safe-publish-latest serve @rescripts/cli @rescripts/rescript-use-babel-config source-map-explorer @pmmmwh/react-refresh-webpack-plugin') } else { this._runSync('npm i -D husky lint-staged eclint in-publish safe-publish-latest serve @rescripts/cli @rescripts/rescript-use-babel-config source-map-explorer @pmmmwh/react-refresh-webpack-plugin') } // update package.json const pkg = fs.readJsonSync(path.resolve(this.targetDir, 'package.json')) if (pkg['eslintConfig']) delete pkg['eslintConfig'] for (let script in pkg.scripts) { if (pkg.scripts[script].includes('react-scripts')) { pkg.scripts[script] = pkg.scripts[script].replace('react-scripts', 'rescripts') } } Object.assign(pkg.scripts, { "prelint": "eclint check $(git ls-files)", "lint": "eslint --report-unused-disable-directives . --ext .ts,.tsx --fix --quiet", "lint:editor": "eclint fix $(git ls-files)", "pretest": "npm run --silent lint", "serve": "serve -s build", "prepare": "(not-in-publish || npm test) && safe-publish-latest", "analyze": "source-map-explorer 'build/static/js/*.js'", }) fs.writeJsonSync(path.resolve(this.targetDir, 'package.json'), pkg, { spaces: 2, }) stopSpinner() console.log('🎉 Successfully enable Eslint and Prettier.') console.log() fs.copySync(path.resolve(this.sourceRoot(), this.cliOptions.type, 'template'), this.targetDir) } }) process.on('SIGINT', () => { fs.removeSync(this.targetDir) }) process.on('SIGTERM', () => { fs.removeSync(this.targetDir) }) break case 'vue': execa( 'npx', [ 'vue', 'create', '-p', path.resolve(this.sourceRoot(), this.cliOptions.type, 'presets.json'), // use npm as default '-m', 'npm', this.serviceName ], { stdio: 'inherit', }, ).then(() => { if (fs.existsSync(path.resolve(this.targetDir, 'package.json'))) { // fs.copySync(path.resolve(this.sourceRoot(), this.cliOptions.type, 'template'), // this.targetDir) // enable Eslint and Prettier console.log() logWithSpinner('Enabling Eslint and Prettier...', '🎀') console.log() const useYarn = hasProjectYarn(this.cwd) || hasYarn() this._runSync( `npx install-peerdeps --dev eslint-config-dsx-vue`) if (useYarn) { this._runSync('yarn add -D husky lint-staged eclint in-publish safe-publish-latest eslint-import-resolver-webpack serve') } else { this._runSync('npm i -D husky lint-staged eclint in-publish safe-publish-latest eslint-import-resolver-webpack serve') } // update package.json const pkg = fs.readJsonSync(path.resolve(this.targetDir, 'package.json')) Object.assign(pkg.scripts, { "prelint": "eclint check $(git ls-files)", "lint": "eslint --report-unused-disable-directives . --ext .ts,.tsx,.vue --fix --quiet", "lint:editor": "eclint fix $(git ls-files)", "pretest": "npm run --silent lint", "test": "npm run --silent test:unit", "serve": "serve -s dist", "prepare": "(not-in-publish || npm test) && safe-publish-latest" }) fs.writeJsonSync(path.resolve(this.targetDir, 'package.json'), pkg, { spaces: 2, }) stopSpinner() console.log('🎉 Successfully enable Eslint and Prettier.') console.log() fs.copySync(path.resolve(this.sourceRoot(), this.cliOptions.type, 'template'), this.targetDir) } }) process.on('SIGINT', () => { fs.removeSync(this.targetDir) }) process.on('SIGTERM', () => { fs.removeSync(this.targetDir) }) break case 'python': console.log('🎉 Creating Python Project') clearConsole() // create project directory structure logWithSpinner(`Creating project in ${chalk.yellow(this.targetDir)}.`, '✨') if (!this.inCurrent) { fs.ensureDirSync(this.targetDir) } // copy template files to destination directory fs.copySync(path.resolve(this.sourceRoot(), this.cliOptions.type), this.targetDir) // install packages if (this.cliOptions.installDeps) { stopSpinner() console.log('⚙ Installing required Packages using PIP') console.log() this._runSync('pip install --upgrade pip') this._runSync('pip install -r requirements.txt') } stopSpinner() console.log() console.log(`🎉 Successfully created a python project ${chalk.yellow(this.serviceName)}.\n`) console.log('👉 Get started with the following commands:\n\n' + (this.targetDir === process.cwd() ? '' : chalk.cyan(`cd ${this.serviceName}\n`)) + (this.cliOptions.installDeps ? '' : chalk.cyan('pip install -r requirements.txt\n'))) this._runSync('make') break default: // start the process of microservice application creation clearConsole() // 1.create project directory structure logWithSpinner(`Creating project in ${chalk.yellow(this.targetDir)}.`, '✨') if (!this.inCurrent) { fs.ensureDirSync(this.targetDir) } // copy template files to destination directory fs.copySync(path.resolve(this.sourceRoot(), this.cliOptions.type), this.targetDir) // update package.json const pkg = fs.readJsonSync(path.resolve(this.targetDir, 'package.json')) Object.assign(pkg, { name: this.serviceName, version: '1.0.0', }) fs.writeJsonSync(path.resolve(this.targetDir, 'package.json'), pkg, { spaces: 2, }) // intilaize git repository before installing deps const shouldInitGit = this._shouldInitGit(this.options) if (shouldInitGit) { logWithSpinner('Initializing git repository...', '🗃') this._runSync('git init', { stdio: 'ignore' }) } // install plugins const useYarn = hasProjectYarn(this.cwd) || hasYarn() if (this.cliOptions.installDeps) { stopSpinner() console.log('⚙ Installing CLI plugins. This might take a while...') console.log() if (useYarn) { this._runSync('yarn install') } else { this._runSync('npm install') } } // enable Eslint and Prettier stopSpinner() console.log() logWithSpinner('Enabling Eslint and Prettier...', '🎀') console.log() this._runSync('npx install-peerdeps --dev eslint-config-dsx-base') // generate README.md stopSpinner() console.log() logWithSpinner('Generating README.md...', '📄') const readmeText = generateReadme(pkg, useYarn) fs.outputFileSync(path.resolve(this.targetDir, 'README.md'), readmeText) console.log() logWithSpinner('Generating CHANGELOG.md...', '📄') const changelogText = generateChangelog(this.serviceName) fs.outputFileSync(path.resolve(this.targetDir, 'CHANGELOG.md'), changelogText) // commit initial state let gitCommitFailed = false if (shouldInitGit) { this._runSync('git add -A', { stdio: 'ignore' }) let commitMsg = 'feat: first commit' const argvMsg = minimist(process.argv.slice(5))._ if (argvMsg.length) { commitMsg = argvMsg.join(' ') } try { this._runSync(`git commit -m '${commitMsg}'`, { stdio: 'ignore' }) } catch (e) { gitCommitFailed = true } } // log instructions stopSpinner() console.log() console.log(`🎉 Successfully created project ${chalk.yellow(this.serviceName)}.`) console.log('👉 Get started with the following commands:\n\n' + (this.targetDir === process.cwd() ? '' : chalk.cyan(` ${chalk.gray('$')} cd ${this.serviceName}\n`)) + (this.cliOptions.installDeps ? '' : chalk.cyan(` ${chalk.gray('$')} ${useYarn ? 'yarn install' : 'npm install'}\n`)) + chalk.cyan(` ${chalk.gray('$')} ${useYarn ? 'yarn start' : 'npm run start'}`)) console.log() if (gitCommitFailed) { console.warn( 'Skipped git commit due to missing username and email in git config.\n' + 'You will need to perform the initial commit yourself.\n', ) } break } } conflicts () {} install () {} end () {} }
32.829703
211
0.579649