anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
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... |
Functions to log when we connect/disconnect main observer, for debugging | function observerON() {
debug('Turning observer ON');
if (validPointer(mainObserver)) {mainObserver.observe(mainTargetNode, mainConfig);}
} |
moons: lib: code.org library Draws all the moons that are larger than or equal to 6 pixels in radius. Then, it moves them to the left before checking if it should change one into a small moon. Written by Keegan Brown | moons (lib){
for (var i=0;i<7;i++){
let moon = this.madeMoons[i];
var size = moon.s;
lib.moveTo(moon.x, moon.y);
lib.penRGB(moon.r, moon.g, moon.b);
let movingLeft = true;
let behind = false;
if (moon.s < 6) {
... |
! ctxMenu v1.1.1 | (c) Nikolaj Kappler | ! | function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")} |
migration to version 3 (part 2) | function migrateLocalStore(txn, cb) {
var localStore = txn.objectStore(LOCAL_STORE);
var docStore = txn.objectStore(DOC_STORE);
var seqStore = txn.objectStore(BY_SEQ_STORE);
var cursor = docStore.openCursor();
cursor.onsuccess = function (event) {
var cursor = event.target.result;
... |
a function to download the .svg file | function downloadAsSVG(fileName) {
// use default name if not provided
fileName = fileName || "output.svg";
// create a data url of the file
var svgData = project.exportSVG({
asString: true
});
var url = "data:image/svg+xml;utf8," + encodeURIComponent(svgData);
// create a link to the data, and "cli... |
Refresh notifications Subtracts the cycles (1 second a cycle), if 0 hides the notification. | function refreshhNotifications(){
var html = '';
for(var i = 0;i < currentNotifications.length;i++){
var typeClass = "";
var typeText = "";
if(currentNotifications[i].type == "positive"){
typeClass = "positive-notification";
typeText = "dark-text";
}else if(currentNotifications[i].type == "negative"){... |
vkBeautify Version 0.99.00.beta Copyright (c) 2012 Vadim Kiryukhin | function vkXML (text, step) {
const ar = text.replace(/>\s{0,}</g, "><")
.replace(/</g, "~::~<")
.replace(/\s*xmlns\:/g, "~::~xmlns:")
// .replace(/\s*xmlns\=/g,"~::~xmlns=")
.split("~::~");
const len = ar.length;
let inComment = false;
let deep = 0;
let str = "";
const space = (step != null... |
TODO: Pass the Bot transcript to this method for adding to the prechat details. | async initializeChat(conversationData, userInfo, botTranscript) {
var buttonOverrides = new Array(process.env.BUTTON_ID);
var preChatDetails = this.initializePrechatDetails(userInfo, botTranscript);
var chasitorInit = this.initializeSalesForceChatObject(preChatDetails, userInfo, conversationData... |
=========================================================================== For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. (It will be regenerated if this run of deflate switches away from Huffman.) | function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
... |
Creates the primary movie list | function movieList(query, sortBy, order) {
getMovies(query, sortBy, order).then((movies) => {
//console.log('Here are all the movies:');
movies.forEach(({title, rating, id, tvdb, imdb_id, fav}) => {
// console.log(`id#${id} - ${title} - rating: ${rating}`);
let moviePoster = "images... |
Returns true if PageElement's width eventually equals the expected width or if it deviates no more than the specified tolerance from the expected width within a specific timeout. | hasWidth(width, opts = { tolerance: 0 }) {
return this._node.__eventually(() => this._node.wait.hasWidth(width, { tolerance: opts.tolerance, timeout: opts.timeout }));
} |
Returns true if the given element is within a currentlycollapsed collapse block. | function isWithinCollapsedBlock(element) {
/* If the element is not within a collapse block at all, it obviously can't
be within a *currently-collapsed* collapse block.
*/
let collapseParent = element.closest(".collapse");
if (!collapseParent) return false;
/* If the element is within a collapse block a... |
Retrive JSON from local storage | function retrieveData(key) {
var retrieved = JSON.parse(window.localStorage.getItem(key));
return retrieved;
} |
Load Add Club Editor | function loadAddClubEditor(mobile) {
build = "\
<div id='editorContainer'>\
<div id='editor-fields'>\
<input type='text' id='club-name' placeholder='Name of your Club..' />\
<div id='color-picker-container'>\
<label>Color of your Club</label>\
<span id='blue' class='color-box checked' onclick='c... |
Add a second passphrase to an account | function createSecondPassphrase (selectedAccount) {
var bip39 = require('bip39')
var data = { secondPassphrase: bip39.generateMnemonic() }
if (selectedAccount.secondSignature) {
return formatAndToastError(
gettextCatalog.getString('This account already has a second passphrase: ' + s... |
Handle main application initialization. Prepare main interface by requiring all necessary modules needed for the application to run. | function onAppReady(obj) {
"use strict";
console.log("init.js: onAppReady");
require(["MainApp", "Router", "Config", "DataService", "handlebars", "templates"], function (MainApp, Router, Config, DataService, handlebars, templates) {
window.app = new MainApp(Config, templates, DataSer... |
Get the config object. | static get() {
if (this._config) {
return this._config;
} else {
return this.build();
}
} |
fonction qui remet la valeur (tapez votre email, tapez votre mot de passe ...) dans le champ de l'input | function retablir(txt, id_controle) {
if(document.getElementById(id_controle).value==''){
document.getElementById(id_controle).value=txt;
}
} |
Load contribute buttons Must refresh more frequently, so it is seperate If uploading gets competitive, refresh may need to be upped | function activeSubmit()
{
$.ajax(
{
url: "../ajax/active-submit.php",
type: "POST",
data: { slug: slug },
cache: false,
success: function(html)
{
$("#contributeA").html(html);
$("#contributeB").ht... |
criar a bolinha para mudar a foto na tela | function generateBullets (qtd) {
for (var i=0; i<qtd; i++){
var bullet = $("<a>").html("• ").attr("href","#").data("id",i);
$(".bullets").append(bullet);
}
$(".bullets a").eq(position).addClass("active");
} |
Enter a parse tree produced by MmParsersoundName. | enterSoundName(ctx) {
} |
I wanted to implement forEach, but couldn't figure out how to. | function map(words, instruction) {
// console.log(words.forEach(instruction));
var result = [];
for (var i = 0; i < words.length; i++) {
result.push(instruction(words[i]));
}
console.log(result);
} |
Everything here to the check letter function is my attempt to generate a new photo every time a new word is generated. | function randomImg() {
imgURL = images[Math.floor(Math.random() * images.length)];
console.log(imgURL);
} |
return true if (i,i+1) crosses (k,k+1) | function isCrossing(i, k){
if ( i == k || i == k + 1 || i == k - 1){
return false;
}
var path1 = [pointarray[i].LatLng, pointarray[i + 1].LatLng, pointarray[k].LatLng];
var path2 = [pointarray[i].LatLng, pointarray[i + 1].LatLng, pointarray[k + 1].LatLng];
var path3 = [pointarray[k].LatLng, pointarray[k + ... |
renders todo info on edit modal | function renderModalEdit(todo) {
var form = $('#form-todo-edit');
var id = todo.attr('data-id'),
title = todo.attr('data-title'),
priority = todo.attr('data-priority'),
details = todo.attr('data-details'),
created = todo.attr('data-created'),
elapsed = parseInt(todo.attr('data-elapsed')),
... |
fn(relativePos) Parameters: block (obj) block whose button was clicked relativePos (buttonpos) position of button (14) | onAddButtonClick(fn) { this.onAddButtonClickFn = fn } |
This function tries to parse a single expression at a given offset in a string. Useful for parsing mixedlanguage formats that embed JavaScript expressions. | function parseExpressionAt(input, pos, options) {
var p = new Parser(options, input, pos);
p.nextToken();
return p.parseExpression()
} |
this is an array to store players info | function setup(){
database = firebase.database();
console.log(database);
createCanvas(displayWidth/2, displayHeight/2);
game = new Game();
game.start();
} |
if the user specifies include_docs=true, then we don't want to block the main cursor while we're fetching the doc | function fetchDocAsynchronously(metadata, row, winningRev) {
var key = metadata.id + "::" + winningRev;
docIdRevIndex.get(key).onsuccess = function onGetDoc(e) {
row.doc = decodeDoc(e.target.result);
if (opts.conflicts) {
row.doc._conflicts = collectConflicts(metadata);
... |
clear old shape then load a new one from Shape.js | function createNewShape() {
agentNewShape = true;
emptyShapeElements();
shape = CreateShape();
nextShape = nextShapeDisplay();
ghostShape = createGhostShape();
sortShapePos(shape);
timeStep = originalTimeStep;
} |
Get the item prefix e.g. " 1. " for a numbered list, " " for a bulleted list. | function getItemPrefix() {
var prefix;
if(args.tag === "ol") {
prefix = " " + num + ". ";
num = num + 1;
} else {
prefix = " " + bullet + " ";
}
return prefix;
} |
endregion region Element Toggle Helpers | function setEnabled(element, condition) {
if (condition) element.removeAttribute('disabled');
else element.setAttribute('disabled', '');
} |
function when user logs out | function handleLogout(event) {
setUser(false);
NavbarComponents.pop(); // Remove Admin page in Navbar
NavbarComponents.pop(); // Change Log out to Log in in Navbar
NavbarComponents.push(
<li key="login">
<Link to="/login">Giriş Yap</Link>
</li>
);
} |
Return method is a function and therefore you can use it as you would a function. To invoke a function, simply call it like this: plus1(); plus2(); Function Declarations | function plus1(a,b){
return(a+b);
} |
Change the key in the lock | function set_key(lock, key, callback) {
let str = JSON.stringify({
Action: "SET",
Attribute: "KEY",
Value: key
})
send_command(lock, str)
callback(f.hacker.ingverb())
} |
! SCOREBOARD ASSETS This is the function that runs to add scoreboard assets | function addScoreboardAssets(){
manifest.push({src:'assets/scoreboard/bg_scoreboard.png', id:'bgScoreboard'});
manifest.push({src:'assets/scoreboard/icon_replay.png', id:'iconReplay'});
manifest.push({src:'assets/scoreboard/icon_save.png', id:'iconSave'});
manifest.push({src:'assets/scoreboard/icon_scoreboard.png',... |
functions to activate achievements | function onFireAction(){
} |
Fetches all pages of the provided categories, calling the `callback` function for each page loaded. | async fetchPages(categories, callback) {
let pages = [];
for (const category of categories) {
const pagesInCategory = await request.get(
`${API_ROOT}/categories/${category}/docs`,
this.httpOptions
);
for (const json of pagesInCategory) {
pages.push(this.fetchPage(json, ... |
get the terminal configuration using the id | getTerminalConfiguration(terminalConfigurationId)
{
return this.dataElement.terminalConfigurations.find(tc => tc.terminalConfigurationId === terminalConfigurationId);
} |
no vr plugin error message | function no_vr_plugin()
{
var errorBox = ID("errorBox");
errorBox.innerHTML = ""+
"<center>"+
"<br>"+
"<h1 style='margin-bottom:0;'>NPVR Browser Plugin required!</h1>"+
"<br>"+
"Get the plugin here and install it:<br>"+
"<br>"+
"<a href='https://github.com/CodingCooky/npvr/#npvr' target='_blank'>https:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.