blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
3
236
src_encoding
stringclasses
29 values
length_bytes
int64
8
7.94M
score
float64
2.52
5.72
int_score
int64
3
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
8
7.94M
download_success
bool
1 class
6212770630c9e255e8e01952848ea0b341adaa96
JavaScript
goldironhack/IH-Project-2018-5adfa262c2bee800145a994d_webapp_phase1
/index.js
UTF-8
2,167
2.640625
3
[]
no_license
var map; var iniMap={lat:40.7291,lng:-73.9965}; const api_key="AIzaSyAzpOBqITSBf9XFZTm1OuSdU1KRqtJmCgw"; const Neighborhood_Names_GIS="https://data.cityofnewyork.us/api/views/xyye-rtrs/rows.json?accessType=DOWNLOAD"; var infoRows = []; var JDistric = $.get(Neighborhood_Names_GIS) //<!-- Funcion para crear el mapa --> function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 10, center: iniMap }); map.data.loadGeoJson('http://services5.arcgis.com/GfwWNkhOj9bNBqoJ/arcgis/rest/services/nycd/FeatureServer/0/query?where=1=1&outFields=*&outSR=4326&f=geojson'); } //Carga de datos del Neighborhood Names GIS function getDataFromURL(URL){ var data = $.get(URL, function(){ console.log(URL) }) .done( function(){ console.log(data.responseJSON.data); }) .fail( function(error){ console.error(error); }) } function updateAllDatasets(){ var URL = Neighborhood_Names_GIS; getDataFromURL(URL); } //actualiza datos en la tabla(testeo carga de datos) function updateTable(){ tableReference = $("#mainTableBody")[0]; var newRow, district, boroughs ; for( var i = 0; i < (JDistric.responseJSON.data).length; i++){ newRow = tableReference.insertRow(tableReference.rows.length); district = newRow.insertCell(0); boroughs = newRow.insertCell(1); district.innerHTML = JDistric.responseJSON.data[i][10]; boroughs .innerHTML =JDistric.responseJSON.data[i][16]; } } /*var Distric = []; function getDatasDistric() { JDistric .done(function(){ for(var i = 0; i < (JDistric.responseJSON.data).length; i++){ var pS = JDistric.responseJSON.data[i][10]; var marker = new google.maps.Marker({ position: lalg, map: map, }); Distric.push(marker); } }) .fail(function(error){ console.log(error); }); }*/ //uso de los buttons $(document).ready( function(){ $("#getDataButton").on("click", updateAllDatasets); $("#updateTableButton").on("click", updateTable); })
true
27082d2170f09ab99c3cc13a08c015828d01f52b
JavaScript
postcert/CookbookMeanStack
/server/models/Cookbook.js
UTF-8
1,610
2.703125
3
[]
no_license
var mongoose = require('mongoose'); var minRating = [0, 'The value of field `{PATH}` ({VALUE}) lower than the limit ({MIN}).']; var maxRating = [5, 'The value of field `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; var cookbookSchema = mongoose.Schema({ title: {type: String, required:'{PATH} is required', unique: true}, creator: {type: String, required:'{PATH} is required'}, featured: {type: Boolean, required:'{PATH} is required'}, rating: {type: Number, required:'{PATH} is required', max:maxRating, min:minRating}, published: {type: Date, required:'{PATH} is required'} }); var Cookbook = mongoose.model('Cookbook', cookbookSchema); function createDefaultCookbooks() { Cookbook.find({}).exec(function(err, collection) { if(collection.length === 0) { Cookbook.create({title:'Favorites', creator:'dan', featured: true, rating: 4, published: new Date('4/21/2015')}); Cookbook.create({title:'Tasty', creator:'dan', featured: false, rating: 5, published: new Date('1/1/2111')}); Cookbook.create({title:'Yummy', creator:'john', featured: true, rating: 4, published: new Date('2/21/2065')}); Cookbook.create({title:'Food', creator:'john', featured: false, rating: 1, published: new Date('1/1/2111')}); Cookbook.create({title:'Best', creator:'john', featured: true, rating: 3, published: new Date('7/21/1915')}); Cookbook.create({title:'Average', creator:'john', featured: false, rating: 2, published: new Date('4/1/1911')}); } }) } exports.createDefaultCookbooks = createDefaultCookbooks;
true
3ead35a762caae89f96620087840389219424cbc
JavaScript
macalada/reactPractice
/hello-react/src/components/LifecycleA.js
UTF-8
1,203
2.625
3
[]
no_license
import React, { Component } from 'react' import LifecycleB from './LifecycleB' class LifecycleA extends Component { constructor(props) { super(props) this.state = { name:'Bebana' } console.log("A constructor") } static getDerivedStateFromProps(props,state){ console.log("A get derived statefrom props") return null } componentDidMount(){ console.log("A component did mount") } shouldComponentUpdate(){ console.log("A should component update") return true } getSnapshotBeforeUpdate(prevProps, prevState){ console.log('A snapshot before update') return null } componentDidUpdate(){ console.log('A component did update') } handleClick = ()=>{ this.setState({ name:'Baby' }) } render() { console.log("A rendering") return ( <div> <div>LifecycleA</div> <button onClick={this.handleClick}>Change State</button> {/* <LifecycleB/> */} </div> ) } } export default LifecycleA
true
779688c6e437b5aeb5a3948c675b69f0f8ad41da
JavaScript
tsmasuda/finanzieren
/src/main/webapp/resources/js/input.js
UTF-8
160
2.765625
3
[]
no_license
function showLength(str) { var bufsize = 256 - str.value.length; document.getElementById("noteinfo").innerHTML = "あと" + bufsize + "文字入力可能"; }
true
6be12d7995c6afa0152fdf07a0bc30d031d8f71e
JavaScript
NathanWaterman/Stock-Market-React-Demo
/src/components/login/Login.js
UTF-8
4,935
2.5625
3
[]
no_license
import React, { Component, useState, useEffect } from "react"; import { BrowserRouter as Router, Route } from 'react-router-dom'; import { stockInfo } from "../../api/marketData"; import './login.css'; import ErrorUI from '../Error'; import ValidUser from "../App"; class Login extends Component { state = { login_TOKEN: '', loggedin: false, isError: false, } onInputChange = async e => { await this.setState({ login_TOKEN: e.target.value }); }; loginSubmit = e => { e.preventDefault(); window.ACCESS_TOKEN = this.state.login_TOKEN; stockInfo("ba", window.ACCESS_TOKEN) .then(() => { this.setState({ loggedin: true, isError: false }); }) .catch(err => { this.setState({ isError: true }); console.log(err); }); }; removeErr = updateErr => { this.setState({ isError: updateErr }); } isAuth = () => { if (this.state.loggedin) { return <Route component={ValidUser} /> } else { return <div className="login-ui"> <div className="column"> <h2 className="ui teal image header"> <div className="content"> Please Enter Authentication Token</div> </h2> <form className="ui large form" onSubmit={this.loginSubmit}> <div className="ui stacked segment"> <div className="field"> <div className="ui left icon input"> <i className="lock icon"></i> <input type="text" onChange={this.onInputChange} /> </div> </div> <button className="ui fluid large teal submit button" type="submit">Login</button> </div> </form> {this.state.isError ? <ErrorUI removeErr={this.removeErr} errMsg="Please Enter the Correct Authentication Token" /> : ''} </div> </div> } } componentDidMount() { this.isAuth(); } render() { return ( <Router> <div> {this.isAuth()} </div> </Router> ) } } export default Login; // REACT HOOK // const Login = () => { // const [login_TOKEN, SET_login_TOKEN] = useState(''); // const [loggedin, setLoggedIn] = useState(false); // const [isError, setIsError] = useState(false); // const onInputChange = async e => { // await SET_login_TOKEN(e.target.value); // }; // const loginSubmit = e => { // e.preventDefault(); // window.ACCESS_TOKEN = login_TOKEN; // stockInfo("ba", window.ACCESS_TOKEN) // .then(() => { // setLoggedIn(true); // setIsError(false); // }) // .catch(err => { // setIsError(true); // console.log(err); // }); // }; // const removeErr = updateErr => { // setIsError(updateErr); // } // const isAuth = () => { // if (loggedin) { // return <Route component={ValidUser} /> // } // else { // return <div className="login-ui"> // <div className="column"> // <h2 className="ui teal image header"> // <div className="content"> Please Enter Authentication Token</div> // </h2> // <form className="ui large form" onSubmit={loginSubmit}> // <div className="ui stacked segment"> // <div className="field"> // <div className="ui left icon input"> // <i className="lock icon"></i> // <input type="text" onChange={onInputChange} /> // </div> // </div> // <button className="ui fluid large teal submit button" type="submit">Login</button> // </div> // </form> // {isError ? <LoginError removeErr={removeErr} /> : ''} // </div> // </div> // } // } // return ( // <Router> // <div> // {isAuth()} // </div> // </Router> // ); // } // export default Login;
true
f4bed04e463e30dded80976747307ab6b81d0eb9
JavaScript
daniel12fsp/simple_http_server
/app.js
UTF-8
415
2.90625
3
[]
no_license
/* salvar o arquivo ./app.js */ const http = require("http"); const url = require("url"); const port = process.env.PORT || 3000; const server = http.createServer((req, res) => { res.writeHead(200, { "Content-Type": "text/html" }); res.statusCode = 200; res.write(`<h1>Hello World</h1>${new Date()}`); res.end(); }); server.listen(port, () => { console.log(`Server listening on the port ${port}`); });
true
f8204b478e1526f2012d0ec447f651d900dada74
JavaScript
Joetib/gmsa
/static/js/base.js
UTF-8
1,898
2.953125
3
[ "MIT" ]
permissive
function readURL(input, destination) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { destination.innerText = ""; let img = document.createElement("img"); img.src = e.target.result; img.classList.add("img-default"); img.style.height = "100%"; destination.appendChild(img); } reader.readAsDataURL(input.files[0]); // convert to base64 string } } function readMultipleURL(input, destination) { if (input.files && input.files[0]) { destination.innerText = ""; for (item of input.files){ var reader = new FileReader(); reader.onload = function (e) { let column = document.createElement("div"); column.classList.add("col-6"); column.classList.add("col-sm-4"); column.classList.add("col-md-4"); column.classList.add("p-0"); let img = document.createElement("img"); img.src = e.target.result; img.classList.add("img-thumbnail"); img.style.height="100px" img.style.width = "100px"; img.style.objectFit = "cover"; destination.appendChild(img); column.appendChild(img); destination.appendChild(column); } reader.readAsDataURL(item); }; //reader.readAsDataURL(input.files[0]); // convert to base64 string } } $(document).ready(function () { let items = document.getElementsByClassName("image-form-section") for (let item of items ) { item.querySelector("input[type='file']").addEventListener("change", (e) => { readMultipleURL(e.target, item.querySelector(".img-display")) }); } });
true
41471c1af72d0a72397178bacc7f62e39723c1f7
JavaScript
Odintsov11/loftschool-burgers
/src/js/slider.js
UTF-8
2,026
2.796875
3
[]
no_license
//slider const initSlider = () => { const ENTER_KEY_CODE = 13; const arrows = $('.slider__arrow'); const slider = $('.slider__list'); const sliderItems = slider.find('.slider__item'); const count = sliderItems.length; const defineSlide = () => { const sliderItemActive = sliderItems.filter('.slider__item--active'); let index = sliderItemActive.index(); return { activeSlide: sliderItemActive, nextIndex: index === count - 1 ? 0 : index + 1, prevIndex: index === 0 ? count - 1 : index - 1 }; }; const performSlider = index => { const width = 100 / count; slider.css('transform', 'translateX(' + -width * index + '%)'); slider.on('transitionend', evt => { if (evt.originalEvent.propertyName !== 'transform') { return; } sliderItems .eq(index) .addClass('slider__item--active') .siblings() .removeClass('slider__item--active'); }); }; const slideEventHandler = evt => { const target = $(evt.currentTarget); let index; if (target.hasClass('slider__arrow--right')) { index = defineSlide().nextIndex; } else { index = defineSlide().prevIndex; } performSlider(index); }; arrows.on({ click: slideEventHandler, keydown: evt => { if (evt.keyCode === ENTER_KEY_CODE) { slideEventHandler(evt); } } }); if (window.matchMedia('screen and (max-width: 768px)').matches) { let startX; slider.on('touchstart', evt => { startX = +evt.originalEvent.changedTouches[0].clientX; }); slider.on('touchend', evt => { const BASE_DELTA_X = 50; const deltaX = +evt.originalEvent.changedTouches[0].clientX - startX; let index; if (deltaX > BASE_DELTA_X) { index = defineSlide().prevIndex; } else if (deltaX < -BASE_DELTA_X) { index = defineSlide().nextIndex; } else { return; } performSlider(index); }); } }; export default initSlider;
true
5c2bdcf0873f5a4045a89ff5e200c6026b806217
JavaScript
zhangshuo00/JS-advanced-lessons
/课程练习/ES6迭代器和生成器/0202.js
UTF-8
672
3.515625
4
[]
no_license
/**Promise */ setTimeout(function(){ console.log("world"); },3000); console.log("hello"); /** Promise将异步的操作写成同步执行的方式 * * resolve是异步操作成功时的调用 * reject是异步操作失败时的调用 */ new Promise(function(resolve,reject){ setTimeout(function(){ console.log('world'); resolve(); },3000) }).then(function(){ /**对应resolve() */ console.log('hello'); console.log(val); },function(){ /**对应reject() */ }).catch(function(e){ // console.log(val); console.log(e); }).finally(function(){ /**无论如何都会执行 */ console.log("finally执行结束"); })
true
0a00cdb296ee7e945292efa1ddc541d41f9e01dd
JavaScript
ztrabzada1988/omdb-api
/app.js
UTF-8
1,209
3.359375
3
[]
no_license
$(document).ready(function() { // once submit button is clicked, plug the searchItem in url $('#button').on('click', function(event) { event.preventDefault(); // varibale that takes the searched item from submit var searchItem = $('#query').val() // run getRequest function getRequest(searchItem); // empty form $('#query').val(""); }); }); // define getRequest function that takes requests data from omdb server function getRequest(searchItem) { // define search and data type parameters var params = { s: searchItem, r: 'json' }; // define url of the server website url = 'http://www.omdbapi.com'; // request to get results as JSON from server $.getJSON(url, params, function(data){ showResults(data.Search); }); } // define showResults function the inserts searchItem result into search-results div function showResults(results){ var result = ""; // got through each array and get the value of the Title only $.each(results, function(index,value){ result += '<p>' + value.Title + '</p>'; }); // append the information into search-results div. $('#search-results').append(result); }
true
4833baca344ffb2b3adab99e53eda8efff9547ee
JavaScript
panda-os/media-platform-js-sdk
/src/platform/management/job/source.js
UTF-8
402
2.71875
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
function Source(data) { /** * @type {string} */ this.fileId = null; /** * @type {string} */ this.path = null; if (data) { this.deserialize(data); } } /** * @param data * @private */ Source.prototype.deserialize = function (data) { this.fileId = data.fileId; this.path = data.path; }; /** * @type {Source} */ module.exports = Source;
true
8340e2638e9e67a056b3ad41c36748a7f7518cb1
JavaScript
heyannag/Project_2_TLLDL
/encounter_plots.js
UTF-8
1,539
2.65625
3
[]
no_license
function unpack(rows, index) { return rows.map(function(row) { return row[index]; }); }; function getData() { d3.json(/* database/encounters_table */).then(function(data) { var state = unpack(/* state data, index */); var age = unpack(/* age data, index */); var gender = unpack(/* gender data, index */); var race = unpack(/* race data, index */); var city = unpack(/* city data */); var lat = unpack(/* latitude data */); var long = unpack(/* longitude data */); var mental_illness = unpack(/* mental illness data */); var year = unpack(/* year */); buildPlot(/* table.length, state */); }) } function buildPlot() { d3.json(/* database/encounters_table */).then(function(data) { var state = unpack(/* state data, index */); var age = unpack(/* age data, index */); var gender = unpack(/* gender data, index */); var race = unpack(/* race data, index */); var city = unpack(/* city data */); var lat = unpack(/* latitude data */); var long = unpack(/* longitude data */); var mental_illness = unpack(/* mental illness data */); var year = unpack(/* year */); getData(); var trace = { type: "bar", name: /* data name? */, x: /* data to plot */, y: /* encounters.length */, } var data = [trace]; var layout = { title: "", } }) }
true
0a662366c1a8892432b2a21af0532706646eca25
JavaScript
KhristinaVasko/KhristinaVasko.github.io
/final/js/script.js
UTF-8
2,558
2.671875
3
[]
no_license
$(document).ready(function(){ //slider $('.slider').slick({ infinite: true, autoplay: true, speed: 500, arrows: false, fade: true, cssEase: 'linear', dots: false, }); // part of code for counting numbers in block 5 $(".counter").counterUp({ delay:10, time:1000}) }); function openNav() { document.getElementById("mySidenav").style.width = "250px"; } function closeNav() { document.getElementById("mySidenav").style.width = "0"; } // modal window for counting calories var modal = document.getElementById("myModal"); var btn = document.getElementById("modalbutton"); var span = document.getElementsByClassName("close")[0]; btn.onclick = function() { modal.style.display = "block"; } span.onclick = function() { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } //scroll const anchors = document.querySelectorAll('a[href*="#"]') for (let anchor of anchors) { anchor.addEventListener('click', function (e) { e.preventDefault() const blockID = anchor.getAttribute('href').substr(1) document.getElementById(blockID).scrollIntoView({ behavior: 'smooth', block: 'start' }) }) } //cart const cartBtn = document.querySelector('.cart-btn'); const closeCartBtn = document.querySelector('.close-cart'); const clearCartBtn = document.querySelector('.clear-cart'); const cartDOM = document.querySelector('.cart'); const cartOverlay= document.querySelector('.cart-overlay'); const cartItems= document.querySelector('.cart-items'); const cartTotal= document.querySelector('.cart-total'); const cartContent= document.querySelector('.cart-content'); const productsDOM= document.querySelector('.products-center'); // let cart = []; //getting products class Products{ async getProducts(){ try{ let result = await fetch('products.json'); let data = await result.json(); return data; return result } catch (error){ console.log(error); } } } // display prod class UI { } // local storage class Storage{ } document.addEventListener("DOMContentLoaded",()=>{ const ui = newUI(); const products = new Products(); //get all products products.getProducts().then(data => console.log(data)); })
true
b5c464e3fc434283109cb9b7502e7327b66d0b2f
JavaScript
n0thanks/CS20-Portfolio
/CS20 Projekt/js/main.js
UTF-8
1,103
3.328125
3
[]
no_license
// Reaction Time Project // Global Variables let redButtonEl = document.getElementById("red-circle"); redButtonEl.addEventListener("click", badClick); let startBtnEl = document.getElementById("start-btn"); startBtnEl.addEventListener("click", startTest); let reactionBtnEl = document.getElementById("green-circle"); reactionBtnEl.addEventListener("click", reactionClicked); let currentTime = document.getElementById("click-time"); let average = document.getElementById("average-time"); let nextReaction = setInterval(reactionClicked, randomInt(1000, 3001)); let time = [reactionClicked.now()]; function startTest(event) { setInterval(changeColor, randomInt(1500, 3001)); } function changeColor() { redButtonEl.style = "display: none;"; reactionBtnEl.style = "display: initial;"; } function reactionClicked(event) { reactionBtnEl.style = "display: none;"; redButtonEl.style = "display: initial;"; currentTime.innerHTML = `${time}`; nextReaction+= 5; } function badClick(event) { alert("Do not click before the circle is green!"); }
true
3c27096e1af4a309972ef016ecbfecfa26d484fe
JavaScript
maryhoag/TriviaGame
/assets/javascript/app.js
UTF-8
2,727
3.25
3
[]
no_license
// $(document).ready(function() { var app = { // will these need to be outside the app object? counter: 10, index: 0, wins: 0, losses: 0, questions: [ "What's with the pineapples? It's an inside joke.", "The actor who plays Lassie once played a psychic.", "Every actor from The Breakfast Club has appeared on Psych.", "Shawn always chews Wrigley's doublemint gum.", "In season 5, Gus teaches Lassiter to tap dance.", "Since Shawn will never go fishing, Shawn's father takes Lassiter.", "In one epsidoe, Juliette waits all day in a train station for an ex boyfriend.", "Shawn and Gus give Gus' car a nickname -- The Blackberry!", "In one epsidoe, Shawn gets a part on a Bollywood movie.", "Shawn's father is named Harry." ], answers: [ true, true, false, false, true, true, true, false, false, false ], //delivers next qustion newQuestion: function() { //setTimeout($(".gameboard").html(app.questions[app.index]), (10 * 1000)); $(".gameboard").html(app.questions[app.index]); app.start(); }, correctAnswer: function() { $(".gameboard").html("Correct! What are you, psychic?"); app.wins++; app.counter = 10; $(".correct").html("# Correct: " + app.wins); }, incorrectAnswer: function() { $(".gameboard").html("Wrong! Some psychic detective you are!"); app.losses++; app.counter = 10; $(".incorrect").html("# Incorrect: " + app.losses); }, start: function() { setInterval(app.count, 1000); $(".timer").html("Time remaining:" + app.counter); }, count: function() { app.counter--; //$(".timer").html("Time remaining:" + app.counter); if(app.counter === 0) { app.stop() } }, //sop counting stop: function() { clearInterval(app.count); }, //sets replay button again: function() { $("#replay").append('<button type="button" class="btn btn-warning centered">Wanna play again?</button>'); }, game: function() { //use index for i here, or will i want them seperate //i've hard coded 5 here: fix or add a random question generator for(var i = 0; i < app.questions.length; i++) { app.index = i; //ask question var trueness; app.newQuestion(); var pause = setInterval(function() { $(".response").click(function() { console.log("message"); return trueness = $(this).data("truth"); }); //console.log(trueness); if(trueness == app.answers[app.index]) { app.correctAnswer(); console.log(trueness); } else { app.incorrectAnswer(); } }, 10 * 1000); setTimeout(function(){ console.log("waiting"); }, 10 * 1000); } clearInterval(app.counting); console.log(this); setTimeout(app.again, 10 * 1000); } }; app.game(); });
true
7a36c2b608fe4a07daa94ebf52657964219e8cd0
JavaScript
mzulli/misc-js-work
/spyCoder.js
UTF-8
1,419
4.03125
4
[]
no_license
// encode or decode the string // // sample string: ("encode: the big brown bear") // // first word of input will be "encode" or "decode" // // to encode: replace any of the six most common letters in english lang // with the next most common. ie, replace 'e' with 't', 'a' with 'o'. // 'n' gets replaced with 'e'. // // most common letters are, in order: e, t, a, o, i, n // // decoding is the reverse procedure. ie, replace 't' with 'e', 'i' with 'o', // 'e' with 'n'. function spyCoder(input) { // set up arrays of most common letters and replacements var common = ['e', 't', 'a', 'o', 'i', 'n']; var encode = ['t', 'a', 'o', 'i', 'n', 'e']; var decode = ['n', 'e', 't', 'a', 'o', 'i']; var process; // capture the string to be processed var text = input.slice(8).split(''); // decide whether to encode or decode if (input.charAt(0) === 'e') process = encode; else process = decode; // loop through text for (var i = 0; i < text.length; i++) { // loop through common letters for (var j = 0; j < common.length; j++) { if (text[i] === common[j]) { text[i] = process[j]; break; } // if } // j loop } // i loop return(text.join('')); } spyCoder("encode: the big brown bear"); // aht bng briwe btor spyCoder("decode: aht bng briwe btor"); // the big brown bear
true
8e98c77398bffabad7c2037c3f498efdf3788915
JavaScript
sunxing102005/vue_management_system
/vue-express-backstage/websocket/wsServer.js
UTF-8
1,320
2.78125
3
[]
no_license
let webSocketServer = require('websocket').server; let http = require('http'); let server = http.createServer((req,res)=>{ console.log('received request from '+req.url); res.end(); }) server.listen(8090, function() { console.log((new Date()) + ' Server is listening on port 8090'); }); let wsServer = new webSocketServer({ httpServer:server, autoAcceptConnections:false }) function originIsAllowed(origin) { // put logic here to detect whether the specified origin is allowed. return true; } wsServer.on('request',function(request){ if (!originIsAllowed(request.origin)) { // Make sure we only accept requests from an allowed origin request.reject(); console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); return; } let connection = request.accept('',request.origin); connection.on('message',(message)=>{ debugger if(message.type=='utf8'){ connection.sendUTF(message.utf8Data); console.log('server accept message:'+message.utf8Data); }else{ connection.send(message); } }) connection.on('close', function(reasonCode, description) { console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); }); })
true
970a542818a1ba328fb2d9d05b4c1e73c1d03273
JavaScript
tranmike270/Liri-CLI
/liri.js
UTF-8
3,876
2.828125
3
[]
no_license
var Spotify = require('node-spotify-api'); var Twitter = require('twitter'); var request = require('request'); require('dotenv').config(); var keys = require('./keys.js'); var fs = require('fs'); var spotify = new Spotify(keys.spotify); var client = new Twitter(keys.twitter); switch(process.argv[2]){ case 'my-tweets': getTweets(); break; case 'spotify-this-song': if(process.argv[3]){ var song = process.argv[3] for(var i = 4; typeof process.argv[i] !== 'undefined'; i++){ song += ("+" + process.argv[i]); } getSong(song); }else{ getSong('Ace of Base The Sign'); } break; case 'movie-this': if(process.argv[3]){ var movie = process.argv[3]; for(var i = 4; typeof process.argv[i] !== 'undefined'; i++){ movie += ("+" + process.argv[i]); } getMovie(movie); }else{ getMovie('Mr. Nobody'); } break; case 'do-what-it-says': doText(); break; default: console.log("Please Enter a valid command") break; } function getTweets(){ var params = {screen_name: 'themichaelttran', count: 20}; client.get('statuses/user_timeline', params, function(error, tweets, response){ if(error){ console.log(error); }else { console.log("These are the 20 recent tweets from user @themichaeltran"); for(var i = 0; i < tweets.length; i++){ var tweetNum = i + 1; console.log("Tweet " + tweetNum); console.log("Created at : " + tweets[i].created_at); console.log(tweets[i].text) console.log("------------------------------------"); } } }) }; function getSong(song){ spotify.search({type: 'track', query: song, limit: 1}, function(err, data){ if(err){ return console.log('Error occurred ' + err); } var artist = data.tracks.items[0].artists console.log("List of artist"); for(var j = 0; j < artist.length; j++){ console.log("-" + artist[j].name); } console.log("The song's name"); console.log("-" + data.tracks.items[0].name); console.log("Link of the song from Spotify"); console.log("-" + data.tracks.items[0].external_urls.spotify); console.log("The album the song is from") console.log("-" + data.tracks.items[0].album.name); console.log("-----------------------------------------------------") }) } function getMovie(movie){ var queryUrl = "http://www.omdbapi.com/?t=" + movie + "&y=&plot=short&apikey=f9722351"; request(queryUrl, {json : true}, (err, res, body) => { if(err) { return console.log(err); } console.log('```'); console.log(" * Title: " + body.Title); console.log(" * Year: " + body.Year); console.log(" * IMDB Rating: " + body.imdbRating); console.log(" * Rotten Tomatoes Rating: " + body.Ratings[1].Value); console.log(" * Country(s): " + body.Country); console.log(" * Language(s): " + body.Language); console.log(" * Plot: " + body.Plot); console.log(" * Actors: " + body.Actors); console.log('```'); }) }; function doText(){ fs.readFile('./random.txt', 'utf8', function(error, data){ var dataArr = data.split(','); var method = dataArr[0]; var argument = dataArr[1]; console.log(method + " " + argument); switch(method){ case 'spotify-this-song': getSong(argument); break; case 'movie-this': getMovie(argument); break; } }) }
true
29d7f3740cd1b4c8edc07f2283a26626b956e69c
JavaScript
howardbdev/javascript-handlebars-templates-lab-v-000
/index.js
UTF-8
4,378
3.953125
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// 1 Create a form template with an id of recipe-form-template that will be used to enter new recipes. Make the form submit with a createRecipe() function. Provide inputs for recipe name, description, and at least five ingredients. Hint: Get comfy collecting values with getElementsByName(). // 2 Create a template with an id of recipe-template. This template should contain the recipe name and an "Edit Recipe" link, and render the recipeDetailsPartial in step 3. Render this template with the recipe data when the user submits the form. function init() { //put any page initialization/handlebars initialization here Handlebars.registerHelper('displayIngredient', function(ingredient) { return new Handlebars.SafeString("<li name='ingredientsList'>" + ingredient + "</li>") }) Handlebars.registerPartial('recipeFormPartial', document.getElementById('recipe-form-partial').innerHTML) Handlebars.registerPartial('recipeDetailsPartial', document.getElementById("recipe-details-partial").innerHTML) let formTemplate = document.getElementById("recipe-form-template").innerHTML let template = Handlebars.compile(formTemplate) document.getElementsByTagName('main')[0].innerHTML = template({'submitAction':'createRecipe()'}) // 3 Register a partial called recipeDetailsPartial for for the description and ingredients of the recipe. Create a template with an id of recipe-details-partial to hold the markup. Use the each helper to display the collection of ingredients. // 4 Use a custom helper called displayIngredient to display each ingredient within the each block. } document.addEventListener("DOMContentLoaded", function(event) { init() }) // function displayEditForm(){ // let name = document.getElementById("nameHeader").innerText // let description = document.getElementById("recipeDescription").innerText // let ingredientElements = document.getElementsByName("ingredientsList").innerText // let ingredients = [] // for (let i = 0, l = ingredientElements.length; i < l; i++) { // ingredients.push(ingredientElements[i].innerText) // } function displayEditForm() { var name = document.getElementById("nameHeader").innerText var description = document.getElementById("recipeDescription").innerText var ingredientsNodes = document.getElementsByName("ingredientsList") var ingredients = [] for(var i=0;i<ingredientsNodes.length;i++) { ingredients.push(ingredientsNodes[i].innerText) } let recipe = {name, description, ingredients, submitAction: 'createRecipe()'} let recipeFormTemplate = document.getElementById('recipe-form-template').innerHTML let template = Handlebars.compile(recipeFormTemplate) document.getElementById("main").innerHTML = template(recipe) } function createRecipe(){ const recipe = getRecipeValues() let recipeTemplate = document.getElementById('recipe-template').innerHTML let template = Handlebars.compile(recipeTemplate) document.getElementById("main").innerHTML = template(recipe) } function updateRecipe(){ const recipe = getRecipeValues() let recipeTemplate = document.getElementById('recipe-template').innerHTML let template = Handlebars.compile(recipeTemplate) document.getElementById("main").innerHTML = template(recipe) } function getRecipeValues(){ let name = document.getElementsByName("name").value let description = document.getElementsByName("description").value const ingredentElements = document.getElementsByName("ingredients") let ingredients = [] for (let i = 0, l = ingredients.length; i < l; i++) { if (ingredientElements[i].value !== "") { ingredients.push(ingredientElements[i].value) } } let recipe = {name, ingredients, description} return recipe } // 5 On click of your "Edit Recipe" link, call a displayEditForm() function that renders a template called recipe-form-template. Allow your recipe to be edited using this form, and re-render the recipe template with the updated information using a updateRecipe() function on form submit. // 6 Refactor your forms so that recipe-form and the edit form template are both constructed with the same recipe-form-template. The template should render with the recipe data for edit, and with empty values for a new recipe. Hint: Don't forget you can pass any object with any properties as the context for your templates, including, for instance, values for onsubmit.
true
8bf52a4b897c94e3efb0bdc83950d05bc2290032
JavaScript
anikonchuk/fleddit-client
/src/actions/postsActions.js
UTF-8
1,833
2.671875
3
[ "MIT" ]
permissive
const BASE_URL = "https://fleddit-api.herokuapp.com" export function fetchAllPosts() { return (dispatch) => { dispatch({type: 'START_ADDING_POSTS'}); return fetch(`${BASE_URL}/api/posts`) .then(response => response.json()) .then(posts => dispatch({type: 'ADD_ALL_POSTS', posts})); }; } export function fetchTargetPost(postId) { return (dispatch) => { dispatch({type: 'START_ADDING_POSTS'}); return fetch(`${BASE_URL}/api/posts/${postId}`) .then(response => response.json()) .then(post => dispatch({type: 'ADD_TARGET_POST', post})) } } export function createPost(post) { return (dispatch) => { return fetch(`${BASE_URL}/api/posts`, { method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ post: post }) }) // .then(res => { // if (res.ok) { // return res // } // // return throw Error(res) // }) .then(response => response.json()) .then(post => { dispatch(addPost(post)); }) //.catch(alert("Something went wrong. Please try again")) } } export function updateLikes(id, likes) { return (dispatch) => { const post_likes = { likes: likes } return fetch(`${BASE_URL}/api/posts/${id}`, { method: "PATCH", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({post: post_likes}) }) .then(response => response.json()) .then(post => { dispatch(updatePost(post)); }) } } function updatePost(post) { return { type: 'UPDATE_LIKES_SUCCESS', post } } function addPost(post){ return { type: 'CREATE_POST_SUCCESS', post } } export function removeTargetPost() { return { type: 'CLEAR_TARGET_POST' } }
true
85234d856971217c68c740a17721d5d036c4d1a5
JavaScript
pzyu/CAT048
/js/app - Copy.js
UTF-8
16,880
2.828125
3
[]
no_license
const animSpd = 100; // Animation speed in ms var main = function() { var active = $('.tile').first(); var startingPos = $('#grid-12'); active.css({top: startingPos.position().top, left: startingPos.position().left}); active.text(startingPos.attr('id')); startingPos.addClass('taken-tile'); var next = active.next(); var nextPos = $('#grid-13'); next.css({top: nextPos.position().top, left: nextPos.position().left}); next.css("background-color", "red"); next.text(nextPos.attr('id')); nextPos.addClass('taken-tile'); $(document).keyup(function(event) { var end = $('.grid-tile').first(); switch(event.which) { case 37: console.log('left was pressed'); $('.tile').each(moveLeft); break; case 38: console.log('up was pressed'); $($('.tile').get().reverse()).each(moveUp); break; case 39: console.log('right was pressed'); //$('.tile').each(moveRight); $($('.tile').get().reverse()).each(moveRight); break; case 40: console.log('down was pressed'); $('.tile').each(moveDown); break; default: return; }; }); }; function moveUp() { console.log('moving up'); //console.log(this); getTopAtCol($('.tile:contains(' + this.textContent + ')'), this.textContent); }; function moveDown() { console.log('moving down'); getBtmAtCol($('.tile:contains(' + this.textContent + ')'), this.textContent); }; function moveLeft() { console.log('moving left'); getTopAtRow($('.tile:contains(' + this.textContent + ')'), this.textContent); }; function moveRight() { console.log('moving right'); getBtmAtRow($('.tile:contains(' + this.textContent + ')'), this.textContent); }; function getTopAtCol1(tile, col) { console.log("Checking for top at: " + col); // If grid 0 not taken if (!$('#grid-0').hasClass('taken-tile')) { tile.animate({ top: $('#grid-0').position().top }, animSpd); tile.text('grid-0'); // Add class and remove from current $('#grid-0').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } }; function getBtmAtCol1(tile, col) { console.log("Checking for btm at: " + col); if (!$('#grid-12').hasClass('taken-tile')) { tile.animate({ top: $('#grid-12').position().top }, animSpd); tile.text('grid-12'); $('#grid-12').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } }; function getTopAtCol(tile, col) { console.log("Checking for top at: " + col); //console.log(col); console.log(tile); //console.log(tile); // If in first column, check through each // And not in grid-0 // Check for position later if (col === 'grid-4' || col === 'grid-8' || col === 'grid-12') { // Check if any tile is at grid-0 if ($('.tile:contains("grid-0")').length === 0) { // If no tiles, the move up to that col // Move to grid 0 and rename tile.animate({ top: $('#grid-0').position().top }, animSpd); tile.text('grid-0'); $('#grid-0').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-4")').length === 0) { tile.animate({ top: $('#grid-4').position().top }, animSpd); tile.text('grid-4'); $('#grid-4').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-8")').length === 0) { tile.animate({ top: $('#grid-8').position().top }, animSpd); tile.text('grid-8'); $('#grid-8').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else { console.log ("Stuck at 12"); } } if (col === 'grid-5' || col === 'grid-9' || col === 'grid-13') { console.log($('.tile:contains("grid-1")')); if ($('.tile:contains("grid-1")').length === 0) { tile.animate({ top: $('#grid-1').position().top }, animSpd); tile.text('grid-1'); $('#grid-1').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-5")').length === 0) { tile.animate({ top: $('#grid-5').position().top }, animSpd); tile.text('grid-5'); $('#grid-5').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-9")').length === 0) { tile.animate({ top: $('#grid-9').position().top }, animSpd); tile.text('grid-9'); $('#grid-9').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else { console.log ("Stuck at 13"); } } if (col === 'grid-6' || col === 'grid-10' || col === 'grid-14') { if ($('.tile:contains("grid-2")').length === 0) { tile.animate({ top: $('#grid-2').position().top }, animSpd); tile.text('grid-2'); $('#grid-2').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-6")').length === 0) { tile.animate({ top: $('#grid-6').position().top }, animSpd); tile.text('grid-6'); $('#grid-6').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-10")').length === 0) { tile.animate({ top: $('#grid-10').position().top }, animSpd); tile.text('grid-10'); $('#grid-10').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else { console.log ("Stuck at 14"); } } if (col === 'grid-7' || col === 'grid-11' || col === 'grid-15') { if ($('.tile:contains("grid-3")').length === 0) { tile.animate({ top: $('#grid-3').position().top }, animSpd); tile.text('grid-3'); $('#grid-3').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-7")').length === 0) { tile.animate({ top: $('#grid-7').position().top }, animSpd); tile.text('grid-7'); $('#grid-7').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-11")').length === 0) { tile.animate({ top: $('#grid-11').position().top }, animSpd); tile.text('grid-11'); $('#grid-11').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else { console.log ("Stuck at 15"); } } }; function getBtmAtCol(tile, col) { console.log("Checking for btm at: " + col); // If in first column, check through each if (col === 'grid-0' || col === 'grid-4' || col === 'grid-8') { // Check if any tile is at grid-12 if ($('.tile:contains("grid-12")').length === 0) { // If no tiles, the move up to that col // Move to grid 0 and rename tile.animate({ top: $('#grid-12').position().top }, animSpd); tile.text('grid-12'); $('#grid-12').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-8")').length === 0) { tile.animate({ top: $('#grid-8').position().top }, animSpd); tile.text('grid-8'); $('#grid-8').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-4")').length === 0) { tile.animate({ top: $('#grid-4').position().top }, animSpd); tile.text('grid-4'); $('#grid-4').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else { console.log ("Stuck at 0"); } } if (col === 'grid-1' || col === 'grid-5' || col === 'grid-9') { if ($('.tile:contains("grid-13")').length === 0) { tile.animate({ top: $('#grid-13').position().top }, animSpd); tile.text('grid-13'); $('#grid-13').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-9")').length === 0) { tile.animate({ top: $('#grid-9').position().top }, animSpd); tile.text('grid-9'); $('#grid-9').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-5")').length === 0) { tile.animate({ top: $('#grid-5').position().top }, animSpd); tile.text('grid-5'); $('#grid-5').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else { console.log ("Stuck at 1"); } } if (col === 'grid-2' || col === 'grid-6' || col === 'grid-10') { if ($('.tile:contains("grid-14")').length === 0) { tile.animate({ top: $('#grid-14').position().top }, animSpd); tile.text('grid-14'); $('#grid-14').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-10")').length === 0) { tile.animate({ top: $('#grid-10').position().top }, animSpd); tile.text('grid-10'); $('#grid-10').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-6")').length === 0) { tile.animate({ top: $('#grid-6').position().top }, animSpd); tile.text('grid-6'); $('#grid-6').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else { console.log ("Stuck at 2"); } } if (col === 'grid-3' || col === 'grid-7' || col === 'grid-11') { if ($('.tile:contains("grid-15")').length === 0) { tile.animate({ top: $('#grid-15').position().top }, animSpd); tile.text('grid-15'); $('#grid-15').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-11")').length === 0) { tile.animate({ top: $('#grid-11').position().top }, animSpd); tile.text('grid-11'); $('#grid-11').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else if ($('.tile:contains("grid-7")').length === 0) { tile.animate({ top: $('#grid-7').position().top }, animSpd); tile.text('grid-7'); $('#grid-7').addClass('taken-tile'); $('#' + col).removeClass('taken-tile'); } else { console.log ("Stuck at 3"); } } } // Get leftmost function getTopAtRow(tile, row) { console.log("Checking for leftmost at: " + row); // If in first column, check through each if (row === 'grid-1' || row === 'grid-2' || row === 'grid-3') { if ($('.tile:contains("grid-0")').length === 0) { tile.animate({ left: $('#grid-0').position().left }, animSpd); tile.text('grid-0'); $('#grid-0').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-1")').length === 0) { tile.animate({ left: $('#grid-1').position().left }, animSpd); tile.text('grid-1'); $('#grid-1').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-2")').length === 0) { tile.animate({ left: $('#grid-2').position().left }, animSpd); tile.text('grid-2'); $('#grid-2').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else { console.log("Stuck at 3"); } } if (row === 'grid-5' || row === 'grid-6' || row === 'grid-7') { if ($('.tile:contains("grid-4")').length === 0) { tile.animate({ left: $('#grid-4').position().left }, animSpd); tile.text('grid-4'); $('#grid-4').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-5")').length === 0) { tile.animate({ left: $('#grid-5').position().left }, animSpd); tile.text('grid-5'); $('#grid-5').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-6")').length === 0) { tile.animate({ left: $('#grid-6').position().left }, animSpd); tile.text('grid-6'); $('#grid-6').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else { console.log("Stuck at 7"); } } if (row === 'grid-9' || row === 'grid-10' || row === 'grid-11') { if ($('.tile:contains("grid-8")').length === 0) { tile.animate({ left: $('#grid-8').position().left }, animSpd); tile.text('grid-8'); $('#grid-8').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-9")').length === 0) { tile.animate({ left: $('#grid-9').position().left }, animSpd); tile.text('grid-9'); $('#grid-9').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-10")').length === 0) { tile.animate({ left: $('#grid-10').position().left }, animSpd); tile.text('grid-10'); $('#grid-10').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else { console.log("Stuck at 11"); } } if (row === 'grid-13' || row === 'grid-14' || row === 'grid-15') { if ($('.tile:contains("grid-12")').length === 0) { tile.animate({ left: $('#grid-12').position().left }, animSpd); tile.text('grid-12'); $('#grid-12').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-13")').length === 0) { tile.animate({ left: $('#grid-13').position().left }, animSpd); tile.text('grid-13'); $('#grid-13').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-14")').length === 0) { tile.animate({ left: $('#grid-14').position().left }, animSpd); tile.text('grid-14'); $('#grid-14').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else { console.log("Stuck at 15"); } } }; // Get rightmost function getBtmAtRow(tile, row) { console.log("Checking for rightmost at: " + row); // If in first rowumn, check through each if (row === 'grid-0' || row === 'grid-1' || row === 'grid-2') { if ($('.tile:contains("grid-3")').length === 0) { tile.animate({ left: $('#grid-3').position().left }, animSpd); tile.text('grid-3'); $('#grid-3').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-2")').length === 0) { tile.animate({ left: $('#grid-2').position().left }, animSpd); tile.text('grid-2'); $('#grid-2').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-1")').length === 0) { tile.animate({ left: $('#grid-1').position().left }, animSpd); tile.text('grid-1'); $('#grid-1').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else { console.log("Stuck at 0"); } } if (row === 'grid-4' || row === 'grid-5' || row === 'grid-6') { if ($('.tile:contains("grid-7")').length === 0) { tile.animate({ left: $('#grid-7').position().left }, animSpd); tile.text('grid-7'); $('#grid-7').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-6")').length === 0) { tile.animate({ left: $('#grid-6').position().left }, animSpd); tile.text('grid-6'); $('#grid-6').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-5")').length === 0) { tile.animate({ left: $('#grid-5').position().left }, animSpd); tile.text('grid-5'); $('#grid-5').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else { console.log("Stuck at 4"); } } if (row === 'grid-8' || row === 'grid-9' || row === 'grid-10') { if ($('.tile:contains("grid-11")').length === 0) { tile.animate({ left: $('#grid-11').position().left }, animSpd); tile.text('grid-11'); $('#grid-11').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-10")').length === 0) { tile.animate({ left: $('#grid-10').position().left }, animSpd); tile.text('grid-10'); $('#grid-10').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-9")').length === 0) { tile.animate({ left: $('#grid-9').position().left }, animSpd); tile.text('grid-9'); $('#grid-9').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else { console.log("Stuck at 8"); } } if (row === 'grid-12' || row === 'grid-13' || row === 'grid-14') { if ($('.tile:contains("grid-15")').length === 0) { tile.animate({ left: $('#grid-15').position().left }, animSpd); tile.text('grid-15'); $('#grid-15').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-14")').length === 0) { tile.animate({ left: $('#grid-14').position().left }, animSpd); tile.text('grid-14'); $('#grid-14').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else if ($('.tile:contains("grid-14")').length === 0) { tile.animate({ left: $('#grid-13').position().left }, animSpd); tile.text('grid-13'); $('#grid-13').addClass('taken-tile'); $('#' + row).removeClass('taken-tile'); } else { console.log("Stuck at 12"); } }}; function merge(target, source) { }; function spawnRandomTile() { // Create new div to add var newTile = $('<div>'); newTile.addClass('tile'); $('.col-sm-1').append(newTile); // Set position newTile.css({top: nextPos.position().top, left: nextPos.position().left}); newTile.css("background-color", "red"); newTile.text(nextPos.attr('id')); }; $(document).ready(main);
true
cb1f793e460feb0a139222b5b45cd27e65e691e8
JavaScript
alexdmccabe/FFGNDS-Discord-Dice-Roller
/modules/SW.GENESYS/roll.js
UTF-8
7,324
2.609375
3
[ "MIT" ]
permissive
const config = require('../').config; const diceFaces = require('./').diceFaces; const dice = require('../').dice; const emoji = require('../').emoji; const writeData = require('../').writeData; const sleep = require('../').sleep; const order = require('./').order; const symbols = require('./').symbols; const _ = require('lodash'); const finalText = (text) => text.length > 1500 ? 'Too many dice to display.' : text; const roll = async (bot, message, params, channelEmoji, desc, diceResult, diceOrder) => { return new Promise(async resolve => { if (!diceResult) diceResult = initDiceResult(); if (!params[0]) { message.reply('No dice rolled.'); return; } //process each identifier and set it into an array if (!diceOrder) diceOrder = processType(message, params); //rolls each die and begins rollResults diceOrder.forEach(die => { if (!diceResult.roll[die]) { diceResult.roll[die] = [...Array(diceOrder.filter(x => x === die).length)].map(() => rollDice(die)) } }); //counts the symbols rolled diceResult = countSymbols(diceResult, message, channelEmoji); writeData(bot, message, 'diceResult', diceResult.roll); let messageGif, textGif = printAnimatedEmoji(diceOrder, message, channelEmoji); if (textGif) messageGif = await message.channel.send(finalText(textGif)).catch(console.error); resolve(diceResult); await sleep(desc.includes('roll') ? 0 : 1000); printResults(diceResult, message, desc, channelEmoji, messageGif); }).catch(error => message.reply(`That's an Error! ${error}`)); }; //init diceResult function initDiceResult() { return { roll: {}, results: { face: '', success: 0, advantage: 0, triumph: 0, failure: 0, threat: 0, despair: 0, lightpip: 0, darkpip: 0 } }; } //processes the params and give an array of the type of dice to roll const processType = (message, params) => { if (0 >= params.length) { message.reply('No dice rolled.'); return []; } if (params.some(param => +(param).replace(/\D/g, "") > +config.maxRollsPerDie)) { message.reply('Roll exceeds max roll per die limit of ' + config.maxRollsPerDie + ' . Please try again.'); return []; } const diceOrder = (params) => { if (params[0].match(/\d+/g)) { return _.flatten(params.map(param => { const diceQty = +(param).replace(/\D/g, ""), color = param.replace(/\d/g, ""); return [...Array(diceQty)].map(() => color); })); } else return params.join('').split('').map(type => type); }; return diceOrder(params).map(die => { switch (die) { case 'yellow': case 'y': case 'proficiency': case 'pro': return 'yellow'; case 'green': case 'g': case 'ability': case 'a': return 'green'; case 'blue': case 'b': case 'boost': case 'boo': return 'blue'; case 'red': case 'r': case 'challenge': case 'c': return 'red'; case 'purple': case 'p': case 'difficulty': case 'd': return 'purple'; case 'black': case 'blk': case 'k': case 's': case 'sb': case 'setback': return 'black'; case 'white': case 'w': case 'force': case 'f': return 'white'; case 'success': case 'suc': case '*': return 'success'; case 'advantage': case 'adv': case 'v': return 'advantage'; case 'triumph': case 'tri': case '!': return 'triumph'; case 'failure': case 'fail': case '-': return 'failure'; case 'threat': case 'thr': case 't': return 'threat'; case 'despair': case 'des': case '$': return 'despair'; case 'lightside': case 'lightpip': case 'light': case 'l': return 'lightpip'; case 'darkside': case 'darkpip': case 'dark': case 'n': return 'darkpip'; default: return; } }).filter(Boolean).sort(); }; //rolls one die and returns the results in an array const rollDice = (die) => { //roll dice and match them to a side and add that face to the message if (!die) return; return dice(Object.keys(diceFaces[die]).length); }; function countSymbols(diceResult) { diceResult.results = { face: '', success: 0, advantage: 0, triumph: 0, failure: 0, threat: 0, despair: 0, lightpip: 0, darkpip: 0 }; Object.keys(diceResult.roll).sort((a, b) => order.indexOf(a) - order.indexOf(b)).forEach(color => { diceResult.roll[color].forEach(number => { let face = diceFaces[color][number].face; for (let i = 0; i < face.length; i++) { switch (face[i]) { case 's': diceResult.results.success++; break; case 'a': diceResult.results.advantage++; break; case 'r': diceResult.results.triumph++; diceResult.results.success++; break; case 'f': diceResult.results.failure++; break; case 't': diceResult.results.threat++; break; case 'd': diceResult.results.despair++; diceResult.results.failure++; break; case 'l': diceResult.results.lightpip++; break; case 'n': diceResult.results.darkpip++; break; default: break; } } }); }); return diceResult; } const printAnimatedEmoji = (diceOrder, message, channelEmoji) => { const text = diceOrder .sort((a, b) => order.indexOf(a) - order.indexOf(b)) .map(die => { if (order.slice(0, -8).includes(die)) return emoji(`${die}gif`, channelEmoji); return emoji(die, channelEmoji); }); if (text.length > 1500) return 'Too many dice to display.'; else return text.join(''); }; const printResults = ({roll, results}, message, desc, channelEmoji, messageGif) => { //creates finalCount by cancelling results let finalCount = {}; if (results.success > results.failure) finalCount.success = results.success - results.failure; if (results.failure > results.success) finalCount.failure = results.failure - results.success; if (results.advantage > results.threat) finalCount.advantage = results.advantage - results.threat; if (results.threat > results.advantage) finalCount.threat = results.threat - results.advantage; if (results.triumph > 0) finalCount.triumph = results.triumph; if (results.despair > 0) finalCount.despair = results.despair; if (results.lightpip > 0) finalCount.lightpip = results.lightpip; if (results.darkpip > 0) finalCount.darkpip = results.darkpip; //prints faces const colors = Object.entries(roll).sort(([a,], [b,]) => order.indexOf(a) - order.indexOf(b)).filter(([color, numbers]) => numbers.length > 0), facesList = _.flatten(colors.map(([color, numbers]) => numbers.map(number => `${color}${symbols.includes(color) ? '' : diceFaces[color][number].face}`))), faces = facesList.map(str => emoji(str, channelEmoji)).join(''), response = Object.keys(finalCount).map(symbol => `${emoji(symbol, channelEmoji)} ${finalCount[symbol]}`).join(''); if (0 >= faces.length) { message.reply("No dice rolled."); return; } if (messageGif) messageGif.edit(finalText(faces)).catch(console.error); else message.channel.send(finalText(faces)).catch(console.error); if (faces) message.reply(`${desc} results:\n\n\t${response.length > 0 ? response : 'All dice have cancelled out'}`); }; exports.roll = roll; exports.processType = processType; exports.rollDice = rollDice; exports.countSymbols = countSymbols; exports.printResults = printResults;
true
8162fabd174e3f3c2c40b9f1e7ee659772104bf3
JavaScript
paradoxrevolver/polyominosolver
/Vec2.js
UTF-8
2,015
3.84375
4
[ "MIT" ]
permissive
/* A Vec2 is a 2-dimensional vector, a vector with only two values: an X and a Y. */ ps.Vec2 = function (x, y) { let that = this; /* Initalization */ that.init = function (x, y) { // VARIABLES // a 2D vector just stores its x and y that.x = x || 0; that.y = y || 0; // initalization that.updateHash(); } /* Quickly adds to the values of x and y on this vector */ that.shift = function (x, y) { that.x += x; that.y += y; // values were changed, update the hash that.updateHash(); } /* Checks if this Vec2 is equal to another Vec2 */ that.equals = function (vector) { if (vector.hash === that.hash) return true; return false; } /* Performs a transformation on the vector, based on a pair of linear combinations */ that.transform = function (a, b, c, d) { /* console.log("| " + a.toString().padStart(2, " ") + " " + b.toString().padStart(2, " ") + " |\n" + "| " + c.toString().padStart(2, " ") + " " + d.toString().padStart(2, " ") + " |"); */ // first we do matrix multiplication var newX = that.x * a + that.y * b; var newY = that.x * c + that.y * d; // then we save the results to the vector that.x = newX; that.y = newY; // values were changed, update the hash that.updateHash(); } /* Returns a reference to a new Vec2 that is a clone of this Vec2 */ that.clone = function () { let newVec = new ps.Vec2(that.x, that.y); return newVec; } /* Generates a hashcode for this Vec2 that is supposedly unique for all Vec2. The reason this function exists is to use a HashMap in Polyominoes. */ that.updateHash = function () { that.hash = ps.hashVector(that); } /* Converts Vec2 to a String */ that.toString = function () { return "<" + that.x + ", " + that.y + ">"; } // init that.init(x, y); }
true
9a2b8abd151d60d779c018c7e1c6348733471d97
JavaScript
sueddeutsche/json-data-services
/test/State.test.js
UTF-8
2,142
2.8125
3
[]
no_license
/* eslint object-property-newline: 0, max-nested-callbacks: 0 */ const expect = require("chai").expect; const State = require("../lib/state"); describe("state", () => { let state; beforeEach(() => { state = new State(); }); it("should dispatch action", () => { let calledAction; function reducer(state = {}, action) { calledAction = action; return state; } state.register("data", reducer); state.dispatch({ type: "DUMMY_ACTION", value: 14 }); expect(calledAction).to.deep.eq({ type: "DUMMY_ACTION", value: 14 }); }); it("should register multiple reducers", () => { const calledActions = []; const action = { type: "DUMMY_ACTION", value: 14 }; state.register("A", (state = {}, action) => { action.type === "DUMMY_ACTION" && calledActions.push(action); return state; }); state.register("B", (state = {}, action) => { action.type === "DUMMY_ACTION" && calledActions.push(action); return state; }); state.dispatch(action); expect(calledActions).to.deep.equal([action, action]); }); it("should register reducers on separate entry points", () => { const calledActions = []; const action = { type: "DUMMY_ACTION", value: 14 }; state.register("A", (state = {}, action) => { action.type === "DUMMY_ACTION" && calledActions.push(action); return { id: "A" }; }); state.register("B", (state = {}, action) => { action.type === "DUMMY_ACTION" && calledActions.push(action); return { id: "B" }; }); state.dispatch(action); const currentState = state.get(); expect(currentState.A).to.deep.equal({ id: "A" }); expect(currentState.B).to.deep.equal({ id: "B" }); }); it("should return state of given reducer", () => { state.register("A", (state = {}, action) => ({ id: "A" })); const stateA = state.get("A"); expect(stateA).to.deep.eq({ id: "A" }); }); });
true
ea5682ad7b57f9175240191183050a1529b735f2
JavaScript
itsmepronay/Social-Share-Button
/main.js
UTF-8
1,693
2.71875
3
[]
no_license
/* Social Share Links: WhatsApp: https://wa.me/?text=[post-title] [post-url] Facebook: https://www.facebook.com/sharer.php?u=[post-url] Twitter: https://twitter.com/share?url=[post-url]&text=[post-title] Pinterest: https://pinterest.com/pin/create/bookmarklet/?media=[post-img]&url=[post-url]&is_video=[is_video]&description=[post-title] LinkedIn: https://www.linkedin.com/shareArticle?url=[post-url]&title=[post-title] */ const ffbBtn = document.querySelector(".facebook-btn"); const ftwBtn = document.querySelector(".twitter-btn"); const fpiBtn = document.querySelector(".pinterest-btn"); const fliBtn = document.querySelector(".linkedin-btn"); const fpoBtn = document.querySelector(".pocket-btn") const fwaBtn = document.querySelector(".whatsapp-btn") function init() { let postUrl = encodeURI(document.location.href); let postTitle = encodeURI("Hi everyone, please check this out: "); let via = encodeURI("itsmepronay"); ffbBtn.setAttribute( "href", `https://www.facebook.com/sharer.php?u=${postUrl}` ); ftwBtn.setAttribute( "href", `https://twitter.com/share?url=${postUrl}&text=${postTitle}&via=${via}` ); fpiBtn.setAttribute( "href", `https://pinterest.com/pin/create/bookmarklet/?url=${postUrl}&description=${postTitle}` ); fliBtn.setAttribute( "href", `https://www.linkedin.com/shareArticle?url=${postUrl}&title=${postTitle}` ); fpoBtn.setAttribute( "href", `https://getpocket.com/save?url=${postUrl}&title=${postTitle}` ); fwaBtn.setAttribute( "href", `https://wa.me/?text=${postTitle} ${postUrl}` ); } init();
true
d90862995f68ae6505133e578a21026a5c7e3cdf
JavaScript
shaggyrec/telegra.ph-nodejs
/server/lib/quill.js
UTF-8
967
2.75
3
[ "MIT" ]
permissive
function toHtml(data){ let result = '' if(data) { data = typeof data !== 'object' ? JSON.parse(data) : data for (let item in data) { item = data[item] result += `<${item.tag}` if(item.attrs){ for(let attr in item.attrs){ result += ` ${attr}="${item.attrs[attr]}"` } } result += '>' for(let child in item.children){ child = item.children[child] // console.log(item.tag) // console.log(child) if(typeof child === 'object'){ result +=toHtml(item.children) //console.log(child) }else{ result += child } } result += `</${item.tag}>` } } return result } module.exports = { toHtml }
true
59837d7a8ba815a74a958a8081e9b710aff52da5
JavaScript
damoclesgil/Learn-TypeScript-and-JavaScript
/javascript/cursos/curso-javascript-ninja/challenge-15/main2.js
UTF-8
128
2.90625
3
[]
no_license
(function () { function myFunction(arg1, arg2) { return arguments[0]; } console.log(myFunction(1, 2)); })();
true
bfa36caaf6814ea248ddcc371e0d884e0830fdf5
JavaScript
WilfredNtulis/Artist-Search
/public/assets/artist.js
UTF-8
244
2.875
3
[]
no_license
var list = document.querySelectorAll('.list'); list.forEach(function(list){ list.addEventListener('click', function(){ fetch('http://localhost:3000/test') .then(response => response.json()) .then(json => console.log(json)) }) })
true
b7c895019a7b11f59f682ee7b1d090f3801bd5d0
JavaScript
tanujvyas10/Regex-string-generator
/app.js
UTF-8
703
2.9375
3
[]
no_license
const express = require("express"); const Generate = require("./Generator"); const app = express(); app.get("/", (req, res) => { /** * Please change the value n and regexp to check the Generate function */ let n = 10; let regexp = "/[-+]?[0-9]{1,16}[.][0-9]{1,6}/"; //(1[0-2]|0[1-9])(:[0-5][0-9]){2} (A|P)M const result = Generate(regexp, n); /** * console.log("The generated strings are",result) */ /** * The following line sending the result at our browser screen * Please go to the browser and type "localhost:3000" so see the result on screen */ res.send(JSON.stringify(result)); }); app.listen(3000, function () { console.log("server started.."); });
true
495de2a37f9e743127628371e3f1f2c95008107c
JavaScript
zhoukekestar/drafts
/2019-08~12/2019-09-29-typescript/greeter.js
UTF-8
269
3.5625
4
[ "MIT" ]
permissive
function hello(person) { console.log('hi' + person); } function hello2(person) { console.log("hello " + person.firstName + " " + person.lastName); } hello('world'); hello([1, 2, 3]); hello2({ firstName: 'zkk', lastName: 'abc' }); hello2({ firstName: [1, 2] });
true
a528a20e56d7d0a42046c16790d5f2c97254793e
JavaScript
martinperezlouzao/mobile_games_project
/wildPunch/js/SecondPlayer.js
UTF-8
429
2.6875
3
[]
no_license
class SecondPlayer extends Player { constructor(imageSecondPlayer, centreX, centreY) { super(imageSecondPlayer, centreX, centreY); var width = canvas.width, height = canvas.height; this.WIDTH_OF_PLAYER = width/16; this.HEIGHT_OF_PLAYER = height/16; this.centreX = centreX; this.centreY = centreY; //this.PLAYER_SPEED = 12; this.jumpNumber = 3; } }
true
78953bb3a1430840ec03b302bc168b06dfa68c17
JavaScript
Leandro-Da-Souza/nodejs-the-one-where-we-build-a-web-application-assignment-2
/js/main.js
UTF-8
1,085
2.9375
3
[]
no_license
let productPage = document.querySelector('.products ul'); let baseURL = 'http://localhost:8080'; let customerID = 'f6a796d0-3f60-11ea-80cd-8bb22b23e2bf'; let counter = document.querySelector('#counter'); const fetchBasket = async custID => { let response = await fetch(`${baseURL}/getBasket?customerID=${custID}`, { method: 'GET' }); let data = response.json(); return data; }; const fetchProducts = async () => { let response = await fetch(`${baseURL}/products`, { method: 'GET' }); let data = await response.json(); return data; }; window.addEventListener('load', async () => { let products = await fetchProducts(); let basket = await fetchBasket(customerID); let output = ''; products.forEach(product => { console.log(product); output += ` <li> <h4>${product.name}</h4> <a href="./productPage.html?id=${product._id}" >More Info</a> <hr> </li> `; productPage.innerHTML = output; }); counter.innerHTML = basket.length + ' Items In Cart'; });
true
31eed072f1050a7d17065a645772d86d10423944
JavaScript
Destroyer012/dungeongang
/commands/bot/help.js
UTF-8
4,334
2.75
3
[]
no_license
const Discord = require('discord.js'); const yes = `845121770590961696`; const no = `845121806049869824`; const package = require('../../package.json') module.exports = { name: 'help', aliases: ['h', 'info', `commands`], usage: 'help [command]', description: 'Gets information about the bot', hidden: false, async execute() { let message = messageParam, args = argsParam, config = configParam, fs = fsParam // console.log(args) if (args.length === 1) { const commandFolders = fs.readdirSync('./commands'); let embed = new Discord.MessageEmbed() .setAuthor(`Help - Dungeon Gang`, message.client.user.avatarURL()) .setDescription(`For more information run \`help [command]\``) .setColor('0x00bfff') var commandsNum = 0; for (const folder of commandFolders) { let descriptions = []; const commandFiles = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const command = require(`../${folder}/${file}`); if (!command.hidden) { let currentCommand = []; currentCommand.push(`\`${command.name}\``); currentCommand.push('-'); currentCommand.push(command.description); descriptions.push(currentCommand.join(' ')); commandsNum++; } } embed.addField((folder.charAt(0).toUpperCase() + folder.slice(1)), descriptions.join('\n')) } embed.addField('Info', [ `Prefix: \`${config.prefix}\``, `Channel: ${message.channel}`, `Discord: [Dungeon Gang](https://discord.gg/dungeon)`, `Utility & Poll Bot`, `Made by nick#0404 and alon#1396` ].join('\n'), true) embed.addField('Stats', [ `Server Members: \`${message.client.users.cache.size.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')}\``, `Servers: \`${message.client.guilds.cache.size.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')}\``, `Version: \`${package.version}\``, `Uptime: \`${timeConversion(message.client.uptime)}\``, `Commands: \`${commandsNum}\`` ].join('\n'), true) return message.channel.send(embed) } const name = args[1].toLowerCase(); const command = message.client.commands.get(name) || message.client.commands.find(c => c.aliases && c.aliases.includes(name)); if (!command) { return message.channel.send( new Discord.MessageEmbed() .setDescription(`\`${name}\` isn't a valid command`) .setColor('0x00bfff') ); } let embed = new Discord.MessageEmbed() .setAuthor(`Help - ${command.name}`, message.client.user.avatarURL()) .setColor('0x00bfff') var desc = [`*${command.description}*`, `Usage: \`${command.usage}\``]; embed.setDescription(desc.join('\n')) embed.addField('Aliases', `\`${command.aliases.join('\n')}\``, true) return message.channel.send(embed) .catch(() => { message.channel.send( new Discord.MessageEmbed() .setDescription(`${message.author}, Error!`) .setColor('0x00bfff') ) }); }, }; function timeConversion(millisec) { var seconds = (millisec / 1000).toFixed(0); var minutes = (millisec / (1000 * 60)).toFixed(0); var hours = (millisec / (1000 * 60 * 60)).toFixed(0); var days = (millisec / (1000 * 60 * 60 * 24)).toFixed(0); var weeks = (millisec / (1000 * 60 * 60 * 24 * 7)).toFixed(0); if (seconds < 60) { return seconds + " Seconds"; } else if (minutes < 60) { return minutes + " Minutes"; } else if (hours < 24) { return hours + " Hours"; } else if (days > 7) { return days + " Days" } else { return weeks + " Weeks" } }
true
66e3f623d75b297718219b3a7bbba508b7d6e995
JavaScript
hanjos/bootcamp-solidity-puc
/Investment/test/2_Funds_Investing.js
UTF-8
4,093
2.609375
3
[ "MIT" ]
permissive
var Funds = artifacts.require("./Funds.sol"); assert.bigNumberEqual = function (actual, expected, message) { if(! actual.eq(expected)) { message = (message != undefined) ? message + ": " : ""; throw new AssertionError(message + "expected " + actual.toString() + " to equal " + expected.toString()); } } contract('Funds: Investing phase', function (accounts) { const owner = accounts[0]; const investor1 = accounts[1]; const investor2 = accounts[2]; const wallet = accounts[3]; const minimumInvestment = Math.pow(10, 18); // TODO no idea why, but transfer costs seem to be consistently this * gasUsed const actualGasPrice = Math.pow(10, 11); const errorMargin = 1; var meta; // XXX since the ABI doesn't store enum values (as per https://solidity.readthedocs.io/en/latest/frequently-asked-questions.html#if-i-return-an-enum-i-only-get-integer-values-in-web3-js-how-to-get-the-named-values), // here we go const STATE_OPEN = 0; const STATE_INVESTING = 1; const STATE_FINISHED = 2; async function calculateLatestGasCost() { var gasUsed = await web3.eth.getBlock('latest').gasUsed; return gasUsed * actualGasPrice; } beforeEach(async function () { meta = await Funds.new(minimumInvestment, 0, {from: owner}); await meta.setOperatingWallet(wallet); await meta.invest({ from: investor1, value: minimumInvestment }); await meta.invest({ from: investor2, value: 2 * minimumInvestment }); await meta.start(); }); it("can't call invest during Investing", async function () { try { await meta.invest({ from: investor1, value: minimumInvestment + 1000 }); assert.fail("Should've failed earlier"); } catch(e) { if(e.name === "AssertionError") { throw e; } } }); it("can't call divest during Investing", async function () { try { await meta.divest({ from: investor2, value: minimumInvestment }); assert.fail("Should've failed earlier"); } catch(e) { if(e.name === "AssertionError") { throw e; } } }); it("can't receive money from just anybody", async function () { var ownerStartingBalance = await web3.eth.getBalance(owner); var metaStartingBalance = await web3.eth.getBalance(meta.contract.address); var eventWatcher = meta.allEvents(); try { await meta.receive({from: owner, value: minimumInvestment }); assert.fail("Should've failed earlier"); } catch(e) { if(e.name === "AssertionError") { throw e; } } var gasCost = await calculateLatestGasCost(); var ownerEndingBalance = await web3.eth.getBalance(owner); var metaEndingBalance = await web3.eth.getBalance(meta.contract.address); var events = await eventWatcher.get(); assert.bigNumberEqual(ownerEndingBalance, ownerStartingBalance.minus(gasCost), "Shouldn't have paid"); assert.bigNumberEqual(metaEndingBalance, metaStartingBalance, "Shouldn't have received"); assert.equal(events.length, 0, "Wrong number of events"); }); it("only the wallet can put money back in", async function () { var walletStartingBalance = await web3.eth.getBalance(wallet); var metaStartingBalance = await web3.eth.getBalance(meta.contract.address); var eventWatcher = meta.allEvents(); var amount = minimumInvestment; // no minimum investment await meta.receive({from: wallet, value: amount }); var gasCost = await calculateLatestGasCost(); var walletEndingBalance = await web3.eth.getBalance(wallet); var metaEndingBalance = await web3.eth.getBalance(meta.contract.address); var events = await eventWatcher.get(); assert.bigNumberEqual(walletEndingBalance, walletStartingBalance.minus(amount).minus(gasCost), "Should've paid"); assert.bigNumberEqual(metaEndingBalance, metaStartingBalance.plus(amount), "Should've received"); assert.equal(events.length, 1, "Wrong number of events"); assert.equal(events[0].event, "ReturnsReceived", "Wrong event"); assert.equal(events[0].args.value, amount, "Wrong value transferred"); }); });
true
6822676e8773190f3f4eb1aae0a360ff9bbaa5dc
JavaScript
LainaJ/diaboo-frontend
/src/index.js
UTF-8
1,105
3.015625
3
[]
no_license
// import React from 'react'; // import ReactDOM from 'react-dom'; // import './index.css'; // import App from './App'; // import * as serviceWorker from './serviceWorker'; function isPrime(num) { if (num < 2){ return false } for (let i = 2; i <= Math.sqrt(num); i++){ if (num % i === 0) { return false } } return true } function allPrime(num) { let primes = [] for (let i = 2; i < num; i++){ if (isPrime(i)) { primes.push(i) } } return primes } //arrays problem function removeDuplicates (nums) { let numBeforeI = 0 for (let i = 1; i < nums.length; i++){ if (nums[i] !== nums[i++]){ nums[numBeforeI] = nums[i] numBeforeI++; } } console.log("nums:", nums) }; let nums = [1, 2, 2] removeDuplicates(nums) // ReactDOM.render(<App />, document.getElementById('root')); // // 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();
true
e081e577d8c6b2ecd7d3a80823fd81a9d225bc3f
JavaScript
kertron/extjs-demo
/routes/index.js
UTF-8
2,066
2.5625
3
[]
no_license
var Article = require('../models/article.js'); module.exports = function (app) { // 主页 app.get('/', function(req, res){ Article.get(null, function(err, articles){ if(err){ articles = []; } res.render('index', { title : '主页', articles : articles }); }); }); // 文章清单 app.get('/articles', function(req, res) { var totalCount = 0; query= "limit " + req.query.start + "," + req.query.limit Article.getQuantity(function(err, total){ console.log(total); totalCount = total; }); Article.get(query, function(err, articles){ if(err){ articles = []; } res.contentType('json'); res.json({success: true, data: articles, totalCount: totalCount}); }); }); // 新建文章 app.post('/articles', function(req, res) { article = new Article(req.body.user, req.body.title, req.body.content, req.body.happened_at); article.save(function(err, result){ if(err){ console.log('发布失败!'); res.json({success: false}); } console.log('发布成功!'); //insertId用于更新页面表单中的id article.id = result.insertId; res.json({success: true, data: article}); }); }); // 编辑文章 app.put('/articles/:id', function(req, res) { article = new Article(req.body.user, req.body.title, req.body.content, req.body.happened_at, req.body.id); article.update(function(err, result){ if(err){ console.log('修改失败!'); res.json({success: false}); } console.log('修改成功!'); res.contentType('json'); res.json({success: true, data: article}); }); }); // 删除文章 app.delete('/articles/:id', function(req, res) { var query = 'id = ' + req.body.id; Article.remove(query, function(err) { if(err){ console.log('删除失败!'); return res.json({success: false}); } console.log('删除成功!'); res.json({success: true}); }); }); }
true
169d43d35ad53dca026786a54510d74c4b480d6c
JavaScript
ojoesuff/ewd-api-labs-2021
/node-lab1/api/movies/index.js
UTF-8
1,243
2.734375
3
[]
no_license
import express from 'express'; import { movies, movieReviews, movieDetails } from './moviesData.js'; import uniqid from 'uniqid' import { notFound } from '../responses/index.js' const router = express.Router(); router.get('/', (req, res) => { res.json(movies); }); // Get movie reviews router.get('/:id/reviews', (req, res) => { const id = parseInt(req.params.id); // find reviews in list if (movieReviews.id == id) { res.status(200).json(movieReviews); } else { res.status(404).json(notFound); } }); // Get movie details router.get('/:id', (req, res) => { const id = parseInt(req.params.id); if (movieDetails.id == id) { res.status(200).json(movieDetails); } else { res.status(404).json(notFound); } }); //Post a movie review router.post('/:id/reviews', (req, res) => { const id = parseInt(req.params.id); if (movieReviews.id == id) { req.body.created_at = new Date(); req.body.updated_at = new Date(); req.body.id = uniqid(); movieReviews.results.push(req.body); //push the new review onto the list res.status(201).json(req.body); } else { res.status(404).json(notFound); } }); export default router;
true
5b996c48b088db1f789ec57ce589fd21b6c1c873
JavaScript
yuanxiaochen1/yidongduan
/js/index.js
UTF-8
2,950
2.546875
3
[]
no_license
let moveimg=function(){ function pageMove() { //=>this:swiperExample let activeIndex = this.activeIndex, slides = this.slides; //=>给当前页面设置ID,让其内容有动画效果 [].forEach.call(slides, (item, index) => { if (index === activeIndex) { activeIndex === 0 ? activeIndex = 6 : null; activeIndex === 7 ? activeIndex = 1 : null; item.id = 'page' + activeIndex; return; } item.id = null; }); } /* ==音乐的处理== */ function handleMusic() { let $musicAudio = $('.musicAudio'), musicAudio = $musicAudio[0], $musicIcon = $('.musicIcon'); $musicAudio.on('canplay', function () { $musicIcon.css('display', 'block') .addClass('move'); }); $musicIcon.tap(function () { if (musicAudio.paused) { //=>当前暂停状态 play(); $musicIcon.addClass('move'); return; } //=>当前播放状态 musicAudio.pause(); $musicIcon.removeClass('move'); }); function play() { musicAudio.play(); document.removeEventListener("touchstart", play); } play(); //=>兼容处理 document.addEventListener("WeixinJSBridgeReady", play); document.addEventListener("YixinJSBridgeReady", play); document.addEventListener("touchstart", play); } /* ==第六页轮播如处理== */ let $page5=$('.page5'), $box=$page5.find('.box'), $leftBtn=$box.children('.imgBtn1'), $rightBtn=$box.children('.imgBtn2'), $imgBox=$box.children('.imgBox'), $item=$imgBox.children('.item'); let step=0; function handleArrow() { $rightBtn.tap(function(){ step++; step>=3?step=0:null; $item.css('transform', `translateX(-${step*2.6}rem)`); }); //给回退按钮绑定点击事件 $leftBtn.tap(function () { step--; step<0?step=2:null; $item.css('transform', `translateX(-${step*2.6}rem)`); }) } return{ init:function(){ //设置滑动效果 let swiperExample = new Swiper('.swiper-container', { direction: 'horizontal', //=>'vertical' loop: true, effect: 'flip', //=>"cube"、"fade"、"coverflow"、"flip" pagination: '.swiper-pagination', paginationType: 'progress', on: { init: pageMove, transitionEnd: pageMove } }); //设置音乐定时器 setTimeout(handleMusic, 1000); //第五页滑动图 handleArrow(); } } }() moveimg.init()
true
df3b4e05f4abdcfda773ed7c6a56946c9e0b2e20
JavaScript
egierdian/javascript-firebase
/js/category.js
UTF-8
2,867
2.828125
3
[]
no_license
// Initialize Firebase var config = { apiKey: "AIzaSyB5usrQKua0zDoUMWS-NoMf6wGoihAz4rE", authDomain: "warmat-9d32d.firebaseapp.com", databaseURL: "https://warmat-9d32d.firebaseio.com", projectId: "warmat-9d32d", storageBucket: "warmat-9d32d.appspot.com", messagingSenderId: "124927091557", appId: "1:124927091557:web:531ed441a700752f5df78c", measurementId: "G-KB1D9J96DN" }; firebase.initializeApp(config); let db , dataRef; // referensi ke database db = firebase.database(); dataRef = db.ref('products/data'); console.log(dataRef); // menampilkan data ke halaman browser dataRef.on('value' , dataBerhasil , dataGagal); function dataBerhasil (data) { // console.log(data); let urlParam = new URLSearchParams(window.location.search); let idParam = urlParam.get("category").toLowerCase(); // console.log(idParam); let tampilkan = ""; let ambilData = document.getElementById("body-content"); // console.log(data.val()); data.forEach(function(konten) { let c = konten.val().Category.replace(/"/g, '').toLowerCase(); if(c == idParam){ // console.log(konten.val()); let str = konten.val().Image; let nama = konten.val().Name; // console.log(str); let hasil = str.replace(/\\/g, ''); let replacenama = nama.replace(/"/g, ''); let harga = konten.val().Harga.replace(/"/g, ''); // konversi harga ke format rupiah let number_string = harga.toString(), sisa = number_string.length % 3, rupiah = number_string.substr(0, sisa), ribuan = number_string.substr(sisa).match(/\d{3}/g); if (ribuan) { separator = sisa ? '.' : ''; rupiah += separator + ribuan.join('.'); } tampilkan += ` <div class="col s12 m4 l3" style="padding-top:15px;"> <div class="card" style="border-bottom: solid 2px #d81b60;"> <div class="card-image"> <a href="/detail.html?id=${konten.val().ID.replace(/"/g,'')}"><img src="${hasil.replace(/""/g,'')}" height="200px"></a> </div> <div class="card-content" style="margin: -15px -10px;"> <a href="/detail.html?id=${konten.val().ID.replace(/"/g,'')}"><span class="card-title" style="font-size:16px; line-height: 16px;">${replacenama}</span></a> <p style="font-size:13px;">Rp. ${rupiah}</p> </div> </div> </div>`; } }); ambilData.innerHTML = tampilkan; } function dataGagal (err) { console.log(err); }
true
9ce176775be0b5929bc47f6c84d3b631fe9371b5
JavaScript
aditpandey3090/Tree-Visualization-Task-Survey
/surveyed-papers/js/utility.js
UTF-8
2,720
3.15625
3
[]
no_license
$('[data-toggle="tooltip"]').tooltip(); //Create a function that can take entire data, and indexing variable to create a frequency chart function createFrequencyData(data, dimension) { var result = []; data.reduce(function (res, value) { if (!res[value[dimension]]) { res[value[dimension]] = { Id: value[dimension], count: 0, entireData: value, }; result.push(res[value[dimension]]); } res[value[dimension]].count += 1; return res; }, {}); return result.sort((data1, data2) => { return parseInt(data1.Id) - parseInt(data2.Id); }); } //Special version of frequency Chart for columns with commma-seperated value function createMultiValueFreqData(data, dimension) { var result = []; // var res = {}; data.reduce(function (res, value) { let vizTypes = value[dimension].split(","); vizTypes.forEach((element) => { if (!res[element]) { res[element] = { Id: element, count: 0, entireData: value, }; result.push(res[element]); } res[element].count += 1; }); return res; }, {}); return result; } // GLOBAL vars const MIN_YEAR_DEFAULT = 0; const MAX_YEAR_DEFAULT = 1000000; let minYear = MIN_YEAR_DEFAULT; let maxYear = MAX_YEAR_DEFAULT; function setYearToDefault() { minYear = MIN_YEAR_DEFAULT; maxYear = MAX_YEAR_DEFAULT; } function setRange(min, max) { minYear = min; maxYear = max; } /** * Filters datatable on year column for the provided range. * Could be used to clear the range filter on year column. * * Usages: * - rangeFilterOnYear(2015, 2020) * - rangeFilterOnYear(clear = true) * * @param {number} min * @param {number} max * @param {boolean} clear :[OPTIONAL] false by default. If set to true, filter would be removed */ function rangeFilterOnYear(min, max, clear = false) { if (clear) { setYearToDefault(); } else { setRange(min, max); } $("#vizDataTable").DataTable().draw(); } // Tooltip initialization // Add tooltip data const yearOfPubToolTipData = "This is <br /> sample data. <br />Example of line break above."; $("#yearOfPubToolTip").attr("title", yearOfPubToolTipData); const paperTypeToolTip = "This is <br /> sample data. <br />Example of line break above."; $("#paperTypeToolTip").attr("title", paperTypeToolTip); const evaluationTypeToolTip = "This is <br /> sample data. <br />Example of line break above."; $("#evaluationTypeToolTip").attr("title", evaluationTypeToolTip); const visEncodingToolTip = "This is <br /> sample data. <br />Example of line break above."; $("#visEncodingToolTip").attr("title", visEncodingToolTip); $(".card-tooltip").tooltip({ container: "body", });
true
2ca52b6980d6968deb2045f03574e4a4de65fdea
JavaScript
GSung95/genesunglao.github.io
/todo/scripts.js
UTF-8
521
3.203125
3
[]
no_license
document.getElementById("mybtn").addEventListener("click", function() { let mycup = document.getElementById("theitem").value; console.log(mycup); if (mycup !== "") { const newBTN = document.createElement("button"); newBTN.innerHTML="\u274C"; const newLI = document.createElement("li"); newLI.textContent = mycup; newLI.appendChild(newBTN); document.getElementById("favs").appendChild(newLI); document.getElementById("theitem").value = ""; } });
true
c34842bd742ff20bd679e5c6561ecbdd492f0200
JavaScript
mvolkmann/react-crud
/src/crud/form.js
UTF-8
2,985
2.5625
3
[]
no_license
import {arrayOf, func, object, shape, string} from 'prop-types'; import React, {useState} from 'react'; import './crud.scss'; function Form({cancel, fields, item, save}) { const [newItem, setNewItem] = useState(item); function getInput(field, index) { const {max, min, placeholder, propertyName, type} = field; const value = newItem[propertyName] || ''; if (type === 'radio') { return field.options.map(option => ( <div className="radio" key={`${propertyName}-${option}`}> <input checked={value === option} name={propertyName} onChange={e => onChange(e, propertyName)} type="radio" value={option} /> <label>{option}</label> </div> )); } if (type === 'select') { return ( <select onChange={e => onChange(e, propertyName)} value={value}> {field.options.map(option => ( <option key={`${propertyName}-${option}`} value={option}> {option} </option> ))} </select> ); } const inputProps = { autoFocus: index === 0, onChange: e => onChange(e, propertyName), placeholder, type, value }; if (type === 'range') { if (max !== undefined) inputProps.max = max; if (min !== undefined) inputProps.min = min; if (!value) inputProps.value = 0; return ( <div className="range"> <input {...inputProps} /> {inputProps.value} </div> ); } if (type === 'checkbox') inputProps.checked = value; return <input {...inputProps} />; } function onChange(event, propertyName) { const {checked, type, value} = event.target; const valueToUse = type === 'checkbox' ? checked : value; setNewItem(newItem => ({...newItem, [propertyName]: valueToUse})); } function onCancel(event) { event.preventDefault(); cancel(); } function onSave(event) { event.preventDefault(); save(newItem); } function renderRow(field, index) { return ( <div className="row" key={field.propertyName}> <label>{field.label}</label> <div className="input">{getInput(field, index)}</div> </div> ); } const haveAllRequired = fields.every( field => !field.required || Boolean(newItem[field.propertyName]) ); return ( <form> {fields.map(renderRow)} <div className="buttons"> <button disabled={!haveAllRequired} onClick={onSave}> {item ? 'Save' : 'Add'} </button> <button onClick={onCancel}>Cancel</button> </div> </form> ); } Form.propTypes = { cancel: func.isRequired, fields: arrayOf( shape({ className: string, label: string.isRequired, placeholder: string, propertyName: string.isRequired, type: string.isRequired }) ), item: object, save: func.isRequired }; export default Form;
true
eb6848383343b6a4525968817129032143633a89
JavaScript
damiencal/webglproject
/shoot.js
UTF-8
3,605
2.953125
3
[ "MIT" ]
permissive
var shootShader; function initShootShader() { shootShader = initShaders("shoot-vs","shoot-fs"); // active ce shader gl.useProgram(shootShader); // recupere la localisation de l'attribut dans lequel on souhaite acceder aux positions shootShader.vertexPositionAttribute = gl.getAttribLocation(shootShader, "aVertexPosition"); gl.enableVertexAttribArray(shootShader.vertexPositionAttribute); // active cet attribut // pareil pour les coordonnees de texture shootShader.vertexCoordAttribute = gl.getAttribLocation(shootShader, "aVertexCoord"); gl.enableVertexAttribArray(shootShader.vertexCoordAttribute); // adresse de la variable uniforme uOffset dans le shader shootShader.positionUniform = gl.getUniformLocation(shootShader, "uPosition"); spaceshipShader.maTextureUniform = gl.getUniformLocation(spaceshipShader, "uMaTextureShoot"); console.log("shoot shader initialized"); } function Shoot(theme) { this.initParameters(theme); // cree un nouveau buffer sur le GPU et l'active this.vertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); // un tableau contenant les positions des sommets (sur CPU donc) var wo2 = 0.3*this.width; var ho2 = 0.8*this.height; var vertices = [ -wo2,-ho2, -0.5, wo2,-ho2, -0.5, wo2, ho2, -0.5, -wo2, ho2, -0.5 ]; // on envoie ces positions au GPU ici (et on se rappelle de leur nombre/taille) gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); this.vertexBuffer.itemSize = 3; this.vertexBuffer.numItems = 4; // meme principe pour les couleurs this.coordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.coordBuffer); var coords = [ 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0 ]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(coords), gl.STATIC_DRAW); this.coordBuffer.itemSize = 2; this.coordBuffer.numItems = 4; // creation des faces du cube (les triangles) avec les indices vers les sommets this.triangles = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.triangles); var tri = [0,1,2,0,2,3]; gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(tri), gl.STATIC_DRAW); this.triangles.numItems = 6; console.log("shoot initialized"); } Shoot.prototype.initParameters = function(theme) { this.width = 0.05; this.height = 0.05; this.position = [0.0, -0.55]; this.maTexture = initTexture("img/"+theme+"/shoot.png"); } Shoot.prototype.setParameters = function(elapsed) { // on pourrait animer des choses ici } Shoot.prototype.setPosition = function(x,y) { this.position = [x,y]; } Shoot.prototype.shader = function() { return shootShader; } Shoot.prototype.sendUniformVariables = function() { //Texture gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D,this.maTexture); gl.uniform1i(spaceshipShader.maTextureUniform, 0); gl.uniform2fv(shootShader.positionUniform,this.position); } Shoot.prototype.draw = function() { // active le buffer de position et fait le lien avec l'attribut aVertexPosition dans le shader gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); gl.vertexAttribPointer(enemyShader.vertexPositionAttribute, this.vertexBuffer.itemSize, gl.FLOAT, false, 0, 0); // active le buffer de coords gl.bindBuffer(gl.ARRAY_BUFFER, this.coordBuffer); gl.vertexAttribPointer(enemyShader.vertexCoordAttribute, this.coordBuffer.itemSize, gl.FLOAT, false, 0, 0); // dessine les buffers actifs gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.triangles); gl.drawElements(gl.TRIANGLES, this.triangles.numItems, gl.UNSIGNED_SHORT, 0); }
true
b09fe16607eab593d431c2e79bb36bcf22c8118c
JavaScript
fullmoon-sg/get-try
/01-edit/index.js
UTF-8
468
2.6875
3
[]
no_license
const axios = require("axios"); async function editMovies(){ let url = "https://ckx-movies-api.herokuapp.com"; let response = await axios.patch(url + "/movie/5fb4c1cab4f44550712da26c",{ title : "Gong Fu", plot : "The lord is in trouble" }) console.log(response.data); } editMovies(); async function getMovies(){ let response = await axios.get("https://ckx-movies-api.herokuapp.com/movies"); console.log(response.data); } getMovies();
true
56c44248ca85abe873dded4a8b6a257307239c96
JavaScript
javierj/PickAGem
/src/Gem.js
UTF-8
372
2.859375
3
[]
no_license
function Gem() { } Gem.prototype = new createjs.Bitmap(); Gem.prototype.init = function(gemImg, gemType) { this.initialize(gemImg); this.gemType = gemType; //console.log("Gem::init() image: " + this.image); //this.height = this.image.height; //this.width = this.image.width; } Gem.prototype.isOfType = function(newType) { return this.gemType == newType; }
true
27fa8c7dd2c83f264d3676455479097cc76fe38d
JavaScript
paigen11/egghead-react-starter
/src/ReactRef.js
UTF-8
1,488
2.84375
3
[]
no_license
import React, {Component} from 'react'; import ReactDOM from 'react-dom'; class ReactRef extends Component { constructor(){ super(); this.state = {a: ''} } // currently, both the a and b fields will be updated regardless of which input is typed in // so remove the event, and set a and b equal to the refs value so only the reference value is updated // you can even go a step further by setting the ref's node equal to this.a then referencing just that in the update function // or you can create a child component that updates onChange and ref the original input with this.a.refs.input.value update = () => { this.setState({ // a: e.target.value, // b: e.target.value // a: this.a.value, a: this.a.refs.input.value, b: this.refs.b.value }) }; render() { return ( <div> <Input ref={component => this.a = component} onChange={this.update.bind(this)} /> {this.state.a} <hr /> <input type="text" ref="b" onChange={this.update.bind(this)} /> {this.state.b} </div> ) } } class Input extends Component { render() { return (<div> <input ref='input' type="text" onChange={this.props.update}/> </div>) } } export default ReactRef;
true
c99077440e123f637e4a5a0f33188576df4e8706
JavaScript
henriwi/spark-twitter-aws
/src/main/webapp/app.js
UTF-8
501
2.71875
3
[]
no_license
$(function () { var protocol = location.protocol === "https:" ? "wss:" : "ws:"; var ws = new WebSocket(protocol + "//" + location.host + "/ws"); ws.onmessage = function (msg) { var data = JSON.parse(msg.data); render(data) } console.log("ready!"); }); function render(data) { $("#content").html(""); data.forEach(function(value) { $("#content").append("<div class='element'>" + "#" + value.hashTag + " (" + value.count + ")" + "</div>"); }) }
true
eb228b8035d576aa45ed92c6fa5ef1f2ff5abfc1
JavaScript
WaliiidAls/TicTacToe
/script.js
UTF-8
4,917
3.078125
3
[]
no_license
let bg1 = document.getElementsByClassName("bg1"); let bg2 = document.getElementsByClassName("bg2"); let bg3 = document.getElementsByClassName("bg3"); let bg4 = document.getElementsByClassName("bg4"); let bg = [bg1, bg2, bg3, bg4]; function background() { for (let i = 0; i < 4; i++) { let rgba1 = [ Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), 0.5, ]; let rgba2 = [ Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), 0.5, ]; let rgba3 = [ Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), 0.5, ]; let rgba4 = [ Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), Math.floor(Math.random() * 256), 0.5, ]; let rgba = [rgba1, rgba2, rgba3, rgba4]; bg[ i ][0].style.backgroundColor = `rgba(${rgba[i][0]}, ${rgba[i][1]}, ${rgba[i][2]}, ${rgba[i][3]})`; bg[i][0].style.transform = `rotate(${Math.floor(Math.random() * 360)}deg)`; } } function begin() { let beginSign = document.getElementsByClassName("begin"); beginSign[0].style.display = "none"; slots = [ ["", "", ""], ["", "", ""], ["", "", ""], ]; won = false; turn = "X"; moves = 0; match += 1; document.getElementById("matchNumber").innerHTML = `MATCH ${match}`; document.getElementById("turn").innerHTML = `${turn}'s Turn`; document.getElementById("00").innerHTML = ""; document.getElementById("00").style.pointerEvents = "auto"; document.getElementById("01").innerHTML = ""; document.getElementById("01").style.pointerEvents = "auto"; document.getElementById("02").innerHTML = ""; document.getElementById("02").style.pointerEvents = "auto"; document.getElementById("10").innerHTML = ""; document.getElementById("10").style.pointerEvents = "auto"; document.getElementById("11").innerHTML = ""; document.getElementById("11").style.pointerEvents = "auto"; document.getElementById("12").innerHTML = ""; document.getElementById("12").style.pointerEvents = "auto"; document.getElementById("20").innerHTML = ""; document.getElementById("20").style.pointerEvents = "auto"; document.getElementById("21").innerHTML = ""; document.getElementById("21").style.pointerEvents = "auto"; document.getElementById("22").innerHTML = ""; document.getElementById("22").style.pointerEvents = "auto"; } // 00 01 02 // 10 11 12 // 20 21 22 let slots = [ ["", "", ""], ["", "", ""], ["", "", ""], ]; let match = 0; let turn = "X"; let moves = 0; let won = false; function pressed(x) { let slot = document.getElementById(`${x}`); slot.style.pointerEvents = "none"; slot.innerHTML = turn; slot.style.color = turn == "X" ? "#ffa931" : "#12cad6"; pickedSlots(x, turn); background(); check4Winner(turn); turn = turn == "X" ? "O" : "X"; document.getElementById("turn").innerHTML = `${turn}'s Turn`; moves += 1; if (moves == 9 && won == false) { document.getElementsByClassName("begin")[0].innerHTML = `Tie`; document.getElementsByClassName("begin")[0].style.color = "white"; document.getElementsByClassName("begin")[0].style.display = "block"; } } function pickedSlots(x, player) { let num = x, output = [], sNumber = num.toString(); for (let i = 0; i < 2; i++) { output.push(+sNumber.charAt(i)); } slots[output[0]][output[1]] = player; } function check4Winner(player) { if ( slots[0][0] == slots[0][1] && slots[0][1] == slots[0][2] && slots[0][2] == player ) { Winner(player); } else if ( slots[1][0] == slots[1][1] && slots[1][1] == slots[1][2] && slots[1][2] == player ) { Winner(player); } else if ( slots[2][0] == slots[2][1] && slots[2][1] == slots[2][2] && slots[2][2] == player ) { Winner(player); } else if ( slots[0][0] == slots[1][0] && slots[1][0] == slots[2][0] && slots[2][0] == player ) { Winner(player); } else if ( slots[0][1] == slots[1][1] && slots[1][1] == slots[2][1] && slots[2][1] == player ) { Winner(player); } else if ( slots[0][2] == slots[1][2] && slots[1][2] == slots[2][2] && slots[2][2] == player ) { Winner(player); } else if ( slots[0][0] == slots[1][1] && slots[1][1] == slots[2][2] && slots[2][2] == player ) { Winner(player); } else if ( slots[0][2] == slots[1][1] && slots[1][1] == slots[2][0] && slots[2][0] == player ) { Winner(player); } } function Winner(winner) { won = true; document.getElementsByClassName("begin")[0].innerHTML = `${winner} won`; document.getElementsByClassName("begin")[0].style.color = winner == "X" ? "#ffa931" : "#12cad6"; document.getElementsByClassName("begin")[0].style.display = "block"; }
true
d9c5e18fc55ee31f0ed9033593eda31781a7cb93
JavaScript
mjaracz/node-exc
/node/JunggleAsh/3GetReghttps.js
UTF-8
489
2.828125
3
[]
no_license
const http = require('http'); const httpGet = require('./modul-callback.js'); const bl = require('bl'); let count = 0; var arr = []; const get = function(index) { http.get(process.argv[2 + index], (respons) => { respons.pipe(bl((err, data) => { if(err) { console.error(err) } arr.push(data.toString()); // console.log(arr) })) }); console.log(arr) } for(let i = 0; i < 3; i++) { get(i); count++; } if(count === 3) { arr.map(item => console.log(item)); }
true
6008baf8b8d8e3394fb44c0086e9af05c8658954
JavaScript
jschlitz/Slideshow
/slideshow.js
UTF-8
1,595
3.265625
3
[]
no_license
"use strict"; //var IMAGES is defined in another file. var SHIFT, FADE, STEADY; SHIFT = 10; FADE = 1500; STEADY = 5000; $(document).ready(function(){ console.log(IMAGES.length); doSlides('#leftImage', 0, IMAGES); setTimeout(function(){doSlides('#rightImage', 50, IMAGES);}, STEADY); }); ///Do the slideshow for the img element, perpetually. /// id - css id to use /// baseOffset - how far left do we go as a percentage /// files - array of files function doSlides(id, baseOffset, files){ var item, lshift, vshift, p0, p1, p2, p3, fraction; item = $(id); item[0].src = randomItem(files); //there is probably a better way of doing this console.log(item[0].src); lshift = randomInt(2*SHIFT) - SHIFT; vshift = (randomInt(2*SHIFT) - SHIFT); fraction = STEADY / (2*FADE + STEADY); p0 = {opacity:0, left:(baseOffset + lshift) + '%', top:vshift + '%'}; p1 = {opacity:0.9, left:(baseOffset + lshift*fraction) + '%', top:(vshift*fraction) + '%'}; p2 = {opacity:0.9, left:(baseOffset + lshift*(fraction-1)) + '%', top:(vshift*(fraction-1)) + '%'}; p3 = {opacity:0, left:(baseOffset - lshift) + '%', top: (-1 * vshift) + '%'}; item.css(p0) .animate(p1, FADE, 'linear') .animate(p2, STEADY, 'linear') .animate(p3, FADE, 'linear', function() { doSlides(id, baseOffset, files); //let's see if this blows the stack. }); } ///random number from [0-max) function randomInt(max){ return Math.floor(Math.random()*max); } ///Get a random item from an array. yeah, you can break it with [] function randomItem(arr){ return arr[randomInt(arr.length)]; }
true
6fccb0997e3433f94ee24d349cb5022a845a7179
JavaScript
smoreira1/Vanilla-Component-YMCA
/src/ymca-search-component.js
UTF-8
5,165
2.59375
3
[]
no_license
window.ymcaSearchComponent = { apiPath: '', loggedIn: false, async: true, renderResultsNow: false, familyName: 'Not logged in.', filters: { familyCenter: '', zipCode: '', program: '', dayOfTheWeek: '', times: '' }, familyCenters: [], programs: [], init: async function (filters, loggedIn, async, renderResultsNow, apiPath) { this.config(filters, loggedIn, async, renderResultsNow, apiPath); //NOTE: FIX ME! THESE ASYNC CALLS DO NOT DEPEND ON EACH OTHER. this.programs = await fetch(`${this.apiPath}/programs.json` , {mode:'cors'}).then((response) => { return response.json(); }); this.familyCenters = await fetch(`${this.apiPath}/familyCenters.json` , {mode:'cors'}).then((response) => { return response.json(); }); this.render(); if(this.renderResultsNow){ this.search(); } }, config: function (filters, loggedIn, async, renderResultsNow, apiPath) { this.apiPath = apiPath; this.filters.familyCenter = filters.familyCenter; this.filters.zipCode = filters.zipCode; this.filters.program = filters.program; this.filters.daysOfTheWeek = filters.daysOfTheWeek; this.filters.times = filters.times; this.loggedIn = loggedIn; this.async = async; this.renderResultsNow = renderResultsNow; }, render: function () { document.getElementById("ymca-search-component").innerHTML = `<div class='ymca-component-search'> <div class='ymca-component-search-header'>Search Programs</div> <div class="ymca-component-family-logged-in">Family: ${this.familyName}</div> ${this.getFamilyCentersRendered()} <input class="ymca-component-zipcode ymca-component-input" placeholder="ZIP Code" value='${this.filters.zipCode}'></input> ${this.getProgramsRendered()} <div class="ymca-component-search-button-container"><button class="ymca-component-search-button" onclick="ymcaSearchComponent.search()" type="button">Search</button></div> </div> </div>`; }, getSearchResultsRender: function () { return fetch(`${this.apiPath}/ymcaPrograms.json`) .then((response) => { return response.json(); }) .then((data) => { return data.map(i => `<div class="ymca-search-result"> <div class="ymca-search-result-title">${i.title}</div> <div class="ymca-search-result-body"> <div class="ymca-search-result-times">${i.times}</div> <div class="ymca-search-result-details">${i.details}</div> <div class="ymca-search-result-actions"> <a href="" class="details-action">Details</a> <a href="" class="visit_action">Visit This Y</a> </div> </div> </div>`).join(''); }); }, getProgramsRendered: function () { const programOptions = this.programs.map(i => { if (this.filters.program === i.value) { return `<option value='${i.value}' selected>${i.name}</option>` } else { return `<option value='${i.value}'>${i.name}</option>` } }).join(''); return `<select class='ymca-program-select ymca-component-select' name='ymca-programs'>${programOptions}</select>`; }, getFamilyCentersRendered: function () { const familyCentersOptions = this.familyCenters.map(i => { if (this.filters.familyCenter === i.value) { return `<option value='${i.value}' selected>${i.name}</option>` } else { return `<option value='${i.value}'>${i.name}</option>` } }).join(''); return `<select class='ymca-family-center-select ymca-component-select' name='ymca-family-center'>${familyCentersOptions}</select>`; }, search: function () { if (this.async) { this.getSearchResultsRender().then((response) => { document.getElementById("ymca-search-results").innerHTML = response; }); } else { //Navigate to a specific url in the domain so the user can potentially see other data. window.location.href = window.location.hostname; } } }
true
edcca49cf833c4e1402d6358106655db72194582
JavaScript
bredek/LoftShool-js
/app/js/hw1.js
UTF-8
341
2.875
3
[]
no_license
function consoleRec(input, index) { if (index < input.length) { console.log(input[index]); consoleRec(input, ++index); } } var hw1 = { init: function() { var testData = ['Ja', 'умею', 'писать', 'рекурсивные', 'функции']; consoleRec(testData, 0); } } hw1.init();
true
278cb0954eb22d4408a4969d10701ea62d84c31e
JavaScript
sayttplx/hamsterwars
/server/scripts/getHamsterById.js
UTF-8
450
2.75
3
[]
no_license
const { db } = require('../firebase') const HAMSTERS = 'hamsters' getHamsterById(id) async function getHamsterById(id) { console.log('Looking for Sixten...'); const hamsterId = id const hamsterSnapshot = await db.collection(HAMSTERS).doc(hamsterId).get() if (!hamsterSnapshot.exists) { console.log('Could not find him!'); return null } const hamster = await hamsterSnapshot.data() return hamster; }
true
a70442dc658f4249a41c98be0e71d3bf8fe79e92
JavaScript
KarpusKonstantin/brackets
/src/index.js
UTF-8
618
2.78125
3
[ "MIT" ]
permissive
module.exports = function check(str, bracketsConfig) { function getBracketsArray (config) { // console.log(config); return config.map(function(item) { // console.log(item.join('')); return item.join(''); }); } let bracketsArray = getBracketsArray(bracketsConfig); // console.log(str, bracketsArray); for (let i = 0; i < bracketsArray.length;) { if (str.indexOf(bracketsArray[i]) !== -1) { str = str.replace(bracketsArray[i], ''); // console.log(str); i = 0; } else i++; }; return !str; }
true
36a565f8a6e4ab650c1e1092345804734ac08eb3
JavaScript
vitalyli81/Algorithmic-problems
/src/problem-set-2/dp/permutations/permute.js
UTF-8
508
3.5
4
[]
no_license
/** * @param {number[]} nums * @return {number[][]} */ const permute = nums => { if (!nums) return null; const permutations = []; if (nums.length === 0) { permutations.push([]); return permutations; } const first = nums[0]; const remainder = nums.slice(1); const prevPerms = permute(remainder); prevPerms.forEach(prev => { for (let i = 0; i <= prev.length; i++) { permutations.push([...prev.slice(0, i), first, ...prev.slice(i)]); } }); return permutations; };
true
d3f9e54f60073077f7855f60daf2fadd65e415b9
JavaScript
Probir-gayen/blog
/public/js/control.js
UTF-8
4,335
2.546875
3
[ "MIT" ]
permissive
$("document").ready(function(){ var inc = 0; $("#email").blur(function(e){ var check="val="+$('#email').val()+"&opt=email"; $.ajax({ type :'post' , url:"http://localhost/Blog/public/login/ajax", data : check, success : function(data) { if(data == "Email Already Exist") { //alert(data); $("#semail").html(data); } else { $("#semail").html(data); } } }); }); $("#fname").blur(function(e){ var check1="val="+$('#fname').val()+"&opt=fname"; $.ajax({ type :'post' , url:"http://localhost/Blog/public/login/ajax", data : check1, success : function(data) { if(data == "Name Already Exist") { //alert(data); $("#sname").html(data); } else { $("#sname").html(data); } } }); }); $("#category").click(function(e){ var cat=$('#category').val(); var data; if(cat=="Technical"){ data = '<option>Select Tag</option><option>Java</option><option>PHP</option><option>C and C++</option><option>dot Net</option><option>C Sharp</option><option>Others</option>'; $("#tag").html(data); } if(cat=="Communication"){ data = '<option>Select Tag</option><option>Facebook</option><option>Line</option><option>Hike</option><option>Blog</option><option>WhatsApp</option><option>Others</option>'; $("#tag").html(data); } if(cat=="Food"){ data = '<option>Select Tag</option><option>Non-veg</option><option>Veg</option><option>dot Net</option><option>Others</option>'; $("#tag").html(data); } if(cat=="Entertainment"){ data = '<option>Select Tag</option><option>Comedy</option><option>Hollywood</option><option>Bollywood</option><option>Circus</option><option>Zoo</option><option>Others</option>'; $("#tag").html(data); } if(cat=="Ethical"){ data = '<option>Select Tag</option><option>Religion</option><option>Others</option>'; $("#tag").html(data); } if(cat=="Social Message"){ data = '<option>Select Tag</option><option>Facebook</option><option>Twitter</option><option>Blog</option><option>Linkdine</option><option>Others</option>'; $("#tag").html(data); } if(cat=="News"){ data = '<option>Select Tag</option><option>National</option><option>International</option><option>Politics</option><option>Sports</option><option>Business</option><option>Others</option>'; $("#tag").html(data); } if(cat=="Awareness"){ data = '<option>Select Tag</option><option>Diseases</option><option>Soical Awar</option><option>New Act</option><option>Others</option>'; $("#tag").html(data); } if(cat=="Others"){ data ='<input type="text" name="categoryop" placeholder="Enter Category">'; $("#catop").html(data); $('#tag').html('<option>Others</others>'); $('#tagop').html('<input type="text" name="tagop" placeholder="Enter Tag">'); } else{ $("#catop").toggle(); $("#tagop").toggle(); } }); $("#tag").click(function(e){ var cat=$('#tag').val(); if(cat=="Others") { $('#tagop').html('<input type="text" name="tagop" placeholder="Enter Tag" required>'); } }); $(".moref").click(function(e){ if(inc<20) { inc+=1; $('#more').append('<input type="text" name="tag'+inc+'" placeholder="Enter Tag" required>') } }); });
true
26e54fab1e4078cba54e47422d7ac25bda58bdf0
JavaScript
ghelloumi/TodoApp
/src/services/pictureFetch.js
UTF-8
283
2.6875
3
[]
no_license
const fetchImage = async () => { const myInit = {method: 'GET', mode: 'cors', cache: 'default'} try { const res = await fetch('http://aws.random.cat/meow', myInit) return res.json() } catch (e) { console.error(e) return null } } export default fetchImage()
true
70c8831f9ea998d210f9c1beb57a7730c79d6f3f
JavaScript
rahamin1/mypet
/src/reducers/_history/AuthReducer.save.js
UTF-8
2,025
2.53125
3
[]
no_license
import * as actions from '../actions/types'; const INITIAL_STATE = { email: '', uid: '', checkAuthInProcess: true, // upon initialization, a check is made // In firebase, whether already logged in loginInProcess: false, loginError: '', signupInProcess: false, signupError: '', emailChangeInProcess: false, passwordChangeInProcess: false }; export default function AuthReducer(state = INITIAL_STATE, action) { switch (action.type) { case actions.INIT_USER_STATE: return INITIAL_STATE; case actions.LOGIN_START: return { ...state, loginInProcess: true, loginError: '', email: '', uid: '' }; case actions.LOGIN_USER_SUCCESS: return { ...state, loginInProcess: false, loginError: '', email: action.payload.email, uid: action.payload.uid }; case actions.LOGIN_USER_FAIL: return { ...state, loginInProcess: false, loginError: action.payload.message, email: '', uid: '' }; case actions.SIGNUP_START: return { ...state, signupInProcess: true, signupError: '', email: '', uid: '' }; case actions.SIGNUP_USER_SUCCESS: return { ...state, signupInProcess: false, signupError: '', email: action.payload.email, uid: action.payload.uid }; // Mark in the store that the user is signed-in case actions.AUTH_USER: return { ...state, email: action.payload.email, uid: action.payload.uid, checkAuthInProcess: false }; case actions.SIGNUP_USER_FAIL: return { ...state, signupInProcess: false, signupError: action.payload.message, email: '', uid: '' }; case actions.EMAIL_CHANGED: return { ...state, email: action.payload, emailChangeInProcess: false }; case actions.PASSWORD_CHANGED: return { ...state, password: action.payload, passwordChangeInProcess: false }; case actions.SIGN_OUT: case actions.SIGN_OUT_ALL: return { ...INITIAL_STATE, checkAuthInProcess: false }; default: return state; } }
true
cf18194e593769c8d244df1607dfb493ed5fdb17
JavaScript
armandogj1/advent-of-code-2020
/DaySeven/bagChecker.js
UTF-8
1,766
2.9375
3
[]
no_license
const readline = require('readline'); const { createReadStream } = require('fs'); const bagRules = new Map(); const fileStream = createReadStream('./input.txt'); const lineReader = readline.createInterface({ input: fileStream, }); lineReader.on('line', (line) => { const [key, innerMap] = ruleSplitter(line); bagRules.set(key, innerMap); }); lineReader.on('close', () => { // run function console.log(bagRules.size); // console.log(ruleSplitter(bagRules[0])); console.log(checkValidOuter(bagRules, 'shiny gold', new Set())); console.log(bagRules.get('shiny gold')); let totalBags = findAllTheBags('shiny gold', bagRules, []); totalBags = totalBags.reduce((acc, value) => { return (acc += value); }, 0); console.log(totalBags); }); const ruleSplitter = (rule) => { let [outerBag, innerBag] = rule.trim().split('contain'); outerBag = outerBag.trim().split(' ').slice(0, -1).join(' '); splitInners = innerBag.split(',').map((bag) => { const temp = bag.trim().split(' ').slice(0, -1); const color = temp.slice(1).join(' '); return [color, temp[0]]; }); innerBag = new Map(splitInners); return [outerBag, innerBag]; }; const checkValidOuter = (bags, bagToCheck, arrayOfBags) => { let countValid = 0; let count = 0; bags.forEach((innerBags, key) => { if (innerBags.has(bagToCheck)) { arrayOfBags.add(key); checkValidOuter(bags, key, arrayOfBags); } }); return arrayOfBags.size; }; const findAllTheBags = (bag, allBags, totalBags) => { if (allBags.has(bag)) { allBags.get(bag).forEach((value, key) => { if (value !== 'no') { const amount = Number(value); totalBags.push(amount); for (let i = 0; i < amount; i++) { findAllTheBags(key, allBags, totalBags); } } }); } return totalBags; };
true
07fbf36fb8a7197d56645270cf450b1cc2429fa7
JavaScript
sirius8611/vocabulary
/src/redux/features/WordList/wordList.js
UTF-8
3,374
2.625
3
[]
no_license
import React, { useState } from 'react' import { useSelector, useDispatch } from 'react-redux'; import {removeWord, selectWordList, changeStatus } from './wordListSlice'; import './wordList.css' export const WordList = () => { const dispatch = useDispatch() const wordlist = useSelector(selectWordList) let btnColor, numberOfLearnedWord = 0 const [modalContent, setContent] = useState({ title: '', text: '' }) function popModal(component) { setContent({ title: component.word, text: component.meaning }) } function handleClick(component) { dispatch(changeStatus(component)) } function handleDelete(component) { dispatch(removeWord(component)) } function congrats(perc){ if(perc===100){ return ( <h1 className="text-center">Damn you kill the vocabs. Congrats!!!!!<i class="bi bi-emoji-sunglasses"></i><i class="bi bi-emoji-sunglasses"></i></h1> ) } else{ return <span></span> } } const list = wordlist.map(w => { numberOfLearnedWord += w.status === false ? 1 : 0 const wordStatus = w.status ? 'New' : 'Learned' btnColor = w.status ? 'btn-danger' : 'btn-success' return ( <React.Fragment> <div className="md-9 col"> <label for='modal-1' onClick={() => popModal(w)} className="btn-block paper-btn text-center">{w.word}</label> </div> <div className="md-2 col wordBtn"> <button className={btnColor} onClick={() => handleClick(w)}>{wordStatus}</button> </div> <div className="md-1 col wordBtn"> <button className="text-center" onClick={() => handleDelete(w)}><i class="bi bi-hand-thumbs-down"></i></button> </div> {/* <fieldset class="form-group"> <label for="status" class="paper-switch-tile"> <input id="status" name="status" type="checkbox" /> <div class="paper-switch-tile-card border"> <div class="paper-switch-tile-card-front status-paper border background-danger">New</div> <div class="paper-switch-tile-card-back status-paper border background-success">Learned</div> </div> </label> </fieldset> */} </React.Fragment> ) }) let percent = Math.round(numberOfLearnedWord/(wordlist.length) * 100) let progressPercent = `bar success w-${percent}` console.log(numberOfLearnedWord) console.log(wordlist.length) const message = (num) => { let text = num<= 1 ? 'word. Finally!' : 'words' if(num === 0){ return <span className="text-danger">nothing, you lazy.</span> } else{ return <span className="text-success">{num} {text}</span> } } return ( <div className="row flex-center"> <div className="col-12 col"> You have learned {message(numberOfLearnedWord)} </div> {list} <div className="col-9 col "> <div className="progress flex-center margin-bottom margin-top-large"> <div className={progressPercent}> </div> </div> </div> <div className="col-12 col">{congrats(percent)}</div> <input className="modal-state" id="modal-1" type="checkbox" /> <div className="modal col-12 col"> <label className="modal-bg" for="modal-1"></label> <div className="modal-body"> <label className="btn-close" for="modal-1">X</label> <h2 className="modal-title">{modalContent.title}</h2> <h4 className="modal-text">{modalContent.text}</h4> <label for='modal-1' className="border paper-btn">Got it!</label> </div> </div> </div> ) }
true
885323c3b607146a4ad090dcc8935836a744a4d0
JavaScript
ajbates2/noteful-assignment
/src/AddFolder/addFolder.js
UTF-8
1,745
2.515625
3
[]
no_license
import React, { Component } from 'react'; import NoteContext from '../noteContext' class AddFolder extends Component { static contextType = NoteContext; handleSubmit = event => { event.preventDefault(); const { folderName } = event.target const folder = { name: folderName.value } console.log({ folderName }) fetch(`http://localhost:9090/folders`, { headers: { 'Content-Type': 'application/json' }, method: 'POST', body: JSON.stringify(folder) }) .then(response => { if (!response.ok) { return response.json().then(error => { throw error }) } return response.json() }) .then(data => { folderName.value = '' this.context.handleAddFolder(data) this.props.history.push(`/folder/${data.id}`) }) .catch(error => { console.error(error) }) } render() { return ( <form className="Noteful-form" onSubmit={this.handleSubmit}> <div className="field"> <label htmlFor="folder-name-input">Name {' '}</label> <input type="text" id="folderName" name="folderName" required /> </div> <div className="buttons"> <button type="submit">Add folder</button> </div> </form> ) } } export default AddFolder;
true
a8f38a1076fd7c826a66d173fd4eaf048e2486bb
JavaScript
niza3001/EnactmentProject
/emid5.3/Assets/Scripts/Screens/GenerateScreen4.js
UTF-8
7,206
2.546875
3
[]
no_license
//Aligning the 3 boxes in all resolutions will be a CHALLENGE! saveMyStrings function saves all the playerprefs at once. //Playerprefs : summaryBegin, summaryMid, summaryEnd, stateOfStory #pragma strict import System.IO; import System; public var customSkin:GUISkin; public var label2Style:GUIStyle; public var label3Style:GUIStyle; public var question:String = "What is your story about?"; public var bgTexture : Texture2D; private var menuBar:boolean = true; private var stage:boolean = true; private var questionWindow : Rect = new Rect(0,0, 800,200); private var storyTitle:String = ""; private var summaryBegin:String = ""; private var summaryMid:String = ""; private var summaryEnd:String = ""; private var buttonClicked:String = ""; private var verticalSpacing:float = Screen.height*0.1; private var horizontalSpacing:int = Screen.width/10; private var boxHeight:int = Screen.height/4; private var boxWidth:int = Screen.width/4; private var freshStory:int ; private var scrollPositionBegin : Vector2 = Vector2.zero; private var scrollPositionMid : Vector2 = Vector2.zero; private var scrollPositionEnd : Vector2 = Vector2.zero; private var storyTeller1:String = ""; private var storyTeller2:String = ""; private var fileName:String = ""; function Start() { storyTitle = PlayerPrefs.GetString("storyTitle"); storyTeller1 = PlayerPrefs.GetString("storyTeller1"); storyTeller2 = PlayerPrefs.GetString("storyTeller2"); fileName = storyTeller1+storyTeller2; freshStory = PlayerPrefs.GetInt("freshStory",freshStory); if(!freshStory) { summaryBegin = PlayerPrefs.GetString("summaryBegin",summaryBegin); summaryMid = PlayerPrefs.GetString("summaryMid",summaryMid); summaryEnd = PlayerPrefs.GetString("summaryEnd",summaryEnd); } saveInfoForDataAnalysis(); } private var builtInArray1 : String[]; private var builtInArray2 : String[]; private var builtInArray3 : String[]; function saveInfoForDataAnalysis() { //AppendAllText(C:\Users\Kumar\Documents\Dime\Assets); //This function takes in SUmaryBegin, mid, End, AND storyTitle, beginTabArray, midTabArray, endTabArray var dt = DateTime.Now; var AllData:String = ""; AllData += "\n\n\n Home Button was clicked at Time:"; AllData += dt.ToString(); AllData += "\nStory Title:"+storyTitle; AllData += "\n Story Authors are"+storyTeller1+"and"+storyTeller2+"\n"; AllData += "\nBeginning Summary:"+summaryBegin+"\nMiddle Summary:"+summaryMid+"\nEnding Summary:"+summaryEnd+"\n\n"; builtInArray1 = PlayerPrefsX.GetStringArray("beginTabArray"); builtInArray2 = PlayerPrefsX.GetStringArray("midTabArray"); builtInArray3 = PlayerPrefsX.GetStringArray("endTabArray"); for(var i = 0;i < builtInArray1.length; i++) { //parse through all the array elements and print it to the alldata if(builtInArray1[i] != "BLANK" && builtInArray1[i] != "") { AllData += "\nBeginning Frame Number"+i.ToString()+":"+builtInArray1[i]; } } for( i = 0;i < builtInArray2.length; i++) { if(builtInArray2[i] != "BLANK" && builtInArray2[i] != "") { AllData += "\nMiddle Frame Number"+i.ToString()+":"+builtInArray2[i]; } } for( i = 0;i < builtInArray3.length; i++) { //parse through all the array elements and print it to the alldata if(builtInArray2[i] != "BLANK" && builtInArray2[i] != "") { AllData += "\nEnding Frame Number"+i.ToString()+":"+builtInArray3[i]; } } Debug.Log(AllData); File.AppendAllText(fileName,AllData); } function saveMyStrings() //Saves all the needed strings to PlayerPrefabs and saves it to hard disk { if(menuBar) { PlayerPrefs.SetString("storyTitle",storyTitle); PlayerPrefs.Save(); } if(stage) { PlayerPrefs.SetString("summaryBegin",summaryBegin); PlayerPrefs.SetString("summaryMid",summaryMid); PlayerPrefs.SetString("summaryEnd",summaryEnd); PlayerPrefs.SetString("stateOfStory", buttonClicked); PlayerPrefs.SetInt("freshStory",freshStory); PlayerPrefs.Save(); } } function OnGUI() { GUI.skin = customSkin; //for label alignment GUI.DrawTexture(Rect(0,0,Screen.width,Screen.height), bgTexture, ScaleMode.StretchToFill); if(menuBar) { GUILayout.BeginHorizontal(); //GUILayout.Label("Home", GUILayout.Width(300)); GUILayout.Space(Screen.width-600); GUILayout.Label("Story Title:",GUILayout.Width(220),GUILayout.Height(50)); //storyTitle = PlayerPrefs.GetString("storyTitle"); storyTitle = GUILayout.TextField (storyTitle, 36,GUI.skin.FindStyle("menuText"), GUILayout.Width(300),GUILayout.Height(60)); saveMyStrings(); GUILayout.EndHorizontal(); } if(stage) { GUILayout.BeginVertical(); GUILayout.Space(verticalSpacing*0.6); GUILayout.Label(question,GUI.skin.FindStyle("screen4LabelCenter")); //GUILayout.Space(horizontalSpacing/4); GUILayout.Label("Write a summary of the beginning middle and end of your story",GUI.skin.FindStyle("screen4LabelCenter2")); GUILayout.EndVertical(); GUILayout.BeginHorizontal(); GUILayout.BeginArea(Rect(horizontalSpacing,2*verticalSpacing,boxWidth, 3*boxHeight)); GUILayout.BeginVertical(); GUILayout.Space(verticalSpacing); GUILayout.Label("Beginning",label3Style); // scrollPositionBegin = GUILayout.BeginScrollView(scrollPositionBegin, false, true ,GUILayout.Width(1.2*boxWidth),GUILayout.Height(1.5*boxHeight)); summaryBegin = GUILayout.TextArea(summaryBegin, 200,GUILayout.Width(boxWidth),GUILayout.Height(1.5*boxHeight)); // GUILayout.EndScrollView(); if(GUILayout.Button("Create story",GUILayout.Width(boxWidth*0.96),GUILayout.Height(80))) { freshStory = 0; buttonClicked = "Beginning"; saveMyStrings(); Application.LoadLevel(5); } GUILayout.EndVertical(); GUILayout.EndArea(); GUILayout.BeginArea(Rect(20+boxWidth+horizontalSpacing,2*verticalSpacing,boxWidth,3*boxHeight)); GUILayout.BeginVertical(); GUILayout.Space(verticalSpacing); GUILayout.Label("Middle",label3Style); // scrollPositionMid = GUILayout.BeginScrollView(scrollPositionMid, false, true ,GUILayout.Height(1.5*boxHeight)); summaryMid = GUILayout.TextArea(summaryMid, 200,GUILayout.Width(boxWidth),GUILayout.Height(1.5*boxHeight)); // GUILayout.EndScrollView(); if(GUILayout.Button("Create story",GUILayout.Width(boxWidth*0.96),GUILayout.Height(80))) { freshStory = 0; buttonClicked = "Middle"; saveMyStrings(); Application.LoadLevel(5); } GUILayout.EndVertical(); GUILayout.EndArea(); GUILayout.BeginArea(Rect(20+(2*boxWidth)+horizontalSpacing,2*verticalSpacing,boxWidth,3*boxHeight)); GUILayout.BeginVertical(); GUILayout.Space(verticalSpacing); GUILayout.Label("Ending",label3Style); // scrollPositionEnd = GUILayout.BeginScrollView(scrollPositionEnd, true,true ,GUILayout.Height(1.5*boxHeight)); summaryEnd = GUILayout.TextArea(summaryEnd, 200,GUILayout.Width(boxWidth),GUILayout.Height(1.5*boxHeight)); // GUILayout.EndScrollView(); if(GUILayout.Button("Create a story",GUILayout.Width(boxWidth*0.96),GUILayout.Height(80))) { freshStory = 0; buttonClicked = "Ending"; saveMyStrings(); Application.LoadLevel(5); } GUILayout.EndVertical(); GUILayout.EndArea(); GUILayout.EndHorizontal(); } }
true
338571fa4743fc54fa03fea84e97071192c92f24
JavaScript
itsAnyTime/recordShop-mongoose
/controller/orders-controller.js
UTF-8
2,960
3
3
[]
no_license
//importiere das Model für Records (RecordItem) const Order = require('../models/order') //npm packet um codesparender (1 Zeile) Fehler zu schreiben const createError = require('http-errors') //Anfragen mit Callback/////////////////////////////////////////////////////////////////////////////////////// // const ordersGetController = (req, res, next) => { // Order.find((err, ergebnis)=> { // if (err){ // res.status(500).send('Fehler bei GET auf /orders/:'+err) // }else{ // res.status(200).send(ergebnis) // } // }) // } // const ordersPostController = (req, res, next)=>{ // const newOrder = req.body // // console.log(newOrder) // // //1. Parameter ein Object - 2 Paramenter callback Funktion, die ausgeführt wird, wenn er fertig ist // Order.create(newOrder, (err, ergebnis)=>{ // if(err){ // res.status(500).send('Fehler bei POST auf /orders/:'+err) // }else{ // res.status(201).send(ergebnis) // } // }) // } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// //eleganter mit Async / Await const ordersPostController = async (req, res, next) => { try { const neueDaten = new Order(req.body); await neueDaten.save() res.status(201).send(neueDaten) } catch (error) { //dieser Fehler wird mit next an die Fehlerbehandlungsfunktion weitergegen next(error) } } const ordersGetController = async (req, res, next) => { try { const myOrderlist = await Order.find({}) res.status(200).send(myOrderlist) } catch (error) { next(error) } } const ordersGetOneController = async (req, res, next) => { try { const { id } = req.params; const myOneOrder = await Order.find({ _id: id }) if(!id || myOneOrder.length<1) throw new Error res.status(200).send(myOneOrder) } catch (error) { //wenn wir keinen eigenen error spezifizieren und mit next(myError weitergeben) übernimmt unsere Error Middleware //die Fehlermeldung mit Standards let myError=createError(404, 'bitte gebe eine gültige ID an') next(myError) // next(error) } } const ordersPutController = async (req, res, next) =>{ try { const {id} =req.params; const valuesToChange =req.body; const updatedOrderEntry = await Order.updateOne({_id:id},valuesToChange) res.status(200).send(updatedOrderEntry) }catch(error){ next(error) } } const ordersDeleteController = async (req, res, next)=>{ try{ const {id} = req.params; let orderToDelete = await Order.deleteOne({_id:id}); res.status(200).send(orderToDelete) }catch(error){ next(error) } } module.exports = { ordersPostController, ordersGetController, ordersGetOneController, ordersPutController, ordersDeleteController }
true
7b1baa0d264349b4268496f190950cfcc17988ab
JavaScript
Monicadorthy/Assignment5FrontendDevelopment
/app3Assignment5.4.js
UTF-8
639
2.671875
3
[]
no_license
var Employee= ["Employee name","age","salary","city","state","pincode", {Employeename1:"Employee name" ,age:"age", salary:"salary" ,city:"city ",state:"state", pincode:"pincode"} ,{Employeename2:"Employee name" ,age:"age", salary:"salary" ,city:"city ",state:"state", pincode:"pincode"} ,{Employeename3:"Employee name" ,age:"age", salary:"salary" ,city:"city ",state:"state", pincode:"pincode"} ,{Employeename4:"Employee name" ,age:"age", salary:"salary" ,city:"city ",state:"state", pincode:"pincode"} ,{Employeename5:"Employee name" ,age:"age", salary:"salary" ,city:"city ",state:"state", pincode:"pincode"} ]; console.log(Employee);
true
2e77a2e2b718c4f7d9fa11684c9651ffa0ec10b7
JavaScript
alfiomartini/city-weather
/static/old-weather-scripts.js
UTF-8
1,961
3.078125
3
[]
no_license
var CLEAR_RESULT = false; var CLEAR_TABLE = false; // I could use jQuery $(document).ready(function() { /* code here */ }); // window.onload = resetCountry; function buttonClear(){ clearResult(); CLEAR_RESULT = false; } function inputFocus(){ let input = document.querySelector('input'); $('input').focus(); } function clearResult(){ hideResult(); resetCountry(); } function cleanInput(){ $(document).ready(function(){ $('input[name="city"]').val(''); }); } function resetCountry(){ elem = document.getElementById("countryId"); elem.selectedIndex = 0; } function hideCities(){ $(document).ready(function(){ $("#search").html(''); }); } function hideResult(){ $(document).ready(function(){ $("#result").html(""); }); } function hideSpinner(){ $(document).ready(function(){ $("#spinner").html(""); }); } function evalForm(form){ // clean table of cities hideCities(); CLEAR_TABLE = false; $.get('spinner', function(data){ //alert(data); document.getElementById('spinner').innerHTML = data; }); var city = form['city'].value; var country = form['country'].value; var param = city; // country is an optional selection if (country) param = param + '/' + country; $.get('form/' + param, function(data){ hideSpinner(); document.getElementById("result").innerHTML = data; }); CLEAR_RESULT = true; cleanInput(); } let input = document.querySelector('input'); input.onkeypress = function(){ if (CLEAR_RESULT) { clearResult(); CLEAR_RESULT = false; } if (CLEAR_TABLE) { hideCities(); CLEAR_TABLE = false; } } input.onkeyup = function(){ // data is a table of elements that is returned from the "/search" route $.get('search/' + input.value, function(data){ document.querySelector('#search').innerHTML = data; }); CLEAR_TABLE = true; };
true
9b8addf7d029000f2eedb96f212578abb79a080f
JavaScript
ellipsis-ai/qrcode
/actions/decode/function.js
UTF-8
1,079
2.921875
3
[]
no_license
function(file, ellipsis) { const jpeg = require('jpeg-js'); const PNG = require('pngjs').PNG; const jsQR = require("jsqr"); file.fetch().then(res => { decode(res).then(image => { const code = jsQR(image.data, image.width, image.height); if (code && code.data) { ellipsis.success(code.data); } else { const details = code ? `\n\n${code.error}` : ""; ellipsis.error("Not a valid JPEG or PNG QR code." + details); } }); }); function decode(res) { return new Promise((resolve, reject) => { const ctype = res.contentType.toLowerCase(); if (ctype === "image/png") { res.value.pipe(new PNG({ filterType: 4 })).on('parsed', function(err, data) { resolve(this); }); } else if (ctype === "image/jpeg") { const bufs = []; res.value.on('data', function(d){ bufs.push(d); }); res.value.on('end', function() { const buf = Buffer.concat(bufs); resolve(jpeg.decode(buf, true)); }); } else { reject(`I don't know how to read images of type: ${ctype}`); } }); } }
true
b50c6964795f29c98c47653a0e256314621253c3
JavaScript
StefanS97/free-time-fun-javascript
/phoneNum.js
UTF-8
264
2.9375
3
[ "MIT" ]
permissive
function createPhoneNumber(numbers){ blank = ''; numbers.length == 10 ? numbers.forEach(n => blank += n) : ''; return '(' + blank[0] + blank[1] + blank[2] + ')' + ' ' + blank[3] + blank[4] + blank[5] + '-' + blank[6] + blank[7] + blank[8] + blank[9]; }
true
1b206033389867f5be82da727b2fde2521a2bbb3
JavaScript
veerapos/temp1
/NumberSound.js
UTF-8
7,711
2.890625
3
[]
no_license
function clearZero(Txt) { let i = 0 for(i=0; i<Txt.length; i++){ // ตัดเลข 0 ที่อยู่ข้างหน้าทิ้ง if(Txt[i] !== "0"){ break; } } return Txt.slice(i); } function reverseNumber(txt) { let reverseTxt = ""; for(i=0; i<txt.length; i++){ reverseTxt = txt[i] + reverseTxt; } return reverseTxt } function number2sound(nTextFromDoc) { // เสียงของตัวเลข เช่น หนึ่ง สอง สาม ... ซึ่งเมื่ออยู่กับค่าหลักบางหลักจะออกเสียงต่างกันเช่น เอ็ด ยี่ // [ 0, เสียงของตัวเลขเมื่ออยู่หลักหน่วย // 1, เสียงของตัวเลขเมื่ออยู่หลักสิบ // 2, เสียงของตัวเลขเมื่ออยู่หลักร้อย // 3, เสียงของตัวเลขเมื่ออยู่หลักพัน // 4, เสียงของตัวเลขเมื่ออยู่หลักหมื่น // 5 ] เสียงของตัวเลขเมื่ออยู่หลักแสน /* a['x1','x2','x3'] --> a[0]==> 'x1' a[1]==>'x2' b[ p['p1','p2'], q['q1','q2'] ] --> b[0][1]==>'p2' */ let numberSound = [ [ "", "เอ็ด", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า", "เสียงตัวเลขหลักหน่วย"], [ "", "", "ยี่", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า", "เสียงตัวเลขหลักสิบ" ], [ "", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า", "เสียงตัวเลขหลักร้อย" ], [ "", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า", "เสียงตัวเลขหลักพัน" ], [ "", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า", "เสียงตัวเลขหลักหมื่น" ], [ "", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า", "เสียงตัวเลขหลักแสน" ] ]; let numberSoundCol1 = [ "ศูนย์", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า" ]; // เสียงของค่าหลัก เช่น หลักหน่วย หลักสิบ ... หา index โดย mod ด้วย 6 // [ 0, 1, 2, 3, 4, 5 ] let valueSound = ["", "สิบ", "ร้อย", "พัน", "หมื่น", "แสน"]; let i = 0; let nText = ""; let nText2 = ""; // for reverse number let nTextLenght = 0; let n = 0; let nCol = 0; // ค่าของหลัก เช่น หน่วย สิบ ร้อย ... let vSound = "", nSound = ""; let nSoundFromDoc = ""; // เริ่มโปรแกรม if (nTextFromDoc === "") { return ""; // ไม่มีตัวเลขให้ออกเสียง } if(nTextFromDoc.length === 1){ // เป็นตัวเลขหลักเดียว return numberSoundCol1[nTextFromDoc]; //return nSoundFromDoc = numberSoundCol1[nTextFromDoc]; } nText = clearZero(nTextFromDoc); if(nText.length === 0){ // ถ้าไม่มีข้อมูลเหลือแสดงว่าป้อนค่าเป็น 0 มามากกว่า 1 ตัว return "ศูนย์" } nTextLenght = nText.length; n = 0; nCol = 0; // ค่าของหลัก เช่น หน่วย สิบ ร้อย ... vSound = "", nSound = ""; nSoundFromDoc = ""; // ทำการ reverse ตัวเลข 1234 --> 4321 nText2 = reverseNumber(nText); // ออกเสียงตัวเลข nSoundFromDoc = ""; for (i=0; i<nTextLenght; i++){ n = Number(nText2[i]); // ตัวเลขที่ต้องการออกเสียง nCol = i % 6; // ค่าของหลัก 0=หน่วย 1=สิบ ... if(i === nTextLenght-1 && nCol == 0){ // ตัวเลขที่อยู่ซ้ายมือสุดและเป็นหลักหน่วยต้องออกเสียง หนึ่ง เสมอ nSound = numberSoundCol1[n]; } else{ nSound = numberSound[nCol][n]; } if(n === 0){ // เลข 0 ไม่ออกเสียงหลัก vSound = ""; } else{ vSound = valueSound[nCol]; } if(nCol === 0 && i >= 6){ // ถ้ามีตัวเลขตั้งแต่ 6 ตัวต้องออกเสียง ล้าน ที่หลักหน่วย vSound = vSound + "ล้าน"; } nSoundFromDoc = nSound + vSound + nSoundFromDoc; } return nSoundFromDoc; } function numberFormat(nTextFromDoc) { if (nTextFromDoc === "") { return ""; // ไม่มีตัวเลข } let nText = clearZero(nTextFromDoc); // ตัวเลขที่ต้องการ format if(nText.length === 0){ // ถ้าไม่มีข้อมูลเหลือแสดงว่าป้อนค่าเป็น 0 มามากกว่า 1 ตัว return "0" } let nText2 = ""; // for reverse number let i = 0; let txt = ""; // เก็บผลลัพธ์ // ทำการ reverse ตัวเลข 1234 --> 4321 nText2 = reverseNumber(nText); for (i = 0; i<nText2.length; i++){ txt = nText2[i] + txt; if ((i+1) % 3 === 0 && i !== nText2.length-1){ // เติม , คั่นทุก 3 ตัวเลข txt = "," + txt; } } return txt; } function numberPad(n){ /* รับค่า event OnClick จากหน้า webpage 0..9 = Clear */ let eqFlag = !(document.getElementById("nSound").innerHTML === ""); if(n === "Clear") { document.getElementById("nText").innerHTML = ""; document.getElementById("nSound").innerHTML = ""; eqFlag = false; } else if(n === "=" && !eqFlag) { if(document.getElementById("nText").innerHTML !== ""){ document.getElementById("nSound").innerHTML = "อ่านว่า "+ number2sound(document.getElementById("nText").innerHTML); document.getElementById("nText").innerHTML = numberFormat(document.getElementById("nText").innerHTML); eqFlag = true; } } else if(!eqFlag) { document.getElementById("nText").innerHTML += n; } }
true
297c23f67573c2bdd4edb2a83189d6186e35e864
JavaScript
ValentinH/reactfinland2020
/pages/05-field-level-validation/SignupForm.js
UTF-8
2,346
2.546875
3
[]
no_license
import React from 'react' import { Form, Field } from 'react-final-form' import isEmail from 'sane-email-validation' import onSubmit from '../../common/onSubmit' /** * Objective: Convert from record-level to field-level validation * * Requirements: * - It should call `onSubmit` when the form is submitted. * - The form should not submit if the values are invalid * (React Final Form will handle this for you) * - Errors should be displayed next to the inputs in a `<span>` */ export default function SignupForm() { return ( <Form onSubmit={onSubmit}> {({ handleSubmit }) => ( <form onSubmit={handleSubmit}> <Field name="firstName" validate={(value) => { if (!value) { return 'Required' } }} > {({ input, meta }) => ( <div> <label htmlFor="firstName">First Name</label> <input {...input} id="firstName" type="text" placeholder="First Name" /> {meta.error && meta.touched && <span>{meta.error}</span>} </div> )} </Field> <Field name="lastName" validate={(value) => { if (!value) { return 'Required' } }} > {({ input, meta }) => ( <div> <label htmlFor="lastName">Last Name</label> <input {...input} id="lastName" type="text" placeholder="Last Name" /> {meta.error && meta.touched && <span>{meta.error}</span>} </div> )} </Field> <Field name="email" validate={(value) => { if (!value) { return 'Required' } else if (!isEmail(value)) { return 'Invalid email' } }} > {({ input, meta }) => ( <div> <label htmlFor="email">Email</label> <input {...input} id="email" type="email" placeholder="Email" /> {meta.error && meta.touched && <span>{meta.error}</span>} </div> )} </Field> <button type="submit">Submit</button> </form> )} </Form> ) }
true
26aca8868c656271664d6b0fd242cce1f3e8663c
JavaScript
SamHenningsen/IntroWebDevelopmentSubmission
/luckySevens/luckySevens.js
UTF-8
2,088
3.515625
4
[]
no_license
function clearErrors() { for (var loopCounter = 0; loopCounter < document.forms["betForm"].elements.length; loopCounter++){ if (document.forms["betForm"].elements[loopCounter].parentElement.parentElement.className.indexOf("has-") != -1){ document.forms["betForm"].elements[loopCounter].parentElement.parentElement.className = "form-group"; } } } function rollDice(){ return Math.floor(Math.random() * 6) + 1; } function playLuckySevens(){ var die1 = rollDice(); var die2 = rollDice(); return die1 + die2; } function bettingResults(startingBid){ var loopCounter = 0; var currentCash = startingBid; var mostWon = startingBid; var roundMostWon = 0; while (currentCash >= 1){ loopCounter++; if (playLuckySevens() == 7){ currentCash = currentCash + 4; } else { currentCash = currentCash - 1; } if (currentCash > mostWon){ mostWon = currentCash; roundMostWon = loopCounter; } } return [startingBid,loopCounter,mostWon,roundMostWon]; } function validateBet() { clearErrors(); var bet = document.forms["betForm"]["bet"].value; if (bet == "" || isNaN(bet) || bet <= 0) { alert("Bet must be filled in with a positive number."); document.forms["betForm"]["bet"].parentElement.parentElement.parentElement.parentElement.className = "form-group has-error"; document.forms["betForm"]["bet"].focus(); return false; } result = bettingResults(Number(bet)); document.getElementById("results").style.display = ""; document.getElementById("submitButton").innerText = "Play Again"; document.forms["betForm"]["bet"].value = 0; document.forms["betForm"]["bet"].focus(); document.getElementById("startingBet").innerText = result[0]; document.getElementById("addResult").innerText = result[1]; document.getElementById("subtractResult").innerText = result[2]; document.getElementById("multiplyResult").innerText = result[3]; return false; }
true
1593438f96b7a527724ba4c3b4fdd4f8f1fae48a
JavaScript
dylanowen/guac
/snake.js
UTF-8
2,036
3.125
3
[ "MIT" ]
permissive
var DIRECTION_MAPPING = { "right": {dx:1, dy:0, opp:"left"}, "left": {dx:-1, dy:0, opp:"right"}, "up": {dx:0, dy:-1, opp:"down"}, "down": {dx:0, dy:1, opp:"up"}, } var drawSnake = function(newSnake, applePixel) { var goblin = document.createElement("IMG"); goblin.src = "goblin.png"; var drawableSnake = { img: goblin, color: "green", pixels: newSnake }; var apple = {img: goblin, pixels: [applePixel]} var drawableObjects = [drawableSnake, apple]; var canvasDraw = function() { snakeCanvas.draw(drawableObjects); } if(goblin.complete) { canvasDraw() }else { goblin.onload = canvasDraw(); } } var moveSnake = function(currentSnake, direction) { var oldSegment = currentSnake[0]; var newX = (snakeCanvas.gameWidth() + oldSegment.left + direction.dx) % snakeCanvas.gameWidth(); var newY = (snakeCanvas.gameHeight() + oldSegment.top + direction.dy) % snakeCanvas.gameHeight(); var newSegment = { top: newY, left: newX }; if(snakeCanvas.detectCollisionBetween([newSegment], [appleLocation])){ eatApple(); } currentSnake.unshift(newSegment); if(delay > 0){ delay -= 1; } else{ currentSnake.pop(); } } var advanceGame = function() { moveSnake(snake, DIRECTION_MAPPING[snakeDirection]); drawSnake(snake, appleLocation); } var react = function(direction){ if(DIRECTION_MAPPING[snakeDirection].opp != direction){ snakeDirection = direction; } } var eatApple= function(){ delay = 2; appleLocation = snakeCanvas.randomLocation(); } document.addEventListener('keydown', function(e) { if (snakeCanvas.KEY_MAPPING[e.which]) { e.preventDefault(); react(snakeCanvas.KEY_MAPPING[e.which]); } }); var snake = [{ top: 0, left: 4},{ top: 0, left: 3},{ top: 0, left: 2}, { top: 0, left: 1}, { top: 0, left: 0}]; var snakeDirection = "right"; var appleLocation = snakeCanvas.randomLocation(); var delay = 0; snakeCanvas.executeNTimesPerSecond(advanceGame, 2);
true
be031d2a1849e9da6f01a3d00084455f7939275b
JavaScript
sudo-cho/droom
/app/assets/modules/useful.js
UTF-8
1,985
2.671875
3
[]
no_license
var useful = { isMobile() { if(window.innerWidth <= 768) return true; else return false; }, getOffset(el) { el = el.getBoundingClientRect(); return { left: el.left + window.scrollX, top: el.top + window.scrollY } }, pxToTime(time, px){ let realTime = time if(time===0) realTime = 3000; return realTime*px/window.innerHeight }, bpmToMs(bpm) { return bpm * 2000 / 120 }, bpmToS(bpm) { return this.bpmToMs(bpm) / 1000 }, checkColor(val) { if(val<0) return 0; else if(val>255) return 255; return val; }, checkTime(val) { if(val < 0) return 0; return val; }, toggleFullScreen() { if ((document.fullScreenElement && document.fullScreenElement !== null) || (!document.mozFullScreen && !document.webkitIsFullScreen)) { this.goFullScreen(); } else { this.exitFullScreen(); } }, goFullScreen() { if (document.documentElement.requestFullScreen) { document.documentElement.requestFullScreen(); } else if (document.documentElement.mozRequestFullScreen) { document.documentElement.mozRequestFullScreen(); } else if (document.documentElement.webkitRequestFullScreen) { document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } }, exitFullScreen() { if (document.cancelFullScreen) { document.cancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } }, randBetween(min,max) { return Math.floor(Math.random() * max) + min } } module.exports = useful;
true
7ad5b9ca0d48c4770b169208095ecdad604669c9
JavaScript
nhatban25912345/Dang-ky-hoc-phan-demo-1
/Đăng ký học phần/guinhat-main/project/JS-Object/ObjectList.js
UTF-8
1,708
2.96875
3
[]
no_license
const $template = document.getElementById("object-list-template"); export class ObjectList extends HTMLElement { id = ""; objects = []; constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.append($template.content.cloneNode(true)); this.objects = this.shadowRoot.getElementById("objects"); } static get observedAttributes() { return ['id']; } attributeChangedCallback(name, oldValue, newValue) { console.log("23456"); if(name == 'id') { this.id = newValue; console.log(this.id); } this.render(); } setObjects(objects) { this.objects = objects; console.log(this.objects); this.render(); } // update() { // let foundObject = this.objects.find(function (item) { // return item.id === object.id; // }); // if (foundObject != null) { // foundObject.content = object.content; // } // firebase.firestore().collection("ObjectList").doc(this.id).update({ // objects: this.objects, // }); // } render() { console(this.id); this.$objects.innerHTML = this.objects.map(function (object) { return ` <object-container number="${object.number}" object-id="${object.objectId}" object-name="${object.objectName}" teacher-name="${object.teacherName}" class="${object.class}" number-tc="${object.numberTc}" tuition="${object.tuition}"> </object-container>`; }).join(""); } } window.customElements.define("object-list", ObjectList);
true
6237f0bee1c3f3b11de58b69f49a2ef89eb5c8a2
JavaScript
samqty/jGeez
/unittests/jquery.jgeez.js
UTF-8
32,307
2.703125
3
[]
no_license
/* Author : Samuel Teklu Cherinet Version : 1.1.0.0 Date : April 25, 2012 Description : this is a jGeez plugin source code(development version). the library helps users type geez literals directly on their browsers. for further detail please refer to the official jGeez site at this address, http://www.jgeez.com */ //character class definition //an object model that represents a single geez character in a given textbox control function Character(EnglishString,ShiftKey,Index) { _englishString=EnglishString; _shiftKey=ShiftKey; _Index=Index return { //the english string(one or two characters) that has been translated to a single geez letter englishString: _englishString, //a flag the shows if a shiftkey was pressed during the capturing of the key stroke //this information is vital in determining if capslock was on shiftKey: _shiftKey, //index of this letter on the HTML Textbox //this information is used when printing amharic letters index: _Index }; } //a namespace used in classifying and defining functions and constants used in this plugin var JGeezUtility = { //determines if the asciicode falls in the range of characters set aside as modifier //modifier in this plugin scope is a character used to modify a root character to different //sounds of the same category //JGeezUtility.isModifier isModifier: function (ch) { for (mod in JGeezUtility.UNICODEModifierMatrix) if (ch == JGeezUtility.UNICODEModifierMatrix[mod][0]) return true; return false; }, //converts an english string and optionally a modifier //uses a matrix of predfined character combinitions to return the correct //geez letter for a given combination //JGeezUtility.UNICODE UNICODE: function (ch) { //locally identify the variables that will be used in the conversion _root = ch.englishString.substr(0, 1); _modifier = ch.englishString.substr(1, 1); _shift = ch.shiftKey; _caps = (_shift && (_root.charCodeAt(0) > 96)) || (!_shift && (_root.charCodeAt(0) <= 96)); //first get all the unicodes that correspond to this character //make sure all the unicodes are selected regardless of the letter case //or if shift was pressed or caps was on since this option tries to do //closest match to the criteria _matches = Array(); _rootlower = _root.toLowerCase(); for (i in JGeezUtility.UNICODEMatrix) { //provide a set value for measuring resemblence _resemblence = 100; //create a local copy of the mapping data to avoid indexing the array every time _currentunicode = JGeezUtility.UNICODEMatrix[i]; //check if the string matches regardless of the letter case if (_currentunicode[1].toLowerCase() == _rootlower) { //reduce the resemblence if the cases doesn't match if (_currentunicode[1] != _root) _resemblence -= 20; //reduce the resemblence if the mapping requires the shift key //this will be offsetted if the shift key matches if (_currentunicode[2]!=null) _resemblence -= 5; //increase the resemblence if the shift value matches the given character if (_currentunicode[2] == _shift) _resemblence += 7; //reduce the resemblence if the mapping requires the capslock turned on/off //this will be offsetted if the capslock state matches if (_currentunicode[3]!=null) _resemblence -= 5; //increase the resemblence if the capslock state matches the given character if (_currentunicode[3] == _caps) _resemblence += 7; //add the information about the matched unicode to the matches collection _matches.push({ index: i, resemblence: _resemblence, unicode: _currentunicode[0] }); } } //determine the unicode with highest resemblence to the key combination specified in the character var _maxmatch; for (_m in _matches) { if (!_maxmatch) _maxmatch = _matches[_m]; else { if (_matches[_m].resemblence > _maxmatch.resemblence) _maxmatch = _matches[_m]; } } //get the unicode value from a predefined set of english to unicode mapping matrix var _rootUnicode; if(_maxmatch) _rootUnicode = _maxmatch.unicode; //if a modifier is defined in the character definition //then modify the unicode by adding the modifying sound index (1-6) if (_rootUnicode && _modifier) { for (mod in JGeezUtility.UNICODEModifierMatrix) if (JGeezUtility.UNICODEModifierMatrix[mod][0] == _modifier) _rootUnicode = _rootUnicode + JGeezUtility.UNICODEModifierMatrix[mod][1]; } //if a valid unicode is retrieved from the matrix then return the character representation of the unicode if (_rootUnicode) return String.fromCharCode(_rootUnicode); return _root; }, //constants used to save data on the HTML textbox //holds data about the currently pressed character //JGeezUtility.cIdx cIdx: "c_Ch", //holds data about the letter that is currently being evaluated //for example an modified geez character //JGeezUtility.aIdx aIdx: "a_Ch", //a helper namespace //JGeezUtility.Print Print: { //checks if a given character is printable/can be converted to geez //JGeezUtility.Print.isPrintable isPrintable: function (ASCIICode) { return (ASCIICode >= 65 && ASCIICode <= 90) || (ASCIICode >= 97 && ASCIICode <= 122); }, //JGeezUtility.Print.newCharacter //inserts the character in the HTML text box at a given index newCharacter: function (character, textbox) { //todo: looks like the to parameter of substr is not inclusive, test!! //get the strings that are on the left and right side of the character //this code is required in to make sure the user can start typing in the middle of a text //right side of the character rightstr = textbox.attr("value").substr(0, character.index); leftstr = ""; //left side of the character if (character.index < textbox.attr("value").length) leftstr = textbox.attr("value").substr(character.index, textbox.attr("value").length - character.index); //combine the string and assign the final string to the textbox textbox.attr("value", rightstr + JGeezUtility.UNICODE(character) + leftstr); JGeezUtility.Caret.setPosition(textbox, character.index + 1); }, //JGeezUtility.Print.replaceCharacter //relaces the character in the HTML text box at a given index replaceCharacter: function (character, textbox) { //get the strings that are on the left and right side of the character //this code is required in to make sure the user can start typing in the middle of a text //right side of the character rightstr = textbox.attr("value").substr(character.index + 1); leftstr = ""; //left side of the character if (character.index < textbox.attr("value").length) leftstr = textbox.attr("value").substr(0, character.index); //combine the string and assign the final string to the textbox textbox.attr("value", leftstr + JGeezUtility.UNICODE(character) + rightstr); JGeezUtility.Caret.setPosition(textbox, character.index + 1); } }, //JGeezUtility.Caret //this namespace holds the methods that are used to set the position of the //caret (AKA cursor) in a given textbox Caret: { //gets the current position (index) of the caret in the text box getPosition: function (ctrl) { var CaretPos = 0; ctrl = ctrl[0]; // IE Support if (document.selection) { ctrl.focus(); var Sel = document.selection.createRange(); Sel.moveStart('character', -ctrl.value.length); CaretPos = Sel.text.length; } // Firefox support else if (ctrl.selectionStart || ctrl.selectionStart == '0') CaretPos = ctrl.selectionStart; return (CaretPos); }, //sets the current position (index) of the caret in the text box setPosition: function (ctrl, pos) { ctrl = ctrl[0]; if (ctrl.setSelectionRange) { ctrl.focus(); ctrl.setSelectionRange(pos, pos); } else if (ctrl.createTextRange) { var range = ctrl.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } } }, //holds information about the client's font status(if the user has geez font installed on his computer) //by default it is assumed that the user does not have geez font installed //this variable will be set by jgeez when the document is loaded hasGeezFont:false, //holds data about all the instance of the elements on which jgeez has been applied to //this info is separted out of the element is because, information is lost when AJAX calls disrupt the DOM structure instances:[], //this method will bind events that are queued up for each of the jgeez instance elemetns on the page //it is particulary used to combat the issue of AJAX disrupting the events binding on the DOM bindEvents:function(){ //go through all the event handlers and rebind them to the element jgeez plugin is applied on for(o in JGeezUtility.instances){ //check if the event has already been handled //so that multiple event handlers wouldn't be bound to the element target=$(":[jgeez-index="+o+"]"); if(!target.data("jgeez-event")){ options=JGeezUtility.instances[o]; for(e in options.eventHandlers){ options.eventHandlers[e].element.on(options.eventHandlers[e].event, options.eventHandlers[e].data, options.eventHandlers[e].handler); } target.data("jgeez-event",true) } } } }; //main plugin code ( function ($) { //plugin main function $.fn.jGeez = function(method){ //this code ensure multiple method call using one plugin namespace if ( methods[method] ) { return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.jGeez' ); } }; //methods that are available on text boxes var methods={ //changes the pre-existing options on the plugin //is used after the plugin is initialized changeoptions:function(options){ _options=JGeezUtility.instances[$(this).attr("jgeez-index")]; _options=$.extend(_options,options); $(this).data("jGeez",_options); }, //allows developers to reattach events that might be lost during an AJAX call reattachevents:function(){ //go through all the event handlers and rebind them to the element options=JGeezUtility.instances[$(this).attr("jgeez-index")]; //check if the event has already been handled //so that multiple event handlers wouldn't be bound to the element if(!$(this).data("jgeez-event")){ for(e in options.eventHandlers){ options.eventHandlers[e].element.on(options.eventHandlers[e].event, options.eventHandlers[e].data, options.eventHandlers[e].handler); } $(this).data("jgeez-event",true) } }, //initializes the textbox with all sorts of options //options definition //showtoggle:true/false //togglebutton //togleshortcut init:function (options) { //create default option values var options=$.extend({ 'showhelpbutton':true, 'showtogglebutton':true, 'enabled':true, 'geezbutton':'', 'englishbutton':'', 'helpbutton':'', 'toggleshortcut':'q' },options); //hold reference to the event handlers options.eventHandlers=[]; //add reference to the index of this textbox in the jgeez instance on the page $(this).attr("jgeez-index",JGeezUtility.instances.length); JGeezUtility.instances.push(options); //show help button if(options.showhelpbutton){ _help= $("#"+options.helpbutton); _help.attr("href", "http://jgeez.com/home/help"); _help.attr("target", "_blank"); } //is used to change the current mode of writing //and handles the UI change as well function toggle(txtbox){ //load settings _options=JGeezUtility.instances[txtbox.attr("jgeez-index")]; __gbtn = $("#"+_options.geezbutton); __ebtn = $("#"+_options.englishbutton); _options.enabled=!_options.enabled; if(__ebtn&&__gbtn){ if(_options.enabled){ __ebtn.show(); __gbtn.hide(); } else{ __ebtn.hide(); __gbtn.show(); } } } //show toggle button //get the toggle buttons if(options.geezbutton &&options.englishbutton) { _gbtn = $("#"+options.geezbutton); _ebtn = $("#"+options.englishbutton); //check both the toggle buttons have been specified at the plugin level if(_gbtn.length>0 &&_ebtn.length>0){ //on english button disable geez options.eventHandlers.push({ element:_ebtn, event:'click', data:{txtbox:$(this)}, handler:function(event){ toggle(event.data.txtbox); event.data.txtbox.focus(); } }); //on geez button enable geez typing options.eventHandlers.push({ element:_gbtn, event:'click', data:{txtbox:$(this)}, handler:function(event){ toggle(event.data.txtbox); event.data.txtbox.focus(); } }); //if the show toggle button options is not selected hide both buttons if(!options.showtogglebutton){ _ebtn.hide(); _gbtn.hide(); } else{ //ensure that only one button(either geez or english) is actively visible at anytime if(options.enabled){ _gbtn.hide(); _ebtn.show(); } else{ _gbtn.show(); _ebtn.hide(); } } } } //shortcut toggle options.eventHandlers.push({ element:$(this), event:'keyup', handler:function(event){ //load settings _options=JGeezUtility.instances[$(this).attr("jgeez-index")]; if(event.altKey ||event.ctrlKey ||!JGeezUtility.Print.isPrintable(event.which)){ //handle ctrl shortcut values(toggle) if(String.fromCharCode(event.which).toLowerCase()==_options.toggleshortcut.toLowerCase()) toggle($(this)); } } }); options.eventHandlers.push({ element:$(this), event:'keypress', handler:function (event) { //load settings _options=JGeezUtility.instances[$(this).attr("jgeez-index")]; //check if the character pressed is printable //ignore anything that will not be displayed (alt,ctrl ...) //ignore key presses for short cut keys (combination of alt+key or ctrl+key) if(event.altKey ||event.ctrlKey ||!JGeezUtility.Print.isPrintable(event.which)){ //clear out any root character waiting for a modifier $(this).data(JGeezUtility.aIdx,null); } else{ //if the plugin is disabled exit the event handler if(!_options.enabled) return; //instantiate new character object for the key that is pressed var _cCh=Character(String.fromCharCode(event.which), event.shiftKey,JGeezUtility.Caret.getPosition($(this))); //save this character object in the data cache $(this).data(JGeezUtility.cIdx, _cCh); //retrieve the active character object from the data cache //the active character holds information on root characters that //are possibly waiting for a modifier var _aCh=$(this).data(JGeezUtility.aIdx); //if there is no active character waiting for a modifier //or if the active character and the new key are not consecutive(which effictively means that they are not related) //then copy the current character to active character cache //print the key pressed to the screen if(!_aCh ||_aCh.index+1!=_cCh.index){ //copy current character to the active character _aCh=Character(_cCh.englishString ,_cCh.shiftKey ,_cCh.index); //save the active character to the data cache $(this).data(JGeezUtility.aIdx, _aCh); //print the new active character to the screen JGeezUtility.Print.newCharacter(_aCh,$(this)); } else{ //if there is an active character waiting to be modified proceed //check if the current character is a modifier if(JGeezUtility.isModifier(_cCh.englishString)){ //if modifier, then append the modifier character to the active character's english string _aCh.englishString+=_cCh.englishString; //and replace the unicode character that corresponds to the active character //by a new unicode evaluated from the modified (root+modifier) version of the active character JGeezUtility.Print.replaceCharacter(_aCh,$(this)); //clear out the active character data cache, since this character is no longer //eligible for modification $(this).data(JGeezUtility.aIdx,null); } else{ //if the current character is not a modifier //then copy the current character to the active character _aCh=Character(_cCh.englishString ,_cCh.shiftKey ,_cCh.index); $(this).data(JGeezUtility.aIdx, _aCh); //print the new active character to the string JGeezUtility.Print.newCharacter(_aCh,$(this)); } } //if a unicode value is some how displayed(new/replace print) then cancel the event from bubbling //so that the default character is not displayed event.preventDefault(); } } }); //attach the event handlers queued up for this handler for(e in options.eventHandlers){ options.eventHandlers[e].element.on(options.eventHandlers[e].event, options.eventHandlers[e].data, options.eventHandlers[e].handler); } } }; } )(jQuery); //unicode matrix for modifiers //this matrix describes which modifier will change the unicode character relative to the first letter in //geez alphabet //for example h alone represents the first alphabet and any value added like 1 would change it to "hu" ... //todo: add more description here JGeezUtility.UNICODEModifierMatrix = [ ['a', 3], ['e', 5], ['i', 2], ['o', 6], ['u', 1], ['y', 4], ['A', 3], ['E', 5], ['I', 2], ['O', 6], ['U', 1] ]; //unicode matrix for root characters //this matrix describes the relationship/mapping of (english alphabet+shift+caps) the a geez unicode character //shift and caps values are optional, meaning, if there is only one unicode related to an english alphabet //then there is no need to identify the shift and caps, the algorith will take the clothest matching set JGeezUtility.UNICODEMatrix= [ [0x1200, 'h'], [0x1208, 'l'], [0x1210, 'H',true], [0x1218, 'm'], [0x1220, 's',true,true], [0x1228, 'r'], [0x1230, 's'], [0x1238, 'S'], [0x1240, 'q'], [0x124A, 'Q'], [0x1260, 'b'], [0x1268, 'v'], [0x1270, 't'], [0x1278, 'c'], [0x1280, 'h',true,true], [0x1290, 'n'], [0x1298, 'N'], [0x12A0, 'x'], [0x12A8, 'k'], [0x12B8, 'h',true], [0x12C8, 'w'], [0x12D0, 'x'], [0x12D8, 'z'], [0x12E0, 'Z'], [0x12E8, 'Y'], [0x12F0, 'd'], [0x12F8, 'P'], [0x1300, 'j'], [0x1308, 'g'], [0x1320, 'T'], [0x1328, 'C'], [0x1338, 't', true, true], [0x1340, 'T',false,true], [0x1348, 'f'], [0x1350, 'P'], [0x12A0, 'a'], [0x12A1, 'u'], [0x12A2, 'i'], [0x12A4, 'e'], [0x12A6, 'o'], [0x12E8, 'y'] ]; //root level attribute definition var jGeezLibraryAttributes = { mode:{ auto:'auto', manual:'manual' } }; //elelment plugin level options function jGeezAttributes(){ return { enabled: {name:'jgeez-enabled',value:true}, englishbutton: {name:'jgeez-englishbutton',value:""}, geezbutton: {name:'jgeez-geezbutton',value:""}, showtogglebutton:{name:'jgeez-showtogglebutton',value:true}, helpbutton: {name:'jgeez-helpbutton',value:""}, showhelpbutton: {name:'jgeez-showhelpbutton',value:true}, toggleshortcut: {name:'jgeez-toggleshortcut',value:"q"}, font: {name:'jgeez-font',value:"jiret"} }; } $(document).ready(function () { //detect if geez font exists //render the sample characters _scriptheader=$("script[src*='jgeez']"); _mode =_scriptheader.attr("mode"); var _geezattributes = jGeezAttributes(); var _jg_random = Math.floor(Math.random() * 1000 + 1); $("body").append('<span id="s' + _jg_random + '" style="width:10px; font-size:30px;overflow:visible;">ሀ</span'); $("body").append('<span id="s' + (_jg_random + 1) + '" style="width:10px; font-size:30px;overflow:visible;">መ</span'); //check if the characters are rendered correctly by comparing their width //download geez font if the user doesn't have a font installed or opted out to use one of the fonts //shipped with jgeez _font=_scriptheader.attr(_geezattributes.font.name); if ($("#s" + _jg_random).width() == $("#s" + (_jg_random + 1)).width() || _font) { //if font not specified then assignt the default value if(!_font) _font=_geezattributes.font.value; //if not install geez $("<link>").appendTo($('head')) .attr({ type: 'text/css', rel: 'stylesheet' }) .attr('href', 'http://www.jgeez.com/cdn/styles/'+_font+'/style.css'); } //remove the sample characters $("#s" + _jg_random).remove(); $("#s" + (_jg_random + 1)).remove(); //add code to automatically relink events handlers upon ajax call completion $("body").ajaxComplete(function(){ JGeezUtility.bindEvents(); }); if (_mode == jGeezLibraryAttributes.mode.auto) { //button styles var _buttonstyle = { 'padding': '0px 6px', 'font-weight': 'bold', 'cursor': 'pointer', 'margin-left': '1px', 'text-decoration': 'none' }; //find input elements that have jgeezenable attribute turned on/off _geezinputs = $("[jgeez-enabled='true']"); if (_geezinputs.length == 0) //if no jgeez attributes are found then select all the input and textarea elements _geezinputs = $("input,textarea"); _geezinputs.each(function () { //collect all the attribute info here //enabled if ($(this).is("[" + _geezattributes.enabled.name + "]")) _geezattributes.enabled.value = $(this).attr(_geezattributes.enabled.name) == "true"; //englishbutton if ($(this).is("[" + _geezattributes.englishbutton.name + "]")) _geezattributes.englishbutton.value = $(this).attr(_geezattributes.englishbutton.name); //geezbutton if ($(this).is("[" + _geezattributes.geezbutton.name + "]")) _geezattributes.geezbutton.value = $(this).attr(_geezattributes.geezbutton.name); //showtogglebutton if ($(this).is("[" + _geezattributes.showtogglebutton.name + "]")) _geezattributes.showtogglebutton.value = $(this).attr(_geezattributes.showtogglebutton.name) == "true"; //helpbutton if ($(this).is("[" + _geezattributes.helpbutton.name + "]")) _geezattributes.helpbutton.value = $(this).attr(_geezattributes.helpbutton.name); //showhelpbutton if ($(this).is("[" + _geezattributes.showhelpbutton.name + "]")) _geezattributes.showhelpbutton.value = $(this).attr(_geezattributes.showhelpbutton.name) == "true"; //toggleshortcut if ($(this).is("[" + _geezattributes.toggleshortcut.name + "]")) _geezattributes.toggleshortcut.value = $(this).attr(_geezattributes.toggleshortcut.name); //if jgeez is disabled then don't apply geez typing on it //if the input is a non-text input skip to the next element if (!_geezattributes.enabled || ($(this).is("input") && $(this).attr("type") != undefined && $(this).attr("type") != "text")) return; //if help button is enabled prepare the helpbutton if (_geezattributes.showhelpbutton.value) { var _helpbutton; //check if the user has already identified a button to use for help if (_geezattributes.helpbutton.value) _helpbutton = $("#" + _geezattributes.helpbutton.value); //if the user has not specified create one with the default design if (!_helpbutton) { _helpbutton = $("<a></a>"); _helpbutton.attr("id", "geezhelp_" + (_jg_random++)); _helpbutton.css(_buttonstyle); _helpbutton.css({ 'background-image': 'url(../Content/themes/base/images/helpsmall.png)' }); _helpbutton.html("&nbsp"); _helpbutton.insertAfter($(this)); if ($(this).is("textarea")) _helpbutton.css({ 'vertical-align': 'top' }); } _geezattributes.helpbutton.value = _helpbutton.attr("id"); } if (_geezattributes.showtogglebutton.value) { var _englishbutton; //check if the user has alread identified a button to use for toggling to english typing mode if (_geezattributes.englishbutton.value) _englishbutton = $("#" + _geezattributes.englishbutton.value); //english button if (!_englishbutton) { _englishbutton = $("<a></a>"); _englishbutton.attr("id", "englishtoggle_" + (_jg_random++)); _englishbutton.css(_buttonstyle); _englishbutton.css({ 'background-image': 'url(http://jgeez.com/Samples/Images/united_kindom.png)' }); _englishbutton.html("&nbsp"); _englishbutton.insertAfter($(this)); if ($(this).is("textarea")) _englishbutton.css({ 'vertical-align': 'top' }); } var _amharicbutton; //check if the user has already identified a button to use for toggling to english typing mode if (_geezattributes.geezbutton.value) _amharicbutton = $("#" + _geezattributes.geezbutton.value); if (!_amharicbutton) { _amharicbutton = $("<a></a>"); _amharicbutton.attr("id", "geeztoggle_" + (_jg_random++)); _amharicbutton.css(_buttonstyle); _amharicbutton.css({ 'background-image': 'url(http://jgeez.com/Samples/Images/ethiopia_flag.png)' }); _amharicbutton.html("&nbsp"); _amharicbutton.insertAfter($(this)); if ($(this).is("textarea")) _amharicbutton.css({ 'vertical-align': 'top' }); } //update the toggle button ids _geezattributes.englishbutton.value = _englishbutton.attr("id"); _geezattributes.geezbutton.value = _amharicbutton.attr("id"); } $(this).jGeez({ 'englishbutton': _geezattributes.englishbutton.value, 'geezbutton': _geezattributes.geezbutton.value, 'showtogglebutton': _geezattributes.showtogglebutton.value, 'helpbutton': _geezattributes.helpbutton.value, 'showhelpbutton': _geezattributes.showhelpbutton.value, 'toggleshortcut': _geezattributes.toggleshortcut.value }); }); } });
true
d442435a88d7454a3544cbec1159608b3369c763
JavaScript
debfdias/Code-Wars
/breaking_chocolate_problem.js
UTF-8
164
3.109375
3
[]
no_license
var breakChocolate = function(n, m) { var area = n * m; var totalBreaks = area - 1; if (totalBreaks <= 0){ return 0; } else { return totalBreaks; }; };
true
2e829cd58e9d64e20d8492b9ad19222888b526a3
JavaScript
carlos8v/trybe-exercises
/exercises/testes-automatizados-com-jest_3/exercise3.test.js
UTF-8
866
3.125
3
[]
no_license
const service = require('./exerciseFunctions'); describe('randomNumber', () => { it('should return a multiplication between three numbers', () => { service.randomNumber = jest.fn().mockImplementation((a, b, c) => a * b * c); expect(service.randomNumber(5, 5, 5)).toBe(125); expect(service.randomNumber).toHaveBeenCalled(); expect(service.randomNumber).toHaveBeenCalledTimes(1); expect(service.randomNumber).toHaveBeenCalledWith(5, 5, 5); }); it('should return a number argument times two', () => { service.randomNumber.mockReset(); service.randomNumber = jest.fn().mockImplementation((n) => n * 2); expect(service.randomNumber(7)).toBe(14); expect(service.randomNumber).toHaveBeenCalled(); expect(service.randomNumber).toHaveBeenCalledTimes(1); expect(service.randomNumber).toHaveBeenCalledWith(7); }); });
true
5fec938ae7b360987584c525d115dfa6cb6e9580
JavaScript
Tcbyco/WatchAndCode
/Practical JavaScript/09_Version_09_EscapeFromConsole.js
UTF-8
3,604
3.828125
4
[]
no_license
// V9: Escape from console // Ul, Li, dynamically adding li and text to the webpage var todoList = { // todos array todos: [], // addTodos method addTodo: function (todoText) { this.todos.push({ todoText: todoText, completed: false }); }, // changeTodo changes the text property of the object changeTodo: function (index, updatedText) { this.todos[index].todoText = updatedText; }, // deleteTodos method deleteTodo: function (index) { this.todos.splice(index, 1); }, // toggleCompleted toggles the the todo object's "completed" property toggleCompleted: function (index) { var todoObj = this.todos[index]; todoObj.completed = !todoObj.completed; }, toggleAll: function() { var allTasksCompleted; var numCompleted = 0; for (var i = 0; i < this.todos.length; i++) { if (this.todos[i].completed) { numCompleted++; } } // checking if all completed if (numCompleted === this.todos.length) allTasksCompleted = true; else allTasksCompleted = false; // if all completed, set all to uncompleted // else set all to completed if (allTasksCompleted) { for (var i = 0; i < this.todos.length; i++) { this.todos[i].completed = false; } } else { for (var i = 0; i < this.todos.length; i++) { this.todos[i].completed = true; } } view.displayTodos(); } }; var handlers = { addTodo: function() { var addTodoTextInput = document.getElementById("addTodoTextInput"); todoList.addTodo(addTodoTextInput.value); addTodoTextInput.value = ""; view.displayTodos(); }, changeTodo: function() { var indexObj = document.getElementById("changeTodoIndexInput"); var textObj = document.getElementById("changeTodoTextInput"); todoList.changeTodo(indexObj.valueAsNumber, textObj.value); indexObj.value = ""; textObj.value = ""; view.displayTodos(); }, deleteTodo: function() { var indexObj = document.getElementById("deleteTodoIndexInput"); todoList.deleteTodo(indexObj.valueAsNumber); indexObj.value = ""; view.displayTodos(); }, toggleCompleted: function() { var indexObj = document.getElementById("toggleCompletedIndexInput"); todoList.toggleCompleted(indexObj.valueAsNumber); indexObj.value = ""; view.displayTodos(); }, toggleAll: function() { todoList.toggleAll(); view.displayTodos(); } }; // when introducing a new feature, make it work without modifying old code // think of the functionality that this method in the new version is supposed to introduce / replace // replaces todoList.displayTodos(); // when it is activated it should display all the todos in the array. // it is activated when youu click the button which calls the methods on the handler object. var view = { displayTodos: function() { var todosUlElement = document.querySelector("ul"); todosUlElement.innerHTML = ""; for (var i = 0; i < todoList.todos.length; i++) { var newLiElement = document.createElement("li"); var todoTextWithCompletetion = ""; var currentTodo = todoList.todos[i]; if (currentTodo.completed) { todoTextWithCompletetion = "(x) " + currentTodo.todoText; } else { todoTextWithCompletetion = "( ) " + currentTodo.todoText; } newLiElement.id = i; newLiElement.textContent = todoTextWithCompletetion; newLiElement.appendChild(this.createDeleteButton()); todosUlElement.appendChild(newLiElement); } }, };
true
ccf58552ac322bf3d9b1bf3e411c2a90067682bb
JavaScript
jesusx21/mongo-migrator
/lib/utils.js
UTF-8
1,130
2.796875
3
[]
no_license
'use strict'; const fs = require('fs'); const pad = function(str, max) { str = str.toString(); return str.length < max ? pad('0' + str, max) : str; }; const getDateArgs = function(date) { return [ pad(date.getFullYear(), 4), pad(date.getMonth() + 1, 2), pad(date.getDate(), 2), pad(date.getHours(), 2), pad(date.getMinutes(), 2), pad(date.getSeconds(), 2), pad(date.getMilliseconds(), 3) ]; }; const getUniqueId = function() { const dateArgs = getDateArgs(new Date()); const id = dateArgs.join(''); return id; } const createMigrationFile = function (name, fileName, callback) { let BODY = `'use strict'; const id = '${name}'; const upgrade = function(done) { // use this.db for MongoDB communication, and this.log() for logging done(); }; const downgrade = function(done) { // use this.db for MongoDB communication, and this.log() for logging done(); }; module.exports = { id: id, upgrade: upgrade, downgrade: downgrade }; `; fs.writeFile(fileName, BODY, callback); } module.exports = { getUniqueId: getUniqueId, createMigrationFile: createMigrationFile }
true
92049b08d6e1034941ef2ddb8c6cd1d806f9be0b
JavaScript
Arvy1998/Laboratory-Work-With-Javascript
/2LAB_Arvydas_Baranauskas_PRIF_17_2/index.js
UTF-8
2,657
2.6875
3
[]
no_license
import TodoList from './models/todoList'; import { savePersonData, saveCompanyData, saveTaskData, saveProjectData, saveUsersData, readUsersData, readTaskData, readProjectData, readPersonData, readCompanyData } from './fileStream'; import runMenu from './console-interface'; let personArray, companyArray, taskArray, projectArray, userArray; const todoList = new TodoList(); /* PRIES PALEIDIMA NUSKAITOME DUOMENIS IS FAILU */ const readAllDataBeforeEnter = function() { try { personArray = readPersonData(); companyArray = readCompanyData(); taskArray = readTaskData(); projectArray = readProjectData(); userArray = readUsersData(); } catch(error) { console.error('Error while reading file: ' + error); } } const omitListsForUsage = function () { return { personArray, companyArray, taskArray, projectArray, userArray }; } export default omitListsForUsage; /* GAUTUS DUOMENIS IS FAILU JUOS PARUOSIAME NAUDOJIMUI PROGRAMOS VIDUJE */ readAllDataBeforeEnter(); todoList.initData(); /* PALEIDZIAME MENIU */ /* jeigu kursite naujus userius, nepamirskite, jog programa neleis sukurti to pacio userio su pasikartojanciu username, to reikia, kad uztikrinti, jog loginas tikrins tik unique fieldus */ /* demo duomenys */ // todoList.registerCompany(1, '1', 1, 1, 1, 1); // todoList.registerCompany(55, '1', 1, 1, 1, 1); // todoList.registerCompany('Company1', '456875', 1, 1, 1, 1); // todoList.registerPerson(2, '1', 1, 1, 1); // todoList.registerPerson(5888, '1', 1, 1, 1); // todoList.createTask('title', {username: 44, password: '123456'}); // todoList.createTask('title2', {username: 1, password: '0012122'}); // todoList.createTask('title3', {username: 1, password: '1212445'}); // todoList.createProject('PPtitle', {username: 44, password: '45484tt45'}); // todoList.createProject('PPtitle2', {username: 55, password: 'admin123'}); // todoList.createProject('PPtitle3', {username: 1, password: 'nginx'}); // todoList.registerPerson(1, '1', 1, 1, 1); // todoList.registerPerson(1, '1', 1, 1, 1); runMenu(todoList); /* PRIES ISJUNGIMA DUOMENIS ISSAUGOME FAILUOSE */ const saveAllDataBeforeExit = async function() { try { await Promise.all([ savePersonData(todoList.getPersonList()), saveCompanyData(todoList.getCompanyList()), saveTaskData(todoList.getTaskList()), saveProjectData(todoList.getProjectList()), saveUsersData(todoList.getUserList()) ]); } catch(error) { console.error(error); } } saveAllDataBeforeExit();
true
93fe4bb724c40efc53ac663f28f452d37d28097a
JavaScript
lucie-gonzalez/luciegonzalez_7_19052021
/back-end/controllers/users.js
UTF-8
4,222
2.546875
3
[]
no_license
const mysql = require('mysql') const db = require('../mysql') const bcrypt = require('bcrypt') const jwt = require('jsonwebtoken') const pwdValidator = require('password-validator') const fn = require('../middleware/function') require('dotenv').config(); // Exigence du mot de passe let pwd = new pwdValidator(); pwd .is().min(8) // minimum 8 caractères .is().max(25) // maximum 25 caractères .has().uppercase() // une majuscule .has().lowercase() // une minuscule .has().not().spaces() // pas d'espaces .has().digits() // un chiffre let nameValid = new pwdValidator(); nameValid .is().min(3) .is().max(20) .has().not().digits() exports.signup = async (req, res) => { //RECUPERATION DES VALEURS ENVOYER PAR L'UTILISATEUR const { email, password, firstname, lastname } = req.body const userSQL = mysql.format(`SELECT email FROM users WHERE email = ?`, [email]) try { if (!email || !password || !firstname || !lastname) throw "Vous avez oublié des champs !" if (!pwd.validate(password)) throw 'Votre mot de passe est trop simple !' if (!nameValid.validate(lastname)) throw 'Votre nom doit comprendre entre 3 et 20 caractères !' if (!nameValid.validate(firstname)) throw 'Votre prénom doit comprendre entre 3 et 20 caractères !' const userExist = await db.query(userSQL) if (userExist[0].length > 0) throw 'user exist' bcrypt.hash(password, 10) .then(hash => { const sql = mysql.format(`INSERT INTO users (email, password, lastname, firstname) VALUES (?, ?, ?, ?)`, [email, hash, lastname, firstname]); db.query(sql) return res.status(201).json({ message: 'ok'}) }) .catch(err => res.status(500).json(err)) } catch (err) { res.status(500).json(err) } } exports.login = async (req, res) => { const { email, password, remember } = req.body const sql = mysql.format(`SELECT id, password, lastname, firstname, img_profil, description, role FROM users WHERE email = ?`, [email]) try { if (!email || !password) throw 'Vous devez remplir les deux champs.' const user = await db.query(sql); if (user[0].length === 0) throw 'user not valid' const info = { userid: user[0][0].id, lastname: user[0][0].lastname, firstname: user[0][0].firstname, img_profil: user[0][0].img_profil ? 'http://localhost:3000/images/profile/' + user[0][0].img_profil : 'http://localhost:3000/images/profile/noprofile.png', description: user[0][0].description, role: user[0][0].role } bcrypt.compare(password, user[0][0].password) .then(valid => { if (!valid) throw 'invalid password' res.status(200).json({ userinfo: info, token: jwt.sign( {userId: user[0][0].id, role: user[0][0].role}, process.env.SECRET, {expiresIn: (remember === true ? '24h' : 600)} ) }) }) .catch(err => res.status(500).json(err)) } catch (err) { res.status(500).json(err) } } exports.isLogged = async (req, res, next) => { const { userId } = req.token const sql = mysql.format(`SELECT id, lastname, firstname, img_profil, description, role FROM users WHERE id = ?`, [userId]) try { const user = await db.query(sql) if (user[0].length === 0) throw 'user not valid' const info = { userid: user[0][0].id, lastname: user[0][0].lastname, firstname: user[0][0].firstname, img_profil: user[0][0].img_profil ? 'http://localhost:3000/images/profile/' + user[0][0].img_profil : 'http://localhost:3000/images/profile/noprofile.png', description: user[0][0].description, role: user[0][0].role } return res.status(200).json(info) } catch (err) { res.status(500).json(err) } } exports.ctrlToken = (req, res) => { res.status(200).json({message: 'ok'}) }
true
8d49f4d6df2a5745894b4d0e1956464e87e60248
JavaScript
asonni/sigorta
/server/modules/api/plans/controller.js
UTF-8
1,988
2.6875
3
[]
no_license
const express = require("express") const _ = require('lodash') const moment = require('moment') const Service = require('./service') class PlansAPIController { plansIndex(req, res) { const service = new Service(req) service.fetchPlans() .then(plans => { res.json({ plans: plans }) }) .catch(e => { console.log("\nError on at plansIndex - GET /plans", e) res.status(400).json({ error: e }) }) } plansShow(req, res) { const service = new Service(req) const { id } = req.params service.fetchPlanById(id) .then(plan => { res.json({ plan: plan }) }) .catch(e => { console.log(`\nError at GET /plans/${id}`, e) res.status(400).json({ error: e }) }) } plansCreate(req, res) { const service = new Service(req) const { name, price } = req.body if (!name) { return res.status(400).json({ error: `You must provide a plan name.` }) } if (!price) { return res.status(400).json({ error: `You must provide a plan price.` }) } service.createPlan({ name, price }) .then(plan => { return res.status(201).send({ plan }) }) .catch(e => { return res.status(401).json({ error: `Error persisting plan: ${e}` }) }) } plansUpdate(req, res) { const service = new Service(req) const { id } = req.params let updatePlan = service.findByIdAndUpdate(id, req.body) updatePlan.then(plan => res.status(200).json({ plan })) .catch(e => { console.log(`Error at PUT /plans/${id}`, e) return res.status(400).json({ error: e }) }) } plansDelete(req, res) { const service = new Service(req) const { id } = req.params let deletePlan = service.deletePlanById(id) deletePlan.then(() => res.status(200).json({ id })) .catch(e => { console.log(`Error at Delete /plans/${id}`, e) return res.status(400).json({ error: e }) }) } } module.exports = new PlansAPIController
true
16e23cbc31c6cdc5f6056b800078c2d1828d8410
JavaScript
LuckyGStar/LifeJavascriptComponents
/components/matrix-challenge/matrix-challenge.js
UTF-8
274
2.859375
3
[]
no_license
const analyse = (matrix) => { const rowCount = matrix.length; const colCount = matrix[0].length; for (let i = 0; i < rowCount; i++) { for (let j = 0; j < colCount; j++) { const value = matrix[i][j]; } } return matrix; }; exports.analyse = analyse;
true
5f9df6c984539679e160120e17193f84d40df1f6
JavaScript
nikhilxb/xnode-db
/server/client/examples/actions/example.js
UTF-8
1,608
3.03125
3
[]
no_license
/** Action type definitions. */ export const ExampleActions = { // Must take form of `[module]Actions` SYNC_ACTION: "EXAMPLE::SYNC_ACTION", ASYNC_ACTION: "EXAMPLE::ASYNC_ACTION", }; // TODO: Feature grouping // ---------------------- /** Action creator to __. */ export function syncAction(value) { // Must take form of `[name]Action` return { type: ExampleActions.SYNC_ACTION, value // ES6 shorthand for `value: value` }; }; /** Action creator to __. */ export function asyncAction(value) { return { type: ExampleActions.ASYNC_ACTION, promise: null, // e.g. `fetch(value)` or some other async action that returns Promise (see redux-pack docs) meta: { onSuccess: (result, getState) => { // for chaining Promises: can make another call here } } }; }; function anotherActionThunk(value) { return (dispatch) => { return Promise.resolve().then(dispatch(syncAction(value))); } } /** Action creator to ___ then ___ if ___. */ export function asyncActionThunk(value) { // Must take form of `[name]Thunk` return (dispatch, getState) => { let nodispatchCondition = getState().nodispatchCondition; if (nodispatchCondition) { return Promise.resolve(); } else { return dispatch(anotherActionThunk(value)).then( () => { dispatch(syncAction(value)); dispatch(syncAction(value)); } ).catch((error) => console.log(error)); } } }
true
0b31c95ae81605ef6e5e04de6e7bcbf10b63d7be
JavaScript
zhongyw/itranswarp.js
/www/cache.js
UTF-8
4,034
2.609375
3
[ "Apache-2.0" ]
permissive
'use strict'; // init memcache: var _ = require('lodash'), thunkify = require('thunkify'), Memcached = require('memcached'), config = require('./config'); // init memcached: console.log('init memcache...'); var DEFAULT_LIFETIME = 86400, // 24h CACHE_PREFIX = config.cache.prefix, memcached = new Memcached(config.cache.host + ':' + config.cache.port, { 'timeout': config.cache.timeout, 'retries': config.cache.retries }), $m_incr = thunkify(function (key, inc, callback) { memcached.incr(key, inc, callback); }), $m_get = thunkify(function (key, callback) { memcached.get(key, callback); }), $m_set = thunkify(function (key, value, lifetime, callback) { memcached.set(key, value, lifetime, callback); }), $m_del = thunkify(function (key, callback) { memcached.del(key, callback); }), $m_getMulti = thunkify(function (keys, callback) { memcached.getMulti(keys, callback); }); module.exports = { $incr: function* (key, initial) { var k = CACHE_PREFIX + key, data = yield $m_incr(k, 1); if (data === false) { if (initial === undefined) { initial = 0; } yield $m_set(k, initial + 1, DEFAULT_LIFETIME); data = initial + 1; } return data; }, $count: function* (key) { var k = CACHE_PREFIX + key, num = yield $m_get(k); return (num === false) ? 0 : num; }, $counts: function* (keys) { if (keys.length === 0) { return []; } var multiKeys = _.map(keys, function (key) { return CACHE_PREFIX + key; }), data = yield $m_getMulti(multiKeys); return _.map(multiKeys, function (key) { return data[key] || 0; }); }, $get: function* (key, defaultValueOrFn, lifetime) { /** * get value from cache by key. If key not exist: * return default value if defaultValueOrFn is not a function, * otherwise call defaultValueOfFn, put the result into cache * and return as value. */ var k = CACHE_PREFIX + key, data = yield $m_get(k); if (data) { // console.log('[cache] hit: ' + key); return data; } console.log('[Cache] NOT hit: ' + key); if (defaultValueOrFn) { lifetime = lifetime || DEFAULT_LIFETIME; if (typeof (defaultValueOrFn) === 'function') { if (defaultValueOrFn.constructor.name === 'GeneratorFunction') { console.log('yield generator to fill cache...'); data = yield defaultValueOrFn(); console.log('yield generator ok.') } else { console.log('call function to fill cache...'); data = defaultValueOrFn(); console.log('call function ok.'); } } else { data = defaultValueOrFn; } yield $m_set(k, data, lifetime); console.log('[cache] cache set for key: ' + key); } else { data = null; } return data; }, $gets: function* (keys) { if (keys.length === 0) { return []; } var multiKeys = _.map(keys, function (key) { return CACHE_PREFIX + key; }), data = yield $m_getMulti(multiKeys); return _.map(multiKeys, function (key) { return data[key] || null; }); }, $set: function* (key, value, lifetime) { var k = CACHE_PREFIX + key; yield $m_set(k, value, lifetime || DEFAULT_LIFETIME); }, $remove: function* (key) { var k = CACHE_PREFIX + key; yield $m_del(k); } };
true
698555ef09bfdbb343e8d46d42c04f6f77049b0a
JavaScript
BPopek/assignments
/exercises/node-calculator/app.js
UTF-8
1,182
4.09375
4
[]
no_license
const readlineSync = require("readline-sync") function add(num1, num2) { result = parseInt(num1) + parseInt(num2) return result } function sub(num1, num2) { result = parseInt(num1) - parseInt(num2) return result } function mul(num1, num2) { result = parseInt(num1) * parseInt(num2) return result } function div(num1, num2) { result = parseInt(num1) / parseInt(num2) return result } let firstNum = readlineSync.question("Please enter your first number: ",{ hideEchoBack: false }); let secondNum = readlineSync.question("Please enter your second number: ",{ hideEchoBack: false }); let operation = readlineSync.question("Please enter the operation to perform: add, sub, mul, div. ",{ hideEchoBack: false }); if(operation === "add") { console.log("The result is: ", add(firstNum, secondNum)); } else if (operation === "sub") { console.log("The result is: ", sub(firstNum, secondNum)); } else if (operation === "mul") { console.log("The result is: ", mul(firstNum, secondNum)); } else if (operation === "div") { console.log("The result is: ", div(firstNum, secondNum)); } else { console.log("Unexpected entry") }
true
d52b48b14890331f9c1fa0198ac22411670f91d1
JavaScript
catberry/catberry-oauth2-client
/lib/endpoints/AuthorizationCodeFlowEndpoint.js
UTF-8
4,510
2.53125
3
[ "MIT" ]
permissive
'use strict'; const URI = require('catberry-uri').URI; const httpHelper = require('../helpers/httpHelper'); const AuthorizationCodeSender = require('../grants/AuthorizationCodeSender'); const GrantFlowMiddlewareBase = require('../middlewares/GrantFlowMiddlewareBase'); const FIELD_CODE = 'code'; class AuthorizationCodeFlowEndpoint extends GrantFlowMiddlewareBase { /** * Creates new instance of authorization code flow endpoint. * @param {ServiceLocator} locator Service locator to resolve * dependencies. * @param {Object} authConfig Authorization configuration. * @param {string} authConfig.clientId Id of OAuth 2.0 client. * @param {string} authConfig.clientSecret Secret of OAuth 2.0 client. * @param {string} authConfig.authServerUrl URL to OAuth 2.0 * authentication server. * @param {number?} authConfig.timeout Grant send timeout (30000 ms by default). * @param {boolean?} authConfig.unsafeHTTPS Determines if sender will send grant * via unsafe HTTPS connection with invalid certificate (false by default). * @param {string?} authConfig.tokenEndpointPath URL path to * OAuth 2.0 token endpoint (/token by default). * @param {Object} endpointConfig Endpoint configuration. * @param {string?} endpointConfig.scope Access scope for endpoint. * @param {string} endpointConfig.redirectUri Redirect URI used for * obtaining code. * @param {string} endpointConfig.returnUri Return URI used to redirect * user agent after authorization. * @param {Object} endpointConfig.cookie Token cookie configuration. * @param {string} endpointConfig.cookie.accessTokenName Name of cookie * with access token. * @param {string?} endpointConfig.cookie.accessTokenExpiresIn Expiration time * in seconds for access token cookie if it is not specified by authorization * server (3 600 secs by default, 1 hour). * @param {string} endpointConfig.cookie.refreshTokenName Name of cookie * with refresh token. * @param {string?} endpointConfig.cookie.refreshTokenExpiresIn Expiration time * in seconds for refresh token cookie * (3 110 400 000 secs by default, 100 years). * @param {string?} endpointConfig.cookie.path Path attribute for cookie * ('/' by default). * @param {string?} endpointConfig.cookie.domain Domain attribute for cookie. */ constructor(locator, authConfig, endpointConfig) { super(locator, endpointConfig); /** * Current authorization code sender. * @type {AuthorizationCodeSender} * @private */ this._sender = new AuthorizationCodeSender(locator, authConfig); if (typeof (endpointConfig.redirectUri) !== 'string' || endpointConfig.redirectUri.length === 0) { throw new Error('"redirectUri" not found in config'); } /** * Current redirect URI used for obtaining authorization. * @type {string} * @private */ this._redirectUri = endpointConfig.redirectUri; if (typeof (endpointConfig.returnUri) !== 'string' || endpointConfig.returnUri.length === 0) { throw new Error('"returnUri" not found in config'); } /** * Current return URI used to redirect user agent after authorization. * @type {URI} * @private */ this._returnUri = new URI(endpointConfig.returnUri); } /** * Handles endpoint invocation. * @param {http.IncomingMessage} request HTTP request. * @param {http.ServerResponse} response HTTP response. */ handler(request, response) { this._eventBus.emit('trace', 'Obtaining access token for authorization code...'); this._obtainAuthorization(request) .then(issuedAuth => this._handleIssuedAuthorization(request, response, issuedAuth)) .then(() => httpHelper.redirectResponse(response, this._returnUri)) .catch(reason => { this._eventBus.emit('error', reason); httpHelper.writeError(reason, response); }); } /** * Obtains authorization from authorization server. * @param {http.IncomingMessage} request Incoming HTTP request. * @returns {Promise<Object>} Promise for issued authorization. * @private */ _obtainAuthorization(request) { const methodError = httpHelper.checkMethod(request, 'get'); if (methodError) { return Promise.reject(methodError); } const uri = new URI(request.url); if (!uri.query || typeof (uri.query.values.code) !== 'string') { const error = new Error('"code" is required parameter'); error.code = 400; return Promise.reject(error); } return this._sender.send(uri.query.values[FIELD_CODE], this._redirectUri); } } module.exports = AuthorizationCodeFlowEndpoint;
true
434286c3c2bb39a0cbd7c8c3d5547a4afecc4582
JavaScript
jfdesrochers/jfdcomponents
/src/statemanager.js
UTF-8
2,510
3.796875
4
[]
no_license
/////////////////////////// // StateManager // Holds various enumerable properties with getter/setters and custom callback support /** * Creates a State Manager * @constructor * @param {object} initState Object containing the initial properties to add of the format : {prop: 'defaultvalue'} or {prop: ['defaultvalue', function callback() {...}]}. Callback is called when setting a value. */ const StateManager = class { constructor (initState) { Object.defineProperty(this, '__props', { enumerable: false, configurable: true, value: {} }) for (let o in initState) { if (Array.isArray(initState[o]) && initState[o].length === 2 && typeof initState[o][1] === 'function') { this.addProp(o, initState[o][0], initState[o][1]) } else { this.addProp(o, initState[o]) } } } /** * Invokes the property setter in a functional fashion (ex.: myState.set('myprop')('newvalue')) * @param {string} propname Name of the property to set. * @returns {function} Setter for the new value */ set (propname) { return function (newValue) { if (typeof this.__props[propname].callback === 'function') { if (this.__props[propname].callback(this.__props[propname].value, newValue) === false) return } this.__props[propname].value = newValue }.bind(this) } /** * Adds a new property to the State Manager * @param {string} propname Name of the new property * @param {*} defaultValue Default value of the new property * @param {function} callback Optional callback when a new value is set. Callback receives (oldValue, newValue). Return false to cancel the value change. */ addProp (propname, defaultValue, callback) { this.__props[propname] = { 'value': defaultValue, 'callback': callback } Object.defineProperty(this, propname, { get: function () { return this.__props[propname].value }, set: this.set(propname), enumerable: true, configurable: true }) } /** * Removes a property from the State Manager * @param {string} propname Name of the property to remove */ delProp (propname) { delete this.__props[propname] delete this[propname] } } module.exports = StateManager
true
d5b5a07c691edd318834340c2bc1d3b5b6e79f0f
JavaScript
Josefine-Schougaard/MUL-Festform
/Festform-prototype/validation.js
UTF-8
2,983
2.984375
3
[]
no_license
// formcheck // Tjekker om inputs er udfyldt med appropiate data type, skriver en validation besked, tilføjer invalid klassen const checkInputs = (form)=>{ let inputsValid = true; const subGroups = form.querySelectorAll('.sub-group, .requiredCheck'); subGroups.forEach(subGroup =>{ const input = subGroup.querySelector('input'); const valMessage = subGroup.querySelector('.validation-message'); if(input.checkValidity()){ valMessage.classList.remove("invalid"); input.classList.remove("invalid"); valMessage.innerHTML = ''; } else{ valMessage.classList.add("invalid"); input.classList.add("invalid"); valMessage.innerHTML = input.validationMessage; inputsValid = false; } }); if(checkShiftTable() == false){ inputsValid = false; } return inputsValid; }; // Sikre at der er valgt vagtønsker fra skemaet, eller at noshifts checkboxen er afkrydset const checkShiftTable = ()=>{ let inputsValid = true; const selectedShifts = []; document.querySelectorAll('.shift-table td.isSelected').forEach(cell =>{ const shiftTime = cell.innerHTML; const shiftDay = cell.dataset.day; const selectedShift = {shiftDay: shiftDay, shiftTime: shiftTime}; selectedShifts.push(selectedShift); }); const selectedShiftsJson = JSON.stringify(selectedShifts); const hiddenInput = document.querySelector('.selectedShifts'); hiddenInput.value = selectedShiftsJson; const noShifts = document.querySelector('.noShifts'); const noShiftsCheckbox = noShifts.querySelector('input'); const customValidationMSG = noShifts.querySelector('.validation-message'); if(selectedShifts.length === 0){ if(noShiftsCheckbox.checked == false){ customValidationMSG.innerHTML = "Bekræft venligst at du ikke har nogle vagtønsker."; customValidationMSG.classList.add("invalid"); inputsValid = false; }else{ customValidationMSG.innerHTML = ''; customValidationMSG.classList.remove("invalid"); } }else{ if(noShiftsCheckbox.checked == true){ customValidationMSG.innerHTML = "Afkryds ikke her hvis du har vagtønsker"; customValidationMSG.classList.add("invalid"); inputsValid = false; }else{ customValidationMSG.innerHTML = ''; customValidationMSG.classList.remove("invalid"); } } return inputsValid; }; // Forhindre formularen i at blive sendt og siden i at reloade document.querySelectorAll('.formgroup').forEach(form =>{ form.addEventListener('submit', (event) =>{ const checkInputsResult = checkInputs(form); if(!checkInputsResult){ event.preventDefault(); } }); });
true
7006bdc60d4db64deb86ba20283d22dd35d18fba
JavaScript
fschell/cryptool-online
/_ctoLegacy/js/transposition.js
UTF-8
11,092
2.78125
3
[]
no_license
//*******************************(service-layer) //******************************* //******************************* function CTOTranspositionAlgorithm(alpha) { var alphabet=alpha; //transposition (decrypt) //@author Christian Sieche //@version 30.12.2008 //@params: // chipertext (string), keysquare (string), key (string) this.decodePartA=decodePartA; function decodePartA(ciphertext, key) { var keybackup=key; klen = key.length; var cols; cols = new Array(klen); var newcols = new Array(klen); var transposition=""; chars=alphabet; j=0; i=0; //get transposition sequence while(j<klen) { t=key.indexOf(chars.charAt(i)); if(t >= 0) { newcols[t] = cols[j++]; arrkw = key.split(""); arrkw[t] = "_"; key = arrkw.join(""); if (transposition != "") { transposition = transposition + "-" + t; } else { transposition = "" + t; } } else i++; } var chars = ciphertext.length; //how many extra cols are needed because text is not dividable by key var extracols = chars % klen; //write transposition sequence to array var transparray = transposition.split("-"); //get the array position of the needed extra cols var indizesarray = new Array(extracols); var o; for (o=0; o<extracols; o++) { //int to str var helper; helper = o + ""; indizesarray[o]=transparray.indexOf(helper); indizesarray[o]=transparray.indexOf(helper); } var colLength = ciphertext.length / klen; //must be int! colLength=parseInt(colLength) var extra=0; //transposition for(i=0; i < klen; i++) { var helper; helper = i + ""; if (indizesarray.indexOf(i)==-1) cols[i] = ciphertext.substr((i*colLength)+extra,colLength); //if this col got more signs else { cols[i] = ciphertext.substr((i*colLength)+extra,colLength+1); extra+=1; } } outputarray = new Array(klen); //write cols in correct sequence to an output array for (i=0; i<klen; i++) { var helper; helper = i + ""; outputarray[i] = cols[transparray.indexOf(helper)]; } //read outbut array by rows not columns plaintext1 = ""; var tmpcolLength=colLength; if (extracols>0) tmpcolLength++; for(i=0; i < tmpcolLength; i++) { for(j=0; j < klen; j++) plaintext1 += outputarray[j].charAt(i); } //add tranposition information and return endarrayint = new Array(transparray.length); endarraystring = new Array(transparray.length); for (var i=0; i<transparray.length; i++) { endarrayint[transparray[i]]=i+1; endarraystring[i]=keybackup.charAt(transparray[i]); } var endoutput1=endarrayint.join("-"); var endoutput2=endarraystring.join(""); var endoutput3=endoutput1+" ("+endoutput2+")"; outputarray = new Array(plaintext1,endoutput3); return(outputarray); } //transposition (encrypt) column by column //@author Christian Sieche //@version 30.12.2008 //@params: // substitutiontext (string), key (string) this.encodePartB = encodePartB; function encodePartB (substitutiontext, key) { var output=""; var keybackup=key; var colLength = substitutiontext.length / key.length; var transposition=""; ciphertext = ""; k=0; for(i=0; i < key.length; i++) { while(k<alphabet.length) { t = key.indexOf(alphabet.charAt(k)); arrkw = key.split(""); arrkw[t] = "_"; key = arrkw.join(""); if(t >= 0) break; else k++; } if (transposition != "") { transposition = transposition + "-" + t; } else { transposition = "" + t; } for(j=0; j < colLength; j++) output += substitutiontext.charAt(j*key.length + t); } var transparray = transposition.split("-"); endarrayint = new Array(transparray.length); endarraystring = new Array(transparray.length); for (var i=0; i<transparray.length; i++) { endarrayint[transparray[i]]=i+1; endarraystring[i]=keybackup.charAt(transparray[i]); } var endoutput1=endarrayint.join("-"); var endoutput2=endarraystring.join(""); var endoutput3=endoutput1+" ("+endoutput2+")"; outputarray = new Array(output,endoutput3); return(outputarray); } } //*******************************(gui-access-layer) //******************************* //******************************* function CTOTranspositionGuiAccess () { var alphabet = ""; var cryptoclass = new CTOTranspositionAlgorithm(alphabet); var ctolib = new CTOLib(); //@author Christian Sieche //@version 23.12.2008 //@params: this.ChangeParseAlphabetTextA = ChangeParseAlphabetTextA; function ChangeParseAlphabetTextA() { //get latest status var status=document.getElementById("vertical_statusA").innerHTML; var alphtext; //if its closed... if (status=="close") { alphabetSlide.slideIn(); alphtext = document.getElementById("v_toggleA").value; alphtext = alphtext.replace(/>>/g, "<<"); } else { alphabetSlide.slideOut(); alphtext = document.getElementById("v_toggleA").value; alphtext = alphtext.replace(/<</g, ">>"); } document.getElementById("v_toggleA").value = alphtext; } //@author Christian Sieche //@version 26.12.2008 //@params: click(int) item which has been clicked. 1=uppercase, 2=blanks, 3=digits, // 4=punctuation marks, 5=lowercase, 6=umlauts this.setAlphabet = setAlphabet; //specify the alphabet function setAlphabet(click) { // 0=click(int), 1=uppercase(boolean), 2=blanks(boolean), // 3=digits(boolean), 4=punctuation marks(boolean), 5=lowercase(boolean), // 6=umlauts(boolean), 7=rot-13(boolean), 8=alphabet(string) params = new Array( click, document.getElementById("uppercase").checked, document.getElementById("blanks").checked, document.getElementById("digits").checked, document.getElementById("punctuationmarks").checked, document.getElementById("lowercase").checked, document.getElementById("umlauts").checked, false, alphabet); params = ctolib.setAlphabet(params); document.getElementById("uppercase").checked = params[1]; document.getElementById("blanks").checked = params[2]; document.getElementById("digits").checked = params[3]; document.getElementById("punctuationmarks").checked = params[4]; document.getElementById("lowercase").checked = params[5]; document.getElementById("umlauts").checked = params[6]; alphabet = params[8]; document.getElementById("plaintextabc").innerHTML = ctolib.niceAlphabetOutput(alphabet); document.getElementById("alphalength").value = alphabet.length; cryptoclass = new CTOTranspositionAlgorithm(alphabet); checkKey(); //starts encryption too } //@author Christian Sieche //@version 26.12.2008 //@params: this.checkKey = checkKey; function checkKey() //check the key { var key=document.getElementById("key").value; var copy = key; if (document.getElementById("uppercase").checked == true && document.getElementById("lowercase").checked == false) key = key.toUpperCase(); if (document.getElementById("uppercase").checked == false && document.getElementById("lowercase").checked == true) key = key.toLowerCase(); key=ctolib.cleanInputString(key, alphabet, false); if (copy!=key) document.getElementById("key").value=key; transpositionCrypt(false); } //@author Christian Sieche //@version 30.12.2008 //@params: // type = "encode" or "decode" this.transpositionCrypt = transpositionCrypt; function transpositionCrypt(type) //starts encryption { //set value to radiogroup if (type == "encode") { document.CTOTranspositionForm1.code[0].checked = true; document.CTOTranspositionForm1.code[1].checked = false; } if (type == "decode") { document.CTOTranspositionForm1.code[0].checked = false; document.CTOTranspositionForm1.code[1].checked = true; } //get value of radiogroup var type; for (var i = 0; i < document.CTOTranspositionForm1.code.length; i++) if (document.CTOTranspositionForm1.code[i].checked) type = document.CTOTranspositionForm1.code[i].value; //start check key var key = document.getElementById("key").value; var allowedkeys=alphabet; key = ctolib.cleanInputString(key, allowedkeys, false); document.getElementById("key").value=key; //end check key if (type == "encode") { document.getElementById('codtxt').className = 'ctoformcss-txtinput-style ctoformcss-default-input-size'; var orgtext = document.getElementById("orgtxt").value; if (key != "") { // transposition outputarray = cryptoclass.encodePartB(orgtext, key); document.getElementById("codtxt").value = outputarray[0]; document.getElementById("columns").value = outputarray[1]; } else { document.getElementById("key").value = key; document.getElementById("codtxt").value = ""; document.getElementById("columns").value = ""; } } if (type == "decode") { if (document.getElementById('clean').checked==true) document.getElementById('clean').checked=false; var codtext = document.getElementById("codtxt").value // transposition if(key.length <= 0){ return; } outputarray = cryptoclass.decodePartA(codtext, key); document.getElementById("columns").value = outputarray[1]; document.getElementById("orgtxt").value = outputarray[0]; } } } //FX.Slide Effekt var alphabetSlide; window.addEvent('domready', function() { var status = { 'true': 'open', 'false': 'close' }; //-vertical this.alphabetSlide = new Fx.Slide('alphabet-options'); this.alphabetSlide.hide(); $('vertical_statusA').set('html', status[alphabetSlide.open]); // When Vertical Slide ends its transition, we check for its status // note that complete will not affect 'hide' and 'show' methods alphabetSlide.addEvent('complete', function() { $('vertical_statusA').set('html', status[alphabetSlide.open]); }); }); //create transposition object with alphabet and start necessary scripts var CTOTranspositionScripts = new CTOTranspositionGuiAccess();
true
ca9057e67dce4d3a860d053dde9203a5ff23b8ae
JavaScript
Nicetomeetyou777/MyProject
/MyProject_hire/hire_server/routes/index.js
UTF-8
5,918
2.671875
3
[]
no_license
var express = require('express'); var router = express.Router(); const { UserModel, ChatModel } = require('../db/model') const md5 = require('blueimp-md5') const filter = { password: 0, _v: 0 }//查询时过滤出制定的属性 /* GET home page. */ router.get('/', function (req, res, next) { res.render('index', { title: 'Express' }); }); //注册一个路由:用户注册 /** * 提供一个用户注册的接口 a) path 为: /register b) 请求方式为: POST c) 接收 username 和 password 参数 d) admin 是已注册用户 e) 注册成功返回: {code: 0, data: {_id: 'abc', username: ‘xxx’, password:’123’} f) 注册失败返回: {code: 1, msg: '此用户已存在'} */ // router.post('/register',function(req,res){ // // 1,获取请求参数 // const {username,password}=req.body // // 2,处理请求 // if(username==='admin'){//注册失败 // res.send({code:1,msg:'此用户已存在'}) // }else{//注册成功 // res.send({code:0,data:{_id: 'abc', username, password}}) // } // // 3,返回响应 // }) /** * 注册的路由 */ router.post('/register', (req, res) => { //读取参数数据 const { username, password, type } = req.body //处理 //判断用户是否存在,如果存在,返回错误信息,如果不存在,保存 //查询(根据username) UserModel.findOne({ username }, (error, userDoc) => { //如果userDoc有值 if (userDoc) { res.send({ code: 1, msg: '此用户已存在' })//返回错误信息 } else {//没值 new UserModel({ username, type, password: md5(password) }).save((error, user) => { //生成cookie,并交给浏览器保存 res.cookie('userid', user._id, { masAge: 1000 * 60 * 60 * 24 * 30 }) //返回包含userDoc的json数据 const data = { username, type, _id: user._id } res.send({ code: 0, data }) }) } }) //返回相应数据 }) /** * 登录的路由 */ router.post('/login', (req, res) => { //获取参数 const { username, password } = req.body //处理,根据username,password查询数据库users UserModel.findOne({ username, password: md5(password) }, filter, (err, user) => { if (user) {//登陆成功 res.cookie('userid', user._id, { maxAge: 1000 * 60 * 60 * 24 * 30 }) res.send({ code: 0, data: user }) } else { res.send({ code: 1, msg: '用户名或密码不正确' }) }//登录失败 }) }) /** * 更新用户路由 */ router.post('/update', (req, res) => { const { userid } = req.cookies //如果不存在 if (!userid) { res.send({ code: 1, msg: '请重新登录' }) } //如果不存在 //根据userid更新对应的user文档数据 //得到提交的用户数据 const user = req.body//没有_id UserModel.findByIdAndUpdate({ _id: userid }, user, (err, oldUser) => { if (!oldUser) { //通知浏览器删除cookie res.clearCookie('userid') //返回错误通知信息 res.send({ code: 1, msg: '请先登录' }) } else { //返回数据 const { _id, username, type } = oldUser const data = Object.assign(user, { _id, username, type }) res.send({ code: 0, data }) } }) }) //获取用户信息的路由(根据cookie中的userid) router.get('/user', (req, res) => { //从请求的cookie中得到userid const { userid } = req.cookies //如果不存在,直接返回一个提示信息 if (!userid) { return res.send({ code: 1, msg: '请先登录' }) } //根据userid查询对应的user UserModel.findOne({ _id: userid }, filter, (err, user) => { if (!user) { //通知浏览器删除cookie res.clearCookie('userid') //返回错误通知信息 res.send({ code: 1, msg: '请先登录' }) } else { res.send({ code: 0, data: user }) } }) }) //获取用户列表的路由(根据类型) router.get('/userlist', (req, res) => { //req.params '/userlist:type' const { type } = req.query if (!type) { return res.send({ code: 1, msg: '请先选择用户类型' }) } else { UserModel.find({ type }, filter, (err, user) => { res.json({ code: 0, data: user }) }) } //获取当前用户所有相关聊天信息列表 router.get('/msglist', (req, res) => { //获得cookie中的userid const { userid } = req.cookies //查询得到所有user文档数组 UserModel.find(function (err, userDocs) { //用对象存储所有user信息:key为user的_id,val为name和header组成的user对象 //const users = {}对象容器 // userDocs.forEach(user => { // users[user._id] = { username: user.username, header: user.header } // }) const users =userDocs.reduce((users,user)=>{ users[user._id] = { username: user.username, header: user.header } return users },{})//累加 /**查询userid相关的所有聊天信息 * 参数1:查询条件 * 参数2:过滤条件 * 参数3:回调函数 */ //or 或 ChatModel.find({ '$or': [{ from: userid }, { to: userid }] }, filter, function (err, chatMsgs) { //返回包含所有用户和当前用户相关的所有聊天信息的数据 res.send({ code: 0, data: { users, chatMsgs } }) }) }) }) }) /** * 修改指定已读消息 */ router.post('/readmsg',function(req,res){ //得到请求中的from和to const from=req.body.from const to=req.cookies.userid /** * 更新数据库中的chat数据 * 参数1:查询条件 * 参数2:更新为指定的数据对象 * 参数3:是否1次更新多条,默认只更新一条 * 参数4:更新完成的回调函数 */ ChatModel.update({from,to,read:false},{read:true},{multi:true},function(err,doc){ console.log('/readmsg',doc) res.send({code:0,data:doc.nModefied})//更新修改的数量 }) }) module.exports = router;
true
b1fdeceb5279877f6adf7f41cb757e4c6f230241
JavaScript
eni9889/FiOS
/src/gui/core/frida/agents/filesystem/writable.js
UTF-8
1,388
2.671875
3
[ "BSD-3-Clause" ]
permissive
module.exports = function(apath){ return new Promise(function (resolve, reject) { if (ObjC.available) { var NSFileManager = ObjC.classes.NSFileManager; var NSString = ObjC.classes.NSString; // get a file manager instance var fm = NSFileManager.defaultManager(); // init the path we want to check var path = NSString.stringWithString_(apath); var writable = fm.isWritableFileAtPath_(path); resolve(Boolean(writable)) } else if (Java.available) { Java.perform(function () { // Determines if a path on the Android device is writable. var File = Java.use('java.io.File'); var file = File.$new('{{ path }}'); var response = { status: 'success', error_reason: NaN, type: 'file-writable', data: { path: '{{ path }}', writable: Boolean(file.canWrite()) } }; send(response); // -- Sample Java Code // // File d = new File("."); // d.canWrite(); }) } else { reject(new Error('Language not supported')) } }); };
true
3c3aa3201f2a7650ece609c65eb965275a73da0a
JavaScript
huxiaoshanhe/df
/src/app/search/search.service.js
UTF-8
819
2.515625
3
[]
no_license
(function() { 'use strict'; angular .module('pf.search') .factory('searchService', searchService); searchService.$inject = ['dataService', 'sheetService']; function searchService(dataService, sheetService) { var service = { 'search': getSearchData }; return service; /** * 简单表内节点搜索, 带个类型 * @param {String} type 搜索区分 * @param {String} keywords 搜索关键字 * @return {promise} */ function getSearchData(type, keywords) { var sheetId = sheetService.getSheetId(); var params = { 'action': type, 'sheetId': sheetId, 'keywords': keywords }; return dataService.get('search', params) .then(function(source) { return source; }); } } })();
true
22fdcb59d2bb5b80365c831bd6d1c1ffa6bf2750
JavaScript
DevloperM/weekendPractice
/script.js
UTF-8
3,338
3.421875
3
[]
no_license
let myTextbox = document.querySelector("input"); myTextbox.addEventListener("keydown", handleInputBoxEnterKey); let myButton = document.querySelector("button"); myButton.addEventListener("click", handleJokeButton); function addMsg() { let c = document.querySelector("#chatbox"); //Create Message div block let m = document.createElement("div"); m.className = "message"; m.id = c.childElementCount + 1; /**************************************** */ let tim = document.createElement("span"); tim.innerHTML = getCurrentTime(); m.appendChild(tim); /**************************************** */ let nam = document.createElement("span"); nam.className = "sender"; nam.innerHTML = getRandomName(); m.appendChild(nam); /**************************************** */ let msg = document.createElement("span"); let x = document.querySelector("input"); msg.innerHTML = x.value; //todo: replace with text m.appendChild(msg); /**************************************** */ let del = document.createElement("span"); del.className = "delete"; del.innerHTML = "❌"; //todo: add event del.addEventListener("click", deleteMsg); m.appendChild(del); /**************************************** */ c.appendChild(m); //add to chatbox } function deleteMsg() { let c = document.querySelector("#chatbox"); c.removeChild(event.path[1]); } function handleJokeButton() { //console.log("add jokes"); fetch("https://api.icndb.com/jokes/random") .then((r) => r.json()) .then((data) => { let joke = data.value.joke; let c = document.querySelector("#chatbox"); //Create Message div block let m = document.createElement("div"); m.className = "message"; m.id = c.childElementCount + 1; /**************************************** */ let tim = document.createElement("span"); tim.innerHTML = getCurrentTime(); m.appendChild(tim); /**************************************** */ let nam = document.createElement("span"); nam.className = "sender"; nam.innerHTML = "Fact"; m.appendChild(nam); /**************************************** */ let msg = document.createElement("span"); msg.innerHTML = joke; //todo: replace with text m.appendChild(msg); /**************************************** */ let del = document.createElement("span"); del.className = "delete"; del.innerHTML = "❌"; //todo: add event del.addEventListener("click", deleteMsg); m.appendChild(del); /**************************************** */ c.appendChild(m); //add to chatbox }); } function handleInputBoxEnterKey() { if (event.key == "Enter") { event.preventDefault(); addMsg(); let x = document.querySelector("input"); x.value = ""; } } function getRandomName() { //return Me, Myself or I let names = ["I", "Me", "Myself"]; let i = Math.floor(Math.random() * 3); let ans = names[i]; return ans; } function getCurrentTime() { let dt = new Date(); let h = dt.getHours(); let m = dt.getMinutes(); if (h < 10) { h = "0" + h; } if (m < 10) { m = "0" + m; } let ans = h + ":" + m; return ans; }
true
918bb1ebd90d5ff9238b1f06b3e051ccc9c630be
JavaScript
swc-project/swc
/crates/swc/tests/tsc-references/objectTypeWithRecursiveWrappedPropertyCheckedNominally.1.normal.js
UTF-8
1,148
2.59375
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
//// [objectTypeWithRecursiveWrappedPropertyCheckedNominally.ts] // Types with infinitely expanding recursive types are type checked nominally import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; var List = function List() { "use strict"; _class_call_check(this, List); }; var MyList = function MyList() { "use strict"; _class_call_check(this, MyList); }; var list1 = new List(); var list2 = new List(); var myList1 = new MyList(); var myList2 = new MyList(); list1 = myList1; // error, not nominally equal list1 = myList2; // error, type mismatch list2 = myList1; // error, not nominally equal list2 = myList2; // error, type mismatch var rList1 = new List(); var rMyList1 = new List(); rList1 = rMyList1; // error, not nominally equal function foo(t, u) { t = u; // error u = t; // error var a; var b; a = t; // ok a = u; // error b = t; // error b = u; // ok } function foo2(t, u) { t = u; // error u = t; // was error, ok after constraint made illegal, doesn't matter var a; var b; a = t; // error a = u; // error b = t; // ok b = u; // ok }
true
0d29995c415db0f5ee41d198c6c86de3fbeea6e1
JavaScript
CBNU-8/OpenSourceProject
/kakao_map.js
UTF-8
5,621
3.0625
3
[]
no_license
var mapContainer = document.getElementById('map'), // 지도를 표시할 div mapOption = { center: new kakao.maps.LatLng(36.628583, 127.457583), // 지도의 중심좌표 level: 5 // 지도의 확대 레벨 }; // 지도를 생성합니다 var map = new kakao.maps.Map(mapContainer, mapOption); // 지도에 확대 축소 컨트롤을 생성한다 var zoomControl = new kakao.maps.ZoomControl(); // 지도의 우측에 확대 축소 컨트롤을 추가한다 map.addControl(zoomControl, kakao.maps.ControlPosition.RIGHT); // 지도 타입 변경 컨트롤을 생성한다 var mapTypeControl = new kakao.maps.MapTypeControl(); // 지도의 상단 우측에 지도 타입 변경 컨트롤을 추가한다 map.addControl(mapTypeControl, kakao.maps.ControlPosition.TOPRIGHT); function RemoveMarker(){ marker.setMap(null); } // 주소-좌표 변환 객체를 생성합니다 var geocoder = new kakao.maps.services.Geocoder(); function searchPlaces() { var address = document.getElementById('address').value; if (!address.replace(/^\s+|\s+$/g, '')) { alert('키워드를 입력해주세요!'); return false; } // 주소로 좌표를 검색합니다 geocoder.addressSearch(address, function(result, status) { // 정상적으로 검색이 완료됐으면 if (status === kakao.maps.services.Status.OK) { var coords = new kakao.maps.LatLng(result[0].y, result[0].x); var imageSrc = "http://127.0.0.1:5500/PNG/cycling_road.png", // 마커이미지의 주소입니다 imageSize = new kakao.maps.Size(64, 69), // 마커이미지의 크기입니다 imageOption = {offset: new kakao.maps.Point(27, 69)}; // 마커이미지의 옵션입니다. 마커의 좌표와 일치시킬 이미지 안에서의 좌표를 설정합니다. // 마커의 이미지정보를 가지고 있는 마커이미지를 생성합니다 var markerImage = new kakao.maps.MarkerImage(imageSrc, imageSize, imageOption), markerPosition = new kakao.maps.LatLng(result[0].y, result[0].x); // 마커가 표시될 위치입니다 // 마커를 생성합니다 var marker = new kakao.maps.Marker({ position: markerPosition, image: markerImage // 마커이미지 설정 }); // 마커가 지도 위에 표시되도록 설정합니다 marker.setMap(map); // 커스텀 오버레이에 표출될 내용으로 HTML 문자열이나 document element가 가능합니다 var content = '<div class="customoverlay">' + ' <a href="https://map.kakao.com/link/map/11394059" target="_blank">' + ' <span class="title">위치</span>' + ' </a>' + '</div>'; // 커스텀 오버레이가 표시될 위치입니다 var position = new kakao.maps.LatLng(result[0].y, result[0].x); // 커스텀 오버레이를 생성합니다 var customOverlay = new kakao.maps.CustomOverlay({ map: map, position: position, content: content, yAnchor: 1 }); // 지도의 중심을 결과값으로 받은 위치로 이동시킵니다 map.setCenter(coords); } }); // 현재 지도 중심좌표로 주소를 검색해서 지도 좌측 상단에 표시합니다 searchAddrFromCoords(map.getCenter(), displayCenterInfo); // 중심 좌표나 확대 수준이 변경됐을 때 지도 중심 좌표에 대한 주소 정보를 표시하도록 이벤트를 등록합니다 kakao.maps.event.addListener(map, 'idle', function() { searchAddrFromCoords(map.getCenter(), displayCenterInfo); }); function searchAddrFromCoords(coords, callback) { // 좌표로 행정동 주소 정보를 요청합니다 geocoder.coord2RegionCode(coords.getLng(), coords.getLat(), callback); } function searchDetailAddrFromCoords(coords, callback) { // 좌표로 법정동 상세 주소 정보를 요청합니다 geocoder.coord2Address(coords.getLng(), coords.getLat(), callback); } // 지도 좌측상단에 지도 중심좌표에 대한 주소정보를 표출하는 함수입니다 function displayCenterInfo(result, status) { if (status === kakao.maps.services.Status.OK) { var infoDiv = document.getElementById('centerAddr'); for(var i = 0; i < result.length; i++) { // 행정동의 region_type 값은 'H' 이므로 if (result[i].region_type === 'H') { infoDiv.innerHTML = result[i].address_name; break; } } } } } /* // 마커에 마우스오버 이벤트를 등록합니다 kakao.maps.event.addListener(marker, 'mouseover', function() { // 마커에 마우스오버 이벤트가 발생하면 인포윈도우를 마커위에 표시합니다 infowindow.open(map, marker); }); // 마커에 마우스아웃 이벤트를 등록합니다 kakao.maps.event.addListener(marker, 'mouseout', function() { // 마커에 마우스아웃 이벤트가 발생하면 인포윈도우를 제거합니다 infowindow.close(); }); */
true
1e12840baad3f70f7194a49796cde60c1d0103b3
JavaScript
ocalvet/app_manager
/src/services/Authenticator.js
UTF-8
873
2.625
3
[ "MIT" ]
permissive
import axios from 'axios'; class Authenticator { authenticate = async (username, password) => { try { const response = await axios({ url: `${process.env.REACT_APP_API_URL}/auth/signin`, headers: new Headers({ 'Content-Type': 'application/json' }), method: 'POST', data: { username, password } }); if (response.status !== 200) throw new Error('Error in response'); localStorage.setItem('user', JSON.stringify(response.data)); return response.data; } catch (e) { console.log('ERROR', e); this.signout(); throw new Error('Wrong user name or password'); } }; getUser = () => { return JSON.parse(localStorage.getItem('user')); }; signout = () => { localStorage.removeItem('user'); }; } export default Authenticator;
true
11dfcdfc4c3bbf825e81dc9198a74c40cbe8443d
JavaScript
JamalYusuf/JavaScript
/Club Age conditions/script.js
UTF-8
212
3.734375
4
[]
no_license
var age = prompt("What is your age?"); if(age < 0) console.log("Error age cannot be negative!"); else if (age === 21) console.log("Happy 21st birthday!!!"); else if ((age%2)!==0) console.log("your age is odd!");
true
0ad462449185504d64c90298b5b5acd4bbd3e8eb
JavaScript
contibru/bootcampigti
/modulo_02/desafio/index.js
UTF-8
4,743
2.5625
3
[]
no_license
import express from "express" import { promises as fs } from "fs"; import { stringify } from "querystring"; const app = express(); app.use(express.json()) const db = JSON.parse(await fs.readFile("./db/grades.json")) // // // // Logs // // // const myFormat = winston.format.printf(({ // level, // message, // label, // timestamp // }) => { // return `${timestamp} [${label}] ${level}: ${message} ` // }) // const logger = winston.createLogger({ // level: "silly", // transports: [ // new(winston.transports.Console)(), // new(winston.transports.File)({ // filename: "debug.log" // }), // ], // format: winston.format.combine( // winston.format.label({ // label: "my-app" // }), // winston.format.timestamp(), // myFormat // ) // }) // logger.error("Error log") // logger.warn("Warn log") // logger.info("Info log") // logger.verbose("verbose log") // logger.debug("debug log") // logger.silly("silly log") // app.use((req, res, next) => { // console.log(req.body); // next() // }) // app.get("/", (req, res) => { // res.send("Sou um get") // }) // // Exemplos de caracteres que podem ser usados nas rotas. // // Aceita qualquer caractere no ?. // app.get("/teste?", (req, res) => { // res.send("Teste com ?") // }) // // Aceita vários caracteres iguais ao anterior ao +. // app.get("/buzz+", (req, res) => { // res.send("Teste com +") // }) // // Aceitar qualquer coisa entre one e Blue. // app.get("/one*Blue", (req, res) => { // res.send("Teste com *") // }) // // Aceitar tanto test quanto testing. // app.get("/test(ing)", (req, res) => { // res.send("Teste com ()") // }) // app.post("/", (req, res) => { // res.send("Sou um post") // }) app.route("/grades") .get(async (req, res) => { res.send(db.grades) }) .post((req, res) => { let newGrade = req.body newGrade = {id: db.nextId, ...newGrade, timestamp: new Date()} db.grades.push(newGrade) db.nextId++ fs.writeFile('./db/grades.json',JSON.stringify(db)) res.send(newGrade) }) app.route("/grades/sumValueStudentSubject") .get(async (req, res) => { const sumValues = db.grades.reduce((acc, curr) => { return acc + (curr.student === req.body.student && curr.subject === req.body.subject ? curr.value : 0); },0) console.log(sumValues); res.status(200).send(sumValues.toString()) }) app.route("/grades/avgValueSubjectType") .get(async (req, res) => { let totFounded = 0 const sumValues = db.grades.reduce((acc, curr) => { if (curr.subject === req.body.subject && curr.type === req.body.type) { totFounded++ return acc + curr.value } else { return acc + 0 } }, 0) console.log(sumValues); console.log(totFounded); res.status(200).send((sumValues / totFounded).toString()) }) app.route("/grades/orderByValueSubjectType") .get(async (req, res) => { const gradesFiltered = db.grades.filter(value => { return value.subject === req.body.subject && value.type === req.body.type }) console.log(gradesFiltered); const gradesSorted = gradesFiltered.sort((a, b) => { return a.value - b.value }).reverse().splice(0,3) res.status(200).send(gradesSorted) }) app.route("/grades/:id") .get(async (req, res) => { const grade = db.grades.find(el => { return el.id === parseInt(req.params.id) }) res.send(grade) }) .put((req, res) => { let grade = req.body const index = db.grades.findIndex(el => el.id === parseInt(req.params.id)) if (index < 0) { res.status(404).send(`Grade ${req.params.id} not found!`) } grade = { id: db.grades[index].id, ...grade, timestamp: new Date() } db.grades[index] = grade fs.writeFile('./db/grades.json',JSON.stringify(db)) res.send(grade) }) .delete((req, res) => { const index = db.grades.findIndex(el => el.id === parseInt(req.params.id)) if (index < 0) { res.status(404).send(`Grade ${req.params.id} not found!`) } db.grades.splice(index, 1) fs.writeFile('./db/grades.json',JSON.stringify(db)) res.send(`Grade ${req.params.id} deleted!`) }) // Tratamento de erro. app.use((err, req, res, next) => { res.status(500).send("Ocorreu um erro") }) app.listen(3000, () => { console.log("Ouvindo na porta 3000."); })
true
61760beaab9081ca5228e65c39891c814a171d39
JavaScript
LeamonLee/Js_Snippet
/Ninja_tutorial/DOM/TheNetNinja/Tutorial-DOMTraverse1-7/app.js
UTF-8
941
3.828125
4
[]
no_license
const bookList = document.querySelector('#book-list'); // 99% time parentNode and parentElement are gonna return the same element. console.log('book list parent node:', bookList.parentNode); console.log('book list parent element:', bookList.parentElement); console.log('book list parent element:', bookList.parentElement.parentElement); console.log('all node children:'); // childNodes will return a list of elements including linebreak(textnode), element, linebreak, element, linebreak... Array.from(bookList.childNodes).forEach(function(node){ console.log(node); }); console.log('all element children:'); // whereas children won't contain textnode. instead it's only gonna return elements. Array.from(bookList.children).forEach(function(node){ console.log(node); }); const titles = bookList.querySelectorAll('.name'); console.log('Book titles:'); Array.from(titles).forEach(function(title){ console.log(title.textContent); });
true
24b72b5df6b8bec6f446343081c81ce370856f62
JavaScript
kobzarvs/test-job
/src/modules/testJob1.js
UTF-8
726
3.34375
3
[]
no_license
/** * Вычислительная сложность: O(2n) * Сложность по памяти: O(2n) * Время выполнения на моем ПК 10 млн элементов массива, обработались * данной функицей примерно за 3 сек. */ export const piecesToPercents = ({ list }) => { if (!Array.isArray(list)) return null // 1. Считаем общую сумму элементов const sum = list.reduce((acc, item) => acc + parseFloat(item), 0) // 2. Вычисление доли в процентном выражении с точностью до трех знаков return list.map(item => ((parseFloat(item) * 100) / sum).toFixed(3)) }
true