language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function ce(elementName, className, child) {
const el = document.createElement(elementName);
className && (el.className = className);
child && ac(el, child);
return el;
} | function ce(elementName, className, child) {
const el = document.createElement(elementName);
className && (el.className = className);
child && ac(el, child);
return el;
} |
JavaScript | function multilineStringToNodes(input) {
const textNodes = input.split('\n').map((s) => ctn(s));
let returnedNodes = [];
textNodes.forEach((e) => {
returnedNodes.push(e);
returnedNodes.push(document.createElement('br'));
})
return returnedNodes.slice(0,-1);
} | function multilineStringToNodes(input) {
const textNodes = input.split('\n').map((s) => ctn(s));
let returnedNodes = [];
textNodes.forEach((e) => {
returnedNodes.push(e);
returnedNodes.push(document.createElement('br'));
})
return returnedNodes.slice(0,-1);
} |
JavaScript | function initMap(data, filters) {
const element = document.getElementById('map');
if (!element) {
return;
}
$(".map-container").show();
map = new google.maps.Map(element);
secondaryCluster = new MarkerClusterer(map, [], {
clusterClass: 'secondarycluster',
imagePath: 'images/markercluster/m',
minimumClusterSize: 5,
zIndex: 1,
});
primaryCluster = new MarkerClusterer(map, [],
{
imagePath: 'images/markercluster/m',
minimumClusterSize: 5,
zIndex: 2
});
primaryCluster.addListener('click', function(e) {
sendEvent('map', 'click', 'primaryCluster');
});
secondaryCluster.addListener('click', function(e) {
sendEvent('map', 'click', 'secondaryCluster');
});
showMarkers(data, filters);
// Initialize autosuggest/search field above the map.
initMapSearch(data, filters);
loadOtherCountries();
} | function initMap(data, filters) {
const element = document.getElementById('map');
if (!element) {
return;
}
$(".map-container").show();
map = new google.maps.Map(element);
secondaryCluster = new MarkerClusterer(map, [], {
clusterClass: 'secondarycluster',
imagePath: 'images/markercluster/m',
minimumClusterSize: 5,
zIndex: 1,
});
primaryCluster = new MarkerClusterer(map, [],
{
imagePath: 'images/markercluster/m',
minimumClusterSize: 5,
zIndex: 2
});
primaryCluster.addListener('click', function(e) {
sendEvent('map', 'click', 'primaryCluster');
});
secondaryCluster.addListener('click', function(e) {
sendEvent('map', 'click', 'secondaryCluster');
});
showMarkers(data, filters);
// Initialize autosuggest/search field above the map.
initMapSearch(data, filters);
loadOtherCountries();
} |
JavaScript | function initMapSearch(data, filters) {
// If disabled, hide the search fields and don't bother attaching any functionality to them.
if (!showMapSearch) {
$('.map-search-wrap').hide();
return;
}
// Search element (jquery + html element for autocompleter)
const $search = $('#map-search'),
searchEl = $search[0];
// Initialize the map search autocompleter.
autocomplete = new google.maps.places.Autocomplete(
searchEl, { types: ['geocode'] }
);
// Avoid paying for data that you don't need by restricting the set of place fields that are returned to just the
// address components.
autocomplete.setFields(['geometry']);
// When the user selects an address from the drop-down, populate the address fields in the form.
autocomplete.addListener('place_changed', () => {
let place = autocomplete.getPlace();
if (place.geometry) {
// Get the location object that we can map.setCenter() on
sendEvent("map","autocomplete", $search.val());
let viewport = place.geometry.viewport;
if (viewport) {
fitMapToMarkersNearBounds(viewport);
} else {
sendEvent("map","autocomplete-fail", $search.val());
console.warn('Location data not found in place geometry (place.geometry.location).')
}
} else {
console.warn('No geometry found, attempting geocode...');
sendEvent("map","search", $search.val());
// Attempt a geocode of the direct user input instead.
const geocoder = new google.maps.Geocoder();
const searchText = $search.val();
geocoder.geocode({ address: searchText }, (results, status) => {
// Ensure we got a valid response with an array of at least one result.
if (status === 'OK' && Array.isArray(results) && results.length > 0) {
let viewport = results[0].geometry.viewport;
fitMapToMarkersNearBounds(viewport);
} else {
console.warn('Geocode failed: ' + status);
sendEvent("map","geocode-fail", $search.val());
}
});
}
});
// Setup event listeners for map action links.
$('#use-location').on('click', (e) => {
e.preventDefault();
sendEvent("map","center","user-location");
centerMapToMarkersNearUser();
});
$('#reset-map').on('click', (e) => {
e.preventDefault();
resetMap(data, filters);
$search.val('');
sendEvent("map","reset","default-location");
});
} | function initMapSearch(data, filters) {
// If disabled, hide the search fields and don't bother attaching any functionality to them.
if (!showMapSearch) {
$('.map-search-wrap').hide();
return;
}
// Search element (jquery + html element for autocompleter)
const $search = $('#map-search'),
searchEl = $search[0];
// Initialize the map search autocompleter.
autocomplete = new google.maps.places.Autocomplete(
searchEl, { types: ['geocode'] }
);
// Avoid paying for data that you don't need by restricting the set of place fields that are returned to just the
// address components.
autocomplete.setFields(['geometry']);
// When the user selects an address from the drop-down, populate the address fields in the form.
autocomplete.addListener('place_changed', () => {
let place = autocomplete.getPlace();
if (place.geometry) {
// Get the location object that we can map.setCenter() on
sendEvent("map","autocomplete", $search.val());
let viewport = place.geometry.viewport;
if (viewport) {
fitMapToMarkersNearBounds(viewport);
} else {
sendEvent("map","autocomplete-fail", $search.val());
console.warn('Location data not found in place geometry (place.geometry.location).')
}
} else {
console.warn('No geometry found, attempting geocode...');
sendEvent("map","search", $search.val());
// Attempt a geocode of the direct user input instead.
const geocoder = new google.maps.Geocoder();
const searchText = $search.val();
geocoder.geocode({ address: searchText }, (results, status) => {
// Ensure we got a valid response with an array of at least one result.
if (status === 'OK' && Array.isArray(results) && results.length > 0) {
let viewport = results[0].geometry.viewport;
fitMapToMarkersNearBounds(viewport);
} else {
console.warn('Geocode failed: ' + status);
sendEvent("map","geocode-fail", $search.val());
}
});
}
});
// Setup event listeners for map action links.
$('#use-location').on('click', (e) => {
e.preventDefault();
sendEvent("map","center","user-location");
centerMapToMarkersNearUser();
});
$('#reset-map').on('click', (e) => {
e.preventDefault();
resetMap(data, filters);
$search.val('');
sendEvent("map","reset","default-location");
});
} |
JavaScript | function centerMapToMarkersNearUser() {
// First check to see if the user will accept getting their location, if not, silently return
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
// Use navigator provided lat/long coords to center map now.
centerMapToMarkersNearCoords(position.coords.latitude, position.coords.longitude);
}, (err) => {
// Hide the "User my location" link since we know that will not work.
$('#use-location').hide();
}, {
maximumAge: Infinity,
timeout: 10000
});
}
} | function centerMapToMarkersNearUser() {
// First check to see if the user will accept getting their location, if not, silently return
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
// Use navigator provided lat/long coords to center map now.
centerMapToMarkersNearCoords(position.coords.latitude, position.coords.longitude);
}, (err) => {
// Hide the "User my location" link since we know that will not work.
$('#use-location').hide();
}, {
maximumAge: Infinity,
timeout: 10000
});
}
} |
JavaScript | function fitMapToMarkersNearBounds(bounds) {
// get center of bounding box and use it to sort markers by distance
let center = bounds.getCenter();
const markersByDistance = getMarkersByDistanceFrom(center.lat(), center.lng());
// extend bounds to fit closest three markers
[0,1,2].forEach((i) => {
const marker = markersByDistance[i];
if (marker) {
bounds.extend(marker.position);
}
});
map.fitBounds(bounds);
} | function fitMapToMarkersNearBounds(bounds) {
// get center of bounding box and use it to sort markers by distance
let center = bounds.getCenter();
const markersByDistance = getMarkersByDistanceFrom(center.lat(), center.lng());
// extend bounds to fit closest three markers
[0,1,2].forEach((i) => {
const marker = markersByDistance[i];
if (marker) {
bounds.extend(marker.position);
}
});
map.fitBounds(bounds);
} |
JavaScript | function centerMapToMarkersNearCoords(latitude, longitude) {
const markersByDistance = getMarkersByDistanceFrom(latitude, longitude);
// center the map on the user
const latlng = new google.maps.LatLng(latitude, longitude);
const bounds = new google.maps.LatLngBounds();
let hasMarker = false;
bounds.extend(latlng);
// Extend the bounds to contain the three closest markers
[0,1,2].forEach((i) => {
const marker = markersByDistance[i];
if (marker) {
hasMarker = true;
bounds.extend(marker.position);
}
});
if (hasMarker) {
// zoom to fit user loc + nearest markers
map.fitBounds(bounds);
} else {
// just has user loc - shift view without zooming
map.setCenter(latlng);
}
} | function centerMapToMarkersNearCoords(latitude, longitude) {
const markersByDistance = getMarkersByDistanceFrom(latitude, longitude);
// center the map on the user
const latlng = new google.maps.LatLng(latitude, longitude);
const bounds = new google.maps.LatLngBounds();
let hasMarker = false;
bounds.extend(latlng);
// Extend the bounds to contain the three closest markers
[0,1,2].forEach((i) => {
const marker = markersByDistance[i];
if (marker) {
hasMarker = true;
bounds.extend(marker.position);
}
});
if (hasMarker) {
// zoom to fit user loc + nearest markers
map.fitBounds(bounds);
} else {
// just has user loc - shift view without zooming
map.setCenter(latlng);
}
} |
JavaScript | function showMarkers(data, filters) {
if (!map || !primaryCluster) {
return;
}
const bounds = new google.maps.LatLngBounds();
const applied = filters.applied || {};
const hasFilters = applied.states || applied.acceptItems;
const markers = getMarkers(data, applied, hasFilters && bounds);
if (applied.states) {
primaryMarkers = markers.instate;
secondaryMarkers = markers.outofstate;
} else {
primaryMarkers = markers.outofstate;
secondaryMarkers = [];
}
primaryCluster && primaryCluster.clearMarkers();
secondaryCluster && secondaryCluster.clearMarkers();
for (const marker of primaryMarkers) {
marker.setOptions(primaryMarkerOptions);
}
for (const marker of secondaryMarkers) {
marker.setOptions(secondaryMarkerOptions);
}
updateClusters(primaryCluster, secondaryCluster);
let $mapStats = $('#map-stats');
updateStats($mapStats, markers.instate.length + markers.outofstate.length);
// HACK. On some browsers, the markercluster freaks out if it gets a bunch of new markers
// immediately followed by a map view change. Making the view change async works around
// this bug.
setTimeout(() => {
centerMapToBounds(map, bounds, 9);
}, 0);
} | function showMarkers(data, filters) {
if (!map || !primaryCluster) {
return;
}
const bounds = new google.maps.LatLngBounds();
const applied = filters.applied || {};
const hasFilters = applied.states || applied.acceptItems;
const markers = getMarkers(data, applied, hasFilters && bounds);
if (applied.states) {
primaryMarkers = markers.instate;
secondaryMarkers = markers.outofstate;
} else {
primaryMarkers = markers.outofstate;
secondaryMarkers = [];
}
primaryCluster && primaryCluster.clearMarkers();
secondaryCluster && secondaryCluster.clearMarkers();
for (const marker of primaryMarkers) {
marker.setOptions(primaryMarkerOptions);
}
for (const marker of secondaryMarkers) {
marker.setOptions(secondaryMarkerOptions);
}
updateClusters(primaryCluster, secondaryCluster);
let $mapStats = $('#map-stats');
updateStats($mapStats, markers.instate.length + markers.outofstate.length);
// HACK. On some browsers, the markercluster freaks out if it gets a bunch of new markers
// immediately followed by a map view change. Making the view change async works around
// this bug.
setTimeout(() => {
centerMapToBounds(map, bounds, 9);
}, 0);
} |
JavaScript | function updateClusters(primaryCluster, secondaryCluster) {
if (primaryCluster) {
primaryCluster.clearMarkers();
primaryCluster.addMarkers(primaryMarkers);
}
if (secondaryCluster) {
secondaryCluster.clearMarkers();
secondaryCluster.addMarkers(otherMarkers);
secondaryCluster.addMarkers(secondaryMarkers);
}
} | function updateClusters(primaryCluster, secondaryCluster) {
if (primaryCluster) {
primaryCluster.clearMarkers();
primaryCluster.addMarkers(primaryMarkers);
}
if (secondaryCluster) {
secondaryCluster.clearMarkers();
secondaryCluster.addMarkers(otherMarkers);
secondaryCluster.addMarkers(secondaryMarkers);
}
} |
JavaScript | function updateStats($elem, count, states) {
let statsHtml = '',
prettyMarkerCount = number_format(count, 0);
// Default to no states.
statsHtml = `(${prettyMarkerCount})`;
if (typeof states === 'undefined') states = [];
if (states.length > 0) {
let statesFormatted = states.join(', ');
statsHtml = `in ${statesFormatted} ` + statsHtml;
}
// If we're at zero, just clear it out for now.
if (count === 0) statsHtml = '';
$elem.html(statsHtml);
} | function updateStats($elem, count, states) {
let statsHtml = '',
prettyMarkerCount = number_format(count, 0);
// Default to no states.
statsHtml = `(${prettyMarkerCount})`;
if (typeof states === 'undefined') states = [];
if (states.length > 0) {
let statesFormatted = states.join(', ');
statsHtml = `in ${statesFormatted} ` + statsHtml;
}
// If we're at zero, just clear it out for now.
if (count === 0) statsHtml = '';
$elem.html(statsHtml);
} |
JavaScript | function number_format(number, decimal_places, dec_seperator, thou_seperator) {
// Init defaults.
if (typeof decimal_places === 'undefined') decimal_places = 0;
if (typeof dec_seperator === 'undefined') dec_seperator = '.';
if (typeof thou_seperator === 'undefined') thou_seperator = ',';
number = Math.round(number * Math.pow(10, decimal_places)) / Math.pow(10, decimal_places);
let e = number + '';
let f = e.split('.');
if (!f[0]) {
f[0] = '0';
}
if (!f[1]) {
f[1] = '';
}
if (f[1].length < decimal_places) {
let g = f[1];
for (let i = f[1].length + 1; i <= decimal_places; i++) {
g += '0';
}
f[1] = g;
}
if (thou_seperator != '' && f[0].length > 3) {
let h = f[0];
f[0] = '';
for (let j = 3; j < h.length; j += 3) {
let i = h.slice(h.length - j, h.length - j + 3);
f[0] = thou_seperator + i + f[0] + '';
}
let j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
f[0] = j + f[0];
}
dec_seperator = (decimal_places <= 0) ? '' : dec_seperator;
return f[0] + dec_seperator + f[1];
} | function number_format(number, decimal_places, dec_seperator, thou_seperator) {
// Init defaults.
if (typeof decimal_places === 'undefined') decimal_places = 0;
if (typeof dec_seperator === 'undefined') dec_seperator = '.';
if (typeof thou_seperator === 'undefined') thou_seperator = ',';
number = Math.round(number * Math.pow(10, decimal_places)) / Math.pow(10, decimal_places);
let e = number + '';
let f = e.split('.');
if (!f[0]) {
f[0] = '0';
}
if (!f[1]) {
f[1] = '';
}
if (f[1].length < decimal_places) {
let g = f[1];
for (let i = f[1].length + 1; i <= decimal_places; i++) {
g += '0';
}
f[1] = g;
}
if (thou_seperator != '' && f[0].length > 3) {
let h = f[0];
f[0] = '';
for (let j = 3; j < h.length; j += 3) {
let i = h.slice(h.length - j, h.length - j + 3);
f[0] = thou_seperator + i + f[0] + '';
}
let j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
f[0] = j + f[0];
}
dec_seperator = (decimal_places <= 0) ? '' : dec_seperator;
return f[0] + dec_seperator + f[1];
} |
JavaScript | parse(text) {
const input = text || '';
const chars = new antlr4.InputStream(input);
const lexer = new SightlyLexer(chars);
const tokens = new antlr4.CommonTokenStream(lexer);
const parser = new SightlyParser(tokens);
if (this._errorListener) {
parser.addErrorListener(this._errorListener);
}
return parser.interpolation().interp;
} | parse(text) {
const input = text || '';
const chars = new antlr4.InputStream(input);
const lexer = new SightlyLexer(chars);
const tokens = new antlr4.CommonTokenStream(lexer);
const parser = new SightlyParser(tokens);
if (this._errorListener) {
parser.addErrorListener(this._errorListener);
}
return parser.interpolation().interp;
} |
JavaScript | _flushBuffer() {
if (this._buffer.length > 0) {
this._handler.onText(this._buffer, this._startPos.line, this._startPos.column);
this._startPos = { line: this._line, column: this._column };
this._buffer = '';
}
} | _flushBuffer() {
if (this._buffer.length > 0) {
this._handler.onText(this._buffer, this._startPos.line, this._startPos.column);
this._startPos = { line: this._line, column: this._column };
this._buffer = '';
}
} |
JavaScript | _processTag(source, line, column) {
const snippet = this._buffer + source;
this._buffer = '';
const tok = this._tagTokenizer.tokenize(snippet, 0, snippet.length, line, column);
if (!tok.endTag) {
this._handler.onOpenTagStart(tok.tagName, line, column);
tok.attributes.forEach((attr) => {
const decoded = attr.value ? he.decode(attr.value, { isAttributeValue: true }) : attr.value;
this._handler.onAttribute(attr.name, decoded, attr.quoteChar, attr.line, attr.column);
});
this._handler.onOpenTagEnd(tok.endSlash, VOID_ELEMENTS[tok.tagName]);
} else {
this._handler.onCloseTag(tok.tagName, VOID_ELEMENTS[tok.tagName]);
}
return tok.tagName.toUpperCase() === 'SCRIPT' && !tok.endSlash;
} | _processTag(source, line, column) {
const snippet = this._buffer + source;
this._buffer = '';
const tok = this._tagTokenizer.tokenize(snippet, 0, snippet.length, line, column);
if (!tok.endTag) {
this._handler.onOpenTagStart(tok.tagName, line, column);
tok.attributes.forEach((attr) => {
const decoded = attr.value ? he.decode(attr.value, { isAttributeValue: true }) : attr.value;
this._handler.onAttribute(attr.name, decoded, attr.quoteChar, attr.line, attr.column);
});
this._handler.onOpenTagEnd(tok.endSlash, VOID_ELEMENTS[tok.tagName]);
} else {
this._handler.onCloseTag(tok.tagName, VOID_ELEMENTS[tok.tagName]);
}
return tok.tagName.toUpperCase() === 'SCRIPT' && !tok.endSlash;
} |
JavaScript | function animationHover(element, animation) {
element = $(element);
element.hover(
function() {
element.addClass("animated " + animation);
},
function() {
//wait for animation to finish before removing classes
window.setTimeout(function() {
element.removeClass("animated " + animation);
}, 2000);
}
);
} | function animationHover(element, animation) {
element = $(element);
element.hover(
function() {
element.addClass("animated " + animation);
},
function() {
//wait for animation to finish before removing classes
window.setTimeout(function() {
element.removeClass("animated " + animation);
}, 2000);
}
);
} |
JavaScript | function linearFit(xSeries, ySeries) {
let sum = function (p, c) {
return p + c
}
let xBar = xSeries.reduce(sum) * 1.0 / xSeries.length
let yBar = ySeries.reduce(sum) * 1.0 / ySeries.length
let ssXX = xSeries.map(function (d) {
return (d - xBar) * (d - xBar)
}).reduce(sum)
let ssYY = ySeries.map(function (d) {
return (d - yBar) * (d - yBar)
}).reduce(sum)
let ssXY = xSeries.map(function (d, i) {
return (d - xBar) * (ySeries[i] - yBar)
}).reduce(sum)
let m = ssXY / ssXX
let b = yBar - (xBar * m)
return (x => {
return (m * x) + b
})
} | function linearFit(xSeries, ySeries) {
let sum = function (p, c) {
return p + c
}
let xBar = xSeries.reduce(sum) * 1.0 / xSeries.length
let yBar = ySeries.reduce(sum) * 1.0 / ySeries.length
let ssXX = xSeries.map(function (d) {
return (d - xBar) * (d - xBar)
}).reduce(sum)
let ssYY = ySeries.map(function (d) {
return (d - yBar) * (d - yBar)
}).reduce(sum)
let ssXY = xSeries.map(function (d, i) {
return (d - xBar) * (ySeries[i] - yBar)
}).reduce(sum)
let m = ssXY / ssXX
let b = yBar - (xBar * m)
return (x => {
return (m * x) + b
})
} |
JavaScript | async create() {
if(!this.validate(this.table) || !this.validate(this.db)) {
return false;
}
let queryData = "";
for(let name in this.fields) {
queryData = queryData + name;
/**
* Add column data
*/
if(this.validate(this.fields[name].type)) {
let type = this.fields[name].type;
queryData = queryData + " " + type;
}
if(this.validate(this.fields[name].length)) {
let length = this.fields[name].length;
queryData = queryData + "(" + length + ")";
}
if(this.validate(this.fields[name].constrains)) {
let constrains = this.fields[name].constrains;
queryData = queryData + " " + constrains;
}
queryData = queryData + ", "
}
queryData = queryData.slice(0, -2);
try{
let statement = "CREATE TABLE IF NOT EXISTS " + pgPrepare(this.table) + " ( id SERIAL PRIMARY KEY " + pgPrepare(queryData) + ");";
let createTableData = await this.db.query(statement);
if(createTableData.rowCount !== 0){
return true;
}
} catch(e) {
}
return false;
} | async create() {
if(!this.validate(this.table) || !this.validate(this.db)) {
return false;
}
let queryData = "";
for(let name in this.fields) {
queryData = queryData + name;
/**
* Add column data
*/
if(this.validate(this.fields[name].type)) {
let type = this.fields[name].type;
queryData = queryData + " " + type;
}
if(this.validate(this.fields[name].length)) {
let length = this.fields[name].length;
queryData = queryData + "(" + length + ")";
}
if(this.validate(this.fields[name].constrains)) {
let constrains = this.fields[name].constrains;
queryData = queryData + " " + constrains;
}
queryData = queryData + ", "
}
queryData = queryData.slice(0, -2);
try{
let statement = "CREATE TABLE IF NOT EXISTS " + pgPrepare(this.table) + " ( id SERIAL PRIMARY KEY " + pgPrepare(queryData) + ");";
let createTableData = await this.db.query(statement);
if(createTableData.rowCount !== 0){
return true;
}
} catch(e) {
}
return false;
} |
JavaScript | validate(data, checks = {checkNull: true}) {
if(checks.checkNull) {
if(data == null || typeof data == "undefined") {
return false;
}
}
return true;
} | validate(data, checks = {checkNull: true}) {
if(checks.checkNull) {
if(data == null || typeof data == "undefined") {
return false;
}
}
return true;
} |
JavaScript | async create() {
if(!this.repository.validate(this.table) || !this.repository.validate(this.db)) {
return false;
}
let queryDataNames = "";
let queryDataValues = "";
for(let name in this.repository.fields) {
let value = this[name];
if(this.repository.validate(value)) {
queryDataNames = queryDataNames + name + ", ";
if(typeof value == "string") {
value = "'" + value + "'";
}
queryDataValues = queryDataValues + value + ", ";
}
}
queryDataNames = queryDataNames.slice(0, -2);
queryDataValues = queryDataValues.slice(0, -2);
try{
let statement = "INSERT INTO " + pgPrepare(this.table) + " (" + pgPrepare(queryDataNames) + ") VALUES (" + pgPrepare(queryDataValues) + ");";
let insertData = await this.db.query(statement);
if(insertData.rowCount !== 0){
return true;
}
} catch(e) {
}
return false;
} | async create() {
if(!this.repository.validate(this.table) || !this.repository.validate(this.db)) {
return false;
}
let queryDataNames = "";
let queryDataValues = "";
for(let name in this.repository.fields) {
let value = this[name];
if(this.repository.validate(value)) {
queryDataNames = queryDataNames + name + ", ";
if(typeof value == "string") {
value = "'" + value + "'";
}
queryDataValues = queryDataValues + value + ", ";
}
}
queryDataNames = queryDataNames.slice(0, -2);
queryDataValues = queryDataValues.slice(0, -2);
try{
let statement = "INSERT INTO " + pgPrepare(this.table) + " (" + pgPrepare(queryDataNames) + ") VALUES (" + pgPrepare(queryDataValues) + ");";
let insertData = await this.db.query(statement);
if(insertData.rowCount !== 0){
return true;
}
} catch(e) {
}
return false;
} |
JavaScript | checkInputs(inputChar) {
if (this.mode === 'Inputting') {
const tempString = this.userInput + inputChar;
this.userInput += inputChar;
this.showinputProgressCircles(tempString);
this.blocks.flashAndPlayAudio(inputChar);
// Checking input one on one
if (this.levelString.indexOf(tempString) === 0) {
// console.log('So far good.');
// If the player's input is completely same to this.levelString
if (tempString === this.levelString) {
this.gameContinue();
}
} else {
this.replayTimes > 0 ? this.replayCurrentLevel() : this.gameOver();
}
}
} | checkInputs(inputChar) {
if (this.mode === 'Inputting') {
const tempString = this.userInput + inputChar;
this.userInput += inputChar;
this.showinputProgressCircles(tempString);
this.blocks.flashAndPlayAudio(inputChar);
// Checking input one on one
if (this.levelString.indexOf(tempString) === 0) {
// console.log('So far good.');
// If the player's input is completely same to this.levelString
if (tempString === this.levelString) {
this.gameContinue();
}
} else {
this.replayTimes > 0 ? this.replayCurrentLevel() : this.gameOver();
}
}
} |
JavaScript | showinputProgressCircles(tempString) {
this.inputProgressElement.innerHTML = '';
// Updata circle div elements in any level
this.levelString.split('').forEach((data, index) => {
this.inputProgressElement.innerHTML += `
<div class="circle${index < tempString.length ? ' correct' : ''}"></div>`;
});
this.inputProgressElement.classList.remove('correct', 'wrong');
// If all inputs are correct, make circles blue
if (tempString === this.levelString) {
setTimeout(() => {
this.inputProgressElement.classList.add('correct');
}, this.playInterval);
}
// If not, make circles red immediately
if (this.levelString.indexOf(tempString) !== 0) {
this.inputProgressElement.classList.add('wrong');
}
} | showinputProgressCircles(tempString) {
this.inputProgressElement.innerHTML = '';
// Updata circle div elements in any level
this.levelString.split('').forEach((data, index) => {
this.inputProgressElement.innerHTML += `
<div class="circle${index < tempString.length ? ' correct' : ''}"></div>`;
});
this.inputProgressElement.classList.remove('correct', 'wrong');
// If all inputs are correct, make circles blue
if (tempString === this.levelString) {
setTimeout(() => {
this.inputProgressElement.classList.add('correct');
}, this.playInterval);
}
// If not, make circles red immediately
if (this.levelString.indexOf(tempString) !== 0) {
this.inputProgressElement.classList.add('wrong');
}
} |
JavaScript | function bac2Color(bac) {
bac = bac * 255;
var base = 0x0000FF, color = base;
//remove the 'blue' value the higher the bac is.
color -= bac;
//add the 'red' value the higher the bac is.
color += (bac << 16);
color = Math.round(color);
color = color.toString(16);
//zero-fill string
while(color.length < 6) {
color = '0' + color;
}
color = '#' + color;
return color;
} | function bac2Color(bac) {
bac = bac * 255;
var base = 0x0000FF, color = base;
//remove the 'blue' value the higher the bac is.
color -= bac;
//add the 'red' value the higher the bac is.
color += (bac << 16);
color = Math.round(color);
color = color.toString(16);
//zero-fill string
while(color.length < 6) {
color = '0' + color;
}
color = '#' + color;
return color;
} |
JavaScript | function update(dt) {
updateEntities(dt);
checkCollisions();
checkWater();
} | function update(dt) {
updateEntities(dt);
checkCollisions();
checkWater();
} |
JavaScript | function updateTally(result) {
if (result === 'lose') {
score.tally--;
} else if (result === 'win') {
score.tally++;
}
} | function updateTally(result) {
if (result === 'lose') {
score.tally--;
} else if (result === 'win') {
score.tally++;
}
} |
JavaScript | function checkCollisions() {
/*
* loop through the enemies and identify them as 'enemy'
*/
for (var i = 0; i <= allEnemies.length - 1; i++) {
var enemy = allEnemies[i];
// if you're on the same row as enemy
if (enemy.y === player.y) {
//delineate player and enemy boundaries
var testThis = enemy.rightLimit >= player.leftLimit;
var testThat = enemy.leftLimit <= player.rightLimit;
// if you're within the boundaries of an enemy
if (testThis && testThat) {
//reset player position
player.init();
// loop through all the enemies and indivdually reset them (passing the lose parameter)
allEnemies.forEach(function(enemy) {
enemy.init('lose');
});
// update the tally and render it
updateTally('lose');
score.render();
}
}
}
} | function checkCollisions() {
/*
* loop through the enemies and identify them as 'enemy'
*/
for (var i = 0; i <= allEnemies.length - 1; i++) {
var enemy = allEnemies[i];
// if you're on the same row as enemy
if (enemy.y === player.y) {
//delineate player and enemy boundaries
var testThis = enemy.rightLimit >= player.leftLimit;
var testThat = enemy.leftLimit <= player.rightLimit;
// if you're within the boundaries of an enemy
if (testThis && testThat) {
//reset player position
player.init();
// loop through all the enemies and indivdually reset them (passing the lose parameter)
allEnemies.forEach(function(enemy) {
enemy.init('lose');
});
// update the tally and render it
updateTally('lose');
score.render();
}
}
}
} |
JavaScript | function checkWater() {
if (player.y < gameProps.rowHeight - 40) {
youWin();
}
} | function checkWater() {
if (player.y < gameProps.rowHeight - 40) {
youWin();
}
} |
JavaScript | function youWin() {
player.init();
allEnemies.forEach(function(enemy) {
enemy.init('win');
});
updateTally('win');
score.render();
} | function youWin() {
player.init();
allEnemies.forEach(function(enemy) {
enemy.init('win');
});
updateTally('win');
score.render();
} |
JavaScript | async function openCloudDBZone() {
console.log('try to open zone')
try {
const config = new CloudDBZoneConfig('BaseZoneA');
cloudDBZone = await agcCloudDB.openCloudDBZone(config);
console.log('open zone success:');
console.log(cloudDBZone);
return true;
} catch (e) {
console.log('open zone failed:' + e.message);
return false;
}
} | async function openCloudDBZone() {
console.log('try to open zone')
try {
const config = new CloudDBZoneConfig('BaseZoneA');
cloudDBZone = await agcCloudDB.openCloudDBZone(config);
console.log('open zone success:');
console.log(cloudDBZone);
return true;
} catch (e) {
console.log('open zone failed:' + e.message);
return false;
}
} |
JavaScript | async function subscribeSnapshot(onSnapshotListener) {
try {
const query = CloudDBZoneQuery.where(BookInfo);
query.equalTo('shadowFlag', true);
const listenerHandler = await cloudDBZone.subscribeSnapshot(query, onSnapshotListener);
return listenerHandler;
} catch (e) {
console.log('subscribeSnapshot error:' + e.message);
return null;
}
} | async function subscribeSnapshot(onSnapshotListener) {
try {
const query = CloudDBZoneQuery.where(BookInfo);
query.equalTo('shadowFlag', true);
const listenerHandler = await cloudDBZone.subscribeSnapshot(query, onSnapshotListener);
return listenerHandler;
} catch (e) {
console.log('subscribeSnapshot error:' + e.message);
return null;
}
} |
JavaScript | async function executeQueryComposite(object) {
try {
return await new Promise(resolve => {
console.log(object);
const query = CloudDBZoneQuery.where(BookInfo);
if (object.name.length > 0) {
query.equalTo('bookName', object.name);
}
if (parseFloat(object.minPrice) > 0) {
query.greaterThanOrEqualTo('price', parseFloat(object.minPrice));
}
if (parseFloat(object.maxPrice) > 0 && parseFloat(object.maxPrice) > parseFloat(object.minPrice)) {
query.lessThanOrEqualTo('price', parseFloat(object.maxPrice));
}
if (parseInt(object.bookCount) > 0) {
query.limit(parseInt(object.bookCount));
}
query.orderByAsc('id');
cloudDBZone.executeQuery(query).then(snapshot => {
const resultArray = snapshot.getSnapshotObjects();
resolve(resultArray);
});
});
} catch (e) {
console.log('query failed with reason:' + e.message);
return null;
}
} | async function executeQueryComposite(object) {
try {
return await new Promise(resolve => {
console.log(object);
const query = CloudDBZoneQuery.where(BookInfo);
if (object.name.length > 0) {
query.equalTo('bookName', object.name);
}
if (parseFloat(object.minPrice) > 0) {
query.greaterThanOrEqualTo('price', parseFloat(object.minPrice));
}
if (parseFloat(object.maxPrice) > 0 && parseFloat(object.maxPrice) > parseFloat(object.minPrice)) {
query.lessThanOrEqualTo('price', parseFloat(object.maxPrice));
}
if (parseInt(object.bookCount) > 0) {
query.limit(parseInt(object.bookCount));
}
query.orderByAsc('id');
cloudDBZone.executeQuery(query).then(snapshot => {
const resultArray = snapshot.getSnapshotObjects();
resolve(resultArray);
});
});
} catch (e) {
console.log('query failed with reason:' + e.message);
return null;
}
} |
JavaScript | async function queryDataByOrderWay(filedName, sortType) {
try {
return await new Promise(resolve => {
const query = CloudDBZoneQuery.where(BookInfo);
if (sortType === 1) {
query.orderByAsc(filedName);
} else {
query.orderByDesc(filedName);
}
cloudDBZone.executeQuery(query).then(snapshot => {
const resultArray = snapshot.getSnapshotObjects();
resolve(resultArray);
});
});
} catch (e) {
console.log('query failed with reason:' + e.message);
return null;
}
} | async function queryDataByOrderWay(filedName, sortType) {
try {
return await new Promise(resolve => {
const query = CloudDBZoneQuery.where(BookInfo);
if (sortType === 1) {
query.orderByAsc(filedName);
} else {
query.orderByDesc(filedName);
}
cloudDBZone.executeQuery(query).then(snapshot => {
const resultArray = snapshot.getSnapshotObjects();
resolve(resultArray);
});
});
} catch (e) {
console.log('query failed with reason:' + e.message);
return null;
}
} |
JavaScript | function loginWithPhone(countryCode, account, password, verifyCode) {
let credential = getPhoneCredential(countryCode, account, password, verifyCode);
if (!credential) {
return Promise.reject(new Error('credential is undefined'));
}
return login(credential);
} | function loginWithPhone(countryCode, account, password, verifyCode) {
let credential = getPhoneCredential(countryCode, account, password, verifyCode);
if (!credential) {
return Promise.reject(new Error('credential is undefined'));
}
return login(credential);
} |
JavaScript | function loginWithWeChat(token, openId, autoCreateUser = true) {
let credential = agconnect.auth.WeixinAuthProvider.credentialWithToken(token, openId, autoCreateUser);
if (!credential) {
return Promise.reject(new Error('credential is undefined'));
}
return login(credential);
} | function loginWithWeChat(token, openId, autoCreateUser = true) {
let credential = agconnect.auth.WeixinAuthProvider.credentialWithToken(token, openId, autoCreateUser);
if (!credential) {
return Promise.reject(new Error('credential is undefined'));
}
return login(credential);
} |
JavaScript | function loginWithQQ(token, openId, autoCreateUser = true) {
let credential = agconnect.auth.QQAuthProvider.credentialWithToken(token, openId, autoCreateUser);
if (!credential) {
return Promise.reject(new Error('credential is undefined'));
}
return login(credential);
} | function loginWithQQ(token, openId, autoCreateUser = true) {
let credential = agconnect.auth.QQAuthProvider.credentialWithToken(token, openId, autoCreateUser);
if (!credential) {
return Promise.reject(new Error('credential is undefined'));
}
return login(credential);
} |
JavaScript | function link(linkObj, param1, param2, param3) {
return agconnect.auth().getCurrentUser().then(async user => {
let credential = undefined;
if (linkObj == "phone") {
credential = getPhoneCredential('86', param1, param2, param3);
} else if (linkObj == "email") {
credential = getEmailCredential(param1, param2, param3);
} else if (linkObj == "QQ") {
credential = agconnect.auth.QQAuthProvider.credentialWithToken(param1, param2, true);
} else if (linkObj == "weChat") {
credential = agconnect.auth.WeixinAuthProvider.credentialWithToken(param1, param2, true);
}
if (!credential) {
return Promise.reject(new Error('credential is undefined'));
}
await user.link(credential);
});
} | function link(linkObj, param1, param2, param3) {
return agconnect.auth().getCurrentUser().then(async user => {
let credential = undefined;
if (linkObj == "phone") {
credential = getPhoneCredential('86', param1, param2, param3);
} else if (linkObj == "email") {
credential = getEmailCredential(param1, param2, param3);
} else if (linkObj == "QQ") {
credential = agconnect.auth.QQAuthProvider.credentialWithToken(param1, param2, true);
} else if (linkObj == "weChat") {
credential = agconnect.auth.WeixinAuthProvider.credentialWithToken(param1, param2, true);
}
if (!credential) {
return Promise.reject(new Error('credential is undefined'));
}
await user.link(credential);
});
} |
JavaScript | function userReauthenticateByPhone(countryCode, phoneNumber, password, verifyCode) {
let credential;
if (verifyCode) {
credential = agconnect.auth.PhoneAuthProvider.credentialWithVerifyCode(countryCode, phoneNumber, password, verifyCode);
} else {
credential = agconnect.auth.PhoneAuthProvider.credentialWithPassword(countryCode, phoneNumber, password);
}
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.userReauthenticate(credential);
} else {
return Promise.reject(new Error("no user login"));
}
})
} | function userReauthenticateByPhone(countryCode, phoneNumber, password, verifyCode) {
let credential;
if (verifyCode) {
credential = agconnect.auth.PhoneAuthProvider.credentialWithVerifyCode(countryCode, phoneNumber, password, verifyCode);
} else {
credential = agconnect.auth.PhoneAuthProvider.credentialWithPassword(countryCode, phoneNumber, password);
}
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.userReauthenticate(credential);
} else {
return Promise.reject(new Error("no user login"));
}
})
} |
JavaScript | function userReauthenticateByEmail(email, password, verifyCode) {
let credential = '';
if (verifyCode) {
credential = agconnect.auth.EmailAuthProvider.credentialWithVerifyCode(email, password, verifyCode);
} else {
credential = agconnect.auth.EmailAuthProvider.credentialWithPassword(email, password);
}
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.userReauthenticate(credential);
} else {
return Promise.reject(new Error("no user login"));
}
})
} | function userReauthenticateByEmail(email, password, verifyCode) {
let credential = '';
if (verifyCode) {
credential = agconnect.auth.EmailAuthProvider.credentialWithVerifyCode(email, password, verifyCode);
} else {
credential = agconnect.auth.EmailAuthProvider.credentialWithPassword(email, password);
}
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.userReauthenticate(credential);
} else {
return Promise.reject(new Error("no user login"));
}
})
} |
JavaScript | function updatePhonePwd(newPassword, verifyCode) {
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.updatePassword(newPassword, verifyCode, 11);
} else {
return Promise.reject(new Error("no user login"));
}
});
} | function updatePhonePwd(newPassword, verifyCode) {
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.updatePassword(newPassword, verifyCode, 11);
} else {
return Promise.reject(new Error("no user login"));
}
});
} |
JavaScript | function updateEmailPwd(newPassword, verifyCode) {
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.updatePassword(newPassword, verifyCode, 12);
} else {
return Promise.reject(new Error("no user login"));
}
});
} | function updateEmailPwd(newPassword, verifyCode) {
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.updatePassword(newPassword, verifyCode, 12);
} else {
return Promise.reject(new Error("no user login"));
}
});
} |
JavaScript | function updatePhone(newPhone, verifyCode, lang) {
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.updatePhone("86", newPhone, verifyCode, lang);
} else {
return Promise.reject(new Error("no user login"));
}
});
} | function updatePhone(newPhone, verifyCode, lang) {
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.updatePhone("86", newPhone, verifyCode, lang);
} else {
return Promise.reject(new Error("no user login"));
}
});
} |
JavaScript | function updateEmail(newEmail, verifyCode, lang) {
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.updateEmail(newEmail, verifyCode, lang);
} else {
return Promise.reject(new Error("no user login"));
}
});
} | function updateEmail(newEmail, verifyCode, lang) {
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.updateEmail(newEmail, verifyCode, lang);
} else {
return Promise.reject(new Error("no user login"));
}
});
} |
JavaScript | function updateProfile(profile) {
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.updateProfile(profile);
} else {
return Promise.reject(new Error("no user login"));
}
});
} | function updateProfile(profile) {
return agconnect.auth().getCurrentUser().then(async user => {
if (user) {
await user.updateProfile(profile);
} else {
return Promise.reject(new Error("no user login"));
}
});
} |
JavaScript | function startApp() {
inquirer.prompt({
name: "mainmenu",
type: "list",
message: "What would you like to do?",
choices: [
"Show All Employees",
"Add Employee Info",
"Remove Employee",
"Show Roles",
"Add Role",
"Remove Role",
"Show Departments",
"Add Department",
"Remove Department",
"Exit"
]
}).then(responses => {
console.log("You selected: ", responses.mainmenu);
switch (responses.mainmenu) {
case "Show All Employees":
showEmployees();
break;
case "Add Employee Info":
addEmployee();
break;
case "Remove Employee":
removeEmployee();
break;
case "Show Roles":
showRoles();
break;
case "Add Role":
addRole();
break;
case "Remove Role":
removeRole();
break;
case "Show Departments":
showDepartments();
break;
case "Add Department":
addDepartment();
break;
case "Remove Department":
removeDepartment();
break;
case "Exit":
connection.end();
break;
}
});
} | function startApp() {
inquirer.prompt({
name: "mainmenu",
type: "list",
message: "What would you like to do?",
choices: [
"Show All Employees",
"Add Employee Info",
"Remove Employee",
"Show Roles",
"Add Role",
"Remove Role",
"Show Departments",
"Add Department",
"Remove Department",
"Exit"
]
}).then(responses => {
console.log("You selected: ", responses.mainmenu);
switch (responses.mainmenu) {
case "Show All Employees":
showEmployees();
break;
case "Add Employee Info":
addEmployee();
break;
case "Remove Employee":
removeEmployee();
break;
case "Show Roles":
showRoles();
break;
case "Add Role":
addRole();
break;
case "Remove Role":
removeRole();
break;
case "Show Departments":
showDepartments();
break;
case "Add Department":
addDepartment();
break;
case "Remove Department":
removeDepartment();
break;
case "Exit":
connection.end();
break;
}
});
} |
JavaScript | function showEmployees() {
// select from the database
let query = "SELECT employee.id, employee.first_name, employee.last_name, role.title, department.name AS department, role.salary FROM employee LEFT JOIN role ON employee.role_id = role.id LEFT JOIN department on role.department_id = department.id;";
connection.query(query, function (err, res) {
if (err) throw err;
console.table(res);
startApp();
});
} | function showEmployees() {
// select from the database
let query = "SELECT employee.id, employee.first_name, employee.last_name, role.title, department.name AS department, role.salary FROM employee LEFT JOIN role ON employee.role_id = role.id LEFT JOIN department on role.department_id = department.id;";
connection.query(query, function (err, res) {
if (err) throw err;
console.table(res);
startApp();
});
} |
JavaScript | function addEmployee() {
inquirer
.prompt([
{
type: "input",
message: "What's the first name of the employee?",
name: "firstName"
},
{
type: "input",
message: "What's the last name of the employee?",
name: "lastName"
},
{
type: "input",
message: "What is the employee's role id number?",
name: "roleId"
},
{
type: "input",
message: "What is the manager id number?",
name: "managerId"
}
])
.then(answer => {
connection.query("INSERT INTO employee (first_name, last_name, role_id, manager_id) VALUES (?, ?, ?, ?)", [answer.firstName, answer.lastName, answer.roleId, answer.managerId], function (err, res) {
if (err) throw err;
console.table(res);
startApp();
});
});
} | function addEmployee() {
inquirer
.prompt([
{
type: "input",
message: "What's the first name of the employee?",
name: "firstName"
},
{
type: "input",
message: "What's the last name of the employee?",
name: "lastName"
},
{
type: "input",
message: "What is the employee's role id number?",
name: "roleId"
},
{
type: "input",
message: "What is the manager id number?",
name: "managerId"
}
])
.then(answer => {
connection.query("INSERT INTO employee (first_name, last_name, role_id, manager_id) VALUES (?, ?, ?, ?)", [answer.firstName, answer.lastName, answer.roleId, answer.managerId], function (err, res) {
if (err) throw err;
console.table(res);
startApp();
});
});
} |
JavaScript | function showRoles() {
// select from the database
let query = "SELECT * FROM role";
connection.query(query, function (err, res) {
if (err) throw err;
console.table(res);
startApp();
});
} | function showRoles() {
// select from the database
let query = "SELECT * FROM role";
connection.query(query, function (err, res) {
if (err) throw err;
console.table(res);
startApp();
});
} |
JavaScript | function addRole() {
inquirer
.prompt([
{
type: "input",
message: "What's the name of the role?",
name: "roleName"
},
{
type: "input",
message: "What is the salary for this role?",
name: "salaryTotal"
},
{
type: "input",
message: "What is the department id number?",
name: "deptId"
}
])
.then(answer => {
connection.query("INSERT INTO role (title, salary, department_id) VALUES (?, ?, ?)", [answer.roleName, answer.salaryTotal, answer.deptId], function (err, res) {
if (err) throw err;
console.table(res);
startApp();
});
});
} | function addRole() {
inquirer
.prompt([
{
type: "input",
message: "What's the name of the role?",
name: "roleName"
},
{
type: "input",
message: "What is the salary for this role?",
name: "salaryTotal"
},
{
type: "input",
message: "What is the department id number?",
name: "deptId"
}
])
.then(answer => {
connection.query("INSERT INTO role (title, salary, department_id) VALUES (?, ?, ?)", [answer.roleName, answer.salaryTotal, answer.deptId], function (err, res) {
if (err) throw err;
console.table(res);
startApp();
});
});
} |
JavaScript | function showDepartments() {
// select from the database
let query = "SELECT * FROM department";
connection.query(query, function (err, res) {
if (err) throw err;
console.table(res);
startApp();
});
} | function showDepartments() {
// select from the database
let query = "SELECT * FROM department";
connection.query(query, function (err, res) {
if (err) throw err;
console.table(res);
startApp();
});
} |
JavaScript | function addDepartment() {
inquirer.prompt({
type: "input",
message: "What is the name of the department?",
name: "deptName"
}).then(answer => {
connection.query("INSERT INTO department (name) VALUES (?)", [answer.deptName], function (err, res) {
if (err) throw err;
console.table(res)
startApp()
})
})
} | function addDepartment() {
inquirer.prompt({
type: "input",
message: "What is the name of the department?",
name: "deptName"
}).then(answer => {
connection.query("INSERT INTO department (name) VALUES (?)", [answer.deptName], function (err, res) {
if (err) throw err;
console.table(res)
startApp()
})
})
} |
JavaScript | function downloadCsv(req, res) {
// choosing to utilize axios OVER an import of the service
// because making a "GET" request will allow this controller
// to utilize a micro-service located at the following endpoint:
const url = 'https://' + config.get('server.fqdn') + '/api/content/search/contacts.json?category=SBIC'
axios
.get(url)
.then(result => {
const csv = createCsvFromJson(result.data)
res
.header('Content-Type', 'text/csv')
.status(httpStatus.OK)
.send(csv)
})
.catch(error => {
res.status(httpStatus.INTERNAL_SERVER_ERROR).send(error)
})
} | function downloadCsv(req, res) {
// choosing to utilize axios OVER an import of the service
// because making a "GET" request will allow this controller
// to utilize a micro-service located at the following endpoint:
const url = 'https://' + config.get('server.fqdn') + '/api/content/search/contacts.json?category=SBIC'
axios
.get(url)
.then(result => {
const csv = createCsvFromJson(result.data)
res
.header('Content-Type', 'text/csv')
.status(httpStatus.OK)
.send(csv)
})
.catch(error => {
res.status(httpStatus.INTERNAL_SERVER_ERROR).send(error)
})
} |
JavaScript | async function checkHomepage(url) {
$browser.get(url)
.then(async () => {
console.log(`Page ${url} loaded.`);
if (url === `${baseUrl}/`) {
// First make sure the main homepage is not static
let staticMarker;
try {
staticMarker = await $browser.findElement($driver.By.id('___WARNING__STATIC_HOMEPAGE___'));
} catch (e) {
// good
}
if (staticMarker) {
assert.fail('This homepage is static: backend must be down!');
}
assert.ok(await $browser.findElement($driver.By.css('div.featured-article')), 'no featured article');
}
});
} | async function checkHomepage(url) {
$browser.get(url)
.then(async () => {
console.log(`Page ${url} loaded.`);
if (url === `${baseUrl}/`) {
// First make sure the main homepage is not static
let staticMarker;
try {
staticMarker = await $browser.findElement($driver.By.id('___WARNING__STATIC_HOMEPAGE___'));
} catch (e) {
// good
}
if (staticMarker) {
assert.fail('This homepage is static: backend must be down!');
}
assert.ok(await $browser.findElement($driver.By.css('div.featured-article')), 'no featured article');
}
});
} |
JavaScript | async function decorateSocialLinks(blockEl) {
blockEl.querySelectorAll(':scope a').forEach((linkEl) => {
const { title, type, className } = getSocialLinkDetails(linkEl.href);
if (type === 'unknown') {
// remove links with unknown type
linkEl.remove();
return;
}
if (type === 'email') {
linkEl.setAttribute('title', title);
linkEl.href = `mailto:${linkEl.textContent}`;
linkEl.className = className;
return;
}
linkEl.innerHTML = '';
linkEl.appendChild(createSVG(type));
linkEl.setAttribute('title', title);
linkEl.className = className;
});
const ul = blockEl.querySelector('ul');
if (ul.hasChildNodes()) {
// add language specific text
const parent = ul.parentNode;
const placeholders = await fetchPlaceholders();
const followMe = document.createElement('p');
followMe.classList.add('social-links-text');
followMe.textContent = placeholders.social;
parent.prepend(followMe);
}
} | async function decorateSocialLinks(blockEl) {
blockEl.querySelectorAll(':scope a').forEach((linkEl) => {
const { title, type, className } = getSocialLinkDetails(linkEl.href);
if (type === 'unknown') {
// remove links with unknown type
linkEl.remove();
return;
}
if (type === 'email') {
linkEl.setAttribute('title', title);
linkEl.href = `mailto:${linkEl.textContent}`;
linkEl.className = className;
return;
}
linkEl.innerHTML = '';
linkEl.appendChild(createSVG(type));
linkEl.setAttribute('title', title);
linkEl.className = className;
});
const ul = blockEl.querySelector('ul');
if (ul.hasChildNodes()) {
// add language specific text
const parent = ul.parentNode;
const placeholders = await fetchPlaceholders();
const followMe = document.createElement('p');
followMe.classList.add('social-links-text');
followMe.textContent = placeholders.social;
parent.prepend(followMe);
}
} |
JavaScript | _signTransaction(fromAddress, hash, privateKey) {
let key = ec.keyFromPrivate(privateKey, 'hex');
// * Elliptic cryptography offers us a public key in form of
// * `y^2 = ax^3 + bx + c`, with prefix of 0x04.
// * I tried extracting 'x' component of ec public key to use that as
// * wallet address, but the library does not support calculating 'y'
// * component of public address from 'x' component.
// * Therefore, I am settling for Public Key as wallet address for now.
// TODO: Revisit this
if (key.getPublic('hex') !== fromAddress) {
throw new Error(
'You are attempting to sign someone else\'s Transaction'
);
}
let sign = key.sign(hash);
return sign.toDER('hex');
} | _signTransaction(fromAddress, hash, privateKey) {
let key = ec.keyFromPrivate(privateKey, 'hex');
// * Elliptic cryptography offers us a public key in form of
// * `y^2 = ax^3 + bx + c`, with prefix of 0x04.
// * I tried extracting 'x' component of ec public key to use that as
// * wallet address, but the library does not support calculating 'y'
// * component of public address from 'x' component.
// * Therefore, I am settling for Public Key as wallet address for now.
// TODO: Revisit this
if (key.getPublic('hex') !== fromAddress) {
throw new Error(
'You are attempting to sign someone else\'s Transaction'
);
}
let sign = key.sign(hash);
return sign.toDER('hex');
} |
JavaScript | addTransactionToThePool(transaction) {
if (this.#transactionPool.length >= this.#maxTransactionPoolSize) {
// broadcast this transactionPool to enable mining
eventEmitter.emit(constants.EVENTS.TRANSACTION_POOL_FILLED, this.transactionPool);
this.#transactionPool = [];
}
// Here transaction.fromAddress acts as a public key
let isTransactionValid = this.verifyTransaction(transaction,
transaction.fromAddress);
// TODO: add a method to check if the transaction is already in pool
if (isTransactionValid) {
this.#transactionPool.push(transaction);
} else {
throw new Error(
'Attempted to push invalid transaction onto the pool'
);
}
} | addTransactionToThePool(transaction) {
if (this.#transactionPool.length >= this.#maxTransactionPoolSize) {
// broadcast this transactionPool to enable mining
eventEmitter.emit(constants.EVENTS.TRANSACTION_POOL_FILLED, this.transactionPool);
this.#transactionPool = [];
}
// Here transaction.fromAddress acts as a public key
let isTransactionValid = this.verifyTransaction(transaction,
transaction.fromAddress);
// TODO: add a method to check if the transaction is already in pool
if (isTransactionValid) {
this.#transactionPool.push(transaction);
} else {
throw new Error(
'Attempted to push invalid transaction onto the pool'
);
}
} |
JavaScript | createTransaction(fromAddress, toAddress, data, privateKey) {
// Do not allow transactions if there are any other transactions pending in the pool
if(this.isAnyTransactionPending(fromAddress)) {
throw new Error(`There is already one Transaction pending from this Address:
${fromAddress}`);
}
let transaction = {};
transaction.fromAddress = fromAddress;
transaction.toAddress = toAddress;
transaction.data = JSON.stringify(data);
transaction.timeStamp = Date.now();
transaction.signature = this._signTransaction(
transaction.fromAddress,
this._generateHash(transaction.fromAddress, transaction.toAddress,
transaction.data, transaction.timeStamp),
privateKey);
return transaction;
} | createTransaction(fromAddress, toAddress, data, privateKey) {
// Do not allow transactions if there are any other transactions pending in the pool
if(this.isAnyTransactionPending(fromAddress)) {
throw new Error(`There is already one Transaction pending from this Address:
${fromAddress}`);
}
let transaction = {};
transaction.fromAddress = fromAddress;
transaction.toAddress = toAddress;
transaction.data = JSON.stringify(data);
transaction.timeStamp = Date.now();
transaction.signature = this._signTransaction(
transaction.fromAddress,
this._generateHash(transaction.fromAddress, transaction.toAddress,
transaction.data, transaction.timeStamp),
privateKey);
return transaction;
} |
JavaScript | isAnyTransactionPending(fromAddress) {
for(let i = 0; i < this.#transactionPool.length; i++) {
if(fromAddress === this.#transactionPool[i].fromAddress) {
return true;
}
}
return false;
} | isAnyTransactionPending(fromAddress) {
for(let i = 0; i < this.#transactionPool.length; i++) {
if(fromAddress === this.#transactionPool[i].fromAddress) {
return true;
}
}
return false;
} |
JavaScript | createBlockchain(name) {
this.#blockChain = new Blockchain(name);
eventEmitter.on(constants.TRANSACTION_CREATED, this.#onTransactionListener);
eventEmitter.on(constants.TRANSACTION_POOL_FILLED, (transactionPool) => {
this.#pendingTransactionPool = transactionPool;
});
eventEmitter.on(constants.BLOCK_MINED, this.#onBlockMinedListener);
return this;
} | createBlockchain(name) {
this.#blockChain = new Blockchain(name);
eventEmitter.on(constants.TRANSACTION_CREATED, this.#onTransactionListener);
eventEmitter.on(constants.TRANSACTION_POOL_FILLED, (transactionPool) => {
this.#pendingTransactionPool = transactionPool;
});
eventEmitter.on(constants.BLOCK_MINED, this.#onBlockMinedListener);
return this;
} |
JavaScript | saveBlockChain() {
return localforage.setItem(this.#blockChain.getName(),
this.#blockChain.getBlockChain())
.then(() => {
console.log('Successfully saved Blockchain');
return this;
}).catch((error) => {
console.log('Failed to save Blockchain');
console.log(error);
});
} | saveBlockChain() {
return localforage.setItem(this.#blockChain.getName(),
this.#blockChain.getBlockChain())
.then(() => {
console.log('Successfully saved Blockchain');
return this;
}).catch((error) => {
console.log('Failed to save Blockchain');
console.log(error);
});
} |
JavaScript | loadBlockChain(name) {
localforage.getItem(name).then((blockChain) => {
this.#blockChain = new Blockchain(name, blockChain);
eventEmitter.on(constants.TRANSACTION_CREATED, this.#onTransactionListener);
eventEmitter.on(constants.TRANSACTION_POOL_FILLED, (transactionPool) => {
this.#pendingTransactionPool = transactionPool;
});
eventEmitter.on(constants.BLOCK_MINED, this.#onBlockMinedListener);
return this;
}).catch((error) => {
console.log('Failed to load Blockchain');
console.log(error);
});
} | loadBlockChain(name) {
localforage.getItem(name).then((blockChain) => {
this.#blockChain = new Blockchain(name, blockChain);
eventEmitter.on(constants.TRANSACTION_CREATED, this.#onTransactionListener);
eventEmitter.on(constants.TRANSACTION_POOL_FILLED, (transactionPool) => {
this.#pendingTransactionPool = transactionPool;
});
eventEmitter.on(constants.BLOCK_MINED, this.#onBlockMinedListener);
return this;
}).catch((error) => {
console.log('Failed to load Blockchain');
console.log(error);
});
} |
JavaScript | saveWallet() {
return localforage.setItem(this.#wallet.getWalletAddress(),
this.#wallet.getPrivateKey())
.then(() => {
console.log('Successfully saved Wallet');
return this;
}).catch((error) => {
console.log('Failed to save Wallet');
console.log(error);
});
} | saveWallet() {
return localforage.setItem(this.#wallet.getWalletAddress(),
this.#wallet.getPrivateKey())
.then(() => {
console.log('Successfully saved Wallet');
return this;
}).catch((error) => {
console.log('Failed to save Wallet');
console.log(error);
});
} |
JavaScript | loadWallet(walletAddress) {
localforage.getItem(walletAddress).then((walletPrivateKey) => {
this.#wallet = new Wallet(walletPrivateKey);
return this;
}).catch((error) => {
console.log('Failed to load Wallet');
console.log(error);
});
} | loadWallet(walletAddress) {
localforage.getItem(walletAddress).then((walletPrivateKey) => {
this.#wallet = new Wallet(walletPrivateKey);
return this;
}).catch((error) => {
console.log('Failed to load Wallet');
console.log(error);
});
} |
JavaScript | createTransaction(toAddress, data) {
let balance = 0;
let newTransaction = null;
if(data.type == 'currency') {
balance = this.#blockChain.getBalance(this.getWalletAddress);
if(balance >= data.value) {
newTransaction = transaction.createTransaction(this.#wallet.getWalletAddress(),
toAddress, data, this.#wallet.getPrivateKey());
} else {
throw new Error(`Transaction amount exceeds balance: ${balance}`);
}
} else {
newTransaction = transaction.createTransaction(this.#wallet.getWalletAddress(),
toAddress, data, this.#wallet.getPrivateKey());
}
eventEmitter.emit(constants.EVENTS.TRANSACTION_CREATED, newTransaction);
return this;
} | createTransaction(toAddress, data) {
let balance = 0;
let newTransaction = null;
if(data.type == 'currency') {
balance = this.#blockChain.getBalance(this.getWalletAddress);
if(balance >= data.value) {
newTransaction = transaction.createTransaction(this.#wallet.getWalletAddress(),
toAddress, data, this.#wallet.getPrivateKey());
} else {
throw new Error(`Transaction amount exceeds balance: ${balance}`);
}
} else {
newTransaction = transaction.createTransaction(this.#wallet.getWalletAddress(),
toAddress, data, this.#wallet.getPrivateKey());
}
eventEmitter.emit(constants.EVENTS.TRANSACTION_CREATED, newTransaction);
return this;
} |
JavaScript | _generateHash() {
if (arguments.length === 0) {
throw new Error('There is no data to hash');
}
let dataToHash = '';
for (let i = 0; i < arguments.length; i++) {
dataToHash += arguments[i];
}
let hash = sha256()
.update(dataToHash)
.digest('hex')
.toString();
return hash;
} | _generateHash() {
if (arguments.length === 0) {
throw new Error('There is no data to hash');
}
let dataToHash = '';
for (let i = 0; i < arguments.length; i++) {
dataToHash += arguments[i];
}
let hash = sha256()
.update(dataToHash)
.digest('hex')
.toString();
return hash;
} |
JavaScript | verifyNewBlock(block, difficulty) {
let difficultyString = Array(difficulty + 1).join('0');
let hash = this._generateHash(block.previousHash,
block.data, block.timeStamp, block.nonce);
if((this.getLastBlockHash() === block.previousHash)
&& (hash === block.hash)
&& (hash.substring(0, difficulty) === difficultyString)) {
return true;
} else {
return false;
}
} | verifyNewBlock(block, difficulty) {
let difficultyString = Array(difficulty + 1).join('0');
let hash = this._generateHash(block.previousHash,
block.data, block.timeStamp, block.nonce);
if((this.getLastBlockHash() === block.previousHash)
&& (hash === block.hash)
&& (hash.substring(0, difficulty) === difficultyString)) {
return true;
} else {
return false;
}
} |
JavaScript | proxyData(data) {
Object.keys(data).forEach(key => {
Object.defineProperty(this, key, {
get() {
return data[key];
},
set(newVal) {
data[key] = newVal;
}
});
});
} | proxyData(data) {
Object.keys(data).forEach(key => {
Object.defineProperty(this, key, {
get() {
return data[key];
},
set(newVal) {
data[key] = newVal;
}
});
});
} |
JavaScript | function doneTalking(roomId, userName) {
return (dispatch) => {
if (socket) {
socket.send(JSON.stringify({
action: socketAction.TALKING_FINISHED,
roomId: roomId,
userName: userName
}))
dispatch({
type: STOP_TALKING, payload: {
action: socketAction.TALKING_FINISHED,
roomId: roomId,
userName: userName,
}
})
}
}
} | function doneTalking(roomId, userName) {
return (dispatch) => {
if (socket) {
socket.send(JSON.stringify({
action: socketAction.TALKING_FINISHED,
roomId: roomId,
userName: userName
}))
dispatch({
type: STOP_TALKING, payload: {
action: socketAction.TALKING_FINISHED,
roomId: roomId,
userName: userName,
}
})
}
}
} |
JavaScript | function userIsOnMobileDevice() {
var userAgentString = HtmlService.getUserAgent(),
mobileKeywords = [ 'mobile', 'android', 'iphone' ];
for (var j in mobileKeywords) {
if (userAgentString.toLowerCase().indexOf(mobileKeywords[j]) !== -1) return true;
}
return false;
} | function userIsOnMobileDevice() {
var userAgentString = HtmlService.getUserAgent(),
mobileKeywords = [ 'mobile', 'android', 'iphone' ];
for (var j in mobileKeywords) {
if (userAgentString.toLowerCase().indexOf(mobileKeywords[j]) !== -1) return true;
}
return false;
} |
JavaScript | function countdown() {
// call function to be executed every 1 second
let timeInterval = setInterval(function() {
// when last question is done, stops timer and calls All Done
if (questionNum === questionsArr.length) {
clearInterval(timeInterval);
}
// time left, decrement by 1
else if (timeLeft > 0) {
timeLeft--;
timerEl.textContent = timeLeft;
}
// stops timer and sets time left to 0, when reaches 0
else{
timeLeft === 0;
clearInterval(timeInterval);
timerEl.textContent = timeLeft;
qDisplayEl.remove();
allDone();
}
}, 1000);
} | function countdown() {
// call function to be executed every 1 second
let timeInterval = setInterval(function() {
// when last question is done, stops timer and calls All Done
if (questionNum === questionsArr.length) {
clearInterval(timeInterval);
}
// time left, decrement by 1
else if (timeLeft > 0) {
timeLeft--;
timerEl.textContent = timeLeft;
}
// stops timer and sets time left to 0, when reaches 0
else{
timeLeft === 0;
clearInterval(timeInterval);
timerEl.textContent = timeLeft;
qDisplayEl.remove();
allDone();
}
}, 1000);
} |
JavaScript | function condenseArray(arr) {
if (arr.length === 1) {
console.log(arr[0])
return;
}
for (let i = 0; i < arr.length - 1; i++) {
arr[i] = Number(arr[i]) + Number(arr[i + 1]);
}
arr.pop();
condenseArray(arr);
} | function condenseArray(arr) {
if (arr.length === 1) {
console.log(arr[0])
return;
}
for (let i = 0; i < arr.length - 1; i++) {
arr[i] = Number(arr[i]) + Number(arr[i + 1]);
}
arr.pop();
condenseArray(arr);
} |
JavaScript | function ageToPrice(typeDay, age) {
let isOld = age > 64 && age <= 122;
let isMidAge = age > 18 && age <= 64;
let isKid = age >= 0 && age <= 18;
let prices = {'Weekday' : ['12$', '18$', '12$'], 'Weekend' : ['15$', '20$', '15$'], 'Holiday' : ['5$', '12$', '10$'] };
return isOld ? prices[typeDay][2] : isMidAge ? prices[typeDay][1] : isKid ? prices[typeDay][0] : 'Error!';
} | function ageToPrice(typeDay, age) {
let isOld = age > 64 && age <= 122;
let isMidAge = age > 18 && age <= 64;
let isKid = age >= 0 && age <= 18;
let prices = {'Weekday' : ['12$', '18$', '12$'], 'Weekend' : ['15$', '20$', '15$'], 'Holiday' : ['5$', '12$', '10$'] };
return isOld ? prices[typeDay][2] : isMidAge ? prices[typeDay][1] : isKid ? prices[typeDay][0] : 'Error!';
} |
JavaScript | function multiplicationTable(num) {
for (let i = 1; i <= 10; i++) {
console.log(`${num} X ${i} = ${num * i}`);
}
} | function multiplicationTable(num) {
for (let i = 1; i <= 10; i++) {
console.log(`${num} X ${i} = ${num * i}`);
}
} |
JavaScript | activate (key) {
this.disposables.add(
atom.commands.add('atom-text-editor', {
[`rails-transporter-plus:open-${this.type}`]: () => this.trigger()
}),
atom.keymaps.add(`rails-transporter-plus/${this.type}`, {
'atom-text-editor': { [`${key}`]: `rails-transporter-plus:open-${this.type}` }
})
)
} | activate (key) {
this.disposables.add(
atom.commands.add('atom-text-editor', {
[`rails-transporter-plus:open-${this.type}`]: () => this.trigger()
}),
atom.keymaps.add(`rails-transporter-plus/${this.type}`, {
'atom-text-editor': { [`${key}`]: `rails-transporter-plus:open-${this.type}` }
})
)
} |
JavaScript | function handleDrag(event) {
var explorePanel = document.getElementById("explore_panel"),
renderPanel = document.getElementById("render_panel"),
handle = document.getElementById("split_handle");
// Sets limits to sizes of panes
if (event.clientX < window.innerWidth - 10 && event.clientX > 200) {
// Resizes panes based on mouse position
handle.style.left = 100 * (event.clientX / window.innerWidth) + '%';
explorePanel.style.width = 100 * (event.clientX / window.innerWidth) + '%';
renderPanel.style.width = 100 * ((window.innerWidth - event.clientX) / window.innerWidth) + '%';
// More taxing to update tabs here (updates tab sizes)
chromeTabs.layoutTabs();
}
} | function handleDrag(event) {
var explorePanel = document.getElementById("explore_panel"),
renderPanel = document.getElementById("render_panel"),
handle = document.getElementById("split_handle");
// Sets limits to sizes of panes
if (event.clientX < window.innerWidth - 10 && event.clientX > 200) {
// Resizes panes based on mouse position
handle.style.left = 100 * (event.clientX / window.innerWidth) + '%';
explorePanel.style.width = 100 * (event.clientX / window.innerWidth) + '%';
renderPanel.style.width = 100 * ((window.innerWidth - event.clientX) / window.innerWidth) + '%';
// More taxing to update tabs here (updates tab sizes)
chromeTabs.layoutTabs();
}
} |
JavaScript | function goToSearchView() {
// Hides file view components and shows search view components
let search = document.getElementById("search_view");
let searchBtn = document.getElementById("search_tab_btn");
let files = document.getElementById("files_view");
let filesBtn = document.getElementById("files_tab_btn");
search.classList.remove("hidden");
files.classList.add("hidden");
searchBtn.classList.add("open");
filesBtn.classList.remove("open");
} | function goToSearchView() {
// Hides file view components and shows search view components
let search = document.getElementById("search_view");
let searchBtn = document.getElementById("search_tab_btn");
let files = document.getElementById("files_view");
let filesBtn = document.getElementById("files_tab_btn");
search.classList.remove("hidden");
files.classList.add("hidden");
searchBtn.classList.add("open");
filesBtn.classList.remove("open");
} |
JavaScript | function saveHtmlFile() {
console.log("write file called");
// Gets iframe doc and html
let iframe = document.getElementById("html_disp");
let doc = iframe.contentDocument? iframe.contentDocument: iframe.contentWindow.document;
let htmlString = doc.documentElement.innerHTML;
// Writes html from iframe to file
fs.writeFile(open_files, htmlString, (err) => { // writes to file that is open in iframe
if (err) {
alert("An error ocurred updating the file" + err.message);
console.log(err);
return;
}
alert("The file has been succesfully saved");
});
} | function saveHtmlFile() {
console.log("write file called");
// Gets iframe doc and html
let iframe = document.getElementById("html_disp");
let doc = iframe.contentDocument? iframe.contentDocument: iframe.contentWindow.document;
let htmlString = doc.documentElement.innerHTML;
// Writes html from iframe to file
fs.writeFile(open_files, htmlString, (err) => { // writes to file that is open in iframe
if (err) {
alert("An error ocurred updating the file" + err.message);
console.log(err);
return;
}
alert("The file has been succesfully saved");
});
} |
JavaScript | function updateTab(node) {
if (tabMap.get(node.id)) {
chromeTabs.updateTab(tabMap.get(node.id), {
title: node.name,
id: node.id,
favicon: node.element.childNodes[0].getElementsByClassName('file-icon')[0].src
});
}
} | function updateTab(node) {
if (tabMap.get(node.id)) {
chromeTabs.updateTab(tabMap.get(node.id), {
title: node.name,
id: node.id,
favicon: node.element.childNodes[0].getElementsByClassName('file-icon')[0].src
});
}
} |
JavaScript | function renderPage(node) {
// Check if file exists
try {
// Throws error if file does not exist
let integrity = fs.statSync(node.path);
console.log(integrity);
// Add new tab
if (!(chromeMap.has(node.id))) {
chromeTabs.addTab({
title: node.name,
id: node.id,
favicon: node.element.childNodes[0].getElementsByClassName('file-icon')[0].src
});
chromeMap.set(node.id, node.path);
tabMap.set(node.id, chromeTabs.activeTabEl);
}
else {
chromeTabs.setCurrentTab(tabMap.get(node.id))
}
// Render web page
let disp = document.getElementById('html_disp');
disp.src = node.path;
// Saves the open file path for saving
open_files = node.path;
// update date last accessed
let currentTime = new Date();
let date = currentTime.yyyymmdd()
if (node.last_accessed != date) {
updateNode(node, "last_accessed", date);
}
}
// Path integrity has failed
catch (err) {
missingPath(node);
}
} | function renderPage(node) {
// Check if file exists
try {
// Throws error if file does not exist
let integrity = fs.statSync(node.path);
console.log(integrity);
// Add new tab
if (!(chromeMap.has(node.id))) {
chromeTabs.addTab({
title: node.name,
id: node.id,
favicon: node.element.childNodes[0].getElementsByClassName('file-icon')[0].src
});
chromeMap.set(node.id, node.path);
tabMap.set(node.id, chromeTabs.activeTabEl);
}
else {
chromeTabs.setCurrentTab(tabMap.get(node.id))
}
// Render web page
let disp = document.getElementById('html_disp');
disp.src = node.path;
// Saves the open file path for saving
open_files = node.path;
// update date last accessed
let currentTime = new Date();
let date = currentTime.yyyymmdd()
if (node.last_accessed != date) {
updateNode(node, "last_accessed", date);
}
}
// Path integrity has failed
catch (err) {
missingPath(node);
}
} |
JavaScript | function openInBrowser(node) {
// Opens path in another electron window (NOT IN USE)
//window.open(path, '_system');
// Check if file exists
try {
let integrity = fs.statSync(node.path);
console.log(integrity);
// Opens path in external browser
//shell.openExternal(path).then(_ => _);
shell.openItem(node.path);
// update date last accessed (if does not match currently)
let currentTime = new Date();
let date = currentTime.yyyymmdd()
if (node.last_accessed != date) {
updateNode(node, "last_accessed", date);
}
}
// Path integrity has failed
catch (err) {
missingPath(node);
}
} | function openInBrowser(node) {
// Opens path in another electron window (NOT IN USE)
//window.open(path, '_system');
// Check if file exists
try {
let integrity = fs.statSync(node.path);
console.log(integrity);
// Opens path in external browser
//shell.openExternal(path).then(_ => _);
shell.openItem(node.path);
// update date last accessed (if does not match currently)
let currentTime = new Date();
let date = currentTime.yyyymmdd()
if (node.last_accessed != date) {
updateNode(node, "last_accessed", date);
}
}
// Path integrity has failed
catch (err) {
missingPath(node);
}
} |
JavaScript | function renderSearchResults(results) {
// Clear results list
let resultListHtmlObj = document.getElementById("results_list");
resultListHtmlObj.innerHTML = "";
for (let i = 0; i < results.length; i++) {
let treeNode = $(`#${currentWorkspace}_tree`).tree('getNodeById', results[i].id);
resultListHtmlObj.appendChild(
createSearchResultListItem(treeNode));
}
// Show new result quantity
let resultsLabel = document.getElementById("results_label");
resultsLabel.innerText = `(${results.length} results)`
} | function renderSearchResults(results) {
// Clear results list
let resultListHtmlObj = document.getElementById("results_list");
resultListHtmlObj.innerHTML = "";
for (let i = 0; i < results.length; i++) {
let treeNode = $(`#${currentWorkspace}_tree`).tree('getNodeById', results[i].id);
resultListHtmlObj.appendChild(
createSearchResultListItem(treeNode));
}
// Show new result quantity
let resultsLabel = document.getElementById("results_label");
resultsLabel.innerText = `(${results.length} results)`
} |
JavaScript | function createSearchResultListItem(node) {
let resultNode = document.createElement("LI");
resultNode.className = "list-group-item"; // for bootstrap
// Result itself will be an anchor
let resultAnchor = document.createElement("A");
resultAnchor.className = node.id;
resultAnchor.appendChild(document.createTextNode(node.name));
// Opens context menu on right click of workspace button
resultAnchor.oncontextmenu = function (event) { spawnContextMenu("search-result", event, node) };
resultAnchor.ondblclick = function () {
renderPage(node);
}
resultNode.appendChild(resultAnchor);
return resultNode
} | function createSearchResultListItem(node) {
let resultNode = document.createElement("LI");
resultNode.className = "list-group-item"; // for bootstrap
// Result itself will be an anchor
let resultAnchor = document.createElement("A");
resultAnchor.className = node.id;
resultAnchor.appendChild(document.createTextNode(node.name));
// Opens context menu on right click of workspace button
resultAnchor.oncontextmenu = function (event) { spawnContextMenu("search-result", event, node) };
resultAnchor.ondblclick = function () {
renderPage(node);
}
resultNode.appendChild(resultAnchor);
return resultNode
} |
JavaScript | function spawnContextMenu(type, event, context) {
// Base context menu element
let menu = document.getElementById("context_menu");
// Base list element for context menu options
let menuList = menu.getElementsByClassName("menu-options")[0];
menuList.innerHTML = "";
// Initialize default positioning
let posX = 0;
let posY = 0;
// If event has node associated with it (jqtree event)
if (type == "file-tree") {
// Menu options for all nodes
menuList.appendChild(makeContextMenuOption("Rename", function () { openModal("single-input", "Rename", ["New Name: "], function (name) { updateNode(event.node, "name", name) }) }));
menuList.appendChild(makeContextMenuOption("Delete", function () { openModal("confirmation", "Delete", ["Are you sure you want to delete this?"], function () { deleteNode(event.node) }) }));
/*menuList.appendChild(makeContextMenuOption("cut", function () { alert("implement cut paste") }));*/
// Menu options for folder nodes only
if (event.node.type == "folder") {
menuList.appendChild(makeContextMenuOption("Create Folder", function() { openModal('single-input', 'New Folder', ['Folder Name: '], function (name) { createFolder(event.node, name); })}));
menuList.appendChild(makeContextMenuOption("Import File", function () { get_file(event.node) }));
menuList.appendChild(makeContextMenuOption("Import Folder", function () { get_folder("folder", event.node) }));
menuList.appendChild(makeContextMenuOption("Import Web-Scrapbook", function () { get_folder("wsb", event.node) }));
menuList.appendChild(makeContextMenuOption("Import Scrapbook", function () { get_folder("sb", event.node) }));
}
// Menu options for file nodes only
else if (event.node.type == "file") {
menuList.appendChild(makeContextMenuOption("Open in Browser", function () { openInBrowser(event.node) }));
menuList.appendChild(makeContextMenuOption("Get Info", function () { openModal("get-info", "Information", [event.node], null) }));
}
// Set menu position based on click event
posX = event.click_event.pageX;
posY = event.click_event.pageY;
}
// Right click on workspace button
else if (type == "workspace-button") {
// Menu options for all workspaces
menuList.appendChild(makeContextMenuOption("Rename", function () { openModal("single-input", "Rename", ["New Name: "], function (name) { renameWorkspace(name, context) }) }));
// Check if backend is not indexing
if (workspaceQueues[context].length != 0) {
let opt = document.createElement("LI");
opt.className = "menu-option";
opt.appendChild(document.createTextNode('Delete'));
opt.style.cursor = 'not-allowed';
menuList.appendChild(opt)
} else {
menuList.appendChild(makeContextMenuOption("Delete", function () { openModal("confirmation", "Delete", ["Are you sure you want to delete this?"], function () { deleteWorkspace(context) })}));
}
//menuList.appendChild(makeContextMenuOption("cut", function () { alert("implement cut paste") }));
// Set menu position based on click event
posX = event.pageX;
posY = event.pageY;
}
// Right click on search result
else if (type == "search-result") {
// Menu options for all search results
menuList.appendChild(makeContextMenuOption("Preview", function() { renderPage(context) }));
menuList.appendChild(makeContextMenuOption("Open in Browser", function() { openInBrowser(context) }));
menuList.appendChild(makeContextMenuOption("Show in Tree", function() { seeSearchResultInTree(context) }));
menuList.appendChild(makeContextMenuOption("Get Info", function () { openModal("get-info", "Information", [context], null) }));
// Set menu position based on click event
posX = event.pageX;
posY = event.pageY;
}
// Window height and width
let windWidth = window.innerWidth;
let windHeight = window.innerHeight;
// Display and position context menu element
menu.style.left = posX + "px";
if (posY > windHeight / 2) {
menu.style.top = (posY - menu.offsetHeight) + "px";
}
else {
menu.style.top = posY + "px";
}
menu.style.display = "block";
} | function spawnContextMenu(type, event, context) {
// Base context menu element
let menu = document.getElementById("context_menu");
// Base list element for context menu options
let menuList = menu.getElementsByClassName("menu-options")[0];
menuList.innerHTML = "";
// Initialize default positioning
let posX = 0;
let posY = 0;
// If event has node associated with it (jqtree event)
if (type == "file-tree") {
// Menu options for all nodes
menuList.appendChild(makeContextMenuOption("Rename", function () { openModal("single-input", "Rename", ["New Name: "], function (name) { updateNode(event.node, "name", name) }) }));
menuList.appendChild(makeContextMenuOption("Delete", function () { openModal("confirmation", "Delete", ["Are you sure you want to delete this?"], function () { deleteNode(event.node) }) }));
/*menuList.appendChild(makeContextMenuOption("cut", function () { alert("implement cut paste") }));*/
// Menu options for folder nodes only
if (event.node.type == "folder") {
menuList.appendChild(makeContextMenuOption("Create Folder", function() { openModal('single-input', 'New Folder', ['Folder Name: '], function (name) { createFolder(event.node, name); })}));
menuList.appendChild(makeContextMenuOption("Import File", function () { get_file(event.node) }));
menuList.appendChild(makeContextMenuOption("Import Folder", function () { get_folder("folder", event.node) }));
menuList.appendChild(makeContextMenuOption("Import Web-Scrapbook", function () { get_folder("wsb", event.node) }));
menuList.appendChild(makeContextMenuOption("Import Scrapbook", function () { get_folder("sb", event.node) }));
}
// Menu options for file nodes only
else if (event.node.type == "file") {
menuList.appendChild(makeContextMenuOption("Open in Browser", function () { openInBrowser(event.node) }));
menuList.appendChild(makeContextMenuOption("Get Info", function () { openModal("get-info", "Information", [event.node], null) }));
}
// Set menu position based on click event
posX = event.click_event.pageX;
posY = event.click_event.pageY;
}
// Right click on workspace button
else if (type == "workspace-button") {
// Menu options for all workspaces
menuList.appendChild(makeContextMenuOption("Rename", function () { openModal("single-input", "Rename", ["New Name: "], function (name) { renameWorkspace(name, context) }) }));
// Check if backend is not indexing
if (workspaceQueues[context].length != 0) {
let opt = document.createElement("LI");
opt.className = "menu-option";
opt.appendChild(document.createTextNode('Delete'));
opt.style.cursor = 'not-allowed';
menuList.appendChild(opt)
} else {
menuList.appendChild(makeContextMenuOption("Delete", function () { openModal("confirmation", "Delete", ["Are you sure you want to delete this?"], function () { deleteWorkspace(context) })}));
}
//menuList.appendChild(makeContextMenuOption("cut", function () { alert("implement cut paste") }));
// Set menu position based on click event
posX = event.pageX;
posY = event.pageY;
}
// Right click on search result
else if (type == "search-result") {
// Menu options for all search results
menuList.appendChild(makeContextMenuOption("Preview", function() { renderPage(context) }));
menuList.appendChild(makeContextMenuOption("Open in Browser", function() { openInBrowser(context) }));
menuList.appendChild(makeContextMenuOption("Show in Tree", function() { seeSearchResultInTree(context) }));
menuList.appendChild(makeContextMenuOption("Get Info", function () { openModal("get-info", "Information", [context], null) }));
// Set menu position based on click event
posX = event.pageX;
posY = event.pageY;
}
// Window height and width
let windWidth = window.innerWidth;
let windHeight = window.innerHeight;
// Display and position context menu element
menu.style.left = posX + "px";
if (posY > windHeight / 2) {
menu.style.top = (posY - menu.offsetHeight) + "px";
}
else {
menu.style.top = posY + "px";
}
menu.style.display = "block";
} |
JavaScript | function makeContextMenuOption(text, func) {
let opt = document.createElement("LI");
opt.className = "menu-option";
opt.appendChild(document.createTextNode(text));
opt.onclick = func;
return opt;
} | function makeContextMenuOption(text, func) {
let opt = document.createElement("LI");
opt.className = "menu-option";
opt.appendChild(document.createTextNode(text));
opt.onclick = func;
return opt;
} |
JavaScript | function postRequest(path, context, json_obj) {
console.log("Post Request called: ", path, context, json_obj);
var start = performance.now();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// For latency
var end = performance.now()
console.log(`Index time: ${end-start}`);
// Handles response
handleResponse(xhttp.responseText, context);
}
};
xhttp.open("POST", "http://localhost:5000/" + path, true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(JSON.stringify(json_obj));
} | function postRequest(path, context, json_obj) {
console.log("Post Request called: ", path, context, json_obj);
var start = performance.now();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// For latency
var end = performance.now()
console.log(`Index time: ${end-start}`);
// Handles response
handleResponse(xhttp.responseText, context);
}
};
xhttp.open("POST", "http://localhost:5000/" + path, true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(JSON.stringify(json_obj));
} |
JavaScript | function addToQueue(endpoint, context, jsonObj, guid) {
// If queue is empty, add to queue run command immediately
if (workspaceQueues[guid].length == 0) {
workspaceQueues[guid].push([endpoint, context, jsonObj]);
// Enabling overlay to disable search functionality if command requires indexing
queueOverlay("index");
// Make post request
postRequest(endpoint, context, jsonObj);
}
// If queue is not empty, add command to queue and wait
else {
workspaceQueues[guid].push([endpoint, context, jsonObj]);
}
console.log("Added", [endpoint, context], "to " + guid + "queue: " + workspaceQueues[guid].length);
} | function addToQueue(endpoint, context, jsonObj, guid) {
// If queue is empty, add to queue run command immediately
if (workspaceQueues[guid].length == 0) {
workspaceQueues[guid].push([endpoint, context, jsonObj]);
// Enabling overlay to disable search functionality if command requires indexing
queueOverlay("index");
// Make post request
postRequest(endpoint, context, jsonObj);
}
// If queue is not empty, add command to queue and wait
else {
workspaceQueues[guid].push([endpoint, context, jsonObj]);
}
console.log("Added", [endpoint, context], "to " + guid + "queue: " + workspaceQueues[guid].length);
} |
JavaScript | function initTrees(workspaces) {
workspaces.forEach((workspace) => {
readTree(workspace);
});
} | function initTrees(workspaces) {
workspaces.forEach((workspace) => {
readTree(workspace);
});
} |
JavaScript | function readTree(workspace) {
console.log('read_tree called');
fs.readFile(appDataPath + "/workspace_repo/" + workspace + "/tree.json", 'utf-8', (err, data) => {
if (err) {
alert("An error occurred reading the tree file :" + err.message);
return;
}
console.log("The tree file content is : " + data);
// If json contains tree data: make a tree
if (data.length > 0) {
makeTree(workspace, JSON.parse(data));
}
});
} | function readTree(workspace) {
console.log('read_tree called');
fs.readFile(appDataPath + "/workspace_repo/" + workspace + "/tree.json", 'utf-8', (err, data) => {
if (err) {
alert("An error occurred reading the tree file :" + err.message);
return;
}
console.log("The tree file content is : " + data);
// If json contains tree data: make a tree
if (data.length > 0) {
makeTree(workspace, JSON.parse(data));
}
});
} |
JavaScript | function createFolder(node, folderName) {
let newFolder = {
name: folderName,
type: 'folder',
id: uuid4()
};
let $tree = $('#' + currentWorkspace + '_tree');
// If parent node
if (node) {
$tree.tree(
'appendNode',
newFolder,
node
);
}
// If root
else {
if ($tree.tree('getTree')) {
$tree.tree(
'appendNode',
newFolder,
);
}
else {
makeTree(currentWorkspace, [newFolder]);
}
}
// Write tree data to tree json file in the workspace repo
treeToJson(currentWorkspace);
treeToBackupJson(currentWorkspace);
// Adds tooltip logic to tree (when adding a folder node in this case)
addTreeTooltips(currentWorkspace);
} | function createFolder(node, folderName) {
let newFolder = {
name: folderName,
type: 'folder',
id: uuid4()
};
let $tree = $('#' + currentWorkspace + '_tree');
// If parent node
if (node) {
$tree.tree(
'appendNode',
newFolder,
node
);
}
// If root
else {
if ($tree.tree('getTree')) {
$tree.tree(
'appendNode',
newFolder,
);
}
else {
makeTree(currentWorkspace, [newFolder]);
}
}
// Write tree data to tree json file in the workspace repo
treeToJson(currentWorkspace);
treeToBackupJson(currentWorkspace);
// Adds tooltip logic to tree (when adding a folder node in this case)
addTreeTooltips(currentWorkspace);
} |
JavaScript | function deleteNode(node) {
console.log(node);
var toDeleteFromIdx = getChildFileNodes(node);
console.log(toDeleteFromIdx);
// Update tree
$('#' + currentWorkspace + '_tree').tree('removeNode', node);
// Write tree data to tree json file in the workspace repo
//treeToJson(currentWorkspace);
// Adds tooltip logic to tree (when deleting a node in this case)
addTreeTooltips(currentWorkspace);
// Sends index command, node Id, and current workspace to backend
// Adds command to queue
addToQueue("index/delete/" + currentWorkspace, null, {'json_lst': toDeleteFromIdx}, currentWorkspace);
} | function deleteNode(node) {
console.log(node);
var toDeleteFromIdx = getChildFileNodes(node);
console.log(toDeleteFromIdx);
// Update tree
$('#' + currentWorkspace + '_tree').tree('removeNode', node);
// Write tree data to tree json file in the workspace repo
//treeToJson(currentWorkspace);
// Adds tooltip logic to tree (when deleting a node in this case)
addTreeTooltips(currentWorkspace);
// Sends index command, node Id, and current workspace to backend
// Adds command to queue
addToQueue("index/delete/" + currentWorkspace, null, {'json_lst': toDeleteFromIdx}, currentWorkspace);
} |
JavaScript | function updateNode(node, key, value) {
console.log("update node called: ");
console.log(node);
let tempObj = {};
tempObj[key] = value;
// Update the node
$('#' + currentWorkspace + '_tree').tree(
'updateNode',
node,
tempObj
);
// Updates chrome tab for the node
updateTab(node)
// Write tree data to tree json file in the workspace repo
//treeToJson(currentWorkspace);
// Adds tooltip logic to tree (when when updating a node in this case)
addTreeTooltips(currentWorkspace);
// Trigger reindexing of node
if (node.type == "file") {
// Convert to required format for JSON.stringify (no circular relationships in JSON)
var sendData = {
id: node.id,
path: node.path,
name: node.name,
legacy_ingest: node.legacy_ingest,
ingest: node.ingest,
source: node.source,
icon: node.icon,
last_accessed: node.last_accessed
}
console.log("Send data: ");
console.log(sendData);
// Sends index command, node Id, and current workspace to backend
addToQueue("index/update/" + currentWorkspace, null, {"json_lst": [sendData]}, currentWorkspace);
}
} | function updateNode(node, key, value) {
console.log("update node called: ");
console.log(node);
let tempObj = {};
tempObj[key] = value;
// Update the node
$('#' + currentWorkspace + '_tree').tree(
'updateNode',
node,
tempObj
);
// Updates chrome tab for the node
updateTab(node)
// Write tree data to tree json file in the workspace repo
//treeToJson(currentWorkspace);
// Adds tooltip logic to tree (when when updating a node in this case)
addTreeTooltips(currentWorkspace);
// Trigger reindexing of node
if (node.type == "file") {
// Convert to required format for JSON.stringify (no circular relationships in JSON)
var sendData = {
id: node.id,
path: node.path,
name: node.name,
legacy_ingest: node.legacy_ingest,
ingest: node.ingest,
source: node.source,
icon: node.icon,
last_accessed: node.last_accessed
}
console.log("Send data: ");
console.log(sendData);
// Sends index command, node Id, and current workspace to backend
addToQueue("index/update/" + currentWorkspace, null, {"json_lst": [sendData]}, currentWorkspace);
}
} |
JavaScript | function treeToJson(workspace) {
console.log("tree to json called: " + workspace);
// Gets tree json of current workspace tree
treeJson = $('#' + workspace + '_tree').tree('toJson');
// Writes to tree json
fs.writeFile(appDataPath + "/workspace_repo/" + workspace + "/tree.json", treeJson, (err) => {
if (err) {
alert("An error ocurred updating the file" + err.message);
console.log(err);
return;
}
console.log("The tree json has been succesfully written: " + workspace);
});
} | function treeToJson(workspace) {
console.log("tree to json called: " + workspace);
// Gets tree json of current workspace tree
treeJson = $('#' + workspace + '_tree').tree('toJson');
// Writes to tree json
fs.writeFile(appDataPath + "/workspace_repo/" + workspace + "/tree.json", treeJson, (err) => {
if (err) {
alert("An error ocurred updating the file" + err.message);
console.log(err);
return;
}
console.log("The tree json has been succesfully written: " + workspace);
});
} |
JavaScript | function treeToBackupJson(workspace) {
console.log("tree to json called: " + workspace);
// Gets tree json of current workspace tree
treeJson = $('#' + workspace + '_tree').tree('toJson');
// Writes to tree_backup.json
fs.writeFile(appDataPath + "/workspace_repo/" + workspace + "/tree_backup.json", treeJson, (err) => {
if (err) {
alert("An error ocurred updating the file" + err.message);
console.log(err);
return;
}
console.log("The tree backup json has been succesfully written: " + workspace);
});
} | function treeToBackupJson(workspace) {
console.log("tree to json called: " + workspace);
// Gets tree json of current workspace tree
treeJson = $('#' + workspace + '_tree').tree('toJson');
// Writes to tree_backup.json
fs.writeFile(appDataPath + "/workspace_repo/" + workspace + "/tree_backup.json", treeJson, (err) => {
if (err) {
alert("An error ocurred updating the file" + err.message);
console.log(err);
return;
}
console.log("The tree backup json has been succesfully written: " + workspace);
});
} |
JavaScript | function scrollToNodeInTree(node) {
// Open up all parent folders if a node is nested
let parent = node.parent
while (parent) {
$(`#${currentWorkspace}_tree`).tree('openNode', parent);
parent = parent.parent
}
// Scroll to node
$(`#${currentWorkspace}_tree`).tree('scrollToNode', node);
// Highlight the node
$(`#${currentWorkspace}_tree`).tree('addToSelection', node);
// Unselects node onclick
document.addEventListener('click', tempDeselectNode, true);
function tempDeselectNode() {
console.log("temp deselect called");
let nodeTemp = $(`#${currentWorkspace}_tree`).tree('getNodeById', node.id);
$(`#${currentWorkspace}_tree`).tree('removeFromSelection', nodeTemp);
document.removeEventListener('click', tempDeselectNode, true);
}
} | function scrollToNodeInTree(node) {
// Open up all parent folders if a node is nested
let parent = node.parent
while (parent) {
$(`#${currentWorkspace}_tree`).tree('openNode', parent);
parent = parent.parent
}
// Scroll to node
$(`#${currentWorkspace}_tree`).tree('scrollToNode', node);
// Highlight the node
$(`#${currentWorkspace}_tree`).tree('addToSelection', node);
// Unselects node onclick
document.addEventListener('click', tempDeselectNode, true);
function tempDeselectNode() {
console.log("temp deselect called");
let nodeTemp = $(`#${currentWorkspace}_tree`).tree('getNodeById', node.id);
$(`#${currentWorkspace}_tree`).tree('removeFromSelection', nodeTemp);
document.removeEventListener('click', tempDeselectNode, true);
}
} |
JavaScript | function replaceFilePath(node, newPath) {
// TEMPORARY UNTIL INDEXES ON NODES
updateNode(node, "path", newPath);
// Renders page
renderPage(node);
/*$('#' + currentWorkspace + '_tree').tree(
'updateNode',
node,
{
path: newPath
}
);
// Writes to tree file
treeToJson(currentWorkspace);
// Renders page
renderPage(node);
// Writes to tree backup file
treeToBackupJson(currentWorkspace);
// Adds tooltip logic to tree (when first making the tree in this case)
addTreeTooltips(currentWorkspace);*/
} | function replaceFilePath(node, newPath) {
// TEMPORARY UNTIL INDEXES ON NODES
updateNode(node, "path", newPath);
// Renders page
renderPage(node);
/*$('#' + currentWorkspace + '_tree').tree(
'updateNode',
node,
{
path: newPath
}
);
// Writes to tree file
treeToJson(currentWorkspace);
// Renders page
renderPage(node);
// Writes to tree backup file
treeToBackupJson(currentWorkspace);
// Adds tooltip logic to tree (when first making the tree in this case)
addTreeTooltips(currentWorkspace);*/
} |
JavaScript | function enableOverlay() {
document.getElementById('overlay-label').innerHTML = 'indexing...';
$('#overlay').show();
$('#overlay-message').css('display', 'flex');
} | function enableOverlay() {
document.getElementById('overlay-label').innerHTML = 'indexing...';
$('#overlay').show();
$('#overlay-message').css('display', 'flex');
} |
JavaScript | function addTreeTooltips(workspace) {
let titles = document.getElementsByClassName("jqtree-element"); // jqtree-title (alt)
for (let x = 0; x < titles.length; x++) {
titles[x].onmousemove = function (e) {
// Clears global timeout on move
if (delay) {
clearTimeout(delay);
}
// Begins new timeout
delay = setTimeout(function () {
// Gets the node corresponding to the element
let node = $('#' + workspace + '_tree').tree('getNodeByHtmlElement', e.target);
// Sets content for tooltip
let content = [node.name];
if (node.source) {
content.push("<i>" + node.source + "</i>");
}
//content.push("(www.example.com)"); // TEMPORARY EXAMPLE
// Spawns popup for tooltip
spawnTooltip(e, content);
}, 600)
}
// Prevents spawning of tooltip if hover breaks
titles[x].onmouseleave = function (e) {
if (delay) {
clearTimeout(delay);
}
}
}
} | function addTreeTooltips(workspace) {
let titles = document.getElementsByClassName("jqtree-element"); // jqtree-title (alt)
for (let x = 0; x < titles.length; x++) {
titles[x].onmousemove = function (e) {
// Clears global timeout on move
if (delay) {
clearTimeout(delay);
}
// Begins new timeout
delay = setTimeout(function () {
// Gets the node corresponding to the element
let node = $('#' + workspace + '_tree').tree('getNodeByHtmlElement', e.target);
// Sets content for tooltip
let content = [node.name];
if (node.source) {
content.push("<i>" + node.source + "</i>");
}
//content.push("(www.example.com)"); // TEMPORARY EXAMPLE
// Spawns popup for tooltip
spawnTooltip(e, content);
}, 600)
}
// Prevents spawning of tooltip if hover breaks
titles[x].onmouseleave = function (e) {
if (delay) {
clearTimeout(delay);
}
}
}
} |
JavaScript | function usernamePrompt() {
dialogs.prompt("Please enter your desired username and confirm", "user").then(function (r) {
if (r.result) {
appSettings.set("username", r.text);
}
});
} | function usernamePrompt() {
dialogs.prompt("Please enter your desired username and confirm", "user").then(function (r) {
if (r.result) {
appSettings.set("username", r.text);
}
});
} |
JavaScript | function update(protocol) {
DEFS.VERSION = protocol.VERSION
DEFS.TYPES = protocol.TYPES
DEFS.SCHEMES_NAMES = protocol.SCHEMES_NAMES
DEFS.SCHEMES = protocol.SCHEMES
DEFS.RPC = protocol.RPC
DEFS.compile()
} | function update(protocol) {
DEFS.VERSION = protocol.VERSION
DEFS.TYPES = protocol.TYPES
DEFS.SCHEMES_NAMES = protocol.SCHEMES_NAMES
DEFS.SCHEMES = protocol.SCHEMES
DEFS.RPC = protocol.RPC
DEFS.compile()
} |
JavaScript | function payload(msg) {
return JSON.stringify({
op: "publish",
topic: "/foo",
msg: msg
});
} | function payload(msg) {
return JSON.stringify({
op: "publish",
topic: "/foo",
msg: msg
});
} |
JavaScript | function runBenchmark(name, benchmarkData) {
console.log(name);
// encode object to CBOR byte array
console.time("CBOR encode");
var x = CBOR.encode(benchmarkData);
console.timeEnd("CBOR encode");
// payload as base64
console.time("CBOR payload");
var xp = payload(arrayBufferToBase64(x));
console.timeEnd("CBOR payload");
// payload object as JSON
console.time("JSON payload");
var zp = payload(benchmarkData);
console.timeEnd("JSON payload");
// size over the wire
console.log("CBOR payd:", xp.length, "bytes");
console.log("JSON payd:", zp.length, "bytes");
// depayload from base64
console.time("CBOR depay");
var xd = base64ToArrayBuffer(JSON.parse(xp).msg);
console.timeEnd("CBOR depay");
// decode CBOR byte array to object
console.time("CBOR decode");
var x1 = CBOR.decode(xd);
console.timeEnd("CBOR decode");
// depayload object from JSON
console.time("JSON depay");
var z1 = JSON.parse(zp).msg;
console.timeEnd("JSON depay");
} | function runBenchmark(name, benchmarkData) {
console.log(name);
// encode object to CBOR byte array
console.time("CBOR encode");
var x = CBOR.encode(benchmarkData);
console.timeEnd("CBOR encode");
// payload as base64
console.time("CBOR payload");
var xp = payload(arrayBufferToBase64(x));
console.timeEnd("CBOR payload");
// payload object as JSON
console.time("JSON payload");
var zp = payload(benchmarkData);
console.timeEnd("JSON payload");
// size over the wire
console.log("CBOR payd:", xp.length, "bytes");
console.log("JSON payd:", zp.length, "bytes");
// depayload from base64
console.time("CBOR depay");
var xd = base64ToArrayBuffer(JSON.parse(xp).msg);
console.timeEnd("CBOR depay");
// decode CBOR byte array to object
console.time("CBOR decode");
var x1 = CBOR.decode(xd);
console.timeEnd("CBOR decode");
// depayload object from JSON
console.time("JSON depay");
var z1 = JSON.parse(zp).msg;
console.timeEnd("JSON depay");
} |
JavaScript | function add_id_to_all_forms(){
var iteration = 1; // Iteration of forms
var id_text = ""; // Auxilary variable
$("form").each(function(){
id_text = "form_" + iteration; // Variable with prepared ID
if(!$(this).attr('id')){ // If form doesn't have ID already...
$(this).attr('id',id_text); // Add automatically generated ID
iteration++;
}
});
} | function add_id_to_all_forms(){
var iteration = 1; // Iteration of forms
var id_text = ""; // Auxilary variable
$("form").each(function(){
id_text = "form_" + iteration; // Variable with prepared ID
if(!$(this).attr('id')){ // If form doesn't have ID already...
$(this).attr('id',id_text); // Add automatically generated ID
iteration++;
}
});
} |
Subsets and Splits