language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function measure(program, interval) {
const csv = csvWriter();
csv.pipe(fs.createWriteStream(`results-${program}.csv`))
setInterval(() => {
exec(`powershell -command "(Get-Process ${program} | Measure-Object WorkingSet -sum).sum"`, {
//shell: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
}, (err, stdout, stderr) => {
if (err) {
console.log(stderr);
throw err
} else if (stderr) {
console.log(stderr);
}
// Add to Spreadsheet
const writeOBJ = {}
const std0 = stdout.split("\n")[0];
writeOBJ[program] = parseInt(std0) / 1000 / 1000; // In MB
csv.write(writeOBJ);
console.log(`${program}: ${std0}`)
})
}, interval);
} | function measure(program, interval) {
const csv = csvWriter();
csv.pipe(fs.createWriteStream(`results-${program}.csv`))
setInterval(() => {
exec(`powershell -command "(Get-Process ${program} | Measure-Object WorkingSet -sum).sum"`, {
//shell: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
}, (err, stdout, stderr) => {
if (err) {
console.log(stderr);
throw err
} else if (stderr) {
console.log(stderr);
}
// Add to Spreadsheet
const writeOBJ = {}
const std0 = stdout.split("\n")[0];
writeOBJ[program] = parseInt(std0) / 1000 / 1000; // In MB
csv.write(writeOBJ);
console.log(`${program}: ${std0}`)
})
}, interval);
} |
JavaScript | toObject() {
let object = {};
if (typeof this.content === 'string') object.content = this.content;
else object.embed = this.content;
const row = new MessageActionRow({
components: this.buttons
})
object.components = [ row ];
return object;
} | toObject() {
let object = {};
if (typeof this.content === 'string') object.content = this.content;
else object.embed = this.content;
const row = new MessageActionRow({
components: this.buttons
})
object.components = [ row ];
return object;
} |
JavaScript | function showQuestions(questionIndex) {
// Clears existing data
questionsDiv.innerHTML = "";
ulCreate.innerHTML = "";
//loops through questions array
for (var i = 0; i < questions.length; i++) {
// question title element
var userQuestion = questions[questionIndex].title;
var userChoices = questions[questionIndex].choices;
questionsDiv.textContent = userQuestion;
}
//creates the possible answer elements
userChoices.forEach(function (newItem) {
var listItem = document.createElement("li");
listItem.textContent = newItem;
questionsDiv.appendChild(ulCreate);
ulCreate.appendChild(listItem);
//event listner checking for answer clicked on
listItem.addEventListener("click", (checkAnswer));
})
} | function showQuestions(questionIndex) {
// Clears existing data
questionsDiv.innerHTML = "";
ulCreate.innerHTML = "";
//loops through questions array
for (var i = 0; i < questions.length; i++) {
// question title element
var userQuestion = questions[questionIndex].title;
var userChoices = questions[questionIndex].choices;
questionsDiv.textContent = userQuestion;
}
//creates the possible answer elements
userChoices.forEach(function (newItem) {
var listItem = document.createElement("li");
listItem.textContent = newItem;
questionsDiv.appendChild(ulCreate);
ulCreate.appendChild(listItem);
//event listner checking for answer clicked on
listItem.addEventListener("click", (checkAnswer));
})
} |
JavaScript | function sleep(durationMillis) {
var now = new Date().getTime();
while(new Date().getTime() < now + durationMillis) {
// do nothing
}
} | function sleep(durationMillis) {
var now = new Date().getTime();
while(new Date().getTime() < now + durationMillis) {
// do nothing
}
} |
JavaScript | function init_map_locations(batteries) {
var locations = get_locations(batteries);
if(locations.length > 0){
var corner_points = get_corners(locations);
var center = get_center(corner_points[0], corner_points[1]);
}
else{
var center = [0.00000, 0.00000];
}
generate_location_map(center, locations, batteries);
} | function init_map_locations(batteries) {
var locations = get_locations(batteries);
if(locations.length > 0){
var corner_points = get_corners(locations);
var center = get_center(corner_points[0], corner_points[1]);
}
else{
var center = [0.00000, 0.00000];
}
generate_location_map(center, locations, batteries);
} |
JavaScript | function generate_location_map(center, locations, batteries){
var map_id;
if (locations.length > 1) {
map_id = 'all';
}
else{
map_id = batteries[0].id;
}
// Generates the map
var map = new google.maps.Map(document.getElementById('map_' + map_id), {
zoom: 13,
center: new google.maps.LatLng(center[0], center[1]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = get_markers(map, locations, batteries);
// Now fit the map to the newly inclusive bounds
if (locations.length > 1){
map.fitBounds(bounds);
}
} | function generate_location_map(center, locations, batteries){
var map_id;
if (locations.length > 1) {
map_id = 'all';
}
else{
map_id = batteries[0].id;
}
// Generates the map
var map = new google.maps.Map(document.getElementById('map_' + map_id), {
zoom: 13,
center: new google.maps.LatLng(center[0], center[1]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = get_markers(map, locations, batteries);
// Now fit the map to the newly inclusive bounds
if (locations.length > 1){
map.fitBounds(bounds);
}
} |
JavaScript | function show_mini_maps(batteries){
batteries.forEach(function (battery){
init_map_locations([battery]);
Stats.graph_battery_life(5, battery)
});
} | function show_mini_maps(batteries){
batteries.forEach(function (battery){
init_map_locations([battery]);
Stats.graph_battery_life(5, battery)
});
} |
JavaScript | function init_map_path(path, battery) {
if(path.length > 0){
var corner_points = get_corners(path);
var center = get_center(corner_points[0], corner_points[1]);
}
else{
var center = [0.00000, 0.00000];
}
generate_path_map(center, path, battery);
} | function init_map_path(path, battery) {
if(path.length > 0){
var corner_points = get_corners(path);
var center = get_center(corner_points[0], corner_points[1]);
}
else{
var center = [0.00000, 0.00000];
}
generate_path_map(center, path, battery);
} |
JavaScript | function generate_path_map(center, path, battery){
// Generates the map
var id;
if (battery){
id = battery.id;
}
else{
id = 'all';
}
var map = new google.maps.Map(document.getElementById('map_' + id), {
zoom: 13,
center: new google.maps.LatLng(center[0], center[1]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Adds a marker at end points, create a path between each data point
if(path.length > 0 && id != 'all'){
var marker, i;
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow({});
for (i = 0; i < path.length; i++) {
if(i == 0 || i == path.length - 1){
marker = new google.maps.Marker({
position: new google.maps.LatLng(path[i].lat, path[i].lng),
map: map
});
infowindow = new google.maps.InfoWindow({});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent('EXAMPLE: Add start/end time');
infowindow.open(map, marker);
}
})(marker, i));
}
else{
marker = new google.maps.Marker({
position: new google.maps.LatLng(path[i].lat, path[i].lng),
});
}
// Extend the bounds to include each marker's position
bounds.extend(marker.position);
}
// Now fit the map to the newly inclusive bounds
if(path.length > 1){
map.fitBounds(bounds);
}
}
//paths.forEach(function(path){
var path_characteristics = new google.maps.Polyline({
path: path,
geodesic: false,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
path_characteristics.setMap(map);
//});
} | function generate_path_map(center, path, battery){
// Generates the map
var id;
if (battery){
id = battery.id;
}
else{
id = 'all';
}
var map = new google.maps.Map(document.getElementById('map_' + id), {
zoom: 13,
center: new google.maps.LatLng(center[0], center[1]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Adds a marker at end points, create a path between each data point
if(path.length > 0 && id != 'all'){
var marker, i;
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow({});
for (i = 0; i < path.length; i++) {
if(i == 0 || i == path.length - 1){
marker = new google.maps.Marker({
position: new google.maps.LatLng(path[i].lat, path[i].lng),
map: map
});
infowindow = new google.maps.InfoWindow({});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent('EXAMPLE: Add start/end time');
infowindow.open(map, marker);
}
})(marker, i));
}
else{
marker = new google.maps.Marker({
position: new google.maps.LatLng(path[i].lat, path[i].lng),
});
}
// Extend the bounds to include each marker's position
bounds.extend(marker.position);
}
// Now fit the map to the newly inclusive bounds
if(path.length > 1){
map.fitBounds(bounds);
}
}
//paths.forEach(function(path){
var path_characteristics = new google.maps.Polyline({
path: path,
geodesic: false,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
path_characteristics.setMap(map);
//});
} |
JavaScript | function generate_location_map(center, locations, batteries){
if (locations.length > 1) {
map_id = 'all';
}
else{
map_id = batteries[0].id;
}
// Generates the map
var map = new google.maps.Map(document.getElementById('map_' + map_id), {
zoom: 13,
center: new google.maps.LatLng(center[0], center[1]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = get_markers(map, locations, batteries);
// Now fit the map to the newly inclusive bounds
if (locations.length > 1){
map.fitBounds(bounds);
}
} | function generate_location_map(center, locations, batteries){
if (locations.length > 1) {
map_id = 'all';
}
else{
map_id = batteries[0].id;
}
// Generates the map
var map = new google.maps.Map(document.getElementById('map_' + map_id), {
zoom: 13,
center: new google.maps.LatLng(center[0], center[1]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = get_markers(map, locations, batteries);
// Now fit the map to the newly inclusive bounds
if (locations.length > 1){
map.fitBounds(bounds);
}
} |
JavaScript | function show_mini_maps(batteries){
batteries.forEach(function (battery){
init_map_locations([battery]);
graph_battery_life(5, battery)
});
} | function show_mini_maps(batteries){
batteries.forEach(function (battery){
init_map_locations([battery]);
graph_battery_life(5, battery)
});
} |
JavaScript | function generate_path_map(center, path, battery){
// Generates the map
if (battery){
id = battery.id;
}
else{
id = 'all';
}
var map = new google.maps.Map(document.getElementById('map_' + id), {
zoom: 13,
center: new google.maps.LatLng(center[0], center[1]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Adds a marker at end points, create a path between each data point
if(path.length > 0 && id != 'all'){
var marker, i;
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow({});
for (i = 0; i < path.length; i++) {
if(i == 0 || i == path.length - 1){
marker = new google.maps.Marker({
position: new google.maps.LatLng(path[i].lat, path[i].lng),
map: map
});
infowindow = new google.maps.InfoWindow({});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent('EXAMPLE: Add start/end time');
infowindow.open(map, marker);
}
})(marker, i));
}
else{
marker = new google.maps.Marker({
position: new google.maps.LatLng(path[i].lat, path[i].lng),
});
}
// Extend the bounds to include each marker's position
bounds.extend(marker.position);
}
// Now fit the map to the newly inclusive bounds
if(path.length > 1){
map.fitBounds(bounds);
}
}
//paths.forEach(function(path){
var path_characteristics = new google.maps.Polyline({
path: path,
geodesic: false,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
path_characteristics.setMap(map);
//});
} | function generate_path_map(center, path, battery){
// Generates the map
if (battery){
id = battery.id;
}
else{
id = 'all';
}
var map = new google.maps.Map(document.getElementById('map_' + id), {
zoom: 13,
center: new google.maps.LatLng(center[0], center[1]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Adds a marker at end points, create a path between each data point
if(path.length > 0 && id != 'all'){
var marker, i;
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow({});
for (i = 0; i < path.length; i++) {
if(i == 0 || i == path.length - 1){
marker = new google.maps.Marker({
position: new google.maps.LatLng(path[i].lat, path[i].lng),
map: map
});
infowindow = new google.maps.InfoWindow({});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent('EXAMPLE: Add start/end time');
infowindow.open(map, marker);
}
})(marker, i));
}
else{
marker = new google.maps.Marker({
position: new google.maps.LatLng(path[i].lat, path[i].lng),
});
}
// Extend the bounds to include each marker's position
bounds.extend(marker.position);
}
// Now fit the map to the newly inclusive bounds
if(path.length > 1){
map.fitBounds(bounds);
}
}
//paths.forEach(function(path){
var path_characteristics = new google.maps.Polyline({
path: path,
geodesic: false,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
path_characteristics.setMap(map);
//});
} |
JavaScript | function find_path_length(path){
var total_distance = 0;
var segment_distance;
var point;
for (point=0; point < path.length - 1; point++){
segment_distance = get_distance (path[point], path[point + 1]);
total_distance += segment_distance;
}
return total_distance;
} | function find_path_length(path){
var total_distance = 0;
var segment_distance;
var point;
for (point=0; point < path.length - 1; point++){
segment_distance = get_distance (path[point], path[point + 1]);
total_distance += segment_distance;
}
return total_distance;
} |
JavaScript | function display_distance(path, battery){
if (path.path.length > 1){
var display = document.getElementById('distance_display_' + battery.id);
distance = find_path_length(path.path).toFixed(2);
display.innerHTML = path.id + ': ' + distance + ' meters';
}
else{
clear_div('distance_display_' + battery.id);
}
} | function display_distance(path, battery){
if (path.path.length > 1){
var display = document.getElementById('distance_display_' + battery.id);
distance = find_path_length(path.path).toFixed(2);
display.innerHTML = path.id + ': ' + distance + ' meters';
}
else{
clear_div('distance_display_' + battery.id);
}
} |
JavaScript | function graph_battery_life(frequency, battery){
battery_info = get_battery_life(battery);
var coordinate = battery_info[1];
var trace1 = battery_info[0];
var data = [trace1];
if (coordinate[1]!=0){
var trace2 = predict_battery_life(frequency, coordinate);
data.push(trace2);
}
var layout = {
width: 300,
height: 300,
title: 'Battery Life',
xaxis: {
title: 'Time (hours)',
zeroline: true,
showline: true
},
yaxis: {
title: 'Battery Life (percentage)',
zeroline: true,
showline: true,
range: [0,100]
}
};
Plotly.newPlot('battery_graph_' + battery.id, data, layout);
} | function graph_battery_life(frequency, battery){
battery_info = get_battery_life(battery);
var coordinate = battery_info[1];
var trace1 = battery_info[0];
var data = [trace1];
if (coordinate[1]!=0){
var trace2 = predict_battery_life(frequency, coordinate);
data.push(trace2);
}
var layout = {
width: 300,
height: 300,
title: 'Battery Life',
xaxis: {
title: 'Time (hours)',
zeroline: true,
showline: true
},
yaxis: {
title: 'Battery Life (percentage)',
zeroline: true,
showline: true,
range: [0,100]
}
};
Plotly.newPlot('battery_graph_' + battery.id, data, layout);
} |
JavaScript | function predict_battery_life(frequency, coordinate){
var x_value = coordinate[0];
var y_value = coordinate[1];
var slope = rate_of_decay(frequency);
var trace = {
fill: 'none',
mode: 'lines',
dash: 'dot',
linecolor: '#055ea8',
name: 'Predicted Battery Life',
x: [x_value],
y: [y_value]
}
while (y_value > 0){
x_value += slope.x;
y_value += slope.y;
trace.x.push(x_value);
trace.y.push(y_value);
//console.log();
}
console.log(trace);
return trace;
} | function predict_battery_life(frequency, coordinate){
var x_value = coordinate[0];
var y_value = coordinate[1];
var slope = rate_of_decay(frequency);
var trace = {
fill: 'none',
mode: 'lines',
dash: 'dot',
linecolor: '#055ea8',
name: 'Predicted Battery Life',
x: [x_value],
y: [y_value]
}
while (y_value > 0){
x_value += slope.x;
y_value += slope.y;
trace.x.push(x_value);
trace.y.push(y_value);
//console.log();
}
console.log(trace);
return trace;
} |
JavaScript | function rate_of_decay(frequency){
var rate;
if (frequency == 5){
rate = {x:1, y:-2}
}
else if (frequency == 10){
rate = {x:3, y:-3}
}
else if (frequency == 30){
rate = {x:8, y:-4}
}
console.log('rate: ' + rate);
return rate;
} | function rate_of_decay(frequency){
var rate;
if (frequency == 5){
rate = {x:1, y:-2}
}
else if (frequency == 10){
rate = {x:3, y:-3}
}
else if (frequency == 30){
rate = {x:8, y:-4}
}
console.log('rate: ' + rate);
return rate;
} |
JavaScript | function toggle_collapse_menu(){
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
}
else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
} | function toggle_collapse_menu(){
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
}
else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
} |
JavaScript | function create_collapse_menus(batteries){
var info;
var button;
var battery_life_display;
var select = document.getElementById('collapse_menus');
batteries.forEach(function(battery){
info = "<div class='info_bar' id='edit_" + battery.id +
"' contenteditable='true' onkeyup='saveEdits(this.id, batteries)'>" + battery.id + "</div>";
console.log(battery.id)
select_menu = "<select class='info_bar' id='select_" + battery.id + "' onchange=' graph_battery_life(this.value, " + battery.id + ")'>" +
"<option value='5' class='freq_" + battery.id + "'>5</option>" +
"<option value='10' class='freq_" + battery.id + "'>10</option>" +
"<option value='30' class='freq_" + battery.id + "'>30</option>" +
"</select>"
battery_life_display = "<p class='info_bar' id='battery_display_" + battery.id + "'>Hello</p>"
button = "<button class='collapsible info_bar' id='collapsible_" + battery.id + "' value =" + battery.id + "> " + battery.id + " </button>";
content =
"<div class='content' name=" + battery.id + ">" +
"<div id='map_" + battery.id + "' class='map'></div>" +
"<div id='dropdowns'>" +
"<select id='path_dropdown_" + battery.id + "' onload='populate_paths(" + battery.id + ")' onchange='change_path_map(this.value, " + battery.id +")'></select>" +
"</div>" +
"<div id='stats'>" +
"<div class='distance_display' id='distance_display_" + battery.id + "'>Distance</div>" +
"<div class='altitude_graph' id='altitude_graph_" + battery.id + "'></div>" +
"<div class='battery_graph' id='battery_graph_" + battery.id + "'></div>" +
"</div>" +
"</div>";
select.innerHTML += info;
select.innerHTML += battery_life_display;
select.innerHTML += select_menu;
select.innerHTML += button;
select.innerHTML += content;
populate_paths(battery);
});
toggle_collapse_menu();
} | function create_collapse_menus(batteries){
var info;
var button;
var battery_life_display;
var select = document.getElementById('collapse_menus');
batteries.forEach(function(battery){
info = "<div class='info_bar' id='edit_" + battery.id +
"' contenteditable='true' onkeyup='saveEdits(this.id, batteries)'>" + battery.id + "</div>";
console.log(battery.id)
select_menu = "<select class='info_bar' id='select_" + battery.id + "' onchange=' graph_battery_life(this.value, " + battery.id + ")'>" +
"<option value='5' class='freq_" + battery.id + "'>5</option>" +
"<option value='10' class='freq_" + battery.id + "'>10</option>" +
"<option value='30' class='freq_" + battery.id + "'>30</option>" +
"</select>"
battery_life_display = "<p class='info_bar' id='battery_display_" + battery.id + "'>Hello</p>"
button = "<button class='collapsible info_bar' id='collapsible_" + battery.id + "' value =" + battery.id + "> " + battery.id + " </button>";
content =
"<div class='content' name=" + battery.id + ">" +
"<div id='map_" + battery.id + "' class='map'></div>" +
"<div id='dropdowns'>" +
"<select id='path_dropdown_" + battery.id + "' onload='populate_paths(" + battery.id + ")' onchange='change_path_map(this.value, " + battery.id +")'></select>" +
"</div>" +
"<div id='stats'>" +
"<div class='distance_display' id='distance_display_" + battery.id + "'>Distance</div>" +
"<div class='altitude_graph' id='altitude_graph_" + battery.id + "'></div>" +
"<div class='battery_graph' id='battery_graph_" + battery.id + "'></div>" +
"</div>" +
"</div>";
select.innerHTML += info;
select.innerHTML += battery_life_display;
select.innerHTML += select_menu;
select.innerHTML += button;
select.innerHTML += content;
populate_paths(battery);
});
toggle_collapse_menu();
} |
JavaScript | function saveEdits(id) {
var editElem = document.getElementById(id);
var userVersion = editElem.innerHTML;
//save the content to local storage
localStorage[id] = userVersion;
} | function saveEdits(id) {
var editElem = document.getElementById(id);
var userVersion = editElem.innerHTML;
//save the content to local storage
localStorage[id] = userVersion;
} |
JavaScript | function show_mini_maps(batteries){
batteries.forEach(function (battery){
init_map_locations([battery]);
});
} | function show_mini_maps(batteries){
batteries.forEach(function (battery){
init_map_locations([battery]);
});
} |
JavaScript | function generate_path_map(center, path, battery){
// Generates the map
if (battery){
id = battery.id;
}
else{
id = 'all';
}
console.log(id);
var map = new google.maps.Map(document.getElementById('map_' + id), {
zoom: 13,
center: new google.maps.LatLng(center[0], center[1]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Adds a marker at end points, create a path between each data point
if(path.length > 0 && id != 'all'){
var marker, i;
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow({});
for (i = 0; i < path.length; i++) {
if(i == 0 || i == path.length - 1){
marker = new google.maps.Marker({
position: new google.maps.LatLng(path[i].lat, path[i].lng),
map: map
});
infowindow = new google.maps.InfoWindow({});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent('EXAMPLE: Add start/end time');
infowindow.open(map, marker);
}
})(marker, i));
}
else{
marker = new google.maps.Marker({
position: new google.maps.LatLng(path[i].lat, path[i].lng),
});
}
// Extend the bounds to include each marker's position
bounds.extend(marker.position);
}
// Now fit the map to the newly inclusive bounds
if(path.length > 1){
map.fitBounds(bounds);
}
}
//paths.forEach(function(path){
var path_characteristics = new google.maps.Polyline({
path: path,
geodesic: false,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
path_characteristics.setMap(map);
//});
} | function generate_path_map(center, path, battery){
// Generates the map
if (battery){
id = battery.id;
}
else{
id = 'all';
}
console.log(id);
var map = new google.maps.Map(document.getElementById('map_' + id), {
zoom: 13,
center: new google.maps.LatLng(center[0], center[1]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Adds a marker at end points, create a path between each data point
if(path.length > 0 && id != 'all'){
var marker, i;
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow({});
for (i = 0; i < path.length; i++) {
if(i == 0 || i == path.length - 1){
marker = new google.maps.Marker({
position: new google.maps.LatLng(path[i].lat, path[i].lng),
map: map
});
infowindow = new google.maps.InfoWindow({});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent('EXAMPLE: Add start/end time');
infowindow.open(map, marker);
}
})(marker, i));
}
else{
marker = new google.maps.Marker({
position: new google.maps.LatLng(path[i].lat, path[i].lng),
});
}
// Extend the bounds to include each marker's position
bounds.extend(marker.position);
}
// Now fit the map to the newly inclusive bounds
if(path.length > 1){
map.fitBounds(bounds);
}
}
//paths.forEach(function(path){
var path_characteristics = new google.maps.Polyline({
path: path,
geodesic: false,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
path_characteristics.setMap(map);
//});
} |
JavaScript | function populate_paths(battery_id){
/* if(battery_id == "show_all_batteries"){
init_map_locations();
populate("", 'path_dropdown');
clear_div('altitude_graph');
clear_div('distance_display');
}
else{ */
batteries.forEach(function(battery){
if (battery.id == battery_id){
populate(battery.paths, 'path_dropdown_' + battery.id);
init_map_path(battery.paths[0].path);
display_distance(battery.paths[0]);
get_altitude(battery.paths[0]);
}
});
} | function populate_paths(battery_id){
/* if(battery_id == "show_all_batteries"){
init_map_locations();
populate("", 'path_dropdown');
clear_div('altitude_graph');
clear_div('distance_display');
}
else{ */
batteries.forEach(function(battery){
if (battery.id == battery_id){
populate(battery.paths, 'path_dropdown_' + battery.id);
init_map_path(battery.paths[0].path);
display_distance(battery.paths[0]);
get_altitude(battery.paths[0]);
}
});
} |
JavaScript | function populate(list_items, select_id){
var select = document.getElementById(select_id);
select.innerHTML = "";
var newOption;
/*if (list_items.length > 0 && select_id == 'battery_dropdown'){
newOption = document.createElement("option");
newOption.value = 'show_all_batteries';
newOption.innerHTML = "Show All Batteries";
select.options.add(newOption);
} */
for(item in list_items){
newOption = document.createElement("option");
newOption.value = list_items[item].id;
newOption.innerHTML = list_items[item].id;
select.options.add(newOption);
}
} | function populate(list_items, select_id){
var select = document.getElementById(select_id);
select.innerHTML = "";
var newOption;
/*if (list_items.length > 0 && select_id == 'battery_dropdown'){
newOption = document.createElement("option");
newOption.value = 'show_all_batteries';
newOption.innerHTML = "Show All Batteries";
select.options.add(newOption);
} */
for(item in list_items){
newOption = document.createElement("option");
newOption.value = list_items[item].id;
newOption.innerHTML = list_items[item].id;
select.options.add(newOption);
}
} |
JavaScript | function display_distance(path){
if (path.path.length > 1){
var display = document.getElementById('distance_display');
distance = find_path_length(path.path).toFixed(2);
display.innerHTML = path.id + ': ' + distance + ' meters';
}
else{
clear_div('distance_display');
}
} | function display_distance(path){
if (path.path.length > 1){
var display = document.getElementById('distance_display');
distance = find_path_length(path.path).toFixed(2);
display.innerHTML = path.id + ': ' + distance + ' meters';
}
else{
clear_div('distance_display');
}
} |
JavaScript | function toggle_collapse_menu(){
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
console.log('Close Collapse Menu')
}
else {
content.style.maxHeight = content.scrollHeight + "px";
console.log('Open Collapse Menu');
}
});
}
} | function toggle_collapse_menu(){
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
console.log('Close Collapse Menu')
}
else {
content.style.maxHeight = content.scrollHeight + "px";
console.log('Open Collapse Menu');
}
});
}
} |
JavaScript | function maximumPathSumII(triangle) {
for (let i = triangle.length - 2; i >= 0; i--)
for (let j = 0; j <= i; j++)
triangle[i][j] += ((triangle[i+1][j] > triangle[i+1][j+1]) ? triangle[i+1][j] : triangle[i+1][j+1]);
return triangle[0][0];
} | function maximumPathSumII(triangle) {
for (let i = triangle.length - 2; i >= 0; i--)
for (let j = 0; j <= i; j++)
triangle[i][j] += ((triangle[i+1][j] > triangle[i+1][j+1]) ? triangle[i+1][j] : triangle[i+1][j+1]);
return triangle[0][0];
} |
JavaScript | function longestCollatzSequence(limit) {
//The number with the largest chain
let longest = 1;
//The length of the largest chain
let maxLength = 1;
for (let i = Math.floor(limit / 2); i < limit; i++) {
//length of chain
let len = colLen(i);
//if chain is longest, store number details and length
if (len > maxLength)
{
longest = i;
maxLength = len;
}
}
return longest;
} | function longestCollatzSequence(limit) {
//The number with the largest chain
let longest = 1;
//The length of the largest chain
let maxLength = 1;
for (let i = Math.floor(limit / 2); i < limit; i++) {
//length of chain
let len = colLen(i);
//if chain is longest, store number details and length
if (len > maxLength)
{
longest = i;
maxLength = len;
}
}
return longest;
} |
JavaScript | function isPrime(n) {
for (let i=2; i<=Math.sqrt(n); i++)
if (n%i==0)
return false;
return true;
} | function isPrime(n) {
for (let i=2; i<=Math.sqrt(n); i++)
if (n%i==0)
return false;
return true;
} |
JavaScript | function multiplesOf3and5(number) {
var sum = 0;
for (let i=3; i<number; i++)
if (i%3==0 && i%5==0)
sum += i;
return sum;
} | function multiplesOf3and5(number) {
var sum = 0;
for (let i=3; i<number; i++)
if (i%3==0 && i%5==0)
sum += i;
return sum;
} |
JavaScript | function sumSquareDifference(n) {
//Using series formulae
var sumOfSquares = n*(n+1)*(2*n+1)/6;
var squareOfSum = Math.pow(n*(n+1)/2, 2);
return squareOfSum - sumOfSquares;
} | function sumSquareDifference(n) {
//Using series formulae
var sumOfSquares = n*(n+1)*(2*n+1)/6;
var squareOfSum = Math.pow(n*(n+1)/2, 2);
return squareOfSum - sumOfSquares;
} |
JavaScript | function powerDigitSum(exponent) {
//You can't just do 2^1000 because a normal computer can't do that ( 64 bit can only do 2^64 )
const num = BigInt(2**exponent);
//converting number to string of digits
const digits = num.toString().split('');
//Taking sum of digits
const sumOfDigits = digits.reduce((sum, digit) => sum + Number(digit), 0)
return sumOfDigits;
} | function powerDigitSum(exponent) {
//You can't just do 2^1000 because a normal computer can't do that ( 64 bit can only do 2^64 )
const num = BigInt(2**exponent);
//converting number to string of digits
const digits = num.toString().split('');
//Taking sum of digits
const sumOfDigits = digits.reduce((sum, digit) => sum + Number(digit), 0)
return sumOfDigits;
} |
JavaScript | function primeSummation2(n) {
let isPrime = Array(n).fill(true); //initialize array of n elements and fill with true
//0 and 1 are not prime
isPrime[0] = false;
isPrime[1] = false;
//change multiples of each prime number to false since they are not false
for (let i=2; i<=Math.sqrt(n); i++)
if (isPrime[i])
for (let j=i**2; j<n; j+=i)
isPrime[j] = false;
let sum = 0;
for (let i=0; i<n; i++)
if (isPrime[i])
sum += i;
return sum;
//return isPrime.reduce((sum, prime, index) => prime ? sum + index : sum, 0;
} | function primeSummation2(n) {
let isPrime = Array(n).fill(true); //initialize array of n elements and fill with true
//0 and 1 are not prime
isPrime[0] = false;
isPrime[1] = false;
//change multiples of each prime number to false since they are not false
for (let i=2; i<=Math.sqrt(n); i++)
if (isPrime[i])
for (let j=i**2; j<n; j+=i)
isPrime[j] = false;
let sum = 0;
for (let i=0; i<n; i++)
if (isPrime[i])
sum += i;
return sum;
//return isPrime.reduce((sum, prime, index) => prime ? sum + index : sum, 0;
} |
JavaScript | function largestGridProduct(arr) {
let max = 0;
function maxCheck(n) {
if (n > max)
return max = n;
}
for (let i=0; i<arr.length; i++)
{
for (let j=0; j<arr[i].length; j++)
{
let prod = 1;
//horizontal
if (j < arr[i].length-3)
{
prod = arr[i][j] * arr[i][j+1] * arr[i][j+2] * arr[i][j+3];
maxCheck(prod);
}
//vertical
if (i < arr.length-3)
{
prod = arr[i][j] * arr[i+1][j] * arr[i+2][j] * arr[i+3][j];
maxCheck(prod);
}
//diagonal [\]
if (j < arr[i].length-3 && i < arr.length-3)
{
prod = arr[i][j] * arr[i+1][j+1] * arr[i+2][j+2] * arr[i+3][j+3];
maxCheck(prod);
}
//diagonal [/]
if (j > 3 && i < arr.length-3)
{
prod = arr[i][j] * arr[i-1][j-1] * arr[i-2][j-2] * arr[i-3][j-3];
maxCheck(prod);
}
}
}
return max;
} | function largestGridProduct(arr) {
let max = 0;
function maxCheck(n) {
if (n > max)
return max = n;
}
for (let i=0; i<arr.length; i++)
{
for (let j=0; j<arr[i].length; j++)
{
let prod = 1;
//horizontal
if (j < arr[i].length-3)
{
prod = arr[i][j] * arr[i][j+1] * arr[i][j+2] * arr[i][j+3];
maxCheck(prod);
}
//vertical
if (i < arr.length-3)
{
prod = arr[i][j] * arr[i+1][j] * arr[i+2][j] * arr[i+3][j];
maxCheck(prod);
}
//diagonal [\]
if (j < arr[i].length-3 && i < arr.length-3)
{
prod = arr[i][j] * arr[i+1][j+1] * arr[i+2][j+2] * arr[i+3][j+3];
maxCheck(prod);
}
//diagonal [/]
if (j > 3 && i < arr.length-3)
{
prod = arr[i][j] * arr[i-1][j-1] * arr[i-2][j-2] * arr[i-3][j-3];
maxCheck(prod);
}
}
}
return max;
} |
JavaScript | function multiply(n, v) {
let carry = 0;
let size = v.length;
/*
Explanation:
2 1
7 4 4 * 3 = 12 => 1 carry and 2 is the digit
x 3 1 + (7 * 3) = 22 => 2 carry and 2 is the digit
-------- then placing each digit of the carry in the next array index => 2 is the next digit
2 2 2
*/
for (let i = 0; i < size; i++)
{
let result = (v[i] * n) + carry;
//Storing the ones digit in the array of that multiplication
v[i] = result % 10;
//Carrying over the rest of the number
carry = Math.floor(result / 10);
}
//Placing each digit of the carry
while (carry != 0)
{
v.push(carry % 10);
carry = Math.floor(carry / 10);
}
} | function multiply(n, v) {
let carry = 0;
let size = v.length;
/*
Explanation:
2 1
7 4 4 * 3 = 12 => 1 carry and 2 is the digit
x 3 1 + (7 * 3) = 22 => 2 carry and 2 is the digit
-------- then placing each digit of the carry in the next array index => 2 is the next digit
2 2 2
*/
for (let i = 0; i < size; i++)
{
let result = (v[i] * n) + carry;
//Storing the ones digit in the array of that multiplication
v[i] = result % 10;
//Carrying over the rest of the number
carry = Math.floor(result / 10);
}
//Placing each digit of the carry
while (carry != 0)
{
v.push(carry % 10);
carry = Math.floor(carry / 10);
}
} |
JavaScript | function maximumPathSumI(triangle) {
for (let i = triangle.length - 2; i >= 0; i--)
for (let j = 0; j <= i; j++)
triangle[i][j] += ((triangle[i+1][j] > triangle[i+1][j+1]) ? triangle[i+1][j] : triangle[i+1][j+1]);
return triangle[0][0];
} | function maximumPathSumI(triangle) {
for (let i = triangle.length - 2; i >= 0; i--)
for (let j = 0; j <= i; j++)
triangle[i][j] += ((triangle[i+1][j] > triangle[i+1][j+1]) ? triangle[i+1][j] : triangle[i+1][j+1]);
return triangle[0][0];
} |
JavaScript | function digitnPowers(n) {
//Initializing sum
var total = 0;
//Checking the condition for every number
for (let i = 2; i <= Math.pow(9, n) * n; i++)
{
//Storing digits in array
let digits = i.toString().split('');
//Raising each digit to the power n
for (let j = 0; j < digits.length; j++)
digits[j] = digits[j] ** n;
//Taking sum of digit
let powerSum = digits.reduce((sum, digit) => sum + Number(digit), 0);
//Adding it to the sum
if (powerSum == i)
total += i;
}
return total;
} | function digitnPowers(n) {
//Initializing sum
var total = 0;
//Checking the condition for every number
for (let i = 2; i <= Math.pow(9, n) * n; i++)
{
//Storing digits in array
let digits = i.toString().split('');
//Raising each digit to the power n
for (let j = 0; j < digits.length; j++)
digits[j] = digits[j] ** n;
//Taking sum of digit
let powerSum = digits.reduce((sum, digit) => sum + Number(digit), 0);
//Adding it to the sum
if (powerSum == i)
total += i;
}
return total;
} |
JavaScript | function daysInFeb(year) {
if (year % 4 != 0)
return 28;
if (year % 100 == 0 && year % 400 != 0)
return 28;
return 29;
} | function daysInFeb(year) {
if (year % 4 != 0)
return 28;
if (year % 100 == 0 && year % 400 != 0)
return 28;
return 29;
} |
JavaScript | function sendHighlightedText(tabs) {
// Send message to the content script
chrome.tabs.sendMessage(tabs[0].id, {
message: "get_txt"
}, response => {
// Check if the response from pop up script is "successfull"
if (response.message === "successful") {
$("#criteria").val(response.payload);
}
});
} | function sendHighlightedText(tabs) {
// Send message to the content script
chrome.tabs.sendMessage(tabs[0].id, {
message: "get_txt"
}, response => {
// Check if the response from pop up script is "successfull"
if (response.message === "successful") {
$("#criteria").val(response.payload);
}
});
} |
JavaScript | function removeModule ({ commit }, module) {
commit('setIsEditing', true)
/**
* Collect nested module data and store in array for removal
*/
const nestedModules = [...module.node.querySelectorAll('[data-module]')]
const moduleDataToRemove = this.state.modules.filter(
moduleObj => nestedModules.indexOf(moduleObj.node) !== -1
)
moduleDataToRemove.push(module)
/**
* Remove node from DOM
*/
this.state.context.nestedModules = this.state.context.nestedModules.filter(
node => node !== module.node
)
module.node.remove()
/**
* Remove data from state
*/
commit('removeModuleData', moduleDataToRemove)
this.dispatch('updateHighlights')
this.dispatch('setHighlightedModule', null)
} | function removeModule ({ commit }, module) {
commit('setIsEditing', true)
/**
* Collect nested module data and store in array for removal
*/
const nestedModules = [...module.node.querySelectorAll('[data-module]')]
const moduleDataToRemove = this.state.modules.filter(
moduleObj => nestedModules.indexOf(moduleObj.node) !== -1
)
moduleDataToRemove.push(module)
/**
* Remove node from DOM
*/
this.state.context.nestedModules = this.state.context.nestedModules.filter(
node => node !== module.node
)
module.node.remove()
/**
* Remove data from state
*/
commit('removeModuleData', moduleDataToRemove)
this.dispatch('updateHighlights')
this.dispatch('setHighlightedModule', null)
} |
JavaScript | async function loadScripts (scripts) {
const scriptsWithSrc = scripts.filter(script => script.src)
const inlineScripts = scripts.filter(script => !script.src)
// inline scripts most likely rely on an external api, run first
if (scriptsWithSrc.length) {
await fetchExternalScripts(scriptsWithSrc)
}
if (inlineScripts.length) {
runInlineScripts(inlineScripts)
}
} | async function loadScripts (scripts) {
const scriptsWithSrc = scripts.filter(script => script.src)
const inlineScripts = scripts.filter(script => !script.src)
// inline scripts most likely rely on an external api, run first
if (scriptsWithSrc.length) {
await fetchExternalScripts(scriptsWithSrc)
}
if (inlineScripts.length) {
runInlineScripts(inlineScripts)
}
} |
JavaScript | function runInlineScripts (scripts) {
scripts.forEach(inlineScript => {
// eslint-disable-next-line no-eval
eval(inlineScript.innerHTML)
})
} | function runInlineScripts (scripts) {
scripts.forEach(inlineScript => {
// eslint-disable-next-line no-eval
eval(inlineScript.innerHTML)
})
} |
JavaScript | function fetchExternalScripts (scripts) {
return new Promise((resolve, reject) => {
const scriptPromises = scripts.map(scriptTag => new Promise((resolve, reject) => {
const scriptEl = document.createElement('script')
scriptEl.onload = () => { resolve() }
scriptEl.src = scriptTag.src
document.body.appendChild(scriptEl)
}))
Promise.all(scriptPromises).then(resolve)
})
} | function fetchExternalScripts (scripts) {
return new Promise((resolve, reject) => {
const scriptPromises = scripts.map(scriptTag => new Promise((resolve, reject) => {
const scriptEl = document.createElement('script')
scriptEl.onload = () => { resolve() }
scriptEl.src = scriptTag.src
document.body.appendChild(scriptEl)
}))
Promise.all(scriptPromises).then(resolve)
})
} |
JavaScript | async uploadFile (uri) {
this.confirmEl.classList.remove('-active')
this.fileUi.classList.add('-active')
const response = await axios
.post('/api/v1/cms/files/', uri, {
headers: {
'X-CSRF-Token': store.state.token,
'Content-Type': 'text/plain'
}
})
this.fileUi.classList.remove('-active')
return response.headers.location
} | async uploadFile (uri) {
this.confirmEl.classList.remove('-active')
this.fileUi.classList.add('-active')
const response = await axios
.post('/api/v1/cms/files/', uri, {
headers: {
'X-CSRF-Token': store.state.token,
'Content-Type': 'text/plain'
}
})
this.fileUi.classList.remove('-active')
return response.headers.location
} |
JavaScript | function openModulesList ({ commit }, orderArray) {
const { context } = this.state
const { modules } = this.state
commit('setIsEditing', true)
/**
* Create module data array based on order of module IDs
*/
const relatedModuleData = orderArray.map(id => {
let correspondingModule = {}
modules.forEach(module => {
if (module.id === id) {
correspondingModule = module
}
})
return correspondingModule
})
/**
* Clean up highlight classes
*/
context.nestedModules.forEach(module => {
module.classList.remove('-highlight')
})
/**
* Remove modules from visible dom
*/
while (context.node.firstChild) {
context.node.removeChild(context.node.firstChild)
}
/**
* Reappend same referenced nodes in new order
*/
relatedModuleData.forEach(module => {
context.node.append(module.node)
})
/**
* Update data representation for current container
*/
commit('setContextModules', relatedModuleData)
this.dispatch('updateHighlights')
} | function openModulesList ({ commit }, orderArray) {
const { context } = this.state
const { modules } = this.state
commit('setIsEditing', true)
/**
* Create module data array based on order of module IDs
*/
const relatedModuleData = orderArray.map(id => {
let correspondingModule = {}
modules.forEach(module => {
if (module.id === id) {
correspondingModule = module
}
})
return correspondingModule
})
/**
* Clean up highlight classes
*/
context.nestedModules.forEach(module => {
module.classList.remove('-highlight')
})
/**
* Remove modules from visible dom
*/
while (context.node.firstChild) {
context.node.removeChild(context.node.firstChild)
}
/**
* Reappend same referenced nodes in new order
*/
relatedModuleData.forEach(module => {
context.node.append(module.node)
})
/**
* Update data representation for current container
*/
commit('setContextModules', relatedModuleData)
this.dispatch('updateHighlights')
} |
JavaScript | function resetListContext ({ commit }) {
/**
* NOTE: Yes this is hacky, if I figure out a way to remount
* the list component in a better way that doesn't require
* statechange I'll update it.
*/
const tempContextRef = this.state.context
commit('setIsModuleMode', false)
commit('setContext', tempContextRef)
setTimeout(() => {
commit('setIsModuleMode', true)
}, 0)
} | function resetListContext ({ commit }) {
/**
* NOTE: Yes this is hacky, if I figure out a way to remount
* the list component in a better way that doesn't require
* statechange I'll update it.
*/
const tempContextRef = this.state.context
commit('setIsModuleMode', false)
commit('setContext', tempContextRef)
setTimeout(() => {
commit('setIsModuleMode', true)
}, 0)
} |
JavaScript | toggleShortUrl () {
if (this.isShortened) {
this.shareUrl = this.currentUrl
} else {
let context = this
this.short().then((shortUrl => {
context.shareUrl = shortUrl
context.isShortened = true
context.showSuccess(context.$t('share.urlShortened'), { timeout: 2000 })
})).catch(() => {
context.showError(context.$t('share.shorteningNotPossible'), { timeout: 2000 })
})
}
this.isShortened = !this.isShortened
} | toggleShortUrl () {
if (this.isShortened) {
this.shareUrl = this.currentUrl
} else {
let context = this
this.short().then((shortUrl => {
context.shareUrl = shortUrl
context.isShortened = true
context.showSuccess(context.$t('share.urlShortened'), { timeout: 2000 })
})).catch(() => {
context.showError(context.$t('share.shorteningNotPossible'), { timeout: 2000 })
})
}
this.isShortened = !this.isShortened
} |
JavaScript | copyUrl () {
const url = this.shareUrl ? this.shareUrl : this.currentUrl
if (this.copyToClipboard(url)) {
this.showSuccess(this.$t('share.urlCopied'), { timeout: 2000 })
}
} | copyUrl () {
const url = this.shareUrl ? this.shareUrl : this.currentUrl
if (this.copyToClipboard(url)) {
this.showSuccess(this.$t('share.urlCopied'), { timeout: 2000 })
}
} |
JavaScript | copyEmbed () {
if (this.copyToClipboard(this.embedCode)) {
this.showSuccess(this.$t('share.embedCodeCopied'), { timeout: 2000 })
}
} | copyEmbed () {
if (this.copyToClipboard(this.embedCode)) {
this.showSuccess(this.$t('share.embedCodeCopied'), { timeout: 2000 })
}
} |
JavaScript | copyToClipboard (str) {
const tempTextArea = document.createElement('textarea')
tempTextArea.value = str
this.$refs.shareContainer.appendChild(tempTextArea)
tempTextArea.select()
const result = document.execCommand('copy')
document.body.removeChild(tempTextArea)
return result
} | copyToClipboard (str) {
const tempTextArea = document.createElement('textarea')
tempTextArea.value = str
this.$refs.shareContainer.appendChild(tempTextArea)
tempTextArea.select()
const result = document.execCommand('copy')
document.body.removeChild(tempTextArea)
return result
} |
JavaScript | short () {
const bitlyBaseApiUrl = 'https://api-ssl.bitly.com/v3/shorten'
const apiKey = appConfig.bitlyApiKey
const login = appConfig.bitlyLogin
let publicUrl = location.href
// The bit.ly service does not work with localhost.
// So we always replace the current host by the public host
if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') {
const baseUrl = `${location.protocol}//${location.host}`
publicUrl = location.href.replace(baseUrl, constants.orsPublicHost)
}
const longUrl = encodeURIComponent(publicUrl)
const shortenerRequestUrl = `${bitlyBaseApiUrl}?login=${login}&apiKey=${apiKey}&longUrl=${longUrl}`
// Run the request and get the short url
let httpClient = new HttpClient({getVueInstance: () => { return this }})
return new Promise((resolve, reject) => {
httpClient.http.get(shortenerRequestUrl).then((response) => {
if (response.data.status_code === 200) {
resolve(response.data.data.url)
} else {
console.log(response)
reject(response)
}
}).catch((error) => {
console.log(error)
reject(error)
})
})
} | short () {
const bitlyBaseApiUrl = 'https://api-ssl.bitly.com/v3/shorten'
const apiKey = appConfig.bitlyApiKey
const login = appConfig.bitlyLogin
let publicUrl = location.href
// The bit.ly service does not work with localhost.
// So we always replace the current host by the public host
if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') {
const baseUrl = `${location.protocol}//${location.host}`
publicUrl = location.href.replace(baseUrl, constants.orsPublicHost)
}
const longUrl = encodeURIComponent(publicUrl)
const shortenerRequestUrl = `${bitlyBaseApiUrl}?login=${login}&apiKey=${apiKey}&longUrl=${longUrl}`
// Run the request and get the short url
let httpClient = new HttpClient({getVueInstance: () => { return this }})
return new Promise((resolve, reject) => {
httpClient.http.get(shortenerRequestUrl).then((response) => {
if (response.data.status_code === 200) {
resolve(response.data.data.url)
} else {
console.log(response)
reject(response)
}
}).catch((error) => {
console.log(error)
reject(error)
})
})
} |
JavaScript | drawOptions (cantIntersectMsg) {
var options = {
position: 'topleft',
draw: {
polyline: false,
rectangle: true,
marker: false,
circlemarker: false,
circle: false, // circle is not supported as an avoid area
polygon: {
allowIntersection: false, // Restricts shapes to simple polygons
drawError: {
color: '#e1e100', // Color the shape will turn when intersects
message: cantIntersectMsg // Message that will show when intersect
},
shapeOptions: {
color: 'blue'
},
showArea: true,
showLength: true
}
}
}
return options
} | drawOptions (cantIntersectMsg) {
var options = {
position: 'topleft',
draw: {
polyline: false,
rectangle: true,
marker: false,
circlemarker: false,
circle: false, // circle is not supported as an avoid area
polygon: {
allowIntersection: false, // Restricts shapes to simple polygons
drawError: {
color: '#e1e100', // Color the shape will turn when intersects
message: cantIntersectMsg // Message that will show when intersect
},
shapeOptions: {
color: 'blue'
},
showArea: true,
showLength: true
}
}
}
return options
} |
JavaScript | function parseFnKeyConst( str_ , runtime ) {
var separatorIndex = nextSeparator( str_ , runtime ) ;
var str = str_.slice( runtime.i , separatorIndex ) ;
//console.log( 'str before:' , str_ ) ;
//console.log( 'str after:' , str ) ;
//var indexOf ;
//str = str.slice( runtime.i , runtime.iEndOfLine ) ;
//if ( ( indexOf = str.indexOf( ' ' ) ) !== -1 ) { str = str.slice( 0 , indexOf ) ; }
runtime.i += str.length ;
if (
str_[ separatorIndex ] === ':' ||
( str_[ separatorIndex ] === ' ' && afterSpacesChar( str_ , runtime , separatorIndex ) === ':' )
) {
// This is a key, return the unquoted string
return str ;
}
else if ( str in common.constants ) {
return common.constants[ str ] ;
}
else if ( fnOperators[ str ] ) {
return fnOperators[ str ] ;
}
else if ( str in expressionConstants ) {
return expressionConstants[ str ] ;
}
else if ( runtime.operators && runtime.operators[ str ] ) {
if ( ! runtime.operators[ str ].xop ) { runtime.operators[ str ].xop = true ; } // Mark the function as being from extra operators
return runtime.operators[ str ] ;
}
else if ( runtime.constants && ( str in runtime.constants ) ) {
return runtime.constants[ str ] ;
}
throw new SyntaxError( "Unexpected '" + str + "' in expression" ) ;
} | function parseFnKeyConst( str_ , runtime ) {
var separatorIndex = nextSeparator( str_ , runtime ) ;
var str = str_.slice( runtime.i , separatorIndex ) ;
//console.log( 'str before:' , str_ ) ;
//console.log( 'str after:' , str ) ;
//var indexOf ;
//str = str.slice( runtime.i , runtime.iEndOfLine ) ;
//if ( ( indexOf = str.indexOf( ' ' ) ) !== -1 ) { str = str.slice( 0 , indexOf ) ; }
runtime.i += str.length ;
if (
str_[ separatorIndex ] === ':' ||
( str_[ separatorIndex ] === ' ' && afterSpacesChar( str_ , runtime , separatorIndex ) === ':' )
) {
// This is a key, return the unquoted string
return str ;
}
else if ( str in common.constants ) {
return common.constants[ str ] ;
}
else if ( fnOperators[ str ] ) {
return fnOperators[ str ] ;
}
else if ( str in expressionConstants ) {
return expressionConstants[ str ] ;
}
else if ( runtime.operators && runtime.operators[ str ] ) {
if ( ! runtime.operators[ str ].xop ) { runtime.operators[ str ].xop = true ; } // Mark the function as being from extra operators
return runtime.operators[ str ] ;
}
else if ( runtime.constants && ( str in runtime.constants ) ) {
return runtime.constants[ str ] ;
}
throw new SyntaxError( "Unexpected '" + str + "' in expression" ) ;
} |
JavaScript | function extractAnimatedPropValues(props) {
const {animatedProps, ...otherProps} = props;
return animatedProps.reduce((result, animatedPropName) => {
if (Object.prototype.hasOwnProperty.call(otherProps, animatedPropName)) {
result[animatedPropName] = otherProps[animatedPropName];
}
return result;
}, {});
} | function extractAnimatedPropValues(props) {
const {animatedProps, ...otherProps} = props;
return animatedProps.reduce((result, animatedPropName) => {
if (Object.prototype.hasOwnProperty.call(otherProps, animatedPropName)) {
result[animatedPropName] = otherProps[animatedPropName];
}
return result;
}, {});
} |
JavaScript | function graphe(O,u){
i=-w/u;
context.strokeStyle="rgba(42,16,140,1)"; // Couleur du graphe
context.lineWidth="2"; // Largeur de la ligne du graphe
context.beginPath(); // On commence le traçage
while(i<(w/u)){
var a=((-f(i)*u+O.Y)); // On calcul l'image pour chaque i puis on multiplie par l'unité graphique et on fais la translation dans le nouveau repère.
context.lineTo(i*u+O.X,a); // On place le point apartenant au graphe
i+=0.01; // On incrémente i
}
context.stroke();
} | function graphe(O,u){
i=-w/u;
context.strokeStyle="rgba(42,16,140,1)"; // Couleur du graphe
context.lineWidth="2"; // Largeur de la ligne du graphe
context.beginPath(); // On commence le traçage
while(i<(w/u)){
var a=((-f(i)*u+O.Y)); // On calcul l'image pour chaque i puis on multiplie par l'unité graphique et on fais la translation dans le nouveau repère.
context.lineTo(i*u+O.X,a); // On place le point apartenant au graphe
i+=0.01; // On incrémente i
}
context.stroke();
} |
JavaScript | function second(){
if(btn[11].innerHTML=="↓"){
btn[11] .innerHTML="↑";
btn[11].style.background="#c0c0c0";
btn[11] .style.color="black";
sin.innerHTML="sin";
cos.innerHTML="cos";
tan.innerHTML="tan";
sin.removeEventListener("click", asinus, false);
sin.addEventListener("click", sinus, false);
cos.removeEventListener("click", acosnus, false);
cos.addEventListener("click", cosnus, false);
tan.removeEventListener("click", atangente, false);
tan.addEventListener("click", tangente, false);
}else{
btn[11].innerHTML="↓";
sin.innerHTML="sin-1";
cos.innerHTML="cos-1";
tan.innerHTML="tan-1";
sin.removeEventListener("click", sinus, false);
sin.addEventListener("click", asinus, false);
cos.removeEventListener("click", cosnus, false);
cos.addEventListener("click", acosnus, false);
tan.removeEventListener("click", tangente, false);
tan.addEventListener("click", atangente, false);
btn[11].style.background="rgba(42,16,140,1)";
btn[11].style.color="white";
}
} | function second(){
if(btn[11].innerHTML=="↓"){
btn[11] .innerHTML="↑";
btn[11].style.background="#c0c0c0";
btn[11] .style.color="black";
sin.innerHTML="sin";
cos.innerHTML="cos";
tan.innerHTML="tan";
sin.removeEventListener("click", asinus, false);
sin.addEventListener("click", sinus, false);
cos.removeEventListener("click", acosnus, false);
cos.addEventListener("click", cosnus, false);
tan.removeEventListener("click", atangente, false);
tan.addEventListener("click", tangente, false);
}else{
btn[11].innerHTML="↓";
sin.innerHTML="sin-1";
cos.innerHTML="cos-1";
tan.innerHTML="tan-1";
sin.removeEventListener("click", sinus, false);
sin.addEventListener("click", asinus, false);
cos.removeEventListener("click", cosnus, false);
cos.addEventListener("click", acosnus, false);
tan.removeEventListener("click", tangente, false);
tan.addEventListener("click", atangente, false);
btn[11].style.background="rgba(42,16,140,1)";
btn[11].style.color="white";
}
} |
JavaScript | function parse(program) {
var result = parseExpression(program);
if (skipSpace(result.rest).length > 0)
throw new SyntaxError("Unexpected text after program");
return result.expr;
} | function parse(program) {
var result = parseExpression(program);
if (skipSpace(result.rest).length > 0)
throw new SyntaxError("Unexpected text after program");
return result.expr;
} |
JavaScript | function hasError(error) {
if (error) {
$("#program-form-group").removeClass("has-success");
$("#program-form-group").addClass("has-error");
} else {
$("#program-form-group").removeClass("has-error");
$("#program-form-group").addClass("has-success");
}
} | function hasError(error) {
if (error) {
$("#program-form-group").removeClass("has-success");
$("#program-form-group").addClass("has-error");
} else {
$("#program-form-group").removeClass("has-error");
$("#program-form-group").addClass("has-success");
}
} |
JavaScript | function _getUid(from, to, date, subject) {
if(Array.isArray(date)) date = date[0];
if(Array.isArray(from)) from = from[0];
if(Array.isArray(to)) to = to[0];
if(Array.isArray(subject)) subject = subject[0];
to = typeof to !== "object" ? (to ? to.split(',')[0] : 'toUnknown') : to;
from = typeof from !== "object" ? (from ? from.split(',')[0] : 'fromUnknown') : from;
const momentDate = moment.utc(date).format("DD/MM/YYYY HH:mm:ss");
const fromAddress = typeof from === "object" ? from.address : from;
const toAddress = typeof to === "object" ? to.address : to;
const realFromAddress = fromAddress ? (fromAddress.indexOf('<') > -1 ? fromAddress.match(/<(.*?)>/i)[0]
.replace('<', '').replace('>', '') : fromAddress) : '';
const realToAddress = toAddress ? (toAddress.indexOf('<') > -1 ? toAddress.match(/<(.*?)>/i)[0]
.replace('<', '').replace('>', ''): toAddress) : '';
const uid = crypto.createHash('md5').update(
subject+
realFromAddress+
realToAddress+
momentDate
).digest('hex');
return uid;
} | function _getUid(from, to, date, subject) {
if(Array.isArray(date)) date = date[0];
if(Array.isArray(from)) from = from[0];
if(Array.isArray(to)) to = to[0];
if(Array.isArray(subject)) subject = subject[0];
to = typeof to !== "object" ? (to ? to.split(',')[0] : 'toUnknown') : to;
from = typeof from !== "object" ? (from ? from.split(',')[0] : 'fromUnknown') : from;
const momentDate = moment.utc(date).format("DD/MM/YYYY HH:mm:ss");
const fromAddress = typeof from === "object" ? from.address : from;
const toAddress = typeof to === "object" ? to.address : to;
const realFromAddress = fromAddress ? (fromAddress.indexOf('<') > -1 ? fromAddress.match(/<(.*?)>/i)[0]
.replace('<', '').replace('>', '') : fromAddress) : '';
const realToAddress = toAddress ? (toAddress.indexOf('<') > -1 ? toAddress.match(/<(.*?)>/i)[0]
.replace('<', '').replace('>', ''): toAddress) : '';
const uid = crypto.createHash('md5').update(
subject+
realFromAddress+
realToAddress+
momentDate
).digest('hex');
return uid;
} |
JavaScript | function _parseMessage(message) {
return new Promise((resolve, reject)=>{
const mailParser = new MailParser();
mailParser.on("end", parsedMessage=>{
parsedMessage['fromString'] = normalizeFromAndTo(parsedMessage.from);
parsedMessage['toString'] = normalizeFromAndTo(parsedMessage.to);
parsedMessage['ccString'] = normalizeFromAndTo(parsedMessage.cc);
var header = Imap.parseHeader(message);
parsedMessage['uid'] = _getUid(parsedMessage.from, parsedMessage.to, header.date, header.subject);
resolve(parsedMessage)
});
mailParser.write(message);
mailParser.end();
})
} | function _parseMessage(message) {
return new Promise((resolve, reject)=>{
const mailParser = new MailParser();
mailParser.on("end", parsedMessage=>{
parsedMessage['fromString'] = normalizeFromAndTo(parsedMessage.from);
parsedMessage['toString'] = normalizeFromAndTo(parsedMessage.to);
parsedMessage['ccString'] = normalizeFromAndTo(parsedMessage.cc);
var header = Imap.parseHeader(message);
parsedMessage['uid'] = _getUid(parsedMessage.from, parsedMessage.to, header.date, header.subject);
resolve(parsedMessage)
});
mailParser.write(message);
mailParser.end();
})
} |
JavaScript | _discoverSite( creds ) {
creds = creds || null;
if ( ! creds ) {
console.error( 'No credentials supplied to discover site.' );
return false;
}
// get the site
fetch( creds.url + '/wp-json/' )
.then( resp => {
resp.json()
.then( site => {
this.setState({
message: 'We found your site!'
});
// we got the site,
// let's authenticate the user
const auth = window.wpApiAuth( {
oauth_consumer_key: creds.key,
oauth_secret: creds.secret,
url: creds.api_url,
urls: site.authentication.oauth1,
singlepage: false,
});
// save the endpoint for use later
const endpoint = site.url
+ '/wp-json/wp/v2/premise_time_tracker';
// save the ptt object
const newPtt = {
creds,
site,
auth,
endpoint,
};
PTT.set( newPtt );
// save Cookies
PTT.setCookies();
// authenticate!
auth.authenticate( this._maybeAuthenticated.bind(this) );
});
});
} | _discoverSite( creds ) {
creds = creds || null;
if ( ! creds ) {
console.error( 'No credentials supplied to discover site.' );
return false;
}
// get the site
fetch( creds.url + '/wp-json/' )
.then( resp => {
resp.json()
.then( site => {
this.setState({
message: 'We found your site!'
});
// we got the site,
// let's authenticate the user
const auth = window.wpApiAuth( {
oauth_consumer_key: creds.key,
oauth_secret: creds.secret,
url: creds.api_url,
urls: site.authentication.oauth1,
singlepage: false,
});
// save the endpoint for use later
const endpoint = site.url
+ '/wp-json/wp/v2/premise_time_tracker';
// save the ptt object
const newPtt = {
creds,
site,
auth,
endpoint,
};
PTT.set( newPtt );
// save Cookies
PTT.setCookies();
// authenticate!
auth.authenticate( this._maybeAuthenticated.bind(this) );
});
});
} |
JavaScript | componentWillMount() {
// Fetch terms from server before component is rendered.
this._fetchTerms();
if ( this.props.taxonomyName === 'project' ) {
this._setUpdateProjectGlobalCallback();
}
} | componentWillMount() {
// Fetch terms from server before component is rendered.
this._fetchTerms();
if ( this.props.taxonomyName === 'project' ) {
this._setUpdateProjectGlobalCallback();
}
} |
JavaScript | loadTaxonomy( slug, callback ) {
slug = slug || null;
if ( ! slug ) return false;
fetch( PTT.get( 'endpoint' )
+ '_' + slug
+ '/'
+ this._defaultParams() )
.then( response => {
response.json()
.then( _terms => {
callback( _terms );
});
});
} | loadTaxonomy( slug, callback ) {
slug = slug || null;
if ( ! slug ) return false;
fetch( PTT.get( 'endpoint' )
+ '_' + slug
+ '/'
+ this._defaultParams() )
.then( response => {
response.json()
.then( _terms => {
callback( _terms );
});
});
} |
JavaScript | componentWillMount() {
// if we have a form id,
// then lets get the post
// before loading the form
if ( this.state.form.id ) {
this._buildForm();
}
} | componentWillMount() {
// if we have a form id,
// then lets get the post
// before loading the form
if ( this.state.form.id ) {
this._buildForm();
}
} |
JavaScript | _buildForm() {
this._startProcess('Building the form..');
// get the post and save it
TimerFetch.getPost( this.state.form.id )
.then( _p => {
let _foundClient, _foundProject;
if ( _p.premise_time_tracker_client.length ) {
const _clientList = TimerDB.get( 'client' );
_foundClient = _clientList.find( function( client ) {
return client.id === _p.premise_time_tracker_client[0]
});
}
if ( _p.premise_time_tracker_project.length ) {
const _projectList = TimerDB.get( 'project' );
_foundProject = _projectList.find( function( project ) {
return project.id === _p.premise_time_tracker_project[0]
});
}
// Build form before showing it.
const buildForm = Object.assign( this.state.form, {
title: _p.title.rendered,
content: _p.content.rendered,
client: (_foundClient) ? _foundClient.name : '',
project: (_foundProject) ? _foundProject.name : '',
} );
this.setState( {
post: _p,
form: buildForm,
});
this._startProcess('Loading clients & projects..');
this._loadClients();
this._loadProjects();
setTimeout(this._endProcess, 500);
} );
} | _buildForm() {
this._startProcess('Building the form..');
// get the post and save it
TimerFetch.getPost( this.state.form.id )
.then( _p => {
let _foundClient, _foundProject;
if ( _p.premise_time_tracker_client.length ) {
const _clientList = TimerDB.get( 'client' );
_foundClient = _clientList.find( function( client ) {
return client.id === _p.premise_time_tracker_client[0]
});
}
if ( _p.premise_time_tracker_project.length ) {
const _projectList = TimerDB.get( 'project' );
_foundProject = _projectList.find( function( project ) {
return project.id === _p.premise_time_tracker_project[0]
});
}
// Build form before showing it.
const buildForm = Object.assign( this.state.form, {
title: _p.title.rendered,
content: _p.content.rendered,
client: (_foundClient) ? _foundClient.name : '',
project: (_foundProject) ? _foundProject.name : '',
} );
this.setState( {
post: _p,
form: buildForm,
});
this._startProcess('Loading clients & projects..');
this._loadClients();
this._loadProjects();
setTimeout(this._endProcess, 500);
} );
} |
JavaScript | _loadClients() {
TimerFetch.getTaxonomy( 'client' ).then( premise_time_tracker_client => {
this.setState({
premise_time_tracker_client
});
});
} | _loadClients() {
TimerFetch.getTaxonomy( 'client' ).then( premise_time_tracker_client => {
this.setState({
premise_time_tracker_client
});
});
} |
JavaScript | _loadProjects() {
TimerFetch.getTaxonomy( 'project' ).then( premise_time_tracker_project => {
this.setState({
premise_time_tracker_project,
});
});
} | _loadProjects() {
TimerFetch.getTaxonomy( 'project' ).then( premise_time_tracker_project => {
this.setState({
premise_time_tracker_project,
});
});
} |
JavaScript | _checkTermId(taxonomy, term) {
let _t = this.state[taxonomy].find(function(_t){
return _t.name === term;
});
return ( typeof _t !== 'undefined' )
? _t.id
: false;
} | _checkTermId(taxonomy, term) {
let _t = this.state[taxonomy].find(function(_t){
return _t.name === term;
});
return ( typeof _t !== 'undefined' )
? _t.id
: false;
} |
JavaScript | render() {
return (
<svg viewBox="0 0 352 401" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink">
<g id="timer_svg" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
<path d="M121.606,0 C117.712,0 114.647,3.1064 114.647,6.9584 C114.647,10.8522 117.754,13.9972 121.606,13.9972 L139.001,13.9972 L139.001,52.672 C59.631,69.573 -2.84217094e-14,140.2213 -2.84217094e-14,224.5209 C-2.84217094e-14,321.4144 78.84,400.1733 175.734,400.1733 C272.627,400.1733 351.385,321.4144 351.385,224.5209 C351.385,190.5527 341.584,158.8881 324.848,131.9621 L346.127,110.6833 C347.41,109.3561 348.231,107.5295 348.231,105.6664 C348.231,103.8033 347.41,102.057 346.127,100.7313 L324.605,79.1288 C321.871,76.3943 317.388,76.3943 314.653,79.1288 L296.53,97.2523 C273.456,75.3385 244.574,59.5486 212.305,52.672 L212.305,13.9972 L229.78,13.9972 C233.675,13.9972 236.738,10.8544 236.738,6.9584 C236.738,3.1056 233.632,5.68434189e-14 229.78,5.68434189e-14 L212.305,5.68434189e-14 L139.001,5.68434189e-14 L121.606,5.68434189e-14 L121.606,0 Z M153.079,13.9972 L198.307,13.9972 L198.307,50.4064 C190.892,49.4547 183.316,48.7875 175.653,48.7875 C167.989,48.7875 160.495,49.4146 153.079,50.4064 L153.079,13.9972 Z M175.653,62.7854 C264.8,62.7854 337.308,135.3739 337.308,224.5209 C337.308,313.7097 264.8,386.1762 175.653,386.1762 C86.464,386.1762 13.917,313.7097 13.917,224.5209 C13.917,135.3746 86.464,62.7854 175.653,62.7854 Z M319.589,94.0158 L331.239,105.6664 L316.676,120.2306 C313.362,115.7566 309.926,111.5084 306.239,107.3658 L319.589,94.0158 Z M175.653,217.482 C173.862,217.482 172.084,218.2185 170.717,219.5858 C167.983,222.3202 167.983,226.7227 170.717,229.4568 L248.875,307.6141 C250.242,308.9814 251.989,309.634 253.81,309.634 C255.589,309.634 257.417,308.9376 258.827,307.6141 C261.561,304.8796 261.561,300.4771 258.827,297.7431 L180.588,219.5858 C179.222,218.2185 177.445,217.482 175.653,217.482 L175.653,217.482 Z" id="Shape" fillRule="nonzero"></path>
</g>
</svg>
);
} | render() {
return (
<svg viewBox="0 0 352 401" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink">
<g id="timer_svg" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
<path d="M121.606,0 C117.712,0 114.647,3.1064 114.647,6.9584 C114.647,10.8522 117.754,13.9972 121.606,13.9972 L139.001,13.9972 L139.001,52.672 C59.631,69.573 -2.84217094e-14,140.2213 -2.84217094e-14,224.5209 C-2.84217094e-14,321.4144 78.84,400.1733 175.734,400.1733 C272.627,400.1733 351.385,321.4144 351.385,224.5209 C351.385,190.5527 341.584,158.8881 324.848,131.9621 L346.127,110.6833 C347.41,109.3561 348.231,107.5295 348.231,105.6664 C348.231,103.8033 347.41,102.057 346.127,100.7313 L324.605,79.1288 C321.871,76.3943 317.388,76.3943 314.653,79.1288 L296.53,97.2523 C273.456,75.3385 244.574,59.5486 212.305,52.672 L212.305,13.9972 L229.78,13.9972 C233.675,13.9972 236.738,10.8544 236.738,6.9584 C236.738,3.1056 233.632,5.68434189e-14 229.78,5.68434189e-14 L212.305,5.68434189e-14 L139.001,5.68434189e-14 L121.606,5.68434189e-14 L121.606,0 Z M153.079,13.9972 L198.307,13.9972 L198.307,50.4064 C190.892,49.4547 183.316,48.7875 175.653,48.7875 C167.989,48.7875 160.495,49.4146 153.079,50.4064 L153.079,13.9972 Z M175.653,62.7854 C264.8,62.7854 337.308,135.3739 337.308,224.5209 C337.308,313.7097 264.8,386.1762 175.653,386.1762 C86.464,386.1762 13.917,313.7097 13.917,224.5209 C13.917,135.3746 86.464,62.7854 175.653,62.7854 Z M319.589,94.0158 L331.239,105.6664 L316.676,120.2306 C313.362,115.7566 309.926,111.5084 306.239,107.3658 L319.589,94.0158 Z M175.653,217.482 C173.862,217.482 172.084,218.2185 170.717,219.5858 C167.983,222.3202 167.983,226.7227 170.717,229.4568 L248.875,307.6141 C250.242,308.9814 251.989,309.634 253.81,309.634 C255.589,309.634 257.417,308.9376 258.827,307.6141 C261.561,304.8796 261.561,300.4771 258.827,297.7431 L180.588,219.5858 C179.222,218.2185 177.445,217.482 175.653,217.482 L175.653,217.482 Z" id="Shape" fillRule="nonzero"></path>
</g>
</svg>
);
} |
JavaScript | function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
} | function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
} |
JavaScript | function sendAll(requests, fnName, concurrency, callback) {
if (typeof concurrency === 'function') {
callback = concurrency;
concurrency = 1;
}
var q = queue(concurrency);
requests.forEach(function(req) {
q.defer(function(next) {
if (!req) return next();
req.on('complete', function(response) {
next(null, response);
}).send();
});
});
q.awaitAll(function(err, responses) {
if (err) return callback(err);
var errors = [];
var data = [];
var unprocessed = [];
responses.forEach(function(response) {
if (!response) response = { error: null, data: null };
errors.push(response.error);
data.push(response.data);
if (!response.data) return unprocessed.push(null);
var newParams = {
RequestItems: response.data.UnprocessedItems || response.data.UnprocessedKeys
};
if (newParams.RequestItems && !Object.keys(newParams.RequestItems).length)
return unprocessed.push(null);
unprocessed.push(newParams.RequestItems ? newParams : null);
});
unprocessed = unprocessed.map(function(params) {
if (params) return client[fnName].bind(client)(params);
else return null;
});
var unprocessedCount = unprocessed.filter(function(req) { return !!req; }).length;
if (unprocessedCount) unprocessed.sendAll = sendAll.bind(null, unprocessed, fnName);
var errorCount = errors.filter(function(err) { return !!err; }).length;
callback(
errorCount ? errors : null,
data,
unprocessedCount ? unprocessed : null
);
});
} | function sendAll(requests, fnName, concurrency, callback) {
if (typeof concurrency === 'function') {
callback = concurrency;
concurrency = 1;
}
var q = queue(concurrency);
requests.forEach(function(req) {
q.defer(function(next) {
if (!req) return next();
req.on('complete', function(response) {
next(null, response);
}).send();
});
});
q.awaitAll(function(err, responses) {
if (err) return callback(err);
var errors = [];
var data = [];
var unprocessed = [];
responses.forEach(function(response) {
if (!response) response = { error: null, data: null };
errors.push(response.error);
data.push(response.data);
if (!response.data) return unprocessed.push(null);
var newParams = {
RequestItems: response.data.UnprocessedItems || response.data.UnprocessedKeys
};
if (newParams.RequestItems && !Object.keys(newParams.RequestItems).length)
return unprocessed.push(null);
unprocessed.push(newParams.RequestItems ? newParams : null);
});
unprocessed = unprocessed.map(function(params) {
if (params) return client[fnName].bind(client)(params);
else return null;
});
var unprocessedCount = unprocessed.filter(function(req) { return !!req; }).length;
if (unprocessedCount) unprocessed.sendAll = sendAll.bind(null, unprocessed, fnName);
var errorCount = errors.filter(function(err) { return !!err; }).length;
callback(
errorCount ? errors : null,
data,
unprocessedCount ? unprocessed : null
);
});
} |
JavaScript | function sendCompletely(requests, fnName, maxRetries, concurrency, callback) {
if (typeof concurrency === 'function') {
callback = concurrency;
concurrency = 1;
}
function sendOne(req, callback) {
if (!req) return callback();
var result = { error: undefined, data: {} };
var retryCount = 0;
(function send(req) {
req.on('complete', function(response) {
if (!response.data) {
result.error = response.error;
return callback(null, result);
}
if (response.data.Responses) {
result.data.Responses = result.data.Responses || {};
Object.keys(response.data.Responses).forEach(function(table) {
result.data.Responses[table] = result.data.Responses[table] || [];
response.data.Responses[table].forEach(function(res) {
result.data.Responses[table].push(res);
});
});
}
if (response.data.ConsumedCapacity) {
result.data.ConsumedCapacity = result.data.ConsumedCapacity || {};
reduceCapacity(result.data.ConsumedCapacity, response.data.ConsumedCapacity);
}
var newParams = {
RequestItems: response.data.UnprocessedItems || response.data.UnprocessedKeys,
ReturnConsumedCapacity: req.params.ReturnConsumedCapacity
};
if (newParams.RequestItems && Object.keys(newParams.RequestItems).length && retryCount < maxRetries) {
var delay = 50 * Math.pow(2, retryCount - 1);
retryCount++;
return setTimeout(function() {
send(client[fnName](newParams));
}, delay);
}
if (response.data.UnprocessedKeys) {
result.data.UnprocessedKeys = result.data.UnprocessedKeys || {};
Object.keys(response.data.UnprocessedKeys).forEach(function(table) {
result.data.UnprocessedKeys[table] = result.data.UnprocessedKeys[table] || { Keys: [] };
response.data.UnprocessedKeys[table].Keys.forEach(function(res) {
result.data.UnprocessedKeys[table].Keys.push(res);
});
});
}
if (response.data.UnprocessedItems) {
result.data.UnprocessedItems = result.data.UnprocessedItems || {};
Object.keys(response.data.UnprocessedItems).forEach(function(table) {
result.data.UnprocessedItems[table] = result.data.UnprocessedItems[table] || [];
response.data.UnprocessedItems[table].forEach(function(res) {
result.data.UnprocessedItems[table].push(res);
});
});
}
callback(null, result);
}).send();
})(req);
}
var q = queue(concurrency);
requests.forEach(function(req) {
q.defer(sendOne, req);
});
q.awaitAll(function(_, responses) {
var err;
var result = { };
responses.forEach(function(res) {
if (res.error) err = res.error;
if (res.data.Responses) {
result.Responses = result.Responses || {};
Object.keys(res.data.Responses).forEach(function(table) {
result.Responses[table] = result.Responses[table] || [];
res.data.Responses[table].forEach(function(r) {
result.Responses[table].push(r);
});
});
}
if (res.data.UnprocessedItems) {
result.UnprocessedItems = result.UnprocessedItems || {};
Object.keys(res.data.UnprocessedItems).forEach(function(table) {
result.UnprocessedItems[table] = result.UnprocessedItems[table] || [];
res.data.UnprocessedItems[table].forEach(function(r) {
result.UnprocessedItems[table].push(r);
});
});
}
if (res.data.UnprocessedKeys) {
result.UnprocessedKeys = result.UnprocessedKeys || {};
Object.keys(res.data.UnprocessedKeys).forEach(function(table) {
result.UnprocessedKeys[table] = result.UnprocessedKeys[table] || { Keys: [] };
res.data.UnprocessedKeys[table].Keys.forEach(function(r) {
result.UnprocessedKeys[table].Keys.push(r);
});
});
}
if (res.data.ConsumedCapacity) {
result.ConsumedCapacity = result.ConsumedCapacity || {};
reduceCapacity(result.ConsumedCapacity, res.data.ConsumedCapacity);
}
});
callback(err, result);
});
} | function sendCompletely(requests, fnName, maxRetries, concurrency, callback) {
if (typeof concurrency === 'function') {
callback = concurrency;
concurrency = 1;
}
function sendOne(req, callback) {
if (!req) return callback();
var result = { error: undefined, data: {} };
var retryCount = 0;
(function send(req) {
req.on('complete', function(response) {
if (!response.data) {
result.error = response.error;
return callback(null, result);
}
if (response.data.Responses) {
result.data.Responses = result.data.Responses || {};
Object.keys(response.data.Responses).forEach(function(table) {
result.data.Responses[table] = result.data.Responses[table] || [];
response.data.Responses[table].forEach(function(res) {
result.data.Responses[table].push(res);
});
});
}
if (response.data.ConsumedCapacity) {
result.data.ConsumedCapacity = result.data.ConsumedCapacity || {};
reduceCapacity(result.data.ConsumedCapacity, response.data.ConsumedCapacity);
}
var newParams = {
RequestItems: response.data.UnprocessedItems || response.data.UnprocessedKeys,
ReturnConsumedCapacity: req.params.ReturnConsumedCapacity
};
if (newParams.RequestItems && Object.keys(newParams.RequestItems).length && retryCount < maxRetries) {
var delay = 50 * Math.pow(2, retryCount - 1);
retryCount++;
return setTimeout(function() {
send(client[fnName](newParams));
}, delay);
}
if (response.data.UnprocessedKeys) {
result.data.UnprocessedKeys = result.data.UnprocessedKeys || {};
Object.keys(response.data.UnprocessedKeys).forEach(function(table) {
result.data.UnprocessedKeys[table] = result.data.UnprocessedKeys[table] || { Keys: [] };
response.data.UnprocessedKeys[table].Keys.forEach(function(res) {
result.data.UnprocessedKeys[table].Keys.push(res);
});
});
}
if (response.data.UnprocessedItems) {
result.data.UnprocessedItems = result.data.UnprocessedItems || {};
Object.keys(response.data.UnprocessedItems).forEach(function(table) {
result.data.UnprocessedItems[table] = result.data.UnprocessedItems[table] || [];
response.data.UnprocessedItems[table].forEach(function(res) {
result.data.UnprocessedItems[table].push(res);
});
});
}
callback(null, result);
}).send();
})(req);
}
var q = queue(concurrency);
requests.forEach(function(req) {
q.defer(sendOne, req);
});
q.awaitAll(function(_, responses) {
var err;
var result = { };
responses.forEach(function(res) {
if (res.error) err = res.error;
if (res.data.Responses) {
result.Responses = result.Responses || {};
Object.keys(res.data.Responses).forEach(function(table) {
result.Responses[table] = result.Responses[table] || [];
res.data.Responses[table].forEach(function(r) {
result.Responses[table].push(r);
});
});
}
if (res.data.UnprocessedItems) {
result.UnprocessedItems = result.UnprocessedItems || {};
Object.keys(res.data.UnprocessedItems).forEach(function(table) {
result.UnprocessedItems[table] = result.UnprocessedItems[table] || [];
res.data.UnprocessedItems[table].forEach(function(r) {
result.UnprocessedItems[table].push(r);
});
});
}
if (res.data.UnprocessedKeys) {
result.UnprocessedKeys = result.UnprocessedKeys || {};
Object.keys(res.data.UnprocessedKeys).forEach(function(table) {
result.UnprocessedKeys[table] = result.UnprocessedKeys[table] || { Keys: [] };
res.data.UnprocessedKeys[table].Keys.forEach(function(r) {
result.UnprocessedKeys[table].Keys.push(r);
});
});
}
if (res.data.ConsumedCapacity) {
result.ConsumedCapacity = result.ConsumedCapacity || {};
reduceCapacity(result.ConsumedCapacity, res.data.ConsumedCapacity);
}
});
callback(err, result);
});
} |
JavaScript | function del(url) {
const request = new Request(baseUrl + url, {
method: 'DELETE'
});
return fetch(request).then(onSuccess, onError);
} | function del(url) {
const request = new Request(baseUrl + url, {
method: 'DELETE'
});
return fetch(request).then(onSuccess, onError);
} |
JavaScript | function initListeners(hostOrigin, { onNcsItemRequest, onNcsAppInfo }) {
window.addEventListener('message', ({ data, origin }) => {
if (event.origin !== hostOrigin) {
console.log(`Received a message with incorrect origin: "${origin}"`)
return
}
try {
const obj = xmlStringToObject(data)
const messageType = getObjectType(obj)
switch (messageType) {
case objectTypes.MOS_NCS_ITEM_REQUEST:
onNcsItemRequest()
break
case objectTypes.MOS_NCS_APP_INFO:
onNcsAppInfo(obj)
break
}
} catch (error) {
console.log('Discarded incoming message (unable to parse):', data)
}
})
} | function initListeners(hostOrigin, { onNcsItemRequest, onNcsAppInfo }) {
window.addEventListener('message', ({ data, origin }) => {
if (event.origin !== hostOrigin) {
console.log(`Received a message with incorrect origin: "${origin}"`)
return
}
try {
const obj = xmlStringToObject(data)
const messageType = getObjectType(obj)
switch (messageType) {
case objectTypes.MOS_NCS_ITEM_REQUEST:
onNcsItemRequest()
break
case objectTypes.MOS_NCS_APP_INFO:
onNcsAppInfo(obj)
break
}
} catch (error) {
console.log('Discarded incoming message (unable to parse):', data)
}
})
} |
JavaScript | function signalReadyToHost() {
if (window.parent && window.parent !== window) {
sendXmlData(window.parent, ncsReqAppInfo())
}
} | function signalReadyToHost() {
if (window.parent && window.parent !== window) {
sendXmlData(window.parent, ncsReqAppInfo())
}
} |
JavaScript | function xmlStringToObject(xmlString) {
const domparser = new window.DOMParser()
const doc = domparser.parseFromString(xmlString, 'text/xml')
return xmlToObject(doc)
} | function xmlStringToObject(xmlString) {
const domparser = new window.DOMParser()
const doc = domparser.parseFromString(xmlString, 'text/xml')
return xmlToObject(doc)
} |
JavaScript | function xmlToObject(doc) {
if (doc.firstChild) {
return {
[doc.firstChild.nodeName]: nodeToObj(doc.firstChild)
}
}
return {}
} | function xmlToObject(doc) {
if (doc.firstChild) {
return {
[doc.firstChild.nodeName]: nodeToObj(doc.firstChild)
}
}
return {}
} |
JavaScript | searchClip(criteria) {
const { path, params } = REQUESTS.CLIP_SEARCH
const url = new URL(this.host)
url.pathname = url.pathname + path
const queryParamValue = buildQueryParam(
Object.assign({}, criteria, {
poolId: this.poolId
})
)
url.searchParams.append(params.QUERY, queryParamValue)
return fetch(url.href)
.then((response) => {
if (response.ok) {
return response.text()
} else
throw new Error(
`Unable to fetch results: ${response.status} - ${response.statusText}`
)
})
.then(xmlStringToObject)
.then((results) => {
if (!results?.feed) {
return { clips: [] }
}
const { entry } = results.feed
const clips = Array.isArray(entry) ? [...entry] : [entry]
return { clips: clips.map((clip) => mapClipData(clip, this.host)) }
})
} | searchClip(criteria) {
const { path, params } = REQUESTS.CLIP_SEARCH
const url = new URL(this.host)
url.pathname = url.pathname + path
const queryParamValue = buildQueryParam(
Object.assign({}, criteria, {
poolId: this.poolId
})
)
url.searchParams.append(params.QUERY, queryParamValue)
return fetch(url.href)
.then((response) => {
if (response.ok) {
return response.text()
} else
throw new Error(
`Unable to fetch results: ${response.status} - ${response.statusText}`
)
})
.then(xmlStringToObject)
.then((results) => {
if (!results?.feed) {
return { clips: [] }
}
const { entry } = results.feed
const clips = Array.isArray(entry) ? [...entry] : [entry]
return { clips: clips.map((clip) => mapClipData(clip, this.host)) }
})
} |
JavaScript | function draw(id) {
const cell = $('#' + id);
if (game.currentPlayer === USER) {
cell.html(game.user[HTML_INDEX]);
cell.removeAttr('onclick');
update(id, game.user[SYMBOL_INDEX]);
switchPlayer(USER)
} else if (game.currentPlayer === USER_TWO) {
cell.html(game.user_two[HTML_INDEX]);
cell.removeAttr('onclick');
update(id, game.user_two[SYMBOL_INDEX]);
switchPlayer(USER_TWO);
} else if (game.currentPlayer === COMPUTER) {
cell.html(game.computer[HTML_INDEX]);
cell.removeAttr('onclick');
update(id, game.computer[SYMBOL_INDEX]);
switchPlayer(COMPUTER)
}
checkWin()
} | function draw(id) {
const cell = $('#' + id);
if (game.currentPlayer === USER) {
cell.html(game.user[HTML_INDEX]);
cell.removeAttr('onclick');
update(id, game.user[SYMBOL_INDEX]);
switchPlayer(USER)
} else if (game.currentPlayer === USER_TWO) {
cell.html(game.user_two[HTML_INDEX]);
cell.removeAttr('onclick');
update(id, game.user_two[SYMBOL_INDEX]);
switchPlayer(USER_TWO);
} else if (game.currentPlayer === COMPUTER) {
cell.html(game.computer[HTML_INDEX]);
cell.removeAttr('onclick');
update(id, game.computer[SYMBOL_INDEX]);
switchPlayer(COMPUTER)
}
checkWin()
} |
JavaScript | function verifyBoard() {
// clear any error before assigning new ones
clearError();
// call back-end to see the state of the board
$(() => {
$.getJSON("/games/sudoku/verify", {}, (data) => {
// get the data passed in from back-end
const result = data['result'];
const id_list = data['id_list'];
// if result is true, meaning the game is won, call end game function
if (result === true) {
endGame()
}
// if result is false, meaning the board isn't complete, do nothing
else if (result === false) {
}
// else, meaning there are errors on board, highlight the wrong number
else {
// loop through all the ids of the wrong number
for (let i = 0; i < id_list.length; i++) {
const cell = $('p', '#' + id_list[i]);
// remove the base color
cell.removeClass('not-pencil');
try {
// if the move was made by the player, remove player move color too
if (cell.attr('class').includes('player')) {
cell.removeClass('player');
}
} catch (TypeError) { // silence type error
}
// add error color to the numbers
cell.addClass('error');
}
}
});
})
} | function verifyBoard() {
// clear any error before assigning new ones
clearError();
// call back-end to see the state of the board
$(() => {
$.getJSON("/games/sudoku/verify", {}, (data) => {
// get the data passed in from back-end
const result = data['result'];
const id_list = data['id_list'];
// if result is true, meaning the game is won, call end game function
if (result === true) {
endGame()
}
// if result is false, meaning the board isn't complete, do nothing
else if (result === false) {
}
// else, meaning there are errors on board, highlight the wrong number
else {
// loop through all the ids of the wrong number
for (let i = 0; i < id_list.length; i++) {
const cell = $('p', '#' + id_list[i]);
// remove the base color
cell.removeClass('not-pencil');
try {
// if the move was made by the player, remove player move color too
if (cell.attr('class').includes('player')) {
cell.removeClass('player');
}
} catch (TypeError) { // silence type error
}
// add error color to the numbers
cell.addClass('error');
}
}
});
})
} |
JavaScript | function reset() {
// remove color for current cell
$('#' + game.currentCell).removeClass('selected');
// set game variables to original state
game.currentCell = 'None';
game.pencil = false;
game.undo = 0;
// update information panel
updateInfo();
// loop through all cells and clear the content in it
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= 9; j++) {
// get id and select the cell
const id = ref[i] + '-' + ref[j];
// clear board content and remove all associated classes
$('#' + id).html('');
}
}
} | function reset() {
// remove color for current cell
$('#' + game.currentCell).removeClass('selected');
// set game variables to original state
game.currentCell = 'None';
game.pencil = false;
game.undo = 0;
// update information panel
updateInfo();
// loop through all cells and clear the content in it
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= 9; j++) {
// get id and select the cell
const id = ref[i] + '-' + ref[j];
// clear board content and remove all associated classes
$('#' + id).html('');
}
}
} |
JavaScript | function start() {
// assign event handlers to side-bar number pad and game board cells
$('.num').click(setNum);
$('.game-field').click(selectCell);
// calls back-end to setup sudoku board and render the puzzle
$.getJSON("/games/sudoku/setup", {}, (data) => {
renderBoard(data['board']);
});
} | function start() {
// assign event handlers to side-bar number pad and game board cells
$('.num').click(setNum);
$('.game-field').click(selectCell);
// calls back-end to setup sudoku board and render the puzzle
$.getJSON("/games/sudoku/setup", {}, (data) => {
renderBoard(data['board']);
});
} |
JavaScript | function clearError() {
// loop through all cells to remove errors assigned to cells
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= 9; j++) {
// select the cell
const id = ref[i] + '-' + ref[j];
const cell = $('p', '#' + id);
// remove error color and add base non-pencil color
cell.removeClass('error');
cell.addClass('not-pencil');
// add player move color is the move made by player
try {
if (cell.attr('class').includes('player-con')) {
cell.addClass('player')
}
} catch (TypeError) { // silence TypeError
}
}
}
} | function clearError() {
// loop through all cells to remove errors assigned to cells
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= 9; j++) {
// select the cell
const id = ref[i] + '-' + ref[j];
const cell = $('p', '#' + id);
// remove error color and add base non-pencil color
cell.removeClass('error');
cell.addClass('not-pencil');
// add player move color is the move made by player
try {
if (cell.attr('class').includes('player-con')) {
cell.addClass('player')
}
} catch (TypeError) { // silence TypeError
}
}
}
} |
JavaScript | function renderBoard(board) {
// loop through every element in the given 2D-array board
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
// get value from the given board on position (i, j)
const id = ref[i + 1] + '-' + ref[j + 1];
const val = board[i][j];
// if value on board isn't 0, then draws the correct number onto the web page
if (val !== 0) {
const cell = $('#' + id);
cell.html(num_ref[ref[val]][0]);
// remove onclick attribute to prevent user from changing base puzzle
cell.removeAttr('onclick');
// call function to add number in back-end board
// addMove(id, val)
}
}
}
} | function renderBoard(board) {
// loop through every element in the given 2D-array board
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
// get value from the given board on position (i, j)
const id = ref[i + 1] + '-' + ref[j + 1];
const val = board[i][j];
// if value on board isn't 0, then draws the correct number onto the web page
if (val !== 0) {
const cell = $('#' + id);
cell.html(num_ref[ref[val]][0]);
// remove onclick attribute to prevent user from changing base puzzle
cell.removeAttr('onclick');
// call function to add number in back-end board
// addMove(id, val)
}
}
}
} |
JavaScript | function selectCell(e) {
if (e.target.id !== "") {
// remove the highlighting on that current selected cell
if (game.currentCell !== 'None') {
$('#' + game.currentCell).removeClass('selected');
}
// highlight target cell and save it to game variable
$('#' + e.target.id).addClass('selected');
game.currentCell = e.target.id;
}
} | function selectCell(e) {
if (e.target.id !== "") {
// remove the highlighting on that current selected cell
if (game.currentCell !== 'None') {
$('#' + game.currentCell).removeClass('selected');
}
// highlight target cell and save it to game variable
$('#' + e.target.id).addClass('selected');
game.currentCell = e.target.id;
}
} |
JavaScript | function undo(id, num, pencil) {
// if id passed in isn't empty
if (id !== false) {
// update info pad
game.undo++;
updateInfo();
// if number passed in isn't 0
if (num !== 0) {
// if pencil passed in is true, then draw number in cell with pencil
if (pencil) {
$('#' + id).html(num_ref[ref[num]][1]);
}
// if pencil passed in is false, then draw number in cell without pencil
else {
$('#' + id).html(num_ref[ref[num]][0]);
$('p', '#' + id).addClass('player');
}
}
// if number passed in is 0, then empty the cell
else {
$('#' + id).html('');
}
// calls function to verify the board
verifyBoard();
}
} | function undo(id, num, pencil) {
// if id passed in isn't empty
if (id !== false) {
// update info pad
game.undo++;
updateInfo();
// if number passed in isn't 0
if (num !== 0) {
// if pencil passed in is true, then draw number in cell with pencil
if (pencil) {
$('#' + id).html(num_ref[ref[num]][1]);
}
// if pencil passed in is false, then draw number in cell without pencil
else {
$('#' + id).html(num_ref[ref[num]][0]);
$('p', '#' + id).addClass('player');
}
}
// if number passed in is 0, then empty the cell
else {
$('#' + id).html('');
}
// calls function to verify the board
verifyBoard();
}
} |
JavaScript | function updateInfo() {
$('#numUndo').text("Undo: " + game.undo);
if (game.pencil) {
$('#pencilOn').text("Pencil: On");
} else {
$('#pencilOn').text("Pencil: Off");
}
} | function updateInfo() {
$('#numUndo').text("Undo: " + game.undo);
if (game.pencil) {
$('#pencilOn').text("Pencil: On");
} else {
$('#pencilOn').text("Pencil: Off");
}
} |
JavaScript | function saveMove(id, num, pencil) {
$.get("/games/sudoku/save_move", {
id: id,
num: num,
pencil: pencil
});
} | function saveMove(id, num, pencil) {
$.get("/games/sudoku/save_move", {
id: id,
num: num,
pencil: pencil
});
} |
JavaScript | function addMove(id, num) {
$.get("/games/sudoku/add_move", {
id: id,
num: num
});
} | function addMove(id, num) {
$.get("/games/sudoku/add_move", {
id: id,
num: num
});
} |
JavaScript | function HttpError(status, message) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'HttpError';
this.status = status;
this.message = message;
} | function HttpError(status, message) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'HttpError';
this.status = status;
this.message = message;
} |
JavaScript | async function calculateTtl (ttl = TX_TTL, relative = true) {
if (ttl === 0) return 0
if (ttl < 0) throw new Error('ttl must be greater than 0')
if (relative) {
const { height } = await this.api.getCurrentKeyBlock()
return +(height) + ttl
}
return ttl
} | async function calculateTtl (ttl = TX_TTL, relative = true) {
if (ttl === 0) return 0
if (ttl < 0) throw new Error('ttl must be greater than 0')
if (relative) {
const { height } = await this.api.getCurrentKeyBlock()
return +(height) + ttl
}
return ttl
} |
JavaScript | async function prepareTxParams (txType, { senderId, nonce: n, ttl: t, fee: f, gas, absoluteTtl, vsn, strategy }) {
n = n || (await this.api.getAccountNextNonce(senderId, { strategy }).catch(e => ({ nextNonce: 1 }))).nextNonce
const ttl = await calculateTtl.call(this, t, !absoluteTtl)
const fee = calculateFee(f, txType, { showWarning: this.showWarning, gas, params: R.merge(R.last(arguments), { nonce: n, ttl }), vsn })
return { fee, ttl, nonce: n }
} | async function prepareTxParams (txType, { senderId, nonce: n, ttl: t, fee: f, gas, absoluteTtl, vsn, strategy }) {
n = n || (await this.api.getAccountNextNonce(senderId, { strategy }).catch(e => ({ nextNonce: 1 }))).nextNonce
const ttl = await calculateTtl.call(this, t, !absoluteTtl)
const fee = calculateFee(f, txType, { showWarning: this.showWarning, gas, params: R.merge(R.last(arguments), { nonce: n, ttl }), vsn })
return { fee, ttl, nonce: n }
} |
JavaScript | function prepareSchema (type, bindings) {
const { t, generic } = readType(type, bindings)
switch (t) {
case SOPHIA_TYPES.int:
return Joi.number().unsafe()
case SOPHIA_TYPES.variant:
return Joi.alternatives().try(
Joi.string().valid(
...generic.reduce((acc, el) => {
const [[t, g]] = Object.entries(el)
if (!g || !g.length) acc.push(t)
return acc
}, [])
),
Joi.object(generic
.reduce(
(acc, el) => {
const variant = Object.keys(el)[0]
return { ...acc, [variant]: Joi.array() }
},
{})
).or(...generic.map(e => Object.keys(e)[0]))
)
case SOPHIA_TYPES.ChainTtl:
return Joi.string()
case SOPHIA_TYPES.string:
return Joi.string()
case SOPHIA_TYPES.address:
return Joi.string().regex(/^(ak_|ct_|ok_|oq_)/)
case SOPHIA_TYPES.bool:
return Joi.boolean()
case SOPHIA_TYPES.list:
return Joi.array().items(prepareSchema(generic, bindings))
case SOPHIA_TYPES.tuple:
return Joi.array().ordered(...generic.map(type => prepareSchema(type, bindings).required())).label('Tuple argument')
case SOPHIA_TYPES.record:
return Joi.object(
generic.reduce((acc, { name, type }) => ({ ...acc, [name]: prepareSchema(type, bindings) }), {})
)
case SOPHIA_TYPES.hash:
return JoiBinary.binary().encoding('hex').length(32)
case SOPHIA_TYPES.bytes:
return JoiBinary.binary().encoding('hex').length(generic)
case SOPHIA_TYPES.signature:
return JoiBinary.binary().encoding('hex').length(64)
case SOPHIA_TYPES.option:
return prepareSchema(generic, bindings).optional()
// @Todo Need to transform Map to Array of arrays before validating it
// case SOPHIA_TYPES.map:
// return Joi.array().items(Joi.array().ordered(...generic.map(type => prepareSchema(type))))
default:
return Joi.any()
}
} | function prepareSchema (type, bindings) {
const { t, generic } = readType(type, bindings)
switch (t) {
case SOPHIA_TYPES.int:
return Joi.number().unsafe()
case SOPHIA_TYPES.variant:
return Joi.alternatives().try(
Joi.string().valid(
...generic.reduce((acc, el) => {
const [[t, g]] = Object.entries(el)
if (!g || !g.length) acc.push(t)
return acc
}, [])
),
Joi.object(generic
.reduce(
(acc, el) => {
const variant = Object.keys(el)[0]
return { ...acc, [variant]: Joi.array() }
},
{})
).or(...generic.map(e => Object.keys(e)[0]))
)
case SOPHIA_TYPES.ChainTtl:
return Joi.string()
case SOPHIA_TYPES.string:
return Joi.string()
case SOPHIA_TYPES.address:
return Joi.string().regex(/^(ak_|ct_|ok_|oq_)/)
case SOPHIA_TYPES.bool:
return Joi.boolean()
case SOPHIA_TYPES.list:
return Joi.array().items(prepareSchema(generic, bindings))
case SOPHIA_TYPES.tuple:
return Joi.array().ordered(...generic.map(type => prepareSchema(type, bindings).required())).label('Tuple argument')
case SOPHIA_TYPES.record:
return Joi.object(
generic.reduce((acc, { name, type }) => ({ ...acc, [name]: prepareSchema(type, bindings) }), {})
)
case SOPHIA_TYPES.hash:
return JoiBinary.binary().encoding('hex').length(32)
case SOPHIA_TYPES.bytes:
return JoiBinary.binary().encoding('hex').length(generic)
case SOPHIA_TYPES.signature:
return JoiBinary.binary().encoding('hex').length(64)
case SOPHIA_TYPES.option:
return prepareSchema(generic, bindings).optional()
// @Todo Need to transform Map to Array of arrays before validating it
// case SOPHIA_TYPES.map:
// return Joi.array().items(Joi.array().ordered(...generic.map(type => prepareSchema(type))))
default:
return Joi.any()
}
} |
JavaScript | function validateArguments (aci, params) {
const validationSchema = Joi.array().ordered(
...aci.arguments
.map(({ type }, i) => prepareSchema(type, aci.bindings).label(`[${params[i]}]`))
).sparse(true).label('Argument')
const { error } = validationSchema.validate(params, { abortEarly: false })
if (error) {
throw error
}
} | function validateArguments (aci, params) {
const validationSchema = Joi.array().ordered(
...aci.arguments
.map(({ type }, i) => prepareSchema(type, aci.bindings).label(`[${params[i]}]`))
).sparse(true).label('Argument')
const { error } = validationSchema.validate(params, { abortEarly: false })
if (error) {
throw error
}
} |
JavaScript | async function recover (password, keyObject) {
validateKeyObj(keyObject)
const nonce = Uint8Array.from(str2buf(keyObject.crypto.cipher_params.nonce))
const salt = Uint8Array.from(str2buf(keyObject.crypto.kdf_params.salt))
const kdfParams = keyObject.crypto.kdf_params
const kdf = keyObject.crypto.kdf
const key = await decrypt(
Uint8Array.from(str2buf(keyObject.crypto.ciphertext)),
await deriveKey(password, salt, { kdf, kdf_params: kdfParams }),
nonce,
keyObject.crypto.symmetric_alg
)
if (!key) throw new Error('Invalid password')
if (Buffer.from(key).length === 64) return Buffer.from(key).toString('hex')
return Buffer.from(key).toString('utf-8')
} | async function recover (password, keyObject) {
validateKeyObj(keyObject)
const nonce = Uint8Array.from(str2buf(keyObject.crypto.cipher_params.nonce))
const salt = Uint8Array.from(str2buf(keyObject.crypto.kdf_params.salt))
const kdfParams = keyObject.crypto.kdf_params
const kdf = keyObject.crypto.kdf
const key = await decrypt(
Uint8Array.from(str2buf(keyObject.crypto.ciphertext)),
await deriveKey(password, salt, { kdf, kdf_params: kdfParams }),
nonce,
keyObject.crypto.symmetric_alg
)
if (!key) throw new Error('Invalid password')
if (Buffer.from(key).length === 64) return Buffer.from(key).toString('hex')
return Buffer.from(key).toString('utf-8')
} |
JavaScript | _resolveAccount (account) {
if (account === null) {
throw new Error('No account or wallet configured')
} else {
switch (typeof account) {
case 'string':
decode(account, 'ak')
if (!this.accounts[account]) throw new Error(`Account for ${account} not available`)
return this.accounts[account]
case 'object':
return isAccountBase(account) ? account : MemoryAccount({ keypair: account })
default:
throw new Error(`Unknown account type: ${typeof account} (account: ${account})`)
}
}
} | _resolveAccount (account) {
if (account === null) {
throw new Error('No account or wallet configured')
} else {
switch (typeof account) {
case 'string':
decode(account, 'ak')
if (!this.accounts[account]) throw new Error(`Account for ${account} not available`)
return this.accounts[account]
case 'object':
return isAccountBase(account) ? account : MemoryAccount({ keypair: account })
default:
throw new Error(`Unknown account type: ${typeof account} (account: ${account})`)
}
}
} |
JavaScript | function update (from, to, amount, sign, metadata) {
return new Promise((resolve, reject) => {
enqueueAction(
this,
(channel, state) => state.handler === handlers.channelOpen,
(channel, state) => {
send(channel, {
jsonrpc: '2.0',
method: 'channels.update.new',
params: { from, to, amount, meta: metadata }
})
return {
handler: handlers.awaitingOffChainTx,
state: {
resolve,
reject,
sign
}
}
}
)
})
} | function update (from, to, amount, sign, metadata) {
return new Promise((resolve, reject) => {
enqueueAction(
this,
(channel, state) => state.handler === handlers.channelOpen,
(channel, state) => {
send(channel, {
jsonrpc: '2.0',
method: 'channels.update.new',
params: { from, to, amount, meta: metadata }
})
return {
handler: handlers.awaitingOffChainTx,
state: {
resolve,
reject,
sign
}
}
}
)
})
} |
JavaScript | async function balances (accounts) {
return R.reduce((acc, item) => ({
...acc,
[item.account]: item.balance
}), {}, await call(this, 'channels.get.balances', { accounts }))
} | async function balances (accounts) {
return R.reduce((acc, item) => ({
...acc,
[item.account]: item.balance
}), {}, await call(this, 'channels.get.balances', { accounts }))
} |
JavaScript | function leave () {
return new Promise((resolve, reject) => {
enqueueAction(
this,
(channel, state) => state.handler === handlers.channelOpen,
(channel, state) => {
send(channel, { jsonrpc: '2.0', method: 'channels.leave', params: {} })
return {
handler: handlers.awaitingLeave,
state: { resolve, reject }
}
})
})
} | function leave () {
return new Promise((resolve, reject) => {
enqueueAction(
this,
(channel, state) => state.handler === handlers.channelOpen,
(channel, state) => {
send(channel, { jsonrpc: '2.0', method: 'channels.leave', params: {} })
return {
handler: handlers.awaitingLeave,
state: { resolve, reject }
}
})
})
} |
JavaScript | function withdraw (amount, sign, { onOnChainTx, onOwnWithdrawLocked, onWithdrawLocked } = {}) {
return new Promise((resolve, reject) => {
enqueueAction(
this,
(channel, state) => state.handler === handlers.channelOpen,
(channel, state) => {
send(channel, { jsonrpc: '2.0', method: 'channels.withdraw', params: { amount } })
return {
handler: handlers.awaitingWithdrawTx,
state: {
sign,
resolve,
reject,
onOnChainTx,
onOwnWithdrawLocked,
onWithdrawLocked
}
}
}
)
})
} | function withdraw (amount, sign, { onOnChainTx, onOwnWithdrawLocked, onWithdrawLocked } = {}) {
return new Promise((resolve, reject) => {
enqueueAction(
this,
(channel, state) => state.handler === handlers.channelOpen,
(channel, state) => {
send(channel, { jsonrpc: '2.0', method: 'channels.withdraw', params: { amount } })
return {
handler: handlers.awaitingWithdrawTx,
state: {
sign,
resolve,
reject,
onOnChainTx,
onOwnWithdrawLocked,
onWithdrawLocked
}
}
}
)
})
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.