anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
makes a function to compare the object values from the specified compare operation callback
function makeCompare (fn) { return function (value, key) { return hasOwn(this, key) && fn(value, this[key]) } }
resets the amount of tasks to 0 takes the todosFile json and modifies the tasks in it this function is invoked when the user enter the command 'reset'
function resetTodosList (jsonObject) { //empty tasks jsonObject.tasks = []; console.log('tasks list emptied successfully'); //turn into string and save it to the file jsonObject = JSON.stringify(jsonObject); return fs.writeFile('todo.json',jsonObject); }
draws one round corner, starting at origin (needs to be translated/rotated to be placed properly).
function drawRoundCorner(Wright, r, transform$$1) { var angle = Math.PI/2 * Wright / (Wright + Wtop); // not sanitizing this one, because negative values // are useful to fill the box correctly. var ri = { x: r.x - Wright, y: r.y - Wtop ...
Helper functions for state...
function updateQuiz(pointer, value, currentlyEditing) { setQuiz(oldQuiz => { let q = [...oldQuiz.problems]; q = q.map((problem, i) => { if (i === pointer) { if (currentlyEditing.type === QUESTION) { return { ...problem, question: value }; } else if (currentlyEditi...
Carga la MT / 1. Comprueba si el API es compatible con el navegador 2. Hacemos trigger en el input que carga la ventana del explorador de archivos
function cargarMT(){ if( APIcompatible() ) { //[1] $('#cargarMT').trigger('click'); //[2] }else{ mostrarAlert('API FileRader no compatible con este navegador.') } }
Mark a component as needing a rerender, adding an optional callback to a list of functions which will be executed once the rerender occurs.
function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setState, forceUpdate, etc....
Retrieving an icon for the card's footer:
function retrieveFooterIcon(iconNum) { iconNum = iconNum ? iconNum : 0 switch(iconNum) { // Devices Cards case '1': return <FontAwesomeIcon icon={faMapMarkerAlt} style={{width: '20px', height: '20px'}} />; // Warehouses Cards case '2': return <FontAwesomeIcon icon={faWare...
test for square code
function squareTest(t){ //t=1 for player1, t=2 for player2 j=1; while (gotSquare==0 && j<n+1){ i=1; while (gotSquare==0 && i<n+1){ if (state[i][j]==t){ for (l=j;l<n+1;l++){ if (l==j){start=i+1}else{start=1;} for (k=start;k<n+1;k++){ if (state[k][l]==t){ if ((0<k+l-j && k+l-j<n+1 &&...
combines searchURL with user input
function formatQueryParams(params) { const queryItems = Object.keys(params).map( (key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}` ); return queryItems.join("&"); }
This does the same as the function above, but for the weekList table.
function changeEmojiWeek(){ var em = document.getElementById("weekList").childElementCount; if(em == 0){ document.getElementById("emojiWeek").innerHTML = "😀"; }else if(em < 3){ document.getElementById("emojiWeek").innerHTML = "🙄"; }else if(em < 5){ document.getElementById("emojiWeek").innerHTML...
Get the value for the table cell
function getIt(id) { var result; result = document.getElementById(id).value.trim(); return result; }
set xurrent route name
setCurrentRouteName(routeName){ currentRoute = routeName; currentPoiIndex = null; }
Show or hide the ondemand details panel.
function toggleDetails() { const details = d3.select("#details"); details.style("display", details.style("display") === "none" ? "block" : "none" ); d3.select("#guide strong").text( details.style("display") === "none" ? "show" : "hide" ); }
Hooks and props are merged as arrays.
function mergeHook ( parentVal, childVal ) { var res = childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal; return res ? dedupeHooks(res) : res }
Convert Stringformatted options into Objectformatted ones
function createOptions( options ) { var object = {}; jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; }
Partial class which not works on its own
createMultiplayerIO() { this.socket.on("pong", (pingTimestamp) => { var pongTimestamp = Date.now(); var ping = pongTimestamp - pingTimestamp; this.events.emit('ping', ping); }); this.otherPlayers = this.physics.add.group(); this.socket.on('currentPlayers', function (data) { this.createAllPlayers(...
Create an data object exposed by 's events
function createCoreData(draggable /*: DraggableCore*/, x /*: number*/, y /*: number*/) /*: DraggableData*/ { var state = draggable.state; var isStart = !(0, _shims.isNum)(state.lastX); var node = findDOMNode(draggable); if (isStart) { // If this is our first move, use the x and y as last coords. return...
Attach a set of options to widget
setOption(internal_name, option) { if (IsString(internal_name, true) && IsObject(option)) { PopLog.info(this.name, `Option set for ${internal_name}`, option); this.asset.option.set(internal_name, option); } }
Grabs the external_id from the Pivotal API
function getExternalId(story) { $.ajax({ url: pivotalProjectUrl + "/stories/" + story.getAttribute('data-id'), async: false, dataType: 'json', success: function(data) { id = data.external_id; if(id !== null) { jiraUrl = jiraBase + id; ...
So we can use nice names
isWorseThan(other) { return !this.isBetterThan(other); }
Creates the mail body and encodes it to base64 format.
makeBody(){ // an object for mail let mail; mail = new mailComposer({ to: this.to, text: this.body, subject: this.sub, textEncoding: "base64" }); //Compiles and encodes the mail. mail.compile().build((err, msg) => { if (err){ return console.log('Error compiling email ' + error); } ...
FROM, SELECT, WHERE, ORDERBY, CALLBACK
static findOneWhereOrder(from, select, where, orderBy, callback) { findOne(from, where, select, orderBy, callback); }
Fetch an image (html img snippet with inline base64 src attribute) snippet and save the image as file
function fetchImage2base64 (path, dest, key) { return limitedFetch(`${domain}${path}`) .then(r=>r.buffer()) .then(buf=>{ const imgdom = new JSDOM(buf); const src = imgdom.window.document.querySelector('img').getAttribute('src'); const imageBuffer = decodeBase64Ima...
Display path on map, along with markers for start and end waypoints, and for the next waypoint.
displayPath() { // Show start and end waypoints. let startMarker = new google.maps.Marker({ position: this._navPath.waypoints[0], map: this._map, icon: { path: google.maps.SymbolPath.CIRCLE, scale: 5, fillCo...
Instance of the element is created/upgraded. Use: initializing state, set up event listeners, create shadow dom.
constructor() { super(); }
Compute the average with .forEach()
function average(numbers) { let sum = 0; numbers.forEach(function(arrNum) { sum = arrNum += sum; }); let arrAvg = sum/numbers.length; return arrAvg; }
helper function to make title case
function toTitleCase(str) { return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); }
Return the PKCS1 RSA encryption of "text" as an evenlength hex string
function RSAEncrypt(text) { var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3); if(m == null) return null; var c = this.doPublic(m); if(c == null) return null; var h = c.toString(16); if((h.length & 1) == 0) return h; else return "0" + h; }
LOGIC TO DELETE COURSE
function deleteCourse() { let courseId = $(this).attr('data-id'); coursesService.deleteCourse(courseId) .then(() => { showInfo('Course deleted.'); loadMyCourses(); // showView('Catalog'); }).catch(handleError); }
Fill the formatted Salutation in the Form
fillForm(fSalut) { this.salutationForm.setValue({ firstname: fSalut.firstname, gender: fSalut.gender, // language: fSalut.language, language: this.convertLanguage(fSalut.language), lastname: fSalut.lastname, letterSalutation: fSalut.letterS...
check if the heap is empty
isEmpty() { return this.heap.length === 0; }
logic function calculate which numbers to replace with fizz/buzz
function fizzBuzz(fizz, buzz) { // initialize an array to hold our results let resultsArray = []; // use a for loop to replace words divisable by 3, 5, or both with fizz, buzz, or fizzbuzz respectively // use the continue statement to exit the current iteration of the for loop and continue to the next ...
Produces a GraphQL Value AST given a JavaScript value. A GraphQL type must be provided, which will be used to interpret different JavaScript values. | JSON Value | GraphQL Value | | | | | Object | Input Object | | Array | List | | Boolean | Boolean | | String | String / Enum Value | | Number | Int / Float | | Mixed | E...
function astFromValue(value, type) { // Ensure flow knows that we treat function params as const. var _value = value; if (type instanceof _definition.GraphQLNonNull) { var astValue = astFromValue(_value, type.ofType); if (astValue && astValue.kind === Kind.NULL) { return null; } return astV...
Function to put stmts from path in a HTML format with linkouts
function generatePathLinkout(pathArray) { // Build an html string of the paths // pathArray is a list of dicts for each edge in the path: // pathArray[i] gives a dict for the support of edge i // pathArray[i][stmt type j] is a list of all statements of type j supporting edge i // pathArray[i][stmt type j][k] ...
gotoCheckLimit is configured only for [n_item = +1 or 1] it may be extended later
gotoCheckLimit(current_line, n_item, line_limit) { if (n_item > 0 && current_line < line_limit) { return true; } else if (n_item < 0 && current_line > line_limit) { return true; } else { return false; } }
Initializes the scene views with the values read from the XML file.
initViews() { let viewsId = []; //array used for interface cameras dropdown for (var key in this.graph.views) { if (this.graph.views.hasOwnProperty(key)) { var view = this.graph.views[key]; if (view.type === "ortho") { let v = new CGFcame...
Alert if clicked on outside of ul list and menu button
function handleClickOutside(event) { if (ref.current && !ref.current.contains(event.target) && menuButtonRef.current && !menuButtonRef.current.contains(event.target) && props.isColumnNavBarDisplayed) { // If outside, then close the ul list props.requireColumnNavBarDisplayedToggle(); ...
format date using native date object
function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); return formatFunctions[format](m); }
public function avialble for evryone just like function prototype
greet() { console.log('hello' + ' ' + this.firstname + ' ' + this.lastname); }
Helper that calls fromDotSeparatedString() but wraps any error thrown.
function fieldPathFromArgument(methodName, path) { if (path instanceof FieldPath$1) { return path._internalPath; } else if (typeof path === 'string') { return fieldPathFromDotSeparatedString(methodName, path); } else { var message = 'Field path arguments must be of ty...
TODO optimise for this common case
function interpolate(from, to, direction, stream) { circleStream(stream, radius, delta, direction, from, to); }
replace this once we get the database in place
function getRegularCustomerAccountsAndValue(jsonFeed){ var regValues = new Array(4); regValues[0] = jsonFeed[3]; regValues[1] = jsonFeed[4]; regValues[2] = jsonFeed[1]; regValues[3] = jsonFeed[1]; return regValues; }
zeros(number, size) { var stringNumber = String(number); while(stringNumber.length < (size || 2)) { stringNumber = '0' + stringNumber; } return stringNumber; }
to make score 6 zeros
function verNotaRecibida(nroNotaRec, nameArchivo) { var URL = getUrlApp() + "/DownloadServlet?tipo=VER_NOTA_REC&nroNotaRec=" + nroNotaRec + "&nameArchivo=" + nameArchivo + TAB_ID_REQUEST; /* window.status = URL; var w = window.open(URL,"Memo","width=" + ancho + ",height=" + alto + ",top=" + posX + ",le...
Esta funcion se usa para ver la nota recibida en la consulta de notas recibida
function updateTopics(topics) { topics.forEach(function(d, i) { d.r = Math.max(12, r(d.count)); }); // min. collision force.nodes(data.topics = topics).start(); updateNodes(); updateLabels(); }
Update the known topics.
function PlaySfx() { if (blockSfx) return; blockSfx = true; audio.PlayOneShot(swingSfx,1.0); yield WaitForSeconds(swingSfx.length); blockSfx = false; }
play sound of swing
function ResetBoard() { var allSquares = $(".square"); for (var i = 0; i < allSquares.length; i++) { $(".square:eq(" + i + ")").removeClass('movable'); } }
Remove movable space promts from each square
function renderGesture() { if (!webGl) { return; } // Gesture renders are entirely disabled for canvas renderers (it's just too slow at the moment!) /* * Only one gesture is rendered at a time, so first the current gesture - if any - is removed. */ clearGesture(); /* * The LeapTrainer controller s...
This function is called when a training gesture is saved and when a gesture is recognized. It depends on the LeapTrainer Controller providing a renderableGesture array.
constructor(id, admins) { super(id, 'IT'); // calls the constructor of the base class // must call super before using the 'this' keyword this.admins = admins; }
will use base class constructor by default
deleteOne(condition, cb) { orm.deleteOne( 'burgers', condition, (res) => cb(res) ); }
Deletes a burger from the table
function walk(node, fn) { const queue = [node] while (queue.length) { const next = queue.shift() if (fn(next) !== false) { Array.from(next.children, (c) => queue.push(c)) } } }
Breadthfirst node tree walk. Doesn't recurse into child when the callback fn returns false
get id() { return this.constructor.id; }
Way to get a static property without explicitly specifying the class
function addDeletedOrLocalIndex(txn, callback) { var docStore = txn.objectStore(DOC_STORE); docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false}); docStore.openCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { var metadata = cur...
migration to version 2 unfortunately "deletedOrLocal" is a misnomer now that we no longer store local docs in the main docstore, but whaddyagonnado
function updatesHandler() { let apiKey = localStorage.getItem("apiKey"); // include @bookId let title = document.getElementById(titleFieldId).value; let author = document.getElementById(authorFieldId).value; let category = document.getElementById(categoryFieldId).value; let file = document.getEl...
view update complete handle changes
function TimeoutNextClickCheck(tot) { if(IsRadioClick==false) { // BMOD: use confirm instead of alert // alert("You did not click on an answer"); // return false; if(!confirm("Proceed without answer?")) { return false; } } // alert("new func"); var checked = 0; for(nn = 0; nn < tot; nn++) { if(document.Q...
BRENDAN MOD: NEW FUNCTION
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...
The DOM updates done when an operation finishes are batched so that the minimum number of relayouts are required.
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 ...
Used only with promisify. Transform callback to promise result.
constructor(x, y) { this.x = x; this.y = y; }
creates conservation at x, y with type x, y are given in coordinates from 0 to 1
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...
NEW build layers function
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....
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
componentDidMount() { this.getDataFromDb(); if (!this.state.intervalIsSet) { let interval = setInterval(this.getDataFromDb, 1000); this.setState({ intervalIsSet: interval }); } }
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
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(); }
Update the machine recipe URL
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) ....
Delete the true_false using id and update the table
canTransitionToStep(wizard, destinationIndex) { return this.isNavigable(wizard, destinationIndex); }
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...
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 = ...
date from iso format
function Obj() { //函数有自己的this const f = ()=>console.log(this); f(); }
o is the this
function cfnPatchBaselinePropsToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnPatchBaselinePropsValidator(properties).assertSuccess(); return { Name: cdk.stringToCloudFormation(properties.name), ApprovalRules: cfnPatchBaselineRuleGroupPro...
Renders the AWS CloudFormation properties of an `AWS::SSM::PatchBaseline` resource
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 ==...
POST the photo name and data to /queue_photos route via an AJAX request
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 () =>...
get the list of all players excluding current player
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...
Safely install SIGINT listener. NOTE: this will only work on OSX and Linux.
function hide(Id){ document.getElementById(Id).style.display = "none"; }
Function to change display property to none.
function Calendar_Class(ClassCSS){ jq( "."+ClassCSS ).datepicker(); }
cargar el calendario atraves de un clase jquery para funciones tienen que estar cargada la clase
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...
exam search by exam name
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...
Helper function to rotate the bird depending on their vertical velocity
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...
Building the list of items
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...
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 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 ; } ...
$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 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) { ...
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.
_equal(a, b) { return a === b; }
This should be overriden.
getById (url, id) { url = `${url}/${id}?f=json`; return this.request(url, {method: 'GET'}); }
Get a record by id
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...
sec_exponent = hash(passphrase) XOR hash(random_seed)
jump() { if (this.isJumping()) { return; } this.verticalVelocity = Constants.SKIER_JUMP_VELOCITY; }
Jump the skier, but do nothing if already jumping
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)) //...
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 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...
draws a circle around a designated point to show locations needed to get to
function closeConnection() { //alert("closing"); if (socket != null) { socket.close(); } }
closes the connection, this is used once you leave the page/closes the tab/closes the browser
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" ...
global, used for tooltips
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...
================================================================================ Create Pokemon Card ================================================================================
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>" ); ...
appending options in to and from
function initiateCall() { prepareCall(); navigator.getUserMedia({ "audio": false, "video": { mediaSource: "screen", width: 800, height: 600 } }, function(stream) { localVideoStream = stream; peerConn.addStream(localVideoStream); ...
run start(true) to initiate a call
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); ...
Convert a raw string to a hex string
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> ); }
the router components to navigate through the pages
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...
Define o que acontece quando se deixa de pressionar certas teclas
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...
Reorder objects attributes so that that the table works. Should put this as a service/factory.
function loadPage() { getRandomVideo(false); setTimeout(function() { loadSidebar(); stopLogo(); loadScreen(); }, 500); }
loads the full page content
handleHidesOnOutsideEsc(show) { if (show) { this._escKeyHandler = ev => ev.key === 'Escape' && this.hide(); document.addEventListener('keyup', this._escKeyHandler); } else { document.removeEventListener('keyup', this._escKeyHandler); }...
add listeners for escape key press
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 { ...
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 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 = ...
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 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); } }
Remove an element from the dom
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]; } } }
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 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...
Add the basic UI items to the page