`;\ntableDome.innerHTML = theadHtml + tbodyHtml;\nconsole.log(theadHtml);\ndivDom.appendChild(tableDome);"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":779,"cells":{"blob_id":{"kind":"string","value":"e00b5ef5ec67f411f994979c63b36db06e2d92f3"},"language":{"kind":"string","value":"JavaScript"},"repo_name":{"kind":"string","value":"makkoli/wiki_viewer"},"path":{"kind":"string","value":"/wiki.js"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1090,"string":"1,090"},"score":{"kind":"number","value":3.203125,"string":"3.203125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"$(document).ready(function() {\n // Begin search for new item\n $(\"#container\").on('click', '.search', function() {\n getWikiPages();\n });\n});\n\n// Grabs the first 8 wikipedia titles and summaries using wikipedia api\n// @term: term to search wikipedia for\nfunction getWikiPages(term) {\n // Get the results from the search\n $.ajax({\n url: \"https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=\" + document.getElementById(\"query\").value + \"&namespace=0&limit=8&callback=?\",\n dataType: 'json',\n type: 'POST',\n success: function(data) {\n console.log(data);\n var list = \"\";\n\n // Construct the results list\n for (var i = 1; i < data[1].length; i++) {\n list += '
/*\
module-type: relinkfilteroperator
Given a title as an operand, returns all non-shadow tiddlers that have any
sort of updatable reference to it.
`relink:backreferences[]]`
`relink:references[]]`
Returns all tiddlers that reference `fromTiddler` somewhere inside them.
Input is ignored. Maybe it shouldn't do this.
\*/
var LinkedList = $tw.utils.LinkedList;
if (!LinkedList) {
/* If the linked list isn't available, make a quick crappy version. */
LinkedList = function() {this.array=[];};
LinkedList.prototype.pushTop = function(array) {
$tw.utils.pushTop(this.array, array);
};
LinkedList.prototype.toArray = function() {
return this.array;
};
};
exports.backreferences = function(source,operator,options) {
var results = new LinkedList();
source(function(tiddler,title) {
results.pushTop(Object.keys(options.wiki.getTiddlerRelinkBackreferences(title,options)));
});
return results.toArray();
};
exports.references = function(source,operator,options) {
var results = new LinkedList();
source(function(tiddler,title) {
var refs = options.wiki.getTiddlerRelinkReferences(title,options);
if (refs) {
results.pushTop(Object.keys(refs));
}
});
return results.toArray();
};
true
0ca95bde4ecd710566a065745cdf4f6b2aafd036
JavaScript
ryan-sherman/SDD-Preferate
/WebDocs/js/group.js
UTF-8
998
3.0625
3
[
"Apache-2.0",
"MIT"
]
permissive
//Javascript for make/edit group
$(document).ready(function(){
//localhost;8080/createGroup?owner_id=_&group_name=Hello&members=1-2-3
//when the user clicks create group
$("#CreateGroup").click(function(){
var friends = [];
$.each($("input[name='friend']:checked"), function(){
friends.push($(this).val());
});
//alert("My friends are: " + friends.join(", "));
friend_str = friends.join("-");
friend_str += "-" + user_id;
//make API call
var createURL = "http://localhost:8080/createGroup?owner_id=" + encodeURIComponent(user_id) +
"&group_name=" + encodeURIComponent($("#gname").val()) +
"&members=" + encodeURIComponent(friend_str);
$.ajax({
url: createURL
}).then(function(data, status, jqxhr){
console.log(data);
getGroups();
});
});
});
const content = "최수현의 포트폴리오"
const text = document.querySelector(".text")
let index = 0;
function typing(){
text.textContent += content[index++]
if(index > content.length){
text.textContent = ""
index = 0;
}
}
setInterval(typing, 500)
true
119be0bb70e69479ded6a72061cf4f60a6d7dee1
JavaScript
ATHULKNAIR/30-Days-0f-code-MySolutions
/Day-9-Recursions.js
UTF-8
167
3.90625
4
[]
no_license
function factorial(n){
var fact =1 ;
for(let i = n;i>0;i--){ // Get factorial of the number
fact = fact * i
}
return fact;
}
true
bfa076eff567840df4a12d6cca002ccfdb351d8f
JavaScript
mengyliu/turtle
/script.js
UTF-8
2,535
3.1875
3
[]
no_license
$(document).ready(function() {
console.log( "ready!" );
init()
});
var color = '#FF0000'
function init() {
var paint = true;
canvas = document.getElementById('canvas')
canvas.setAttribute("width", window.innerWidth * 0.8)
canvas.setAttribute("height", window.innerHeight * 0.8)
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
canvas.addEventListener("mouseover", function (e) {
if (paint) {
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw()
}
});
canvas.addEventListener("mousemove", function (e) {
if (paint) {
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw()
}
});
// on mobile phone
canvas.addEventListener("touchover", function (e) {
if (paint) {
prevX = currX;
prevY = currY;
currX = e.touches[0].clientX - canvas.offsetLeft;
currY = e.touches[0].clientY - canvas.offsetTop;
draw()
}
});
canvas.addEventListener("touchmove", function (e) {
if (paint) {
currX = e.touches[0].clientX - canvas.offsetLeft;
currY = e.touches[0].clientY - canvas.offsetTop;
draw()
}
});
document.addEventListener("keypress", function (e) {
switch (e.code) {
case "Space":
erase();
break;
case "KeyB":
color = "#0000FF";
break;
case "KeyG":
color = "#008000";
break;
case "KeyR":
color = "#FF0000";
break;
case "KeyY":
color = "#FFFF00";
break;
}
document.getElementById("picker").value = color;
});
document.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == '38') {
paint = false;
}
// down arrow
else if (e.keyCode == '40') {
paint = true;
}
}
document.getElementById('picker').addEventListener("input", function(e) {
color = this.value;
})
window.addEventListener("orientationchange", function() {
var w = screen.width;
var h = screen.height;
canvas.width = w*0.8;
canvas.height = h*0.8;
erase();
});
}
function draw() {
ctx.beginPath();
ctx.fillStyle = color;
ctx.rect(currX-15, currY-15, 30, 30);
ctx.fill();
}
function erase() {
ctx.clearRect(0, 0, w, h);
}
true
0974db050b632d1687f8ac21cfa13e0a5023443a
JavaScript
glomotion/tesseract-js
/test/notifications.js
UTF-8
2,185
2.84375
3
[
"MIT"
]
permissive
var tesseract = require('../src/Tesseract.js');
// Tests for listening to notifications.
function connectAndRun(test, body) {
test.expect(2);
tesseract.connect(null, function (err, client) {
test.equals(err, null);
body(client);
});
}
var insertInterval;
function fireInserts(client) {
insertInterval = setInterval(function () {
client.insert('people', {
'name': 'Joe Bloggs'
});
}, 100);
}
exports.testListenToAll = function(test) {
connectAndRun(test, function(client) {
var listener = client.listen('people')
.then(function (data) {
clearInterval(insertInterval);
listener.stop();
test.equals(JSON.stringify(data), '{"name":"Joe Bloggs"}');
test.done();
client.close();
});
fireInserts(client);
});
};
exports.testListenWithFilterThatMatches = function(test) {
connectAndRun(test, function(client) {
var listener = client.listen('people')
.where('name like "Joe %"')
.then(function (data) {
clearInterval(insertInterval);
listener.stop();
test.equals(JSON.stringify(data), '{"name":"Joe Bloggs"}');
test.done();
client.close();
});
fireInserts(client);
});
};
exports.testListenWithFilterThatDoesNotMatch = function (test) {
connectAndRun(test, function(client) {
function testDone() {
test.done();
client.close();
}
var listener = client.listen('people')
.where('name like "Bob %"')
.then(function (data) {
test.ok(false, "We didn't want to receive this notification.");
testDone();
});
fireInserts(client);
// With all the notifications firing 10 times a second, we shouldn't
// hear anything for a whole second.
setTimeout(function() {
clearInterval(insertInterval);
listener.stop();
test.ok(true);
testDone();
}, 1000);
});
};
true
86919046e69926f2d3372a2f6b1f5a6e55eec4d3
JavaScript
dennis/bombermanjs
/public/js/canvas_manager.js
UTF-8
463
2.765625
3
[
"MIT"
]
permissive
"use strict";
function CanvasManager() {
this.mapWidth = 0;
this.mapHeight = 0;
}
CanvasManager.prototype.init = function(canvasId, mapWidth, mapHeight) {
this.canvas = document.getElementById(canvasId);
if(this.canvas.getContext) {
this.context = this.canvas.getContext('2d');
this.canvas.width = this.mapWidth = mapWidth;
this.canvas.height = this.mapHeight = mapHeight;
}
else {
throw new "No canvas support for element " + canvasId;
}
};
true
299704dcba1602061edd878b2ffc9eea77248524
JavaScript
aleksanderbrymora/sei-36
/warmups/week10/day2/withInquirer.js
UTF-8
2,280
4.09375
4
[]
no_license
const inquirer = require('inquirer');
// Reverse a string
const revStr = (str) => {
// str.split('').reverse().join('');
let out = '';
for (let i = str.length - 1; i >= 0; i--) {
out += str[i];
}
return out;
};
// console.log('Reverse a string:', revStr('stuff'));
// Print odd numvers from 1 to 99
const odds = () => {
const out = [];
let i = 1;
while (i <= 99) {
out.push(i);
i += 2;
}
return out.join(', ');
};
// console.log('\nOdds:', odds());
// Largest in array
const largest = (arr) => arr.sort()[arr.length - 1];
// console.log('\nlargest in array:', largest([1, 2, 3, 89, 2, 6, 6, 4]));
const fib = (left, now = 1, last = 1) => {
if (left === 1 || left === 2) return now;
return fib(left - 1, now + last, now);
};
// console.log('\nfibonacci:', fib(6));
inquirer
.prompt([
{
name: 'yegge',
type: 'list',
message: 'Pick one',
choices: [
'Reverse a string',
'Print all the odds up to 99',
'Find the largest number in an array',
'Find nth Fibonnacci number',
'All of them',
],
},
])
.then(async (answer) => {
let res;
switch (answer.yegge) {
case 'Reverse a string':
res = await inquirer.prompt([
{
name: 'string',
type: 'input',
message: 'What string do you want to reverse',
},
]);
console.log('Reverse a string:', revStr(res.string));
break;
case 'Print all the odds up to 99':
console.log('\nOdds:', odds());
break;
case 'Find the largest number in an array':
res = await inquirer.prompt([
{
name: 'numbers',
type: 'input',
message: 'Type in numbers separated by a space',
},
]);
console.log('\nlargest in array:', largest(res.numbers.split(' ')));
break;
case 'Find nth Fibonnacci number':
res = await inquirer.prompt([
{
name: 'number',
type: 'number',
message: 'What number would you like to check',
},
]);
console.log('\nfibonacci:', fib(res.number));
break;
case 'All of them':
console.log('Reverse a string:', revStr('stuff'));
console.log('\nOdds:', odds());
console.log('\nlargest in array:', largest([1, 2, 3, 89, 2, 6, 6, 4]));
console.log('\nfibonacci:', fib(6));
break;
default:
break;
}
});
true
25c3d04c5f5a1f07c26dfda4b552fb14a3c829a2
JavaScript
holynova/algorithm
/速算24/getAllSolutions.js
UTF-8
346
3.21875
3
[]
no_license
const log = console.log.bind(console)
const Combinatorics = require('js-combinatorics');
function range(start = 1, end = 13) {
let arr = []
for (let i = start; i <= end; i++) {
arr.push(i)
}
return arr
}
log(range(1, 4))
let cmb = Combinatorics.combination(range(1, 13), 4)
log(cmb.toArray())
function getAll(start=1,end=13){
}
//7. Write a JS Program to get minimum of three numbers
function minOfThreeNums(a, b, c) {
console.log(a < b < c ? a : b < c ? b : c);
}
minOfThreeNums(1, 2, 3);
minOfThreeNums(1, 20, 3);
minOfThreeNums(-1, 12, 30);
minOfThreeNums(0, 0, 0);
true
4e524b41855b2f78aeca5fb1030cdafda70e46d3
JavaScript
Derlys/javascript1
/Curso JS Moderno - Fin/13-DOM/js/05-scripts.js
UTF-8
1,069
3.453125
3
[]
no_license
// en este video estaremos viendo querySelectorAll
// la buena noticia es que la sintaxis para selectores es la misma, es decir similar a CSS, con el punto para las classes y el numeral o signo de gato para los ID's, también puedes añadir un selector especifico..
// Pero la diferencia principal, es que querySelectorAll va a retornar todos los elementos que concuerden con el selector y no va a limitarte al primero como querySelector.
// En nuestro HTML hay muchos cards, cuando utilizamos querySelector vimos que retornaba unicamente el primero..
const cards = document.querySelectorAll('.card');
console.log(cards);
// si recuerdas tenemos dos elementos con el id de formulario
const formularios = document.querySelectorAll('#formulario');
console.log(formularios); // Puedes ver quue eso si funciona, sin embargo recuerda que no rescomendable tener el mismo ID más de una vez por docuemnto...
// Si no hay elementos no va a retornar nada
// Si un selector no existe,
const noExiste = document.querySelectorAll('#no-existe');
console.log(noExiste);
true
3e937fac92d9a551d691b908bf31616f40b63224
JavaScript
ilqarilyasov/typescript
/main.js
UTF-8
1,309
3.65625
4
[]
no_license
"use strict";
exports.__esModule = true;
var message = 'Welcome back!';
console.log(message);
var x = 10; // can be without init value
var y = 20; // always init value
var sum;
var title = 'Learn Typescript';
// boolean, number, string - primitive type
// Boolean, Number, String - object type
var isBeginner = true;
var total = 0;
var name = 'Bernie';
var sentence = "My name is " + name + ",\nI am a beginner in Typescript";
console.log(sentence);
var n = null;
var u = undefined;
var isNew = null;
var myName = undefined;
var list1 = [1, 2, 3];
var list2 = [1, 2, 3];
var person1 = ['Chris', 22]; // tuple
var Color;
(function (Color) {
Color[Color["Red"] = 5] = "Red";
Color[Color["Green"] = 6] = "Green";
Color[Color["Blue"] = 7] = "Blue";
})(Color || (Color = {}));
;
var c = Color.Green;
console.log(c);
// Any type. Compiler doesn't check its type until we access it
var randomValue = 10;
randomValue = true;
randomValue = 10;
randomValue = 'value';
// Typescript won't trow any errors
var myVariable = 10;
function hasName(obj) {
return !!obj &&
typeof obj === "object" &&
"name" in obj;
}
if (hasName(myVariable)) {
console.log(myVariable.name);
}
myVariable.toUpperCase; // Type assertion - casting
var a;
a = 10;
a = true;
var b = 20;
b = true;
console.log(b);
true
c3d18a7552aded779a895b9408b83ba9d64bc7fd
JavaScript
ManasviBendigeri/Compiler
/compiler.js
UTF-8
1,141
4.125
4
[]
no_license
//User input for calcution
let input = ['sum',200,200]
//Lexical Analysis
let operArr = []
let numberArr = []
//Tokenization
for(let i = input.length-1; i >=0;i--){
if(typeof input[i] === 'string'){
operArr.push(input[i])
}else{
numberArr.push(input[i])
}
};
//Intializing value
let value = 0
//Actions
switch(operArr[0]){
case 'sum':
if(operArr[0] === 'sum'){
for(let i = 0; i <= numberArr.length-1;i++){
value = numberArr[i] + value;
}
}
break;
case 'sub':
if(operArr[0] === 'sub'){
value = 0;
for(let i = 0; i <= numberArr.length-1;i++){
value = value - numberArr[i];
}
}
break;
case 'mul':
if(operArr[0] === 'mul'){
value = 1;
for(let i = 0; i <= numberArr.length-1;i++){
value = numberArr[i] * value;
}
}
break;
case 'div':
if(operArr[0] === 'div'){
value = 1;
for(let i = 0; i <= numberArr.length-1;i++){
value = numberArr[i] / value;
}
}
break;
}
//Results
console.log("Numbers: ", numberArr);
console.log("Operand: ", operArr);
console.log("Result:", value);
true
18c3bb3f1ca374fa3f3f0caffe84ae58122c0a1d
JavaScript
LearnChemE/LearnChemE.github.io
/lab-experiments/garage_door/src/js/svg/SVG.js
UTF-8
1,321
2.84375
3
[]
no_license
const SVGObject = require("./SVGObject");
/** Creates an SVG object for the <svg> element. */
class SVG extends SVGObject {
/**
* @constructor
* @param {object} options - Default options
* @property {element} parent - The SVGObject parent (default {element: document.body})
* @property {string} id - Id of the element
* @property {SVGobject[]} children - The child SVG objects of the group
* @property {string[]} classList - ["string", "string2", ...] List of classes for line. (default [])
* @property {number[]} viewBox - [0, 0, number, number2] Size of the viewbox (default [0, 0, 100, 100])
*/
constructor(options) {
super({ ...options, objectName: "svg" });
this.viewBox = options.viewBox ?? [0, 0, 100, 20];
this.element.setAttribute("xmlns", "http://www.w3.org/2000/svg");
this.element.setAttribute("viewBox", `${this.viewBox[0]} ${this.viewBox[1]} ${this.viewBox[2]} ${this.viewBox[3]}`);
}
/**
* Function to resize the viewbox
* @param {number} width - third value of viewbox
* @param {number} height - fourth value of viewbox
*/
resizeViewbox(width, height) {
this.viewBox = [ 0, 0, width, height ];
this.element.setAttribute("viewBox", `${this.viewBox[0]} ${this.viewBox[1]} ${this.viewBox[2]} ${this.viewBox[3]}`);
}
}
module.exports = SVG;
true
b424141858ed239abe31fe3ea5183a6fb33fe59f
JavaScript
jocelynlozano/calculadora
/app.js
UTF-8
2,977
3.90625
4
[]
no_license
{var opcion = parseInt(prompt("elija una de las siguientes opciones \n" +
"1. Calculadora Aritmetica \n" +
"2. Caluladora Relacional"));
switch(opcion){
case 1:
var opcionElegida1 = parseInt(prompt("ingrese la operacion deseada \n" +
"1. Suma \n" +
"2. Resta \n" +
"3. Multiplicacion \n" +
"4. Division \n" +
"5. Resto"));
switch (opcionElegida1){
case 1:
var num1 = parseInt(prompt("ingrese el numero 1"));
var num2 = parseInt(prompt("ingrese el numero 2"));
var suma = num1 + num2;
window.alert("la suma es:" + suma);
break;
case 2:
var num1 = parseInt(prompt ("ingrese el numero 1"));
var num2 = parseInt(prompt ("ingrese el numero 2"));
var resta = num1 + num2;
window.alert("la resta es:" + resta);
break;
case 3:
var num1 = parseInt(prompt ("ingrese el numero 1"));
var num2 = parseInt(prompt ("ingrese el numero 2"));
var multiplicacion = num1 * num2;
window.alert("el producto es:" + multiplicacion);
break;
case 4:
var num1 = parseInt(prompt ("ingrese el numero 1"));
var num2 = parseInt(prompt ("ingrese el numero 2"));
var cociente = num1 / num2;
window.alert("el cociente es:" + cociente);
break;
case 5:
var num1 = parseInt(prompt ("ingrese el numero 1"));
var num2 = parseInt(prompt ("ingrese el numero 2"));
var residuo = num1 / num2;
window.alert("el residuo es:" + residuo);
break;
default:
window.alert("no es una opcion valida");
break;
}
break;
case 2:
var opcionElegida2 = parseInt(prompt("ingrese la operacion deseada \n" +
"1. Menor que \n" +
"2. Mayor que \n" +
"3. Menor o igual que \n" +
"4. Mayor o igual que \n"));
switch(opcionElegida2){
case 1:
var num1 = parseInt(prompt("ingrese el numero 1"));
var num2 = parseInt(prompt("ingrese el numero 2"));
var menor = num1 < num2;
window.alert("El numero " + num1+ " es menor que " + num2+ " : " + menor);
break;
case 2:
var num1 = parseInt(prompt("ingrese el numero 1"));
var num2 = parseInt(prompt("ingrese el numero 2"));
var mayor = num1 > num2;
window.alert("El numero " + num1+ " es mayor que " + num2+ " : " +mayor);
break;
case 3:
var num1 = parseInt(prompt("ingrese el numero 1"));
var num2 = parseInt(prompt("ingrese el numero 2"));
var menorIgual = num1 <= num2;
window.alert("El numero " + num1+ " es menor o igual que " + num2+ " : " + menorIgual);
break;
case 4:
var num1 = parseInt(prompt("ingrese el numero 1"));
var num2 = parseInt(prompt("ingrese el numero 2"));
var mayorIgual = num1 >= num2;
window.alert("El numero " + num1+ " es mayor o igual que " + num2+ " : " +mayorIgual);
break;
default:
window.alert("no es una opción valida");
break;
}
break;
}
}
true
e3a425d028c6b09d108f0136bbcc0ce4c80b8d24
JavaScript
mrako/todo-nodejs-server
/app/routes.js
UTF-8
1,899
2.546875
3
[]
no_license
'use strict';
var Todo = require('./models/todo');
module.exports = function(app) {
// GET ALL ====================================================================
app.get('/api/todos', function(req, res) {
Todo.find(function(err, todos) {
if (err) {
res.send(err);
}
res.json(todos);
});
});
// FIND BY ID =================================================================
app.get('/api/todos/:todoId', function(req, res) {
Todo.findById(req.params.todoId ,function(err, todo) {
if (err) {
res.send(err);
}
res.json(todo);
});
});
// CREATE =====================================================================
app.post('/api/todos', function(req, res) {
Todo.create({
text : req.body.text,
done : false
}, function(err) {
if (err) {
res.send(err);
}
Todo.find(function(err, todos) {
if (err) {
res.send(err);
}
res.json(todos);
});
});
});
// UPDATE =====================================================================
app.put('/api/todos/:todoId', function(req, res) {
Todo.update({
_id: req.params.todoId
},{
text : req.body.text,
done : req.body.done
}, function(err) {
if (err) {
res.send(err);
}
Todo.find(function(err, todos) {
if (err) {
res.send(err);
}
res.json(todos);
});
});
});
// DELETE =====================================================================
app.delete('/api/todos/:todoId', function(req, res) {
Todo.remove({
_id : req.params.todoId
}, function(err) {
if (err) {
res.send(err);
}
Todo.find(function(err, todos) {
if (err) {
res.send(err);
}
res.json(todos);
});
});
});
};
true
7ec2ca4e4cdbd27d144ce26db3a520c217ad7941
JavaScript
codingbits/MindMap
/es6/structs/AbstractGraph.js
UTF-8
4,078
3.046875
3
[
"MIT"
]
permissive
"use strict";
load.provide("mm.structs.emptyGraph", (function() {
/** Just a simple, emtpy graph
*
* For use when a graph is needed, but none is provided.
* @type object
*/
return {
"version":1,
"nodes":[],
"edges":[],
"canvas":{
"height":200,
"width":200,
}
};
}));
load.provide("mm.structs.AbstractGraph", (function() {
let TypesFile = load.require("mm.structs.TypesFile");
let ObjectsData = load.require("mm.structs.ObjectsData");
let getfile = load.require("mm.utils.getfile");
let emptyGraph = load.require("mm.structs.emptyGraph");
/** This represents a graph. */
return class AbstractGraph {
constructor(objectsUrl, typesUrl) {
/** True if this object is ready for use (that is, the files have been downloaded)
*
* @type boolean
*/
this.ready = false;
/** When downloaded, the types file object.
*
* @type mm.structs.TypesFile
* @private
*/
this.types = null;
/** When downloaded, the objects data object.
*
* @type mm.structs.ObjectsData
* @private
*/
this.objects = null;
/** The url of the types file
* @type string
* @private
*/
this._typesUrl = typesUrl;
/** The url of the objects file
* @type string
* @private
*/
this._objectsUrl = objectsUrl;
}
/** Downloads the data from the files passed in the constructor
*
* @async
*/
async load() {
// If it is an object, return it. If it is a string, JSON.parse it.
let jsonMaybe = function(o) {
if(typeof o === "string") return JSON.parse(o);
return o;
}
if(this._objectsUrl) {
// We have an objects file to download
return Promise.all([
getfile(this._typesUrl),
getfile(this._objectsUrl)
]).then((contents) => {
this.types = new TypesFile(jsonMaybe(contents[0]));
this.objects =
new ObjectsData(jsonMaybe(contents[1]), this.types);
this.ready = true;
});
}else{
// We only have a types file
let typesf = await getfile(this._typesUrl);
this.types = new TypesFile(jsonMaybe(typesf));
this.objects = new ObjectsData(emptyGraph, this.types);
this.ready = true;
}
}
/** Deletes the node with the given id, and any edges that happen to link it.
*
* Then returns a special object that can be used to recover them.
*
* You can either specify one node, or multiple nodes. If specifying multiple, they all get deleted.
*
* @param {int|node|array<node>} id The node(s) to delete.
* @return {object} A recovery object
*/
cascadingRemoveNode(nodes) {
// Object used to recover
let recovery = {edges:[], nodes:[]};
// Make sure the input is an array of node ids, rather than anything else
if(!Array.isArray(nodes)) nodes = [nodes];
nodes = nodes.map((x) => typeof(x) == "number" ? x : x.id);
// And loop through them
for(let n of nodes) {
// Make sure to delete and collect the edges as well
let edges = this.objects.getEdgesConnectedToNode(n);
recovery.edges = recovery.edges.concat(edges.map((e) => e.toJson()));
edges.forEach((e) => this.objects.removeEdge(e.id));
let node = this.objects.getNode(n);
recovery.nodes.push(node.toJson());
this.objects.removeNode(n);
}
return recovery;
}
/** Recovers the nodes and edges deleted by cascadingRemoveNode
*
* @param {object} recover The recovery object.
*/
cascadingRemoveNodeRecovery(recover) {
for(let n of recover.nodes) {
this.objects.insertNode(n);
}
for(let e of recover.edges) {
this.objects.insertEdge(e);
}
}
/** Returns an array of links where both ends are connected to a node in the given set.
*
* @param {array<mm.structs.ObjectNode>} nodes The set of nodes to find edges for.
* @return {array<mm.structs.ObjectEdge>} All edges connected between any nodes.
*/
connectedEdges(nodes) {
return this.objects.edges.filter((e) =>
nodes.some((n) => e.origin == n.id) && nodes.some((n) => e.dest == n.id)
);
}
};
}));
true
7446a88555d8fa8bd7e066cbce9f55c7d7914d3f
JavaScript
drewthedev9-tech/API-server
/server.js
UTF-8
1,949
2.609375
3
[]
no_license
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require ('knex');
const register = require('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');
// connecting to database:
const db = knex({
client: 'pg',
connection: {
connectionString : process.env.DATABASE_URL,
ssl: true
}
});
// usual format knex.select('title', 'author', 'year').from('books')
db.select('*').from ('users').then(data =>{
console.log(data);
});
const app = express();
// nodyParser is a middleware
// req.body is getting things from the body of HTML and and parsing, also in JSON format.
app.use(bodyParser.json());
// cors is middle ware for connecting API to front end security.
app.use(cors());
// get request to see if front end is talking to server.
app.get('/', (req, res)=>{
// respnding with the user database after they are updated.
res.send('it is working')
})
//sign -- POST successful/fail.
// sign in to handle the sign inswith the database above.
app.post('/signin', (req, res)=> {signin.handleSignin(req, res,db, bcrypt)})
// register --> POST = user.
// registering to a new user so adding to the database.
// register function is in teh controllers file pushing these parameters to to the
// function.
app.post('/register', (req, res)=>{register.handleRegister(req, res,db, bcrypt)})
// matching id endpoint to get user.
app.get('/profile/:id', (req, res)=>{profile.handelProfileGet(req, res,db)})
// increse their entries count
app.put('/image',(req,res)=> {image.handleImage(req,res,db)})
app.post('/imageUrl',(req,res)=> {image.handleApiCall(req,res)})
app.listen (process.env.PORT || 3000, ()=> {
console.log(`app is running on port ${process.env.PORT}`)
})
var c1 = document.querySelector(".c1");
var c2 = document.querySelector(".c2");
var css= document.querySelector("h3");
var body= document.getElementById("gradient");
var buttonl = document.getElementById("buttonl");
var buttonr = document.getElementById("buttonr");
function bgchange(){
body.style.background= "radial-gradient( " + c1.value +","+c2.value+")";
css.textContent = body.style.background + ";";
}
function linear() {
body.style.background= "linear-gradient(to right, " + c1.value +","+c2.value+")";
css.textContent = body.style.background + ";";
}
c1.addEventListener("input", bgchange);
c2.addEventListener("input", bgchange);
buttonl.addEventListener("click", linear);
buttonr.addEventListener("click", bgchange);
true
2f4b61e44f598855a2589f2aecf3e2abac4550b4
JavaScript
HuyckS/C-.NET-Core
/algos/day4.js
UTF-8
3,414
4.40625
4
[]
no_license
class Queue {
constructor() {
this.values = [];
}
/**
* Adds a value and returns the new size.
*
* @param {any} val
* @returns {number} the new size
*/
enqueue(val) {
this.values.push(val);
return this.values.length;
}
/**
* @returns {any} the removed (front) value
*/
dequeue() {
return this.values.shift();
}
/**
* @returns {boolean}
*/
isEmpty() {
return this.values.length === 0;
}
/**
* @returns {number}
*/
size() {
return this.values.length;
}
/**
* Determines whether the first half's sum equals the second half's sum
* DO NOT manually index the queue items,
* only use the provided queue methods,
* use no additional arrays or objects for storage
* Restore the queue to its original state.
*
* @returns {boolean}
*/
sumOfHalvesEqual() {
// your code here
}
}
const queue = new Queue();
queue.enqueue(1);
// 1
queue.enqueue(2);
// 1 - 2
queue.enqueue(3);
// 1 - 2 - 3
queue.enqueue(3);
// 1 - 2 - 3 - 3
queue.enqueue(2);
// 1 - 2 - 3 - 3 - 2
queue.enqueue(1);
// 1 - 2 - 3 - 3 - 2 - 1
console.log(queue.sumOfHalvesEqual());
// should log true (6 and 6)
class Stack {
constructor() {
this.values = [];
}
/**
* Adds a new value to the top.
*
* @param {any} val the value to add
* @returns {number} the new size of the stack
*/
push(val) {
this.values.push(val);
return this.size();
}
/**
* Removes and returns the top value.
*
* @returns {any} the removed top value
*/
pop() {
return this.values.pop();
}
/**
* Returns whether the stack is empty.
*
* @returns {boolean}
*/
isEmpty() {
return this.size() === 0;
}
/**
* @returns {number} the number of items in the stack
*/
size() {
return this.values.length;
}
/**
* Returns, but doesn't remove, the top value.
*
* @returns {any} the top value
*/
peek() {
return this.size() === 0
? null
: this.values.slice(-1)[0];
}
}
class QueueWithStacks {
constructor() {
this.stack1 = new Stack();
this.stack2 = new Stack();
}
/**
* Adds a value and returns the new size of the queue
* Only use the two stacks and their methods
* How do you make a FIFO (First In First Out) structure from
* two LIFO (Last In First Out) structures?
*
* @param {any} val the value to add
* @returns {number} the new size of the queue
*/
enqueue(val) {
// your code here
}
/**
* Removes the value at the front of the queue
* Only use the two stacks and their methods
*
* @returns {any} the front value or null if empty
*/
dequeue() {
// your code here
}
}
const stacksQueue = new QueueWithStacks();
console.log(stacksQueue.enqueue('a')); // should log 1
// a
console.log(stacksQueue.enqueue('b')); // should log 2
// a - b
console.log(stacksQueue.enqueue('c')); // should log 3
// a - b - c
console.log(stacksQueue.dequeue()); // should log 'a'
// b - c
console.log(stacksQueue.dequeue()); // should log 'b'
// c
console.log(stacksQueue.dequeue()); // should log 'c'
// empty
// EXTRA: NextQueue
// Design a Queue class that automatically sends every 3rd dequeued person object to a next queue that can be specified
// Imagine a security queue where every 3rd person is randomly sent to an additional security queue
true
f79ec9864879e51d174bf074808b9a77e511b27a
JavaScript
timcritt/updated-learn-redux
/src/index.js
UTF-8
2,103
2.859375
3
[]
no_license
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
//import App from './App';
import * as serviceWorker from './serviceWorker';
import { Provider, connect } from 'react-redux';
//redux imports
import {createStore } from 'redux';
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
//REDUX FROM HERE DOWN
//reducer: A pure function that accepts 2 parameters: state and action.
const countReducer = function ( state = 0, action) {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state -1;
case "RESET":
return 0;
default:
return state;
}
};
//store: holds the state for the whole application
let store = createStore(countReducer);
//map state to props
const mapStateToProps = state => {
return {
count: state
};
};
// Map actions (dispatches) to props
const mapDispatchToProps = dispatch => {
return {
handleIncrementClick: () => dispatch({type: 'INCREMENT'}),
handleDecrementClick: () => dispatch({type: 'DECREMENT'}),
handleResetClick: () => dispatch({type: 'RESET'})
}
}
//a react, presentational (aka dumb) component (presentational means isn't directly connected to store)
const Component = ({count, handleIncrementClick, handleDecrementClick, handleResetClick}) => (
<div>
<h1>HelloWorld React and Redux {count}</h1>
<button onClick={handleDecrementClick}>Decrement</button>
<button onClick={handleIncrementClick}>Increment</button>
<button onClick={handleResetClick}>Reset</button>
</div>
);
//smart components have the state connected to them with connect
const Container = connect(mapStateToProps, mapDispatchToProps)(Component);
//provider supplies the component tree with the global state
const App = () => (
<Provider store={store}>
<Container></Container>
</Provider>
);
ReactDOM.render(<App />, document.getElementById('root'));
true
9e16c0bdb797e382d5ed28e904a5d6b0a56317da
JavaScript
kporcelainluv/100_days_of_JS
/avgAlth.js
UTF-8
580
3.171875
3
[]
no_license
function orbitalPeriod(arr) {
let getOrbPeriod = obj => {
var GM = 398600.4418;
var earthRadius = 6367.4447;
let avgAlth = obj["avgAlt"];
let pi = Math.PI;
let res = 2 * pi * Math.sqrt((earthRadius + avgAlth) ** 3 / GM);
delete obj["avgAlt"];
obj["orbitalPeriod"] = Math.round(res);
return obj;
};
for (var index in arr) {
arr[index] = getOrbPeriod(arr[index]);
}
return arr;
}
console.log(
orbitalPeriod([
{ name: "iss", avgAlt: 413.6 },
{ name: "hubble", avgAlt: 556.7 },
{ name: "moon", avgAlt: 378632.553 }
])
);
true
5cf4f732a0c74edbc40d118db1e35b88eba954b8
JavaScript
O-Liruk/JS
/homework_17/script.js
UTF-8
2,990
3.328125
3
[]
no_license
'use strict';
const TODOS_URL = 'https://jsonplaceholder.typicode.com/todos/';
const DONE_CLASS = 'done';
const DELETE_BTN_CLASS = 'delete-btn';
const TASK_ITEM_CLASS = 'task-item';
const TASK_ITEM_SELECTOR = '.' + TASK_ITEM_CLASS;
const taskInput = document.getElementById('taskNameInput');
const taskTemplate = document.getElementById('newTaskTemplate').innerHTML;
const listEl = document.getElementById('taskList');
let todoList = [];
// document.getElementById('newTaskForm').addEventListener('submit', onFormSubmit);
listEl.addEventListener('click', onListClick);
init();
function init() {
fetchTodos ()
}
function onListClick(e) {
const taskEl = getTaskElement(e.target);
switch (true) {
case e.target.classList.contains(DELETE_BTN_CLASS):
return deleteTask(+taskEl.dataset.id);
case e.target.classList.contains(TASK_ITEM_CLASS):
return toggleTodo(+taskEl.dataset.id);
}
}
function getTaskElement(el) {
return el.closest(TASK_ITEM_SELECTOR);
}
function fetchTodos () {
fetch(TODOS_URL)
.then((res) => res.json())
.then(setTodos)
.then(renderTodos)
}
function setTodos(list){
return todoList = list
}
function renderTodos(list) {
const html = list.map(getTodoHtml).join('')
listEl.innerHTML = html
}
function getTodoHtml (todo) {
return taskTemplate
.replace('{{doneClass}}', todo.completed ? DONE_CLASS :'')
.replace('{{text}}', todo.title)
.replace('{{id}}', todo.id)
}
function deleteTask(todoId) {
const todo = todoList.findIndex((todo) => todo.id === todoId)
todoList.splice(todo, 1)
renderTodos(todoList)
}
function toggleTodo(todoId) {
const todo = todoList.find((todo) => todo.id === todoId)
todo.completed = !todo.completed
renderTodos(todoList)
}
// function onFormSubmit(e) {
// e.preventDefault();
// const title = taskInput.value;
// if (isValid(title)) {
// addNewTask(title);
// clearInput();
// } else {
// alert('task is invalid');
// }
// }
// function onListClick(e) {
// const taskEl = getTaskElement(e.target);
// switch (true) {
// case e.target.classList.contains(DELETE_BTN_CLASS):
// return deleteTask(taskEl);
// case e.target.classList.contains(TASK_ITEM_CLASS):
// return toggleTask(taskEl);
// }
// }
// function isValid(text) {
// return !!text;
// }
// function addNewTask(title) {
// const newTaskHtml = getTaskHtml(title);
// listEl.insertAdjacentHTML('beforeend', newTaskHtml);
// }
// function getTaskHtml(title) {
// return taskTemplate.replace('{{text}}', title);
// }
// function clearInput() {
// taskInput.value = '';
// }
// function getTaskElement(el) {
// return el.closest(TASK_ITEM_SELECTOR);
// }
// function toggleTask(el) {
// el.classList.toggle(DONE_CLASS);
// }
// function deleteTask(el) {
// el.remove();
// }
/* eslint-disable no-alert */
import Big from "big.js";
import operate from "./operar";
import isNumber from "./isNumber";
export default function calculate(obj, buttonName) {
Big.DP = 7;
if (buttonName === "AC") {
return {
total: null,
siguiente: null,
operacion: null,
};
}
if (isNumber(buttonName)) {
if (buttonName === "0" && obj.siguiente === "0") {
return {};
}
if (obj.operacion) {
if (obj.siguiente) {
if(obj.siguiente.length < 9){
return { siguiente: obj.siguiente + buttonName };
}
alert("Error numero maximo de digitos sobrepasado");
}
return { siguiente: buttonName };
}
if (obj.siguiente) {
if(obj.siguiente.length < 9){
const siguiente = obj.siguiente === "0" ? buttonName : obj.siguiente + buttonName;
return {
siguiente,
total: null,
};
}
alert("Error numero maximo de digitos sobrepasado");
}
return {
siguiente: buttonName,
total: null,
};
}
if (buttonName === "%") {
if (obj.operacion && obj.siguiente) {
const result = operate(obj.total, obj.siguiente, obj.operacion);
return {
total: Big(result)
.div(Big("100"))
.toString(),
siguiente: null,
operacion: null,
};
}
if (obj.siguiente) {
return {
siguiente: Big(obj.siguiente)
.div(Big("100"))
.toString(),
};
}
return {};
}
if (buttonName === ".") {
if (obj.siguiente) {
if (obj.siguiente.includes(".")) {
return {};
}
return { siguiente: `${obj.siguiente }.` };
}
return { siguiente: "0." };
}
if (buttonName === "=") {
if (obj.siguiente && obj.operacion) {
return {
total: operate(obj.total, obj.siguiente, obj.operacion),
siguiente: null,
operacion: null,
};
}
return {};
}
if (buttonName === "+/-") {
if (obj.siguiente) {
return { siguiente: (-1 * parseFloat(obj.siguiente)).toString() };
}
if (obj.total) {
return { total: (-1 * parseFloat(obj.total)).toString() };
}
return {};
}
if (obj.operacion) {
return {
total: operate(obj.total, obj.siguiente, obj.operacion),
siguiente: null,
operacion: buttonName,
};
}
if (!obj.siguiente) {
return { operacion: buttonName };
}
return {
total: obj.siguiente,
siguiente: null,
operacion: buttonName,
};
}
true
79b46651685bad27c0c80aedbe8cb74cd64ce5a2
JavaScript
YehorZapara/Ucode
/Sprint_04/ezapara/t01_elements/js/script.js
UTF-8
714
2.921875
3
[]
no_license
let li = document.getElementsByTagName('li');
for (let i = 0; i < li.length; i++) {
if (li[i].className !== 'good' && li[i].className !== 'evil' && li[i].className !== 'unknown') {
li[i].className = 'unknown';
}
if (!li[i].hasAttribute('data-element')) {
li[i].setAttribute('data-element', 'none');
}
let data = li[i].getAttribute('data-element').split(' ');
li[i].insertAdjacentHTML('beforeend', '<br/>');
data.forEach(function (el) {
if (el.length > 0) {
li[i].insertAdjacentHTML('beforeend', '<div class="elem ' + el + '">'
+ (el === 'none' ? '<div class="line"></div>' : ' ')
+ '</div>');
}
});
}
true
4ef3354ad704f2707e312b6abbba516a38be324a
JavaScript
Mitch-Kenward/Lotide
/test/tailTest.js
UTF-8
770
3.453125
3
[]
no_license
const { assert } = require("chai");
const tail = require("../tail");
describe("#tail", () => {
const words = ["bright", "Lighthouse", "Labs"];
it("returns 3 for words.length", () => {
assert.strictEqual((words.length), 3);
});
it("returns 2 for tail(words).length", () => {
assert.strictEqual(tail(words).length, 2);
});
it("returns ['Lighthouse', 'Labs'] for tail(words)", () => {
assert.deepEqual(tail(words), ['Lighthouse', 'Labs']);
});
});
//const result = tail(["Hello", "Lighthouse", "Labs"]);
//assertEqual(result.length, 2); // ensure we get back two elements
//assertEqual(result[0], "Lighthouse"); // ensure first element is "Lighthouse"
//assertEqual(result[1], "Labs"); // ensure second element is "Labs"
module.exports = tail;
true
efc99910f82b0a645883948f829e161d56464546
JavaScript
Subhadeep-sm/bmi-calculator
/js/bmi.js
UTF-8
2,216
3.609375
4
[]
no_license
function weightunit(){
if (document.getElementById('weight-unit').value == "Pounds"){
let x = parseFloat(document.getElementById('weight').value);
document.getElementById('weight').value= 0.45359237 * x;
}
else{
let x = parseFloat(document.getElementById('weight').value);
}
}
function heightunit(){
if (document.getElementById('height-unit').value == "Centimeters"){
let x = parseFloat(document.getElementById('height').value);
document.getElementById('height').value= 0.01 * x ;
}
if (document.getElementById('height-unit').value == "Feet"){
let x = parseFloat(document.getElementById('height').value);
document.getElementById('height').value= 0.3048 * x ;
}
if (document.getElementById('height-unit').value == "Inches"){
let x = parseFloat(document.getElementById('height').value);
document.getElementById('height').value= 0.0254 * x ;
}
else{
let x = parseFloat(document.getElementById('height').value);
document.getElementById('height').value= x ;
}
}
function bmi(){
let weight= parseFloat(document.getElementById('weight').value);
let height= parseFloat(document.getElementById('height').value);
let bmi= weight/ height**2 ;
document.getElementById('result').style.visibility = "visible";
document.getElementById('weight').value=null;
document.getElementById('height').value=null;
if (bmi.toFixed(1) < 18.5){
document.getElementById('result').innerHTML= "BMI : " + bmi.toFixed(1) + " (Underweight)";
}
if (bmi.toFixed(1) >= 18.5 && bmi.toFixed(1) <= 25){
document.getElementById('result').innerHTML= "BMI : " + bmi.toFixed(1) + " (Normal)";
}
if (bmi.toFixed(1) > 25){
document.getElementById('result').innerHTML= "BMI : " + bmi.toFixed(1) + " (Overweight)";
}
else{
document.getElementById('result').innerHTML= "-No Input-" ;
}
}
function allclear(){
document.getElementById('weight').value=null;
document.getElementById('height').value=null;
document.getElementById('result').innerHTML= null;
document.getElementById('result').style.visibility = "hidden";
}
true
6b1e2c2e6c877b281efac46d7a9e5e2ef1169283
JavaScript
fullmontis/fullmontis.github.io
/monster-girl-diaries/menu.js
UTF-8
1,700
3.375
3
[]
no_license
"use strict";
var stories = document.getElementsByClassName("story");
var story_buttons = document.getElementsByClassName("monster-button");
var story_close = document.getElementById("button-close");
var story_close_container = document.getElementsByClassName("button-close-container")[0];
function jump_to( id ) {
window.location.href="#" + id;
}
// open button callback
function open_story( id ) {
return function () {
story_id = id;
story_elems[id].button.classList.add("hidden");
story_elems[id].story.classList.remove("hidden");
story_close_container.classList.remove("hidden");
};
}
// create events for each button
var story_elems = {};
for( var i=0; i < story_buttons.length; i++ ) {
var b = story_buttons[i];
if( b.id != "button-close" ) {
var story_name = b.dataset.monster;
story_elems[story_name] = {};
story_elems[story_name].button = b;
b.addEventListener("click", open_story(story_name));
}
}
for( var i=0; i < stories.length; i++ ) {
var s = stories[i];
var story_name = s.dataset.monster;
story_elems[story_name].story = s;
s.classList.add("hidden");
}
// close button
var story_id = "index";
function close_all() {
for( var monster in story_elems ) {
var e = story_elems[monster];
e.story.classList.add("hidden");
e.button.classList.remove("hidden");
}
story_close_container.classList.add("hidden");
jump_to(story_id);
}
story_close.addEventListener( "click", close_all);
story_close_container.classList.add("hidden");
// create index
function capitalize( string ) {
return string[0].toUpperCase() + string.slice(1);
}
/**
* Created by chongrui on 2014/9/25 0025.
*/
$(document).ready(function (){
// Initially has 10 bombs and 8*8 table
var bombSize = 10;
var row = 8;
var col = 8;
buildBoard(row,col);
setBomb(row,col,bombSize);
myEvent(row,col,bombSize);
// if GameOptions are reset, will invoke step 1,2,3 again
setGameOptions(row, col, bombSize);
});
function checkAB(num) {
var A, B;
for (let i = 0; i < num.length; i++) {
if (num[i] === 'a') {
A = i;
} else if (num[i] === 'b') {
B = i;
}
var jarak = Math.abs(B - A) - 1;
}
if (jarak === 3) {
return true;
} else {
return false;
}
}
// TEST CASES
console.log(checkAB('lane borrowed')); // true
console.log(checkAB('i am sick')); // false
console.log(checkAB('you are boring')); // true
console.log(checkAB('barbarian')); // true
console.log(checkAB('bacon and meat')); // false
true
01010a58049fdb9b7b9789358b7057ccf98e1f07
JavaScript
andogq/rts
/server.js
UTF-8
5,813
2.59375
3
[]
no_license
// Imports
const http = require("http");
const url = require("url");
const fs = require("fs");
class Server {
constructor(port, staticDir) {
this.port = port == undefined ? 8000 : port;
this.staticDir = staticDir == undefined ? "static" : staticDir;
this.server = http.createServer(this.incomingRequest.bind(this));
this.functions = {};
}
start() {
return new Promise((resolve, reject) => {
console.log(`Searching for static files in directory ${this.staticDir}`);
this.findStaticFiles().then(() => {
console.log(`Starting server on port ${this.port}`);
this.server.listen(this.port);
}).catch((err) => {
reject(err);
});
});
}
findFiles(directory) {
return new Promise((resolve, reject) => {
fs.readdir(directory, {withFileTypes: true}, (err, contents) => {
if (err) reject(err);
let files = [];
let promises = [];
// Go through all the returned files
contents.forEach((file) => {
let fileName = `${directory}/${file.name}`
// Add it to the list if it's a normal file
if (file.isFile()) files.push(fileName);
// If it's a directory search it for files
else if (file.isDirectory()) promises.push(this.findFiles(fileName));
});
// If there's directories being searched
if (promises.length > 0) {
promises.forEach((promise) => {
// For new files in each directory
promise.then((newFiles) => {
files = files.concat(newFiles.files);
});
});
Promise.all(promises).then(() => {
resolve({files: files, dir: directory});
});
}
else resolve({files: files, dir: directory});
});
});
}
findStaticFiles() {
return new Promise((resolve, reject) => {
this.findFiles(this.staticDir).then(({files}) => {
// Remove static directory from start of string
this.staticFiles = files.map((file) => {
return file.replace(/^[^\s/\\]+\/(.+)$/, "$1");
});
resolve();
}).catch(reject);
});
}
// Adds a function to an end point
addFunction(name, func) {
this.functions[name] = func;
}
incomingRequest(request, response) {
request.url = url.parse(request.url);
request.url.pathname = request.url.pathname == "/" ? "index.html" : request.url.pathname.slice(1);
// Promise allows asynchronous actions to take place and response to be sent in one place
new Promise((resolve, reject) => {
if (this.staticFiles.indexOf(request.url.pathname) > -1) {
// Static file requested
fs.readFile(`${this.staticDir}/${request.url.pathname}`, (err, file) => {
if (err) reject(err);
let fileType = request.url.pathname.match(/^.+?\.([\w\d]+)$/)[1];
let contentType;
switch (fileType) {
case "ttf":
contentType = "font/ttf";
break;
case "jpg":
case "jpeg":
contentType = "image/jpeg";
break;
case "svg":
contentType = "image/svg+xml";
break;
case "js":
contentType = "text/javascript";
break;
default:
contentType = `text/${fileType}`;
break;
}
fileType = fileType == "js" ? "javascript" : fileType;
resolve({statusCode: 200, data: file, headers: {"Content-Type": contentType}});
});
} else if (Object.keys(this.functions).indexOf(request.url.pathname) > -1) {
this.functions[request.url.pathname](request).then(resolve);
} else {
// 404
resolve({statusCode: 404});
}
}).then(({statusCode, data, cookies, headers}) => {
// Send response
console.log(`${statusCode}: ${request.url.path}`);
response.statusCode = statusCode;
// Adds any cookies that need to be added
if (cookies != undefined) {
let cookieArray = []
for (let cookie of cookies) {
let expireString = cookie.expires != undefined ? `expires=${cookie.expires}` : "";
cookieArray.push(`${cookie.name}=${cookie.value}; ${expireString}`);
}
response.setHeader("Set-Cookie", cookieArray);
}
// Add any other headers
if (headers != undefined) {
Object.keys(headers).forEach((header) => {
response.setHeader(header, headers[header]);
});
}
response.end(data);
}).catch((err) => {
throw err;
});
}
}
module.exports = Server;
true
7a0e0101755df1b0be6770b4acde82647bbda7df
JavaScript
YuryRegis/StarKid
/comandos/tags.js
UTF-8
5,477
2.734375
3
[]
no_license
const { MessageEmbed } = require("discord.js");
const getID = require('../funcoes/ids.json');
const { promptMessage } = require("../funcoes.js");
const { verificaPerm } = require('../funcoes/members');
const opcoes = [`👤`,`👥`,`👑`,`🤠`,`🎹`,`🎨`,`🔰`,`🗺️`,`🧢`,`🧚`,`🤳`,`🎒`,`❤️`,`💍`,`💍`,`😄`,`💋`, `💙`,`🧓`,`🃏`]
exports.help = {
name: "tags"
}
exports.run = async (client, message, args) => {
const flood = client.channels.cache.get(getID.sala.FLOOD),
salaLogs = client.channels.cache.get(getID.sala.LOGS);
const perm = await verificaPerm(message.member);
if(message.channel.id != flood.id && !perm){
return message.channel.send(`Este comando não é permitido nesse canal.
Use o canal ${flood} , por gentileza.`)
}
const embed = new MessageEmbed();
embed.setTitle("**ThatSkyGameBrasil - TAGS**");
embed.setColor("RANDOM");
embed.setThumbnail("https://image.freepik.com/vetores-gratis/tag-neon-verde-noite-brilhante-elemento-de-propaganda_1262-13490.jpg");
embed.setFooter(message.guild.me.displayName, client.user.displayAvatarURL);
embed.setDescription("Escolha **uma** TAG clicando na reação correspondente:\n")
embed.addField("**Tags Customizáveis**","👤 - Jogador Solo \n👥 - Formador de grupos \n" +
"👑 - Colecionador \n🤠 - Explorador \n🎹 - Músico Skyniano \n🎨 - Desenhista / Pintor \n" +
"🔰 - Veterano \n🗺️ - Guia Turístico \n🧢 - Turista \n🧚 - Ajudante \n🎒 - Carregado \n" +
"❤️ - Trocador \n🤳 - YouTuber\n💍 - Casado\n😄 - Solteiro\n💋 - Namorando\n💙 - Capa azul\n"+
"🧓 - Elder \n🃏 - UNO")
embed.setTimestamp();
//Envia mensagem richEmbed
const m = await message.channel.send(embed);
//Adiciona reações e aguarda 30 segundos por uma escolha do usuário
const cargoEscolhido = await promptMessage(m, message.author, 30, opcoes);
if (cargoEscolhido === `👤`) {
var chave = "Jogador Solo"
} else if (cargoEscolhido === `👥`) {
var chave = "Formador de Grupos"
} else if (cargoEscolhido === `👑`) {
var chave = "Colecionador"
} else if (cargoEscolhido === `🤠`) {
var chave = "Explorador"
} else if (cargoEscolhido === `🤠`) {
var chave = "Músico Skyniano"
} else if (cargoEscolhido === `🎨`) {
var chave = "Desenhista / Pintor"
} else if (cargoEscolhido === `🔰`) {
var chave = "Veterano"
} else if (cargoEscolhido === `🗺️`) {
var chave = "Guia Turístico"
} else if (cargoEscolhido === `🧢`) {
var chave = "Turista"
} else if (cargoEscolhido === `🧚`) {
var chave = "Ajudante"
} else if (cargoEscolhido === `🎒`) {
var chave = "Carregado"
} else if (cargoEscolhido === `❤️`) {
var chave = "Trocador"
} else if (cargoEscolhido === `🤳`) {
var chave = "🚩 🆈🅾🆄🆃🆄🅱🅴🆁"
} else if (cargoEscolhido === "💍") {
var chave = "Casado"
} else if (cargoEscolhido === "😄") {
var chave = "Solteiro"
} else if (cargoEscolhido === "💋") {
var chave = "Namorando"
} else if (cargoEscolhido === "💙") {
var chave = "Capa azul"
} else if (cargoEscolhido === `🧓`) {
var chave = "Elder"
} else if (cargoEscolhido === `🃏`) {
var chave = "UNO"
}
else {
embed.addField("**TAG NÃO DEFINIDA**",`Use o comando \`!tags\` novamente.`);
m.edit(embed);
message.delete();
return m.delete(15000)
}; // retorna nada para caso de emoji diferente
var cargo = await message.guild.roles.cache.find(role => role.name.toLowerCase() === chave.toLowerCase());
var member = await message.guild.members.cache.find(member => member.id === message.author.id);
if (cargo == null) { // Caso não exista o cargo com o valor de chave passado
embed.addField(`TAG ${chave.toUpperCase()} NÃO ENCONTRADA`)
m.edit(embed)
message.delete()
return m.delete(15000)
}
// se o membro ja tiver o cargo selecionado, apague o mesmo
if (member.roles.cache.some(x => x.name === cargo.name)) {
member.roles.remove(cargo.id)
.then(member => {
console.log(`${member.user.username} removeu o cargo ${cargo.name}`);
salaLogs.send(`${member.displayName} removeu o cargo ${cargo.name}`);
})
.catch(err => console.log(err));
embed.addField("**\nREMOVIDO**",
`${member.user.username} removeu o cargo ${cargo.name}\n` +
`Use o comando \`!cargo\` novamente para adicionar ou remover outro cargo.`);
} else { // caso contrario, adicione cargo selecionado
member.roles.add(cargo.id)
.then(member => {
var nome = member.user.username;
console.log(`${nome} adicionou o cargo ${chave}`);
salaLogs.send(`${nome} adicionou o cargo ${chave}`);
})
.catch(err => console.error);
embed.addField("**\nADICIONADO**",
`${member.user.username} adicionou a tag ${cargo.name}\n` +
`Use o comando \`!tags\` novamente para adicionar ou remover outra tag.`);
}
m.edit(embed);
message.delete();
m.delete({timeout:40000});
return
}
//This entity script will be attached to zones
(function()
{
//set up entity id storage
var _selfEntityID;
//Subscribe to channel to listen to notices
Messages.subscribe("zoneNotice");
//Stores entity id on creation
this.preload = function(entityID)
{
_selfEntityID = entityID;
};
Messages.messageReceived.connect(function (channel, message, senderID, localOnly)
{
if(message === "deleteZone")
{
//Self delete
Entities.deleteEntity(_selfEntityID);
}
});
//Upon entering, sends message to engine that zone has been entered
this.enterEntity = function()
{
//Send message to engine to confirm selection
var textProp = Entities.getEntityProperties(_selfEntityID, ["name"]);
textProp = JSON.stringify(textProp.name);
Messages.sendMessage("engine",textProp);
};
});
true
5ca05f949d376cab668425b21163ddb68104c7f1
JavaScript
danielcawen/buggy-todomvc
/cypress/integration/todo_list_spec.js
UTF-8
7,436
2.875
3
[]
no_license
context('TODO List', () => {
beforeEach(() => {
cy.visit('http://qa-challenge.gopinata.com/')
cy.get('body').then($element => {
if ($element.find("[type='checkbox']").length > 0) {
cy.get('.todo-list li')
.each(function($el, index, $list){
$el.find('.destroy').click()
})
}
})
})
it('User is able to add an item into the TODOs list', () => {
var max = 30
var min = 5
var text = ''
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz !@#$%^&*()_+=-`~{}[]ñ|\':;/.,<>?"
var random = Math.floor(Math.random() * (max - min)) + min
for (var i = 0; i < random; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length))
cy.get('.new-todo')
.type(text).should('have.value', text)
.type('{enter}')
cy.get('.todo-list').find('label')
.should('have.length', 1)
.should('have.text', text)
})
it('XSS verification', () => {
var text = "<script>alert('hello there');</script>"
const stub = cy.stub()
cy.on ('window:alert', stub)
cy.get('.new-todo')
.type(text).should('have.value', text)
.type('{enter}')
.then(() => {
expect(stub.getCall(0)).to.be.null
})
cy.get('.todo-list').find('label')
.should('have.length', 1)
.should('have.text', text)
})
it('Digits are allowed and correctly displayed in the tasks', () => {
cy.get('.new-todo')
.type('123').should('have.value', '123')
.type('{enter}')
cy.get('.todo-list').find('label')
.should('have.length', 1)
.should('have.text', '123')
})
it('Special characters are allowed and correctly displayed in the tasks', () => {
cy.get('.new-todo')
.type('!@#$%^&*()_+`~=-{}|][";:?><,./\'\\').should('have.value', '!@#$%^&*()_+`~=-{}|][";:?><,./\'\\')
.type('{enter}')
cy.get('.todo-list').find('label')
.should('have.length', 1)
.should('have.text', '!@#$%^&*()_+`~=-{}|][";:?><,./\'\\')
})
it('User is able to mark an item as completed', () => {
cy.get('.new-todo')
.type('coffee!').should('have.value', 'coffee!')
.type('{enter}')
cy.get('.todo-list').find('[type=\'checkbox\']')
.check().should('be.checked')
cy.get('.todo-list')
.find('.completed')
.find('label')
.should('have.text', 'coffee!')
})
it('User is able to remove completed items', () => {
cy.get('.new-todo')
.type('coffee!').should('have.value', 'coffee!')
.type('{enter}')
cy.get('.todo-list').find('[type=\'checkbox\']')
.check().should('be.checked')
cy.get('.clear-completed')
.click()
cy.get('.todo-list').find('label')
.each(($el, index, $list) => {
expect($list).to.have.length(0)
})
})
it('Only tasks with text are allowed', () => {
cy.get('.new-todo')
.click()
.type('{enter}')
cy.get('.todo-list').find('label')
.should('have.length', 0)
})
it('Verify that long text is displayed inside the label box', () => {
let before
let after
cy.document()
.then((doc) => {
before = doc.documentElement.scrollWidth
})
.then(() =>
cy.get('.new-todo')
.type('qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty .123 qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty .123!')
.type('{enter}')
.then(() => {
cy.document()
.then((doc) => {
after = doc.documentElement.scrollWidth
expect(before).to.equal(after)
})
})
)
})
it('Verify item count', () => {
cy.get('.new-todo')
.type('coffee!').should('have.value', 'coffee!')
.type('{enter}')
.type('hamburgers').should('have.value', 'hamburgers')
.type('{enter}')
.type('asado').should('have.value', 'asado')
.type('{enter}')
cy.get('.todo-count')
.should('have.text', '3 items left')
})
it('Verify filter: completed items', () => {
cy.get('.new-todo')
.type('item 1').should('have.value', 'item 1')
.type('{enter}')
.type('item 2').should('have.value', 'item 2')
.type('{enter}')
.type('item 3').should('have.value', 'item 3')
.type('{enter}')
cy.get('.todo-list').find('[type=\'checkbox\']').first()
.check().should('be.checked')
cy.get('.filters li').contains('Completed')
.click()
cy.get('.todo-list').find('label')
.should('have.length', 1)
})
it('Verify filter: active items', () => {
cy.get('.new-todo')
.type('item 1').should('have.value', 'item 1')
.type('{enter}')
.type('item 2').should('have.value', 'item 2')
.type('{enter}')
.type('item 3').should('have.value', 'item 3')
.type('{enter}')
cy.get('.todo-list').find('[type=\'checkbox\']').first()
.check().should('be.checked')
cy.get('.filters li').contains('Active')
.click()
cy.get('.todo-list').find('label')
.should('have.length', 2)
})
it('Verify that all items are completed when they are marked as completed', () => {
cy.get('.new-todo')
.type('item 1').should('have.value', 'item 1')
.type('{enter}')
.type('item 2').should('have.value', 'item 2')
.type('{enter}')
.type('item 3').should('have.value', 'item 3')
.type('{enter}')
cy.get('.todo-list').find('[type=\'checkbox\']')
.check().should('be.checked')
cy.get('.todo-count')
.should('have.text', 'No items left')
})
it('User is able to edit an option', () => {
cy.get('.new-todo')
.type('coffee!').should('have.value', 'coffee!')
.type('{enter}')
cy.get('.todo-list').find('label')
.dblclick()
cy.get('.todo-list').find('.editing').find('.edit')
.clear()
.type('a lot of coffee!').should('have.value', 'a lot of coffee!')
.type('{enter}')
cy.get('.todo-list').find('label')
.should('not.have.text', 'coffee!')
cy.get('.todo-list').find('label')
.should('have.text', 'a lot of coffee!')
})
it('Verify that the label is the same on view mode and edit mode', () => {
cy.get('.new-todo')
.type('a lot of space')
.type('{enter}')
cy.get('.todo-list').find('label')
.should('have.text', 'a' + '\xa0\xa0\xa0' + 'lot' + '\xa0\xa0\xa0\xa0' + 'of' + '\xa0\xa0\xa0\xa0\xa0' + 'space')
cy.get('.todo-list').find('label')
.dblclick()
cy.get('.todo-list').find('.editing').find('.edit')
.should('have.value', 'a' + '\xa0\xa0\xa0' + 'lot' + '\xa0\xa0\xa0\xa0' + 'of' + '\xa0\xa0\xa0\xa0\xa0' + 'space')
})
// LOAD TEST:
// it('Add 1000 elements and verify the user can remove items', () => {
// var number = 0;
// var max = 1000
// var min = 0
// while (number < max) {
// cy.get('.new-todo')
// .type(number)
// .type('{enter}')
// cy.get('.todo-count')
// .should('contain', (number + 1).toString())
// number++
// }
// var random = Math.floor(Math.random() * (max - min)) + min
// cy.log(random)
// cy.get('.todo-list').find('[type=\'checkbox\']')
// .eq(random)
// .check().should('be.checked')
// })
})
true
d3ac87f1e26dcd782c1aa3d0af9dc28cc220eef9
JavaScript
nch0w/uprising
/commands/draw.js
UTF-8
2,364
2.796875
3
[]
no_license
const { games, backup } = require("../models");
const { deepCopier } = require("../helpers");
function execute(message, args, user) {
if (message.channel.id in games) {
let person = message.author;
if (message.mentions.members.first()) {
person = message.mentions.members.first().user;
}
const player = games[message.channel.id].players.find(
(element) => element.user === person
);
if (player) {
if (args.length > 0 && "cc" === args[0].toLowerCase()) {
if (["Russia", "ROK"].includes(player.revealed)) {
const newcard = games[message.channel.id].deck.shift();
player.specialcards.push(newcard);
person.send(
`You drew a ${newcard} and placed it on your Country Card.\nYour hand is: ${player.cards.join(
", "
)}`
);
message.channel.send(
`<@${player.id}> drew a card and placed it on their Country Card!`
);
backup[message.channel.id].push({
state: deepCopier(games[message.channel.id]),
action: "draw",
user: person,
});
} else {
return message.channel.send(
`<@${player.id}> not allowed to draw to Country Card.`
);
}
} else {
const newcard = games[message.channel.id].deck.shift();
player.cards.push(newcard);
if (player.death === "~~") {
player.death = "";
}
if (player.specialcards.length > 0) {
person.send(
`You drew a ${newcard}.\nYour hand is now: ${player.cards.join(
", "
)}\nThe card on your Country Card is ${player.specialcards}`
);
} else {
person.send(
`You drew a ${newcard}.\nYour hand is now: ${player.cards.join(
", "
)}`
);
}
message.channel.send(`<@${player.id}> drew a card!`);
backup[message.channel.id].push({
state: deepCopier(games[message.channel.id]),
action: "draw",
user: person,
});
}
} else {
return message.channel.send("User not a player in game.");
}
} else {
return message.channel.send("No game to draw a card in.");
}
}
module.exports = {
name: "draw",
aliases: ["d"],
execute,
};
true
e4dbefde452e7b13a3ad0d2b9e122d2a329bdc86
JavaScript
DetlefDmann/dentist_react
/src/components/Patients.js
UTF-8
2,495
2.796875
3
[]
no_license
import React, { useContext, useState } from 'react'
import { GlobalContext } from '../GlobalContext'
import { v4 as uuid } from "uuid"
const Patients = () => {
const [state, setState] = useContext(GlobalContext);
const [newPatient, setNewPatient] = useState({
firstName:"",
lastName:"",
phoneNr:"",
eMail:"",
gender:"",
isSick:false,
birthYear:""
})
const handleChange = (e) => {
const {value , name} = e.target;
console.log(value);
console.log(name);
setNewPatient({
...newPatient,[name]:value,
id:uuid(),
});
}
const setNewVictim = (e) => {
e.preventDefault();
setState({
...state, patients:[...state.patients, newPatient]
})
}
return (
<form>
<h3>Voeg een nieuwe patient toe.</h3><br/>
<label htmlFor="firstName">Voornaam</label><br/>
<input type="text" name="firstName" id="firstName" onChange={handleChange} /><br/>
<label htmlFor="lastName">Achternaam</label><br/>
<input type="text" name="lastName" id="lastName" onChange={handleChange} /><br/>
<label htmlFor="phoneNr">Telefoonnummer</label><br/>
<input type="tel" name="phoneNr" id="phoneNr" onChange={handleChange}/><br/>
<label htmlFor="eMail">E-mail</label><br/>
<input type="email" name="eMail" id="eMail" onChange={handleChange}/><br/>
<label htmlFor="gender">Geslacht</label><br/>
<input type="text" name="gender" id="gender" onChange={handleChange}/><br/>
<label htmlFor="birthYear">Geboorte jaar</label><br/>
<input type="text" name="birthYear" id="birthYear" onChange={handleChange}/><br/>
<p>De volgende gegevens zijn ingevuld: <br/><br/>
{newPatient.firstName} <br/>
{newPatient.lastName} <br/>
{newPatient.phoneNr} <br/>
{newPatient.eMail}<br/>
{newPatient.birthYear} <br/>
Geslacht is: {newPatient.gender}<br/>
<br/>
Kloppen deze gegevens?
</p><br/><br/>
<p>Het e-mail adres is als volgt: {newPatient.eMail} <br/><br/>
Als alles klopt kunnen we de patient nu toevoegen aan de database.
</p><br/>
<button onClick={setNewVictim}>Voeg toe</button>
</form>
)
}
export default Patients
true
1f463b5ca58ad1612ffa3973754f905f28710113
JavaScript
inkyysleeves/cruise-shipz
/__tests__/port.test.js
UTF-8
327
2.625
3
[]
no_license
const Port = require("../src/port.js");
describe("port", () => {
it("returns a port object", () => {
const port = new Port("dover");
expect(new Port()).toBeInstanceOf(Object);
});
it("can see a port has a name", () => {
const port = new Port("Dover");
expect(port.name).toEqual('Dover');
});
});
true
c925ca636006a74596e6f1e81a535d336e214a26
JavaScript
Project-AirPods/booking-module
/database/index.js
UTF-8
4,369
2.53125
3
[]
no_license
const config = require('./config.js');
const { Pool, Client } = require('pg');
const client = new Client(config);
client.connect();
module.exports.getCoreData = function getBaseDataForListing(listingId, callback) {
const query = `SELECT l.*, ROUND(AVG(p.cost_per_night), 0) as avg_cost_per_night
FROM listings l
JOIN listing_daily_prices p ON l.id = p.listing_id
WHERE l.id = ${listingId}
GROUP BY 1,2,3,4,5,6,7`;
client.query(query, (err, results) => {
if (err) {
callback(err, null);
} else {
results.rows[0].avg_rating = parseFloat(results.rows[0].avg_rating);
results.rows[0].cleaning_fee = parseFloat(results.rows[0].cleaning_fee);
results.rows[0].service_fee_perc = parseFloat(results.rows[0].service_fee_perc);
results.rows[0].occ_tax_rate_perc = parseFloat(results.rows[0].occ_tax_rate_perc);
results.rows[0].additional_guest_fee = parseFloat(results.rows[0].additional_guest_fee);
results.rows[0].avg_cost_per_night = parseFloat(results.rows[0].avg_cost_per_night);
callback(null, results.rows);
}
});
};
module.exports.getReservationData = function getReservationDataForDateRange(listingId, startDate, endDate, callback) {
const query = `SELECT id, start_date, end_date
FROM reservations
WHERE listing_id = ${listingId}
AND (start_date BETWEEN '${startDate}' AND '${endDate}'
OR end_date BETWEEN '${startDate}' AND '${endDate}');`;
client.query(query, (err, results) => {
if (err) {
callback(err, null);
} else {
callback(null, results.rows);
}
});
};
const getMaxPrice = function getMaxPrice(listingId, callback) {
const maxQuery = `SELECT id, start_date, cost_per_night
FROM listing_daily_prices
WHERE listing_id = ${listingId}
ORDER BY start_date DESC LIMIT 1;`;
client.query(maxQuery, (err, results) => {
if (err) {
callback(err, null);
} else {
for (var i = 0; i < results.rows.length; i++) {
results.rows[i].cost_per_night = parseFloat(results.rows[i].cost_per_night);
}
callback(null, results.rows);
}
});
};
module.exports.getPricingData = function getPricingDataForDateRange(listingId, startDate, endDate, callback) {
const query = `SELECT id, start_date, cost_per_night
FROM listing_daily_prices
WHERE listing_id = ${listingId}
AND start_date < '${endDate}';`;
client.query(query, (err, results) => {
if (err) {
callback(err, null);
} else if (results.length > 0) {
console.log(results.rows);
callback(null, results);
} else { // if no results in date range, just get most recent price
getMaxPrice(listingId, callback);
}
});
};
// POST
module.exports.postReservationData = function postReservationDataForDateRange(listingId, startDate, endDate, callback) {
const idquery = `SELECT id FROM reservations ORDER BY id DESC LIMIT 1;`;
client.query(idquery, (err, results) => {
if (err) {
callback(err, null);
} else {
const query = `INSERT INTO reservations (id, listing_id, start_date, end_date)
VALUES (${results.rows[0].id + 1}, ${listingId}, (to_date('${startDate}', 'YYYY-MM-DD')), (to_date('${endDate}', 'YYYY-MM-DD')));`;
client.query(query, (err, results) => {
if (err) {
callback(err, null);
} else {
callback(null, results.rows);
}
});
}
});
};
// DELETE
module.exports.deleteReservationData = function deleteReservationDataForDateRange(listingId, startDate, endDate, callback) {
const query = `DELETE FROM reservations WHERE listing_id = ${listingId} AND start_date = '${startDate}' AND end_date = '${endDate}';`;
client.query(query, (err, results) => {
if (err) {
callback(err, null);
} else {
callback(null, results.rows);
}
});
};
// PUT
module.exports.putReservationData = function putReservationDataForDateRange(listingId, startDate, endDate, newStartDate, newEndDate, callback) {
const query = `UPDATE reservations SET start_date = '${newStartDate}',
end_date = '${newEndDate}' WHERE listing_id = ${listingId} AND
start_date = '${startDate}' AND
end_date = '${endDate}';`;
client.query(query, (err, results) => {
if (err) {
callback(err, null);
} else {
callback(null, results.rows);
}
});
};
true
d7ba186688c36ecdf5243163fc2e3c0a7ea1b29e
JavaScript
KhangNguyen007/cliexa
/public/javascripts/Rectangle.js
UTF-8
1,293
3.15625
3
[]
no_license
class Rectangle{
constructor() {
}
//Create without onClick
create(x,y,height,width,fill,zIndex){
let svgns = "http://www.w3.org/2000/svg"
var rect = document.createElementNS(svgns, 'rect'); //Create a path in SVG's namespace
rect.setAttributeNS(null, 'x', x.toString());
rect.setAttributeNS(null, 'y', y.toString());
rect.setAttributeNS(null, 'height', height.toString());
rect.setAttributeNS(null, 'width', width.toString());
rect.setAttributeNS(null, 'fill', fill);
rect.setAttributeNS(null, 'z-index', zIndex);
$("svg").append(rect);
}
//Create with onClick
createWithOnClick(x,y,height,width,fill,zIndex,onclick){
let svgns = "http://www.w3.org/2000/svg"
var rect = document.createElementNS(svgns, 'rect'); //Create a path in SVG's namespace
rect.setAttributeNS(null, 'x', x.toString());
rect.setAttributeNS(null, 'y', y.toString());
rect.setAttributeNS(null, 'height', height.toString());
rect.setAttributeNS(null, 'width', width.toString());
rect.setAttributeNS(null, 'fill', fill);
rect.setAttributeNS(null, 'z-index', zIndex);
rect.setAttributeNS(null, 'onclick', onclick);
$("svg").append(rect);
}
}
// Multiple-Lock, use queue to maintain holder. Each lock instance could be held by
// at most k functions. The rests have to wait.
//
// Author: Levy (levythu)
// Date: 2016/04/02
(function() {
var Queue=require("./queue");
function Lock(maxHolder)
{
if (maxHolder==null)
this.rest=1;
else
this.rest=maxHolder;
this.waitingQueue=new Queue();
}
Lock.prototype.Lock=function(callback)
{
if (this.rest==0)
{
// No more lock to use, stuck it.
this.waitingQueue.EnQueue(callback);
return;
}
this.rest--;
callback();
}
Lock.prototype.Unlock=function()
{
if (this.waitingQueue.len>0)
{
process.nextTick(this.waitingQueue.DeQueue());
return;
}
this.rest++;
}
module.exports=Lock;
})();
true
58f2744039b975404e315a87bbf77cc3f0252e6f
JavaScript
DWL321/Web2.0_homework
/web第七次作业/优化/修改后/js/Whac-a-mole.js
UTF-8
2,277
2.9375
3
[]
no_license
/*19335040 丁维力*/
/*打地鼠小游戏脚本文件*/
/*初始化全局变量*/
var time_ = 30;
var timer = null;
var score_ = 0;
var mole = -1;//纪录地鼠出现位置,-1表示未出现地鼠
var hit = -2;//记录打击位置,-2表示地鼠未出现,-1表示未击打
var playing = false;
/*添加当玩家鼠标点击元素时触发的事件监听器*/
$(function () {
$('#start').click(game_start);
$('#stop').click(game_over);
$('[name="hole"]').click(check);
});
// 重置控制游戏的全局变量
function reset_control(){
hit=-2;
time_=30;
score_=0;
playing=true;
if(timer!==null)clearInterval(timer);
}
/*游戏开始,倒计时重置*/
function game_start() {
reset_control();
$('#time_value').text(time_);
$('#score_value').text(score_);
timer=setInterval(countdown,1000);
$("#over").text("Game Start");
appear();
}
/*检测上一个地鼠出现的时间段内玩家是否落下锤子*/
function check_last(){
if(hit==-1&&mole!==-1){
score_--;
$('#score_value').text(score_);
}
}
/*地鼠每秒随机出现一次*/
function appear(){
if(playing==true){
check_last();
var next=$('[name="hole"]')[_.random(59)].value;
mole=(next==mole)? (next+1)%60:next;//防止连续两次地鼠在同一个地方出现
$('[name="hole"]')[mole].checked="true";
hit=-1;
}
}setInterval("appear()",1000);
/*游戏倒计时*/
function countdown(){
time_--;
$('#time_value').text(time_);
if(playing==false||time_<=0){
clearInterval(timer);
game_over();
}
}
/*游戏结束,倒计时停止,输出结束提示*/
function game_over() {
playing=false;
$("#over").text("Game Over");
}
/*玩家点击洞,检测是否砸中地鼠*/
function check() {
if(playing==true&&hit<0)
for(hit=0;hit<$('[name="hole"]').length;hit++)
if($('[name="hole"]')[hit].checked){
$('[name="hole"]')[hit].checked=false;
score_=($('[name="hole"]')[hit].value==$('[name="hole"]')[mole].value)? score_+1:score_-1;
$('#score_value').text(score_);
return ;
}
}
true
e0eb70b81969e71d1556820f05336ef5cf6b2384
JavaScript
apparition47/LeetCode
/124 - Binary Tree Maximum Path Sum.js
UTF-8
785
3.328125
3
[]
no_license
// https://leetcode.com/problems/binary-tree-maximum-path-sum/
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxPathSum = function(root) {
const dfs = node => {
if (!node) return 0
let left=0,right=0
if (node.left) left=Math.max(dfs(node.left),0)
if (node.right) right=Math.max(dfs(node.right),0)
opt = Math.max(opt, left+right+node.val)
return node.val + Math.max(left,right)
}
let opt = Number.MIN_SAFE_INTEGER
dfs(root)
return opt
};
true
bba4af331d6baeba98be0898157d585ee1ee66b9
JavaScript
floraxue/TextThresher
/app/components/quiz/QuizContext.js
UTF-8
1,019
2.578125
3
[
"Apache-2.0"
]
permissive
import React from 'react';
export default React.createClass({
displayName: 'QuizContext',
propTypes: {
context: React.PropTypes.object.isRequired
},
render() {
var text = this.props.context.text;
var highlights = this.props.context.highlights;
var start = 0;
var tail = '';
var l = highlights.length;
if (highlights[l - 1][1] !== text.length) {
tail = <span>{text.substring(highlights[l - 1][1], text.length)}</span>;
}
return (
<p className='quiz__context'>
{Array(highlights.length * 2).fill().map((_,i) => {
var curHL = highlights[i / 2 | 0];
if (i % 2 === 0) {
// render normal text
return (<span key={i}>{text.substring(start, curHL[0])}</span>);
} else {
// render highlight
start = curHL[1];
return (<span key={i} className='highlighted'>{text.substring(curHL[0], curHL[1])}</span>);
}
})}
{ tail }
</p>
);
}
});
const common = require('../common');
const expect = common.expect;
const FileBasedRepository = require('../../domain/TravelDestination/FileBasedRepository');
const User = require('../../domain/TravelDestination/User');
const ErrorMessage = require('../../utils/ErrorMessage');
const uuid = require('uuid/v4');
const fs = require('fs-extra')
describe('FileBasedRepository', function() {
const TMP_DIRECTORY = './tmp/repository/';
var repository;
beforeEach('before each test build the repository', function() {
repository = new FileBasedRepository(TMP_DIRECTORY);
});
afterEach('after each test clear the repository', function() {
repository.clear();
});
describe('#persist()', function() {
it('when a user is persisted to the repository, it is added to the file system', function(done) {
// Given
var userId = uuid();
var travelId = uuid();
var user = new User('foo', userId, [travelId]);
// When
var promise = repository.persist(user);
// Then
promise.then(returnedUser => {
expect(fs.pathExistsSync(TMP_DIRECTORY + userId + "/user.json")).to.be.true;
expect(returnedUser.userId).to.be.a('string');
expect(returnedUser.userId).to.equal(userId);
expect(returnedUser.userName).to.be.a('string');
expect(returnedUser.userName).to.be.equal('foo');
expect(returnedUser.travelDestinationIds).to.have.lengthOf(1);
expect(returnedUser.travelDestinationIds[0]).to.be.a('string');
expect(returnedUser.travelDestinationIds[0]).to.be.equal(travelId);
done();
})
.catch(error => expect(error).fail());
});
});
describe('#persist()', function() {
it('test that when a user is persisted to the repository twice, that the'
+ '\n first time it is added to the file system'
+ '\n and the second time an error is thrown', function(done) {
// Given
var userId = uuid();
var travelId = uuid();
var user = new User('foo', userId, [travelId]);
// When
repository.persist(user).then(returnedUser => {
var promise = repository.persist(user);
expect(Promise.all([
// The user should be there
expect(fs.pathExists(TMP_DIRECTORY + userId + "/user.json")).to.eventually.be.true,
// But the promise result of the second attempt should be rejected
expect(promise).to.be.rejected
]))
.and.notify(done);
}).catch(error => done(error));
})
});
});
"use strict";
// import fs module for interacting with the filesystem
const fs = require('fs');
const questionsFilePath = __dirname + '/../data.json';
// check if the questions file exists or not
// throw error if it doesn't
if (! fs.existsSync(questionsFilePath))
throw new Error('Questions file is required for your application.');
const questions = JSON.parse(fs.readFileSync(questionsFilePath));
const Questions = {
// assumed marks for each difficulty
allotedMarks: {
easy: 2,
medium: 3,
hard: 5
},
// set the questions
questions: questions,
// get all the questions
get: function() {
return this.questions;
},
// get easy questions based on the limit passed
getEasy: function(limit) {
return applyLimit(this.questions.filter(question => {
return question.difficulty == 'easy';
}), limit);
},
// get medium questions
getMedium: function(limit) {
return applyLimit(this.questions.filter(question => {
return question.difficulty == 'medium';
}), limit);
},
// get hard questions
getHard: function(limit) {
return applyLimit(this.questions.filter(question => {
return question.difficulty == 'hard';
}), limit);
}
};
// seperate function to limit the results
// moving out of the class as we want to hide this functionality
function applyLimit(questions, limit) {
// return all the questions if no limit is specified
if (limit === 'undefined') return questions;
return questions.filter((question, index) => {
return index <= (limit - 1);
});
}
module.exports = Questions;
$(document).ready(function() {
// Begin search for new item
$("#container").on('click', '.search', function() {
getWikiPages();
});
});
// Grabs the first 8 wikipedia titles and summaries using wikipedia api
// @term: term to search wikipedia for
function getWikiPages(term) {
// Get the results from the search
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=" + document.getElementById("query").value + "&namespace=0&limit=8&callback=?",
dataType: 'json',
type: 'POST',
success: function(data) {
console.log(data);
var list = "";
// Construct the results list
for (var i = 1; i < data[1].length; i++) {
list += '<a href="' + data[3][i] + '" target="_blank"><div class="result"><h4><u>' + data[1][i] + '</u></h4>';
list += "<p>" + data[2][i] + "</p></div></a>";
}
// Update the results list
$("#results").html(list);
},
error: function(jqXHR, status, error) {
console.log("Status: " + status);
console.log("Error: " + error);
}
});
}
$(document).ready(function () {
$(".catBtn").on("click", function () {
console.log($(this));
let catId = $(this).data("value");
console.log(catId);
window.location.replace("/dashboard/" + catId)
});
});
true
36e7401cb5887f3b66c02573d7fcc78512d1f706
JavaScript
luismigeek/bootcamp
/js/main.js
UTF-8
1,939
3.578125
4
[
"MIT"
]
permissive
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var efect = "tada";
var gift = document.getElementById('gift');
var preload = document.getElementById('preload');
var loading = document.getElementById('loading');
var code = document.getElementById('code');
var fullname = document.getElementById('fullname');
var institution = document.getElementById('institution');
var genera = document.getElementById('generar');
var reiniciar = document.getElementById('reiniciar');
genera.onclick = () => {
var x = document.getElementById("myAudio");
x.play();
// the code you're looking for
var number = getRandomInt(1, 90);
console.log('Numero: ', number);
preload.classList.add("preloader");
loading.classList.add("loading-circle");
loading.classList.add("fa-spin");
setTimeout(() => {
preload.classList.remove("preloader");
loading.classList.remove("loading-circle");
loading.classList.remove("fa-spin");
gift.classList.add(efect);
code.innerHTML = list[number - 1].code;
fullname.innerHTML = list[number - 1].fullname;
institution.innerHTML = list[number - 1].institution;
}, 7500);
}
/**
genera.onclick = () => {
// the code you're looking for
var number = getRandomInt(1, 90);
// iterate over each element in the array
for (var i = 0; i < list.length; i++) {
// look for the entry with a matching `code` value
if (list[i].code == number) {
console.log(list[i].code);
code.innerHTML = list[i].code;
fullname.innerHTML = list[i].fullname;
institution.innerHTML = list[i].institution;
}
}
}
*/
reiniciar.onclick = () => {
code.innerHTML = ' xx ';
fullname.innerHTML = 'xx - xx - xx - xx ';
institution.innerHTML = 'xx - xx';
gift.classList.remove(efect);
}
const ageGuard = require('./age-guard');
it('There should be function named ageGuard', () => {
expect(ageGuard).toBeDefined();
});
it('Persons under 18 should not be granted access', () => {
expect(ageGuard(14)).toBe('You are not old enough to access this site');
});
it('Persons 18 and above should be granted access', () => {
expect(ageGuard(18)).toBe('You\'ve been granted access to this site');
});
true
ce1f282b5b06ded8ece430d2bddd8b53aeb23d0c
JavaScript
hhernan83/Hernans-repo
/07_Node/SuperProject/App.js
UTF-8
445
3.1875
3
[]
no_license
var marvel = require('marvel-characters')
console.log(marvel())
console.log(`# of characters in the db: `+marvel.characters.length)
let names = marvel.characters.filter(function(el){
return el.substring(0,3) == "Man"
})
console.log(names)
let IronMan = marvel.characters.filter(el=>{
return el == "Iron Man"
})
let result = IronMan.length !=0 ? IronMan: "No matches found"
console.log(result)
console.log(IronMan)
true
0dfad7f8a5189a8e7f213b551650ed8c63c223e5
JavaScript
landonbar/muta
/src/pathResolver.js
UTF-8
965
2.828125
3
[]
no_license
// the PathResolver is a namespace that uses a browser hack to generate an
// absolute path from a url string -- using an anchor tag's href.
// it combines the aliasMap with a file and possible base directory.
const PathResolver = {};
const ANCHOR = document.createElement('a');
PathResolver.resolveFile = function resolveFile(aliasMap, file, dir) {
file = aliasMap ? (aliasMap[file] || file) : file;
if(dir && file.indexOf('http') !== 0) {
dir = aliasMap ? (aliasMap[dir] || dir) : dir;
const lastChar = dir.substr(-1);
file = (lastChar !== '/') ? dir + '/' + file : dir + file;
}
ANCHOR.href = file;
return ANCHOR.href;
};
PathResolver.resolveDir = function resolveDir(aliasMap, file, dir){
return toDir(PathResolver.resolveFile(aliasMap, file, dir));
};
function toDir(path){
const i = path.lastIndexOf('/');
return path.substring(0, i + 1);
}
export default PathResolver;
true
308fcf4490edba61bc9f6732510d399a950ce21c
JavaScript
rlong/javascript.lib.dinky_require
/dinkyRequire.js
UTF-8
3,644
2.640625
3
[
"MIT"
]
permissive
// Copyright (c) 2017 Richard Long
//
// Released under the MIT license ( http://opensource.org/licenses/MIT )
//
"use strict";
var microRequireModules = {};
{
var loadResource = function( path, callback, errorCallback ) {
var xhr = new XMLHttpRequest();
var finished = false;
xhr.onabort = xhr.onerror = function xhrError() {
finished = true;
if( errorCallback ) {
errorCallback( xhr );
} else {
console.error( xhr );
}
};
xhr.onreadystatechange = function xhrStateChange() {
if (xhr.readyState === 4 && !finished) {
finished = true;
var section;
try {
callback( xhr.responseText );
} catch (e) {
if( errorCallback ) {
errorCallback( xhr );
} else {
console.error( e );
}
}
}
};
xhr.open('GET', path);
xhr.send();
}
var setupModule = function( cursor, moduleConfig ) {
// console.info( "loading lib: " + moduleConfig.name );
loadResource( moduleConfig.src, function (scriptText) {
moduleConfig.scriptText = scriptText;
if( moduleConfig === cursor.current() ) {
do {
{
window.exports = {};
eval.apply( window, [moduleConfig.scriptText]);
// did the module `export` anything
if( 0 < Object.keys(window.exports).length ) {
microRequireModules[moduleConfig.name] = window.exports;
}
delete window.exports;
console.info( "loaded lib: " + moduleConfig.name );
}
moduleConfig = cursor.next();
}
while( null != moduleConfig && null != moduleConfig.scriptText );
} else {
// we are still waiting for an earlier library to load ... no-op
}
});
}
var setup = function( config ) {
for( var i = 0, count = config.length; i < count; i++ ) {
var moduleConfig = config[i];
if( !moduleConfig.src ) {
moduleConfig.src = moduleConfig.name + ".js"
}
}
var cursor = {
index: 0,
next: function () {
cursor.index++;
if( cursor.index == config.length ) {
return null;
}
var answer = config[cursor.index];
return answer;
},
current: function () {
return config[cursor.index];
}
}
for( var i = 0, count = config.length; i < count; i++ ) {
setupModule( cursor, config[i] );
}
}
loadResource( "./dinkyConfig.json",
function (jsonText) {
var config = JSON.parse( jsonText );
setup( config );
},
function ( error ) {
console.error( "failed to load './dinkyConfig.json'");
console.error( error );
});
}
function require( lib ) {
var answer = microRequireModules[lib];
if( undefined == answer ) {
// take a punt ...
answer = window[lib];
}
if( undefined == answer ) {
console.error( "'"+lib+"' not found!" );
}
return answer;
}
true
5f54739fbb20393801a634a6f42369f1455b1a3f
JavaScript
Hugovarellaa/verificador-de-idade
/app.js
UTF-8
1,805
3.515625
4
[]
no_license
const button = document.querySelector('button');
button.addEventListener('click', () => {
const data = new Date();
const anoAtual = data.getFullYear()
const ano = document.querySelector('input#txtano').value;
const hoje = Number(anoAtual) - Number(ano)
const sexo = document.getElementsByName('radsexo');
const resultado = document.querySelector('div#res');
const img = document.createElement('img');
img.setAttribute('id', 'foto')
if (ano == '') {
resultado.textContent = `Preencha os campos e veja o resultado`
} else {
genero = ''
if (sexo[0].checked) {
genero = 'Homen'
if (hoje < 10) {
//foto da criança homem
img.src = './_Imagens/H1.png'
} else if (hoje < 21) {
//foto do jovem homem
img.src = './_Imagens/H2.png'
} else if (hoje < 50) {
//foto do adulto homem
img.src = './_Imagens/H3.png'
} else {
//foto do idoso homem
img.src = './_Imagens/H4.png'
}
} else if (sexo[1].checked) {
genero = 'Mulher'
if (hoje < 10) {
//foto da criança mulher
img.src = './_Imagens/M1.png'
} else if (hoje < 21) {
//foto da jovem mulher
img.src = './_Imagens/M2.png'
} else if (hoje < 50) {
//foto da adulto mulher
img.src = './_Imagens/M3.png'
} else {
//foto da idosa mulher
img.src = './_Imagens/M4.png'
}
}
resultado.textContent = `Detectamos... ${genero} com a ${hoje} anos`
}
resultado.appendChild(img)
})
const Thing = require('Grow.js');
var inquirer = require('inquirer');
var _ = require('underscore')
const growfile = require('./tomato.js')
var args = process.argv.slice(2);
var uuid = args[0];
var token = args[1];
var questions = [
{
type: 'input',
name: 'uuid',
message: 'Enter device UUID (you are given this when you create a new thing)',
},
{
type: 'input',
name: 'token',
message: 'Enter token',
},
];
if(_.isUndefined(uuid) || _.isUndefined(token)) {
inquirer.prompt(questions).then(function (answers) {
uuid = answers.uuid;
token = answers.token;
createGrowHub(uuid, token);
});
} else {
createGrowHub(uuid, token);
}
// Create a new growHub instance and connect to https://growHub.commongarden.org
function createGrowHub(u, t) {
const growHub = new Thing({
uuid: u,
token: t,
component: 'BioReactor',
// Properties can be updated by the API
properties: {
state: 'off',
light_state: 'off',
fan_state: 'off',
pump_state: 'off',
threshold: 300,
interval: 3000,
currently: null,
lightconditions: null,
growfile: {
phases: {
vegetative: {
targets: {
ph: {
min: 6.0,
ideal: 6.15,
max: 6.3,
},
ec: {
min: 1400,
ideal: 1500,
max: 1700,
},
humidity: {
min: 51,
max: 61
},
},
// You can have more cycles than just day or night.
cycles: {
day: {
start: 'after 6:00am',
targets: {
temperature: 24,
co2: {
min: 900,
max: 1600
}
}
},
night: {
start: 'after 9:00pm',
targets: {
temperature: 20,
co2: {
min: 400,
max: 1000
},
}
}
}
},
bloom: {
targets: {
ph: {
min: 6.0,
ideal: 6.15,
max: 6.3,
},
ec: {
min: 1400,
ideal: 1500,
max: 1700,
},
humidity: {
min: 51,
max: 59
},
},
cycles: {
day: {
start: 'after 7:00am',
targets: {
temperature: 24,
}
},
night: {
start: 'after 7:00pm',
targets: {
temperature: 20,
co2: 400,
},
}
}
}
}
}
},
start: function () {
console.log('Grow-Hub initialized.');
let interval = this.get('interval');
emit_and_analyze = setInterval(()=> {
this.temp_data();
this.hum_data();
this.ph_data();
this.ec_data();
this.lux_data();
this.water_temp_data();
// this.power_data();
}, interval);
// this.parseCycles(growfile.properties.cycles);
},
stop: function () {
console.log("Grow-Hub stopped.");
clearInterval(emit_and_analyze);
this.removeAllListeners();
},
day: function () {
console.log('It is day!');
},
night: function () {
console.log('It is night!');
},
turn_light_on: function () {
console.log('light on');
this.set('light_state', 'on');
},
turn_light_off: function () {
console.log('light off');
this.set('light_state', 'off');
},
turn_fan_on: function () {
console.log('Fan on');
this.set('fan_state', 'on');
},
turn_fan_off: function () {
console.log('Fan off');
this.set('fan_state', 'off');
},
turn_pump_on: function () {
console.log('Pump on');
this.set('pump_state', 'on');
},
turn_pump_off: function () {
console.log('Pump off');
this.set('pump_state', 'off');
},
ec_data: function () {
eC_reading = Math.random() * 1000;
this.emit('ec', eC_reading);
console.log('Conductivity: ' + eC_reading);
},
ph_data: function () {
pH_reading = Math.random() * 14;
this.emit('ph', pH_reading);
console.log('ph: ' + pH_reading);
},
temp_data: function () {
let currentTemp = Math.random();
this.emit('temperature', currentTemp);
console.log('Temp: ' + currentTemp);
},
water_temp_data: function () {
let currentWaterTemp = Math.random();
this.emit('water_temperature', currentWaterTemp);
console.log('Water Temp: ' + currentWaterTemp);
},
// power_data: function () {
// this.emit({
// type: 'fan_power',
// value: {
// current: Math.random(),
// voltage: Math.random(),
// power: Math.random(),
// total: Math.random()
// }
// });
// this.emit({
// type: 'pump_power',
// value: {
// current: Math.random(),
// voltage: Math.random(),
// power: Math.random(),
// total: Math.random()
// }
// });
// this.emit({
// type: 'light_power',
// value: {
// current: Math.random(),
// voltage: Math.random(),
// power: Math.random(),
// total: Math.random()
// }
// });
// },
lux_data: function () {
let lux = Math.random();
this.emit('lux', lux);
console.log('Lux: ' + lux);
},
hum_data: function () {
let currentHumidity = Math.random();
this.emit('humidity', currentHumidity);
console.log("Humidity: " + currentHumidity);
}
}).connect();
console.log(growHub);
}
true
5f4f9b1ab3743f11acda465fa1261aa2b4549b9f
JavaScript
alexpower1/man-utd
/src/components/Pages/OldTrafford/OldTrafford.js
UTF-8
2,332
2.984375
3
[]
no_license
import React, { Component } from "react";
import Spinner from "../../Layout/Spinner/Spinner";
class OldTrafford extends Component {
state = {
latitude: null,
longitude: null,
distance: "00.00KM",
errorMessage: "",
calculated: false
};
componentDidMount() {
// On mount, use Geolocate API to determine user position
window.navigator.geolocation.getCurrentPosition(
position =>
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude
}),
err =>
this.setState({
distance: "",
errorMessage:
"Error: " +
err.message +
". Make sure you have provided access to your location."
})
);
}
calculateDistance = () => {
console.log(this.state);
// Set Old Trafford position
const OTLAT = 53.4631;
const OTLON = -2.2913;
let deg2rad = deg => {
return deg * (Math.PI / 180);
};
const R = 6371; // Radius of the earth in km
let dLat = deg2rad(OTLAT - this.state.latitude);
let dLon = deg2rad(OTLON - this.state.longitude);
let a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(this.state.latitude)) *
Math.cos(deg2rad(OTLAT)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
let d = R * c; // Distance in km
let e = Math.round(d * 100) / 100;
this.setState({ distance: e + "km", calculated: true });
};
render() {
let button = "";
if (this.state.errorMessage === "") {
if (this.state.latitude) {
button = (
<button
onClick={this.calculateDistance}
disabled={this.state.calculated}
>
Calculate
</button>
);
} else {
button = <Spinner />;
}
} else {
button = (
<p>
<strong>{this.state.errorMessage}</strong>
</p>
);
}
return (
<div className="OldTrafford">
<h1>Old Trafford</h1>
<p>Calculate your distance from Manchester United's stadium.</p>
<div className="OldTraffordCalc">{button}</div>
<h1>{this.state.distance}</h1>
</div>
);
}
}
export default OldTrafford;
true
a93bb1ab2f187e54f8f2ed265361d1fee869ca05
JavaScript
syntax01/music_box
/js/app.js
UTF-8
1,917
2.9375
3
[]
no_license
$(document).ready( function() {
const playClass = 'playing';
const playDelay = 300;
var clicks = [];
const keyCodes = [67, 72, 65, 82, 76, 69];
const keyChars = ["c","d","e","f","g","a","b"];
var eKey = 69;
var eFlag = 0;
function playAudio(x) {
let box = document.getElementById(x);
let audio = document.getElementById(x + 'Audio');
audio.currentTime = 0;
audio.play();
box.classList.add(playClass);
clicks.push(x);
}
function stopAudio(e) {
if (e.propertyName !== 'transform') return;
e.target.classList.remove(playClass);
}
function playClicks() {
/*
Copy clicks array to new array
Each call to playAudio is going to add the key
to the clicks array... so we need to clone and
empty it before starting the loop
*/
let c = [...clicks];
resetClicks();
console.table(c);
for(var i = 0; i < c.length; i++) {
(function(i){
setTimeout(function(){
playAudio(c[i]);
}, playDelay * i)
})(i);
}
}
function resetClicks() {
clicks.length = 0;
}
function keyAudio(e) {
let k = e.keyCode;
let i = keyCodes.indexOf(k);
if(i > -1) {
if(k == eKey) {
i += eFlag;
eFlag = (eFlag == 0 ? 1 : 0);
}
playAudio(keyChars[i]);
}
}
const boxes = Array.from(document.querySelectorAll('.box'));
boxes.forEach(box => box.addEventListener('mousedown', function(){
playAudio(this.id);
})
);
boxes.forEach(box => box.addEventListener('transitionend', stopAudio));
$('#replay').click(playClicks);
$('#reset').click(resetClicks);
window.addEventListener('keydown', keyAudio);
});
true
632637cec3e2673f8d0e16ba92cd3ddd6f9e2636
JavaScript
ControleVersion/DBM_PORTAL
/painel/public/site/js/regDegust.js
UTF-8
618
3.03125
3
[
"MIT"
]
permissive
//recuoera o valor do cookie para colocar no input de email
var useremail = document.cookie;
var useremail = useremail.split(';');
var getEmail = getCookie('useremail');
$('#form-register-email').attr('value', getEmail);
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)){
var emailVal = strArray[j].split('=');
$('#form-register-email').val(getEmail);
$('#form-register-email').attr('value', getEmail);
$('#form-register-nome').focus();
}
}
}
searchStringInArray('useremail',useremail);
/*
* Write a JavaScript function sortLetters(string, boolean) that gets as an input a string and a boolean. The function
* sorts all letters in the string in alphabetical order and returns the newly formed string. The sorting is ascending if
* the boolean is true otherwise the sorting is in descending order.
* Note: The sorting is case-insensitive but the output should use the same casing as the input!
* Hint: You are allowed to use .sort() function.
*/
let input = 'HelloWorld';
const sortLetters = (string, boolean) => {
let stringToArray = string.split('');
let result;
if (boolean) {
result = stringToArray.sort((a, b) => a.toLowerCase() > b.toLowerCase());
} else {
result = stringToArray.sort((a, b) => a.toLowerCase() < b.toLowerCase());
}
return result.join('');
};
console.log(sortLetters(input, true));
console.log(sortLetters(input, false));
true
68f82c8e4306775df973cc84ff9b26ebae212b79
JavaScript
jacobmccaskey/ascend-coding-challenge
/functions.js
UTF-8
5,991
2.890625
3
[]
no_license
const { routes } = require("./data/data");
function findAllRoutes(startPoint, endPoint, startDistance) {
let routeChain = {
totalDistance: startDistance,
start: startPoint,
end: endPoint,
connections: [],
};
if (!routeChain.cache) {
routeChain.cache = [];
}
if (startPoint === endPoint) {
console.log(
"please help the environment by walking your delivery to the location"
);
return routeChain;
}
const checkIfStartMapped = routes.find(
(route) => route.startPoint === startPoint.toLowerCase()
);
const checkIfEndMapped = routes.find(
(route) => route.startPoint === endPoint.toLowerCase()
);
if (!checkIfStartMapped || !checkIfEndMapped) {
throw new Error("looks like this city isnt mapped yet");
}
for (const route of routes) {
if (route.startPoint === startPoint) {
const { connectingCities } = route;
// checks to see if connecting city is destination and returns routeChain with totalDistance
let connectsToEndPoint = connectingCities.filter(
(connecting) => connecting.city === endPoint
);
// console.log(`${startPoint} ,` + JSON.stringify(connectsToEndPoint));
if (connectsToEndPoint.length !== 0) {
routeChain.totalDistance += connectsToEndPoint[0].distance;
return routeChain;
}
if (connectsToEndPoint.length === 0 || connectsToEndPoint === undefined) {
routeChain.cache.push(startPoint);
let possibleConnects = [];
connectingCities.forEach((option) =>
possibleConnects.push(option.city)
);
routeChain.cache.forEach(
(city) =>
(possibleConnects = possibleConnects.filter(
(connect) => city !== connect
))
);
let routesToCheck = [];
for (let i = 0; i < possibleConnects.length; i++) {
for (let j = 0; j < routes.length; j++) {
// finds next route in routes array to check if that route has connection with destination
if (possibleConnects[i] === routes[j].startPoint) {
routesToCheck.push(routes[j]);
}
}
}
let routeReducer = [];
for (let i = 0; i < routesToCheck.length; i++) {
for (const opt of routesToCheck[i].connectingCities) {
if (opt.city === endPoint) {
routeReducer.push(routesToCheck[i]);
}
}
}
if (routeReducer.length === 0) {
// triggers the recursive function to have another go at finding connections between current city's connections and the final destination
return {
recurse: true,
start: startPoint,
end: endPoint,
connections: connectingCities,
mileCount: startDistance,
routes: routesToCheck,
cache: routeChain.cache,
};
}
// the rest of this code constructs return object based on the parameters given one or several connecting cities connect to final destination.
// start and end city is returned, totalDistance is calculated, and the last connecting point is returned with object.
let shortestRoute = [];
for (let i = 0; i < routeReducer.length; i++) {
for (let point of routeReducer[i].connectingCities) {
if (point.city === endPoint) {
shortestRoute.push({ index: i, distance: point.distance });
}
}
}
let shortest = shortestRoute.reduce((a, b) =>
a.distance < b.distance ? a : b
);
let bestConnectingRoute = routeReducer[shortest.index];
let destinationFromBestRoute = bestConnectingRoute.connectingCities.filter(
(each) => each.city === endPoint
);
let distToConnection = route.connectingCities
.map((connecting) =>
connecting.city === bestConnectingRoute.startPoint
? connecting.distance
: null
)
.filter((num) => num !== null);
let connectionForRouteChain = {
city: bestConnectingRoute.startPoint,
end: destinationFromBestRoute[0].city,
distance: destinationFromBestRoute[0].distance,
};
routeChain.totalDistance += distToConnection[0];
routeChain.totalDistance += shortest.distance;
routeChain.connections.push(connectionForRouteChain);
}
}
}
return routeChain;
}
function recursive(data, array, cache, start) {
let { connections } = data;
let result;
let shortestRoute;
if (cache) {
// filters out cached connections from data that will be looped through
cache.forEach(
(city) =>
(connections = connections.filter((connect) => city !== connect.city))
);
}
for (const connecting of connections) {
result = findAllRoutes(connecting.city, data.end, connecting.distance);
if (!result.recurse) {
result.totalDistance += data.mileCount;
array.push(result);
}
if (array.length > 4) {
shortestRoute = array.reduce((a, b) =>
a.totalDistance < b.totalDistance ? a : b
);
shortestRoute.start = data.start;
return shortestRoute;
}
}
if (array.length === 0) {
return recursive(result, array, cache, start);
}
if (array.length !== 0) {
shortestRoute = array.reduce((a, b) =>
a.totalDistance < b.totalDistance ? a : b
);
shortestRoute.start = start;
return shortestRoute;
}
}
function determineShortestRoute(start, end, miles) {
let options = [];
let cache = [];
const routeDiscovery = findAllRoutes(start, end, miles);
if (routeDiscovery.recurse) {
cache = routeDiscovery.cache;
return recursive(routeDiscovery, options, cache, start);
} else {
return routeDiscovery;
}
}
// let result = determineShortestRoute("miami", "houston", 0);
// console.log(result);
module.exports = { determineShortestRoute };
true
058cbef916920ec3037cf6b3290e1b8c65880463
JavaScript
TrueMistake/quizVanillaJs
/script.js
UTF-8
2,276
3.234375
3
[]
no_license
const quizData = [
{
question: 'How old is Florin',
a: '10',
b: '17',
c: '26',
d: '110',
correct: 'c'
},
{
question: 'What is the most programming language in 2019',
a: 'Java',
b: 'C',
c: 'Python',
d: 'Javascript',
correct: 'd'
},
{
question: 'How old is Florin',
a: '10',
b: '17',
c: '26',
d: '110',
correct: 'c'
},
{
question: 'What is the most programming language in 2019',
a: 'Java',
b: 'C',
c: 'Python',
d: 'Javascript',
correct: 'd'
}
];
const quiz = document.querySelector('.quiz');
const question = document.querySelector('.question');
const radio = document.querySelectorAll('input[type=radio]');
const a_text = document.querySelector('#a');
const b_text = document.querySelector('#b');
const c_text = document.querySelector('#c');
const d_text = document.querySelector('#d');
const btn = document.querySelector('.btn');
let currentQuestion = 0;
let score = 0;
loadQuiz();
function loadQuiz() {
const currentQuiz = quizData[currentQuestion];
question.innerText = currentQuiz.question;
a_text.innerText = currentQuiz.a;
b_text.innerText = currentQuiz.b;
c_text.innerText = currentQuiz.c;
d_text.innerText = currentQuiz.d;
}
function getSelect() {
let answer = undefined;
radio.forEach(el => {
if (el.checked) {
answer = el.nextElementSibling.id;
}
});
return answer;
}
function clearSelect() {
radio.forEach(el => {
el.checked = false;
});
}
btn.addEventListener('click', () => {
let answer = getSelect();
if (answer) {
if (answer === quizData[currentQuestion].correct) {
score++;
}
currentQuestion++;
if (currentQuestion < quizData.length) {
loadQuiz();
clearSelect();
} else {
quiz.innerHTML = `<h2>You answered correctly at ${score} / ${quizData.length} questions</h2> <button onclick="location.reload()">Reload</button>`
}
}
});