language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function resolveHostAndPort() { const connectionOptions = this.connection_options; return connectionOptions ? [connectionOptions.host, connectionOptions.port] : this.options ? [this.options.host, this.options.port] : [defaultHost, defaultPort]; }
function resolveHostAndPort() { const connectionOptions = this.connection_options; return connectionOptions ? [connectionOptions.host, connectionOptions.port] : this.options ? [this.options.host, this.options.port] : [defaultHost, defaultPort]; }
JavaScript
function normalizePort(val) { const ret_port = parseInt(val, 10); if (Number.isNaN(ret_port)) { // named pipe return val; } if (ret_port >= 0) { // port number return ret_port; } return false; }
function normalizePort(val) { const ret_port = parseInt(val, 10); if (Number.isNaN(ret_port)) { // named pipe return val; } if (ret_port >= 0) { // port number return ret_port; } return false; }
JavaScript
function check_dungeon_list(){ if(dungeons.length > 0){ // Add zone 3020 to dungeon list if(dungeons.findIndex(d => d.id == 3020) === -1){ const s = { en: "Sea of Honor", kr: "금비늘호", jp: "探宝の金鱗号", de: "Goldschuppe", fr: "l'Écaille dorée", tw: "金麟號", ru: "Золотая чешуя" }; dungeons.push({ "id": 3020, "name": (s[language] || s["en"]) }); } return; } // Try to read dungeon list from "guides" directory, as dungeon name uses first line of guide js-file fs.readdirSync(path.join(__dirname, GUIDES_DIR)).filter(x => x.indexOf("js") !== -1).forEach(file => { const id = parseInt(file.split(".")[0]); if(id){ const lineReader = readline.createInterface({ input: fs.createReadStream(path.join(__dirname, GUIDES_DIR, file)) }); lineReader.on("line", function(line){ const name = line.replace(/^[\/\s]+/g, "") || id; // eslint-disable-line no-useless-escape dungeons.push({ "id": id, "name": name }); lineReader.close(); lineReader.removeAllListeners(); }); } }); }
function check_dungeon_list(){ if(dungeons.length > 0){ // Add zone 3020 to dungeon list if(dungeons.findIndex(d => d.id == 3020) === -1){ const s = { en: "Sea of Honor", kr: "금비늘호", jp: "探宝の金鱗号", de: "Goldschuppe", fr: "l'Écaille dorée", tw: "金麟號", ru: "Золотая чешуя" }; dungeons.push({ "id": 3020, "name": (s[language] || s["en"]) }); } return; } // Try to read dungeon list from "guides" directory, as dungeon name uses first line of guide js-file fs.readdirSync(path.join(__dirname, GUIDES_DIR)).filter(x => x.indexOf("js") !== -1).forEach(file => { const id = parseInt(file.split(".")[0]); if(id){ const lineReader = readline.createInterface({ input: fs.createReadStream(path.join(__dirname, GUIDES_DIR, file)) }); lineReader.on("line", function(line){ const name = line.replace(/^[\/\s]+/g, "") || id; // eslint-disable-line no-useless-escape dungeons.push({ "id": id, "name": name }); lineReader.close(); lineReader.removeAllListeners(); }); } }); }
JavaScript
function debug_message(d, ...args){ if(d){ console.log(`[${Date.now() % 100000}][Guide]`, ...args); if(debug.chat) command.message(args.toString()); } }
function debug_message(d, ...args){ if(d){ console.log(`[${Date.now() % 100000}][Guide]`, ...args); if(debug.chat) command.message(args.toString()); } }
JavaScript
function class_position_check(class_position){ // if it's not defined we assume that it's for everyone if(!class_position) return true; // If it's an array if(Array.isArray(class_position)){ // If one of the class_positions pass, we can accept it for(const ent of class_position){if(class_position_check(ent)) return true;} // All class_positions failed, so we return false return false; } switch(class_position){ case "tank":{ // if it's a warrior with dstance abnormality if(player.job === 0){ // Loop thru tank abnormalities for(const id of WARRIOR_TANK_IDS){ // if we have the tank abnormality return true if(effect.hasAbnormality(id)) return true; } } // if it's a tank return true if(TANK_CLASS_IDS.includes(player.job)) return true; break; } case "dps":{ // If it's a warrior with dstance abnormality if(player.job === 0){ // Loop thru tank abnormalities for(const id of WARRIOR_TANK_IDS){ // if we have the tank abnormality return false if(effect.hasAbnormality(id)) return false; } // warrior didn't have tank abnormality return true; } // if it's a dps return true if(DPS_CLASS_IDS.includes(player.job)) return true; break; } case "heal":{ // if it's a healer return true if(HEALER_CLASS_IDS.includes(player.job)) return true; break; } case "priest":{ if(player.job === 6) return true; // For Priest specific actions (eg Arise) break; } case "mystic":{ if(player.job === 7) return true; // For Mystic specific actions break; } case "lancer":{ if(player.job === 1) return true; // For Lancer specific actions (eg Blue Shield) break; } default:{ debug_message(true, "Failed to find class_position value:", class_position); } } return false; }
function class_position_check(class_position){ // if it's not defined we assume that it's for everyone if(!class_position) return true; // If it's an array if(Array.isArray(class_position)){ // If one of the class_positions pass, we can accept it for(const ent of class_position){if(class_position_check(ent)) return true;} // All class_positions failed, so we return false return false; } switch(class_position){ case "tank":{ // if it's a warrior with dstance abnormality if(player.job === 0){ // Loop thru tank abnormalities for(const id of WARRIOR_TANK_IDS){ // if we have the tank abnormality return true if(effect.hasAbnormality(id)) return true; } } // if it's a tank return true if(TANK_CLASS_IDS.includes(player.job)) return true; break; } case "dps":{ // If it's a warrior with dstance abnormality if(player.job === 0){ // Loop thru tank abnormalities for(const id of WARRIOR_TANK_IDS){ // if we have the tank abnormality return false if(effect.hasAbnormality(id)) return false; } // warrior didn't have tank abnormality return true; } // if it's a dps return true if(DPS_CLASS_IDS.includes(player.job)) return true; break; } case "heal":{ // if it's a healer return true if(HEALER_CLASS_IDS.includes(player.job)) return true; break; } case "priest":{ if(player.job === 6) return true; // For Priest specific actions (eg Arise) break; } case "mystic":{ if(player.job === 7) return true; // For Mystic specific actions break; } case "lancer":{ if(player.job === 1) return true; // For Lancer specific actions (eg Blue Shield) break; } default:{ debug_message(true, "Failed to find class_position value:", class_position); } } return false; }
JavaScript
function handle_event(ent, id, called_from_identifier, prefix_identifier, d, speed = 1.0, stage = false){ const unique_id = `${prefix_identifier}-${ent["huntingZoneId"]}-${ent["templateId"]}`; const key = `${unique_id}-${id}`; const stage_string = (stage === false ? '' : `-${stage}`); debug_message(d, `${called_from_identifier}: ${id} | Started by: ${unique_id} | key: ${key + stage_string}`); if(stage !== false){ const entry = active_guide[key + stage_string]; if(entry) start_events(entry, ent, speed); } const entry = active_guide[key]; if(entry) start_events(entry, ent, speed); }
function handle_event(ent, id, called_from_identifier, prefix_identifier, d, speed = 1.0, stage = false){ const unique_id = `${prefix_identifier}-${ent["huntingZoneId"]}-${ent["templateId"]}`; const key = `${unique_id}-${id}`; const stage_string = (stage === false ? '' : `-${stage}`); debug_message(d, `${called_from_identifier}: ${id} | Started by: ${unique_id} | key: ${key + stage_string}`); if(stage !== false){ const entry = active_guide[key + stage_string]; if(entry) start_events(entry, ent, speed); } const entry = active_guide[key]; if(entry) start_events(entry, ent, speed); }
JavaScript
function start_events(events = [], ent, speed = 1.0){ // Loop over the events for(const event of events){ const func = function_event_handlers[event["type"]]; // The function couldn"t be found, so it"s an invalid type if(!func) debug_message(true, "An event has invalid type:", event["type"]); // If the function is found and it passes the class position check, we start the event else if(class_position_check(event["class_position"])) func(event, ent, speed = 1.0); } }
function start_events(events = [], ent, speed = 1.0){ // Loop over the events for(const event of events){ const func = function_event_handlers[event["type"]]; // The function couldn"t be found, so it"s an invalid type if(!func) debug_message(true, "An event has invalid type:", event["type"]); // If the function is found and it passes the class position check, we start the event else if(class_position_check(event["class_position"])) func(event, ent, speed = 1.0); } }
JavaScript
function entry_zone(zone){ // Check and generate gungeon list if it is not exists check_dungeon_list(); // Create default dungeon configuration create_dungeon_configuration(); // Enable errors debug let debug_errors = true; // Disable trigger event flag is_event = false; // Clear current hp values for all zone mobs mobs_hp = {}; // Clear out the timers fake_dispatch._clear_all_timers(); for(const key in timers) dispatch.clearTimeout(timers[key]); timers = {}; // Clear out previous hooks, that our previous guide module hooked fake_dispatch._remove_all_hooks(); // Send debug message debug_message(debug.debug, "Entered zone:", zone); // Remove potential cached guide from require cache, so that we don"t need to relog to refresh guide try { delete require.cache[require.resolve("./" + GUIDES_DIR + "/" + zone)]; } catch (e){} // Try loading a guide try { entered_guide = {}; // Check guide and attach settings from config for(const dungeon of dungeons){ if(dungeon.id == zone){ // Create zone data for entered guide entered_guide = dungeon; // Reload guide configuration reload_dungeon_configuration(entered_guide.id); break; } } // Load test guide data if(zone == "test"){ entered_guide = { "id": "test", "name": "Test Guide", "settings": default_dungeon_settings }; } if(!entered_guide.id){ debug_errors = debug.debug; throw "Guide for zone " + zone + " not found"; } // active_guide = require("./" + GUIDES_DIR + "/" + zone); if(SP_ZONE_IDS.includes(zone)){ spguide = true; // skill 1000-3000 esguide = false; } else if(ES_ZONE_IDS.includes(zone)){ spguide = false; // skill 100-200-3000 esguide = true; } else { spguide = false; // skill 100-200 esguide = false; } guide_found = true; if(entered_guide.name){ if(spguide){ text_handler({ "sub_type": "PRMSG", "message": `${lang.enteresdg}: ${cr}${entered_guide.name} ${cw}[${zone}]` }); } else if(esguide){ text_handler({ "sub_type": "PRMSG", "message": `${lang.enterspdg}: ${cr}${entered_guide.name} ${cw}[${zone}]` }); } else { text_handler({ "sub_type": "PRMSG", "message": `${lang.enterdg}: ${cr}${entered_guide.name} ${cw}[${zone}]` }); } text_handler({ "sub_type": "CGMSG", "message": `${lang.helpheader}\n` + `${lang.stream}: ${dispatch.settings.stream ? lang.enabled : lang.disabled}\n` + `${lang.gNotice}: ${dispatch.settings.gNotice ? lang.enabled : lang.disabled}\n` + `${lang.speaks}: ${dispatch.settings.speaks ? lang.enabled : lang.disabled}` }); } } catch (e){ entered_guide = {}; active_guide = {}; guide_found = false; debug_message(debug_errors, e); } if(guide_found){ // Try calling the "load" function try { active_guide.load(fake_dispatch); } catch (e){ debug_message(debug_errors, e); } } }
function entry_zone(zone){ // Check and generate gungeon list if it is not exists check_dungeon_list(); // Create default dungeon configuration create_dungeon_configuration(); // Enable errors debug let debug_errors = true; // Disable trigger event flag is_event = false; // Clear current hp values for all zone mobs mobs_hp = {}; // Clear out the timers fake_dispatch._clear_all_timers(); for(const key in timers) dispatch.clearTimeout(timers[key]); timers = {}; // Clear out previous hooks, that our previous guide module hooked fake_dispatch._remove_all_hooks(); // Send debug message debug_message(debug.debug, "Entered zone:", zone); // Remove potential cached guide from require cache, so that we don"t need to relog to refresh guide try { delete require.cache[require.resolve("./" + GUIDES_DIR + "/" + zone)]; } catch (e){} // Try loading a guide try { entered_guide = {}; // Check guide and attach settings from config for(const dungeon of dungeons){ if(dungeon.id == zone){ // Create zone data for entered guide entered_guide = dungeon; // Reload guide configuration reload_dungeon_configuration(entered_guide.id); break; } } // Load test guide data if(zone == "test"){ entered_guide = { "id": "test", "name": "Test Guide", "settings": default_dungeon_settings }; } if(!entered_guide.id){ debug_errors = debug.debug; throw "Guide for zone " + zone + " not found"; } // active_guide = require("./" + GUIDES_DIR + "/" + zone); if(SP_ZONE_IDS.includes(zone)){ spguide = true; // skill 1000-3000 esguide = false; } else if(ES_ZONE_IDS.includes(zone)){ spguide = false; // skill 100-200-3000 esguide = true; } else { spguide = false; // skill 100-200 esguide = false; } guide_found = true; if(entered_guide.name){ if(spguide){ text_handler({ "sub_type": "PRMSG", "message": `${lang.enteresdg}: ${cr}${entered_guide.name} ${cw}[${zone}]` }); } else if(esguide){ text_handler({ "sub_type": "PRMSG", "message": `${lang.enterspdg}: ${cr}${entered_guide.name} ${cw}[${zone}]` }); } else { text_handler({ "sub_type": "PRMSG", "message": `${lang.enterdg}: ${cr}${entered_guide.name} ${cw}[${zone}]` }); } text_handler({ "sub_type": "CGMSG", "message": `${lang.helpheader}\n` + `${lang.stream}: ${dispatch.settings.stream ? lang.enabled : lang.disabled}\n` + `${lang.gNotice}: ${dispatch.settings.gNotice ? lang.enabled : lang.disabled}\n` + `${lang.speaks}: ${dispatch.settings.speaks ? lang.enabled : lang.disabled}` }); } } catch (e){ entered_guide = {}; active_guide = {}; guide_found = false; debug_message(debug_errors, e); } if(guide_found){ // Try calling the "load" function try { active_guide.load(fake_dispatch); } catch (e){ debug_message(debug_errors, e); } } }
JavaScript
function Login(){ const { push } = useHistory(); // Initialize state for errors, values, and disabled. const [loginValues, setLoginValues] = useState(initialLoginValues); const [users, setUsers] = useState([]); const [loginErrors, setLoginErrors] = useState(initialErrors); const [disabled, setDisabled] = useState(true) ///// HELPERS ///// const postNewUser = (newUser) => { axios .post( "https://african-marketplace-back-end.herokuapp.com/auth/login", newUser ) .then((res) => { console.log("Successful Login:", res.data); setUsers([newUser, ...users]); setLoginValues(initialLoginValues); window.localStorage.setItem("token", res.data.token); push('/Market') }) .catch((error) => { console.log("Unsuccessful Login:", error); }); }; ///// EVENT HANDLERS ///// // Input change. const onChange = (e) => { const name = e.target.name; const value = e.target.value; yup .reach(schema, name) .validate(value) .then(() => { setLoginErrors({ ...loginErrors, [name]: "", }); }) .catch((error) => { setLoginErrors({ ...loginErrors, [name]: error.errors[0], }); }); setLoginValues({ ...loginValues, [name]: value, }); }; // Input submit. const onSubmit = (e) => { e.preventDefault(); // added by steven const newUser = { username: loginValues.username.trim(), password: loginValues.password.trim(), }; postNewUser(newUser); }; ///// SIDE EFFECTS ///// useEffect(() => { schema.isValid(loginValues).then((valid) => { setDisabled(!valid); }); }, [loginValues]); ///// FORM ///// return ( <section className='signup-section'> <form className="signup-form" onSubmit={onSubmit}> <h2>Please sign in to view your account.</h2> <hr /> <div className='textForm-containers'> <TextField className='login-textform' variant="outlined" name="username" type="string" value={loginValues.username} placeholder="Username" onChange={onChange} /> <TextField className='login-textform' variant="outlined" name="password" type="password" value={loginValues.password} placeholder="Password" onChange={onChange} /> </div> <div className='button-container'> <button className='login-button' disabled={disabled}>Login</button> </div> </form> </section> ); }
function Login(){ const { push } = useHistory(); // Initialize state for errors, values, and disabled. const [loginValues, setLoginValues] = useState(initialLoginValues); const [users, setUsers] = useState([]); const [loginErrors, setLoginErrors] = useState(initialErrors); const [disabled, setDisabled] = useState(true) ///// HELPERS ///// const postNewUser = (newUser) => { axios .post( "https://african-marketplace-back-end.herokuapp.com/auth/login", newUser ) .then((res) => { console.log("Successful Login:", res.data); setUsers([newUser, ...users]); setLoginValues(initialLoginValues); window.localStorage.setItem("token", res.data.token); push('/Market') }) .catch((error) => { console.log("Unsuccessful Login:", error); }); }; ///// EVENT HANDLERS ///// // Input change. const onChange = (e) => { const name = e.target.name; const value = e.target.value; yup .reach(schema, name) .validate(value) .then(() => { setLoginErrors({ ...loginErrors, [name]: "", }); }) .catch((error) => { setLoginErrors({ ...loginErrors, [name]: error.errors[0], }); }); setLoginValues({ ...loginValues, [name]: value, }); }; // Input submit. const onSubmit = (e) => { e.preventDefault(); // added by steven const newUser = { username: loginValues.username.trim(), password: loginValues.password.trim(), }; postNewUser(newUser); }; ///// SIDE EFFECTS ///// useEffect(() => { schema.isValid(loginValues).then((valid) => { setDisabled(!valid); }); }, [loginValues]); ///// FORM ///// return ( <section className='signup-section'> <form className="signup-form" onSubmit={onSubmit}> <h2>Please sign in to view your account.</h2> <hr /> <div className='textForm-containers'> <TextField className='login-textform' variant="outlined" name="username" type="string" value={loginValues.username} placeholder="Username" onChange={onChange} /> <TextField className='login-textform' variant="outlined" name="password" type="password" value={loginValues.password} placeholder="Password" onChange={onChange} /> </div> <div className='button-container'> <button className='login-button' disabled={disabled}>Login</button> </div> </form> </section> ); }
JavaScript
function updateClock(days, hours, minutes) { var $container = $('.container__top__hours-wasted'), $daysContainer = $container.find('.hours-wasted__days'), $hoursContainer = $container.find('.hours-wasted__hours'), $minutesContainer = $container.find('.hours-wasted__minutes'); // replace content // $daysContainer.find('.numbers').text(days); // $hoursContainer.find('.numbers').text(hours); // $minutesContainer.find('.numbers').text(minutes); // countUp plugin update number var daysCount = new countUp("days", 00, days, 0, 2), hoursCount = new countUp("hours", 00, hours, 0, 4), minutesCount = new countUp("minutes", 00, minutes, 0, 6); daysCount.reset(); hoursCount.reset(); minutesCount.reset(); daysCount.start(); hoursCount.start(); minutesCount.start(); // check label "1 minute" not "1 minutes" (days == '01') ? $daysContainer.find('.description').text('day') : $daysContainer.find('.description').text('days'); (hours == '01') ? $hoursContainer.find('.description').text('hour') : $hoursContainer.find('.description').text('hours'); (minutes == '01') ? $minutesContainer.find('.description').text('minute') : $minutesContainer.find('.description').text('minutes'); // tweet link text change if (days < 01) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + hours + ' hours and ' + minutes + ' minutes of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else if (days == 01) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' day, ' + hours + ' hours, and ' + minutes + ' minutes of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else if (hours < 01) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' days and ' + minutes + ' minutes of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else if (hours == 01) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' days, ' + hours + ' hour, and ' + minutes + ' minutes of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else if (minutes < 01) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' days and ' + hours + ' hours of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else if (minutes == 01) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' days, ' + hours + ' hours, and ' + minutes + ' minute of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else if ((hours < 01) && (minutes < 01)) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' days of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' days, ' + hours + ' hours, and ' + minutes + ' minutes of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } }
function updateClock(days, hours, minutes) { var $container = $('.container__top__hours-wasted'), $daysContainer = $container.find('.hours-wasted__days'), $hoursContainer = $container.find('.hours-wasted__hours'), $minutesContainer = $container.find('.hours-wasted__minutes'); // replace content // $daysContainer.find('.numbers').text(days); // $hoursContainer.find('.numbers').text(hours); // $minutesContainer.find('.numbers').text(minutes); // countUp plugin update number var daysCount = new countUp("days", 00, days, 0, 2), hoursCount = new countUp("hours", 00, hours, 0, 4), minutesCount = new countUp("minutes", 00, minutes, 0, 6); daysCount.reset(); hoursCount.reset(); minutesCount.reset(); daysCount.start(); hoursCount.start(); minutesCount.start(); // check label "1 minute" not "1 minutes" (days == '01') ? $daysContainer.find('.description').text('day') : $daysContainer.find('.description').text('days'); (hours == '01') ? $hoursContainer.find('.description').text('hour') : $hoursContainer.find('.description').text('hours'); (minutes == '01') ? $minutesContainer.find('.description').text('minute') : $minutesContainer.find('.description').text('minutes'); // tweet link text change if (days < 01) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + hours + ' hours and ' + minutes + ' minutes of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else if (days == 01) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' day, ' + hours + ' hours, and ' + minutes + ' minutes of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else if (hours < 01) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' days and ' + minutes + ' minutes of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else if (hours == 01) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' days, ' + hours + ' hour, and ' + minutes + ' minutes of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else if (minutes < 01) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' days and ' + hours + ' hours of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else if (minutes == 01) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' days, ' + hours + ' hours, and ' + minutes + ' minute of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else if ((hours < 01) && (minutes < 01)) { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' days of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } else { $('.sharing-link').attr('href', 'https://twitter.com/share?text=I’ve wasted ' + days + ' days, ' + hours + ' hours, and ' + minutes + ' minutes of my life watching TV shows. Calculate your time:&url=http://tiii.me'); } }
JavaScript
function contains(cell) { let gameState = this; let cellAsString = JSON.stringify(cell); let result = gameState.some(function (item) { return JSON.stringify(item) == cellAsString; }); return result; }
function contains(cell) { let gameState = this; let cellAsString = JSON.stringify(cell); let result = gameState.some(function (item) { return JSON.stringify(item) == cellAsString; }); return result; }
JavaScript
function renderElectionShape() { var x; var dim; var electionType; var onEnter; var calcDim = function(d) { return dim(d[electionType]); }; var calcX; var calcY; var label = function(d) { var count = d[electionType]; return count + " " + RACE_TYPE_LABELS[electionType].toLowerCase() + " " + pluralize("election", count); }; function render(selection) { selection.enter().call(onEnter); } render.calcDim = function(val) { if (!arguments.length) return calcDim; calcDim = val; return render; }; render.label = function(val) { if (!arguments.length) return label; label = val; return render; }; render.x = function(val) { if (!arguments.length) return x; x = val; return render; }; render.y = function(val) { if (!arguments.length) return y; y = val; return render; }; render.dim = function(val) { if (!arguments.length) return dim; dim = val; return render; }; render.electionType = function(val) { if (!arguments.length) return electionType; electionType = val; return render; }; render.onEnter = function(val) { if (!arguments.length) return onEnter; onEnter = val; return render; }; render.calcX = function(val) { if (!arguments.length) return calcX; calcX = val; return render; }; render.calcY = function(val) { if (!arguments.length) return calcY; calcY = val; return render; }; return render; }
function renderElectionShape() { var x; var dim; var electionType; var onEnter; var calcDim = function(d) { return dim(d[electionType]); }; var calcX; var calcY; var label = function(d) { var count = d[electionType]; return count + " " + RACE_TYPE_LABELS[electionType].toLowerCase() + " " + pluralize("election", count); }; function render(selection) { selection.enter().call(onEnter); } render.calcDim = function(val) { if (!arguments.length) return calcDim; calcDim = val; return render; }; render.label = function(val) { if (!arguments.length) return label; label = val; return render; }; render.x = function(val) { if (!arguments.length) return x; x = val; return render; }; render.y = function(val) { if (!arguments.length) return y; y = val; return render; }; render.dim = function(val) { if (!arguments.length) return dim; dim = val; return render; }; render.electionType = function(val) { if (!arguments.length) return electionType; electionType = val; return render; }; render.onEnter = function(val) { if (!arguments.length) return onEnter; onEnter = val; return render; }; render.calcX = function(val) { if (!arguments.length) return calcX; calcX = val; return render; }; render.calcY = function(val) { if (!arguments.length) return calcY; calcY = val; return render; }; return render; }
JavaScript
function renderSquare() { var render = renderElectionShape() .calcX(function(d) { return render.x()(d.year) + (render.x().rangeBand() / 2) - (render.calcDim()(d) / 2); }) .calcY(function(d) { return render.y()(render.electionType()) - (render.calcDim()(d) / 2); }); render.onEnter(function(selection) { selection.append('rect') .attr('class', render.electionType().replace('_', '-')) .attr('x', render.calcX()) .attr('y', render.calcY()) .attr('width', render.calcDim()) .attr('height', render.calcDim()) .append('title') .text(function(d) { return render.label()(d); }); }); return render; }
function renderSquare() { var render = renderElectionShape() .calcX(function(d) { return render.x()(d.year) + (render.x().rangeBand() / 2) - (render.calcDim()(d) / 2); }) .calcY(function(d) { return render.y()(render.electionType()) - (render.calcDim()(d) / 2); }); render.onEnter(function(selection) { selection.append('rect') .attr('class', render.electionType().replace('_', '-')) .attr('x', render.calcX()) .attr('y', render.calcY()) .attr('width', render.calcDim()) .attr('height', render.calcDim()) .append('title') .text(function(d) { return render.label()(d); }); }); return render; }
JavaScript
function renderCircle() { var render = renderElectionShape() .calcX(function(d) { var x = render.x(); return x(d.year) + (x.rangeBand() / 2); }) .calcY(function(d) { return render.y()(render.electionType()); }); render.onEnter(function(selection) { selection.append('circle') .attr('class', render.electionType().replace('_', '-')) .attr('cx', render.calcX()) .attr('cy', render.calcY()) .attr('r', function(d) { return render.calcDim()(d) / 2; }) .append('title') .text(function(d) { return render.label()(d); }); }); return render; }
function renderCircle() { var render = renderElectionShape() .calcX(function(d) { var x = render.x(); return x(d.year) + (x.rangeBand() / 2); }) .calcY(function(d) { return render.y()(render.electionType()); }); render.onEnter(function(selection) { selection.append('circle') .attr('class', render.electionType().replace('_', '-')) .attr('cx', render.calcX()) .attr('cy', render.calcY()) .attr('r', function(d) { return render.calcDim()(d) / 2; }) .append('title') .text(function(d) { return render.label()(d); }); }); return render; }
JavaScript
function xtoyear(d, xScale) { var barWidth = xScale.rangeBand(); var w = barWidth + (barWidth * barPadding); var i = Math.floor(d / w); var domain = xScale.domain(); if (i >= domain.length) { return null; } return domain[i]; }
function xtoyear(d, xScale) { var barWidth = xScale.rangeBand(); var w = barWidth + (barWidth * barPadding); var i = Math.floor(d / w); var domain = xScale.domain(); if (i >= domain.length) { return null; } return domain[i]; }
JavaScript
function sizeRange(d, max, pctChg) { // Starting with the maximum, each item should decrease by the pct // change var range = d.map(function(val) { return max * Math.exp(-1 * pctChg * val); }).reverse(); // Zero should map to zero if (d[0] === 0) { range[0] = 0; } return range; }
function sizeRange(d, max, pctChg) { // Starting with the maximum, each item should decrease by the pct // change var range = d.map(function(val) { return max * Math.exp(-1 * pctChg * val); }).reverse(); // Zero should map to zero if (d[0] === 0) { range[0] = 0; } return range; }
JavaScript
function renderToggle(el) { var resultsBtn = el.append('button') .attr('class', 'btn-toggle btn-results') .text("Data"); var metaBtn = el.append('button') .attr('class', 'btn-toggle btn-metadata') .text("Metadata"); metaBtn.on('click', function() { dispatcher.maptype('metadata'); }); resultsBtn.on('click', function() { dispatcher.maptype('results'); }); return el; }
function renderToggle(el) { var resultsBtn = el.append('button') .attr('class', 'btn-toggle btn-results') .text("Data"); var metaBtn = el.append('button') .attr('class', 'btn-toggle btn-metadata') .text("Metadata"); metaBtn.on('click', function() { dispatcher.maptype('metadata'); }); resultsBtn.on('click', function() { dispatcher.maptype('results'); }); return el; }
JavaScript
function showNewRect() { const ne = rectangle.getBounds().getNorthEast(); const sw = rectangle.getBounds().getSouthWest(); e = ne.lng() // North w = sw.lng() // South n = ne.lat() // East s = sw.lat() // West const contentString = "<b>Rectangle moved.</b><br>" + "New north-east corner: " + n + ", " + e + "<br>" + "New south-west corner: " + s + ", " + w; // Set the info window's content and position. infoWindow.setContent(contentString); infoWindow.setPosition(ne); infoWindow.open(map); var xhttpGeonames = new XMLHttpRequest(); xhttpGeonames.addEventListener('load', function() { if (this.readyState == 4 && this.status == 200) { if (typeof callBackLogainm === 'function') { callBackGeonames(xhttpGeonames.responseText); } } else { console.error('[Error] API request failed.'); } }); xhttpGeonames.open("GET", `https://jacobem.com/app/dri-location/api-2?n=${n}&s=${s}&e=${e}&w=${w}`, true); xhttpGeonames.send(); updateCode() }
function showNewRect() { const ne = rectangle.getBounds().getNorthEast(); const sw = rectangle.getBounds().getSouthWest(); e = ne.lng() // North w = sw.lng() // South n = ne.lat() // East s = sw.lat() // West const contentString = "<b>Rectangle moved.</b><br>" + "New north-east corner: " + n + ", " + e + "<br>" + "New south-west corner: " + s + ", " + w; // Set the info window's content and position. infoWindow.setContent(contentString); infoWindow.setPosition(ne); infoWindow.open(map); var xhttpGeonames = new XMLHttpRequest(); xhttpGeonames.addEventListener('load', function() { if (this.readyState == 4 && this.status == 200) { if (typeof callBackLogainm === 'function') { callBackGeonames(xhttpGeonames.responseText); } } else { console.error('[Error] API request failed.'); } }); xhttpGeonames.open("GET", `https://jacobem.com/app/dri-location/api-2?n=${n}&s=${s}&e=${e}&w=${w}`, true); xhttpGeonames.send(); updateCode() }
JavaScript
function updateCode() { const ne = rectangle.getBounds().getNorthEast(); const sw = rectangle.getBounds().getSouthWest(); country = getRelCountry(); if (!(country == "")) { e = ne.lng() // North w = sw.lng() // South n = ne.lat() // East s = sw.lat() // West // console.log({n, e, s, w}) if (window.regionOrCity == "region") { result.innerText = `<dcterms:spatial>name=${country}; northlimit=${n}; eastlimit=${e}; southlimit=${s}; westlimit=${w};</dcterms:spatial>`; } else { result.innerText = `<dcterms:spatial>name=${country}; north=${n}; east=${e};</dcterms:spatial>`; } result.innerText += window.logainm || ""; result.innerText += window.geonames || ""; } else { let result = document.querySelector('#result'); result.innerText = `Waiting for you to input the relevant region...`; } }
function updateCode() { const ne = rectangle.getBounds().getNorthEast(); const sw = rectangle.getBounds().getSouthWest(); country = getRelCountry(); if (!(country == "")) { e = ne.lng() // North w = sw.lng() // South n = ne.lat() // East s = sw.lat() // West // console.log({n, e, s, w}) if (window.regionOrCity == "region") { result.innerText = `<dcterms:spatial>name=${country}; northlimit=${n}; eastlimit=${e}; southlimit=${s}; westlimit=${w};</dcterms:spatial>`; } else { result.innerText = `<dcterms:spatial>name=${country}; north=${n}; east=${e};</dcterms:spatial>`; } result.innerText += window.logainm || ""; result.innerText += window.geonames || ""; } else { let result = document.querySelector('#result'); result.innerText = `Waiting for you to input the relevant region...`; } }
JavaScript
function parseDoc(doc, newEdits, dbOpts) { if (!dbOpts) { dbOpts = { deterministic_revs: true }; } var nRevNum; var newRevId; var revInfo; var opts = { status: 'available' }; if (doc._deleted) { opts.deleted = true; } if (newEdits) { if (!doc._id) { doc._id = pouchdbUtils.uuid(); } newRevId = pouchdbUtils.rev(doc, dbOpts.deterministic_revs); if (doc._rev) { revInfo = parseRevisionInfo(doc._rev); if (revInfo.error) { return revInfo; } doc._rev_tree = [{ pos: revInfo.prefix, ids: [revInfo.id, { status: 'missing' }, [[newRevId, opts, []]]] }]; nRevNum = revInfo.prefix + 1; } else { doc._rev_tree = [{ pos: 1, ids: [newRevId, opts, []] }]; nRevNum = 1; } } else { if (doc._revisions) { doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts); nRevNum = doc._revisions.start; newRevId = doc._revisions.ids[0]; } if (!doc._rev_tree) { revInfo = parseRevisionInfo(doc._rev); if (revInfo.error) { return revInfo; } nRevNum = revInfo.prefix; newRevId = revInfo.id; doc._rev_tree = [{ pos: nRevNum, ids: [newRevId, opts, []] }]; } } pouchdbUtils.invalidIdError(doc._id); doc._rev = nRevNum + '-' + newRevId; var result = { metadata: {}, data: {} }; for (var key in doc) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(doc, key)) { var specialKey = key[0] === '_'; if (specialKey && !reservedWords[key]) { var error = pouchdbErrors.createError(pouchdbErrors.DOC_VALIDATION, key); error.message = pouchdbErrors.DOC_VALIDATION.message + ': ' + key; throw error; } else if (specialKey && !dataWords[key]) { result.metadata[key.slice(1)] = doc[key]; } else { result.data[key] = doc[key]; } } } return result; }
function parseDoc(doc, newEdits, dbOpts) { if (!dbOpts) { dbOpts = { deterministic_revs: true }; } var nRevNum; var newRevId; var revInfo; var opts = { status: 'available' }; if (doc._deleted) { opts.deleted = true; } if (newEdits) { if (!doc._id) { doc._id = pouchdbUtils.uuid(); } newRevId = pouchdbUtils.rev(doc, dbOpts.deterministic_revs); if (doc._rev) { revInfo = parseRevisionInfo(doc._rev); if (revInfo.error) { return revInfo; } doc._rev_tree = [{ pos: revInfo.prefix, ids: [revInfo.id, { status: 'missing' }, [[newRevId, opts, []]]] }]; nRevNum = revInfo.prefix + 1; } else { doc._rev_tree = [{ pos: 1, ids: [newRevId, opts, []] }]; nRevNum = 1; } } else { if (doc._revisions) { doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts); nRevNum = doc._revisions.start; newRevId = doc._revisions.ids[0]; } if (!doc._rev_tree) { revInfo = parseRevisionInfo(doc._rev); if (revInfo.error) { return revInfo; } nRevNum = revInfo.prefix; newRevId = revInfo.id; doc._rev_tree = [{ pos: nRevNum, ids: [newRevId, opts, []] }]; } } pouchdbUtils.invalidIdError(doc._id); doc._rev = nRevNum + '-' + newRevId; var result = { metadata: {}, data: {} }; for (var key in doc) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(doc, key)) { var specialKey = key[0] === '_'; if (specialKey && !reservedWords[key]) { var error = pouchdbErrors.createError(pouchdbErrors.DOC_VALIDATION, key); error.message = pouchdbErrors.DOC_VALIDATION.message + ': ' + key; throw error; } else if (specialKey && !dataWords[key]) { result.metadata[key.slice(1)] = doc[key]; } else { result.data[key] = doc[key]; } } } return result; }
JavaScript
_patchHttpHandler() { if (this._debugEnabled) { process.env['FORCE_COLOR'] = true; const http = require('http'); const patch = require('monkeypatch'); const chalk = require('chalk'); const util = require('util'); patch(http, 'request', (requestUnpatched, options, cb) => { const req = requestUnpatched(options, cb); // Patch request.end function patch(req, 'end', (endUnpatched, data) => { this._log(chalk.red(`${req.method}`) + chalk.blue(` ${req.path}`)); const headers = req.getHeaders(); if (headers) this._log(chalk.green("HEADERS: ") + chalk.green(util.inspect(headers, {depth: 5}))); if (data) this._log(chalk.gray(util.inspect(data, {depth: 5}))); if (req.output) this._log(chalk.gray(util.inspect(req.output, {depth: 5}))); return endUnpatched(data); }); // Patch response data function req.on('response', resp => { const headers = resp ? resp.headers : {}; resp.on('data', data => { this._log(chalk.red("RESPONSE") + chalk.blue(` ${req.path}`)); if (headers) this._log(chalk.green("HEADERS: ") + chalk.green(util.inspect(headers, {depth: 5}))); if (data instanceof Buffer) { this._log(chalk.gray(util.inspect(data.toString('utf8'), {depth: 5}))); } else { this._log(chalk.gray(util.inspect(data, {depth: 5}))); } }); }); return req; }); } }
_patchHttpHandler() { if (this._debugEnabled) { process.env['FORCE_COLOR'] = true; const http = require('http'); const patch = require('monkeypatch'); const chalk = require('chalk'); const util = require('util'); patch(http, 'request', (requestUnpatched, options, cb) => { const req = requestUnpatched(options, cb); // Patch request.end function patch(req, 'end', (endUnpatched, data) => { this._log(chalk.red(`${req.method}`) + chalk.blue(` ${req.path}`)); const headers = req.getHeaders(); if (headers) this._log(chalk.green("HEADERS: ") + chalk.green(util.inspect(headers, {depth: 5}))); if (data) this._log(chalk.gray(util.inspect(data, {depth: 5}))); if (req.output) this._log(chalk.gray(util.inspect(req.output, {depth: 5}))); return endUnpatched(data); }); // Patch response data function req.on('response', resp => { const headers = resp ? resp.headers : {}; resp.on('data', data => { this._log(chalk.red("RESPONSE") + chalk.blue(` ${req.path}`)); if (headers) this._log(chalk.green("HEADERS: ") + chalk.green(util.inspect(headers, {depth: 5}))); if (data instanceof Buffer) { this._log(chalk.gray(util.inspect(data.toString('utf8'), {depth: 5}))); } else { this._log(chalk.gray(util.inspect(data, {depth: 5}))); } }); }); return req; }); } }
JavaScript
async initialize({code, redirectUri, token}) { // Install http debug output handler if debug output enabled this._patchHttpHandler(); this._workspaceClient = new workspace.ApiClient(); this._workspaceClient.basePath = this._workspaceUrl; this._workspaceClient.enableCookies = true; this.cookieJar = this._workspaceClient.agent.jar; if (this.apiKey) { this._workspaceClient.defaultHeaders = {'x-api-key': this.apiKey}; } this._sessionApi = new workspace.SessionApi(this._workspaceClient); this.voice = new VoiceApi(this, this._workspaceClient, this._debugEnabled); this.targets = new TargetsApi(this._workspaceClient, this._debugEnabled); this.reporting = new ReportingApi(this._workspaceClient, this._debugEnabled); this.chat = new ChatApi(this._workspaceClient, this._debugEnabled); this.media = new MediaApi(this._workspaceClient, this._debugEnabled); let options = {}; if (code) { options.code = code; options.redirectUri = redirectUri; } else if (token) { options.authorization = 'Bearer ' + token; } this._log('Initializing workspace...'); let response = await this._sessionApi.initializeWorkspaceWithHttpInfo(options); this._sessionCookie = response.response.header['set-cookie'].find(v => v.startsWith('WORKSPACE_SESSIONID')); this._patchSecureCookieFlag(this._sessionCookie); this._log('WORKSPACE_SESSIONID is: ' + this._sessionCookie); let data = await this._initializeCometd(); this.user = data.user; this.configuration = data.configuration; this._log('Initialization complete.'); this._initialized = true; }
async initialize({code, redirectUri, token}) { // Install http debug output handler if debug output enabled this._patchHttpHandler(); this._workspaceClient = new workspace.ApiClient(); this._workspaceClient.basePath = this._workspaceUrl; this._workspaceClient.enableCookies = true; this.cookieJar = this._workspaceClient.agent.jar; if (this.apiKey) { this._workspaceClient.defaultHeaders = {'x-api-key': this.apiKey}; } this._sessionApi = new workspace.SessionApi(this._workspaceClient); this.voice = new VoiceApi(this, this._workspaceClient, this._debugEnabled); this.targets = new TargetsApi(this._workspaceClient, this._debugEnabled); this.reporting = new ReportingApi(this._workspaceClient, this._debugEnabled); this.chat = new ChatApi(this._workspaceClient, this._debugEnabled); this.media = new MediaApi(this._workspaceClient, this._debugEnabled); let options = {}; if (code) { options.code = code; options.redirectUri = redirectUri; } else if (token) { options.authorization = 'Bearer ' + token; } this._log('Initializing workspace...'); let response = await this._sessionApi.initializeWorkspaceWithHttpInfo(options); this._sessionCookie = response.response.header['set-cookie'].find(v => v.startsWith('WORKSPACE_SESSIONID')); this._patchSecureCookieFlag(this._sessionCookie); this._log('WORKSPACE_SESSIONID is: ' + this._sessionCookie); let data = await this._initializeCometd(); this.user = data.user; this.configuration = data.configuration; this._log('Initialization complete.'); this._initialized = true; }
JavaScript
async destroy() { if (this._initialized) { if (this._cometd) { this._log('Disconnecting cometd...'); this._cometd.disconnect(); } this._log('Logging out...'); await this._sessionApi.logout(); this._initialized = false; } }
async destroy() { if (this._initialized) { if (this._cometd) { this._log('Disconnecting cometd...'); this._cometd.disconnect(); } this._log('Logging out...'); await this._sessionApi.logout(); this._initialized = false; } }
JavaScript
async activateChannels(agentId, dn, placeName) { let data = {data: {}}; if (agentId) { data.data.agentId = agentId; } else if (this.user && this.user.agentLogin) { data.data.agentId = this.user.agentLogin; } else if (this.user && this.user.employeeId) { data.data.agentId = this.user.employeeId; } else { throw new Error('agentId was not provided and no default login could be found.'); } if (dn) { data.data.dn = dn; } else if (placeName) { data.data.placeName = placeName; } else if (this.user && this.user.defaultPlace) { data.data.placeName = this.user.defaultPlace; } else { throw new Error('No dn or placeName was provided and no default could be found.'); } this._log(`Sending activate-channels with: ${JSON.stringify(data)}`); return await this._sessionApi.activateChannels(data); }
async activateChannels(agentId, dn, placeName) { let data = {data: {}}; if (agentId) { data.data.agentId = agentId; } else if (this.user && this.user.agentLogin) { data.data.agentId = this.user.agentLogin; } else if (this.user && this.user.employeeId) { data.data.agentId = this.user.employeeId; } else { throw new Error('agentId was not provided and no default login could be found.'); } if (dn) { data.data.dn = dn; } else if (placeName) { data.data.placeName = placeName; } else if (this.user && this.user.defaultPlace) { data.data.placeName = this.user.defaultPlace; } else { throw new Error('No dn or placeName was provided and no default could be found.'); } this._log(`Sending activate-channels with: ${JSON.stringify(data)}`); return await this._sessionApi.activateChannels(data); }
JavaScript
async search(searchTerm, limit) { this._log(`Searching targets with searchTerm [${searchTerm}]...`); const response = await this._api.getTargets(searchTerm, { limit: limit || 10 }); return response.data.targets; }
async search(searchTerm, limit) { this._log(`Searching targets with searchTerm [${searchTerm}]...`); const response = await this._api.getTargets(searchTerm, { limit: limit || 10 }); return response.data.targets; }
JavaScript
async addRecentTarget(target, media) { const resp = await this._api.addRecentTargetWithHttpInfo({ data: { target: target, recentInformation: { media: media } } }); return resp.response.body; }
async addRecentTarget(target, media) { const resp = await this._api.addRecentTargetWithHttpInfo({ data: { target: target, recentInformation: { media: media } } }); return resp.response.body; }
JavaScript
async savePersonalFavorite(target, category) { return this._api.savePersonalFavorite({ data: { target: target, category: category } }); }
async savePersonalFavorite(target, category) { return this._api.savePersonalFavorite({ data: { target: target, category: category } }); }
JavaScript
_onInteractionStateChanged(cometdMsg) { let interactionData = cometdMsg.data.interaction; let chatId = interactionData.id; // Add chat information this.chats[chatId] = interactionData; let msg = { id: chatId, data: interactionData, notificationType: cometdMsg.data.notificationType}; this._eventEmitter.emit('InteractionStateChanged', msg); }
_onInteractionStateChanged(cometdMsg) { let interactionData = cometdMsg.data.interaction; let chatId = interactionData.id; // Add chat information this.chats[chatId] = interactionData; let msg = { id: chatId, data: interactionData, notificationType: cometdMsg.data.notificationType}; this._eventEmitter.emit('InteractionStateChanged', msg); }
JavaScript
async sendCustomNotification(chatId, mediaType, message, optional) { let data = { message: message }; data = Object.assign(data, optional); this._log(`Sending custom notification [${message}] for chat [${chatId}]...`); return await this._chatApi.sendCustomNotification(mediaType, chatId, {customNotificationData: {data: data}}); }
async sendCustomNotification(chatId, mediaType, message, optional) { let data = { message: message }; data = Object.assign(data, optional); this._log(`Sending custom notification [${message}] for chat [${chatId}]...`); return await this._chatApi.sendCustomNotification(mediaType, chatId, {customNotificationData: {data: data}}); }
JavaScript
async sendMessage(chatId, mediaType, message, optional) { let data = { message: message }; data = Object.assign(data, optional); this._log(`Sending message [${message}] for chat [${chatId}] members...`); return await this._chatApi.sendMessage(chatId, mediaType, {acceptData: {data: data}}); }
async sendMessage(chatId, mediaType, message, optional) { let data = { message: message }; data = Object.assign(data, optional); this._log(`Sending message [${message}] for chat [${chatId}] members...`); return await this._chatApi.sendMessage(chatId, mediaType, {acceptData: {data: data}}); }
JavaScript
async sendUrlData(chatId, mediaType, url, optional) { let data = { url: url }; data = Object.assign(data, optional); this._log(`Sending url [${url}] for chat [${chatId}] members...`); return await this._chatApi.sendUrlData(chatId, mediaType, {acceptData: {data: data}}); }
async sendUrlData(chatId, mediaType, url, optional) { let data = { url: url }; data = Object.assign(data, optional); this._log(`Sending url [${url}] for chat [${chatId}] members...`); return await this._chatApi.sendUrlData(chatId, mediaType, {acceptData: {data: data}}); }
JavaScript
async chatMessages(chatId, mediaType) { this._log(`Getting chat transcript [${chatId}]...`); const response = await this._chatApi.chatMessages(mediaType, chatId); return response.data.messages; }
async chatMessages(chatId, mediaType) { this._log(`Getting chat transcript [${chatId}]...`); const response = await this._chatApi.chatMessages(mediaType, chatId); return response.data.messages; }
JavaScript
function toggleMassEditForm(){ const massEditForm = document.getElementById("mass_edit_container"); massEditForm.previousElementSibling.style.display = massEditForm.previousElementSibling.style.display == "none" ? "block" : "none"; massEditForm.style.display = massEditForm.style.display == "none" ? "flex" : "none"; }
function toggleMassEditForm(){ const massEditForm = document.getElementById("mass_edit_container"); massEditForm.previousElementSibling.style.display = massEditForm.previousElementSibling.style.display == "none" ? "block" : "none"; massEditForm.style.display = massEditForm.style.display == "none" ? "flex" : "none"; }
JavaScript
function parseChapterList(){ // mod tab is parsed through the inline edit form const parsedChapters = new Map(); const unparsedElements = [...getChapterTable().getElementsByTagName("tbody")[0].getElementsByTagName("tr")]; while(unparsedElements.length > 0){ // throw away the chapter element and get the inputs from the inline edit element unparsedElements.shift(); const inlineEdit = unparsedElements.shift(); const chapterID = inlineEdit.getElementsByClassName("btn btn-sm btn-danger mass_edit_delete_button")[0].id; const infoFields = inlineEdit.getElementsByTagName("input"); parsedChapters.set(chapterID, { "manga_id": infoFields[0].value, "volume_number": infoFields[1].value, "chapter_number": infoFields[2].value, "chapter_title": infoFields[3].value, "language_id": infoFields[4].value, "group_id": infoFields[5].value, "group_2_id": infoFields[6].value, "group_3_id": infoFields[7].value, "uploader_id": infoFields[8].value, "availability": infoFields[9].checked ? "0" : "1", "file": "", }); } return parsedChapters; }
function parseChapterList(){ // mod tab is parsed through the inline edit form const parsedChapters = new Map(); const unparsedElements = [...getChapterTable().getElementsByTagName("tbody")[0].getElementsByTagName("tr")]; while(unparsedElements.length > 0){ // throw away the chapter element and get the inputs from the inline edit element unparsedElements.shift(); const inlineEdit = unparsedElements.shift(); const chapterID = inlineEdit.getElementsByClassName("btn btn-sm btn-danger mass_edit_delete_button")[0].id; const infoFields = inlineEdit.getElementsByTagName("input"); parsedChapters.set(chapterID, { "manga_id": infoFields[0].value, "volume_number": infoFields[1].value, "chapter_number": infoFields[2].value, "chapter_title": infoFields[3].value, "language_id": infoFields[4].value, "group_id": infoFields[5].value, "group_2_id": infoFields[6].value, "group_3_id": infoFields[7].value, "uploader_id": infoFields[8].value, "availability": infoFields[9].checked ? "0" : "1", "file": "", }); } return parsedChapters; }
JavaScript
function loadExperimentsList() { $http.get(base_path + '/expression/experiments', {headers: {"Accept": "application/json"}}).success(function (data) { $scope.availableExperiments = data.items; }) }
function loadExperimentsList() { $http.get(base_path + '/expression/experiments', {headers: {"Accept": "application/json"}}).success(function (data) { $scope.availableExperiments = data.items; }) }
JavaScript
function dispalyThreeImages() { leftIndex=generateRandomIndex(); RightIndex=generateRandomIndex(); MiddleIndex=generateRandomIndex(); console.log(leftIndex); console.log(MiddleIndex); console.log(RightIndex); while (leftIndex===RightIndex || leftIndex===MiddleIndex || RightIndex===MiddleIndex || newArr.includes(leftIndex) || newArr.includes(RightIndex) || newArr.includes(MiddleIndex)){ leftIndex=generateRandomIndex(); RightIndex=generateRandomIndex(); MiddleIndex=generateRandomIndex(); } newArr=[leftIndex,RightIndex,MiddleIndex]; console.log(newArr); leftImageElement.src= BusMall.all[leftIndex].source; BusMall.all[leftIndex].shown++; rightImageElement.src=BusMall.all[RightIndex].source; BusMall.all[RightIndex].shown++; middleImageElement.src=BusMall.all[MiddleIndex].source; BusMall.all[MiddleIndex].shown++; }
function dispalyThreeImages() { leftIndex=generateRandomIndex(); RightIndex=generateRandomIndex(); MiddleIndex=generateRandomIndex(); console.log(leftIndex); console.log(MiddleIndex); console.log(RightIndex); while (leftIndex===RightIndex || leftIndex===MiddleIndex || RightIndex===MiddleIndex || newArr.includes(leftIndex) || newArr.includes(RightIndex) || newArr.includes(MiddleIndex)){ leftIndex=generateRandomIndex(); RightIndex=generateRandomIndex(); MiddleIndex=generateRandomIndex(); } newArr=[leftIndex,RightIndex,MiddleIndex]; console.log(newArr); leftImageElement.src= BusMall.all[leftIndex].source; BusMall.all[leftIndex].shown++; rightImageElement.src=BusMall.all[RightIndex].source; BusMall.all[RightIndex].shown++; middleImageElement.src=BusMall.all[MiddleIndex].source; BusMall.all[MiddleIndex].shown++; }
JavaScript
function handleClicking(event){ clickingNumber++; console.log(event.target.id); if (rounds >= clickingNumber){ if(event.target.id==='leftimage'){ BusMall.all[leftIndex].votes++; dispalyThreeImages(); }else if (event.target.id==='rightimage'){ BusMall.all[RightIndex].votes++; dispalyThreeImages(); }else if (event.target.id==='middleimage'){ BusMall.all[MiddleIndex].votes++; console.log(clickingNumber); dispalyThreeImages(); }}else if (clickingNumber===25){ button(); } else { leftImageElement.removeEventListener('click',handleClicking); rightImageElement.removeEventListener('click',handleClicking); middleImageElement.removeEventListener('click',handleClicking); savingData(); } }
function handleClicking(event){ clickingNumber++; console.log(event.target.id); if (rounds >= clickingNumber){ if(event.target.id==='leftimage'){ BusMall.all[leftIndex].votes++; dispalyThreeImages(); }else if (event.target.id==='rightimage'){ BusMall.all[RightIndex].votes++; dispalyThreeImages(); }else if (event.target.id==='middleimage'){ BusMall.all[MiddleIndex].votes++; console.log(clickingNumber); dispalyThreeImages(); }}else if (clickingNumber===25){ button(); } else { leftImageElement.removeEventListener('click',handleClicking); rightImageElement.removeEventListener('click',handleClicking); middleImageElement.removeEventListener('click',handleClicking); savingData(); } }
JavaScript
function list(){ ul.textContent = '' ; for (let i=0 ;i < BusMall.all.length;i++){ arrOfShown.push(BusMall.all[i].shown); arrOfVotes.push(BusMall.all[i].votes); let li=document.createElement('li'); ul.appendChild(li); li.textContent = `${BusMall.all[i].name} has ${BusMall.all[i].votes} Votes and has ${BusMall.all[i].shown} shown .`; ul.appendChild(li); } }
function list(){ ul.textContent = '' ; for (let i=0 ;i < BusMall.all.length;i++){ arrOfShown.push(BusMall.all[i].shown); arrOfVotes.push(BusMall.all[i].votes); let li=document.createElement('li'); ul.appendChild(li); li.textContent = `${BusMall.all[i].name} has ${BusMall.all[i].votes} Votes and has ${BusMall.all[i].shown} shown .`; ul.appendChild(li); } }
JavaScript
function Calculate(initInv,Years,avgReturn,InvYearly){ var money = parseInt(initInv); var avgreturn = parseInt(avgReturn); var extramoneyYearly = parseInt(InvYearly); var yearsInvesting = parseInt(Years); var count = yearsInvesting; while (count > 0){ count = count -1; money = money + extramoneyYearly + (money*avgreturn)/100 ; } return money; }
function Calculate(initInv,Years,avgReturn,InvYearly){ var money = parseInt(initInv); var avgreturn = parseInt(avgReturn); var extramoneyYearly = parseInt(InvYearly); var yearsInvesting = parseInt(Years); var count = yearsInvesting; while (count > 0){ count = count -1; money = money + extramoneyYearly + (money*avgreturn)/100 ; } return money; }
JavaScript
render(renderer, inputBuffer, outputBuffer, deltaTime, stencilTest) { const overrideClearColor = this.overrideClearColor; const overrideClearAlpha = this.overrideClearAlpha; const clearAlpha = renderer.getClearAlpha(); const hasOverrideClearColor = (overrideClearColor !== null); const hasOverrideClearAlpha = (overrideClearAlpha >= 0.0); if(hasOverrideClearColor) { color.copy(renderer.getClearColor()); renderer.setClearColor(overrideClearColor, hasOverrideClearAlpha ? overrideClearAlpha : clearAlpha); } else if(hasOverrideClearAlpha) { renderer.setClearAlpha(overrideClearAlpha); } renderer.setRenderTarget(this.renderToScreen ? null : inputBuffer); renderer.clear(this.color, this.depth, this.stencil); if(hasOverrideClearColor) { renderer.setClearColor(color, clearAlpha); } else if(hasOverrideClearAlpha) { renderer.setClearAlpha(clearAlpha); } }
render(renderer, inputBuffer, outputBuffer, deltaTime, stencilTest) { const overrideClearColor = this.overrideClearColor; const overrideClearAlpha = this.overrideClearAlpha; const clearAlpha = renderer.getClearAlpha(); const hasOverrideClearColor = (overrideClearColor !== null); const hasOverrideClearAlpha = (overrideClearAlpha >= 0.0); if(hasOverrideClearColor) { color.copy(renderer.getClearColor()); renderer.setClearColor(overrideClearColor, hasOverrideClearAlpha ? overrideClearAlpha : clearAlpha); } else if(hasOverrideClearAlpha) { renderer.setClearAlpha(overrideClearAlpha); } renderer.setRenderTarget(this.renderToScreen ? null : inputBuffer); renderer.clear(this.color, this.depth, this.stencil); if(hasOverrideClearColor) { renderer.setClearColor(color, clearAlpha); } else if(hasOverrideClearAlpha) { renderer.setClearAlpha(clearAlpha); } }
JavaScript
load() { const assets = this.assets; const loadingManager = this.loadingManager; const cubeTextureLoader = new CubeTextureLoader(loadingManager); const path = "textures/skies/space3/"; const format = ".jpg"; const urls = [ path + "px" + format, path + "nx" + format, path + "py" + format, path + "ny" + format, path + "pz" + format, path + "nz" + format ]; return new Promise((resolve, reject) => { if(assets.size === 0) { loadingManager.onError = reject; loadingManager.onProgress = (item, loaded, total) => { if(loaded === total) { resolve(); } }; cubeTextureLoader.load(urls, function(textureCube) { assets.set("sky", textureCube); }); this.loadSMAAImages(); } else { resolve(); } }); }
load() { const assets = this.assets; const loadingManager = this.loadingManager; const cubeTextureLoader = new CubeTextureLoader(loadingManager); const path = "textures/skies/space3/"; const format = ".jpg"; const urls = [ path + "px" + format, path + "nx" + format, path + "py" + format, path + "ny" + format, path + "pz" + format, path + "nz" + format ]; return new Promise((resolve, reject) => { if(assets.size === 0) { loadingManager.onError = reject; loadingManager.onProgress = (item, loaded, total) => { if(loaded === total) { resolve(); } }; cubeTextureLoader.load(urls, function(textureCube) { assets.set("sky", textureCube); }); this.loadSMAAImages(); } else { resolve(); } }); }
JavaScript
static fromJSON(json) { const { polarRadius, polarTheta, polarPhi, velocityTheta, isEnabled = true, } = json; return new PolarVelocity( new Polar3D(polarRadius, polarTheta, polarPhi), velocityTheta, isEnabled ); }
static fromJSON(json) { const { polarRadius, polarTheta, polarPhi, velocityTheta, isEnabled = true, } = json; return new PolarVelocity( new Polar3D(polarRadius, polarTheta, polarPhi), velocityTheta, isEnabled ); }
JavaScript
load() { const assets = this.assets; const loadingManager = this.loadingManager; const cubeTextureLoader = new CubeTextureLoader(loadingManager); const textureLoader = new TextureLoader(loadingManager); const modelLoader = new GLTFLoader(loadingManager); const path = "textures/skies/starry/"; const format = ".png"; const urls = [ path + "px" + format, path + "nx" + format, path + "py" + format, path + "ny" + format, path + "pz" + format, path + "nz" + format ]; return new Promise((resolve, reject) => { if(assets.size === 0) { loadingManager.onError = reject; loadingManager.onProgress = (item, loaded, total) => { if(loaded === total) { resolve(); } }; cubeTextureLoader.load(urls, function(textureCube) { assets.set("sky", textureCube); }); modelLoader.load("models/tree/scene.gltf", function(gltf) { gltf.scene.scale.multiplyScalar(2.5); gltf.scene.position.set(0, -2.3, 0); gltf.scene.rotation.set(0, 3, 0); assets.set("model", gltf.scene); }); textureLoader.load("textures/sun.png", function(texture) { assets.set("sun-diffuse", texture); }); this.loadSMAAImages(); } else { resolve(); } }); }
load() { const assets = this.assets; const loadingManager = this.loadingManager; const cubeTextureLoader = new CubeTextureLoader(loadingManager); const textureLoader = new TextureLoader(loadingManager); const modelLoader = new GLTFLoader(loadingManager); const path = "textures/skies/starry/"; const format = ".png"; const urls = [ path + "px" + format, path + "nx" + format, path + "py" + format, path + "ny" + format, path + "pz" + format, path + "nz" + format ]; return new Promise((resolve, reject) => { if(assets.size === 0) { loadingManager.onError = reject; loadingManager.onProgress = (item, loaded, total) => { if(loaded === total) { resolve(); } }; cubeTextureLoader.load(urls, function(textureCube) { assets.set("sky", textureCube); }); modelLoader.load("models/tree/scene.gltf", function(gltf) { gltf.scene.scale.multiplyScalar(2.5); gltf.scene.position.set(0, -2.3, 0); gltf.scene.rotation.set(0, 3, 0); assets.set("model", gltf.scene); }); textureLoader.load("textures/sun.png", function(texture) { assets.set("sun-diffuse", texture); }); this.loadSMAAImages(); } else { resolve(); } }); }
JavaScript
update(renderer, inputBuffer, deltaTime) { const renderTarget = this.renderTarget; this.luminancePass.render(renderer, inputBuffer, renderTarget); this.blurPass.render(renderer, renderTarget, renderTarget); }
update(renderer, inputBuffer, deltaTime) { const renderTarget = this.renderTarget; this.luminancePass.render(renderer, inputBuffer, renderTarget); this.blurPass.render(renderer, renderTarget, renderTarget); }
JavaScript
initialize(renderer, alpha) { this.blurPass.initialize(renderer, alpha); if(!alpha) { this.renderTarget.texture.format = RGBFormat; } }
initialize(renderer, alpha) { this.blurPass.initialize(renderer, alpha); if(!alpha) { this.renderTarget.texture.format = RGBFormat; } }
JavaScript
initialize(particle) { particle.transform.scaleA = this.scaleA.getValue(); particle.transform.oldRadius = particle.radius; particle.transform.scaleB = this.same ? particle.transform.scaleA : this.scaleB.getValue(); }
initialize(particle) { particle.transform.scaleA = this.scaleA.getValue(); particle.transform.oldRadius = particle.radius; particle.transform.scaleB = this.same ? particle.transform.scaleA : this.scaleB.getValue(); }
JavaScript
mutate(particle, time, index) { this.energize(particle, time, index); particle.scale = MathUtils.lerp( particle.transform.scaleA, particle.transform.scaleB, this.energy ); if (particle.scale < 0.0005) { particle.scale = 0; } particle.radius = particle.transform.oldRadius * particle.scale; }
mutate(particle, time, index) { this.energize(particle, time, index); particle.scale = MathUtils.lerp( particle.transform.scaleA, particle.transform.scaleB, this.energy ); if (particle.scale < 0.0005) { particle.scale = 0; } particle.radius = particle.transform.oldRadius * particle.scale; }
JavaScript
static fromJSON(json) { const { scaleA, scaleB, life, easing, isEnabled = true } = json; return new Scale(scaleA, scaleB, life, getEasingByName(easing), isEnabled); }
static fromJSON(json) { const { scaleA, scaleB, life, easing, isEnabled = true } = json; return new Scale(scaleA, scaleB, life, getEasingByName(easing), isEnabled); }
JavaScript
initialize(particle) { var body = this.body.getValue(); if (this.w) { particle.body = { width: this.w, height: this.h, body: body, }; } else { particle.body = body; } }
initialize(particle) { var body = this.body.getValue(); if (this.w) { particle.body = { width: this.w, height: this.h, body: body, }; } else { particle.body = body; } }
JavaScript
render(delta) { // Let the effect composer take care of rendering. this.composer.render(delta); }
render(delta) { // Let the effect composer take care of rendering. this.composer.render(delta); }
JavaScript
dispose() { const material = this.getFullscreenMaterial(); if(material !== null) { material.dispose(); } for(const key of Object.keys(this)) { if(this[key] !== null && typeof this[key].dispose === "function") { /** @ignore */ this[key].dispose(); } } }
dispose() { const material = this.getFullscreenMaterial(); if(material !== null) { material.dispose(); } for(const key of Object.keys(this)) { if(this[key] !== null && typeof this[key].dispose === "function") { /** @ignore */ this[key].dispose(); } } }
JavaScript
function dataset(element) { if (element === window) { return windowData; } return element.dataset; }
function dataset(element) { if (element === window) { return windowData; } return element.dataset; }
JavaScript
function on(element, evnt, handler) { // Extract the event name from the event (the event can include a namespace (click.foo)). var evntName = evnt.split('.')[0]; // Add a new ID to the list of IDs for the event for the element. var id = uniqueId; var ids = getIDs(element, evnt); ids.push('' + id); setIDs(element, evnt, ids); // Store the handler so it can be removed with the "off" function. listeners[id] = handler; // Add the event listener. element.addEventListener(evntName, handler); // Keep the ID unique. uniqueId++; }
function on(element, evnt, handler) { // Extract the event name from the event (the event can include a namespace (click.foo)). var evntName = evnt.split('.')[0]; // Add a new ID to the list of IDs for the event for the element. var id = uniqueId; var ids = getIDs(element, evnt); ids.push('' + id); setIDs(element, evnt, ids); // Store the handler so it can be removed with the "off" function. listeners[id] = handler; // Add the event listener. element.addEventListener(evntName, handler); // Keep the ID unique. uniqueId++; }
JavaScript
function off(element, evnt) { // Extract the event name from the event (the event can include a namespace (click.foo)). var evntName = evnt.split('.')[0]; // Get the list of IDs for the event for the element. var ids = getIDs(element, evnt); ids.forEach(id => { // Remove the event listener. element.removeEventListener(evntName, listeners[id]); // Delete the stored handler. delete listeners[id]; }); // Delete the list of IDs for the event for the element. delete dataset(element)[evnt]; }
function off(element, evnt) { // Extract the event name from the event (the event can include a namespace (click.foo)). var evntName = evnt.split('.')[0]; // Get the list of IDs for the event for the element. var ids = getIDs(element, evnt); ids.forEach(id => { // Remove the event listener. element.removeEventListener(evntName, listeners[id]); // Delete the stored handler. delete listeners[id]; }); // Delete the list of IDs for the event for the element. delete dataset(element)[evnt]; }
JavaScript
function trigger(element, evnt, options) { var ids = getIDs(element, evnt); ids.forEach(id => { // Invoke the stored handler. listeners[id](options || {}); }); }
function trigger(element, evnt, options) { var ids = getIDs(element, evnt); ids.forEach(id => { // Invoke the stored handler. listeners[id](options || {}); }); }
JavaScript
static fromJSON(json) { const { x, y, z, force, radius, life, easing, isEnabled = true } = json; return new Repulsion( new Vector3D(x, y, z), force, radius, life, getEasingByName(easing), isEnabled ); }
static fromJSON(json) { const { x, y, z, force, radius, life, easing, isEnabled = true } = json; return new Repulsion( new Vector3D(x, y, z), force, radius, life, getEasingByName(easing), isEnabled ); }
JavaScript
render(delta) { const objectA = this.objectA; const objectB = this.objectB; const objectC = this.objectC; const twoPI = 2.0 * Math.PI; objectA.rotation.x += 0.0005; objectA.rotation.y += 0.001; objectB.rotation.copy(objectA.rotation); objectC.rotation.copy(objectA.rotation); if(objectA.rotation.x >= twoPI) { objectA.rotation.x -= twoPI; } if(objectA.rotation.y >= twoPI) { objectA.rotation.y -= twoPI; } super.render(delta); }
render(delta) { const objectA = this.objectA; const objectB = this.objectB; const objectC = this.objectC; const twoPI = 2.0 * Math.PI; objectA.rotation.x += 0.0005; objectA.rotation.y += 0.001; objectB.rotation.copy(objectA.rotation); objectC.rotation.copy(objectA.rotation); if(objectA.rotation.x >= twoPI) { objectA.rotation.x -= twoPI; } if(objectA.rotation.y >= twoPI) { objectA.rotation.y -= twoPI; } super.render(delta); }
JavaScript
load() { const assets = this.assets; const loadingManager = this.loadingManager; const cubeTextureLoader = new CubeTextureLoader(loadingManager); const path = "textures/skies/sunset/"; const format = ".png"; const urls = [ path + "px" + format, path + "nx" + format, path + "py" + format, path + "ny" + format, path + "pz" + format, path + "nz" + format ]; return new Promise((resolve, reject) => { if(assets.size === 0) { loadingManager.onError = reject; loadingManager.onProgress = (item, loaded, total) => { if(loaded === total) { resolve(); } }; cubeTextureLoader.load(urls, function(textureCube) { assets.set("sky", textureCube); }); this.loadSMAAImages(); } else { resolve(); } }); }
load() { const assets = this.assets; const loadingManager = this.loadingManager; const cubeTextureLoader = new CubeTextureLoader(loadingManager); const path = "textures/skies/sunset/"; const format = ".png"; const urls = [ path + "px" + format, path + "nx" + format, path + "py" + format, path + "ny" + format, path + "pz" + format, path + "nz" + format ]; return new Promise((resolve, reject) => { if(assets.size === 0) { loadingManager.onError = reject; loadingManager.onProgress = (item, loaded, total) => { if(loaded === total) { resolve(); } }; cubeTextureLoader.load(urls, function(textureCube) { assets.set("sky", textureCube); }); this.loadSMAAImages(); } else { resolve(); } }); }
JavaScript
initialize(particle) { switch (this.rotationType) { case 'same': break; case 'set': this._setRotation(particle.rotation, this.x); break; case 'to': particle.transform.fR = particle.transform.fR || new Vector3D(); particle.transform.tR = particle.transform.tR || new Vector3D(); this._setRotation(particle.transform.fR, this.x); this._setRotation(particle.transform.tR, this.y); break; case 'add': particle.transform.addR = new Vector3D( this.x.getValue(), this.y.getValue(), this.z.getValue() ); break; } }
initialize(particle) { switch (this.rotationType) { case 'same': break; case 'set': this._setRotation(particle.rotation, this.x); break; case 'to': particle.transform.fR = particle.transform.fR || new Vector3D(); particle.transform.tR = particle.transform.tR || new Vector3D(); this._setRotation(particle.transform.fR, this.x); this._setRotation(particle.transform.tR, this.y); break; case 'add': particle.transform.addR = new Vector3D( this.x.getValue(), this.y.getValue(), this.z.getValue() ); break; } }
JavaScript
_setRotation(particleRotation, value) { particleRotation = particleRotation || new Vector3D(); if (value == 'random') { var x = MathUtils.randomAToB(-PI, PI); var y = MathUtils.randomAToB(-PI, PI); var z = MathUtils.randomAToB(-PI, PI); particleRotation.set(x, y, z); } // we can't ever get here because value will never be a Vector3D! // consider refactoring to // if (value instance of Span) { vec3.add(value.getValue()); } else if (value instanceof Vector3D) { particleRotation.copy(value); } }
_setRotation(particleRotation, value) { particleRotation = particleRotation || new Vector3D(); if (value == 'random') { var x = MathUtils.randomAToB(-PI, PI); var y = MathUtils.randomAToB(-PI, PI); var z = MathUtils.randomAToB(-PI, PI); particleRotation.set(x, y, z); } // we can't ever get here because value will never be a Vector3D! // consider refactoring to // if (value instance of Span) { vec3.add(value.getValue()); } else if (value instanceof Vector3D) { particleRotation.copy(value); } }
JavaScript
mutate(particle, time, index) { const particles = this.emitter ? this.emitter.particles.slice(index) : this.particles.slice(index); let otherParticle, lengthSq, overlap, distance, averageMass1, averageMass2; let i = particles.length; while (i--) { otherParticle = particles[i]; if (otherParticle == particle) { continue; } this.delta.copy(otherParticle.position).sub(particle.position); lengthSq = this.delta.lengthSq(); distance = particle.radius + otherParticle.radius; if (lengthSq <= distance * distance) { overlap = distance - Math.sqrt(lengthSq); overlap += 0.5; averageMass1 = this._getAverageMass(particle, otherParticle); averageMass2 = this._getAverageMass(otherParticle, particle); particle.position.add( this.delta .clone() .normalize() .scalar(overlap * -averageMass1) ); otherParticle.position.add( this.delta.normalize().scalar(overlap * averageMass2) ); this.onCollide && this.onCollide(particle, otherParticle); } } }
mutate(particle, time, index) { const particles = this.emitter ? this.emitter.particles.slice(index) : this.particles.slice(index); let otherParticle, lengthSq, overlap, distance, averageMass1, averageMass2; let i = particles.length; while (i--) { otherParticle = particles[i]; if (otherParticle == particle) { continue; } this.delta.copy(otherParticle.position).sub(particle.position); lengthSq = this.delta.lengthSq(); distance = particle.radius + otherParticle.radius; if (lengthSq <= distance * distance) { overlap = distance - Math.sqrt(lengthSq); overlap += 0.5; averageMass1 = this._getAverageMass(particle, otherParticle); averageMass2 = this._getAverageMass(otherParticle, particle); particle.position.add( this.delta .clone() .normalize() .scalar(overlap * -averageMass1) ); otherParticle.position.add( this.delta.normalize().scalar(overlap * averageMass2) ); this.onCollide && this.onCollide(particle, otherParticle); } } }
JavaScript
mutate(particle, time, index) { this.energize(particle, time, index); this.zone.crossing.call(this.zone, particle); }
mutate(particle, time, index) { this.energize(particle, time, index); this.zone.crossing.call(this.zone, particle); }
JavaScript
static fromJSON(json) { const { zoneType, zoneParams, crossType, life, easing, isEnabled = true, } = json; const zone = new Zone[zoneType](...Object.values(zoneParams)); return new CrossZone( zone, crossType, life, getEasingByName(easing), isEnabled ); }
static fromJSON(json) { const { zoneType, zoneParams, crossType, life, easing, isEnabled = true, } = json; const zone = new Zone[zoneType](...Object.values(zoneParams)); return new CrossZone( zone, crossType, life, getEasingByName(easing), isEnabled ); }
JavaScript
toCanvas() { return (typeof document === "undefined") ? null : createCanvas( this.width, this.height, this.data, this.channels ); }
toCanvas() { return (typeof document === "undefined") ? null : createCanvas( this.width, this.height, this.data, this.channels ); }
JavaScript
static fromJSON(json) { const { x, y, z, force, radius, life, easing, isEnabled = true } = json; return new Attraction( new Vector3D(x, y, z), force, radius, life, getEasingByName(easing), isEnabled ); }
static fromJSON(json) { const { x, y, z, force, radius, life, easing, isEnabled = true } = json; return new Attraction( new Vector3D(x, y, z), force, radius, life, getEasingByName(easing), isEnabled ); }
JavaScript
update(renderer, inputBuffer, deltaTime) { this.clearPass.render(renderer, this.renderTargetColorEdges); this.colorEdgesPass.render(renderer, inputBuffer, this.renderTargetColorEdges); this.weightsPass.render(renderer, this.renderTargetColorEdges, this.renderTargetWeights); }
update(renderer, inputBuffer, deltaTime) { this.clearPass.render(renderer, this.renderTargetColorEdges); this.colorEdgesPass.render(renderer, inputBuffer, this.renderTargetColorEdges); this.weightsPass.render(renderer, this.renderTargetColorEdges, this.renderTargetWeights); }
JavaScript
static get searchImageDataURL() { return searchImageDataURL; }
static get searchImageDataURL() { return searchImageDataURL; }
JavaScript
static get areaImageDataURL() { return areaImageDataURL; }
static get areaImageDataURL() { return areaImageDataURL; }
JavaScript
initialize(particle) { particle.useAlpha = true; particle.transform.alphaA = this.alphaA.getValue(); particle.transform.alphaB = this.same ? particle.transform.alphaA : this.alphaB.getValue(); }
initialize(particle) { particle.useAlpha = true; particle.transform.alphaA = this.alphaA.getValue(); particle.transform.alphaB = this.same ? particle.transform.alphaA : this.alphaB.getValue(); }
JavaScript
static fromJSON(json) { const { alphaA, alphaB, life, easing, isEnabled = true } = json; return new Alpha(alphaA, alphaB, life, getEasingByName(easing), isEnabled); }
static fromJSON(json) { const { alphaA, alphaB, life, easing, isEnabled = true } = json; return new Alpha(alphaA, alphaB, life, getEasingByName(easing), isEnabled); }
JavaScript
load() { const assets = this.assets; const loadingManager = this.loadingManager; const cubeTextureLoader = new CubeTextureLoader(loadingManager); const path = "textures/skies/space/"; const format = ".jpg"; const urls = [ path + "px" + format, path + "nx" + format, path + "py" + format, path + "ny" + format, path + "pz" + format, path + "nz" + format ]; return new Promise((resolve, reject) => { if(assets.size === 0) { loadingManager.onError = reject; loadingManager.onProgress = (item, loaded, total) => { if(loaded === total) { resolve(); } }; cubeTextureLoader.load(urls, function(textureCube) { assets.set("sky", textureCube); }); } else { resolve(); } }); }
load() { const assets = this.assets; const loadingManager = this.loadingManager; const cubeTextureLoader = new CubeTextureLoader(loadingManager); const path = "textures/skies/space/"; const format = ".jpg"; const urls = [ path + "px" + format, path + "nx" + format, path + "py" + format, path + "ny" + format, path + "pz" + format, path + "nz" + format ]; return new Promise((resolve, reject) => { if(assets.size === 0) { loadingManager.onError = reject; loadingManager.onProgress = (item, loaded, total) => { if(loaded === total) { resolve(); } }; cubeTextureLoader.load(urls, function(textureCube) { assets.set("sky", textureCube); }); } else { resolve(); } }); }
JavaScript
reset() { if (!this.zones) { this.zones = []; } else { this.zones.length = 0; } /** * @desc The zones to use as bounds for calculating the particle's starting position. * @type {array<Zone>} */ this.zones = this.zones.concat(Array.prototype.slice.call(arguments)); }
reset() { if (!this.zones) { this.zones = []; } else { this.zones.length = 0; } /** * @desc The zones to use as bounds for calculating the particle's starting position. * @type {array<Zone>} */ this.zones = this.zones.concat(Array.prototype.slice.call(arguments)); }
JavaScript
static fromJSON(json) { const { zoneType, ...params } = json; if (!SUPPORTED_JSON_ZONE_TYPES.includes(zoneType)) { throw new Error( `The zone type ${zoneType} is invalid or not yet supported` ); } return new Position(new Zone[zoneType](...Object.values(params))); }
static fromJSON(json) { const { zoneType, ...params } = json; if (!SUPPORTED_JSON_ZONE_TYPES.includes(zoneType)) { throw new Error( `The zone type ${zoneType} is invalid or not yet supported` ); } return new Position(new Zone[zoneType](...Object.values(params))); }
JavaScript
initialize(particle) { if (this.lifePan.a == Infinity || this.lifePan.a == 'infi') { particle.life = Infinity; } else { particle.life = this.lifePan.getValue(); } }
initialize(particle) { if (this.lifePan.a == Infinity || this.lifePan.a == 'infi') { particle.life = Infinity; } else { particle.life = this.lifePan.getValue(); } }
JavaScript
static fromJSON(json) { const { min, max, center = false, isEnabled = true } = json; return new Life(min, max, center, isEnabled); }
static fromJSON(json) { const { min, max, center = false, isEnabled = true } = json; return new Life(min, max, center, isEnabled); }
JavaScript
static fromJSON(json) { const { particlesMin, particlesMax, perSecondMin, perSecondMax } = json; return new Rate( new Span(particlesMin, particlesMax), new Span(perSecondMin, perSecondMax) ); }
static fromJSON(json) { const { particlesMin, particlesMax, perSecondMin, perSecondMax } = json; return new Rate( new Span(particlesMin, particlesMax), new Span(perSecondMin, perSecondMax) ); }
JavaScript
static fromJSON(json) { const { x, y, z, theta, isEnabled = true } = json; return new VectorVelocity(new Vector3D(x, y, z), theta, isEnabled); }
static fromJSON(json) { const { x, y, z, theta, isEnabled = true } = json; return new VectorVelocity(new Vector3D(x, y, z), theta, isEnabled); }
JavaScript
static fromJSON(json) { const { x, y, z, spring, friction, life, easing, isEnabled = true } = json; return new Spring( x, y, z, spring, friction, life, getEasingByName(easing), isEnabled ); }
static fromJSON(json) { const { x, y, z, spring, friction, life, easing, isEnabled = true } = json; return new Spring( x, y, z, spring, friction, life, getEasingByName(easing), isEnabled ); }
JavaScript
function isTouchDevice () { let prefixes = ' -webkit- -moz- -o- -ms- '.split(' '); let mq = function(query) { return window.matchMedia(query).matches; }; if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) { return true; } // include the 'heartz' as a way to have a non matching MQ to help terminate the join // https://git.io/vznFH let query = ['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join(''); return mq(query); }
function isTouchDevice () { let prefixes = ' -webkit- -moz- -o- -ms- '.split(' '); let mq = function(query) { return window.matchMedia(query).matches; }; if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) { return true; } // include the 'heartz' as a way to have a non matching MQ to help terminate the join // https://git.io/vznFH let query = ['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join(''); return mq(query); }
JavaScript
function isiOS() { return [ 'iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod' ].includes(navigator.platform) // iPad on iOS 13 detection || (navigator.userAgent.includes("Mac") && "ontouchend" in document) }
function isiOS() { return [ 'iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod' ].includes(navigator.platform) // iPad on iOS 13 detection || (navigator.userAgent.includes("Mac") && "ontouchend" in document) }
JavaScript
function sceneTraverse(obj, fn) { if (!obj) return fn(obj); if (obj.children && obj.children.length > 0) { obj.children.forEach(o => { sceneTraverse(o, fn); }); } }
function sceneTraverse(obj, fn) { if (!obj) return fn(obj); if (obj.children && obj.children.length > 0) { obj.children.forEach(o => { sceneTraverse(o, fn); }); } }
JavaScript
function wait (ms) { return new Promise((resolve, reject) => { try { setTimeout(() => { return resolve() }, ms) } catch (e) { return reject(e) } }) }
function wait (ms) { return new Promise((resolve, reject) => { try { setTimeout(() => { return resolve() }, ms) } catch (e) { return reject(e) } }) }
JavaScript
function initDatGUI (conf) { const gui = new DAT.GUI(); $( ".dg.ac" ).css("zIndex", "99"); for (let o of conf) { // console.log(o); gui.add(o, o.name).min(o.min).max(o.max).step(o.step ? o.step : 0.1).onChange(v => {o.cb(v)}) } }
function initDatGUI (conf) { const gui = new DAT.GUI(); $( ".dg.ac" ).css("zIndex", "99"); for (let o of conf) { // console.log(o); gui.add(o, o.name).min(o.min).max(o.max).step(o.step ? o.step : 0.1).onChange(v => {o.cb(v)}) } }
JavaScript
static fromJSON(json) { const { colorA, colorB, life, easing, isEnabled = true } = json; return new Color(colorA, colorB, life, getEasingByName(easing), isEnabled); }
static fromJSON(json) { const { colorA, colorB, life, easing, isEnabled = true } = json; return new Color(colorA, colorB, life, getEasingByName(easing), isEnabled); }
JavaScript
_dead(particle) { var d = particle.position.distanceTo(this); if (d - particle.radius > this.radius) particle.dead = true; }
_dead(particle) { var d = particle.position.distanceTo(this); if (d - particle.radius > this.radius) particle.dead = true; }
JavaScript
function done(status, nativeStatusText, responses, headers) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if (state === 2) { return; } // State is "done" now state = 2; // Clear timeout if it exists if (timeoutTimer) { clearTimeout(timeoutTimer); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if (responses) { response = ajaxHandleResponses(s, jqXHR, responses); } // If successful, handle type chaining if (status >= 200 && status < 300 || status === 304) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if (s.ifModified) { modified = jqXHR.getResponseHeader("Last-Modified"); if (modified) { jQuery.lastModified[ifModifiedKey] = modified; } modified = jqXHR.getResponseHeader("Etag"); if (modified) { jQuery.etag[ifModifiedKey] = modified; } } // If not modified if (status === 304) { statusText = "notmodified"; isSuccess = true; // If we have data } else { isSuccess = ajaxConvert(s, response); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if (!statusText || status) { statusText = "error"; if (status < 0) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = (nativeStatusText || statusText) + ""; // Success/Error if (isSuccess) { deferred.resolveWith(callbackContext, [success, statusText, jqXHR]); } else { deferred.rejectWith(callbackContext, [jqXHR, statusText, error]); } // Status-dependent callbacks jqXHR.statusCode(statusCode); statusCode = undefined; if (fireGlobals) { globalEventContext.trigger("ajax" + (isSuccess ? "Success" : "Error"), [jqXHR, s, isSuccess ? success : error]); } // Complete completeDeferred.fireWith(callbackContext, [jqXHR, statusText]); if (fireGlobals) { globalEventContext.trigger("ajaxComplete", [jqXHR, s]); // Handle the global AJAX counter if (!(--jQuery.active)) { jQuery.event.trigger("ajaxStop"); } } }
function done(status, nativeStatusText, responses, headers) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if (state === 2) { return; } // State is "done" now state = 2; // Clear timeout if it exists if (timeoutTimer) { clearTimeout(timeoutTimer); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if (responses) { response = ajaxHandleResponses(s, jqXHR, responses); } // If successful, handle type chaining if (status >= 200 && status < 300 || status === 304) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if (s.ifModified) { modified = jqXHR.getResponseHeader("Last-Modified"); if (modified) { jQuery.lastModified[ifModifiedKey] = modified; } modified = jqXHR.getResponseHeader("Etag"); if (modified) { jQuery.etag[ifModifiedKey] = modified; } } // If not modified if (status === 304) { statusText = "notmodified"; isSuccess = true; // If we have data } else { isSuccess = ajaxConvert(s, response); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if (!statusText || status) { statusText = "error"; if (status < 0) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = (nativeStatusText || statusText) + ""; // Success/Error if (isSuccess) { deferred.resolveWith(callbackContext, [success, statusText, jqXHR]); } else { deferred.rejectWith(callbackContext, [jqXHR, statusText, error]); } // Status-dependent callbacks jqXHR.statusCode(statusCode); statusCode = undefined; if (fireGlobals) { globalEventContext.trigger("ajax" + (isSuccess ? "Success" : "Error"), [jqXHR, s, isSuccess ? success : error]); } // Complete completeDeferred.fireWith(callbackContext, [jqXHR, statusText]); if (fireGlobals) { globalEventContext.trigger("ajaxComplete", [jqXHR, s]); // Handle the global AJAX counter if (!(--jQuery.active)) { jQuery.event.trigger("ajaxStop"); } } }
JavaScript
function indexMap(dictionary, { separator = '/', path = '__path' } = {}) { /** * Join de path parts if exsists * @param {Array} parts Path parts to be joined * @returns {string|undefined} The path string if had more than one part */ function joinPath(parts) { return parts.length === 0 ? undefined : parts.join(separator); } /** * Gets the dictionary proxy handler * @param {string} [parentPath] A string to prefix the current path and value. * @returns {ProxyHandler} The handler for the dictionary proxy. */ function getProxyHandler(parentPath) { return { get(target, key) { const pathParts = []; if (typeof parentPath === 'string') { pathParts.push(parentPath); } const currentPath = target[path]; if (typeof currentPath === 'string') { pathParts.push(currentPath); } const currentValue = target[key]; if (typeof currentValue === 'string') { pathParts.push(currentValue); const fullPath = joinPath(pathParts); return fullPath; } if (typeof currentValue === 'object' && currentValue !== null) { const fullPath = joinPath(pathParts); return new Proxy(currentValue, getProxyHandler(fullPath)); } return currentValue; }, }; } return new Proxy(dictionary, getProxyHandler()); }
function indexMap(dictionary, { separator = '/', path = '__path' } = {}) { /** * Join de path parts if exsists * @param {Array} parts Path parts to be joined * @returns {string|undefined} The path string if had more than one part */ function joinPath(parts) { return parts.length === 0 ? undefined : parts.join(separator); } /** * Gets the dictionary proxy handler * @param {string} [parentPath] A string to prefix the current path and value. * @returns {ProxyHandler} The handler for the dictionary proxy. */ function getProxyHandler(parentPath) { return { get(target, key) { const pathParts = []; if (typeof parentPath === 'string') { pathParts.push(parentPath); } const currentPath = target[path]; if (typeof currentPath === 'string') { pathParts.push(currentPath); } const currentValue = target[key]; if (typeof currentValue === 'string') { pathParts.push(currentValue); const fullPath = joinPath(pathParts); return fullPath; } if (typeof currentValue === 'object' && currentValue !== null) { const fullPath = joinPath(pathParts); return new Proxy(currentValue, getProxyHandler(fullPath)); } return currentValue; }, }; } return new Proxy(dictionary, getProxyHandler()); }
JavaScript
function R33333(stringConveritble) { let output = String(stringConveritble); // if colour if (output[0] === "\x1b") { const justText = output.slice(5, output.length - 4).toUpperCase(); output = stringConveritble.charAt(3) == "1" ? f1r3tr7ck(justText) : d1n0s47r(justText); // normal case } else output = output.toUpperCase(); console.log(output); // So that super commands can be used return output; }
function R33333(stringConveritble) { let output = String(stringConveritble); // if colour if (output[0] === "\x1b") { const justText = output.slice(5, output.length - 4).toUpperCase(); output = stringConveritble.charAt(3) == "1" ? f1r3tr7ck(justText) : d1n0s47r(justText); // normal case } else output = output.toUpperCase(); console.log(output); // So that super commands can be used return output; }
JavaScript
function normalizePort(val) { const result = parseInt(val, 10) if (isNaN(result)) { // named pipe return val } if (result >= 0) { // port number return result } return false }
function normalizePort(val) { const result = parseInt(val, 10) if (isNaN(result)) { // named pipe return val } if (result >= 0) { // port number return result } return false }
JavaScript
function onListening() { const addr = server.address() const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}` logger.info(`Listening on ${bind}`) }
function onListening() { const addr = server.address() const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}` logger.info(`Listening on ${bind}`) }
JavaScript
function deleteUsers(usersIds) { return (dispatch) => { dispatch({ type: actions.users.delete.started }) return axios({ method: 'delete', url: '/api/users', data: usersIds }) .then((response) => { if (response.data.some((individualResponse) => individualResponse.status !== 'SUCCESS')) { return Promise.reject('Could not delete some users') } return dispatch({ type: actions.users.delete.fulfilled, payload: response.data }) }) .catch((error) => { dispatch({ type: actions.users.delete.rejected }) dispatch({ type: actions.alerts.error, payload: 'Could not delete users' }) return Promise.reject(error) }) } }
function deleteUsers(usersIds) { return (dispatch) => { dispatch({ type: actions.users.delete.started }) return axios({ method: 'delete', url: '/api/users', data: usersIds }) .then((response) => { if (response.data.some((individualResponse) => individualResponse.status !== 'SUCCESS')) { return Promise.reject('Could not delete some users') } return dispatch({ type: actions.users.delete.fulfilled, payload: response.data }) }) .catch((error) => { dispatch({ type: actions.users.delete.rejected }) dispatch({ type: actions.alerts.error, payload: 'Could not delete users' }) return Promise.reject(error) }) } }
JavaScript
function timeTracker(){ //get current hour var timeNow = moment().hour(); // loop timeblocks $(".time-block").each(function (){ var timeBlock = parseInt($(this).attr('id').split('hour-')[1]); //check time and add class if (timeBlock < timeNow) { $(this).removeClass("future"); $(this).removeClass("present"); $(this).addClass("past"); } else if (timeBlock === timeNow) { $(this).removeClass("future"); $(this).addClass("present"); $(this).removeClass("past"); } else { $(this).addClass("future"); $(this).removeClass("present"); $(this).removeClass("past"); } }) }
function timeTracker(){ //get current hour var timeNow = moment().hour(); // loop timeblocks $(".time-block").each(function (){ var timeBlock = parseInt($(this).attr('id').split('hour-')[1]); //check time and add class if (timeBlock < timeNow) { $(this).removeClass("future"); $(this).removeClass("present"); $(this).addClass("past"); } else if (timeBlock === timeNow) { $(this).removeClass("future"); $(this).addClass("present"); $(this).removeClass("past"); } else { $(this).addClass("future"); $(this).removeClass("present"); $(this).removeClass("past"); } }) }
JavaScript
markBlocks(){ for(let i=0;i<this.jsonMap.length;i++){ let item=this.jsonMap[i]; let blocks = item.blocks; if(blocks){ for(let b=0;b<blocks.length;b++){ let block=blocks[b]; block.mergeAble = block.originalBlockArray.length === 6; if(!block.validFace){ block.mergeAble = false; } block.id=this.lastBlockId; this.lastBlockId++; } } } }
markBlocks(){ for(let i=0;i<this.jsonMap.length;i++){ let item=this.jsonMap[i]; let blocks = item.blocks; if(blocks){ for(let b=0;b<blocks.length;b++){ let block=blocks[b]; block.mergeAble = block.originalBlockArray.length === 6; if(!block.validFace){ block.mergeAble = false; } block.id=this.lastBlockId; this.lastBlockId++; } } } }
JavaScript
function calculateEpsPerf(dates) { dates.map(function (qtr, index) { if (index - 4 >= 0 && dates[index - 4].eps.eps != 0) { qtr.eps.negativeCompQtr = false; qtr.eps.negativeTurnaround = false; qtr.eps.perf = Math.round( 100 * ((qtr.eps.eps - dates[index - 4].eps.eps) / Math.abs(dates[index - 4].eps.eps)) ); if (qtr.eps.eps < 0 && dates[index - 4].eps.eps) { qtr.eps.negativeCompQtr = true; } else if (dates[index - 4].eps.eps < 0) { qtr.eps.negativeTurnaround = true; } } }); }
function calculateEpsPerf(dates) { dates.map(function (qtr, index) { if (index - 4 >= 0 && dates[index - 4].eps.eps != 0) { qtr.eps.negativeCompQtr = false; qtr.eps.negativeTurnaround = false; qtr.eps.perf = Math.round( 100 * ((qtr.eps.eps - dates[index - 4].eps.eps) / Math.abs(dates[index - 4].eps.eps)) ); if (qtr.eps.eps < 0 && dates[index - 4].eps.eps) { qtr.eps.negativeCompQtr = true; } else if (dates[index - 4].eps.eps < 0) { qtr.eps.negativeTurnaround = true; } } }); }
JavaScript
function calculateAnnualPerf(dates) { dates.map(function (item, index) { if (index - 1 >= 0) { if (dates[index - 1].eps != 0) { item.epsPerf = Math.round( 100 * ((item.eps - dates[index - 1].eps) / Math.abs(dates[index - 1].eps)) ); } if (dates[index - 1].rev != 0) { item.revPerf = Math.round( 100 * ((item.rev - dates[index - 1].rev) / Math.abs(dates[index - 1].rev)) ); } } }); }
function calculateAnnualPerf(dates) { dates.map(function (item, index) { if (index - 1 >= 0) { if (dates[index - 1].eps != 0) { item.epsPerf = Math.round( 100 * ((item.eps - dates[index - 1].eps) / Math.abs(dates[index - 1].eps)) ); } if (dates[index - 1].rev != 0) { item.revPerf = Math.round( 100 * ((item.rev - dates[index - 1].rev) / Math.abs(dates[index - 1].rev)) ); } } }); }
JavaScript
initSlider() { this .validateConfig .setActionButton .resizeSlide .startTouch(); if (this.configSlide.autoPlay) this.autoPlay(); return 0; }
initSlider() { this .validateConfig .setActionButton .resizeSlide .startTouch(); if (this.configSlide.autoPlay) this.autoPlay(); return 0; }
JavaScript
get validateConfig() { const KEYS = [ "arrowNext", "arrowPrevious", "contentItem", ]; const { callbacks, jump } = this.configSlide; const PIXEL_RATIO = window.devicePixelRatio; KEYS.forEach((item) => { const SELECTOR = this.configSlide[item]; const ELEMENT = Utils.getElementDom(SELECTOR); const JUMP = (Utils.isMobile === "desktop") ? 128 : jump; if (ELEMENT) { this.configSlide[item] = ELEMENT; if (item === "contentItem") { const ITEM = ELEMENT.children[0] || {}; const ITEM_WIDTH = ITEM.offsetWidth || 0; const MOVE_TO = Math.ceil(ITEM_WIDTH / JUMP); const NEW_CONFIG = { items: ELEMENT.children.length - 1, itemWidth: ITEM_WIDTH, moveTo: MOVE_TO, scrollWidth: ELEMENT.scrollWidth || 0, time: (this.configSlide.time * 1000) / 512, item: ITEM, content: ELEMENT, }; this.configSlide.active = (NEW_CONFIG.items > 0 && NEW_CONFIG.moveTo > 0); Object.assign(this.configSlide, NEW_CONFIG); if (!this.configSlide.isInfinite) { Utils.displayToggle(this.configSlide.arrowPrevious, "none"); } } } }); this.configSlide.callbacks = Utils.getCallbacksConfig(callbacks); return this.validateConfigAutoPlay; }
get validateConfig() { const KEYS = [ "arrowNext", "arrowPrevious", "contentItem", ]; const { callbacks, jump } = this.configSlide; const PIXEL_RATIO = window.devicePixelRatio; KEYS.forEach((item) => { const SELECTOR = this.configSlide[item]; const ELEMENT = Utils.getElementDom(SELECTOR); const JUMP = (Utils.isMobile === "desktop") ? 128 : jump; if (ELEMENT) { this.configSlide[item] = ELEMENT; if (item === "contentItem") { const ITEM = ELEMENT.children[0] || {}; const ITEM_WIDTH = ITEM.offsetWidth || 0; const MOVE_TO = Math.ceil(ITEM_WIDTH / JUMP); const NEW_CONFIG = { items: ELEMENT.children.length - 1, itemWidth: ITEM_WIDTH, moveTo: MOVE_TO, scrollWidth: ELEMENT.scrollWidth || 0, time: (this.configSlide.time * 1000) / 512, item: ITEM, content: ELEMENT, }; this.configSlide.active = (NEW_CONFIG.items > 0 && NEW_CONFIG.moveTo > 0); Object.assign(this.configSlide, NEW_CONFIG); if (!this.configSlide.isInfinite) { Utils.displayToggle(this.configSlide.arrowPrevious, "none"); } } } }); this.configSlide.callbacks = Utils.getCallbacksConfig(callbacks); return this.validateConfigAutoPlay; }
JavaScript
get validateConfigAutoPlay() { const { active, ctrlPlay, ctrlStop, timeAutoPlay, } = this.configSlide; if (active) { const CONFIG = { timeAutoPlay: (timeAutoPlay * 1000), ctrlPlay: Utils.getElementDom(ctrlPlay), ctrlStop: Utils.getElementDom(ctrlStop), }; Object.assign(this.configSlide, CONFIG); } return this; }
get validateConfigAutoPlay() { const { active, ctrlPlay, ctrlStop, timeAutoPlay, } = this.configSlide; if (active) { const CONFIG = { timeAutoPlay: (timeAutoPlay * 1000), ctrlPlay: Utils.getElementDom(ctrlPlay), ctrlStop: Utils.getElementDom(ctrlStop), }; Object.assign(this.configSlide, CONFIG); } return this; }
JavaScript
function objToSql(ob) { var arr = []; // loop through the keys and push the key/value as a string int arr for (var key in ob) { var value = ob[key]; // // check to skip hidden properties if (Object.hasOwnPropert.call(ob, key)){ // //if string with spaces, add quotations (Lana Del Grey => 'Lana Del Grey') if (typeof value === "string" && value.indexOf(" ") >= 0){ value = "'" + value + "'"; } // // e.g. {name: 'Lana Del Grey'} => ["name='Lana Del Grey'"] // // e.g. {devoured: true} => ["sleepy=true"] arr.push(key + "=" + value); } } // translate array of strings to a single comma-separated string return arr.toString(); }
function objToSql(ob) { var arr = []; // loop through the keys and push the key/value as a string int arr for (var key in ob) { var value = ob[key]; // // check to skip hidden properties if (Object.hasOwnPropert.call(ob, key)){ // //if string with spaces, add quotations (Lana Del Grey => 'Lana Del Grey') if (typeof value === "string" && value.indexOf(" ") >= 0){ value = "'" + value + "'"; } // // e.g. {name: 'Lana Del Grey'} => ["name='Lana Del Grey'"] // // e.g. {devoured: true} => ["sleepy=true"] arr.push(key + "=" + value); } } // translate array of strings to a single comma-separated string return arr.toString(); }
JavaScript
function parsePing(m, fromUserId, groupInfo) { let originalMessage = m; let users = []; const allMatch = m.match(/@(all|everyone|channel)/i); if (allMatch && allMatch[1]) { // Alert everyone users = Object.keys(groupInfo.members); // Remove sending user from recipients users.splice(users.indexOf(groupInfo.names[fromUserId]), 1); m = m.split("@" + allMatch[1]).join(""); } else { let matches = matchesWithUser("@", m, fromUserId, groupInfo, false, ""); while (matches && matches[1]) { users.push(matches[1].toLowerCase()); const beforeSplit = m; m = m.split(`@${matches[1]}`).join(""); // Remove discovered match from string if (m == beforeSplit) { // Discovered match was "me" or alias m = m.split("@me").join(""); const alias = groupInfo.aliases[matches[1]]; if (alias) { m = m.split(`@${alias}`).join(""); } } matches = matchesWithUser("@", m, fromUserId, groupInfo, false, ""); } // After loop, m will contain the message without the pings (the message to be sent) } return { /* Return array of names to ping, but remove sending user */ "users": users.filter(e => (e != groupInfo.names[fromUserId].toLowerCase())), "message": originalMessage.trim(), "parsed": m.trim() }; }
function parsePing(m, fromUserId, groupInfo) { let originalMessage = m; let users = []; const allMatch = m.match(/@(all|everyone|channel)/i); if (allMatch && allMatch[1]) { // Alert everyone users = Object.keys(groupInfo.members); // Remove sending user from recipients users.splice(users.indexOf(groupInfo.names[fromUserId]), 1); m = m.split("@" + allMatch[1]).join(""); } else { let matches = matchesWithUser("@", m, fromUserId, groupInfo, false, ""); while (matches && matches[1]) { users.push(matches[1].toLowerCase()); const beforeSplit = m; m = m.split(`@${matches[1]}`).join(""); // Remove discovered match from string if (m == beforeSplit) { // Discovered match was "me" or alias m = m.split("@me").join(""); const alias = groupInfo.aliases[matches[1]]; if (alias) { m = m.split(`@${alias}`).join(""); } } matches = matchesWithUser("@", m, fromUserId, groupInfo, false, ""); } // After loop, m will contain the message without the pings (the message to be sent) } return { /* Return array of names to ping, but remove sending user */ "users": users.filter(e => (e != groupInfo.names[fromUserId].toLowerCase())), "message": originalMessage.trim(), "parsed": m.trim() }; }