language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function documentDistance(a, b) {
let num = 0;
let sum = 0;
for (k in a) {
if (!a.hasOwnProperty(k)) continue;
sum += fieldDistance(a[k], b[k]);
num += 1;
}
return sum / num;
} | function documentDistance(a, b) {
let num = 0;
let sum = 0;
for (k in a) {
if (!a.hasOwnProperty(k)) continue;
sum += fieldDistance(a[k], b[k]);
num += 1;
}
return sum / num;
} |
JavaScript | function selectMajority(d, attribute, weights) {
var scores = {};
d.sources.forEach(s => {
let weight = 1;
if (weights != null) {
let sourceSystem = s["_id"].match(/^([^-]+)/)[1];
if (sourceSystem != null) {
let newWeight = weights[sourceSystem];
if (newWeight != null) weight = newWeight;
}
}
if (!s.hasOwnProperty(attribute)) {
return;
} else {
if (!scores.hasOwnProperty(s[attribute])) {
scores[s[attribute]] = weight;
} else {
scores[s[attribute]] += weight;
}
}
});
var max_score = 0;
var majority_value = undefined;
for (var v in scores) {
if (scores.hasOwnProperty(v)) {
if (scores[v] > max_score) {
max_score = scores[v];
majority_value = v;
}
}
}
return majority_value;
} | function selectMajority(d, attribute, weights) {
var scores = {};
d.sources.forEach(s => {
let weight = 1;
if (weights != null) {
let sourceSystem = s["_id"].match(/^([^-]+)/)[1];
if (sourceSystem != null) {
let newWeight = weights[sourceSystem];
if (newWeight != null) weight = newWeight;
}
}
if (!s.hasOwnProperty(attribute)) {
return;
} else {
if (!scores.hasOwnProperty(s[attribute])) {
scores[s[attribute]] = weight;
} else {
scores[s[attribute]] += weight;
}
}
});
var max_score = 0;
var majority_value = undefined;
for (var v in scores) {
if (scores.hasOwnProperty(v)) {
if (scores[v] > max_score) {
max_score = scores[v];
majority_value = v;
}
}
}
return majority_value;
} |
JavaScript | function selectDistinct(d, attribute, fuzz) {
let result = [];
let fuzzFactor = fuzz || 0;
d["sources"].map(s => s[attribute]).forEach(v => {
if (!containsValue(result, v, fuzzFactor)) result.push(v);
});
return result.length == 1 ? result[0] : result;
} | function selectDistinct(d, attribute, fuzz) {
let result = [];
let fuzzFactor = fuzz || 0;
d["sources"].map(s => s[attribute]).forEach(v => {
if (!containsValue(result, v, fuzzFactor)) result.push(v);
});
return result.length == 1 ? result[0] : result;
} |
JavaScript | function closestWithinThreshold(a, x) {
let minValue = 1;
let minIndex = -1;
for (let i=0; i<a.length; i++) {
let d = DISTANCE(a[i], x);
if (d < DISTANCE_THRESHOLD && d < minValue) {
minValue = d;
minIndex = i;
}
}
return minIndex == -1 ? undefined : a[minIndex];
} | function closestWithinThreshold(a, x) {
let minValue = 1;
let minIndex = -1;
for (let i=0; i<a.length; i++) {
let d = DISTANCE(a[i], x);
if (d < DISTANCE_THRESHOLD && d < minValue) {
minValue = d;
minIndex = i;
}
}
return minIndex == -1 ? undefined : a[minIndex];
} |
JavaScript | function loadScript() {
for (let src of scripts) {
if (fs.existsSync(src)) {
var data = fs.readFileSync(src, 'utf8')
if (data != "") {
console.log(`prestart: loading script from ${ src }`)
return data
}
}
}
} | function loadScript() {
for (let src of scripts) {
if (fs.existsSync(src)) {
var data = fs.readFileSync(src, 'utf8')
if (data != "") {
console.log(`prestart: loading script from ${ src }`)
return data
}
}
}
} |
JavaScript | async function loadPlayer() {
console.log('Loading Player');
fetchDailies(player, setHabits, setLevelUp, setDailiesCount);
refreshStats();
fetchLatestWin(
setActiveModalStats,
refreshStats,
setLevelUp,
triggerWinModal,
setShowWinModal,
player
);
} | async function loadPlayer() {
console.log('Loading Player');
fetchDailies(player, setHabits, setLevelUp, setDailiesCount);
refreshStats();
fetchLatestWin(
setActiveModalStats,
refreshStats,
setLevelUp,
triggerWinModal,
setShowWinModal,
player
);
} |
JavaScript | async function loadPlayer() {
console.log('Loading Player');
fetchDailies(player, setHabits, setLevelUp, setDailiesCount);
refreshStats();
} | async function loadPlayer() {
console.log('Loading Player');
fetchDailies(player, setHabits, setLevelUp, setDailiesCount);
refreshStats();
} |
JavaScript | function initializePlayer() {
try {
if (userOnboarding.onboarding_state.includes('4')) {
loadPlayer();
} else {
router.push('/account');
}
} catch (error) {
alert(error.message);
} finally {
console.log('InitializedPlayer');
}
} | function initializePlayer() {
try {
if (userOnboarding.onboarding_state.includes('4')) {
loadPlayer();
} else {
router.push('/account');
}
} catch (error) {
alert(error.message);
} finally {
console.log('InitializedPlayer');
}
} |
JavaScript | function initializePlayer() {
try {
if (userOnboarding.onboarding_state.includes('4')) {
loadPlayer();
} else {
setOnboardingState(parseInt(userOnboarding.onboarding_state, 10));
console.log('Setting onboarding state...', parseInt(userOnboarding.onboarding_state, 10))
}
} catch (error) {
alert(error.message);
} finally {
console.log('InitializedPlayer');
}
} | function initializePlayer() {
try {
if (userOnboarding.onboarding_state.includes('4')) {
loadPlayer();
} else {
setOnboardingState(parseInt(userOnboarding.onboarding_state, 10));
console.log('Setting onboarding state...', parseInt(userOnboarding.onboarding_state, 10))
}
} catch (error) {
alert(error.message);
} finally {
console.log('InitializedPlayer');
}
} |
JavaScript | async function loadPlayer() {
console.log('Loading Player');
await refreshStats();
if (win_id) loadSpecificWin(win_id);
} | async function loadPlayer() {
console.log('Loading Player');
await refreshStats();
if (win_id) loadSpecificWin(win_id);
} |
JavaScript | async function updateProfile({ image_url, type }) {
try {
setLoading(true);
if (type === 'avatar') {
let { error } = await supabase
.from('users')
.update({
avatar_url: image_url
})
.eq('id', user.id);
if (error) {
throw error;
}
} else if (type === 'background') {
let { error } = await supabase
.from('users')
.update({
background_url: image_url
})
.eq('id', user.id);
if (error) {
throw error;
}
}
} catch (error) {
alert(error.message);
} finally {
setLoading(false);
}
} | async function updateProfile({ image_url, type }) {
try {
setLoading(true);
if (type === 'avatar') {
let { error } = await supabase
.from('users')
.update({
avatar_url: image_url
})
.eq('id', user.id);
if (error) {
throw error;
}
} else if (type === 'background') {
let { error } = await supabase
.from('users')
.update({
background_url: image_url
})
.eq('id', user.id);
if (error) {
throw error;
}
}
} catch (error) {
alert(error.message);
} finally {
setLoading(false);
}
} |
JavaScript | async function loadPlayer() {
console.log('Loading Player');
fetchActiveParties();
fetchRecruitingParties();
refreshStats();
} | async function loadPlayer() {
console.log('Loading Player');
fetchActiveParties();
fetchRecruitingParties();
refreshStats();
} |
JavaScript | function normalizePort(val) {
const port = parseInt(val, 10)
if (Number.isNaN(port)) {
// named pipe
return val
}
if (port >= 0) {
// port number
return port
}
return false
} | function normalizePort(val) {
const port = parseInt(val, 10)
if (Number.isNaN(port)) {
// named pipe
return val
}
if (port >= 0) {
// port number
return port
}
return false
} |
JavaScript | async function connect() {
const uri = await mongod.getConnectionString()
const mongooseOpts = {
useNewUrlParser: true,
autoReconnect: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000,
}
await mongoose.connect(uri, mongooseOpts)
} | async function connect() {
const uri = await mongod.getConnectionString()
const mongooseOpts = {
useNewUrlParser: true,
autoReconnect: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000,
}
await mongoose.connect(uri, mongooseOpts)
} |
JavaScript | async function closeDatabase() {
await mongoose.connection.dropDatabase()
await mongoose.connection.close()
await mongod.stop()
} | async function closeDatabase() {
await mongoose.connection.dropDatabase()
await mongoose.connection.close()
await mongod.stop()
} |
JavaScript | async function clearDatabase() {
const {collections} = mongoose.connection
for (const key in collections) {
const collection = collections[key]
await collection.deleteMany()
}
} | async function clearDatabase() {
const {collections} = mongoose.connection
for (const key in collections) {
const collection = collections[key]
await collection.deleteMany()
}
} |
JavaScript | function Switch(input) {
if ('checkbox' !== input.type) throw new Error('You can\'t make Switch out of non-checkbox input');
this.input = input;
this.input.style.display = 'none'; // hide the actual input
this.el = document.createElement('div');
$(this.input).removeClass("ios-switch");
this.el.className = 'iswitch '+$(this.input).attr("class");
this._prepareDOM();
this.input.parentElement.insertBefore(this.el, this.input);
// read initial state and set Switch state accordingly
if (this.input.checked) this.turnOn()
var ele = this;
this.el.addEventListener('click', function(e){
e.preventDefault();
ele.toggle();
}, false);
} | function Switch(input) {
if ('checkbox' !== input.type) throw new Error('You can\'t make Switch out of non-checkbox input');
this.input = input;
this.input.style.display = 'none'; // hide the actual input
this.el = document.createElement('div');
$(this.input).removeClass("ios-switch");
this.el.className = 'iswitch '+$(this.input).attr("class");
this._prepareDOM();
this.input.parentElement.insertBefore(this.el, this.input);
// read initial state and set Switch state accordingly
if (this.input.checked) this.turnOn()
var ele = this;
this.el.addEventListener('click', function(e){
e.preventDefault();
ele.toggle();
}, false);
} |
JavaScript | function update_info(message) {
sensorID = message.sensorID;
//collect info from messages --> PROBLEM: the output reacts to clicking in former function AND receiving a message here, makes the processing appear longer
if (Object.keys(storage).length === 0){
for (var i = 0; i < allSensors.length; i++ ){
storage[allSensors[i]] = [] //--> creates object of arrays with sensor names as keys
}
console.log("storage can be filled now")
}
let d = new Date();
let curr_min = d.getMinutes();
let curr_hour = d.getHours();
let curr_date = d.getDate();
let curr_month = d.getMonth() + 1;
let curr_year = d.getFullYear();
let date = (curr_year + "-" + curr_month + "-" + curr_date + " " + curr_hour + ":" + curr_min)
// replace old modal content with new one
var bod = document.getElementById("body-"+sensorID)
bod.childNodes[0].nodeValue = "Value: "+message.value;
bod.childNodes[2].nodeValue = "Status: "+message.standard;
bod.childNodes[4].nodeValue = "Time: "+date;
// IMPORTANT?: the order is changed, object in alphabetical order unlike allSensors array!
storage[sensorID].push([date, message.value, message.standard]); // adds new info at the end
if (storage[sensorID].length > 6){
//delete oldest entry
let tooOld = storage[sensorID].shift()
}
console.log(storage)
if (Object.keys(storage).includes(objName)){
let div_info = document.getElementById("information");
// add headline
let info_title = document.createElement("P");
let gapA = document.createElement("br");
let gapB = document.createElement("br");
let title_text = document.createTextNode("Recent changes of Sensor "+objName);
info_title.appendChild(title_text)
info_title.appendChild(gapA);
div_info.appendChild(info_title);
div_info.appendChild(gapB);
//create p element with a for loop
for (var u = 0; u < storage[objName].length; u++ ){ //u is the array with date, value and status
let p_info = document.createElement("P");
for (var v = 0; v < storage[objName][u].length; v++){
let text = document.createTextNode(storage[objName][u][v]); //how to add keys here? (key + whats already there)
let br = document.createElement("br");
p_info.appendChild(text);
p_info.appendChild(br);
}
div_info.appendChild(p_info);
let msg_seperator = document.createElement("br");
div_info.appendChild(msg_seperator);
div_info.scrollTop = div_info.scrollHeight;
}
}
//message here is not the same as in on message arrived!
console.log(message); // loggs as a JS object
sensorID = message.sensorID;
console.log(message.sensorID);
let iframe = document.getElementById('embeddedViewer');
let viewer = iframe.contentWindow.bimViewer.viewer;
let metaObjects = viewer.metaScene.metaObjects;
//let ObjectList = Object.entries(metaObjects); // --> neccessary?
const allObjects = Object.values(metaObjects);
} | function update_info(message) {
sensorID = message.sensorID;
//collect info from messages --> PROBLEM: the output reacts to clicking in former function AND receiving a message here, makes the processing appear longer
if (Object.keys(storage).length === 0){
for (var i = 0; i < allSensors.length; i++ ){
storage[allSensors[i]] = [] //--> creates object of arrays with sensor names as keys
}
console.log("storage can be filled now")
}
let d = new Date();
let curr_min = d.getMinutes();
let curr_hour = d.getHours();
let curr_date = d.getDate();
let curr_month = d.getMonth() + 1;
let curr_year = d.getFullYear();
let date = (curr_year + "-" + curr_month + "-" + curr_date + " " + curr_hour + ":" + curr_min)
// replace old modal content with new one
var bod = document.getElementById("body-"+sensorID)
bod.childNodes[0].nodeValue = "Value: "+message.value;
bod.childNodes[2].nodeValue = "Status: "+message.standard;
bod.childNodes[4].nodeValue = "Time: "+date;
// IMPORTANT?: the order is changed, object in alphabetical order unlike allSensors array!
storage[sensorID].push([date, message.value, message.standard]); // adds new info at the end
if (storage[sensorID].length > 6){
//delete oldest entry
let tooOld = storage[sensorID].shift()
}
console.log(storage)
if (Object.keys(storage).includes(objName)){
let div_info = document.getElementById("information");
// add headline
let info_title = document.createElement("P");
let gapA = document.createElement("br");
let gapB = document.createElement("br");
let title_text = document.createTextNode("Recent changes of Sensor "+objName);
info_title.appendChild(title_text)
info_title.appendChild(gapA);
div_info.appendChild(info_title);
div_info.appendChild(gapB);
//create p element with a for loop
for (var u = 0; u < storage[objName].length; u++ ){ //u is the array with date, value and status
let p_info = document.createElement("P");
for (var v = 0; v < storage[objName][u].length; v++){
let text = document.createTextNode(storage[objName][u][v]); //how to add keys here? (key + whats already there)
let br = document.createElement("br");
p_info.appendChild(text);
p_info.appendChild(br);
}
div_info.appendChild(p_info);
let msg_seperator = document.createElement("br");
div_info.appendChild(msg_seperator);
div_info.scrollTop = div_info.scrollHeight;
}
}
//message here is not the same as in on message arrived!
console.log(message); // loggs as a JS object
sensorID = message.sensorID;
console.log(message.sensorID);
let iframe = document.getElementById('embeddedViewer');
let viewer = iframe.contentWindow.bimViewer.viewer;
let metaObjects = viewer.metaScene.metaObjects;
//let ObjectList = Object.entries(metaObjects); // --> neccessary?
const allObjects = Object.values(metaObjects);
} |
JavaScript | function isConnected(socketName) {
clients.forEach((client) => {
if (client.name === socketName)
return true;
});
return false;
} | function isConnected(socketName) {
clients.forEach((client) => {
if (client.name === socketName)
return true;
});
return false;
} |
JavaScript | function broadcast(header, data, area) {
clients.forEach((client) => {
if (client.area == area) {
send(client.socket, header, data, client.websocket);
}
});
} | function broadcast(header, data, area) {
clients.forEach((client) => {
if (client.area == area) {
send(client.socket, header, data, client.websocket);
}
});
} |
JavaScript | function packetBuilder(header, packetContents) {
let packet = header + "#";
packetContents.forEach((datum) => {
if(datum != undefined)
packet += datum.toString() + "#";
else
packet += "#";
});
packet += "%";
return packet;
} | function packetBuilder(header, packetContents) {
let packet = header + "#";
packetContents.forEach((datum) => {
if(datum != undefined)
packet += datum.toString() + "#";
else
packet += "#";
});
packet += "%";
return packet;
} |
JavaScript | function send(socket, header, data, ws) {
if(ws === undefined){
console.error("Send called without ws arg!!");
console.error("If you are reading this contact gameboyprinter#0000 on discord and send him everything you see below");
console.trace();
return;
}
if (ws) {
data = packetBuilder(header, data);
let frame = [];
frame.push(0x81); // text opcode
if (data.length < 126)
frame.push(data.length & 0x7F);
else { // TODO: implement 64 bit length
frame.push(126);
frame.push((data.length & 0xFF00) >> 8);
frame.push((data.length & 0xFF));
}
for (let i = 0; i < data.length; i++) {
frame.push(data.charCodeAt(i));
}
socket.write(Buffer.from(frame));
} else {
socket.write(packetBuilder(header, data));
}
} | function send(socket, header, data, ws) {
if(ws === undefined){
console.error("Send called without ws arg!!");
console.error("If you are reading this contact gameboyprinter#0000 on discord and send him everything you see below");
console.trace();
return;
}
if (ws) {
data = packetBuilder(header, data);
let frame = [];
frame.push(0x81); // text opcode
if (data.length < 126)
frame.push(data.length & 0x7F);
else { // TODO: implement 64 bit length
frame.push(126);
frame.push((data.length & 0xFF00) >> 8);
frame.push((data.length & 0xFF));
}
for (let i = 0; i < data.length; i++) {
frame.push(data.charCodeAt(i));
}
socket.write(Buffer.from(frame));
} else {
socket.write(packetBuilder(header, data));
}
} |
JavaScript | function ban(client, config) {
client.socket.end();
config.bans.push({
ip: client.socket.remoteAddress,
hwid: client.hardware
});
fs.writeFileSync("./config.json", JSON.stringify(config, null, 2));
} | function ban(client, config) {
client.socket.end();
config.bans.push({
ip: client.socket.remoteAddress,
hwid: client.hardware
});
fs.writeFileSync("./config.json", JSON.stringify(config, null, 2));
} |
JavaScript | function camera_top_view() {
camera.rotation.x += Math.PI/2;
camera.position.y = 6;
camera.lookAt(new THREE.Vector3(0,0,0));
} | function camera_top_view() {
camera.rotation.x += Math.PI/2;
camera.position.y = 6;
camera.lookAt(new THREE.Vector3(0,0,0));
} |
JavaScript | function camera_perspective_view() {
camera.rotation.x += Math.PI/4;
camera.position.x = -1;
camera.position.z = 6;
camera.position.y = -0.4;
camera.lookAt(new THREE.Vector3(0,0,0))
} | function camera_perspective_view() {
camera.rotation.x += Math.PI/4;
camera.position.x = -1;
camera.position.z = 6;
camera.position.y = -0.4;
camera.lookAt(new THREE.Vector3(0,0,0))
} |
JavaScript | function add_elements_to_scene() {
// Adds the Atom's Nucleus
add_atom_nucleus_to_scene();
// Adds the Atom's Particles' States and Orbits
add_atom_orbit_state_to_scene_1();
add_atom_orbit_state_to_scene_2();
add_atom_orbit_state_to_scene_3();
add_atom_orbit_state_to_scene_4();
} | function add_elements_to_scene() {
// Adds the Atom's Nucleus
add_atom_nucleus_to_scene();
// Adds the Atom's Particles' States and Orbits
add_atom_orbit_state_to_scene_1();
add_atom_orbit_state_to_scene_2();
add_atom_orbit_state_to_scene_3();
add_atom_orbit_state_to_scene_4();
} |
JavaScript | function add_atom_nucleus_to_scene() {
// Creates the Geometry of the Sphere representing
// the Atom's Nucleus
atom_nucleus_geometry = new THREE.SphereGeometry(0.6, 40, 40);
// Creates the Material of the Sphere representing
// the Atom's Nucleus
atom_nucleus_material = new THREE.MeshBasicMaterial(
{
color: 0xdda0dd
}
);
// Creates the Mesh of the Atom's Nucleus
atom_nucleus_mesh = new THREE.Mesh(atom_nucleus_geometry, atom_nucleus_material);
// Creates the group for the Atom's Nucleus' Pivot
atom_nucleus_pivot = new THREE.Group();
// Adds the Mesh of the Atom's Nucleus to
// the group for the Atom's Nucleus' Pivot
atom_nucleus_pivot.add(atom_nucleus_mesh);
// Adds the group for the Atom's Nucleus' Pivot to
// the Scene (Atom Representation Scene)
atom_representation_scene.add(atom_nucleus_pivot);
} | function add_atom_nucleus_to_scene() {
// Creates the Geometry of the Sphere representing
// the Atom's Nucleus
atom_nucleus_geometry = new THREE.SphereGeometry(0.6, 40, 40);
// Creates the Material of the Sphere representing
// the Atom's Nucleus
atom_nucleus_material = new THREE.MeshBasicMaterial(
{
color: 0xdda0dd
}
);
// Creates the Mesh of the Atom's Nucleus
atom_nucleus_mesh = new THREE.Mesh(atom_nucleus_geometry, atom_nucleus_material);
// Creates the group for the Atom's Nucleus' Pivot
atom_nucleus_pivot = new THREE.Group();
// Adds the Mesh of the Atom's Nucleus to
// the group for the Atom's Nucleus' Pivot
atom_nucleus_pivot.add(atom_nucleus_mesh);
// Adds the group for the Atom's Nucleus' Pivot to
// the Scene (Atom Representation Scene)
atom_representation_scene.add(atom_nucleus_pivot);
} |
JavaScript | function create_atom_particle_state_1() {
// Creates the Geometry of the Sphere representing
// the Atom's Particle #1
atom_particle_geometry_1 = new THREE.SphereGeometry(0.22, 40, 40);
// Creates the Material of the Sphere representing
// the Atom's Particle #1
atom_particle_material_1 = new THREE.MeshBasicMaterial(
{
color: 0xff2200,
depthTest: true,
transparent: true,
opacity: 1.0
}
);
// Creates the Mesh of the Atom's Particle's State #1
atom_particle_mesh_1 = new THREE.Mesh(atom_particle_geometry_1, atom_particle_material_1);
// Translates/Moves the Atom's Particle's State #1
// -2.51 units, regarding the X Axis
atom_particle_mesh_1.position.x = -2.51;
// Creates the group for the Atom's Particle's State's Pivot #1
atom_particle_state_pivot_1 = new THREE.Group();
// Adds the Mesh of the Atom's Particle's State #1
// the group for the Atom's Particle's State's Pivot #1
atom_particle_state_pivot_1.add(atom_particle_mesh_1);
} | function create_atom_particle_state_1() {
// Creates the Geometry of the Sphere representing
// the Atom's Particle #1
atom_particle_geometry_1 = new THREE.SphereGeometry(0.22, 40, 40);
// Creates the Material of the Sphere representing
// the Atom's Particle #1
atom_particle_material_1 = new THREE.MeshBasicMaterial(
{
color: 0xff2200,
depthTest: true,
transparent: true,
opacity: 1.0
}
);
// Creates the Mesh of the Atom's Particle's State #1
atom_particle_mesh_1 = new THREE.Mesh(atom_particle_geometry_1, atom_particle_material_1);
// Translates/Moves the Atom's Particle's State #1
// -2.51 units, regarding the X Axis
atom_particle_mesh_1.position.x = -2.51;
// Creates the group for the Atom's Particle's State's Pivot #1
atom_particle_state_pivot_1 = new THREE.Group();
// Adds the Mesh of the Atom's Particle's State #1
// the group for the Atom's Particle's State's Pivot #1
atom_particle_state_pivot_1.add(atom_particle_mesh_1);
} |
JavaScript | function add_atom_orbit_state_to_scene_1() {
// Creates the Atom's Particle's State's Orbit #1
create_atom_particle_state_orbit_1();
// Creates the Atom's Particle's State #1
create_atom_particle_state_1();
// Creates the group for the Atom's State's Pivot #1
atom_state_pivot_1 = new THREE.Group();
// Adds the Mesh of the Atom's State's Orbit #1 to
// the group for the Atom's State's Pivot #1
atom_state_pivot_1.add(atom_orbit_mesh_1);
// Adds the Mesh of the Atom's Particle's State's Pivot #1 to
// the group for the Atom's State's Pivot #1
atom_state_pivot_1.add(atom_particle_state_pivot_1);
// Adds the group for the Atom's State's Pivot #1 to
// the Scene (Atom Representation Scene)
atom_representation_scene.add(atom_state_pivot_1);
} | function add_atom_orbit_state_to_scene_1() {
// Creates the Atom's Particle's State's Orbit #1
create_atom_particle_state_orbit_1();
// Creates the Atom's Particle's State #1
create_atom_particle_state_1();
// Creates the group for the Atom's State's Pivot #1
atom_state_pivot_1 = new THREE.Group();
// Adds the Mesh of the Atom's State's Orbit #1 to
// the group for the Atom's State's Pivot #1
atom_state_pivot_1.add(atom_orbit_mesh_1);
// Adds the Mesh of the Atom's Particle's State's Pivot #1 to
// the group for the Atom's State's Pivot #1
atom_state_pivot_1.add(atom_particle_state_pivot_1);
// Adds the group for the Atom's State's Pivot #1 to
// the Scene (Atom Representation Scene)
atom_representation_scene.add(atom_state_pivot_1);
} |
JavaScript | function create_atom_particle_state_2() {
// Creates the Geometry of the Sphere representing
// the Atom's Particle #2
atom_particle_geometry_2 = new THREE.SphereGeometry(0.22, 40, 40);
// Creates the Material of the Sphere representing
// the Atom's Particle #2
atom_particle_material_2 = new THREE.MeshBasicMaterial(
{
color: 0xff2200,
depthTest: true,
transparent: true,
opacity: 1.0
}
);
// Creates the Mesh of the Atom's Particle's State #2
atom_particle_mesh_2 = new THREE.Mesh(atom_particle_geometry_2, atom_particle_material_2);
// Translates/Moves the Atom's Particle's State #2
// 2.51 units, regarding the Z Axis
atom_particle_mesh_2.position.z = 2.51;
// Creates the group for the Atom's Particle's State's Pivot #2
atom_particle_state_pivot_2 = new THREE.Group();
// Adds the Mesh of the Atom's Particle's State #2
// the group for the Atom's Particle's State's Pivot #2
atom_particle_state_pivot_2.add(atom_particle_mesh_2);
} | function create_atom_particle_state_2() {
// Creates the Geometry of the Sphere representing
// the Atom's Particle #2
atom_particle_geometry_2 = new THREE.SphereGeometry(0.22, 40, 40);
// Creates the Material of the Sphere representing
// the Atom's Particle #2
atom_particle_material_2 = new THREE.MeshBasicMaterial(
{
color: 0xff2200,
depthTest: true,
transparent: true,
opacity: 1.0
}
);
// Creates the Mesh of the Atom's Particle's State #2
atom_particle_mesh_2 = new THREE.Mesh(atom_particle_geometry_2, atom_particle_material_2);
// Translates/Moves the Atom's Particle's State #2
// 2.51 units, regarding the Z Axis
atom_particle_mesh_2.position.z = 2.51;
// Creates the group for the Atom's Particle's State's Pivot #2
atom_particle_state_pivot_2 = new THREE.Group();
// Adds the Mesh of the Atom's Particle's State #2
// the group for the Atom's Particle's State's Pivot #2
atom_particle_state_pivot_2.add(atom_particle_mesh_2);
} |
JavaScript | function add_atom_orbit_state_to_scene_2() {
// Creates the Atom's Particle's State's Orbit #2
create_atom_particle_state_orbit_2();
// Creates the Atom's Particle's State #2
create_atom_particle_state_2();
// Creates the group for the Atom's State's Pivot #2
atom_state_pivot_2 = new THREE.Group();
// Adds the Mesh of the Atom's State's Orbit #2 to
// the group for the Atom's State's Pivot #2
atom_state_pivot_2.add(atom_orbit_mesh_2);
// Adds the Mesh of the Atom's Particle's State's Pivot #1 to
// the group for the Atom's State's Pivot #2
atom_state_pivot_2.add(atom_particle_state_pivot_2);
// Rotates the Atom's State's Pivot #2 PI/2
// (i.e., 90º degrees), regarding the Y Axis
atom_state_pivot_2.rotation.x += Math.PI / 2;
// Adds the group for the Atom's State's Pivot #2 to
// the Scene (Atom Representation Scene)
atom_representation_scene.add(atom_state_pivot_2);
} | function add_atom_orbit_state_to_scene_2() {
// Creates the Atom's Particle's State's Orbit #2
create_atom_particle_state_orbit_2();
// Creates the Atom's Particle's State #2
create_atom_particle_state_2();
// Creates the group for the Atom's State's Pivot #2
atom_state_pivot_2 = new THREE.Group();
// Adds the Mesh of the Atom's State's Orbit #2 to
// the group for the Atom's State's Pivot #2
atom_state_pivot_2.add(atom_orbit_mesh_2);
// Adds the Mesh of the Atom's Particle's State's Pivot #1 to
// the group for the Atom's State's Pivot #2
atom_state_pivot_2.add(atom_particle_state_pivot_2);
// Rotates the Atom's State's Pivot #2 PI/2
// (i.e., 90º degrees), regarding the Y Axis
atom_state_pivot_2.rotation.x += Math.PI / 2;
// Adds the group for the Atom's State's Pivot #2 to
// the Scene (Atom Representation Scene)
atom_representation_scene.add(atom_state_pivot_2);
} |
JavaScript | function create_atom_particle_state_3() {
// Creates the Geometry of the Sphere representing
// the Atom's Particle #3
atom_particle_geometry_3 = new THREE.SphereGeometry(0.22, 40, 40);
// Creates the Material of the Sphere representing
// the Atom's Particle #3
atom_particle_material_3 = new THREE.MeshBasicMaterial(
{
color: 0xff2200,
depthTest: true,
transparent: true,
opacity: 1.0
}
);
// Creates the Mesh of the Atom's Particle's State #3
atom_particle_mesh_3 = new THREE.Mesh(atom_particle_geometry_3, atom_particle_material_3);
// Translates/Moves the Atom's Particle's State #3
// 2.51 units, regarding the Z Axis
atom_particle_mesh_3.position.z = 2.51;
// Creates the group for the Atom's Particle's State's Pivot #3
atom_particle_state_pivot_3 = new THREE.Group();
// Adds the Mesh of the Atom's Particle #3
// the group for the Atom's Particle's State's Pivot #3
atom_particle_state_pivot_3.add(atom_particle_mesh_3);
} | function create_atom_particle_state_3() {
// Creates the Geometry of the Sphere representing
// the Atom's Particle #3
atom_particle_geometry_3 = new THREE.SphereGeometry(0.22, 40, 40);
// Creates the Material of the Sphere representing
// the Atom's Particle #3
atom_particle_material_3 = new THREE.MeshBasicMaterial(
{
color: 0xff2200,
depthTest: true,
transparent: true,
opacity: 1.0
}
);
// Creates the Mesh of the Atom's Particle's State #3
atom_particle_mesh_3 = new THREE.Mesh(atom_particle_geometry_3, atom_particle_material_3);
// Translates/Moves the Atom's Particle's State #3
// 2.51 units, regarding the Z Axis
atom_particle_mesh_3.position.z = 2.51;
// Creates the group for the Atom's Particle's State's Pivot #3
atom_particle_state_pivot_3 = new THREE.Group();
// Adds the Mesh of the Atom's Particle #3
// the group for the Atom's Particle's State's Pivot #3
atom_particle_state_pivot_3.add(atom_particle_mesh_3);
} |
JavaScript | function add_atom_orbit_state_to_scene_3() {
// Creates the Atom's Particle's State's Orbit #3
create_atom_particle_state_orbit_3();
// Creates the Atom's Particle's State #3
create_atom_particle_state_3();
// Creates the group for the Atom's State's Pivot #3
atom_state_pivot_3 = new THREE.Group();
// Adds the Mesh of the Atom's State's Orbit #3 to
// the group for the Atom's State's Pivot #3
atom_state_pivot_3.add(atom_orbit_mesh_3);
// Adds the Mesh of the Atom's Particle's State's Pivot #3 to
// the group for the Atom's State's Pivot #3
atom_state_pivot_3.add(atom_particle_state_pivot_3);
// Adds the group for the Atom's State's Pivot #3 to
// the Scene (Atom Representation Scene)
atom_representation_scene.add(atom_state_pivot_3);
} | function add_atom_orbit_state_to_scene_3() {
// Creates the Atom's Particle's State's Orbit #3
create_atom_particle_state_orbit_3();
// Creates the Atom's Particle's State #3
create_atom_particle_state_3();
// Creates the group for the Atom's State's Pivot #3
atom_state_pivot_3 = new THREE.Group();
// Adds the Mesh of the Atom's State's Orbit #3 to
// the group for the Atom's State's Pivot #3
atom_state_pivot_3.add(atom_orbit_mesh_3);
// Adds the Mesh of the Atom's Particle's State's Pivot #3 to
// the group for the Atom's State's Pivot #3
atom_state_pivot_3.add(atom_particle_state_pivot_3);
// Adds the group for the Atom's State's Pivot #3 to
// the Scene (Atom Representation Scene)
atom_representation_scene.add(atom_state_pivot_3);
} |
JavaScript | function create_atom_particle_state_4() {
// Creates the Geometry of the Sphere representing
// the Atom's Particle #4
atom_particle_geometry_4 = new THREE.SphereGeometry(0.22, 40, 40);
// Creates the Material of the Sphere representing
// the Atom's Particle #4
atom_particle_material_4 = new THREE.MeshBasicMaterial(
{
color: 0xff2200,
depthTest: true,
transparent: true,
opacity: 1.0
}
);
// Creates the Mesh of the Atom's Particle's State #4
atom_particle_mesh_4 = new THREE.Mesh(atom_particle_geometry_4, atom_particle_material_4);
// Translates/Moves the Atom's Particle's State #4
// -2.51 units, regarding the Z Axis
atom_particle_mesh_4.position.z = -2.51;
// Creates the group for the Atom's Particle's State's Pivot #4
atom_particle_state_pivot_4 = new THREE.Group();
// Adds the Mesh of the Atom's Particle #4
// the group for the Atom's Particle's State's Pivot #4
atom_particle_state_pivot_4.add(atom_particle_mesh_4);
} | function create_atom_particle_state_4() {
// Creates the Geometry of the Sphere representing
// the Atom's Particle #4
atom_particle_geometry_4 = new THREE.SphereGeometry(0.22, 40, 40);
// Creates the Material of the Sphere representing
// the Atom's Particle #4
atom_particle_material_4 = new THREE.MeshBasicMaterial(
{
color: 0xff2200,
depthTest: true,
transparent: true,
opacity: 1.0
}
);
// Creates the Mesh of the Atom's Particle's State #4
atom_particle_mesh_4 = new THREE.Mesh(atom_particle_geometry_4, atom_particle_material_4);
// Translates/Moves the Atom's Particle's State #4
// -2.51 units, regarding the Z Axis
atom_particle_mesh_4.position.z = -2.51;
// Creates the group for the Atom's Particle's State's Pivot #4
atom_particle_state_pivot_4 = new THREE.Group();
// Adds the Mesh of the Atom's Particle #4
// the group for the Atom's Particle's State's Pivot #4
atom_particle_state_pivot_4.add(atom_particle_mesh_4);
} |
JavaScript | function add_atom_orbit_state_to_scene_4() {
// Creates the Atom's Particle's State's Orbit #4
create_atom_particle_state_orbit_4();
// Creates the Atom's Particle's State #4
create_atom_particle_state_4();
// Creates the group for the Atom's State's Pivot #4
atom_state_pivot_4 = new THREE.Group();
// Adds the Mesh of the Atom's State's Orbit #4 to
// the group for the Atom's State's Pivot #4
atom_state_pivot_4.add(atom_orbit_mesh_4);
// Adds the Mesh of the Atom's Particle's State's Pivot #4 to
// the group for the Atom's State's Pivot #4
atom_state_pivot_4.add(atom_particle_state_pivot_4);
// Adds the group for the Atom's State's Pivot #4 to
// the Scene (Atom Representation Scene)
atom_representation_scene.add(atom_state_pivot_4);
} | function add_atom_orbit_state_to_scene_4() {
// Creates the Atom's Particle's State's Orbit #4
create_atom_particle_state_orbit_4();
// Creates the Atom's Particle's State #4
create_atom_particle_state_4();
// Creates the group for the Atom's State's Pivot #4
atom_state_pivot_4 = new THREE.Group();
// Adds the Mesh of the Atom's State's Orbit #4 to
// the group for the Atom's State's Pivot #4
atom_state_pivot_4.add(atom_orbit_mesh_4);
// Adds the Mesh of the Atom's Particle's State's Pivot #4 to
// the group for the Atom's State's Pivot #4
atom_state_pivot_4.add(atom_particle_state_pivot_4);
// Adds the group for the Atom's State's Pivot #4 to
// the Scene (Atom Representation Scene)
atom_representation_scene.add(atom_state_pivot_4);
} |
JavaScript | function add_lights_to_scene() {
// Creates a white directional light
var directional_light_1 = new THREE.DirectionalLight(0xffffff);
// Sets the direction/position (x=1, y=1, z=1) of
// the previously created directional light
directional_light_1.position.set(1, 1, 1);
// Adds the previously created directional light to
// Scene (Atom Representation Scene)
atom_representation_scene.add(directional_light_1);
// Creates a blue directional light
var directional_light_2 = new THREE.DirectionalLight(0x002288);
// Sets the direction/position (x=-1, y=-1, z=-1) of
// the previously created directional light
directional_light_2.position.set(- 1, - 1, - 1);
// Adds the previously created directional light to
// Scene (Atom Representation Scene)
atom_representation_scene.add(directional_light_2);
// Creates a gray ambient light
var ambient_light = new THREE.AmbientLight(0x222222);
// Adds the previously created ambient light to
// Scene (Atom Representation Scene)
atom_representation_scene.add(ambient_light);
} | function add_lights_to_scene() {
// Creates a white directional light
var directional_light_1 = new THREE.DirectionalLight(0xffffff);
// Sets the direction/position (x=1, y=1, z=1) of
// the previously created directional light
directional_light_1.position.set(1, 1, 1);
// Adds the previously created directional light to
// Scene (Atom Representation Scene)
atom_representation_scene.add(directional_light_1);
// Creates a blue directional light
var directional_light_2 = new THREE.DirectionalLight(0x002288);
// Sets the direction/position (x=-1, y=-1, z=-1) of
// the previously created directional light
directional_light_2.position.set(- 1, - 1, - 1);
// Adds the previously created directional light to
// Scene (Atom Representation Scene)
atom_representation_scene.add(directional_light_2);
// Creates a gray ambient light
var ambient_light = new THREE.AmbientLight(0x222222);
// Adds the previously created ambient light to
// Scene (Atom Representation Scene)
atom_representation_scene.add(ambient_light);
} |
JavaScript | function create_renderer_of_scene() {
renderer = new THREE.WebGLRenderer(
{
antialias: true
}
);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
} | function create_renderer_of_scene() {
renderer = new THREE.WebGLRenderer(
{
antialias: true
}
);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
} |
JavaScript | function trigger_event_listeners() {
// Handles/Triggers the Function for
// changes in the Motions' Radio
on_change_motions();
// Handles/Triggers the Function for
// changes in the Camera View's Radio
on_change_camera_view();
// Handles/Triggers the Function for
// changes in the XZ Grid's Checkbox
on_check_xz_grid();
// Handles/Triggers the Function for
// changes in the Atomic Orbit's Checkbox
on_check_atomic_orbits();
// Handles/Triggers the Function for
// changes in the Atom's Particle's State #1 Checkbox
on_check_atom_particle_state_1();
// Handles/Triggers the Function for
// changes in the Atom's Particle's State #2 Checkbox
on_check_atom_particle_state_2();
// Handles/Triggers the Function for
// changes in the Atom's Particle's State #3 Checkbox
on_check_atom_particle_state_3();
// Handles/Triggers the Function for
// changes in the Atom's Particle's State #4 Checkbox
on_check_atom_particle_state_4();
} | function trigger_event_listeners() {
// Handles/Triggers the Function for
// changes in the Motions' Radio
on_change_motions();
// Handles/Triggers the Function for
// changes in the Camera View's Radio
on_change_camera_view();
// Handles/Triggers the Function for
// changes in the XZ Grid's Checkbox
on_check_xz_grid();
// Handles/Triggers the Function for
// changes in the Atomic Orbit's Checkbox
on_check_atomic_orbits();
// Handles/Triggers the Function for
// changes in the Atom's Particle's State #1 Checkbox
on_check_atom_particle_state_1();
// Handles/Triggers the Function for
// changes in the Atom's Particle's State #2 Checkbox
on_check_atom_particle_state_2();
// Handles/Triggers the Function for
// changes in the Atom's Particle's State #3 Checkbox
on_check_atom_particle_state_3();
// Handles/Triggers the Function for
// changes in the Atom's Particle's State #4 Checkbox
on_check_atom_particle_state_4();
} |
JavaScript | function on_window_resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
controls.handleResize();
render();
} | function on_window_resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
controls.handleResize();
render();
} |
JavaScript | function on_document_mouse_move(event) {
// The following line would stop any other event handler from firing
// (such as the mouse's TrackballControls)
event.preventDefault();
// Update the mouse variable
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
} | function on_document_mouse_move(event) {
// The following line would stop any other event handler from firing
// (such as the mouse's TrackballControls)
event.preventDefault();
// Update the mouse variable
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
} |
JavaScript | function on_change_motions() {
for(var i = 0, length = motions_radios.length; i < length; i++) {
motions_radios[i].onchange = function() {
if(motions_radios[0].checked) {
motions_factor = 1.0;
}
else {
motions_factor = 0.0;
}
start_trackball_controls();
}
}
} | function on_change_motions() {
for(var i = 0, length = motions_radios.length; i < length; i++) {
motions_radios[i].onchange = function() {
if(motions_radios[0].checked) {
motions_factor = 1.0;
}
else {
motions_factor = 0.0;
}
start_trackball_controls();
}
}
} |
JavaScript | function on_change_camera_view() {
for(var i = 0, length = camera_view_radios.length; i < length; i++) {
camera_view_radios[i].onchange = function() {
if(camera_view_radios[0].checked) {
reset_camera();
camera_top_view();
}
else {
reset_camera();
camera_perspective_view();
}
start_trackball_controls();
}
}
} | function on_change_camera_view() {
for(var i = 0, length = camera_view_radios.length; i < length; i++) {
camera_view_radios[i].onchange = function() {
if(camera_view_radios[0].checked) {
reset_camera();
camera_top_view();
}
else {
reset_camera();
camera_perspective_view();
}
start_trackball_controls();
}
}
} |
JavaScript | function on_check_xz_grid() {
var show_xz_grid = document.getElementById("show_xz_grid");
show_xz_grid.onchange = function() {
if(show_xz_grid.checked) {
atom_representation_scene.add(xz_grid);
}
else {
atom_representation_scene.remove(xz_grid);
}
}
} | function on_check_xz_grid() {
var show_xz_grid = document.getElementById("show_xz_grid");
show_xz_grid.onchange = function() {
if(show_xz_grid.checked) {
atom_representation_scene.add(xz_grid);
}
else {
atom_representation_scene.remove(xz_grid);
}
}
} |
JavaScript | function on_check_atomic_orbits() {
var show_atomic_orbits = document.getElementById("show_atomic_orbits");
show_atomic_orbits.onchange = function() {
if(show_atomic_orbits.checked) {
if(atom_particle_state_checked_1) {
atom_orbit_mesh_1.material.opacity = 1.0;
atom_orbit_mesh_1.material.depthTest = true;
}
if(atom_particle_state_checked_2) {
atom_orbit_mesh_2.material.opacity = 1.0;
atom_orbit_mesh_2.material.depthTest = true;
}
if(atom_particle_state_checked_3) {
atom_orbit_mesh_3.material.opacity = 1.0;
atom_orbit_mesh_3.material.depthTest = true;
}
if(atom_particle_state_checked_4) {
atom_orbit_mesh_4.material.opacity = 1.0;
atom_orbit_mesh_4.material.depthTest = true;
}
atomic_orbits_checked = true;
}
else {
atom_orbit_mesh_1.material.opacity = 0.0;
atom_orbit_mesh_1.material.depthTest = false;
atom_orbit_mesh_2.material.opacity = 0.0;
atom_orbit_mesh_2.material.depthTest = false;
atom_orbit_mesh_3.material.opacity = 0.0;
atom_orbit_mesh_3.material.depthTest = false;
atom_orbit_mesh_4.material.opacity = 0.0;
atom_orbit_mesh_4.material.depthTest = false;
atomic_orbits_checked = false;
}
}
} | function on_check_atomic_orbits() {
var show_atomic_orbits = document.getElementById("show_atomic_orbits");
show_atomic_orbits.onchange = function() {
if(show_atomic_orbits.checked) {
if(atom_particle_state_checked_1) {
atom_orbit_mesh_1.material.opacity = 1.0;
atom_orbit_mesh_1.material.depthTest = true;
}
if(atom_particle_state_checked_2) {
atom_orbit_mesh_2.material.opacity = 1.0;
atom_orbit_mesh_2.material.depthTest = true;
}
if(atom_particle_state_checked_3) {
atom_orbit_mesh_3.material.opacity = 1.0;
atom_orbit_mesh_3.material.depthTest = true;
}
if(atom_particle_state_checked_4) {
atom_orbit_mesh_4.material.opacity = 1.0;
atom_orbit_mesh_4.material.depthTest = true;
}
atomic_orbits_checked = true;
}
else {
atom_orbit_mesh_1.material.opacity = 0.0;
atom_orbit_mesh_1.material.depthTest = false;
atom_orbit_mesh_2.material.opacity = 0.0;
atom_orbit_mesh_2.material.depthTest = false;
atom_orbit_mesh_3.material.opacity = 0.0;
atom_orbit_mesh_3.material.depthTest = false;
atom_orbit_mesh_4.material.opacity = 0.0;
atom_orbit_mesh_4.material.depthTest = false;
atomic_orbits_checked = false;
}
}
} |
JavaScript | function on_check_atom_particle_state_1() {
var show_atom_particle_state_1 = document.getElementById("show_atom_particle_state_1");
show_atom_particle_state_1.onchange = function() {
if(show_atom_particle_state_1.checked) {
if(atomic_orbits_checked) {
atom_orbit_mesh_1.material.opacity = 1.0;
atom_orbit_mesh_1.material.depthTest = true;
}
atom_particle_mesh_1.material.opacity = 1.0;
atom_particle_mesh_1.material.depthTest = true;
atom_particle_state_checked_1 = true;
}
else {
atom_orbit_mesh_1.material.opacity = 0.0;
atom_orbit_mesh_1.material.depthTest = false;
atom_particle_mesh_1.material.opacity = 0.0;
atom_particle_mesh_1.material.depthTest = false;
atom_particle_state_checked_1 = false;
}
}
} | function on_check_atom_particle_state_1() {
var show_atom_particle_state_1 = document.getElementById("show_atom_particle_state_1");
show_atom_particle_state_1.onchange = function() {
if(show_atom_particle_state_1.checked) {
if(atomic_orbits_checked) {
atom_orbit_mesh_1.material.opacity = 1.0;
atom_orbit_mesh_1.material.depthTest = true;
}
atom_particle_mesh_1.material.opacity = 1.0;
atom_particle_mesh_1.material.depthTest = true;
atom_particle_state_checked_1 = true;
}
else {
atom_orbit_mesh_1.material.opacity = 0.0;
atom_orbit_mesh_1.material.depthTest = false;
atom_particle_mesh_1.material.opacity = 0.0;
atom_particle_mesh_1.material.depthTest = false;
atom_particle_state_checked_1 = false;
}
}
} |
JavaScript | function on_check_atom_particle_state_2() {
var show_atom_particle_state_2 = document.getElementById("show_atom_particle_state_2");
show_atom_particle_state_2.onchange = function() {
if(show_atom_particle_state_2.checked) {
if(atomic_orbits_checked) {
atom_orbit_mesh_2.material.opacity = 1.0;
atom_orbit_mesh_2.material.depthTest = true;
}
atom_particle_mesh_2.material.opacity = 1.0;
atom_particle_mesh_2.material.depthTest = true;
atom_particle_state_checked_2 = true;
}
else {
atom_orbit_mesh_2.material.opacity = 0.0;
atom_orbit_mesh_2.material.depthTest = false;
atom_particle_mesh_2.material.opacity = 0.0;
atom_particle_mesh_2.material.depthTest = false;
atom_particle_state_checked_2 = false;
}
}
} | function on_check_atom_particle_state_2() {
var show_atom_particle_state_2 = document.getElementById("show_atom_particle_state_2");
show_atom_particle_state_2.onchange = function() {
if(show_atom_particle_state_2.checked) {
if(atomic_orbits_checked) {
atom_orbit_mesh_2.material.opacity = 1.0;
atom_orbit_mesh_2.material.depthTest = true;
}
atom_particle_mesh_2.material.opacity = 1.0;
atom_particle_mesh_2.material.depthTest = true;
atom_particle_state_checked_2 = true;
}
else {
atom_orbit_mesh_2.material.opacity = 0.0;
atom_orbit_mesh_2.material.depthTest = false;
atom_particle_mesh_2.material.opacity = 0.0;
atom_particle_mesh_2.material.depthTest = false;
atom_particle_state_checked_2 = false;
}
}
} |
JavaScript | function on_check_atom_particle_state_3() {
var show_atom_particle_state_3 = document.getElementById("show_atom_particle_state_3");
show_atom_particle_state_3.onchange = function() {
if(show_atom_particle_state_3.checked) {
if(atomic_orbits_checked) {
atom_orbit_mesh_3.material.opacity = 1.0;
atom_orbit_mesh_3.material.depthTest = true;
}
atom_particle_mesh_3.material.opacity = 1.0;
atom_particle_mesh_3.material.depthTest = true;
atom_particle_state_checked_3 = true;
}
else {
atom_orbit_mesh_3.material.opacity = 0.0;
atom_orbit_mesh_3.material.depthTest = false;
atom_particle_mesh_3.material.opacity = 0.0;
atom_particle_mesh_3.material.depthTest = false;
atom_particle_state_checked_3 = false;
}
}
} | function on_check_atom_particle_state_3() {
var show_atom_particle_state_3 = document.getElementById("show_atom_particle_state_3");
show_atom_particle_state_3.onchange = function() {
if(show_atom_particle_state_3.checked) {
if(atomic_orbits_checked) {
atom_orbit_mesh_3.material.opacity = 1.0;
atom_orbit_mesh_3.material.depthTest = true;
}
atom_particle_mesh_3.material.opacity = 1.0;
atom_particle_mesh_3.material.depthTest = true;
atom_particle_state_checked_3 = true;
}
else {
atom_orbit_mesh_3.material.opacity = 0.0;
atom_orbit_mesh_3.material.depthTest = false;
atom_particle_mesh_3.material.opacity = 0.0;
atom_particle_mesh_3.material.depthTest = false;
atom_particle_state_checked_3 = false;
}
}
} |
JavaScript | function on_check_atom_particle_state_4() {
var show_atom_particle_state_4 = document.getElementById("show_atom_particle_state_4");
show_atom_particle_state_4.onchange = function() {
if(show_atom_particle_state_4.checked) {
if(atomic_orbits_checked) {
atom_orbit_mesh_4.material.opacity = 1.0;
atom_orbit_mesh_4.material.depthTest = true;
}
atom_particle_mesh_4.material.opacity = 1.0;
atom_particle_mesh_4.material.depthTest = true;
atom_particle_state_checked_4 = true;
}
else {
atom_orbit_mesh_4.material.opacity = 0.0;
atom_orbit_mesh_4.material.depthTest = false;
atom_particle_mesh_4.material.opacity = 0.0;
atom_particle_mesh_4.material.depthTest = false;
atom_particle_state_checked_4 = false;
}
}
} | function on_check_atom_particle_state_4() {
var show_atom_particle_state_4 = document.getElementById("show_atom_particle_state_4");
show_atom_particle_state_4.onchange = function() {
if(show_atom_particle_state_4.checked) {
if(atomic_orbits_checked) {
atom_orbit_mesh_4.material.opacity = 1.0;
atom_orbit_mesh_4.material.depthTest = true;
}
atom_particle_mesh_4.material.opacity = 1.0;
atom_particle_mesh_4.material.depthTest = true;
atom_particle_state_checked_4 = true;
}
else {
atom_orbit_mesh_4.material.opacity = 0.0;
atom_orbit_mesh_4.material.depthTest = false;
atom_particle_mesh_4.material.opacity = 0.0;
atom_particle_mesh_4.material.depthTest = false;
atom_particle_state_checked_4 = false;
}
}
} |
JavaScript | function atom_nucleus_and_particles_rotation_movements() {
var atom_nucleus_rotation_speed = ( motions_factor * 0.0001 * 28 );
var atom_particles_rotation_speed = ( motions_factor * 0.01 * 28 );
atom_nucleus_mesh.rotation.y += atom_nucleus_rotation_speed;
atom_particle_mesh_1.rotation.y += atom_particles_rotation_speed;
atom_particle_mesh_2.rotation.y += atom_particles_rotation_speed;
atom_particle_mesh_3.rotation.y += atom_particles_rotation_speed;
atom_particle_mesh_4.rotation.y += atom_particles_rotation_speed;
} | function atom_nucleus_and_particles_rotation_movements() {
var atom_nucleus_rotation_speed = ( motions_factor * 0.0001 * 28 );
var atom_particles_rotation_speed = ( motions_factor * 0.01 * 28 );
atom_nucleus_mesh.rotation.y += atom_nucleus_rotation_speed;
atom_particle_mesh_1.rotation.y += atom_particles_rotation_speed;
atom_particle_mesh_2.rotation.y += atom_particles_rotation_speed;
atom_particle_mesh_3.rotation.y += atom_particles_rotation_speed;
atom_particle_mesh_4.rotation.y += atom_particles_rotation_speed;
} |
JavaScript | function particles_translaction_movements() {
// Creating the quarternion for the Atom's State #1
var quaternion_for_atom_state_1 = new THREE.Quaternion();
// Setting and applying the quarternion's Y Axis for the Atom's State #1
quaternion_for_atom_state_1.setFromAxisAngle( y_axis, ( motions_factor * 0.02 ) );
atom_particle_mesh_1.position.applyQuaternion(quaternion_for_atom_state_1);
// Creating the quarternion for the Atom's State #2
var quaternion_for_atom_state_2 = new THREE.Quaternion();
// Setting and applying the quarternion's X Axis for the Atom's State #2
quaternion_for_atom_state_2.setFromAxisAngle( x_axis, ( motions_factor * 0.02 ) );
atom_particle_mesh_2.position.applyQuaternion(quaternion_for_atom_state_2);
// Creating the quarternion for the Atom's State #3
var quaternion_for_atom_state_3 = new THREE.Quaternion();
// Setting and applying the quarternion's XY Axis for the Atom's State #3
quaternion_for_atom_state_3.setFromAxisAngle( xy_axis_1, ( motions_factor * 0.02 ) );
atom_particle_mesh_3.position.applyQuaternion(quaternion_for_atom_state_3);
// Creating the quarternion for the Atom's State #4
var quaternion_for_atom_state_4 = new THREE.Quaternion();
// Setting and applying the quarternion's XY Axis for the Atom's State #4
quaternion_for_atom_state_4.setFromAxisAngle( xy_axis_2, ( motions_factor * 0.02 ) );
atom_particle_mesh_4.position.applyQuaternion(quaternion_for_atom_state_4);
} | function particles_translaction_movements() {
// Creating the quarternion for the Atom's State #1
var quaternion_for_atom_state_1 = new THREE.Quaternion();
// Setting and applying the quarternion's Y Axis for the Atom's State #1
quaternion_for_atom_state_1.setFromAxisAngle( y_axis, ( motions_factor * 0.02 ) );
atom_particle_mesh_1.position.applyQuaternion(quaternion_for_atom_state_1);
// Creating the quarternion for the Atom's State #2
var quaternion_for_atom_state_2 = new THREE.Quaternion();
// Setting and applying the quarternion's X Axis for the Atom's State #2
quaternion_for_atom_state_2.setFromAxisAngle( x_axis, ( motions_factor * 0.02 ) );
atom_particle_mesh_2.position.applyQuaternion(quaternion_for_atom_state_2);
// Creating the quarternion for the Atom's State #3
var quaternion_for_atom_state_3 = new THREE.Quaternion();
// Setting and applying the quarternion's XY Axis for the Atom's State #3
quaternion_for_atom_state_3.setFromAxisAngle( xy_axis_1, ( motions_factor * 0.02 ) );
atom_particle_mesh_3.position.applyQuaternion(quaternion_for_atom_state_3);
// Creating the quarternion for the Atom's State #4
var quaternion_for_atom_state_4 = new THREE.Quaternion();
// Setting and applying the quarternion's XY Axis for the Atom's State #4
quaternion_for_atom_state_4.setFromAxisAngle( xy_axis_2, ( motions_factor * 0.02 ) );
atom_particle_mesh_4.position.applyQuaternion(quaternion_for_atom_state_4);
} |
JavaScript | pick(...attrs) {
return attrs.reduce((memo, attr) => Object.assign(
memo,
this.has(attr) ? {[attr]: this.get(attr)} : {}
), {});
} | pick(...attrs) {
return attrs.reduce((memo, attr) => Object.assign(
memo,
this.has(attr) ? {[attr]: this.get(attr)} : {}
), {});
} |
JavaScript | fetch(options={}) {
options = {parse: true, method: 'GET', ...options};
return this.sync(this, options)
.then(([json, response]) => {
var serverAttrs = options.parse ? this.parse(json, options) : json;
this.set(serverAttrs, options);
// sync update
this.triggerUpdate();
return [this, response];
})
.catch((response) => Promise.reject(response));
} | fetch(options={}) {
options = {parse: true, method: 'GET', ...options};
return this.sync(this, options)
.then(([json, response]) => {
var serverAttrs = options.parse ? this.parse(json, options) : json;
this.set(serverAttrs, options);
// sync update
this.triggerUpdate();
return [this, response];
})
.catch((response) => Promise.reject(response));
} |
JavaScript | save(attrs, options) {
var previousAttributes = this.toJSON();
options = {parse: true, ...options};
attrs = attrs || this.toJSON();
// If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`
if (!options.wait) {
this.set(attrs, options);
} else {
// sneaky: this will show up at this point if you .toJSON(), but it will not
// be associated with an update. this is so that in the sync method, they can get all
// attributes via .toJSON()
this.attributes = {...this.attributes, ...attrs};
}
options.method = this.isNew() ? 'POST' : options.patch ? 'PATCH' : 'PUT';
if (options.method === 'PATCH' && !options.attrs) {
options.attrs = attrs;
}
return this.sync(this, options)
.then(([json, response]) => {
var serverAttrs = options.parse ? this.parse(json, options) : json;
if (options.wait) {
serverAttrs = {...attrs, ...serverAttrs};
}
// avoid triggering any updates in the set call since we'll do it immediately after
this.set(serverAttrs, {silent: true, ...options});
// sync update
this.triggerUpdate();
return [this, response];
})
.catch((response) => {
if (!options.wait) {
// keep the clear silent so that we only render when we reset attributes
this.clear({silent: true}).set(previousAttributes, options);
} else {
this.attributes = previousAttributes;
}
return Promise.reject(response);
});
} | save(attrs, options) {
var previousAttributes = this.toJSON();
options = {parse: true, ...options};
attrs = attrs || this.toJSON();
// If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`
if (!options.wait) {
this.set(attrs, options);
} else {
// sneaky: this will show up at this point if you .toJSON(), but it will not
// be associated with an update. this is so that in the sync method, they can get all
// attributes via .toJSON()
this.attributes = {...this.attributes, ...attrs};
}
options.method = this.isNew() ? 'POST' : options.patch ? 'PATCH' : 'PUT';
if (options.method === 'PATCH' && !options.attrs) {
options.attrs = attrs;
}
return this.sync(this, options)
.then(([json, response]) => {
var serverAttrs = options.parse ? this.parse(json, options) : json;
if (options.wait) {
serverAttrs = {...attrs, ...serverAttrs};
}
// avoid triggering any updates in the set call since we'll do it immediately after
this.set(serverAttrs, {silent: true, ...options});
// sync update
this.triggerUpdate();
return [this, response];
})
.catch((response) => {
if (!options.wait) {
// keep the clear silent so that we only render when we reset attributes
this.clear({silent: true}).set(previousAttributes, options);
} else {
this.attributes = previousAttributes;
}
return Promise.reject(response);
});
} |
JavaScript | destroy(options={}) {
var request = this.isNew() ?
Promise.resolve([]) :
this.sync(this, {method: 'DELETE', ...options}),
collection = this.collection;
if (!options.wait) {
this.triggerUpdate();
this.collection?.remove(this, {silent: true});
}
return request.then(([json, response]) => {
if (options.wait && !this.isNew()) {
this.triggerUpdate();
this.collection?.remove(this, {silent: true});
}
return [this, response];
}).catch((response) => {
if (!options.wait && !this.isNew()) {
collection?.add(this);
}
return Promise.reject(response);
});
} | destroy(options={}) {
var request = this.isNew() ?
Promise.resolve([]) :
this.sync(this, {method: 'DELETE', ...options}),
collection = this.collection;
if (!options.wait) {
this.triggerUpdate();
this.collection?.remove(this, {silent: true});
}
return request.then(([json, response]) => {
if (options.wait && !this.isNew()) {
this.triggerUpdate();
this.collection?.remove(this, {silent: true});
}
return [this, response];
}).catch((response) => {
if (!options.wait && !this.isNew()) {
collection?.add(this);
}
return Promise.reject(response);
});
} |
JavaScript | url(options=this.urlOptions) {
var base = result(this, 'urlRoot', options) || result(this.collection, 'url', options) ||
urlError();
if (this.isNew()) {
return base;
}
return base.replace(/[^/]$/, '$&/') +
window.encodeURIComponent(this.get(this.constructor.idAttribute));
} | url(options=this.urlOptions) {
var base = result(this, 'urlRoot', options) || result(this.collection, 'url', options) ||
urlError();
if (this.isNew()) {
return base;
}
return base.replace(/[^/]$/, '$&/') +
window.encodeURIComponent(this.get(this.constructor.idAttribute));
} |
JavaScript | function generateResources(getResources, props) {
return Object.entries(getResources(ResourceKeys, props) || {})
.reduce((memo, [name, config={}]) =>
memo.concat([[name, {
modelKey: config.modelKey || name,
refetch: props.refetches?.includes(name),
...config
}]].concat(
// expand prefetched resources with their own options based on
// their prefetch props, and store those in the `prefetch` property
(config.prefetches || []).map((prefetch) => ([name, {
modelKey: config.modelKey || name,
...getResources(ResourceKeys, {...props, ...prefetch})[name],
prefetch
}]))
)), []);
} | function generateResources(getResources, props) {
return Object.entries(getResources(ResourceKeys, props) || {})
.reduce((memo, [name, config={}]) =>
memo.concat([[name, {
modelKey: config.modelKey || name,
refetch: props.refetches?.includes(name),
...config
}]].concat(
// expand prefetched resources with their own options based on
// their prefetch props, and store those in the `prefetch` property
(config.prefetches || []).map((prefetch) => ([name, {
modelKey: config.modelKey || name,
...getResources(ResourceKeys, {...props, ...prefetch})[name],
prefetch
}]))
)), []);
} |
JavaScript | function findConfig([name, {prefetch}], getResources, props) {
var [, config={}] = generateResources(getResources, props)
.find(([_name, _config={}]) => name === _name &&
// cheap deep equals
JSON.stringify(_config.prefetch) === JSON.stringify(prefetch)) || [];
return config;
} | function findConfig([name, {prefetch}], getResources, props) {
var [, config={}] = generateResources(getResources, props)
.find(([_name, _config={}]) => name === _name &&
// cheap deep equals
JSON.stringify(_config.prefetch) === JSON.stringify(prefetch)) || [];
return config;
} |
JavaScript | function buildResourcesLoadingState(resources, props, defaultState=LoadingStates.LOADED) {
return resources.reduce((state, [name, config]) => Object.assign(state, {
[getResourceState(name)]:
!config.refetch && (shouldBypassFetch(props, [name, config]) || getModelFromCache(config)) ?
defaultState :
(!hasAllDependencies(props, [, config]) ? LoadingStates.PENDING : LoadingStates.LOADING)
}), {});
} | function buildResourcesLoadingState(resources, props, defaultState=LoadingStates.LOADED) {
return resources.reduce((state, [name, config]) => Object.assign(state, {
[getResourceState(name)]:
!config.refetch && (shouldBypassFetch(props, [name, config]) || getModelFromCache(config)) ?
defaultState :
(!hasAllDependencies(props, [, config]) ? LoadingStates.PENDING : LoadingStates.LOADING)
}), {});
} |
JavaScript | function useForceUpdate() {
var [, forceUpdate] = useState({});
return () => forceUpdate({});
} | function useForceUpdate() {
var [, forceUpdate] = useState({});
return () => forceUpdate({});
} |
JavaScript | function useIsMounted() {
var isMountedRef = useRef(false);
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
return isMountedRef;
} | function useIsMounted() {
var isMountedRef = useRef(false);
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
return isMountedRef;
} |
JavaScript | function trackRequestTime(name, {params, options}) {
var measurementName = `${name}Fetch`,
fetchEntry;
// ensure that another resource request hasn't removed the perf mark
if (window.performance.getEntriesByName(name).length) {
window.performance.measure(measurementName, name);
fetchEntry = window.performance.getEntriesByName(measurementName).pop();
ResourcesConfig.track('API Fetch', {
Resource: name,
params,
options,
duration: Math.round(fetchEntry.duration)
});
window.performance.clearMarks(name);
window.performance.clearMeasures(measurementName);
}
} | function trackRequestTime(name, {params, options}) {
var measurementName = `${name}Fetch`,
fetchEntry;
// ensure that another resource request hasn't removed the perf mark
if (window.performance.getEntriesByName(name).length) {
window.performance.measure(measurementName, name);
fetchEntry = window.performance.getEntriesByName(measurementName).pop();
ResourcesConfig.track('API Fetch', {
Resource: name,
params,
options,
duration: Math.round(fetchEntry.duration)
});
window.performance.clearMarks(name);
window.performance.clearMeasures(measurementName);
}
} |
JavaScript | function modelAggregator(resources) {
var newModels = resources.reduce((memo, [name, config]) => Object.assign(memo, {
[getResourcePropertyName(name, config.modelKey)]: getModelFromCache(config) ||
getEmptyModel(config)
}), {});
return (models={}) => Object.keys(newModels).filter(
// this comparison is so that if no models have changed, we don't change state and rerender.
// this is only important when a model is cached when a component mounts, because it will still
// be included in resourcesToUpdate even though its model will be seeded in state already
(key) => models[key] !== newModels[key]
).length ? {...models, ...newModels} : models;
} | function modelAggregator(resources) {
var newModels = resources.reduce((memo, [name, config]) => Object.assign(memo, {
[getResourcePropertyName(name, config.modelKey)]: getModelFromCache(config) ||
getEmptyModel(config)
}), {});
return (models={}) => Object.keys(newModels).filter(
// this comparison is so that if no models have changed, we don't change state and rerender.
// this is only important when a model is cached when a component mounts, because it will still
// be included in resourcesToUpdate even though its model will be seeded in state already
(key) => models[key] !== newModels[key]
).length ? {...models, ...newModels} : models;
} |
JavaScript | function partitionResources(resourcesToUpdate, loadingStates) {
return resourcesToUpdate.reduce((memo, [name, config]) =>
config.refetch || config.prefetch || !hasLoaded(loadingStates[getResourceState(name)]) ?
[memo[0], memo[1].concat([[name, config]])] :
[memo[0].concat([[name, config]]), memo[1]],
[[], []]);
} | function partitionResources(resourcesToUpdate, loadingStates) {
return resourcesToUpdate.reduce((memo, [name, config]) =>
config.refetch || config.prefetch || !hasLoaded(loadingStates[getResourceState(name)]) ?
[memo[0], memo[1].concat([[name, config]])] :
[memo[0].concat([[name, config]]), memo[1]],
[[], []]);
} |
JavaScript | function loaderReducer(
{loadingStates, requestStatuses, hasInitiallyLoaded},
{type, payload={}}
) {
var {name, status, resources} = payload;
switch (type) {
case LoadingStates.ERROR:
case LoadingStates.LOADED: {
let nextLoadingStates = {...loadingStates, [getResourceState(name)]: type};
return {
loadingStates: nextLoadingStates,
requestStatuses: {...requestStatuses, [getResourceStatus(name)]: status},
hasInitiallyLoaded: hasInitiallyLoaded || (type === LoadingStates.LOADED &&
hasLoaded(getCriticalLoadingStates(nextLoadingStates, resources)) && !hasInitiallyLoaded)
};
}
case LoadingStates.LOADING:
return {
loadingStates: {...loadingStates, ...payload},
requestStatuses,
hasInitiallyLoaded
};
default:
return {loadingStates, requestStatuses, hasInitiallyLoaded};
}
} | function loaderReducer(
{loadingStates, requestStatuses, hasInitiallyLoaded},
{type, payload={}}
) {
var {name, status, resources} = payload;
switch (type) {
case LoadingStates.ERROR:
case LoadingStates.LOADED: {
let nextLoadingStates = {...loadingStates, [getResourceState(name)]: type};
return {
loadingStates: nextLoadingStates,
requestStatuses: {...requestStatuses, [getResourceStatus(name)]: status},
hasInitiallyLoaded: hasInitiallyLoaded || (type === LoadingStates.LOADED &&
hasLoaded(getCriticalLoadingStates(nextLoadingStates, resources)) && !hasInitiallyLoaded)
};
}
case LoadingStates.LOADING:
return {
loadingStates: {...loadingStates, ...payload},
requestStatuses,
hasInitiallyLoaded
};
default:
return {loadingStates, requestStatuses, hasInitiallyLoaded};
}
} |
JavaScript | function shouldMeasureRequest(modelKey, config) {
if (!window.performance || !window.performance.mark) {
return false;
}
return typeof ModelMap[modelKey].measure === 'function' ?
ModelMap[modelKey].measure(config) :
!!ModelMap[modelKey].measure;
} | function shouldMeasureRequest(modelKey, config) {
if (!window.performance || !window.performance.mark) {
return false;
}
return typeof ModelMap[modelKey].measure === 'function' ?
ModelMap[modelKey].measure(config) :
!!ModelMap[modelKey].measure;
} |
JavaScript | function fetchResources(resources, props, {
component,
isCurrentResource,
setResourceState,
onRequestSuccess,
onRequestFailure
}) {
// ensure critical requests go out first
/* eslint-disable id-length */
resources = resources.concat().sort((a, b) =>
a[1].prefetch ? 2 : b[1].prefetch ? -2 : a[1].noncritical ? 1 : b[1].noncritical ? -1 : 0);
/* eslint-enable id-length */
return Promise.all(
// nice visual for this promise chain: http://tinyurl.com/y6wt47b6
resources.map(([name, config]) => {
var {params, modelKey, provides={}, refetch, ...rest} = config,
cacheKey = getCacheKey(config),
shouldMeasure = shouldMeasureRequest(modelKey, config) && !getModelFromCache(config);
if (shouldMeasure) {
window.performance.mark(name);
}
return request(cacheKey, ModelMap[modelKey], {
fetch: !UnfetchedResources.has(modelKey),
params,
component,
force: refetch,
...rest
}).then(
// success callback, where we track request time and add any dependent props or models
([model, status]) => {
if (shouldMeasure) {
trackRequestTime(name, config);
}
// add unfetched resources that a model might provide
if (ModelMap[modelKey].providesModels) {
ModelMap[modelKey].providesModels(model, ResourceKeys).forEach((uConfig) => {
var uCacheKey = getCacheKey(uConfig),
existingModel = ModelCache.get(uCacheKey);
if (typeof uConfig.shouldCache !== 'function' ||
uConfig.shouldCache(existingModel, uConfig)) {
// components may be listening to existing models, so only create
// new model if one does not currently exist
existingModel ?
existingModel.set(uConfig.data) :
ModelCache.put(
uCacheKey,
new ModelMap[uConfig.modelKey](uConfig.data, uConfig.options),
component
);
}
});
}
// don't continue unless component is still mounted and resource is current
if (isCurrentResource([name, config], cacheKey)) {
// add any dependencies this resource might provide for other resources
if (Object.entries(provides).length) {
setResourceState((state) => ({
...state,
...Object.entries(provides).reduce((memo, [provide, transform]) => Object.assign({
memo,
...(provide === SPREAD_PROVIDES_CHAR ?
transform(model, props) :
{[provide]: transform(model, props)})
}), {})
}));
}
onRequestSuccess(model, status, [name, config]);
}
},
// error callback
(status) => {
// this catch block gets called _only_ for request errors.
// don't set error state unless resource is current
if (isCurrentResource([name, config], cacheKey)) {
onRequestFailure(status, [name, config]);
}
}
);
})
);
} | function fetchResources(resources, props, {
component,
isCurrentResource,
setResourceState,
onRequestSuccess,
onRequestFailure
}) {
// ensure critical requests go out first
/* eslint-disable id-length */
resources = resources.concat().sort((a, b) =>
a[1].prefetch ? 2 : b[1].prefetch ? -2 : a[1].noncritical ? 1 : b[1].noncritical ? -1 : 0);
/* eslint-enable id-length */
return Promise.all(
// nice visual for this promise chain: http://tinyurl.com/y6wt47b6
resources.map(([name, config]) => {
var {params, modelKey, provides={}, refetch, ...rest} = config,
cacheKey = getCacheKey(config),
shouldMeasure = shouldMeasureRequest(modelKey, config) && !getModelFromCache(config);
if (shouldMeasure) {
window.performance.mark(name);
}
return request(cacheKey, ModelMap[modelKey], {
fetch: !UnfetchedResources.has(modelKey),
params,
component,
force: refetch,
...rest
}).then(
// success callback, where we track request time and add any dependent props or models
([model, status]) => {
if (shouldMeasure) {
trackRequestTime(name, config);
}
// add unfetched resources that a model might provide
if (ModelMap[modelKey].providesModels) {
ModelMap[modelKey].providesModels(model, ResourceKeys).forEach((uConfig) => {
var uCacheKey = getCacheKey(uConfig),
existingModel = ModelCache.get(uCacheKey);
if (typeof uConfig.shouldCache !== 'function' ||
uConfig.shouldCache(existingModel, uConfig)) {
// components may be listening to existing models, so only create
// new model if one does not currently exist
existingModel ?
existingModel.set(uConfig.data) :
ModelCache.put(
uCacheKey,
new ModelMap[uConfig.modelKey](uConfig.data, uConfig.options),
component
);
}
});
}
// don't continue unless component is still mounted and resource is current
if (isCurrentResource([name, config], cacheKey)) {
// add any dependencies this resource might provide for other resources
if (Object.entries(provides).length) {
setResourceState((state) => ({
...state,
...Object.entries(provides).reduce((memo, [provide, transform]) => Object.assign({
memo,
...(provide === SPREAD_PROVIDES_CHAR ?
transform(model, props) :
{[provide]: transform(model, props)})
}), {})
}));
}
onRequestSuccess(model, status, [name, config]);
}
},
// error callback
(status) => {
// this catch block gets called _only_ for request errors.
// don't set error state unless resource is current
if (isCurrentResource([name, config], cacheKey)) {
onRequestFailure(status, [name, config]);
}
}
);
})
);
} |
JavaScript | function ajax(options) {
var hasParams = !!Object.keys(options.params || {}).length,
hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method) && hasParams;
if (options.method === 'GET' && hasParams) {
options.url += (options.url.indexOf('?') > -1 ? '&' : '?') +
ResourcesConfig.stringify(options.params, options);
}
options = {...options, ...prefilter(options)};
return window.fetch(options.url, {
...options,
headers: {
Accept: MIME_TYPE_JSON,
// only set contentType header if a write request and if there is body params. also, default
// to JSON contentTypes, but allow for it to be overridden, ie with x-www-form-urlencoded.
...hasBodyContent ? {'Content-Type': options.contentType} : {},
...options.headers
},
...hasBodyContent ? {
body: typeof options.params === 'string' ?
options.params :
options.contentType === MIME_TYPE_JSON ?
JSON.stringify(options.params) :
ResourcesConfig.stringify(options.params, options)
} : {}
// catch block here handles the case where the response isn't valid json,
// like for example a 204 no content
}).then(
(res) => res.json()
.catch(() => ({}))
.then((json) => res.ok ? [json, res] : Promise.reject(Object.assign(res, {json})))
).catch(options.error);
} | function ajax(options) {
var hasParams = !!Object.keys(options.params || {}).length,
hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method) && hasParams;
if (options.method === 'GET' && hasParams) {
options.url += (options.url.indexOf('?') > -1 ? '&' : '?') +
ResourcesConfig.stringify(options.params, options);
}
options = {...options, ...prefilter(options)};
return window.fetch(options.url, {
...options,
headers: {
Accept: MIME_TYPE_JSON,
// only set contentType header if a write request and if there is body params. also, default
// to JSON contentTypes, but allow for it to be overridden, ie with x-www-form-urlencoded.
...hasBodyContent ? {'Content-Type': options.contentType} : {},
...options.headers
},
...hasBodyContent ? {
body: typeof options.params === 'string' ?
options.params :
options.contentType === MIME_TYPE_JSON ?
JSON.stringify(options.params) :
ResourcesConfig.stringify(options.params, options)
} : {}
// catch block here handles the case where the response isn't valid json,
// like for example a 204 no content
}).then(
(res) => res.json()
.catch(() => ({}))
.then((json) => res.ok ? [json, res] : Promise.reject(Object.assign(res, {json})))
).catch(options.error);
} |
JavaScript | put(cacheKey, model, component) {
modelCache.set(cacheKey, model);
if (component) {
this.register(cacheKey, component);
} else {
scheduleForRemoval(cacheKey);
}
} | put(cacheKey, model, component) {
modelCache.set(cacheKey, model);
if (component) {
this.register(cacheKey, component);
} else {
scheduleForRemoval(cacheKey);
}
} |
JavaScript | register(cacheKey, component) {
window.clearTimeout(timeouts[cacheKey]);
componentManifest.set(cacheKey, componentManifest.get(cacheKey) || new Set());
componentManifest.get(cacheKey).add(component);
} | register(cacheKey, component) {
window.clearTimeout(timeouts[cacheKey]);
componentManifest.set(cacheKey, componentManifest.get(cacheKey) || new Set());
componentManifest.get(cacheKey).add(component);
} |
JavaScript | unregister(component, ...cacheKeys) {
cacheKeys = cacheKeys.length ? cacheKeys : componentManifest.keys();
for (let cacheKey of cacheKeys) {
let componentSet = componentManifest.get(cacheKey);
if (componentSet && componentSet.has(component)) {
componentSet.delete(component);
if (!componentSet.size) {
scheduleForRemoval(cacheKey);
}
}
}
} | unregister(component, ...cacheKeys) {
cacheKeys = cacheKeys.length ? cacheKeys : componentManifest.keys();
for (let cacheKey of cacheKeys) {
let componentSet = componentManifest.get(cacheKey);
if (componentSet && componentSet.has(component)) {
componentSet.delete(component);
if (!componentSet.size) {
scheduleForRemoval(cacheKey);
}
}
}
} |
JavaScript | function scheduleForRemoval(cacheKey) {
timeouts[cacheKey] = window.setTimeout(() => {
clearModel(cacheKey);
}, ResourcesConfig.cacheGracePeriod);
} | function scheduleForRemoval(cacheKey) {
timeouts[cacheKey] = window.setTimeout(() => {
clearModel(cacheKey);
}, ResourcesConfig.cacheGracePeriod);
} |
JavaScript | function clearModel(cacheKey) {
window.clearTimeout(timeouts[cacheKey]);
delete timeouts[cacheKey];
modelCache.delete(cacheKey);
} | function clearModel(cacheKey) {
window.clearTimeout(timeouts[cacheKey]);
delete timeouts[cacheKey];
modelCache.delete(cacheKey);
} |
JavaScript | remove(models, options={}) {
var removed = this._removeModels(!Array.isArray(models) ? [models] : models);
if (!options.silent && removed.length) {
// update trigger on collection, necessary because removed models won't trigger collection
// response at this point
this.triggerUpdate();
}
return this;
} | remove(models, options={}) {
var removed = this._removeModels(!Array.isArray(models) ? [models] : models);
if (!options.silent && removed.length) {
// update trigger on collection, necessary because removed models won't trigger collection
// response at this point
this.triggerUpdate();
}
return this;
} |
JavaScript | reset(models=[], options={}) {
for (let i = 0; i < this.models.length; i++) {
this._removeReference(this.models[i]);
}
this._reset();
// this is silent so that we don't trigger until we are all done. this is extra
// important after a request returns because as of React 17 those are still synchronous udpates
this.add(models, {silent: true, ...options});
if (!options.silent) {
// reset trigger
this.triggerUpdate();
}
return this;
} | reset(models=[], options={}) {
for (let i = 0; i < this.models.length; i++) {
this._removeReference(this.models[i]);
}
this._reset();
// this is silent so that we don't trigger until we are all done. this is extra
// important after a request returns because as of React 17 those are still synchronous udpates
this.add(models, {silent: true, ...options});
if (!options.silent) {
// reset trigger
this.triggerUpdate();
}
return this;
} |
JavaScript | where(attrs, first) {
var predicate = (model) => {
for (let [attr, val] of Object.entries(attrs)) {
if (!isDeepEqual(model.get(attr), val)) {
return false;
}
}
return true;
};
return this[first ? 'find' : 'filter'](predicate);
} | where(attrs, first) {
var predicate = (model) => {
for (let [attr, val] of Object.entries(attrs)) {
if (!isDeepEqual(model.get(attr), val)) {
return false;
}
}
return true;
};
return this[first ? 'find' : 'filter'](predicate);
} |
JavaScript | sort() {
if (!this.comparator) {
throw new Error('Cannot sort a set without a comparator');
}
// Run sort based on type of `comparator`.
if (typeof this.comparator === 'function' && this.comparator.length > 1) {
this.models.sort(this.comparator.bind(this));
} else {
this.models = sortBy(
this.models,
(model) => typeof this.comparator === 'function' ?
this.comparator(model) :
model.get(this.comparator)
);
}
return this;
} | sort() {
if (!this.comparator) {
throw new Error('Cannot sort a set without a comparator');
}
// Run sort based on type of `comparator`.
if (typeof this.comparator === 'function' && this.comparator.length > 1) {
this.models.sort(this.comparator.bind(this));
} else {
this.models = sortBy(
this.models,
(model) => typeof this.comparator === 'function' ?
this.comparator(model) :
model.get(this.comparator)
);
}
return this;
} |
JavaScript | fetch(options={}) {
options = {parse: true, method: 'GET', ...options};
return this.sync(this, options)
.then(([json, response]) => {
this.reset(json, {silent: true, ...options});
// sync trigger
this.triggerUpdate();
return [this, response];
})
.catch((response) => Promise.reject(response));
} | fetch(options={}) {
options = {parse: true, method: 'GET', ...options};
return this.sync(this, options)
.then(([json, response]) => {
this.reset(json, {silent: true, ...options});
// sync trigger
this.triggerUpdate();
return [this, response];
})
.catch((response) => Promise.reject(response));
} |
JavaScript | create(model, options={}) {
model = this._prepareModel(model, options);
if (!options.wait) {
this.add(model, options);
}
return model.save(null, options)
.then((...args) => {
if (options.wait) {
// note that this is NOT silent because even though we are already triggering an update
// after the model sync, because the model isn't added, the collection doesn't also get
// an update
this.add(model, options);
}
// model should now have an id property if it didn't previously
this._addReference(model);
return args[0];
})
.catch((response) => {
if (!options.wait) {
this.remove(model);
}
return Promise.reject(response);
});
} | create(model, options={}) {
model = this._prepareModel(model, options);
if (!options.wait) {
this.add(model, options);
}
return model.save(null, options)
.then((...args) => {
if (options.wait) {
// note that this is NOT silent because even though we are already triggering an update
// after the model sync, because the model isn't added, the collection doesn't also get
// an update
this.add(model, options);
}
// model should now have an id property if it didn't previously
this._addReference(model);
return args[0];
})
.catch((response) => {
if (!options.wait) {
this.remove(model);
}
return Promise.reject(response);
});
} |
JavaScript | _getModelClass() {
if (this.constructor.modelIdAttribute) {
let attr = this.constructor.modelIdAttribute;
return class extends Model {
static idAttribute = attr
};
}
return this.constructor.Model;
} | _getModelClass() {
if (this.constructor.modelIdAttribute) {
let attr = this.constructor.modelIdAttribute;
return class extends Model {
static idAttribute = attr
};
}
return this.constructor.Model;
} |
JavaScript | _reset() {
this.length = 0;
this.models = [];
this._byId = {};
} | _reset() {
this.length = 0;
this.models = [];
this._byId = {};
} |
JavaScript | _prepareModel(attrs, options) {
if (this._isModel(attrs)) {
if (!attrs.collection) {
attrs.collection = this;
}
return attrs;
}
return new this.Model(attrs, {...options, collection: this});
} | _prepareModel(attrs, options) {
if (this._isModel(attrs)) {
if (!attrs.collection) {
attrs.collection = this;
}
return attrs;
}
return new this.Model(attrs, {...options, collection: this});
} |
JavaScript | _removeModels(models) {
var removed = [];
for (let i = 0; i < models.length; i++) {
let model = this.get(models[i]);
if (!model) {
continue;
}
let index = this.models.indexOf(model);
this.models.splice(index, 1);
this.length--;
delete this._byId[model.cid];
if (model.attributes[this.Model.idAttribute]) {
delete this._byId[model.attributes[this.Model.idAttribute]];
}
removed.push(model);
this._removeReference(model);
}
return removed;
} | _removeModels(models) {
var removed = [];
for (let i = 0; i < models.length; i++) {
let model = this.get(models[i]);
if (!model) {
continue;
}
let index = this.models.indexOf(model);
this.models.splice(index, 1);
this.length--;
delete this._byId[model.cid];
if (model.attributes[this.Model.idAttribute]) {
delete this._byId[model.attributes[this.Model.idAttribute]];
}
removed.push(model);
this._removeReference(model);
}
return removed;
} |
JavaScript | _addReference(model) {
this._byId[model.cid] = model;
let id = model.attributes[this.Model.idAttribute];
if (id || typeof id === 'number') {
this._byId[id] = model;
}
model.onUpdate(this.triggerUpdate, this);
} | _addReference(model) {
this._byId[model.cid] = model;
let id = model.attributes[this.Model.idAttribute];
if (id || typeof id === 'number') {
this._byId[id] = model;
}
model.onUpdate(this.triggerUpdate, this);
} |
JavaScript | _removeReference(model) {
delete this._byId[model.cid];
let id = model.attributes[this.Model.idAttribute];
if (id) {
delete this._byId[id];
}
delete model.collection;
model.offUpdate(this);
} | _removeReference(model) {
delete this._byId[model.cid];
let id = model.attributes[this.Model.idAttribute];
if (id) {
delete this._byId[id];
}
delete model.collection;
model.offUpdate(this);
} |
JavaScript | function waitsFor(condition, time=3000, name='something to happen') {
var interval,
timeout = origSetTimeout(() => {
origClearInterval(interval);
throw new Error(`Timed out after ${time}ms waiting for ${name}`);
}, time);
return new Promise((res) => {
interval = origSetInterval(() => {
if (condition()) {
origClearInterval(interval);
origClearTimeout(timeout);
res();
}
}, 0);
});
} | function waitsFor(condition, time=3000, name='something to happen') {
var interval,
timeout = origSetTimeout(() => {
origClearInterval(interval);
throw new Error(`Timed out after ${time}ms waiting for ${name}`);
}, time);
return new Promise((res) => {
interval = origSetInterval(() => {
if (condition()) {
origClearInterval(interval);
origClearTimeout(timeout);
res();
}
}, 0);
});
} |
JavaScript | function unregisterComponent(comp) {
jest.useFakeTimers();
ModelCache.unregister(comp);
jest.advanceTimersByTime(CACHE_WAIT);
jest.useRealTimers();
} | function unregisterComponent(comp) {
jest.useFakeTimers();
ModelCache.unregister(comp);
jest.advanceTimersByTime(CACHE_WAIT);
jest.useRealTimers();
} |
JavaScript | async function validatePassword(name, pwd) {
const data = await db.getPassword(name);
return (mc.check(pwd, data.salt, data.password));
} | async function validatePassword(name, pwd) {
const data = await db.getPassword(name);
return (mc.check(pwd, data.salt, data.password));
} |
JavaScript | function createActionTypes(namespace) {
return new Proxy(
{},
{
get: function(target, key) {
if (typeof namespace === 'string') {
return namespace + '/' + key;
} else {
return key;
}
}
}
);
} | function createActionTypes(namespace) {
return new Proxy(
{},
{
get: function(target, key) {
if (typeof namespace === 'string') {
return namespace + '/' + key;
} else {
return key;
}
}
}
);
} |
JavaScript | function findSumUnsorted (arr, sum) {
const complements = []
for (let i=0; i<arr.length; i++) {
const compliment = arr[i] > sum ? arr[i] - sum : sum - arr[i]
if (complements.indexOf(compliment) !== -1) {
return true
}
complements.push(compliment)
}
return false
} | function findSumUnsorted (arr, sum) {
const complements = []
for (let i=0; i<arr.length; i++) {
const compliment = arr[i] > sum ? arr[i] - sum : sum - arr[i]
if (complements.indexOf(compliment) !== -1) {
return true
}
complements.push(compliment)
}
return false
} |
JavaScript | function findSum (arr, sum) {
let found = false
function search (leftIndex, rightIndex, cb) {
const searchSum = arr[leftIndex] + arr[rightIndex]
if (searchSum === sum) {
found = true
return true
}
if (leftIndex === rightIndex) {
found = false
return false
}
if (searchSum > sum) {
search(leftIndex, rightIndex - 1, cb)
} else {
search(leftIndex + 1, rightIndex, cb)
}
}
search(0, arr.length - 1)
return found
} | function findSum (arr, sum) {
let found = false
function search (leftIndex, rightIndex, cb) {
const searchSum = arr[leftIndex] + arr[rightIndex]
if (searchSum === sum) {
found = true
return true
}
if (leftIndex === rightIndex) {
found = false
return false
}
if (searchSum > sum) {
search(leftIndex, rightIndex - 1, cb)
} else {
search(leftIndex + 1, rightIndex, cb)
}
}
search(0, arr.length - 1)
return found
} |
JavaScript | function cryptobox_custom(url, paid, path, ext, redirect)
{
var start = new Date().getTime();
var st = new Date().getTime();
var received = false;
var error = false;
if (typeof paid !== 'number') paid = 0;
if (typeof path !== 'string') path = '';
if (typeof ext !== 'string') ext = 'gourl_';
if (typeof redirect !== 'string') redirect = '';
cryptobox_callout = function ()
{
$.ajax(
{
type: 'GET',
url: url,
cache: false,
contentType: 'application/json; charset=utf-8',
data: { format: 'json' },
dataType: 'json'
})
.fail(function()
{
$('.'+ext+'error_message').html('Error loading data !   <a target="_blank" href="'+url+'">Raw details here »</a>');
$('.'+ext+'loader_button' ).fadeOut(400, function(){ $('.'+ext+'loader').show(); $('.'+ext+'cryptobox_error').fadeIn(400); })
error = true;
})
.done(function( data )
{
cryptobox_update_page(data, ext);
if (data.status == "payment_received")
{
received = true;
// update record in local db
if (!paid) $.post( path+"cryptobox.callback.php", data )
.fail( function() {alert( "Internal Error! Unable to find file cryptobox.callback.php. Please contact the website administrator.") })
.done(function(txt) { if (txt != "cryptobox_newrecord" && txt != "cryptobox_updated" && txt != "cryptobox_nochanges") alert("Internal Error! "+txt); });
// optional, redirect to another page after payment is received
if (redirect) setTimeout(function() { window.location = redirect; }, 5000);
}
if (!received && !error)
{
var end = new Date().getTime();
if ((end - start) > 20*60*1000)
{
$('.'+ext+'button_wait').hide();
$('.'+ext+'button_refresh').removeClass('btn-default').addClass('btn-info');
$('.'+ext+'cryptobox_unpaid .panel').removeClass('panel-info').removeClass('panel-primary').removeClass('panel-warning').removeClass('panel-success').addClass('panel-default').fadeTo("slow" , 0.4, function() {});
$('[data-original-title]').tooltip('disable');
}
else
{
setTimeout(cryptobox_callout, 7000);
}
}
});
}
cryptobox_callout();
return true;
} | function cryptobox_custom(url, paid, path, ext, redirect)
{
var start = new Date().getTime();
var st = new Date().getTime();
var received = false;
var error = false;
if (typeof paid !== 'number') paid = 0;
if (typeof path !== 'string') path = '';
if (typeof ext !== 'string') ext = 'gourl_';
if (typeof redirect !== 'string') redirect = '';
cryptobox_callout = function ()
{
$.ajax(
{
type: 'GET',
url: url,
cache: false,
contentType: 'application/json; charset=utf-8',
data: { format: 'json' },
dataType: 'json'
})
.fail(function()
{
$('.'+ext+'error_message').html('Error loading data !   <a target="_blank" href="'+url+'">Raw details here »</a>');
$('.'+ext+'loader_button' ).fadeOut(400, function(){ $('.'+ext+'loader').show(); $('.'+ext+'cryptobox_error').fadeIn(400); })
error = true;
})
.done(function( data )
{
cryptobox_update_page(data, ext);
if (data.status == "payment_received")
{
received = true;
// update record in local db
if (!paid) $.post( path+"cryptobox.callback.php", data )
.fail( function() {alert( "Internal Error! Unable to find file cryptobox.callback.php. Please contact the website administrator.") })
.done(function(txt) { if (txt != "cryptobox_newrecord" && txt != "cryptobox_updated" && txt != "cryptobox_nochanges") alert("Internal Error! "+txt); });
// optional, redirect to another page after payment is received
if (redirect) setTimeout(function() { window.location = redirect; }, 5000);
}
if (!received && !error)
{
var end = new Date().getTime();
if ((end - start) > 20*60*1000)
{
$('.'+ext+'button_wait').hide();
$('.'+ext+'button_refresh').removeClass('btn-default').addClass('btn-info');
$('.'+ext+'cryptobox_unpaid .panel').removeClass('panel-info').removeClass('panel-primary').removeClass('panel-warning').removeClass('panel-success').addClass('panel-default').fadeTo("slow" , 0.4, function() {});
$('[data-original-title]').tooltip('disable');
}
else
{
setTimeout(cryptobox_callout, 7000);
}
}
});
}
cryptobox_callout();
return true;
} |
JavaScript | function itTest(i, day, cb) {
var expected = ((i & day) === day);
it(i + ' should return ' + expected, function () {
assert.equal(cb(i), expected, 'expected is:' + expected);
});
} | function itTest(i, day, cb) {
var expected = ((i & day) === day);
it(i + ' should return ' + expected, function () {
assert.equal(cb(i), expected, 'expected is:' + expected);
});
} |
JavaScript | function itTestToday(i, today) {
rule.Weekdays = i;
expected = ((i & today) === today);
it('today (' + today + ') it should return ' + expected + ' when Weekdays is ' + rule.Weekdays, function () {
assert.equal(rulevalidation.TodayIsTheCorrectWeekday(rule), expected);
});
} | function itTestToday(i, today) {
rule.Weekdays = i;
expected = ((i & today) === today);
it('today (' + today + ') it should return ' + expected + ' when Weekdays is ' + rule.Weekdays, function () {
assert.equal(rulevalidation.TodayIsTheCorrectWeekday(rule), expected);
});
} |
JavaScript | function showDebugInfo(data) {
//simply show message generated by server
//$('#debugInfo').html(data.ServerStatusMessage);
//run through data
var elementParent = '';
var elementChildDesc = '';
var elementchildValue = '';
var value = '';
for (key in data) {
//skip ServerStatusMessage
if (key === 'ServerStatusMessage') {
continue;
}
//create element if not existing
elementParent = key;
elementChildDesc = key + 'Desc';
elementchildValue = key + 'Value';
if (!$('#' + elementParent).length) {
$('#debugInfo').append('<div id="' + elementParent + '" class="debugInfoParent"><div id="' + elementChildDesc + '" class="debugInfoChildDesc"></div><div id="' + elementchildValue + '" class="debugInfoChildValue"></div></div>');
$('#' + elementChildDesc).html(key);
$('#' + elementchildValue).html(data[key]);
} else {
//generate value
if (key === "CurrentRule") {
if (data[key]) {
value = 'id:' + data[key].id + ', Priority:' + data[key].Priority + ', From:' + data[key].From + ', To:' + data[key].To + ', DimTime:' + data[key].DimTime + ', Weekdays:' + data[key].Weekdays;
} else {
value = 'no rule active...';
}
} else {
value = data[key].toString();
}
//element exists already. just write value when changed
if ($('#' + elementchildValue).html() !== value) {
$('#' + elementchildValue).html(value);
}
}
}
} | function showDebugInfo(data) {
//simply show message generated by server
//$('#debugInfo').html(data.ServerStatusMessage);
//run through data
var elementParent = '';
var elementChildDesc = '';
var elementchildValue = '';
var value = '';
for (key in data) {
//skip ServerStatusMessage
if (key === 'ServerStatusMessage') {
continue;
}
//create element if not existing
elementParent = key;
elementChildDesc = key + 'Desc';
elementchildValue = key + 'Value';
if (!$('#' + elementParent).length) {
$('#debugInfo').append('<div id="' + elementParent + '" class="debugInfoParent"><div id="' + elementChildDesc + '" class="debugInfoChildDesc"></div><div id="' + elementchildValue + '" class="debugInfoChildValue"></div></div>');
$('#' + elementChildDesc).html(key);
$('#' + elementchildValue).html(data[key]);
} else {
//generate value
if (key === "CurrentRule") {
if (data[key]) {
value = 'id:' + data[key].id + ', Priority:' + data[key].Priority + ', From:' + data[key].From + ', To:' + data[key].To + ', DimTime:' + data[key].DimTime + ', Weekdays:' + data[key].Weekdays;
} else {
value = 'no rule active...';
}
} else {
value = data[key].toString();
}
//element exists already. just write value when changed
if ($('#' + elementchildValue).html() !== value) {
$('#' + elementchildValue).html(value);
}
}
}
} |
JavaScript | function toLog (Message) {
logger.LogIt(Message)
// logger.ToConsole(Message);
if (showDebugInfo) {
// var now = new Date(new Date().toLocaleString());
// var debugStamp = now / 1000;
// console.log('[%d]\t' + Message, debugStamp);
// testing winston
// logger.log({ level: 'info', message: Message });
}
} | function toLog (Message) {
logger.LogIt(Message)
// logger.ToConsole(Message);
if (showDebugInfo) {
// var now = new Date(new Date().toLocaleString());
// var debugStamp = now / 1000;
// console.log('[%d]\t' + Message, debugStamp);
// testing winston
// logger.log({ level: 'info', message: Message });
}
} |
JavaScript | function writeDAC (value) {
if (!Number.isInteger(value)) {
toLog('writeDAC: value not integer')
}
if (value < 0) {
toLog('writeDAC: value < 0')
}
if (value > 0xff) {
toLog('writeDAC: value > 0xff')
}
// only write when legal
if (Number.isInteger(value) && value >= 0 && value <= 0xff) {
i2c1.writeByteSync(PCF8591_ADDR, CMD_ACCESS_CONFIG, value)
}
} | function writeDAC (value) {
if (!Number.isInteger(value)) {
toLog('writeDAC: value not integer')
}
if (value < 0) {
toLog('writeDAC: value < 0')
}
if (value > 0xff) {
toLog('writeDAC: value > 0xff')
}
// only write when legal
if (Number.isInteger(value) && value >= 0 && value <= 0xff) {
i2c1.writeByteSync(PCF8591_ADDR, CMD_ACCESS_CONFIG, value)
}
} |
JavaScript | function showDebugInfo(data) {
//simply show message generated by server
//$('#debugInfo').html(data.ServerStatusMessage);
//run through data
var elementParent = '';
var elementChildDesc = '';
var elementchildValue = '';
var value = '';
for (key in data) {
//skip ServerStatusMessage
if (key === 'ServerStatusMessage') {
continue;
}
//create element if not existing
elementParent = key;
elementChildDesc = key + 'Desc';
elementchildValue = key + 'Value';
if (!$('#' + elementParent).length) {
$('#debugInfo').append('<div id="' + elementParent + '" class="debugInfoParent"><div id="' + elementChildDesc + '" class="debugInfoChildDesc"></div><div id="' + elementchildValue + '" class="debugInfoChildValue"></div></div>');
$('#' + elementChildDesc).html(key);
$('#' + elementchildValue).html(data[key]);
} else {
//generate value
if (key === "CurrentRule") {
if (data[key]) {
value = 'id:' + data[key].id + ', Priority:' + data[key].Priority + ', From:' + data[key].From + ', To:' + data[key].To + ', DimTime:' + data[key].DimTime + ', Weekdays:' + data[key].Weekdays;
} else {
value = 'no rule active...';
}
} else {
value = data[key].toString();
}
//element exists already. just write value when changed
if ($('#' + elementchildValue).html() !== value) {
$('#' + elementchildValue).html(value);
}
}
}
} | function showDebugInfo(data) {
//simply show message generated by server
//$('#debugInfo').html(data.ServerStatusMessage);
//run through data
var elementParent = '';
var elementChildDesc = '';
var elementchildValue = '';
var value = '';
for (key in data) {
//skip ServerStatusMessage
if (key === 'ServerStatusMessage') {
continue;
}
//create element if not existing
elementParent = key;
elementChildDesc = key + 'Desc';
elementchildValue = key + 'Value';
if (!$('#' + elementParent).length) {
$('#debugInfo').append('<div id="' + elementParent + '" class="debugInfoParent"><div id="' + elementChildDesc + '" class="debugInfoChildDesc"></div><div id="' + elementchildValue + '" class="debugInfoChildValue"></div></div>');
$('#' + elementChildDesc).html(key);
$('#' + elementchildValue).html(data[key]);
} else {
//generate value
if (key === "CurrentRule") {
if (data[key]) {
value = 'id:' + data[key].id + ', Priority:' + data[key].Priority + ', From:' + data[key].From + ', To:' + data[key].To + ', DimTime:' + data[key].DimTime + ', Weekdays:' + data[key].Weekdays;
} else {
value = 'no rule active...';
}
} else {
value = data[key].toString();
}
//element exists already. just write value when changed
if ($('#' + elementchildValue).html() !== value) {
$('#' + elementchildValue).html(value);
}
}
}
} |
JavaScript | function cloneMouseEvent(event) {
var eventToDispatch;
if (document.createEvent) { // IE prevents the use of new MouseEvent(ev.type, ev)
eventToDispatch = document.createEvent('MouseEvent');
eventToDispatch.initMouseEvent(event.type,
event.bubbles,
event.cancelable,
event.view,
event.detail,
event.screenX,
event.screenY,
event.clientX,
event.clientY,
event.ctrlKey,
event.altKey,
event.shiftKey,
event.metaKey,
event.button,
event.relatedTarget);
} else {
eventToDispatch = new MouseEvent(event.type, event);
}
var buttonsValue = event.buttons;
if (eventToDispatch.buttons !== buttonsValue)
Object.defineProperty(eventToDispatch, 'buttons', { get: function () { return buttonsValue; } });
return eventToDispatch;
} | function cloneMouseEvent(event) {
var eventToDispatch;
if (document.createEvent) { // IE prevents the use of new MouseEvent(ev.type, ev)
eventToDispatch = document.createEvent('MouseEvent');
eventToDispatch.initMouseEvent(event.type,
event.bubbles,
event.cancelable,
event.view,
event.detail,
event.screenX,
event.screenY,
event.clientX,
event.clientY,
event.ctrlKey,
event.altKey,
event.shiftKey,
event.metaKey,
event.button,
event.relatedTarget);
} else {
eventToDispatch = new MouseEvent(event.type, event);
}
var buttonsValue = event.buttons;
if (eventToDispatch.buttons !== buttonsValue)
Object.defineProperty(eventToDispatch, 'buttons', { get: function () { return buttonsValue; } });
return eventToDispatch;
} |
JavaScript | function updateTeams(arr){
for (var i = 0; i < arr.length; i++){
arr[i].home.gp += 1;
arr[i].away.gp += 1;
if (arr[i].Hscore > arr[i].Ascore){
arr[i].home.won += 1;
arr[i].away.lost += 1;
arr[i].home.points += 3;
};
if (arr[i].Ascore > arr[i].Hscore){
arr[i].away.won += 1;
arr[i].home.lost += 1;
arr[i].away.points += 3;
};
if (arr[i].Hscore == arr[i].Ascore){
arr[i].home.points += 1;
arr[i].away.points += 1;
arr[i].home.drawn += 1;
arr[i].away.drawn += 1;
};
var goalDifferential = (arr[i].Hscore - arr[i].Ascore);
arr[i].home.gf += arr[i].Hscore;
arr[i].home.ga += arr[i].Ascore;
arr[i].home.gd += goalDifferential;
arr[i].away.gf += arr[i].Ascore;
arr[i].away.ga += arr[i].Hscore;
arr[i].away.gd -= goalDifferential;
};
} | function updateTeams(arr){
for (var i = 0; i < arr.length; i++){
arr[i].home.gp += 1;
arr[i].away.gp += 1;
if (arr[i].Hscore > arr[i].Ascore){
arr[i].home.won += 1;
arr[i].away.lost += 1;
arr[i].home.points += 3;
};
if (arr[i].Ascore > arr[i].Hscore){
arr[i].away.won += 1;
arr[i].home.lost += 1;
arr[i].away.points += 3;
};
if (arr[i].Hscore == arr[i].Ascore){
arr[i].home.points += 1;
arr[i].away.points += 1;
arr[i].home.drawn += 1;
arr[i].away.drawn += 1;
};
var goalDifferential = (arr[i].Hscore - arr[i].Ascore);
arr[i].home.gf += arr[i].Hscore;
arr[i].home.ga += arr[i].Ascore;
arr[i].home.gd += goalDifferential;
arr[i].away.gf += arr[i].Ascore;
arr[i].away.ga += arr[i].Hscore;
arr[i].away.gd -= goalDifferential;
};
} |
JavaScript | remove (item) {
if (this._verify()) {
window.localStorage.removeItem(item)
} else {
console.error('Error removing value from localStorage')
}
} | remove (item) {
if (this._verify()) {
window.localStorage.removeItem(item)
} else {
console.error('Error removing value from localStorage')
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.