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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ea40f721c8e81e92dfe952ed6fed61ad114c1621 | 3,123 | js | JavaScript | lib/alerts/containers/ActiveAlertEditor.js | 5Tsrl/TransitCafe | 5d49304fb42ce7278b819b40b5f16c58a4c7348b | [
"MIT"
] | null | null | null | lib/alerts/containers/ActiveAlertEditor.js | 5Tsrl/TransitCafe | 5d49304fb42ce7278b819b40b5f16c58a4c7348b | [
"MIT"
] | 6 | 2017-07-14T13:41:01.000Z | 2017-07-19T14:14:50.000Z | lib/alerts/containers/ActiveAlertEditor.js | 5Tsrl/TransitCafe | 5d49304fb42ce7278b819b40b5f16c58a4c7348b | [
"MIT"
] | null | null | null | import { connect } from 'react-redux'
import { browserHistory } from 'react-router'
import {
createAlert,
deleteAlert,
fetchRtdAlerts,
saveAlert,
setActiveAlert
} from '../actions/alerts'
import {
setActiveProperty,
setActivePublished,
addActiveEntity,
deleteActiveEntity,
updateActiveEntity
} from '../actions/activeAlert'
import AlertEditor from '../components/AlertEditor'
import { getFeedsForPermission } from '../../common/util/permissions'
import {updatePermissionFilter} from '../../gtfs/actions/filter'
import {getActiveFeeds} from '../../gtfs/selectors'
import {fetchProjects} from '../../manager/actions/projects'
import {getActiveProject} from '../../manager/selectors'
const mapStateToProps = (state, ownProps) => {
return {
activeFeeds: getActiveFeeds(state),
alert: state.alerts.active,
editableFeeds: getFeedsForPermission(getActiveProject(state), state.user, 'edit-alert'),
permissionFilter: state.gtfs.filter.permissionFilter,
project: getActiveProject(state),
publishableFeeds: getFeedsForPermission(getActiveProject(state), state.user, 'approve-alert'),
user: state.user
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onComponentMount: (initialProps) => {
const {location, alert, user} = initialProps
const alertId = location.pathname.split('/alert/')[1]
if (alert) return
let activeProject
dispatch(fetchProjects(true))
.then(project => {
activeProject = project
return dispatch(fetchRtdAlerts())
})
// logic for creating new alert or setting active alert (and checking project permissions)
.then(() => {
if (!user.permissions.hasProjectPermission(activeProject.organizationId, activeProject.id, 'edit-alert')) {
console.log('cannot create alert!')
browserHistory.push('/alerts')
return
}
if (!alertId) {
dispatch(createAlert())
} else {
dispatch(setActiveAlert(+alertId))
}
if (initialProps.permissionFilter !== 'edit-alert') {
dispatch(updatePermissionFilter('edit-alert'))
}
})
},
onSaveClick: (alert) => dispatch(saveAlert(alert)),
onDeleteClick: (alert) => dispatch(deleteAlert(alert)),
onPublishClick: (alert, published) => dispatch(setActivePublished(published)),
propertyChanged: (payload) => dispatch(setActiveProperty(payload)),
onAddEntityClick: (type, value, agency, newEntityId) => dispatch(addActiveEntity(type, value, agency, newEntityId)),
onDeleteEntityClick: (entity) => dispatch(deleteActiveEntity(entity)),
entityUpdated: (entity, field, value, agency) => dispatch(updateActiveEntity(entity, field, value, agency)),
editorStopClick: (stop, agency, newEntityId) => dispatch(addActiveEntity('STOP', stop, agency, newEntityId)),
editorRouteClick: (route, agency, newEntityId) => dispatch(addActiveEntity('ROUTE', route, agency, newEntityId))
}
}
const ActiveAlertEditor = connect(
mapStateToProps,
mapDispatchToProps
)(AlertEditor)
export default ActiveAlertEditor
| 36.741176 | 120 | 0.697727 |
ea42b1b4330993623556e59703ecfaf9a9376a67 | 345 | js | JavaScript | app/assets/javascripts/ak65/main.js | holzleube/tuniboard | cf056e93626d7829d73d76a672329db1f009da61 | [
"MIT"
] | null | null | null | app/assets/javascripts/ak65/main.js | holzleube/tuniboard | cf056e93626d7829d73d76a672329db1f009da61 | [
"MIT"
] | null | null | null | app/assets/javascripts/ak65/main.js | holzleube/tuniboard | cf056e93626d7829d73d76a672329db1f009da61 | [
"MIT"
] | null | null | null | /**
* Manages all sub-modules so other RequireJS modules only have to import the package.
*/
define(['angular', './routes', './controllers'], function(angular, routes, controllers) {
'use strict';
var mod = angular.module('ak65', ['ngRoute', 'ak65.routes']);
mod.controller('AK65Ctrl', controllers.AK65Ctrl);
return mod;
});
| 28.75 | 89 | 0.663768 |
ea443dd718a04960355159519b3ca9297dc9dd40 | 3,353 | js | JavaScript | src/js/game/LayerManager.js | JordanMachado/goodboytest | cca803f5799539473f65b9b1cbb5f6845699e70b | [
"MIT"
] | null | null | null | src/js/game/LayerManager.js | JordanMachado/goodboytest | cca803f5799539473f65b9b1cbb5f6845699e70b | [
"MIT"
] | null | null | null | src/js/game/LayerManager.js | JordanMachado/goodboytest | cca803f5799539473f65b9b1cbb5f6845699e70b | [
"MIT"
] | null | null | null | import PIXI from 'pixi.js';
import GLOBAL from 'Global';
import {
START_GAME,
} from 'Messages';
import Mediator from 'Mediator';
import Layer from './Layer';
import TreeManager from './TreeManager';
import FlowerManager from './FlowerManager';
import ColumnManager from './ColumnManager';
import LavaParticles from './LavaParticles';
import BonusManager from './BonusManager';
export default class LayerManager {
constructor({ background, middleGround, forGround }) {
this.back = background;
this.mid = middleGround;
this.for = forGround;
// todo in json
const layerData = [
{
id: '05_far_BG.jpg',
position: {
x: 0,
y: 0,
},
damping: 0.3,
container: this.back,
},
{
id: '03_rear_canopy.png',
position: {
x: 0,
y: 0,
},
damping: 0.4,
container: this.back,
},
{
id: '02_front_canopy.png',
position: {
x: 0,
y: 0,
},
container: this.mid,
damping: 0.5,
},
{
id: '00_roof_leaves.png',
position: {
x: 0,
y: 0,
},
damping: 0.9,
container: this.for,
},
{
id: '03_rear_silhouette.png',
position: {
x: 0,
y: GLOBAL.GAME.height - 96,
},
damping: 0.45,
container: this.mid,
},
{
id: '01_front_silhouette.png',
position: {
x: 0,
y: GLOBAL.GAME.height - 108,
},
damping: 0.95,
container: this.for,
},
];
this.layers = [];
const textures = PIXI.loader.resources['assets/images/WorldAssets.json'].textures;
for (let i = 0; i < layerData.length; i += 1) {
const layer = new Layer({
texture: textures[layerData[i].id],
width: GLOBAL.GAME.width,
height: textures[layerData[i].id].height,
damping: layerData[i].damping,
position: {
x: layerData[i].position.x,
y: layerData[i].position.y,
},
});
layerData[i].container.addChild(layer);
this.layers.push(layer);
}
this.treeManager = new TreeManager({
container: this.back,
});
this.flowerManager = new FlowerManager({
container: this.mid,
});
this.lavaparticles = new LavaParticles({
container: this.for,
texture: PIXI.loader.resources['assets/images/particle.png'].texture,
});
this.bonusManager = new BonusManager({
container: this.for,
});
window.columnManager = this.columnManager = new ColumnManager({
container: this.for,
});
Mediator.on(START_GAME, () => {
this.columnManager.spawn(true);
});
}
init() {
this.treeManager.start();
this.flowerManager.start();
}
update() {
for (let i = 0; i < this.layers.length; i += 1) {
this.layers[i].update();
}
this.treeManager.update();
this.flowerManager.update();
this.columnManager.update();
this.lavaparticles.update();
this.bonusManager.update();
}
reset() {
this.treeManager.reset();
this.treeManager.start();
this.flowerManager.reset();
this.flowerManager.start();
this.columnManager.reset();
this.bonusManager.reset();
}
}
| 23.284722 | 86 | 0.549657 |
ea4440fa39b198acd725969bdca4fa130e1ad7e0 | 428 | js | JavaScript | src/components/SimpleTitle.js | roots-id/rootswallet | 380228acae1c28c9a6bb1beaadd572c4e228ab99 | [
"Apache-2.0"
] | 3 | 2022-01-06T23:55:28.000Z | 2022-02-18T17:46:28.000Z | src/components/SimpleTitle.js | roots-id/rootswallet | 380228acae1c28c9a6bb1beaadd572c4e228ab99 | [
"Apache-2.0"
] | 32 | 2022-01-07T15:39:41.000Z | 2022-03-25T11:36:01.000Z | src/components/SimpleTitle.js | roots-id/rootswallet | 380228acae1c28c9a6bb1beaadd572c4e228ab99 | [
"Apache-2.0"
] | null | null | null | import React from 'react';
import { Image, StyleSheet, Text, View } from 'react-native';
export default function SimpleTitle(...props) {
// <React.Fragment>
return (
<View style={{flexDirection:'row',}}>
<Text style={{ color: '#eeeeee',fontSize: 22,fontWeight: 'normal',textAlignVertical: "center",textAlign: "center", }}>
{props[0]["title"]}
</Text>
</View>
);
}
| 30.571429 | 130 | 0.579439 |
ea44499b21604b825debcb0c093ad322f405eea6 | 254 | js | JavaScript | src/tools/getPrefix.js | rmotafreitas/BotKaoriDiscord | e1a7e814cd609048cd37e66252d63992f64be321 | [
"MIT"
] | 12 | 2020-11-05T18:48:12.000Z | 2021-11-12T12:03:15.000Z | src/tools/getPrefix.js | rmotafreitas/BotKaoriDiscord | e1a7e814cd609048cd37e66252d63992f64be321 | [
"MIT"
] | 10 | 2021-01-02T02:25:10.000Z | 2022-03-12T23:15:12.000Z | src/tools/getPrefix.js | rmotafreitas/BotKaoriDiscord | e1a7e814cd609048cd37e66252d63992f64be321 | [
"MIT"
] | 4 | 2021-02-02T15:13:12.000Z | 2021-09-17T18:27:59.000Z | const prefixs = require("./../models/prefixs");
const getPrefix = async (id) => {
let guild = await prefixs.findOne({
guildID: id,
});
if (guild) {
return guild.prefix;
} else {
return "$";
}
};
module.exports = {
getPrefix,
};
| 14.941176 | 47 | 0.570866 |
ea44ef2956e639c032cad20abeda14742ad8065b | 536 | js | JavaScript | src/server/model/Bonus/BonusEnemyFast.js | eleven-labs/curvytron | bddc847123c2c269924585ad8def40776ccbd946 | [
"MIT"
] | null | null | null | src/server/model/Bonus/BonusEnemyFast.js | eleven-labs/curvytron | bddc847123c2c269924585ad8def40776ccbd946 | [
"MIT"
] | null | null | null | src/server/model/Bonus/BonusEnemyFast.js | eleven-labs/curvytron | bddc847123c2c269924585ad8def40776ccbd946 | [
"MIT"
] | null | null | null | /**
* Fast Enemy Bonus
*
* @param {Array} position
*/
function BonusEnemyFast(position)
{
BonusEnemy.call(this, position);
}
BonusEnemyFast.prototype = Object.create(BonusEnemy.prototype);
BonusEnemyFast.prototype.constructor = BonusEnemyFast;
/**
* Duration
*
* @type {Number}
*/
BonusEnemyFast.prototype.duration = 6000;
/**
* Get effects
*
* @param {Avatar} avatar
*
* @return {Array}
*/
BonusEnemyFast.prototype.getEffects = function(avatar)
{
return [['velocity', 0.75 * BaseAvatar.prototype.velocity]];
}; | 17.290323 | 64 | 0.69403 |
ea4547735a26dc530df4aea35433f09a2011da97 | 1,162 | js | JavaScript | lib/serviceDiscovery/service.js | lzubiaur/mage | f1b846136f7bf134a7d2485214f797214a2808a6 | [
"MIT"
] | null | null | null | lib/serviceDiscovery/service.js | lzubiaur/mage | f1b846136f7bf134a7d2485214f797214a2808a6 | [
"MIT"
] | null | null | null | lib/serviceDiscovery/service.js | lzubiaur/mage | f1b846136f7bf134a7d2485214f797214a2808a6 | [
"MIT"
] | null | null | null | 'use strict';
/**
* @module serviceDiscovery
*/
const EventEmitter = require('events').EventEmitter;
const util = require('util');
/**
* This is our constructor, you should parse the provided options based on your service's need
*
* @constructor
*/
function Service() {
// do nothing
}
util.inherits(Service, EventEmitter);
/**
* Announce your service to the whole world
*
* @param {number} port The service port
* @param {Object} [metadata] Some private metadata that the service may need for connection
* @param {Function} [cb] An optional callback, the first parameter will be an Error if anything wrong happened
*/
Service.prototype.announce = function (port, metadata, cb) {
if (cb) {
cb(new Error('Not implemented'));
}
};
/**
* Start service discovery, after that the service should start browsing the network and fire up and down events
*/
Service.prototype.discover = function () {
throw new Error('Not implemented');
};
/**
* Stops all functions of the service discovery process, does nothing by default
*/
Service.prototype.close = function (cb) {
return setImmediate(cb);
};
exports.Service = Service;
| 23.714286 | 117 | 0.702238 |
ea46d328368118d8948f8cc832c9425b14bc3c1f | 12,020 | js | JavaScript | lib/boids.js | XDargu/wavelength | 45f92b660539211a6c6bc04b04486bf2beb19f64 | [
"MIT"
] | null | null | null | lib/boids.js | XDargu/wavelength | 45f92b660539211a6c6bc04b04486bf2beb19f64 | [
"MIT"
] | null | null | null | lib/boids.js | XDargu/wavelength | 45f92b660539211a6c6bc04b04486bf2beb19f64 | [
"MIT"
] | null | null | null | /*jshint esversion: 6 */
const GameStage = { PLANET: 0, JUMPINGOUT: 1, JUMPINGIN: 2 };
Object.freeze(GameStage);
class GameState {
constructor() {
"use strict";
this.step = 0;
this.stage = GameStage.PLANET;
this.encounters = {};
this.usedEncounters = [];
this.visitedPlanets = 0;
this.exploredPlanets = [];
this.address = "000000000";
this.addressType = "";
this.fuel = 100;
this.food = 100;
this.encounterTimeout = null;
this.options = {
simulation: {
tscale: 1,
}
};
this.fpsCounter = new FPSCounter(0.1);
this.processEncounters();
}
processEncounters() {
let id = 1;
for (let i=0; i<rawEncounters.length; ++i) {
this.encounters[id++] = rawEncounters[i]
}
}
isEncounterValid(encounter, type) {
// Evaluate requirements
if (encounter.type) {
if (encounter.type != type) { return false; }
}
if (!encounter.requires) { return true; }
if (encounter.requires.system) {
if (encounter.requires.system != this.addressType) { return false; }
}
if (encounter.requires.planet) {
if (encounter.requires.planet != mainViewCanvas.planet.type) { return false; }
}
if (encounter.requires.fuel != undefined) {
if (encounter.requires.fuel >= 0 && this.fuel < encounter.requires.fuel) { return false; }
else if (this.fuel > -encounter.requires.fuel) { return false; }
}
if (encounter.requires.food != undefined) {
if (encounter.requires.food >= 0 && this.food < encounter.requires.food) { return false; }
else if (this.food > -encounter.requires.food) { return false; }
}
if (encounter.requires.visitedPlanets != undefined) {
if (encounter.requires.visitedPlanets >= 0 && this.visitedPlanets < encounter.requires.visitedPlanets) { return false; }
else if (this.visitedPlanets > -encounter.requires.visitedPlanets) { return false; }
}
return true;
}
evaluateEncounters(seed, type) {
let rng = new RNG(seed);
let candidates = [];
for (let id in this.encounters) {
if (!this.usedEncounters.includes(id)) {
if (this.isEncounterValid(this.encounters[id], type)) {
let roll = rng.nextFloat() * 100;
console.log(this.encounters[id])
console.log(roll)
if (roll <= this.encounters[id].probability) {
candidates.push(id);
break;
}
}
}
}
if (candidates.length > 0)
{
let resultId = rng.choice(candidates);
let result = this.encounters[resultId]
let delay = 100;
if (result.delay) {
delay = result.delay * 1000;
}
var thisObj = this;
this.encounterTimeout = setTimeout(function(){
let text = result.text;
if (result.repeat == false) {
thisObj.usedEncounters.push(resultId);
}
if (result.rewards) {
if (result.rewards.fuel != undefined) {
if (result.rewards.fuel >= 0) {
text += "\n - You get " + result.rewards.fuel + " fuel";
thisObj.fuel += result.rewards.fuel;
}
else {
text += "\n - You lose " + -result.rewards.fuel + " fuel";
thisObj.fuel -= result.rewards.fuel;
}
}
if (result.rewards.food != undefined) {
if (result.rewards.food >= 0) {
text += "\n - You get " + result.rewards.food + " food";
thisObj.food += result.rewards.food;
}
else {
text += "\n - You lose " + -result.rewards.food + " food";
thisObj.food -= result.rewards.food;
}
}
}
alert(text);
updateUI();
}, delay);
}
}
update(deltaTime) {
this.step++;
this.fpsCounter.update(deltaTime);
}
render(cx) {
renderText(cx, new Vector(10, 40), "Step: " + this.step);
this.fpsCounter.render(cx);
}
setAddress(address) {
this.address = address;
}
travel(transition) {
if (transition) {
this.changeStage(GameStage.JUMPINGOUT);
}
else {
this.changeStage(GameStage.JUMPINGOUT);
this.changeStage(GameStage.JUMPINGIN);
this.changeStage(GameStage.PLANET);
}
}
changeStage(newStage) {
if (newStage == GameStage.JUMPINGIN) {
let rng = new RNG(this.address);
const typeSeed = rng.nextInt();
const encounterSeed = rng.nextInt();
this.generateType(typeSeed);
mainViewCanvas.reset(this.address);
waveCanvas.reset(this.address);
this.visitedPlanets++;
updateUI();
}
else if (newStage == GameStage.JUMPINGOUT) {
if (this.encounterTimeout) {
clearTimeout(this.encounterTimeout);
}
let explorePlanet = document.getElementById("explorePlanet");
explorePlanet.disabled = true;
document.getElementById("jumpToCoord").disabled = true;
document.getElementById("jumpRand").disabled = true;
}
else if (newStage == GameStage.PLANET) {
let rng = new RNG(this.address);
const typeSeed = rng.nextInt();
const encounterSeed = rng.nextInt();
let explorePlanet = document.getElementById("explorePlanet");
explorePlanet.disabled = this.exploredPlanets.includes(this.address);
document.getElementById("jumpToCoord").disabled = false;
document.getElementById("jumpRand").disabled = false;
this.evaluateEncounters(encounterSeed, "travel");
}
this.stage = newStage;
}
explore() {
let rng = new RNG(this.address);
const encounterSeed = rng.nextInt();
if (this.encounterTimeout) {
clearTimeout(this.encounterTimeout);
}
this.evaluateEncounters(encounterSeed, "explore");
this.exploredPlanets.push(this.address);
let explorePlanet = document.getElementById("explorePlanet");
explorePlanet.disabled = true;
}
canUseFuel(amount) {
return this.fuel >= amount;
}
useFuel(amount) {
this.fuel -= amount;
}
canUseFood(amount) {
return this.food >= amount;
}
useFood(amount) {
this.food -= amount;
}
generateType(seed) {
let rng = new RNG(seed);
// sum of weights must be 100!
const choices = [
{type: "quiet", weigth: 80},
{type: "dead", weigth: 4},
{type: "echoes", weigth: 15},
{type: "active", weigth: 1},
];
let rnd = rng.nextFloat() * 100;
for (let i=0; i<choices.length; ++i) {
if(rnd < choices[i].weigth) {
this.addressType = choices[i].type;
break;
}
rnd -= choices[i].weigth;
}
}
}
var gameState = new GameState();
var mousePosition = new Vector(0, 0);
function getMousePos(canvas, evt) {
"use strict";
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function onMouseMove(e) {
"use strict";
var pos = getMousePos(canvas, e);
mousePosition.x = pos.x;
mousePosition.y = pos.y;
}
class WaveCanvas extends Canvas2D {
constructor() {
super('waveCanvas', 60);
this.wave = new Wave(this, gameState.address);
}
update(deltaTime) {
this.wave.update(deltaTime, this.currentTime);
}
render(cx) {
this.wave.render(cx);
}
reset(seed) {
this.wave.reset(seed, gameState.addressType);
}
resize() {
this.cw = window.innerWidth;
this.canvas.width = this.cw;
this.canvas.style.width = this.cw + "px";
this.ch = window.innerHeight * 0.3;
this.canvas.height = this.ch;
this.canvas.style.height = this.ch + "px";
};
}
class MainViewCanvas extends Canvas2D {
constructor() {
super('canvas', 30);
this.stars = new Stars(this, gameState.address);
this.planet = new Planet(this, gameState.address);
this.canvas.color = "black";
}
reset(seed) {
this.stars.reset(seed);
this.planet.reset(seed);
}
update(deltaTime) {
this.stars.update(deltaTime, this.currentTime);
this.planet.update(deltaTime, this.currentTime);
if (gameState.stage == GameStage.JUMPINGOUT) {
this.stars.hOffset += deltaTime * 3000;
this.planet.hOffset -= deltaTime * 3400;
if (this.planet.hOffset <= -this.cw) {
console.log(this.planet.hOffset);
gameState.changeStage(GameStage.JUMPINGIN);
// Move to other side
this.planet.hOffset = this.cw * 2;
}
}
else if (gameState.stage == GameStage.JUMPINGIN) {
this.stars.hOffset += deltaTime * 3000;
this.planet.hOffset = Math.max(this.planet.hOffset - deltaTime * 3400, 0);
if (this.planet.hOffset <= 0) {
gameState.changeStage(GameStage.PLANET);
}
}
else if (gameState.stage == GameStage.PLANET) {
this.planet.hOffset = 0;
}
}
render(cx) {
this.stars.render(cx);
this.planet.render(cx);
}
resize() {
this.cw = window.innerWidth;
this.canvas.width = this.cw;
this.canvas.style.width = this.cw + "px";
this.ch = window.innerHeight * 0.7;
this.canvas.height = this.ch;
this.canvas.style.height = this.ch + "px";
this.planet.resize();
};
}
var waveCanvas = new WaveCanvas();
var mainViewCanvas = new MainViewCanvas();
var paused = false,
stepRequested = false;
function onResize() {
waveCanvas.resize();
mainViewCanvas.resize();
}
function generateAddress() {
let rng = new RNG();
let address = "";
for (let i=0; i<9; ++i) {
address += rng.nextRange(0, 9);
}
return address;
}
function sanitizeInputCoord(input) {
let sanitizedValue = input.value;
for (let i=0; i<sanitizedValue.length; ++i)
{
if (parseInt(sanitizedValue[i]) == NaN) {
sanitizedValue[i] = "0";
}
}
if (input.value.length > 9) {
sanitizedValue = sanitizedValue.substr(0, 9);
}
else if (input.value.length < 9) {
const extraZeroes = 9 - input.value.length;
for (let i=0; i<extraZeroes; ++i)
{
sanitizedValue = "0" + sanitizedValue;
}
}
input.value = sanitizedValue;
return sanitizedValue;
}
function onAddressChanged(address, transition) {
gameState.setAddress(address);
document.getElementById("addressInput").value = address;
gameState.travel(transition);
updateUI();
}
function updateUI() {
document.getElementById("fuelBar").value = gameState.fuel;
document.getElementById("foodBar").value = gameState.food;
document.getElementById("planetType").innerText = mainViewCanvas.planet.subtype;
document.getElementById("radioType").innerText = gameState.addressType;
}
function init() {
"use strict";
onAddressChanged(generateAddress(), false);
waveCanvas.init();
mainViewCanvas.init();
updateUI();
// Change address
let input = document.getElementById("addressInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
let jumpToCoordinates = document.getElementById("jumpToCoord");
jumpToCoordinates.click();
}
});
let jumpToCoordinates = document.getElementById("jumpToCoord");
jumpToCoordinates.onclick = function() {
let input = document.getElementById("addressInput");
const address = sanitizeInputCoord(input);
if (address != gameState.address && gameState.canUseFuel(10)) {
gameState.useFuel(10);
onAddressChanged(address, true);
}
};
let jumpRandomly = document.getElementById("jumpRand");
jumpRandomly.onclick = function() {
if (gameState.canUseFuel(5)) {
gameState.useFuel(5);
onAddressChanged(generateAddress(), true);
}
};
let explorePlanet = document.getElementById("explorePlanet");
explorePlanet.onclick = function() {
if (gameState.canUseFood(5)) {
gameState.useFood(5);
updateUI();
gameState.explore();
}
};
// Webkit/Blink will fire this on load, but Gecko doesn't.
window.onresize = onResize;
// So we fire it manually...
onResize();
// Input
document.onkeypress = function (e) {
e = e || window.event;
var keyMapping = {
pause: 102,
step: 103,
stepBack: 100
};
if (e.keyCode === keyMapping.pause) {
paused = !paused;
if (paused)
{
document.body.classList.add("paused");
}
else
{
document.body.classList.remove("paused");
}
}
else if (e.keyCode === keyMapping.step) {
stepRequested = true;
}
};
window.addEventListener('mousemove', onMouseMove, false);
}
init(); | 22.938931 | 123 | 0.639101 |
ea4777d44a4408da037e3f44c2646204a44f8743 | 1,453 | js | JavaScript | events/guildMemberRemove.js | fudgepop01/Floofy-Bot | b8b8a0de00775323812a3ad5b28a30454f0e2ae1 | [
"MIT"
] | 2 | 2019-08-25T15:33:43.000Z | 2021-07-11T06:16:10.000Z | events/guildMemberRemove.js | dar2355/Floofy-Bot | b8b8a0de00775323812a3ad5b28a30454f0e2ae1 | [
"MIT"
] | null | null | null | events/guildMemberRemove.js | dar2355/Floofy-Bot | b8b8a0de00775323812a3ad5b28a30454f0e2ae1 | [
"MIT"
] | null | null | null | exports.run = (bot, member) => {
// leaves/kicks
const logs = bot.provider.get(member.guild, 'logs');
const mentions = bot.provider.get(member.guild, 'mentions');
let rolestate = bot.provider.get(member.guild, 'rolestate', {});
if (logs && logs.enable && logs.channel && logs.fields.leaves !== false) {
let embed = new bot.methods.Embed();
embed.setColor('#ff5050').setTimestamp().setAuthor(`${member.user.username} (${member.user.id})`, member.user.avatarURL).setFooter(bot.user.username, bot.user.avatarURL);
if (mentions && mentions.enabled && mentions.action === 'kick') embed.addField('\u274C MENTION ABUSE KICK', `${member.user.username} has been removed from the server!`);
else embed.addField('\u274C NEW LEAVE', `${member.user.username} has left or been kicked from the server!`);
member.guild.channels.get(logs.channel).sendEmbed(embed).catch(() => null);
}
// rolestate
if (rolestate && rolestate.enabled) {
member.guild.fetchBans().then(users => {
if (users.has(member.id)) {
// if (!rolestate.users) rolestate.users = {};
rolestate.users[member.id] = member.roles.map(role => role.id);
bot.provider.set(member.guild, 'rolestate', rolestate);
}
}).catch(err => { member.guild.owner.sendMessage(`\uD83D\uDEAB I do not have access to the banned members of server: \`${member.guild.name}\`. Please give me the \`ban members\` or \`administrator\` permission for rolestate to work!${err}`); });
}
};
| 53.814815 | 247 | 0.685478 |
ea47d51ca93e8c276362090aae4c7423228719f7 | 119 | js | JavaScript | src/core/entities/cron.js | mahaplatform/mahaplatform.com | a96d8f7b12288c7cb01b036077182238c77d5b03 | [
"MIT"
] | null | null | null | src/core/entities/cron.js | mahaplatform/mahaplatform.com | a96d8f7b12288c7cb01b036077182238c77d5b03 | [
"MIT"
] | 52 | 2019-10-28T15:38:35.000Z | 2022-02-28T04:23:48.000Z | src/core/entities/cron.js | mahaplatform/mahaplatform.com | a96d8f7b12288c7cb01b036077182238c77d5b03 | [
"MIT"
] | null | null | null | import { startQueues } from '@core/services/queues'
const cron = () => {
startQueues('cron')
}
export default cron
| 14.875 | 51 | 0.672269 |
ea4806e7028c74a5c36e5a0a01374e90d7849d76 | 1,372 | js | JavaScript | icons/BellRinging2Icon.js | liebsoer/vue-tabler-icons | d206d524fccd488fed438164eabab3c329282c61 | [
"MIT"
] | null | null | null | icons/BellRinging2Icon.js | liebsoer/vue-tabler-icons | d206d524fccd488fed438164eabab3c329282c61 | [
"MIT"
] | null | null | null | icons/BellRinging2Icon.js | liebsoer/vue-tabler-icons | d206d524fccd488fed438164eabab3c329282c61 | [
"MIT"
] | null | null | null | import _mergeJSXProps from "@vue/babel-helper-vue-jsx-merge-props";
export default {
name: 'BellRinging2Icon',
props: {
size: {
type: String,
default: '24'
}
},
functional: true,
render(h, ctx) {
const size = parseInt(ctx.props.size) + 'px';
const attrs = ctx.data.attrs || {};
attrs.width = attrs.width || size;
attrs.height = attrs.height || size;
ctx.data.attrs = attrs;
return h("svg", _mergeJSXProps([{
"attrs": {
"xmlns": "http://www.w3.org/2000/svg",
"width": "24",
"height": "24",
"viewBox": "0 0 24 24",
"stroke-width": "2",
"stroke": "currentColor",
"fill": "none",
"stroke-linecap": "round",
"stroke-linejoin": "round"
},
"class": "icon icon-tabler icon-tabler-bell-ringing-2"
}, ctx.data]), [" ", h("path", {
"attrs": {
"stroke": "none",
"d": "M0 0h24v24H0z",
"fill": "none"
}
}), " ", h("path", {
"attrs": {
"d": "M19.364 4.636a2 2 0 0 1 0 2.828a7 7 0 0 1 -1.414 7.072l-2.122 2.12a4 4 0 0 0 -.707 3.536l-11.313 -11.312a4 4 0 0 0 3.535 -.707l2.121 -2.123a7 7 0 0 1 7.072 -1.414a2 2 0 0 1 2.828 0z"
}
}), " ", h("path", {
"attrs": {
"d": "M7.343 12.414l-.707 .707a3 3 0 0 0 4.243 4.243l.707 -.707"
}
}), " "]);
}
}; | 28.583333 | 196 | 0.494898 |
ea48baf093069f3db9e8d400d2a565b3eeb2e84c | 184 | js | JavaScript | node_modules/@luma.gl/webgl2-polyfill/src/index.js | calebperelini/nzbikeaccidents | a7edd0d51137afcf1130698cb3308ef0a852d848 | [
"MIT"
] | 5 | 2019-10-17T02:19:14.000Z | 2020-02-25T07:00:01.000Z | modules/webgl2-polyfill/src/index.js | cheeaun/luma.gl | 8b9a575133a7dcff29bb4609a3aaa4b6de9e5f9b | [
"MIT"
] | 7 | 2020-09-06T23:09:55.000Z | 2022-02-18T07:58:04.000Z | modules/webgl2-polyfill/src/index.js | fakeNetflix/uber-repo-luma.gl | 9c56079a055fd4821096f7671ad66005bb076d3f | [
"MIT"
] | null | null | null | // Installs polyfills to support a subset of WebGL2 APIs on WebGL1 contexts
export {default as polyfillContext} from './polyfill-context';
export {default} from './polyfill-context';
| 36.8 | 75 | 0.771739 |
ea48bc95b9d7b8d16eb6485275249c27fc738479 | 608 | js | JavaScript | node_modules/@iconify/icons-ic/outline-breakfast-dining.js | kagwicharles/Seniorproject-ui | 265956867c8a00063067f03e8772b93f2986c626 | [
"MIT"
] | null | null | null | node_modules/@iconify/icons-ic/outline-breakfast-dining.js | kagwicharles/Seniorproject-ui | 265956867c8a00063067f03e8772b93f2986c626 | [
"MIT"
] | null | null | null | node_modules/@iconify/icons-ic/outline-breakfast-dining.js | kagwicharles/Seniorproject-ui | 265956867c8a00063067f03e8772b93f2986c626 | [
"MIT"
] | 1 | 2021-09-28T19:15:17.000Z | 2021-09-28T19:15:17.000Z | var data = {
"body": "<path d=\"M18 3H6C3.79 3 2 4.79 2 7c0 1.48.81 2.75 2 3.45V19c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-8.55c1.19-.69 2-1.97 2-3.45c0-2.21-1.79-4-4-4zm1 5.72l-1 .58V19H6V9.31l-.99-.58C4.38 8.35 4 7.71 4 7c0-1.1.9-2 2-2h12c1.1 0 2 .9 2 2c0 .71-.38 1.36-1 1.72z\" fill=\"currentColor\"/><path d=\"M12.71 9.29C12.51 9.1 12.26 9 12 9s-.51.1-.71.29l-3 3a.996.996 0 0 0 0 1.41l3 3c.2.2.45.3.71.3s.51-.1.71-.29l3-3a.996.996 0 0 0 0-1.41l-3-3.01zM12 14.58L10.41 13L12 11.41L13.59 13L12 14.58z\" fill=\"currentColor\"/>",
"width": 24,
"height": 24
};
exports.__esModule = true;
exports.default = data;
| 76 | 512 | 0.634868 |
ea4b565959c1b3d45d3f14597b628c05a775c023 | 1,996 | js | JavaScript | packages/react-widgets/src/util/interaction.js | jafin/react-widgets | a4fdd45afd2b14ef484b62168fc1ad190ddf20a7 | [
"MIT"
] | null | null | null | packages/react-widgets/src/util/interaction.js | jafin/react-widgets | a4fdd45afd2b14ef484b62168fc1ad190ddf20a7 | [
"MIT"
] | null | null | null | packages/react-widgets/src/util/interaction.js | jafin/react-widgets | a4fdd45afd2b14ef484b62168fc1ad190ddf20a7 | [
"MIT"
] | null | null | null | import { findDOMNode } from 'react-dom';
import matches from 'dom-helpers/query/matches';
export const isInDisabledFieldset = (inst) => {
let node
try {
node = findDOMNode(inst)
} catch (err) { /* ignore */ }
return !!node && matches(node, 'fieldset[disabled] *')
}
export let widgetEnabled = interactionDecorator(true)
export let widgetEditable = interactionDecorator(false)
function interactionDecorator(disabledOnly) {
function wrap(method) {
return function decoratedMethod(...args) {
let { disabled, readOnly } = this.props;
disabled = (
isInDisabledFieldset(this) ||
disabled == true ||
(!disabledOnly && readOnly === true)
);
if (!disabled) return method.apply(this, args)
}
}
return function decorate(target, key, desc) {
if (desc.initializer) {
let init = desc.initializer
desc.initializer = function () {
return wrap(init.call(this)).bind(this)
}
}
else desc.value = wrap(desc.value)
return desc
}
}
import { spyOnComponent } from 'react-component-managers'
export const disabledManager = (component) => {
let mounted = false;
let isInFieldSet = false;
let useCached = false;
spyOnComponent(component, {
componentDidMount() {
mounted = true
// becasue we can't access a dom node in the first render we need to
// render again if the component was disabled via a fieldset
if (isInDisabledFieldset(this))
this.forceUpdate()
},
componentWillUpdate() {
isInFieldSet = mounted && isInDisabledFieldset(component)
useCached = mounted;
},
componentDidUpdate() {
useCached = false;
},
componentWillUnmount() {
component = null;
}
})
return () => (
component.props.disabled === true ||
(useCached ? isInFieldSet : (mounted && isInDisabledFieldset(component))) ||
component.props.disabled // return the prop if nothing is true in case it's an array
)
}
| 25.922078 | 88 | 0.645792 |
ea4b76732f189fce0eafcc3973b89888bccec2d1 | 15,496 | js | JavaScript | connectedhomeip/docs/html/classchip_1_1_device_layer_1_1_connectivity_manager.js | yhoyoon/yhoyoon.github.io | 0651d6b45f74922cfb6acba14a0ad5b037fa297c | [
"MIT"
] | null | null | null | connectedhomeip/docs/html/classchip_1_1_device_layer_1_1_connectivity_manager.js | yhoyoon/yhoyoon.github.io | 0651d6b45f74922cfb6acba14a0ad5b037fa297c | [
"MIT"
] | null | null | null | connectedhomeip/docs/html/classchip_1_1_device_layer_1_1_connectivity_manager.js | yhoyoon/yhoyoon.github.io | 0651d6b45f74922cfb6acba14a0ad5b037fa297c | [
"MIT"
] | null | null | null | var classchip_1_1_device_layer_1_1_connectivity_manager =
[
[ "ThreadPollingConfig", "structchip_1_1_device_layer_1_1_connectivity_manager_1_1_thread_polling_config.html", "structchip_1_1_device_layer_1_1_connectivity_manager_1_1_thread_polling_config" ],
[ "BLEAdvertisingMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a60af5dc0cca9010a4711ab30a5fca31c", [
[ "kFastAdvertising", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a60af5dc0cca9010a4711ab30a5fca31ca85185c216bf431544881d319a389f94b", null ],
[ "kSlowAdvertising", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a60af5dc0cca9010a4711ab30a5fca31cabd825623924c7867dfcb639a0ff0bd7f", null ]
] ],
[ "CHIPoBLEServiceMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a918876d0395f5c4ff1a7ef802ff268af", [
[ "kCHIPoBLEServiceMode_NotSupported", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a918876d0395f5c4ff1a7ef802ff268afa97351cce261cc9bb9ed68804d32316a8", null ],
[ "kCHIPoBLEServiceMode_Enabled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a918876d0395f5c4ff1a7ef802ff268afabf2e0bb19c1c97914ae7a14bfda8994d", null ],
[ "kCHIPoBLEServiceMode_Disabled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a918876d0395f5c4ff1a7ef802ff268afa853df05201e6c817997a681d9b38232e", null ]
] ],
[ "ThreadDeviceType", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ab3d1f32b512ccabb86bf40a30b769821", [
[ "kThreadDeviceType_NotSupported", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ab3d1f32b512ccabb86bf40a30b769821a4c559011a7a37825bb7bd7ca2941ea35", null ],
[ "kThreadDeviceType_Router", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ab3d1f32b512ccabb86bf40a30b769821a49e3cea51bea6e4378cf376130f6d7fe", null ],
[ "kThreadDeviceType_FullEndDevice", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ab3d1f32b512ccabb86bf40a30b769821a1c7085011367bf20eb42248d10983ef7", null ],
[ "kThreadDeviceType_MinimalEndDevice", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ab3d1f32b512ccabb86bf40a30b769821a6994731b71cd789bf16a8982af4544d4", null ],
[ "kThreadDeviceType_SleepyEndDevice", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ab3d1f32b512ccabb86bf40a30b769821a1c70317c580412239d8e60b1671e6ea7", null ]
] ],
[ "ThreadMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a7f46754404068e9c6165b8b264b5854f", [
[ "kThreadMode_NotSupported", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a7f46754404068e9c6165b8b264b5854fafbb23aafb315b98494ebd2f333bdac49", null ],
[ "kThreadMode_ApplicationControlled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a7f46754404068e9c6165b8b264b5854fa387a73c230a1c65814b9b23213a0210e", null ],
[ "kThreadMode_Disabled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a7f46754404068e9c6165b8b264b5854fa7150f2e5a47accc355f91b402be22d31", null ],
[ "kThreadMode_Enabled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a7f46754404068e9c6165b8b264b5854fa708ec1089e3b2cb038ea8c5630682526", null ]
] ],
[ "WiFiAPMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a79639b5b4305587adc9fdc609a84c8f5", [
[ "kWiFiAPMode_NotSupported", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a79639b5b4305587adc9fdc609a84c8f5abf8b11380c16f4f4a14da3a7041e3580", null ],
[ "kWiFiAPMode_ApplicationControlled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a79639b5b4305587adc9fdc609a84c8f5a88d1bb069db5bca4d0cbb9ed4d034c23", null ],
[ "kWiFiAPMode_Disabled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a79639b5b4305587adc9fdc609a84c8f5adcc16890b0752ea7c35b123997e718b8", null ],
[ "kWiFiAPMode_Enabled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a79639b5b4305587adc9fdc609a84c8f5a12416b8ad4fa62893c607dd188b30dcb", null ],
[ "kWiFiAPMode_OnDemand", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a79639b5b4305587adc9fdc609a84c8f5ae4bc2d9ced8a256ec06c74638e432f17", null ],
[ "kWiFiAPMode_OnDemand_NoStationProvision", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a79639b5b4305587adc9fdc609a84c8f5a338684b51d59a06fe0c99cc1f5420d22", null ]
] ],
[ "WiFiAPState", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ac28f3aa1be6e499e3d2a03b83c14f3b1", [
[ "kWiFiAPState_NotActive", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ac28f3aa1be6e499e3d2a03b83c14f3b1aa7eaa1f27ef16e98671a99737d77c6d8", null ],
[ "kWiFiAPState_Activating", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ac28f3aa1be6e499e3d2a03b83c14f3b1a8dbe52f872f2b4726cd37fb9c76d1eab", null ],
[ "kWiFiAPState_Active", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ac28f3aa1be6e499e3d2a03b83c14f3b1a70693196465a945a5889d6622edde56b", null ],
[ "kWiFiAPState_Deactivating", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ac28f3aa1be6e499e3d2a03b83c14f3b1a12d11327dffc1bbb782894733e30df9f", null ]
] ],
[ "WiFiStationMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a3c150539805bedd184720c830723318b", [
[ "kWiFiStationMode_NotSupported", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a3c150539805bedd184720c830723318ba147d60b6550eb604e74f5e14e4af27b8", null ],
[ "kWiFiStationMode_ApplicationControlled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a3c150539805bedd184720c830723318ba71d3153e0dc03d58e50554219d464197", null ],
[ "kWiFiStationMode_Disabled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a3c150539805bedd184720c830723318ba0fd3c62d9ab77b7c81b4f724dae9424f", null ],
[ "kWiFiStationMode_Enabled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a3c150539805bedd184720c830723318ba8b94341970e7710b74bed3357ff0a408", null ]
] ],
[ "WiFiStationState", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a5bbc91dfce95591099b020782f31a4d2", [
[ "kWiFiStationState_NotConnected", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a5bbc91dfce95591099b020782f31a4d2adfa4aea84f8682f64a8db0a1d0208ce9", null ],
[ "kWiFiStationState_Connecting", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a5bbc91dfce95591099b020782f31a4d2a1645ffac192ff7ef274e04813a0a54b8", null ],
[ "kWiFiStationState_Connecting_Succeeded", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a5bbc91dfce95591099b020782f31a4d2a17d8b63e3087bec41803ccb06e9b268d", null ],
[ "kWiFiStationState_Connecting_Failed", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a5bbc91dfce95591099b020782f31a4d2a37cb69c99dd3936f86e9601d75007514", null ],
[ "kWiFiStationState_Connected", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a5bbc91dfce95591099b020782f31a4d2a93fa135b0995d0869befff828061fb7f", null ],
[ "kWiFiStationState_Disconnecting", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a5bbc91dfce95591099b020782f31a4d2a0265bd1cfaa6b3a86008276ff3263e79", null ]
] ],
[ "ConnectivityManager", "classchip_1_1_device_layer_1_1_connectivity_manager.html#abd8f991b382c72693129f2affb966227", null ],
[ "~ConnectivityManager", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a6d6d2cd50fc790669993cb13ba725e03", null ],
[ "ConnectivityManager", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a3ff78d454af0be515aadc42115957239", null ],
[ "ConnectivityManager", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a687eeabb790ba7fbcf87c10ed2fd7011", null ],
[ "CHIPoBLEServiceModeToStr", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a1b29d4f3c8962c58f7b5b673dfe2f697", null ],
[ "ClearWiFiStationProvision", "classchip_1_1_device_layer_1_1_connectivity_manager.html#acc47309711b79a797c02933209b8da2b", null ],
[ "DemandStartWiFiAP", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a14e7fed53e726d148cd8c370c68770b6", null ],
[ "ErasePersistentInfo", "classchip_1_1_device_layer_1_1_connectivity_manager.html#aa275f39d735c0883066b0ee65b46da9f", null ],
[ "GetAndLogWifiStatsCounters", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ae3e8bbf0992ca44c6054e2d4358cc449", null ],
[ "GetBLEDeviceName", "classchip_1_1_device_layer_1_1_connectivity_manager.html#aefbd1e2ee9f8cd0a38e2819880d3c165", null ],
[ "GetBleLayer", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a810834e8f952859c906a4a2732105171", null ],
[ "GetCHIPoBLEServiceMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a8fcbef84be893be4f850a8b675fcfbad", null ],
[ "GetThreadDeviceType", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a29db33eafac133dd0e4cd77bcc74abca", null ],
[ "GetThreadMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ac1617cbd8020a10c4ce5c4d518873d90", null ],
[ "GetThreadPollingConfig", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a1bdf5d090e8e56dc565a02d0f233a254", null ],
[ "GetUserSelectedModeTimeout", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a972bfb216054143c4233ddcd0a1371fb", null ],
[ "GetWiFiAPIdleTimeoutMS", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ab26b23f4abeb1ce94f4956648015d322", null ],
[ "GetWiFiAPMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#af1aa15abae6450323cfa4445a150e3d6", null ],
[ "GetWiFiStationMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#af6db947ffa3de629e85a56e07cadeba3", null ],
[ "GetWiFiStationReconnectIntervalMS", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a2cdc4f1f63397eb9faf29ad0e7cd61a3", null ],
[ "HaveIPv4InternetConnectivity", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a34cdb4883ab309a612b7fd95130744ab", null ],
[ "HaveIPv6InternetConnectivity", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a7486c9e0d0d8ef2c33e9eb77cabb3f97", null ],
[ "HaveServiceConnectivity", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a06d522e80ca2ea1107cf4a19d0c0d0d1", null ],
[ "HaveServiceConnectivityViaThread", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a142c61165440da94fdba301134e85317", null ],
[ "IsBLEAdvertising", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a6dba1fdad0c465d4e24015330c684fd6", null ],
[ "IsBLEAdvertisingEnabled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a9ffa7fa0d968c8c1e6eb950e8368acec", null ],
[ "IsThreadApplicationControlled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ad5026ae956a58871d2c4864e6de0444d", null ],
[ "IsThreadAttached", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a0ac95729d727c9c843be57ff88a548c0", null ],
[ "IsThreadEnabled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#aeb211e96d85219445b402df3ca5b9690", null ],
[ "IsThreadProvisioned", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a7b5e64de37c46a0c369cf094437719be", null ],
[ "IsUserSelectedModeActive", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a6708d9c709fc3532b36d38f5aa40a35a", null ],
[ "IsWiFiAPActive", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a14077697a5a181ed13f2517690a97826", null ],
[ "IsWiFiAPApplicationControlled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a980fa898b0dcf75069f44189f46527de", null ],
[ "IsWiFiStationApplicationControlled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ac90614d60d7b102860dff17ccc234cdf", null ],
[ "IsWiFiStationConnected", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a1f5f1c0a63ef3b8ad489936b8d58948c", null ],
[ "IsWiFiStationEnabled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a2ad83c3e2fdeb3c6443a771c7d03cb5b", null ],
[ "IsWiFiStationProvisioned", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a94b166b3178570e3551288ba0510d6f0", null ],
[ "MaintainOnDemandWiFiAP", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a7503a58bb2eda03df9cc13191dfa8b7d", null ],
[ "NumBLEConnections", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a6b36dc7d6421afc6743020a20f76df2d", null ],
[ "operator=", "classchip_1_1_device_layer_1_1_connectivity_manager.html#acb3dc6a9c003032b080e63a97efd3487", null ],
[ "SetBLEAdvertisingEnabled", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a2f50ad9f26bbf4353f1c62a04cb1377a", null ],
[ "SetBLEAdvertisingMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ad757e469dd14e11eae45912a456b8160", null ],
[ "SetBLEDeviceName", "classchip_1_1_device_layer_1_1_connectivity_manager.html#abeb325cda71eda3f4e514fcbb28290f6", null ],
[ "SetCHIPoBLEServiceMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ac311bff412be0d8c765200d68a133f97", null ],
[ "SetThreadDeviceType", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a7d3895d4d4ea6f1e133c0297c0ac2139", null ],
[ "SetThreadMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a4c1c0012f7dd2d8a863c288480f06e6e", null ],
[ "SetThreadPollingConfig", "classchip_1_1_device_layer_1_1_connectivity_manager.html#aaf226670d281a3879e38f5dd962be7e9", null ],
[ "SetUserSelectedMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#aadedd1227161f5f1c5f2ef504be93b2b", null ],
[ "SetUserSelectedModeTimeout", "classchip_1_1_device_layer_1_1_connectivity_manager.html#abfc893ed9ad939a39fe8cdc71dddc24a", null ],
[ "SetWiFiAPIdleTimeoutMS", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a26e5615d61d76ce69190d7b2d08763ec", null ],
[ "SetWiFiAPMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a5e511c8147b2add3024276efef8d22ad", null ],
[ "SetWiFiStationMode", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a5331b990a2cf17ffeccd22aa6f55dea5", null ],
[ "SetWiFiStationReconnectIntervalMS", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a5781ccd4d0d0beb6f61684174f5c2ee6", null ],
[ "StopOnDemandWiFiAP", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ab35cb518f5ef394bce811598041b4341", null ],
[ "WiFiAPModeToStr", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a64d333f2db31385ed5f009f27abe7473", null ],
[ "WiFiAPStateToStr", "classchip_1_1_device_layer_1_1_connectivity_manager.html#aa92fb01b1af877583963babff28e31da", null ],
[ "WiFiStationModeToStr", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a57d8be43566dd6d1f900edc96223cd8e", null ],
[ "WiFiStationStateToStr", "classchip_1_1_device_layer_1_1_connectivity_manager.html#acac39af5bfc96a4f2d200b39559ed9fa", null ],
[ "Internal::GenericPlatformManagerImpl", "classchip_1_1_device_layer_1_1_connectivity_manager.html#a929b8c50e573b52988f41760a0377430", null ],
[ "Internal::GenericPlatformManagerImpl_FreeRTOS", "classchip_1_1_device_layer_1_1_connectivity_manager.html#aab4efedc666ea89b201be84c10faee9d", null ],
[ "Internal::GenericPlatformManagerImpl_POSIX", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ae442cfbf06ded6604c83e41b66654d80", null ],
[ "PlatformManagerImpl", "classchip_1_1_device_layer_1_1_connectivity_manager.html#ac31a0df4105578f7404846c15568b820", null ]
]; | 133.586207 | 199 | 0.855963 |
ea4ba52a8a977497223049fd6167970de07fa0b3 | 818 | js | JavaScript | lib/index.js | vidigami/backbone-mongo | ff1706b6f5539603f16dc91ef1245e0d22279062 | [
"MIT"
] | 1 | 2015-04-03T20:15:16.000Z | 2015-04-03T20:15:16.000Z | lib/index.js | vidigami/backbone-mongo | ff1706b6f5539603f16dc91ef1245e0d22279062 | [
"MIT"
] | 3 | 2015-04-03T20:20:51.000Z | 2021-05-26T19:56:01.000Z | lib/index.js | vidigami/backbone-mongo | ff1706b6f5539603f16dc91ef1245e0d22279062 | [
"MIT"
] | 6 | 2015-04-06T00:12:10.000Z | 2017-04-26T14:16:26.000Z | // Generated by CoffeeScript 1.9.0
/*
backbone-mongo.js 0.6.10
Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-mongo
License: MIT (http://www.opensource.org/licenses/mit-license.php)
*/
(function() {
var Backbone, BackboneMongo, BackboneORM, key, publish, value, _, _ref, _ref1;
_ref = BackboneORM = require('backbone-orm'), _ = _ref._, Backbone = _ref.Backbone;
module.exports = BackboneMongo = require('./core');
publish = {
configure: require('./lib/configure'),
sync: require('./sync'),
_: _,
Backbone: Backbone
};
_.extend(BackboneMongo, publish);
BackboneMongo.modules = {
'backbone-orm': BackboneORM
};
_ref1 = BackboneORM.modules;
for (key in _ref1) {
value = _ref1[key];
BackboneMongo.modules[key] = value;
}
}).call(this);
| 22.722222 | 85 | 0.658924 |
ea4bf1a2322de5a468bae42ec503f8d938304cb6 | 63,630 | js | JavaScript | src.54c4a183.js | aalises/test-musixmatch | 5b921e4ef6cf70cc471359302b37ae928520d36c | [
"MIT"
] | null | null | null | src.54c4a183.js | aalises/test-musixmatch | 5b921e4ef6cf70cc471359302b37ae928520d36c | [
"MIT"
] | null | null | null | src.54c4a183.js | aalises/test-musixmatch | 5b921e4ef6cf70cc471359302b37ae928520d36c | [
"MIT"
] | null | null | null | // modules are defined as an array
// [ module function, map of requires ]
//
// map of requires is short require name -> numeric require
//
// anything defined in a previous bundle is accessed via the
// orig method which is the require for previous bundles
// eslint-disable-next-line no-global-assign
parcelRequire = (function (modules, cache, entry, globalName) {
// Save the require from previous bundle to this closure if any
var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
var nodeRequire = typeof require === 'function' && require;
function newRequire(name, jumped) {
if (!cache[name]) {
if (!modules[name]) {
// if we cannot find the module within our internal map or
// cache jump to the current global require ie. the last bundle
// that was added to the page.
var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
if (!jumped && currentRequire) {
return currentRequire(name, true);
}
// If there are other bundles on this page the require from the
// previous one is saved to 'previousRequire'. Repeat this as
// many times as there are bundles until the module is found or
// we exhaust the require chain.
if (previousRequire) {
return previousRequire(name, true);
}
// Try the node require function if it exists.
if (nodeRequire && typeof name === 'string') {
return nodeRequire(name);
}
var err = new Error('Cannot find module \'' + name + '\'');
err.code = 'MODULE_NOT_FOUND';
throw err;
}
localRequire.resolve = resolve;
var module = cache[name] = new newRequire.Module(name);
modules[name][0].call(module.exports, localRequire, module, module.exports, this);
}
return cache[name].exports;
function localRequire(x){
return newRequire(localRequire.resolve(x));
}
function resolve(x){
return modules[name][1][x] || x;
}
}
function Module(moduleName) {
this.id = moduleName;
this.bundle = newRequire;
this.exports = {};
}
newRequire.isParcelRequire = true;
newRequire.Module = Module;
newRequire.modules = modules;
newRequire.cache = cache;
newRequire.parent = previousRequire;
newRequire.register = function (id, exports) {
modules[id] = [function (require, module) {
module.exports = exports;
}, {}];
};
for (var i = 0; i < entry.length; i++) {
newRequire(entry[i]);
}
if (entry.length) {
// Expose entry point to Node, AMD or browser globals
// Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
var mainExports = newRequire(entry[entry.length - 1]);
// CommonJS
if (typeof exports === "object" && typeof module !== "undefined") {
module.exports = mainExports;
// RequireJS
} else if (typeof define === "function" && define.amd) {
define(function () {
return mainExports;
});
// <script>
} else if (globalName) {
this[globalName] = mainExports;
}
}
// Override the current require with this new one
return newRequire;
})({"OmAK":[function(require,module,exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var VNode = function VNode() {};
var options = {};
var stack = [];
var EMPTY_CHILDREN = [];
function h(nodeName, attributes) {
var children = EMPTY_CHILDREN,
lastSimple,
child,
simple,
i;
for (i = arguments.length; i-- > 2;) {
stack.push(arguments[i]);
}
if (attributes && attributes.children != null) {
if (!stack.length) stack.push(attributes.children);
delete attributes.children;
}
while (stack.length) {
if ((child = stack.pop()) && child.pop !== undefined) {
for (i = child.length; i--;) {
stack.push(child[i]);
}
} else {
if (typeof child === 'boolean') child = null;
if (simple = typeof nodeName !== 'function') {
if (child == null) child = '';else if (typeof child === 'number') child = String(child);else if (typeof child !== 'string') simple = false;
}
if (simple && lastSimple) {
children[children.length - 1] += child;
} else if (children === EMPTY_CHILDREN) {
children = [child];
} else {
children.push(child);
}
lastSimple = simple;
}
}
var p = new VNode();
p.nodeName = nodeName;
p.children = children;
p.attributes = attributes == null ? undefined : attributes;
p.key = attributes == null ? undefined : attributes.key;
if (options.vnode !== undefined) options.vnode(p);
return p;
}
function extend(obj, props) {
for (var i in props) {
obj[i] = props[i];
}return obj;
}
var defer = typeof Promise == 'function' ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout;
function cloneElement(vnode, props) {
return h(vnode.nodeName, extend(extend({}, vnode.attributes), props), arguments.length > 2 ? [].slice.call(arguments, 2) : vnode.children);
}
var IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;
var items = [];
function enqueueRender(component) {
if (!component._dirty && (component._dirty = true) && items.push(component) == 1) {
(options.debounceRendering || defer)(rerender);
}
}
function rerender() {
var p,
list = items;
items = [];
while (p = list.pop()) {
if (p._dirty) renderComponent(p);
}
}
function isSameNodeType(node, vnode, hydrating) {
if (typeof vnode === 'string' || typeof vnode === 'number') {
return node.splitText !== undefined;
}
if (typeof vnode.nodeName === 'string') {
return !node._componentConstructor && isNamedNode(node, vnode.nodeName);
}
return hydrating || node._componentConstructor === vnode.nodeName;
}
function isNamedNode(node, nodeName) {
return node.normalizedNodeName === nodeName || node.nodeName.toLowerCase() === nodeName.toLowerCase();
}
function getNodeProps(vnode) {
var props = extend({}, vnode.attributes);
props.children = vnode.children;
var defaultProps = vnode.nodeName.defaultProps;
if (defaultProps !== undefined) {
for (var i in defaultProps) {
if (props[i] === undefined) {
props[i] = defaultProps[i];
}
}
}
return props;
}
function createNode(nodeName, isSvg) {
var node = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName);
node.normalizedNodeName = nodeName;
return node;
}
function removeNode(node) {
var parentNode = node.parentNode;
if (parentNode) parentNode.removeChild(node);
}
function setAccessor(node, name, old, value, isSvg) {
if (name === 'className') name = 'class';
if (name === 'key') {} else if (name === 'ref') {
if (old) old(null);
if (value) value(node);
} else if (name === 'class' && !isSvg) {
node.className = value || '';
} else if (name === 'style') {
if (!value || typeof value === 'string' || typeof old === 'string') {
node.style.cssText = value || '';
}
if (value && typeof value === 'object') {
if (typeof old !== 'string') {
for (var i in old) {
if (!(i in value)) node.style[i] = '';
}
}
for (var i in value) {
node.style[i] = typeof value[i] === 'number' && IS_NON_DIMENSIONAL.test(i) === false ? value[i] + 'px' : value[i];
}
}
} else if (name === 'dangerouslySetInnerHTML') {
if (value) node.innerHTML = value.__html || '';
} else if (name[0] == 'o' && name[1] == 'n') {
var useCapture = name !== (name = name.replace(/Capture$/, ''));
name = name.toLowerCase().substring(2);
if (value) {
if (!old) node.addEventListener(name, eventProxy, useCapture);
} else {
node.removeEventListener(name, eventProxy, useCapture);
}
(node._listeners || (node._listeners = {}))[name] = value;
} else if (name !== 'list' && name !== 'type' && !isSvg && name in node) {
try {
node[name] = value == null ? '' : value;
} catch (e) {}
if ((value == null || value === false) && name != 'spellcheck') node.removeAttribute(name);
} else {
var ns = isSvg && name !== (name = name.replace(/^xlink:?/, ''));
if (value == null || value === false) {
if (ns) node.removeAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase());else node.removeAttribute(name);
} else if (typeof value !== 'function') {
if (ns) node.setAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase(), value);else node.setAttribute(name, value);
}
}
}
function eventProxy(e) {
return this._listeners[e.type](options.event && options.event(e) || e);
}
var mounts = [];
var diffLevel = 0;
var isSvgMode = false;
var hydrating = false;
function flushMounts() {
var c;
while (c = mounts.pop()) {
if (options.afterMount) options.afterMount(c);
if (c.componentDidMount) c.componentDidMount();
}
}
function diff(dom, vnode, context, mountAll, parent, componentRoot) {
if (!diffLevel++) {
isSvgMode = parent != null && parent.ownerSVGElement !== undefined;
hydrating = dom != null && !('__preactattr_' in dom);
}
var ret = idiff(dom, vnode, context, mountAll, componentRoot);
if (parent && ret.parentNode !== parent) parent.appendChild(ret);
if (! --diffLevel) {
hydrating = false;
if (!componentRoot) flushMounts();
}
return ret;
}
function idiff(dom, vnode, context, mountAll, componentRoot) {
var out = dom,
prevSvgMode = isSvgMode;
if (vnode == null || typeof vnode === 'boolean') vnode = '';
if (typeof vnode === 'string' || typeof vnode === 'number') {
if (dom && dom.splitText !== undefined && dom.parentNode && (!dom._component || componentRoot)) {
if (dom.nodeValue != vnode) {
dom.nodeValue = vnode;
}
} else {
out = document.createTextNode(vnode);
if (dom) {
if (dom.parentNode) dom.parentNode.replaceChild(out, dom);
recollectNodeTree(dom, true);
}
}
out['__preactattr_'] = true;
return out;
}
var vnodeName = vnode.nodeName;
if (typeof vnodeName === 'function') {
return buildComponentFromVNode(dom, vnode, context, mountAll);
}
isSvgMode = vnodeName === 'svg' ? true : vnodeName === 'foreignObject' ? false : isSvgMode;
vnodeName = String(vnodeName);
if (!dom || !isNamedNode(dom, vnodeName)) {
out = createNode(vnodeName, isSvgMode);
if (dom) {
while (dom.firstChild) {
out.appendChild(dom.firstChild);
}
if (dom.parentNode) dom.parentNode.replaceChild(out, dom);
recollectNodeTree(dom, true);
}
}
var fc = out.firstChild,
props = out['__preactattr_'],
vchildren = vnode.children;
if (props == null) {
props = out['__preactattr_'] = {};
for (var a = out.attributes, i = a.length; i--;) {
props[a[i].name] = a[i].value;
}
}
if (!hydrating && vchildren && vchildren.length === 1 && typeof vchildren[0] === 'string' && fc != null && fc.splitText !== undefined && fc.nextSibling == null) {
if (fc.nodeValue != vchildren[0]) {
fc.nodeValue = vchildren[0];
}
} else if (vchildren && vchildren.length || fc != null) {
innerDiffNode(out, vchildren, context, mountAll, hydrating || props.dangerouslySetInnerHTML != null);
}
diffAttributes(out, vnode.attributes, props);
isSvgMode = prevSvgMode;
return out;
}
function innerDiffNode(dom, vchildren, context, mountAll, isHydrating) {
var originalChildren = dom.childNodes,
children = [],
keyed = {},
keyedLen = 0,
min = 0,
len = originalChildren.length,
childrenLen = 0,
vlen = vchildren ? vchildren.length : 0,
j,
c,
f,
vchild,
child;
if (len !== 0) {
for (var i = 0; i < len; i++) {
var _child = originalChildren[i],
props = _child['__preactattr_'],
key = vlen && props ? _child._component ? _child._component.__key : props.key : null;
if (key != null) {
keyedLen++;
keyed[key] = _child;
} else if (props || (_child.splitText !== undefined ? isHydrating ? _child.nodeValue.trim() : true : isHydrating)) {
children[childrenLen++] = _child;
}
}
}
if (vlen !== 0) {
for (var i = 0; i < vlen; i++) {
vchild = vchildren[i];
child = null;
var key = vchild.key;
if (key != null) {
if (keyedLen && keyed[key] !== undefined) {
child = keyed[key];
keyed[key] = undefined;
keyedLen--;
}
} else if (min < childrenLen) {
for (j = min; j < childrenLen; j++) {
if (children[j] !== undefined && isSameNodeType(c = children[j], vchild, isHydrating)) {
child = c;
children[j] = undefined;
if (j === childrenLen - 1) childrenLen--;
if (j === min) min++;
break;
}
}
}
child = idiff(child, vchild, context, mountAll);
f = originalChildren[i];
if (child && child !== dom && child !== f) {
if (f == null) {
dom.appendChild(child);
} else if (child === f.nextSibling) {
removeNode(f);
} else {
dom.insertBefore(child, f);
}
}
}
}
if (keyedLen) {
for (var i in keyed) {
if (keyed[i] !== undefined) recollectNodeTree(keyed[i], false);
}
}
while (min <= childrenLen) {
if ((child = children[childrenLen--]) !== undefined) recollectNodeTree(child, false);
}
}
function recollectNodeTree(node, unmountOnly) {
var component = node._component;
if (component) {
unmountComponent(component);
} else {
if (node['__preactattr_'] != null && node['__preactattr_'].ref) node['__preactattr_'].ref(null);
if (unmountOnly === false || node['__preactattr_'] == null) {
removeNode(node);
}
removeChildren(node);
}
}
function removeChildren(node) {
node = node.lastChild;
while (node) {
var next = node.previousSibling;
recollectNodeTree(node, true);
node = next;
}
}
function diffAttributes(dom, attrs, old) {
var name;
for (name in old) {
if (!(attrs && attrs[name] != null) && old[name] != null) {
setAccessor(dom, name, old[name], old[name] = undefined, isSvgMode);
}
}
for (name in attrs) {
if (name !== 'children' && name !== 'innerHTML' && (!(name in old) || attrs[name] !== (name === 'value' || name === 'checked' ? dom[name] : old[name]))) {
setAccessor(dom, name, old[name], old[name] = attrs[name], isSvgMode);
}
}
}
var recyclerComponents = [];
function createComponent(Ctor, props, context) {
var inst,
i = recyclerComponents.length;
if (Ctor.prototype && Ctor.prototype.render) {
inst = new Ctor(props, context);
Component.call(inst, props, context);
} else {
inst = new Component(props, context);
inst.constructor = Ctor;
inst.render = doRender;
}
while (i--) {
if (recyclerComponents[i].constructor === Ctor) {
inst.nextBase = recyclerComponents[i].nextBase;
recyclerComponents.splice(i, 1);
return inst;
}
}
return inst;
}
function doRender(props, state, context) {
return this.constructor(props, context);
}
function setComponentProps(component, props, renderMode, context, mountAll) {
if (component._disable) return;
component._disable = true;
component.__ref = props.ref;
component.__key = props.key;
delete props.ref;
delete props.key;
if (typeof component.constructor.getDerivedStateFromProps === 'undefined') {
if (!component.base || mountAll) {
if (component.componentWillMount) component.componentWillMount();
} else if (component.componentWillReceiveProps) {
component.componentWillReceiveProps(props, context);
}
}
if (context && context !== component.context) {
if (!component.prevContext) component.prevContext = component.context;
component.context = context;
}
if (!component.prevProps) component.prevProps = component.props;
component.props = props;
component._disable = false;
if (renderMode !== 0) {
if (renderMode === 1 || options.syncComponentUpdates !== false || !component.base) {
renderComponent(component, 1, mountAll);
} else {
enqueueRender(component);
}
}
if (component.__ref) component.__ref(component);
}
function renderComponent(component, renderMode, mountAll, isChild) {
if (component._disable) return;
var props = component.props,
state = component.state,
context = component.context,
previousProps = component.prevProps || props,
previousState = component.prevState || state,
previousContext = component.prevContext || context,
isUpdate = component.base,
nextBase = component.nextBase,
initialBase = isUpdate || nextBase,
initialChildComponent = component._component,
skip = false,
snapshot = previousContext,
rendered,
inst,
cbase;
if (component.constructor.getDerivedStateFromProps) {
state = extend(extend({}, state), component.constructor.getDerivedStateFromProps(props, state));
component.state = state;
}
if (isUpdate) {
component.props = previousProps;
component.state = previousState;
component.context = previousContext;
if (renderMode !== 2 && component.shouldComponentUpdate && component.shouldComponentUpdate(props, state, context) === false) {
skip = true;
} else if (component.componentWillUpdate) {
component.componentWillUpdate(props, state, context);
}
component.props = props;
component.state = state;
component.context = context;
}
component.prevProps = component.prevState = component.prevContext = component.nextBase = null;
component._dirty = false;
if (!skip) {
rendered = component.render(props, state, context);
if (component.getChildContext) {
context = extend(extend({}, context), component.getChildContext());
}
if (isUpdate && component.getSnapshotBeforeUpdate) {
snapshot = component.getSnapshotBeforeUpdate(previousProps, previousState);
}
var childComponent = rendered && rendered.nodeName,
toUnmount,
base;
if (typeof childComponent === 'function') {
var childProps = getNodeProps(rendered);
inst = initialChildComponent;
if (inst && inst.constructor === childComponent && childProps.key == inst.__key) {
setComponentProps(inst, childProps, 1, context, false);
} else {
toUnmount = inst;
component._component = inst = createComponent(childComponent, childProps, context);
inst.nextBase = inst.nextBase || nextBase;
inst._parentComponent = component;
setComponentProps(inst, childProps, 0, context, false);
renderComponent(inst, 1, mountAll, true);
}
base = inst.base;
} else {
cbase = initialBase;
toUnmount = initialChildComponent;
if (toUnmount) {
cbase = component._component = null;
}
if (initialBase || renderMode === 1) {
if (cbase) cbase._component = null;
base = diff(cbase, rendered, context, mountAll || !isUpdate, initialBase && initialBase.parentNode, true);
}
}
if (initialBase && base !== initialBase && inst !== initialChildComponent) {
var baseParent = initialBase.parentNode;
if (baseParent && base !== baseParent) {
baseParent.replaceChild(base, initialBase);
if (!toUnmount) {
initialBase._component = null;
recollectNodeTree(initialBase, false);
}
}
}
if (toUnmount) {
unmountComponent(toUnmount);
}
component.base = base;
if (base && !isChild) {
var componentRef = component,
t = component;
while (t = t._parentComponent) {
(componentRef = t).base = base;
}
base._component = componentRef;
base._componentConstructor = componentRef.constructor;
}
}
if (!isUpdate || mountAll) {
mounts.unshift(component);
} else if (!skip) {
if (component.componentDidUpdate) {
component.componentDidUpdate(previousProps, previousState, snapshot);
}
if (options.afterUpdate) options.afterUpdate(component);
}
while (component._renderCallbacks.length) {
component._renderCallbacks.pop().call(component);
}if (!diffLevel && !isChild) flushMounts();
}
function buildComponentFromVNode(dom, vnode, context, mountAll) {
var c = dom && dom._component,
originalComponent = c,
oldDom = dom,
isDirectOwner = c && dom._componentConstructor === vnode.nodeName,
isOwner = isDirectOwner,
props = getNodeProps(vnode);
while (c && !isOwner && (c = c._parentComponent)) {
isOwner = c.constructor === vnode.nodeName;
}
if (c && isOwner && (!mountAll || c._component)) {
setComponentProps(c, props, 3, context, mountAll);
dom = c.base;
} else {
if (originalComponent && !isDirectOwner) {
unmountComponent(originalComponent);
dom = oldDom = null;
}
c = createComponent(vnode.nodeName, props, context);
if (dom && !c.nextBase) {
c.nextBase = dom;
oldDom = null;
}
setComponentProps(c, props, 1, context, mountAll);
dom = c.base;
if (oldDom && dom !== oldDom) {
oldDom._component = null;
recollectNodeTree(oldDom, false);
}
}
return dom;
}
function unmountComponent(component) {
if (options.beforeUnmount) options.beforeUnmount(component);
var base = component.base;
component._disable = true;
if (component.componentWillUnmount) component.componentWillUnmount();
component.base = null;
var inner = component._component;
if (inner) {
unmountComponent(inner);
} else if (base) {
if (base['__preactattr_'] && base['__preactattr_'].ref) base['__preactattr_'].ref(null);
component.nextBase = base;
removeNode(base);
recyclerComponents.push(component);
removeChildren(base);
}
if (component.__ref) component.__ref(null);
}
function Component(props, context) {
this._dirty = true;
this.context = context;
this.props = props;
this.state = this.state || {};
this._renderCallbacks = [];
}
extend(Component.prototype, {
setState: function setState(state, callback) {
if (!this.prevState) this.prevState = this.state;
this.state = extend(extend({}, this.state), typeof state === 'function' ? state(this.state, this.props) : state);
if (callback) this._renderCallbacks.push(callback);
enqueueRender(this);
},
forceUpdate: function forceUpdate(callback) {
if (callback) this._renderCallbacks.push(callback);
renderComponent(this, 2);
},
render: function render() {}
});
function render(vnode, parent, merge) {
return diff(merge, vnode, {}, false, parent, false);
}
var preact = {
h: h,
createElement: h,
cloneElement: cloneElement,
Component: Component,
render: render,
rerender: rerender,
options: options
};
exports.default = preact;
exports.h = h;
exports.createElement = h;
exports.cloneElement = cloneElement;
exports.Component = Component;
exports.render = render;
exports.rerender = rerender;
exports.options = options;
//# sourceMappingURL=preact.mjs.map
},{}],"8wWJ":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.messages = [["It has been", "since King Gizzard and the Lizard Wizard last released an album"], ["Already", "since the newest King Gizzie and the Lizzie Wizzie came out"], ["Phew! it has been", "since the last album of the King Gizzard and the Lizard Wizard boys"], ["It has been", "since we got new epic music and flute solos from the King Gizzardos and the Lizard Wizardos"]];
function getRandMessage() {
var randomIdx = Math.floor(Math.random() * this.messages.length);
return this.messages[randomIdx];
}
exports.getRandMessage = getRandMessage;
exports.defaultDate = new Date("2017-12-31T08:00:00Z"); //Gumboot Soup Release Date
exports.RequestCredentials = {
apikey: "980245d987a606ff935db4b119108d78",
artist_id: "13962767"
};
},{}],"TkLn":[function(require,module,exports) {
/*global window */
/**
* @license countdown.js v2.6.0 http://countdownjs.org
* Copyright (c)2006-2014 Stephen M. McKamey.
* Licensed under The MIT License.
*/
/*jshint bitwise:false */
/**
* @public
* @type {Object|null}
*/
var module;
/**
* API entry
* @public
* @param {function(Object)|Date|number} start the starting date
* @param {function(Object)|Date|number} end the ending date
* @param {number} units the units to populate
* @return {Object|number}
*/
var countdown = (
/**
* @param {Object} module CommonJS Module
*/
function(module) {
/*jshint smarttabs:true */
'use strict';
/**
* @private
* @const
* @type {number}
*/
var MILLISECONDS = 0x001;
/**
* @private
* @const
* @type {number}
*/
var SECONDS = 0x002;
/**
* @private
* @const
* @type {number}
*/
var MINUTES = 0x004;
/**
* @private
* @const
* @type {number}
*/
var HOURS = 0x008;
/**
* @private
* @const
* @type {number}
*/
var DAYS = 0x010;
/**
* @private
* @const
* @type {number}
*/
var WEEKS = 0x020;
/**
* @private
* @const
* @type {number}
*/
var MONTHS = 0x040;
/**
* @private
* @const
* @type {number}
*/
var YEARS = 0x080;
/**
* @private
* @const
* @type {number}
*/
var DECADES = 0x100;
/**
* @private
* @const
* @type {number}
*/
var CENTURIES = 0x200;
/**
* @private
* @const
* @type {number}
*/
var MILLENNIA = 0x400;
/**
* @private
* @const
* @type {number}
*/
var DEFAULTS = YEARS|MONTHS|DAYS|HOURS|MINUTES|SECONDS;
/**
* @private
* @const
* @type {number}
*/
var MILLISECONDS_PER_SECOND = 1000;
/**
* @private
* @const
* @type {number}
*/
var SECONDS_PER_MINUTE = 60;
/**
* @private
* @const
* @type {number}
*/
var MINUTES_PER_HOUR = 60;
/**
* @private
* @const
* @type {number}
*/
var HOURS_PER_DAY = 24;
/**
* @private
* @const
* @type {number}
*/
var MILLISECONDS_PER_DAY = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MILLISECONDS_PER_SECOND;
/**
* @private
* @const
* @type {number}
*/
var DAYS_PER_WEEK = 7;
/**
* @private
* @const
* @type {number}
*/
var MONTHS_PER_YEAR = 12;
/**
* @private
* @const
* @type {number}
*/
var YEARS_PER_DECADE = 10;
/**
* @private
* @const
* @type {number}
*/
var DECADES_PER_CENTURY = 10;
/**
* @private
* @const
* @type {number}
*/
var CENTURIES_PER_MILLENNIUM = 10;
/**
* @private
* @param {number} x number
* @return {number}
*/
var ceil = Math.ceil;
/**
* @private
* @param {number} x number
* @return {number}
*/
var floor = Math.floor;
/**
* @private
* @param {Date} ref reference date
* @param {number} shift number of months to shift
* @return {number} number of days shifted
*/
function borrowMonths(ref, shift) {
var prevTime = ref.getTime();
// increment month by shift
ref.setMonth( ref.getMonth() + shift );
// this is the trickiest since months vary in length
return Math.round( (ref.getTime() - prevTime) / MILLISECONDS_PER_DAY );
}
/**
* @private
* @param {Date} ref reference date
* @return {number} number of days
*/
function daysPerMonth(ref) {
var a = ref.getTime();
// increment month by 1
var b = new Date(a);
b.setMonth( ref.getMonth() + 1 );
// this is the trickiest since months vary in length
return Math.round( (b.getTime() - a) / MILLISECONDS_PER_DAY );
}
/**
* @private
* @param {Date} ref reference date
* @return {number} number of days
*/
function daysPerYear(ref) {
var a = ref.getTime();
// increment year by 1
var b = new Date(a);
b.setFullYear( ref.getFullYear() + 1 );
// this is the trickiest since years (periodically) vary in length
return Math.round( (b.getTime() - a) / MILLISECONDS_PER_DAY );
}
/**
* Applies the Timespan to the given date.
*
* @private
* @param {Timespan} ts
* @param {Date=} date
* @return {Date}
*/
function addToDate(ts, date) {
date = (date instanceof Date) || ((date !== null) && isFinite(date)) ? new Date(+date) : new Date();
if (!ts) {
return date;
}
// if there is a value field, use it directly
var value = +ts.value || 0;
if (value) {
date.setTime(date.getTime() + value);
return date;
}
value = +ts.milliseconds || 0;
if (value) {
date.setMilliseconds(date.getMilliseconds() + value);
}
value = +ts.seconds || 0;
if (value) {
date.setSeconds(date.getSeconds() + value);
}
value = +ts.minutes || 0;
if (value) {
date.setMinutes(date.getMinutes() + value);
}
value = +ts.hours || 0;
if (value) {
date.setHours(date.getHours() + value);
}
value = +ts.weeks || 0;
if (value) {
value *= DAYS_PER_WEEK;
}
value += +ts.days || 0;
if (value) {
date.setDate(date.getDate() + value);
}
value = +ts.months || 0;
if (value) {
date.setMonth(date.getMonth() + value);
}
value = +ts.millennia || 0;
if (value) {
value *= CENTURIES_PER_MILLENNIUM;
}
value += +ts.centuries || 0;
if (value) {
value *= DECADES_PER_CENTURY;
}
value += +ts.decades || 0;
if (value) {
value *= YEARS_PER_DECADE;
}
value += +ts.years || 0;
if (value) {
date.setFullYear(date.getFullYear() + value);
}
return date;
}
/**
* @private
* @const
* @type {number}
*/
var LABEL_MILLISECONDS = 0;
/**
* @private
* @const
* @type {number}
*/
var LABEL_SECONDS = 1;
/**
* @private
* @const
* @type {number}
*/
var LABEL_MINUTES = 2;
/**
* @private
* @const
* @type {number}
*/
var LABEL_HOURS = 3;
/**
* @private
* @const
* @type {number}
*/
var LABEL_DAYS = 4;
/**
* @private
* @const
* @type {number}
*/
var LABEL_WEEKS = 5;
/**
* @private
* @const
* @type {number}
*/
var LABEL_MONTHS = 6;
/**
* @private
* @const
* @type {number}
*/
var LABEL_YEARS = 7;
/**
* @private
* @const
* @type {number}
*/
var LABEL_DECADES = 8;
/**
* @private
* @const
* @type {number}
*/
var LABEL_CENTURIES = 9;
/**
* @private
* @const
* @type {number}
*/
var LABEL_MILLENNIA = 10;
/**
* @private
* @type {Array}
*/
var LABELS_SINGLUAR;
/**
* @private
* @type {Array}
*/
var LABELS_PLURAL;
/**
* @private
* @type {string}
*/
var LABEL_LAST;
/**
* @private
* @type {string}
*/
var LABEL_DELIM;
/**
* @private
* @type {string}
*/
var LABEL_NOW;
/**
* Formats a number & unit as a string
*
* @param {number} value
* @param {number} unit
* @return {string}
*/
var formatter;
/**
* Formats a number as a string
*
* @private
* @param {number} value
* @return {string}
*/
var formatNumber;
/**
* @private
* @param {number} value
* @param {number} unit unit index into label list
* @return {string}
*/
function plurality(value, unit) {
return formatNumber(value)+((value === 1) ? LABELS_SINGLUAR[unit] : LABELS_PLURAL[unit]);
}
/**
* Formats the entries with singular or plural labels
*
* @private
* @param {Timespan} ts
* @return {Array}
*/
var formatList;
/**
* Timespan representation of a duration of time
*
* @private
* @this {Timespan}
* @constructor
*/
function Timespan() {}
/**
* Formats the Timespan as a sentence
*
* @param {string=} emptyLabel the string to use when no values returned
* @return {string}
*/
Timespan.prototype.toString = function(emptyLabel) {
var label = formatList(this);
var count = label.length;
if (!count) {
return emptyLabel ? ''+emptyLabel : LABEL_NOW;
}
if (count === 1) {
return label[0];
}
var last = LABEL_LAST+label.pop();
return label.join(LABEL_DELIM)+last;
};
/**
* Formats the Timespan as a sentence in HTML
*
* @param {string=} tag HTML tag name to wrap each value
* @param {string=} emptyLabel the string to use when no values returned
* @return {string}
*/
Timespan.prototype.toHTML = function(tag, emptyLabel) {
tag = tag || 'span';
var label = formatList(this);
var count = label.length;
if (!count) {
emptyLabel = emptyLabel || LABEL_NOW;
return emptyLabel ? '<'+tag+'>'+emptyLabel+'</'+tag+'>' : emptyLabel;
}
for (var i=0; i<count; i++) {
// wrap each unit in tag
label[i] = '<'+tag+'>'+label[i]+'</'+tag+'>';
}
if (count === 1) {
return label[0];
}
var last = LABEL_LAST+label.pop();
return label.join(LABEL_DELIM)+last;
};
/**
* Applies the Timespan to the given date
*
* @param {Date=} date the date to which the timespan is added.
* @return {Date}
*/
Timespan.prototype.addTo = function(date) {
return addToDate(this, date);
};
/**
* Formats the entries as English labels
*
* @private
* @param {Timespan} ts
* @return {Array}
*/
formatList = function(ts) {
var list = [];
var value = ts.millennia;
if (value) {
list.push(formatter(value, LABEL_MILLENNIA));
}
value = ts.centuries;
if (value) {
list.push(formatter(value, LABEL_CENTURIES));
}
value = ts.decades;
if (value) {
list.push(formatter(value, LABEL_DECADES));
}
value = ts.years;
if (value) {
list.push(formatter(value, LABEL_YEARS));
}
value = ts.months;
if (value) {
list.push(formatter(value, LABEL_MONTHS));
}
value = ts.weeks;
if (value) {
list.push(formatter(value, LABEL_WEEKS));
}
value = ts.days;
if (value) {
list.push(formatter(value, LABEL_DAYS));
}
value = ts.hours;
if (value) {
list.push(formatter(value, LABEL_HOURS));
}
value = ts.minutes;
if (value) {
list.push(formatter(value, LABEL_MINUTES));
}
value = ts.seconds;
if (value) {
list.push(formatter(value, LABEL_SECONDS));
}
value = ts.milliseconds;
if (value) {
list.push(formatter(value, LABEL_MILLISECONDS));
}
return list;
};
/**
* Borrow any underflow units, carry any overflow units
*
* @private
* @param {Timespan} ts
* @param {string} toUnit
*/
function rippleRounded(ts, toUnit) {
switch (toUnit) {
case 'seconds':
if (ts.seconds !== SECONDS_PER_MINUTE || isNaN(ts.minutes)) {
return;
}
// ripple seconds up to minutes
ts.minutes++;
ts.seconds = 0;
/* falls through */
case 'minutes':
if (ts.minutes !== MINUTES_PER_HOUR || isNaN(ts.hours)) {
return;
}
// ripple minutes up to hours
ts.hours++;
ts.minutes = 0;
/* falls through */
case 'hours':
if (ts.hours !== HOURS_PER_DAY || isNaN(ts.days)) {
return;
}
// ripple hours up to days
ts.days++;
ts.hours = 0;
/* falls through */
case 'days':
if (ts.days !== DAYS_PER_WEEK || isNaN(ts.weeks)) {
return;
}
// ripple days up to weeks
ts.weeks++;
ts.days = 0;
/* falls through */
case 'weeks':
if (ts.weeks !== daysPerMonth(ts.refMonth)/DAYS_PER_WEEK || isNaN(ts.months)) {
return;
}
// ripple weeks up to months
ts.months++;
ts.weeks = 0;
/* falls through */
case 'months':
if (ts.months !== MONTHS_PER_YEAR || isNaN(ts.years)) {
return;
}
// ripple months up to years
ts.years++;
ts.months = 0;
/* falls through */
case 'years':
if (ts.years !== YEARS_PER_DECADE || isNaN(ts.decades)) {
return;
}
// ripple years up to decades
ts.decades++;
ts.years = 0;
/* falls through */
case 'decades':
if (ts.decades !== DECADES_PER_CENTURY || isNaN(ts.centuries)) {
return;
}
// ripple decades up to centuries
ts.centuries++;
ts.decades = 0;
/* falls through */
case 'centuries':
if (ts.centuries !== CENTURIES_PER_MILLENNIUM || isNaN(ts.millennia)) {
return;
}
// ripple centuries up to millennia
ts.millennia++;
ts.centuries = 0;
/* falls through */
}
}
/**
* Ripple up partial units one place
*
* @private
* @param {Timespan} ts timespan
* @param {number} frac accumulated fractional value
* @param {string} fromUnit source unit name
* @param {string} toUnit target unit name
* @param {number} conversion multiplier between units
* @param {number} digits max number of decimal digits to output
* @return {number} new fractional value
*/
function fraction(ts, frac, fromUnit, toUnit, conversion, digits) {
if (ts[fromUnit] >= 0) {
frac += ts[fromUnit];
delete ts[fromUnit];
}
frac /= conversion;
if (frac + 1 <= 1) {
// drop if below machine epsilon
return 0;
}
if (ts[toUnit] >= 0) {
// ensure does not have more than specified number of digits
ts[toUnit] = +(ts[toUnit] + frac).toFixed(digits);
rippleRounded(ts, toUnit);
return 0;
}
return frac;
}
/**
* Ripple up partial units to next existing
*
* @private
* @param {Timespan} ts
* @param {number} digits max number of decimal digits to output
*/
function fractional(ts, digits) {
var frac = fraction(ts, 0, 'milliseconds', 'seconds', MILLISECONDS_PER_SECOND, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'seconds', 'minutes', SECONDS_PER_MINUTE, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'minutes', 'hours', MINUTES_PER_HOUR, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'hours', 'days', HOURS_PER_DAY, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'days', 'weeks', DAYS_PER_WEEK, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'weeks', 'months', daysPerMonth(ts.refMonth)/DAYS_PER_WEEK, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'months', 'years', daysPerYear(ts.refMonth)/daysPerMonth(ts.refMonth), digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'years', 'decades', YEARS_PER_DECADE, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'decades', 'centuries', DECADES_PER_CENTURY, digits);
if (!frac) { return; }
frac = fraction(ts, frac, 'centuries', 'millennia', CENTURIES_PER_MILLENNIUM, digits);
// should never reach this with remaining fractional value
if (frac) { throw new Error('Fractional unit overflow'); }
}
/**
* Borrow any underflow units, carry any overflow units
*
* @private
* @param {Timespan} ts
*/
function ripple(ts) {
var x;
if (ts.milliseconds < 0) {
// ripple seconds down to milliseconds
x = ceil(-ts.milliseconds / MILLISECONDS_PER_SECOND);
ts.seconds -= x;
ts.milliseconds += x * MILLISECONDS_PER_SECOND;
} else if (ts.milliseconds >= MILLISECONDS_PER_SECOND) {
// ripple milliseconds up to seconds
ts.seconds += floor(ts.milliseconds / MILLISECONDS_PER_SECOND);
ts.milliseconds %= MILLISECONDS_PER_SECOND;
}
if (ts.seconds < 0) {
// ripple minutes down to seconds
x = ceil(-ts.seconds / SECONDS_PER_MINUTE);
ts.minutes -= x;
ts.seconds += x * SECONDS_PER_MINUTE;
} else if (ts.seconds >= SECONDS_PER_MINUTE) {
// ripple seconds up to minutes
ts.minutes += floor(ts.seconds / SECONDS_PER_MINUTE);
ts.seconds %= SECONDS_PER_MINUTE;
}
if (ts.minutes < 0) {
// ripple hours down to minutes
x = ceil(-ts.minutes / MINUTES_PER_HOUR);
ts.hours -= x;
ts.minutes += x * MINUTES_PER_HOUR;
} else if (ts.minutes >= MINUTES_PER_HOUR) {
// ripple minutes up to hours
ts.hours += floor(ts.minutes / MINUTES_PER_HOUR);
ts.minutes %= MINUTES_PER_HOUR;
}
if (ts.hours < 0) {
// ripple days down to hours
x = ceil(-ts.hours / HOURS_PER_DAY);
ts.days -= x;
ts.hours += x * HOURS_PER_DAY;
} else if (ts.hours >= HOURS_PER_DAY) {
// ripple hours up to days
ts.days += floor(ts.hours / HOURS_PER_DAY);
ts.hours %= HOURS_PER_DAY;
}
while (ts.days < 0) {
// NOTE: never actually seen this loop more than once
// ripple months down to days
ts.months--;
ts.days += borrowMonths(ts.refMonth, 1);
}
// weeks is always zero here
if (ts.days >= DAYS_PER_WEEK) {
// ripple days up to weeks
ts.weeks += floor(ts.days / DAYS_PER_WEEK);
ts.days %= DAYS_PER_WEEK;
}
if (ts.months < 0) {
// ripple years down to months
x = ceil(-ts.months / MONTHS_PER_YEAR);
ts.years -= x;
ts.months += x * MONTHS_PER_YEAR;
} else if (ts.months >= MONTHS_PER_YEAR) {
// ripple months up to years
ts.years += floor(ts.months / MONTHS_PER_YEAR);
ts.months %= MONTHS_PER_YEAR;
}
// years is always non-negative here
// decades, centuries and millennia are always zero here
if (ts.years >= YEARS_PER_DECADE) {
// ripple years up to decades
ts.decades += floor(ts.years / YEARS_PER_DECADE);
ts.years %= YEARS_PER_DECADE;
if (ts.decades >= DECADES_PER_CENTURY) {
// ripple decades up to centuries
ts.centuries += floor(ts.decades / DECADES_PER_CENTURY);
ts.decades %= DECADES_PER_CENTURY;
if (ts.centuries >= CENTURIES_PER_MILLENNIUM) {
// ripple centuries up to millennia
ts.millennia += floor(ts.centuries / CENTURIES_PER_MILLENNIUM);
ts.centuries %= CENTURIES_PER_MILLENNIUM;
}
}
}
}
/**
* Remove any units not requested
*
* @private
* @param {Timespan} ts
* @param {number} units the units to populate
* @param {number} max number of labels to output
* @param {number} digits max number of decimal digits to output
*/
function pruneUnits(ts, units, max, digits) {
var count = 0;
// Calc from largest unit to smallest to prevent underflow
if (!(units & MILLENNIA) || (count >= max)) {
// ripple millennia down to centuries
ts.centuries += ts.millennia * CENTURIES_PER_MILLENNIUM;
delete ts.millennia;
} else if (ts.millennia) {
count++;
}
if (!(units & CENTURIES) || (count >= max)) {
// ripple centuries down to decades
ts.decades += ts.centuries * DECADES_PER_CENTURY;
delete ts.centuries;
} else if (ts.centuries) {
count++;
}
if (!(units & DECADES) || (count >= max)) {
// ripple decades down to years
ts.years += ts.decades * YEARS_PER_DECADE;
delete ts.decades;
} else if (ts.decades) {
count++;
}
if (!(units & YEARS) || (count >= max)) {
// ripple years down to months
ts.months += ts.years * MONTHS_PER_YEAR;
delete ts.years;
} else if (ts.years) {
count++;
}
if (!(units & MONTHS) || (count >= max)) {
// ripple months down to days
if (ts.months) {
ts.days += borrowMonths(ts.refMonth, ts.months);
}
delete ts.months;
if (ts.days >= DAYS_PER_WEEK) {
// ripple day overflow back up to weeks
ts.weeks += floor(ts.days / DAYS_PER_WEEK);
ts.days %= DAYS_PER_WEEK;
}
} else if (ts.months) {
count++;
}
if (!(units & WEEKS) || (count >= max)) {
// ripple weeks down to days
ts.days += ts.weeks * DAYS_PER_WEEK;
delete ts.weeks;
} else if (ts.weeks) {
count++;
}
if (!(units & DAYS) || (count >= max)) {
//ripple days down to hours
ts.hours += ts.days * HOURS_PER_DAY;
delete ts.days;
} else if (ts.days) {
count++;
}
if (!(units & HOURS) || (count >= max)) {
// ripple hours down to minutes
ts.minutes += ts.hours * MINUTES_PER_HOUR;
delete ts.hours;
} else if (ts.hours) {
count++;
}
if (!(units & MINUTES) || (count >= max)) {
// ripple minutes down to seconds
ts.seconds += ts.minutes * SECONDS_PER_MINUTE;
delete ts.minutes;
} else if (ts.minutes) {
count++;
}
if (!(units & SECONDS) || (count >= max)) {
// ripple seconds down to milliseconds
ts.milliseconds += ts.seconds * MILLISECONDS_PER_SECOND;
delete ts.seconds;
} else if (ts.seconds) {
count++;
}
// nothing to ripple milliseconds down to
// so ripple back up to smallest existing unit as a fractional value
if (!(units & MILLISECONDS) || (count >= max)) {
fractional(ts, digits);
}
}
/**
* Populates the Timespan object
*
* @private
* @param {Timespan} ts
* @param {?Date} start the starting date
* @param {?Date} end the ending date
* @param {number} units the units to populate
* @param {number} max number of labels to output
* @param {number} digits max number of decimal digits to output
*/
function populate(ts, start, end, units, max, digits) {
var now = new Date();
ts.start = start = start || now;
ts.end = end = end || now;
ts.units = units;
ts.value = end.getTime() - start.getTime();
if (ts.value < 0) {
// swap if reversed
var tmp = end;
end = start;
start = tmp;
}
// reference month for determining days in month
ts.refMonth = new Date(start.getFullYear(), start.getMonth(), 15, 12, 0, 0);
try {
// reset to initial deltas
ts.millennia = 0;
ts.centuries = 0;
ts.decades = 0;
ts.years = end.getFullYear() - start.getFullYear();
ts.months = end.getMonth() - start.getMonth();
ts.weeks = 0;
ts.days = end.getDate() - start.getDate();
ts.hours = end.getHours() - start.getHours();
ts.minutes = end.getMinutes() - start.getMinutes();
ts.seconds = end.getSeconds() - start.getSeconds();
ts.milliseconds = end.getMilliseconds() - start.getMilliseconds();
ripple(ts);
pruneUnits(ts, units, max, digits);
} finally {
delete ts.refMonth;
}
return ts;
}
/**
* Determine an appropriate refresh rate based upon units
*
* @private
* @param {number} units the units to populate
* @return {number} milliseconds to delay
*/
function getDelay(units) {
if (units & MILLISECONDS) {
// refresh very quickly
return MILLISECONDS_PER_SECOND / 30; //30Hz
}
if (units & SECONDS) {
// refresh every second
return MILLISECONDS_PER_SECOND; //1Hz
}
if (units & MINUTES) {
// refresh every minute
return MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE;
}
if (units & HOURS) {
// refresh hourly
return MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE * MINUTES_PER_HOUR;
}
if (units & DAYS) {
// refresh daily
return MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY;
}
// refresh the rest weekly
return MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY * DAYS_PER_WEEK;
}
/**
* API entry point
*
* @public
* @param {Date|number|Timespan|null|function(Timespan,number)} start the starting date
* @param {Date|number|Timespan|null|function(Timespan,number)} end the ending date
* @param {number=} units the units to populate
* @param {number=} max number of labels to output
* @param {number=} digits max number of decimal digits to output
* @return {Timespan|number}
*/
function countdown(start, end, units, max, digits) {
var callback;
// ensure some units or use defaults
units = +units || DEFAULTS;
// max must be positive
max = (max > 0) ? max : NaN;
// clamp digits to an integer between [0, 20]
digits = (digits > 0) ? (digits < 20) ? Math.round(digits) : 20 : 0;
// ensure start date
var startTS = null;
if ('function' === typeof start) {
callback = start;
start = null;
} else if (!(start instanceof Date)) {
if ((start !== null) && isFinite(start)) {
start = new Date(+start);
} else {
if ('object' === typeof startTS) {
startTS = /** @type{Timespan} */(start);
}
start = null;
}
}
// ensure end date
var endTS = null;
if ('function' === typeof end) {
callback = end;
end = null;
} else if (!(end instanceof Date)) {
if ((end !== null) && isFinite(end)) {
end = new Date(+end);
} else {
if ('object' === typeof end) {
endTS = /** @type{Timespan} */(end);
}
end = null;
}
}
// must wait to interpret timespans until after resolving dates
if (startTS) {
start = addToDate(startTS, end);
}
if (endTS) {
end = addToDate(endTS, start);
}
if (!start && !end) {
// used for unit testing
return new Timespan();
}
if (!callback) {
return populate(new Timespan(), /** @type{Date} */(start), /** @type{Date} */(end), /** @type{number} */(units), /** @type{number} */(max), /** @type{number} */(digits));
}
// base delay off units
var delay = getDelay(units),
timerId,
fn = function() {
callback(
populate(new Timespan(), /** @type{Date} */(start), /** @type{Date} */(end), /** @type{number} */(units), /** @type{number} */(max), /** @type{number} */(digits)),
timerId
);
};
fn();
return (timerId = setInterval(fn, delay));
}
/**
* @public
* @const
* @type {number}
*/
countdown.MILLISECONDS = MILLISECONDS;
/**
* @public
* @const
* @type {number}
*/
countdown.SECONDS = SECONDS;
/**
* @public
* @const
* @type {number}
*/
countdown.MINUTES = MINUTES;
/**
* @public
* @const
* @type {number}
*/
countdown.HOURS = HOURS;
/**
* @public
* @const
* @type {number}
*/
countdown.DAYS = DAYS;
/**
* @public
* @const
* @type {number}
*/
countdown.WEEKS = WEEKS;
/**
* @public
* @const
* @type {number}
*/
countdown.MONTHS = MONTHS;
/**
* @public
* @const
* @type {number}
*/
countdown.YEARS = YEARS;
/**
* @public
* @const
* @type {number}
*/
countdown.DECADES = DECADES;
/**
* @public
* @const
* @type {number}
*/
countdown.CENTURIES = CENTURIES;
/**
* @public
* @const
* @type {number}
*/
countdown.MILLENNIA = MILLENNIA;
/**
* @public
* @const
* @type {number}
*/
countdown.DEFAULTS = DEFAULTS;
/**
* @public
* @const
* @type {number}
*/
countdown.ALL = MILLENNIA|CENTURIES|DECADES|YEARS|MONTHS|WEEKS|DAYS|HOURS|MINUTES|SECONDS|MILLISECONDS;
/**
* Customize the format settings.
* @public
* @param {Object} format settings object
*/
var setFormat = countdown.setFormat = function(format) {
if (!format) { return; }
if ('singular' in format || 'plural' in format) {
var singular = format.singular || [];
if (singular.split) {
singular = singular.split('|');
}
var plural = format.plural || [];
if (plural.split) {
plural = plural.split('|');
}
for (var i=LABEL_MILLISECONDS; i<=LABEL_MILLENNIA; i++) {
// override any specified units
LABELS_SINGLUAR[i] = singular[i] || LABELS_SINGLUAR[i];
LABELS_PLURAL[i] = plural[i] || LABELS_PLURAL[i];
}
}
if ('string' === typeof format.last) {
LABEL_LAST = format.last;
}
if ('string' === typeof format.delim) {
LABEL_DELIM = format.delim;
}
if ('string' === typeof format.empty) {
LABEL_NOW = format.empty;
}
if ('function' === typeof format.formatNumber) {
formatNumber = format.formatNumber;
}
if ('function' === typeof format.formatter) {
formatter = format.formatter;
}
};
/**
* Revert to the default formatting.
* @public
*/
var resetFormat = countdown.resetFormat = function() {
LABELS_SINGLUAR = ' millisecond| second| minute| hour| day| week| month| year| decade| century| millennium'.split('|');
LABELS_PLURAL = ' milliseconds| seconds| minutes| hours| days| weeks| months| years| decades| centuries| millennia'.split('|');
LABEL_LAST = ' and ';
LABEL_DELIM = ', ';
LABEL_NOW = '';
formatNumber = function(value) { return value; };
formatter = plurality;
};
/**
* Override the unit labels.
* @public
* @param {string|Array=} singular a pipe ('|') delimited list of singular unit name overrides
* @param {string|Array=} plural a pipe ('|') delimited list of plural unit name overrides
* @param {string=} last a delimiter before the last unit (default: ' and ')
* @param {string=} delim a delimiter to use between all other units (default: ', ')
* @param {string=} empty a label to use when all units are zero (default: '')
* @param {function(number):string=} formatNumber a function which formats numbers as a string
* @param {function(number,number):string=} formatter a function which formats a number/unit pair as a string
* @deprecated since version 2.6.0
*/
countdown.setLabels = function(singular, plural, last, delim, empty, formatNumber, formatter) {
setFormat({
singular: singular,
plural: plural,
last: last,
delim: delim,
empty: empty,
formatNumber: formatNumber,
formatter: formatter
});
};
/**
* Revert to the default unit labels.
* @public
* @deprecated since version 2.6.0
*/
countdown.resetLabels = resetFormat;
resetFormat();
if (module && module.exports) {
module.exports = countdown;
} else if (typeof window.define === 'function' && typeof window.define.amd !== 'undefined') {
window.define('countdown', [], function() {
return countdown;
});
}
return countdown;
})(module);
},{}],"J6GP":[function(require,module,exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function (qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr,
vstr,
k,
v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
},{}],"bvhO":[function(require,module,exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var stringifyPrimitive = function (v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function (obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function (k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function (v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map(xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
},{}],"+00f":[function(require,module,exports) {
'use strict';
exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');
},{"./decode":"J6GP","./encode":"bvhO"}],"3Pj7":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("../utils/utils");
var querystring_1 = require("querystring");
function getLastAlbum() {
var promise = new Promise(function (resolve, reject) {
fetch("https://api.musixmatch.com/ws/1.1/artist.albums.get?" + querystring_1.stringify(RequestParams), {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
}).then(function (response) {
response.json().then(function (data) {
return data.error ? reject(data.error.message) : resolve(getLastDate(data));
}).catch(function (err) {
return reject(err);
});
}).catch(function (err) {
return reject(err);
});
});
return promise;
}
exports.getLastAlbum = getLastAlbum;
//Gets the last date from the object returned
function getLastDate(data) {
console.log("Data:", data);
return utils_1.defaultDate;
}
var RequestParams = {
apikey: "" + utils_1.RequestCredentials.apikey,
artist_id: "" + utils_1.RequestCredentials.artist_id,
s_release_date: "desc",
g_album_name: 1
};
},{"../utils/utils":"8wWJ","querystring":"+00f"}],"8Jz0":[function(require,module,exports) {
"use strict";
var __extends = this && this.__extends || function () {
var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) {
if (b.hasOwnProperty(p)) d[p] = b[p];
}
};
return function (d, b) {
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
}();
Object.defineProperty(exports, "__esModule", { value: true });
var preact_1 = require("preact");
var countdown = require("countdown");
var services_1 = require("../utils/services");
var utils_1 = require("../utils/utils");
var Clock = /** @class */function (_super) {
__extends(Clock, _super);
function Clock() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.state = {
time: "",
lastReleaseDate: null
};
return _this;
}
Clock.prototype.componentDidMount = function () {
var _this = this;
if (this.state.lastReleaseDate) return; //If the date has already been set do not perform the call again (not to overload the API)
services_1.getLastAlbum().then(function (data) {
return _this.setState({ lastReleaseDate: data }, _this.cbkDataSet);
}).catch(function (err) {
return console.log("Error:", err) || _this.setState({ lastReleaseDate: utils_1.defaultDate });
});
setInterval(function () {
return _this.setTime();
}, 1000);
};
Clock.prototype.cbkDataSet = function () {
if (!this.state.lastReleaseDate) this.setState({ lastReleaseDate: utils_1.defaultDate });
this.setTime();
};
Clock.prototype.setTime = function () {
this.setState({ time: countdown(this.state.lastReleaseDate).toString() });
};
Clock.prototype.render = function () {
return preact_1.h("h4", null, this.state.time);
};
return Clock;
}(preact_1.Component);
exports.default = Clock;
},{"preact":"OmAK","countdown":"TkLn","../utils/services":"3Pj7","../utils/utils":"8wWJ"}],"OLp4":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var preact_1 = require("preact");
exports.default = function (props) {
return preact_1.h("span", null, preact_1.h("h4", null, "Created"), preact_1.h("span", { role: "img", "aria-label": "rock" }, props.emoji), preact_1.h("h4", null, " by "), preact_1.h("a", { href: "" }, props.author), preact_1.h("h4", null, "by the time the the Lord of Lighting defeated the Balrog. View the Code on"), preact_1.h("a", { href: "" }, "Github"));
};
},{"preact":"OmAK"}],"Izf3":[function(require,module,exports) {
"use strict";
var __extends = this && this.__extends || function () {
var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) {
if (b.hasOwnProperty(p)) d[p] = b[p];
}
};
return function (d, b) {
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
}();
Object.defineProperty(exports, "__esModule", { value: true });
var preact_1 = require("preact");
var utils_1 = require("../utils/utils");
var Clock_1 = require("./Clock");
var Footer_1 = require("./Footer");
var Main = /** @class */function (_super) {
__extends(Main, _super);
function Main() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.state = {
message: ["", ""]
};
return _this;
}
Main.prototype.componentDidMount = function () {
this.setState({ message: utils_1.getRandMessage() });
};
Main.prototype.render = function () {
return preact_1.h("div", null, preact_1.h("span", null, preact_1.h("h4", null, this.state.message[0]), preact_1.h(Clock_1.default, null), preact_1.h("h4", null, this.state.message[1])), preact_1.h(Footer_1.default, { author: "aalises", emoji: "\uD83E\uDD18" }));
};
return Main;
}(preact_1.Component);
exports.default = Main;
},{"preact":"OmAK","../utils/utils":"8wWJ","./Clock":"8Jz0","./Footer":"OLp4"}],"zo2T":[function(require,module,exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var preact_1 = require("preact");
var Main_1 = require("./components/Main");
var mountNode = document.getElementById('root');
preact_1.render(preact_1.h(Main_1.default, null), mountNode, mountNode.lastChild);
// Hot Module Replacement
if (module.hot) {
module.hot.accept();
}
},{"preact":"OmAK","./components/Main":"Izf3"}]},{},["zo2T"], null)
//# sourceMappingURL=src.54c4a183.map | 24.90411 | 386 | 0.628446 |
ea4c95e380d41ff0958aeb45ab907a9a425c6bb3 | 1,496 | js | JavaScript | src/views/PersonalExterno/ModalExternals/Map.js | wama2308/smart_clinics | df7556787e70af432afc179478c303d4441dbbce | [
"MIT"
] | null | null | null | src/views/PersonalExterno/ModalExternals/Map.js | wama2308/smart_clinics | df7556787e70af432afc179478c303d4441dbbce | [
"MIT"
] | null | null | null | src/views/PersonalExterno/ModalExternals/Map.js | wama2308/smart_clinics | df7556787e70af432afc179478c303d4441dbbce | [
"MIT"
] | null | null | null | import React, { Component } from "react";
import { compose } from "recompose";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
InfoWindow
} from "react-google-maps";
const MapWithAMarker = compose(
withScriptjs,
withGoogleMap
)(props => {
return (
<GoogleMap
defaultZoom={13}
defaultCenter={{ lat: props.location.lat, lng: props.location.lng }}
>
{ props.markers.map((marker, i) => {
const onClick = props.onClick.bind(this, marker);
return (
<Marker
key={i}
icon={{
url:`${marker.logo}`,
scaledSize: { width: 20, height: 20 }
}}
onClick={onClick}
onMouseOver={()=>props.over(marker)}
onMouseOut={props.deletePosition}
position={{ lat: marker.lat, lng: marker.log }}
>
{props.selectedMarker.lat === marker.lat &&
props.selectedMarker.lng === marker.lng && (
<InfoWindow>
<div>
<h4 style={{ borderBottom: "1px solid #eadfd1" }}>
{marker.name}
</h4>
<br />
<div style={{ paddingBottom: 20 }}>
{marker.description}
</div>
</div>
</InfoWindow>
)}
</Marker>
);
})}
</GoogleMap>
);
});
export default MapWithAMarker;
| 25.793103 | 74 | 0.470588 |
ea4d51d440936e2a3812aafa5ef6d68b7a0e9d2a | 56 | js | JavaScript | node_modules/styled-icons/boxicons-solid/LowVision/LowVision.esm.js | chs6558/chs6558.github.io | 32dd0275105d1db5b085d3162126b0e847ec9c16 | [
"MIT"
] | null | null | null | node_modules/styled-icons/boxicons-solid/LowVision/LowVision.esm.js | chs6558/chs6558.github.io | 32dd0275105d1db5b085d3162126b0e847ec9c16 | [
"MIT"
] | null | null | null | node_modules/styled-icons/boxicons-solid/LowVision/LowVision.esm.js | chs6558/chs6558.github.io | 32dd0275105d1db5b085d3162126b0e847ec9c16 | [
"MIT"
] | null | null | null | export * from '@styled-icons/boxicons-solid/LowVision';
| 28 | 55 | 0.767857 |
ea4dc80f7cc99546e4856d8f790acf8634952459 | 2,313 | js | JavaScript | tests/baselines/reference/tsserver/inferredProjects/create-inferred-project.js | eshimischi/TypeScript | b24b6a1125321fb62d53dd544a6c59f03a6eac07 | [
"Apache-2.0"
] | null | null | null | tests/baselines/reference/tsserver/inferredProjects/create-inferred-project.js | eshimischi/TypeScript | b24b6a1125321fb62d53dd544a6c59f03a6eac07 | [
"Apache-2.0"
] | 2 | 2022-01-23T06:09:01.000Z | 2022-02-04T03:57:44.000Z | tests/baselines/reference/tsserver/inferredProjects/create-inferred-project.js | eshimischi/TypeScript | b24b6a1125321fb62d53dd544a6c59f03a6eac07 | [
"Apache-2.0"
] | null | null | null | Provided types map file "/typesMap.json" doesn't exist
Search path: /user/username/projects/myproject
For info: /user/username/projects/myproject/app.ts :: No config files found.
Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded
FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/tsconfig.json 2000 undefined WatchType: Config file for the inferred project root
FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/jsconfig.json 2000 undefined WatchType: Config file for the inferred project root
Starting updateGraphWorker: Project: /dev/null/inferredProject1*
DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject 0 undefined Project: /dev/null/inferredProject1* WatchType: Failed Lookup Locations
Elapsed:: *ms DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject 0 undefined Project: /dev/null/inferredProject1* WatchType: Failed Lookup Locations
FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/module.d.ts 500 undefined WatchType: Closed Script info
FileWatcher:: Added:: WatchInfo: /a/lib/lib.d.ts 500 undefined WatchType: Closed Script info
DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Project: /dev/null/inferredProject1* WatchType: Type roots
Elapsed:: *ms DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Project: /dev/null/inferredProject1* WatchType: Type roots
Finishing updateGraphWorker: Project: /dev/null/inferredProject1* Version: 1 structureChanged: true structureIsReused:: Not Elapsed:: *ms
Project '/dev/null/inferredProject1*' (Inferred)
Files (3)
/a/lib/lib.d.ts
/user/username/projects/myproject/module.d.ts
/user/username/projects/myproject/app.ts
../../../../a/lib/lib.d.ts
Default library for target 'es5'
module.d.ts
Imported via "./module" from file 'app.ts'
app.ts
Root file specified for compilation
-----------------------------------------------
Project '/dev/null/inferredProject1*' (Inferred)
Files (3)
-----------------------------------------------
Open files:
FileName: /user/username/projects/myproject/app.ts ProjectRootPath: undefined
Projects: /dev/null/inferredProject1* | 64.25 | 177 | 0.753134 |
ea4ead98dbe44d7632754b07fac293464f090487 | 325 | js | JavaScript | test/comment.test.js | hrkt/fizzbuzz-scheme | a612607024b52fe7e35556355324d5f50912ebfd | [
"MIT"
] | null | null | null | test/comment.test.js | hrkt/fizzbuzz-scheme | a612607024b52fe7e35556355324d5f50912ebfd | [
"MIT"
] | 52 | 2021-08-22T01:24:32.000Z | 2022-03-30T11:42:26.000Z | test/comment.test.js | hrkt/fizzbuzz-scheme | a612607024b52fe7e35556355324d5f50912ebfd | [
"MIT"
] | null | null | null | 'use strict'
import FS from 'fs'
import { FsInteger } from '../src/datatypes.js'
import { FizzBuzzScheme as FBS } from '../src/index.js'
test('evaluating comment.test.1.scm', () => {
const code1 = FS.readFileSync('test/code/comment.test.1.scm', 'utf8')
expect(new FBS().eval(code1)).toStrictEqual(new FsInteger(2))
})
| 27.083333 | 71 | 0.683077 |
ea4ef1a3004942a84b3ccad809aca7b3f3f3d1cc | 347 | js | JavaScript | .typedoc.js | dzcpy/nestjs-relay | 931c9517d0b8cc91737dcd040de227f835755d3e | [
"MIT"
] | 51 | 2020-06-24T02:27:23.000Z | 2022-02-20T06:31:21.000Z | .typedoc.js | dzcpy/nestjs-relay | 931c9517d0b8cc91737dcd040de227f835755d3e | [
"MIT"
] | 212 | 2020-06-14T16:47:50.000Z | 2022-01-21T19:46:28.000Z | .typedoc.js | dzcpy/nestjs-relay | 931c9517d0b8cc91737dcd040de227f835755d3e | [
"MIT"
] | 11 | 2020-09-01T18:23:45.000Z | 2021-10-10T06:41:45.000Z | module.exports = {
// entryPoint: '"nestjs-relay"',
exclude: '**/*+(index|.spec|.e2e).ts',
excludeExternals: true,
excludeNotExported: true,
includeVersion: true,
inputFiles: ['src'],
mode: 'modules',
name: 'NestJS Relay',
out: 'public',
plugin: 'typedoc-neo-theme',
theme: './node_modules/typedoc-neo-theme/bin/default',
};
| 24.785714 | 56 | 0.651297 |
ea5075e79c4e503de309521301c52927a6588175 | 6,121 | js | JavaScript | js/app.js | jyoung7834/bus-mall | 75a9c501c95706ef3e81d318b5fca3c2d16f4920 | [
"MIT"
] | null | null | null | js/app.js | jyoung7834/bus-mall | 75a9c501c95706ef3e81d318b5fca3c2d16f4920 | [
"MIT"
] | null | null | null | js/app.js | jyoung7834/bus-mall | 75a9c501c95706ef3e81d318b5fca3c2d16f4920 | [
"MIT"
] | null | null | null | 'use strict';
// create some product objects
// will have an array of product objects, and randomly display 3 different on the page
// we will click on these products to vote
// // we will track our clicks
// when we hit 10 clicks, remove event listener - close polls
// when the polls have closed, we render the results
// the results will be the name of the product, the number of times it was viewed, and number of votes received
//global variables
var allProducts = [];
var totalClicksAllowed = 25;
var clicks = 0;
var myContainer = document.getElementById('container');
var imgOneEl = document.getElementById('image-one');
var imgTwoEl = document.getElementById('image-two');
var imgThreeEl = document.getElementById('image-three');
var myList = document.getElementById('list');
var view = [];
var selections = [];
var productlabels = [];
var renderQ = [];
//constructor
function Product(name) {
this.name = name;
this.views = 0;
this.votes = 0;
this.source = `img/${name}.jpg`;
allProducts.push(this);
}
//function
function getRandomProductsIndex() {
return Math.floor(Math.random() * allProducts.length);
}
var retrievedResults = localStorage.getItem('productResults');
if (retrievedResults) {
var parsendRetrievedResults = JSON.parse(retrievedResults);
allProducts = parsendRetrievedResults;
} else {
//executable code
new Product('banana');
new Product('bag');
new Product('bathroom');
new Product('boots');
new Product('breakfast');
new Product('bubblegum');
new Product('chair');
new Product('cthulhu');
new Product('dog-duck');
new Product('dragon');
new Product('pen');
new Product('pet-sweep');
new Product('scissors');
new Product('shark');
new Product('sweep');
new Product('tauntaun');
new Product('unicorn');
new Product('usb');
new Product('water-can');
new Product('wine-glass');
}
// console.log(getRandomProductsIndex());
function populateRenderQ() {
while (renderQ.length > 3) {
renderQ.shift();
}
while (renderQ.length < 6) {
var uniqueProd = getRandomProductsIndex();
while (renderQ.includes(uniqueProd)) {
uniqueProd = getRandomProductsIndex();
}
renderQ.push(uniqueProd);
}
// console.log(renderQ);
}
function retrieveData() {
for (var i = 0; i < allProducts.length; i++) {
view.push(allProducts[i].views);
productlabels.push(allProducts[i].name);
selections.push(allProducts[i].votes);
}
}
function renderallProducts() {
populateRenderQ();
var productOne = renderQ[0];
var productTwo = renderQ[1];
var productThree = renderQ[2];
// with three indexes this gets more complex!!! maybe use an array, maybe see if the index in question is included in that array, if it is, choose another index
// NOTE: we've used myArray.push. how do you remove something from an array? how do we add something to the FRONT of an array? remove from the FRONT, how do you remove from the BACK?
// *** I found splice() to remove arbitrary item, shift() to remove from beginning and pop() to remove from end
// THIS WHILE LOOP IS NO LONGER NEEDED BECAUSE AN ARRAY WAS CREATED WITH A UNIQUE PRODUCT
// while (productOne === productTwo) {
// productTwo = getRandomProductsIndex();
// // if (productThreee === productTwo || productOne) {
// // productThree = getRandomProductsIndex();
// }
imgOneEl.src = allProducts[productOne].source;
imgOneEl.alt = allProducts[productOne].name;
allProducts[productOne].views++;
imgTwoEl.src = allProducts[productTwo].source;
imgTwoEl.alt = allProducts[productTwo].name;
allProducts[productTwo].views++;
imgThreeEl.src = allProducts[productThree].source;
imgThreeEl.alt = allProducts[productThree].name;
allProducts[productThree].views++;
}
function renderResults() {
for (var i = 0; i < allProducts.length; i++) {
// create element
var li = document.createElement('li');
// give it content
li.textContent = `${allProducts[i].name} had ${allProducts[i].votes}, and was seen ${allProducts[i].views} times`;
// append it to the dom
myList.appendChild(li);
}
}
renderallProducts();
//event handler
// event handler takes 1 parameter: event or atfen "e"
function handleClick(event) {
// this grabs the image alt property - which is the same as the product name property
var clickedProduct = event.target.alt;
clicks++;
for (var i = 0; i < allProducts.length; i++) {
// we are looking at ALL the name properties inside the product array and comparing them to our image alt property
if (clickedProduct === allProducts[i].name) {
// if true, we KNOW we have the correct product and we can increment its votes!
allProducts[i].votes++;
}
}
console.log(view, selections, productlabels);
renderallProducts();
if (clicks === totalClicksAllowed) {
// remove event listener takes parameters: event, and the callback functions.
myContainer.removeEventListener('click', handleClick);
retrieveData();
renderChart();
// renders our results in a list
renderResults();
var stgringifiedResults = JSON.stringify(allProducts);
localStorage.setItem('productResults', stgringifiedResults);
}
// console.log(clickedProduct);
}
// console.log(getRandomProductsIndex());
//event listener takes 2 parameters: event, and the callback function
myContainer.addEventListener('click', handleClick);
// chart javascript
var ctx = document.getElementById('myChart').getContext('2d');
function renderChart() {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: productlabels,
datasets: [{
label: '# of Votes',
data: selections,
backgroundColor: 'rgba(255, 255, 51)',
borderColor: 'rgba(255, 255, 51)',
borderWidth: 1
}, {
label: '# of View',
data: view,
backgroundColor: 'rgba(0, 255, 0)',
borderColor: 'rgba(0, 255, 0)',
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
| 28.469767 | 187 | 0.675707 |
ea51a262458bf84aba88a9bcf7fd5c4c647ca964 | 6,402 | js | JavaScript | src/constants.js | scc416/currency-converter | 9a52bac4990f58cb292a3f4b64c4b2f05c0443b6 | [
"MIT"
] | null | null | null | src/constants.js | scc416/currency-converter | 9a52bac4990f58cb292a3f4b64c4b2f05c0443b6 | [
"MIT"
] | null | null | null | src/constants.js | scc416/currency-converter | 9a52bac4990f58cb292a3f4b64c4b2f05c0443b6 | [
"MIT"
] | null | null | null | export const INIT_SETUP = "INIT_SETUP";
export const RECEIVE_NEW_CURRENCY = "RECEIVE_NEW_CURRENCY";
export const RECEIVE_NEW_VALUE = "RECEIVE_NEW_VALUE";
export const ADD_CURRENCY = "ADD_CURRENCY";
export const REMOVE_CURRENCY = "REMOVE_CURRENCY";
export const SET_ERROR = "SET_ERROR";
export const REMOVE_ERROR = "REMOVE_ERROR";
export const MAX_NUM_CURRENCIES = 10;
export const MIN_NUM_CURRENCIES = 2;
export const ERROR_TOO_MANY_CURRENCIES = `You can have at most ${MAX_NUM_CURRENCIES} currencies.`;
export const ERROR_TOO_LESS_CURRENCIES = `You need at least ${MIN_NUM_CURRENCIES} currencies`;
export const INIT_VALUE = 1;
export const INIT_INDEX = 0;
export const INIT_RATE = 1;
export const initState = {
availableCurrencies: [],
currencies: [
{ code: "hkd", value: INIT_VALUE },
{ code: "cad", value: INIT_VALUE },
],
value: INIT_VALUE,
rate: null,
rates: [],
error: null,
};
export const latestRatesURL =
"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/hkd.json";
export const availableCurrenciesURL =
"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies.json";
export const currenciesEmoji = [
{ code: "aed", emoji: "🇦🇪" },
{ code: "afn", emoji: "🇦🇫" },
{ code: "all", emoji: "🇦🇱" },
{ code: "amd", emoji: "🇦🇲" },
{ code: "ang", emoji: "🇨🇼" },
{ code: "aoa", emoji: "🇦🇴" },
{ code: "ars", emoji: "🇦🇷" },
{ code: "aud", emoji: "🇦🇺" },
{ code: "awg", emoji: "🇦🇼" },
{ code: "azn", emoji: "🇦🇿" },
{ code: "bam", emoji: "🇧🇦" },
{ code: "bdt", emoji: "🇧🇩" },
{ code: "bgn", emoji: "🇧🇬" },
{ code: "bhd", emoji: "🇧🇭" },
{ code: "bif", emoji: "🇧🇮" },
{ code: "bnd", emoji: "🇧🇳" },
{ code: "bbd", emoji: "🇧🇧" },
{ code: "bsd", emoji: "🇧🇸" },
{ code: "bmd", emoji: "🇧🇲" },
{ code: "bob", emoji: "🇧🇴" },
{ code: "brl", emoji: "🇧🇷" },
{ code: "btn", emoji: "🇧🇹" },
{ code: "bwp", emoji: "🇧🇼" },
{ code: "byr", emoji: "🇧🇾" },
{ code: "bzd", emoji: "🇧🇿" },
{ code: "cad", emoji: "🇨🇦" },
{ code: "cdf", emoji: "🇨🇩" },
{ code: "chf", emoji: "🇨🇭" },
{ code: "clp", emoji: "🇨🇱" },
{ code: "cuc", emoji: "🇨🇺" },
{ code: "cny", emoji: "🇨🇳" },
{ code: "cop", emoji: "🇨🇴" },
{ code: "cup", emoji: "🇨🇺" },
{ code: "crc", emoji: "🇨🇷" },
{ code: "cve", emoji: "🇨🇻" },
{ code: "czk", emoji: "🇨🇿" },
{ code: "djf", emoji: "🇩🇯" },
{ code: "dkk", emoji: "🇩🇰" },
{ code: "dop", emoji: "🇩🇴" },
{ code: "dzd", emoji: "🇩🇿" },
{ code: "eek", emoji: "🇪🇪" },
{ code: "egp", emoji: "🇪🇬" },
{ code: "ern", emoji: "🇪🇷" },
{ code: "etb", emoji: "🇪🇹" },
{ code: "eur", emoji: "🇪🇺" },
{ code: "fkp", emoji: "🇫🇰" },
{ code: "fjd", emoji: "🇫🇯" },
{ code: "gbp", emoji: "🇬🇧" },
{ code: "gel", emoji: "🇬🇪" },
{ code: "ghs", emoji: "🇬🇭" },
{ code: "gip", emoji: "🇬🇮" },
{ code: "gnf", emoji: "🇬🇳" },
{ code: "gtq", emoji: "🇬🇹" },
{ code: "gyd", emoji: "🇬🇾" },
{ code: "gmd", emoji: "🇬🇲" },
{ code: "ggp", emoji: "🇬🇬" },
{ code: "hkd", emoji: "🇭🇰" },
{ code: "hnl", emoji: "🇭🇳" },
{ code: "hrk", emoji: "🇭🇷" },
{ code: "huf", emoji: "🇭🇺" },
{ code: "htg", emoji: "🇭🇹" },
{ code: "idr", emoji: "🇮🇩" },
{ code: "ils", emoji: "🇮🇱" },
{ code: "imp", emoji: "🇮🇲" },
{ code: "inr", emoji: "🇮🇳" },
{ code: "iqd", emoji: "🇮🇶" },
{ code: "irr", emoji: "🇮🇷" },
{ code: "isk", emoji: "🇮🇸" },
{ code: "jmd", emoji: "🇯🇲" },
{ code: "jod", emoji: "🇯🇴" },
{ code: "jpy", emoji: "🇯🇵" },
{ code: "kgs", emoji: "🇰🇬" },
{ code: "khr", emoji: "🇰🇭" },
{ code: "kmf", emoji: "🇰🇲" },
{ code: "kpw", emoji: "🇰🇵" },
{ code: "krw", emoji: "🇰🇷" },
{ code: "kwd", emoji: "🇰🇼" },
{ code: "kyd", emoji: "🇰🇾" },
{ code: "kzt", emoji: "🇰🇿" },
{ code: "kes", emoji: "🇰🇪" },
{ code: "lak", emoji: "🇱🇦" },
{ code: "lbp", emoji: "🇱🇧" },
{ code: "lkr", emoji: "🇱🇰" },
{ code: "lrd", emoji: "🇱🇷" },
{ code: "ltl", emoji: "🇱🇹" },
{ code: "lsl", emoji: "🇱🇸" },
{ code: "lvl", emoji: "🇱🇻" },
{ code: "lyd", emoji: "🇱🇾" },
{ code: "mad", emoji: "🇲🇦" },
{ code: "mdl", emoji: "🇲🇩" },
{ code: "mga", emoji: "🇲🇬" },
{ code: "mkd", emoji: "🇲🇰" },
{ code: "mmk", emoji: "🇲🇲" },
{ code: "mop", emoji: "🇲🇴" },
{ code: "mur", emoji: "🇲🇺" },
{ code: "mwk", emoji: "🇲🇼" },
{ code: "mvr", emoji: "🇲🇻" },
{ code: "mxn", emoji: "🇲🇽" },
{ code: "myr", emoji: "🇲🇾" },
{ code: "mzn", emoji: "🇲🇿" },
{ code: "nad", emoji: "🇳🇦" },
{ code: "ngn", emoji: "🇳🇬" },
{ code: "nio", emoji: "🇳🇮" },
{ code: "nok", emoji: "🇳🇴" },
{ code: "npr", emoji: "🇳🇵" },
{ code: "nzd", emoji: "🇳🇿" },
{ code: "omr", emoji: "🇴🇲" },
{ code: "pab", emoji: "🇵🇦" },
{ code: "pen", emoji: "🇵🇪" },
{ code: "php", emoji: "🇵🇭" },
{ code: "pkr", emoji: "🇵🇰" },
{ code: "pgk", emoji: "🇵🇬" },
{ code: "pln", emoji: "🇵🇱" },
{ code: "pyg", emoji: "🇵🇾" },
{ code: "qar", emoji: "🇶🇦" },
{ code: "ron", emoji: "🇷🇴" },
{ code: "rsd", emoji: "🇷🇸" },
{ code: "rub", emoji: "🇷🇺" },
{ code: "rwf", emoji: "🇷🇼" },
{ code: "sar", emoji: "🇸🇦" },
{ code: "scr", emoji: "🇸🇨" },
{ code: "wst", emoji: "🇼🇸" },
{ code: "sbd", emoji: "🇸🇧" },
{ code: "svc", emoji: "🇸🇻" },
{ code: "sdg", emoji: "🇸🇩" },
{ code: "srd", emoji: "🇸🇷" },
{ code: "sek", emoji: "🇸🇪" },
{ code: "sgd", emoji: "🇸🇬" },
{ code: "sll", emoji: "🇸🇱" },
{ code: "sos", emoji: "🇸🇴" },
{ code: "ssp", emoji: "🇸🇸" },
{ code: "stn", emoji: "🇸🇹" },
{ code: "shp", emoji: "🇸🇭" },
{ code: "syp", emoji: "🇸🇾" },
{ code: "szl", emoji: "🇸🇿" },
{ code: "thb", emoji: "🇹🇭" },
{ code: "tjs", emoji: "🇹🇭" },
{ code: "tnd", emoji: "🇹🇳" },
{ code: "top", emoji: "🇹🇴" },
{ code: "try", emoji: "🇹🇷" },
{ code: "tmt", emoji: "🇹🇲" },
{ code: "ttd", emoji: "🇹🇹" },
{ code: "twd", emoji: "🇹🇼" },
{ code: "jep", emoji: "🇯🇪" },
{ code: "tzs", emoji: "🇹🇿" },
{ code: "uah", emoji: "🇺🇦" },
{ code: "ugx", emoji: "🇺🇬" },
{ code: "mru", emoji: "🇲🇷" },
{ code: "mnt", emoji: "🇲🇳" },
{ code: "usd", emoji: "🇺🇸" },
{ code: "uyu", emoji: "🇺🇾" },
{ code: "uzs", emoji: "🇺🇿" },
{ code: "vef", emoji: "🇻🇪" },
{ code: "vnd", emoji: "🇻🇳" },
{ code: "vuv", emoji: "🇻🇺" },
{ code: "xaf", emoji: "🇨🇫" },
{ code: "xcd", emoji: "🇦🇬" },
{ code: "xof", emoji: "🇨🇮" },
{ code: "xpf", emoji: "🇵🇫" },
{ code: "yer", emoji: "🇾🇪" },
{ code: "zar", emoji: "🇿🇦" },
{ code: "zmk", emoji: "🇿🇲" },
{ code: "zwl", emoji: "🇿🇼" },
];
| 31.850746 | 98 | 0.445486 |
ea527e1a96bdb8dca93316dc88a5501c9574b2fe | 276 | js | JavaScript | src/utils/constant.js | kukelove/beer | fc0724050d86f25bb484f0effa9be65ef9645e0b | [
"MIT"
] | null | null | null | src/utils/constant.js | kukelove/beer | fc0724050d86f25bb484f0effa9be65ef9645e0b | [
"MIT"
] | null | null | null | src/utils/constant.js | kukelove/beer | fc0724050d86f25bb484f0effa9be65ef9645e0b | [
"MIT"
] | null | null | null | export const ROLE_TYPE = {
ADMIN: 'admin',
DEFAULT: 'admin',
DEVELOPER: 'developer',
}
export const GENDER_TYPE = {
1: '男',
2: '女',
}
export const PRIVILAGE_TYPE = {
1: '门店管理',
2: '会员管理',
3: '卡券管理'
}
export const CANCEL_REQUEST_MESSAGE = 'cancel request'
| 13.142857 | 54 | 0.623188 |
ea5357947fbfb11b741ad7fa46484fbaecf5fb4a | 438 | js | JavaScript | src/pages/index.js | crwydryn/portfolio | 9652f61eae40cee57964c7e628467018105330b5 | [
"MIT"
] | null | null | null | src/pages/index.js | crwydryn/portfolio | 9652f61eae40cee57964c7e628467018105330b5 | [
"MIT"
] | null | null | null | src/pages/index.js | crwydryn/portfolio | 9652f61eae40cee57964c7e628467018105330b5 | [
"MIT"
] | null | null | null | // React Component
import React from "react"
import { Link } from "gatsby"
import Layout from "../components/layout.js"
import Title from "../components/title.js"
//functional component definition; JSX resembles HTML
export default () => (
<Layout>
<Title text="Shaw Malcolm" subtitle= "Javascript Developer (in training)"/>
<p>
ES6 | React | Redux | HTML5 | CSS3 | SASS
</p>
</Layout>
)
| 23.052632 | 83 | 0.627854 |
ea53b7bb2737e52b202bdf43eb80165576599971 | 22,657 | js | JavaScript | brico.js | patrickfournier/pentris | 6648e6b6c14bdad0452d6f6f378d25b47a506d2e | [
"Apache-2.0"
] | null | null | null | brico.js | patrickfournier/pentris | 6648e6b6c14bdad0452d6f6f378d25b47a506d2e | [
"Apache-2.0"
] | null | null | null | brico.js | patrickfournier/pentris | 6648e6b6c14bdad0452d6f6f378d25b47a506d2e | [
"Apache-2.0"
] | null | null | null | document.addEventListener('DOMContentLoaded', function() {
/* TODO:
- animate line removal
- new game button
*/
var brico = brico || {};
/*
The palette is a list of 18 RGBA colors; each color has 5 shades.
Generated with the help of http://paletton.com
*/
brico.Palette = [
[[127,127,127,1], [255,255,255,1], [190,190,190,1], [ 62, 62, 62,1], [ 0, 0, 0,1]],
[[255,232, 0,1], [255,248,178,1], [255,238, 62,1], [226,206, 0,1], [162,148, 0,1]],
[[ 98, 10,215,1], [176,151,209,1], [120, 61,198,1], [ 68, 4,153,1], [ 48, 1,110,1]],
[[255,255, 0,1], [255,255,178,1], [255,255, 62,1], [226,226, 0,1], [162,162, 0,1]],
[[ 0,215,123,1], [146,210,183,1], [ 49,200,135,1], [ 0,155, 89,1], [ 0,111, 64,1]],
[[255, 73, 0,1], [255,200,178,1], [255,117, 62,1], [226, 64, 0,1], [162, 46, 0,1]],
[[ 0,205,205,1], [138,197,197,1], [ 45,185,185,1], [ 0,136,136,1], [ 0, 97, 97,1]],
[[255,116, 0,1], [255,213,178,1], [255,150, 62,1], [226,102, 0,1], [162, 74, 0,1]],
[[208,251, 0,1], [237,250,175,1], [217,249, 61,1], [181,218, 0,1], [130,157, 0,1]],
[[ 7,122,210,1], [146,179,204,1], [ 57,133,192,1], [ 3, 83,145,1], [ 1, 59,104,1]],
[[211, 0,211,1], [205,143,205,1], [193, 47,193,1], [147, 0,147,1], [105, 0,105,1]],
[[255,170, 0,1], [255,229,178,1], [255,191, 62,1], [226,151, 0,1], [162,108, 0,1]],
[[109,241, 0,1], [200,239,167,1], [138,236, 58,1], [ 91,201, 0,1], [ 65,145, 0,1]],
[[ 17, 17,217,1], [157,157,212,1], [ 72, 72,202,1], [ 7, 7,158,1], [ 2, 2,114,1]],
[[255,191, 0,1], [255,236,178,1], [255,207, 62,1], [226,169, 0,1], [162,122, 0,1]],
[[242, 0, 73,1], [240,167,189,1], [236, 58,112,1], [202, 0, 61,1], [145, 0, 44,1]],
[[ 0,230, 0,1], [158,226,158,1], [ 54,220, 54,1], [ 0,181, 0,1], [ 0,130, 0,1]],
[[255, 0, 0,1], [255,178,178,1], [255, 62, 62,1], [226, 0, 0,1], [162, 0, 0,1]],
];
/* Color */
brico.Color = function(c, s) {
var color = brico.Palette[c][s];
this.colorString = "rgba(" + color[0].toString() + "," + color[1].toString() + "," + color[2].toString() + "," + color[3].toString() + ")";
};
brico.Color.prototype.toString = function() {
return this.colorString;
};
/**
Shape
Shapes are defined by a 5x5 array of bools.
*/
brico.Shape = function(color1, color2, shape) {
this.color1 = color1;
this.color2 = color2;
this.rotation = 0;
this.x = 0;
this.y = 0;
this.width = 5;
this.height = 5;
this.def = new Array(this.width * this.height);
this.def.fill(false);
for (var i = 0; i < shape.length; i++) {
this.def[shape[i]] = true;
}
// Compute bounding box.
var minX = this.width;
var maxX = 0;
var minY = this.height;
var maxY = 0;
var squares = this.getOccupiedSquares();
for (var i = 0; i < squares.length; i++) {
minX = Math.min(minX, squares[i][0]);
maxX = Math.max(maxX, squares[i][0]);
minY = Math.min(minY, squares[i][1]);
maxY = Math.max(maxY, squares[i][1]);
}
this.bboxLeft = minX;
this.bboxTop = minY;
this.bboxWidth = maxX - minX + 1;
this.bboxHeight = maxY - minY + 1;
};
// Index lookup table for rotated shapes. Rotations are clockwise.
brico.Shape.prototype.rotationLookupTable = {
0 : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
90 : [20, 15, 10, 5, 0, 21, 16, 11, 6, 1, 22, 17, 12, 7, 2, 23, 18, 13, 8, 3, 24, 19, 14, 9, 4],
180: [24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
270: [4, 9, 14, 19, 24, 3, 8, 13, 18, 23, 2, 7, 12, 17, 22, 1, 6, 11, 16, 21, 0, 5, 10, 15, 20]
};
brico.Shape.prototype.move = function(dx, dy) {
this.x += dx;
this.y += dy;
};
brico.Shape.prototype.rotate = function(clockwise) {
var delta = clockwise ? 90 : 270;
this.rotation = (this.rotation + delta) % 360;
};
brico.Shape.prototype.getOccupiedSquares = function() {
return this.getOccupiedSquaresAfterMove(0, 0, null);
};
brico.Shape.prototype.getOccupiedSquaresAfterMove = function(dx, dy, clockwiseRotation) {
var occupiedSquares = [];
var r = this.rotation;
if (clockwiseRotation === true) {
r = (this.rotation + 90) % 360;
}
else if (clockwiseRotation === false) {
r = (this.rotation + 270) % 360;
}
var rlut = this.rotationLookupTable[r];
for (var i = 0; i < this.def.length; i++) {
var j = rlut[i];
if (this.def[j]) {
var x = (this.x + dx + (i % this.width));
var y = (this.y + dy + Math.floor(i / this.width));
occupiedSquares.push([x, y]);
}
}
return occupiedSquares;
};
/* Shape factory */
brico.ShapeFactory = function() {};
brico.ShapeFactory.shapes = [
[7, 11, 12, 13, 17], // X
[7, 8, 12, 13, 17], // P
[6, 7, 11, 12, 17], // Mirrored P
[7, 8, 11, 12, 17], // F
[6, 7, 12, 13, 17], // Mirrored F
[6, 11, 16, 17, 18], // V
[6, 11, 12, 17, 18], // W
[2, 6, 7, 12, 17], // Y
[2, 7, 8, 12, 17], // Mirrored Y
[2, 7, 12, 17, 22], // I
[6, 7, 8, 12, 17], // T
[6, 7, 12, 17, 18], // Z
[7, 8, 12, 16, 17], // Mirrored Z (S)
[6, 8, 11, 12, 13], // U
[5, 6, 11, 12, 13], // N
[8, 9, 11, 12, 13], // Mirrored N
[9, 11, 12, 13, 14], // L
[5, 10, 11, 12, 13], // Mirrored L (J)
];
brico.ShapeFactory.newShape = function(shapeId) {
var color1 = new brico.Color(shapeId, 0);
var color2 = new brico.Color(shapeId, 3);
var shape = new brico.Shape(color1, color2, this.shapes[shapeId]);
return shape;
};
brico.ShapeFactory.randomShape = function() {
var r = Math.random();
var shapeId = Math.floor(r * this.shapes.length);
return this.newShape(shapeId);
};
/* GridView */
brico.GridView = function(canvasId, grid) {
var canvas = document.getElementById(canvasId);
this.ctx = canvas.getContext('2d');
this.grid = grid;
this.x = 0;
this.y = 0;
this.pixelWidth = canvas.width;
this.pixelHeight = canvas.height;
this.xs = this.pixelWidth / this.grid.width;
this.ys = this.pixelHeight / this.grid.height;
this.insetX = Math.floor(this.xs/6);
this.insetY = Math.floor(this.ys/6);
this.lastGridUpdateId = grid.updateId - 1;
this.animate();
};
brico.GridView.prototype.drawSquarePrepare = function() {
this.ctx.strokeStyle = "rgba(30,30,30,1)";
this.ctx.lineWidth = 2;
};
brico.GridView.prototype.drawSquare = function(x, y, color1Str, color2Str) {
x = x * this.xs + this.x;
y = y * this.ys + this.y;
this.ctx.fillStyle = color1Str;
this.ctx.fillRect(x, y, this.xs, this.ys);
this.ctx.fillStyle = color2Str;
this.ctx.fillRect(x+this.insetX, y+this.insetY, this.xs-2*this.insetX, this.ys-2*this.insetY);
this.ctx.strokeRect(x, y, this.xs, this.ys);
};
brico.GridView.prototype.draw = function() {
if (this.lastGridUpdateId != grid.updateId) {
this.lastGridUpdateId = grid.updateId;
this.ctx.clearRect(this.x, this.y, this.pixelWidth, this.pixelHeight);
this.drawSquarePrepare();
for (var i = 0; i < this.grid.gridData.length; i++) {
if (this.grid.gridData[i]) {
var x = i % this.grid.width;
var y = Math.floor(i / this.grid.width);
var c1 = this.grid.gridData[i][0].toString();
var c2 = this.grid.gridData[i][1].toString();
this.drawSquare(x, y, c1, c2);
}
}
if (this.grid.currentShape) {
var c1 = this.grid.currentShape.color1.toString();
var c2 = this.grid.currentShape.color2.toString();
var squares = this.grid.currentShape.getOccupiedSquares();
for (var i = 0; i < squares.length; i++) {
this.drawSquare(squares[i][0], squares[i][1], c1, c2);
}
}
}
};
brico.GridView.prototype.animate = function() {
this.draw();
window.requestAnimationFrame(this.animate.bind(this));
};
/* Shape Preview */
brico.ShapePreviewView = function(canvasId, grid) {
brico.GridView.call(this, canvasId, grid);
this.xs = this.pixelWidth / 6;
this.ys = this.pixelHeight / 6;
this.insetX = Math.floor(this.xs/6);
this.insetY = Math.floor(this.ys/6);
this.lastShapeDrawn = this.grid.nextShape;
};
brico.ShapePreviewView.prototype = Object.create(brico.GridView.prototype);
brico.ShapePreviewView.prototype.draw = function() {
if (this.lastShapeDrawn != this.grid.nextShape) {
this.lastShapeDrawn = this.grid.nextShape;
this.ctx.clearRect(this.x, this.y, this.pixelWidth, this.pixelHeight);
this.drawSquarePrepare();
if (this.grid.nextShape) {
var padX = (6 - this.grid.nextShape.bboxWidth) / 2. - this.grid.nextShape.bboxLeft;
var padY = (6 - this.grid.nextShape.bboxHeight) / 2. - this.grid.nextShape.bboxTop;
var c1 = this.grid.nextShape.color1.toString();
var c2 = this.grid.nextShape.color2.toString();
var squares = this.grid.nextShape.getOccupiedSquares();
for (var i = 0; i < squares.length; i++) {
this.drawSquare(squares[i][0] + padX, squares[i][1] + padY, c1, c2);
}
}
}
};
/* Grid */
brico.Grid = function(width, height) {
this.width = width;
this.height = height;
this.nextShape = brico.ShapeFactory.randomShape();
this.currentShape = undefined;
this.gridData = new Array(this.width * this.height);
this.updateId = 0;
};
brico.Grid.prototype.bake = function() {
if (this.currentShape) {
var occupiedSquares = this.currentShape.getOccupiedSquares();
for (var i = 0; i < occupiedSquares.length; i++) {
var j = occupiedSquares[i][1] * this.width + occupiedSquares[i][0];
this.gridData[j] = [this.currentShape.color1, this.currentShape.color2];
}
this.currentShape = undefined;
var event = document.createEvent('Event');
event.initEvent('brico-bake', true, true);
document.dispatchEvent(event);
this.updateId++;
}
};
brico.Grid.prototype.detectCollision = function(shapeSquares) {
for (var i = 0; i < shapeSquares.length; i++) {
var j = shapeSquares[i][1] * this.width + shapeSquares[i][0];
if ((this.gridData[j] != undefined) ||
(shapeSquares[i][0] < 0) ||
(shapeSquares[i][0] >= this.width) ||
(shapeSquares[i][1] >= this.height)) {
return true;
}
}
return false;
};
brico.Grid.prototype.tryMove = function(dx, dy) {
if (this.currentShape) {
var shapeSquares = this.currentShape.getOccupiedSquaresAfterMove(dx, dy, undefined);
if (!this.detectCollision(shapeSquares)) {
this.currentShape.move(dx, dy);
this.updateId++;
return true;
}
}
return false;
};
brico.Grid.prototype.tryRotate = function(clockwise) {
if (this.currentShape) {
var shapeSquares = this.currentShape.getOccupiedSquaresAfterMove(0, 0, clockwise);
if (!this.detectCollision(shapeSquares)) {
this.currentShape.rotate(clockwise);
this.updateId++;
return true;
}
}
return false;
};
brico.Grid.prototype.drop = function() {
if (this.currentShape) {
var dy = 1;
var shapeSquares = this.currentShape.getOccupiedSquaresAfterMove(0, dy, undefined);
while (!this.detectCollision(shapeSquares)) {
dy++;
for (var i = 0; i < shapeSquares.length; i++) {
shapeSquares[i][1]++;
}
}
if (dy > 1) {
this.currentShape.move(0, dy - 1);
var event = document.createEvent('Event');
event.dy = dy - 1;
event.initEvent('brico-drop', true, true);
document.dispatchEvent(event);
this.updateId++;
return true;
}
}
return false;
};
brico.Grid.prototype.removeFullLines = function() {
var fullLines = [];
for (var j = this.height - 1; j >= 0; j--) {
var isFull = true;
for (var i = 0; i < this.width; i++) {
if (!this.gridData[j * this.width + i]) {
isFull = false;
break;
}
}
if (isFull) {
fullLines.push(j);
}
}
if (fullLines.length > 0) {
for (var i = 0; i < fullLines.length; i++) {
var j = fullLines[i];
this.gridData.splice(j*this.width, this.width);
}
var newLines = new Array(fullLines.length * this.width);
this.gridData = newLines.concat(this.gridData);
var event = document.createEvent('Event');
event.lines = fullLines.length;
event.initEvent('brico-lines', true, true);
document.dispatchEvent(event);
this.updateId++;
}
};
brico.Grid.prototype.tick = function() {
if (!this.tryMove(0, 1)) {
// merge shape into grid
this.bake();
// delete lines
this.removeFullLines();
// create new shape.
this.currentShape = this.nextShape;
if (!this.tryMove((this.width - 5)/2, 0)) {
// game over
this.currentShape = undefined;
var event = document.createEvent('Event');
event.initEvent('brico-gameover', true, true);
document.dispatchEvent(event);
}
else {
this.nextShape = brico.ShapeFactory.randomShape();
}
}
};
brico.Background = function() {
this.backgrounds = [
{photo_url: "https://farm4.staticflickr.com/3842/15088487045_94b6a4fc31_k_d.jpg",
flickr_url: "https://flic.kr/p/oZjrwn",
author: "Normand Gaudreault",
author_url: "https://www.flickr.com/photos/95930823@N08/"},
{photo_url: "https://farm6.staticflickr.com/5134/5515913152_2f50ab52b0_o_d.jpg",
flickr_url: "https://flic.kr/p/9pquNU",
author: "Nick Kenrick",
author_url: "https://www.flickr.com/photos/zedzap/"},
{photo_url: "https://farm8.staticflickr.com/7608/16617366738_6a9222745f_o_d.jpg",
flickr_url: "https://flic.kr/p/rjqmc5",
author: "Guiseppe Milo",
author_url: "https://www.flickr.com/photos/giuseppemilo/"},
{photo_url: "https://farm9.staticflickr.com/8524/8478269827_08fcb6bc75_k_d.jpg",
flickr_url: "https://flic.kr/p/dVcmeZ",
author: "Stephan Oppermann",
author_url: "https://www.flickr.com/photos/s_oppermann/"},
{photo_url: "https://farm6.staticflickr.com/5526/11277422085_27afdde687_k_d.jpg",
flickr_url: "https://flic.kr/p/ibxJFP",
author: "Arnaud Fougerouse",
author_url: "https://www.flickr.com/photos/hihaa/"},
{photo_url: "https://farm6.staticflickr.com/5487/14141331128_78dd600bac_k_d.jpg",
flickr_url: "https://flic.kr/p/nxC24W",
author: "Christian",
author_url: "https://www.flickr.com/photos/blavandmaster/"},
{photo_url: "https://farm8.staticflickr.com/7695/17056169627_3ab896d24e_o_d.jpg",
flickr_url: "https://flic.kr/p/rZck18",
author: "Guiseppe Milo",
author_url: "https://www.flickr.com/photos/giuseppemilo/"},
{photo_url: "https://farm8.staticflickr.com/7392/16458204126_b9455a9dce_k_d.jpg",
flickr_url: "https://flic.kr/p/r5mAG7",
author: "Mibby23",
author_url: "https://www.flickr.com/photos/mibby23/"},
{photo_url: "https://farm9.staticflickr.com/8122/8609523972_a5de909ffa_o_d.jpg",
flickr_url: "https://flic.kr/p/e7N4wu",
author: "Christian",
author_url: "https://www.flickr.com/photos/blavandmaster/"},
{photo_url: "https://farm8.staticflickr.com/7609/16781847658_c919709c38_k_d.jpg",
flickr_url: "https://flic.kr/p/ryXmD1",
author: "Guven Gul",
author_url: "https://www.flickr.com/photos/guvengul/"},
];
this.initBackground();
document.addEventListener('brico-nextlevel', brico.Background.prototype.changeBackground.bind(this));
};
brico.Background.prototype.initBackground = function() {
// Load first image and wait until it is loaded before setting the background.
var image = new Image();
image.src = this.backgrounds[0].photo_url;
var bg = document.getElementsByTagName('html')[0];
var credit = document.getElementsByClassName('brico-background-image-credit')[0];
var il = credit.getElementsByClassName('image-link')[0];
var al = credit.getElementsByClassName('author-link')[0];
var self = this;
image.addEventListener('load', function() {
bg.style.backgroundImage = 'url(' + self.backgrounds[0].photo_url + ')';
il.setAttribute('href', self.backgrounds[0].flickr_url);
al.setAttribute('href', self.backgrounds[0].author_url);
al.innerHTML = self.backgrounds[0].author;
});
// Preload next image. We keep it in this.nextImage to prevent the
// object from being garbage collected.
this.nextImage = new Image();
this.nextImage.src = this.backgrounds[1].photo_url;
};
brico.Background.prototype.changeBackground = function(e) {
var bgindex = (e.level - 1) % this.backgrounds.length;
var bg = document.getElementsByTagName('html')[0];
bg.style.backgroundImage = 'url(' + this.backgrounds[bgindex].photo_url + ')';
var credit = document.getElementsByClassName('brico-background-image-credit')[0];
var il = credit.getElementsByClassName('image-link')[0];
var al = credit.getElementsByClassName('author-link')[0];
il.setAttribute('href', this.backgrounds[bgindex].flickr_url);
al.setAttribute('href', this.backgrounds[bgindex].author_url);
al.innerHTML = this.backgrounds[bgindex].author;
// Preload next image
bgindex = (bgindex + 1) % this.backgrounds.length;
this.nextImage = new Image();
this.nextImage.src = this.backgrounds[bgindex].photo_url;
};
/* Game */
brico.Game = function(grid, interval) {
this.playing = false;
this.grid = grid;
this.interval = interval;
this.score = 0;
this.lineCompleted = 0;
this.level = 1;
this.linesPerLevel = 10;
this.scoreElem = document.getElementById('brico-score');
this.levelElem = document.getElementById('brico-level');
this.highScoreElem = document.getElementById('brico-highscore');
var highscore = window.localStorage.getItem('highscore') || 0;
this.highScoreElem.innerHTML = highscore;
this.dropSound = [new Audio('sounds/drop.ogg'), new Audio('sounds/drop.ogg'), new Audio('sounds/drop.ogg')];
this.linesSound = new Audio('sounds/magic_wand.ogg');
this.fourLinesSound = new Audio('sounds/cheers.ogg');
this.gameOverSound = new Audio('sounds/sad_trombone.ogg');
document.addEventListener('brico-bake', brico.Game.prototype.bakeEventListener.bind(this));
document.addEventListener('brico-lines', brico.Game.prototype.fullLinesEventListener.bind(this));
document.addEventListener('brico-drop', brico.Game.prototype.dropEventListener.bind(this));
document.addEventListener('brico-gameover', brico.Game.prototype.gameOverEventListener.bind(this));
var self = this;
document.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode) {
if (String.fromCharCode(charCode) == 'p') {
self.togglePause();
e.preventDefault();
}
if (self.playing) {
switch (String.fromCharCode(charCode)) {
case 'j':
grid.tryMove(-1, 0);
e.preventDefault();
break;
case 'k':
grid.tryRotate(false);
e.preventDefault();
break;
case 'l':
grid.tryMove(1, 0);
e.preventDefault();
break;
case 'i':
grid.tryRotate(true);
e.preventDefault();
break;
case ' ':
grid.drop();
grid.bake();
e.preventDefault();
break;
case 'h':
grid.tryMove(0, 1);
e.preventDefault();
break;
}
}
}
};
};
brico.Game.prototype.start = function() {
var self = this;
this.playing = true;
this.grid.tick();
this.periodicTask = window.setInterval(function() {
self.grid.tick();
}, this.interval);
};
brico.Game.prototype.stop = function() {
window.clearInterval(this.periodicTask);
this.playing = false;
};
brico.Game.prototype.togglePause = function() {
if (this.playing) {
this.stop();
}
else {
this.start();
}
};
brico.Game.prototype.bakeEventListener = function(e) {
this.score += 5;
this.scoreElem.innerHTML = this.score;
};
brico.Game.prototype.fullLinesEventListener = function(e) {
this.linesSound.currentTime = 0;
this.linesSound.play();
this.score += 10 * e.lines;
if (e.lines >= 4) {
this.score += (e.lines - 3) * 100;
this.fourLinesSound.currentTime = 0;
this.fourLinesSound.play();
}
this.scoreElem.innerHTML = this.score;
this.lineCompleted += e.lines;
var currentInterval = this.interval;
while (this.lineCompleted >= this.linesPerLevel) {
this.lineCompleted -= this.linesPerLevel;
this.level++;
this.interval *= 0.9;
this.levelElem.innerHTML = this.level;
var event = document.createEvent('Event');
event.level = this.level;
event.initEvent('brico-nextlevel', true, true);
document.dispatchEvent(event);
}
if (currentInterval != this.interval) {
this.stop();
this.start();
}
};
brico.Game.prototype.dropEventListener = function(e) {
var i = 0;
while ((i < this.dropSound.length) && !this.dropSound[i].paused) {
i++;
}
if (i == 3) {
i = 0;
}
this.dropSound[i].currentTime = 0;
this.dropSound[i].play();
this.score += 2 * e.dy;
};
brico.Game.prototype.gameOverEventListener = function(e) {
this.stop();
var highscore = window.localStorage.getItem('highscore');
if (this.score > highscore) {
window.localStorage.setItem("highscore", this.score);
this.highScoreElem.innerHTML = this.score;
}
this.gameOverSound.currentTime = 0;
this.gameOverSound.play();
document.getElementById('brico-gameover').style.display = "block";
};
var grid = new brico.Grid(13, 26);
var gridView = new brico.GridView('brico-board', grid);
var shapePreview = new brico.ShapePreviewView('brico-preview', grid);
var backgroundView = new brico.Background();
var game = new brico.Game(grid, 500);
game.start();
}, false);
| 33.715774 | 143 | 0.595666 |
ea565a85bd3a4227c95c01139c94c6228494f4f8 | 757 | js | JavaScript | sencha/apps/cloud/app/Cloud/view/image/View.js | liverbool/c.com | 912c2da503b2e0eca1e0d6d5fcd037fd459a3cc1 | [
"MIT"
] | null | null | null | sencha/apps/cloud/app/Cloud/view/image/View.js | liverbool/c.com | 912c2da503b2e0eca1e0d6d5fcd037fd459a3cc1 | [
"MIT"
] | null | null | null | sencha/apps/cloud/app/Cloud/view/image/View.js | liverbool/c.com | 912c2da503b2e0eca1e0d6d5fcd037fd459a3cc1 | [
"MIT"
] | null | null | null | Ext.define('Magice.Cloud.view.image.View', {
extend: 'Ext.panel.Panel',
xtype: 'images',
itemId: 'images',
border: false,
controller: 'images',
viewModel: {
type: 'images'
},
dockedItems: {
xtype: 'view-images-toolbar'
},
bind: {
loading: '{maskingimages}'
},
xlayout: {
type: 'vbox',
pack: 'start',
align: 'stretch'
},
defaults: {
flex: 1,
border: false
},
config: {
activeState: null,
defaultActiveState: 'all'
},
maskings: {
key: 'maskingimages',
stores: ['images']
},
validStates: {
all: 1,
backup: 1,
snapshot: 1
},
isValidState: function(state) {
return !!this.validStates[state];
},
items: [
{
xtype: 'image-list'
}
]
});
| 16.106383 | 44 | 0.550859 |
ea56c8ec6ed40ac6461a361247169f5dd27a83fa | 144 | js | JavaScript | node_modules/carbon-icons-svelte/lib/WatsonHealthAnnotationVisibility20/index.js | seekersapp2013/new | 1e393c593ad30dc1aa8642703dad69b84bad3992 | [
"MIT"
] | null | null | null | node_modules/carbon-icons-svelte/lib/WatsonHealthAnnotationVisibility20/index.js | seekersapp2013/new | 1e393c593ad30dc1aa8642703dad69b84bad3992 | [
"MIT"
] | null | null | null | node_modules/carbon-icons-svelte/lib/WatsonHealthAnnotationVisibility20/index.js | seekersapp2013/new | 1e393c593ad30dc1aa8642703dad69b84bad3992 | [
"MIT"
] | null | null | null | import WatsonHealthAnnotationVisibility20 from "./WatsonHealthAnnotationVisibility20.svelte";
export default WatsonHealthAnnotationVisibility20; | 72 | 93 | 0.909722 |
ea57b1797f6987fd023450111439b724e82aeb24 | 4,002 | js | JavaScript | src/client/third-party/react-pixi-fiber/src/possibleStandardNames.js | roc-and-roll/roc-and-roll | 3aea4a8a0962277690bd463503279c5c29e1ad2a | [
"MIT"
] | null | null | null | src/client/third-party/react-pixi-fiber/src/possibleStandardNames.js | roc-and-roll/roc-and-roll | 3aea4a8a0962277690bd463503279c5c29e1ad2a | [
"MIT"
] | 15 | 2022-02-12T14:52:04.000Z | 2022-03-23T19:04:53.000Z | src/client/third-party/react-pixi-fiber/src/possibleStandardNames.js | roc-and-roll/roc-and-roll | 3aea4a8a0962277690bd463503279c5c29e1ad2a | [
"MIT"
] | null | null | null | // Based on: https://github.com/facebook/react/blob/27535e7bfcb63e8a4d65f273311e380b4ca12eff/packages/react-dom/src/shared/possibleStandardNames.js
import { TYPES } from "./types";
// http://pixijs.download/release/docs/PIXI.DisplayObject.html
const eventsStandardNames = {
added: "added",
click: "click",
mousedown: "mousedown",
mousemove: "mousemove",
mouseout: "mouseout",
mouseover: "mouseover",
mouseup: "mouseup",
mouseupoutside: "mouseupoutside",
pointercancel: "pointercancel",
pointerdown: "pointerdown",
pointermove: "pointermove",
pointerout: "pointerout",
pointerover: "pointerover",
pointertap: "pointertap",
pointerup: "pointerup",
pointerupoutside: "pointerupoutside",
removed: "removed",
rightclick: "rightclick",
rightdown: "rightdown",
rightup: "rightup",
rightupoutside: "rightupoutside",
tap: "tap",
touchcancel: "touchcancel",
touchend: "touchend",
touchendoutside: "touchendoutside",
touchmove: "touchmove",
touchstart: "touchstart",
};
// http://pixijs.download/release/docs/PIXI.DisplayObject.html
const displayObjectStandardNames = {
...eventsStandardNames,
alpha: "alpha",
angle: "angle",
buttonmode: "buttonMode",
cacheasbitmap: "cacheAsBitmap",
cursor: "cursor",
filterarea: "filterArea",
filters: "filters",
hitarea: "hitArea",
interactive: "interactive",
mask: "mask",
name: "name",
pivot: "pivot",
position: "position",
renderable: "renderable",
rotation: "rotation",
scale: "scale",
skew: "skew",
transform: "transform",
visible: "visible",
x: "x",
y: "y",
};
// http://pixijs.download/release/docs/PIXI.Container.html
const containerStandardNames = {
...displayObjectStandardNames,
height: "height",
interactivechildren: "interactiveChildren",
sortablechildren: "sortableChildren",
sortdirty: "sortDirty",
width: "width",
};
// http://pixijs.download/release/docs/PIXI.Sprite.html
const spriteStandardNames = {
...containerStandardNames,
anchor: "anchor",
blendmode: "blendMode",
pluginname: "pluginName",
roundpixels: "roundPixels",
shader: "shader",
texture: "texture",
tint: "tint",
};
// http://pixijs.download/release/docs/PIXI.extras.BitmapText.html
const bitmapTextStandardNames = {
...containerStandardNames,
align: "align",
anchor: "anchor",
font: "font",
letterspacing: "letterSpacing",
maxwidth: "maxWidth",
roundpixels: "roundPixels",
style: "style",
text: "text",
tint: "tint",
};
// http://pixijs.download/release/docs/PIXI.Graphics.html
const graphicsStandardNames = {
...containerStandardNames,
blendmode: "blendMode",
geometry: "geometry",
pluginname: "pluginName",
tint: "tint",
};
// http://pixijs.download/release/docs/PIXI.particles.ParticleContainer.html
const particleContainerStandardNames = {
...containerStandardNames,
autoresize: "autoResize",
batchsize: "batchSize",
blendmode: "blendMode",
interactivechildren: "interactiveChildren",
maxsize: "maxSize",
properties: "properties",
roundpixels: "roundPixels",
tint: "tint",
};
// http://pixijs.download/release/docs/PIXI.Text.html
const textStandardNames = {
...spriteStandardNames,
canvas: "canvas",
context: "context",
resolution: "resolution",
style: "style",
text: "text",
};
// http://pixijs.download/release/docs/PIXI.extras.TilingSprite.html
const tilingSpriteStandardNames = {
...spriteStandardNames,
clampmargin: "clampMargin",
tileposition: "tilePosition",
tilescale: "tileScale",
tiletransform: "tileTransform",
uvrespectanchor: "uvRespectAnchor",
uvmatrix: "uvMatrix",
};
const possibleStandardNames = {
[TYPES.BITMAP_TEXT]: bitmapTextStandardNames,
[TYPES.CONTAINER]: containerStandardNames,
[TYPES.GRAPHICS]: graphicsStandardNames,
[TYPES.PARTICLE_CONTAINER]: particleContainerStandardNames,
[TYPES.SPRITE]: spriteStandardNames,
[TYPES.TEXT]: textStandardNames,
[TYPES.TILING_SPRITE]: tilingSpriteStandardNames,
};
export default possibleStandardNames;
| 26.503311 | 147 | 0.721389 |
ea5862c3ae37a81abbabd10bf6c1eb8e88d5e416 | 3,610 | js | JavaScript | resources/hemesh/ref/html/interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.js | DweebsUnited/CodeMonkey | 3b27e9c189c897b06002498aea639bb44671848a | [
"BSD-3-Clause"
] | null | null | null | resources/hemesh/ref/html/interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.js | DweebsUnited/CodeMonkey | 3b27e9c189c897b06002498aea639bb44671848a | [
"BSD-3-Clause"
] | 7 | 2016-06-03T05:41:27.000Z | 2018-08-07T07:09:40.000Z | resources/hemesh/ref/html/interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.js | DweebsUnited/CodeMonkey | 3b27e9c189c897b06002498aea639bb44671848a | [
"BSD-3-Clause"
] | null | null | null | var interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d =
[
[ "apply2DSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a607085ce4efc6284f8958399d26ba7d6", null ],
[ "applyAsNormal2DSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a2cb03a84a8b5ab1658a802f7752c2255", null ],
[ "applyAsNormalSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a394f1b6bd68c716c8ba50c6406d3f541", null ],
[ "applyAsPoint2DSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a57034125826f6cfba036546558dea90d", null ],
[ "applyAsPointSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#ad817e9df683086ea23b751c1eeccf0c5", null ],
[ "applyAsVector2DSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a5a68f79defc4284d8f85f56c6eb97a78", null ],
[ "applyAsVectorSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#aed777e5e53b0bc6c1342aef0406c535c", null ],
[ "applySelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#ace414a483c98c47f0a1545363f235792", null ],
[ "rotateAboutAxis2PSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a8b2965ea4ef5e62bce93037743d9c918", null ],
[ "rotateAboutAxis2PSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a2ddf9f20a6fdbc924d0909c102da96e5", null ],
[ "rotateAboutAxisSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#aca5700fa6b9a8037c5658d2384020973", null ],
[ "rotateAboutAxisSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a36f741f27c940799635da3c91fa38c85", null ],
[ "rotateAboutOrigin2DSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a09ecc4f7234c4466fe68b8a0a43c2c93", null ],
[ "rotateAboutOriginSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a5d431f2662c0693dd184f88a38a9a7bf", null ],
[ "rotateAboutOriginSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a96fb8410777750d30266d4d57e887f02", null ],
[ "rotateAboutPoint2DSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#af76508cb958484652759469b7d96217d", null ],
[ "rotateAboutPoint2DSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#abf5e31e693ee23626bddf3843a9699e5", null ],
[ "scale2DSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#af5375e8813f3313387e636827e00f5f0", null ],
[ "scale2DSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#af3f64cfff04a016699186a40b7ac518e", null ],
[ "scaleSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a0fdc804d08f73287defe1b60e38c10be", null ],
[ "scaleSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#af784a342eb83f36c054d85341d30d87a", null ],
[ "translate2DSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a75504e147fb51ac774f60f20b998988e", null ],
[ "translate2DSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#ad19e6e02f8c5866f60129591b5dc7014", null ],
[ "translateSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#a0ccfe2889c2098e36a140a76011409bf", null ],
[ "translateSelf", "interfacewblut_1_1geom_1_1_w_b___mutable_coordinate_transform3_d.html#ab701ec9ffa4105615df68aacdb3e08c0", null ]
]; | 128.928571 | 147 | 0.859557 |
ea58a0af0af946af8aa99965690046d649dae8f2 | 1,159 | js | JavaScript | src/node.js | glayzzle/code-snipper | 5b4a8af9153caa6156301157c48f167f1da739c3 | [
"BSD-3-Clause"
] | 1 | 2017-03-18T17:10:07.000Z | 2017-03-18T17:10:07.000Z | src/node.js | glayzzle/code-snipper | 5b4a8af9153caa6156301157c48f167f1da739c3 | [
"BSD-3-Clause"
] | null | null | null | src/node.js | glayzzle/code-snipper | 5b4a8af9153caa6156301157c48f167f1da739c3 | [
"BSD-3-Clause"
] | 1 | 2022-02-08T16:09:05.000Z | 2022-02-08T16:09:05.000Z | /*!
* Copyright (C) 2018 Glayzzle (BSD3 License)
* @authors https://github.com/glayzzle/code-sniper/graphs/contributors
* @url http://glayzzle.com/code-sniper
*/
export default class Node {
constructor(document, parent, node) {
this.ownerDocument = document;
this.parentNode = parent;
this.nodeName = node.kind;
this.children = [];
this.attributes = {};
this.classList = [];
this.ast = node;
if (node.hasOwnProperty('name')) {
this.id = node.name;
}
for(var k in node) {
let value = node[k];
if (value === null) continue;
if (value === true) {
this.classList.push(k);
} else if (typeof value === 'string' || typeof value === 'number') {
this.attributes[k] = value;
} else {
if (Array.isArray(value)) {
value.forEach((item) => {
this.children.push(
new Node(document, this, item)
);
});
} else if (value.hasOwnProperty('kind')) {
// @fixme : lost attribute ?
this.children.push(
new Node(document, this, value)
);
}
}
}
}
}
| 26.340909 | 74 | 0.535807 |
ea59110154070cc4326c13dbba82c502af345e9f | 6,602 | js | JavaScript | public/book/js/common.js | Matvey021292/lookbook | dafa894825e95937d133f2da3d9519683e1884ea | [
"MIT"
] | null | null | null | public/book/js/common.js | Matvey021292/lookbook | dafa894825e95937d133f2da3d9519683e1884ea | [
"MIT"
] | 3 | 2021-03-09T21:40:27.000Z | 2022-02-26T19:36:05.000Z | public/book/js/common.js | Matvey021292/lookbook | dafa894825e95937d133f2da3d9519683e1884ea | [
"MIT"
] | null | null | null |
let glides = document.querySelectorAll(".glide");
glides.forEach(function (e, i) {
let glides_slide = e.getAttribute('data-slide-count') || 7;
if (e.querySelectorAll(".VerticalBookCard__tinyBook").length <= glides_slide) {
e.querySelector(".glide__arrows").innerHTML = "";
return;
}
new Glide(e, {
perView: glides_slide,
type: "carousel",
startAt: 0
}).mount();
if (document.querySelectorAll('.loader')) {
document.querySelectorAll('.loader').forEach(function (e, i) {
e.classList.remove('show')
});
}
});
if (document.querySelector('.single-slider')) {
wheelSlider();
}
function wheelSlider() {
window.addEventListener('wheel', function (event) {
if (event.deltaY < 0) {
document.querySelector('.single-slider .arrowRight').click()
}
else if (event.deltaY > 0) {
document.querySelector('.single-slider .arrowLeft').click()
}
});
}
new autoComplete({
data: {
src: async () => {
const query = document.querySelector("#autoComplete").value;
const source = await fetch(
`${ajax_login_object.search_url}?search=${query}`
);
const data = await source.json();
return data.recipes;
},
key: ["title"],
cache: false
},
placeHolder: "Поиск",
selector: "#autoComplete",
threshold: 3,
debounce: 300,
searchEngine: "strict",
resultsList: {
render: true,
container: source => {
source.setAttribute("id", "autoComplete_list");
},
destination: document.querySelector("#autoComplete"),
position: "afterend",
element: "ul"
},
maxResults: 12,
highlight: true,
resultItem: {
content: (data, source) => {
source.innerHTML = data.match;
},
element: "li"
},
noResults: () => {
const result = document.createElement("li");
result.setAttribute("class", "no_result");
result.setAttribute("tabindex", "1");
result.innerHTML = "No Results";
document.querySelector("#autoComplete_list").appendChild(result);
},
onSelection: feedback => {
document.querySelector("#autoComplete").value =
feedback.selection.value.title;
console.log(feedback.selection.value.book_id);
window.location = '/book/' + feedback.selection.value.book_id;
}
});
function showMessageNotAuth(e, message) {
e.preventDefault();
alert(message);
}
document.addEventListener('click', function () {
document.querySelector('#autoComplete_list').innerHTML = '';
})
let password = document.getElementById("new_password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword() {
if (password.value != confirm_password.value) {
confirm_password.setCustomValidity("Пароли не совпадают");
} else {
confirm_password.setCustomValidity('');
}
}
if (password) {
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
}
let switcher = document.querySelectorAll('.FormTextInput__passwordVisibilitySwitcher');
switcher.forEach(function (e, i) {
e.addEventListener('click', function (e) {
switchValue(e);
})
})
function switchValue(e) {
e.preventDefault();
let parent = e.target.closest('.FormTextInput__control');
parent.classList.toggle('visible');
parent.querySelector('input').type = 'password';
if (parent.classList.contains('visible')) {
parent.querySelector('input').type = 'text';
}
}
function handleChangeFiles(files, img) {
for (let i = 0; i < files.length; i++) {
let file = files[i];
if (!file.type.startsWith('image/')) { alert('Загрузите изображение'); continue }
let img = document.querySelector(img);
let reader = new FileReader();
reader.onload = (function (aImg) { return function (e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
}
}
let inputElement = document.querySelector('input[name="profile_image"]');
if (inputElement) {
inputElement.addEventListener("change", function () {
handleChangeFiles(this.files, '.UserSettingsAvatar__userImagePreviewContent');
});
}
document.addEventListener('click', function (event) {
if (!document.querySelector('.BookStatusChangePopup__buttonFunctional')) return;
let e = event.target;
let add = 'add_book_my_list';
let remove = 'remove_book_my_list';
let data = {
'book': book_id,
};
if (e.classList.contains(add)) {
requestPostData(route_booklist_add, data)
.then(e => console.log(e.message));
e.innerText = 'Удалить книгу из моего списка';
reverseClassList(e, remove, add);
} else if (e.classList.contains(remove)) {
requestPostData(route_booklist_remove, data)
.then(e => console.log(e.message));
e.innerText = 'Добавить книгу в мой список';
reverseClassList(e, add, remove);
}
})
function reverseClassList(e, classadd, classremove) {
e.classList.add(classadd);
e.classList.remove(classremove);
}
async function requestPostData(route, data) {
let meta = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
let response = await fetch(route, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8',
'X-CSRF-TOKEN': meta
},
body: JSON.stringify(data)
});
return await response.json();
}
let download_files = document.querySelectorAll('.download_file');
download_files.forEach(function (el, i) {
el.addEventListener('click', function (e) {
if (!e.target.dataset.format) return;
e.preventDefault();
let data = {
'file': e.target.href,
'format': e.target.dataset.format
}
requestPostData(download_route, data)
.then(e => window.open(e.message))
})
})
function showLoader() {
document.querySelector('.loader').classList.add('show');
}
function hideLoader() {
document.querySelector('.loader').classList.remove('show');
}
let collapse_btn = document.querySelectorAll('*[data-toggle="collapse"] .toggle-icon');
collapse_btn.forEach(function (e, i) {
e.addEventListener('click', function () {
e.closest('*[data-toggle="collapse"]').classList.toggle('open');
})
}) | 27.974576 | 104 | 0.619358 |
ea5a447af5f0b561fe538a997cbd9a54dc7c00a0 | 4,383 | js | JavaScript | index.js | Lukasa/language-restructuredtext | 30706379beb55bf17b3404546e4e3dccff516b5d | [
"MIT"
] | 33 | 2015-03-19T00:57:28.000Z | 2021-08-20T18:06:30.000Z | index.js | Lukasa/language-restructuredtext | 30706379beb55bf17b3404546e4e3dccff516b5d | [
"MIT"
] | 67 | 2015-02-05T11:23:37.000Z | 2021-12-14T10:44:51.000Z | index.js | Lukasa/language-restructuredtext | 30706379beb55bf17b3404546e4e3dccff516b5d | [
"MIT"
] | 30 | 2015-02-05T11:29:29.000Z | 2020-06-25T12:52:55.000Z | "use strict";
const name = "language-restructuredtext";
let disposables = null;
module.exports = {
activate(){
const {CompositeDisposable} = require("atom");
disposables = new CompositeDisposable();
disposables.add(
atom.commands.add("atom-text-editor", `${name}:fit-borders`, this.fitBorders.bind(this))
);
},
deactivate(){
if(disposables){
disposables.dispose();
disposables = null;
}
},
fitBorders(){
const editor = atom.workspace.getActiveTextEditor();
if(!editor) return;
editor.transact(125, () => {
let haveSelectedRegions = false;
for(const cursor of editor.getCursors())
cursor.selection.isEmpty()
? fitBordersAtCursor(cursor)
: (haveSelectedRegions = true);
if(haveSelectedRegions)
editor.mutateSelectedText(s => fitBordersInSelection(s), 75);
});
}
};
function fitBordersInSelection(selection){
const insetHeading = /((^|\n)([-=~`#"^+*:.'_])\3{2,})[ \t]*\n([ \t]*\S.*?)[ \t]*\n(\3{3,})[ \t]*(?=$|\n)/g;
const plainHeading = /((?:^|\n)[ \t]*\n)(\S.*?)[ \t]*\n(([-=~`#"^+*:.'_])\4{2,})[ \t]*(?=$|\n)/g;
const modifiedText = selection.getText()
.replace(insetHeading, (...args) => {
const [match, topLine, nl, borderStyle, titleText, bottomLine] = args;
const padding = titleText.match(/^ */)[0].length;
const newLength = titleText.length + padding;
const newBorder = borderStyle.repeat(newLength);
return `${nl}${newBorder}\n${titleText}\n${newBorder}`;
})
.replace(plainHeading, (...args) => {
const [match, blankLine, titleText, borderLine, borderStyle] = args;
const newLength = titleText.length;
const newBorder = borderStyle.repeat(newLength);
return `${blankLine}${titleText}\n${newBorder}`;
});
selection.insertText(modifiedText, {select: true});
}
function fitBordersAtCursor(cursor){
const {editor} = cursor;
const {scopes} = cursor.getScopeDescriptor();
const borderScope = "punctuation.definition.heading.restructuredtext";
if(-1 !== scopes.indexOf(borderScope)){
const position = cursor.getBufferPosition();
const numLines = editor.getLineCount();
const range = editor.bufferRangeForScopeAtPosition(borderScope, position);
const {row} = position;
const lines = [];
for(let i = -2; i < 3; ++i){
const offsetRow = row + i;
if(offsetRow < 0 || offsetRow >= numLines) continue;
const {scopes} = editor.tokenForBufferPosition({row: offsetRow, column: 0});
const isBorder = -1 !== scopes.indexOf(borderScope);
const text = editor.lineTextForBufferRow(offsetRow);
lines.push({isBorder, row: offsetRow, scopes, text});
}
// Cursor's located underneath a section heading
if(/\w/.test(lines[1].text) && lines[2].isBorder){
if(lines[0].isBorder)
fitInsetHeading(editor, [,,...lines]);
else{
const blankLine = /^[ \t]*$/.test(lines[0].text);
if(blankLine && /^\S/.test(lines[1].text))
fitPlainHeading(editor, lines);
}
}
// Cursor's located in the row above a heading
else{
if(row <= 3)
lines.unshift(...new Array(5 - lines.length));
if(/\w/.test(lines[3].text) && lines[2].isBorder && lines[4].isBorder)
fitInsetHeading(editor, lines);
}
}
}
function fitInsetHeading(editor, lines){
const topStyle = lines[2].text[0];
const bottomStyle = lines[4].text[0];
const titleText = lines[3].text;
if(topStyle !== bottomStyle) return;
editor.transact(75, () => {
const padding = titleText.match(/^ */)[0].length;
const newLength = titleText.replace(/[ \t]+$/, "").length + padding;
const scaledBorder = topStyle.repeat(newLength);
const rowRange = i => editor.bufferRangeForBufferRow(lines[i].row);
// Avoid adding an undo step if nothing changed.
if(scaledBorder === lines[2].text && scaledBorder === lines[4].text)
return editor.abortTransaction();
editor.buffer.setTextInRange(rowRange(2), scaledBorder);
editor.buffer.setTextInRange(rowRange(4), scaledBorder);
});
}
function fitPlainHeading(editor, lines){
const borderStyle = lines[2].text[0];
const titleText = lines[1].text;
editor.transact(75, () => {
const {length} = titleText.replace(/[ \t]+$/, "");
const scaled = borderStyle.repeat(length);
const range = editor.bufferRangeForBufferRow(lines[2].row);
if(scaled !== editor.buffer.getTextInRange(range))
editor.buffer.setTextInRange(range, scaled);
});
}
| 30.65035 | 108 | 0.655031 |
ea5a7f32584c1378964e17d9ede9e2877e541ecb | 3,414 | js | JavaScript | admin/CRUDEntry.js | newsomellc/compages | 36dc10d76c936dd053e7b8ef9be22674eba84ce4 | [
"MIT"
] | null | null | null | admin/CRUDEntry.js | newsomellc/compages | 36dc10d76c936dd053e7b8ef9be22674eba84ce4 | [
"MIT"
] | null | null | null | admin/CRUDEntry.js | newsomellc/compages | 36dc10d76c936dd053e7b8ef9be22674eba84ce4 | [
"MIT"
] | null | null | null | 'use strict';
module.exports = CRUDEntry;
const CRUDTable = require('./CRUDTable');
const CRUDTree = require('./CRUDTree');
const define_property = require('../util/define_property');
const ENUMS = require('./ENUMS');
/**
* Sets up a heading in the admin. A heading can contain CRUDs. This isn't REALLY a crud,
* but it's used in almost every context a CRUD is on the front end, so I treat it as one.
*
* params
* {id} A unique text ID for this heading. This is used for the URL slug.
* {name}(o) A name to display in menus etc... Defaults to the ID with the first letter capitalized.
* {children}(o) A list of data sources to use as a descendant of this.
* {page} A template or something else to display when this item is clicked in the menu. Defaults to nothing.
* {permissions}(o) An object with string properties 'view', 'change', 'add', 'delete' etc. Adds them to the user settings menu too if they aren't already.
* {permissionCB)(o) A function that will determine if a user can access this datasource. Allows advanced permissions.
* {path}(o) A reference to the path object of this data source.
*/
function CRUDEntry (params, socket)
{
///class init
if (new.target) throw Error(this.constructor.name + ' cannot be called with `new` keyword.');
const self = Object.create(PROTOTYPE);
const type = 'CRUDEntry';
const children = Object.create(null);
const actions = Object.create(null);
///properties
const id = params.id;
const name = params.name || id[0].toUpperCase() + id.slice(1);
const name_plural = params.name_plural || name+'s';
const permissions = params.permissions || ENUMS.DEFAULT_PERMISSIONS
.reduce((ag, th) => { ag[th] = self.id + '-' + th; return ag;}, Object.create(null));
const permissionCB = params.permissionCB;
let path = [params.id]; //Always assume you're root when first created.
///functions
/**
* Add a CRUD inside of this.
*/
function add (c)
{
if (!c.type)
throw Error('If not passing an instantiated `CRUDSource` object, `type` param is required.');
if (!PROTOTYPE.isPrototypeOf(c))
switch (c.type)
{
case 'CRUDEntry':
c = CRUDEntry(c, socket);
break;
case 'CRUDTable':
c = CRUDTable(c, socket);
break;
case 'CRUDTree':
c = CRUDTree(c, socket);
break;
default:
throw Error('Unknown type: ' + c.type);
}
c.path = [...path, c.id];
children[c.id] = c;
return c;
}
if (!typeof params.id === 'string')
throw Error('Expected param `id` to be a string, got: ' + typeof params.children);
///publishing
let dp = define_property.DefReadOnly(self);
let dpw = define_property.DefGetSet(self);
dp('id', () => id);
dp('type', () => type);
dp('name', () => name);
dp('name_plural', () => name_plural);
dp('add', () => add);
dp('children', () => children);
dp('actions', () => actions);
dp('socket', () => socket);
dpw('path', () => path, p => path=p);
///logic
if (params.children)
Object.values(params.children).forEach(add);
//else
//throw Error('Expected param `children` to be an array, got: ' + typeof params.children);
return self;
}
///constants
/**
* Lets us do things like obj.isPrototypeOf().
*/
const PROTOTYPE = Object.create(CRUDEntry);
| 33.80198 | 161 | 0.623902 |
ea5c41ca431b26cf823fa13fb1cc0d37094bd173 | 1,874 | js | JavaScript | wavemaker/wavemaker-studio/src/main/webapp/pages/PreferencesPane/PreferencesPane.widgets.js | michaelkantor/wavemaker | aa25d6fa75ed2a904f4bd7b94e0e16a0da7baf9e | [
"Apache-2.0"
] | null | null | null | wavemaker/wavemaker-studio/src/main/webapp/pages/PreferencesPane/PreferencesPane.widgets.js | michaelkantor/wavemaker | aa25d6fa75ed2a904f4bd7b94e0e16a0da7baf9e | [
"Apache-2.0"
] | null | null | null | wavemaker/wavemaker-studio/src/main/webapp/pages/PreferencesPane/PreferencesPane.widgets.js | michaelkantor/wavemaker | aa25d6fa75ed2a904f4bd7b94e0e16a0da7baf9e | [
"Apache-2.0"
] | 1 | 2018-08-24T02:01:07.000Z | 2018-08-24T02:01:07.000Z | /*
* Copyright (C) 2009-2013 VMware, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
PreferencesPane.widgets = {
layoutBox1: ["wm.Layout", {height: "100%", width: "100%"}, {}, {
mainPanel: ["wm.studio.DialogMainPanel", {},{}, {
panel2: ["wm.Panel", {height: "100%", width: "100%", verticalAlign: "middle", horizontalAlign: "left", layoutKind: "top-to-bottom"}, {}, {
wavemakerFolderEditor: ["wm.SelectMenu", {_classes: {captionNode: ["wm_FontColor_White"]}, restrictValues: false, captionSize: "130px", caption: "WaveMaker Folder", width: "100%"}, {onEnterKeyPress: "okButtonClick"}, {}],
demoFolderEditor: ["wm.Text", {showing: false, _classes: {captionNode: ["wm_FontColor_White"]}, captionSize: "130px", caption: "Demos Folder", width: "100%"}, {onEnterKeyPress: "okButtonClick"}, {
}]
}]
}],
footer: ["wm.Panel", {_classes: {domNode: ["dialogfooter"]}, height: "30px", layoutKind: "left-to-right", horizontalAlign: "right"}, {}, {
okButton: ["wm.Button", {_classes: {domNode: ["StudioButton"]},caption: "OK", width: "70px", padding: "0"}, {onclick: "okButtonClick"}],
spacer4: ["wm.Spacer", {width: "10px"}, {}],
cancelButton: ["wm.Button", {_classes: {domNode: ["StudioButton"]},caption: "Cancel", width: "70px", padding: "0"}, {onclick: "cancelButtonClick"}]
}]
}]
}
| 60.451613 | 227 | 0.665422 |
ea5c5886a893d14a68c056fa07a14b5f8550a722 | 1,235 | js | JavaScript | src/app/router.js | keithwhor/dotcom | f4fc8f900ac6b809b27b2212ddab71345ab57804 | [
"MIT"
] | 9 | 2016-03-08T03:51:03.000Z | 2016-05-12T15:46:41.000Z | src/app/router.js | keithwhor/dotcom | f4fc8f900ac6b809b27b2212ddab71345ab57804 | [
"MIT"
] | null | null | null | src/app/router.js | keithwhor/dotcom | f4fc8f900ac6b809b27b2212ddab71345ab57804 | [
"MIT"
] | null | null | null | module.exports = (function() {
'use strict';
const Dotcom = require('dotcom');
const router = new Dotcom.Router();
/* Middleware */
/* executed *before* Controller-specific middleware */
// const ForceWWWMiddleware = Dotcom.require('middleware/force_www_middleware.js');
// const ForceHTTPSMiddleware = Dotcom.require('middleware/force_https_middleware.js');
// router.middleware.use(ForceWWWMiddleware);
// router.middleware.use(ForceHTTPSMiddleware);
/* Renderware */
/* executed *after* Controller-specific renderware */
const GzipRenderware = Dotcom.require('renderware/gzip_renderware.js')
router.renderware.use(GzipRenderware);
/* Routes */
const IndexController = Dotcom.require('app/controllers/index_controller.js');
const StaticController = Dotcom.require('app/controllers/static_controller.js');
const Error404Controller = Dotcom.require('app/controllers/error/404_controller.js');
/* generator: begin imports */
/* generator: end imports */
router.route('/').use(IndexController);
router.route('/static/*').use(StaticController);
/* generator: begin routes */
/* generator: end routes */
router.route('/*').use(Error404Controller);
return router;
})();
| 25.729167 | 89 | 0.718219 |
ea5d822c43f768eaf1288d3eeaed127926b2209e | 32 | js | JavaScript | test/tests/existing2/src/models/fixtures/fixtures.js | donejs/generator-donejs | 3bde311fc47e98d479c20a68acb647a1d504f0fe | [
"MIT"
] | 9 | 2015-08-12T05:02:28.000Z | 2019-04-29T20:29:25.000Z | test/tests/existing2/src/models/fixtures/fixtures.js | donejs/generator-donejs | 3bde311fc47e98d479c20a68acb647a1d504f0fe | [
"MIT"
] | 263 | 2015-07-27T14:01:37.000Z | 2020-01-23T17:23:08.000Z | test/tests/existing2/src/models/fixtures/fixtures.js | donejs/generator-donejs | 3bde311fc47e98d479c20a68acb647a1d504f0fe | [
"MIT"
] | 9 | 2016-01-03T14:16:20.000Z | 2022-01-27T18:55:30.000Z | import '~/models/fixtures/foo';
| 16 | 31 | 0.71875 |
ea5dac7b14319d22c297ce1123df89bc4a6066e5 | 2,351 | js | JavaScript | src/components/weatherApp/weatherCards.js | marteiduel/Weather | 7ac2768b6b3fc7253bfad180f99a0afd3a670581 | [
"MIT"
] | null | null | null | src/components/weatherApp/weatherCards.js | marteiduel/Weather | 7ac2768b6b3fc7253bfad180f99a0afd3a670581 | [
"MIT"
] | null | null | null | src/components/weatherApp/weatherCards.js | marteiduel/Weather | 7ac2768b6b3fc7253bfad180f99a0afd3a670581 | [
"MIT"
] | null | null | null | import { ContactSupport } from "@material-ui/icons";
import React, { Component } from "react";
export default class Cards extends Component {
constructor(props) {
super(props);
this.state = {
high: "",
low: "",
icon: "",
};
this.getData = this.getData.bind(this);
this.displayWeather = this.displayWeather.bind(this);
this.CheckDay = this.CheckDay.bind(this);
}
componentDidUpdate(propsanteriores) {
if (this.props.ciudad != propsanteriores.ciudad) {
console.log(this.props.ciudad);
this.setState({ city: this.props.ciudad });
this.getData();
}
}
getData() {
fetch(
"https://api.openweathermap.org/data/2.5/forecast?q=" +
this.props.ciudad +
"&units=imperial&appid=" +
"1b08555925c4b3f206e5d97823c01850"
)
.then((response) => {
return response.json();
})
.then((data) => this.displayWeather(data));
}
displayWeather(data) {
console.log(data);
this.setState({
high: data.list[this.props.id].main.temp_max,
low: data.list[this.props.id].main.temp_min,
icon: data.list[this.props.id].weather[0].icon,
});
}
CheckDay() {
var weekday = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
var dy = new Date();
console.log(parseInt(this.props.id) + dy.getDay());
if (parseInt(this.props.id) + dy.getDay() > 6) {
console.log(weekday[parseInt(this.props.id) + dy.getDay() - 7]);
return weekday[parseInt(this.props.id) + dy.getDay() - 7];
} else {
console.log(weekday[parseInt(this.props.id) + dy.getDay()]);
return weekday[parseInt(this.props.id) + dy.getDay()];
}
}
render() {
return (
<div className="card-section">
<div className="card-wrapper">
<div className="top-part">
<div className="day-of-week">{this.CheckDay()}</div>
<div className="card-img">
<img
src={`http://openweathermap.org/img/wn/${this.state.icon}@2x.png`}
/>
</div>
</div>
<div className="bottom-part">
<p>Min: {this.state.high}°</p>
<p>Max: {this.state.low}°</p>
</div>
</div>
</div>
);
}
}
| 26.715909 | 82 | 0.55168 |
ea5dd00adba658ee4eb841453fc10a7aacbd23c9 | 1,876 | js | JavaScript | server/externs/WeakRef.js | amithathreya/CodeCity | fc7db4e23c5c178568e85893564dfe2b1467f33a | [
"Apache-2.0"
] | 1 | 2021-03-02T21:43:19.000Z | 2021-03-02T21:43:19.000Z | server/externs/WeakRef.js | 1Crazymoney/CodeCity | 91d3959883bec55ba7734df02d6208057f32a966 | [
"Apache-2.0"
] | null | null | null | server/externs/WeakRef.js | 1Crazymoney/CodeCity | 91d3959883bec55ba7734df02d6208057f32a966 | [
"Apache-2.0"
] | null | null | null | /**
* @license
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Closure Compiler externs for the new tc39 WeakRef and
* FinalizationGroup API https://github.com/tc39/proposal-weakrefs
* @author cpcallen@google.com (Christopher Allen)
* @externs
*/
/**
* @constructor
* @param {T} target
* @template T
*/
// TODO(cpcallen): Make T bounded to {!Object} once closure-compiler
// supports bounded generic types.
var WeakRef = function(target) {};
/**
* @return {T}
*/
WeakRef.prototype.deref = function() {};
/**
* @constructor
* @param {function(!Iterator<HOLDINGS>)} cleanupCallback
* @template TARGET, HOLDINGS, TOKEN
*/
// TODO(cpcallen): Make TARGET and TOKEN bounded to {!Object} once
// closure-compiler supports bounded generic types.
var FinalizationGroup = function(cleanupCallback) {};
/**
* @param {TARGET} target
* @param {HOLDINGS} holdings
* @param {?TOKEN} unregisterToken
* @return {void}
*/
FinalizationGroup.prototype.register =
function(target, holdings, unregisterToken) {};
/**
* @param {?TOKEN} unregisterToken
* @return {void}
*/
FinalizationGroup.prototype.unregister = function(unregisterToken) {};
/**
* @param {function(!Iterator<HOLDINGS>)} cleanupCallback
* @return {void}
*/
FinalizationGroup.prototype.cleanupSome = function(cleanupCallback) {};
| 27.588235 | 75 | 0.714286 |
ea5e006cb766fc7aabf61f2715f981b3824a5f5a | 441 | js | JavaScript | webpack/webpack.parts.js | michaelpoltorak/react-shared | 58ca55408f8e24ce3aa4a3b66b4f1199b5a557b3 | [
"MIT"
] | null | null | null | webpack/webpack.parts.js | michaelpoltorak/react-shared | 58ca55408f8e24ce3aa4a3b66b4f1199b5a557b3 | [
"MIT"
] | null | null | null | webpack/webpack.parts.js | michaelpoltorak/react-shared | 58ca55408f8e24ce3aa4a3b66b4f1199b5a557b3 | [
"MIT"
] | null | null | null | const webpack = require('webpack');
exports.devServer = function(host, port) {
return {
devServer: {
historyApiFallback: true,
inline:true,
hot:true,
stats: 'errors-only',
host: host, // Defaults to `localhost`
port: port, // Defaults to 8080
overlay: {
errors: true,
warnings: true,
},
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
};
}; | 22.05 | 47 | 0.562358 |
ea5ebf499e2d5487a6f1cabe1e603530d24b7175 | 555 | js | JavaScript | test/regexp.js | DreamYuki/coins-trading-system | d87a4dd7e81cc57f7fd8b88e5093a85144402a8f | [
"MIT"
] | null | null | null | test/regexp.js | DreamYuki/coins-trading-system | d87a4dd7e81cc57f7fd8b88e5093a85144402a8f | [
"MIT"
] | null | null | null | test/regexp.js | DreamYuki/coins-trading-system | d87a4dd7e81cc57f7fd8b88e5093a85144402a8f | [
"MIT"
] | null | null | null | let str = "XEM/USDT2021-03-1203:15:56买入0.59";
let coin = str.split("/USDT")[0];
let date = str.split("/USDT")[1].slice(0,18)
let intent = str.split("/USDT")[1].slice(18,20)
let cost = str.split("/USDT")[1].slice(20)
let str2 = "USDT403.8";
let num = str2.replace(/USDT/, "");
let arr = [coin, date, intent, cost, num];
console.log(arr.slice(0,4));
let str3 = "XEM--完全成交查看详情";
console.log(str3.indexOf("完全成交"));
let arr4 = ["XEM", "2021-03-12,03:15:56", "买入", 0.5923, 51.545];
let fixindex = arr4[3].toString().split(".")[1].length;
console.log(fixindex); | 37 | 64 | 0.637838 |
ea6036c1cc08ef5de65f39e1f9d83b586f38bf9c | 748 | js | JavaScript | react-demo/build/precache-manifest.5cbc871c4459a7dfe05777c78c58b385.js | 3010147651/cloudbase-templates | 121184bc3efa9955e74eccf3ae0d6d7df4600d30 | [
"Apache-2.0"
] | null | null | null | react-demo/build/precache-manifest.5cbc871c4459a7dfe05777c78c58b385.js | 3010147651/cloudbase-templates | 121184bc3efa9955e74eccf3ae0d6d7df4600d30 | [
"Apache-2.0"
] | null | null | null | react-demo/build/precache-manifest.5cbc871c4459a7dfe05777c78c58b385.js | 3010147651/cloudbase-templates | 121184bc3efa9955e74eccf3ae0d6d7df4600d30 | [
"Apache-2.0"
] | null | null | null | self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "800febb32b17782767354e2519c5266f",
"url": "/index.html"
},
{
"revision": "a6955fe842066b6b0854",
"url": "/static/css/2.804f42c7.chunk.css"
},
{
"revision": "692f7cec3daddf07b729",
"url": "/static/css/main.f3976341.chunk.css"
},
{
"revision": "a6955fe842066b6b0854",
"url": "/static/js/2.b05a4b59.chunk.js"
},
{
"revision": "11da4d0289ce192632a3fc6590a86fde",
"url": "/static/js/2.b05a4b59.chunk.js.LICENSE"
},
{
"revision": "692f7cec3daddf07b729",
"url": "/static/js/main.0f95c101.chunk.js"
},
{
"revision": "9d87d2f92af112f4e835",
"url": "/static/js/runtime-main.072e3011.js"
}
]); | 24.933333 | 66 | 0.622995 |
ea607fb1b383740fe8b4813f70dbd08b587545ad | 2,250 | js | JavaScript | test/google-payment/unit/index.js | lemmalearning/braintree-web | 6e987da40c8b914592210323e4e0d57f1cdb2432 | [
"MIT"
] | null | null | null | test/google-payment/unit/index.js | lemmalearning/braintree-web | 6e987da40c8b914592210323e4e0d57f1cdb2432 | [
"MIT"
] | null | null | null | test/google-payment/unit/index.js | lemmalearning/braintree-web | 6e987da40c8b914592210323e4e0d57f1cdb2432 | [
"MIT"
] | null | null | null | 'use strict';
var Promise = require('../../../src/lib/promise');
var basicComponentVerification = require('../../../src/lib/basic-component-verification');
var googlePayment = require('../../../src/google-payment');
var GooglePayment = require('../../../src/google-payment/google-payment');
var fake = require('../../helpers/fake');
describe('googlePayment', function () {
describe('create', function () {
beforeEach(function () {
var configuration = fake.configuration();
configuration.gatewayConfiguration.androidPay = {
enabled: true,
googleAuthorizationFingerprint: 'fingerprint',
supportedNetworks: ['visa', 'amex']
};
this.fakeClient = fake.client({
configuration: configuration
});
this.fakeClient._request = function () {};
this.sandbox.stub(basicComponentVerification, 'verify').resolves();
});
it('returns a promise', function () {
var promise = googlePayment.create({
client: this.fakeClient
});
expect(promise).to.be.an.instanceof(Promise);
});
it('verifies with basicComponentVerification', function (done) {
var client = this.fakeClient;
googlePayment.create({
client: client
}, function () {
expect(basicComponentVerification.verify).to.be.calledOnce;
expect(basicComponentVerification.verify).to.be.calledWith({
name: 'Google Pay',
client: client
});
done();
});
});
it('instantiates a Google Pay integration', function (done) {
googlePayment.create({
client: this.fakeClient
}, function (err, thingy) {
expect(err).not.to.exist;
expect(thingy).to.be.an.instanceof(GooglePayment);
done();
});
});
it('returns error if android pay is not enabled', function (done) {
var client = fake.client();
googlePayment.create({
client: client
}, function (err) {
expect(err).to.exist;
expect(err.type).to.equal('MERCHANT');
expect(err.code).to.equal('GOOGLE_PAYMENT_NOT_ENABLED');
expect(err.message).to.equal('Google Pay is not enabled for this merchant.');
done();
});
});
});
});
| 29.220779 | 90 | 0.608 |
ea6175a1542417167b8d550c1ed21e836caa544c | 3,361 | js | JavaScript | src/ui/src/store/modules/api/business-synchronous.js | wivw0306/bk-cmdb | 330bb6e6a5aa40987a26562a740bb8cb37ac1f66 | [
"Apache-2.0"
] | 1 | 2022-01-29T10:13:07.000Z | 2022-01-29T10:13:07.000Z | src/ui/src/store/modules/api/business-synchronous.js | 941103git/bk-cmdb | 2915b5512e1444bfa5daa46101e702499189526e | [
"Apache-2.0"
] | null | null | null | src/ui/src/store/modules/api/business-synchronous.js | 941103git/bk-cmdb | 2915b5512e1444bfa5daa46101e702499189526e | [
"Apache-2.0"
] | 1 | 2022-03-16T08:31:28.000Z | 2022-03-16T08:31:28.000Z | /* eslint-disable no-unused-vars, max-len */
/*
* Tencent is pleased to support the open source community by making 蓝鲸 available.
* Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
import $http from '@/api'
const state = {}
const getters = {}
const actions = {
/**
* 根据服务模板、模块查询进程实例与服务模板之间的差异
* @param {Function} commit store commit mutation hander
* @param {Object} state store state
* @param {String} dispatch store dispatch action hander
* @param {Object} params 参数
* @return {promises} promises 对象
*/
searchServiceInstanceDifferences({ commit, state, dispatch, rootGetters }, { params, config }) {
return $http.post('find/proc/service_instance/difference', params, config)
},
/**
* 获取进程模板 diff 状态
*/
getProcessTplDiffState({ commit, state, dispatch, rootGetters }, { params, config }) {
return $http.post(`findmany/topo/service_template_sync_status/bk_biz_id/${params.bk_biz_id}`, params, config)
},
/**
* 获取已修改的进程模板列表
*/
getAllProcessTplDiffs({ commit, state, dispatch, rootGetters }, { params, config }) {
return $http.post('/find/proc/service_template/general_difference', params, config)
},
/**
* 获取进程下涉及到变更的实例
* @param {number} params.bk_biz_id 业务 ID
* @param {number} params.service_template_id 服务模板 ID
* @param {number} params.process_template_id 进程模板 ID
* @param {number} params.bk_module_id 模块 ID
* @param {string} [params.process_template_name] 进程模板名称。因为被删除的模板 ID 都为 0,所以需要进程模板名称配合来获取对应进程下的实例。
* @param {boolean} [params.service_category] 是否是服务分类变更
* @returns {Promise}
*/
getDiffInstances({ commit, state, dispatch, rootGetters }, { params, config }) {
return $http.post('/find/proc/difference/service_instances', params, config)
},
/**
* 获取单个实例的对比详情
* @param {number} params.bk_biz_id 业务 ID
* @param {number} params.service_template_id 服务模板 ID
* @param {number} params.process_template_id 进程模板 ID
* @param {number} params.bk_module_id 模块 ID
* @param {number} params.service_instance_id 服务实例 ID
* @returns {Promise}
*/
getInstanceDiff({ commit, state, dispatch, rootGetters }, { params, config }) {
return $http.post('/find/proc/service_instance/difference_detail', params, config)
},
/**
* 批量更新服务实例中的进程信息,保持和服务模板一致
* @param {Function} commit store commit mutation hander
* @param {Object} state store state
* @param {String} dispatch store dispatch action hander
* @param {Object} params 参数
* @return {promises} promises 对象
*/
syncServiceInstanceByTemplate({ commit, state, dispatch, rootGetters }, { params, config }) {
return $http.put('update/proc/service_instance/sync', params, config)
}
}
const mutations = {}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
| 37.344444 | 136 | 0.703065 |
ea6205eb52ba3e7f5140664620532fd04613ead7 | 8,676 | js | JavaScript | myCode.js | robertfg/Memory- | 5732e26fc1e824d65fc29c3896307f5c349ca746 | [
"MIT"
] | null | null | null | myCode.js | robertfg/Memory- | 5732e26fc1e824d65fc29c3896307f5c349ca746 | [
"MIT"
] | null | null | null | myCode.js | robertfg/Memory- | 5732e26fc1e824d65fc29c3896307f5c349ca746 | [
"MIT"
] | null | null | null | var sketchProc = function( processingInstance ){
with ( processingInstance ){
/* ********** BEGIN GENERAL NONCUSTOM CODE ********** */
processingInstance.size(400, 400);
processingInstance.background(0xFFF);
var mouseIsPressed = false;
processingInstance.mousePressed = function () { mouseIsPressed = true; };
processingInstance.mouseReleased = function () { mouseIsPressed = false; };
var keyIsPressed = false;
processingInstance.keyPressed = function () { keyIsPressed = true; };
processingInstance.keyReleased = function () { keyIsPressed = false; };
// This function is required to use "getImage"
function getImage(s) {
processingInstance.externals.sketch.imageCache.add(s);
return processingInstance.loadImage(s);
}
/* ********** BEGIN GENERAL CUSTOM CODE ********** */
// Global variables
var NUM_COLS = 5;
var NUM_ROWS = 4;
// Initialize these in the initializeGame() function
var flippedTiles;
var tiles;
var delayStartFC; // FC = Frame Count, used with draw
var numTries;
// Get images for faces
var faces = [
getImage("leafers-seed.png"),
getImage("leafers-seedling.png"),
getImage("leafers-sapling.png"),
getImage("leafers-tree.png"),
getImage("leafers-ultimate.png"),
getImage("marcimus.png"),
getImage("mr-pants.png"),
getImage("mr-pink.png"),
getImage("old-spice-man.png"),
getImage("robot_female_1.png"),
getImage("piceratops-tree.png"),
getImage("orange-juice-squid.png")
];
/*
* Potential values: 0 - Choose either "Start Game" or "End Game" buttons
* 1 - Draw the tiles
* 2 - Play the game
* 3 - "End Game" pressed: Game Over message
*/
var playGame = 0;
background(255, 255, 150);
/* ********** BEGIN SPECIFIC CUSTOM CODE ********** */
/* ****************************************
* BUTTON *
**************************************** */
// Constructor: set defaults
var Button = function(buttonConfig) {
this.x = buttonConfig.x || 0;
this.y = buttonConfig.y || 0;
this.width = buttonConfig.width || 130;
this.height = buttonConfig.height || 40;
this.label = buttonConfig.label || "New Game";
this.onClick = buttonConfig.onClick || function() {};
};
// Function to draw the button
Button.prototype.draw = function() {
fill(0, 0, 0);
rect(this.x, this.y, this.width, this.height, 5);
fill(255, 255, 255);
textSize(19);
textAlign(LEFT, TOP);
text(this.label, this.x+20, this.y+this.height/4);
};
// Function to check if you've clicked the button
Button.prototype.isMouseInside = function() {
return (mouseX >= this.x &&
mouseX <= (this.x+this.width) &&
mouseY >= this.y &&
mouseY <= (this.y+this.height));
};
// Function to handle mouse click
Button.prototype.handleMouseClick = function() {
if ( this.isMouseInside() ) {
this.onClick();
}
};
// Define button
var startButton = new Button({
x: 135,
y: 100,
onClick: function() {
playGame = 1;
loop();
}
});
var exitButton = new Button({
x: 135,
y: 150,
label: "End Game",
onClick: function() {
//document.body.innerHTML = "<h1>GAME OVER !!!</h1>";
background(255, 255, 150);
fill(255, 0, 0);
textSize(36);
text("GAME OVER !!!", 75, 160);
playGame = 3;
noLoop();
}
});
/* ****************************************
* TILE *
**************************************** */
// Tile constructor function
var Tile = function(x, y, face) {
this.x = x;
this.y = y;
this.face = face;
this.width = 70;
//this.isMatch = false;
};
// Draw the tile face down
Tile.prototype.drawFaceDown = function() {
fill(214, 247, 202);
strokeWeight(2);
rect(this.x, this.y, this.width, this.width, 10);
image(getImage("leaf-green.png"), this.x, this.y, this.width, this.width);
this.isFaceUp = false;
};
// Draw the tile face up
Tile.prototype.drawFaceUp = function() {
fill(214, 247, 202);
strokeWeight(2);
rect(this.x, this.y, this.width, this.width, 10);
image(this.face, this.x, this.y, this.width, this.width);
this.isFaceUp = true;
};
// Check to see if the mouse is over a card
Tile.prototype.isUnderMouse = function(x, y) {
return ( x >= this.x && x <= this.x + this.width &&
y >= this.y && y <= this.y + this.width );
};
// Function to handle mouse click
Tile.prototype.handleMouseClick = function() {
// Is the mouse over the card?
if ( this.isUnderMouse(mouseX, mouseY) ) {
// Flip 2 cards as long as they're not face up
if ( flippedTiles.length < 2 && !this.isFaceUp ) {
// Turn the card over and increment the counter
this.drawFaceUp();
flippedTiles.push(this);
// Once you flip 2 cards, get ready to flip them back over
if ( flippedTiles.length === 2 ) {
if ( flippedTiles[0].face === flippedTiles[1].face ) {
flippedTiles[0].isMatch = true;
flippedTiles[1].isMatch = true;
}
// Increment global score-keeping variable
numTries++;
// Set initial frame count
delayStartFC = frameCount;
// Call draw
loop();
}
}
}
};
// initializeGame: select images from the faces array, 2 of each, and randomize
var initializeGame = function() {
// Initialize global variables
flippedTiles = [];
tiles = [];
delayStartFC = null;
numTries = 0;
// Local variables
var possibleFaces = faces.slice(0);
var selected = [];
// You need half the number of cards for faces.
for (var i = 0; i < (NUM_COLS * NUM_ROWS) / 2; i++) {
// Randomly pick one from the array of faces
var randomInd = floor(random(faces.length));
var face = faces[randomInd];
// Push 2 copies onto array
selected.push(face);
selected.push(face);
// Remove from faces array so we don't re-pick
faces.splice(randomInd, 1);
}
// Sort the faces array randomly:
selected.sort(function() {
return 0.5 - Math.random();
});
// Generate x, y coordinate of the tiles array
for (var i = 0; i < NUM_COLS; i++) {
for (var j = 0; j < NUM_ROWS; j++) {
tiles.push( new Tile(i * 78 + 10, j * 78 + 40, selected.pop()) );
}
}
};
/* ****************************************
* MOUSE CLICK *
**************************************** */
// Turn over any clicked cards
mouseClicked = function() {
if ( playGame === 0 ) {
startButton.handleMouseClick();
exitButton.handleMouseClick();
}
else if ( playGame === 2 ) {
for (var i = 0; i < tiles.length; i++) {
tiles[i].handleMouseClick();
}
// Check that you've found all matches
var foundAllMatches = true;
for (var i = 0; i < tiles.length; i++) {
foundAllMatches = foundAllMatches && tiles[i].isMatch;
}
// If all matches found, display the score
if ( foundAllMatches ) {
background(255, 255, 150);
fill(255, 0, 0);
textSize(24);
text("Nice job!", 150, 250);
text("You found them all in " + numTries + " tries.", 50, 300);
// Reset variables
playGame = 0;
//tiles = [];
//loop();
}
}
};
/* ****************************************
* START GAME *
**************************************** */
draw = function() {
if ( playGame === 0 ) {
// Draw the start and exit buttons:
//background(255, 255, 150);
startButton.draw();
exitButton.draw();
} else if ( playGame === 1 ) {
// Initialize the game
initializeGame();
// Draw the tiles
background(255, 255, 150);
for (var i = 0; i < tiles.length; i++) {
tiles[i].drawFaceDown();
}
// Set variable to play the game
playGame = 2;
}
// If you've flipped 2 cards and 2 seconds haven't passed
if ( delayStartFC && ( frameCount - delayStartFC ) > 60 ) {
// Turn the cards over again
for (var i = 0; i < tiles.length; i++) {
if (!tiles[i].isMatch) {
tiles[i].drawFaceDown();
}
}
// Reset counters
flippedTiles = [];
delayStartFC = null;
// Don't call draw
noLoop();
}
};
/* ********** END SPECIFIC CUSTOM CODE ********** */
}
};
| 26.944099 | 82 | 0.540111 |
ea621d31051943f26207a44118992b33891f2180 | 1,310 | js | JavaScript | __tests__/api/login.test.js | KCFindstr/ourpixels-node | 1a334c99579e13924c6958c2980706a4ce346bc3 | [
"MIT"
] | null | null | null | __tests__/api/login.test.js | KCFindstr/ourpixels-node | 1a334c99579e13924c6958c2980706a4ce346bc3 | [
"MIT"
] | null | null | null | __tests__/api/login.test.js | KCFindstr/ourpixels-node | 1a334c99579e13924c6958c2980706a4ce346bc3 | [
"MIT"
] | null | null | null | require('dotenv').config()
const frisby = require('frisby');
const { Joi } = frisby;
const url = 'http://localhost:8080';
it('login without username and password should return a 422', () => {
return frisby
.post(url + '/login/')
.expect('status', 422)
.expect('json', {
errors: ['Username and password are required.']
});
});
it('login without username should return a 422', () => {
return frisby
.post(url + '/login/', {
username: 'test'
})
.expect('status', 422)
.expect('json', {
errors: ['Username and password are required.']
});
});
it('login without username should return a 422', () => {
return frisby
.post(url + '/login/', {
password: 'root'
})
.expect('status', 422)
.expect('json', {
errors: ['Username and password are required.']
});
});
it('login with wrong credentials should return a 422', () => {
return frisby
.post(url + '/login/', {
username: 'test',
password: 'root'
})
.expect('status', 422)
.expect('json', {
errors: ['Authentication failed.']
});
});
it('should return a 200 when successfully login', () => {
return frisby
.post(url + '/login/', {
username: 'test',
password: 'password'
})
.expect('status', 200)
.expect('json', {
username: 'test',
success: true,
})
.expect('jsonTypes', 'token', Joi.string().required());
}); | 21.47541 | 69 | 0.61374 |
ea624e51f2f4712e95482d47d34adc2fda515712 | 19,497 | js | JavaScript | packages/react-bootstrap-table2/test/body.test.js | anu1097/react-bootstrap-table2 | a8ca13d9690ea439d4de58f1d5b835d76e69e623 | [
"MIT"
] | null | null | null | packages/react-bootstrap-table2/test/body.test.js | anu1097/react-bootstrap-table2 | a8ca13d9690ea439d4de58f1d5b835d76e69e623 | [
"MIT"
] | null | null | null | packages/react-bootstrap-table2/test/body.test.js | anu1097/react-bootstrap-table2 | a8ca13d9690ea439d4de58f1d5b835d76e69e623 | [
"MIT"
] | 1 | 2018-10-04T14:28:22.000Z | 2018-10-04T14:28:22.000Z | import React from 'react';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import Body from '../src/body';
import Row from '../src/row';
import Const from '../src/const';
import RowSection from '../src/row-section';
import mockBodyResolvedProps from './test-helpers/mock/body-resolved-props';
describe('Body', () => {
let wrapper;
const columns = [{
dataField: 'id',
text: 'ID'
}, {
dataField: 'name',
text: 'Name'
}];
const data = [{
id: 1,
name: 'A'
}, {
id: 2,
name: 'B'
}];
const keyField = 'id';
describe('simplest body', () => {
beforeEach(() => {
wrapper = shallow(<Body { ...mockBodyResolvedProps } keyField="id" columns={ columns } data={ data } />);
});
it('should render successfully', () => {
expect(wrapper.length).toBe(1);
expect(wrapper.find('tbody').length).toBe(1);
expect(wrapper.find(Row).length).toBe(data.length);
});
});
describe('when data is empty', () => {
beforeEach(() => {
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
keyField="id"
columns={ columns }
data={ data }
visibleColumnSize={ columns.length }
isEmpty
/>);
});
it('should not render', () => {
expect(wrapper.length).toBe(1);
expect(wrapper.find('tbody').length).toBe(0);
expect(wrapper.find(RowSection).length).toBe(0);
});
describe('when noDataIndication props is defined', () => {
let emptyIndication;
describe('and it is not a function', () => {
beforeEach(() => {
emptyIndication = 'Table is empty';
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
keyField="id"
columns={ columns }
data={ data }
visibleColumnSize={ columns.length }
noDataIndication={ emptyIndication }
isEmpty
/>);
});
it('should render successfully', () => {
expect(wrapper.length).toBe(1);
expect(wrapper.find('tbody').length).toBe(1);
expect(wrapper.find(RowSection).length).toBe(1);
expect(wrapper.find(RowSection).prop('content')).toEqual(emptyIndication);
});
});
describe('and it is a function', () => {
const content = 'Table is empty';
let emptyIndicationCallBack;
beforeEach(() => {
emptyIndicationCallBack = sinon.stub().returns(content);
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
keyField="id"
columns={ columns }
data={ data }
visibleColumnSize={ columns.length }
noDataIndication={ emptyIndicationCallBack }
isEmpty
/>);
});
it('should render successfully', () => {
expect(wrapper.length).toBe(1);
expect(wrapper.find('tbody').length).toBe(1);
expect(wrapper.find(RowSection).length).toBe(1);
expect(wrapper.find(RowSection).prop('content')).toEqual(emptyIndication);
});
it('should call custom noDataIndication function correctly', () => {
expect(emptyIndicationCallBack.callCount).toBe(1);
});
});
});
});
describe('when rowStyle prop is defined', () => {
const rowStyle = { backgroundColor: 'red', color: 'white' };
describe('and it is a style object', () => {
beforeEach(() => {
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
keyField="id"
columns={ columns }
data={ data }
rowStyle={ rowStyle }
/>);
});
it('should rendering Row component with correct style', () => {
const rows = wrapper.find(Row);
rows.forEach((row) => {
expect(row.props().style).toEqual(rowStyle);
});
});
});
describe('and it is a callback functoin', () => {
const rowStyleCallBack = sinon.stub().returns(rowStyle);
beforeEach(() => {
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
keyField="id"
columns={ columns }
data={ data }
rowStyle={ rowStyleCallBack }
/>);
});
it('should calling rowStyle callBack correctly', () => {
expect(rowStyleCallBack.callCount).toBe(data.length);
});
it('should calling rowStyle callBack with correct argument', () => {
expect(rowStyleCallBack.firstCall.calledWith(data[0], 0)).toBeTruthy();
expect(rowStyleCallBack.secondCall.calledWith(data[1], 1)).toBeTruthy();
});
it('should rendering Row component with correct style', () => {
const rows = wrapper.find(Row);
rows.forEach((row) => {
expect(row.props().style).toEqual(rowStyle);
});
});
});
describe('when selectRow.style is defined', () => {
const selectedRowKey = data[0][keyField];
const selectedRowKeys = [selectedRowKey];
const selectedStyle = { backgroundColor: 'green', fontWeight: 'bold' };
const selectRow = { mode: 'radio', style: selectedStyle };
beforeEach(() => {
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
keyField="id"
columns={ columns }
data={ data }
rowStyle={ rowStyle }
selectRow={ selectRow }
selectedRowKeys={ selectedRowKeys }
/>);
});
it('should rendering selected Row component with mixing selectRow.style correctly', () => {
const selectedRow = wrapper.find(Row).get(0);
expect(JSON.stringify(selectedRow.props.style)).toBe(JSON.stringify({
...rowStyle,
...selectedStyle
}));
});
describe('and selectRow.bgColor is also defined', () => {
beforeEach(() => {
selectRow.bgColor = 'gray';
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
keyField="id"
columns={ columns }
data={ data }
rowStyle={ rowStyle }
selectRow={ selectRow }
selectedRowKeys={ selectedRowKeys }
/>);
});
it('should rendering selected Row component with mixing selectRow.style correctly', () => {
const selectedRow = wrapper.find(Row).get(0);
expect(JSON.stringify(selectedRow.props.style)).toBe(JSON.stringify({
...rowStyle,
...selectedStyle,
backgroundColor: selectRow.bgColor
}));
});
it('should render selected Row component with correct style.backgroundColor', () => {
const selectedRow = wrapper.find(Row).get(0);
expect(selectedRow.props.style.backgroundColor).toEqual(selectRow.bgColor);
});
});
});
describe('when selectRow.bgColor is defined', () => {
const selectedRowKey = data[0][keyField];
const selectedRowKeys = [selectedRowKey];
const selectRow = { mode: 'radio', bgColor: 'gray' };
beforeEach(() => {
selectRow.bgColor = 'gray';
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
keyField="id"
columns={ columns }
data={ data }
rowStyle={ rowStyle }
selectRow={ selectRow }
selectedRowKeys={ selectedRowKeys }
/>);
});
it('should rendering selected Row component with correct style', () => {
const selectedRow = wrapper.find(Row).get(0);
expect(JSON.stringify(selectedRow.props.style)).toBe(JSON.stringify({
...rowStyle,
backgroundColor: selectRow.bgColor
}));
});
});
});
describe('when rowClasses prop is defined', () => {
const rowClasses = 'test-classe';
describe('and it is a string', () => {
beforeEach(() => {
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
keyField="id"
columns={ columns }
data={ data }
rowClasses={ rowClasses }
/>);
});
it('should rendering Row component with correct className', () => {
const rows = wrapper.find(Row);
rows.forEach((row) => {
expect(row.props().className).toEqual(rowClasses);
});
});
});
describe('and it is a callback function', () => {
const rowClassesCallBack = sinon.stub().returns(rowClasses);
beforeEach(() => {
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
keyField="id"
columns={ columns }
data={ data }
rowClasses={ rowClassesCallBack }
/>);
});
it('should calling rowClasses callback correctly', () => {
expect(rowClassesCallBack.callCount).toBe(data.length);
});
it('should calling rowClasses callback with correct argument', () => {
expect(rowClassesCallBack.firstCall.calledWith(data[0], 0)).toBeTruthy();
expect(rowClassesCallBack.secondCall.calledWith(data[1], 1)).toBeTruthy();
});
it('should rendering Row component with correct className', () => {
const rows = wrapper.find(Row);
rows.forEach((row) => {
expect(row.props().className).toEqual(rowClasses);
});
});
});
describe('when selectRow.classes is defined', () => {
const selectedRowKey = data[0][keyField];
const selectedRowKeys = [selectedRowKey];
const selectedClasses = 'selected-classes';
const selectRow = { mode: 'radio', classes: selectedClasses };
beforeEach(() => {
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
keyField="id"
columns={ columns }
data={ data }
rowClasses={ rowClasses }
selectRow={ selectRow }
selectedRowKeys={ selectedRowKeys }
/>);
});
it('should rendering selected Row component with mixing selectRow.classes correctly', () => {
const selectedRow = wrapper.find(Row).get(0);
expect(selectedRow.props.className).toBe(`${rowClasses} ${selectedClasses}`);
});
});
});
describe('when rowEvents prop is defined', () => {
const rowEvents = { onClick: sinon.stub() };
describe('and it is a string', () => {
beforeEach(() => {
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
keyField="id"
columns={ columns }
data={ data }
rowEvents={ rowEvents }
/>);
});
it('should rendering Row component with correct attrs prop', () => {
const rows = wrapper.find(Row);
rows.forEach((row) => {
expect(row.props().attrs).toEqual(rowEvents);
});
});
});
});
describe('when cellEdit.nonEditableRows props is defined', () => {
const nonEditableRows = [data[1].id];
const cellEdit = {
mode: Const.CLICK_TO_CELL_EDIT,
nonEditableRows
};
beforeEach(() => {
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
data={ data }
columns={ columns }
keyField={ keyField }
cellEdit={ cellEdit }
/>
);
});
it('should render Row component with correct editable prop', () => {
expect(wrapper.length).toBe(1);
const rows = wrapper.find(Row);
for (let i = 0; i < rows.length; i += 1) {
if (nonEditableRows.indexOf(rows.get(i).props.row[keyField]) > -1) {
expect(rows.get(i).props.editable).toBeFalsy();
} else {
expect(rows.get(i).props.editable).toBeTruthy();
}
}
});
});
describe('when selectRow.mode is checkbox or radio (row was selectable)', () => {
const selectRow = { mode: 'checkbox' };
const selectedRowKey = data[0][keyField];
const selectedRowKeys = [selectedRowKey];
beforeEach(() => {
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
data={ data }
columns={ columns }
keyField={ keyField }
selectedRowKeys={ selectedRowKeys }
selectRow={ selectRow }
/>
);
});
it('should render Row component with correct selected prop', () => {
const rows = wrapper.find(Row);
for (let i = 0; i < rows.length; i += 1) {
const row = rows.get(i);
expect(row.props.selected).toBe(selectedRowKeys.indexOf(row.props.row[keyField]) > -1);
}
});
describe('if selectRow.style is defined as an object', () => {
const style = { backgroundColor: 'red' };
beforeEach(() => {
selectRow.style = style;
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
data={ data }
columns={ columns }
keyField={ keyField }
selectedRowKeys={ selectedRowKeys }
selectRow={ selectRow }
/>
);
});
it('should render Row component with correct style prop', () => {
expect(JSON.stringify(wrapper.find(Row).get(0).props.style)).toBe(JSON.stringify(style));
});
});
describe('if selectRow.style is defined as a function', () => {
const style = { backgroundColor: 'red' };
const styleCallBack = sinon.stub().returns(style);
beforeEach(() => {
selectRow.style = styleCallBack;
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
data={ data }
columns={ columns }
keyField={ keyField }
selectedRowKeys={ selectedRowKeys }
selectRow={ selectRow }
/>
);
});
it('should calling style callback correctly', () => {
expect(styleCallBack.callCount).toBe(1);
expect(styleCallBack.calledWith(data[0]), 1);
});
it('should render Row component with correct style prop', () => {
expect(JSON.stringify(wrapper.find(Row).get(0).props.style)).toBe(JSON.stringify(style));
});
});
describe('if selectRow.classes is defined as a string', () => {
const className = 'custom-class';
beforeEach(() => {
selectRow.classes = className;
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
data={ data }
columns={ columns }
keyField={ keyField }
selectedRowKeys={ selectedRowKeys }
selectRow={ selectRow }
/>
);
});
it('should render Row component with correct className prop', () => {
expect(wrapper.find(Row).get(0).props.className).toEqual(className);
});
});
describe('if selectRow.classes is defined as a function', () => {
const className = 'custom-class';
const classesCallBack = sinon.stub().returns(className);
beforeEach(() => {
selectRow.classes = classesCallBack;
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
data={ data }
columns={ columns }
keyField={ keyField }
selectedRowKeys={ selectedRowKeys }
selectRow={ selectRow }
/>
);
});
it('should calling style callback correctly', () => {
expect(classesCallBack.callCount).toBe(1);
expect(classesCallBack.calledWith(data[0]), 1);
});
it('should render Row component with correct style prop', () => {
expect(wrapper.find(Row).get(0).props.className).toEqual(className);
});
});
describe('if selectRow.bgColor is defined as a string', () => {
const bgColor = 'red';
beforeEach(() => {
selectRow.bgColor = bgColor;
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
data={ data }
columns={ columns }
keyField={ keyField }
selectedRowKeys={ selectedRowKeys }
selectRow={ selectRow }
/>
);
});
it('should render Row component with correct style.backgroundColor prop', () => {
expect(wrapper.find(Row).get(0).props.style).toEqual({ backgroundColor: bgColor });
});
});
describe('if selectRow.bgColor is defined as a string', () => {
const bgColor = 'red';
const bgColorCallBack = sinon.stub().returns(bgColor);
beforeEach(() => {
selectRow.bgColor = bgColorCallBack;
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
data={ data }
columns={ columns }
keyField={ keyField }
selectedRowKeys={ selectedRowKeys }
selectRow={ selectRow }
/>
);
});
it('should calling selectRow.bgColor callback correctly', () => {
expect(bgColorCallBack.calledOnce).toBeTruthy();
expect(bgColorCallBack.calledWith(data[0]), 1).toBeTruthy();
});
it('should render Row component with correct style.backgroundColor prop', () => {
expect(wrapper.find(Row).get(0).props.style).toEqual({ backgroundColor: bgColor });
});
});
describe('if selectRow.bgColor defined and selectRow.style.backgroundColor defined', () => {
const bgColor = 'yellow';
const style = { backgroundColor: 'red' };
beforeEach(() => {
selectRow.style = style;
selectRow.bgColor = bgColor;
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
data={ data }
columns={ columns }
keyField={ keyField }
selectedRowKeys={ selectedRowKeys }
selectRow={ selectRow }
/>
);
});
it('should take selectRow.bgColor as higher priority', () => {
expect(wrapper.find(Row).get(0).props.style.backgroundColor).toBe(bgColor);
});
});
describe('if selectRow.nonSelectable is defined', () => {
const nonSelectableRowIndex = 1;
const nonSelectable = [data[nonSelectableRowIndex][keyField]];
beforeEach(() => {
selectRow.nonSelectable = nonSelectable;
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
data={ data }
columns={ columns }
keyField={ keyField }
selectedRowKeys={ selectedRowKeys }
selectRow={ selectRow }
/>
);
});
it('should render Row component with correct selectable prop', () => {
expect(wrapper.find(Row).get(0).props.selectable).toBeTruthy();
expect(wrapper.find(Row).get(nonSelectableRowIndex).props.selectable).toBeFalsy();
});
});
});
describe('when selectRow.mode is ROW_SELECT_DISABLED (row was un-selectable)', () => {
beforeEach(() => {
wrapper = shallow(
<Body
{ ...mockBodyResolvedProps }
data={ data }
columns={ columns }
keyField={ keyField }
selectedRowKeys={ [] }
/>
);
});
it('prop selected should be null', () => {
expect(wrapper.find(Row).get(0).props.selected).toBeNull();
});
});
});
| 30.559561 | 111 | 0.53875 |
ea62cbea04125732af38e9c0dc218fd4b6dbad1f | 5,566 | js | JavaScript | tornjak-frontend/src/components/work-load-attestor-modal.js | mrsabath/tornjak-1 | 9db5336c39331abfc8a1db3db1d200832e145642 | [
"Apache-2.0"
] | 28 | 2021-08-23T18:50:02.000Z | 2022-03-20T08:21:05.000Z | tornjak-frontend/src/components/work-load-attestor-modal.js | mrsabath/tornjak-1 | 9db5336c39331abfc8a1db3db1d200832e145642 | [
"Apache-2.0"
] | 61 | 2021-02-24T15:04:45.000Z | 2021-08-18T21:07:05.000Z | tornjak-frontend/src/components/work-load-attestor-modal.js | mrsabath/tornjak-1 | 9db5336c39331abfc8a1db3db1d200832e145642 | [
"Apache-2.0"
] | 9 | 2021-08-23T19:19:03.000Z | 2022-03-13T04:01:54.000Z | import React from "react";
import { ModalWrapper, Dropdown, TextArea } from "carbon-components-react";
import { connect } from 'react-redux';
import IsManager from './is_manager';
import TornjakApi from './tornjak-api-helpers';
import {
agentsListUpdateFunc,
agentworkloadSelectorInfoFunc,
} from 'redux/actions';
class WorkLoadAttestor extends React.Component {
constructor(props) {
super(props);
this.TornjakApi = new TornjakApi();
this.state = {
workloadPlugin: "",
selectorsList: "",
selectors: "",
wLoadAttdata: [{}],
agentId: "",
agentSpiffeId: "",
};
this.onChangeWorkloadPlugin = this.onChangeWorkloadPlugin.bind(this);
this.prepareAgentData = this.prepareAgentData.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
this.prepareAgentData();
// if (IsManager) {
// this.TornjakApi.refreshSelectorsState(this.props.globalServerSelected, this.props.agentworkloadSelectorInfoFunc);
// }
// else {
// this.TornjakApi.refreshLocalSelectorsState(this.props.agentworkloadSelectorInfoFunc, this.props.globalServerSelected);
// }
}
componentDidUpdate(prevProps, prevState) {
if(prevProps !== this.props) {
this.prepareAgentData();
}
}
prepareAgentData() {
const { spiffeid } = this.props;
this.setState({
agentSpiffeId: spiffeid,
})
}
handleSubmit = () => {
var wLoadAttdata = {
"spiffeid": this.state.agentSpiffeId,
"plugin": this.state.workloadPlugin,
};
if (IsManager) {
this.TornjakApi.registerSelectors(this.props.globalServerSelected, wLoadAttdata, this.TornjakApi.refreshSelectorsState, this.props.agentworkloadSelectorInfoFunc);
this.TornjakApi.refreshSelectorsState(this.props.globalServerSelected, this.props.agentworkloadSelectorInfoFunc);
} else {
this.TornjakApi.registerLocalSelectors(wLoadAttdata, this.TornjakApi.refreshLocalSelectorsState, this.props.agentworkloadSelectorInfoFunc);
this.TornjakApi.refreshLocalSelectorsState(this.props.agentworkloadSelectorInfoFunc, this.props.globalServerSelected);
}
return true;
};
onChangeWorkloadPlugin = selected => {
var selectors = "";
var sid = selected.selectedItem.label;
var selectorsObject = this.props.globalWorkloadSelectorInfo[sid];
for (let i = 0; i < selectorsObject.length; i++) {
if (i !== sid.length - 1) {
selectors = selectors + selectorsObject[i].label + ":\n";
}
else {
selectors = selectors + selectorsObject[i].label + ":"
}
}
this.setState({
workloadPlugin: sid,
selectorsList: selectors,
})
}
render() {
//TODO: dynamically populated pluginlist
const PluginList =
[
{
id: "1",
label: "Docker",
},
{
id: "2",
label: "Kubernetes",
},
{
id: "3",
label: "Unix",
},
];
return (
<div>
<ModalWrapper
triggerButtonKind="ghost"
buttonTriggerText="Add/ Edit WorkLoad Attestor"
primaryButtonText="Save & Add"
handleSubmit={this.handleSubmit}
shouldCloseAfterSubmit={true}
>
<p> Define WorkLoad Attestor Information: </p>
<br />
<div className="parentId-drop-down">
<Dropdown
ariaLabel="workload-attestor-kind-drop-down"
id="workload-attestor-kind-drop-down"
items={PluginList}
label="Select WorkLoad Attestor Plugin"
titleText="WorkLoad Attestor Plugin"
onChange={this.onChangeWorkloadPlugin}
/>
</div>
<div className="selectors-textArea">
<TextArea
cols={50}
helperText="i.e. docker:label:,..."
id="selectors-textArea"
invalidText="A valid value is required"
labelText="Workload Selectors"
placeholder="Select Workload Attestor Plugin from above and selectors will be populated here - Refer to Workload Attestor Plugin"
defaultValue={this.state.selectorsList}
rows={8}
disabled
/>
</div>
</ModalWrapper>
</div>
);
}
}
const mapStateToProps = (state) => ({
globalServerSelected: state.servers.globalServerSelected,
globalAgentsList: state.agents.globalAgentsList,
globalWorkloadSelectorInfo: state.servers.globalWorkloadSelectorInfo,
})
export default connect(
mapStateToProps,
{ agentsListUpdateFunc, agentworkloadSelectorInfoFunc }
)(WorkLoadAttestor)
| 37.106667 | 174 | 0.536292 |
ea63b317502c75a3ab2aaba0df99337ef0a40255 | 155 | js | JavaScript | commands/commands.js | ThomasEsseul/Shan-bot | 90e0c4a9c0d56ce924a7b36af7cef739a5f3cc22 | [
"Apache-2.0"
] | null | null | null | commands/commands.js | ThomasEsseul/Shan-bot | 90e0c4a9c0d56ce924a7b36af7cef739a5f3cc22 | [
"Apache-2.0"
] | null | null | null | commands/commands.js | ThomasEsseul/Shan-bot | 90e0c4a9c0d56ce924a7b36af7cef739a5f3cc22 | [
"Apache-2.0"
] | null | null | null | import { help } from './help.js'
import { prune } from './prune.js'
// Allow to enable or disable commands
export const activatedCommands = [help, prune]
| 25.833333 | 46 | 0.703226 |
ea6417513c1962adb3cd82f81f66cfec52de6327 | 1,108 | js | JavaScript | src/ui/Collapsible/Collapsible.stories.js | the-wing/components | fb6e8d4874597ac0d14f3aa969b3fde99d253cb1 | [
"MIT"
] | null | null | null | src/ui/Collapsible/Collapsible.stories.js | the-wing/components | fb6e8d4874597ac0d14f3aa969b3fde99d253cb1 | [
"MIT"
] | 2 | 2018-11-07T21:04:28.000Z | 2018-11-29T22:55:53.000Z | src/ui/Collapsible/Collapsible.stories.js | the-wing/components | fb6e8d4874597ac0d14f3aa969b3fde99d253cb1 | [
"MIT"
] | 1 | 2019-01-28T23:43:27.000Z | 2019-01-28T23:43:27.000Z | import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import Button from 'ui/Button/Button';
import Collapsible from 'ui/Collapsible/Collapsible';
storiesOf('UI/Collapsible', module)
.add('default', () => (
<Collapsible
onToggle={action('custom onToggle')}
trigger={({ toggle }) => <Button onClick={toggle}>Toggle the content</Button>}
>
{({ isOpen }) => {
if (!isOpen) return false;
return <div>I am hidden content sometimes.</div>;
}}
</Collapsible>
))
.add('hidden title on toggle open', () => (
<Collapsible
onToggle={action('custom onToggle')}
trigger={({ isOpen, toggle }) => {
if (isOpen) return false;
return <Button onClick={toggle}>Toggle the content</Button>;
}}
>
{({ isOpen, toggle }) => {
if (!isOpen) return false;
return (
<div>
You hid the original toggle button. <button onClick={toggle}>So click me.</button>
</div>
);
}}
</Collapsible>
));
| 27.7 | 94 | 0.574007 |
ea643233ebe34787ed9b56ba1086826a449aabb3 | 354 | js | JavaScript | rollup.config.js | asakura42/markwright | 7a390a21b2055076a00d4ec8be613e4bc04dc3fc | [
"MIT"
] | null | null | null | rollup.config.js | asakura42/markwright | 7a390a21b2055076a00d4ec8be613e4bc04dc3fc | [
"MIT"
] | 2 | 2022-02-14T12:44:35.000Z | 2022-02-27T17:05:05.000Z | rollup.config.js | asakura42/markwright | 7a390a21b2055076a00d4ec8be613e4bc04dc3fc | [
"MIT"
] | null | null | null | import typescript from 'rollup-plugin-typescript';
export default [
{
input: 'src/markwright/index.tsx',
external: [
'react',
'react-promise',
'simple-markdown',
'react-window',
'fast-deep-equal'
],
output: {
file: 'dist/markwright.js',
format: 'esm'
},
plugins: [typescript()]
}
];
| 17.7 | 50 | 0.553672 |
ea64ea66a8d96d9f3db01a43589c7f56ea489d45 | 1,265 | js | JavaScript | app/scripts/JSONParse.js | kosh89/eGamings-class | cf13a54b6fdaa8e707bae8c7cc9fb2999598fef7 | [
"MIT"
] | null | null | null | app/scripts/JSONParse.js | kosh89/eGamings-class | cf13a54b6fdaa8e707bae8c7cc9fb2999598fef7 | [
"MIT"
] | 1 | 2022-02-13T01:46:20.000Z | 2022-02-13T01:46:20.000Z | app/scripts/JSONParse.js | kosh89/eGamings-class | cf13a54b6fdaa8e707bae8c7cc9fb2999598fef7 | [
"MIT"
] | null | null | null | fetch('./games/games.json')
.then(function (resp) {
return resp.json();
})
.then(function (data) {
const games = data;
class JSONParse {
constructor(data) {
this.data = data;
}
showCatTags() {
const tags = new Set();
this.data.categories.forEach(category => {
category.Tags.forEach (tag => {
tags.add(tag);
});
});
return tags;
};
showCatOnTag(tag) {
return this.data.categories.filter(category => category.Tags.includes(tag)).map(category => category.Name.en);
};
showCatOnLang(lang) {
return this.data.categories.map(category => category.Name[lang]);
};
showGamesWithDemo() {
return this.data.games.filter(game => game.hasDemo).map(game => game);
}
showGamesOnMerchantId(id) {
return this.data.games.filter(game => game.MerchantID === id.toString()).map(game => game);
}
}
const myParse = new JSONParse(games);
console.log(myParse.showCatTags());
console.log(myParse.showCatOnTag('menu'));
console.log(myParse.showCatOnLang('uk'));
console.log(myParse.showGamesWithDemo());
console.log(myParse.showGamesOnMerchantId(959));
})
| 23.867925 | 118 | 0.586561 |
ea65642ed347e3a3633ae94ef1870c3f42405e8a | 3,439 | js | JavaScript | src/index.js | PatriotCodes/simply-fetch | 5b6cdb1f4b0ae5b42d337c3ce6171d727930af5f | [
"MIT"
] | null | null | null | src/index.js | PatriotCodes/simply-fetch | 5b6cdb1f4b0ae5b42d337c3ce6171d727930af5f | [
"MIT"
] | 1 | 2021-05-11T02:28:23.000Z | 2021-05-11T02:28:23.000Z | src/index.js | PatriotCodes/simply-fetch | 5b6cdb1f4b0ae5b42d337c3ce6171d727930af5f | [
"MIT"
] | null | null | null | function ExtendedFetch(route, options, method, config) {
this.config = config;
this.timeout = undefined;
this.exceedsTimeout = false;
const httpMethods = {
GET: { bodyLess: true },
HEAD: { bodyLess: true },
OPTIONS: { bodyLess: true },
DELETE: { bodyLess: true },
CONNECT: { bodyLess: true },
POST: { bodyLess: false },
PUT: { bodyLess: false },
PATCH: { bodyLess: false },
};
const buildRoute = function(route) {
return route[0] === '/'
? `${window.location.protocol}//${window.location.host}${route}`
: !new RegExp('^http').test(route)
? `${config.BASE_URL}${route}`
: route;
};
const buildOptions = function(method, { headers, body, ...options }) {
return {
method: method,
headers: {
...(config.TOKEN() && {
Authorization: `${config.AUTH_TYPE ? `${config.AUTH_TYPE} ` : ''}${config.TOKEN()}`,
}),
...(!httpMethods[method].bodyLess && {
'Content-Type':
headers && headers['Content-Type'] ? headers['Content-Type'] : 'application/json',
}),
...headers,
},
...(body && {
body:
headers &&
headers['Content-Type'] &&
!headers['Content-Type'].includes('application/json')
? body
: JSON.stringify(body),
}),
...options,
};
};
this.controller = new AbortController();
this.nativeFetch = window.fetch(
buildRoute(route),
buildOptions(method, { ...options, signal: this.controller.signal }),
);
this.then = function(callback) {
this.nativeFetch = new Promise((resolve, reject) => {
this.timeout = setTimeout(() => {
this.exceedsTimeout = true;
reject(new Error(`Timeout of ${this.config.TIMEOUT}ms exceeded`));
}, this.config.TIMEOUT);
this.nativeFetch
.then(response => {
clearTimeout(this.timeout);
if (!this.exceedsTimeout) {
if (!response.ok) {
reject(response);
} else {
resolve(callback(response));
}
}
})
.catch(error => {
if (error.name !== 'AbortError') {
reject(error);
}
});
});
return this;
};
this.catch = function(callback) {
this.nativeFetch = this.nativeFetch.catch(error => {
if (error.name !== 'AbortError') {
return callback(error);
}
});
return this;
};
this.finally = function(callback) {
this.nativeFetch = this.nativeFetch.finally(callback);
return this;
};
this.abort = function() {
clearTimeout(this.timeout);
this.controller.abort();
};
}
const fetchz = {
config: {
BASE_URL: '/',
TOKEN: () => undefined,
TIMEOUT: 5000,
AUTH_TYPE: '',
},
};
fetchz.get = function(route, options = {}) {
return new ExtendedFetch(route, options, 'GET', fetchz.config);
};
fetchz.post = function(route, options = {}) {
return new ExtendedFetch(route, options, 'POST', fetchz.config);
};
fetchz.put = function(route, options = {}) {
return new ExtendedFetch(route, options, 'PUT', fetchz.config);
};
fetchz.delete = function(route, options = {}) {
return new ExtendedFetch(route, options, 'DELETE', fetchz.config);
};
fetchz.patch = function(route, options = {}) {
return new ExtendedFetch(route, options, 'PATCH', fetchz.config);
};
export default fetchz;
| 26.05303 | 94 | 0.563536 |
ea661463639ef3dba13ba2f78d9763b05f5421b5 | 609 | js | JavaScript | Fundamentos/Intermediario/Destructuring/destructuring1.js | JoanPedro/Javascript | ad7bcd4e438a446aeb00539f95eba96e4c37add6 | [
"MIT"
] | 1 | 2020-04-07T17:46:26.000Z | 2020-04-07T17:46:26.000Z | Fundamentos/Intermediario/Destructuring/destructuring1.js | JoanPedro/Javascript | ad7bcd4e438a446aeb00539f95eba96e4c37add6 | [
"MIT"
] | null | null | null | Fundamentos/Intermediario/Destructuring/destructuring1.js | JoanPedro/Javascript | ad7bcd4e438a446aeb00539f95eba96e4c37add6 | [
"MIT"
] | null | null | null | // Novo recurso ES6
const pessoa = {
nome: 'Joan',
idade: 22,
endereco: {
logradouro: 'Rua Pais das Maravilhas',
numero: 15
}
}
console.log(typeof pessoa)
const receber = pessoa.endereco.logradouro
console.log(receber) // Notação Ponto
const { endereco: { logradouro } } = pessoa // Destructuring, Logradouro fica disponível -> Extraido do Objeto pessoa.
console.log(logradouro)
const { endereco: { numero: identificador }, nome: palavra } = pessoa // Destructuring, Numero -> Identificador
console.log(identificador, palavra) // || Nome -> Palavra disponíveis | 30.45 | 118 | 0.679803 |
ea66c3983a22a80663cf1db5860d6221df09b119 | 271 | js | JavaScript | ast/xml.js | ldthomas/apg-js2-examples | 61a36fd963ba544c0630a533c053f60d18d878d2 | [
"BSD-3-Clause"
] | 8 | 2016-01-17T16:08:28.000Z | 2020-11-02T22:08:11.000Z | ast/xml.js | ldthomas/apg-js2-examples | 61a36fd963ba544c0630a533c053f60d18d878d2 | [
"BSD-3-Clause"
] | 1 | 2016-03-11T16:25:47.000Z | 2016-03-17T19:06:50.000Z | ast/xml.js | ldthomas/apg-js2-examples | 61a36fd963ba544c0630a533c053f60d18d878d2 | [
"BSD-3-Clause"
] | 3 | 2017-11-05T06:24:42.000Z | 2021-01-07T03:40:04.000Z | // Parse the input string and get the `AST` object.
var setup = require("./setup.js");
var ast = setup();
// Convert the `AST` to `XML` format and display it on the console.
var xml = ast.toXml();
console.log();
console.log("test: display AST in XML");
console.log(xml);
| 30.111111 | 67 | 0.678967 |
ea676091266fa073785d176ee14a0a959984910e | 1,304 | js | JavaScript | dev_resource/component/input.js | BrickCarvingArtist/www | a5cc0a6b32b798806a373ac391d6a1a6299273c0 | [
"MIT"
] | null | null | null | dev_resource/component/input.js | BrickCarvingArtist/www | a5cc0a6b32b798806a373ac391d6a1a6299273c0 | [
"MIT"
] | null | null | null | dev_resource/component/input.js | BrickCarvingArtist/www | a5cc0a6b32b798806a373ac391d6a1a6299273c0 | [
"MIT"
] | null | null | null | import React, {Component} from "react";
import Validate from "./validate";
export default class InputRow extends Component{
constructor(props){
super(props);
this.state = props;
this.validate = e => {
let state = this.state,
validate = state.validate,
option = state.option;
if(validate){
let message = Validate.validate(option.id, option.label, e.target.value, option.validate);
validate(option.id, message);
}
};
this.handleSubmit = e => {
e.keyCode === 13 && this.state.form && this.state.form.handleSubmit();
};
}
componentWillReceiveProps(nextProps){
this.setState(nextProps);
}
render(){
let state = this.state,
option = state.option;
return (
<div className={`row ${option.rowBorder ? "border" : "normal"}`}>
<label htmlFor={option.id}>
{`${option.label}`}
</label>
<input
id={option.id}
className={`ipt-txt${state.value || state.value === null ? " disabled" : ""}`}
type={option.type}
placeholder={`请输入${option.label}`}
maxLength={option.maxlength}
readOnly={option.readOnly}
value={state.value}
onChange={this.validate}
onBlur={this.validate}
onKeyDown={this.handleSubmit}
ref="ipt" />
{
option.unit ? <em>{option.unit}</em> : []
}
</div>
);
}
}; | 26.612245 | 94 | 0.621933 |
ea682ec2416462080a4643b9024509d56e522fe9 | 121 | js | JavaScript | node_modules/syncml-js/test/lib/wrapper/elementtree/treebuilder.js | mahamaha1/dev-days | 4f147f2440cdbc2c4305c48e463331abdbaa8ce3 | [
"Apache-2.0"
] | 1 | 2018-10-24T08:15:35.000Z | 2018-10-24T08:15:35.000Z | node_modules/syncml-js/test/lib/wrapper/elementtree/treebuilder.js | mahamaha1/dev-days | 4f147f2440cdbc2c4305c48e463331abdbaa8ce3 | [
"Apache-2.0"
] | null | null | null | node_modules/syncml-js/test/lib/wrapper/elementtree/treebuilder.js | mahamaha1/dev-days | 4f147f2440cdbc2c4305c48e463331abdbaa8ce3 | [
"Apache-2.0"
] | null | null | null | define(['../../node_modules/elementtree/lib/treebuilder'], function() {
return {TreeBuilder: exports.TreeBuilder};
});
| 30.25 | 71 | 0.710744 |
ea6837eae50386e9a69cbd65f655c055d29f93bb | 7,705 | js | JavaScript | smart-contract-auditing-and-security/discount-forward-transaction-space/truffle/test/inProtocolDemo.js | BlackSwine/compendium | 8ca631d79605c4e34ef2cec1dc5a469ab7639623 | [
"BSD-3-Clause-Clear",
"Unlicense"
] | null | null | null | smart-contract-auditing-and-security/discount-forward-transaction-space/truffle/test/inProtocolDemo.js | BlackSwine/compendium | 8ca631d79605c4e34ef2cec1dc5a469ab7639623 | [
"BSD-3-Clause-Clear",
"Unlicense"
] | null | null | null | smart-contract-auditing-and-security/discount-forward-transaction-space/truffle/test/inProtocolDemo.js | BlackSwine/compendium | 8ca631d79605c4e34ef2cec1dc5a469ab7639623 | [
"BSD-3-Clause-Clear",
"Unlicense"
] | 1 | 2021-04-14T17:12:14.000Z | 2021-04-14T17:12:14.000Z | require('truffle-test-utils').init();
var ProtocolGasFuturesArtifact = artifacts.require("ProtocolGasFutures");
var ProtocolGasFuturesTokenArtifact = artifacts.require("ProtocolGasFuturesToken");
var DexArtifact = artifacts.require("Dex");
var Utils = require('./Utils')(DexArtifact);
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
contract('In Protocol', function(accounts) {
let web3 = ProtocolGasFuturesArtifact.web3;
try {
web3.personal.importRawKey("1111111111111111111111111110111111111111111111111111111111111110", "password");
}
catch(e) {}
try {
web3.personal.importRawKey("1111111111111111111111110111111111111111111111111111111111111100", "password1");
}
catch(e) {}
try {
web3.personal.importRawKey("1111111111011111111111111111111111111111111111111111111111111000", "password2");
}
catch(e) {}
try {
web3.personal.importRawKey("1100111111111111111111111110111111111111111111111111111111111110", "password");
}
catch(e) {}
console.log(web3.eth.accounts);
web3.personal.unlockAccount("0xe035e5542e113f144286847c7b97a1da110df49f", "password");
web3.personal.unlockAccount("0xd9ea12a4b2fd5ea63f73f4e1eddcbfd0aad41638", "password1");
web3.personal.unlockAccount("0xa8b1d1c085f807b3b07c86f809ae5cf05e24093b", "password2");
web3.personal.unlockAccount("0x90f6e4681c51ac40223d39d7092c5cf1ac8ec0ee", "password");
let dexAdmin = "0xe035e5542e113f144286847c7b97a1da110df49f";
let miner = web3.eth.coinbase;
let bidder1 = "0xd9ea12a4b2fd5ea63f73f4e1eddcbfd0aad41638";
let bidder2 = "0xa8b1d1c085f807b3b07c86f809ae5cf05e24093b";
let bidder3 = "0x90f6e4681c51ac40223d39d7092c5cf1ac8ec0ee";
let gasFutureIds = [];
let fiveETH = Number(web3.toWei(5,'ether'));
web3.eth.sendTransaction({ from: miner, to: dexAdmin, value: fiveETH * 10 });
web3.eth.sendTransaction({ from: miner, to: bidder1, value: fiveETH * 10 });
web3.eth.sendTransaction({ from: miner, to: bidder2, value: fiveETH * 10 });
web3.eth.sendTransaction({ from: miner, to: bidder3, value: fiveETH * 10 });
wait(10000);
it('DEX admin should be able to add token to DEX', async() => {
let dex = await DexArtifact.deployed();
let token = await ProtocolGasFuturesTokenArtifact.deployed();
let tokenName = await token.name.call();
let exists = await dex.checkToken.call(tokenName);
if(!exists){
Utils.log(tokenName + " doesn't exist in DEX");
Utils.log("Adding " + tokenName + " to DEX " + dex.address);
Utils.log(token.address);
//let setadmin = await dex.admin.call();
//Utils.log("Admin " + setadmin);
let addTx = await dex.addNFToken(token.address, tokenName, { from: dexAdmin });
let id = await token.totalSupply.call();
}
});
it('miner should be able to issue gas future', async () => {
let dex = await DexArtifact.deployed();
let protocolInstance = await ProtocolGasFuturesArtifact.deployed();
let token = await ProtocolGasFuturesTokenArtifact.deployed();
Utils.log("Protocol deployed at " + protocolInstance.address);
let tokenName = await token.name.call();
let issueTx = await protocolInstance.issue({ from: miner });
console.log("ISSUE");
console.log(issueTx);
//let issueTx = await web3.eth.sendTransaction({from: miner, to: protocolInstance.address, gas: 2000000, gasPrice: 0});
assert(issueTx.logs.length > 0);
var expected = [];
for(var i = 0; i < issueTx.logs.length; i++){
if(issueTx.logs[i].event == 'CreatedGasFuture'){
var tokenId = issueTx.logs[i].args.id;
gasFutureIds.push(tokenId);
expected.push({
'event': 'CreatedGasFuture',
'args': {
'id': tokenId.toNumber()
}
});
}
}
assert.web3Events(issueTx, expected);
// let owner = await token.ownerOf.call(gasFutureIds);
// Utils.log(owner);
// Utils.log("Created gas future (id=" + gasFutureId + ")");
});
it('bidder should be able to submit bids', async () => {
let dex = await DexArtifact.deployed();
let token = await ProtocolGasFuturesTokenArtifact.deployed();
let tokenName = await token.name.call();
let deposit1 = await dex.depositEther({ from: bidder1, value: fiveETH });
assert.web3Event(deposit1, {
'event': 'Deposit',
'args': {
'symbolName': 'ETH',
'user': bidder1,
'value': fiveETH,
'balance': fiveETH
}
});
let deposit2 = await dex.depositEther({ from: bidder2, value: fiveETH });
assert.web3Event(deposit2, {
'event': 'Deposit',
'args': {
'symbolName': 'ETH',
'user': bidder2,
'value': fiveETH,
'balance': fiveETH
}
});
let deposit3 = await dex.depositEther({ from: bidder3, value: fiveETH });
assert.web3Event(deposit3, {
'event': 'Deposit',
'args': {
'symbolName': 'ETH',
'user': bidder3,
'value': fiveETH,
'balance': fiveETH
}
});
for(var i = 0; i < gasFutureIds.length; i++){
let bid1 = await dex.bidOrderERC721(tokenName, 'ETH', gasFutureIds[i], 10, 0x0, { from: bidder1 });
assert.web3Event(bid1, {
'event': 'NewOrder',
'args': {
'tokenA': tokenName,
'tokenB': 'ETH',
'orderType': 'Bid',
'volume': gasFutureIds[i].toNumber(),
'price': 10
}
});
let bid2 = await dex.bidOrderERC721(tokenName, 'ETH', gasFutureIds[i], 20, 0x1, { from: bidder2 });
assert.web3Event(bid2, {
'event': 'NewOrder',
'args': {
'tokenA': tokenName,
'tokenB': 'ETH',
'orderType': 'Bid',
'volume': gasFutureIds[i].toNumber(),
'price': 20
}
});
let bid3 = await dex.bidOrderERC721(tokenName, 'ETH', gasFutureIds[i], 30, 0x2, { from: bidder3 });
assert.web3Event(bid3, {
'event': 'NewOrder',
'args': {
'tokenA': tokenName,
'tokenB': 'ETH',
'orderType': 'Bid',
'volume': gasFutureIds[i].toNumber(),
'price': 30
}
});
}
});
it('dex should run auction', async () => {
wait(60000);
for(var i = 0; i < gasFutureIds.length; i++){
let protocolInstance = await ProtocolGasFuturesArtifact.deployed();
let dex = await DexArtifact.deployed();
let token = await ProtocolGasFuturesTokenArtifact.deployed();
let tokenName = await token.name.call();
let auctionTx = await protocolInstance.runAuction(gasFutureIds[i], { from: miner });
assert.web3Event(auctionTx, {
'event': 'AuctionResult',
'args': {
'id': gasFutureIds[i].toNumber(),
'price': 30
}
});
try{
let withdrawTx1 = await dex.withdrawalNFToken(tokenName, gasFutureIds[i], { from: bidder1 });
assert.fail('should not withdraw');
}catch(e){
}
let withdrawTx3 = await dex.withdrawalNFToken(tokenName, gasFutureIds[i], { from: bidder3 });
assert.web3Event(withdrawTx3, {
'event': 'Withdrawal',
'args': {
'symbolName': tokenName,
'user': bidder3,
'value': gasFutureIds[i].toNumber(),
'balance': 1,
}
});
}
});
});
| 33.354978 | 124 | 0.598053 |
ea6870c9578b8cbe75e82e98faa2b6fd05143b32 | 802 | js | JavaScript | src/Book.test.js | edhzsz/reactnd-myreads | 0bf81056e436fec2772a33607b907e4109dfd401 | [
"MIT"
] | null | null | null | src/Book.test.js | edhzsz/reactnd-myreads | 0bf81056e436fec2772a33607b907e4109dfd401 | [
"MIT"
] | null | null | null | src/Book.test.js | edhzsz/reactnd-myreads | 0bf81056e436fec2772a33607b907e4109dfd401 | [
"MIT"
] | null | null | null | import React from 'react';
import ReactDOM from 'react-dom';
import Book from './Book.js';
import renderer from 'react-test-renderer';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
describe('Component: Book', () => {
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<Book />, div);
});
it('should match its empty snapshot', () => {
const tree = toJson(shallow(
<Book />
));
expect(tree).toMatchSnapshot();
});
it('should render the props', () => {
const book = { title:"Test Name", authors:["test author 1", "test author 2"], imageLinks: { thumbnail: "test-url" } };
const tree = toJson(shallow(
<Book book={book} />
));
expect(tree).toMatchSnapshot();
});
}); | 25.870968 | 122 | 0.608479 |
ea694ffd012c2232d6df162adb95e5c1bf668e80 | 3,477 | js | JavaScript | src/components/HomePage/HomePage.js | forceofseth/QA-Tool | fc8452f0c5acf941a9a2e9ca3b5bce043faad64b | [
"MIT"
] | null | null | null | src/components/HomePage/HomePage.js | forceofseth/QA-Tool | fc8452f0c5acf941a9a2e9ca3b5bce043faad64b | [
"MIT"
] | 6 | 2021-03-09T17:14:16.000Z | 2022-02-18T09:44:33.000Z | src/components/HomePage/HomePage.js | forceofseth/QA-Tool | fc8452f0c5acf941a9a2e9ca3b5bce043faad64b | [
"MIT"
] | 2 | 2020-03-05T08:25:25.000Z | 2020-04-20T14:22:36.000Z | import React from 'react';
import {useAuthorizationRedirect} from "../../hooks/useAuthorizationRedirect";
import {ADD_CASE} from "../../constants/routes";
import {Link} from "react-router-dom";
import Container from "@material-ui/core/Container";
import AddCircleOutlineOutlinedIcon from '@material-ui/icons/AddCircleOutlineOutlined';
import './HomePage.css';
import '../global.css';
import SimpleSnackbarContainer from "../Ui/Snackbar/SimpleSnackbarContainer";
import ExpansionPanel from "@material-ui/core/ExpansionPanel";
import ExpansionPanelSummary from "@material-ui/core/ExpansionPanelSummary";
import ExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails";
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import Button from "@material-ui/core/Button";
import HomeTableHeader from "../Ui/HomeTable/HomeTableHeader";
import HomeTableRow from "../Ui/HomeTable/HomeTableRow";
import Loading from "../Status/Loading";
const HomePage = (props) => {
useAuthorizationRedirect(props.auth);
const sortedCases = props.cases && props.cases
//sorting the cases from newest to oldest
.sort((a, b) => {
return b.date.toDate() - a.date.toDate();
});
return (
sortedCases?
<Container maxWidth="lg" className="mainContainer">
<h1 className="title">Projects</h1>
<div className="addCase">
<Link to={ADD_CASE}>
<Button color="primary" variant="contained">
<span>Add Case</span>
<AddCircleOutlineOutlinedIcon className="addCaseIcon" fontSize="large"/>
</Button>
</Link>
</div>
<table>
<HomeTableHeader/>
<tbody>
{sortedCases && sortedCases
.filter(singleCase => singleCase.archived === false)
.map(singleCase => {
return (
<HomeTableRow key={singleCase.id} singleCase={singleCase}
updateCaseArchiveState={props.updateCaseArchiveState}/>
)
})}
</tbody>
</table>
<br/><br/>
<ExpansionPanel>
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon/>}
aria-controls="panel1a-content"
id="panel1a-header"
>
<h3>Archived Projects</h3>
</ExpansionPanelSummary>
<ExpansionPanelDetails>
<table>
<HomeTableHeader/>
<tbody>
{sortedCases && sortedCases
.filter(singleCase => singleCase.archived === true)
.map(singleCase => {
return (
<HomeTableRow key={singleCase.id} singleCase={singleCase}
updateCaseArchiveState={props.updateCaseArchiveState}/>
)
})}
</tbody>
</table>
</ExpansionPanelDetails>
</ExpansionPanel>
<SimpleSnackbarContainer/>
</Container>:<Loading/>
);
};
export default HomePage;
| 39.965517 | 105 | 0.526891 |
ea6b07407f1012d68017c611c11365b95463e064 | 642 | js | JavaScript | vehiclesMiddleware/vehiclesDelete.js | adrianncatalan/ApiRestNodeJs | 0b0bb14fbf2404b3f51272a10c8d7dc82291bf0e | [
"CC0-1.0"
] | null | null | null | vehiclesMiddleware/vehiclesDelete.js | adrianncatalan/ApiRestNodeJs | 0b0bb14fbf2404b3f51272a10c8d7dc82291bf0e | [
"CC0-1.0"
] | null | null | null | vehiclesMiddleware/vehiclesDelete.js | adrianncatalan/ApiRestNodeJs | 0b0bb14fbf2404b3f51272a10c8d7dc82291bf0e | [
"CC0-1.0"
] | null | null | null | //Creamos una función middleware para eliminar un vehículo filtrado por ID en la tabla registro_vehiculos de nuestra base de datos
const eliminar_vehiculo = (req, res, connection) => {
const { id } = req.params;
const result = req.body;
const sql = `DELETE FROM registro_vehiculos WHERE id_usuario = "${id}"`;
connection.query(sql, error => {
if (error) throw error;
// res.send('Vehículo eliminado exitosamente.');
res.json(result);
});
}
//Exportamos el bloque de código que permite eliminar un determinado vehículo filtrado por ID
module.exports.eliminar_vehiculo = eliminar_vehiculo; | 27.913043 | 131 | 0.697819 |
ea6b6f4b81fa4bad8436418d9562c62474457660 | 2,392 | js | JavaScript | superfields/src/main/resources/META-INF/resources/frontend/unload-observer.js | vaadin-miki/super-fields | 704428d99df0de0b1b3f04c6c62efa7fbbc0940c | [
"Apache-2.0"
] | 8 | 2020-06-04T16:16:52.000Z | 2021-12-05T14:59:14.000Z | superfields/src/main/resources/META-INF/resources/frontend/unload-observer.js | vaadin-miki/super-fields | 704428d99df0de0b1b3f04c6c62efa7fbbc0940c | [
"Apache-2.0"
] | 294 | 2020-04-07T14:07:29.000Z | 2022-03-31T21:29:48.000Z | superfields/src/main/resources/META-INF/resources/frontend/unload-observer.js | vaadin-miki/super-fields | 704428d99df0de0b1b3f04c6c62efa7fbbc0940c | [
"Apache-2.0"
] | 6 | 2020-07-01T09:25:16.000Z | 2021-04-23T10:36:09.000Z | import {html, PolymerElement} from '@polymer/polymer/polymer-element.js';
/**
* A web component that listens to {@code beforeunload} events and sends them to server-side.
* This requires Flow and a corresponding server-side Java component to work properly.
* Alternatively, make sure that this.$server.unloadAttempted() is available.
* Based on the code written by Kaspar Scherrer and Stuart Robinson: https://vaadin.com/forum/thread/17523194/unsaved-changes-detect-page-exit-or-reload
*/
export class UnloadObserver extends PolymerElement {
static get template() {
return html``;
}
static get is() {
return 'unload-observer';
}
/**
* Initialises the observer and registers a beforeunload listener.
*/
initObserver() {
const src = this;
if (window.Vaadin.unloadObserver === undefined) {
window.Vaadin.unloadObserver = {
attemptHandler: undefined
}
}
if (window.Vaadin.unloadObserver.attemptHandler !== undefined) {
window.removeEventListener('beforeunload', window.Vaadin.unloadObserver.attemptHandler);
}
window.Vaadin.unloadObserver.attemptHandler = event => src.unloadAttempted(src, event);
window.addEventListener('beforeunload', window.Vaadin.unloadObserver.attemptHandler);
}
/**
* Invoked in response to beforeunload browser event.
* @param source An unload observer.
* @param event Event that happened.
*/
unloadAttempted(source, event) {
if (window.Vaadin.unloadObserver.query) {
console.log("UO: responding to unload attempt...");
event.preventDefault();
event.returnValue = '';
if (source.$server) {
source.$server.unloadAttempted();
}
}
else source.$server.unloadHappened();
}
/**
* Controls whether or not prevent unload events.
* @param value When {@code truthy} (recommended String "true"), unload event will be prevented.
*/
queryOnUnload(value) {
if (value) {
window.Vaadin.unloadObserver.query = 'true';
}
else {
delete window.Vaadin.unloadObserver.query;
}
}
static get properties() {
return {
};
}
}
customElements.define(UnloadObserver.is, UnloadObserver);
| 32.767123 | 152 | 0.631689 |
ea6c61c8386458b5d4c9e8137074a6f5ce5d74ec | 570 | js | JavaScript | api/lib/BaseDocumentNotDuplicate.js | scientilla/scientilla | b3cce6edbfa28408715461d4d25a109acddf766b | [
"MIT"
] | 96 | 2015-02-20T21:48:49.000Z | 2022-03-25T13:02:32.000Z | api/lib/BaseDocumentNotDuplicate.js | scientilla/scientilla | b3cce6edbfa28408715461d4d25a109acddf766b | [
"MIT"
] | 33 | 2016-02-08T10:32:15.000Z | 2022-03-29T16:19:30.000Z | api/lib/BaseDocumentNotDuplicate.js | scientilla/scientilla | b3cce6edbfa28408715461d4d25a109acddf766b | [
"MIT"
] | 13 | 2015-06-10T12:36:56.000Z | 2020-03-04T10:11:39.000Z | /* global DocumentNotDuplicate, DocumentNotDuplicateGroup*/
module.exports = {
attributes: {
duplicate: {
model: 'document'
},
document: {
model: 'document'
}
},
async insert(doc1, doc2, researchEntity) {
const NotDuplicateModel = researchEntity.getDocumentNotDuplicateModel();
return await NotDuplicateModel.create({
document: Math.min(doc1.id, doc2.id),
duplicate: Math.max(doc1.id, doc2.id),
researchEntity: researchEntity
});
}
};
| 24.782609 | 80 | 0.580702 |
ea6ec6240ece81e7b8054f186684fdf36302d98a | 1,433 | js | JavaScript | stories/ListCard.stories.js | tomsoderlund/react-zeroconfig-components | 55c64ea890b99d29917e2ae46010796397095cf2 | [
"ISC"
] | 2 | 2021-04-12T21:26:56.000Z | 2021-12-30T18:52:27.000Z | stories/ListCard.stories.js | tomsoderlund/react-zeroconfig-components | 55c64ea890b99d29917e2ae46010796397095cf2 | [
"ISC"
] | 7 | 2020-09-16T16:03:27.000Z | 2021-12-05T13:56:44.000Z | stories/ListCard.stories.js | tomsoderlund/react-zeroconfig-components | 55c64ea890b99d29917e2ae46010796397095cf2 | [
"ISC"
] | null | null | null | import React from 'react'
// import { action } from '@storybook/addon-actions'
// import { linkTo } from '@storybook/addon-links' // linkTo('Button')
import ListCard from '../src/components/ListCard'
import '../src/components/ListCard.css'
import '../src/components/common.css'
// ----- Story -----
export default {
title: 'ListCard'
}
export const standard = () => {
return (
<div className='ListCardContainer' style={{ backgroundColor: 'lightgray', padding: '1em' }}>
<ListCard
name='Sam Lowry'
details='Main character'
imageUrl='https://pbs.twimg.com/profile_images/943955598718017536/XVuOSUzc_400x400.jpg'
>
<button>Edit</button>
<button>Delete</button>
</ListCard>
<ListCard
name='Jill Layton'
details='Main character'
imageUrl='https://miro.medium.com/max/800/1*KgS8OcADTJ7iv2zF1C3ZAw.jpeg'
>
<button>Edit</button>
<button>Delete</button>
</ListCard>
<ListCard
name='Mr. Kurtzmann'
details='Secondary character'
imageUrl='https://assets.mycast.io/characters/mr-kurtzman-1364907-normal.jpg'
>
<button>Edit</button>
<button>Delete</button>
</ListCard>
<ListCard
name='New item'
image={<button>Set image</button>}
>
<button>Edit</button>
<button>Delete</button>
</ListCard>
</div>
)
}
| 26.054545 | 96 | 0.605024 |
ea703443b7e097e5d1c98fb0c6ef9b1163d1f872 | 1,418 | js | JavaScript | backend/app/config/functions/bootstrap.js | asbah-amjad/huld-hub | 88199f742b820536dc1c8be834e910f1bc39ecae | [
"MIT"
] | 2 | 2022-01-24T07:02:16.000Z | 2022-02-21T08:19:06.000Z | backend/app/config/functions/bootstrap.js | asbah-amjad/huld-hub | 88199f742b820536dc1c8be834e910f1bc39ecae | [
"MIT"
] | 6 | 2022-02-14T19:21:21.000Z | 2022-03-08T23:39:44.000Z | backend/app/config/functions/bootstrap.js | asbah-amjad/huld-hub | 88199f742b820536dc1c8be834e910f1bc39ecae | [
"MIT"
] | null | null | null | "use strict";
/**
* An asynchronous bootstrap function that runs before
* your application gets started.
*
* This gives you an opportunity to set up your data model,
* run jobs, or perform some special logic.
*
* See more details here: https://strapi.io/documentation/developer-docs/latest/setup-deployment-guides/configurations.html#bootstrap
*/
const { permissionSetup } = require('./permissionSetup');
const { roleSetup } = require("./roleSetup");
const { userSetup } = require("./userSetup");
const { domainSetup } = require("./domainSetup");
const { defaultSettings } = require("./defaultSettings");
const { DEFAULT_ROLES, DEFAULT_USERS, DEFAULT_COMPETENCES, DEFAULT_SETTINGS, DEFAULT_PROFILES, DEFAULT_DOMAINS } = require("./defaultData");
const competenceSetup = require('./competenceSetup');
const profileSetup = require('./profileSetup');
module.exports = async () => {
await domainSetup(DEFAULT_DOMAINS);
await permissionSetup();
await roleSetup([DEFAULT_ROLES.ADMIN, DEFAULT_ROLES.EMPLOYEE, DEFAULT_ROLES.PUBLIC]);
await defaultSettings(DEFAULT_SETTINGS);
if (process.env.NODE_ENV !== 'test')
await competenceSetup(DEFAULT_COMPETENCES);
if (process.env.NODE_ENV === "development") {
try {
await userSetup(DEFAULT_USERS);
await profileSetup(DEFAULT_PROFILES);
} catch (e) {
console.error("Something went wrong in bootstraping", e);
}
}
};
| 32.976744 | 140 | 0.722144 |
ea7117384dbc27c1845ebb00dbb2b28ec5775d32 | 887 | js | JavaScript | backend/routes/admin.js | wog-js/wog | f424b61c73953fe6a0367c7d7a62f0a7b9f521fb | [
"MIT"
] | 4 | 2021-04-04T20:27:08.000Z | 2021-08-12T11:58:07.000Z | backend/routes/admin.js | wog-js/wog | f424b61c73953fe6a0367c7d7a62f0a7b9f521fb | [
"MIT"
] | 28 | 2018-07-01T04:11:31.000Z | 2020-07-31T18:03:25.000Z | backend/routes/admin.js | wog-js/wog | f424b61c73953fe6a0367c7d7a62f0a7b9f521fb | [
"MIT"
] | 1 | 2018-06-03T19:08:23.000Z | 2018-06-03T19:08:23.000Z | // Require modules
const { createController } = require('awilix-express');
const { bindFn } = require('@wogjs/utils');
const AdminController = require('../controllers/AdminController');
const { CreateUserValidator, UpdateUserValidator, DeleteUserValidator } = require('../validation/AdminValidators');
const checkAuth = require('../app/middleware/auth');
module.exports = createController(AdminController)
.prefix('/admin')
.before([ checkAuth.isAdmin ])
.post('/user/list', 'listUsers')
.put('/user/create', 'createUser', {
before: bindFn(new CreateUserValidator(), "validate")
})
.patch('/user/edit', 'editUser', {
before: bindFn(new UpdateUserValidator(), "validate")
})
.post('/user/delete', 'deleteUser', {
before: bindFn(new DeleteUserValidator(), "validate")
})
.post('/config/list', 'listConfig')
.post('/statistics/list', 'listStatistics');
| 35.48 | 115 | 0.694476 |
ea711b26834d47ede09ace6e1aa9bb985477897c | 1,219 | js | JavaScript | src/views/UserList/UserList.js | tungns-2145/hutect-conf | 7c3a17efccee61ebaa5ab9fa2d4439528b5760a2 | [
"MIT"
] | null | null | null | src/views/UserList/UserList.js | tungns-2145/hutect-conf | 7c3a17efccee61ebaa5ab9fa2d4439528b5760a2 | [
"MIT"
] | 3 | 2021-05-09T02:34:23.000Z | 2022-02-27T08:31:51.000Z | src/views/UserList/UserList.js | tungns-2145/hutect-conf | 7c3a17efccee61ebaa5ab9fa2d4439528b5760a2 | [
"MIT"
] | null | null | null | import React, { useState } from 'react';
import { makeStyles } from '@material-ui/styles';
import {
Grid
} from '@material-ui/core';
import { UsersTable } from './components';
import mockData from './data';
const useStyles = makeStyles(theme => ({
root: {
padding: theme.spacing(3)
},
content: {
marginTop: theme.spacing(2)
}
}));
const UserList = () => {
const classes = useStyles();
const [users] = useState(mockData);
const [search] = useState('');
let userList = users
let user = search.trim().toLowerCase();
if (user.length > 0) {
userList = users.filter(val => val.email.toLowerCase().match(user) || val.name.toLowerCase().match(user));
}
return (
<div className={classes.root}>
<Grid
item
lg={4}
md={6}
xl={4}
xs={12}
>
{/* <UsersToolbar onChange = {onChange}/> */}
</Grid>
<Grid
item
lg={8}
md={6}
xl={8}
xs={12}
>
<div className={classes.content}>
<UsersTable
users={userList}
/>
</div>
</Grid>
</div>
);
};
export default UserList;
| 20.661017 | 110 | 0.510254 |
ea72e1e09bb8db1eb44c8b1a7a6904c331d306fe | 201 | js | JavaScript | aula16/funcao04.js | andrefmuller/curso_javascript | fb237c72217e8e3cc9fbd55a49b0318e5c6c5eb5 | [
"MIT"
] | null | null | null | aula16/funcao04.js | andrefmuller/curso_javascript | fb237c72217e8e3cc9fbd55a49b0318e5c6c5eb5 | [
"MIT"
] | null | null | null | aula16/funcao04.js | andrefmuller/curso_javascript | fb237c72217e8e3cc9fbd55a49b0318e5c6c5eb5 | [
"MIT"
] | null | null | null | //Fatorial 5! = 5 x 4 x 3 x 2 x 1
function fatorial(n) {
var fat = 1
for(var c = n; c > 1; c-= 1) {
fat = fat * c
}
return fat
}
console.log(`O fatorial de 5 é ${fatorial(5)}.`) | 22.333333 | 48 | 0.507463 |
ea7426ef747601e5c8d43ebae0af55c4a1e69866 | 380 | js | JavaScript | HW8/Q2/JavaDoc/type-search-index.js | nevzatseferoglu/CSE222-DataStructure-Algorithm | 2a757af16dd3f82b0aed041a00989b2f638afdff | [
"MIT"
] | 1 | 2021-12-02T17:53:04.000Z | 2021-12-02T17:53:04.000Z | HW8/Q2/JavaDoc/type-search-index.js | nevzatseferoglu/cse222-coursework | 2a757af16dd3f82b0aed041a00989b2f638afdff | [
"MIT"
] | null | null | null | HW8/Q2/JavaDoc/type-search-index.js | nevzatseferoglu/cse222-coursework | 2a757af16dd3f82b0aed041a00989b2f638afdff | [
"MIT"
] | null | null | null | typeSearchIndex = [{"p":"edu.gtu","l":"AbstractGraph"},{"l":"All Classes","url":"allclasses-index.html"},{"p":"edu.gtu","l":"BreadthFirstSearch"},{"p":"edu.gtu","l":"DepthFirstSearch"},{"p":"edu.gtu","l":"Edge"},{"p":"edu.gtu","l":"Graph"},{"p":"edu.gtu","l":"GtuGraph"},{"p":"edu.gtu","l":"GtuGraph.GtuGraphIter"},{"p":"<Unnamed>","l":"Main"},{"p":"edu.gtu","l":"GtuGraph.Node"}] | 380 | 380 | 0.581579 |
ea776596193485e9a76d4386db5b328967e17699 | 402 | js | JavaScript | jsonp/440282.js | c-tsy/data_location | f7db57bf8cfec889b7d90f5d30b3a062490b2125 | [
"MIT"
] | null | null | null | jsonp/440282.js | c-tsy/data_location | f7db57bf8cfec889b7d90f5d30b3a062490b2125 | [
"MIT"
] | null | null | null | jsonp/440282.js | c-tsy/data_location | f7db57bf8cfec889b7d90f5d30b3a062490b2125 | [
"MIT"
] | null | null | null | if(_area_jsonp_440282){_area_jsonp_440282({"440282001":"雄州街道","440282100":"乌迳镇","440282103":"界址镇","440282104":"坪田镇","440282105":"黄坑镇","440282106":"邓坊镇","440282107":"油山镇","440282109":"南亩镇","440282110":"水口镇","440282111":"江头镇","440282112":"湖口镇","440282113":"珠玑镇","440282115":"主田镇","440282116":"古市镇","440282118":"全安镇","440282120":"百顺镇","440282121":"澜河镇","440282122":"帽子峰镇","440282400":"东莞大岭山(南雄)产业转移工业园"})} | 402 | 402 | 0.69403 |
ea77a9a4638aae1e8052ee2d0bd70e7f15e84a6c | 524 | js | JavaScript | src/BarChart.js | eltoque/eltoque.github.io | 3c7d2c49b36e6fcfa0dfcbd4de367cf6c7175cf4 | [
"MIT"
] | null | null | null | src/BarChart.js | eltoque/eltoque.github.io | 3c7d2c49b36e6fcfa0dfcbd4de367cf6c7175cf4 | [
"MIT"
] | 11 | 2020-07-07T19:31:24.000Z | 2022-03-25T18:31:58.000Z | src/BarChart.js | eltoque/eltoque.github.io | 3c7d2c49b36e6fcfa0dfcbd4de367cf6c7175cf4 | [
"MIT"
] | null | null | null | import {Bar, mixins} from 'vue-chartjs'
const {reactiveProp} = mixins
export default {
extends: Bar,
mixins: [reactiveProp],
name: "BarChart",
props: {
chartData: {
type: Object,
default: null
},
options: {
type: Object,
default: null
}
},
methods: {
renderBarChart: function () {
this.renderChart(this.chartData, this.options)
}
},
mounted() {
this.renderBarChart()
}
} | 19.407407 | 58 | 0.498092 |
ea77e56790594fad0e54410c80c9d2e834db7da0 | 1,372 | js | JavaScript | app/components/PokemonTypeList.js | TheFated/pokedex-salestock | 2fdf02c2f8592f1eca87bc31cb540a7855d58386 | [
"MIT"
] | 6 | 2018-10-03T19:32:20.000Z | 2022-03-04T12:49:46.000Z | app/components/PokemonTypeList.js | TheFated/pokedex-salestock | 2fdf02c2f8592f1eca87bc31cb540a7855d58386 | [
"MIT"
] | 4 | 2021-05-06T20:30:47.000Z | 2022-02-17T14:10:20.000Z | app/components/PokemonTypeList.js | TheFated/pokedex-salestock | 2fdf02c2f8592f1eca87bc31cb540a7855d58386 | [
"MIT"
] | 3 | 2020-04-09T11:58:57.000Z | 2022-02-03T16:30:54.000Z | /**
* Created by gilangaramadan on 18-12-17.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ButtonType from './ButtonType';
export default class PokemonTypeList extends Component {
static propTypes = {
getbytype: PropTypes.func,
};
static defaultProps = {
getbytype: () => {},
};
state = {
types: [],
fetched: false,
loading: true,
};
componentDidMount() {
this.getAllTypes();
}
getAllTypes() {
fetch(`${PokemonTypeList.API_URL}/type/`)
.then(d => d.json())
.then((response) => {
this.setState({
types: response.results,
loading: false,
fetched: true,
});
});
}
static API_URL = 'http://pokeapi.salestock.net/api/v2';
render() {
const { fetched, loading, types } = this.state;
let content;
if (fetched) {
content = types.map(type => (<ButtonType
key={type.name}
type={type.name}
onKeyDown={() => {}}
onClick={() => this.props.getbytype(type.name)}
/>));
} else if (loading && !fetched) {
content = <div className="spinner"><div className="double-bounce1" /><div className="double-bounce2" /></div>;
} else {
content = <div />;
}
return (
<div className="row center-xs">
{content}
</div>
);
}
}
| 21.107692 | 116 | 0.553936 |
ea78464b1deac812b64a9334ef3508a2652803f2 | 4,692 | js | JavaScript | lib/views/Planet.js | xaroth8088/react-planet | d959deb265387a7b5d589e16ea9484ff9aa9d80b | [
"MIT"
] | 3 | 2018-09-08T13:49:07.000Z | 2022-03-05T23:41:32.000Z | lib/views/Planet.js | xaroth8088/react-planet | d959deb265387a7b5d589e16ea9484ff9aa9d80b | [
"MIT"
] | 24 | 2020-09-04T20:44:52.000Z | 2022-02-26T10:38:23.000Z | lib/views/Planet.js | xaroth8088/react-planet | d959deb265387a7b5d589e16ea9484ff9aa9d80b | [
"MIT"
] | null | null | null | import * as PropTypes from 'prop-types';
import React, { useCallback } from 'react';
import Application from '../Application';
function Planet(props) {
let app;
// TODO: every time the props change, we're destroying and recreating the Application.
// TODO: if we can preserve it somehow, then we can try to kill the web workers every
// TODO: time the config changes (so that there's only ever the one running)
const canvasRef = useCallback((node) => {
if (node !== null) {
// Filter out null props
const newProps = Object.keys(props)
.filter(key => props[key] !== null)
.reduce(
(res, key) => {
res[key] = props[key];
return res;
}, {}
);
// Randomize any non-supplied seeds
const { surfaceSeed, landSeed, cloudSeed } = props;
if (surfaceSeed === null) {
newProps.surfaceSeed = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
}
if (landSeed === null) {
newProps.landSeed = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
}
if (cloudSeed === null) {
newProps.cloudSeed = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
}
// Start up the application
app = new Application(node, newProps);
app.init();
app.update();
} else {
app = null;
}
}, []);
// Any props that the library doesn't care about should be passed on to the containing div
const divProps = {};
Object.keys(props).forEach(
(key) => {
if (!(key in Planet.defaultProps)) {
divProps[key] = props[key];
}
}
);
return (
<div ref={canvasRef} {...divProps} />
);
}
// The properties required by the WebAssembly texture generator
const wasmProperties = {
resolution: null,
surfaceSeed: null,
surfaceiScale: null,
surfaceiOctaves: null,
surfaceiFalloff: null,
surfaceiIntensity: null,
surfaceiRidginess: null,
surfacesScale: null,
surfacesOctaves: null,
surfacesFalloff: null,
surfacesIntensity: null,
landSeed: null,
landColor1: null,
landColor2: null,
landiScale: null,
landiOctaves: null,
landiFalloff: null,
landiIntensity: null,
landiRidginess: null,
landsScale: null,
landsOctaves: null,
landsFalloff: null,
landsIntensity: null,
waterDeep: null,
waterShallow: null,
waterLevel: null,
waterSpecular: null,
waterFalloff: null,
cloudSeed: null,
cloudColor: null,
cloudOpacity: null,
cloudiScale: null,
cloudiOctaves: null,
cloudiFalloff: null,
cloudiIntensity: null,
cloudiRidginess: null,
cloudsScale: null,
cloudsOctaves: null,
cloudsFalloff: null,
cloudsIntensity: null
};
Planet.defaultProps = {
normalScale: 0.05,
animate: true,
...wasmProperties
};
Planet.propTypes = {
resolution: PropTypes.number,
surfaceSeed: PropTypes.number,
surfaceiScale: PropTypes.number,
surfaceiOctaves: PropTypes.number,
surfaceiFalloff: PropTypes.number,
surfaceiIntensity: PropTypes.number,
surfaceiRidginess: PropTypes.number,
surfacesScale: PropTypes.number,
surfacesOctaves: PropTypes.number,
surfacesFalloff: PropTypes.number,
surfacesIntensity: PropTypes.number,
landSeed: PropTypes.number,
landColor1: PropTypes.string,
landColor2: PropTypes.string,
landiScale: PropTypes.number,
landiOctaves: PropTypes.number,
landiFalloff: PropTypes.number,
landiIntensity: PropTypes.number,
landiRidginess: PropTypes.number,
landsScale: PropTypes.number,
landsOctaves: PropTypes.number,
landsFalloff: PropTypes.number,
landsIntensity: PropTypes.number,
waterDeep: PropTypes.string,
waterShallow: PropTypes.string,
waterLevel: PropTypes.number,
waterSpecular: PropTypes.number,
waterFalloff: PropTypes.number,
cloudSeed: PropTypes.number,
cloudColor: PropTypes.string,
cloudOpacity: PropTypes.number,
cloudiScale: PropTypes.number,
cloudiOctaves: PropTypes.number,
cloudiFalloff: PropTypes.number,
cloudiIntensity: PropTypes.number,
cloudiRidginess: PropTypes.number,
cloudsScale: PropTypes.number,
cloudsOctaves: PropTypes.number,
cloudsFalloff: PropTypes.number,
cloudsIntensity: PropTypes.number,
normalScale: PropTypes.number,
animate: PropTypes.bool
};
export default Planet;
| 28.26506 | 94 | 0.632353 |
ea792a6bc138c4d19c958a289a1f722176b87111 | 2,198 | js | JavaScript | tests/EventListener.spec.js | MaximDevoir/event-listener | 770ed263d59f24370d00a15026c422cd0629667d | [
"MIT"
] | null | null | null | tests/EventListener.spec.js | MaximDevoir/event-listener | 770ed263d59f24370d00a15026c422cd0629667d | [
"MIT"
] | 40 | 2019-10-21T19:59:25.000Z | 2021-07-26T13:18:39.000Z | tests/EventListener.spec.js | MaximDevoir/event-listener | 770ed263d59f24370d00a15026c422cd0629667d | [
"MIT"
] | null | null | null | import chai from 'chai'
import sinon from 'sinon'
import sinonChai from 'sinon-chai'
import EventListener from '../src/EventListener'
chai.should()
chai.use(sinonChai)
const { expect } = chai
describe('Event Listener', () => {
const trueop = () => true
const event = 'eventname'
const webElement = {
addEventListener: sinon.spy(),
removeEventListener: sinon.spy()
}
const fallbackElement = {
attachEvent: sinon.spy(),
detachEvent: sinon.spy()
}
const webAddSpy = webElement.addEventListener
const webRemoveSpy = webElement.removeEventListener
const fallbackAddSpy = fallbackElement.attachEvent
const fallbackRemoveSpy = fallbackElement.detachEvent
const useCapture = false
expect(trueop.call()).to.equal(true)
it('should be a object', () => {
(typeof EventListener).should.eql('function')
})
describe('.add()', () => {
it('should have .add() method', () => {
expect(EventListener).to.have.property('add')
})
it('should use addEventListener when available', () => {
EventListener.add(webElement, event, trueop, useCapture)
expect(webAddSpy.calledOnce).to.equal(true)
expect(webAddSpy.calledWithExactly(event, trueop, useCapture)).to.equal(true)
})
it('should fallback to .attachEvent() ', () => {
EventListener.add(fallbackElement, event, trueop)
expect(fallbackAddSpy.calledOnce).to.equal(true)
expect(fallbackAddSpy.calledWithExactly(`on${event}`, trueop)).to.equal(true)
})
})
describe('.remove()', () => {
it('should have .remove() method', () => {
expect(EventListener).to.have.property('remove')
})
it('should use removeEventListener when available', () => {
EventListener.remove(webElement, event, trueop, useCapture)
expect(webRemoveSpy.calledOnce).to.equal(true)
expect(webRemoveSpy.calledWithExactly(event, trueop, useCapture)).to.equal(true)
})
it('should fallback to .detachEvent() ', () => {
EventListener.remove(fallbackElement, event, trueop)
expect(fallbackRemoveSpy.calledOnce).to.equal(true)
expect(fallbackRemoveSpy.calledWithExactly(`on${event}`, trueop)).to.equal(true)
})
})
})
| 31.4 | 86 | 0.677889 |
ea793d85d53f03f2be37a42697126e2742086430 | 117 | js | JavaScript | demos/maps/effex-demo-markers/src/yourMapsApi.js | brucemcpherson/effex | 71670a42f125d9caf952f255e3ea9d5d13754b83 | [
"MIT"
] | 1 | 2017-03-17T08:38:46.000Z | 2017-03-17T08:38:46.000Z | demos/maps/effex-demo-markers/src/yourMapsApi.js | brucemcpherson/effex | 71670a42f125d9caf952f255e3ea9d5d13754b83 | [
"MIT"
] | null | null | null | demos/maps/effex-demo-markers/src/yourMapsApi.js | brucemcpherson/effex | 71670a42f125d9caf952f255e3ea9d5d13754b83 | [
"MIT"
] | null | null | null |
function getMapsApiKey () {
return 'AxxxxxxxxxxxxxxxxxU'; /// Put your Google maps api key here
}; | 29.25 | 85 | 0.623932 |
ea79525e2b6013d4a4fec5adb88c293828d9b009 | 1,329 | js | JavaScript | Client/raf-timer.js | ItsAlxl/depicture | 2534977658728cce92961b2033748786abcdb524 | [
"Unlicense"
] | 1 | 2020-10-11T00:18:07.000Z | 2020-10-11T00:18:07.000Z | Client/raf-timer.js | ItsAlxl/depicture | 2534977658728cce92961b2033748786abcdb524 | [
"Unlicense"
] | 1 | 2020-10-08T01:54:37.000Z | 2020-10-08T01:54:37.000Z | Client/raf-timer.js | ItsAlxl/depicture | 2534977658728cce92961b2033748786abcdb524 | [
"Unlicense"
] | 3 | 2020-10-08T00:21:20.000Z | 2020-10-29T15:15:39.000Z | class rAFCountdownTimer {
updateCallback;
finishCallback;
tsStart = null;
msDuration = 0;
msElapsed = 0;
cancelOnNextTick = false;
rAFid;
constructor(finishCallback, updateCallback = null) {
this.finishCallback = finishCallback;
this.updateCallback = updateCallback;
this.rAFCallback = this.rAFCallback.bind(this);
}
start() {
if (this.msDuration > 0) {
this.tsStart = null;
this.rAFid = requestAnimationFrame(this.rAFCallback);
}
}
rAFCallback(ts) {
if (this.tsStart == null) {
this.tsStart = ts;
}
this.msElapsed = ts - this.tsStart;
let msRemain = this.getMsRemaining();
if (this.updateCallback != null) {
this.updateCallback(msRemain);
}
if (msRemain <= 0) {
if (this.finishCallback != null) {
this.finishCallback();
}
} else {
if (this.cancelOnNextTick) {
this.cancelOnNextTick = false;
} else {
this.rAFid = requestAnimationFrame(this.rAFCallback);
}
}
}
cancel() {
this.cancelOnNextTick = true;
}
getMsRemaining() {
return this.msDuration - this.msElapsed;
}
} | 23.315789 | 69 | 0.536494 |
ea79ac94f1edd8b5630fc1c6aafa2f75761a4de0 | 334 | js | JavaScript | config/routes.js | Rawphs/sails-hook-authorization | 9b9618b6d433123262ac504b37ca152e2f13f621 | [
"MIT"
] | 15 | 2016-06-21T07:38:49.000Z | 2019-05-16T18:14:51.000Z | config/routes.js | Rawphs/sails-hook-authorization | 9b9618b6d433123262ac504b37ca152e2f13f621 | [
"MIT"
] | 15 | 2016-06-21T07:36:06.000Z | 2017-11-22T14:30:44.000Z | config/routes.js | Rawphs/sails-hook-authorization | 9b9618b6d433123262ac504b37ca152e2f13f621 | [
"MIT"
] | 16 | 2016-05-18T06:58:19.000Z | 2019-02-07T10:05:01.000Z | module.exports.routes = {
'POST /auth/login' : 'AuthController.login',
'POST /auth/signup' : 'AuthController.signup',
'GET /auth/verify-email/:token': 'AuthController.verifyEmail',
'GET /auth/me' : 'AuthController.me',
'POST /auth/refresh-token' : 'AuthController.refreshToken'
};
| 41.75 | 64 | 0.610778 |
ea7a816fa729cdb0f04c3dfbbe1dd5475a0163c5 | 7,917 | js | JavaScript | ui/src/js/pages/repository/shared/header/Header.js | gigabackup/gigantum-client | 70fe6b39b87b1c56351f2b4c551b6f1693813e4f | [
"MIT"
] | 60 | 2018-09-26T15:46:00.000Z | 2021-10-10T02:37:14.000Z | ui/src/js/pages/repository/shared/header/Header.js | gigabackup/gigantum-client | 70fe6b39b87b1c56351f2b4c551b6f1693813e4f | [
"MIT"
] | 1,706 | 2018-09-26T16:11:22.000Z | 2021-08-20T13:37:59.000Z | ui/src/js/pages/repository/shared/header/Header.js | griffinmilsap/gigantum-client | 70fe6b39b87b1c56351f2b4c551b6f1693813e4f | [
"MIT"
] | 11 | 2019-03-14T13:23:51.000Z | 2022-01-25T01:29:16.000Z | // vendor
import React, { Component } from 'react';
import classNames from 'classnames';
// store
import {
setSyncingState,
setPublishingState,
setExportingState,
setModalVisible,
} from 'JS/redux/actions/labbook/labbook';
import { setIsSyncing, setIsExporting } from 'JS/redux/actions/dataset/dataset';
// components
import ErrorBoundary from 'Components/errorBoundary/ErrorBoundary';
import TitleSection from './titleSection/TitleSection';
import ActionsSection from './actionsSection/ActionsSection';
import Branches from './branches/Branches';
import Container from './container/Container';
import Navigation from './navigation/Navigation';
// assets
import './Header.scss';
/**
@param {Object} branches
@return {Array}
*/
const getBranches = (props) => {
let branches = [];
if (props.branches) {
branches = props.branches;
} else {
const commitsBehind = (props.dataset && props.dataset.commitsBehind)
? props.dataset.commitsBehind
: 0;
const commitsAhead = (props.dataset && props.dataset.commitsAhead)
? props.dataset.commitsAhead
: 0;
branches = [{
branchName: 'master',
isActive: true,
commitsBehind,
commitsAhead,
}];
}
if (props.showMigrationButton) {
branches = branches.filter(({ branchName }) => branchName !== 'master');
}
return branches;
};
type Props = {
auth: Object,
branchName: string,
branchesOpen: string,
dataset: {
name: string,
owner: string,
},
diskLow: boolean,
isDeprecated: boolean,
isExporting: boolean,
isPublishing: boolean,
isSticky: boolean,
isSyncing: boolean,
isLocked: boolean,
isLockedSync: boolean,
labbook: {
name: string,
owner: string,
},
mergeFilter: boolean,
modalVisible: boolean,
sectionType: string,
setBranchUptodate: Function,
toggleBranchesView: Function,
};
class Header extends Component<Props> {
/** *******************
* child functions
*
******************** */
/**
@param {boolean} newIsExporting
updates container status state
updates labbook state
*/
_setExportingState = (newIsExporting) => {
const { sectionType, isExporting } = this.props;
const { owner, name } = this.props[sectionType];
if (isExporting !== newIsExporting) {
setExportingState(owner, name, newIsExporting);
}
if (sectionType === 'dataset') {
setIsExporting(owner, name, isExporting);
}
}
/**
@param {}
updates html element classlist and labbook state
*/
_showLabbookModal = () => {
const { props } = this;
const { owner, name } = props[props.sectionType];
if (!props.modalVisible) {
setModalVisible(owner, name, true);
}
}
/**
@param {}
updates html element classlist and labbook state
*/
_hideLabbookModal = () => {
const { props } = this;
const { owner, name } = props[props.sectionType];
// TODO remove document to add classname, should use react state and classnames
if (document.getElementById('labbookModal')) {
document.getElementById('labbookModal').classList.add('hidden');
}
if (document.getElementById('modal__cover')) {
document.getElementById('modal__cover').classList.add('hidden');
}
if (props.modalVisible) {
setModalVisible(owner, name, false);
}
}
/**
@param {boolean} isPublishing
updates container status state
updates labbook state
*/
_setPublishingState = (owner, name, isPublishing) => {
const { props } = this;
if ((props.isPublishing !== isPublishing)) {
setPublishingState(owner, name, isPublishing);
}
if (props.sectionType === 'dataset') {
setIsSyncing(owner, name, isPublishing);
}
}
/** *
@param {Node} element
checks if element is too large for card area
@return {boolean}
*/
_checkOverflow = (element) => {
if (element) {
const curOverflow = element.style.overflow;
if (!curOverflow || (curOverflow === 'visible')) {
element.style.overflow = 'hidden';
}
const isOverflowing = (element.clientWidth < element.scrollWidth)
|| (element.clientHeight < element.scrollHeight);
element.style.overflow = curOverflow;
return isOverflowing;
}
return null;
}
/** ***
* @param {boolean} isSyncing
* updates container status state
* updates labbook state
* @return {}
*/
_setSyncingState = (isSyncing) => {
const { props } = this;
const { owner, name } = props[props.sectionType];
if (props.isSyncing !== isSyncing) {
setSyncingState(owner, name, isSyncing);
}
if (props.sectionType === 'dataset') {
setIsSyncing(owner, name, isSyncing);
}
}
render() {
const {
labbook,
branchName,
dataset,
isSticky,
isDeprecated,
branchesOpen,
diskLow,
sectionType,
toggleBranchesView,
mergeFilter,
auth,
isLocked,
isLockedSync,
setBranchUptodate,
} = this.props;
const {
visibility,
description,
collaborators,
defaultRemote,
id,
} = labbook || dataset;
const section = labbook || dataset;
const isLabbookSection = sectionType === 'labbook';
const branches = getBranches(this.props);
// declare css here
const headerCSS = classNames({
Header: true,
'Header--sticky': isSticky,
'Header--disk-low': diskLow,
'Header--deprecated': isDeprecated,
'Header--branchesOpen': branchesOpen,
});
const branchesErrorCSS = classNames({
BranchesError: branchesOpen,
hidden: !branchesOpen,
});
return (
<div className="Header__wrapper">
<div className={headerCSS}>
<div className="Header__flex">
<div className="Header__columnContainer Header__columnContainer--flex-1">
<TitleSection
self={this}
{...this.props}
/>
<ErrorBoundary
type={branchesErrorCSS}
key="branches"
>
<Branches
{...this.props}
activeBranch={section.activeBranchName || 'master'}
auth={auth}
branches={branches}
branchesOpen={branchesOpen}
defaultRemote={section.defaultRemote}
isLocked={isLocked}
isLockedSync={isLockedSync}
isSticky={isSticky}
mergeFilter={mergeFilter}
section={section}
sectionId={section.id}
sectionType={sectionType}
setExportingState={this._setExportingState}
setBranchUptodate={setBranchUptodate}
setPublishingState={this._setPublishingState}
setSyncingState={this._setSyncingState}
toggleBranchesView={toggleBranchesView}
visibility={visibility}
/>
</ErrorBoundary>
</div>
<div className="Header__columnContainer Header__columnContainer--fixed-width">
<ActionsSection
visibility={visibility}
description={description}
collaborators={collaborators}
defaultRemote={defaultRemote}
labbookId={id}
remoteUrl={defaultRemote}
setSyncingState={this._setSyncingState}
setExportingState={this._setExportingState}
branchName={branchName}
isSticky={isSticky}
{...this.props}
/>
{ isLabbookSection
&& <Container {...this.props} />}
</div>
</div>
<Navigation {...this.props} />
</div>
</div>
);
}
}
export default Header;
| 26.128713 | 90 | 0.595933 |
ea7c1c68c94179f79a37ccc7db1a26dfa0d7747d | 281 | js | JavaScript | src/pages/projects.js | KyleKCarter/Learning-Gatsby | 804bc4cc8286739537e506bf7999c3498708a15f | [
"MIT"
] | null | null | null | src/pages/projects.js | KyleKCarter/Learning-Gatsby | 804bc4cc8286739537e506bf7999c3498708a15f | [
"MIT"
] | null | null | null | src/pages/projects.js | KyleKCarter/Learning-Gatsby | 804bc4cc8286739537e506bf7999c3498708a15f | [
"MIT"
] | null | null | null | import React from "react"
//components
import Layout from "../components/layout/layout"
const Projects = () => {
return (
<Layout>
<div>
<h1>My Projects</h1>
<p>Here are my recent projects</p>
</div>
</Layout>
)
}
export default Projects
| 15.611111 | 48 | 0.587189 |
ea7c84d1b05b35988789c34d6c61f9761da97e53 | 1,448 | js | JavaScript | src/map/js/components/LayerPanel/ReportLegend.js | wri/gfw-water | ef23589a0953c219336a2985a8b9cf3e314f1e1b | [
"MIT"
] | 2 | 2016-07-12T16:59:21.000Z | 2017-09-03T14:40:14.000Z | src/map/js/components/LayerPanel/ReportLegend.js | wri/gfw-water | ef23589a0953c219336a2985a8b9cf3e314f1e1b | [
"MIT"
] | 6 | 2015-12-31T18:35:07.000Z | 2016-08-24T17:00:49.000Z | src/map/js/components/LayerPanel/ReportLegend.js | wri/gfw-water | ef23589a0953c219336a2985a8b9cf3e314f1e1b | [
"MIT"
] | 3 | 2016-07-08T12:44:04.000Z | 2019-03-27T12:21:05.000Z | import React from 'react';
export default class ReportLegend extends React.Component {
render() {
return (
<div className='report-legend-inner'>
{this.props.title === 'Historical Forest Loss' ? null :
<div className='report-legend-label'>{this.props.title}</div>
}
{this.props.title === 'Recent Forest Loss' ?
<span dangerouslySetInnerHTML={{__html: '<svg width="10" height="10"><rect width="10" height="10" style="fill:rgb(255,96,151);"></svg>'}} />
: null}
{this.props.title === 'Historical Forest Loss' ?
<span className='historical-loss-holder'>
<div className='report-legend-data'>Tree cover
<span className='report-legend-svg' dangerouslySetInnerHTML={{__html: '<svg width="10" height="10"><rect width="10" height="10" style="fill:rgb(0,179,0);"></svg>'}} />
</div>
<div className='report-legend-data'>Potential forest coverage
<span className='report-legend-svg' dangerouslySetInnerHTML={{__html: '<svg width="10" height="10"><rect width="10" height="10" style="fill:rgb(255,255,112);"></svg>'}} />
</div>
</span>
: null}
{this.props.title === 'Active Fires' ?
<img className='report-legend-fire' src='/css/images/fire_icon.png' />
: null}
</div>
);
}
}
ReportLegend.propTypes = {
title: React.PropTypes.string.isRequired
};
| 42.588235 | 185 | 0.596685 |
ea7da5b9dfd7787ea063e308c33f618626d81081 | 872 | js | JavaScript | lib/middleware/expresslogger.js | Yonomi/thincloud-test-device | 50b35c26f7b17e4c6859c0173740c4efce0662c8 | [
"Apache-2.0"
] | null | null | null | lib/middleware/expresslogger.js | Yonomi/thincloud-test-device | 50b35c26f7b17e4c6859c0173740c4efce0662c8 | [
"Apache-2.0"
] | null | null | null | lib/middleware/expresslogger.js | Yonomi/thincloud-test-device | 50b35c26f7b17e4c6859c0173740c4efce0662c8 | [
"Apache-2.0"
] | null | null | null | 'use strict';
const uuid = require('uuid-1345');
const defaultLogger = require('../utils/logger');
/**
* Express Logger
* @param {object} options
*/
module.exports = function ({ logger = defaultLogger } = {}) {
return function (req, res, next) {
const startTime = process.hrtime();
req.log = res.log = logger.child({
reqId: req.reqId || uuid.v4(),
traceId: req.traceId, // AWS X-RAY specific
fwdAddress: req.header('x-forwarded-for')
});
req.log.info({ req: req }, 'request start');
res.on('finish', () => {
res.log.info({ req, res, duration: getDuration(startTime) }, 'request finish');
});
return next();
};
};
/**
* Difference between start and now (hrtime)
* @param {number} start
*/
function getDuration(start) {
var hrtime = process.hrtime(start);
return hrtime[0] * 1e3 + hrtime[1] * 1e-6;
}
| 22.947368 | 85 | 0.607798 |
ea7da627986fcaa42a31d4250064efbcdc4ee3aa | 298 | js | JavaScript | signalhub.js | AraBlocks/cfsnet | 2d531f7e3d58832a85abae5e908be073f793a052 | [
"MIT"
] | 11 | 2019-03-13T20:43:25.000Z | 2020-12-11T04:24:43.000Z | signalhub.js | AraBlocks/cfsnet | 2d531f7e3d58832a85abae5e908be073f793a052 | [
"MIT"
] | null | null | null | signalhub.js | AraBlocks/cfsnet | 2d531f7e3d58832a85abae5e908be073f793a052 | [
"MIT"
] | 3 | 2019-07-01T10:46:57.000Z | 2021-10-17T14:29:28.000Z | const SignalHub = require('signalhub')
function createCFSSignalHub({ discoveryKey, urls }) {
return new SignalHub(
Buffer.isBuffer(discoveryKey) ? discoveryKey.toString('hex') : discoveryKey,
urls || [ 'https://signalhub.littlstar.com' ]
)
}
module.exports = {
createCFSSignalHub
}
| 22.923077 | 80 | 0.711409 |
ea7dbd89b03f9cd51bf5a403ad78d45afe4ed9ac | 1,611 | js | JavaScript | scripts/docs-parser/load-config.js | BiosSun/nami | 43bb8c6dbd345cde820063d4bb959a648ed5ecb5 | [
"MIT"
] | 4 | 2018-07-24T10:13:25.000Z | 2018-12-12T08:09:15.000Z | scripts/docs-parser/load-config.js | BiosSun/nami | 43bb8c6dbd345cde820063d4bb959a648ed5ecb5 | [
"MIT"
] | null | null | null | scripts/docs-parser/load-config.js | BiosSun/nami | 43bb8c6dbd345cde820063d4bb959a648ed5ecb5 | [
"MIT"
] | null | null | null | const _ = require('lodash')
const fs = require('fs-extra')
const del = require('del')
const path = require('path')
const weblog = require('webpack-log')
const colors = require('ansi-colors')
const appRoot = require('app-root-path').toString()
const utils = require('./utils')
const log = weblog({ name: 'doc-parser/load-config' })
const configFile = path.join(appRoot, '.docsparserrc')
module.exports = function loadConfig() {
const config = fs.readJsonSync(configFile, { throws: false })
if (validConfig(config) === false) {
return null
} else {
config.outputs.documents = utils.absoluteDir(config.outputs.documents)
config.outputs.demos = utils.absoluteDir(config.outputs.demos)
del.sync([config.outputs.documents, config.outputs.demos])
config.watch = process.argv.indexOf('--watch') !== -1
return config
}
}
function validConfig(config, configFile) {
let isValid = false
if (!config) {
log.error(colors.red(`configuration file not found.`), `<${configFile}>`)
} else if (!config.documents || _.isEmpty(config.documents)) {
log.error(colors.red(`missing \`documents\` configuration item.`))
} else if (!config.outputs) {
log.error(colors.red(`missing \`outputs\` configuration item.`))
} else if (!config.outputs.documents) {
log.error(colors.red(`missing \`outputs.documents\` configuration item.`))
} else if (!config.outputs.demos) {
log.error(colors.red(`missing \`outputs.demos\` configuration item.`))
} else {
isValid = true
}
return isValid
}
| 32.877551 | 82 | 0.654873 |
ea7de10449472825d96772af36debe93d65d285c | 439 | js | JavaScript | src/components/Link/index.js | RobertJaskolski/todoTask | eeb24d037197c60b6fd433976fa623e70a066ef6 | [
"MIT"
] | null | null | null | src/components/Link/index.js | RobertJaskolski/todoTask | eeb24d037197c60b6fd433976fa623e70a066ef6 | [
"MIT"
] | null | null | null | src/components/Link/index.js | RobertJaskolski/todoTask | eeb24d037197c60b6fd433976fa623e70a066ef6 | [
"MIT"
] | null | null | null | import React from 'react';
import PropTypes from 'prop-types';
import { Link as ThemeUiLink } from 'theme-ui';
import { Link as ReactRouterLink } from 'react-router-dom';
const Link = ({ children, to, sx = {} }) => {
return (
<ThemeUiLink sx={{ ...sx }} to={to} as={ReactRouterLink}>
{children}
</ThemeUiLink>
);
};
Link.propTypes = {
to: PropTypes.string.isRequired,
sx: PropTypes.object,
};
export default Link;
| 21.95 | 61 | 0.644647 |
ea7ee7f67a608c953430e43c8ab1c8e823f486d8 | 523 | js | JavaScript | src/master/bad-output-reason-validator.js | jackyruslymoonlay/dl-models | ed7bc46927cfa2fbed99fc808022ea355f035388 | [
"MIT"
] | null | null | null | src/master/bad-output-reason-validator.js | jackyruslymoonlay/dl-models | ed7bc46927cfa2fbed99fc808022ea355f035388 | [
"MIT"
] | 14 | 2018-04-10T05:05:18.000Z | 2019-02-14T07:35:54.000Z | src/master/bad-output-reason-validator.js | jackyruslymoonlay/dl-models | ed7bc46927cfa2fbed99fc808022ea355f035388 | [
"MIT"
] | 74 | 2016-08-08T11:04:08.000Z | 2019-02-14T01:49:57.000Z | require("should");
var validateMachine = require('./machine-validator');
module.exports = function (data) {
data.should.not.equal(null);
data.should.instanceOf(Object);
data.should.have.property('code');
data.code.should.instanceOf(String);
data.should.have.property('reason');
data.reason.should.instanceOf(String);
data.should.have.property('machines');
data.machines.should.instanceOf(Array);
for (var machine of data.machines) {
validateMachine(machine);
}
}; | 27.526316 | 53 | 0.678776 |
ea7f00fe37af448d96979e4fdf64e68f3ed1c42a | 376 | js | JavaScript | src/functions/bind/rendition1.js | adamsilver/jessie | 0480405bf3c338918fa8fd5f5394e5a5a7127c87 | [
"MIT"
] | null | null | null | src/functions/bind/rendition1.js | adamsilver/jessie | 0480405bf3c338918fa8fd5f5394e5a5a7127c87 | [
"MIT"
] | 1 | 2015-07-21T17:40:59.000Z | 2015-07-21T17:40:59.000Z | src/functions/bind/rendition1.js | adamsilver/jessie | 0480405bf3c338918fa8fd5f5394e5a5a7127c87 | [
"MIT"
] | null | null | null | /*global canCall */
/*
Description:
Relies on `Function.prototype.bind`
*/
/*
Degrades:
IE8, IE7, IE6, IE5.5, IE5, IE4, IE3, Chrome 6, Firefox 3.6, Safari 5.1, Opera 11.5
*/
/*
Author:
David Mark
*/
var bind;
if(canCall && Function.prototype.bind){
bind = function(fn, thisObject) {
return fn.bind.apply(fn, Array.prototype.slice.call(arguments, 1));
};
} | 15.666667 | 82 | 0.646277 |
ea7f42fb90a673c60df3e40f04466e8416698c90 | 1,952 | js | JavaScript | src/processors/pre/LocalizedCapitalByLocaleCode.test.js | marc-ed-raffalli/world-geography-data | 0f9dbed3b349bb6cf76a8069205d946336db0b8b | [
"MIT"
] | null | null | null | src/processors/pre/LocalizedCapitalByLocaleCode.test.js | marc-ed-raffalli/world-geography-data | 0f9dbed3b349bb6cf76a8069205d946336db0b8b | [
"MIT"
] | null | null | null | src/processors/pre/LocalizedCapitalByLocaleCode.test.js | marc-ed-raffalli/world-geography-data | 0f9dbed3b349bb6cf76a8069205d946336db0b8b | [
"MIT"
] | null | null | null | const expect = require('chai').expect,
LocalizedCapitalByLocaleCode = require('./LocalizedCapitalByLocaleCode');
describe('LocalizedCapitalByLocaleCode', () => {
let processor;
beforeEach(() => {
processor = new LocalizedCapitalByLocaleCode({
_targetedLocales: ['en', 'fr', 'it']
});
});
describe('extract', () => {
it('returns localized city names', () => {
return processor.process({
sources: {
countries: {
countries: [
{cca2: 'FO', capital: {en: ['capital Foo en']}, name: {common: 'Foo'}},
{cca2: 'BR', capital: {en: ['capital Bar en']}, name: {common: 'Bar'}},
{cca2: 'BZ', capital: {en: ['capital Baz A en', 'capital Baz B en']}, name: {common: 'Baz'}},
{capital: {en: ['no cca2 branch']}, name: {common: 'cca2 missing'}}
]
},
'cldr-dates-full': {
capital: {
en: {cityFoo: 'capital Foo en', cityBaz: 'capital Baz B en'}, // bar missing for en fallback
fr: {cityFoo: 'capital Foo fr', cityBar: 'capital Bar fr', cityBaz: 'capital Baz fr'},
it: {cityFoo: 'capital Foo it'} // partial matching
}
}
}
})
.then(res => {
expect(res).to.deep.equal({
en: {
FO: 'capital Foo en',
BR: 'capital Bar en', // fallback
BZ: 'capital Baz B en',
_missing: []
},
fr: {
FO: 'capital Foo fr',
BZ: 'capital Baz fr',
_missing: [
['capital Bar en'] // Bar fr not matched
]
},
it: {
FO: 'capital Foo it',
_missing: [
['capital Bar en'],
['capital Baz A en', 'capital Baz B en']
]
}
});
});
});
});
});
| 29.575758 | 107 | 0.445697 |
ea7f8f041163a1044b1d39df0da7cb75a932954e | 109 | js | JavaScript | input/releases/qpid-proton-0.33.0/proton/c/api/search/files_7.js | tabish121/qpid-site | d86a295499690bee8f685b96123afd40acd78f7a | [
"Apache-2.0"
] | 2 | 2019-05-20T17:57:24.000Z | 2021-11-06T23:01:16.000Z | input/releases/qpid-proton-0.33.0/proton/c/api/search/files_7.js | tabish121/qpid-site | d86a295499690bee8f685b96123afd40acd78f7a | [
"Apache-2.0"
] | null | null | null | input/releases/qpid-proton-0.33.0/proton/c/api/search/files_7.js | tabish121/qpid-site | d86a295499690bee8f685b96123afd40acd78f7a | [
"Apache-2.0"
] | 7 | 2017-11-02T23:13:56.000Z | 2021-11-06T23:01:05.000Z | var searchData=
[
['raw_5fconnection_2eh_901',['raw_connection.h',['../raw__connection_8h.html',1,'']]]
];
| 21.8 | 87 | 0.688073 |
ea7f90c736143fc2e5f48ebe1c7e848fbaf0946f | 2,342 | js | JavaScript | modules/config/ConfigurationMenu.js | dbeaumon/graphvinci | 9398df5eceea906d85eeed9d2a74984e4a9ff991 | [
"Apache-2.0"
] | 23 | 2021-09-22T16:17:43.000Z | 2022-02-22T18:03:33.000Z | modules/config/ConfigurationMenu.js | dbeaumon/graphvinci | 9398df5eceea906d85eeed9d2a74984e4a9ff991 | [
"Apache-2.0"
] | 2 | 2021-12-27T18:36:59.000Z | 2022-01-30T20:56:12.000Z | modules/config/ConfigurationMenu.js | AlexRogalskiy/graphvinci | df22d9dea6623c1614fafeb374f02c70a8ddfb6c | [
"Apache-2.0"
] | 2 | 2021-11-13T02:10:29.000Z | 2022-01-03T18:06:18.000Z | /*
* Copyright 2018 The GraphVinci Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import MenuData from "../burger_menu/MenuData";
import VerticalMenu, {DEFAULTHEIGHT} from "../burger_menu/VerticalMenu";
import SchemaStack from "../burger_menu/SchemaStack";
import SchemaConfig from "../burger_menu/SchemaConfig";
import AuthStack from "../burger_menu/AuthStack";
import AuthConfig from "../burger_menu/AuthConfig";
import GlobalViz from "../GlobalViz";
export default class ConfigurationMenu extends VerticalMenu {
_get_menu_data() {
let self = this;
this.data = new MenuData();
let update_func = function() {
self.update_state();
}
let schemaStack = new SchemaStack(this.actualWidth, DEFAULTHEIGHT, update_func);
if (! this.openTo) schemaStack.expanded = true;
this.data.add_child(schemaStack);
let schemas = GlobalViz.vis?.config.schemas;
for (let schemaName in schemas) {
let schema = new SchemaConfig(this.actualWidth, DEFAULTHEIGHT, schemas[schemaName])
if (this.openTo && this.openTo.name === schemaName) {
schemaStack.expanded = true;
schema.expanded = true;
}
schemaStack.add_child(schema);
}
let authStack = new AuthStack(this.actualWidth, DEFAULTHEIGHT)
this.data.add_child(authStack);
let authorizations = GlobalViz.vis?.config.authorizations;
for (let authName in authorizations) {
let auth = new AuthConfig(this.actualWidth, DEFAULTHEIGHT, authorizations[authName])
if (this.openTo && this.openTo.name === authName) {
authStack.expanded = true;
auth.expanded = true;
}
authStack.add_child(auth);
}
}
}
| 40.37931 | 96 | 0.665243 |
ea80f40757e93c7c6f9f697bbc2720d7aaf94fc5 | 738 | js | JavaScript | node_modules/react-icons-kit/entypo/drive.js | lananh265/social-network | 8f74dae5affe298671ebbc80991866dd2630f946 | [
"MIT"
] | 3 | 2020-11-28T12:19:12.000Z | 2021-06-01T20:15:41.000Z | node_modules/react-icons-kit/entypo/drive.js | lananh265/social-network | 8f74dae5affe298671ebbc80991866dd2630f946 | [
"MIT"
] | 8 | 2021-03-09T19:53:42.000Z | 2022-02-26T18:45:12.000Z | node_modules/react-icons-kit/entypo/drive.js | lananh265/social-network | 8f74dae5affe298671ebbc80991866dd2630f946 | [
"MIT"
] | 4 | 2020-04-16T08:55:16.000Z | 2021-01-15T17:53:02.000Z | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.drive = void 0;
var drive = {
"viewBox": "0 0 20 20",
"children": [{
"name": "path",
"attribs": {
"d": "M19.059,10.898l-3.171-7.927C15.654,2.384,15.086,2,14.454,2H5.546C4.914,2,4.346,2.384,4.112,2.971l-3.171,7.927\r\n\tc-0.288,0.721-0.373,1.507-0.246,2.272l0.59,3.539C1.409,17.454,2.053,18,2.808,18h14.383c0.755,0,1.399-0.546,1.523-1.291\r\n\tl0.59-3.539C19.433,12.405,19.348,11.619,19.059,10.898z M16.959,15.245C16.887,15.681,16.51,16,16.068,16H3.932\r\n\tc-0.442,0-0.819-0.319-0.891-0.755l-0.365-2.193C2.583,12.501,3.008,12,3.567,12h12.867c0.558,0,0.983,0.501,0.891,1.052\r\n\tL16.959,15.245z"
}
}]
};
exports.drive = drive; | 46.125 | 503 | 0.650407 |
ea813709949cb4f9d72ce8af9451e81abb7c0620 | 5,646 | js | JavaScript | out/dev_compiler/runtime/dart/_foreign_helper.js | cjkao/sunflower-es5-traceur | ac7e53175012a4d2007063dc3e3492c5089092cc | [
"MIT"
] | null | null | null | out/dev_compiler/runtime/dart/_foreign_helper.js | cjkao/sunflower-es5-traceur | ac7e53175012a4d2007063dc3e3492c5089092cc | [
"MIT"
] | null | null | null | out/dev_compiler/runtime/dart/_foreign_helper.js | cjkao/sunflower-es5-traceur | ac7e53175012a4d2007063dc3e3492c5089092cc | [
"MIT"
] | null | null | null | dart_library.library('dart/_foreign_helper', null, /* Imports */[
"dart/_runtime",
'dart/core'
], /* Lazy imports */[
], function(exports, dart, core) {
'use strict';
let dartx = dart.dartx;
function JS(typeDescription, codeTemplate, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11) {
if (arg0 === void 0)
arg0 = null;
if (arg1 === void 0)
arg1 = null;
if (arg2 === void 0)
arg2 = null;
if (arg3 === void 0)
arg3 = null;
if (arg4 === void 0)
arg4 = null;
if (arg5 === void 0)
arg5 = null;
if (arg6 === void 0)
arg6 = null;
if (arg7 === void 0)
arg7 = null;
if (arg8 === void 0)
arg8 = null;
if (arg9 === void 0)
arg9 = null;
if (arg10 === void 0)
arg10 = null;
if (arg11 === void 0)
arg11 = null;
}
dart.fn(JS, dart.dynamic, [core.String, core.String], [dart.dynamic, dart.dynamic, dart.dynamic, dart.dynamic, dart.dynamic, dart.dynamic, dart.dynamic, dart.dynamic, dart.dynamic, dart.dynamic, dart.dynamic, dart.dynamic]);
function JS_CURRENT_ISOLATE_CONTEXT() {
}
dart.fn(JS_CURRENT_ISOLATE_CONTEXT, () => dart.definiteFunctionType(IsolateContext, []));
class IsolateContext extends core.Object {}
function JS_CALL_IN_ISOLATE(isolate, func) {
}
dart.fn(JS_CALL_IN_ISOLATE, dart.dynamic, [dart.dynamic, core.Function]);
function JS_SET_CURRENT_ISOLATE(isolate) {
}
dart.fn(JS_SET_CURRENT_ISOLATE, dart.void, [dart.dynamic]);
function JS_CREATE_ISOLATE() {
}
dart.fn(JS_CREATE_ISOLATE);
function JS_DART_OBJECT_CONSTRUCTOR() {
}
dart.fn(JS_DART_OBJECT_CONSTRUCTOR);
function JS_INTERCEPTOR_CONSTANT(type) {
}
dart.fn(JS_INTERCEPTOR_CONSTANT, dart.dynamic, [core.Type]);
function JS_OPERATOR_IS_PREFIX() {
}
dart.fn(JS_OPERATOR_IS_PREFIX, core.String, []);
function JS_OPERATOR_AS_PREFIX() {
}
dart.fn(JS_OPERATOR_AS_PREFIX, core.String, []);
function JS_OBJECT_CLASS_NAME() {
}
dart.fn(JS_OBJECT_CLASS_NAME, core.String, []);
function JS_NULL_CLASS_NAME() {
}
dart.fn(JS_NULL_CLASS_NAME, core.String, []);
function JS_FUNCTION_CLASS_NAME() {
}
dart.fn(JS_FUNCTION_CLASS_NAME, core.String, []);
function JS_IS_INDEXABLE_FIELD_NAME() {
}
dart.fn(JS_IS_INDEXABLE_FIELD_NAME, core.String, []);
function JS_CURRENT_ISOLATE() {
}
dart.fn(JS_CURRENT_ISOLATE);
function JS_SIGNATURE_NAME() {
}
dart.fn(JS_SIGNATURE_NAME, core.String, []);
function JS_TYPEDEF_TAG() {
}
dart.fn(JS_TYPEDEF_TAG, core.String, []);
function JS_FUNCTION_TYPE_TAG() {
}
dart.fn(JS_FUNCTION_TYPE_TAG, core.String, []);
function JS_FUNCTION_TYPE_VOID_RETURN_TAG() {
}
dart.fn(JS_FUNCTION_TYPE_VOID_RETURN_TAG, core.String, []);
function JS_FUNCTION_TYPE_RETURN_TYPE_TAG() {
}
dart.fn(JS_FUNCTION_TYPE_RETURN_TYPE_TAG, core.String, []);
function JS_FUNCTION_TYPE_REQUIRED_PARAMETERS_TAG() {
}
dart.fn(JS_FUNCTION_TYPE_REQUIRED_PARAMETERS_TAG, core.String, []);
function JS_FUNCTION_TYPE_OPTIONAL_PARAMETERS_TAG() {
}
dart.fn(JS_FUNCTION_TYPE_OPTIONAL_PARAMETERS_TAG, core.String, []);
function JS_FUNCTION_TYPE_NAMED_PARAMETERS_TAG() {
}
dart.fn(JS_FUNCTION_TYPE_NAMED_PARAMETERS_TAG, core.String, []);
function JS_GET_NAME(name) {
}
dart.fn(JS_GET_NAME, core.String, [core.String]);
function JS_EMBEDDED_GLOBAL(typeDescription, name) {
}
dart.fn(JS_EMBEDDED_GLOBAL, dart.dynamic, [core.String, core.String]);
function JS_GET_FLAG(name) {
}
dart.fn(JS_GET_FLAG, core.bool, [core.String]);
function JS_EFFECT(code) {
dart.dcall(code, null);
}
dart.fn(JS_EFFECT, dart.void, [core.Function]);
class JS_CONST extends core.Object {
JS_CONST(code) {
this.code = code;
}
}
dart.setSignature(JS_CONST, {
constructors: () => ({JS_CONST: [JS_CONST, [core.String]]})
});
function JS_STRING_CONCAT(a, b) {
return a + b;
}
dart.fn(JS_STRING_CONCAT, core.String, [core.String, core.String]);
// Exports:
exports.JS = JS;
exports.JS_CURRENT_ISOLATE_CONTEXT = JS_CURRENT_ISOLATE_CONTEXT;
exports.IsolateContext = IsolateContext;
exports.JS_CALL_IN_ISOLATE = JS_CALL_IN_ISOLATE;
exports.JS_SET_CURRENT_ISOLATE = JS_SET_CURRENT_ISOLATE;
exports.JS_CREATE_ISOLATE = JS_CREATE_ISOLATE;
exports.JS_DART_OBJECT_CONSTRUCTOR = JS_DART_OBJECT_CONSTRUCTOR;
exports.JS_INTERCEPTOR_CONSTANT = JS_INTERCEPTOR_CONSTANT;
exports.JS_OPERATOR_IS_PREFIX = JS_OPERATOR_IS_PREFIX;
exports.JS_OPERATOR_AS_PREFIX = JS_OPERATOR_AS_PREFIX;
exports.JS_OBJECT_CLASS_NAME = JS_OBJECT_CLASS_NAME;
exports.JS_NULL_CLASS_NAME = JS_NULL_CLASS_NAME;
exports.JS_FUNCTION_CLASS_NAME = JS_FUNCTION_CLASS_NAME;
exports.JS_IS_INDEXABLE_FIELD_NAME = JS_IS_INDEXABLE_FIELD_NAME;
exports.JS_CURRENT_ISOLATE = JS_CURRENT_ISOLATE;
exports.JS_SIGNATURE_NAME = JS_SIGNATURE_NAME;
exports.JS_TYPEDEF_TAG = JS_TYPEDEF_TAG;
exports.JS_FUNCTION_TYPE_TAG = JS_FUNCTION_TYPE_TAG;
exports.JS_FUNCTION_TYPE_VOID_RETURN_TAG = JS_FUNCTION_TYPE_VOID_RETURN_TAG;
exports.JS_FUNCTION_TYPE_RETURN_TYPE_TAG = JS_FUNCTION_TYPE_RETURN_TYPE_TAG;
exports.JS_FUNCTION_TYPE_REQUIRED_PARAMETERS_TAG = JS_FUNCTION_TYPE_REQUIRED_PARAMETERS_TAG;
exports.JS_FUNCTION_TYPE_OPTIONAL_PARAMETERS_TAG = JS_FUNCTION_TYPE_OPTIONAL_PARAMETERS_TAG;
exports.JS_FUNCTION_TYPE_NAMED_PARAMETERS_TAG = JS_FUNCTION_TYPE_NAMED_PARAMETERS_TAG;
exports.JS_GET_NAME = JS_GET_NAME;
exports.JS_EMBEDDED_GLOBAL = JS_EMBEDDED_GLOBAL;
exports.JS_GET_FLAG = JS_GET_FLAG;
exports.JS_EFFECT = JS_EFFECT;
exports.JS_CONST = JS_CONST;
exports.JS_STRING_CONCAT = JS_STRING_CONCAT;
});
| 36.425806 | 226 | 0.733617 |
ea814c6d60e6b934a6a0ee48b9d026ce4c7ecbcf | 3,883 | js | JavaScript | jobfair/routes/student.js | maricak/JobfairPIA | 210d58ada899087206530d1d932d53b8ea09787a | [
"MIT"
] | null | null | null | jobfair/routes/student.js | maricak/JobfairPIA | 210d58ada899087206530d1d932d53b8ea09787a | [
"MIT"
] | null | null | null | jobfair/routes/student.js | maricak/JobfairPIA | 210d58ada899087206530d1d932d53b8ea09787a | [
"MIT"
] | null | null | null | const express = require("express");
const router = express.Router();
const Student = require('../models/student');
const Fair = require('../models/fair');
const jwt = require('jsonwebtoken');
const config = require('../config/database');
router.use((req, res, next) => {
// console.log("student PROVERA");
let token = req.headers['auth'];
if (!token) {
res.json({ success: false, message: "No token provided" });
} else {
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
res.json({ success: false, message: "Token invalid: " + err.message });
} else {
req.decoded = decoded;
next();
}
})
}
});
router.get('/account/:id', (req, res) => {
let id = req.params.id;
if (req.decoded.type != "student") {
res.json({ success: false, message: "This data is only for students" });
} else if (id !== req.decoded.id) {
res.json({ success: false, message: "Access to others student's data is not allowed" })
} else {
Student.findById(id, (err, student) => {
if (err) {
res.json({ success: false, message: "Error happend while retrieving student's data: ".message });
} else if (student) {
res.json({ success: true, message: "Success", student: student });
} else {
res.json({ success: false, message: "No student in the database" });
}
})
}
})
router.post('/cvupdate', (req, res) => {
let id = req.decoded.id;
Fair.findOne({ finished: false }, (err, fair) => {
if (err) {
res.json({ success: false, message: "Error happened while checking cv update deadline" + err.message });
} else if (fair) {
let today = new Date();
let cvdl = new Date(fair.cvDeadline);
if (cvdl < today) {
res.json({ success: false, message: "Updating cv is not allowed at the moment" });
} else {
Student.findById(id, (err, student) => {
if (err) {
res.json({ success: false, message: "Error happend while retrieving student's data: " + err.message });
} else if (student) {
let cv = req.body;
console.log("cv");
console.log(cv);
student.set({ cv: cv });
student.$ignore('password');
student.save((err, updatedStudent) => {
if (err) {
if (err.errors) {
for (const key in err.errors) {
res.json({ success: false, message: err.errors[key].message });
break;
}
} else {
res.json({ success: false, message: 'Could not save cv info. Error: ' + err.message, student: null });
}
} else if (updatedStudent) {
res.json({ success: true, message: 'Success!', student: updatedStudent });
} else {
res.json({ success: false, message: "Could not save cv info", student: null });
}
})
} else {
res.json({ success: false, message: "No student in the database" });
}
});
}
} else {
res.json({ success: false, message: "Updating cv is not allowed. There is no opened fair" });
}
})
})
module.exports = router; | 40.873684 | 138 | 0.451198 |
ea834195dcbcb200de31809a67872d04dec35ba5 | 1,628 | js | JavaScript | webapp/src/components/NavBar/Navbar.js | aaleks/rest-api-monitoring-project | 0e071f434734b590f30454209dbba1c0fdd98b3e | [
"Apache-2.0"
] | 1 | 2017-02-13T14:48:51.000Z | 2017-02-13T14:48:51.000Z | webapp/src/components/NavBar/Navbar.js | aaleks/rest-api-monitoring-project | 0e071f434734b590f30454209dbba1c0fdd98b3e | [
"Apache-2.0"
] | null | null | null | webapp/src/components/NavBar/Navbar.js | aaleks/rest-api-monitoring-project | 0e071f434734b590f30454209dbba1c0fdd98b3e | [
"Apache-2.0"
] | null | null | null | import React, {Component} from 'react';
import BaseComponent from './../BaseComponent.react.js';
import style from './Navbar.style.scss';
import * as Utilities from '../../utils/Utilities'
import {Link} from 'react-router'
export default class Navbar extends BaseComponent {
constructor(props) {
super(props);
}
render() {
return (<nav className="navbar navbar-default navbar-static-top" role="navigation">
<div className="container-fluid">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"/>
<span className="icon-bar"/>
<span className="icon-bar"/>
</button>
{/* Brand */}
<Link className="navbar-brand" to="/">My Monitor</Link>
</div>
<div className="collapse navbar-collapse animated fadeIn" id="bs-example-navbar-collapse-1">
<ul className="nav navbar-nav animated fadeIn">
<li><Link to="/appchecker">Quick app checker</Link></li>
</ul>
</div>
{/* /.navbar-collapse */}
</div>
{/* /.container-fluid */}
</nav>
);
}
} | 40.7 | 112 | 0.487101 |
ea834f95b5cb3ab9d85a989731d47be08370446e | 694 | js | JavaScript | angular/node_modules/angular-date-value-accessor/src/module.js | DeegC/Zeidon-Northwind | 3a016d759b589096f54da7ca1e276ed9a42c4a28 | [
"Apache-2.0"
] | null | null | null | angular/node_modules/angular-date-value-accessor/src/module.js | DeegC/Zeidon-Northwind | 3a016d759b589096f54da7ca1e276ed9a42c4a28 | [
"Apache-2.0"
] | 2 | 2019-12-31T01:51:48.000Z | 2022-03-02T10:00:45.000Z | angular/node_modules/angular-date-value-accessor/src/module.js | DeegC/Zeidon-Northwind | 3a016d759b589096f54da7ca1e276ed9a42c4a28 | [
"Apache-2.0"
] | null | null | null | "use strict";
var core_1 = require('@angular/core');
var date_value_accessor_1 = require('./date-value-accessor');
var DateValueAccessorModule = (function () {
function DateValueAccessorModule() {
}
DateValueAccessorModule.decorators = [
{ type: core_1.NgModule, args: [{
declarations: [date_value_accessor_1.DateValueAccessor],
exports: [date_value_accessor_1.DateValueAccessor]
},] },
];
/** @nocollapse */
DateValueAccessorModule.ctorParameters = [];
return DateValueAccessorModule;
}());
exports.DateValueAccessorModule = DateValueAccessorModule;
//# sourceMappingURL=module.js.map | 38.555556 | 77 | 0.65562 |
ea83aa2e2da46bdfe79ac0fcb9bbc53ac224d968 | 10,645 | js | JavaScript | src/scripts/statusbar.js | OlavStornes/h5p-digibook | 8300f5ee3a45f7df49e95c4f33b6308c98b5eece | [
"MIT"
] | 1 | 2018-10-10T07:19:12.000Z | 2018-10-10T07:19:12.000Z | src/scripts/statusbar.js | OlavStornes/h5p-digibook | 8300f5ee3a45f7df49e95c4f33b6308c98b5eece | [
"MIT"
] | 82 | 2018-09-20T10:41:16.000Z | 2018-10-31T15:11:17.000Z | src/scripts/statusbar.js | OlavStornes/h5p-digibook | 8300f5ee3a45f7df49e95c4f33b6308c98b5eece | [
"MIT"
] | 5 | 2018-10-10T19:12:50.000Z | 2020-08-25T01:00:56.000Z | /**
* Constructor function.
*/
class StatusBar extends H5P.EventDispatcher {
constructor(contentId, totalChapters, parent, params) {
super();
this.id = contentId;
this.parent = parent;
this.params = this.extend(
{
l10n: {
nextPage: 'Next page',
previousPage: 'Previous page',
navigateToTop: 'Navigate to the top',
}
},
params || {}
);
this.totalChapters = totalChapters;
this.arrows = this.addArrows();
/**
* Top row initializer
*/
this.header = document.createElement('div');
this.headerInfo = document.createElement('div');
this.header.classList.add('h5p-digibook-status-header');
this.headerInfo.classList.add('h5p-digibook-status');
this.headerProgressBar = this.addProgressBar();
this.headerStatus = this.addProgress();
this.footerStatus = this.addProgress();
this.headerMenu = this.addMenu();
this.buttonToTop = this.addToTop();
this.headerChapterTitle = this.addChapterTitle();
this.footerChapterTitle = this.addChapterTitle();
this.header.appendChild(this.headerProgressBar.div);
this.headerInfo.appendChild(this.headerMenu.div);
this.headerInfo.appendChild(this.headerChapterTitle.div);
this.headerInfo.appendChild(this.headerStatus.div);
this.headerInfo.appendChild(this.arrows.divTopPrev);
this.headerInfo.appendChild(this.arrows.divTopNext);
this.header.appendChild(this.headerInfo);
/**
* Bottom row initializer
*/
this.footer = document.createElement('div');
this.footer.classList.add('h5p-digibook-status-footer');
this.footerInfo = document.createElement('div');
this.footerInfo.classList.add('h5p-digibook-status');
this.footerProgressBar = this.addProgressBar();
this.footer.appendChild(this.footerProgressBar.div);
this.footerInfo.appendChild(this.buttonToTop.div);
this.footerInfo.appendChild(this.footerChapterTitle.div);
this.footerInfo.appendChild(this.footerStatus.div);
this.footerInfo.appendChild(this.arrows.divBotPrev);
this.footerInfo.appendChild(this.arrows.divBotNext);
this.footer.appendChild(this.footerInfo);
this.on('updateStatusBar', this.updateStatusBar);
/**
* Sequential traversal of chapters
* Event should be either 'next' or 'prev'
*/
this.on('seqChapter', (event) => {
const eventInput = {
h5pbookid: this.parent.contentId
};
if (event.data.toTop) {
eventInput.section = "top";
}
if (event.data.direction === 'next') {
if (this.parent.activeChapter+1 < this.parent.instances.length) {
eventInput.chapter = this.parent.instances[this.parent.activeChapter+1].subContentId;
}
}
else if (event.data.direction === 'prev') {
if (this.parent.activeChapter > 0) {
eventInput.chapter = this.parent.instances[this.parent.activeChapter-1].subContentId;
}
}
if (eventInput.chapter) {
this.parent.trigger('newChapter', eventInput);
}
});
}
updateProgressBar(chapter) {
let barWidth = ((chapter / this.totalChapters)*100)+"%";
this.headerProgressBar.progress.style.width = barWidth;
this.footerProgressBar.progress.style.width = barWidth;
}
updateStatusBar() {
const currChapter = this.parent.getActiveChapter()+1;
const chapterTitle = this.parent.instances[this.parent.getActiveChapter()].title;
this.headerStatus.current.innerHTML = currChapter;
this.footerStatus.current.innerHTML = currChapter;
this.updateProgressBar(currChapter);
this.headerChapterTitle.p.innerHTML = chapterTitle;
this.footerChapterTitle.p.innerHTML = chapterTitle;
this.headerChapterTitle.p.setAttribute("title", chapterTitle);
this.footerChapterTitle.p.setAttribute("title", chapterTitle);
//assure that the buttons are valid in terms of chapter edges
if (this.parent.activeChapter <= 0) {
this.editButtonStatus('Prev', true);
}
else {
this.editButtonStatus('Prev', false);
}
if ((this.parent.activeChapter+1) >= this.totalChapters) {
this.editButtonStatus('Next', true);
}
else {
this.editButtonStatus('Next', false);
}
}
/**
* Add traversal buttons for sequential travel (next and previous chapter)
*/
addArrows() {
const acm = {};
// Initialize elements
acm.divTopPrev = document.createElement('div');
acm.divTopNext = document.createElement('div');
acm.divBotPrev = document.createElement('div');
acm.divBotNext = document.createElement('div');
acm.botNext = document.createElement('a');
acm.topNext = document.createElement('a');
acm.botPrev = document.createElement('a');
acm.topPrev = document.createElement('a');
acm.divTopPrev.classList.add('h5p-digibook-status-arrow', 'h5p-digibook-status-button');
acm.divTopNext.classList.add('h5p-digibook-status-arrow', 'h5p-digibook-status-button');
acm.divBotPrev.classList.add('h5p-digibook-status-arrow', 'h5p-digibook-status-button');
acm.divBotNext.classList.add('h5p-digibook-status-arrow', 'h5p-digibook-status-button');
acm.topNext.classList.add('icon-next');
acm.botNext.classList.add('icon-next');
acm.topPrev.classList.add('icon-previous');
acm.botPrev.classList.add('icon-previous');
//Initialize trigger events
acm.divTopPrev.onclick = () => {
this.trigger('seqChapter', {
direction:'prev',
toTop: false
});
};
acm.divTopNext.onclick = () => {
this.trigger('seqChapter', {
direction:'next',
toTop: false
});
};
acm.divBotPrev.onclick = () => {
this.trigger('seqChapter', {
direction:'prev',
toTop: true
});
};
acm.divBotNext.onclick = () => {
this.trigger('seqChapter', {
direction:'next',
toTop: true
});
};
//Add tooltip
acm.topNext.setAttribute("title", this.params.l10n.nextPage);
acm.botNext.setAttribute("title", this.params.l10n.nextPage);
acm.topPrev.setAttribute("title", this.params.l10n.previousPage);
acm.botPrev.setAttribute("title", this.params.l10n.previousPage);
// Attach to the respective divs
acm.divTopNext.appendChild(acm.topNext);
acm.divTopPrev.appendChild(acm.topPrev);
acm.divBotNext.appendChild(acm.botNext);
acm.divBotPrev.appendChild(acm.botPrev);
return acm;
}
/**
* Add a menu button which hides and shows the navigation bar
*/
addMenu() {
const that = this;
const row = document.createElement('div');
const item = document.createElement('a');
let iconType = 'icon-menu';
if (this.params.behaviour.defaultTableOfContents) {
row.classList.add('h5p-digibook-status-menu-active');
}
item.classList.add(iconType);
row.classList.add('h5p-digibook-status-menu', 'h5p-digibook-status-button');
row.onclick = function () {
that.parent.trigger('toggleMenu');
this.classList.toggle('h5p-digibook-status-menu-active');
};
row.appendChild(item);
return {
div:row,
a:item
};
}
addProgressBar() {
const div = document.createElement('div');
const progress = document.createElement('div');
div.classList.add('h5p-digibook-status-progressbar-back');
progress.classList.add('h5p-digibook-status-progressbar-front');
div.appendChild(progress);
return {
div,
progress
};
}
/**
* Add a paragraph which indicates which chapter is active
*/
addChapterTitle() {
const div = document.createElement('div');
const chapterTitle = document.createElement('p');
div.classList.add('h5p-digibook-status-chapter');
div.appendChild(chapterTitle);
return {
div,
p:chapterTitle
};
}
/**
* Add a button which scrolls to the top of the page
*/
addToTop() {
const that = this;
const div = document.createElement('div');
const a = document.createElement('a');
div.classList.add('h5p-digibook-status-button', 'h5p-digibook-status-arrow');
a.classList.add ('icon-up');
a.setAttribute('title', this.params.l10n.navigateToTop);
a.onclick = function () {
that.parent.trigger('scrollToTop');
};
div.appendChild(a);
return {
div,
a
};
}
/**
* Edits the footer visibillity
*
* @param {Boolean} input
*/
editFooterVisibillity(input) {
if (input) {
this.footer.classList.add('footer-hidden');
}
else {
this.footer.classList.remove('footer-hidden');
}
}
/**
* Add a status-button which shows current and total chapters
*/
addProgress() {
const div = document.createElement('div');
const p = document.createElement('p');
const current = document.createElement('span');
const divider = document.createElement('span');
const total = document.createElement('span');
p.classList.add('h5p-digibook-status-progress');
current.classList.add('h5p-digibook-status-progress-number');
divider.classList.add('h5p-digibook-status-progress-divider');
total.classList.add('h5p-digibook-status-progress-number');
divider.innerHTML = " / ";
total.innerHTML = this.totalChapters;
p.appendChild(current);
p.appendChild(divider);
p.appendChild(total);
div.appendChild(p);
return {
div,
current,
total,
divider,
p
};
}
/**
* Edit button state on both the top and bottom bar
* @param {bool} state
*/
editButtonStatus(target, state) {
if (state) {
this.arrows['top'+target].classList.add('disabled');
this.arrows['bot'+target].classList.add('disabled');
}
else {
this.arrows['top'+target].classList.remove('disabled');
this.arrows['bot'+target].classList.remove('disabled');
}
}
/**
* Extend an array just like JQuery's extend.
*
* @param {object} arguments Objects to be merged.
* @return {object} Merged objects.
*/
extend() {
for (let i = 1; i < arguments.length; i++) {
for (let key in arguments[i]) {
if (arguments[i].hasOwnProperty(key)) {
if (typeof arguments[0][key] === 'object' && typeof arguments[i][key] === 'object') {
this.extend(arguments[0][key], arguments[i][key]);
}
else {
arguments[0][key] = arguments[i][key];
}
}
}
}
return arguments[0];
}
}
export default StatusBar;
| 27.866492 | 95 | 0.641616 |
ea84b22665b678150ee798ef2cba84672d9cdad4 | 703 | js | JavaScript | dist-mdi/mdi/jira.js | maciejg-git/vue-bootstrap-icons | bc60cf77193e15cc72ec7eb7f9949ed8b552e7ec | [
"MIT",
"CC-BY-4.0",
"MIT-0"
] | null | null | null | dist-mdi/mdi/jira.js | maciejg-git/vue-bootstrap-icons | bc60cf77193e15cc72ec7eb7f9949ed8b552e7ec | [
"MIT",
"CC-BY-4.0",
"MIT-0"
] | null | null | null | dist-mdi/mdi/jira.js | maciejg-git/vue-bootstrap-icons | bc60cf77193e15cc72ec7eb7f9949ed8b552e7ec | [
"MIT",
"CC-BY-4.0",
"MIT-0"
] | null | null | null | import { h } from 'vue'
export default {
name: "Jira",
vendor: "Mdi",
type: "",
tags: ["jira"],
render() {
return h(
"svg",
{"xmlns":"http://www.w3.org/2000/svg","width":"24","height":"24","viewBox":"0 0 24 24","class":"v-icon","fill":"currentColor","data-name":"mdi-jira","innerHTML":"<path d='M11.53,2C11.53,4.4 13.5,6.35 15.88,6.35H17.66V8.05C17.66,10.45 19.6,12.39 22,12.4V2.84A0.84,0.84 0 0,0 21.16,2H11.53M6.77,6.8C6.78,9.19 8.72,11.13 11.11,11.14H12.91V12.86C12.92,15.25 14.86,17.19 17.25,17.2V7.63C17.24,7.17 16.88,6.81 16.42,6.8H6.77M2,11.6C2,14 3.95,15.94 6.35,15.94H8.13V17.66C8.14,20.05 10.08,22 12.47,22V12.43A0.84,0.84 0 0,0 11.63,11.59L2,11.6Z' />"},
)
}
} | 54.076923 | 547 | 0.613087 |
ea8596d601bd3de0ac28801a7b403d2a6aa1bfa0 | 1,333 | js | JavaScript | tests/integration/integration.test.js | luk-schweizer/code-coverage-jest-action | 09a7111acb3c6998ceb34bdf6e9d8651ec8b8d45 | [
"MIT"
] | 4 | 2021-04-01T06:22:09.000Z | 2022-03-06T23:13:55.000Z | tests/integration/integration.test.js | luk-schweizer/code-coverage-jest-action | 09a7111acb3c6998ceb34bdf6e9d8651ec8b8d45 | [
"MIT"
] | 1 | 2022-03-05T16:02:19.000Z | 2022-03-05T16:02:19.000Z | tests/integration/integration.test.js | luk-schweizer/code-coverage-jest-action | 09a7111acb3c6998ceb34bdf6e9d8651ec8b8d45 | [
"MIT"
] | 1 | 2021-03-18T22:07:15.000Z | 2021-03-18T22:07:15.000Z | const retry = require('p-retry');
const fetch = require('node-fetch');
beforeEach(async () => {
jest.setTimeout(10000);
});
test('jest-code-coverage-badge-action output should return an svg badge with label coverage and value 100% when input label is coverage, coverage of test are 100% and key url is not provided', async () => {
const outputUrl = process.env.BADGE_OUTPUT_WITH_URL_NOT_PROVIDED;
console.log(`Url ${outputUrl}`);
const response = await retry(() => fetch(outputUrl, {method: 'get', timeout: 2000}), {retries: 4});
const svg = await response.text();
expect(svg).toMatch(/^<svg/);
expect(svg).toMatch(/<text[^>]*>coverage<\/text>/);
expect(svg).toMatch(/<text[^>]*>100%<\/text>/);
});
test('jest-code-coverage-badge-action output should return an svg badge with label coverage and value 100% when input label is coverageWithUrlProvided, coverage of test are 100% and key url is provided', async () => {
const outputUrl = process.env.BADGE_OUTPUT_WITH_URL_PROVIDED;
console.log(`Url ${outputUrl}`);
const response = await retry(() => fetch(outputUrl, {method: 'get', timeout: 2000}), {retries: 4});
const svg = await response.text();
expect(svg).toMatch(/^<svg/);
expect(svg).toMatch(/<text[^>]*>coverageWithUrlProvided<\/text>/);
expect(svg).toMatch(/<text[^>]*>100%<\/text>/);
});
| 43 | 217 | 0.688672 |
ea867eeb408a3cd00cf88e8dc0a45c1524c0d920 | 1,508 | js | JavaScript | client/component/totara_engage/src/js/mixins/container_mixin.js | woon5118/totara_ub | a38f8e5433c93d295f6768fb24e5eecefa8294cd | [
"PostgreSQL"
] | null | null | null | client/component/totara_engage/src/js/mixins/container_mixin.js | woon5118/totara_ub | a38f8e5433c93d295f6768fb24e5eecefa8294cd | [
"PostgreSQL"
] | null | null | null | client/component/totara_engage/src/js/mixins/container_mixin.js | woon5118/totara_ub | a38f8e5433c93d295f6768fb24e5eecefa8294cd | [
"PostgreSQL"
] | null | null | null | /**
* This file is part of Totara Enterprise Extensions.
*
* Copyright (C) 2020 onwards Totara Learning Solutions LTD
*
* Totara Enterprise Extensions is provided only to Totara
* Learning Solutions LTD's customers and partners, pursuant to
* the terms and conditions of a separate agreement with Totara
* Learning Solutions LTD or its affiliate.
*
* If you do not have an agreement with Totara Learning Solutions
* LTD, you may not access, use, modify, or distribute this software.
* Please contact [licensing@totaralearning.com] for more information.
*
* @author Johannes Cilliers <johannes.cilliers@totaralearning.com>
* @module totara_engage
*/
export default {
props: {
/**
* Specify the container details if the new resource would be created
* inside a container.
*/
container: {
type: Object,
default: null,
validator: container => {
const valid = ['instanceId', 'component', 'access'].every(
prop => prop in container
);
if (!container.autoShareRecipient) {
return valid;
}
// Continue check the validation of the autoShareRecipient props.
return ['area', 'name'].every(prop => prop in container);
},
},
},
computed: {
containerValues() {
const { instanceId, component, access, area, name } =
this.container || {};
return {
instanceId,
component,
access,
area,
name,
};
},
},
};
| 26.45614 | 73 | 0.62931 |
ea87ec6a70bd1a1c4d14435499ff909738a5cece | 182 | js | JavaScript | src/containers/temp/index.js | LQDharmapala/tripitaka | 62fbd84d655f0f605634888f3ea4c876664bc40f | [
"MIT"
] | 3 | 2016-09-14T00:48:51.000Z | 2021-03-21T02:27:40.000Z | src/containers/temp/index.js | LQDharmapala/tripitaka | 62fbd84d655f0f605634888f3ea4c876664bc40f | [
"MIT"
] | null | null | null | src/containers/temp/index.js | LQDharmapala/tripitaka | 62fbd84d655f0f605634888f3ea4c876664bc40f | [
"MIT"
] | null | null | null | require('./index.css');
require('./index.less');
var pageHtml = require('./index.html');
module.exports = function () {
document.querySelector('.content').innerHTML = pageHtml;
} | 30.333333 | 60 | 0.681319 |