anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
The DOM updates done when an operation finishes are batched so that the minimum number of relayouts are required. | function endOperations(group) {
var ops = group.ops;
for (var i = 0; i < ops.length; i++) // Read DOM
{ endOperation_R1(ops[i]); }
for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
{ endOperation_W1(ops[i$1]); }
for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
{ end... |
Used only with promisify. Transform callback to promise result. | function translateError(err, result) {
if (!err) {
return this.resolve(result);
}
if (typeof err === 'object') {
if (err instanceof Error) {
return this.reject(ret);
}
return this.reject(Object.assign(new Error(err.message), { errCode: err.errCode }));
} else ... |
creates conservation at x, y with type x, y are given in coordinates from 0 to 1 | constructor(x, y) {
this.x = x;
this.y = y;
} |
NEW build layers function | function drawLayer(destinationTexture, layer) {
// if isColor = true
if(layer.isColor){
drawColorOnMask(destinationTexture, layer);
texture.needsUpdate = true;
}
// if isColor = false
else if (!layer.isColor) {
drawGraphicOnMask(destinationText... |
NOTE: we should probably more this routine to the synthetic shadow folder and get the allocation to be cached by in the elm instead of in the VM | function allocateInSlot$1(vm, children) {
{
assert$1.invariant(isObject$1$1(vm.cmpSlots), `When doing manual allocation, there must be a cmpSlots object available.`);
}
const {
cmpSlots: oldSlots
} = vm;
const cmpSlots = vm.cmpSlots = create$3(null);
for (let i = 0, len = children.... |
when component mounts, first thing it does is fetch all existing data in our db then we incorporate a polling logic so that we can easily see if our db has changed and implement those changes into our UI | componentDidMount() {
this.getDataFromDb();
if (!this.state.intervalIsSet) {
let interval = setInterval(this.getDataFromDb, 1000);
this.setState({ intervalIsSet: interval });
}
} |
Update the machine recipe URL | updateMachineRecipeLocation(recipeURL) {
if (!this.copyOriginFactory) {
return;
}
let machineConfig = this.copyOriginFactory.workspace.environments[0].machines[0];
machineConfig.source.type = 'recipe';
machineConfig.source.location = recipeURL;
this.updateFactory();
} |
Delete the true_false using id and update the table | function deletetrue_false(id) {
let f = confirm("Are you Sure");
if (f == true) {
firebase
.database()
.ref("Types")
.child(_typeId)
.child(id)
.remove();
firebase
.database()
.ref("Test")
.child(_courseID)
.child("Levels")
.child(_levelID)
.... |
Imposes additional restrictions for `canGoToStep` in current navigation mode. The base implementation allows transition iff the given step is navigable from the navigation bar (see `isNavigable`). However, in some navigation modes `canTransitionToStep` can be more relaxed to allow navigation to certain steps by previou... | canTransitionToStep(wizard, destinationIndex) {
return this.isNavigable(wizard, destinationIndex);
} |
date from iso format | function configFromISO(config) {
var i, l,
string = config._i,
match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
allowTime, dateFormat, timeFormat, tzFormat;
if (match) {
getParsingFlags(config).iso = true;
for (i = 0, l = ... |
o is the this | function Obj() { //函数有自己的this
const f = ()=>console.log(this);
f();
} |
Renders the AWS CloudFormation properties of an `AWS::SSM::PatchBaseline` resource | function cfnPatchBaselinePropsToCloudFormation(properties) {
if (!cdk.canInspect(properties)) {
return properties;
}
CfnPatchBaselinePropsValidator(properties).assertSuccess();
return {
Name: cdk.stringToCloudFormation(properties.name),
ApprovalRules: cfnPatchBaselineRuleGroupPro... |
POST the photo name and data to /queue_photos route via an AJAX request | function queuePhotos(file, index, length) {
$.ajax({
url: "/queue_photos",
type: 'POST',
data: {filename: file.filename, data: file.data},
success: function(data, status, xhr) {},
complete: function(data, status, xhr) {
if (index + 1 ==... |
get the list of all players excluding current player | getOtherPlayerList() {
let observable = new rxjs__WEBPACK_IMPORTED_MODULE_2__["Observable"](observer => {
this.socket.on('serverUpdatePlayerList', (msg) => {
var output = this.getAllOtherPlayersList(msg);
observer.next(output);
});
return () =>... |
Safely install SIGINT listener. NOTE: this will only work on OSX and Linux. | function _safely_install_sigint_listener() {
const listeners = process.listeners(SIGINT);
const existingListeners = [];
for (let i = 0, length = listeners.length; i < length; i++) {
const lstnr = listeners[i];
/* istanbul ignore else */
if (lstnr.name === '_tmp$sigint_listener') {
existingListe... |
Function to change display property to none. | function hide(Id){
document.getElementById(Id).style.display = "none";
} |
cargar el calendario atraves de un clase jquery para funciones tienen que estar cargada la clase | function Calendar_Class(ClassCSS){
jq( "."+ClassCSS ).datepicker();
} |
exam search by exam name | practTableSearch(event) {
event.preventDefault();
var searchText = event.currentTarget.value;
var filter = searchText.toUpperCase();
var table = document.getElementById("ExamListTable");
var tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't m... |
Helper function to rotate the bird depending on their vertical velocity | function rotateAndPaintImage ( context, image, angleInRad , bird ) {
var TO_RADIANS = Math.PI/180;
var yAdjuster = angleInRad < 0 ? (-angleInRad/5) : (-angleInRad/3);
var xAdjuster = angleInRad > angleInRad/2.5 ? angleInRad/3 : 0
var middleX = bird.aabb.x + xAdjuster;
var middle... |
Building the list of items | function start() {
connection.query("SELECT * FROM products", function(err, res) {
if (err) throw err;
console.log(
"--------------------------------------------------------------------------------"
);
for (var i = 0; i < res.length; i++) {
console.log(
"ID: " +
res[i].it... |
You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return 1. | function findEvenIndex(arr) {
if (arr.length < 1 || !arr) {
return -1;
}
for (let i = 0; i < arr.length; i++) {
if (
arr.slice(0, i).reduce((x, y) => x + y, 0) ===
arr.slice(i + 1).reduce((x, y) => x + y, 0)
) {
return i;
}
}
return... |
$asyncbind has multiple uses, depending on the parameter list. It is in Function.prototype, so 'this' is always a function 1) If called with a single argument (this), it is used when defining an async function to ensure when it is invoked, the correct 'this' is present, just like "bind". For legacy reasons, 'this' is g... | function processIncludes(includes,input) {
var src = input.toString() ;
var t = "return "+src ;
var args = src.match(/.*\(([^)]*)\)/)[1] ;
var re = /['"]!!!([^'"]*)['"]/g ;
var m = [] ;
while (1) {
var mx = re.exec(t) ;
if (mx)
m.push(mx) ;
else break ;
}
... |
Copies a specified amount of characters from the list of buffered data chunks. This function is designed to be inlinable, so please take care when making changes to the function body. | function copyFromBufferString(n, list) {
var p = list.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
... |
This should be overriden. | _equal(a, b) {
return a === b;
} |
Get a record by id | getById (url, id) {
url = `${url}/${id}?f=json`;
return this.request(url, {method: 'GET'});
} |
sec_exponent = hash(passphrase) XOR hash(random_seed) | function genCalcHash() {
//document.write("<br>random_seed "+random_seed); //test random_seed value in this function.
if(random_seed == false){//if random_seed not active
//using original brainwallet function
var hash = Crypto.SHA256($('#pass').val());
}else{
//using brainwallet with specifie... |
Jump the skier, but do nothing if already jumping | jump() {
if (this.isJumping()) {
return;
}
this.verticalVelocity = Constants.SKIER_JUMP_VELOCITY;
} |
Buat generasi population = generate_population(5) fitness_values = calculate_population_fitness(population) mating_probability = 0.7 mutation_probability = 0.001 console.log(create_generation(population, fitness_values, mating_probability, mutation_probability)) | function create_generation(population, fitnesses, mating_probability, mutation_probability) {
mating_population = sample_population(population, fitnesses, mating_probability)
parents = crossover(mating_population)
preserved_population = preserve_top(population, fitnesses, (1 - mating_probability).toFixed(1))
//... |
draws a circle around a designated point to show locations needed to get to | function createCircle(map, center, place) {
let circle = new google.maps.Circle({
map: map,
center: {lat: center.placeLat, lng: center.placeLng},
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
radi... |
closes the connection, this is used once you leave the page/closes the tab/closes the browser | function closeConnection() {
//alert("closing");
if (socket != null) {
socket.close();
}
} |
global, used for tooltips | function displayLoadGraph(node_id) {
if (! (node_id in nodes)) {
consoleWarn("Cannot display load graph for unknown node:", node_id);
return;
}
load_redraw = false;
var node_name = node_id;
var low_threshold = 0;
var high_threshold = 100;
var max_tps = 4.999;
if ("state" ... |
================================================================================ Create Pokemon Card ================================================================================ | function CreatePokemonCard (pkmn) {
var output = "";
// create the output string
if (pkmn.party) {
output += "<div class='characterSheetPartyFormatter'>";
} else {
output += "<div class='characterSheetFormatter'>";
}
// pokemon name, type, and gender
output += "<div cla... |
appending options in to and from | function appendCurrency(input) {
var curr = input.currencies;
for (key in curr) {
$("#from").append(
"<option value = " + key + ">" + key + " " + curr[key] + "</option>"
);
}
for (key in curr) {
$("#to").append(
"<option value = " + key + ">" + key + " " + curr[key] + "</option>"
);
... |
run start(true) to initiate a call | function initiateCall() {
prepareCall();
navigator.getUserMedia({
"audio": false,
"video": {
mediaSource: "screen",
width: 800,
height: 600
}
}, function(stream) {
localVideoStream = stream;
peerConn.addStream(localVideoStream);
... |
Convert a raw string to a hex string | function rstr2hex(input) {
var hex_tab = '0123456789abcdef',
output = '',
x,
i;
for (i = 0; i < input.length; i += 1) {
x = input.charCodeAt(i);
output += hex_tab.charAt((x >>> 4) & 0x0F) +
hex_tab.charAt(x & 0x0F);
... |
the router components to navigate through the pages | render() {
return (
<Router>
<div className="app">
<Switch>
<Route path="/" exact render={() => <Home user={this.state.user} />} />
<Route path="/login" exact component={Login} />
<Route path="/register" exact component={Register} />
</Switch>
</div>
</Router>
);
} |
Define o que acontece quando se deixa de pressionar certas teclas | function onKeyUp(value) {
'use strict';
switch(value.keyCode) {
case 81: // q
objV1.userData.rotClockwise = false;
break;
case 69: // e
objV1.userData.rotAntiClockwise = false;
break;
case 65: // a
objV2.userData.rotClock... |
Reorder objects attributes so that that the table works. Should put this as a service/factory. | function convertObjects(objects, list){
blank = []
for(var i=0; i<objects.length; i++)
{
obj = []
object = objects[i]
obj['pk'] = object.pk
for (var j=0; j<list.length; j ++)
{
obj.pu... |
loads the full page content | function loadPage() {
getRandomVideo(false);
setTimeout(function() {
loadSidebar();
stopLogo();
loadScreen();
}, 500);
} |
add listeners for escape key press | handleHidesOnOutsideEsc(show) {
if (show) {
this._escKeyHandler = ev => ev.key === 'Escape' && this.hide();
document.addEventListener('keyup', this._escKeyHandler);
} else {
document.removeEventListener('keyup', this._escKeyHandler);
}... |
This method toggles the display of the element with the specified ID. It is fairly primitive, because it presumes that when displayed, the element uses the default display style. | function TUToggle(elementID) {
// Find the desired element. If it doesn't exist, we do nothing.
var actualElement = document.getElementById(elementID);
if (actualElement !== undefined) {
if (actualElement.style.display == 'none') {
actualElement.style.display = '';
} else {
... |
Pluck off n bytes from an array of buffers. Length is the combined lengths of all the buffers in the list. This function is designed to be inlinable, so please take care when making changes to the function body. | function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = ... |
Remove an element from the dom | function removeElement(elem) {
if (elem.prev)
elem.prev.next = elem.next;
if (elem.next)
elem.next.prev = elem.prev;
if (elem.parent) {
var childs = elem.parent.children;
childs.splice(childs.lastIndexOf(elem), 1);
}
} |
the sum of the first and last elements of the array if there is an even number of elements the difference between the first and last elements of the array if there is an odd number of elements. You can assume the array contains at least one number. | function firstAndLast(array){
for(var i = 0; i < array.length; i++){
if(array.length % 2 === 0){
return array[0] + array[array.length - 1];
} else{
return array[0] - array[array.length - 1];
}
}
} |
Add the basic UI items to the page | function initPage() {
var mainContent = document.getElementById('mainContent');
mainContent.innerHTML = "<h1>My Battles</h1>";
var createBattleButton = document.createElement('p');
createBattleButton.innerHTML = 'Begin a New Battle';
createBattleButton.setAttribute('id', 'createBattle');
var battleForm = document... |
middleware to check if a user owns the comment | function checkCommentOwnership(req, res, next) {
if (req.isAuthenticated()) {
Comment.findById(req.params.comment_id, function(err, foundComment) {
if (err) {
console.log('Error with edit comment route ', err);
res.redirect('back');
} else {
// does user own the comment
... |
The date picker constructor | function DatePicker( picker, settings ) {
var calendar = this,
elementValue = picker.$node[ 0 ].value,
elementDataValue = picker.$node.data( 'value' ),
valueString = elementDataValue || elementValue,
formatString = elementDataValue ? settings.formatSubmit : settings.format
cale... |
Helper function to produce an HTML tag. | function tag(name, attrs, selfclosing) {
if (this.disableTags > 0) {
return;
}
this.buffer += ('<' + name);
if (attrs && attrs.length > 0) {
var i = 0;
var attrib;
while ((attrib = attrs[i]) !== undefined) {
this.buffer += (' ' + attrib[0] + '="' + attrib[1] + '"');
i++;
}
}
... |
we fetch these manually in separate XHRs, because Sync Gateway would normally send it back as multipart/mixed, which we cannot parse. Also, this is more efficient than receiving attachments as base64encoded strings. | function fetch(filename) {
var att = atts[filename];
var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +
'?rev=' + doc._rev;
return ajaxPromise(opts, {
method: 'GET',
url: genDBUrl(host, path),
binary: true
}).then(function (blob... |
Store activity for /Network relay | function storeActivity(nsp, activity) {
db.activities.insert(doc, function(err, doc){
if (err) {
console.log("[!] Error storing activity: "+err);
}
else {
nsp.emit('network', {activity: doc});
}
});
} |
Helper to call ReactRef.attachRefs with this composite component, split out to avoid allocations in the transaction mountready queue. | function attachRefs() {
ReactRef.attachRefs(this, this._currentElement);
} |
Open the picker when user hold alt + DOWN_ARROW | handleKeydownOnHost(event) {
if (event.altKey && event.keyCode === DOWN_ARROW) {
this.dtPicker.open();
event.preventDefault();
}
} |
Example: pragma encoding=utf16; select hex('A'); returns '4100' notice that the 00 comes after the 41 (i.e. it's swizzled) | function parseHexUtf16(str, start, end) {
var result = '';
while (start < end) {
// UTF-16, so swizzle the bytes
result += String.fromCharCode(
(hexToInt(str.charCodeAt(start + 2)) << 12) |
(hexToInt(str.charCodeAt(start + 3)) << 8) |
(hexToInt(str.charCodeAt(start)) << 4) |
he... |
spread operator changes the elements into an array as individual separate arguments | function greeting (hi, hello,hey,sup){ {
return ('hi', hi)
return ('hello', hello)
return ('hey', hey)
return ('sup', sup)
}
} |
Perform raw public operation on "x": return x^e (mod n) | function RSADoPublic(x) {
return x.modPowInt(this.e, this.n);
} |
After returning to main screen from other screen in the site | static restoreSelectedSwitchesInMainScreen(symbolsArr) {
symbolsArr.forEach(function(symbol) {
$(`#${symbol}`).prop("checked", true);
});
} |
Creates a FieldPath from the provided field names. If more than one field name is provided, the path will point to a nested field in a document. | function FieldPath$1() {
var fieldNames = [];
for (var _i = 0; _i < arguments.length; _i++) {
fieldNames[_i] = arguments[_i];
}
validateNamedArrayAtLeastNumberOfElements('FieldPath', fieldNames, 'fieldNames', 1);
for (var i = 0; i < fieldNames.length; ++i) {
... |
extracts the src=myfilename from the URL | function Guidewire_ExtractSrcFromURL() {
var VarDocumentURL = window.WWHFrame.location;
var TheParametersArray = VarDocumentURL.hash.split("&");
var thisParam;
var FMSourceFile = "UNKNOWN_FRAMEMAKER_SOURCE_FILE";
k = TheParametersArray.length;
for (i= 0 ; i < k; i++) {
thisParam = unescape(TheParametersArray... |
clears opponents hand, to be used before refreshing players hand | function clearOpponentsHand() {
$('.opponent-hand').empty();
} |
eslintdisable Constructor for render module | function PivotContextMenu(parent){/* eslint-enable */this.parent=parent;this.parent.contextMenuModule=this;} |
Add document named by string name with specified content to this instance. Update index in this with all nonnoise normalized words in content string. | addContent(name, content) {
//@TODO
let word_map = new Map();
let word_count = new Map();
let map_filename = new Map();
this.words(content);
map3.set(name,content);
let word_offset = [];
let match;
while(match = WORD_REGEX.exec(content)){
if(!this.noise_words.has(match[0])){... |
Support: IE<8 Manipulating tables requires a tbody | function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
} |
THIS IS THE OBJECT IT WILL MANIPULATE | constructor(initList, initIndex){
this.todoList = initList;
this.initList = initList;
this.todoIndex = initIndex;
this.todoItem = this.todoList.items[this.todoIndex];
} |
This is a dummy function to check if the function name has been altered by minification. If the function has been minified and NODE_ENV !== 'production', warn the user. | function isCrushed() {} |
Mutasi population = generate_population(5) mutation_probability = 0.0001 console.log(mutate(population, mutation_probability)) | function mutate(population, mutation_probability) {
for (var i = 0; i < population.length; i++) {
random = Math.random()
if (random < mutation_probability) {
cur_chromosome = population[i]
random = Math.round(Math.random() * (cur_chromosome - 1)) + 0
random_gen = cur_chromosome[Math.round(Ma... |
Called when the game preloads assets for later use | preload(scene) {
} |
Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k. | function formatTrim(s) {
out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
switch (s[i]) {
case ".": i0 = i1 = i; break;
case "0": if (i0 === 0) i0 = i; i1 = i; break;
default: if (i0 > 0) { if (!+s[i]) break out; i0 = 0; } break;
}
}
return i0... |
URL Template v2.0.6 ( | function expand(url, params, variables) {
var tmpl = parse(url),
expanded = tmpl.expand(params);
if (variables) {
variables.push.apply(variables, tmpl.vars);
}
return expanded;
} |
this function stops the player spamming reset until they get favourable wires yet still allows to retain their score pressing reset after picking the correct wire | function resetScore() {
if (lethal) {
score = 0;
lives = 2;
}
else {
return;
}
} |
if we're already writing something, then just put this in the queue, and wait our turn. Otherwise, call _write If we return false, then we need a drain event, so set that flag. | function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (Buffer.isBuffer(chunk))
encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous n... |
date and time from ref 2822 format | function configFromRFC2822(config) {
var match = rfc2822.exec(preprocessRFC2822(config._i));
if (match) {
var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
if (!checkWeekday(match[1], parsedArray, config)) {
r... |
random numbers selected for the crystals, between range 1 12 | function crystalsRandomSel() {
var C = Math.floor(Math.random() * 12) + 1;
return C;
} |
TODO: add tweening register of what objects are travellng TODO: make function parameters an object and use proptypes or alternative to specify mandatory fields and have auto complete. | travelTo(gameObjectTravelling, finalPosition, time, parameters) {
const _from = {
x: gameObjectTravelling.position.x,
y: gameObjectTravelling.position.y,
z: gameObjectTravelling.position.z
};
const _to = {
x: finalPosition.x,
y: finalPosition.y,
z: finalPosition.z
};... |
Busca estudiante por matricula | async function findByMatricula(matricula){
let estudiante = await db.Estudiante.findAll({
where: {
matricula: matricula
}
});
return estudiante;
} |
Filter and Sort buttons Sort buttons can be done in Switch/Case with querySelectorAll Filter dropdowns needs to search through workspacesAll to populate values Need a submit button? Need to remember filter and sort values Need to display from a display array | function workspaceDisplay(){
console.log("data.workspacesAll: ", data.workspacesAll);
let parking, transit;
let workspaceIndex = [];
//fix array iterations
for (let i = 0; i < displayArray.length; i++) {
if (disp... |
Prepare the header to receive styling Replace the ibdof logo gif with a background transparent version Note: cell addresses are relative to cell[0] == class 'bodyline' | function fixLogo() {
var c = document.getElementsByTagName('td')[1];
// background to ibdof logo
c.className = 'topbkg';
// replace the ibdof logo
c.getElementsByTagName('img')[0].src = 'data:image/gif;base64,R0lGODlhaAFrAPcAAPr7/PT2/PT29PTy9Ozu7OTu9OTm5OTi5Nje5Nzd3NLa3NTT1MDW3MTS1MzO1MzNzMTOzMHO1L/KzMDG... |
Given an array of arbitrarily nested arrays, return n, where n is the deepest level that contains a nonarray value. Examples Input Output array: [ [ 5 ], [ [ ] ] ] ==>2 array: [ 10, 20, 30, 40 ] ==>1 array: [ [ 10, 20 ], [ [ 30, [ 40 ] ] ] ] ==>4 array: [ ] ==>0 array: [ [ [ ] ] ] ==>0 | function Arrayception(array, depth = 0) {
var depth = 0
var maxdepth = 0
function checkArray(arr) {
for (var i = 0; i < arr.length; i++) {
if (!Array.isArray(arr[i]) && depth === 0) {
depth++;
if (depth > maxdepth) {
maxdepth = depth
... |
Add a humanreadable date string to a message object. | function addDateStr(messageObj) {
const errMsg = "Unable to parse date stamp in message object";
const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
const d = new Date(message... |
Check if alarms are triggered | function getStatus(trigger,sampleData) {
switch(trigger.op){
case "less":
if (sampleData < trigger.val){
console.log("alarm trigged at",new Date(),"sampleData",sampleData,"less then trigger",trigger.val);
return true;
}
break;
case "larger":
... |
Cancels any currently inprogress render. | cancel() {
this.state.cancelRender = true;
} |
Set url to receive incoming Telegram updates to the webAppUrl of the published Google script | function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
} |
Core of the application, specifies all the routes with React Router allowing website to be multi paged | function App() {
const announcementsList = useSelector((state) => state.announcementList.list);
const [cookie, setCookie, removeCookie] = useCookies(['userToken']);
useEffect(()=>{
document.title = "Virtual Notice Board";
}, [])
return (
<div className = 'App'>
<div cla... |
Creates a more efficient closure of the things that are needed. So the request and the idx. Also prevents code duplication. | function createDisposable(request, idx) {
var disposed = false;
return function() {
if (disposed || request._disposed) {
return;
}
disposed = true;
request._callbacks[idx] = null;
request._optimizedPaths[idx] = [];
request._requestedPaths[idx... |
A quick way to get the value of text fields in the alerts | function valAtIndex (view, index) {
return view.viewAtIndex(index).stringValue()
} |
Gridlines in y axis function | function yAxis() {
return d3.axisLeft(y)
.tickSize(-width)
.tickFormat("")
} |
sorry I couldn't get forEach or every to work... it was probably because of varriable scoping issues | function checkLine( num ){
if( board.grid[0][num].bool && board.grid[1][num].bool &&board.grid[2][num].bool &&board.grid[3][num].bool &&board.grid[4][num].bool &&board.grid[5][num].bool &&board.grid[6][num].bool &&board.grid[7][num].bool &&board.grid[8][num].bool &&board.grid[9][num].bool ){
board.grid.forEach( f... |
Replace all 'object' elements with images of nick cage. Note this is best done with a background image. | function replaceObjectElements(_this, counter) {
var imgType;
var displayType;
var counter = counter;
var newURL;
// get dimensions of current svg
var width = Math.floor(_this.outerWidth());
var height = Math.floor(_this.outerHeight());
var backgroundSiz... |
We don't want to use the entire user object to sign our JWTs that's a lot of information to eventually store in a cookie. Plus, we don't want to be returning huge blocks of what could be sensitive user information. We need control. Let's create a function to select the user information we want to pass through | function setUserInfo(request) {
return {
_id: request._id,
username: request.username,
email: request.email
};
} |
Main entry into role, called for every creep with that role every tick. Must be overridden by Role subclasses. | handle () {
console.log(this.creep.memory.role + ' is not valid role for ' + this.creep.name);
} |
Find the line at the given vertical position, using the height information in the document tree. | function lineAtHeight(chunk, h) {
var n = chunk.first;
outer: do {
for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
var child = chunk.children[i$1], ch = child.height;
if (h < ch) { chunk = child; continue outer }
h -= ch;
n += child.chunkSize();
}
return... |
Fetches a page of starred repos by a particular user. Relies on the custom API middleware defined in ../middleware/api.js. | function fetchStarred(login, nextPageUrl) {
return {
login,
[CALL_API]: {
types: [ STARRED_REQUEST, STARRED_SUCCESS, STARRED_FAILURE ],
endpoint: nextPageUrl,
schema: Schemas.REPO_ARRAY
}
}
} |
clean docs given to us by the user | function cleanDocs(docs) {
for (var i = 0; i < docs.length; i++) {
var doc = docs[i];
if (doc._deleted) {
delete doc._attachments; // ignore atts for deleted docs
} else if (doc._attachments) {
// filter out extraneous keys from _attachments
var atts = Object.keys(doc._attachments... |
We want to be able to alias the order of stimuli to a single number which can be stored and which can easily replicate a given stimulus order. | function changeorder( arr, ordernum ) {
var thisorder = ordernum;
var shufflelocations = new Array();
for (var i=0; i<arr.length; i++) {
shufflelocations.push(i);
}
for (i=arr.length-1; i>=0; --i) {
var loci = shufflelocations[i];
var locj = shufflelocations[thisorder%(i+1)];
thisorder = Math.floo... |
sorting order null > 'asc' > 'desc' | function getMapped(state, dispatch, ownProps) {
const Connected = require('./index').default;
expect(mockConnect).toBeCalled();
const [
mapStateToProps,
mapDispatchToProps,
mergeProps,
] = mockConnect.mock.calls[0];
expect(mapStateToProps)
.toBeInstanceOf(Function);
expect(mapDispatchToPro... |
Using mainly bare JS in this function because it is going to fire very often while typing, and needs to very efficient. | function adjust() {
var height, originalHeight;
if (mirrored !== ta) {
initMirror();
} else {
setWidth();
}
if (!ta.value && options.placeholder) {
// If the textarea is empty, copy the placeholder text into
// the mirror control and use that for sizing so that we
// don't... |
Generates all the rainbow colours for the colour slider selector | function colorgenerator() {
let colours = [],
i;
for (i = 0; i < 372; i++){
colours[i] = 'hsl(' + i + ', 100%, 50%)';
if (i > 359) {
colours[i] = 'hsl(0, 100%, 100%)';
}
}
colours = colours.toString();
//console.log(colours);
root.style.setProperty("--... |
return new muskPos by applying given mov to given pos | function positionFromMove(mv,pos){
"use strict";
var pscp = pos.clone(), nm, i, p = pos.plyr, op, cap, mov;
pscp.sow( [ pos.plyr, mv[0][1] ] );
pscp.plyr = pos.opposite( p );
pscp.possibleMoves = false;
return pscp;
} |
Hides and reveals the relevant elements when the home button is clicked | function selectHome() {
$("#home").on("click", function () {
$("#scheduleImg").addClass("hidden");
$(".contacts").addClass("hidden");
$(".emails").removeClass("hidden");
$(".nav").removeClass("hidden");
$(".files").addClass("hidden");
$("#search").addClass("hidden");
});
} |
This is Professor Beveridges from the rotating pacman lecture | function clearScene() {
context.save();
context.setTransform(h, 0.0, 0.0, -h, 0.0, h);
context.clearRect(0, 0, w, h);
context.restore();
} |
Load opportunity applications from database | getApplication (opportunityId, personId, forceReload) {
var d = $q.defer();
if(!this.loadedOpportunityApplications[`${opportunityId}-${personId}`] || forceReload === true) {
$http.get(`/api/opportunity_applications/${opportunityId}/${personId}`)
.then(response => {
var applicat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.