anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
move all items into array and then dequeu | dequeue(){
if(!this.eQueue.length && !this.dQueue.length) throw Error("Empty Stack");
if(this.dQueue.length === 0){
for(let item of this.eQueue){
this.dQueue.push(item);
}
}
return this.dQueue.pop();
} |
Called when a user clicks on a circle | update() {
let self = this;
d3.select('#directoryChart').selectAll('tspan').remove();
// Get info for entities filtered by:
// Selected cities, selected category, selected funding type, selected year
let fundingType = d3.select('#fundingType').property('value');
let category = d3.select('#categori... |
The chart function Selects a div element (selection) and appends an SVG with the horizontal bar chart | function chart(selection) {
// **********************
// handing new personalized data
// **********************
d3.select("#chart svg")
.remove();
data.forEach(function(d) {
nameLookup[d.name] = d;
});
color
.range(... |
Get the line number of the start of the next visual line after the given line. | function visualLineEndNo(doc, lineN) {
if (lineN > doc.lastLine()) { return lineN }
var line = getLine(doc, lineN), merged;
if (!lineIsHidden(doc, line)) { return lineN }
while (merged = collapsedSpanAtEnd(line))
{ line = merged.find(1, true).line; }
return lineNo(line) + 1
} |
===== End of Funcion para agregar usuario ====== /========================================= = Update de usuario = ========================================= | function UpdateUsuario(req, res){
if (req.usuario.rol === 1 || req.usuario.nombre === req.body.nombre) {
const idUsuario = req.params.idUsuario;
const usuario = {
nombre: req.body.nombre,
edad: req.body.edad,
email: req.body.email,
pass: sha512(req.bod... |
for listing users for dev testing (excluding passwords) | function getUsers() {
return db('users')
.select('id', 'username')
} |
if strike not already in object, make a new object for the strike THEN add the call or put | function makeNewStrike(line, strikeHorder){
strikeHolder[line.strike] = {};
strikeHolder[line.strike].numberStrike = line.numberStrike;
sortCallsAndPuts(line, [strikeHolder[line.strike]]);
} |
let dom: HTMLElement | null = document.getElementById('root'); console.log(dom.id) | function getStr(str) {
console.log(str.length);
} |
GETTING THE MOVIE WHICH IS SELECTED | function getMovie() {
//GETTING THE ID FROMSESSION STORAGE
let movieId = sessionStorage.getItem("movieId");
axios
.get("https://www.omdbapi.com?apikey=af465f0e&i=" + movieId)
.then(response => {
console.log(response);
let movie = response.data;
let imdbid = movie.imdbID;
// UPDATIN... |
using this function for both actors array and genre array by passing true or false to isActor | function checkIfPresent(output, X, isActor){
var set = -1
if(output.length == 0){ return set }
output.forEach((element,index,output) => {
if(isActor){
if(element.Name === X){
set = index
return set
}
}
else{
if(... |
lets you read chars, and optionally reset the cursor to where it was before reading | function createCharReader (nextChar, rewind) {
let charsRead = 0
return {
nextChar () {
charsRead += 1
return nextChar()
},
reset () {
rewind(charsRead)
charsRead = 0
},
rewind (n = 1) {
rewind(n)
charsRead -= n
}
}
} |
Implement the search function | function search() {
const text = this.value;
if (text === '') {
rows.forEach(row => row.style.display = null);
return;
}
const length = names.length;
const regex = new RegExp(text, 'gi');
for (let i = 0; i < length; i++) {
if (names[i].match(regex)) rows[i].style.display ... |
Return true if |object|.|property| can be called without throwing an error. | function canAccessProperty(object, property) {
try {
const unused = object[property];
return true;
} catch (errors) {
return false;
}
} |
get endDate contract in modal register ticket from comboboxDate | function DateRegisterTK(monthExtend) {
// body...
var date = new Date($('#RegisDateTK').val());
date.setMonth(date.getMonth() + monthExtend);
var dd = date.getDate();
var mm = date.getMonth() + 1; //January is 0!
var yyyy = date.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
... |
Function for adding new item from form | function addNew(){
var req = new XMLHttpRequest();
var newExercise = document.getElementById("inputNew");
var measurement;
if (newExercise.elements.name.value == ""){
alert ("Error: Name is required.");
return;
}
/*Formatting measurement*/
if(newExercise.elements.measurement.checked){
... |
practice comparing different values | function compareEquality1(a, b) {
if(a == b) {
return "Equal";
}
return "Not Equal";
} |
this method is called when your extension is deactivated | function deactivate() {} |
Sample Populasi population = generate_population(5) fitnesses = calculate_population_fitness(population) console.log(sample_population(population, fitnesses)) | function sample_population(population, fitnesses, selection_rate) {
num_of_selected_chromosome = parseInt(selection_rate * population.length)
mating_population = []
// console.log(num_of_selected_chromosome + " " + population.length)
for (var i = 0; i < num_of_selected_chromosome; i++)
mating_population.pu... |
Display the list of Tiles for the current Project. | function showTiles() {
var tiles = getTiles();
var formHTML = "<ul>";
for (var i = 0; i < tiles.length; i++)
{
formHTML = formHTML + '<li>' + tiles[i].title + '</li>';
}
formHTML = formHTML + "</ul>";
$( "div#tilesList" ).html(formHTML);
} |
Split a data attribute by | and return the trimmed parts | parts(key) {
var raw = this.param(key);
var parts = raw.split('|');
for (var i = 0; i < parts.length; ++i) {
parts[i] = parts[i].trim();
}
return parts;
} |
Submit a password change request to the backend. | function submitPasswordChangeRequest(form) {
return new Promise(function (resolve, reject) {
// Emulate an API call. Reject a portion of the requests.
setTimeout(function () {
// reject if password is incorrect
if (form.currentPassword !== 'qqQQ11!!') {
reject({
code: 401
... |
Write a function where() that filters for all the values in the properties object. | function where(list, properties, k) {
var names = []
return reduce(list, function(list, v, k) {
var names = true
for (var k in properties) {
if (properties[k] !== v[k]) {
names = false
}
}
if (names == true) {
list.push(v)
... |
evaluate all cells and build new matrix for next generation | function nextGeneration () {
var changes = false;
Life.nextGrid = matrix(Life.HEIGHT, Life.WIDTH, false);
for ( var h=0; h < Life.WIDTH; h++ ) {
for ( var v=0; v < Life.HEIGHT; v++ ) {
// get the number of living neighbors
var aliveCount = evaluateNeighbors( h, v )
switch (true) {
... |
webEdition SDK webEdition CMS $Rev$ $Author$ $Date$ This source is part of the webEdition SDK. The webEdition SDK is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License the Free Software Foundation; either version 3 of the License, or any later version. The G... | function loadTable() {
if (hiddenCmd.dispatch) {
hiddenCmd.dispatch("refresh");
} else {
setTimeout(loadTable, 1000);
}
} |
Toggle expanded / collapsed versions of items' images | function xSwapImg(imgDiv,srcImg,srcAltImg){
/* Update by Christian Vallee <cv@valtechnologie.com>
==> No need to specify absolute URL for images anymore, this feature will find it on its own */
// looking for the images' root URL based on the current image
var str = imgDiv.src;
var pos = str.search(srcImg)... |
Hits API with body of carve | sendMessage() {
// Construct the message here
const message = {
sender: this.state.sender,
reciever: this.props.replier,
subject: 'RE: ',
body: this.state.body,
msgType: 'reply',
reply: this.props.replyId
};
// Post... |
vuerouter v3.0.1 (c) 2017 Evan You | function n(t,e){if(!t)throw new Error("[vue-router] "+e)} |
=========================================================================== Send a value on a given number of bits. IN assertion: length <= 16 and value fits in length bits. | function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += ... |
globals canvasDatagrid: false / this file is for developing in a sandbox on a local machine | function g() {
'use strict';
var x,
y,
grid = canvasDatagrid({
parentNode: document.body,
allowFreezingColumns: true,
allowFreezingRows: true,
debug: false
});
grid.style.columnHeaderCellHeight = 40;
grid.style.cellHeight = 40;
... |
feeds the food array to the renderedList to fix performance | addToRenderedList() {
if (this.state.renderedArray.length <= 5) {
let renderedArray = this.state.renderedArray;
let foodArray = this.state.foodArray;
if (this.state.foodArray.length > 5) {
renderedArray = renderedArray.concat(foodArray.slice(0, 5));
foodArray = foodArray.slice(5);... |
A special extend for ajax options that takes "flat" options (not to be deep extended) Fixes 9887 | function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
retur... |
An agent to draw queues for bfs and dfs | function QueueDrawAgent(selector, h, w, problem, options) {
this.canvas = document.getElementById(selector);
this.canvas.innerHTML = '';
this.two = new Two({
height: h,
width: w
}).appendTo(this.canvas);
this.problem = problem;
this.nodeRadius = 25;
this.options = options;
this.iterate = functi... |
Catch the information of each animal | function received_animals(animals_res, user_input, res){
animals_res.setEncoding("utf8");
let body = "";
animals_res.on("data", function(chunk){
body += chunk;
});
animals_res.on("end", function(){
let animals_info = JSON.parse(body);//convert from a JSON string to js obj
let animals_array_length = animals_i... |
Flash error message and redirect the user back | respondWithRedirect(ctx) {
if (!ctx.session) {
return ctx.response.status(this.status).send('Invalid credentials');
}
ctx.session.flashExcept(['_csrf']);
ctx.session.flash('auth', {
errors: {
uid: this.code === 'E_INVALID_AUTH_UID' ? ['Invalid logi... |
Returns information about a package in a safe way (will throw if they cannot be retrieved) | function getPackageInformationSafe(packageLocator) {
const packageInformation = getPackageInformation(packageLocator);
if (!packageInformation) {
throw internalTools_1.makeError(internalTools_1.ErrorCode.INTERNAL, `Couldn't find a matching entry in the dependency tree for the specified parent (this is pr... |
This command remove 1 or more Tasks | function action(args, env) {
// Prompt for tasks
if ( args.length === 0 ) {
prompt('Task:', _promptFinished);
}
// Process Tasks
else {
for ( let i = 0; i < args[0].length; i++ ) {
_process(args[0][i], i+1, args[0].length);
}
}
} |
Refactoring, using Multiple Pointers method Time Complexity O(N), Space Complexity O(1) | function newSumZero(arr) {
// left = beginning of the array
let left = 0;
// right = end of array, remember it's zero indexed
let right = arr.length - 1;
// left < right is our fail safe
while (left < right) {
let sum = arr[left] + arr[right];
if (sum === 0) {
return [arr[left], arr[right]];
} else if (... |
removes user by UID returns true if successful, false otherwise | removeUser(userID) {
if(userID in this.users) {
delete this.users[userID];
return true;
}
else {
return false;
}
} |
Renders the AWS CloudFormation properties of an `AWS::ServiceDiscovery::HttpNamespace` resource | function cfnHttpNamespacePropsToCloudFormation(properties) {
if (!cdk.canInspect(properties)) {
return properties;
}
CfnHttpNamespacePropsValidator(properties).assertSuccess();
return {
Name: cdk.stringToCloudFormation(properties.name),
Description: cdk.stringToCloudFormation(pro... |
Read the documentation ( to customize this controller | async function createIngredientAndUnit(item) {
//ingredient
let ingredient = await strapi.api.ingredient.services.ingredient.findOne({
name: item.ingredient.name,
});
if (!ingredient) {
ingredient = await strapi.api.ingredient.services.ingredient.create({
name: item.ingredient.name,
});
}
... |
end of doc load | function parseXML(xml){
console.log("in parseXML");
$("h1").html("Final Project Assignment<br>" + "Kody Scharf, Andrew Lee<br>" + "991455754, 991457820<br>");
} |
Moving back and forward is similar to moving. But the offset ratio is cut in half to reflect that the destination is halfatile away. Also, it is a negative ratio, since the offset is behind the unit. | animMoveBack(direction) {
let anim = this.renderAnimation('moveBack', direction);
let board = this.board;
let pixi = this.pixi;
anim.frames.forEach((frame, frameId) => {
let offsetRatio = (frameId + 1) / anim.frames.length;
let offset = board.getOffset(-offsetRatio / 2, direction);
a... |
Displays the "empty page" message on the page | function displayEmptyPageMessage() {
$("#emptyPageMessageWrapper").removeClass("hidden");
} |
Leo wrote this given a boolean, sets user's privacy setting | async function updatePrivacy(privacy, username)
{
if(arguments.length != 2 || typeof privacy !== "string") {
throw("updatePrivacy: You must have a privacy and a username");
}
const usersCollection = await users();
let user = await usersCollection.findOne({userDisplayName: username});
if(user == null)... |
Funcion para poblar los campos | function addRecord(){
let codigo = document.getElementById('codigo').value;
let nombre = document.getElementById('nombre').value;
let precio = document.getElementById('precio').value;
productos.push(new IngrProducto(codigo,nombre,precio));
} |
Method to select/unselect wound from wound list | function frmPatientSummary_checkuncheck(eventobject) {
com.healogics.utility.showLoading();
searchPatient_closeSearchList();
//Sandeep offline changes for chart
if (isIpad && !isNetworkAvailable()) {
var error_label = ERROR_CONSTANTS.NO_NETWORK_CONNECTION;
com.healogics.utility.showError... |
Redirect to the real url | function redirect(url, response) {
console.log('redirect to ' + url);
response.writeHead(301, {Location: 'http://' + url});
response.end();
} |
Returns the current run time | function getCurrentRunTime(startTime, currentTime = undefined) {
if (currentTime === undefined) {
currentTime = new Date().getTime();
}
return currentTime - startTime;
} |
Parse the input string and return an object with department and courseNumber properties filled in. | function parseInput(str) {
var input = {};
var tokens = str.trim().toLowerCase().split(/\s/);
var halves = mergeTokens(tokens);
if (!validateInput(halves))
return null;
input['department'] = halves[0];
input['courseNumber'] = halves[1];
return input;
} |
Update the cart count in the header nav with the number of items in the Cart | function updateCounter() {
var cartCounter = document.getElementById('itemCount');
cartCounter.textContent = cart.items.length;
} |
Return true if the object passed in implements any of the named methods. | function implementsAnyMethods(obj, methods) {
if (typeof obj !== 'object' || obj === null) {
return false;
}
for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {
var method = methods_1[_i];
if (method in obj && typeof obj[method] === 'function') {
r... |
vote poll from Albert's codes | function remember() {
// store our current tweets array in localstorage
// but remove last memory of it first
localStorage.removeItem('twitter');
// remember tweets array
localStorage.setItem('twitter', JSON.stringify(tweets));
} |
Returns a new createHistory function that may be used to create history objects that know how to handle URL queries. | function useQueries(createHistory) {
return function () {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var history = createHistory(options);
var stringifyQuery = options.stringifyQuery;
var parseQueryString = options.parseQueryString;
if (typeo... |
for consuming queuelike objs | consume (key) {
if (_state[key].length > 0)
return _state[key].shift();
return false;
} |
esto me sirve para poner una funcion dentro de otra funcion y me permite trabajar esto de forma bastante espeficica por lo que entiendo abajo sentencio la funcion date con callback y hace un console log como new Date despues hace un metodo setTimeOut | function date(callback) {
console.log(new Date);
setTimeout(function() {
let date = new Date;
callback(date);
},3000)
} |
helper function is used to show the task which was assigned by you to someone | task_assigned_to(){
var user_id = Session.get('mySession');
Meteor.subscribe('fetch_assigned_task_to', user_id);
// var task_assign_by_1 = Session.get('task_assign_to');
// return task_assignment.find({ 'user_id_by' : task_assign_by },{sort: {created_at: -1}}).fetch();
return task_assignment.find... |
TODO publish internal ReactClass displayName transform | function ReactGridLayout(props, context) {
_classCallCheck(this, ReactGridLayout);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_initialiseProps.call(_this);
(0, _utils.autoBindHandlers)(_this, ['onDragStart', 'onDrag', 'onDragStop', 'onResizeStart', 'onR... |
Assert a compiler is available. | function assertCompiler(name, Compiler) {
if (typeof Compiler !== 'function') {
throw new Error('Cannot `' + name + '` without `Compiler`')
}
} |
this is essentially the "update sugar" function from daleharvey/pouchdb1388 the diffFun tells us what delta to apply to the doc. it either returns the doc, or false if it doesn't need to do an update after all | function upsertInner(db, docId, diffFun) {
return new PouchPromise(function (fulfill, reject) {
if (typeof docId !== 'string') {
return reject(new Error('doc id is required'));
}
db.get(docId, function (err, doc) {
if (err) {
/* istanbul ignore next */
if (err.status !== 404) ... |
Keeps the game going until the final question, then it will switch to the final screen. | function wait() {
if ( questionCounter < 7 ) {
questionCounter++;
generateHTML();
counter = 30;
timerWrapper();
} else {
finalScreen();
}
} |
saves the data into local storage | function bookmarkWhere() {
var string = JSON.stringify(where);
localStorage.setItem('whereBookmark', string);
} |
Close navList if click outside div | function clickOutside(e) {
var container = $("#navList");
if ((!container.is(e.target) && !$("#mobile-nav").is(e.target))) // if the target of the click isn't the container...
{
container.removeClass("show");
}
} |
Resets the contents and reenable the find buttons; | function goBack() {
id('data').innerHTML = "";
id("find-btn").disabled = false;
} |
ADD TO main_windows LIST | function add_to_main_windows_list(window_id)
{
var temp_main_windows_list = get_main_windows_list();
var index = temp_main_windows_list.indexOf(window_id);
if (index < 0)
{
//this windows is not in the list currently
temp_main_windows_list.push(window_id);
}
localStorage.main_windows = temp_main_w... |
Obtengo los medicamentos de un determinado paciente | function getMedicamentosPaciente(req, res){
console.log('- GET MEDICAMENTOS PACIENTE -');
var query = Paciente.findById(req.params.idPaciente);
query.populate({
path: 'medicamentos',
model: 'Medicamento'
})
.exec(function (err, paciente) {
if (err) {
... |
Simulate forces and update node and label positions on tick. | function tick(e) {
node
.each(gravity(e.alpha * .1))
.each(collide(.5))
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
label
.style("left", function(d) { return (d.x - d.dx / 2) + "px"; })
.style("top", function(d) { return (d.y - d.dy / 2) + "px"; }... |
create new reply box | function createNewReplyBox(reply_location){
div_top = reply_location.parentElement.parentElement.childNodes[3];
debugger;
div1 = document.createElement("div");
div1.className = "replies";
div1.style.display = "block";
div_top.parentNode.insertBefore(div1, div_top.nextSibling);
blank1 = document.createTex... |
Fahrenheit = Celcius 9/5 +32 | function convertToFahrenheit(temp){
let fahr = temp *9/5 +32;
console.log(`${temp} degrees in C is ${fahr} degrees in F`);
} |
Define our tasks using plain functions | function copy() {
// Copy these folders and contents as is
gulp.src([
'src/background/**',
'src/content/**',
'src/popup/**',
'src/styles/**',
'src/vendor/**'], {base: 'src'})
.pipe(gulp.dest(OUTPUT_DIR_WEB_EXTENSION));
// Compile less into css
gulp.src('src/**/*.less', {base: 'src'})
... |
sets event behaviour button needs always be clickable even if nonClickable layer blocks it | function setEventBehaviour(){
button.style("pointer-events","all");
} |
Sprite based collision checking | function SpriteCollision(offset, sprite1, sprite2)
{
for (var x = 0; x < sprite1.width; ++x)
{
var xx = +x + +offset[0];
if (xx < 0 || xx >= sprite2.width) continue;
for (var y = 0; y < sprite1.height; ++y)
{
var yy = +y + +offset[1];
if (yy < 0 || yy >= sprite2.height) continue;
var pix1 = sprite1.r... |
MERCADO SECCION MONEDAS SUGERENCIAS | function datosugerencia($id_sugerencia){
var id = $id_sugerencia;
var base_url= 'http://localhost/sistema_monedas/';
$.ajax({
url: base_url + "sugerencias/view/" + id,
type:"POST",
success:function(resp){
$("#modal-default .modal-body").html(resp);
... |
A function that sets the transparent state of the navbar. | function handleTransparentNavbar() {
setTransparentNavbar(dispatch, (fixedNavbar && window.scrollY === 0) || !fixedNavbar);
} |
Funcion para eliminar comentarios | function removeComment() {
let shortenId2=this.id.slice(15)
// console.log(shortenId2)
let commentRef3= firebase.database().ref("posts/"+shortenId2);
let optionConfirmRemove = confirm ("Confirma si quieres eliminar el comentario")
if (optionConfirmRemove == true){
commentRef3.remove();
}... |
initialize all the button click function | function buttonsSetting() {
var buttons = document.getElementsByTagName("li");
for (var i = 0; i < buttons.length; i++) {
buttons[i].bubbles = true;
EventUtil.addHandler(buttons[i], "click", buttonFunc(i, "custom"));
}
} |
Gets current value in a desired format. | getProcessedValue(value) {
const {
minDate, maxDate, maxDetail, returnValue,
} = this.props;
const processFunction = (() => {
switch (returnValue) {
case 'start':
return getDetailValueFrom;
case 'end':
return getDetailValueTo;
case 'range':
... |
If you have a new step, just add a condition and create the class | function ScenarioStepFactory(step,ctx) {
this.isAction = () => step.action !== undefined
this.isConsumedMessage = () => (step.message !== undefined) && (step.consumed_by !== undefined)
this.isProducedMessage = () => (step.message !== undefined) && (step.produced_by !== undefined)
this.isCalledAPI = () => (step.... |
Wrapper around buildLineContent which will reuse the structure in display.externalMeasured when possible. | function getLineContent(cm, lineView) {
var ext = cm.display.externalMeasured;
if (ext && ext.line == lineView.line) {
cm.display.externalMeasured = null;
lineView.measure = ext.measure;
return ext.built
}
return buildLineContent(cm, lineView)
} |
Client wants to leave the game | function leaveClient() {
socket.emit('leave', {name: playerId});
} |
Function to set the interval execution | function makeInterval() {
intervalID = setInterval(function() {
fadeOutAndIn();
}, intervalTime);
} |
When LWC is used in the context of an Aura application, the compiler produces AMD modules, that doesn't resolve properly circular dependencies between modules. In order to circumvent this issue, the module loader returns a factory with a symbol attached to it. This method returns the resolved value if it received a fac... | function resolveCircularModuleDependency$1(fn) {
{
if (!isFunction$2(fn)) {
throw new TypeError(`Circular module dependency must be a function.`);
}
}
return fn();
} |
the above contains processing for the entry the following displays it, but should be extracted possibly to the updateVenueMarkerVisibilityFlag... this attempts to display all | function _subfunction(placeObject){
console.log('displayed'+placeObject.name);
var retval=new VenueObject(placeObject);//turn that off
retval.done(function(marker){
placeObject.marker=marker;
});
} |
Get the temp from the the API with a getJSON call | function getTemperature(){
$.getJSON("api/getTemp", function(tempJson){
updateGraph(tempJson);
});
} |
Data fetch: artists' info | async function getArtists() {
//In questa copia del progetto, mi sono salvato tutti gli artisti e le loro informazioni in un file json
artistsList = await fetch('artists.json').then(r => r.json());
} |
This is the common logic for both the Node.js and web browser implementations of `debug()`. | function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = __webpack_require__(4695);
createDebug.destroy = destroy;
Object.keys... |
Function to add to inventory | function addInventory() {
var query = "SELECT * from products";
connection.query(query, function (error, results) {
if (error) throw error;
inquirer.prompt([
{
type: "input",
message: "What is the id of the product you want to add?",
... |
Set player to intial location. | restart() {
this.x = 200;
this.y = 380;
} |
applies the necessary transform value to scale the item up | function applyTransforms(el, nobodyscale) {
// zoomer area and scale value
var zoomerArea = el.querySelector('.zoomer__area'),
zoomerAreaSize = {width: zoomerArea.offsetWidth, height: zoomerArea.offsetHeight},
zoomerOffset = zoomerArea.getBoundingClientRect(),
scaleVal = zoomerAreaSize.width/zoomerAreaSize... |
Change the BG of body | function bodyBG(image) {
let bg = "linear-gradient(45deg,rgba(0, 0, 0, 0.6) 65%, rgba(250, 250, 250, 0.34))";
if (window.innerWidth < 800) {
document.body.style.backgroundImage = bg + ",url('img/sm/" + image + "')";
} else {
document.body.style.backgroundImage = bg + ",url('img/" + image + ... |
Constructor for a stack entry on the global exception handler stack | function HandlerStackEntry(k, next)
{
this.k = k;
this.next = next;
} |
render the children of this component the children of this component is an arrow function that takes the count and inrementCount and renders the original component and passes the count and inrementCount to it | render() {
return (
<div>
{this.props.children(this.state.count, this.incrementCount)}
</div>
);
} |
method to get the movieID and setting it to state | getId(title, year) {
//using the google youtube api to get the video id
let youtube = (params, callback) => {
axios.get(this.state.url, { params: params }).then(function(response) {
callback(response.data.items[0])
}).catch(function(error) {
console.error(error);
});
... |
update the profile and clear the input text | function updateProfile() {
if (newName.value!="") {
name.innerHTML = newName.value;
}
if (newEmail.value!="") {
email.innerHTML = newEmail.value;
}
if (newPhone.value!="") {
phone.innerHTML = newPhone.value;
}
if (newZipcode.value!="") {
zipcode.innerHTML = newZipcode.value;
}
if (newPassw... |
Function to initialize the controls | function createControls(camera, domElement) {
// Create new OrbitControls linked to the camera and the renderer's DOM element
const controls = new OrbitControls(camera, domElement);
return controls;
} |
================================ POSTS =============================== create new user | async createTypePlant(req, res) {
const { name, legendary } = req.body;
const newType = new TypePlant({ name, legendary });
try {
await newType.save(function (err) {
if (err) return res.status(400).json({ error: `Error en los datos ingresados` });
res.status(200).json({ message: `Planta ${name} creada ... |
creates a subscription and returns the unsubscribe function; | function subscribe(name, callback) {
// Subscripton names are lowercased so both 'Shift+Space' and 'shift+space' works.
name = name.toLowerCase();
// remove spaces so both 'Shift + Space' and 'shift+space' works.
name.replace(/\s/, '');
if (typeof __subscriptions[name] === 'undefined') {
__su... |
var j = 0; | function particle() {
for (var i=0; i<50; i++) {
var dir = new THREE.Vector3(2*Math.random()-1, Math.random()*4, 2*Math.random()-1);
dir.multiplyScalar(6/dir.length());
var color = (Math.random() > 0.5) ? 0x333333 : 0x666666;
var p = new Particle(obj.position, dir, color, 0.1);
... |
TODO: check if result is React component and highlight it | function propertyValue(t, v) {
if (t === 'string')
return util.inspect(v, { colors: true });
else if (t === 'number' || t === 'boolean')
return v.toString().blue;
else if (t === 'object' && v == 'null')
return 'null'.blue;
else if (t === 'undefined')
return 'undef... |
returns the negated variants of PageElementCurrently's state check functions | get not() {
return {
/**
* Returns true if PageElement currently does not exist.
*/
exists: () => !this.exists(),
/**
* Returns true if PageElement is currently not visible.
*/
isVisible: () => !this.isVisible(),... |
Adds the comment to local storage via redux actions | onAddComment(evt){
evt.preventDefault();
if (this.state.comment.trim() === ''){
return;
}
const newComment = {
content: this.state.comment,
posted: new Date(),
}
// empty the comment text
this.setState({comment: ''});
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.